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
Add ability to download import template / example CSV in admin UI (#14364)
Damian Legawiec99750688a69e
diff --git a/.changeset/import-sheet-example-csv.md b/.changeset/import-sheet-example-csv.mdindex 56af2865c5..2adfbf2685 100644--- a/.changeset/import-sheet-example-csv.md+++ b/.changeset/import-sheet-example-csv.md@@ -2,4 +2,4 @@"@spree/dashboard-core": patch----The CSV import sheet now links to a downloadable example file alongside the existing (headers-only) template, so you can see a populated CSV before preparing your own — or import it as-is. The examples are Spree's own sample data, the same files `rake spree:load_sample_data` uses, so they always match the current import schema. Import types with no example file simply omit the link.+The CSV import sheet now offers a downloadable example file alongside the existing (headers-only) template, so you can see a populated CSV before preparing your own — or import it as-is. The examples are Spree's own sample data, the same files `rake spree:load_sample_data` uses, served through `GET /api/v3/admin/imports/example` and pinned to the installed Spree version so they always match your import schema. Import types with no example file simply omit the link.diff --git a/packages/dashboard-core/src/components/import-button.tsx b/packages/dashboard-core/src/components/import-button.tsxindex 78940a06bc..9ca2de79e5 100644--- a/packages/dashboard-core/src/components/import-button.tsx+++ b/packages/dashboard-core/src/components/import-button.tsx@@ -19,9 +19,13 @@ import { DownloadIcon, FileSpreadsheetIcon, UploadIcon } from 'lucide-react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'-import { useCreateImport, useDownloadImportTemplate } from '../hooks/use-import'+import {+ useCreateImport,+ useDownloadImportExample,+ useDownloadImportTemplate,+} from '../hooks/use-import'import type { SubjectName } from '../lib/permissions'-import { sampleCsvUrl } from '../lib/sample-csv'+import { hasSampleCsv } from '../lib/sample-csv'import { Can } from './can'import { EMPTY_FILE_UPLOAD_VALUE, FileUploadField, type FileUploadValue } from './file-upload-field'@@ -66,7 +70,8 @@ export function ImportButton({ type, subject, onCreated, label }: ImportButtonPrconst [delimiter, setDelimiter] = useState<Delimiter>(',')const createImport = useCreateImport()const downloadTemplate = useDownloadImportTemplate()- const exampleUrl = sampleCsvUrl(type)+ const downloadExample = useDownloadImportExample()+ const hasExample = hasSampleCsv(type)const delimiterOptions = DELIMITERS.map(({ value, labelKey }) => ({value,@@ -111,6 +116,18 @@ export function ImportButton({ type, subject, onCreated, label }: ImportButtonPr})}+ function handleExampleDownload() {+ downloadExample.mutate(type, {+ onError: (err) => {+ toast.error(+ t('admin.components.import_button.example_failed', {+ message: err instanceof Error ? err.message : String(err),+ }),+ )+ },+ })+ }+return (<Can I="create" a={subject}><Button@@ -176,13 +193,19 @@ export function ImportButton({ type, subject, onCreated, label }: ImportButtonPr{t('admin.components.import_button.download_template')}</Button>- {/* The populated counterpart to the headers-only template above. */}- {exampleUrl && (- <Button type="button" variant="ghost" size="sm" asChild>- <a href={exampleUrl} target="_blank" rel="noopener noreferrer">- <FileSpreadsheetIcon className="size-4" />- {t('admin.components.import_button.download_example')}- </a>+ {/* The populated counterpart to the headers-only template above.+ Fetched through the API so the file matches the installed+ Spree version's schema. */}+ {hasExample && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={handleExampleDownload}+ disabled={downloadExample.isPending}+ >+ <FileSpreadsheetIcon className="size-4" />+ {t('admin.components.import_button.download_example')}</Button>)}</div>diff --git a/packages/dashboard-core/src/hooks/use-import.ts b/packages/dashboard-core/src/hooks/use-import.tsindex 46dafb87f4..62990cbef2 100644--- a/packages/dashboard-core/src/hooks/use-import.ts+++ b/packages/dashboard-core/src/hooks/use-import.ts@@ -47,6 +47,28 @@ export function useDownloadImportTemplate() {})}+/**+ * Downloads the populated example CSV for an import type.+ *+ * Goes through the API rather than linking the file directly: the URL is pinned+ * to the installed Spree version so a released install never links to a newer,+ * incompatible schema — and that version is deliberately not exposed over the+ * API, since it would fingerprint the deployment. Returns 404 for a type that+ * ships no example file.+ */+export function useDownloadImportExample() {+ const { token } = useAuth()++ return useMutation({+ mutationFn: (type: ImportType) =>+ downloadFromApi(+ token,+ `/api/v3/admin/imports/example?type=${encodeURIComponent(type)}`,+ `${type}.csv`,+ ),+ })+}+/** Downloads the originally uploaded CSV of an import — the audit trail. */export function useDownloadImportOriginal() {const { token } = useAuth()diff --git a/packages/dashboard-core/src/lib/sample-csv.ts b/packages/dashboard-core/src/lib/sample-csv.tsindex cc572bed47..58af073b47 100644--- a/packages/dashboard-core/src/lib/sample-csv.ts+++ b/packages/dashboard-core/src/lib/sample-csv.ts@@ -1,23 +1,18 @@import type { ImportType } from '@spree/admin-sdk'/**- * Example CSVs published from Spree's `core/db/sample_data`. These are the same- * files `rake spree:load_sample_data` feeds through the import pipeline, so they- * are working examples rather than hand-written samples that drift from the- * schema.+ * Import types that ship a populated example CSV in Spree's+ * `core/db/sample_data`. Keyed by the API's type shorthand (`"products"`),+ * which is also the CSV's filename stem.*- * Keyed by the API's type shorthand (`"products"`), which is also the CSV's- * filename stem — so this is just the set of types that have an example file.+ * Only used to decide whether to render the download link — the file itself is+ * served by `GET /api/v3/admin/imports/example`, which pins the URL to the+ * installed Spree version. A type missing from this list simply hides the link;+ * the endpoint is the authority and 404s for anything it has no example for.*/const TYPES_WITH_SAMPLE_CSV = new Set(['products', 'customers', 'product_translations'])-const SAMPLE_CSV_BASE_URL =- 'https://raw.githubusercontent.com/spree/spree/refs/heads/main/spree/core/db/sample_data'--/**- * Public URL of the example CSV for an import type, or `null` for a type that- * has no sample file — callers omit the link rather than render a 404.- */-export function sampleCsvUrl(type: ImportType): string | null {- return TYPES_WITH_SAMPLE_CSV.has(type) ? `${SAMPLE_CSV_BASE_URL}/${type}.csv` : null+/** Whether an import type has an example CSV to offer. */+export function hasSampleCsv(type: ImportType): boolean {+ return TYPES_WITH_SAMPLE_CSV.has(type)}diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.jsonindex 370bb4693e..c83f0c7469 100644--- a/packages/dashboard-core/src/locales/en.json+++ b/packages/dashboard-core/src/locales/en.json@@ -493,6 +493,7 @@"download_template": "Download CSV template","download_example": "Download an example CSV","template_failed": "Template download failed: {{message}}",+ "example_failed": "Example download failed: {{message}}","submit": "Continue","failed": "Import failed: {{message}}"},diff --git a/spree/admin/app/views/spree/admin/imports/new.html.erb b/spree/admin/app/views/spree/admin/imports/new.html.erbindex 19b0b3db18..eb908769c2 100644--- a/spree/admin/app/views/spree/admin/imports/new.html.erb+++ b/spree/admin/app/views/spree/admin/imports/new.html.erb@@ -16,6 +16,19 @@</div><%= f.spree_select :preferred_delimiter, options_for_select([',', ';', '|', '\t'], @import.preferred_delimiter) %>++ <div class="flex flex-col items-start gap-2 mt-4">+ <%# The schema is one CSV line, so it's inlined rather than fetched. %>+ <%= link_to_with_icon 'download', Spree.t('admin.imports.download_template_csv'),+ "data:text/csv;charset=utf-8,#{ERB::Util.url_encode(@import.template_csv)}",+ download: @import.template_csv_filename, class: 'text-muted' %>++ <%# The populated counterpart to the headers-only template above. %>+ <% if (sample_csv_url = @import.sample_csv_url) %>+ <%= link_to_with_icon 'download', Spree.t('admin.imports.download_example_csv'), sample_csv_url,+ target: '_blank', rel: 'noopener', class: 'text-muted' %>+ <% end %>+ </div></div><div class="drawer-footer">diff --git a/spree/admin/config/locales/en.yml b/spree/admin/config/locales/en.ymlindex 466dc56bce..9b48477f43 100644--- a/spree/admin/config/locales/en.yml+++ b/spree/admin/config/locales/en.yml@@ -218,6 +218,8 @@ en:usage: Usageimports:all_required_columns_mapped: Good job, all required columns are mapped!+ download_example_csv: Download an example CSV file+ download_template_csv: Download CSV templatefield_required: Field requiredimport_done: All done!json: JSONdiff --git a/spree/admin/spec/controllers/spree/admin/imports_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/imports_controller_spec.rbindex 280acde090..35aec31a46 100644--- a/spree/admin/spec/controllers/spree/admin/imports_controller_spec.rb+++ b/spree/admin/spec/controllers/spree/admin/imports_controller_spec.rb@@ -29,6 +29,26 @@ RSpec.describe Spree::Admin::ImportsController, type: :controller doexpect(assigns(:import).type).to eq('Spree::Imports::Products')endend++ # The drawer builds a base Spree::Import with `type` assigned, so both+ # links have to resolve from the column rather than the instance's class.+ it 'offers the CSV template and the example file' do+ get :new, params: { type: 'Spree::Imports::Products' }++ expect(response.body).to include('data:text/csv')+ expect(response.body).to include('products_import_template.csv')+ expect(response.body).to include(Spree::Imports::Products.sample_csv_url)+ end++ it 'omits the example link for a type with no sample file' do+ allow_any_instance_of(Spree::Import).to receive(:sample_csv_url).and_return(nil)++ get :new, params: { type: 'Spree::Imports::Products' }++ expect(response.body).not_to include('db/sample_data')+ # The template link is schema-derived, so it is always available.+ expect(response.body).to include('products_import_template.csv')+ endenddescribe 'POST #create' dodiff --git a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rbindex c1a16fc552..3de981722d 100644--- a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb@@ -150,13 +150,37 @@ module Spree)end- headers = klass.new.schema_fields.map { |field| field[:name] }- send_data ::CSV.generate_line(headers),- filename: "#{klass.name.demodulize.underscore}_import_template.csv",+ import = klass.new+ send_data import.template_csv,+ filename: import.template_csv_filename,type: 'text/csv',disposition: 'attachment'end+ # GET /api/v3/admin/imports/example?type=products+ #+ # Redirects to the populated example CSV for the type — the counterpart+ # to `template` above. 404s for a type that ships no example file.+ #+ # The client can't build this URL itself: it is pinned to the+ # installed Spree version, and exposing that version over the API+ # would fingerprint the deployment for anyone matching CVEs. Resolving+ # it here keeps the version server-side.+ def example+ klass = resolve_import_type(params[:type])+ url = klass&.sample_csv_url++ unless url+ return render_error(+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:record_not_found],+ message: 'No example CSV for this import type',+ status: :not_found+ )+ end++ redirect_to url, allow_other_host: true, status: :found+ end+protecteddef model_class@@ -245,7 +269,7 @@ module Spreedef import_classcase action_name- when 'create', 'template' then resolve_import_type(params[:type])+ when 'create', 'template', 'example' then resolve_import_type(params[:type])else find_resource.classendenddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 71ae6e96e5..9b9620800e 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -205,6 +205,7 @@ Spree::Core::Engine.add_routes doresources :imports, only: [:index, :show, :create, :destroy] docollection doget :template+ get :exampleendmember dopatch :complete_mappingdiff --git a/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rbindex bf8b6e403c..2876cde2a6 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/imports_controller_spec.rb@@ -330,6 +330,38 @@ RSpec.describe Spree::Api::V3::Admin::ImportsController, type: :controller doendend+ describe 'GET #example' do+ # Redirected rather than linked client-side: the URL is pinned to the+ # installed Spree version, which only the server knows.+ it 'redirects to the example CSV for the installed version' do+ get :example, params: { type: 'products' }++ expect(response).to have_http_status(:found)+ expect(response.location).to eq(Spree::Imports::Products.sample_csv_url)+ expect(response.location).to include("v#{Spree.version}")+ end++ it 'accepts the fully-qualified class name' do+ get :example, params: { type: 'Spree::Imports::Products' }++ expect(response).to redirect_to(Spree::Imports::Products.sample_csv_url)+ end++ it 'returns 404 for a type with no example file' do+ allow(Spree::Imports::Products).to receive(:sample_csv_url).and_return(nil)++ get :example, params: { type: 'products' }++ expect(response).to have_http_status(:not_found)+ end++ it 'returns 404 for an unknown type' do+ get :example, params: { type: 'Spree::User' }++ expect(response).to have_http_status(:not_found)+ end+ end+describe 'DELETE #destroy' doit 'deletes a completed import' doproduct_import.update_columns(status: 'completed')diff --git a/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rbindex 47be5bc45c..df46337bba 100644--- a/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rb+++ b/spree/api/spec/integration/spree/api/v3/admin/imports_spec.rb@@ -148,6 +148,31 @@ RSpec.describe 'Admin Imports API', type: :request, swagger_doc: 'api-reference/endend+ path '/api/v3/admin/imports/example' do+ get 'Download an example import file' do+ tags 'Imports'+ security [api_key: [], bearer_auth: []]+ description 'Redirects to a populated example CSV for the given import type — the same ' \+ 'sample data `rake spree:load_sample_data` uses, pinned to the installed ' \+ 'Spree version. Returns 404 for a type that ships no example file.'+ admin_scope_note 'the write scope of the imported resource — `write_products` for product imports, `write_customers` for customer imports, etc.'++ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true+ parameter name: :Authorization, in: :header, type: :string, required: true+ parameter name: :type, in: :query, type: :string, required: true,+ description: 'Registered import type, e.g. products.'++ response '302', 'Redirect to the example CSV' do+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }+ let(:type) { 'products' }++ run_test! do |response|+ expect(response.headers['Location']).to include('sample_data/products.csv')+ end+ end+ end+ end+path '/api/v3/admin/imports/{id}' dolet(:id) { product_import.prefixed_id }diff --git a/spree/core/app/models/spree/import.rb b/spree/core/app/models/spree/import.rbindex 411c89e07b..4e6071f392 100644--- a/spree/core/app/models/spree/import.rb+++ b/spree/core/app/models/spree/import.rb@@ -7,6 +7,15 @@ module Spreeinclude Spree::NumberIdentifierinclude Spree::Core::NumberGenerator.new(prefix: 'IM')+ # Where the downloadable example CSVs are served from — see `sample_csv_url`.+ #+ # Pinned to the installed version's tag rather than `main`: whether a type+ # *has* an example is answered by the local `db/sample_data`, so pointing+ # elsewhere would let a released install link to a newer, incompatible+ # schema (or a file that has since been removed).+ SAMPLE_DATA_BASE_URL_TEMPLATE =+ 'https://raw.githubusercontent.com/spree/spree/refs/tags/v%<version>s/spree/core/db/sample_data'.freeze+publishes_lifecycle_events# Set event prefix for all Import subclasses@@ -93,6 +102,33 @@ module Spree# links back to it. Blank for legacy-admin or app-created imports.preference :results_url, :string, default: nil+ # Publicly downloadable example CSV for this import's type, or nil when the+ # type has no sample file. Resolved from the `type` column rather than the+ # instance's class, so it works on a record built as the base+ # `Spree::Import` with `type` assigned (which is how the admin's new-import+ # form builds it).+ #+ # @return [String, nil]+ def sample_csv_url+ self.class.available_types.find { |klass| klass.to_s == type.to_s }&.sample_csv_url+ end++ # Header-only CSV for this import's schema — the blank counterpart to+ # `sample_csv_url`. One line, so callers can inline it (e.g. as a `data:`+ # URI) instead of round-tripping to the server for it.+ #+ # @return [String]+ def template_csv+ ::CSV.generate_line(schema_fields.map { |field| field[:name] })+ end++ # Suggested filename for `template_csv`, e.g. "products_import_template.csv".+ #+ # @return [String]+ def template_csv_filename+ "#{self.class.api_type_for(type)}_import_template.csv"+ end+# Returns true if the import has more rows than the large import threshold.# Large imports skip per-row UI broadcasts and use bulk processing.# @return [Boolean]@@ -360,6 +396,36 @@ module Spreeto_s.demodulize.underscore.to_symend+ # Publicly downloadable example CSV for this import type — the same file+ # `rake spree:load_sample_data` feeds through this very pipeline, so it is+ # a working example rather than a hand-maintained sample that can drift+ # from the schema.+ #+ # Whether a type *has* an example is answered by `db/sample_data` itself,+ # so adding or removing a CSV there needs no change here; a type with no+ # sample file returns nil and the UI omits the link. The URL is pinned to+ # the installed version's tag so the file served always matches the schema+ # that check was made against.+ #+ # @return [String, nil]+ def sample_csv_url+ return nil if self == Spree::Import+ return nil unless Spree::Core::Engine.root.join('db', 'sample_data', sample_csv_filename).exist?++ [sample_data_base_url, sample_csv_filename].join('/')+ end++ # @return [String]+ def sample_data_base_url+ format(SAMPLE_DATA_BASE_URL_TEMPLATE, version: Spree.version)+ end++ # eg. Spree::Imports::ProductTranslations => "product_translations.csv"+ # @return [String]+ def sample_csv_filename+ "#{api_type}.csv"+ end+# eg. Spree::Imports::Orders => Spree::Orderdef model_classreturn Spree.user_class if to_s == 'Spree::Imports::Customers'diff --git a/spree/core/spec/models/spree/import_spec.rb b/spree/core/spec/models/spree/import_spec.rbindex 523f3ec84d..19f64b869b 100644--- a/spree/core/spec/models/spree/import_spec.rb+++ b/spree/core/spec/models/spree/import_spec.rb@@ -387,6 +387,68 @@ RSpec.describe Spree::Import, :job, type: :model doendend+ describe '#template_csv' do+ it 'is the schema header row' do+ import = Spree::Imports::Products.new++ expect(import.template_csv.strip.split(',')).to include('slug', 'sku', 'name', 'price')+ expect(import.template_csv.lines.size).to eq(1)+ end++ it 'names the file after the type' do+ expect(Spree::Imports::Products.new.template_csv_filename).to eq('products_import_template.csv')+ end++ # The admin's new-import form builds a base Spree::Import with `type`+ # assigned, so both helpers have to read the column.+ it 'resolves from the type column on a base instance' do+ import = described_class.new(type: 'Spree::Imports::Customers')++ expect(import.template_csv_filename).to eq('customers_import_template.csv')+ expect(import.template_csv.strip.split(',')).to include('email')+ end+ end++ describe '#sample_csv_url' do+ it 'resolves from the type column on a base instance' do+ import = described_class.new(type: 'Spree::Imports::Products')++ expect(import.sample_csv_url).to end_with('/db/sample_data/products.csv')+ end+ end++ describe '.sample_csv_url' do+ it 'points at the example CSV for the type' do+ expect(Spree::Imports::Products.sample_csv_url).to end_with('/db/sample_data/products.csv')+ expect(Spree::Imports::Customers.sample_csv_url).to end_with('/db/sample_data/customers.csv')+ expect(Spree::Imports::ProductTranslations.sample_csv_url).to end_with('/db/sample_data/product_translations.csv')+ end++ # Pinned to the installed version, not `main` — the availability check reads+ # the local db/sample_data, so the served file has to match that schema.+ it 'pins the URL to the installed Spree version' do+ expect(Spree::Imports::Products.sample_csv_url).to eq(+ "https://raw.githubusercontent.com/spree/spree/refs/tags/v#{Spree.version}/spree/core/db/sample_data/products.csv"+ )+ end++ it 'is nil on the base class' do+ expect(described_class.sample_csv_url).to be_nil+ end++ # An import type whose example CSV was never added must not render a link+ # that 404s — the answer comes from db/sample_data, not a hardcoded list.+ it 'is nil for a type with no example file' do+ klass = Class.new(described_class) do+ def self.name+ 'Spree::Imports::Orders'+ end+ end++ expect(klass.sample_csv_url).to be_nil+ end+ end+describe 'custom events', :events dodescribe 'import.completed' dobefore do