Commit 61bda7f1 authored by vaisakh.nair's avatar vaisakh.nair 🎯

updated the logic and formatting

parent 1f974d6a
import logging import logging
from scripts.create_report import DailyReportGenerator from scripts.create_report_email_utility import DailyReportGenerator
# Configure logging # Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
...@@ -14,7 +14,8 @@ def generate_daily_report(): ...@@ -14,7 +14,8 @@ def generate_daily_report():
report_path = report_generator.create_excel_report() report_path = report_generator.create_excel_report()
# Send the email with the report # Send the email with the report
#report_generator.send_email_from_ut(filepath=report_path) # please comment out if you are running the create_report.py file without a email method.
report_generator.send_email_from_ut(filepath=report_path)
return report_path return report_path
......
...@@ -7,9 +7,7 @@ from openpyxl.drawing.image import Image ...@@ -7,9 +7,7 @@ from openpyxl.drawing.image import Image
import yaml import yaml
from dotenv import load_dotenv from dotenv import load_dotenv
from collections import defaultdict from collections import defaultdict
import smtplib
import requests
import logging
load_dotenv(dotenv_path='.env') load_dotenv(dotenv_path='.env')
...@@ -78,7 +76,7 @@ class DailyReportGenerator: ...@@ -78,7 +76,7 @@ class DailyReportGenerator:
# Calculate the previous day's date # Calculate the previous day's date
previous_day = current_time - timedelta(days=1) previous_day = current_time - timedelta(days=1)
report_date = previous_day.strftime("%Y-%m-%d") report_date = previous_day.strftime("%Y-%m-%d")
#report_file = f"daily_report_{report_date}.xlsx" report_file = f"daily_report_{report_date}.xlsx"
wb = load_workbook(self.template_file) wb = load_workbook(self.template_file)
sheet = wb.active sheet = wb.active
...@@ -137,49 +135,3 @@ class DailyReportGenerator: ...@@ -137,49 +135,3 @@ class DailyReportGenerator:
# Return the absolute path of the generated report file # Return the absolute path of the generated report file
file_path = os.path.abspath(report_file) file_path = os.path.abspath(report_file)
return file_path return file_path
def get_receiver_emails(self):
# Connect to MongoDB and retrieve the email addresses from the collection
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
collection = db[os.environ["MONGO_COLLECTION_EMAIL"]]
emails = []
documents = collection.find()
for document in documents:
emails.append(document["email"])
return emails
def send_email_from_ut(self,filename="daily_report.xlsx", filepath=None):
logging.info("Sending email to {}".format(self.get_receiver_emails()))
payload = dict()
payload['from_name'] = os.environ["FROM_ADDRESS"]
payload['receiver_list'] = self.get_receiver_emails()
payload['subject'] = self.config['email']['subject']
payload['content'] = self.config['email']['body']
payload['gateway_id'] = os.environ["GATEWAY"]
headers = {'authorization': os.environ["AUTHORIZATION"]}
count = 0
while count < 3:
try:
if filename and filepath:
files = [('attachments', (filename, open(filepath, 'rb'), 'application/html'))]
response = requests.request("POST", os.environ["URL_WITH_ATTACH"], data=payload,
headers=headers, files=files, timeout=10)
logging.info(f"Response status code for request is: {response.status_code}")
if response.status_code == 200:
return True
else:
response = requests.request("POST", os.environ["URL_WITHOUT_ATTACH"], json=payload,
headers=headers, timeout=10)
logging.info(f"Response status code for request is: {response.status_code}")
if response.status_code == 200:
return True
except Exception as e:
logging.error(e)
count += 1
return False
...@@ -7,7 +7,9 @@ from openpyxl.drawing.image import Image ...@@ -7,7 +7,9 @@ from openpyxl.drawing.image import Image
import yaml import yaml
from dotenv import load_dotenv from dotenv import load_dotenv
from collections import defaultdict from collections import defaultdict
import smtplib
import requests
import logging
load_dotenv(dotenv_path='.env') load_dotenv(dotenv_path='.env')
...@@ -82,7 +84,7 @@ class DailyReportGenerator: ...@@ -82,7 +84,7 @@ class DailyReportGenerator:
sheet = wb.active sheet = wb.active
# Set report date # Set report date
sheet['L6'] = report_date sheet['F5'] = report_date
serial_number = 1 serial_number = 1
# Define the shifts and their respective time ranges # Define the shifts and their respective time ranges
...@@ -122,7 +124,7 @@ class DailyReportGenerator: ...@@ -122,7 +124,7 @@ class DailyReportGenerator:
serial_number += 1 serial_number += 1
# Fill the total count in cell E26 # Fill the total count in cell E26
sheet['F26'] = total_count sheet['F25'] = total_count
# Fill the packer counts in column L # Fill the packer counts in column L
for packer_name, count in packer_counts.items(): for packer_name, count in packer_counts.items():
...@@ -135,3 +137,49 @@ class DailyReportGenerator: ...@@ -135,3 +137,49 @@ class DailyReportGenerator:
# Return the absolute path of the generated report file # Return the absolute path of the generated report file
file_path = os.path.abspath(report_file) file_path = os.path.abspath(report_file)
return file_path return file_path
def get_receiver_emails(self):
# Connect to MongoDB and retrieve the email addresses from the collection
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
collection = db[os.environ["MONGO_COLLECTION_EMAIL"]]
emails = []
documents = collection.find()
for document in documents:
emails.append(document["email"])
return emails
def send_email_from_ut(self,filename="daily_report.xlsx", filepath=None):
logging.info("Sending email to {}".format(self.get_receiver_emails()))
payload = dict()
payload['from_name'] = os.environ["FROM_ADDRESS"]
payload['receiver_list'] = self.get_receiver_emails()
payload['subject'] = self.config['email']['subject']
payload['content'] = self.config['email']['body']
payload['gateway_id'] = os.environ["GATEWAY"]
headers = {'authorization': os.environ["AUTHORIZATION"]}
count = 0
while count < 3:
try:
if filename and filepath:
files = [('attachments', (filename, open(filepath, 'rb'), 'application/html'))]
response = requests.request("POST", os.environ["URL_WITH_ATTACH"], data=payload,
headers=headers, files=files, timeout=10)
logging.info(f"Response status code for request is: {response.status_code}")
if response.status_code == 200:
return True
else:
response = requests.request("POST", os.environ["URL_WITHOUT_ATTACH"], json=payload,
headers=headers, timeout=10)
logging.info(f"Response status code for request is: {response.status_code}")
if response.status_code == 200:
return True
except Exception as e:
logging.error(e)
count += 1
return False
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment