Files
project-managment/src/notifications/email_utils.py
T
sankalp ab0e71f7eb feat(src): add ticketing REST API and admin UI for tickets, settings, and branding
Introduce DRF views for ticket creation, listing, updating, and commenting, integrate admin registrations for new models, and provide a demo data command to seed initial content. This enables full project management workflow within the backend.
2026-06-28 14:16:16 +05:45

238 lines
7.2 KiB
Python

from datetime import date
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from src.notifications.models import DeadlineReminderLog, Notification
from src.tickets.models import Ticket
def send_notification_email(user, notification_type, title, message, data=None):
"""
Queue an email notification to be sent to a user asynchronously.
"""
if not user.email:
return
# Respect user email preference
if hasattr(user, "receive_deadline_emails") and not user.receive_deadline_emails:
return
from django_q.tasks import async_task
async_task(
"src.notifications.email_utils.do_send_notification_email",
user.id,
notification_type,
title,
message,
data,
)
def do_send_notification_email(user_id, notification_type, title, message, data=None):
User = get_user_model()
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
return
if not user.email:
return
if hasattr(user, "receive_deadline_emails") and not user.receive_deadline_emails:
return
data = data or {}
ticket_id = data.get("ticket_id")
ticket_uuid = data.get("ticket_uuid")
project_name = data.get("project_name", "")
user_name = data.get("user_name", "")
ticket_url = ""
if ticket_id:
ticket_url = f"{settings.BASE_URL or 'http://localhost:8000'}/dashboard/tickets/{ticket_id}/"
subject = f"[PM] {title}"
html_content = render_to_string(
"emails/notification.html",
{
"title": title,
"message": message,
"ticket_url": ticket_url,
"ticket_uuid": ticket_uuid,
"project_name": project_name,
"user_name": user_name,
"site_name": getattr(settings, "SITE_NAME", "Project Management"),
},
)
text_content = strip_tags(html_content)
email = EmailMultiAlternatives(
subject=subject,
body=text_content,
from_email=getattr(settings, "DEFAULT_FROM_EMAIL", "noreply@pm.com"),
to=[user.email],
)
email.attach_alternative(html_content, "text/html")
email.send(fail_silently=True)
def send_deadline_reminder_email(user, ticket, days_left):
"""
Queue a deadline reminder email to be sent asynchronously.
"""
if not user.email:
return
# Respect user email preference
if hasattr(user, "receive_deadline_emails") and not user.receive_deadline_emails:
return
from django_q.tasks import async_task
async_task(
"src.notifications.email_utils.do_send_deadline_reminder_email",
user.id,
ticket.id,
days_left,
)
def do_send_deadline_reminder_email(user_id, ticket_id, days_left):
User = get_user_model()
try:
user = User.objects.get(pk=user_id)
ticket = Ticket.objects.select_related("project", "priority", "status").get(
pk=ticket_id
)
except (User.DoesNotExist, Ticket.DoesNotExist):
return
if not user.email:
return
if hasattr(user, "receive_deadline_emails") and not user.receive_deadline_emails:
return
ticket_url = (
f"{settings.BASE_URL or 'http://localhost:8000'}/dashboard/tickets/{ticket.id}/"
)
due_date_str = ticket.due_date.strftime("%b %d, %Y") if ticket.due_date else "N/A"
priority_name = ticket.priority.name if ticket.priority else ""
status_name = ticket.status.name if ticket.status else "Unknown"
subject = f"[PM] Deadline Reminder: {ticket.uuid} - Due in {days_left} day{'s' if days_left != 1 else ''}"
html_content = render_to_string(
"emails/deadline_reminder.html",
{
"days_left": days_left,
"ticket_name": ticket.name,
"ticket_uuid": ticket.uuid,
"ticket_url": ticket_url,
"due_date": due_date_str,
"project_name": ticket.project.name,
"status_name": status_name,
"priority_name": priority_name,
"site_name": getattr(settings, "SITE_NAME", "Project Management"),
},
)
text_content = strip_tags(html_content)
email = EmailMultiAlternatives(
subject=subject,
body=text_content,
from_email=getattr(settings, "DEFAULT_FROM_EMAIL", "noreply@pm.com"),
to=[user.email],
)
email.attach_alternative(html_content, "text/html")
email.send(fail_silently=True)
def process_deadline_reminders(ticket=None):
"""
Central function to process deadline reminders.
Called from:
1. Ticket post_save signal (on create/update)
2. Dashboard load (for time-based checks)
If ticket is provided, only process that ticket.
Otherwise, process all eligible tickets.
"""
REMINDER_DAYS = [15, 10, 5, 2, 1]
today = date.today()
sent_count = 0
tickets_qs = (
Ticket.objects.filter(
status__is_completed=False,
due_date__isnull=False,
)
.exclude(due_date__lt=today)
.select_related("project", "status", "priority")
.prefetch_related("assignees")
)
if ticket:
tickets_qs = tickets_qs.filter(pk=ticket.pk)
for t in tickets_qs:
assignees = list(t.assignees.all())
if t.created_by and t.created_by not in assignees:
assignees.append(t.created_by)
for user in assignees:
if not user.email:
continue
# Respect user email preference
if (
hasattr(user, "receive_deadline_emails")
and not user.receive_deadline_emails
):
continue
days_until_due = (t.due_date - today).days
for days_before in REMINDER_DAYS:
if days_until_due == days_before:
already_sent = DeadlineReminderLog.objects.filter(
ticket=t,
user=user,
days_before=days_before,
).exists()
if already_sent:
continue
send_deadline_reminder_email(user, t, days_before)
DeadlineReminderLog.objects.create(
ticket=t,
user=user,
days_before=days_before,
)
Notification.objects.create(
user=user,
type="deadline_reminder",
title=f"Deadline Reminder: {t.uuid}",
message=(
f"Ticket '{t.name}' is due in {days_before} day{'s' if days_before != 1 else ''} "
f"({t.due_date.strftime('%b %d, %Y')})"
),
data={
"ticket_id": t.id,
"ticket_uuid": t.uuid,
"days_before": days_before,
},
)
sent_count += 1
return sent_count