import sys import json import smtplib import datetime import requests from pathlib import Path from numbers import Real from email.message import EmailMessage from jinja2 import Environment, FileSystemLoader, select_autoescape # Load your real config before calling any API GLOBAL_CONFIG_PATH = "config.json" try: with open(GLOBAL_CONFIG_PATH, "r", encoding="utf-8") as f: config = json.load(f) except Exception as e: print(f"Failed to load config: {e}") sys.exit(1) WEB_CONFIG = config.get("WEB", {}) WEB_BASE_URL = WEB_CONFIG.get("BASE_URL") API_CONFIG = config.get("API", {}) BASE_URL = API_CONFIG.get("BASE_URL") SMPT_CONFIG = config.get("SMPT", {}) SMPTSERVER = SMPT_CONFIG.get("SMPTSERVER") PORT = SMPT_CONFIG.get("PORT") SENDER_EMAIL = SMPT_CONFIG.get("SENDER_EMAIL") SENDER_PASSWORD = SMPT_CONFIG.get("SENDER_PASSWORD") RECIPIENT_EMAILS = SMPT_CONFIG.get("RECIPIENT_EMAILS") UNIQUE_IDENTIFIER_CONFIG = config.get("UNIQUE_IDENTIFIER", {}) PROJECT_IDS = UNIQUE_IDENTIFIER_CONFIG.get("PROJECT_IDS") def render_template_from_file(template_name,context): base_dir = Path(__file__).parent env = Environment( loader=FileSystemLoader(searchpath=str(base_dir)), autoescape=select_autoescape(["html", "xml"]) ) tmpl = env.get_template(template_name) return tmpl.render(**context) def fetch_Project_report(project_id): headers = {"Content-Type": "application/json"} try: response = requests.get(f"{BASE_URL}/market/get/project/report/{project_id}", headers=headers) response.raise_for_status() data = response.json()["data"] print("Project report fetched successfully.") return data except Exception as e: print(f"Select tenant error: {e}") return None def get_percentage(part, whole, decimals: int = 2): if not isinstance(part, Real) or not isinstance(whole, Real): raise TypeError("part and whole must be numbers") if whole == 0: return 0.0 return round((part / whole) * 100.0, decimals) if __name__ == "__main__": template_name = "dpr.html" project_ids = [p.strip() for p in PROJECT_IDS.split(",") if p.strip()] for project_id in project_ids: data = fetch_Project_report(project_id) attendance_percentage = get_percentage(data["todaysAttendances"], data["totalEmployees"], 2) task_percentage = get_percentage(data["totalCompletedTask"], data["totalPlannedTask"], 2) web_url = f"{WEB_BASE_URL}/auth/login" context = { "webUrl":web_url, "date": data["date"], "projectName": data["projectName"], "timeStamp": data["timeStamp"], "todaysAttendances": data["todaysAttendances"], "totalEmployees": data["totalEmployees"], "attendancePercentage":data["attendancePercentage"], "taskPercentage":data["taskPercentage"], "regularizationPending": data["regularizationPending"], "checkoutPending": data["checkoutPending"], "totalPlannedWork": data["totalPlannedWork"], "totalCompletedWork": data["totalCompletedWork"], "totalPlannedTask": data["totalPlannedTask"], "totalCompletedTask": data["totalCompletedTask"], "completionStatus": data["completionStatus"], "reportPending": data["reportPending"], "todaysAssignTasks": data["todaysAssignTasks"], "teamOnSite": data["teamOnSite"], "performedTasks": data["performedTasks"], "performedAttendance": data["performedAttendance"] } # print(context) project_name = data["projectName"] html = render_template_from_file(template_name,context) # print(html) today = datetime.datetime.now() formatted = today.strftime("%d-%b-%Y") msg = EmailMessage() msg["Subject"] = f"DPR - {formatted} - {project_name}" msg["From"] = SENDER_EMAIL msg["To"] = RECIPIENT_EMAILS msg.set_content("HTML version attached as alternative.") msg.add_alternative(html, subtype="html") with smtplib.SMTP(SMPTSERVER, PORT) as smtp: smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(SENDER_EMAIL, SENDER_PASSWORD) smtp.send_message(msg)