Files
web_django_template/site/directmail/tasks.py
T
westfarn f2eb4b7152 Add PCM carrier-route postcard pick-and-send (#12)
## Summary
Closes #11.
Mirrors ai_ml_operations/monica_site#15.

- Direct-mail compose can target the postcard mailing list **or** find and select one or two USPS carrier routes by ZIP (optional radius).
- Estimated cost is shown per route and for the selection (PCM design pricing, else `PCM_POSTCARD_PRICE_*` fallback).
- Selected routes order through PCM `POST /order/postcard/with-list-count` — occupant addresses are not imported into Contacts.
- Not official EDDM postage; PCM FirstClass/Standard purchased occupant lists on carrier routes.

## Test plan
- [ ] Campaign compose: mailing-list audience still quotes list size × per-piece cost.
- [ ] Switch to USPS carrier routes, search a ZIP, pick 1–2 routes, confirm household count + estimated cost.
- [ ] Saving without a selection is rejected; saving with a quote creates one contact-less Message and shows the route panel on the report.
- [ ] Send places `/order/postcard/with-list-count` (not per-recipient `/order/postcard`).
- [ ] `uv run python manage.py test directmail.tests.CarrierRoutePostcardTests directmail.tests.PostcardDesignPickTests`

Reviewed-on: #12
2026-09-21 13:29:53 -07:00

55 lines
1.7 KiB
Python

from django.tasks import task
from django.utils import timezone
from directmail.channels import dispatch_message
from directmail.models import Message
from directmail.services import contact_may_receive, refresh_campaign_status
@task
def send_campaign_message(message_id: str) -> None:
campaign = None
try:
message = Message.objects.select_related("contact", "campaign").get(
pk=message_id
)
except Message.DoesNotExist:
return
campaign = message.campaign
if message.contact_id is None:
pass
elif not contact_may_receive(message.contact, message.channel):
message.status = Message.Status.SUPPRESSED
message.error = "Contact opted out or suppressed"
message.save(update_fields=["status", "error", "updated_at"])
refresh_campaign_status(campaign)
return
try:
result = dispatch_message(message)
message.status = Message.Status.SENT
message.provider = result.provider
message.provider_message_id = result.provider_id
message.sent_at = timezone.now()
message.error = ""
message.save(
update_fields=[
"status",
"provider",
"provider_message_id",
"sent_at",
"error",
"updated_at",
]
)
except Exception as exc: # noqa: BLE001 — persist provider failures
message.status = Message.Status.FAILED
message.error = str(exc)[:2000]
message.save(update_fields=["status", "error", "updated_at"])
refresh_campaign_status(campaign)
raise
refresh_campaign_status(campaign)