import os from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import boto3 from shared.db import get_summary, previous_week _ses = boto3.client("ses") _s3 = boto3.client("s3") def lambda_handler(event, context): week = event.get("week", previous_week()) summary = get_summary(week) if not summary: return {"status": "no_summary", "week": week} payroll_key = summary.get("payroll_csv_s3_key") if not payroll_key: return {"status": "no_payroll_csv", "week": week} bucket = os.environ["REPORTS_BUCKET"] csv_obj = _s3.get_object(Bucket=bucket, Key=payroll_key) csv_content = csv_obj["Body"].read() total_employees = int(summary.get("total_employees", 0)) grand_total = float(summary.get("grand_total", 0)) msg = MIMEMultipart("mixed") msg["Subject"] = f"Meal Order Payroll Deductions — {week}" msg["From"] = os.environ["SENDER_EMAIL"] msg["To"] = os.environ["PAYROLL_EMAIL"] body = MIMEText( f"Attached is the meal order payroll deduction report for {week}.\n\n" f"Employees: {total_employees}\n" f"Total deductions: ${grand_total:.2f}\n\n" f"Please apply these deductions in the next pay period.\n", "plain", ) msg.attach(body) attachment = MIMEApplication(csv_content) attachment.add_header( "Content-Disposition", "attachment", filename=f"payroll-deductions-{week}.csv" ) msg.attach(attachment) _ses.send_raw_email( Source=os.environ["SENDER_EMAIL"], Destinations=[os.environ["PAYROLL_EMAIL"]], RawMessage={"Data": msg.as_string()}, ) return {"status": "sent", "week": week, "to": os.environ["PAYROLL_EMAIL"]}