Record why an email send was rejected or failed

Merged
SI
16d ago
+99-8

Summary

Every rejected or failed POST /api/emails attempt now records why in email_send_log.reason, plus the sending account when auth has resolved it.

Causereason
Body fails the schemainvalid_body: html: a non-empty html or text body is required
Auth failsauth_failed: 401
No recipient given and the account has no emailno_account_email
Recipient gate (no payment method)recipient_not_allowed: a@example.com, …
Resend send failsresend_error: …

Why

recoupable/app#1949 F2: 59% of logged sends were rejected and the log could not say why, so scheduled reports that never arrived could not be diagnosed. The response bodies callers receive are unchanged.

Changes

  • validateSendEmailBody: the rejection branch now carries reason and, after auth, accountId.
  • sendEmailHandler: passes reason/accountId on rejected; records resend_error: … on send_failed.
  • logEmailAttempt: writes reason only when set.
  • types/database.types.ts: adds the column.

Merge order

Merge and apply recoupable/database#132 first; this PR writes the new column. As a guard, inserts include reason only when there is one, so successful sends keep logging even if this deploys early. That matters because welcome, valuation and abandoned-checkout emails dedupe on sent rows.

Tests

Tests first: 8 new assertions failed before the change. pnpm vitest run lib/emails → 218 passed. Lint and Prettier clean on changed files.

🤖 Generated with Claude Code