feat(emails): Admin Telegram notification on every email sent

SW
4mo ago
+255-22

Why

So the team can review the quality and frequency of outgoing email — especially agent/scheduled sends (chat#1815 observability item). Today a send is invisible.

How

  • New notifyEmailSent() (lib/emails/notifyEmailSent.ts) — formats account id, to/cc, subject, Resend id, and a timestamp into a Markdown message and posts it via the existing sendMessage() to the same TELEGRAM_CHAT_ID channel as other alerts (the credit-spend digest, error notifications).
  • Best-effort (try/catch, never throws) — mirrors sendErrorNotification, so a Telegram failure never affects the email response.
  • Wired into sendEmailHandler after a successful send (no notification on a failed send).

Tests

11 emails tests green: notifyEmailSent formats the message + omits CC when absent + swallows Telegram errors; the handler notifies on success and not on failure. tsc/lint clean.

Stacked on api#717 (the credit-charge PR) — both touch sendEmailHandler. Merge #717 first; this branches off it.

Tracked on chat#1815.

🤖 Generated with Claude Code


Summary by cubic

Send an admin Telegram alert for every successful email sent via POST /api/emails, and charge 1 credit per send. Also tags usage events and returns a controlled 500 with CORS on unexpected errors.

  • New Features
    • Added notifyEmailSent() to post a Markdown summary (account id, to/cc, subject, Resend id, timestamp) to TELEGRAM_CHAT_ID via sendMessage. Best-effort and non-blocking; only on success.
    • Per-email charging: ensureCreditsOrShortCircuit gates before sending (402 with CREDIT_AUTO_RECHARGE_FALLBACK_SUCCESS_URL when insufficient), and recordCreditDeduction deducts EMAIL_CREDIT_COST = 1 credit only on success. Stamps usage_events.model_id = "POST /api/emails". No charge or notification on failures.