add mail to table on notif

This commit is contained in:
2025-06-02 09:17:21 +02:00
parent 17e0781b14
commit 7d08a57c85
8 changed files with 233 additions and 5 deletions

View File

@@ -1,5 +1,5 @@
from flask import request
from models import Notif, NotifType, db
from models import Notif, NotifType, db, EmailTemplate, Mail
from typing import Optional, Dict, Any, List
from datetime import datetime, timedelta
from flask_login import current_user
@@ -8,20 +8,65 @@ import logging
logger = logging.getLogger(__name__)
def generate_mail_from_notification(notif: Notif) -> Optional[Mail]:
"""
Generate a mail record from a notification using the appropriate email template.
Args:
notif: The notification object to generate mail from
Returns:
The created Mail object or None if no template was found
"""
logger.debug(f"Generating mail for notification: {notif}")
# Find the corresponding email template based on notif_type
template = EmailTemplate.query.filter_by(name=notif.notif_type).first()
if not template:
logger.warning(f"No email template found for notification type: {notif.notif_type}")
return None
try:
# Fill in the template with notification details
filled_body = template.body
if notif.user:
filled_body = filled_body.replace('{{ user.username }}', notif.user.username)
if notif.details:
for key, value in notif.details.items():
filled_body = filled_body.replace(f'{{{{ {key} }}}}', str(value))
# Create a new Mail record
mail = Mail(
recipient=notif.user.email,
subject=template.subject,
body=filled_body,
status='pending',
template_id=template.id,
notif_id=notif.id
)
db.session.add(mail)
logger.debug(f"Created mail record: {mail}")
return mail
except Exception as e:
logger.error(f"Error generating mail from notification: {str(e)}")
return None
def create_notification(
notif_type: str,
user_id: int,
sender_id: Optional[int] = None,
details: Optional[Dict[str, Any]] = None
details: Optional[Dict[str, Any]] = None,
generate_mail: bool = True
) -> Notif:
"""
Create a notification in the database.
Create a notification in the database and optionally generate a mail record.
Args:
notif_type: The type of notification (must match NotifType enum)
user_id: The ID of the user to notify
sender_id: Optional ID of the user who triggered the notification
details: Optional dictionary containing notification details
generate_mail: Whether to generate a mail record for this notification
Returns:
The created Notif object
@@ -41,6 +86,13 @@ def create_notification(
logger.debug(f"Created notification object: {notif}")
db.session.add(notif)
# Generate mail if requested
if generate_mail:
mail = generate_mail_from_notification(notif)
if mail:
logger.debug(f"Generated mail record for notification: {mail}")
# Don't commit here - let the caller handle the transaction
logger.debug("Notification object added to session")
return notif