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.

25.7 KB
Raw Blame

Email Template Editor

Status: In Progress — backend, Admin API, admin SDK and branding built; dashboard editor and docs in progress on feature/v-3729-email-template-editor 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-10-01 Tracking: Linear V-3729 · GitHub spree/spree#14775

Summary

Every transactional email Spree sends renders from a Liquid template written in MJML, and today only a developer can change one, by adding a file to the app. This plan lets merchants edit the emails their customers receive in the dashboard: each customer email, and the layout and shared blocks those emails are built from. Staff, store-owner and seller emails stay as Spree ships them. Edits are saved as a draft and go live when published; Spree finds the published version before the file, so an edited email goes out on the next send with no deploy. The editor shows the template's code next to a preview rendered on the server by the same renderer customers' emails go through, lists the variables the email receives, sends a test email, and keeps a history the merchant can revert to. Store branding settings (colors, fonts) style every customer email without touching its code, and survive a revert. When a Spree upgrade changes a default the merchant has customized, the dashboard says so and shows what changed.

Key Decisions (do not deviate without discussion)

  • Preview renders on the server (2026-09-30). The dashboard sends the draft template to an Admin API endpoint; the Ruby renderer fills it with sample data and returns the HTML and text parts. What the merchant sees is exactly what customers receive, there is one renderer and one set of filters to maintain, and sending a test email is the same call with a recipient. Rendering in the browser stays an option for later if typing responsiveness demands it.

  • The database is one more step in the existing lookup, in front of the files. A store's saved template for a key wins; without one, the app's file, then Spree's own file, answer as today. No mailer changes: the key (spree/order_mailer/confirm_email) is the same name the file lookup uses. A developer's file override and a merchant's saved template can coexist; the merchant's wins for their store.

  • Templates are store-scoped records (belongs_to :store through Spree::SingleStoreResource), following the rule for store-owned data. A template never leaks between stores.

  • Only customer emails are editable (2026-09-30). Merchants edit what their customers receive: order confirmation, cancellation and payment link, the multi-seller purchase confirmation, shipping, refund, downloads, customer password reset and data export, newsletter confirmation and company invitation. Staff emails in core (admin and seller password resets, staff invitations, import and export results, disabled webhooks), the store-owner notifications and the seller emails stay as Spree's files. The line is who reads the email, not which gem ships it.

    • Accepted trade-off: a merchant cannot reword the new-order notification their own staff receives, or the emails sent to sellers, from the dashboard; a developer still can, with a file.
  • Customer emails can use an edited layout and edited shared partials (2026-09-30). A merchant can edit layouts/spree/base_mailer and the spree/shared/* partials, so the footer or the item row changes once for every customer email.

    • Accepted trade-off: one bad edit to the layout or a partial affects every customer email. Publishing a layout or partial therefore validates every customer email of the store, not just one.
  • Emails that are not editable never read store templates (2026-09-30). Staff, store-owner and seller emails render with Spree's own layout and partials (or the app's files), even when the store has published edited versions. A template edit can never break or rebrand a password reset for staff.

    • Accepted trade-off: the lookup must know which emails are editable, and a merchant's footer change does not appear on staff emails.
  • Edits are drafts until published (2026-09-30). Saving stores a draft; a separate Publish step makes it live and records a revision. Teams can stage and review a change before customers see it.

    • Accepted trade-off: a draft state per template, a publish endpoint and UI, and every screen must make clear whether it shows the draft or the published version.
  • A published template must render. Publishing validates by rendering with sample data under strict variables: a Liquid syntax error, an unknown variable, an unknown filter or invalid MJML is refused with the line and message, so a merchant can never break an email that is already being sent. Drafts may be saved in any state, since they are work in progress. Production sends stay lenient (an unknown variable prints nothing), as today.

  • 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.
    • Superseded in part (2026-10-01): merchants edit one language at a time, in readable text. Translation keys such as {{ 'order_mailer.confirm_email.dear_customer' | t: name: order.customer_name }} stay in Spree's own files, which is how they ship translated into every language, but a merchant can neither read them nor change the text behind them. When a merchant edits a template for a language, the editor writes those keys out as text in that language (Dear {{ order.customer_name }},), in the subject and the body, and the edit becomes that language's version. Languages nobody edited keep Spree's translated default. The editor no longer offers "All languages"; the API still accepts any, and a version for every language published earlier keeps applying to languages without their own. This matches how other platforms handle it: none shows translation keys to merchants, and each language is edited as its own copy.
    • Accepted trade-off: the same change in five languages is made five times.
  • 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) and accepts a record id so a merchant can check a specific case (a discount, a multi-parcel order).

    • Superseded in part (2026-10-01): emails built from a record (orders, order groups, fulfillments, returns) have no in-memory fallback. A store with no such record gets a clear "nothing to preview with yet" message instead of a preview, and publishing such an email checks its Liquid syntax only. Emails that need no record (password reset, newsletter confirmation, company invitation, data export) always preview. An invented order would need every serializer to accept unsaved records, which they do not.
  • 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.

  • 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. A hand-written manifest in the dashboard, typed against those types so a renamed field fails the typecheck, maps each editable email and shared block to the variables it receives. The editor offers those, plus the fields of the data the preview response returns, which also gives real example values at no extra cost. (The email types have no Zod schemas; see the decision on email data types below.)

    • 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.
  • The template remembers the default it started from as text, not a digest (2026-10-01). Drafts and published versions store base_subject and base_body. Comparing them with the current file tells the editor the default changed, and keeping the text lets it show what changed side by side. There is no separate endpoint for the comparison: reading a template returns the current default and, when it changed, the base. A merchant who has reviewed the change keeps their version by saving the draft with rebase. Rejected: a SHA-256 digest, which says that something changed but not what.

  • The API names a template by its key with dots (2026-10-01), spree.order_mailer.confirm_email for spree/order_mailer/confirm_email. Keys never contain dots, so the mapping is exact, and a key stays one URL segment without percent-encoding slashes.

  • The language is the language parameter, not locale (2026-10-01). locale already picks the language of an API response, so reusing it would switch the response's language too, and any is not a language. Responses name the template's language language and the customized ones customized_languages. A per-language version is only accepted in a language the store supports.

  • The editable registry lives in core (2026-10-01), as Spree.editable_email_templates, with spree_emails registering its eleven customer emails, the layout and five shared partials, each with the class that builds its sample data. The Admin API, which does not depend on spree_emails, reads the registry rather than the gem.

  • Branding is edited through the store settings endpoint and permission (2026-10-01). The six branding values are store preferences (preferred_email_accent_color, _background_color, _card_color, _text_color, _heading_color, _font), so they are read and written with the other store settings and need the settings permission, not the email templates one. Only a #RRGGBB color or a font from the fixed list is accepted, and anything else falls back to the default before it reaches an email's CSS, unsaved preview values included. The preview takes unsaved branding values, so the branding card can show them before they are saved.

  • Email data types are self-contained and have Zod schemas (2026-10-01). Every record a customer email serializes has an email serializer of its own (thin subclasses of the Store API ones, such as Spree::Emails::AddressSerializer), associations a request must ask for are left out, and the Email* types are generated into their own folder of @spree/admin-sdk, referencing only each other. Their Zod schemas are generated per folder, and the editor suggests variables by walking them, so every field is offered whether or not the sample record has it. Superseded: an earlier version of this decision dropped the schemas, because the email types then pointed at admin types and the order schema grew too large for TypeScript to emit.

Design Details

Data model

spree_email_templates                spree_email_template_drafts          spree_email_template_revisions
─────────────────────                ───────────────────────────          ──────────────────────────────
id                                   id                                   id
store_id      → spree_stores         store_id      → spree_stores         email_template_id → spree_email_templates
key           string, not null       key           string, not null       subject           text
locale        string, not null       locale        string, not null       body              text, not null
subject       text                   subject       text                   subject           text
body          text, not null         body          text, not null         body              text, not null
base_subject  text                   base_subject  text                   published_by (acted_by)
base_body     text, not null         base_body     text, not null         created_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)
  • key is the name the lookup uses: an editable email's view path (spree/order_mailer/confirm_email), the layout (layouts/spree/base_mailer) or a partial's render name (spree/shared/line_item). It is validated against the editable set and what Spree and the app ship, so a store cannot create a template nothing renders or a staff email it may not edit.
  • locale is a language code, or 'any' for the version every language uses.
  • subject is set for emails and empty for the layout and partials.
  • base_subject and base_body are the default file's subject and body when the merchant started from it. Comparing them with the current default is how the dashboard knows an upgrade changed the default underneath the merchant's version, and shows what changed.
  • 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.
  • 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.editable_email_templates in core, which spree_emails fills and 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'
  3. the app's app/views/<key>.liquid
  4. the first gem's app/views/<key>.liquid

Partials and the layout resolve the same way through the renderer's file system, so a published layouts/spree/base_mailer or spree/shared/line_item applies to every customer email that uses it. For any other email the resolver is built without the store, so steps 1 and 2 never run and the layout and partials come from files. A preview renders the draft being edited in place of its published version, and the published versions of everything else.

Branding

Store preferences, all optional, defaulting to today's design:

  • preferred_email_accent_color (buttons, links)
  • preferred_email_background_color, preferred_email_card_color
  • preferred_email_text_color, preferred_email_heading_color
  • preferred_email_font (from a fixed list of email-safe and web fonts, each with its fallback stack)

Spree::Emails::StoreSerializer exposes them as store.branding. The default layout reads them in <mj-attributes> and <mj-style>, so every default email follows them. A merchant's edited layout can read them too, or ignore them.

Admin API

Under /api/v3/admin/email_templates, keyed by the template key with dots, scoped to the current store. language (a language code, or any, the default) picks the version.

Endpoint What it does
GET /email_templates Every editable template: key, kind (email, layout, partial), what customers receive now, the languages customized, the draft, whether the default changed since
GET /email_templates/:id The published version (the store's, else the default), the draft if any (with lock_version and who saved it last), the default, and the base it started from when the default changed
PUT /email_templates/:id/draft Save the draft's subject and body, in any state; carries lock_version, 409 naming who changed it when stale; rebase marks it as based on the current default
DELETE /email_templates/:id/draft Discard the draft
POST /email_templates/:id/publication Publish the draft; renders it (and, for the layout or a partial, every customer email) with sample data; 422 with each problem's email, line and message when anything does not render
DELETE /email_templates/:id Revert to the default (marks the published row reverted, discards the draft)
POST /email_templates/:id/preview Render an unsaved subject and body with sample data (record_id, email_key for the layout and partials, unsaved branding); returns subject, HTML, text and the variables it rendered with; 422 when it does not render or there is nothing to preview with
POST /email_templates/:id/test_email Send what the preview renders to the signed-in admin
GET /email_templates/:id/revisions History, newest first
POST /email_templates/:id/revisions/:revision_id/restoration Copy a revision into the draft

Publish, preview, test send and restore are not CRUD on the template itself, so each is its own nested resource with create, per the API conventions.

Sample data

Each email declares how to build its sample: the store's most recent matching record (the last completed order, fulfillment, return), a record the merchant picks by its id, or an unsaved sample built in memory so a brand-new store can still preview. Every lookup is scoped to the current store. The same samples feed validation on publish. Token-carrying values (reset links, invitation links) get placeholder URLs, never a real token.

Dashboard

A new Settings → Emails → Templates area (next to the existing sender settings):

  • A list of the customer emails, the layout and the shared blocks, showing which are customized and which have an updated default.
  • The editor: language switcher, subject field, CodeMirror editor with MJML and Liquid highlighting and variable autocomplete, preview pane (desktop and mobile widths, HTML and plain-text tabs, a record picker) refreshed on pause, "Send test email", "Save draft", "Publish", "Discard draft", "Revert to default", and a history drawer. The screen always says whether it shows the draft or the published version.
  • An "Updated by Spree" banner with a side-by-side diff of the old and new default, and the option to keep the customized version or start again from the new default.
  • A Branding card for the colors and fonts, with the preview reflecting them.

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 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's types/generated/emails, type generation for every SDK run from spree_emails so both serializer sets always load, 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 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

  • Keep every email's data in its serializer and every token in its mailer. The editor shows the serialized variables and nothing else; a value a mailer computes in Ruby without passing it to the template cannot be offered to merchants.
  • Don't add Ruby-only template features. Anything a template needs must be a Liquid filter or a serialized field, so a saved template renders exactly like a file.
  • Renaming an email key is now a data migration. Saved templates reference keys; renaming a mailer method needs a rake task moving stored templates to the new key.
  • 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.editable_email_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.
  • Run type generation through rake typelizer:generate, never Typelizer directly. It runs inside spree_emails' test app, the one place where the API and email serializers both load; generating with either set missing deletes the other's types.
  • Keep hard-coded colors and fonts out of customer email templates. Read them from store.branding, so a store's branding reaches every email, including ones added later.

Open Questions

None. Rendering previews in the browser, for instant feedback while typing, is deferred until server-side preview proves too slow in practice.

References

  • 6.0-liquid-mjml-emails.md: the renderer, template keys, email serializers
  • 6.0-admin-rbac.md: permission catalog, the rule for sensitive resources
  • 6.0-admin-spa.md: dashboard conventions, settings navigation
  • 6.0-action-actors.md: acted_by for who saved a revision
  • docs/developer/customization/emails.mdx, docs/developer/customization/email-variables.mdx