crewmeister.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import requests
  2. import json
  3. import pandas as pd
  4. import datetime
  5. from colorama import Fore
  6. from colorama import Style
  7. def pt_to_hours(x):
  8. delta = int(x[2:-1]) / 3600
  9. return round(delta, 2)
  10. #return str(round(delta)) + ":" + str(round((delta - round(delta)) * 60))
  11. def identity(x):
  12. return x
  13. def type_id (x):
  14. if x == 1:
  15. return "Urlaub"
  16. if x == 2:
  17. return "Krank"
  18. if x == 3:
  19. return "Freizeit"
  20. return "anwesend"
  21. class crewmeister():
  22. webservice = "https://api.crewmeister.com/api/v2"
  23. user_name = "bedner@global-cube.de"
  24. user_pass = "7pmicg1w"
  25. crew_id = "26515"
  26. suffix_count = 0
  27. def auth(self):
  28. cookies = {}
  29. r = requests.post(self.webservice + "/user/authentication", { 'userIdentifier': self.user_name, 'password': self.user_pass })
  30. payload = r.json()['payload']
  31. cookies['cmAuthenticationUserToken'] = payload['token']
  32. cookies['cmAuthenticationUserId'] = str(payload['id'])
  33. r = requests.post(self.webservice + "/crew/authentication", { 'crewId': self.crew_id }, cookies=cookies)
  34. payload = r.json()['payload']
  35. cookies['cmAuthenticationCrewToken'] = payload['token']
  36. cookies['cmAuthenticationCrewId'] = payload['id']
  37. return cookies
  38. def userlist(self):
  39. r = requests.get(self.webservice + f"/crew/{self.crew_id}/member", cookies=self.cookies)
  40. return pd.DataFrame(r.json()['payload']).set_index("userId")
  41. def add_to_userlist (self, df):
  42. self.users = self.users.join(df, rsuffix="_"+str(self.suffix_count))
  43. self.suffix_count += 1
  44. def __init__(self):
  45. self.cookies = self.auth()
  46. self.users = self.userlist()
  47. def cm_request(self, querystring, params, cols):
  48. r = requests.get(self.webservice + querystring, params, cookies=self.cookies)
  49. try:
  50. df = pd.DataFrame(r.json()['payload'])
  51. if 'userId' not in df.columns:
  52. df['userId'] = df['groupBy'].map(lambda x: x['userId'])
  53. for (key, (col, map_fun)) in cols.items():
  54. df[key] = df[col].map(map_fun)
  55. items = list(cols.keys())
  56. items.append("userId")
  57. self.add_to_userlist(df.filter(items=items).set_index("userId"))
  58. return True
  59. except Exception as e:
  60. print(r.json())
  61. print(e)
  62. return self.zerofill(cols)
  63. def zerofill(self, cols):
  64. for key in cols.keys():
  65. self.users[key] = 0
  66. return False
  67. def statistics(self):
  68. timestamp = datetime.datetime.now().isoformat()
  69. today = timestamp[:10]
  70. first_of_year = today[:4] + "-01-01"
  71. end_of_year = today[:4] + "-12-31"
  72. prev_month = (datetime.date.fromisoformat(today[:7] + "-01") + datetime.timedelta(days=-1)).isoformat()[:10]
  73. r = requests.get(self.webservice + f"/crew/{self.crew_id}/time-tracking/stamps", { 'startTime': timestamp, 'endTime': timestamp }, cookies=self.cookies)
  74. stamps = pd.DataFrame(r.json()['payload'])
  75. if len(stamps.index) > 0:
  76. self.add_to_userlist(stamps.query("timeAccount==1").groupby('userId').max())
  77. self.cm_request(f"/crew/{self.crew_id}/absence-management/absences", { 'from': today, 'to': today }, { 'absence_today': ("typeId", identity) })
  78. self.cm_request(f"/crew/{self.crew_id}/absence-management/absence-balances", { 'date': first_of_year, 'typeId': 1 }, { 'absence_vac_prev': ("value", identity) })
  79. self.cm_request(f"/crew/{self.crew_id}/absence-management/absence-balances", { 'date': today, 'typeId': 1 }, { 'absence_vacation': ("value", identity) })
  80. self.cm_request(f"/crew/{self.crew_id}/absence-management/absence-balances", { 'date': end_of_year, 'typeId': 1 }, { 'absence_planned': ("value", identity) })
  81. self.cm_request(f"/crew/{self.crew_id}/duration-balances?groupBy%5B%5D=user_id&date%5B%5D={prev_month}", {}, { 'duration_prev_month': ("value", pt_to_hours) })
  82. self.cm_request(f"/crew/{self.crew_id}/duration-balances?groupBy%5B%5D=user_id&date%5B%5D={today}", {}, { 'duration_today': ("value", pt_to_hours) })
  83. return self.users
  84. cm = crewmeister()
  85. user = cm.statistics().loc[86043]
  86. print("Gerade anwesend: " + user['clockInTimestamp'])
  87. print("geplante Abwesenheit heute: " + type_id(user['absence_today']))
  88. print("Urlaub Jahresanfang: " + str(user['absence_vac_prev']))
  89. print("Urlaub genommen: " + str(user['absence_vacation']))
  90. print("Urlaub geplant: " + str(user['absence_planned']))
  91. print("Überstunden Vormonat: " + str(user['duration_prev_month']))
  92. print("Überstunden aktuell: " + str(user['duration_today']))
  93. print(f"{Fore.GREEN}Test!{Style.RESET_ALL}")