Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import print_function
- import os.path
- import pprint
- from googleapiclient.discovery import build
- import json
- import os
- from google.oauth2 import service_account
- from flask import request
- import requests as r
- SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
- TOTAL_ENTERED_LOCATION = "!D37"
- TOTAL_EXPECTED_LOCATION = "!AH4"
- NAME_LOCATION = "!J4"
- class TimesheetInfo:
- """
- Class to store all the information necessary for the analysing of
- the timesheet
- """
- name: str
- surname: str
- expected_days: int
- entered_days: int
- def __init__(self, name, surname, exp_days, ent_days):
- self.name = str.strip(name)
- self.surname = str.strip(surname)
- self.expected_days = exp_days
- self.entered_days = ent_days
- def auth_sheet_api():
- """
- Authenticate to the google API
- :return: Authenticated service
- """
- dirname = os.path.dirname(__file__)
- filename = os.path.join(dirname, 'process-simplifier-413ad26fa687.json')
- credentials = service_account.Credentials.from_service_account_file(filename)
- creds_scope = credentials.with_scopes(SCOPES)
- service = build('sheets', 'v4', credentials=creds_scope)
- return service
- def get_ranges():
- """
- Get the ranges for the timesheet for the current month
- :return: The range (ie: 'Avril!D37')
- """
- import locale
- import datetime
- ranges = []
- locale.setlocale(locale.LC_TIME, 'fr_FR')
- ranges.append(datetime.datetime.now().strftime("%B") + TOTAL_ENTERED_LOCATION)
- ranges.append(datetime.datetime.now().strftime("%B") + TOTAL_EXPECTED_LOCATION)
- ranges.append(datetime.datetime.now().strftime("%B") + NAME_LOCATION)
- return ranges
- def get_info_from_sheet(service, timesheet_id):
- """
- Method to get all the information necessary form the timesheet to analyse
- :param service: Authenticated service
- :param timesheet_id: Timesheet id
- :return: A object of type TimesheetInfo
- """
- range_names = get_ranges()
- result = service.spreadsheets().values().batchGet(
- spreadsheetId=timesheet_id, ranges=range_names).execute()
- # Name parsing
- name, surname = str.split(result['valueRanges'][2]['values'][0][0], ' - ')
- # Other values
- ent_days = result['valueRanges'][0]['values'][0]
- exp_days = result['valueRanges'][1]['values'][0]
- return TimesheetInfo(name, surname, exp_days, ent_days)
- def validate_timesheet(info: TimesheetInfo):
- """
- Function to validate the number of days in the timesheet
- :param info: TimesheetInfo object
- :return: generate report on JSON format (ie:
- {
- sheet_status: (GOOD, BAD),
- sferien: {
- name: Balon,
- prenom: Antoine
- error : {
- // BAD_FORMATTING,
- // MISSING_DAYS,
- // EMPTY_DAYS,
- // TOO_MANY_DAYS
- }
- }
- """
- data = {
- "sferien" : {
- "name": f"{info.name}",
- "surname": f"{info.surname}"
- },
- "status": "BAD",
- "error" : ""
- }
- if info.entered_days == 0:
- # EMPTY TIMESHEET
- data['error'] = 'EMPTY_TIMESHEET'
- elif info.entered_days < info.expected_days:
- # MISSING DAYS
- data['error'] = 'MISSING_DAYS'
- elif info.entered_days > info.expected_days:
- # TOO MUCH DAYS
- data['error'] = 'TOO_MANY_DAYS'
- else:
- # GOOD
- data['status'] = 'GOOD'
- # If validation of timesheet fail, send an email to sférien
- if data['status'] == "BAD":
- send_email(data)
- pprint.pprint(json.dumps(data))
- return json.dumps(data)
- def get_id_from_request(req):
- """
- Get the id of timesheet from the request
- :param request:
- :return: The id of the request
- """
- return req.args.get('id')
- def send_email(validation_json):
- """
- Call the send-email microservices to send an email to the consultant
- who did not complete his timesheet
- :param validation_json:
- :return: None
- """
- req = r.post("https://europe-west1-process-simplifier.cloudfunctions.net/email-sender",
- json=validation_json)
- # TODO: Log req.status_code to the logger microservice
- def timesheet_validator(request):
- # Get id of timesheet from request
- #id = get_id_from_request(request)
- # Auth
- service = auth_sheet_api()
- # Get the numbers of days entered for this month
- info_timesheet = get_info_from_sheet(service, "12TWOnQZiKbTXlTcgA7FWS_PC9PQRP3ILcDLuwtNNf5Y")
- # Validation of numbers of days
- validation_json = validate_timesheet(info_timesheet)
- # TODO : call to a microservice that maintain the status of every consultant for stat purposes.
- return validation_json
- if __name__ == '__main__':
- timesheet_validator('balbal')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement