Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Settled the email editor's variables, draft conflicts and revert history

Damian Legawiec2125320f1555
diff --git a/docs/plans/6.0-email-template-editor.md b/docs/plans/6.0-email-template-editor.md
index c5afcbefcb..597944fb40 100644
--- a/docs/plans/6.0-email-template-editor.md
+++ b/docs/plans/6.0-email-template-editor.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.0
**Depends on:** `6.0-liquid-mjml-emails.md` (Liquid and MJML templates, the template lookup, email serializers), `6.0-admin-rbac.md` (permission catalog), `6.0-admin-spa.md` (dashboard)
**Author:** Damian Legawiec
-**Last updated:** 2026-09-30
+**Last updated:** 2026-10-01
**Tracking:** Linear V-3729 · GitHub spree/spree#14775
## Summary
@@ -28,13 +28,16 @@ Every transactional email Spree sends renders from a Liquid template written in
- **One template serves every language, with optional per-language versions** (2026-09-30). A saved template applies to every language, using translation keys (`{{ 'key' | t }}`) or plain text; a merchant can add a version for one language when its copy must differ. The lookup tries the email's language first, then the every-language version, then the files.
- **`locale` is never NULL:** the every-language version stores `locale = 'any'`, because a unique index treats NULLs as distinct and would let two every-language rows exist for one key.
- **History is the live row plus an append-only revisions table** (2026-09-30). `spree_email_templates` holds what is published, so the lookup on every send is one indexed read; `spree_email_template_revisions` records each publish. Rejected: one versions table with a current flag, which makes every send query the latest version and needs the flag kept consistent under concurrent publishes.
+- **Reverting keeps the row, marked reverted, so history survives** (2026-10-01). A published template has a `status` (`published` or `reverted`, declared with `has_status`); reverting to the default sets it to `reverted` and deletes the draft. The lookup reads only `published` rows, and publishing again later reuses the same row, so its revisions stay reachable. Rejected: deleting the row, which made the email's history unreachable from its screen.
+- **Drafts carry a version number and who saved them last** (2026-10-01). `lock_version` refuses a save made from a stale copy (409), and `updated_by` lets the editor say "Last saved by Ann, 5 minutes ago" and name who changed the draft in that refusal. One shared draft per store, email and language stays; two admins editing at once get a clear conflict instead of silently overwriting each other.
- **Preview uses the latest matching record, and the merchant can pick another** (2026-09-30). Each email builds its sample from the store's most recent matching record (last completed order, fulfillment, return), falls back to an in-memory sample for a new store, and accepts a record id so a merchant can check a specific case (a discount, a multi-parcel order).
- **Test emails go only to the signed-in admin** (2026-09-30). The endpoint cannot be used to send store-branded mail, a phishing risk, to arbitrary addresses. To check another inbox, the admin forwards it.
- **The editor is CodeMirror 6** (2026-09-30), as a headless `CodeEditor` component in `@spree/dashboard-ui` so the seller panel and plugins can reuse it. It is modular and small, and custom completions for Liquid variables and MJML tags are straightforward. Liquid highlighting inside HTML needs a small custom mode. Rejected: Monaco (a multi-megabyte bundle with web workers, poor on mobile) and a plain textarea (no highlighting or autocomplete).
- **The subject is a field of its own.** Files carry the subject as front matter; a saved template stores `subject` and `body` separately, which is the shape the front matter was chosen to map onto. The editor shows the subject as a text field above the code.
- **Email templates are their own permission resource** (`email_templates`), not part of `settings`. A template writes content every customer receives, including links, so the RBAC plan's rule for sensitive resources applies: a role can manage store settings without being able to change what customers are emailed.
- **Branding lives in store preferences** and reaches templates as `store.branding` variables that the layout's `<mj-attributes>` read. It is independent of any template's code, so reverting a template never loses the store's colors and fonts.
-- **The Admin API serves each editable email's variables**, for the editor's autocomplete. How they are derived (declared per email, or read from a sample run of the mailer) is settled during implementation; `email-variables.mdx` is maintained by hand until then.
+- **Autocomplete reads a TypeScript manifest built on generated types; there is no variables API** (2026-10-01). Typelizer, added to `spree_emails`, generates TypeScript types for the email serializers (`EmailOrder`, `EmailOrderGroup`, `EmailFulfillment`, `EmailReturn`, the email store, …) into `@spree/admin-sdk`, and the existing pipeline turns them into Zod schemas. A hand-written manifest in the dashboard maps each editable email and shared block to the variables it receives and their schema; the editor walks the schemas to offer fields. The preview response also returns the data it rendered with, so autocomplete shows real example values at no extra cost.
+ - **Accepted trade-off:** the manifest's list of which variables each email receives is kept in step with its mailer by hand. Field types cannot drift, because they are generated. An extension adding a customer email registers its manifest entry through a dashboard plugin.
## Design Details
@@ -50,8 +53,12 @@ locale string, not null locale string, not null body
subject text subject text base_digest string, not null
body text, not null body text, not null published_by (acted_by)
base_digest string, not null base_digest string, not null created_at
-published_at datetime, not null updated_by (acted_by) index (email_template_id, created_at)
-created_at, updated_at created_at, updated_at
+status string, not null lock_version integer, not null index (email_template_id, created_at)
+published_at datetime, not null updated_by (acted_by)
+published_by (acted_by) created_at, updated_at
+reverted_at datetime
+reverted_by (acted_by)
+created_at, updated_at
unique (store_id, key, locale) unique (store_id, key, locale)
```
@@ -60,15 +67,16 @@ unique (store_id, key, locale) unique (store_id, key, locale)
- **`subject`** is set for emails and empty for the layout and partials.
- **`base_digest`** is the SHA-256 of the default file's source when the merchant started from it. Comparing it with the current default's digest is how the dashboard knows an upgrade changed the default underneath the merchant's version.
- **Drafts** hold work in progress, one per store, key and language. Publishing validates the draft, copies it into `spree_email_templates` (creating the row on first publish), appends a revision and deletes the draft.
-- **Reverting to a revision** copies it into the draft; the merchant publishes it like any other change. **Reverting to the default** deletes the store's published template and draft, so the file answers again. History is never rewritten.
-- The published model publishes lifecycle events (`email_template.published`, `.deleted`), so integrations and audit tooling see what customers will now receive.
+- **`status`** is `published` or `reverted` (`has_status`; set by the publish and revert workflows, no column default). **Reverting to the default** marks the row `reverted` and deletes the draft, so the file answers again; publishing later sets it back to `published` on the same row. **Reverting to a revision** copies it into the draft; the merchant publishes it like any other change. History is never rewritten.
+- **`lock_version`** is Rails' optimistic locking on drafts. A save carrying an old version is refused with 409, naming `updated_by`.
+- The published model publishes lifecycle events (`email_template.published`, `.reverted`), so integrations and audit tooling see what customers will now receive.
### Lookup
An editable-email registry names the customer emails, `Spree::Emails.editable_templates` in `spree_emails`, which an extension appends to for its own customer emails. When a mailer renders one of them, `Spree::Emails::TemplateResolver#find(key)` gains a store:
-1. the store's published template for the key in the email's language
-2. the store's published template for the key with `locale = 'any'`
+1. the store's `published` template for the key in the email's language
+2. the store's `published` template for the key with `locale = 'any'`
3. the app's `app/views/<key>.liquid`
4. the first gem's `app/views/<key>.liquid`
@@ -92,12 +100,12 @@ Under `/api/v3/admin/email_templates`, keyed by the template key (URL-encoded),
| Endpoint | What it does |
| --- | --- |
| `GET /email_templates` | Every editable template: key, name, kind (email, layout, partial), languages customized, whether a draft exists, whether the default changed since |
-| `GET /email_templates/:key?locale=` | The published version (the store's, else the default), the draft if any, the default, and the variables it receives |
-| `PUT /email_templates/:key/draft` | Save the draft's subject and body, in any state |
+| `GET /email_templates/:key?locale=` | The published version (the store's, else the default), the draft if any (with `lock_version` and who saved it last), and the default |
+| `PUT /email_templates/:key/draft` | Save the draft's subject and body, in any state; carries `lock_version`, 409 naming who changed it when stale |
| `DELETE /email_templates/:key/draft` | Discard the draft |
| `POST /email_templates/:key/publication` | Publish the draft; renders it (and, for the layout or a partial, every customer email) with sample data; 422 with line-level errors when anything does not render |
-| `DELETE /email_templates/:key?locale=` | Revert to the default |
-| `POST /email_templates/:key/preview` | Render an unsaved subject and body with sample data (`record_id` optional); returns subject, HTML and text |
+| `DELETE /email_templates/:key?locale=` | Revert to the default (marks the published row `reverted`) |
+| `POST /email_templates/:key/preview` | Render an unsaved subject and body with sample data (`record_id` optional); returns subject, HTML, text and the variables it rendered with |
| `POST /email_templates/:key/test_email` | Send the draft or the published version to the signed-in admin |
| `GET /email_templates/:key/revisions` | History, newest first |
| `POST /email_templates/:key/revisions/:id/restoration` | Copy a revision into the draft |
@@ -122,11 +130,12 @@ All copy goes through i18next in every locale file, per the dashboard rules.
## Migration Path
-1. **Models and lookup**: `Spree::EmailTemplate`, `Spree::EmailTemplateDraft`, `Spree::EmailTemplateRevision`, one migration, the store and language steps in `TemplateResolver`, publish workflow with validation, lifecycle events, permission catalog entry `email_templates`.
+1. **Models and lookup**: `Spree::EmailTemplate`, `Spree::EmailTemplateDraft`, `Spree::EmailTemplateRevision`, one migration, the store and language steps in `TemplateResolver`, publish and revert workflows with validation, lifecycle events, permission catalog entry `email_templates`.
+1a. **Email types**: Typelizer in `spree_emails`, an email writer emitting `Email*` types into `@spree/admin-sdk`, Zod schemas through the existing pipeline, and the Lefthook hook extended to the email serializers.
2. **Sample data and preview**: per-email sample builders, the preview and test email endpoints.
3. **Admin API**: the remaining endpoints, serializers, integration specs, OpenAPI regeneration, Admin SDK methods.
4. **Branding**: store preferences, `store.branding` in the store serializer, the default layout reading them, the branding card.
-5. **Dashboard editor**: `CodeEditor` in `@spree/dashboard-ui`, the list, editor, preview, drafts and publishing, history, revert, update banner with diff.
+5. **Dashboard editor**: `CodeEditor` in `@spree/dashboard-ui`, the variables manifest, the list, editor, preview, drafts and publishing with conflict handling, history, revert, update banner with diff.
6. **Docs**: merchant guide in `docs/user/settings/emails`, developer notes on how saved templates interact with file overrides, and the Admin API reference.
## Constraints on Current Work
@@ -137,7 +146,8 @@ All copy goes through i18next in every locale file, per the dashboard rules.
- **Changing a default template triggers the "updated by Spree" banner** for every store that customized it. Change defaults deliberately, and describe the change in release notes.
- **Keep partial arguments stable.** Merchants can edit partials and the emails that call them independently, so renaming or removing a partial's argument breaks stores that customized either side. Add arguments; don't rename them.
- **Any new way to send an email must go through the lookup.** A mailer that renders a template itself would skip the store's published version.
-- **A new customer email must be registered as editable** in `Spree::Emails.editable_templates` (with a sample builder), or merchants cannot edit it. A new staff, store-owner or seller email must not be registered.
+- **A new customer email must be registered as editable** in `Spree::Emails.editable_templates` (with a sample builder) and in the dashboard's variables manifest, or merchants cannot edit it. A new staff, store-owner or seller email must not be registered.
+- **Changing what a customer email passes to `mail_template` means updating its manifest entry**, and `email-variables.mdx`. Changing an email serializer regenerates its types through the pipeline.
## Open Questions
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 2492522361..f736c785f3 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -99,6 +99,16 @@ Rejected:
**Plans amended:** `6.0-tax-provider.md` (contract, Internal refund limit, "Post-sale tax", lifecycle integration points, Phase 6 follow-ups, Constraints on Current Work), `6.0-returns-exchanges-claims.md` (key decisions, ReturnLineItem, ExchangeLineItem and ClaimLineItem notes, refunding, exchange workflow, Constraints on Current Work, resolved question 7).
+## 2026-10-01: The email editor's variables come from generated types, and reverted templates keep their history
+
+**Context:** Building the email template editor (`6.0-email-template-editor.md`) left three details open: how autocomplete learns each email's variables, how two admins editing one draft avoid overwriting each other, and what reverting to the default does to a template's history.
+
+**Decision:** Typelizer is added to `spree_emails` and generates `Email*` TypeScript types for the email serializers into `@spree/admin-sdk`, turned into Zod schemas by the existing pipeline. A hand-written manifest in the dashboard maps each editable email to its variables and their schemas, and the preview response returns the data it rendered with for example values; there is no variables API. Drafts carry Rails' `lock_version` and `updated_by`, so a stale save is refused naming who changed it. Reverting marks the published row `reverted` (`has_status`) instead of deleting it; the lookup reads only `published` rows and a later publish reuses the row, so history survives.
+
+**Consequences:** Which variables each email receives is kept in step with its mailer by hand in the manifest; their fields cannot drift because they are generated. Extensions adding a customer email add a manifest entry through a dashboard plugin.
+
+**Plans amended:** `6.0-email-template-editor.md`.
+
## 2026-09-30: Merchants edit email templates in the dashboard, as drafts published per store
**Context:** Since the Liquid and MJML plan, every email renders from a template only a developer can change. The end goal was always merchant editing; this settles its shape.