Advertisement
Guest User

Untitled

a guest
Apr 26th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.92 KB | None | 0 0
  1. from __future__ import print_function
  2. import os.path
  3. import pprint
  4.  
  5. from googleapiclient.discovery import build
  6. import json
  7. import os
  8. from google.oauth2 import service_account
  9. from flask import request
  10. import requests as r
  11.  
  12.  
  13. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
  14. TOTAL_ENTERED_LOCATION = "!D37"
  15. TOTAL_EXPECTED_LOCATION = "!AH4"
  16. NAME_LOCATION = "!J4"
  17.  
  18.  
  19. class TimesheetInfo:
  20. """
  21. Class to store all the information necessary for the analysing of
  22. the timesheet
  23. """
  24. name: str
  25. surname: str
  26. expected_days: int
  27. entered_days: int
  28.  
  29. def __init__(self, name, surname, exp_days, ent_days):
  30. self.name = str.strip(name)
  31. self.surname = str.strip(surname)
  32. self.expected_days = exp_days
  33. self.entered_days = ent_days
  34.  
  35.  
  36. def auth_sheet_api():
  37. """
  38. Authenticate to the google API
  39. :return: Authenticated service
  40. """
  41. dirname = os.path.dirname(__file__)
  42. filename = os.path.join(dirname, 'process-simplifier-413ad26fa687.json')
  43. credentials = service_account.Credentials.from_service_account_file(filename)
  44. creds_scope = credentials.with_scopes(SCOPES)
  45. service = build('sheets', 'v4', credentials=creds_scope)
  46. return service
  47.  
  48.  
  49. def get_ranges():
  50. """
  51. Get the ranges for the timesheet for the current month
  52. :return: The range (ie: 'Avril!D37')
  53. """
  54. import locale
  55. import datetime
  56.  
  57. ranges = []
  58.  
  59. locale.setlocale(locale.LC_TIME, 'fr_FR')
  60. ranges.append(datetime.datetime.now().strftime("%B") + TOTAL_ENTERED_LOCATION)
  61. ranges.append(datetime.datetime.now().strftime("%B") + TOTAL_EXPECTED_LOCATION)
  62. ranges.append(datetime.datetime.now().strftime("%B") + NAME_LOCATION)
  63. return ranges
  64.  
  65.  
  66. def get_info_from_sheet(service, timesheet_id):
  67. """
  68. Method to get all the information necessary form the timesheet to analyse
  69. :param service: Authenticated service
  70. :param timesheet_id: Timesheet id
  71. :return: A object of type TimesheetInfo
  72. """
  73. range_names = get_ranges()
  74.  
  75. result = service.spreadsheets().values().batchGet(
  76. spreadsheetId=timesheet_id, ranges=range_names).execute()
  77.  
  78. # Name parsing
  79. name, surname = str.split(result['valueRanges'][2]['values'][0][0], ' - ')
  80. # Other values
  81. ent_days = result['valueRanges'][0]['values'][0]
  82. exp_days = result['valueRanges'][1]['values'][0]
  83.  
  84. return TimesheetInfo(name, surname, exp_days, ent_days)
  85.  
  86.  
  87. def validate_timesheet(info: TimesheetInfo):
  88. """
  89. Function to validate the number of days in the timesheet
  90. :param info: TimesheetInfo object
  91. :return: generate report on JSON format (ie:
  92. {
  93. sheet_status: (GOOD, BAD),
  94. sferien: {
  95. name: Balon,
  96. prenom: Antoine
  97. error : {
  98. // BAD_FORMATTING,
  99. // MISSING_DAYS,
  100. // EMPTY_DAYS,
  101. // TOO_MANY_DAYS
  102. }
  103. }
  104. """
  105. data = {
  106. "sferien" : {
  107. "name": f"{info.name}",
  108. "surname": f"{info.surname}"
  109. },
  110. "status": "BAD",
  111. "error" : ""
  112. }
  113.  
  114. if info.entered_days == 0:
  115. # EMPTY TIMESHEET
  116. data['error'] = 'EMPTY_TIMESHEET'
  117.  
  118. elif info.entered_days < info.expected_days:
  119. # MISSING DAYS
  120. data['error'] = 'MISSING_DAYS'
  121.  
  122. elif info.entered_days > info.expected_days:
  123. # TOO MUCH DAYS
  124. data['error'] = 'TOO_MANY_DAYS'
  125. else:
  126. # GOOD
  127. data['status'] = 'GOOD'
  128.  
  129. # If validation of timesheet fail, send an email to sférien
  130. if data['status'] == "BAD":
  131. send_email(data)
  132.  
  133. pprint.pprint(json.dumps(data))
  134. return json.dumps(data)
  135.  
  136.  
  137. def get_id_from_request(req):
  138. """
  139. Get the id of timesheet from the request
  140. :param request:
  141. :return: The id of the request
  142. """
  143. return req.args.get('id')
  144.  
  145.  
  146. def send_email(validation_json):
  147. """
  148. Call the send-email microservices to send an email to the consultant
  149. who did not complete his timesheet
  150. :param validation_json:
  151. :return: None
  152. """
  153. req = r.post("https://europe-west1-process-simplifier.cloudfunctions.net/email-sender",
  154. json=validation_json)
  155. # TODO: Log req.status_code to the logger microservice
  156.  
  157.  
  158. def timesheet_validator(request):
  159. # Get id of timesheet from request
  160. #id = get_id_from_request(request)
  161. # Auth
  162. service = auth_sheet_api()
  163. # Get the numbers of days entered for this month
  164. info_timesheet = get_info_from_sheet(service, "12TWOnQZiKbTXlTcgA7FWS_PC9PQRP3ILcDLuwtNNf5Y")
  165. # Validation of numbers of days
  166. validation_json = validate_timesheet(info_timesheet)
  167.  
  168. # TODO : call to a microservice that maintain the status of every consultant for stat purposes.
  169.  
  170. return validation_json
  171.  
  172. if __name__ == '__main__':
  173. timesheet_validator('balbal')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement