Record why an email send was rejected or failed
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.
| Cause | reason |
|---|---|
| Body fails the schema | invalid_body: html: a non-empty html or text body is required |
| Auth fails | auth_failed: 401 |
| No recipient given and the account has no email | no_account_email |
| Recipient gate (no payment method) | recipient_not_allowed: a@example.com, … |
| Resend send fails | resend_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 carriesreasonand, after auth,accountId.sendEmailHandler: passesreason/accountIdonrejected; recordsresend_error: …onsend_failed.logEmailAttempt: writesreasononly 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