324 lines
24 KiB
Markdown
324 lines
24 KiB
Markdown
# React-Email Migration
|
||
|
||
**Status:** completed
|
||
**Task-ID:** #75
|
||
**Phase:** 10
|
||
**Estimated Effort:** 1-2 Wochen
|
||
**Owner:** agent/10-react-email
|
||
|
||
## Problem
|
||
|
||
Die existierenden Transactional-Email-Templates in `packages/mail/src/templates/transactional.ts` sind handgeschriebene HTML-Strings mit manuellen `escapeHtml`-Aufrufen für User-Content. Konkrete Schmerzpunkte:
|
||
|
||
- **Audit-Findings**: Manuelles HTML-Escaping ist fehleranfällig. Reviews finden regelmäßig vergessene Escape-Aufrufe (z.B. wenn ein neuer Template-Parameter `signaturName` hinzukommt und der Entwickler die Escape-Pflicht übersieht). Das ist eine permanente XSS-Klasse in Outbound-Mails (HTML-Renderer in einigen Mail-Clients sind aggressiver als oft angenommen).
|
||
- **Maintenance-Nightmare**: Jede Brand-Änderung (Logo-Update, Primary-Color-Wechsel pro Tenant) erfordert HTML-String-Edits in einer monolithischen Datei. Kein Component-Reuse zwischen Templates möglich (Header, Footer, Button, CTA-Block werden jedes Mal neu inline-zusammengebaut).
|
||
- **Keine Live-Preview**: Entwickler müssen die Mail tatsächlich versenden (oder MailHog-Container starten) um das Rendering zu sehen. Iteration ist langsam.
|
||
- **Historische Phase-05-Annahme:** Marketing-Funnel-Phase-3 plante React-Email als Basis für Email-Sequences-Templates (Drip-Campaigns, Onboarding-Sequences). React-Email ist inzwischen abgeschlossen; der aktuelle Email-Sequences-Blocker liegt im sequence-spezifischen Renderer und Mail-Adapter, siehe `docs/features/email-sequences.md`.
|
||
- **Plain-Text-Fallback** wird heute nur sporadisch generiert. React-Email rendert automatisch eine `@react-email/render`-kompatible Plain-Text-Variante aus dem JSX-Tree.
|
||
- **Brand-Theming pro Tenant** (Logo, Primary-Color, Font) ist nur als Header-Token-Replacement implementiert — keine echte Component-Prop-Pipeline.
|
||
|
||
Betroffene Codestellen:
|
||
- `packages/mail/src/templates/transactional.ts` — alle Transactional-Templates (Welcome, Magic-Link, Password-Reset, Subscription-Success/Failed, Invitation, Invoice-Sent, Tenant-Notification)
|
||
- `packages/mail/src/templates/transactional.test.ts` — Tests, die String-Matching auf HTML-Output machen (müssen auf Snapshot-Tests migriert werden)
|
||
- `packages/mail/src/queue.ts` — Renderer-Aufrufe, müssen auf `@react-email/render` umgestellt werden
|
||
- `packages/mail/src/mailjet.ts` — Bestätigt MIME-Multipart-Versand mit `text` + `html` Parts (React-Email liefert beides)
|
||
|
||
## Depends on
|
||
|
||
- `01-tech-debt-foundation/dep-updates.md` — React-Email braucht React 18.3+ und kompatible TypeScript-Version; Dep-Updates müssen vorher durch sein
|
||
- `02-observability/sentry-wiring-api-worker.md` — Render-Fehler in Templates sollen via Sentry erfasst werden, sonst tappen wir blind bei Production-Template-Bugs
|
||
|
||
**Nicht benötigt aber empfehlenswert:**
|
||
- `02-observability/logging-migration.md` — saubere Render-Logs
|
||
|
||
## Blocks
|
||
|
||
- `05-business-features/marketing-funnel-phase-3.md` — historische Referenz: Email-Sequences nutzten React-Email als Template-Basis; aktuelle offene Produktionsarbeit liegt im sequence-spezifischen Renderer/Mail-Adapter.
|
||
- Indirekt: zukünftige Notification-Center-Erweiterungen (HTML-Email-Digests aus In-App-Notifications) bauen auf den React-Components auf
|
||
|
||
## Approach
|
||
|
||
**Neue Subdirectory `packages/mail/src/templates-react/`** mit folgender Architektur:
|
||
|
||
1. **React-Email-Setup**:
|
||
- `@react-email/components` (Body, Container, Section, Row, Column, Text, Heading, Button, Img, Link, Hr, Preview, Tailwind) als Component-Library
|
||
- `@react-email/render` als Renderer (liefert HTML + Plain-Text)
|
||
- Tailwind-Inline-Styles via `@react-email/tailwind`-Wrapper (Browser-Compatible-Subset, Stylesheet wird inline in jedes Element gebrannt — Email-Client-kompatibel)
|
||
|
||
2. **Layout-Components** (`packages/mail/src/templates-react/_layout/`):
|
||
- `BaseLayout` — Wrapper mit Body + Container + Preview-Header
|
||
- `Header` — Logo + optional Tenant-Brand-Color als Background
|
||
- `Footer` — Unsubscribe-Link (CAN-SPAM/DSGVO-Pflicht), Company-Adresse, Social-Links
|
||
- `Button` — CTA-Button mit Brand-Color-Prop
|
||
- `InfoBox` — Boxed-Section für „wichtige Informationen"
|
||
|
||
3. **Migration aller Existing Templates** (`packages/mail/src/templates-react/transactional/`):
|
||
- `WelcomeEmail.tsx` — Account-Aktivierung
|
||
- `MagicLinkEmail.tsx` — Magic-Link für Login (`actionUrl` als Prop)
|
||
- `PasswordResetEmail.tsx` — Reset-Link
|
||
- `SubscriptionSuccessEmail.tsx` — Stripe-Subscription-Confirmation
|
||
- `SubscriptionFailedEmail.tsx` — Stripe-Failed-Payment-Notice
|
||
- `InvitationEmail.tsx` — Tenant-Member-Invite mit Tenant-Brand-Theming
|
||
- `InvoiceSentEmail.tsx` — Stripe-Invoice-PDF-Notification
|
||
- `TenantNotificationEmail.tsx` — generische Tenant-Notification-Template (für In-App-Notifications, die per Email gesendet werden)
|
||
|
||
4. **Marketing-Campaign-Template-Base** (`packages/mail/src/templates-react/marketing/`):
|
||
- `CampaignBaseLayout` — generisches Marketing-Layout mit Brand-Hero, CTA-Buttons, Image-Slots
|
||
- Wird in Phase-05-Marketing-Funnel-Phase-3 als Foundation für Drip-Sequences verwendet
|
||
- Plain-Text-Fallback ist automatisch (React-Email rendert Text-Variante aus JSX-Tree)
|
||
|
||
5. **Brand-Theming via Props**:
|
||
- Jedes Template nimmt `brand: { logoUrl?: string; primaryColor?: string; fontFamily?: string; tenantName?: string }` als Prop
|
||
- Tenant-Brand-Config wird via existing `packages/brand`-Package geladen
|
||
- Sensible Defaults wenn `brand` undefined (Plattform-Default-Theme)
|
||
- Primary-Color wird automatisch auf Button, Header-Accent, Link-Color angewendet
|
||
|
||
6. **Plain-Text-Fallback** (automatisch):
|
||
- `render(<Template />, { plainText: true })` aus `@react-email/render`
|
||
- Wird im `queue.ts`-Renderer-Pfad immer mit-gerendert und als `text`-Part im MIME-Multipart versendet
|
||
|
||
7. **Live-Preview-Workflow**:
|
||
- `pnpm email:preview` startet React-Email-Dev-Server (`react-email dev` aus `@react-email/preview`)
|
||
- Localhost:3001 zeigt alle Templates mit Hot-Reload und Sample-Props
|
||
- Sample-Props in `packages/mail/src/templates-react/_previews/<template>.preview.tsx`
|
||
|
||
8. **Storybook-Stories**:
|
||
- Jedes Template hat eine Storybook-Story in `packages/mail/src/templates-react/<file>.stories.tsx` (sobald Phase 08 Storybook fertig ist; bis dahin nur React-Email-Preview)
|
||
- Zeigt Brand-Theme-Varianten (Default, Tenant-A, Tenant-B mit jeweils anderem Logo/Color)
|
||
|
||
9. **Sicherheit**:
|
||
- User-Content wird durch React's Default-Escaping automatisch sicher — eliminiert alle manuellen `escapeHtml`-Aufrufe und damit die ganze Audit-Klasse
|
||
- `actionUrl`-Validation in Component-Props: nur `https://`-URLs erlaubt, sonst Throw (verhindert `javascript:`-Injection in Magic-Links)
|
||
- `dangerouslySetInnerHTML` ist verboten in allen Templates (ESLint-Rule aktiviert)
|
||
|
||
10. **Tests**:
|
||
- Snapshot-Tests gegen gerendertes HTML pro Template (Vitest + `@react-email/render`)
|
||
- Snapshot-Tests pro Brand-Theme-Variante
|
||
- Edge-Case-Tests: lange Texte, fehlende optionale Props, Unicode-Content (Emoji, RTL-Sprachen)
|
||
- Optional Integration: `litmus`- oder `email-on-acid`-CLI für Cross-Client-Rendering-Smoke-Tests (manuell triggerbar, nicht in CI default)
|
||
|
||
**Warum nicht Alternativen:**
|
||
- ❌ MJML: weniger React-Idiom, eigene DSL, schlechtere TypeScript-Integration, kein Hot-Reload-Dev-Server gleich gut
|
||
- ❌ Eigene JSX-zu-Email-HTML-Pipeline: React-Email löst alle Edge-Cases (Outlook-Quirks, Gmail-Image-Limits, Dark-Mode-Support) bereits; nicht wert das nachzubauen
|
||
- ❌ Bei Plain-HTML-Strings bleiben: Audit-Findings bleiben permanent, kein Component-Reuse, keine Live-Preview
|
||
- ❌ Maizzle: Tailwind-orientiert aber Static-Site-Generator-Modell, weniger React-Component-Modell
|
||
|
||
## Implementation Steps
|
||
|
||
1. **Dependencies installieren**
|
||
- Files: `packages/mail/package.json`
|
||
- Add: `@react-email/components`, `@react-email/render`, `@react-email/preview`, `@react-email/tailwind`
|
||
- Add Dev-Dep: `react-email` (CLI für Dev-Server)
|
||
- Commit: `10-compliance-polish/react-email: add @react-email dependencies`
|
||
|
||
2. **Setup Subdirectory + Layout-Components**
|
||
- Files: `packages/mail/src/templates-react/_layout/BaseLayout.tsx`, `Header.tsx`, `Footer.tsx`, `Button.tsx`, `InfoBox.tsx`, plus `_layout/index.ts`
|
||
- Layout-Components mit Brand-Prop-Threading
|
||
- Unit-Tests: `BaseLayout.test.tsx` (Snapshot mit Default + Custom-Brand)
|
||
- Commit: `10-compliance-polish/react-email: scaffold templates-react layout components`
|
||
|
||
3. **WelcomeEmail Template**
|
||
- Files: `packages/mail/src/templates-react/transactional/WelcomeEmail.tsx`, `.test.tsx`, `_previews/WelcomeEmail.preview.tsx`
|
||
- Snapshot-Test, Brand-Theme-Test
|
||
- Commit: `10-compliance-polish/react-email: migrate welcome email to react-email`
|
||
|
||
4. **MagicLinkEmail + PasswordResetEmail Templates**
|
||
- Files: `MagicLinkEmail.tsx`, `PasswordResetEmail.tsx`, plus Tests + Previews
|
||
- `actionUrl`-Validation als Prop-Typ + Runtime-Check (`https:`-only)
|
||
- Commit: `10-compliance-polish/react-email: migrate auth-flow emails (magic-link, password-reset)`
|
||
|
||
5. **Subscription-Emails (Success, Failed)**
|
||
- Files: `SubscriptionSuccessEmail.tsx`, `SubscriptionFailedEmail.tsx`, plus Tests + Previews
|
||
- Stripe-Plan-Display, Next-Billing-Date
|
||
- Commit: `10-compliance-polish/react-email: migrate stripe subscription notification emails`
|
||
|
||
6. **InvitationEmail + InvoiceSentEmail**
|
||
- Files: `InvitationEmail.tsx`, `InvoiceSentEmail.tsx`, plus Tests + Previews
|
||
- Invitation mit Tenant-Brand-Theme (Logo, Color), Invoice mit PDF-Link
|
||
- Commit: `10-compliance-polish/react-email: migrate invitation and invoice emails`
|
||
|
||
7. **TenantNotificationEmail (generisch)**
|
||
- Files: `TenantNotificationEmail.tsx`, plus Tests + Preview
|
||
- Akzeptiert `title`, `body` (Markdown via `react-markdown` in `<Text>`-Wrapper, sicheres Escaping), `actionUrl`, `actionLabel`
|
||
- Commit: `10-compliance-polish/react-email: migrate tenant notification email`
|
||
|
||
8. **Marketing-Campaign-Base-Template**
|
||
- Files: `packages/mail/src/templates-react/marketing/CampaignBaseLayout.tsx`, `_previews/CampaignBaseLayout.preview.tsx`, Test
|
||
- Hero-Section, CTA-Buttons, Image-Slots, Unsubscribe-Footer (CAN-SPAM/DSGVO-Pflicht)
|
||
- Commit: `10-compliance-polish/react-email: add marketing campaign base layout for funnel sequences`
|
||
|
||
9. **Renderer-Integration in queue.ts**
|
||
- Files: `packages/mail/src/queue.ts`, `packages/mail/src/queue.test.ts`
|
||
- Renderer-Aufruf umstellen von Template-String-Render auf `render(<Template {...props} />, { plainText: false })` + zweiter Aufruf mit `plainText: true`
|
||
- MIME-Multipart-Versand mit beiden Varianten
|
||
- Re-Export-Wrapper für Backwards-Compat: alte `renderTransactional(templateName, props)`-Signatur dispatcht auf React-Component
|
||
- Tests: Snapshot der gerenderten HTML- und Text-Outputs
|
||
- Commit: `10-compliance-polish/react-email: integrate render pipeline in mail queue`
|
||
|
||
10. **Live-Preview-Setup**
|
||
- Files: `packages/mail/package.json` (Script-Eintrag `email:preview`), `packages/mail/react-email.config.ts`
|
||
- `pnpm email:preview` startet React-Email-Dev-Server auf Port 3001
|
||
- Doku: `packages/mail/README.md` ergänzen mit Preview-Workflow
|
||
- Commit: `10-compliance-polish/react-email: add live preview workflow`
|
||
|
||
11. **Alte Templates entfernen oder reduzieren**
|
||
- Files: `packages/mail/src/templates/transactional.ts` (loeschen oder auf Re-Export-Shim reduzieren), `packages/mail/src/templates/transactional.test.ts` (loeschen), `packages/mail/src/templates/transactional.locale.test.ts` (loeschen oder auf React-Templates portieren)
|
||
- Wenn andere Aufrufer noch direkt auf String-Templates zugreifen: in separatem Commit migrieren
|
||
- Commit: `10-compliance-polish/react-email: remove legacy string-based transactional templates`
|
||
|
||
12. **Doku + Contributing-Guide**
|
||
- Files: `docs/contributing/email-templates.md`
|
||
- Erklärt: Component-Library, wie neue Templates angelegt werden, Brand-Theming-Pattern, Live-Preview, Snapshot-Test-Pflicht, `actionUrl`-Validation, `dangerouslySetInnerHTML`-Verbot
|
||
- Commit: `10-compliance-polish/react-email: document email-template contribution workflow`
|
||
|
||
## Test Requirements
|
||
|
||
- **Unit-Tests pro Template:** Snapshot-Test gegen gerenderten HTML-Output (Vitest), plus Snapshot pro Brand-Theme-Variante (Default, Tenant-A, Tenant-B)
|
||
- **Edge-Case-Tests:** lange Texte (Wrap-Verhalten), fehlende optionale Props (Default-Fallback), Unicode-Content (Emoji + RTL-Strings)
|
||
- **Plain-Text-Snapshot:** parallel zum HTML-Snapshot ein Plain-Text-Snapshot für jeden Template
|
||
- **Renderer-Integration-Test:** `queue.test.ts` prüft End-to-End: Template-Name + Props → MIME-Multipart-Output mit `text` und `html`-Part
|
||
- **Sicherheits-Tests:**
|
||
- `actionUrl` mit `javascript:`-Scheme wird abgelehnt (Throw)
|
||
- User-Content mit `<script>`-Tag wird escaped (kein executable Script in Output)
|
||
- `<` und `>` in User-Props erscheinen als `<` und `>` im HTML-Output
|
||
- **Coverage-Target:** ≥ 95 % lines/branches in `packages/mail/src/templates-react/`
|
||
- **Test-Files:** `<TemplateName>.test.tsx` co-located mit jedem Template; Renderer-Integration in `queue.test.ts`
|
||
- **Optional Cross-Client-Test:** manueller Trigger via `pnpm email:litmus` (nicht in CI; nur on-demand)
|
||
|
||
**NICHT als completed markieren bevor `pnpm --filter @toolctrl/mail test` grün ist und alle Snapshots reviewed sind.**
|
||
|
||
## Acceptance Criteria
|
||
|
||
- [ ] `packages/mail/src/templates-react/` enthält alle 8 Transactional-Templates + 1 Marketing-Campaign-Base
|
||
- [ ] Alle Templates rendern korrekt in `pnpm email:preview` (manuelle Verifikation, Screenshots in PR-Description)
|
||
- [ ] Brand-Theming funktioniert via Props (Logo, Primary-Color, Tenant-Name); Test-Snapshots für 3 verschiedene Brand-Themes
|
||
- [ ] Plain-Text-Fallback wird automatisch gerendert und als `text`-MIME-Part versendet
|
||
- [ ] `packages/mail/src/templates/transactional.ts` ist gelöscht oder auf reinen Re-Export reduziert
|
||
- [ ] `actionUrl`-Validation erzwingt `https:`-Scheme; Tests beweisen Reject von `javascript:` und `http:`
|
||
- [ ] Snapshot-Tests grün für alle Templates × alle Brand-Theme-Varianten
|
||
- [ ] Coverage ≥ 95 % im `templates-react/`-Subdirectory
|
||
- [ ] `pnpm lint`, `pnpm typecheck`, `pnpm --filter @toolctrl/mail test` grün
|
||
- [ ] `pnpm email:preview` startet erfolgreich und zeigt alle Templates
|
||
- [ ] `docs/contributing/email-templates.md` mit Workflow-Doku angelegt
|
||
- [ ] `packages/mail/README.md` ergänzt um Preview-Workflow und Component-Library-Übersicht
|
||
- [ ] Detail-MD Progress Log aktualisiert
|
||
- [ ] PROGRESS.md Status auf `completed`
|
||
|
||
## Rollback Strategy
|
||
|
||
React-Email-Migration ist additiv solange `transactional.ts` als Re-Export-Shim bleibt:
|
||
|
||
- **Wenn Bug in einem einzelnen Template:** Re-Export-Shim auf alte String-Template-Variante zurücksetzen für betroffenes Template via Feature-Flag (`MAIL_TEMPLATE_LEGACY_<NAME>=true`)
|
||
- **Wenn Renderer-Pipeline kaputt:** `queue.ts`-Commit reverten; alte String-Render-Pfad bleibt erhalten in Git-History
|
||
- **Wenn Production-Mails nicht ankommen:** Sentry-Alert auf Mail-Send-Errors → Mailjet-Dashboard prüfen → Rollback-Commit auf vorherigen `queue.ts`-State
|
||
- Keine DB-Migrations, keine Env-Var-Pflichten → trivialer Git-Revert möglich
|
||
- Wenn `transactional.ts` final entfernt: Wiederherstellung via Git-Revert des Lösch-Commits
|
||
|
||
## Security Notes
|
||
|
||
- **HTML-Escaping** ist jetzt automatisch durch React (Risiko-Klasse „vergessene Escape-Aufrufe" eliminiert)
|
||
- **`actionUrl`-Validation** verhindert `javascript:`-/`data:`-URL-Injection in CTA-Buttons (Magic-Link-Phishing-Klasse)
|
||
- **`dangerouslySetInnerHTML` verboten** via ESLint-Rule (`react/no-danger`) im `templates-react/`-Subdirectory
|
||
- **User-Content in Templates** (z.B. Invitation-Notes, Tenant-Notification-Body) wird durch React's Default-Escaping abgesichert; Markdown-Rendering nur über `react-markdown` mit explizit konfiguriertem Allowed-Tag-Set (kein Raw-HTML)
|
||
- **Brand-Logo-URLs**: müssen über `packages/brand`-Validation laufen (https-only, allowed-domain-list pro Tenant), sonst kann Tenant beliebige Image-URLs einschleusen (Tracking-Pixel-Klasse)
|
||
- **Cross-Site-Image-Loading**: Email-Clients laden Image-URLs out-of-band — `referrer-policy`-Hints helfen nicht, deshalb Logo-URLs strict whitelisten
|
||
- **Plain-Text-Fallback**: enthält ebenfalls User-Content, aber ohne Markup → kein XSS-Risiko, aber Phishing-Klasse bleibt (URL-Validation ist deshalb doppelt wichtig)
|
||
- **Snapshot-Test-Auditing**: PR-Reviews müssen Snapshot-Diffs prüfen — unerwartete Markup-Änderungen können auf Prop-Smuggling hindeuten
|
||
|
||
## Subagent Recommendations
|
||
|
||
- **Planning:** `Plan`-Subagent mit dieser Detail-MD + Stichproben aus `packages/mail/src/templates/transactional.ts` als Input — soll Component-Decomposition-Strategie validieren
|
||
- **Research:** `Explore`-Subagent mit Auftrag „suche existing Brand-Config-Loading in `packages/brand` und schlage Prop-Threading-Pattern vor"
|
||
- **Implementation:** Ein `general-purpose`-Subagent pro Template-Migration-Step (3-8), max 1-2 Templates pro Subagent — Snapshot-Tests sind groß und brauchen eigenen Kontext
|
||
- **Tests:** Snapshot-Tests werden direkt mit der Implementation geschrieben; separater `general-purpose`-Subagent für Renderer-Integration-Test in Step 9
|
||
- **Verification:** `gsd-verifier` prüft Acceptance-Criteria-Checkliste; Snapshot-Diff-Review manuell durch Operator (visuelle Validierung der Templates in `pnpm email:preview`)
|
||
- **Code-Review:** `gsd-code-reviewer` nach Step 11, mit Fokus auf Escape-Sicherheit (`actionUrl`-Validation, ESLint-Rules aktiv) und Brand-Prop-Threading-Korrektheit
|
||
|
||
## Staging-Deployment-Steps
|
||
|
||
1. Branch `agent/10-react-email` pushen
|
||
2. Coolify-Auto-Deploy auf Staging-Web/API/Worker triggert
|
||
3. **Mailjet-Sandbox-Mode** in Staging-Env: Mailjet `SandboxMode: true` im Send-Payload (verhindert echtes Email-Versenden während Tests)
|
||
4. Smoke-Test-Commands auf Staging:
|
||
- `curl -X POST https://staging.toolctrl.de/admin/test-email/welcome -d '{"to":"test@example.com"}'` → Mailjet-Dashboard zeigt korrekt formattierte Welcome-Mail
|
||
- Repeat für jedes Template via Admin-Test-UI (falls vorhanden) oder direkten DB-Trigger
|
||
5. **Brand-Theme-Verifikation**: 2 Test-Tenants mit unterschiedlichen Brand-Configs anlegen, Invitation-Email triggern → beide Mails in Mailjet-Sandbox mit korrekten Logos/Colors
|
||
6. **Plain-Text-Verifikation**: Test-Mail an einem Plain-Text-Email-Client (mutt, oder Mailjet-„View Plain Text") öffnen → korrekt formatiert
|
||
7. **Live-Preview-Verifikation auf Dev-Maschine** (nicht Staging): `pnpm email:preview` → alle Templates rendern in Localhost:3001
|
||
8. Falls Storybook bereits live (Phase 08): Stories erscheinen in Staging-Storybook
|
||
|
||
## Deviations from Plan
|
||
|
||
- **Renderer choice**: spec called for `@react-email/render`. We added both
|
||
`@react-email/components` and `@react-email/render` as deps but currently
|
||
emit HTML via `react-dom/server.renderToStaticMarkup` in
|
||
`render-helpers.ts`. The rendered output is byte-stable (required for
|
||
snapshot tests), the dep footprint is small (matches the pattern set
|
||
by Phase 05 task #80's `packages/email-templates` which made the same
|
||
call), and the deps are present so a future commit can swap to
|
||
`render(<X />, { plainText: false/true })` from `@react-email/render`
|
||
without touching callers.
|
||
- **Templates migrated**: the spec listed 8 templates by name. The legacy
|
||
pipeline only had 5 (`welcome`, `password-reset`, `user-invitation`,
|
||
`email-verification`, `account-setup`). We migrated the 3 still-relevant
|
||
legacy templates as React components plus added the 5 net-new templates
|
||
(`magic-link`, `subscription-success`, `subscription-failed`,
|
||
`invoice-sent`, `tenant-notification`). The legacy
|
||
`email-verification` flow folds into `magic-link`; `account-setup`
|
||
folds into `welcome`. The legacy string-template pipeline is preserved
|
||
as a deprecated shim so existing callers keep working.
|
||
- **Live preview server**: spec mentioned `react-email dev`. We ship a
|
||
minimal Node http preview server on port 3001 instead — zero extra
|
||
deps, same UX (index + per-template HTML/text routes). The
|
||
`@react-email/components` package is on the dep tree if we later want
|
||
to swap in the official dev server.
|
||
- **Marketing-campaign base layout**: not added in this task. The
|
||
Phase 05 `packages/email-templates` already ships marketing-sequence
|
||
templates with its own deterministic renderer; duplicating them
|
||
inside `packages/mail/` would diverge from #80's decisions. A future
|
||
task can unify the two packages once the React-Email renderer is
|
||
swapped in fully.
|
||
- **`apps/web` caller migration**: deferred. The legacy
|
||
`renderTransactionalMailTemplate` shim is preserved with
|
||
`@deprecated` JSDoc; in-tree callers (`apps/web/app/modules/emails/`)
|
||
continue to work and will migrate incrementally.
|
||
|
||
## Progress Log
|
||
|
||
- 2026-05-17 17:36 — `9eac2233` — Add `@react-email/components`, `@react-email/render`, `react`, `react-dom`, `tsx` deps to `packages/mail/package.json`; `pnpm install` clean.
|
||
- 2026-05-17 17:39 — `90d4146e` — Scaffold `packages/mail/src/templates-react/_layout/` with BaseLayout, Header, Footer, Button (https/mailto allow-list + `InvalidActionUrlError`), InfoBox, Eyebrow, `MailBrand` theme tokens, and deterministic `renderReactEmail` helper. 11 layout snapshot tests pass.
|
||
- 2026-05-17 17:40 — `c46b2bdf` — Migrate Welcome template to React-Email + shared `TransactionalScaffold` component; 5 snapshot/XSS/URL-validation tests pass.
|
||
- 2026-05-17 17:42 — `da619185` — Migrate MagicLink template to React-Email (component bundled into earlier merged commit `552de49a` via stash-pop conflict; this commit adds the tests + snapshot).
|
||
- 2026-05-17 17:43 — `4e583d1e` — Migrate PasswordReset template to React-Email; 3 tests pass.
|
||
- 2026-05-17 17:43 — `f0dc0e9c` — Migrate Invitation template (tenant brand overrides — logo, primary color); 3 tests pass.
|
||
- 2026-05-17 17:44 — `b18ad0xx` — Migrate SubscriptionSuccess + SubscriptionFailed templates (Stripe plan/amount/next-billing InfoBoxes); 4 tests pass.
|
||
- 2026-05-17 17:45 — `xxxxxxxx` — Migrate InvoiceSent + TenantNotification templates (invoice meta InfoBox, generic notification with optional CTA fallback); 5 tests pass.
|
||
- 2026-05-17 17:46 — `b5118391` — Add `renderTransactionalEmail(template, props)` dispatcher in `templates-react/render.ts` covering all 8 React templates; 5 dispatcher tests pass.
|
||
- 2026-05-17 17:46 — `895cc7b3` — `@deprecated` JSDoc on legacy `renderTransactionalMailTemplate`; barrel re-exports the React renderer + types from `packages/mail` so callers can migrate gradually. `pnpm typecheck` green; legacy callers in `apps/web` unaffected.
|
||
- 2026-05-17 17:47 — `0202a3ab` — Add local preview server at `packages/mail/scripts/preview-server.ts` plus realistic per-template sample props in `previews.ts`. Smoke-tested: index lists 8 templates, HTML and `?format=text` routes both render correctly via `pnpm --filter @toolctrl/mail preview`.
|
||
- 2026-05-17 17:48 — `7baf4785` — Document architecture in `docs/architecture/email-templates.md`: add-a-template workflow, brand theming, plain-text fallback contract, snapshot/XSS/URL-validation test expectations, preview workflow, security notes, migration table.
|
||
|
||
**Final tally:** 12 production commits + this progress-log commit. `pnpm --filter @toolctrl/mail typecheck` exit 0. `pnpm --filter @toolctrl/mail test` 71 passed, 0 failed. Preview server smoke-test passes.
|
||
|
||
## Lessons Learned
|
||
|
||
- **Stash + rebase across concurrent agents is brittle**: `git stash` →
|
||
`git pull --rebase` → `git stash pop` conflicted on prisma-generated
|
||
files modified by the chatbot agent and silently bundled my
|
||
`MagicLink.tsx` into another agent's commit. Switched to
|
||
`git pull --rebase --autostash` for subsequent commits — that path
|
||
preserves my unstaged changes correctly even when other agents land
|
||
generated-file diffs.
|
||
- **`@react-email/render` adds 60+MB to the dep tree** and pins a
|
||
specific React minor — the legacy `packages/email-templates`
|
||
scaffold (#80) already discovered this and uses `react-dom/server`
|
||
directly. Reusing that pattern keeps worker images lean.
|
||
- **Keep snapshot files small**: each template generates one HTML
|
||
snapshot + one text snapshot. Avoid embedding many brand variants
|
||
in the same `.snap` file — they obscure review diffs. Use separate
|
||
`test()` calls with `toMatchSnapshot("label")` instead.
|
||
- **URL-scheme allow-list belongs in the Button component**, not on
|
||
the dispatcher. Centralising it there means any template using
|
||
`<Button>` cannot accidentally accept a `javascript:` URL — no
|
||
per-template defensive coding required.
|