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
Fix: Email branding preview ignored the uploaded logo (#14905)
Damian Legawiece7d276dbc5c3
diff --git a/.changeset/email-branding-logo-preview.md b/.changeset/email-branding-logo-preview.mdnew file mode 100644index 0000000000..44d13eacc1--- /dev/null+++ b/.changeset/email-branding-logo-preview.md@@ -0,0 +1,6 @@+---+"@spree/dashboard": patch+"@spree/admin-sdk": patch+---++The email branding preview now shows a newly uploaded or removed logo before saving, and refreshes after saving. The logo now sits in the Branding section of email settings. `EmailTemplatePreviewParams` accepts `mailer_logo_signed_id`.diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yamlindex 8f31926509..d1ff0c7097 100644--- a/docs/api-reference/admin.yaml+++ b/docs/api-reference/admin.yaml@@ -73043,6 +73043,11 @@ components:nullable: truedescription: Unsaved colors and font to preview, named like the store's`email_*` settings.+ mailer_logo_signed_id:+ type: string+ description: 'An unsaved email logo: the signed id of an uploaded image,+ or null to preview without one.'+ nullable: trueEmailTemplateRestoreParams:type: objectproperties:diff --git a/packages/admin-sdk/src/types/params/EmailTemplatePreviewParams.ts b/packages/admin-sdk/src/types/params/EmailTemplatePreviewParams.tsindex 8c2e1cf827..7985875933 100644--- a/packages/admin-sdk/src/types/params/EmailTemplatePreviewParams.ts+++ b/packages/admin-sdk/src/types/params/EmailTemplatePreviewParams.ts@@ -20,4 +20,6 @@ export type EmailTemplatePreviewParams = {heading_color?: string | nullfont?: 'inter' | 'system' | 'helvetica' | 'georgia' | 'roboto' | 'lato' | 'merriweather' | null}+ /** An unsaved email logo: the signed id of an uploaded image, or null to preview without one. */+ mailer_logo_signed_id?: string | null}diff --git a/packages/dashboard/e2e/store-settings.spec.ts b/packages/dashboard/e2e/store-settings.spec.tsindex 73a61b150c..98311aff95 100644--- a/packages/dashboard/e2e/store-settings.spec.ts+++ b/packages/dashboard/e2e/store-settings.spec.ts@@ -223,14 +223,14 @@ test.describe('store settings — general', () => {})test.describe('store settings — emails', () => {- test('hides addresses + logo cards when consumer emails are turned off', async ({ page }) => {+ test('hides addresses + branding cards when consumer emails are turned off', async ({ page }) => {const creds = await login(page)await page.goto(EMAILS_PATH(creds.store_id))await expect(page.getByRole('heading', { name: /^email settings$/i })).toBeVisible({timeout: 15_000,})- // The logo card always shows the reusable ImageUploadField's upload CTA —+ // The branding card always shows the logo's upload CTA —// use that as a proxy for the card's presence. The CardTitle is rendered as// a `<div>` so `role=heading` doesn't apply, and matching plain text would// collide with other strings.@@ -247,7 +247,7 @@ test.describe('store settings — emails', () => {await expect(page.locator('#store-mail-from-address')).toBeVisible()await expect(uploadCta).toBeVisible()- // Toggle off → address + logo cards disappear.+ // Toggle off → address + branding cards disappear.await consumerEmailsToggle.click()await expect(page.locator('#store-mail-from-address')).toHaveCount(0)await expect(uploadCta).toHaveCount(0)diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex ddc6a07e77..8f42f192d3 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -3850,7 +3850,6 @@"logo_dimensions_help": "الموصى بها: 204 × 104 بكسل.","section_addresses": "عناوين Email","section_delivery": "توصيل",- "section_logo": "الشعار","subtitle": "عناوين المرسل والإشعارات والشعار المضمن في رسائل البريد الإلكتروني الخاصة بالمعاملات.","title": "إعدادات Email","branding": {diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 9f064d44eb..02bb9c1a75 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -3822,7 +3822,6 @@"logo_dimensions_help": "Empfohlen: 204×104 Pixel.","section_addresses": "E-Mail-Adressen","section_delivery": "Zustellung",- "section_logo": "Logo","subtitle": "Absenderadressen, Benachrichtigungen und das in Transaktions-E-Mails eingebettete Logo.","title": "E-Mail-Einstellungen","branding": {diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 2f6a4d2703..13f85b9548 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -3822,7 +3822,6 @@"logo_dimensions_help": "Recommended: 204×104 pixels.","section_addresses": "Email addresses","section_delivery": "Delivery",- "section_logo": "Logo","subtitle": "Sender addresses, notifications, and the logo embedded in transactional emails.","title": "Email settings","branding": {diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 2f0a3bc763..3c7fcce5d0 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -467,7 +467,6 @@"logo_dimensions_help": "Recomendado: 204×104 píxeles.","section_addresses": "Direcciones de email","section_delivery": "Entrega",- "section_logo": "Logo","subtitle": "Direcciones de remitente, notificaciones y el logo incorporado en los emails transaccionales.","title": "Configuración de email","branding": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex e747104c26..bc542124ff 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -3822,7 +3822,6 @@"logo_dimensions_help": "Recommandé : 204 × 104 pixels.","section_addresses": "Adresses e-mail","section_delivery": "Distribution",- "section_logo": "Logo","subtitle": "Adresses d'expéditeur, notifications et logo intégré aux e-mails transactionnels.","title": "Paramètres d'e-mail","branding": {diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 0aab6635ce..0d660389c9 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -3870,7 +3870,6 @@"logo_dimensions_help": "Zalecane: 204×104 piksele.","section_addresses": "Adresy e-mail","section_delivery": "Dostarczanie",- "section_logo": "Logo","subtitle": "Adresy nadawców, powiadomienia i logo umieszczane w e-mailach transakcyjnych.","title": "Ustawienia e-mail","branding": {diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex f70f1e5ba0..a50e30a5ef 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -3812,7 +3812,6 @@"logo_dimensions_help": "推荐:204×104 像素。","section_addresses": "邮件地址","section_delivery": "发送",- "section_logo": "徽标","subtitle": "发件人地址、通知,以及嵌入在交易邮件中的徽标。","title": "邮件设置","branding": {diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsxindex 26ce297a46..529822e934 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/emails/index.tsx@@ -277,16 +277,7 @@ function EmailSettingsForm({ store }: { store: Store }) {</CardContent></Card>- <Card>- <CardHeader>- <CardTitle>{t('admin.pages.settings.emails.section_logo')}</CardTitle>- </CardHeader>- <CardContent>- <LogoField form={form} initialLogoUrl={store.mailer_logo_url} />- </CardContent>- </Card>-- <BrandingCard form={form} />+ <BrandingCard form={form} logoUrl={store.mailer_logo_url} /></>)}</>@@ -328,7 +319,13 @@ function LogoField({)}-function BrandingCard({ form }: { form: ReturnType<typeof useForm<StoreEmailsFormValues>> }) {+function BrandingCard({+ form,+ logoUrl,+}: {+ form: ReturnType<typeof useForm<StoreEmailsFormValues>>+ logoUrl: string | null+}) {const { t } = useTranslation()const { permissions } = usePermissions()const { errors } = form.formState@@ -345,6 +342,7 @@ function BrandingCard({ form }: { form: ReturnType<typeof useForm<StoreEmailsFor</CardHeader><CardContent className="grid gap-6 lg:grid-cols-2"><FieldGroup>+ <LogoField form={form} initialLogoUrl={logoUrl} />{EMAIL_BRANDING_COLORS.map((color) => {const name = `email_${color}` as constreturn (@@ -407,7 +405,7 @@ function BrandingCard({ form }: { form: ReturnType<typeof useForm<StoreEmailsForfunction BrandingPreview({ form }: { form: ReturnType<typeof useForm<StoreEmailsFormValues>> }) {const { t } = useTranslation()const preview = useEmailTemplatePreview(BRANDING_PREVIEW_TEMPLATE)- const [accent, background, card, text, heading, font] = useWatch({+ const [accent, background, card, text, heading, font, logoSignedId, logoCleared] = useWatch({control: form.control,name: ['email_accent_color',@@ -416,24 +414,31 @@ function BrandingPreview({ form }: { form: ReturnType<typeof useForm<StoreEmails'email_text_color','email_heading_color','email_font',+ 'mailer_logo_signed_id',+ 'mailer_logo_cleared',],})- const branding = useDebouncedValue(+ // Saving resets the logo fields, which changes the params and re-renders+ // the preview with the logo the store now has.+ const params = useDebouncedValue(JSON.stringify({- accent_color: accent,- background_color: background,- card_color: card,- text_color: text,- heading_color: heading,- font,+ branding: {+ accent_color: accent,+ background_color: background,+ card_color: card,+ text_color: text,+ heading_color: heading,+ font,+ },+ ...signedIdParam('mailer_logo', logoSignedId, logoCleared),}),PREVIEW_DELAY_MS,)const { mutate } = previewuseEffect(() => {- mutate({ branding: JSON.parse(branding) })- }, [branding, mutate])+ mutate(JSON.parse(params))+ }, [params, mutate])// No customer emails installed, so there is nothing to preview.if (preview.error instanceof SpreeError && preview.error.status === 404) return nulldiff --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 9f8e5a67d2..c4716bfcae 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@@ -60,12 +60,17 @@ module Spree# An unsaved subject and body are previewed only when sent, so an# empty body still previews as empty. `branding` previews unsaved- # colors and font.+ # colors and font, `mailer_logo_signed_id` an unsaved logo (null+ # removes it, as it does when saving the store).def preview_argumentsarguments = params.permit(:record_id, :subject, :body).to_h.symbolize_keysarguments[:locale] = languagearguments[:email_key] = params[:email_key].to_s.tr('.', '/').presencearguments[:branding] = params.fetch(:branding, {}).permit(*Spree::Emails::Branding.attribute_names).to_h+ if params.key?(:mailer_logo_signed_id)+ signed_id = params[:mailer_logo_signed_id].presence&.to_s+ arguments.merge!(mailer_logo_signed_id: signed_id, mailer_logo_cleared: signed_id.nil?)+ endargumentsenddiff --git a/spree/api/app/request_schemas/spree/api/v3/admin/email_template_preview_request_schema.rb b/spree/api/app/request_schemas/spree/api/v3/admin/email_template_preview_request_schema.rbindex 030d14b49b..03771ac9dc 100644--- a/spree/api/app/request_schemas/spree/api/v3/admin/email_template_preview_request_schema.rb+++ b/spree/api/app/request_schemas/spree/api/v3/admin/email_template_preview_request_schema.rb@@ -25,6 +25,10 @@ module SpreeSpree::Emails::Branding::COLORS.each { |name| branding.attribute name, :string, nullable: true }branding.attribute :font, :string, nullable: true, choices: Spree::Emails::Branding::FONTS.keysend+ attribute :mailer_logo_signed_id, :string,+ nullable: true,+ permit: false,+ description: 'An unsaved email logo: the signed id of an uploaded image, or null to preview without one.'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 05c8190b88..7faed789e7 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,21 @@ RSpec.describe Spree::Api::V3::Admin::EmailTemplates::PreviewsController, type:expect(store.reload.preferred_email_card_color).to be_nilend+ it 'previews an unsaved logo' do+ blob = ActiveStorage::Blob.create_and_upload!(io: File.open(Spree::Core::Engine.root.join('spec/fixtures/files/icon_256x256.png')),+ filename: 'unsaved-logo.png')++ post :create, params: { email_template_id: id, mailer_logo_signed_id: blob.signed_id }, as: :json++ expect(json_response['variables']['store']['logo_url']).to include('unsaved-logo')+ end++ it 'says so when the unsaved logo is not a valid upload' do+ post :create, params: { email_template_id: id, mailer_logo_signed_id: 'tampered' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+context 'when the sample shows records the caller may not read' dolet(:headers) { { 'x-spree-api-key' => create(:api_key, :secret, store: store, scopes: scopes).plaintext_token } }diff --git a/spree/core/app/mailers/spree/email_template_mailer.rb b/spree/core/app/mailers/spree/email_template_mailer.rbindex b19b21db7d..0e3d8947da 100644--- a/spree/core/app/mailers/spree/email_template_mailer.rb+++ b/spree/core/app/mailers/spree/email_template_mailer.rb@@ -11,11 +11,14 @@ module Spree# @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# @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: {})+ # @param mailer_logo_signed_id [String, nil] the signed id of an unsaved, uploaded email logo+ # @param mailer_logo_cleared [Boolean] whether the email logo is sent as removed+ def test_email(store, recipient, key, locale: nil, subject: nil, body: nil, record_id: nil, email_key: nil, branding: {},+ mailer_logo_signed_id: nil, mailer_logo_cleared: false)@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,- branding: branding+ branding: branding, mailer_logo_signed_id: mailer_logo_signed_id, mailer_logo_cleared: mailer_logo_cleared).callmail(to: recipient, subject: I18n.t('spree.email_templates.test_email_subject', subject: email.subject)) do |format|diff --git a/spree/core/app/services/spree/email_templates/preview.rb b/spree/core/app/services/spree/email_templates/preview.rbindex 9bba4373f2..187ce8ba85 100644--- a/spree/core/app/services/spree/email_templates/preview.rb+++ b/spree/core/app/services/spree/email_templates/preview.rb@@ -23,8 +23,11 @@ module Spree# @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# @param branding [Hash] unsaved branding values (see Spree::Emails::Branding)+ # @param mailer_logo_signed_id [String, nil] the signed id of an unsaved, uploaded email logo+ # @param mailer_logo_cleared [Boolean] whether the email logo is previewed as removeddef initialize(store:, key:, locale: Spree::EmailTemplate::ANY_LOCALE, subject: nil, body: nil,- record_id: nil, email_key: nil, strict: false, branding: {})+ record_id: nil, email_key: nil, strict: false, branding: {}, mailer_logo_signed_id: nil,+ mailer_logo_cleared: false)@store = store@key = key@locale = locale.presence || Spree::EmailTemplate::ANY_LOCALE@@ -34,16 +37,20 @@ module Spree@email_key = email_key@strict = strict@branding = branding+ @mailer_logo_signed_id = mailer_logo_signed_id+ @mailer_logo_cleared = mailer_logo_clearedend# @return [Spree::Emails::RenderedEmail]# @raise [Spree::EmailTemplates::NoSampleRecord] when the store has no record to build the sample from+ # @raise [ActiveRecord::RecordInvalid] when the unsaved logo is one saving the store would refuse+ # @raise [ActiveSupport::MessageVerifier::InvalidSignature] when the unsaved logo's signed id is not validdef callsample = 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,- branding: @branding)+ renderer = Spree::Emails::Renderer.new(resolver: resolver, store: email_store, currency: sample.currency,+ strict: @strict, branding: @branding)sample_variables = sample.variables@variables = renderer.variables(sample_variables)@rendered = renderer.render(resolver.find(email.key), sample_variables)@@ -66,6 +73,20 @@ module SpreeSpree.editable_email_templates[@key] || raise(ArgumentError, "#{@key} is not an editable email template")end+ # The store as the email shows it. An unsaved logo upload or removal is+ # applied to a copy that is never saved, and checked as saving the store+ # checks it, so the preview never shows a logo the Save button refuses.+ def email_store+ return @store if @mailer_logo_signed_id.nil? && !@mailer_logo_cleared++ @email_store ||= @store.class.find(@store.id).tap do |store|+ store.mailer_logo = @mailer_logo_cleared ? nil : @mailer_logo_signed_id+ store.validate+ (store.errors.attribute_names - [:mailer_logo]).each { |attribute| store.errors.delete(attribute) }+ raise ActiveRecord::RecordInvalid, store if store.errors.any?+ end+ end+def resolver@resolver ||= Spree::Emails::TemplateResolver.for_mailers(store: @store, locale: language, drafts: drafts)enddiff --git a/spree/core/spec/services/spree/email_templates/preview_spec.rb b/spree/core/spec/services/spree/email_templates/preview_spec.rbindex e15d6148fe..7e99d3b34d 100644--- a/spree/core/spec/services/spree/email_templates/preview_spec.rb+++ b/spree/core/spec/services/spree/email_templates/preview_spec.rb@@ -37,4 +37,34 @@ describe Spree::EmailTemplates::Preview doexpect(email.subject).to eq('Only the subject changed')expect(email.html).to include(store.name)end++ describe 'an unsaved logo' do+ let(:blob) { ActiveStorage::Blob.create_and_upload!(io: File.open(file_fixture('icon_256x256.png')), filename: 'unsaved-logo.png') }++ it 'shows an uploaded logo the store does not have yet' do+ preview = described_class.new(store: store, key: editable_key, mailer_logo_signed_id: blob.signed_id)+ preview.call++ expect(preview.variables['store']['logo_url']).to include('unsaved-logo')+ expect(store.reload.mailer_logo).not_to be_attached+ end++ it 'shows the email without the logo once it is removed' do+ store = create(:store)+ store.mailer_logo.attach(blob)+ preview = described_class.new(store: store, key: editable_key, mailer_logo_cleared: true)+ preview.call++ expect(preview.variables['store']['logo_url']).to be_nil+ expect(store.reload.mailer_logo).to be_attached+ end++ it 'refuses a file saving the store would refuse' do+ document = ActiveStorage::Blob.create_and_upload!(io: StringIO.new('%PDF-1.4'), filename: 'logo.pdf',+ content_type: 'application/pdf')++ expect { described_class.new(store: store, key: editable_key, mailer_logo_signed_id: document.signed_id).call }.+ to raise_error(ActiveRecord::RecordInvalid)+ end+ endend