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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Added store-scoped email templates with drafts, publishing and history
Damian Legawiecdbfecdf4507a
diff --git a/spree/core/app/mailers/spree/base_mailer.rb b/spree/core/app/mailers/spree/base_mailer.rbindex bb9c0316b4..7889a72480 100644--- a/spree/core/app/mailers/spree/base_mailer.rb+++ b/spree/core/app/mailers/spree/base_mailer.rb@@ -90,8 +90,9 @@ module Spree# @return [Mail::Message]def mail_template(assigns = {}, template: "#{mailer_name}/#{action_name}", **headers)in_store_locale do- email_template = email_resolver.find(template) || raise(ArgumentError, "Missing email template #{template}.liquid")- email = email_renderer.render(email_template, assigns)+ resolver = email_resolver(template)+ email_template = resolver.find(template) || raise(ArgumentError, "Missing email template #{template}.liquid")+ email = email_renderer(resolver).render(email_template, assigns)mail(headers.merge(subject: email.subject)) do |format|format.text { render plain: email.text, layout: false }@@ -116,12 +117,7 @@ module Spree# @param params [Hash] serializer params, over the email's store, currency and locale# @return [Hash, nil]def email_data(object, serializer, **params)- return if object.nil?-- params = { store: current_store, currency: email_currency, locale: I18n.locale.to_s,- storefront_url: current_store.storefront_url.to_s.chomp('/'),- hide_credentials: true }.merge(params)- JSON.parse(serializer.new(object, params: params).serialize)+ Spree::Emails::TemplateData.call(object, serializer, store: current_store, currency: email_currency, **params)end# URI-based merge preserves existing query params and fragments so the token@@ -139,12 +135,18 @@ module Spreeprivate- def email_resolver- @email_resolver ||= Spree::Emails::TemplateResolver.new(self.class.view_paths.paths.map(&:path))+ # The store's published templates apply only to the emails merchants may+ # edit; every other email, and the layout and partials it uses, comes+ # from files.+ def email_resolver(template = nil)+ view_paths = self.class.view_paths.paths.map(&:path)+ return Spree::Emails::TemplateResolver.new(view_paths) unless Spree.editable_email_templates.include?(template)++ Spree::Emails::TemplateResolver.new(view_paths, store: current_store, locale: I18n.locale)end- def email_renderer- Spree::Emails::Renderer.new(resolver: email_resolver, store: current_store, currency: email_currency)+ def email_renderer(resolver = email_resolver)+ Spree::Emails::Renderer.new(resolver: resolver, store: current_store, currency: email_currency)enddef in_store_locale(&block)diff --git a/spree/core/app/models/concerns/spree/email_template_identity.rb b/spree/core/app/models/concerns/spree/email_template_identity.rbnew file mode 100644index 0000000000..e317a95c21--- /dev/null+++ b/spree/core/app/models/concerns/spree/email_template_identity.rb@@ -0,0 +1,45 @@+module Spree+ # What a store's published email template and its draft share: which+ # editable template they are, in which language, and the default they+ # started from.+ module EmailTemplateIdentity+ extend ActiveSupport::Concern++ # The version every language uses. Never NULL, so the unique index on+ # store, key and locale holds for it too.+ ANY_LOCALE = 'any'.freeze+ LOCALE_FORMAT = /\A(any|[a-z]{2,3}(-[A-Za-z0-9]{2,8})*)\z/++ included do+ include Spree::SingleStoreResource++ normalizes :locale, with: ->(locale) { locale.to_s.strip.presence || ANY_LOCALE }++ validates :key, presence: true, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id, :locale] }+ validates :locale, format: { with: LOCALE_FORMAT }+ validates :body, :base_body, presence: true+ validate :key_editable++ scope :for_key, ->(key, locale = ANY_LOCALE) { where(key: key, locale: locale) }+ end++ # @return [Spree::Emails::EditableTemplates::Definition, nil]+ def definition+ Spree.editable_email_templates[key]+ end++ # @return [Boolean] whether Spree's default changed since this version started from it+ # @param default [Spree::Emails::Template, nil] the current default+ def default_changed?(default)+ return false unless default++ default.body != base_body || default.subject.to_s != base_subject.to_s+ end++ private++ def key_editable+ errors.add(:key, :invalid) if key.present? && definition.nil?+ end+ end+enddiff --git a/spree/core/app/models/spree/email_template.rb b/spree/core/app/models/spree/email_template.rbnew file mode 100644index 0000000000..e97be228ea--- /dev/null+++ b/spree/core/app/models/spree/email_template.rb@@ -0,0 +1,23 @@+module Spree+ # A store's published version of an editable email template (an email, the+ # layout or a shared partial). Found before the template file whenever a+ # customer email renders, so it is what customers receive. Reverting marks it+ # reverted rather than deleting it, so its revisions stay reachable.+ class EmailTemplate < Spree.base_class+ has_prefix_id :etpl++ include Spree::EmailTemplateIdentity+ include Spree::HasStatus+ include Spree::ActedBy++ has_status :published, :reverted, default: :published++ acted_by :published_by+ acted_by :reverted_by++ has_many :revisions, -> { order(created_at: :desc) }, class_name: 'Spree::EmailTemplateRevision',+ dependent: :destroy, inverse_of: :email_template++ validates :published_at, presence: true+ end+enddiff --git a/spree/core/app/models/spree/email_template_draft.rb b/spree/core/app/models/spree/email_template_draft.rbnew file mode 100644index 0000000000..5178a02394--- /dev/null+++ b/spree/core/app/models/spree/email_template_draft.rb@@ -0,0 +1,13 @@+module Spree+ # Work in progress on an editable email template, one per store, template+ # and language. Shared by every admin of the store: `lock_version` refuses a+ # save made from a stale copy, and `updated_by` says who saved it last.+ class EmailTemplateDraft < Spree.base_class+ has_prefix_id :etdr++ include Spree::EmailTemplateIdentity+ include Spree::ActedBy++ acted_by :updated_by+ end+enddiff --git a/spree/core/app/models/spree/email_template_revision.rb b/spree/core/app/models/spree/email_template_revision.rbnew file mode 100644index 0000000000..19f9c3f1ba--- /dev/null+++ b/spree/core/app/models/spree/email_template_revision.rb@@ -0,0 +1,17 @@+module Spree+ # One published version of a store's email template, kept so it can be+ # restored. Append-only.+ class EmailTemplateRevision < Spree.base_class+ has_prefix_id :etrv++ include Spree::ActedBy++ belongs_to :email_template, class_name: 'Spree::EmailTemplate', inverse_of: :revisions++ acted_by :published_by++ validates :body, presence: true++ delegate :store, :key, :locale, to: :email_template+ end+enddiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 1aab48bcd0..ecd8ac37f5 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -303,6 +303,8 @@ module Spreehas_many :policies, class_name: 'Spree::Policy', dependent: :destroy, as: :ownerhas_many :webhook_endpoints, class_name: 'Spree::WebhookEndpoint', dependent: :destroy, inverse_of: :store+ has_many :email_templates, class_name: 'Spree::EmailTemplate', dependent: :destroy, inverse_of: :store+ has_many :email_template_drafts, class_name: 'Spree::EmailTemplateDraft', dependent: :destroy, inverse_of: :storehas_many :webhook_deliveries, through: :webhook_endpoints, class_name: 'Spree::WebhookDelivery'has_many :channels, class_name: 'Spree::Channel', dependent: :destroydiff --git a/spree/core/app/services/spree/email_templates/check.rb b/spree/core/app/services/spree/email_templates/check.rbnew file mode 100644index 0000000000..c5163e4edc--- /dev/null+++ b/spree/core/app/services/spree/email_templates/check.rb@@ -0,0 +1,51 @@+module Spree+ module EmailTemplates+ # Renders a draft the way customers would receive it, with sample data+ # and strict variables, and reports what stops it from rendering. A+ # draft of the layout or a shared partial is checked inside every+ # editable email, since all of them use it.+ #+ # An email the store has no record for cannot be rendered with data; its+ # draft is still checked for Liquid syntax errors.+ class Check+ # @param store [Spree::Store]+ # @param draft [Spree::EmailTemplateDraft]+ def initialize(store:, draft:)+ @store = store+ @draft = draft+ end++ # @return [Array<Hash>] one `{ email:, message:, line: }` per problem; empty when the draft renders+ def call+ email_keys.filter_map { |email_key| problem_in(email_key) }+ end++ private++ def email_keys+ definition = @draft.definition+ definition.email? ? [definition.key] : Spree.editable_email_templates.emails.map(&:key)+ end++ def problem_in(email_key)+ Preview.new(store: @store, key: @draft.key, locale: @draft.locale, subject: @draft.subject, body: @draft.body,+ email_key: email_key, strict: true).call+ nil+ rescue Spree::EmailTemplates::NoSampleRecord+ syntax_problem(email_key)+ rescue Liquid::Error => e+ { email: email_key, message: e.message, line: e.line_number }+ rescue MRML::Error => e+ { email: email_key, message: e.message, line: nil }+ end++ def syntax_problem(email_key)+ Liquid::Template.parse(@draft.body, environment: Spree::Emails::Renderer.environment, line_numbers: true)+ Liquid::Template.parse(@draft.subject.to_s, environment: Spree::Emails::Renderer.environment)+ nil+ rescue Liquid::Error => e+ { email: email_key, message: e.message, line: e.line_number }+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/email_templates/no_sample_record.rb b/spree/core/app/services/spree/email_templates/no_sample_record.rbnew file mode 100644index 0000000000..e705dc83cb--- /dev/null+++ b/spree/core/app/services/spree/email_templates/no_sample_record.rb@@ -0,0 +1,7 @@+module Spree+ module EmailTemplates+ # The store has no record to build an email's sample data from, so it+ # cannot be previewed with data yet.+ class NoSampleRecord < StandardError; end+ end+enddiff --git a/spree/core/app/services/spree/email_templates/preview.rb b/spree/core/app/services/spree/email_templates/preview.rbnew file mode 100644index 0000000000..760881bd01--- /dev/null+++ b/spree/core/app/services/spree/email_templates/preview.rb@@ -0,0 +1,90 @@+module Spree+ module EmailTemplates+ # Renders an editable email template with sample data, through the same+ # renderer customers' emails go through. An unsaved subject and body take+ # the place of the store's published version; everything else the email+ # uses comes from the store's published templates and the files.+ #+ # The layout and shared partials are previewed inside an email that uses+ # them, the first editable email unless another is named.+ class Preview+ # @return [Hash] the variables the email was rendered with, once {#call} has run+ attr_reader :variables++ # @param store [Spree::Store]+ # @param key [String] the editable template being previewed+ # @param locale [String] a language code, or "any"+ # @param subject [String, nil] an unsaved subject; nil keeps the current one+ # @param body [String, nil] an unsaved body; nil keeps the current one+ # @param record_id [String, nil] the prefixed id of the record to build sample data from+ # @param email_key [String, nil] for the layout or a partial, the email to show it in+ # @param strict [Boolean] whether an unknown variable raises+ def initialize(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, subject: nil, body: nil,+ record_id: nil, email_key: nil, strict: false)+ @store = store+ @key = key+ @locale = locale.presence || Spree::EmailTemplate::ANY_LOCALE+ @subject = subject+ @body = body+ @record_id = record_id+ @email_key = email_key+ @strict = strict+ end++ # @return [Spree::Emails::RenderedEmail]+ # @raise [Spree::EmailTemplates::NoSampleRecord] when the store has no record to build the sample from+ def call+ sample = email.sample_class.new(store: @store, record_id: @record_id)++ in_locale do+ renderer = Spree::Emails::Renderer.new(resolver: resolver, store: @store, currency: sample.currency, strict: @strict)+ sample_variables = sample.variables+ @variables = renderer.variables(sample_variables)+ renderer.render(resolver.find(email.key), sample_variables)+ end+ end++ # @return [Spree::Emails::EditableTemplates::Definition] the email the preview renders+ def email+ @email ||= if definition.email?+ definition+ else+ Spree.editable_email_templates[@email_key.to_s].then { |named| named&.email? ? named : nil } ||+ Spree.editable_email_templates.emails.first+ end+ end++ private++ def definition+ Spree.editable_email_templates[@key] || raise(ArgumentError, "#{@key} is not an editable email template")+ end++ def resolver+ @resolver ||= Spree::Emails::TemplateResolver.new(+ Spree::BaseMailer.view_paths.paths.map(&:path), store: @store, locale: language, drafts: drafts+ )+ end++ def drafts+ return {} if @body.nil?++ { @key => Spree::Emails::Template.new(key: @key, subject: @subject, body: @body) }+ end++ def language+ @locale == Spree::EmailTemplate::ANY_LOCALE ? @store.default_locale : @locale+ end++ # Mirrors how mailers render: the email's language with the store's+ # translation fallbacks, restored afterwards.+ def in_locale(&block)+ previous_fallbacks = Mobility.store_based_fallbacks+ Spree::Locales::SetFallbackLocaleForStore.new.call(store: @store)+ I18n.with_locale(language.presence || I18n.default_locale, &block)+ ensure+ Mobility.store_based_fallbacks = previous_fallbacks+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/emails/file_system.rb b/spree/core/app/services/spree/emails/file_system.rbindex 503fe27d66..1ff51d83b1 100644--- a/spree/core/app/services/spree/emails/file_system.rb+++ b/spree/core/app/services/spree/emails/file_system.rb@@ -11,10 +11,10 @@ module Spree# @param name [String]# @return [String] the partial's sourcedef read_template_file(name)- path = @resolver.find_partial(name.to_s)- raise Liquid::FileSystemError, "No such email partial: #{name}" unless path+ partial = @resolver.find_partial(name.to_s)+ raise Liquid::FileSystemError, "No such email partial: #{name}" unless partial- File.read(path)+ partial.bodyrescue Spree::Emails::TemplateResolver::InvalidKey => eraise Liquid::FileSystemError, e.messageenddiff --git a/spree/core/app/services/spree/emails/renderer.rb b/spree/core/app/services/spree/emails/renderer.rbindex 428263ce44..504216b1d9 100644--- a/spree/core/app/services/spree/emails/renderer.rb+++ b/spree/core/app/services/spree/emails/renderer.rb@@ -32,17 +32,20 @@ module Spree# @param resolver [Spree::Emails::TemplateResolver]# @param store [Spree::Store]# @param currency [String, nil] what `money` formats in, defaults to the store's- def initialize(resolver:, store:, currency: nil)+ # @param strict [Boolean] whether an unknown variable raises; defaults to+ # true in development and test, false in production+ def initialize(resolver:, store:, currency: nil, strict: Rails.env.local?)@resolver = resolver@store = store@currency = currency.presence || store.default_currency+ @strict = strictend# @param template [Spree::Emails::Template] a Liquid template# @param assigns [Hash] the template's variables# @return [Spree::Emails::RenderedEmail]def render(template, assigns = {})- assigns = prepare(assigns)+ assigns = variables(assigns)subject = subject_for(template, assigns)body = render_liquid(template.body, assigns)html = render_layout(body, assigns.merge('subject' => subject))@@ -59,7 +62,16 @@ module Spreedef wrap(html, subject: nil)body = %(<mj-section><mj-column><mj-text align="left">#{html}</mj-text></mj-column></mj-section>)- render_layout(body, prepare('subject' => subject.to_s))+ render_layout(body, variables('subject' => subject.to_s))+ end++ # Everything a template receives: the given variables plus `store` and+ # `locale`, with string keys.+ #+ # @param assigns [Hash]+ # @return [Hash]+ def variables(assigns = {})+ base_assigns.merge(assigns.deep_stringify_keys)endprivate@@ -70,9 +82,6 @@ module SpreeMRML.to_html(render_liquid(layout.body, assigns.merge('content_for_layout' => body.html_safe)))end- def prepare(assigns)- base_assigns.merge(assigns.deep_stringify_keys)- end# The subject is plain text for a mail header, so it is not HTML-escaped.def subject_for(template, assigns)@@ -95,10 +104,10 @@ module Spreeresource_limits: Liquid::ResourceLimits.new(RESOURCE_LIMITS),rethrow_errors: true)- context.strict_variables = strict?+ context.strict_variables = @strictcontext.strict_filters = true- Liquid::Template.parse(source, environment: self.class.environment).render!(context)+ Liquid::Template.parse(source, environment: self.class.environment, line_numbers: true).render!(context)enddef base_assigns@@ -107,12 +116,6 @@ module Spree'locale' => I18n.locale.to_s}end-- # An unknown variable raises in development and test, so a typo fails- # a spec rather than rendering blank; production renders it empty.- def strict?- Rails.env.local?- endendendenddiff --git a/spree/core/app/services/spree/emails/template.rb b/spree/core/app/services/spree/emails/template.rbindex 010b5c97ee..070dd4ba5a 100644--- a/spree/core/app/services/spree/emails/template.rb+++ b/spree/core/app/services/spree/emails/template.rb@@ -1,26 +1,37 @@module Spreemodule Emails- # One Liquid email template on disk, with optional front matter.+ # One Liquid email template: a file on disk, with optional front matter+ # holding its subject, or a store's saved version with the subject in its+ # own field.class TemplateFRONT_MATTER = /\A---\s*\n(.*?)\n---\s*(?:\n|\z)/mattr_reader :key, :path# @param key [String] the template key, e.g. "spree/order_mailer/confirm_email"- # @param path [String] the file on disk- def initialize(key:, path:)+ # @param path [String, nil] the file on disk+ # @param subject [String, nil] the subject, for a template not read from a file+ # @param body [String, nil] the body, for a template not read from a file+ def initialize(key:, path: nil, subject: nil, body: nil)@key = key@path = path+ @subject = subject+ @body = bodyend- # @return [String, nil] the subject line as Liquid, read from the front matter+ # @return [Boolean] whether this is a store's saved template or a draft, rather than a file+ def stored?+ path.nil?+ end++ # @return [String, nil] the subject line as Liquiddef subject- front_matter['subject']+ stored? ? @subject : front_matter['subject']end# @return [String] the template without its front matterdef body- source.sub(FRONT_MATTER, '')+ stored? ? @body.to_s : source.sub(FRONT_MATTER, '')endprivatediff --git a/spree/core/app/services/spree/emails/template_data.rb b/spree/core/app/services/spree/emails/template_data.rbnew file mode 100644index 0000000000..0dd8fe472e--- /dev/null+++ b/spree/core/app/services/spree/emails/template_data.rb@@ -0,0 +1,23 @@+module Spree+ module Emails+ # Turns a record into the JSON an email template reads: the serializer's+ # output, the same data a renderer outside Ruby would receive. Shared by+ # mailers and by the sample data the template editor previews with.+ # Download links and other bearer tokens stay out of it.+ module TemplateData+ # @param object [Object, nil] the record+ # @param serializer [Class] an email serializer+ # @param store [Spree::Store]+ # @param currency [String, nil] defaults to the store's+ # @param params [Hash] serializer params over the defaults+ # @return [Hash, nil]+ def self.call(object, serializer, store:, currency: nil, **params)+ return if object.nil?++ params = { store: store, currency: currency || store.default_currency, locale: I18n.locale.to_s,+ storefront_url: store.storefront_url.to_s.chomp('/'), hide_credentials: true }.merge(params)+ JSON.parse(serializer.new(object, params: params).serialize)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/emails/template_resolver.rb b/spree/core/app/services/spree/emails/template_resolver.rbindex 0a15ecf010..09f324e3ff 100644--- a/spree/core/app/services/spree/emails/template_resolver.rb+++ b/spree/core/app/services/spree/emails/template_resolver.rb@@ -1,44 +1,83 @@module Spreemodule Emails- # Finds the Liquid template behind an email key, across the app's view- # paths: the host app's own file first, then the first one a gem ships.- # A later database step slots in front of this without changing any mailer.+ # Finds the Liquid template behind an email key.+ #+ # With a store, an editable template (see Spree.editable_email_templates)+ # is looked up in the store first: its published version in the email's+ # language, then its version for every language. Otherwise, and for every+ # other template, the app's own file wins over the one a gem ships.+ # `drafts` puts unsaved templates in front of everything, for previews and+ # for checking a draft before it is published.class TemplateResolverKEY_FORMAT = %r{\A[a-z0-9_]+(?:/[a-z0-9_]+)*\z}class InvalidKey < ArgumentError; end# @param view_paths [Array<String, Pathname>] directories to search, highest precedence first- def initialize(view_paths)+ # @param store [Spree::Store, nil] the store whose published templates apply+ # @param locale [String, Symbol, nil] the email's language+ # @param drafts [Hash{String => Spree::Emails::Template}] unsaved templates by key+ def initialize(view_paths, store: nil, locale: nil, drafts: {})@view_paths = view_paths.map(&:to_s).uniq+ @store = store+ @locale = locale.to_s+ @drafts = drafts+ @stored = {}end# @param key [String] e.g. "spree/order_mailer/confirm_email"# @return [Spree::Emails::Template, nil]def find(key)+ validate!(key)+ @drafts[key] || stored(key) || find_file(key, '.liquid')+ end++ # The default: what answers for the key without the store's templates or drafts.+ #+ # @param key [String]+ # @return [Spree::Emails::Template, nil]+ def find_default(key)+ validate!(key)find_file(key, '.liquid')end+ # A hand-written plain-text part. A store's saved template has none, so+ # its text is always generated from its HTML.+ ## @param key [String]- # @return [Spree::Emails::Template, nil] the hand-written plain-text part, when there is one+ # @return [Spree::Emails::Template, nil]def find_text(key)+ validate!(key)+ return if @drafts[key] || stored(key)+find_file(key, '.text.liquid')end# @param name [String] a partial name, e.g. "spree/shared/line_item"- # @return [String, nil] the partial's path, "spree/shared/_line_item.liquid"+ # @return [Spree::Emails::Template, nil] the store's version, or "spree/shared/_line_item.liquid"def find_partial(name)- *folders, file = name.to_s.split('/')- find_file([*folders, "_#{file}"].join('/'), '.liquid')&.path+ validate!(name)+ override = @drafts[name] || stored(name)+ return override if override++ *folders, file = name.split('/')+ find_file([*folders, "_#{file}"].join('/'), '.liquid')endprivateattr_reader :view_paths- def find_file(key, extension)- validate!(key)+ def stored(key)+ return unless @store && Spree.editable_email_templates.include?(key)+ return @stored[key] if @stored.key?(key)+ record = @store.email_templates.published.where(key: key, locale: [@locale, Spree::EmailTemplate::ANY_LOCALE]).+ min_by { |template| template.locale == Spree::EmailTemplate::ANY_LOCALE ? 1 : 0 }+ @stored[key] = record && Template.new(key: key, subject: record.subject, body: record.body)+ end++ def find_file(key, extension)view_paths.each do |view_path|path = File.join(view_path, "#{key}#{extension}")return Template.new(key: key, path: path) if File.file?(path)diff --git a/spree/core/app/workflows/spree/email_templates/publish.rb b/spree/core/app/workflows/spree/email_templates/publish.rbnew file mode 100644index 0000000000..cc51aad169--- /dev/null+++ b/spree/core/app/workflows/spree/email_templates/publish.rb@@ -0,0 +1,60 @@+module Spree+ module EmailTemplates+ # Makes a draft live. The draft is first rendered the way customers would+ # receive it (see Spree::EmailTemplates::Check); a draft that does not+ # render is refused with what is wrong and where, so an email already+ # being sent can never break. Publishing records a revision and clears+ # the draft.+ class Publish < Spree::Workflow+ def perform(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, actor: nil)+ super+ step :ensure_draft+ step :check++ ApplicationRecord.transaction do+ step :publish+ step :record_revision+ step :clear_draft+ end++ template.publish_event('email_template.published')+ success(template)+ end++ private++ def draft+ @draft ||= store.email_template_drafts.find_by(key: key, locale: locale.presence || Spree::EmailTemplate::ANY_LOCALE)+ end++ def template+ @template ||= store.email_templates.find_or_initialize_by(key: draft.key, locale: draft.locale)+ end++ def ensure_draft+ failure(nil, :no_draft) unless draft+ end++ def check+ problems = Spree::EmailTemplates::Check.new(store: store, draft: draft).call+ failure(problems, :invalid_template) if problems.any?+ end++ def publish+ template.assign_attributes(+ subject: draft.subject, body: draft.body, base_subject: draft.base_subject, base_body: draft.base_body,+ status: :published, published_at: Time.current, published_by: actor, reverted_at: nil, reverted_by: nil+ )+ template.save!+ end++ def record_revision+ template.revisions.create!(subject: template.subject, body: template.body, published_by: actor)+ end++ def clear_draft+ draft.destroy!+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/email_templates/restore_revision.rb b/spree/core/app/workflows/spree/email_templates/restore_revision.rbnew file mode 100644index 0000000000..74f5bfa915--- /dev/null+++ b/spree/core/app/workflows/spree/email_templates/restore_revision.rb@@ -0,0 +1,17 @@+module Spree+ module EmailTemplates+ # Copies a published revision into the draft, to be checked and+ # published like any other change.+ class RestoreRevision < Spree::Workflow+ def perform(revision:, actor: nil, lock_version: nil)+ super+ template = revision.email_template++ Spree.email_template_save_draft_workflow.call(+ store: template.store, key: template.key, locale: template.locale, actor: actor,+ attributes: { subject: revision.subject, body: revision.body, lock_version: lock_version }+ )+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/email_templates/revert.rb b/spree/core/app/workflows/spree/email_templates/revert.rbnew file mode 100644index 0000000000..d2fcd91307--- /dev/null+++ b/spree/core/app/workflows/spree/email_templates/revert.rb@@ -0,0 +1,23 @@+module Spree+ module EmailTemplates+ # Goes back to Spree's default for one template and language: the+ # published version is marked reverted, so the file answers again, and+ # any draft is discarded. The row and its revisions stay, so the history+ # can still be restored.+ class Revert < Spree::Workflow+ def perform(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, actor: nil)+ super+ locale_value = locale.presence || Spree::EmailTemplate::ANY_LOCALE+ template = store.email_templates.find_by(key: key, locale: locale_value)++ ApplicationRecord.transaction do+ store.email_template_drafts.where(key: key, locale: locale_value).destroy_all+ template&.update!(status: :reverted, reverted_at: Time.current, reverted_by: actor) if template&.published?+ end++ template&.publish_event('email_template.reverted') if template&.reverted?+ success(template)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/email_templates/save_draft.rb b/spree/core/app/workflows/spree/email_templates/save_draft.rbnew file mode 100644index 0000000000..66eee092c9--- /dev/null+++ b/spree/core/app/workflows/spree/email_templates/save_draft.rb@@ -0,0 +1,54 @@+module Spree+ module EmailTemplates+ # Saves a draft of an editable email template, in any state: it is work+ # in progress and customers keep receiving the published version. The+ # first save starts from what is published, else Spree's default, and+ # remembers that default so an upgrade changing it can be spotted.+ #+ # A save carrying an older `lock_version` than the draft has is refused,+ # so two admins editing at once cannot overwrite each other.+ class SaveDraft < Spree::Workflow+ def perform(store:, key:, attributes:, locale: Spree::EmailTemplate::ANY_LOCALE, actor: nil)+ super+ step :ensure_editable+ step :ensure_current+ step :save++ success(draft)+ end++ private++ def draft+ @draft ||= store.email_template_drafts.find_or_initialize_by(key: key, locale: locale.presence || Spree::EmailTemplate::ANY_LOCALE)+ end++ def ensure_editable+ failure(nil, :not_editable) unless Spree.editable_email_templates.include?(key)+ end++ def ensure_current+ expected = attributes[:lock_version]+ failure(nil, :stale) if draft.persisted? && !expected.nil? && expected.to_i != draft.lock_version+ end++ def save+ start_from_current if draft.new_record?+ draft.subject = attributes[:subject] if attributes.key?(:subject)+ draft.body = attributes[:body] if attributes.key?(:body)+ draft.updated_by = actor+ failure(draft) unless draft.save+ end++ def start_from_current+ published = store.email_templates.published.find_by(key: key, locale: draft.locale)+ default = Spree::Emails::TemplateResolver.new(Spree::BaseMailer.view_paths.paths.map(&:path)).find_default(key)++ draft.subject = published&.subject || default&.subject+ draft.body = published&.body || default&.body+ draft.base_subject = published ? published.base_subject : default&.subject+ draft.base_body = published ? published.base_body : default&.body+ end+ end+ end+enddiff --git a/spree/core/db/migrate/20261001000001_create_spree_email_templates.rb b/spree/core/db/migrate/20261001000001_create_spree_email_templates.rbnew file mode 100644index 0000000000..24b7c03d12--- /dev/null+++ b/spree/core/db/migrate/20261001000001_create_spree_email_templates.rb@@ -0,0 +1,52 @@+class CreateSpreeEmailTemplates < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_email_templates do |t|+ t.references :store, null: false, index: false+ t.string :key, null: false+ t.string :locale, null: false+ t.string :status, null: false+ t.text :subject+ t.text :body, null: false+ t.text :base_subject+ t.text :base_body, null: false+ t.datetime :published_at, null: false+ t.references :published_by, polymorphic: true, index: true+ t.datetime :reverted_at+ t.references :reverted_by, polymorphic: true, index: true++ t.timestamps+ end++ add_index :spree_email_templates, [:store_id, :key, :locale], unique: true,+ name: 'index_spree_email_templates_on_store_key_locale'+ add_index :spree_email_templates, :status++ create_table :spree_email_template_drafts do |t|+ t.references :store, null: false, index: false+ t.string :key, null: false+ t.string :locale, null: false+ t.text :subject+ t.text :body, null: false+ t.text :base_subject+ t.text :base_body, null: false+ t.integer :lock_version, null: false, default: 0+ t.references :updated_by, polymorphic: true, index: true++ t.timestamps+ end++ add_index :spree_email_template_drafts, [:store_id, :key, :locale], unique: true,+ name: 'index_spree_email_template_drafts_on_store_key_locale'++ create_table :spree_email_template_revisions do |t|+ t.references :email_template, null: false, index: false+ t.text :subject+ t.text :body, null: false+ t.references :published_by, polymorphic: true, index: true+ t.datetime :created_at, null: false+ end++ add_index :spree_email_template_revisions, [:email_template_id, :created_at],+ name: 'index_spree_email_template_revisions_on_template_and_created'+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 70cc26c4f2..83233dc991 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -452,6 +452,13 @@ module Spree# Spree.number_generators[:order] = 'MyApp::BranchOrderNumbers'singleton_class.delegate :number_generators, to: :spree_config+ # The email templates merchants may edit in the dashboard.+ #+ # @return [Spree::Emails::EditableTemplates]+ def self.editable_email_templates+ @editable_email_templates ||= Spree::Emails::EditableTemplates.new+ end+# Event subscribers that handle lifecycle and custom events# @example Adding a custom subscriber# Spree.subscribers << MyApp::OrderNotificationSubscriber@@ -626,6 +633,7 @@ require 'spree/store_scope_guard'require 'spree/checkout/step'require 'spree/checkout/requirement'require 'spree/checkout/registry'+require 'spree/emails/editable_templates'require 'spree/checkout/default_requirements'require 'spree/checkout/requirements'diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex b692267620..9a7bd2dbe2 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -249,6 +249,10 @@ module Spreeseller_payout_complete_workflow: 'Spree::SellerPayouts::Complete',payments_handle_webhook_workflow: 'Spree::Payments::HandleWebhook',payment_session_complete_workflow: 'Spree::PaymentSessions::Complete',+ email_template_save_draft_workflow: 'Spree::EmailTemplates::SaveDraft',+ email_template_publish_workflow: 'Spree::EmailTemplates::Publish',+ email_template_revert_workflow: 'Spree::EmailTemplates::Revert',+ email_template_restore_revision_workflow: 'Spree::EmailTemplates::RestoreRevision',# finderscurrent_store_finder: 'Spree::Stores::FindDefault',diff --git a/spree/core/lib/spree/core/permissions/default_catalog.rb b/spree/core/lib/spree/core/permissions/default_catalog.rbindex bb93260ab0..e146821f12 100644--- a/spree/core/lib/spree/core/permissions/default_catalog.rb+++ b/spree/core/lib/spree/core/permissions/default_catalog.rb@@ -194,6 +194,11 @@ module Spreecatalog.register_scope(:webhooks, group: :settings, resources: -> {[Spree::WebhookEndpoint, Spree::WebhookDelivery]})+ # Separate from settings: a template writes what every customer receives,+ # links included, so managing store settings does not grant it.+ catalog.register_scope(:email_templates, group: :settings, resources: -> {+ [Spree::EmailTemplate, Spree::EmailTemplateDraft, Spree::EmailTemplateRevision]+ })catalog.register_scope(:integrations, group: :settings, resources: -> { [Spree::Integration] })catalog.register_scope(:api_keys, group: :access, resources: -> { [Spree::ApiKey] })diff --git a/spree/core/lib/spree/emails/editable_templates.rb b/spree/core/lib/spree/emails/editable_templates.rbnew file mode 100644index 0000000000..304d6ed7fd--- /dev/null+++ b/spree/core/lib/spree/emails/editable_templates.rb@@ -0,0 +1,82 @@+module Spree+ module Emails+ # The email templates merchants may edit in the dashboard: the emails+ # customers receive, plus the layout and shared partials those emails are+ # built from. Staff, store-owner and seller emails are never registered, so+ # they always render from files. `spree_emails` registers its own; an+ # extension adding a customer email registers it the same way.+ #+ # @example+ # Spree.editable_email_templates.register(+ # 'spree/loyalty_mailer/points_earned_email',+ # kind: :email, sample: 'MyApp::EmailSamples::PointsEarned'+ # )+ class EditableTemplates+ include Enumerable++ KINDS = %i[email layout partial].freeze++ # One editable template.+ class Definition+ attr_reader :key, :kind, :sample++ # @param key [String] the template's view path, e.g. "spree/order_mailer/confirm_email"+ # @param kind [Symbol] :email, :layout or :partial+ # @param sample [String, nil] class building sample variables for an email (see Spree::Emails::Samples::Base)+ def initialize(key:, kind:, sample: nil)+ raise ArgumentError, "Unknown email template kind: #{kind.inspect}" unless KINDS.include?(kind)++ @key = key+ @kind = kind+ @sample = sample+ end++ def email?+ kind == :email+ end++ # @return [Class, nil]+ def sample_class+ sample&.constantize+ end+ end++ def initialize+ @definitions = {}+ end++ # @param key [String]+ # @param kind [Symbol]+ # @param sample [String, nil]+ # @return [Spree::Emails::EditableTemplates::Definition]+ def register(key, kind: :email, sample: nil)+ @definitions[key] = Definition.new(key: key, kind: kind, sample: sample)+ end++ # @param key [String]+ def delete(key)+ @definitions.delete(key)+ end++ # @param key [String]+ # @return [Spree::Emails::EditableTemplates::Definition, nil]+ def [](key)+ @definitions[key]+ end++ # @param key [String]+ def include?(key)+ @definitions.key?(key)+ end++ def each(&block)+ @definitions.each_value(&block)+ end++ # @return [Array<Spree::Emails::EditableTemplates::Definition>] the editable emails, without layout and partials+ def emails+ select(&:email?)+ end+ end+ end+enddiff --git a/spree/core/lib/spree/testing_support/editable_email_templates.rb b/spree/core/lib/spree/testing_support/editable_email_templates.rbnew file mode 100644index 0000000000..666e4bc385--- /dev/null+++ b/spree/core/lib/spree/testing_support/editable_email_templates.rb@@ -0,0 +1,48 @@+# Registers core's staff password reset as an editable email for the length+# of an example, with a fixed sample, so specs in any engine can exercise the+# template editor without spree_emails' customer emails. Restores whatever was+# registered under the key before.+#+# RSpec.describe '...' do+# include_context 'with an editable email template'+# end+module Spree+ module TestingSupport+ class EmailTemplateSample+ def self.record_type+ nil+ end++ def initialize(store:, record_id: nil)+ @store = store+ end++ def currency+ @store.default_currency+ end++ def variables+ {+ user: { 'first_name' => 'Ann', 'email' => '[email protected]' },+ reset_url: "#{@store.storefront_url}/reset-password?token=preview"+ }+ end+ end+ end+end++RSpec.shared_context 'with an editable email template' do+ let(:editable_key) { 'spree/admin_user_mailer/password_reset_email' }++ around do |example|+ registry = Spree.editable_email_templates+ previous = registry[editable_key]+ previous_layout = registry['layouts/spree/base_mailer']+ registry.register(editable_key, kind: :email, sample: 'Spree::TestingSupport::EmailTemplateSample')+ registry.register('layouts/spree/base_mailer', kind: :layout)+ example.run+ ensure+ previous ? registry.register(previous.key, kind: previous.kind, sample: previous.sample) : registry.delete(editable_key)+ previous_layout ? registry.register(previous_layout.key, kind: :layout) : registry.delete('layouts/spree/base_mailer')+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/email_template_factory.rb b/spree/core/lib/spree/testing_support/factories/email_template_factory.rbnew file mode 100644index 0000000000..bb36733e31--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/email_template_factory.rb@@ -0,0 +1,28 @@+FactoryBot.define do+ factory :email_template, class: Spree::EmailTemplate do+ store { Spree::Store.default || create(:store) }+ key { 'spree/admin_user_mailer/password_reset_email' }+ locale { 'any' }+ subject { 'Reset {{ store.name }}' }+ body { '<mj-section><mj-column><mj-text>Hello</mj-text></mj-column></mj-section>' }+ base_subject { 'Reset {{ store.name }}' }+ base_body { '<mj-section><mj-column><mj-text>Default</mj-text></mj-column></mj-section>' }+ published_at { Time.current }+ end++ factory :email_template_draft, class: Spree::EmailTemplateDraft do+ store { Spree::Store.default || create(:store) }+ key { 'spree/admin_user_mailer/password_reset_email' }+ locale { 'any' }+ subject { 'Reset {{ store.name }}' }+ body { '<mj-section><mj-column><mj-text>Draft</mj-text></mj-column></mj-section>' }+ base_subject { 'Reset {{ store.name }}' }+ base_body { '<mj-section><mj-column><mj-text>Default</mj-text></mj-column></mj-section>' }+ end++ factory :email_template_revision, class: Spree::EmailTemplateRevision do+ email_template+ subject { 'Reset {{ store.name }}' }+ body { '<mj-section><mj-column><mj-text>Hello</mj-text></mj-column></mj-section>' }+ end+enddiff --git a/spree/core/spec/models/spree/email_template_spec.rb b/spree/core/spec/models/spree/email_template_spec.rbnew file mode 100644index 0000000000..073c63f08b--- /dev/null+++ b/spree/core/spec/models/spree/email_template_spec.rb@@ -0,0 +1,34 @@+require 'spec_helper'++describe Spree::EmailTemplate, type: :model do+ include_context 'with an editable email template'++ let(:store) { @default_store }++ it 'only accepts templates merchants may edit' do+ template = build(:email_template, store: store, key: 'spree/webhook_mailer/endpoint_disabled')++ expect(template).not_to be_valid+ expect(template.errors[:key]).to be_present+ end++ it 'stores the version for every language as "any", never empty' do+ expect(create(:email_template, store: store, locale: '').locale).to eq('any')+ end++ it 'keeps one version per template and language' do+ create(:email_template, store: store)++ expect(build(:email_template, store: store)).not_to be_valid+ expect(build(:email_template, store: store, locale: 'de')).to be_valid+ end++ describe '#default_changed?' do+ let(:template) { build(:email_template, base_subject: 'S', base_body: 'B') }++ it 'is true once the default it started from changes' do+ expect(template.default_changed?(Spree::Emails::Template.new(key: 'k', subject: 'S', body: 'B'))).to be(false)+ expect(template.default_changed?(Spree::Emails::Template.new(key: 'k', subject: 'S', body: 'New'))).to be(true)+ end+ end+enddiff --git a/spree/core/spec/services/spree/email_templates/preview_spec.rb b/spree/core/spec/services/spree/email_templates/preview_spec.rbnew file mode 100644index 0000000000..50054ab789--- /dev/null+++ b/spree/core/spec/services/spree/email_templates/preview_spec.rb@@ -0,0 +1,26 @@+require 'spec_helper'++describe Spree::EmailTemplates::Preview do+ include_context 'with an editable email template'++ let(:store) { @default_store }++ it 'renders an unsaved draft with sample data, and keeps the variables it used' do+ preview = described_class.new(store: store, key: editable_key, subject: 'Hi {{ user.first_name }}',+ body: '<mj-section><mj-column><mj-text>Draft for {{ user.email }}</mj-text></mj-column></mj-section>')++ email = preview.call++ expect(email.subject).to eq('Hi Ann')+ expect(email.html).to include('Draft for [email protected]', store.name)+ expect(preview.variables.keys).to include('user', 'reset_url', 'store', 'locale')+ end++ it 'shows the layout inside an email that uses it' do+ layout = File.read(Spree::Core::Engine.root.join('app/views/layouts/spree/base_mailer.liquid')).sub('{{ content_for_layout }}', 'LAYOUT DRAFT {{ content_for_layout }}')++ email = described_class.new(store: store, key: 'layouts/spree/base_mailer', body: layout).call++ expect(email.html).to include('LAYOUT DRAFT')+ end+enddiff --git a/spree/core/spec/services/spree/emails/template_resolver_spec.rb b/spree/core/spec/services/spree/emails/template_resolver_spec.rbindex b651828660..ac3ac16b59 100644--- a/spree/core/spec/services/spree/emails/template_resolver_spec.rb+++ b/spree/core/spec/services/spree/emails/template_resolver_spec.rb@@ -36,7 +36,47 @@ describe Spree::Emails::TemplateResolver doit 'finds a partial named without a folder' dopartial = write(gem_views, '_greeting.liquid')- expect(resolver.find_partial('greeting')).to eq(partial)+ expect(resolver.find_partial('greeting').path).to eq(partial)+ end++ describe 'with a store' do+ include_context 'with an editable email template'++ let(:store) { @default_store }+ let(:views) { [Spree::Core::Engine.root.join('app/views')] }+ let(:german) { described_class.new(views, store: store, locale: 'de') }++ it "puts the store's published version in front of the file" do+ create(:email_template, store: store, key: editable_key, body: 'Stored')++ expect(german.find(editable_key).body).to eq('Stored')+ expect(german.find_default(editable_key).path).to end_with("#{editable_key}.liquid")+ end++ it "prefers the email's language over the version for every language" do+ create(:email_template, store: store, key: editable_key, body: 'Any')+ create(:email_template, store: store, key: editable_key, locale: 'de', body: 'German')++ expect(german.find(editable_key).body).to eq('German')+ expect(described_class.new(views, store: store, locale: 'fr').find(editable_key).body).to eq('Any')+ end++ it 'ignores a reverted version' do+ create(:email_template, store: store, key: editable_key, body: 'Stored', status: :reverted)++ expect(german.find(editable_key).path).to end_with("#{editable_key}.liquid")+ end++ it 'never reads the store for a template merchants may not edit' do+ expect(described_class.new(views, store: store).find('spree/webhook_mailer/endpoint_disabled').path).to be_present+ end++ it 'puts an unsaved draft in front of everything' do+ create(:email_template, store: store, key: editable_key, body: 'Stored')+ draft = Spree::Emails::Template.new(key: editable_key, subject: 'S', body: 'Draft')++ expect(described_class.new(views, store: store, drafts: { editable_key => draft }).find(editable_key).body).to eq('Draft')+ endendit 'refuses a key that could leave the view paths' dodiff --git a/spree/core/spec/spec_helper.rb b/spree/core/spec/spec_helper.rbindex c1bf9190c4..6497fd0364 100644--- a/spree/core/spec/spec_helper.rb+++ b/spree/core/spec/spec_helper.rb@@ -56,6 +56,7 @@ require 'spree/testing_support/i18n' if ENV['CHECK_TRANSLATIONS']require 'spree/testing_support/action_text'require 'spree/testing_support/emails'+require 'spree/testing_support/editable_email_templates'require 'spree/testing_support/factories'require 'spree/testing_support/jobs'require 'spree/testing_support/store'diff --git a/spree/core/spec/workflows/spree/email_templates/publish_spec.rb b/spree/core/spec/workflows/spree/email_templates/publish_spec.rbnew file mode 100644index 0000000000..9cc0534eab--- /dev/null+++ b/spree/core/spec/workflows/spree/email_templates/publish_spec.rb@@ -0,0 +1,54 @@+require 'spec_helper'++describe Spree::EmailTemplates::Publish do+ include_context 'with an editable email template'++ let(:store) { @default_store }+ let(:admin) { create(:admin_user) }+ let(:body) { '<mj-section><mj-column><mj-text>Hi {{ user.first_name }}</mj-text></mj-column></mj-section>' }++ before { create(:email_template_draft, store: store, key: editable_key, subject: 'Reset', body: body) }++ def publish+ described_class.new.call(store: store, key: editable_key, actor: admin)+ end++ it 'makes the draft live, records a revision and clears the draft' do+ template = publish.value++ expect(template).to be_published+ expect(template.body).to eq(body)+ expect(template.published_by).to eq(admin)+ expect(template.revisions.count).to eq(1)+ expect(store.email_template_drafts.count).to eq(0)+ end++ it 'refuses a draft that does not render, saying what is wrong and where' do+ store.email_template_drafts.first.update!(body: "<mj-section>\n<mj-column><mj-text>{{ user.nickname }}</mj-text></mj-column></mj-section>")++ result = publish++ expect(result).not_to be_success+ expect(result.error.value).to eq(:invalid_template)+ expect(result.value).to contain_exactly(hash_including(email: editable_key, line: 2, message: /nickname/))+ expect(store.email_templates.count).to eq(0)+ end++ it 'refuses when there is no draft' do+ store.email_template_drafts.destroy_all++ expect(publish.error.value).to eq(:no_draft)+ end++ it 'publishes again over a reverted version, keeping its history' do+ template = publish.value+ template.update!(status: :reverted)+ create(:email_template_draft, store: store, key: editable_key, body: body)++ republished = publish.value++ expect(republished.id).to eq(template.id)+ expect(republished).to be_published+ expect(republished.revisions.count).to eq(2)+ end+enddiff --git a/spree/core/spec/workflows/spree/email_templates/restore_revision_spec.rb b/spree/core/spec/workflows/spree/email_templates/restore_revision_spec.rbnew file mode 100644index 0000000000..1644f6dd01--- /dev/null+++ b/spree/core/spec/workflows/spree/email_templates/restore_revision_spec.rb@@ -0,0 +1,16 @@+require 'spec_helper'++describe Spree::EmailTemplates::RestoreRevision do+ include_context 'with an editable email template'++ let(:store) { @default_store }+ let(:template) { create(:email_template, store: store, key: editable_key) }+ let(:revision) { create(:email_template_revision, email_template: template, subject: 'Old subject', body: 'Old body') }++ it 'copies the revision into the draft, to publish like any change' do+ draft = described_class.new.call(revision: revision).value++ expect(draft).to have_attributes(key: editable_key, subject: 'Old subject', body: 'Old body')+ expect(template.reload.body).not_to eq('Old body')+ end+enddiff --git a/spree/core/spec/workflows/spree/email_templates/revert_spec.rb b/spree/core/spec/workflows/spree/email_templates/revert_spec.rbnew file mode 100644index 0000000000..fc337bc116--- /dev/null+++ b/spree/core/spec/workflows/spree/email_templates/revert_spec.rb@@ -0,0 +1,23 @@+require 'spec_helper'++describe Spree::EmailTemplates::Revert do+ include_context 'with an editable email template'++ let(:store) { @default_store }+ let(:admin) { create(:admin_user) }+ let!(:template) { create(:email_template, store: store, key: editable_key) }++ before do+ create(:email_template_revision, email_template: template)+ create(:email_template_draft, store: store, key: editable_key)+ end++ it 'marks the published version reverted, discards the draft and keeps the history' do+ described_class.new.call(store: store, key: editable_key, actor: admin)++ expect(template.reload).to be_reverted+ expect(template.reverted_by).to eq(admin)+ expect(template.revisions.count).to eq(1)+ expect(store.email_template_drafts.count).to eq(0)+ end+enddiff --git a/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb b/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rbnew file mode 100644index 0000000000..95243ebbd9--- /dev/null+++ b/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb@@ -0,0 +1,48 @@+require 'spec_helper'++describe Spree::EmailTemplates::SaveDraft do+ include_context 'with an editable email template'++ let(:store) { @default_store }+ let(:admin) { create(:admin_user) }++ def save(attributes, **options)+ described_class.new.call(store: store, key: editable_key, attributes: attributes, actor: admin, **options)+ end++ it "starts from Spree's default and remembers it" do+ draft = save({ body: '<mj-section></mj-section>' }).value++ default = File.read(Spree::Core::Engine.root.join("app/views/#{editable_key}.liquid"))+ expect(draft.body).to eq('<mj-section></mj-section>')+ expect(default).to include(draft.base_body.strip)+ expect(draft.subject).to include('password_reset_email.subject')+ expect(draft.updated_by).to eq(admin)+ end++ it 'starts from the published version when the store has one' do+ create(:email_template, store: store, key: editable_key, subject: 'Published', base_body: 'Old default')++ draft = save({ body: 'x' }).value++ expect(draft.subject).to eq('Published')+ expect(draft.base_body).to eq('Old default')+ end++ it 'refuses a save made from a stale copy' do+ draft = save({ body: 'first' }).value+ save({ body: 'second', lock_version: draft.lock_version })++ result = save({ body: 'stale', lock_version: draft.lock_version })++ expect(result).not_to be_success+ expect(result.error.value).to eq(:stale)+ expect(draft.reload.body).to eq('second')+ end++ it 'refuses a template merchants may not edit' do+ result = described_class.new.call(store: store, key: 'spree/webhook_mailer/endpoint_disabled', attributes: { body: 'x' })++ expect(result.error.value).to eq(:not_editable)+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/base.rb b/spree/emails/app/services/spree/emails/samples/base.rbnew file mode 100644index 0000000000..566b7775da--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/base.rb@@ -0,0 +1,60 @@+module Spree+ module Emails+ module Samples+ # Builds what an email's template receives, for previewing a template+ # and checking it before it is published: from the store's most recent+ # matching record, or one the merchant picks. Values that would carry a+ # token (reset, invitation, download links) are always placeholders.+ class Base+ # @return [String, nil] the kind of record the merchant can pick+ # ("order", "order_group", "fulfillment", "return"), or nil when the+ # email needs none+ def self.record_type+ nil+ end++ attr_reader :store, :record_id++ # @param store [Spree::Store]+ # @param record_id [String, nil] a prefixed id of the record to preview with+ def initialize(store:, record_id: nil)+ @store = store+ @record_id = record_id.presence+ end++ # @return [Hash] the template's variables, before `store` and `locale` are added+ def variables+ raise NotImplementedError+ end++ # @return [String] the currency the email's amounts are in+ def currency+ self.class.record_type ? record.currency : store.default_currency+ end++ protected++ def record+ @record ||= if record_id+ records.find_by_prefix_id!(record_id)+ else+ records.first || raise(Spree::EmailTemplates::NoSampleRecord, Spree.t('emails.samples.no_record', record: self.class.record_type.to_s.humanize.downcase))+ end+ end++ # Every lookup goes through the store, so another store's record never answers.+ def records+ raise NotImplementedError+ end++ def data(object, serializer)+ Spree::Emails::TemplateData.call(object, serializer, store: store, currency: currency)+ end++ def placeholder_url(path)+ "#{store.storefront_url.to_s.chomp('/')}/#{path}?token=preview"+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/company_invitation.rb b/spree/emails/app/services/spree/emails/samples/company_invitation.rbnew file mode 100644index 0000000000..462b67c7db--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/company_invitation.rb@@ -0,0 +1,15 @@+module Spree+ module Emails+ module Samples+ class CompanyInvitation < Base+ def variables+ {+ company: data(store.companies.order(created_at: :desc).first || Spree::Company.new(name: 'Acme Corporation', store: store),+ Spree.api.company_serializer),+ accept_url: placeholder_url('account/company-invitation')+ }+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/data_export.rb b/spree/emails/app/services/spree/emails/samples/data_export.rbnew file mode 100644index 0000000000..b898ac6599--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/data_export.rb@@ -0,0 +1,11 @@+module Spree+ module Emails+ module Samples+ class DataExport < Base+ def variables+ { download_url: placeholder_url('account/data-export'), expires_at: 7.days.from_now.iso8601 }+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/downloads.rb b/spree/emails/app/services/spree/emails/samples/downloads.rbnew file mode 100644index 0000000000..2849e36e7c--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/downloads.rb@@ -0,0 +1,28 @@+module Spree+ module Emails+ module Samples+ # The files-ready email. Lists the order's own downloads when it has any,+ # always with placeholder links.+ class Downloads < Order+ def variables+ {+ order: data(record, Spree::Emails::OrderSerializer),+ downloads: downloads,+ resend: false+ }+ end++ private++ def downloads+ links = record.digital_links.includes(digital_asset: { attachment_attachment: :blob }).to_a+ return [{ filename: 'guide.pdf', url: placeholder_url('downloads'), expires_at: nil }] if links.empty?++ links.map do |link|+ { filename: link.filename.to_s, url: placeholder_url('downloads'), expires_at: link.expires_at&.iso8601 }+ end+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/fulfillment.rb b/spree/emails/app/services/spree/emails/samples/fulfillment.rbnew file mode 100644index 0000000000..140ea30102--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/fulfillment.rb@@ -0,0 +1,29 @@+module Spree+ module Emails+ module Samples+ class Fulfillment < Base+ def self.record_type+ 'fulfillment'+ end++ def variables+ {+ fulfillment: data(record, Spree::Emails::FulfillmentSerializer),+ order: data(record.order, Spree::Emails::OrderSerializer),+ resend: false+ }+ end++ def currency+ record.order.currency+ end++ protected++ def records+ store.fulfillments.order(created_at: :desc)+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/newsletter_confirmation.rb b/spree/emails/app/services/spree/emails/samples/newsletter_confirmation.rbnew file mode 100644index 0000000000..ac9d647afe--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/newsletter_confirmation.rb@@ -0,0 +1,11 @@+module Spree+ module Emails+ module Samples+ class NewsletterConfirmation < Base+ def variables+ { confirmation_url: placeholder_url('newsletter/confirm') }+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/order.rb b/spree/emails/app/services/spree/emails/samples/order.rbnew file mode 100644index 0000000000..c471ad0fc9--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/order.rb@@ -0,0 +1,22 @@+module Spree+ module Emails+ module Samples+ # Order confirmation and cancellation.+ class Order < Base+ def self.record_type+ 'order'+ end++ def variables+ { order: data(record, Spree::Emails::OrderSerializer), resend: false }+ end++ protected++ def records+ store.orders.complete.order(completed_at: :desc)+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/order_group.rb b/spree/emails/app/services/spree/emails/samples/order_group.rbnew file mode 100644index 0000000000..84647edd79--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/order_group.rb@@ -0,0 +1,22 @@+module Spree+ module Emails+ module Samples+ # The confirmation of a purchase that divided into several orders.+ class OrderGroup < Base+ def self.record_type+ 'order_group'+ end++ def variables+ { order_group: data(record, Spree::Emails::OrderGroupSerializer), resend: false }+ end++ protected++ def records+ store.order_groups.order(created_at: :desc)+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/password_reset.rb b/spree/emails/app/services/spree/emails/samples/password_reset.rbnew file mode 100644index 0000000000..395c64beef--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/password_reset.rb@@ -0,0 +1,15 @@+module Spree+ module Emails+ module Samples+ class PasswordReset < Base+ def variables+ {+ customer: data(Spree.customer_class.new(first_name: 'Jane', last_name: 'Doe', email: '[email protected]'),+ Spree.api.customer_serializer),+ reset_url: placeholder_url('account/reset-password')+ }+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/payment_link.rb b/spree/emails/app/services/spree/emails/samples/payment_link.rbnew file mode 100644index 0000000000..559a7a23f8--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/payment_link.rb@@ -0,0 +1,17 @@+module Spree+ module Emails+ module Samples+ class PaymentLink < Order+ def variables+ { order: data(record, Spree::Emails::OrderSerializer), payment_url: placeholder_url('checkout/payment') }+ end++ protected++ def records+ store.orders.order(created_at: :desc)+ end+ end+ end+ end+enddiff --git a/spree/emails/app/services/spree/emails/samples/return.rb b/spree/emails/app/services/spree/emails/samples/return.rbnew file mode 100644index 0000000000..bd71d7a8ec--- /dev/null+++ b/spree/emails/app/services/spree/emails/samples/return.rb@@ -0,0 +1,29 @@+module Spree+ module Emails+ module Samples+ class Return < Base+ def self.record_type+ 'return'+ end++ def variables+ {+ return: data(record, Spree::Emails::ReturnSerializer),+ order: data(record.order, Spree::Emails::OrderSerializer),+ resend: false+ }+ end++ def currency+ record.order.currency+ end++ protected++ def records+ store.returns.order(created_at: :desc)+ end+ end+ end+ end+enddiff --git a/spree/emails/config/locales/en.yml b/spree/emails/config/locales/en.ymlindex 4b44aedf75..0addbf688c 100644--- a/spree/emails/config/locales/en.yml+++ b/spree/emails/config/locales/en.yml@@ -31,6 +31,9 @@ en:dear_customer: Dear %{name},instructions: The files from your order %{number} are ready to download.subject: Your files are ready+ emails:+ samples:+ no_record: There is no %{record} in this store to preview this email with yet.fulfillment_mailer:fulfilled_email:dear_customer: Dear %{name},diff --git a/spree/emails/lib/spree/emails/engine.rb b/spree/emails/lib/spree/emails/engine.rbindex db9693bfc7..3f759a5b23 100644--- a/spree/emails/lib/spree/emails/engine.rb+++ b/spree/emails/lib/spree/emails/engine.rb@@ -14,6 +14,30 @@ module Spreeendend+ # The customer emails merchants may edit in the dashboard, with the layout+ # and shared partials they are built from. Staff, store-owner and seller+ # emails are deliberately not registered.+ initializer 'spree_emails.editable_templates' do+ {+ 'spree/order_mailer/confirm_email' => 'Spree::Emails::Samples::Order',+ 'spree/order_mailer/cancel_email' => 'Spree::Emails::Samples::Order',+ 'spree/order_mailer/payment_link_email' => 'Spree::Emails::Samples::PaymentLink',+ 'spree/order_group_mailer/confirm_email' => 'Spree::Emails::Samples::OrderGroup',+ 'spree/fulfillment_mailer/fulfilled_email' => 'Spree::Emails::Samples::Fulfillment',+ 'spree/return_mailer/refunded_email' => 'Spree::Emails::Samples::Return',+ 'spree/digital_asset_mailer/files_ready_email' => 'Spree::Emails::Samples::Downloads',+ 'spree/customer_mailer/password_reset_email' => 'Spree::Emails::Samples::PasswordReset',+ 'spree/customer_mailer/data_export_email' => 'Spree::Emails::Samples::DataExport',+ 'spree/newsletter_mailer/email_confirmation' => 'Spree::Emails::Samples::NewsletterConfirmation',+ 'spree/company_mailer/invitation_email' => 'Spree::Emails::Samples::CompanyInvitation'+ }.each { |key, sample| Spree.editable_email_templates.register(key, kind: :email, sample: sample) }++ Spree.editable_email_templates.register('layouts/spree/base_mailer', kind: :layout)+ %w[line_item order_summary purchase_totals fulfillment_group summary_row].each do |partial|+ Spree.editable_email_templates.register("spree/shared/#{partial}", kind: :partial)+ end+ end+# Add email event subscribersconfig.after_initialize doSpree.subscribers.concat [diff --git a/spree/emails/spec/services/spree/emails/samples_spec.rb b/spree/emails/spec/services/spree/emails/samples_spec.rbnew file mode 100644index 0000000000..e0750555e3--- /dev/null+++ b/spree/emails/spec/services/spree/emails/samples_spec.rb@@ -0,0 +1,50 @@+require 'spec_helper'++# Every customer email merchants may edit has to preview, and pass the+# publish check, with the sample data its builder makes.+describe 'editable email samples' do+ let(:store) { @default_store }++ before do+ order = create(:shipped_order, store: store)+ create(:received_return, store: store, order: order)+ create(:order_group, :with_parcels, store: store, sellers_count: 2)+ end++ it 'registers every customer email, the layout and the shared partials' do+ expect(Spree.editable_email_templates.emails.size).to eq(11)+ expect(Spree.editable_email_templates['layouts/spree/base_mailer']).to be_present+ expect(Spree.editable_email_templates['spree/order_mailer/store_owner_notification_email']).to be_nil+ end++ it 'previews every editable email strictly, with placeholder links' do+ Spree.editable_email_templates.emails.each do |email|+ preview = Spree::EmailTemplates::Preview.new(store: store, key: email.key, strict: true)+ rendered = preview.call++ expect(rendered.subject).to be_present, email.key+ expect(rendered.html).not_to include('{{', '<mj-'), email.key+ expect(preview.variables.to_json).not_to match(/token=(?!preview)/), email.key+ end+ end++ it 'previews with a record the merchant picks, only from the store' do+ order = create(:completed_order_with_totals, store: store)++ preview = Spree::EmailTemplates::Preview.new(store: store, key: 'spree/order_mailer/confirm_email', record_id: order.prefixed_id)++ expect(preview.call.subject).to include(order.number)+ other = create(:completed_order_with_totals, store: create(:store))+ expect do+ Spree::EmailTemplates::Preview.new(store: store, key: 'spree/order_mailer/confirm_email', record_id: other.prefixed_id).call+ end.to raise_error(ActiveRecord::RecordNotFound)+ end++ it 'says so when the store has nothing to preview with' do+ Spree::OrderGroup.where(store: store).delete_all++ expect do+ Spree::EmailTemplates::Preview.new(store: store, key: 'spree/order_group_mailer/confirm_email').call+ end.to raise_error(Spree::EmailTemplates::NoSampleRecord, /order group/)+ end+end