-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
391 lines (310 loc) · 11.8 KB
/
main.py
File metadata and controls
391 lines (310 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import requests
import json
from reportlab.pdfgen import canvas
from reportlab.platypus import Table, Frame
from reportlab.lib.colors import HexColor
import numpy as np
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from reportlab.lib.units import inch
from heroku import *
import datetime
import sys
API_LIST_FILENAME = "api-list.json"
API_KEY_JSON = API_KEY + ".json"
PAYSLIP_LIST_FILENAME = "payslip-list.json"
def fetchApiList():
response = requests.get(f"https://{COMPANY_NAME}/api/{API_KEY_JSON}", auth=(USERNAME, PASSWORD))
return response
def createApiList():
with open(API_LIST_FILENAME, "wb") as file:
file.writelines(fetchApiList())
def searchMainApiList(itemValue, fileName, key):
jsonFile = open(fileName)
jsonData = json.load(jsonFile)
for keyVey in jsonData:
if (itemValue == keyVey[key]):
return keyVey["Key"]
print("No Payslips")
os.remove(API_LIST_FILENAME)
sys.exit()
createApiList()
EMP_LIST_KEY = searchMainApiList("Employee", API_LIST_FILENAME, "Name")
PAYSLIP_LIST_KEY = searchMainApiList("Payslip", API_LIST_FILENAME, "Name")
def fetchEmpInfo(empKey):
empKeyJson = empKey + ".json"
response = requests.get(f"https://{COMPANY_NAME}/api/{API_KEY}/{EMP_LIST_KEY}/{empKeyJson}",
auth=(USERNAME, PASSWORD))
return response
def fetchPayslipList():
payslipListKey = PAYSLIP_LIST_KEY + ".json"
response = requests.get(f"https://{COMPANY_NAME}/api/{API_KEY}/{payslipListKey}", auth=(USERNAME, PASSWORD))
return response
def createPayslipList():
with open(PAYSLIP_LIST_FILENAME, "wb") as file:
file.writelines(fetchPayslipList())
createPayslipList()
def fetchPayslipKey(key):
keyJson = key + ".json"
response = requests.get(f"https://{COMPANY_NAME}/api/{API_KEY}/{PAYSLIP_LIST_KEY}/{keyJson}", auth=(USERNAME,
PASSWORD))
return response
def fetchPayslipItems(key, itemKey):
itemJson = itemKey + ".json"
response = requests.get(f"https://{COMPANY_NAME}/api/{API_KEY}/{PAYSLIP_LIST_KEY}/{key}/{itemJson}",
auth=(USERNAME, PASSWORD))
return response
def populateDictionaries(keyTitle, supKey, key):
value = fetchPayslipKey(key)
data = dict(value.json())
dataItemList = []
if (checkForItem("Employee", key)):
if (checkForItem(keyTitle, key)):
for keyVal in data.get(keyTitle):
keyValJson = keyVal["Item"] + ".json"
dataJson = dict(fetchPayslipItems(key, keyValJson).json())
dataItemList.append(dataJson.get("Name"))
rate = "{:,}".format(keyVal[supKey])
dataItemList.append(rate + " JMD")
return dataItemList
else:
return dataItemList
else:
return dataItemList
def checkPayslipDate(payslipData):
payslipDate = payslipData.get("Date").split("-")
currentDate = datetime.date.today()
year = currentDate.year
month = currentDate.month
count = 0
flag = False
secFlag = False
monthString = str(month)
newMonthString = ""
if(len(monthString) == 1):
newMonthString = '0' + monthString
secFlag = True
while not flag:
if payslipDate[count] == str(year):
count += 1
currentString = newMonthString if secFlag else monthString
if payslipDate[count] == currentString:
flag = True
else:
break
else:
break
return flag
def checkForItem(keyTitle, key):
value = fetchPayslipKey(key)
data = dict(value.json())
if (data.get(keyTitle) is None):
return False
return True
def checkForEarnings(keyTitle, subKey, key):
value = fetchPayslipKey(key)
data = dict(value.json())
for keyVal in data.get(keyTitle):
if (dict(keyVal).get("Item") is None or dict(keyVal).get(subKey) is None or len(list(keyVal)) == 0):
return False
return True
def populateEmpDictionaries(keyTitle, supKey, key):
value = fetchPayslipKey(key)
data = dict(value.json())
dataItemList = []
if (checkForItem("Employee", key)):
if (checkForItem(keyTitle, key)):
for keyVal in data.get(keyTitle):
keyValJson = keyVal["Item"] + ".json"
dataJson = dict(fetchPayslipItems(key, keyValJson).json())
dataItemList.append(dataJson.get("Name"))
rate = "{:,}".format(keyVal[supKey])
dataItemList.append(rate)
return dataItemList
else:
return dataItemList
else:
return dataItemList
def returnPayslipData(key):
value = fetchPayslipKey(key)
data = dict(value.json())
return data
def getEmpFromPayslip(key):
value = fetchPayslipKey(key)
data = dict(value.json())
empData = dict(fetchEmpInfo(data.get("Employee")).json())
return empData
def createEmpJson(payslipData, empData, key):
empEList = populateEmpDictionaries("Earnings", "UnitPrice", key)
empDecList = populateDictionaries("Deductions", "DeductionAmount", key)
if (len(empEList) != 0 and len(empDecList) != 0):
creatingPdf(empData, payslipData, calEmpGross("Earnings", "UnitPrice", key),
deductionCal("Deductions", "DeductionAmount", key),
empEList, empDecList)
emailingService(empData)
# delEmpPayslip(key)
delFiles(empData.get("Name") + "_payslip.pdf")
def pdfTableFormat(empEarningsList, empDecList, empGross, empNet):
splitInto = len(empEarningsList) / 2
splits = np.array_split(empEarningsList, splitInto)
splitIntoDec = len(empDecList) / 2
splitsDec = np.array_split(empDecList, splitIntoDec)
border = 2
ePos = 0
#
empPayslipTable = [
["Description", "Total"]
]
for array in splits:
empPayslipTable.append(list(array))
border += 1
ePos += 1
empPayslipTable.append(["Gross pay", empGross])
for array in splitsDec:
empPayslipTable.append(list(array))
border += 1
empPayslipTable.append(["Net pay", empNet])
#
num = 1
flag = True
borderStyles = [("BOX", (0, 0), (0, 0), 1, HexColor("#000000")), ("BOX", (1, 0), (1, 0), 1, HexColor("#000000")),
("BOTTOMPADDING", (0, 0), (0, 0), 7), ]
while (num <= border):
if (num == 1 and flag == True):
borderStyles.append(("BOX", (1, num), (1, ePos), 1, HexColor("#000000")))
borderStyles.append(("BOTTOMPADDING", (1, num), (1, ePos), 7))
borderStyles.append(("RIGHTPADDING", (1, num), (1, ePos), 7))
flag = False
else:
if (num > ePos):
borderStyles.append(("BOX", (1, num), (1, num), 1, HexColor("#000000")))
borderStyles.append(("BOTTOMPADDING", (1, num), (1, num), 7))
borderStyles.append(("RIGHTPADDING", (1, num), (1, num), 7))
num += 1
borderStyles.append(("BOX", (0, 0), (0, ePos), 1, HexColor("#000000")))
borderStyles.append(("ALIGN", (0, ePos + 1), (0, -1), "RIGHT"))
borderStyles.append(("FONTNAME", (0, 0), (-1, -1), "Helvetica"))
borderStyles.append(("FONTNAME", (0, 0), (1, 0), "Helvetica-Bold"))
borderStyles.append(("FONTSIZE", (0, 0), (-1, -1), 10))
borderStyles.append(("FONTNAME", (0, -1), (1, -1), "Helvetica-Bold"))
borderStyles.append(("RIGHTPADDING", (0, 0), (0, 0), 400))
borderStyles.append(("ALIGN", (1, 0), (1, -1), "RIGHT")),
table = Table(empPayslipTable, style=borderStyles)
return table
def creatingPdf(empData, payslipData, empGross, empDec, empElist, empDecList):
imgFile = "solutech_logo.png"
addX = 20
addY = 746
story = []
frame = Frame(1.1 * inch, 1 * inch, 6 * inch, 8 * inch)
empNet = empGross - empDec
aEmpGross = "{:,}".format(empGross)
fEmpGross = str(aEmpGross) + " JMD"
aEmpNet = "{:,}".format(empNet)
fEmpNet = str(aEmpNet) + " JMD"
table = pdfTableFormat(empElist, empDecList, fEmpGross, fEmpNet)
headerTable = addressTable(payslipData)
pdfName = canvas.Canvas(empData.get("Name") + "_payslip.pdf")
pdfName.setFont("Helvetica-Bold", 23)
pdfName.drawString(20, 790, "Payslip")
pdfName.drawImage(imgFile, 460, 770, width=105, preserveAspectRatio=True, mask='auto')
pdfName.setFont("Helvetica-Bold", 9)
pdfName.drawString(20, 760, empData.get("Name"))
pdfName.setFont("Helvetica", 9)
addSplit = str(empData.get("Address")).split("\n")
for item in addSplit:
pdfName.drawString(addX, addY, item)
addY -= 15
pdfName.setFont("Helvetica", 9)
headerTable.wrapOn(pdfName, 100, 100)
headerTable.drawOn(pdfName, 400, 710, )
story.append(table)
frame.addFromList(story, pdfName)
pdfName.save()
def addressTable(payslipData):
aTable = [
["Date", "Solutech Innovation Ltd."],
[payslipData.get("Date"), "21 Connolley Drive"],
["", "Kingston 4"],
["", "TRN 002 082 080"],
]
contentTable = Table(aTable, 60, 15, style=[
("FONTSIZE", (0, 0), (-1, -1), 9),
("FONTNAME", (0, 0), (-1, -1), "Helvetica"),
("FONTNAME", (0, 0), (1, 0), "Helvetica-Bold"),
("ALIGN", (0, 0), (0, 0), "RIGHT"),
])
return contentTable
def calEmpGross(keyTitle, supKey, key):
valueNew = 0
value = fetchPayslipKey(key)
data = dict(value.json())
for keyVal in data.get(keyTitle):
valueNew = keyVal[supKey] + valueNew
return valueNew
def deductionCal(keyTitle, supKey, key):
valueNew = 0
value = fetchPayslipKey(key)
data = dict(value.json())
for keyVal in data.get(keyTitle):
valueNew = keyVal[supKey] + valueNew
return valueNew
def emailingService(empDictionary):
empName = empDictionary.get("Name")
pdfName = empName + "_payslip.pdf"
subject = empName + "'s Payslip"
empEmail = str(empDictionary.get("Email")).replace("\n", "")
if empEmail == "None":
print("Mail not sent")
return
msg = MIMEMultipart()
msg["From"] = EMAIL_ADDRESS
msg["To"] = empEmail
msg["Subject"] = subject
msg.attach(MIMEText("PDF Documment", "plain"))
# #
binaryPdf = open(pdfName, "rb")
payload = MIMEBase('application', 'octate-stream', Name=pdfName)
payload.set_payload((binaryPdf).read())
#
encoders.encode_base64(payload)
payload.add_header('Content-Decomposition',
'attachment', filename=pdfName)
msg.attach(payload)
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(EMAIL_ADDRESS, APP_KEY)
text = msg.as_string()
session.sendmail(EMAIL_ADDRESS, empEmail, text)
session.quit()
print("Mail sent.")
def delEmpPayslip(key):
keyJson = key + ".json"
response = requests.delete(f"https://{COMPANY_NAME}/api/{API_KEY}/{PAYSLIP_LIST_KEY}/{keyJson}", auth=(USERNAME,
PASSWORD))
return response
def delFiles(empData):
os.remove(empData)
def returnPayslipKey(fileName):
jsonFile = open(fileName)
jsonData = json.load(jsonFile)
for keyVey in jsonData:
key = keyVey["Key"]
empData = getEmpFromPayslip(key)
payslipData = returnPayslipData(key)
# Check date here
if (checkPayslipDate(payslipData)):
createEmpJson(payslipData, empData, key)
print("Task Completed")
###################################################
# Main
###################################################
def main():
returnPayslipKey(PAYSLIP_LIST_FILENAME)
os.remove(PAYSLIP_LIST_FILENAME)
os.remove(API_LIST_FILENAME)
main()