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
Fixed email template review findings
Damian Legawiec1b09780a6dcd
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 5e4364516a..21e16bf888 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -269,6 +269,7 @@ import type {EmailTemplateLanguageParams,EmailTemplatePreviewParams,EmailTemplateRestoreParams,+ EmailTemplateVersionParams,ExchangeCreateParams,ExchangeFulfillParams,ExchangeReceiveParams,@@ -5783,7 +5784,7 @@ export class AdminClient {/** Goes back to Spree's default and discards the draft. Published versions stay in the history. */revert: (id: string,- params?: EmailTemplateLanguageParams,+ params?: EmailTemplateVersionParams,options?: RequestOptions,): Promise<EmailTemplate> =>this.request<EmailTemplate>('DELETE', `/email_templates/${id}`, { ...options, params }),@@ -5802,7 +5803,7 @@ export class AdminClient {delete: (id: string,- params?: EmailTemplateLanguageParams,+ params?: EmailTemplateVersionParams,options?: RequestOptions,): Promise<EmailTemplate> =>this.request<EmailTemplate>('DELETE', `/email_templates/${id}/draft`, {@@ -5814,7 +5815,7 @@ export class AdminClient {/** Makes the draft live; refused with 422 and each problem's email and line when it does not render. */publish: (id: string,- params?: EmailTemplateLanguageParams,+ params?: EmailTemplateVersionParams,options?: RequestOptions,): Promise<EmailTemplate> =>this.request<EmailTemplate>('POST', `/email_templates/${id}/publication`, {diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 95b11e430f..4ae634e3f3 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -3153,6 +3153,11 @@ export type EmailTemplateLanguageParams = {language?: string}+export type EmailTemplateVersionParams = EmailTemplateLanguageParams & {+ /** The draft's `lock_version` as last seen. A draft saved since is refused with 409. */+ lock_version?: number+}+export interface EmailTemplateDraftParams extends EmailTemplateLanguageParams {subject?: string | nullbody?: stringdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/email_template_lookup.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/email_template_lookup.rbindex d834581a45..2c102b365a 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/email_template_lookup.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/email_template_lookup.rb@@ -52,6 +52,21 @@ module Spreeargumentsend+ # Samples show a real record of the store (the latest order, a+ # company), so previewing one needs permission to read it.+ def authorize_sample_data!+ sample = build_preview.email.sample_class+ missing = Array(sample.try(:required_permissions)).reject { |key| holds_permission?(key) }+ return if missing.empty?++ render_error(+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],+ message: Spree.t('email_templates.sample_needs_permission', permissions: missing.to_sentence),+ status: :forbidden,+ details: { required_scope: missing.first }+ )+ end+def build_previewSpree::EmailTemplates::Preview.new(store: current_store, key: email_template.key, strict: true, **preview_arguments)end@@ -67,9 +82,9 @@ module Spree)end+ # Attributed to the template being edited, whose lines the editor marks.def render_render_error(error)- email = params[:email_key].presence || email_template.id- render_template_problems([{ email: email.to_s, message: error.message, line: error.try(:line_number) }])+ render_template_problems([{ email: email_template.id, message: error.message, line: error.try(:line_number) }])enddef render_no_sample(error)diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/drafts_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/drafts_controller.rbindex 13070017f9..410d6bcf29 100644--- a/spree/api/app/controllers/spree/api/v3/admin/email_templates/drafts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/drafts_controller.rb@@ -30,7 +30,11 @@ module Spreedef destroyauthorize! :update, Spree::EmailTemplate- current_store.email_template_drafts.for_key(email_template.key, language).destroy_all+ result = Spree.email_template_discard_draft_workflow.call(+ store: current_store, key: email_template.key, locale: language, lock_version: params[:lock_version].presence+ )+ return render_stale_draft if result.error&.value == :stale+render json: serialize_email_template(reload: true)endenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/previews_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/previews_controller.rbindex 83e51254b7..76f39a2cdf 100644--- a/spree/api/app/controllers/spree/api/v3/admin/email_templates/previews_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/previews_controller.rb@@ -6,6 +6,8 @@ module Spreeclass PreviewsController < Admin::BaseControllerinclude Spree::Api::V3::Admin::EmailTemplateLookup+ before_action :authorize_sample_data!+# POST /api/v3/admin/email_templates/:email_template_id/preview## Renders the template with sample data built from the store's latestdiff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/publications_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/publications_controller.rbindex 74315ab670..fd3d4d60af 100644--- a/spree/api/app/controllers/spree/api/v3/admin/email_templates/publications_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/publications_controller.rb@@ -15,8 +15,10 @@ module Spreeauthorize! :update, Spree::EmailTemplateresult = Spree.email_template_publish_workflow.call(- store: current_store, key: email_template.key, locale: language, actor: current_actor+ store: current_store, key: email_template.key, locale: language, actor: current_actor,+ lock_version: params[:lock_version].presence)+ return render_stale_draft if result.error&.value == :stalereturn render_template_problems(result.value) if result.error&.value == :invalid_templatereturn render_result_error(result) unless result.success?diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/test_emails_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/test_emails_controller.rbindex c1df129b3b..cccef2f7f5 100644--- a/spree/api/app/controllers/spree/api/v3/admin/email_templates/test_emails_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/test_emails_controller.rb@@ -6,6 +6,8 @@ module Spreeclass TestEmailsController < Admin::BaseControllerinclude Spree::Api::V3::Admin::EmailTemplateLookup+ before_action :authorize_sample_data!+# POST /api/v3/admin/email_templates/:email_template_id/test_email## Sends the template, rendered as the preview renders it, to thediff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates_controller.rbindex 62e7169e63..e38f0dc6bc 100644--- a/spree/api/app/controllers/spree/api/v3/admin/email_templates_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates_controller.rb@@ -34,8 +34,10 @@ module Spreeauthorize! :update, Spree::EmailTemplateresult = Spree.email_template_revert_workflow.call(- store: current_store, key: email_template.key, locale: language, actor: current_actor+ store: current_store, key: email_template.key, locale: language, actor: current_actor,+ lock_version: params[:lock_version].presence)+ return render_stale_draft if result.error&.value == :stalereturn render_result_error(result) unless result.success?render json: serialize_email_template(reload: true)diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/drafts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/drafts_controller_spec.rbindex 5a52898ad9..4ccbac75e5 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/drafts_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/drafts_controller_spec.rb@@ -55,5 +55,14 @@ RSpec.describe Spree::Api::V3::Admin::EmailTemplates::DraftsController, type: :cexpect(json_response['draft']).to be_nilexpect(store.email_template_drafts.count).to eq(0)end++ it 'keeps with 409 a draft saved after the one the admin saw' do+ create(:email_template_draft, store: store, key: editable_key).update!(body: 'Newer')++ delete :destroy, params: { email_template_id: id, lock_version: 0 }, as: :json++ expect(response).to have_http_status(:conflict)+ expect(store.email_template_drafts.count).to eq(1)+ endendenddiff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/previews_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/previews_controller_spec.rbindex 5091214bb5..05c8190b88 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/previews_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/previews_controller_spec.rb@@ -31,6 +31,33 @@ RSpec.describe Spree::Api::V3::Admin::EmailTemplates::PreviewsController, type:expect(store.reload.preferred_email_card_color).to be_nilend+ context 'when the sample shows records the caller may not read' do+ let(:headers) { { 'x-spree-api-key' => create(:api_key, :secret, store: store, scopes: scopes).plaintext_token } }++ before { allow(Spree::TestingSupport::EmailTemplateSample).to receive(:required_permissions).and_return(%w[read_orders]) }++ context 'with only the email templates scope' do+ let(:scopes) { %w[write_email_templates] }++ it 'is refused' do+ post :create, params: { email_template_id: id }, as: :json++ expect(response).to have_http_status(:forbidden)+ expect(json_response['error']['details']['required_scope']).to eq('read_orders')+ end+ end++ context 'with the orders scope too' do+ let(:scopes) { %w[write_email_templates read_orders] }++ it 'renders' do+ post :create, params: { email_template_id: id }, as: :json++ expect(response).to have_http_status(:ok)+ end+ end+ end+it 'says what is wrong and where when the template does not render' dopost :create, params: { email_template_id: id, body: "<mj-section>\n{% if %}</mj-section>" }, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/publications_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/publications_controller_spec.rbindex 1a9d208d1e..e8f7cd000c 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/publications_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/publications_controller_spec.rb@@ -33,6 +33,15 @@ RSpec.describe Spree::Api::V3::Admin::EmailTemplates::PublicationsController, tyexpect(store.email_templates.count).to eq(0)end+ it 'refuses with 409 a draft saved after the one the admin reviewed' do+ draft = create(:email_template_draft, store: store, key: editable_key, body: body)+ draft.update!(body: "#{body} changed")++ post :create, params: { email_template_id: id, lock_version: 0 }, as: :json++ expect(response).to have_http_status(:conflict)+ end+it 'refuses when there is no draft' dopost :create, params: { email_template_id: id }, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/test_emails_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/test_emails_controller_spec.rbindex 104f8236a3..5e7d611567 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/test_emails_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/test_emails_controller_spec.rb@@ -19,6 +19,16 @@ RSpec.describe Spree::Api::V3::Admin::EmailTemplates::TestEmailsController, typeexpect(json_response['sent_to']).to eq(admin_user.email)end+ it 'delivers it, with unsaved branding' do+ perform_enqueued_jobs do+ post :create, params: { email_template_id: id, branding: { card_color: '#123456' } }, as: :json+ end++ delivered = ActionMailer::Base.deliveries.last+ expect(delivered.to).to eq([admin_user.email])+ expect(delivered.html_part.body.to_s).to include('#123456')+ end+it 'sends nothing for a template that does not render' doexpect dopost :create, params: { email_template_id: id, body: '{{ user.nickname }}' }, as: :jsondiff --git a/spree/core/app/mailers/spree/base_mailer.rb b/spree/core/app/mailers/spree/base_mailer.rbindex 7889a72480..1b40d26045 100644--- a/spree/core/app/mailers/spree/base_mailer.rb+++ b/spree/core/app/mailers/spree/base_mailer.rb@@ -90,9 +90,7 @@ module Spree# @return [Mail::Message]def mail_template(assigns = {}, template: "#{mailer_name}/#{action_name}", **headers)in_store_locale do- resolver = email_resolver(template)- email_template = resolver.find(template) || raise(ArgumentError, "Missing email template #{template}.liquid")- email = email_renderer(resolver).render(email_template, assigns)+ email = render_email_template(template, assigns)mail(headers.merge(subject: email.subject)) do |format|format.text { render plain: email.text, layout: false }@@ -135,6 +133,24 @@ module Spreeprivate+ # A store's published template passed its checks with sample data, but a+ # real record can still trip it. The customer then gets the email from the+ # files rather than none, and the error is reported.+ def render_email_template(template, assigns)+ resolver = email_resolver(template)+ email_renderer(resolver).render(find_email_template(resolver, template), assigns)+ rescue Liquid::Error, MRML::Error => e+ raise unless resolver&.store++ Rails.error.report(e, context: { email_template: template, store_id: current_store&.id })+ fallback = email_resolver+ email_renderer(fallback).render(find_email_template(fallback, template), assigns)+ end++ def find_email_template(resolver, template)+ resolver.find(template) || raise(ArgumentError, "Missing email template #{template}.liquid")+ end+# 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.diff --git a/spree/core/app/mailers/spree/email_template_mailer.rb b/spree/core/app/mailers/spree/email_template_mailer.rbindex dcd182b6dd..bf7539cbe8 100644--- a/spree/core/app/mailers/spree/email_template_mailer.rb+++ b/spree/core/app/mailers/spree/email_template_mailer.rb@@ -10,10 +10,12 @@ module Spree# @param body [String, nil] an unsaved body# @param record_id [String, nil] the record to build sample data from# @param email_key [String, nil] for the layout or a partial, the email to show it in- def test_email(store, recipient, key, locale: nil, subject: nil, body: nil, record_id: nil, email_key: nil)+ # @param branding [Hash] unsaved branding values+ def test_email(store, recipient, key, locale: nil, subject: nil, body: nil, record_id: nil, email_key: nil, branding: {})@current_store = storeemail = Spree::EmailTemplates::Preview.new(- store: store, key: key, locale: locale, subject: subject, body: body, record_id: record_id, email_key: email_key+ store: store, key: key, locale: locale, subject: subject, body: body, record_id: record_id, email_key: email_key,+ branding: branding).callmail(to: recipient, subject: Spree.t('email_templates.test_email_subject', subject: email.subject)) do |format|diff --git a/spree/core/app/services/spree/email_templates/check.rb b/spree/core/app/services/spree/email_templates/check.rbindex c5163e4edc..bedeebe4b3 100644--- a/spree/core/app/services/spree/email_templates/check.rb+++ b/spree/core/app/services/spree/email_templates/check.rb@@ -3,7 +3,8 @@ module Spree# 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.+ # editable email, since all of them use it, and in every language the+ # store has published its own version of an email in.## An email the store has no record for cannot be rendered with data; its# draft is still checked for Liquid syntax errors.@@ -17,7 +18,7 @@ module Spree# @return [Array<Hash>] one `{ email:, message:, line: }` per problem; empty when the draft rendersdef call- email_keys.filter_map { |email_key| problem_in(email_key) }+ locales.flat_map { |locale| email_keys.filter_map { |email_key| problem_in(email_key, locale) } }.uniqendprivate@@ -27,8 +28,14 @@ module Spreedefinition.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,+ def locales+ return [@draft.locale] if @draft.definition.email? || @draft.locale != Spree::EmailTemplate::ANY_LOCALE++ [@draft.locale, *@store.email_templates.published.where.not(locale: Spree::EmailTemplate::ANY_LOCALE).distinct.pluck(:locale)]+ end++ def problem_in(email_key, locale)+ Preview.new(store: @store, key: @draft.key, locale: locale, subject: @draft.subject, body: @draft.body,email_key: email_key, strict: true).callnilrescue Spree::EmailTemplates::NoSampleRecorddiff --git a/spree/core/app/services/spree/emails/template_resolver.rb b/spree/core/app/services/spree/emails/template_resolver.rbindex 86498c46f8..dfcbb93fc7 100644--- a/spree/core/app/services/spree/emails/template_resolver.rb+++ b/spree/core/app/services/spree/emails/template_resolver.rb@@ -11,6 +11,9 @@ module Spreeclass TemplateResolverKEY_FORMAT = %r{\A[a-z0-9_]+(?:/[a-z0-9_]+)*\z}+ # @return [Spree::Store, nil] the store whose published templates apply+ attr_reader :store+class InvalidKey < ArgumentError; end# @param view_paths [Array<String, Pathname>] directories to search, highest precedence firstdiff --git a/spree/core/app/workflows/spree/email_templates/discard_draft.rb b/spree/core/app/workflows/spree/email_templates/discard_draft.rbnew file mode 100644index 0000000000..c089d2510c--- /dev/null+++ b/spree/core/app/workflows/spree/email_templates/discard_draft.rb@@ -0,0 +1,19 @@+module Spree+ module EmailTemplates+ # Throws away the draft of one template and language. Given the+ # `lock_version` the draft was seen at, a draft saved since is kept.+ class DiscardDraft < Spree::Workflow+ def perform(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, lock_version: nil)+ super+ draft = store.email_template_drafts.find_by(key: key, locale: locale.presence || Spree::EmailTemplate::ANY_LOCALE)+ return success(nil) unless draft+ return failure(nil, :stale) if !lock_version.nil? && lock_version.to_i != draft.lock_version++ draft.destroy!+ success(nil)+ rescue ActiveRecord::StaleObjectError+ failure(nil, :stale)+ end+ end+ end+enddiff --git a/spree/core/app/workflows/spree/email_templates/publish.rb b/spree/core/app/workflows/spree/email_templates/publish.rbindex cc51aad169..e1b9e0ce2c 100644--- a/spree/core/app/workflows/spree/email_templates/publish.rb+++ b/spree/core/app/workflows/spree/email_templates/publish.rb@@ -4,17 +4,23 @@ module Spree# 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.+ # the draft. Given the `lock_version` the draft was reviewed at, a draft+ # saved since is refused rather than published unseen.class Publish < Spree::Workflow- def perform(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, actor: nil)+ def perform(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, actor: nil, lock_version: nil)superstep :ensure_draft+ step :ensure_currentstep :check- ApplicationRecord.transaction do- step :publish- step :record_revision- step :clear_draft+ begin+ ApplicationRecord.transaction do+ step :publish+ step :record_revision+ step :clear_draft+ end+ rescue ActiveRecord::StaleObjectError, ActiveRecord::RecordNotUnique+ failure(nil, :stale)endtemplate.publish_event('email_template.published')@@ -35,6 +41,10 @@ module Spreefailure(nil, :no_draft) unless draftend+ def ensure_current+ failure(nil, :stale) if !lock_version.nil? && lock_version.to_i != draft.lock_version+ end+def checkproblems = Spree::EmailTemplates::Check.new(store: store, draft: draft).callfailure(problems, :invalid_template) if problems.any?diff --git a/spree/core/app/workflows/spree/email_templates/revert.rb b/spree/core/app/workflows/spree/email_templates/revert.rbindex d2fcd91307..6eaf3f21e4 100644--- a/spree/core/app/workflows/spree/email_templates/revert.rb+++ b/spree/core/app/workflows/spree/email_templates/revert.rb@@ -3,15 +3,18 @@ module Spree# 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.+ # can still be restored. Given the `lock_version` the draft was seen at,+ # a draft saved since is not thrown away.class Revert < Spree::Workflow- def perform(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, actor: nil)+ def perform(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, actor: nil, lock_version: nil)superlocale_value = locale.presence || Spree::EmailTemplate::ANY_LOCALEtemplate = store.email_templates.find_by(key: key, locale: locale_value)+ draft = store.email_template_drafts.find_by(key: key, locale: locale_value)+ return failure(nil, :stale) if draft && !lock_version.nil? && lock_version.to_i != draft.lock_versionApplicationRecord.transaction do- store.email_template_drafts.where(key: key, locale: locale_value).destroy_all+ draft&.destroy!template&.update!(status: :reverted, reverted_at: Time.current, reverted_by: actor) if template&.published?enddiff --git a/spree/core/app/workflows/spree/email_templates/save_draft.rb b/spree/core/app/workflows/spree/email_templates/save_draft.rbindex c6869cf3ea..71a76e7cdb 100644--- a/spree/core/app/workflows/spree/email_templates/save_draft.rb+++ b/spree/core/app/workflows/spree/email_templates/save_draft.rb@@ -41,6 +41,8 @@ module Spreedraft.body = attributes[:body] if attributes.key?(:body)draft.updated_by = actorfailure(draft) unless draft.save+ rescue ActiveRecord::StaleObjectError, ActiveRecord::RecordNotUnique+ failure(nil, :stale)enddef start_from_currentdiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 617e998f6d..66f013f1d0 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -925,6 +925,7 @@ en:email_templates:another_admin: another adminno_sample_record: There is no %{record} in this store to preview this email with yet.+ sample_needs_permission: Previewing this email shows your store's records, which needs the %{permissions} permission.stale_draft: "%{name} saved this draft after you opened it. Reload to see their changes before saving yours."test_email_needs_admin: A test email goes to the signed-in admin, so it needs one.test_email_subject: "[Test] %{subject}"diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rbindex 9a7bd2dbe2..e91e43104b 100644--- a/spree/core/lib/spree/core/dependencies.rb+++ b/spree/core/lib/spree/core/dependencies.rb@@ -252,6 +252,7 @@ module Spreeemail_template_save_draft_workflow: 'Spree::EmailTemplates::SaveDraft',email_template_publish_workflow: 'Spree::EmailTemplates::Publish',email_template_revert_workflow: 'Spree::EmailTemplates::Revert',+ email_template_discard_draft_workflow: 'Spree::EmailTemplates::DiscardDraft',email_template_restore_revision_workflow: 'Spree::EmailTemplates::RestoreRevision',# findersdiff --git a/spree/core/spec/mailers/spree/admin_user_mailer_spec.rb b/spree/core/spec/mailers/spree/admin_user_mailer_spec.rbindex 0fe540fe46..6991026a68 100644--- a/spree/core/spec/mailers/spree/admin_user_mailer_spec.rb+++ b/spree/core/spec/mailers/spree/admin_user_mailer_spec.rb@@ -35,6 +35,31 @@ describe Spree::AdminUserMailer, type: :mailer doexpect(email_body(message)).to include("https://admin.example.com/reset-password?token=#{token}")end+ context "with the store's published version, made editable for the example" do+ include_context 'with an editable email template'++ it 'sends the store version' do+ create(:email_template, store: store, key: editable_key, subject: 'Store subject',+ body: '<mj-section><mj-column><mj-text>Store version</mj-text></mj-column></mj-section>')++ message = described_class.password_reset_email(admin_user, token, store)++ expect(message.subject).to eq('Store subject')+ expect(email_body(message)).to include('Store version')+ end++ it "falls back to Spree's template when the store version fails on real data, reporting the error" do+ create(:email_template, store: store, key: editable_key,+ body: '<mj-section><mj-column><mj-text>{{ 1 | divided_by: 0 }}</mj-text></mj-column></mj-section>')+ allow(Rails.error).to receive(:report)++ message = described_class.password_reset_email(admin_user, token, store)++ expect(email_body(message)).to include("token=#{token}")+ expect(Rails.error).to have_received(:report).with(an_instance_of(Liquid::ZeroDivisionError), anything)+ end+ end+context 'when the admin has a dashboard language set' doaround do |example|previous = I18n.available_localesdiff --git a/spree/core/spec/mailers/spree/email_template_mailer_spec.rb b/spree/core/spec/mailers/spree/email_template_mailer_spec.rbindex 7818f05746..1bb104bdb0 100644--- a/spree/core/spec/mailers/spree/email_template_mailer_spec.rb+++ b/spree/core/spec/mailers/spree/email_template_mailer_spec.rb@@ -15,4 +15,10 @@ describe Spree::EmailTemplateMailer, type: :mailer doexpect(mail.html_part.body.to_s).to include('Draft for [email protected]')expect(mail.text_part.body.to_s).to include('Draft for [email protected]')end++ it 'renders unsaved branding' do+ mail = described_class.test_email(store, '[email protected]', editable_key, branding: { card_color: '#123456' })++ expect(mail.html_part.body.to_s).to include('#123456')+ endenddiff --git a/spree/core/spec/workflows/spree/email_templates/discard_draft_spec.rb b/spree/core/spec/workflows/spree/email_templates/discard_draft_spec.rbnew file mode 100644index 0000000000..11f35fdad4--- /dev/null+++ b/spree/core/spec/workflows/spree/email_templates/discard_draft_spec.rb@@ -0,0 +1,21 @@+require 'spec_helper'++describe Spree::EmailTemplates::DiscardDraft do+ include_context 'with an editable email template'++ let(:store) { @default_store }+ let!(:draft) { create(:email_template_draft, store: store, key: editable_key) }++ it 'throws the draft away' do+ described_class.new.call(store: store, key: editable_key, lock_version: 0)++ expect(store.email_template_drafts.count).to eq(0)+ end++ it 'keeps a draft saved after the one the admin saw' do+ draft.update!(body: 'Newer')++ expect(described_class.new.call(store: store, key: editable_key, lock_version: 0).error.value).to eq(:stale)+ expect(store.email_template_drafts.count).to eq(1)+ end+enddiff --git a/spree/core/spec/workflows/spree/email_templates/publish_spec.rb b/spree/core/spec/workflows/spree/email_templates/publish_spec.rbindex 9cc0534eab..218e988712 100644--- a/spree/core/spec/workflows/spree/email_templates/publish_spec.rb+++ b/spree/core/spec/workflows/spree/email_templates/publish_spec.rb@@ -34,6 +34,28 @@ describe Spree::EmailTemplates::Publish doexpect(store.email_templates.count).to eq(0)end+ it 'refuses a draft saved after the one the admin reviewed' do+ store.email_template_drafts.first.update!(body: "#{body} changed")++ result = described_class.new.call(store: store, key: editable_key, actor: admin, lock_version: 0)++ expect(result.error.value).to eq(:stale)+ expect(store.email_templates.count).to eq(0)+ end++ it "checks a layout draft in every language the store published an email in" do+ allow_any_instance_of(Spree::Store).to receive(:supported_locales_list).and_return(%w[de en])+ store.email_template_drafts.destroy_all+ create(:email_template, store: store, key: editable_key, locale: 'de',+ body: '<mj-section><mj-column><mj-text>{{ nur_deutsch }}</mj-text></mj-column></mj-section>')+ layout = File.read(Spree::Core::Engine.root.join('app/views/layouts/spree/base_mailer.liquid'))+ create(:email_template_draft, store: store, key: 'layouts/spree/base_mailer', body: layout)++ result = described_class.new.call(store: store, key: 'layouts/spree/base_mailer', actor: admin)++ expect(result.value).to contain_exactly(hash_including(message: /nur_deutsch/))+ end+it 'refuses when there is no draft' dostore.email_template_drafts.destroy_alldiff --git a/spree/core/spec/workflows/spree/email_templates/revert_spec.rb b/spree/core/spec/workflows/spree/email_templates/revert_spec.rbindex fc337bc116..ec3a7f5cc4 100644--- a/spree/core/spec/workflows/spree/email_templates/revert_spec.rb+++ b/spree/core/spec/workflows/spree/email_templates/revert_spec.rb@@ -20,4 +20,13 @@ describe Spree::EmailTemplates::Revert doexpect(template.revisions.count).to eq(1)expect(store.email_template_drafts.count).to eq(0)end++ it 'keeps a draft saved after the one the admin saw' do+ store.email_template_drafts.first.update!(body: 'Newer')++ result = described_class.new.call(store: store, key: editable_key, actor: admin, lock_version: 0)++ expect(result.error.value).to eq(:stale)+ expect(template.reload).to be_published+ endenddiff --git a/spree/emails/app/services/spree/emails/samples/base.rb b/spree/emails/app/services/spree/emails/samples/base.rbindex 178c5bf83a..d70cb9ae66 100644--- a/spree/emails/app/services/spree/emails/samples/base.rb+++ b/spree/emails/app/services/spree/emails/samples/base.rb@@ -13,6 +13,12 @@ module Spreenilend+ # @return [Array<String>] the permission keys a caller needs to see this+ # sample, since it shows a real record's data+ def self.required_permissions+ record_type ? %w[read_orders] : []+ end+attr_reader :store, :record_id# @param store [Spree::Store]diff --git a/spree/emails/app/services/spree/emails/samples/company_invitation.rb b/spree/emails/app/services/spree/emails/samples/company_invitation.rbindex 462b67c7db..a6a75aa7f4 100644--- a/spree/emails/app/services/spree/emails/samples/company_invitation.rb+++ b/spree/emails/app/services/spree/emails/samples/company_invitation.rb@@ -2,6 +2,10 @@ module Spreemodule Emailsmodule Samplesclass CompanyInvitation < Base+ def self.required_permissions+ %w[read_customers]+ end+def variables{company: data(store.companies.order(created_at: :desc).first || Spree::Company.new(name: 'Acme Corporation', store: store),diff --git a/spree/emails/app/services/spree/emails/samples/fulfillment.rb b/spree/emails/app/services/spree/emails/samples/fulfillment.rbindex 140ea30102..036a4e0e6d 100644--- a/spree/emails/app/services/spree/emails/samples/fulfillment.rb+++ b/spree/emails/app/services/spree/emails/samples/fulfillment.rb@@ -2,6 +2,10 @@ module Spreemodule Emailsmodule Samplesclass Fulfillment < Base+ def self.required_permissions+ %w[read_orders read_fulfillments]+ end+def self.record_type'fulfillment'end