129 lines
4.7 KiB
Python
129 lines
4.7 KiB
Python
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(f"Project report for project \"{data["projectName"]}\" 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)
|
|
if data["attendancePercentage"]:
|
|
attendance_percentage = data["attendancePercentage"]
|
|
print("from API")
|
|
else:
|
|
attendance_percentage = get_percentage(data["todaysAttendances"], data["totalEmployees"], 2)
|
|
|
|
if data["taskPercentage"]:
|
|
task_percentage = data["taskPercentage"]
|
|
print("from API")
|
|
else:
|
|
task_percentage = get_percentage(data["totalCompletedTask"], data["totalPlannedTask"], 2)
|
|
|
|
web_url = f"{WEB_BASE_URL}/auth/login"
|
|
|
|
dt = datetime.datetime.strptime(data["date"], "%Y-%m-%dT%H:%M:%SZ")
|
|
api_formatted_date = dt.strftime("%d-%b-%Y")
|
|
|
|
context = {
|
|
"webUrl":web_url,
|
|
"date": api_formatted_date,
|
|
"projectName": data["projectName"],
|
|
"timeStamp": data["timeStamp"],
|
|
"todaysAttendances": data["todaysAttendances"],
|
|
"totalEmployees": data["totalEmployees"],
|
|
"attendancePercentage":attendance_percentage,
|
|
"taskPercentage":task_percentage,
|
|
"regularizationPending": data["regularizationPending"],
|
|
"checkoutPending": data["checkoutPending"],
|
|
"totalPlannedWork": round(data["totalPlannedWork"],2),
|
|
"totalCompletedWork": round(data["totalCompletedWork"],2),
|
|
"totalPlannedTask": round(data["totalPlannedTask"],2),
|
|
"totalCompletedTask": round(data["totalCompletedTask"],2),
|
|
"completionStatus": round(data["completionStatus"],2),
|
|
"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)
|
|
|
|
msg = EmailMessage()
|
|
msg["Subject"] = f"DPR - {api_formatted_date} - {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)
|