""" modules/notifications.py Email notifications and dynamic reformulation triggers for IntelliForm v1.0. Features: 1. Pilot booking confirmation email to customer + Shehan 2. Regulatory alert email when ingredient gets flagged 3. Dynamic reformulation trigger — detects when saved formulation is at risk and suggests alternative Uses SendGrid (free tier: 100 emails/day) or SMTP fallback. Set SENDGRID_API_KEY or SMTP_HOST/SMTP_USER/SMTP_PASS in environment. """ import os import smtplib import json from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import datetime from typing import Dict, Optional, List from dataclasses import dataclass CHEMENOVA_EMAIL = "shehan@chemenova.com" CHEMENOVA_NAME = "Shehan Makani, ChemeNova LLC" @dataclass class EmailResult: sent: bool method: str # sendgrid | smtp | logged message: str # ── Core email sender ───────────────────────────────────────────────────────── def _send_via_sendgrid(to: str, subject: str, html: str, text: str) -> EmailResult: api_key = os.getenv("SENDGRID_API_KEY", "") if not api_key: return EmailResult(sent=False, method="sendgrid", message="No API key") try: import sendgrid from sendgrid.helpers.mail import Mail sg = sendgrid.SendGridAPIClient(api_key=api_key) message = Mail( from_email=CHEMENOVA_EMAIL, to_emails=to, subject=subject, html_content=html, plain_text_content=text, ) response = sg.send(message) return EmailResult(sent=response.status_code in [200, 202], method="sendgrid", message=f"Status {response.status_code}") except Exception as e: return EmailResult(sent=False, method="sendgrid", message=str(e)) def _send_via_smtp(to: str, subject: str, html: str, text: str) -> EmailResult: host = os.getenv("SMTP_HOST", "") user = os.getenv("SMTP_USER", "") pwd = os.getenv("SMTP_PASS", "") port = int(os.getenv("SMTP_PORT", "587")) if not all([host, user, pwd]): return EmailResult(sent=False, method="smtp", message="SMTP not configured") try: msg = MIMEMultipart("alternative") msg["Subject"] = subject msg["From"] = f"{CHEMENOVA_NAME} <{user}>" msg["To"] = to msg.attach(MIMEText(text, "plain")) msg.attach(MIMEText(html, "html")) with smtplib.SMTP(host, port) as server: server.starttls() server.login(user, pwd) server.sendmail(user, to, msg.as_string()) return EmailResult(sent=True, method="smtp", message="Sent via SMTP") except Exception as e: return EmailResult(sent=False, method="smtp", message=str(e)) def _log_email(to: str, subject: str, text: str) -> EmailResult: """Fallback — log email to console when no service configured.""" print(f"\n[EMAIL LOG] To: {to} | Subject: {subject}\n{text}\n") return EmailResult(sent=True, method="logged", message="Logged to console (no email service configured)") def send_email(to: str, subject: str, html: str, text: str) -> EmailResult: result = _send_via_sendgrid(to, subject, html, text) if result.sent: return result result = _send_via_smtp(to, subject, html, text) if result.sent: return result return _log_email(to, subject, text) # ── Email templates ─────────────────────────────────────────────────────────── def send_pilot_booking_confirmation( customer_email: str, customer_name: str, blend: Dict[str, float], cost_per_kg: float, batch_kg: int, quote_usd: float, application: str, ) -> EmailResult: """Send booking confirmation to customer and notification to Shehan.""" blend_lines_html = "".join( f"
Pilot Batch Booking Confirmed
Dear {customer_name},
Your pilot batch request has been received. Here are the details:
| Ingredient | % |
|---|
| Application | {application.replace('_',' ').title()} |
| Batch size | {batch_kg} kg |
| Cost/kg | ${cost_per_kg:.2f} |
| Total quote | ${quote_usd:,.0f} |
| Lead time | 5 business days |
Questions? Reply to this email or contact {CHEMENOVA_EMAIL}
ChemeNova LLC | Pearl River, NJ | chemrichgroup.com | {date_str}
New pilot booking from {customer_name} ({customer_email})
{html}", text=f"New pilot booking from {customer_name} ({customer_email})\n\n{text}", ) return result def send_regulatory_alert( customer_email: str, customer_name: str, ingredient: str, alert_type: str, blend: Dict[str, float], formulation_name: str = "Your saved formulation", ) -> EmailResult: """Alert customer when a saved formulation ingredient gets flagged.""" date_str = datetime.now().strftime("%B %d, %Y") html = f"""IntelliForm Compliance Monitoring
Dear {customer_name},
Your formulation {formulation_name} contains an ingredient that requires attention:
We recommend scheduling a reformulation consultation to maintain your certification status.
Request ReformulationChemeNova LLC | {CHEMENOVA_EMAIL} | {date_str}
ChemeNova LLC x ChemRich Global
Dear {customer_name},
Your green chemistry formulation proposal has been generated.
| Application | {application.replace('_',' ').title()} |
| Cost/kg | ${cost_per_kg:.2f} |
| EcoScore | {eco_score:.0f}/100 |
Ready to move forward? Book a pilot batch and we'll have your certified formulation ready in 5 days.
Book Pilot BatchChemeNova LLC | {CHEMENOVA_EMAIL} | {date_str}