feat: EmailDeliveryService + professional DSR email templates
- EmailDeliveryService: load template → find published version →
render {{variables}} → send via SMTP → audit log. Fallback to
inline HTML when no published template exists.
- Migration 117: Professional HTML/text content for all 5 DSR
templates (receipt, completion, rejection, identity, extension)
with branded styling and proper Art. references
- DSRArt11Service now uses EmailDeliveryService with dsr_rejection
template instead of hardcoded HTML
[migration-approved]
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -75,33 +75,26 @@ class DSRArt11Service:
|
||||
if not dsr.requester_email:
|
||||
return
|
||||
try:
|
||||
from compliance.services.smtp_sender import send_email
|
||||
send_email(
|
||||
from compliance.services.email_delivery_service import EmailDeliveryService
|
||||
delivery = EmailDeliveryService(self._db)
|
||||
variables = {
|
||||
"requester_name": dsr.requester_name or "Antragsteller/in",
|
||||
"reference_number": dsr.request_number or "",
|
||||
"rejection_reason": "Identifikation nicht moeglich — Art. 11 Abs. 1 DSGVO",
|
||||
"legal_basis": "Art. 11 Abs. 1 DSGVO",
|
||||
"sender_name": "Datenschutzbeauftragter",
|
||||
}
|
||||
# Use published dsr_rejection template, fallback to inline
|
||||
delivery.send(
|
||||
tenant_id=str(dsr.tenant_id),
|
||||
template_type="dsr_rejection",
|
||||
recipient=dsr.requester_email,
|
||||
subject=f"Zu Ihrer Anfrage {dsr.request_number} — Art. 11 DSGVO",
|
||||
body_html=f"""
|
||||
<div style="font-family:system-ui,sans-serif;max-width:600px;margin:0 auto;">
|
||||
<div style="background:#6b7280;color:white;padding:20px 24px;border-radius:12px 12px 0 0;">
|
||||
<h1 style="margin:0;font-size:20px;">Mitteilung zu Ihrer Anfrage</h1>
|
||||
</div>
|
||||
<div style="background:white;padding:24px;border:1px solid #e5e7eb;border-top:none;border-radius:0 0 12px 12px;">
|
||||
<p>Sehr geehrte/r Antragsteller/in,</p>
|
||||
<p>wir haben Ihre Anfrage ({dsr.request_number}) gemaess Art. 15 DSGVO
|
||||
erhalten und geprueft.</p>
|
||||
<p>Leider koennen wir die bei uns gespeicherten Daten (anonymisierte
|
||||
Cookies, IP-Hashes) <strong>keiner identifizierbaren Person zuordnen</strong>.</p>
|
||||
<p>Gemaess <strong>Art. 11 Abs. 1 DSGVO</strong> sind wir nicht verpflichtet,
|
||||
zusaetzliche Informationen zu erheben, um Sie zu identifizieren.
|
||||
Eine Auskunftserteilung ist daher nicht moeglich.</p>
|
||||
<p>Sollten Sie ueber ein Kundenkonto bei uns verfuegen, koennen Sie
|
||||
die Anfrage unter Angabe Ihrer Kundennummer erneut einreichen.</p>
|
||||
<p style="margin-top:24px;color:#6b7280;font-size:12px;">
|
||||
Mit freundlichen Gruessen<br>
|
||||
<strong>Datenschutzbeauftragter</strong>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
variables=variables,
|
||||
fallback_subject=f"Zu Ihrer Anfrage {dsr.request_number} — Art. 11 DSGVO",
|
||||
fallback_html=f"""<p>Sehr geehrte/r {dsr.requester_name or 'Antragsteller/in'},</p>
|
||||
<p>wir koennen die bei uns gespeicherten Daten keiner identifizierbaren Person zuordnen.
|
||||
Gemaess Art. 11 Abs. 1 DSGVO ist eine Auskunftserteilung nicht moeglich.</p>
|
||||
<p>Mit freundlichen Gruessen<br/>Datenschutzbeauftragter</p>""",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Art. 11 notification failed: %s", e)
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
"""
|
||||
Email Template Delivery Service — the missing integration layer.
|
||||
|
||||
Combines: template loading → published version → variable rendering → SMTP → audit log.
|
||||
Used by DSR workflow, document reviews, and other modules that need to send
|
||||
templated emails.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from compliance.db.email_template_models import (
|
||||
EmailSendLogDB,
|
||||
EmailTemplateDB,
|
||||
EmailTemplateVersionDB,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _render(html: str, variables: dict[str, str]) -> str:
|
||||
"""Replace {{variable}} placeholders with values."""
|
||||
result = html
|
||||
for key, value in variables.items():
|
||||
result = result.replace(f"{{{{{key}}}}}", str(value))
|
||||
return result
|
||||
|
||||
|
||||
class EmailDeliveryService:
|
||||
"""Load template → render → send via SMTP → log."""
|
||||
|
||||
def __init__(self, db: Session) -> None:
|
||||
self.db = db
|
||||
|
||||
def get_published_version(
|
||||
self, tenant_id: str, template_type: str,
|
||||
) -> Optional[EmailTemplateVersionDB]:
|
||||
"""Get the latest published version of a template by type."""
|
||||
tid = uuid.UUID(tenant_id)
|
||||
template = (
|
||||
self.db.query(EmailTemplateDB)
|
||||
.filter(EmailTemplateDB.tenant_id == tid, EmailTemplateDB.template_type == template_type)
|
||||
.first()
|
||||
)
|
||||
if not template:
|
||||
return None
|
||||
return (
|
||||
self.db.query(EmailTemplateVersionDB)
|
||||
.filter(
|
||||
EmailTemplateVersionDB.template_id == template.id,
|
||||
EmailTemplateVersionDB.status == "published",
|
||||
)
|
||||
.order_by(EmailTemplateVersionDB.created_at.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
def send(
|
||||
self,
|
||||
tenant_id: str,
|
||||
template_type: str,
|
||||
recipient: str,
|
||||
variables: dict[str, str],
|
||||
fallback_subject: Optional[str] = None,
|
||||
fallback_html: Optional[str] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Send a templated email. Falls back to inline HTML if no published template.
|
||||
|
||||
Args:
|
||||
tenant_id: Tenant UUID string.
|
||||
template_type: E.g. 'dsr_receipt', 'dsr_completion'.
|
||||
recipient: Email address.
|
||||
variables: Dict of {{key}}: value for rendering.
|
||||
fallback_subject: Subject if no template found.
|
||||
fallback_html: HTML body if no template found.
|
||||
"""
|
||||
from compliance.services.smtp_sender import send_email
|
||||
|
||||
tid = uuid.UUID(tenant_id)
|
||||
version = self.get_published_version(tenant_id, template_type)
|
||||
|
||||
if version:
|
||||
subject = _render(version.subject, variables)
|
||||
body_html = _render(version.body_html, variables)
|
||||
version_id = version.id
|
||||
elif fallback_subject and fallback_html:
|
||||
subject = _render(fallback_subject, variables)
|
||||
body_html = _render(fallback_html, variables)
|
||||
version_id = None
|
||||
else:
|
||||
logger.warning("No published template for '%s' and no fallback provided", template_type)
|
||||
return {"success": False, "error": f"No template for {template_type}"}
|
||||
|
||||
result = send_email(recipient=recipient, subject=subject, body_html=body_html)
|
||||
|
||||
# Audit log
|
||||
try:
|
||||
log = EmailSendLogDB(
|
||||
tenant_id=tid,
|
||||
template_type=template_type,
|
||||
version_id=version_id,
|
||||
recipient=recipient,
|
||||
subject=subject,
|
||||
status=result.get("status", "unknown"),
|
||||
variables=variables,
|
||||
error_message=result.get("error"),
|
||||
)
|
||||
self.db.add(log)
|
||||
self.db.commit()
|
||||
except Exception as e:
|
||||
logger.warning("Failed to log email send: %s", e)
|
||||
|
||||
return {
|
||||
"success": result.get("status") == "sent",
|
||||
"template_type": template_type,
|
||||
"recipient": recipient,
|
||||
"subject": subject,
|
||||
"used_template": version is not None,
|
||||
"status": result.get("status"),
|
||||
}
|
||||
Reference in New Issue
Block a user