feat(emails): valuation-report email on valuation complete (chat#1867)

Merged
SW
4mo ago
+1013-1

Implements the "Valuation-report email on valuation complete" item from recoupable/chat#1867.

Problem

The valuation $ number lives only in the user's open browser tab. digital@epitaph.com ran a 10-album measurement on 2026-07-13 and had nothing to return to; email_send_log has never contained a non-task email for a new signup.

What this does

When playcountSnapshotWorkflow reaches its terminal success state (markSnapshotStep(..., { state: "done" })), a new sendValuationEmailStep emails every address on the owning account:

  • Subject: "Your catalog valuation is ready"
  • Body: catalog name, headline estimated value + range, lifetime Spotify streams, songs measured, albums measured, catalog age, and a deep link to https://chat.recoupable.dev/catalogs/{id} (app root https://chat.recoupable.dev when the run has no claimed catalog).
  • $ estimate is server-side, not duplicated: the band is computed with the existing lib/catalog/computeValuationBand.ts — the exact function GET /api/catalogs/{id}/measurements already uses (which itself mirrors the marketing card model). No formula was copied.
  • Design: deterministic house-style renderer mirroring renderScrapeDigestHtml — DESIGN.md achromatic chrome (#0a0a0a on #ffffff, #e8e8e8 borders, #6b6b6b muted), tables + inline styles, system font stack, black CTA button, fixed CHAT_APP_URL (never a derived deployment URL). Range copy uses "to", no em/en dashes.

Idempotency (no duplicate sends on retries)

Two independent guards:

  1. email_send_log marker — the send is logged with raw_body JSON containing "snapshot_id":"<id>"; selectValuationEmailSendLog checks it before any send. Unbounded window.
  2. Resend idempotency key — valuation-report/<snapshot_id> passed to resend.emails.send, covering racing retries within Resend's 24h window.

The step is best-effort: it never throws, so an email failure can never flip a completed measurement run to failed. Failed sends are logged with status send_failed; accounts with no account_emails row are skipped silently.

Files

  • app/workflows/sendValuationEmailStep.ts — new step, wired into playcountSnapshotWorkflow after the done transition
  • lib/emails/valuationReport/sendValuationReportEmail.ts — orchestrator (guards → enrichment → send → log)
  • lib/emails/valuationReport/renderValuationReportHtml.ts — deterministic template
  • lib/emails/valuationReport/formatCompactNumber.ts — K/M/B formatter (digest's formatter stops at M)
  • lib/supabase/email_send_log/selectValuationEmailSendLog.ts — idempotency lookup

Measurement enrichment (selectCatalogById + selectCatalogMeasurementsAggregate + getCatalogEarliestReleaseDate) is wrapped: a read failure degrades to the link-only email rather than dropping the send. Zero measured streams also degrades to link-only (no $0 valuations).

Verification

CheckResult
New unit tests (TDD, red-first): formatter, renderer, idempotency lookup, send orchestrator, workflow step guard20/20 pass
Full suite pnpm test758 files / 4140 tests pass
pnpm exec tsc --noEmitclean
pnpm lint + pnpm format:checkclean
End-to-end send on previewnot yet run — needs a real snapshot run (see below)

How to test on preview

  1. On the preview deployment, POST /api/research/snapshots with a small catalog (an account whose account_emails row is a test inbox — previews share the prod DB, so use your own account, not a customer's).
  2. Wait for the workflow to finish (Vercel dashboard → Workflows, or poll playcount_snapshots.state until done).
  3. Confirm one email arrives with the $ band, streams, and a working /catalogs/{id} deep link.
  4. Confirm exactly one email_send_log row with status='sent' and raw_body containing the snapshot_id marker.
  5. Re-run the workflow for the same snapshot id (or resend the workflow event): no second email, no second sent row.

Internal-only change: no public API contract changes, so no docs PR. Uses the existing RESEND_API_KEY env var; no new env vars.

🤖 Generated with Claude Code


Summary by cubic

Send a valuation report email after a snapshot completes so users can return to their results. The email mirrors the chat report with an artist header and a releases table, and sends after the catalog is materialized (recoupable/chat#1867, chat#1881).

  • New Features

    • Content: Subject "Your catalog valuation is ready". Includes catalog name, valuation band from lib/catalog/computeValuationBand.ts, lifetime Spotify streams, measured tracks, releases, catalog age, and a deep link. Adds artist header (image and followers) and a releases table with album art, streams, and per-release value that sums to the headline.
    • Data build: buildReleaseRollups aggregates per-album streams and joins measurements; album art uses the smallest image from Spotify getAlbums; buildValuationReleaseRows computes proportional values. Safe fallbacks send a link-only email if enrichment fails or streams are zero.
    • Idempotency and logging: Uses selectEmailSendLog with a "snapshot_id":"<id>" marker and Resend key valuation-report/<snapshot_id>. Logs sent or send_failed. Skips when no account email.
  • Refactors

    • Trigger moved to runValuationHandler using next/server after() so it runs post-materialization and never delays the response.
    • Split valuation-report logic into single-purpose helpers and renamed money formatter to formatCompactUsd (distinct from lib/stripe/formatUsd).

Summary by CodeRabbit

  • New Features
    • Added valuation report emails featuring estimated catalog value, key statistics, optional artist header, a releases breakdown with album artwork, and a call-to-action link to view the catalog.
    • Added compact number formatting for large figures (including USD value ranges).
    • Valuation reports are sent automatically after catalog valuation completes.
  • Bug Fixes
    • Prevented duplicate email sends using idempotent delivery checks and skip behavior when recipient emails are unavailable.
    • Continued delivering reports even if additional enrichment data fails.
  • Improvements
    • Escapes user-provided names/links to improve safety and rendering consistency.