-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateAGui.py
354 lines (275 loc) · 15.7 KB
/
createAGui.py
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
from tkinter import *
from tkinter import font
import os
import socket
import pandas as pd
import numpy as np
import pandas.io.formats.excel
import xlsxwriter
from pprint import pprint as pp
from git import Repo,remote
from datetime import datetime as dtime
import math
class manageData:
empDataBase = 'employeeList.csv'
salarayDatabase = 'salaryDatabase.csv'
empListSheet = 'EmployeesList'
monthlyDataSheet = 'MonthlyData'
excelForDisp = 'displayData.xlsx'
gitHubLoc = '[email protected]:tiger-syntex/TimeSheet.git'
repotCheckout = 'H:\Repos\MohitYadavGitHub\TimeSheetV2\TimeSheet'
noOfWorkingDays = 28
def __init__(self,mainWinwdow):
## check for Internet
self.checkInternet = self.is_conencted()
# self.checkInternet = False
## if internet present , pull the latest version from net
if self.checkInternet:
self.gitPull()
## define the colIndex for your database
self.colIndex = self.flattenMixList (['MonthlySalary',
[str(x) for x in list(range(1,32))],
'Days_Worked',
'Advance_Balance',
'Salary_For_Month',
'Paid_In_Month'])
## read the databases in the background when you create the class
self.currMonth = (pd.Period(dtime.now(), 'M')).strftime('%B %Y')
self.lastMonth = (pd.Period(dtime.now(), 'M') - 1).strftime('%B %Y')
self.empList = self.empListRead()
#=======================================================================
# ## create the GUI
#=======================================================================
## Frames
frame = Frame(mainWinwdow,width = 400,height = 100)
frame.pack()
frame2 = Frame(mainWinwdow,width = 400,height = 100)
frame2.pack(side = BOTTOM)
## Font
helv20 = font.Font(family="Helvetica",size=10,weight="bold")
## Button 1 to open excel
self.openExlButton = Button(frame,font= helv20,text = "Feed Data",fg ='blue',command = self.openXlsForUpdate )
self.openExlButton.place(x=5, y=5, relx=0.10,rely=0.2,height=50,width=120)
# self.openExlButton.bind("<Button-1>",self.openXlsForUpdate)
## Button 2 to update database
self.upDatabaseButton = Button(frame,font= helv20,text = "Update Database",fg ='red', command = self.updateDatabse)
self.upDatabaseButton.place(x=5, y=5, relx=0.6,rely=0.2,height=50,width=120)
# upDatabaseButton.bind("<Button-1>",self.updateDatabse)
## Button 3 to Add employee info
self.addEmpButton = Button(frame2,font= helv20,text = "Employee List",fg ='blue',command = self.changeEmpList )
self.addEmpButton.place(x=5, y=5, relx=0.10,rely=0.2,height=50,width=120)
#==========================================================================
# check if there is an Internet Connection
#==========================================================================
def is_conencted(self):
try:
# connect to the host -- tells us if the host is actually
# reachable
socket.create_connection(("www.google.com", 80))
return True
except OSError:
pass
return False
#===========================================================================
# Pull the latest content from Server
#===========================================================================
def gitPull(self):
repo = Repo(self.repotCheckout)
# repo.delete_remote('origin')
# origin = repo.create_remote('origin', self.gitHubLoc)
origin = repo.remote(name='origin')
origin.fetch()
origin.pull(origin.refs[0].remote_head)
#===========================================================================
# Pull the latest content from Server
#===========================================================================
def gitCommitAndPush(self):
repoLocal = Repo(self.repotCheckout)
if repoLocal.is_dirty():
repoLocal.git.add('--all')
repoLocal.git.commit('-m','Database Updated')
origin = repoLocal.remote(name='origin')
origin.push(origin.refs[0].remote_head)
#===========================================================================
# Read the empDataBase
#===========================================================================
def empListRead(self):
with open(self.empDataBase,'r') as ff:
empDf = pd.read_csv(ff)
return (empDf)
#==========================================================================
# Read the Salary Databse
#==========================================================================
def salDataBaseRead (self):
with open(self.salarayDatabase,'r') as ff:
salaryDF = pd.DataFrame.from_csv(ff,parse_dates =False, index_col=[0,1])
# salaryDF = pd.DataFrame.from_csv(ff, index_col=[0,1])
return (salaryDF)
#===========================================================================
# openXlsForUpdate : open the excel file to feed monthly data
#===========================================================================
def openXlsForUpdate(self):
currMonth = self.currMonth
lastMonth = self.lastMonth
salaryDF = self.salDataBaseRead()
listOfEmps = self.empList.EmployeeName.values
newWayForIndex = pd.MultiIndex.from_product([listOfEmps,[self.currMonth,self.lastMonth]],names=['EmployeeName','Month'])
# check if current month entry exists
for (idx, row) in self.empList.iterrows():
emps = row.loc['EmployeeName']
sal = row.loc['Salary']
tupForMonth = (emps,self.currMonth)
tupForPrevMonth = (emps,self.lastMonth)
if not(tupForMonth in salaryDF.index.tolist()):
# check if previous month entry exist
if tupForPrevMonth in salaryDF.index.tolist():
# create dummy current month entry
salaryDF = self.addDummyEntryForDataFrame(salaryDF,emps,sal,self.currMonth)
print(emps,sal)
else:
# create dummy this month and previous month entry
print(emps,sal)
salaryDF = self.addDummyEntryForDataFrame(salaryDF,emps,sal,[self.lastMonth,self.currMonth])
self.writeToSalDatabse(salaryDF)
elif not(tupForPrevMonth in salaryDF.index.tolist()):
salaryDF = self.addDummyEntryForDataFrame(salaryDF,emps,sal,self.lastMonth)
# Filter current month for displaying in excel, and for list of emps
extractDf = salaryDF.xs(self.currMonth,level=1)
exDf_lastMonth = salaryDF.xs(self.lastMonth,level=1)
extractDf = extractDf.filter(listOfEmps,axis=0)
exDf_lastMonth = exDf_lastMonth.filter(listOfEmps,axis=0)
newBalForMonth = exDf_lastMonth['Advance_Balance']+exDf_lastMonth['Paid_In_Month']-exDf_lastMonth['Salary_For_Month']
extractDf['Advance_Balance'] = np.ceil(newBalForMonth / 10.0) * 10
# sorted(list())
# Math Operations before displaying
# write content to excel
# reset the header style of pandas
pandas.io.formats.excel.header_style = None
xlsWr = pd.ExcelWriter(self.excelForDisp)
extractDf.to_excel(xlsWr,self.currMonth)
#=======================================================================
# # format Excel Sheet for view
#=======================================================================
# reset the header style of pandas
pandas.io.formats.excel.header_style = None
wb = xlsWr.book
ws = xlsWr.sheets[self.currMonth]
rowFormat = wb.add_format({'bold': True, 'font_color': 'white', 'align':'center','font_size':'12','bg_color':'blue','locked': True})
lockColFomat = wb.add_format({'bold': True,'locked': True})
unlocked = wb.add_format({'locked': False})
locked = wb.add_format({'locked': True})
ws.set_column('A:XDF', None, locked)
ws.set_column(0, 0, 20,lockColFomat)
ws.set_column(1, 1, 15,lockColFomat)
ws.set_column('AH:AJ', 18,lockColFomat)
ws.set_column('AK:AK', 15,unlocked)
ws.set_column(2,32,3,unlocked)
ws.set_row(0,20,rowFormat)
noOfEmployeesDisplayed = len(extractDf.index.values)
ws.data_validation('C2:AG'+str(noOfEmployeesDisplayed+1),{'validate': 'list',
'source': ['0', '1']})
for index in range(noOfEmployeesDisplayed+1,200):
ws.set_row(index,8,locked)
for index in range(2,noOfEmployeesDisplayed+2):
ws.write_formula('AH'+str(index), '=SUM($C'+str(index)+':$AG'+str(index)+')')
ws.write_formula('AJ'+str(index), '=CEILING(B'+str(index)+'*(SUM($C'+str(index)+':$AG'+str(index)+'))/28,10)')
ws.protect()
# ws.set_row(0,0,locked)
xlsWr.save()
os.startfile(self.excelForDisp)
# excelFile = 'template.xlsx'
# os.startfile(excelFile)
#===========================================================================
# addDummyEntryForDataFrame : create a dummy entry for dataframe
#===========================================================================
def addDummyEntryForDataFrame(self,baseFrame,empName,salary,monthsInput):
if type(monthsInput) == list:
newWayForIndex = pd.MultiIndex.from_product([[empName],monthsInput],names=['EmployeeName','Month'])
dataEntry = self.flattenMixList([salary,np.zeros(len(self.colIndex)-1)])
dataEntry = [np.array(dataEntry),np.array(dataEntry)]
ndf = pd.DataFrame(dataEntry,index=newWayForIndex ,columns=self.colIndex)
baseFrame = pd.concat([baseFrame,ndf], join='inner',).sort_index()
else:
newWayForIndex = pd.MultiIndex.from_product([[empName],[monthsInput]],names=['EmployeeName','Month'])
dataEntry = self.flattenMixList([salary,np.zeros(len(self.colIndex)-1)])
ndf = pd.DataFrame(dataEntry,index=self.colIndex ,columns=newWayForIndex)
ndf = ndf.T
baseFrame = pd.concat([baseFrame,ndf], join='inner',).sort_index()
return baseFrame
#===========================================================================
# updateDatabse : update the employee salary database for data in excel
#===========================================================================
def updateDatabse(self):
## part 1 : update the employee list, based on excel
xlFileToRead = pd.ExcelFile(self.excelForDisp)
if xlFileToRead.sheet_names[0] == self.empListSheet:
# update the employee list and Salary
empList = pd.read_excel(self.excelForDisp,self.empListSheet)
empList.to_csv(self.empDataBase,index = False)
# you just wrote to the database, read it again
self.empList = self.empListRead()
elif xlFileToRead.sheet_names[0] == self.currMonth:
# read the salary database and try to drop the current month info if
# present,since it will be updated in the next steps
salaryDF = self.salDataBaseRead()
salaryDF.drop(self.currMonth,level = 'Month',inplace=True)
# read the current month data from excel and format it to be added
salDataFromExcelForMonth = pd.read_excel(self.excelForDisp,self.currMonth,index_col=[0])
rowMultiIndices = pd.MultiIndex.from_product([salDataFromExcelForMonth.index.values,[self.currMonth]],names=['EmployeeName','Month'])
newDFtoadd = pd.DataFrame (salDataFromExcelForMonth.values,index=rowMultiIndices,columns=self.colIndex)
# add current month data to base dataFrame
salaryDF = pd.concat([salaryDF,newDFtoadd], join='inner',).sort_index()
# write as csv to database
self.writeToSalDatabse(salaryDF)
else:
print('error, xls doesnt have the data')
# check for internet, and push for changes in database
if self.checkInternet:
self.gitCommitAndPush()
#===========================================================================
# writeToSalDatabse : write to Salary Database
#===========================================================================
def writeToSalDatabse(self,dataFrameToWrite):
# write as csv to database
toCsv = dataFrameToWrite.to_csv()
with open(self.salarayDatabase,'w') as ff:
ff.write(toCsv)
#===========================================================================
# addEmployee : add an employee to the employee database
# Idea here is to open the excel to display all data from csv, and update
# the excel with employee list after its closed and update is clicked
#===========================================================================
def changeEmpList(self):
self.empList = self.empListRead()
# reset the header style of pandas
pandas.io.formats.excel.header_style = None
# write content to excel
xlsWr = pd.ExcelWriter(self.excelForDisp)
self.empList.to_excel(xlsWr,self.empListSheet,index = False, header = True)
# format the sheet
wb = xlsWr.book
ws = xlsWr.sheets[self.empListSheet]
format = wb.add_format({'bold': True, 'font_color': 'white', 'align':'center','font_size':'12','bg_color':'blue'})
ws.set_row(0,20,format)
ws.set_column('A:A',25)
# save the sheet
xlsWr.save()
# open the file
os.startfile(self.excelForDisp)
#===========================================================================
## Helpers ##
#=======================================================================
#
#=======================================================================
def flattenMixList(self,inputList):
final = []
for i in inputList:
if type(i) == list or type(i)== np.ndarray:
for j in i:
final.append(j)
else:
final.append(i)
return(final)
mainWinwdow = Tk()
classObj = manageData(mainWinwdow)
mainWinwdow.mainloop()