feat(emails): valuation-report email on valuation complete (chat#1867)
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 roothttps://chat.recoupable.devwhen 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 functionGET /api/catalogs/{id}/measurementsalready uses (which itself mirrors the marketing card model). No formula was copied. - Design: deterministic house-style renderer mirroring
renderScrapeDigestHtml— DESIGN.md achromatic chrome (#0a0a0aon#ffffff,#e8e8e8borders,#6b6b6bmuted), tables + inline styles, system font stack, black CTA button, fixedCHAT_APP_URL(never a derived deployment URL). Range copy uses "to", no em/en dashes.
Idempotency (no duplicate sends on retries)
Two independent guards:
email_send_logmarker — the send is logged withraw_bodyJSON containing"snapshot_id":"<id>";selectValuationEmailSendLogchecks it before any send. Unbounded window.- Resend idempotency key —
valuation-report/<snapshot_id>passed toresend.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 intoplaycountSnapshotWorkflowafter thedonetransitionlib/emails/valuationReport/sendValuationReportEmail.ts— orchestrator (guards → enrichment → send → log)lib/emails/valuationReport/renderValuationReportHtml.ts— deterministic templatelib/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
| Check | Result |
|---|---|
| New unit tests (TDD, red-first): formatter, renderer, idempotency lookup, send orchestrator, workflow step guard | 20/20 pass |
Full suite pnpm test | 758 files / 4140 tests pass |
pnpm exec tsc --noEmit | clean |
pnpm lint + pnpm format:check | clean |
| End-to-end send on preview | not yet run — needs a real snapshot run (see below) |
How to test on preview
- On the preview deployment,
POST /api/research/snapshotswith a small catalog (an account whoseaccount_emailsrow is a test inbox — previews share the prod DB, so use your own account, not a customer's). - Wait for the workflow to finish (Vercel dashboard → Workflows, or poll
playcount_snapshots.stateuntildone). - Confirm one email arrives with the $ band, streams, and a working
/catalogs/{id}deep link. - Confirm exactly one
email_send_logrow withstatus='sent'andraw_bodycontaining thesnapshot_idmarker. - Re-run the workflow for the same snapshot id (or resend the workflow event): no second email, no second
sentrow.
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:
buildReleaseRollupsaggregates per-album streams and joins measurements; album art uses the smallest image from SpotifygetAlbums;buildValuationReleaseRowscomputes proportional values. Safe fallbacks send a link-only email if enrichment fails or streams are zero. - Idempotency and logging: Uses
selectEmailSendLogwith a"snapshot_id":"<id>"marker and Resend keyvaluation-report/<snapshot_id>. Logssentorsend_failed. Skips when no account email.
- Content: Subject "Your catalog valuation is ready". Includes catalog name, valuation band from
-
Refactors
- Trigger moved to
runValuationHandlerusingnext/serverafter()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 fromlib/stripe/formatUsd).
- Trigger moved to
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.