miranda-schedule-checker-v2.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import collections
  2. import fileinput
  3. # https://docs.google.com/spreadsheets/d/1FzYvO825t1de0UpzL3ovzkXE3cRiXGZetLt1zCzzWjE/edit#gid=0
  4. class Color(object):
  5. _ENDC = '\033[0m'
  6. HEADER = '\033[95m%s' + _ENDC
  7. BLUE = '\033[94m%s' + _ENDC
  8. GREEN = '\033[92m%s' + _ENDC
  9. YELLOW = '\033[93m%s' + _ENDC
  10. RED = '\033[91m%s' + _ENDC
  11. BOLD = '\033[1m%s' + _ENDC
  12. UNDERLINE = '\033[4m%s' + _ENDC
  13. _IGNORED = {
  14. 'R',
  15. 'ML',
  16. }
  17. _LEAVE_CODES = {
  18. 'AL',
  19. 'A/L',
  20. 'SD',
  21. 'BH',
  22. }
  23. _DOWS = {
  24. 'Mon',
  25. 'Tue',
  26. 'Wed',
  27. 'Thu',
  28. 'Fri',
  29. 'Sat',
  30. 'Sun',
  31. }
  32. def _parse_roster(columns):
  33. if columns[0]:
  34. return {columns[0]: columns[1:]}
  35. elif columns[1].isdigit() or columns[1].startswith('-'):
  36. return {'dates': [int(x) for x in columns[1:] if x]}
  37. elif columns[1]:
  38. return {'dows': columns[1:]}
  39. else:
  40. return {}
  41. def _parse_staff(columns):
  42. return {
  43. 'name': columns[0],
  44. 'hours': float(columns[1]),
  45. 'driver': columns[2].lower().startswith('y'),
  46. 'gender': columns[3],
  47. }
  48. def _parse_reqs(columns):
  49. if columns[1] in _DOWS:
  50. return {}
  51. elif columns[1].startswith('-') or columns[1].isdigit():
  52. return {}
  53. else:
  54. return {i: v for i, v in enumerate(columns[1:]) if v}
  55. def _block_shared(columns):
  56. pass
  57. def parse():
  58. lines = [x for x in fileinput.input()]
  59. lines.reverse()
  60. roster = {}
  61. staff = []
  62. reqs = collections.defaultdict(list)
  63. blocked = []
  64. func = None
  65. while lines:
  66. line = lines.pop().rstrip('\n').lstrip('"')
  67. if not line.strip():
  68. continue
  69. if line.startswith('#'):
  70. continue
  71. if line.startswith('END'):
  72. break
  73. if line.startswith('Roster'):
  74. func = _parse_roster
  75. elif line.startswith('Name'):
  76. func = _parse_staff
  77. elif line.startswith('Shift requirements'):
  78. func = _parse_reqs
  79. elif line.startswith('Block shared shifts'):
  80. func = _block_shared
  81. else:
  82. columns = line.split('\t')
  83. if func == _parse_reqs:
  84. for i, v in func(columns).iteritems():
  85. reqs[i].append(v)
  86. elif func == _parse_roster:
  87. roster.update(_parse_roster(columns))
  88. elif func == _parse_staff:
  89. staff.append(_parse_staff(columns))
  90. elif func == _block_shared:
  91. blocked.append([c for c in columns if c])
  92. reqs = [reqs[i] for i in range(max(reqs.keys())+1)]
  93. return staff, reqs, roster, blocked
  94. def _get_req_deltas(full_reqs, roster, staff):
  95. names = [x['name'] for x in staff]
  96. missing = []
  97. extra = []
  98. # copy shift requirements for >0 days to format {day: [shifts]}
  99. reqs_copy = {}
  100. for reqs, date in zip(full_reqs, roster['dates']):
  101. if date > 0:
  102. reqs_copy[date] = [req for req in reqs]
  103. for name in names:
  104. for date, shift in zip(roster['dates'], roster[name]):
  105. if date > 0 and shift:
  106. if shift in _IGNORED or shift in _LEAVE_CODES:
  107. continue
  108. if shift.startswith('T/'):
  109. continue
  110. if shift in reqs_copy.get(date, []):
  111. reqs_copy[date].remove(shift)
  112. else:
  113. extra.append((date, shift))
  114. missing = []
  115. for date, reqs in reqs_copy.iteritems():
  116. missing.extend([(date, req) for req in reqs])
  117. return sorted(extra), sorted(missing)
  118. def _parse_shift(shift):
  119. if shift in ['ML', 'AL', 'A/L', 'BH', 'SD']:
  120. return None, None, 8
  121. if shift.startswith('T/'):
  122. return None, None, float(shift[2:])
  123. if shift == 'N':
  124. return 21, 21+12, 12
  125. if shift == 'R':
  126. return None, None, None
  127. if shift[0].isdigit():
  128. start, end = shift.split('/')
  129. return float(start), float(end), float(end) - float(start)
  130. return None, None, None
  131. def _get_staff_delta(member, roster):
  132. total_hours = 0
  133. for date, shift in zip(roster['dates'], roster[member['name']]):
  134. if date > 0 and shift:
  135. _, _, length = _parse_shift(shift)
  136. if length:
  137. total_hours += length
  138. return total_hours, total_hours - member['hours']
  139. def get_cover(staff, roster):
  140. cover = collections.defaultdict(int)
  141. for member in staff:
  142. for date, shift in zip(roster['dates'], roster[member['name']]):
  143. if shift:
  144. start, end, _ = _parse_shift(shift)
  145. if start is not None:
  146. for hr in range(int(start), int(end)):
  147. _date = date if hr < 24 else date + 1
  148. cover[_date, hr % 24] += 1
  149. return cover
  150. def print_covers(covers, roster, colormap):
  151. dates = [d for d in roster['dates'] if d > 0]
  152. s = ''
  153. for label, _ in covers:
  154. s += ' ' + label + ' ' * (26 - len(label))
  155. print s
  156. print ''
  157. hr_str = ''
  158. for _ in covers:
  159. hr_str += ' ' + ''.join([str(hr)[-1] for hr in range(24)])
  160. print hr_str
  161. for d in dates:
  162. s = ''
  163. for label, cover in covers:
  164. s += ' %s%i ' % (' ' if d < 10 else '', d)
  165. for hr in range(24):
  166. _cover = cover.get((d, hr), 0)
  167. if _cover == 0:
  168. s += ' '
  169. elif _cover in colormap:
  170. s += colormap[_cover] % _cover
  171. else:
  172. s += colormap[None] % _cover
  173. print s
  174. print hr_str
  175. def evaluate(staff, reqs, roster):
  176. total_abs_deltas = 0
  177. for member in staff:
  178. print member['name']
  179. total_hours, delta = _get_staff_delta(member, roster)
  180. total_abs_deltas += abs(delta)
  181. color = Color.RED
  182. if abs(delta) < 7:
  183. color = Color.YELLOW
  184. if abs(delta) < 4:
  185. color = Color.GREEN
  186. print color % ('\tHours: %s (%s%s)' % (total_hours, '+' if delta >= 0 else '', delta))
  187. print ''
  188. def run():
  189. staff, reqs, roster, blocked = parse()
  190. # staff: [{"name": string, "hours": float, "driver": bool, "gender": string}]
  191. # reqs: [[string]], e.g. [[], ["7/9", "12/21"]]
  192. # roster: {name: [string], "dows": [string], "dates": [int]}
  193. evaluate(staff, reqs, roster)
  194. print ''
  195. covers = [
  196. ('Cover (overall)', get_cover(staff, roster)),
  197. ('Cover (male)', get_cover([x for x in staff if x['gender'] == 'M'], roster)),
  198. ('Cover (drivers)', get_cover([x for x in staff if x['driver']], roster)),
  199. ]
  200. colormap = {
  201. 1: Color.BLUE,
  202. 2: Color.GREEN,
  203. None: Color.RED,
  204. }
  205. print_covers(covers, roster, colormap)
  206. print ''
  207. print ''
  208. covers = []
  209. for i, names in enumerate(blocked):
  210. _staff = [s for s in staff if s['name'] in names]
  211. covers.append(('Blocked (%i)' % (i+1), get_cover(_staff, roster)))
  212. colormap = {
  213. 1: Color.BLUE,
  214. None: Color.RED,
  215. }
  216. print_covers(covers, roster, colormap)
  217. return
  218. print ''
  219. print ''
  220. extra, missing = _get_req_deltas(reqs, roster, staff)
  221. print 'extra:'
  222. for date, v in extra:
  223. print '\t', date, v
  224. print 'missing:'
  225. for date, v in missing:
  226. print '\t', date, v
  227. run()