Glider
Loading...
Searching...
No Matches
GenReport.py
Go to the documentation of this file.
1import ssl
2import os
3import csv
4import re
5import pyshorteners
6import sys, traceback
7from datetime import datetime
8from pymongo import MongoClient
9from dotenv import load_dotenv
10from botocore.exceptions import ClientError
11from SendEmail import send_report
12from UploadReports import upload_files_s3
13from ReportSnapshot import create_snapshot
14f_path = __file__
15index = f_path.find("report_generation/")
16f_path = f_path[:index]
17sys.path.insert(1, f_path+'importer')
18from MongoConnection import mongo_connection
19load_dotenv()
20
21
22mongo_conn = mongo_connection()
23
24collection = mongo_conn.mongo_conn_sales()
25
26
27ROOT_DIR = os.path.expanduser('~')
28
29path = ROOT_DIR+"/Reports/"
30if not os.path.exists(path):
31 os.mkdir(path)
32
33def get_month(date):
34 """
35 Generate the filename according to date in 'MonthYear' format.
36
37 Args:
38 date (str): accounting date, i.e processing files date
39 Returns: full_date (str)
40 """
41 m = re.findall(r'-\d{2}-', date)[0]
42 m = m.replace("-", "")
43 month_dic = {"01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct", "11": "Nov", "12": "Dec"}
44 month = month_dic[m]
45 year = re.findall(r'20\d{2}-', date)[0]
46 year = year.replace("-", "")
47 full_date = month+year
48 return full_date
49
50def build_csv(event):
51 """
52 Generates the compressed csv file according to sales which matches with 'accounting_date' field
53
54 Args:
55 event (dict): It contains necessary info related to sales and client
56 Returns: Nothing.
57 """
58 date = event["date"]
59 bucket = event["bucket"]
60 # path to upload files, each month it's a different path
61 s3_path = "{}/monthly_reports/{}/".format(event["path"], date)
62 file = get_month(date)
63 filename = f"{file}.csv"
64 print(f"Creating {filename}")
65 date = datetime.strptime(date, "%Y-%m-%d")
66 csv_columns = ["quantity", "isrc_id", "release_id", "release_title", "track_title", "artists", "label_id", "territory_code", "type", "service_id", "date",
67 "accounting_date", "foreign_currency", "total_foreign", "exchange_rate", "currency_period","local_currency", "total_local"]
68 try:
69 with open(path+filename, 'w', encoding='utf-8') as csvfile:
70 writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
71 writer.writeheader()
72 fields = {"_id":0, "quantity": 1, "isrc_id": 1, "release_id": 1, "release_title": 1, "track_title": 1, "artists": 1, "label_id": 1, "territory_code": 1,
73 "type": 1, "service_id": 1, "date": 1, "accounting_date": 1, "foreign_currency": 1, "total_foreign": 1, "exchange_rate": 1, "currency_period":1, "local_currency": 1, "total_local":1}
74 template_sales = collection.find({"accounting_date": {"$in": [date]}, "client_id": event["client_id"], "file": {"$in":event["files"]}},fields)
75 for post in template_sales:
76 writer.writerow(post)
77
78 if os.path.isfile(f"{path+filename}.gz"): # Delete file if it exists to avoid duplicate files
79 os.system("rm {}.gz".format(path+filename))
80 command = f"gzip {path+filename}"
81 os.system(command) # Compress file to gzip (client requirement)
82 filename = filename+".gz"
83 url_to_download, final_path = upload_files_s3(bucket, s3_path, path, filename)
84 create_snapshot(event, final_path)
85 print(f"{filename} is ready!")
86 if url_to_download == None:
87 raise Exception("Link not generated")
88 # print(send_report(event["client_email"], url_to_download, file))
89 os.system("rm -r {}".format(path+filename))
90 return url_to_download
91 except Exception as e:
92 raise Exception("An error occurred: {}".format(e))
93 # print(sys.exc_info()[2])
94 # print(traceback.format_exc())