310 lines
15 KiB
Python
310 lines
15 KiB
Python
import json
|
|
from typing import List, Dict, Any, Optional, Tuple
|
|
from sqlalchemy.orm import Session
|
|
from fastapi import HTTPException, status
|
|
from datetime import datetime, timezone
|
|
from jinja2 import StrictUndefined
|
|
from jinja2.sandbox import SandboxedEnvironment
|
|
from jinja2.meta import find_undeclared_variables
|
|
import ulid
|
|
|
|
from app.models.NotificationTemplateModel import NotificationTemplate
|
|
from app.schemas.NotificationTemplate import (
|
|
NotificationTemplateCreate,
|
|
NotificationTemplateUpdate
|
|
)
|
|
from app.services.EmailTemplateService import EmailTemplateService
|
|
|
|
EVENT_REGISTRY = {
|
|
"ORDER_CREATED": {
|
|
"description": "Triggered when a customer places an order",
|
|
"variables": [
|
|
{"name": "customer_name", "description": "Customer's full name", "example": "Adithiyan"},
|
|
{"name": "order_id", "description": "Order identifier", "example": "ORD-123"},
|
|
{"name": "order_no", "description": "Order number", "example": "ORD-123"},
|
|
{"name": "invoice_no", "description": "Invoice number", "example": "INV-123"},
|
|
{"name": "subtotal", "description": "Order subtotal amount", "example": "1499"},
|
|
{"name": "tax_amount", "description": "Order tax amount", "example": "100"},
|
|
{"name": "total_amount", "description": "Order total / Final amount", "example": "1599"},
|
|
{"name": "final_amount", "description": "Order total / Final amount", "example": "1599"},
|
|
{"name": "payment_status", "description": "Payment status", "example": "PAID"},
|
|
{"name": "pdf_url", "description": "Link to download the invoice PDF", "example": "https://ifixkart.com/invoice/INV-123.pdf"},
|
|
{"name": "store_logo_url", "description": "Store logo image URL", "example": "https://admin.trionixsolution.com/images/logo/ifixkart-logo.webp"},
|
|
{"name": "items", "description": "List of ordered items (use with {% for item in items %})", "example": "[]"}
|
|
]
|
|
},
|
|
"NEW_ORDER_ALERT": {
|
|
"description": "Triggered to notify admins of a new order",
|
|
"variables": [
|
|
{"name": "order_id", "description": "Order identifier", "example": "ORD-123"}
|
|
]
|
|
},
|
|
"SERVICE_BOOKED": {
|
|
"description": "Triggered when a repair service is booked",
|
|
"variables": [
|
|
{"name": "customer_name", "description": "Customer's full name", "example": "Adithiyan"},
|
|
{"name": "job_no", "description": "Service Job Number", "example": "JOB-1234"},
|
|
{"name": "invoice_no", "description": "Invoice Reference", "example": "INV-4321"},
|
|
{"name": "service_name", "description": "Name of the service / repair", "example": "iPhone 13 Screen Replacement"},
|
|
{"name": "subtotal", "description": "Subtotal amount", "example": "2500"},
|
|
{"name": "paid_amount", "description": "Amount already paid", "example": "500"},
|
|
{"name": "balance", "description": "Balance due amount", "example": "2000"},
|
|
{"name": "pdf_url", "description": "URL to download invoice PDF", "example": "https://ifixkart.com/invoice/INV-4321.pdf"},
|
|
{"name": "store_logo_url", "description": "Store logo image url", "example": "https://admin.trionixsolution.com/images/logo/ifixkart-logo.webp"}
|
|
]
|
|
},
|
|
"SERVICE_READY": {
|
|
"description": "Triggered when a repair is completed and ready for pickup/delivery",
|
|
"variables": [
|
|
{"name": "customer_name", "description": "Customer's full name", "example": "Adithiyan"},
|
|
{"name": "job_no", "description": "Service Job Number", "example": "JOB-1234"},
|
|
{"name": "invoice_no", "description": "Invoice Reference", "example": "INV-4321"},
|
|
{"name": "service_name", "description": "Name of the service / repair", "example": "iPhone 13 Screen Replacement"},
|
|
{"name": "subtotal", "description": "Subtotal amount", "example": "2500"},
|
|
{"name": "paid_amount", "description": "Amount already paid", "example": "500"},
|
|
{"name": "balance", "description": "Balance due amount", "example": "2000"},
|
|
{"name": "pdf_url", "description": "URL to download invoice PDF", "example": "https://ifixkart.com/invoice/INV-4321.pdf"},
|
|
{"name": "store_logo_url", "description": "Store logo image url", "example": "https://admin.trionixsolution.com/images/logo/ifixkart-logo.webp"}
|
|
]
|
|
},
|
|
"ORDER_STATUS_CHANGED": {
|
|
"description": "Triggered when an order status is updated",
|
|
"variables": [
|
|
{"name": "order_id", "description": "Order identifier", "example": "ORD-123"},
|
|
{"name": "status", "description": "New status of the order", "example": "SHIPPED"}
|
|
]
|
|
},
|
|
"SERVICE_BOOKED_INTERNAL": {
|
|
"description": "Internal alert when a service is booked",
|
|
"variables": [
|
|
{"name": "job_no", "description": "Service Job Number", "example": "JOB-1234"}
|
|
]
|
|
},
|
|
"SERVICE_STATUS_CHANGED": {
|
|
"description": "Triggered when a repair status changes",
|
|
"variables": [
|
|
{"name": "job_no", "description": "Service Job Number", "example": "JOB-1234"},
|
|
{"name": "status", "description": "New status of the repair", "example": "IN_PROGRESS"}
|
|
]
|
|
},
|
|
"INVENTORY_LOW_STOCK": {
|
|
"description": "Triggered when product inventory falls below threshold",
|
|
"variables": [
|
|
{"name": "product_name", "description": "Name of the product", "example": "iPhone 13 Battery"},
|
|
{"name": "stock_level", "description": "Current stock quantity", "example": "2"}
|
|
]
|
|
},
|
|
"REFUND_TRIGGERED": {
|
|
"description": "Triggered when a refund is processed",
|
|
"variables": [
|
|
{"name": "order_id", "description": "Order identifier", "example": "ORD-123"},
|
|
{"name": "amount", "description": "Refund amount", "example": "500"}
|
|
]
|
|
},
|
|
"END_OF_DAY_REPORT": {
|
|
"description": "Daily summary of sales and repairs",
|
|
"variables": [
|
|
{"name": "report_date", "description": "Date of the report", "example": "2023-10-01"},
|
|
{"name": "total_orders", "description": "Total number of orders", "example": "15"},
|
|
{"name": "order_revenue", "description": "Total sales amount", "example": "15000"},
|
|
{"name": "services_completed", "description": "Total services completed", "example": "5"}
|
|
]
|
|
},
|
|
"REPAIR_SLA_BREACH": {
|
|
"description": "Alert when a repair takes longer than the SLA",
|
|
"variables": [
|
|
{"name": "job_no", "description": "Service Job Number", "example": "JOB-1234"},
|
|
{"name": "days_open", "description": "Number of days open", "example": "4"},
|
|
{"name": "status", "description": "Current status of the repair", "example": "WAITING_FOR_PARTS"}
|
|
]
|
|
},
|
|
"WARRANTY_EXPIRING_SOON": {
|
|
"description": "Alert 7 days before a warranty expires",
|
|
"variables": [
|
|
{"name": "warranty_id", "description": "Warranty ID", "example": "01H2..."},
|
|
{"name": "reference_id", "description": "Order or Service Job ID", "example": "ORD-1234"},
|
|
{"name": "end_date", "description": "Date of expiration", "example": "2023-10-01"}
|
|
]
|
|
}
|
|
# Add more events as needed
|
|
}
|
|
|
|
class TemplateService:
|
|
_env = SandboxedEnvironment(undefined=StrictUndefined)
|
|
|
|
@staticmethod
|
|
def _validate_and_extract_variables(event_key: str, template_body: str, template_subject: Optional[str] = None) -> List[str]:
|
|
if event_key not in EVENT_REGISTRY:
|
|
raise HTTPException(status_code=400, detail=f"Unsupported event_key: {event_key}")
|
|
|
|
allowed_variables = {v["name"] for v in EVENT_REGISTRY[event_key]["variables"]}
|
|
|
|
# Replace HTML entities often inserted by rich text editors
|
|
template_body = template_body.replace(" ", " ").replace("\u200b", "")
|
|
if template_subject:
|
|
template_subject = template_subject.replace(" ", " ").replace("\u200b", "")
|
|
|
|
# Combine subject and body to find all undeclared variables
|
|
full_text = template_body
|
|
if template_subject:
|
|
full_text = template_subject + " " + template_body
|
|
|
|
try:
|
|
ast = TemplateService._env.parse(full_text)
|
|
undeclared = find_undeclared_variables(ast)
|
|
except Exception as e:
|
|
raise HTTPException(status_code=400, detail=f"Jinja2 Syntax Error: {str(e)}")
|
|
|
|
unsupported = undeclared - allowed_variables
|
|
if unsupported:
|
|
raise HTTPException(status_code=400, detail=f"Unsupported variables for {event_key}: {', '.join(unsupported)}")
|
|
|
|
return list(undeclared)
|
|
|
|
@staticmethod
|
|
def render_template(db: Session, event_key: str, channel: str, context: dict, tenant_id: str = "tenant_default") -> Optional[Tuple[str, str]]:
|
|
try:
|
|
template = db.query(NotificationTemplate).filter(
|
|
NotificationTemplate.tenant_id == tenant_id,
|
|
NotificationTemplate.event_key == event_key,
|
|
NotificationTemplate.channel == channel,
|
|
NotificationTemplate.is_active == True
|
|
).first()
|
|
except Exception as query_ex:
|
|
import logging
|
|
logging.getLogger(__name__).warning(f"Error querying notification template: {query_ex}")
|
|
return None
|
|
|
|
if not template:
|
|
return None
|
|
|
|
try:
|
|
compiled_subject = ""
|
|
if template.subject:
|
|
clean_subject = template.subject.replace(" ", " ").replace("\u200b", "")
|
|
jinja_subject = TemplateService._env.from_string(clean_subject)
|
|
compiled_subject = jinja_subject.render(**context)
|
|
|
|
clean_body = template.body_content.replace(" ", " ").replace("\u200b", "")
|
|
jinja_body = TemplateService._env.from_string(clean_body)
|
|
compiled_body = jinja_body.render(**context)
|
|
|
|
if channel == "EMAIL" and event_key == "ORDER_CREATED":
|
|
compiled_body = EmailTemplateService.order_invoice_email_wrapper(compiled_body, context)
|
|
|
|
return compiled_subject, compiled_body
|
|
except Exception as e:
|
|
import logging
|
|
logger = logging.getLogger(__name__)
|
|
logger.error(f"Failed to render template {template.template_id} for event {event_key}: {str(e)}")
|
|
return None
|
|
|
|
@staticmethod
|
|
def preview_template(body_content: str, subject: Optional[str], context: dict) -> Tuple[str, str]:
|
|
# Handle FastAPI dict wrapping if context is sent as {"context": {...}}
|
|
if len(context) == 1 and "context" in context:
|
|
context = context["context"]
|
|
|
|
try:
|
|
compiled_subject = ""
|
|
if subject:
|
|
clean_subject = subject.replace(" ", " ").replace("\u200b", "")
|
|
jinja_subject = TemplateService._env.from_string(clean_subject)
|
|
compiled_subject = jinja_subject.render(**context)
|
|
|
|
clean_body = body_content.replace(" ", " ").replace("\u200b", "")
|
|
jinja_body = TemplateService._env.from_string(clean_body)
|
|
compiled_body = jinja_body.render(**context)
|
|
|
|
# Since preview doesn't strictly have an event_key passed in, we can infer by trying to wrap it if it has order-like context variables
|
|
if "invoice_no" in context and "order_no" in context and "<html" not in body_content.lower():
|
|
compiled_body = EmailTemplateService.order_invoice_email_wrapper(compiled_body, context)
|
|
|
|
return compiled_subject, compiled_body
|
|
except Exception as e:
|
|
raise HTTPException(status_code=400, detail=f"Preview render failed: {str(e)}")
|
|
|
|
@staticmethod
|
|
def get_templates(db: Session, tenant_id: str = "tenant_default") -> List[NotificationTemplate]:
|
|
return db.query(NotificationTemplate).filter(NotificationTemplate.tenant_id == tenant_id).all()
|
|
|
|
@staticmethod
|
|
def create_template(db: Session, data: NotificationTemplateCreate, user_id: str, tenant_id: str = "tenant_default") -> NotificationTemplate:
|
|
variables = TemplateService._validate_and_extract_variables(data.event_key, data.body_content, data.subject)
|
|
|
|
# Check unique constraint (only one per tenant + event + channel)
|
|
existing = db.query(NotificationTemplate).filter(
|
|
NotificationTemplate.tenant_id == tenant_id,
|
|
NotificationTemplate.event_key == data.event_key,
|
|
NotificationTemplate.channel == data.channel
|
|
).first()
|
|
|
|
if existing:
|
|
raise HTTPException(status_code=400, detail=f"A template already exists for {data.event_key} on channel {data.channel}")
|
|
|
|
template = NotificationTemplate(
|
|
template_id=str(ulid.ULID()),
|
|
tenant_id=tenant_id,
|
|
event_key=data.event_key,
|
|
name=data.name,
|
|
channel=data.channel,
|
|
subject=data.subject,
|
|
body_content=data.body_content,
|
|
variables=variables,
|
|
is_active=data.is_active,
|
|
created_by=user_id,
|
|
updated_by=user_id
|
|
)
|
|
db.add(template)
|
|
db.commit()
|
|
db.refresh(template)
|
|
return template
|
|
|
|
@staticmethod
|
|
def update_template(db: Session, template_id: str, data: NotificationTemplateUpdate, user_id: str, tenant_id: str = "tenant_default") -> NotificationTemplate:
|
|
template = db.query(NotificationTemplate).filter(
|
|
NotificationTemplate.template_id == template_id,
|
|
NotificationTemplate.tenant_id == tenant_id
|
|
).first()
|
|
|
|
if not template:
|
|
raise HTTPException(status_code=404, detail="Template not found")
|
|
|
|
if data.body_content is not None or data.subject is not None:
|
|
new_body = data.body_content if data.body_content is not None else template.body_content
|
|
new_subject = data.subject if data.subject is not None else template.subject
|
|
variables = TemplateService._validate_and_extract_variables(template.event_key, new_body, new_subject)
|
|
template.body_content = new_body
|
|
template.subject = new_subject
|
|
template.variables = variables
|
|
|
|
if data.name is not None:
|
|
template.name = data.name
|
|
if data.is_active is not None:
|
|
template.is_active = data.is_active
|
|
|
|
template.updated_by = user_id
|
|
template.updated_at = datetime.now(timezone.utc)
|
|
|
|
db.commit()
|
|
db.refresh(template)
|
|
return template
|
|
|
|
@staticmethod
|
|
def toggle_activation(db: Session, template_id: str, is_active: bool, user_id: str, tenant_id: str = "tenant_default") -> NotificationTemplate:
|
|
template = db.query(NotificationTemplate).filter(
|
|
NotificationTemplate.template_id == template_id,
|
|
NotificationTemplate.tenant_id == tenant_id
|
|
).first()
|
|
|
|
if not template:
|
|
raise HTTPException(status_code=404, detail="Template not found")
|
|
|
|
template.is_active = is_active
|
|
template.updated_by = user_id
|
|
template.updated_at = datetime.now(timezone.utc)
|
|
|
|
db.commit()
|
|
db.refresh(template)
|
|
return template
|
|
|