Spaces:
Runtime error
Runtime error
File size: 5,476 Bytes
e4d23c9 d628201 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | """
Dedalys Backend — Service Email
Gestion des envois d'emails transactionnels via Resend.
"""
import logging
from typing import List, Optional, Dict, Any
from datetime import datetime
import resend
from app.core.config import settings
logger = logging.getLogger(__name__)
# Initialisation de la clé d'API Resend
if settings.RESEND_API_KEY:
resend.api_key = settings.RESEND_API_KEY
async def send_email_async(to: List[str], subject: str, html_body: str) -> bool:
"""Fonction générique pour envoyer un email asynchrone via l'API Resend."""
if not settings.RESEND_API_KEY:
logger.warning(
f"RESEND_API_KEY manquant. L'email vers {to} n'a pas pu être envoyé.")
return False
try:
response = resend.Emails.send({
"from": settings.EMAIL_FROM,
"to": to,
"subject": subject,
"html": html_body
})
logger.info(f"Email envoyé avec succès à {to}: {response}")
return True
except Exception as e:
logger.error(f"Erreur lors de l'envoi de l'email à {to}: {e}")
return False
async def send_audience_reminder(
avocat_email: str,
avocat_nom: str,
dossier_titre: str,
audience_date: str,
audience_heure: str,
juridiction: str,
delay_type: str, # "J-7", "J-3", ou "J-1"
) -> bool:
"""Envoie un email de rappel d'audience (J-7, J-3, J-1) à l'avocat assigné."""
delays_text = {
"J-7": "dans 7 jours",
"J-3": "dans 3 jours",
"J-1": "demain"
}
delay_str = delays_text.get(delay_type, delay_type)
subject = f"[Dedalys] Audience {delay_str} — [{dossier_titre}]"
# URL fictive pour le lien direct (en fonction du FRONTEND_URL de la config)
frontend_url = settings.FRONTEND_URL.rstrip('/')
audience_link = f"{frontend_url}/audiences"
html_body = f"""
<p>Bonjour Maître {avocat_nom},</p>
<p>Ceci est un rappel vous informant qu'une audience aura lieu <strong>{delay_str}</strong> concernant le dossier <strong>{dossier_titre}</strong>.</p>
<ul>
<li><strong>Date :</strong> {audience_date}</li>
<li><strong>Heure :</strong> {audience_heure}</li>
<li><strong>Juridiction :</strong> {juridiction or 'Non spécifiée'}</li>
</ul>
<p>Vous pouvez consulter les détails en vous connectant à votre espace Dedalys :<br>
<a href="{audience_link}">Aller au planning d'audiences</a></p>
<br>
<p>Cordialement,<br>L'équipe Dedalys</p>
"""
return await send_email_async(
to=[avocat_email],
subject=subject,
html_body=html_body
)
async def send_flash_cr_email(
destinataires: List[str],
dossier_titre: str,
date_audience: str,
juridiction: str,
type_decision: str,
prochaine_date: Optional[str] = None,
notes: Optional[str] = None
) -> bool:
"""Envoie automatiquement le compte-rendu 'Flash CR' aux clients après une audience."""
# Formatage de la date en chaîne si ce n'est pas déjà le cas
if isinstance(date_audience, datetime):
date_audience = date_audience.strftime("%d/%m/%Y")
subject = f"Compte-rendu d'audience — [{dossier_titre}] — {date_audience}"
# Textes pour le résumé de la décision
decision_texts = {
"decision_rendue": "Le juge a rendu sa décision.",
"mise_en_delibere": "La décision a été mise en délibéré.",
"renvoi": "L'affaire a été renvoyée.",
"autre": "Mise à jour sur votre dossier."
}
resume_decision = decision_texts.get(type_decision, type_decision)
prochaine_date_html = ""
if type_decision in ("mise_en_delibere", "renvoi") and prochaine_date:
prochaine_date_html = f"<p><strong>Prochaine audience fixée au {prochaine_date}.</strong></p>"
notes_html = f"<p><em>Notes complémentaires :</em><br>{notes}</p>" if notes else ""
html_body = f"""
<p>Bonjour,</p>
<p>Suite à l'audience du <strong>{date_audience}</strong> devant <strong>{juridiction or 'le Tribunal'}</strong>,<br>
<strong>{resume_decision}</strong></p>
{prochaine_date_html}
{notes_html}
<br>
<p>Cordialement,<br>Votre Cabinet</p>
"""
return await send_email_async(
to=destinataires,
subject=subject,
html_body=html_body
)
async def send_subscription_reminder(
destinataires: List[str],
espace_nom: str,
date_expiration: str,
jours_restants: int,
) -> bool:
"""Envoie un email de rappel d'expiration d'abonnement."""
subject = f"[Dedalys] Votre abonnement expire dans {jours_restants} jour{'s' if jours_restants > 1 else ''} — {espace_nom}"
frontend_url = settings.FRONTEND_URL.rstrip('/')
html_body = f"""
<p>Bonjour,</p>
<p>L'abonnement de votre espace <strong>{espace_nom}</strong> sur Dedalys
expire le <strong>{date_expiration}</strong>, soit dans <strong>{jours_restants} jour{'s' if jours_restants > 1 else ''}</strong>.</p>
<p>Pour continuer à utiliser votre espace sans interruption, nous vous invitons
à renouveler votre abonnement dès que possible.</p>
<p><a href="{frontend_url}">Se connecter à Dedalys</a></p>
<br>
<p>Cordialement,<br>L'équipe Dedalys</p>
"""
return await send_email_async(
to=destinataires,
subject=subject,
html_body=html_body
)
|