Skip to content

armgit / spree

Public Imported from GitHub
0

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

Changed email template editing to start from readable text in one language

Damian Legawiec57eab15ccd4a
diff --git a/packages/admin-sdk/src/types/generated/EmailTemplate.ts b/packages/admin-sdk/src/types/generated/EmailTemplate.ts
index 907898a339..343d35cd55 100644
--- a/packages/admin-sdk/src/types/generated/EmailTemplate.ts
+++ b/packages/admin-sdk/src/types/generated/EmailTemplate.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 33a1cbda41b1fe284b7147560021b264
+// Typelizer digest b8e6011a04828879c460e7d9549166b2
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {EmailTemplateDraft} from '@/types'
@@ -15,6 +15,7 @@ interface EmailTemplate {
published_at: string | null;
default_subject: string | null;
default_body: string;
+ published_language: string | null;
default_changed: boolean;
base_subject: string | null;
base_body: string | null;
diff --git a/packages/admin-sdk/src/zod/generated/EmailTemplate.ts b/packages/admin-sdk/src/zod/generated/EmailTemplate.ts
index bb6b050eaa..26b1611fd9 100644
--- a/packages/admin-sdk/src/zod/generated/EmailTemplate.ts
+++ b/packages/admin-sdk/src/zod/generated/EmailTemplate.ts
@@ -14,6 +14,7 @@ export const EmailTemplateSchema = z.object({
published_at: z.string().nullable(),
default_subject: z.string().nullable(),
default_body: z.string(),
+ published_language: z.string().nullable(),
default_changed: z.boolean(),
base_subject: z.string().nullable(),
base_body: z.string().nullable(),
diff --git a/spree/api/app/serializers/spree/api/v3/admin/email_template_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/email_template_serializer.rb
index 42fb65cf66..e0e5920883 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/email_template_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/email_template_serializer.rb
@@ -14,6 +14,7 @@ module Spree
subject: [:string, nullable: true],
body: :string,
published_at: [:string, nullable: true],
+ published_language: [:string, nullable: true],
default_subject: [:string, nullable: true],
default_body: :string,
default_changed: :boolean,
@@ -38,13 +39,11 @@ module Spree
entry.published&.published_at&.iso8601
end
- attribute :default_subject do |entry|
- entry.default&.subject
- end
+ attributes :default_subject, :default_body
- attribute :default_body do |entry|
- entry.default&.body
- end
+ # `any` when this language has no version of its own and customers
+ # receive the one for every language.
+ attribute :published_language, &:published_locale
attribute :default_changed do |entry|
entry.outdated_version.present?
@@ -52,13 +51,7 @@ module Spree
# The default the store's version started from, when Spree's default
# has changed since: compare it with `default_body` to see what changed.
- attribute :base_subject do |entry|
- entry.outdated_version&.base_subject
- end
-
- attribute :base_body do |entry|
- entry.outdated_version&.base_body
- end
+ attributes :base_subject, :base_body
one :draft, resource: proc { Spree.api.admin_email_template_draft_serializer }
end
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.rb
index 4ccbac75e5..d909761759 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
@@ -41,7 +41,8 @@ RSpec.describe Spree::Api::V3::Admin::EmailTemplates::DraftsController, type: :c
it 'refuses a language code that is not one' do
put :update, params: { email_template_id: id, language: 'not a language', body: 'x' }, as: :json
- expect(response).to have_http_status(:unprocessable_content)
+ expect(response).to have_http_status(:bad_request)
+ expect(store.email_template_drafts.count).to eq(0)
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates_controller_spec.rb
index 36992ed32d..4d08204748 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/email_templates_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates_controller_spec.rb
@@ -36,6 +36,22 @@ RSpec.describe Spree::Api::V3::Admin::EmailTemplatesController, type: :controlle
expect(json_response['draft']['updated_by']['label']).to be_present
end
+ it "writes Spree's translation keys out as text for one language" do
+ get :show, params: { id: id, language: 'en' }, as: :json
+
+ expect(json_response['body']).not_to include("| t")
+ expect(json_response['body']).to include(Spree.t('admin_user_mailer.password_reset_email.action'))
+ expect(json_response['default_body']).to eq(json_response['body'])
+ end
+
+ it 'shows the version for every language, saying so, when one language has none of its own' do
+ create(:email_template, store: store, key: editable_key, body: 'For everyone')
+
+ get :show, params: { id: id, language: 'de' }, as: :json
+
+ expect(json_response).to include('body' => 'For everyone', 'customized' => true, 'published_language' => 'any')
+ end
+
it 'reads the version for the language asked for' do
create(:email_template, store: store, key: editable_key, locale: 'de', body: 'German')
diff --git a/spree/core/app/models/spree/email_templates/entry.rb b/spree/core/app/models/spree/email_templates/entry.rb
index a0f9d9cca4..1f338e8fc2 100644
--- a/spree/core/app/models/spree/email_templates/entry.rb
+++ b/spree/core/app/models/spree/email_templates/entry.rb
@@ -2,7 +2,8 @@ module Spree
module EmailTemplates
# One editable email template for one store and language, as the editor
# shows it: what customers receive now, the draft in progress and
- # Spree's default.
+ # Spree's default. For one language, Spree's translation keys are written
+ # out as text in it, so the merchant reads and edits plain words.
class Entry
include ActiveModel::Model
include ActiveModel::Attributes
@@ -19,7 +20,8 @@ module Spree
# @param locale [String] a language code, or "any"
# @return [Array<Spree::EmailTemplates::Entry>] every editable template
def self.all(store, locale: Spree::EmailTemplate::ANY_LOCALE)
- published = store.email_templates.published.where(locale: locale).index_by(&:key)
+ published = store.email_templates.published.where(locale: [locale, Spree::EmailTemplate::ANY_LOCALE]).
+ sort_by { |template| template.locale == locale ? 0 : 1 }.uniq(&:key).index_by(&:key)
drafts = store.email_template_drafts.where(locale: locale).includes(:updated_by).index_by(&:key)
customized = store.email_templates.published.pluck(:key, :locale).group_by(&:first)
@@ -41,7 +43,8 @@ module Spree
locale = locale.presence || Spree::EmailTemplate::ANY_LOCALE
new(
definition: definition, locale: locale,
- published: store.email_templates.published.for_key(definition.key, locale).first,
+ published: store.email_templates.published.where(key: definition.key, locale: [locale, Spree::EmailTemplate::ANY_LOCALE]).
+ min_by { |template| template.locale == locale ? 0 : 1 },
draft: store.email_template_drafts.for_key(definition.key, locale).first,
customized_locales: store.email_templates.published.where(key: definition.key).order(:locale).pluck(:locale)
)
@@ -62,13 +65,35 @@ module Spree
@default ||= Spree::Emails::TemplateResolver.for_mailers.find_default(key)
end
+ # @return [String, nil] the language of the published version customers
+ # receive: this one, or "any" when the version for every language applies
+ def published_locale
+ published&.locale
+ end
+
# What customers receive now.
def subject
- customized? ? published.subject : default&.subject
+ readable(customized? ? published.subject : default&.subject)
end
def body
- customized? ? published.body : default&.body
+ readable(customized? ? published.body : default&.body)
+ end
+
+ def default_subject
+ readable(default&.subject)
+ end
+
+ def default_body
+ readable(default&.body)
+ end
+
+ def base_subject
+ readable(outdated_version&.base_subject)
+ end
+
+ def base_body
+ readable(outdated_version&.base_body)
end
# The default the store's version started from, when Spree's default has
@@ -78,6 +103,14 @@ module Spree
def outdated_version
[draft, published].compact.find { |version| version.default_changed?(default) }
end
+
+ private
+
+ def readable(text)
+ return text if locale == Spree::EmailTemplate::ANY_LOCALE
+
+ Spree::Emails::TranslationInliner.call(text, locale: locale)
+ end
end
end
end
diff --git a/spree/core/app/services/spree/emails/translation_inliner.rb b/spree/core/app/services/spree/emails/translation_inliner.rb
new file mode 100644
index 0000000000..21fae2c697
--- /dev/null
+++ b/spree/core/app/services/spree/emails/translation_inliner.rb
@@ -0,0 +1,99 @@
+module Spree
+ module Emails
+ # Turns Spree's translation keys in a template into readable text in one
+ # language, for a merchant who starts editing it:
+ #
+ # {{ 'order_mailer.confirm_email.dear_customer' | t: name: order.customer_name }}
+ # # => Dear {{ order.customer_name }},
+ #
+ # {% assign heading = 'order_mailer.confirm_email.order_summary' | t: number: order.number %}
+ # # => {% capture heading %}Order {{ order.number }} Summary{% endcapture %}
+ #
+ # A use it cannot turn into text exactly (a plural form, a missing
+ # translation, a value it does not recognize) is left as it was, so the
+ # template still renders the same.
+ class TranslationInliner
+ KEY = /'([a-z0-9_.]+)'/
+ ARGUMENTS = /(?:\s*:\s*([^|}%]+?))?/
+ OUTPUT = /\{\{-?\s*#{KEY}\s*\|\s*t#{ARGUMENTS}\s*(\|[^}]*?)?\s*-?\}\}/
+ ASSIGN = /\{%-?\s*assign\s+(\w+)\s*=\s*#{KEY}\s*\|\s*t#{ARGUMENTS}\s*-?%\}/
+ INTERPOLATION = /%\{(\w+)\}/
+
+ # @param source [String, nil] a template's subject or body
+ # @param locale [String, Symbol] the language to write the text in
+ # @return [String, nil]
+ def self.call(source, locale:)
+ new(locale).call(source)
+ end
+
+ def initialize(locale)
+ @locale = locale
+ end
+
+ def call(source)
+ return source if source.blank?
+
+ source.
+ gsub(ASSIGN) { inline_assign(Regexp.last_match) || Regexp.last_match[0] }.
+ gsub(OUTPUT) { inline_output(Regexp.last_match) || Regexp.last_match[0] }
+ end
+
+ private
+
+ def inline_output(match)
+ _, key, arguments, filters = match.to_a
+ text = translation(key)
+ return unless text
+
+ if filters.present?
+ return if arguments.present? || text.include?("'")
+
+ "{{ '#{text}' #{filters.strip} }}"
+ else
+ interpolate(text, arguments) { |literal| ERB::Util.html_escape(literal) }
+ end
+ end
+
+ def inline_assign(match)
+ _, variable, key, arguments = match.to_a
+ text = translation(key)
+ return unless text
+
+ if arguments.blank? && text.exclude?("'") && text !~ INTERPOLATION
+ "{% assign #{variable} = '#{text}' %}"
+ else
+ body = interpolate(text, arguments) { |literal| ERB::Util.html_escape(literal) }
+ body && "{% capture #{variable} %}#{body}{% endcapture %}"
+ end
+ end
+
+ # Literal text is escaped by the caller's block; each `%{name}` becomes
+ # the Liquid expression the template passed for it.
+ def interpolate(text, arguments)
+ values = parse_arguments(arguments)
+ return unless values
+ return if text.scan(INTERPOLATION).flatten.any? { |name| !values.key?(name) }
+
+ text.split(INTERPOLATION).each_with_index.map do |part, index|
+ index.odd? ? "{{ #{values[part]} }}" : yield(part)
+ end.join
+ end
+
+ def parse_arguments(arguments)
+ return {} if arguments.blank?
+
+ arguments.split(/,\s*(?=\w+\s*:)/).to_h do |pair|
+ name, expression = pair.split(':', 2).map(&:strip)
+ return nil if name.blank? || expression.blank?
+
+ [name, expression]
+ end
+ end
+
+ def translation(key)
+ text = I18n.t(key, scope: :spree, locale: @locale, default: nil)
+ text if text.is_a?(String) && !text.include?('{{') && !text.include?('{%')
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/email_templates/save_draft.rb b/spree/core/app/workflows/spree/email_templates/save_draft.rb
index 1f5af1bea9..445198a6b5 100644
--- a/spree/core/app/workflows/spree/email_templates/save_draft.rb
+++ b/spree/core/app/workflows/spree/email_templates/save_draft.rb
@@ -48,11 +48,14 @@ module Spree
failure(nil, :stale)
end
+ # Starts from what customers in this language receive, with Spree's
+ # translation keys written out as text in it.
def start_from_current
- published = store.email_templates.published.find_by(key: key, locale: draft.locale)
+ published = store.email_templates.published.where(key: key, locale: [draft.locale, Spree::EmailTemplate::ANY_LOCALE]).
+ min_by { |template| template.locale == draft.locale ? 0 : 1 }
- draft.subject = published&.subject || default&.subject
- draft.body = published&.body || default&.body
+ draft.subject = readable(published&.subject || default&.subject)
+ draft.body = readable(published&.body || default&.body)
draft.base_subject = published ? published.base_subject : default&.subject
draft.base_body = published ? published.base_body : default&.body
end
@@ -62,6 +65,12 @@ module Spree
draft.base_body = default&.body
end
+ def readable(text)
+ return text if draft.locale == Spree::EmailTemplate::ANY_LOCALE
+
+ Spree::Emails::TranslationInliner.call(text, locale: draft.locale)
+ end
+
def default
@default ||= Spree::Emails::TemplateResolver.for_mailers.find_default(key)
end
diff --git a/spree/core/spec/services/spree/emails/translation_inliner_spec.rb b/spree/core/spec/services/spree/emails/translation_inliner_spec.rb
new file mode 100644
index 0000000000..70eaa9dc1d
--- /dev/null
+++ b/spree/core/spec/services/spree/emails/translation_inliner_spec.rb
@@ -0,0 +1,64 @@
+require 'spec_helper'
+
+describe Spree::Emails::TranslationInliner do
+ def inline(source, locale: :en)
+ described_class.call(source, locale: locale)
+ end
+
+ around do |example|
+ I18n.backend.store_translations(:en, spree: { inliner_spec: {
+ plain: 'Thanks for shopping',
+ greeting: 'Dear %{name},',
+ heading: 'Order %{number} summary',
+ markup: 'Tom & Jerry <shop>',
+ quoted: "Don't wait",
+ count: { one: 'One item', other: '%{count} items' }
+ } })
+ I18n.backend.store_translations(:de, spree: { inliner_spec: { plain: 'Danke für Ihren Einkauf' } })
+ example.run
+ end
+
+ it 'writes a key out as text in the language asked for' do
+ expect(inline("<mj-text>{{ 'inliner_spec.plain' | t }}</mj-text>")).to eq('<mj-text>Thanks for shopping</mj-text>')
+ expect(inline("{{ 'inliner_spec.plain' | t }}", locale: :de)).to eq('Danke für Ihren Einkauf')
+ end
+
+ it 'turns each value into the variable the template passed' do
+ expect(inline("{{ 'inliner_spec.greeting' | t: name: order.customer_name }}")).to eq('Dear {{ order.customer_name }},')
+ end
+
+ it 'escapes the text, since the filter output was escaped' do
+ expect(inline("{{ 'inliner_spec.markup' | t }}")).to eq('Tom &amp; Jerry &lt;shop&gt;')
+ end
+
+ it 'keeps later filters on text without values' do
+ expect(inline("{{ 'inliner_spec.plain' | t | upcase }}")).to eq("{{ 'Thanks for shopping' | upcase }}")
+ end
+
+ it 'turns an assigned translation into a plain assignment or a capture' do
+ expect(inline("{% assign heading = 'inliner_spec.plain' | t %}")).to eq("{% assign heading = 'Thanks for shopping' %}")
+ expect(inline("{% assign heading = 'inliner_spec.heading' | t: number: order.number %}")).
+ to eq('{% capture heading %}Order {{ order.number }} summary{% endcapture %}')
+ expect(inline("{% assign label = 'inliner_spec.quoted' | t %}")).to eq('{% capture label %}Don&#39;t wait{% endcapture %}')
+ end
+
+ it 'leaves what it cannot write out exactly as it was' do
+ [
+ "{{ 'inliner_spec.count' | t: count: n }}",
+ "{{ 'inliner_spec.greeting' | t }}",
+ "{{ 'inliner_spec.missing' | t }}",
+ "{{ 'inliner_spec.greeting' | t: name: user.name | upcase }}"
+ ].each { |source| expect(inline(source)).to eq(source) }
+ end
+
+ it 'renders the same as the template it came from' do
+ store = @default_store
+ source = "{% assign label = 'inliner_spec.quoted' | t %}<mj-section><mj-column><mj-text>{{ 'inliner_spec.greeting' | t: name: name }} {{ label }} {{ 'inliner_spec.markup' | t }}</mj-text></mj-column></mj-section>"
+ resolver = Spree::Emails::TemplateResolver.for_mailers
+ renderer = Spree::Emails::Renderer.new(resolver: resolver, store: store)
+ original = renderer.render(Spree::Emails::Template.new(key: 'a', subject: 'S', body: source), { name: 'Ann' })
+ inlined = renderer.render(Spree::Emails::Template.new(key: 'a', subject: 'S', body: inline(source)), { name: 'Ann' })
+
+ expect(inlined.html).to eq(original.html)
+ end
+end
diff --git a/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb b/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb
index 3de1fe3863..d8efdbf607 100644
--- a/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb
+++ b/spree/core/spec/workflows/spree/email_templates/save_draft_spec.rb
@@ -20,6 +20,14 @@ describe Spree::EmailTemplates::SaveDraft do
expect(draft.updated_by).to eq(admin)
end
+ it 'starts a language version with the text written out in that language' do
+ draft = save({ subject: nil }, locale: 'en').value
+
+ expect(draft.body).not_to include('| t')
+ expect(draft.body).to include(Spree.t('admin_user_mailer.password_reset_email.action'))
+ expect(draft.base_body).to include("'admin_user_mailer.password_reset_email.action' | t")
+ 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')