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.

Added listing the records an email template can be previewed with

Damian Legawiec6d30d303f159
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index 79d2f60935..5317b183c4 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -8662,6 +8662,75 @@ paths:
example: any
lock_version:
type: integer
+ "/api/v3/admin/email_templates/{email_template_id}/sample_records":
+ parameters:
+ - name: email_template_id
+ in: path
+ required: true
+ description: The template key with dots
+ schema:
+ type: string
+ get:
+ summary: List records to preview an email template with
+ tags:
+ - Email Templates
+ security:
+ - api_key: []
+ bearer_auth: []
+ description: |-
+ The store's five latest records the template can be previewed with,
+ newest first, to pass as `record_id` to the preview. For the layout
+ and partials, those of the email `email_key` names. Empty for an
+ email that needs no record.
+
+
+ **Required scope:** `write_email_templates` (for API-key authentication).
+ x-codeSamples:
+ - lang: javascript
+ label: Spree Admin SDK
+ source: |-
+ import { createAdminClient } from '@spree/admin-sdk'
+
+ const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+ })
+
+ // The latest orders to preview the order confirmation with; pass one's id as `record_id`.
+ const { data: records } = await client.emailTemplates.sampleRecords.list(
+ 'spree.order_mailer.confirm_email',
+ )
+ - lang: bash
+ label: Spree CLI
+ source: spree api get /email_templates/{email_template_id}/sample_records
+ parameters:
+ - name: x-spree-api-key
+ in: header
+ required: true
+ schema:
+ type: string
+ - name: Authorization
+ in: header
+ required: true
+ description: Bearer token for admin authentication
+ schema:
+ type: string
+ - name: email_key
+ in: query
+ required: false
+ description: For the layout or a partial, the email to show it in
+ schema:
+ type: string
+ responses:
+ '200':
+ description: records found
+ content:
+ application/json:
+ example:
+ data:
+ - id: or_UkLWZg9DAJ
+ label: R1001
+ created_at: '2026-01-15T12:00:00.000Z'
"/api/v3/admin/exports":
get:
summary: List exports
@@ -52361,6 +52430,20 @@ components:
- published_by_id
- published_by_type
x-typelizer: true
+ EmailTemplateSampleRecord:
+ type: object
+ properties:
+ id:
+ type: string
+ label:
+ type: string
+ created_at:
+ type: string
+ required:
+ - id
+ - label
+ - created_at
+ x-typelizer: true
EmailTemplate:
type: object
properties:
diff --git a/packages/admin-sdk/examples/email-templates/sample-records.ts b/packages/admin-sdk/examples/email-templates/sample-records.ts
new file mode 100644
index 0000000000..63112831c9
--- /dev/null
+++ b/packages/admin-sdk/examples/email-templates/sample-records.ts
@@ -0,0 +1,16 @@
+import { createAdminClient } from '@spree/admin-sdk'
+
+const client = createAdminClient({
+ baseUrl: 'https://your-store.com',
+ secretKey: 'sk_xxx',
+})
+
+// region:example
+// The latest orders to preview the order confirmation with; pass one's id as `record_id`.
+const { data: records } = await client.emailTemplates.sampleRecords.list(
+ 'spree.order_mailer.confirm_email',
+)
+
+// endregion:example
+
+export { records }
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 21e16bf888..de1f69e08c 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -436,6 +436,7 @@ import type {
EmailTemplate,
EmailTemplatePreview,
EmailTemplateRevision,
+ EmailTemplateSampleRecord,
Exchange,
Export,
Fee,
@@ -5845,6 +5846,20 @@ export class AdminClient {
body: params ?? {},
}),
+ sampleRecords: {
+ /** The store's latest records the template can be previewed with, newest first. */
+ list: (
+ id: string,
+ params?: { email_key?: string },
+ options?: RequestOptions,
+ ): Promise<{ data: EmailTemplateSampleRecord[] }> =>
+ this.request<{ data: EmailTemplateSampleRecord[] }>(
+ 'GET',
+ `/email_templates/${id}/sample_records`,
+ { ...options, params },
+ ),
+ },
+
revisions: {
/** Published versions in one language, newest first. */
list: (
diff --git a/packages/admin-sdk/src/types/generated/EmailTemplateSampleRecord.ts b/packages/admin-sdk/src/types/generated/EmailTemplateSampleRecord.ts
new file mode 100644
index 0000000000..80d6b3d3f3
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/EmailTemplateSampleRecord.ts
@@ -0,0 +1,11 @@
+// Typelizer digest 2bc055b8b2ae67aa062040fb7c2af07d
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface EmailTemplateSampleRecord {
+ id: string;
+ label: string;
+ created_at: string;
+}
+
+export default EmailTemplateSampleRecord;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index f2f0bf481d..101f2f4dca 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest d58432aa78970c927a25efba27407762
+// Typelizer digest a37f6a551bf2092b8d3381b34993d4a5
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { ActorKind, ClaimStatus, DataRequestStatus, ExchangeStatus, FeeKind, FulfillmentItemStatus, FulfillmentStatus, GiftCardStatus, ImportRowStatus, ImportStatus, InvitationStatus, PaymentStatus, PriceListStatus, ProductStatus, ProductSubmissionStatus, ReturnStatus, SellerPayoutStatus, SellerRequirementSubmissionStatus, SellerStatus, SellerTransferStatus, ShippingLabelStatus, StockLocationKind, TaxExemptionCertificateStatus } from './Enums'
@@ -55,6 +55,7 @@ export type { default as Discount } from './Discount'
export type { default as EmailTemplateDraft } from './EmailTemplateDraft'
export type { default as EmailTemplatePreview } from './EmailTemplatePreview'
export type { default as EmailTemplateRevision } from './EmailTemplateRevision'
+export type { default as EmailTemplateSampleRecord } from './EmailTemplateSampleRecord'
export type { default as EmailTemplate } from './EmailTemplate'
export type { default as ExchangeLineItem } from './ExchangeLineItem'
export type { default as Exchange } from './Exchange'
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index c671c7406b..26c4dace64 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -64,6 +64,7 @@ export type { default as EmailTemplate } from './generated/EmailTemplate'
export type { default as EmailTemplateDraft } from './generated/EmailTemplateDraft'
export type { default as EmailTemplatePreview } from './generated/EmailTemplatePreview'
export type { default as EmailTemplateRevision } from './generated/EmailTemplateRevision'
+export type { default as EmailTemplateSampleRecord } from './generated/EmailTemplateSampleRecord'
// Named enums — open string unions for lists an extension may extend (statuses, fee kinds)
export type * from './generated/Enums'
export type { default as Exchange } from './generated/Exchange'
diff --git a/packages/admin-sdk/src/zod/generated/EmailTemplateSampleRecord.ts b/packages/admin-sdk/src/zod/generated/EmailTemplateSampleRecord.ts
new file mode 100644
index 0000000000..02e7c8f545
--- /dev/null
+++ b/packages/admin-sdk/src/zod/generated/EmailTemplateSampleRecord.ts
@@ -0,0 +1,10 @@
+// This file is auto-generated. Do not edit directly.
+import { z } from 'zod';
+
+export const EmailTemplateSampleRecordSchema = z.object({
+ id: z.string(),
+ label: z.string(),
+ created_at: z.string(),
+});
+
+export type EmailTemplateSampleRecord = z.infer<typeof EmailTemplateSampleRecordSchema>;
diff --git a/packages/admin-sdk/src/zod/generated/index.ts b/packages/admin-sdk/src/zod/generated/index.ts
index e5ef4dd06d..5b807bbf0f 100644
--- a/packages/admin-sdk/src/zod/generated/index.ts
+++ b/packages/admin-sdk/src/zod/generated/index.ts
@@ -53,6 +53,7 @@ export { EmailTemplateSchema, type EmailTemplate } from './EmailTemplate';
export { EmailTemplateDraftSchema, type EmailTemplateDraft } from './EmailTemplateDraft';
export { EmailTemplatePreviewSchema, type EmailTemplatePreview } from './EmailTemplatePreview';
export { EmailTemplateRevisionSchema, type EmailTemplateRevision } from './EmailTemplateRevision';
+export { EmailTemplateSampleRecordSchema, type EmailTemplateSampleRecord } from './EmailTemplateSampleRecord';
export { ExchangeSchema, type Exchange } from './Exchange';
export { ExchangeLineItemSchema, type ExchangeLineItem } from './ExchangeLineItem';
export { ExportSchema, type Export } from './Export';
diff --git a/spree/api/app/controllers/spree/api/v3/admin/email_templates/sample_records_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/email_templates/sample_records_controller.rb
new file mode 100644
index 0000000000..4df6f67885
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/email_templates/sample_records_controller.rb
@@ -0,0 +1,33 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module EmailTemplates
+ class SampleRecordsController < Admin::BaseController
+ include Spree::Api::V3::Admin::EmailTemplateLookup
+
+ before_action :authorize_sample_data!
+
+ # GET /api/v3/admin/email_templates/:email_template_id/sample_records
+ #
+ # The store's five latest records the template can be previewed
+ # with (for the layout and partials, those of the email `email_key`
+ # names). Empty for an email that needs no record.
+ def index
+ authorize! :update, Spree::EmailTemplate
+
+ records = build_preview.email.sample_class.new(store: current_store).recent_records
+ render json: { data: records.map { |record| serializer_class.new(record, params: serializer_params).to_h } }
+ end
+
+ private
+
+ def serializer_class
+ Spree.api.admin_email_template_sample_record_serializer
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/email_template_sample_record_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/email_template_sample_record_serializer.rb
new file mode 100644
index 0000000000..24fa029fdd
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/email_template_sample_record_serializer.rb
@@ -0,0 +1,13 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class EmailTemplateSampleRecordSerializer < V3::BaseSerializer
+ typelize label: :string, created_at: :string
+
+ attributes :label, created_at: :iso8601
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index ca06ed0b6f..ad05846dcb 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -290,6 +290,7 @@ Spree::Core::Engine.add_routes do
resource :publication, only: [:create]
resource :preview, only: [:create]
resource :test_email, only: [:create]
+ resources :sample_records, only: [:index]
resources :revisions, only: [:index], constraints: { id: %r{[^/]+} } do
resource :restoration, only: [:create]
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/email_templates/sample_records_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/sample_records_controller_spec.rb
new file mode 100644
index 0000000000..4010425ec3
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/email_templates/sample_records_controller_spec.rb
@@ -0,0 +1,35 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::EmailTemplates::SampleRecordsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+ include_context 'with an editable email template'
+
+ let(:id) { editable_key.tr('/', '.') }
+
+ before { request.headers.merge!(headers) }
+
+ it "lists the store's latest records to preview with, newest first" do
+ orders = create_list(:order, 6, store: store)
+ create(:order, store: create(:store))
+
+ get :index, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data'].map { |record| record['id'] }).to eq(orders.sort_by(&:created_at).reverse.first(5).map(&:prefixed_id))
+ expect(json_response['data'].first).to include('label', 'created_at')
+ end
+
+ context 'without permission to read the records' do
+ let(:headers) { { 'x-spree-api-key' => create(:api_key, :secret, store: store, scopes: %w[write_email_templates]).plaintext_token } }
+
+ before { allow(Spree::TestingSupport::EmailTemplateSample).to receive(:required_permissions).and_return(%w[read_orders]) }
+
+ it 'is refused' do
+ get :index, params: { email_template_id: id }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
index 41639687bf..72ef40f739 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/email_templates_spec.rb
@@ -375,6 +375,38 @@ RSpec.describe 'Admin Email Templates API', type: :request, swagger_doc: 'api-re
end
end
+ path '/api/v3/admin/email_templates/{email_template_id}/sample_records' do
+ parameter name: :email_template_id, in: :path, type: :string, required: true,
+ description: 'The template key with dots'
+
+ get 'List records to preview an email template with' do
+ tags 'Email Templates'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ The store's five latest records the template can be previewed with,
+ newest first, to pass as `record_id` to the preview. For the layout
+ and partials, those of the email `email_key` names. Empty for an
+ email that needs no record.
+ DESC
+ admin_scope :write, :email_templates
+
+ admin_sdk_example 'email-templates/sample-records'
+
+ include_context 'with admin auth parameters'
+ parameter name: :email_key, in: :query, type: :string, required: false,
+ description: 'For the layout or a partial, the email to show it in'
+
+ response '200', 'records found' do
+ before { create(:order, store: store) }
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['data'].size).to eq(1)
+ end
+ end
+ end
+ end
+
path '/api/v3/admin/email_templates/{email_template_id}/revisions' do
parameter name: :email_template_id, in: :path, type: :string, required: true,
description: 'The template key with dots'
diff --git a/spree/core/app/models/spree/email_templates/sample_record.rb b/spree/core/app/models/spree/email_templates/sample_record.rb
new file mode 100644
index 0000000000..29297e850d
--- /dev/null
+++ b/spree/core/app/models/spree/email_templates/sample_record.rb
@@ -0,0 +1,16 @@
+module Spree
+ module EmailTemplates
+ # A record of the store an email can be previewed with, as the editor's
+ # record picker lists it.
+ class SampleRecord
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :id, :string
+ attribute :label, :string
+ attribute :created_at, :datetime
+
+ alias prefixed_id id
+ end
+ end
+end
diff --git a/spree/core/lib/spree/testing_support/editable_email_templates.rb b/spree/core/lib/spree/testing_support/editable_email_templates.rb
index 779c9f7d85..5cf631f4ec 100644
--- a/spree/core/lib/spree/testing_support/editable_email_templates.rb
+++ b/spree/core/lib/spree/testing_support/editable_email_templates.rb
@@ -21,6 +21,12 @@ module Spree
@store.default_currency
end
+ def recent_records(limit: 5)
+ @store.orders.order(created_at: :desc).limit(limit).map do |order|
+ Spree::EmailTemplates::SampleRecord.new(id: order.prefixed_id, label: order.number, created_at: order.created_at)
+ end
+ end
+
def variables
{
user: { 'first_name' => 'Ann', 'email' => '[email protected]' },
diff --git a/spree/emails/app/services/spree/emails/samples/base.rb b/spree/emails/app/services/spree/emails/samples/base.rb
index d70cb9ae66..a7255a243f 100644
--- a/spree/emails/app/services/spree/emails/samples/base.rb
+++ b/spree/emails/app/services/spree/emails/samples/base.rb
@@ -33,6 +33,19 @@ module Spree
raise NotImplementedError
end
+ # @param limit [Integer]
+ # @return [Array<Spree::EmailTemplates::SampleRecord>] the store's latest
+ # records the email can be previewed with; empty when it needs none
+ def recent_records(limit: 5)
+ return [] unless self.class.record_type
+
+ records.limit(limit).map do |record|
+ Spree::EmailTemplates::SampleRecord.new(
+ id: record.prefixed_id, label: record.try(:number).presence || record.prefixed_id, created_at: record.created_at
+ )
+ end
+ end
+
# @return [String] the currency the email's amounts are in
def currency
(self.class.record_type && record.try(:currency)).presence || store.default_currency
diff --git a/spree/emails/spec/services/spree/emails/samples_spec.rb b/spree/emails/spec/services/spree/emails/samples_spec.rb
index e0750555e3..17b93840f4 100644
--- a/spree/emails/spec/services/spree/emails/samples_spec.rb
+++ b/spree/emails/spec/services/spree/emails/samples_spec.rb
@@ -40,6 +40,13 @@ describe 'editable email samples' do
end.to raise_error(ActiveRecord::RecordNotFound)
end
+ it "offers the store's latest records to pick from, and none for an email that needs no record" do
+ order = create(:completed_order_with_totals, store: store, completed_at: 1.minute.from_now)
+
+ expect(Spree::Emails::Samples::Order.new(store: store).recent_records.first).to have_attributes(id: order.prefixed_id, label: order.number)
+ expect(Spree::Emails::Samples::PasswordReset.new(store: store).recent_records).to eq([])
+ end
+
it 'says so when the store has nothing to preview with' do
Spree::OrderGroup.where(store: store).delete_all