Add proper email notifications
This commit is contained in:
@@ -1,45 +1,33 @@
|
||||
"""Submit form view (plan.md §7.4 + §7).
|
||||
"""Submit form view (plan.md §7.4).
|
||||
|
||||
The view persists a `Submission` and, depending on whether the request is
|
||||
authenticated, sets the initial state machine state per plan.md §7.3:
|
||||
|
||||
OAuth user -> processing (email already verified)
|
||||
OAuth user -> processing (email already verified)
|
||||
guest with email -> identifying (waiting for confirmation link click)
|
||||
|
||||
Slug generation, email sending, and validation cron are out of scope here and
|
||||
deferred to plan.md §7.5 (`processor` sidecar) and §7.5 confirmation flow.
|
||||
For the guest path, the confirmation email is sent **synchronously** after
|
||||
the DB commit so we know the Mailtrap API outcome before redirecting. The
|
||||
dashboard then shows a green "check your inbox" notice on success or a red
|
||||
"couldn't send email -- try Google sign-in" notice on failure.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
|
||||
import namesgenerator
|
||||
from django.contrib import messages
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.urls import reverse_lazy
|
||||
from django.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.html import format_html
|
||||
from django.views.generic import CreateView
|
||||
|
||||
from .emails import send_confirmation_email
|
||||
from .forms import SubmissionForm
|
||||
from .models import Submission
|
||||
|
||||
|
||||
def _generate_unique_slug(max_attempts: int = 16) -> str:
|
||||
"""`namesgenerator.get_random_name` with collision retries.
|
||||
|
||||
The slug column is `unique=True`; we retry instead of looping in SQL so
|
||||
the rare collision path stays observable.
|
||||
"""
|
||||
for _ in range(max_attempts):
|
||||
candidate = namesgenerator.get_random_name()
|
||||
if not Submission.objects.filter(slug=candidate).exists():
|
||||
return candidate
|
||||
# Fall through: extremely unlikely, but caller will see IntegrityError
|
||||
# if the next save() still collides.
|
||||
return namesgenerator.get_random_name()
|
||||
|
||||
|
||||
class SubmitView(CreateView):
|
||||
"""Public submit form. GET renders, POST creates a Submission."""
|
||||
|
||||
@@ -52,10 +40,12 @@ class SubmitView(CreateView):
|
||||
kwargs["user"] = self.request.user
|
||||
return kwargs
|
||||
|
||||
@transaction.atomic
|
||||
def form_valid(self, form):
|
||||
submission: Submission = form.save(commit=False)
|
||||
submission.slug = _generate_unique_slug()
|
||||
# The slug is auto-generated in `Submission.save()` if blank, so we
|
||||
# don't need to set one here. The `except IntegrityError` below
|
||||
# handles the rare race where the just-generated slug collides with
|
||||
# a concurrent insert.
|
||||
|
||||
if self.request.user.is_authenticated:
|
||||
submission.submitted_by = self.request.user
|
||||
@@ -70,28 +60,65 @@ class SubmitView(CreateView):
|
||||
submission.status = Submission.Status.IDENTIFYING
|
||||
submission.confirmation_token = secrets.token_urlsafe(32)
|
||||
submission.confirmation_sent_at = timezone.now()
|
||||
# TODO(plan.md §7.4 step 6): send the confirmation email here.
|
||||
|
||||
try:
|
||||
submission.save()
|
||||
except IntegrityError:
|
||||
# Extremely rare slug collision on the unique index; one more try.
|
||||
submission.slug = _generate_unique_slug()
|
||||
submission.save()
|
||||
# Persist inside a tight atomic block so the row is committed BEFORE
|
||||
# we hit the email transport. That way a slow / failing Mailtrap API
|
||||
# call can never roll back a saved submission, and we get to look at
|
||||
# the result and surface it as a user-visible notice.
|
||||
with transaction.atomic():
|
||||
try:
|
||||
submission.save()
|
||||
except IntegrityError:
|
||||
# Extremely rare slug collision on the unique index; clearing
|
||||
# `slug` makes `Submission.save()` regenerate it on retry.
|
||||
submission.slug = ""
|
||||
submission.save()
|
||||
|
||||
self.object = submission
|
||||
|
||||
if submission.status == Submission.Status.IDENTIFYING:
|
||||
messages.info(
|
||||
self.request,
|
||||
f"Submission {submission.slug} created. Check your email "
|
||||
f"({submission.guest_email}) for a confirmation link -- you "
|
||||
f"have 24 hours.",
|
||||
)
|
||||
self._notify_guest(submission)
|
||||
else:
|
||||
messages.success(
|
||||
self.request,
|
||||
f"Submission {submission.slug} accepted. We'll start "
|
||||
f"validating it shortly.",
|
||||
format_html(
|
||||
"Submission <strong class=\"font-mono\">{}</strong> accepted. "
|
||||
"We'll start validating it shortly.",
|
||||
submission.slug,
|
||||
),
|
||||
)
|
||||
|
||||
self.object = submission
|
||||
return super().form_valid(form)
|
||||
|
||||
# ---- guest-path notice ---------------------------------------------------
|
||||
|
||||
def _notify_guest(self, submission: Submission) -> None:
|
||||
"""Send the confirmation email and surface success / failure to the
|
||||
user via the messages framework. Green on 2xx from Mailtrap, red on
|
||||
any transport failure (with a "sign in with Google instead" hint)."""
|
||||
sent = send_confirmation_email(submission)
|
||||
if sent:
|
||||
messages.success(
|
||||
self.request,
|
||||
format_html(
|
||||
"Submission <strong class=\"font-mono\">{slug}</strong> created. "
|
||||
"We've sent a confirmation link to <strong>{email}</strong> — "
|
||||
"click it within 24 hours to add your print to the queue.",
|
||||
slug=submission.slug,
|
||||
email=submission.guest_email,
|
||||
),
|
||||
)
|
||||
else:
|
||||
messages.error(
|
||||
self.request,
|
||||
format_html(
|
||||
"Submission <strong class=\"font-mono\">{slug}</strong> was saved, "
|
||||
"but we couldn't send the confirmation email to <strong>{email}</strong>. "
|
||||
"Try <a href=\"{login_url}\" class=\"underline font-medium\">"
|
||||
"signing in with Google</a> instead — it skips email "
|
||||
"confirmation entirely.",
|
||||
slug=submission.slug,
|
||||
email=submission.guest_email,
|
||||
login_url=reverse("account_login"),
|
||||
),
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user