DavidD003 commited on
Commit
930eac7
·
1 Parent(s): 1118a0b

Upload SchedBuilderUtyModule.py

Browse files
Files changed (1) hide show
  1. SchedBuilderUtyModule.py +439 -0
SchedBuilderUtyModule.py ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from SchedBuilderClasses2 import *
2
+ import openpyxl as pyxl
3
+ import pandas as pd
4
+ import numpy as np
5
+ import sqlite3
6
+ import functools
7
+
8
+
9
+ def debug(func):
10
+ """Print the function signature and return value"""
11
+ @functools.wraps(func)
12
+ def wrapper_debug(*args, **kwargs):
13
+ args_repr = [repr(a) for a in args] # 1
14
+ kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] # 2
15
+ signature = ", ".join(args_repr + kwargs_repr) # 3
16
+ print(f"Calling {func.__name__}({signature})")
17
+ value = func(*args, **kwargs)
18
+ print(f"{func.__name__!r} returned {value!r}") # 4
19
+ return value
20
+ return wrapper_debug
21
+
22
+
23
+
24
+ def addTBL(tblName,fields="",dTypes=None,data=None,addOn=False):
25
+ """Create table if not already existing, optionally with data, optionally clearing out old data if present. Fields as list of strings. Datatypes as list of strings, one must be provided for each field. See sqlite3 docs for mroe info"""
26
+ conn = sqlite3.connect('test16.db')
27
+ c = conn.cursor()
28
+ listedFields=''
29
+ if fields=="": #If none given, make alphabetical
30
+ fields=[chr(65+i) for i in range(len(data[0]))]
31
+ if dTypes==None: #Need not specify dtypes
32
+ for f in fields:
33
+ listedFields=listedFields+', '+ f
34
+ else: #define data types at inception of table
35
+ flds=list(zip(fields,dTypes))
36
+ for pair in flds:
37
+ listedFields=listedFields+', '+pair[0]+' '+pair[1]
38
+ listedFields='('+listedFields[2:]+''')''' #Add leading and closing bracket, remove naively added comma+space from leading field
39
+ c.execute('''CREATE TABLE IF NOT EXISTS '''+tblName+listedFields) # Create table.
40
+ if addOn==False: #Delete if not adding
41
+ c.execute('''DELETE FROM '''+tblName)
42
+ if (data is not None) and len(data)>0:
43
+ stmnt='INSERT INTO '+tblName+' VALUES ('
44
+ for i in range(len(fields)-1):
45
+ stmnt=stmnt+'?,'#Add '?,' equal to num columns less 1
46
+ stmnt=stmnt+'?)' #add closing ?), no final comma
47
+ for subEntry in data:
48
+ c.execute(stmnt, subEntry)
49
+ conn.commit()
50
+
51
+ def isNumeric(n):
52
+ try:
53
+ n=int(n)
54
+ return True
55
+ except ValueError:
56
+ try:
57
+ n=float(n)
58
+ return True
59
+ except:
60
+ return False
61
+
62
+
63
+ def viewTBL(tblName,fields=None,sortBy=None,filterOn=None,returnStatement=0):
64
+ """return np array of table with optional select fields, filtered, sorted. Sort syntax=[(field1,asc/desc),(field2,asc/desc)...] Filter syntax=[(field1,value),(field2,value)...]"""
65
+ conn = sqlite3.connect('test16.db')
66
+ c = conn.cursor()
67
+ stmnt='SELECT '
68
+ if fields!=None:
69
+ flds=''
70
+ for f in fields:
71
+ flds=flds+', '+f
72
+ stmnt=stmnt+flds[2:]+ ' FROM ' +tblName+' '
73
+ else: stmnt=stmnt+'* FROM '+tblName+' ' #unspecified, select all
74
+ if filterOn!=None:
75
+ filt='WHERE '
76
+ for f in filterOn:
77
+ if isNumeric(f[1]): filt=filt+f[0]+' = '+ str(f[1])+' AND '
78
+ else: filt=filt+str(f[0])+' = "'+ str(f[1])+'" AND '
79
+ filt=filt[:-4] #Remove naively added final " and "
80
+ stmnt=stmnt+filt
81
+ if sortBy!=None:
82
+ srt='ORDER BY '
83
+ for s in sortBy:
84
+ srt=srt+s[0]+' '+s[1]+', '
85
+ srt=srt[:-2]
86
+ stmnt=stmnt+srt
87
+ stmnt=stmnt+';'
88
+ if returnStatement==True: # Add option to print out the sql statement for troubleshooting
89
+ return stmnt
90
+ else:
91
+ c.execute(stmnt)
92
+ return [list(x) for x in c.fetchall()] #sqlite3 returns list of tuples.. want sublists for being editable
93
+
94
+ def FTbtRow(ws):
95
+ """Returns the excel row number for the bottom row with data in FT employee sheet"""
96
+ #1st find bottom row with data
97
+ for i in range(5,400):
98
+ ref="C"+str(i) #Referencing EEID column. Failure mode is EEID missing for someone. Thats a bigger problem than the code not working
99
+ if ws[ref].internal_value==None:
100
+ #Condition met when end of data found.
101
+ btmRow=i-1 #backtrack to last data
102
+ break
103
+ return btmRow
104
+
105
+ def getFTinfo(flNm):
106
+ """Returns dataframe with FT employee info (seniority,crew,eeid,name,refusal hours to date, OT hrs worked this week given path to FT refusal sheet"""
107
+ myWb=pyxl.load_workbook(flNm)
108
+ ws=myWb['Hourly OT']
109
+ btmRow=FTbtRow(ws)
110
+ tab=[[x.internal_value for x in sublist] for sublist in ws['A5:I'+str(btmRow)]]
111
+ #for rec in tab: #numeric values getting cast to string on import. cast back
112
+ # for i in [0,2]:
113
+ # rec[i]=int(rec[i])
114
+ # for i in [5,6,7]:
115
+ # rec[i]=float(rec[i])
116
+ #Following to turn into dataframe
117
+ #df_FTinfo=pd.DataFrame(tab)
118
+ #df_FTinfo=df_FTinfo[[0,1,2,3,4,5,8]] #Pull out only required columns
119
+ #df_FTinfo.set_axis(['snrty', 'crew', 'eeid','last','first','yrRef','wkOT'], axis='columns', inplace=True)
120
+ return tab
121
+
122
+
123
+ def FTendCol(ws):
124
+ """Returns column # for last column of skills matrix in excel from FT refusal sheet"""
125
+ for i in range(0,400):
126
+ if ws['A1'].offset(0,i).value=='Start-up':
127
+ #Condition met when end of data found.
128
+ endCol=i-1
129
+ break
130
+ return endCol
131
+
132
+ def getFTskills(flNm):
133
+ """Returns a dataframe containing a table with 2 fields: eeid and job name, with one record for every job an ee is trained in"""
134
+ myWb=pyxl.load_workbook(flNm)
135
+ ws=myWb['Hourly OT']
136
+ endCol=FTendCol(ws) #Get right limit for iteration through skills
137
+ btmRow=FTbtRow(ws) #Get bottom limit for iteration through skills
138
+ skills=[] #Initialize empty skills list
139
+ for i in range(5,btmRow+1): #Data starts on row 5. +1 because range fn not inclusive
140
+ eeid=ws['C'+str(i)].value
141
+ for c in range(10,endCol+1):
142
+ if ws['C'+str(i)].offset(0,c-2).value==1: #subtract 2 from c because the endCol is counted from col A, and we are offsetting from col C, whihc is 2 offset from A
143
+ jobNm=ws['A2'].offset(0,c).value #if 1 indicates trained, pull job name from header row
144
+ skills.append([eeid,jobNm]) #Add new record to skills table
145
+ #idxs=np.array(skills)[:,0]
146
+ #skills=pd.DataFrame(skills,idxs) #Convert to dataframe
147
+ #skills.set_axis(['eeid','skill'], axis='columns', inplace=True)
148
+ return skills
149
+
150
+ def TempbtRow(ws):
151
+ """Returns the excel row number for the bottom row with data in Temp employee sheet"""
152
+ #1st find bottom row with data
153
+ for i in range(4,400):
154
+ ref="C"+str(i) #Referencing EEID column. Failure mode is EEID missing for someone. Thats a bigger problem than the code not working
155
+ if ws[ref].internal_value==None:
156
+ #Condition met when end of data found.
157
+ btmRow=i-1 #backtrack to last data
158
+ break
159
+ return btmRow
160
+
161
+ def getTempinfo(flNm):
162
+ """Returns dataframe with FT employee info (seniority,crew,eeid,name,refusal hours to date, OT hrs worked this week given path to FT refusal sheet"""
163
+ myWb=pyxl.load_workbook(flNm)
164
+ ws=myWb['Temp Refusal']
165
+ btmRow=TempbtRow(ws)
166
+ tab=[[x.internal_value for x in sublist] for sublist in ws['A4:I'+str(btmRow)]]
167
+ #df_Tempinfo=pd.DataFrame(tab)
168
+ #df_Tempinfo=df_Tempinfo[[0,1,2,3,4,5,8]] #Pull out only required columns
169
+ #df_Tempinfo.set_axis(['snrty', 'crew', 'eeid','last','first','yrRef','wkOT'], axis='columns', inplace=True)
170
+ return tab
171
+
172
+ def TempendCol(ws):
173
+ """Returns column # for last column of skills matrix in excel from FT refusal sheet"""
174
+ for i in range(0,400):
175
+ if ws['A2'].offset(0,i).value=='Start Up':
176
+ #Condition met when end of data found.
177
+ endCol=i-1
178
+ break
179
+ return endCol
180
+
181
+ def getTempskills(flNm):
182
+ """Returns a dataframe containing a table with 2 fields: eeid and job name, with one record for every job an ee is trained in"""
183
+ myWb=pyxl.load_workbook(flNm)
184
+ ws=myWb['Temp Refusal']
185
+ endCol=TempendCol(ws) #Get right limit for iteration through skills
186
+ btmRow=TempbtRow(ws) #Get bottom limit for iteration through skills
187
+ skills=[] #Initialize empty skills list
188
+ for i in range(4,btmRow+1): #Data starts on row 5. +1 because range fn not inclusive
189
+ eeid=ws['C'+str(i)].value
190
+ for c in range(11,endCol+1): #First skills column is 11 offset from col A
191
+ if ws['C'+str(i)].offset(0,c-2).value==1: #subtract 2 from c because the endCol is counted from col A, and we are offsetting from col C, which is 2 offset from A
192
+ jobNm=ws['A3'].offset(0,c).value #if 1 indicates trained, pull job name from header row
193
+ skills.append([eeid,jobNm]) #Add new record to skills table
194
+ #idxs=np.array(skills)[:,0]
195
+ #skills=pd.DataFrame(skills,idxs) #Convert to dataframe
196
+ #skills.set_axis(['eeid','skill'], axis='columns', inplace=True)
197
+ return skills
198
+
199
+ def imptXlTbl(XlFl,ShtNm,TblNm):
200
+ myWb=pyxl.load_workbook(XlFl)
201
+ ws=myWb[ShtNm]
202
+ tab=ws.tables[TblNm] #Pull out table
203
+ tab=[[x.value for x in sublist] for sublist in ws[tab.ref]] #Convert to list of lists (each sublist as row of excel table)
204
+ return tab[1:] #Convert nested lists to array, dropping first row which is table headings
205
+
206
+ def imptPolltbl(XlFl,ShtNm,TblNm,tp=None):
207
+ myWb=pyxl.load_workbook(XlFl)
208
+ ws=myWb[ShtNm]
209
+ tab=ws.tables[TblNm] #Pull out table
210
+ tab=[[x.value for x in sublist] for sublist in ws[tab.ref]] #Convert to list of lists (each sublist as row of excel table)
211
+ tab=tab[1:] #Remove header column
212
+ if tp=='FT': #Pull only FT's into FT table
213
+ tab=[rec for rec in tab if rec[3]!=None] #Remove rows without refusal hours
214
+ tab=[rec for rec in tab if rec[3]<10000] #Ft's id'd by less than 10k refusal hours
215
+ if tp=='P': #Pull only probationaries into table
216
+ tab=[rec for rec in tab if rec[3]!=None] #Remove rows without refusal hours
217
+ tab=[rec for rec in tab if rec[3]>=10000] #Probationaries ID'd by 10K or more refusal hours
218
+ return tab
219
+
220
+ def generateMasterPollTbl(pollDict):
221
+ """Given a dictionary containing the polling tables for all crews, generates a master tbl in SQLlite for being able to filter on peoples availabilities, with '1' indicating interest, '0' no interest, and slot seq 1 starting at index 4"""
222
+ mPollTbl=[]
223
+ #the total list of all fields the table has is programmatically generated on these 3 lines
224
+ flds=["eeid",'lastNm','firstNm','ytdRefHrs']
225
+ flds.extend(['slot_'+str(i) for i in range(1,25)])#Note that there is one field for each slot seqID, 1 through 24, for filtering
226
+ flds.append('Comment')
227
+ for crewKey in pollDict:
228
+ tbl=pollDict[crewKey] #Pull the crew specific OT polling table from dictionary
229
+ for rec in tbl:
230
+ cmnt=rec[16]#retrieve comment to tag on later
231
+ slotwise_polling=list(rec[:4])
232
+ for i in range(4,16):
233
+ if rec[i] not in ('n','N',None) :
234
+ slotwise_polling.extend(['y','y']) #Add two entries because 1 entry in polling sheet applies to two slots
235
+ else:
236
+ slotwise_polling.extend(['n','n'])
237
+ slotwise_polling.append(cmnt)
238
+ mPollTbl.append(slotwise_polling)
239
+ addTBL('allPollData',fields=flds, data=mPollTbl,addOn=False)
240
+
241
+
242
+ def pullTbls(FtBook,TempBook,AssnBook,PollBook): #Need to make volunteer shift data puller
243
+ """Take flNm, return ftInfoTbl, ftSkillsMtx, tempInfoTbl, tempSkillsMtx, AssignmentsTbl, slot_Legend, JobTrnCrossRef, pollDict, All_Slots, senList. Uses functions defined previously to return all required tables at once. Function of functions for final script"""
244
+ a=getFTinfo(FtBook) #to sqlite
245
+ b=getFTskills(FtBook) #to sqlite
246
+ b=[[int(d[0]),d[1]] for d in b] #Cast EEid to numeric value
247
+ c=getTempinfo(TempBook) #to sqlite
248
+ d=getTempskills(TempBook) #to sqlite
249
+ d=[[int(data[0]),data[1]] for data in d] #Cast EEid to numeric value
250
+ e=imptXlTbl(AssnBook,'Assignment_List','Assn_List')
251
+ f=imptXlTbl(AssnBook,'Slot_Legend','Slot_Legend')
252
+ g=imptXlTbl(AssnBook,'Job_Training_Crossref','TrainAssnMtx') #to sqlite
253
+ pollDict={} #Generate empty dictionary to store tables of people voluntary overtime
254
+ for crew in ['Blue','Bud','Rock']:
255
+ for eeType in ['FT','P','Temp']:
256
+ if eeType=='Temp': #If type= Temp, proceed to build table
257
+ keyNm='tbl_'+crew+eeType
258
+ tbl=imptXlTbl(PollBook,'Sheet1',keyNm)
259
+ else:
260
+ keyNm='tbl_'+crew+'FT' #If type= FT OR Probationary, will be referring to FT table in excel, so hard code the string
261
+ tbl=imptPolltbl(PollBook,'Sheet1',keyNm,tp=eeType)
262
+ if eeType=='P': #keyNm was made "FT" instead of 'P' so need to manually enter the key when generating dictionry entry
263
+ pollDict['tbl_'+crew+'P']=tbl
264
+ else:
265
+ pollDict[keyNm]=tbl
266
+ pollDict['tbl_wFT']=imptPolltbl(PollBook,'Sheet1','tbl_wFT',tp='FT') #No nice loop to initialize the WWF crew tables in poll sheet
267
+ pollDict['tbl_wP']=imptPolltbl(PollBook,'Sheet1','tbl_wFT',tp='P')
268
+ pollDict['tbl_wT']=imptXlTbl(PollBook,'Sheet1','tbl_wT')
269
+ h=imptXlTbl(AssnBook,'All_Slots','All_Slots')
270
+ #Generate tables in sqlite
271
+ addTBL("sklMtx",fields=["EEID","trnNm"],data=b,addOn=False) #Overwrite all training data and populate FT ops, then append temps for a master table
272
+ addTBL("sklMtx",fields=["EEID","trnNm"],data=d,addOn=True)
273
+ addTBL("xRef",fields=["dispNm","trnNm"],data=g,addOn=False) #Skill name cross ref table for fcn dispToTrn to work
274
+ addTBL("FTinfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=a,addOn=False)
275
+ addTBL("TempInfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=c,addOn=False)
276
+ # addTBL("FTinfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],dTypes=['NUM','TEXT','NUM','TEXT','TEXT','NUM','NUM','NUM'],data=a,addOn=False)
277
+ # addTBL("TempInfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],dTypes=['INTEGER','TEXT','INTEGER','TEXT','TEXT','INTEGER','INTEGER','INTEGER'],data=c,addOn=False)
278
+ #Generate a master seniority table.. following replaces hire date with integers for temps
279
+ senHiLoTemps=viewTBL('TempInfo',sortBy=[('sen','ASC')]) #First retrieve list of temps, most senior to least
280
+ i=100000 #Start new seniority number at arbitrarily high value not to interfere with full timer
281
+ for row in senHiLoTemps:
282
+ row[0]=i
283
+ i+=1
284
+ #Overwrite/make new master sen ref table. Then append the Temp data with integerized values
285
+ addTBL("senRef",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=a,addOn=False)
286
+ addTBL("senRef",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=senHiLoTemps,addOn=True)
287
+ senList=viewTBL('senRef',sortBy=[('sen','ASC')])
288
+ return a,b,c,d,e,f,g,pollDict,h,senList
289
+
290
+ def dispToTrn(dispNm):
291
+ """Returns the trnNm associated with Display name for a given job. assumes popualted sqlite table 'xRef' with dispNm/trnNm pairs"""
292
+ q=viewTBL('xRef',fields=['dispNm','trnNm'],filterOn=[('dispNm',dispNm)])
293
+ if len(q)==0:
294
+ return "Custom func error 'dispToTrn' no entry found in xRef with dispNm="+str(dispNm)
295
+ return q[0][1]
296
+
297
+ def trnToDisp(trnNm):
298
+ """Returns the trnNm associated with Display name for a given job. assumes popualted sqlite table 'xRef' with dispNm/trnNm pairs"""
299
+ q=viewTBL('xRef',fields=['dispNm','trnNm'],filterOn=[('trnNm',trnNm)])
300
+ if len(q)==0:
301
+ return "Custom func error 'trnToDisp' no entry found in xRef with trnNm="+str(trnNm)
302
+ return [e[0] for e in q] #If multiple DispNms for one train name (e.g. L4 Packer -> Packer, Candling) or Bottle Supply -> etc.
303
+ #Then return list of all dispNms
304
+
305
+ def sklChk(eeid,dispNm):
306
+ """Returns True/False if eeid is trained on job with display name or not. Requires skills matrix named sklMtx in sqlite"""
307
+ trnNm=dispToTrn(dispNm)
308
+ if len(viewTBL('sklMtx',filterOn=[('EEID',eeid),('trnNm',trnNm)]))==0:
309
+ return False
310
+ else:
311
+ return True
312
+
313
+
314
+ def makeEEdict(ftInfoTbl,tempInfoTbl,wkHrs=40,tp='id'):
315
+ eeDict={}
316
+ for dtaTbl in [ftInfoTbl,tempInfoTbl]:
317
+ for row in dtaTbl:
318
+ # if row[1].lower().strip() in ['wwf','bud','blue','rock','silver','gold','student']: #Omit people not in packaging, or off, vacation etc
319
+ if row[2] not in list(eeDict.keys()): #Double check ee hasn't already been generated... why Cory would include an ee on temp table with crew reading 'fulltime' is beyond me but there you go
320
+ eeSkills=viewTBL('sklMtx',['trnNm'],filterOn=[('EEID',row[2])])
321
+ eeSkills=[trnToDisp(nm[0]) for nm in eeSkills] #Gather display names for skills trained on, reducing lists within list to spread elements
322
+ sk=[] #Create empty to accumulate all skills present within sublists of eeSkills
323
+ for s in eeSkills:
324
+ sk.extend(s)
325
+ sen=viewTBL('senRef',fields=['sen'],filterOn=[('id',str(row[2]))])[0][0]
326
+ anEE=ee(sen,row[1].lower().strip(),int(row[2]),row[3],row[4],row[5],row[8]+wkHrs,skills=sk) #Pull info from Refusals sheet
327
+ if tp=='id':
328
+ eeDict[anEE.eeID]=anEE
329
+ elif tp=='nm':
330
+ eeDict[anEE.dispNm().lower().replace(' ','-')]=anEE
331
+ return eeDict
332
+
333
+ def makeSlots(eeDict,AllSlots):
334
+ openSlots={} #Open here meaning unassigned.. Will be required when it comes time to force
335
+ for row in AllSlots:
336
+ if row[6]==1: #Check that the slot generation record is labelled as 'active'
337
+ for i in range(row[0],row[1]+1): #Generate a slot for each index over the range indicated... add 1 because python Range fn not inclusive of end point
338
+ sl=Slot(i, row[2],dispToTrn(row[2]))
339
+ #Determine how many eligible volunteers for this slot
340
+ elig=[] #To track how many people trained
341
+ for rec in viewTBL('allPollData',filterOn=[('slot_'+str(sl.seqID),'y')]): # iterate through results (employee info's) of query on who said yes to working at the time of this slot
342
+ if sl.dispNm in eeDict[rec[0]].skills: elig.append(rec[0]) #Append EEID to list 'elig' if the ee is trained on the job
343
+ sl.eligVol=elig # TTake len() to see number of eligible volunteers for the slot.
344
+ openSlots[str(sl.seqID)+'_'+str(sl.dispNm)]=sl #Enter it into the dictionary
345
+ return openSlots
346
+
347
+ def preProcessData(Acrew,wkHrs,FtBook,TempBook,AssnBook,PollBook,pNT=False,assnWWF=False,pVol=True,xtraDays=None,maxI=100):
348
+ """A function to take input data and generate all necessary tables and objects in memory to carry out algorithm. Return Schedule object containing all workSlot objects, and dictioanry fo all employee objects"""
349
+ ftInfoTbl, ftSkillsMtx, tempInfoTbl, tempSkillsMtx, AssignmentsTbl, slot_Legend, JobTrnCrossRef,pollDict,AllSlots,senList=pullTbls(FtBook,TempBook,AssnBook,PollBook)
350
+ #GenerateMasterPollTbl to facilitate making the Slots... require having a table with all employee preferences.
351
+ generateMasterPollTbl(pollDict)
352
+ #Generate Worker Objects, and assign to dictionary keyed by eeID (numeric key, not string keys)
353
+ eeDict=makeEEdict(ftInfoTbl,tempInfoTbl,wkHrs)
354
+ #Generate Schedule Slot objects (all unassigned slots for weekend)
355
+ allSlots=makeSlots(eeDict,AllSlots)
356
+ return Schedule(Acrew,allSlots,eeDict,AssignmentsTbl,senList,pollDict,slot_Legend,pNT=pNT,assnWWF=assnWWF,pVol=pVol,xtraDays=xtraDays,maxI=maxI)
357
+
358
+
359
+ def getEEinfo(FtBook,TempBook): #Need to make volunteer shift data puller
360
+ """Generate employee objects so as to be able to use their names to read pre generated schedule template."""
361
+ a=getFTinfo(FtBook) #to sqlite
362
+ b=getFTskills(FtBook) #to sqlite
363
+ b=[[int(d[0]),d[1]] for d in b] #Cast EEid to numeric value
364
+ c=getTempinfo(TempBook) #to sqlite
365
+ d=getTempskills(TempBook) #to sqlite
366
+ d=[[int(data[0]),data[1]] for data in d] #Cast EEid to numeric value
367
+
368
+ addTBL("FTinfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=a,addOn=False)
369
+ addTBL("TempInfo",fields=['sen','crew','id','last','first','ytd','totref','totchrg','wtdOT'],data=c,addOn=False)
370
+
371
+ return a,c
372
+
373
+ def addRecs(flNm,shNm,tblNm,data):
374
+ """Adds data to existing excel table in new rows. Used to flesh out tables in visual template (blank tables)"""
375
+ wb=pyxl.load_workbook(flNm)
376
+ ws=wb[shNm]
377
+ t=ws.tables[tblNm]
378
+ ref=t.ref
379
+ row,col=ws[ref[ref.index(':')+1:]].row,ws[ref[:ref.index(':')]].column
380
+ records=data
381
+ for rec in records:
382
+ for i in range(len(rec)):
383
+ ws.cell(column=col+i,row=row+records.index(rec)+1).value=rec[i]
384
+ newT=pyxl.worksheet.table.Table(displayName=t.displayName,ref=t.ref[:-len(str(row))]+str(row+len(records)))
385
+ style = pyxl.worksheet.table.TableStyleInfo(name="TableStyleLight1",showRowStripes=True)
386
+ newT.tableStyleInfo = style
387
+ del ws.tables[tblNm]
388
+ ws.add_table(newT)
389
+ wb.save(filename=flNm)
390
+
391
+ def translate_Visual_Template(flNm,ftRef=None,tRef=None):
392
+ """Takes in an assignment list file, and composes the All_Slots table and Assignment_List table by reading the Visual Template"""
393
+ ftInf,tInf=getEEinfo('Oct3 FTref vo.xlsm','Oct3 Tref vo.xlsm')
394
+ eeDict=makeEEdict(ftInf,tInf,tp='nm')
395
+ # return eeDict
396
+ wb=pyxl.load_workbook(flNm)
397
+ ws=wb['Visual_Template']
398
+ #===========================================
399
+ #Print out All_Slots table. Simply observe which jobs are present
400
+ data=[]
401
+ jbNms={}
402
+ maxR=5
403
+ for i in range(5,100): #Based on template job names start at row 5
404
+ if ws['A'+str(i)].value!=None: #Typically just 25 jobs, should be extra, so skip blanks
405
+ data.append([1,24,ws['A'+str(i)].value,'','','',1])
406
+ jbNms[i]=ws['A'+str(i)].value #key job name by row id
407
+ if i>maxR: maxR=i #Track row of last job assigned
408
+ addRecs(flNm,'All_Slots','All_Slots',data)
409
+ #===========================================
410
+ #Print out Assignment_List
411
+ data=[]
412
+ got=[]
413
+ #First, identify all slots that are part of a merged cell, so we know to skip over those coordinates when we get to them when iterating over every single one
414
+ for mRng in ws.merged_cells.ranges:
415
+ rw,cl=next(mRng.cells) #Grab the first cell coordinates within merged range as this is where text is stored
416
+ if rw>4: #Do not capture title etc.
417
+ if ws.cell(row=rw,column=cl).value==None:
418
+ pass #if a blank cell was left merged, skip it. Therefore it will be assigned as normal
419
+ else:
420
+ got.extend(mRng.cells) #Gather up merged coords into got tracker
421
+ if ws.cell(row=rw,column=cl).fill==pyxl.styles.PatternFill(fill_type="solid",start_color='FFCC99FF',end_color='FFCC99FF'):
422
+ tp='F'
423
+ elif ws.cell(row=rw,column=cl).fill==pyxl.styles.PatternFill(fill_type="solid",start_color='FF00B0F0',end_color='FF00B0F0'):
424
+ tp='WWF'
425
+ elif 'N/A' in ws.cell(row=rw,column=cl).value:
426
+ tp='DNS'
427
+ else: tp='V'
428
+ #Active=1, assnType,start slot, end slot, eeid, job
429
+ #slots are -1 because col 1 in excel is job name. Unkn if 2 or 3 cells mrged so use first cell cooridnate already captured, and known that last cell is last entry in got list
430
+ if tp=='DNS':
431
+ data.append([1,tp,cl-1,got[-1][1]-1,"",jbNms[rw]])
432
+ else:
433
+ if ' ' in ws.cell(row=rw,column=cl).value: #Pull name to use as dictionary key as anything before appearance of a space
434
+ nm=ws.cell(row=rw,column=cl).value[:ws.cell(row=rw,column=cl).value.index(' ')].lower()
435
+ else: nm=ws.cell(row=rw,column=cl).value.lower() #No space, use name as appears
436
+ data.append([1,tp,cl-1,got[-1][1]-1,eeDict[nm].eeID,jbNms[rw]])
437
+ addRecs(flNm,'Assignment_List','Assn_List',data)
438
+ wb.save(filename='Primed_'+flNm)
439
+ return 'Primed_'+flNm