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.

Add imports resource to @spree/admin-sdk

Damian Legawiec9ff5d462bffd
diff --git a/packages/admin-sdk/.changeset/csv-imports.md b/packages/admin-sdk/.changeset/csv-imports.md
new file mode 100644
index 0000000000..9384a135f3
--- /dev/null
+++ b/packages/admin-sdk/.changeset/csv-imports.md
@@ -0,0 +1,5 @@
+---
+"@spree/admin-sdk": minor
+---
+
+Add asynchronous CSV imports. `client.imports.create({ type, attachment })` queues an import from a direct-uploaded CSV (pass the `signed_id` from `client.directUploads.create()`); the response is in the `mapping` state and carries the type's `schema_fields`, the file's `csv_headers`, a `sample_row`, and auto-assigned column `mappings`. Adjust mappings if needed and call `client.imports.completeMapping(id, { mappings })` to start background processing, then poll `client.imports.get(id)` — `rows_count`, `completed_rows_count`, and `failed_rows_count` drive progress until the terminal `completed`/`failed` status. Failed rows (with the raw CSV `data` and per-row `validation_errors`) are listed via `client.imports.rows.list(id, { status_eq: 'failed' })` and can be re-processed with `client.imports.retryFailedRows(id)`. New `Import`, `ImportRow`, `ImportMapping`, `ImportType`, `ImportCreateParams`, and `ImportCompleteMappingParams` types describe these shapes.
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 925c00104e..23d4727306 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -101,6 +101,8 @@ import type {
GiftCardBatchCreateParams,
GiftCardCreateParams,
GiftCardUpdateParams,
+ ImportCompleteMappingParams,
+ ImportCreateParams,
InvitationAcceptParams,
InvitationCreateParams,
LineItemCreateParams,
@@ -171,6 +173,8 @@ import type {
Fulfillment,
GiftCard,
GiftCardBatch,
+ Import,
+ ImportRow,
Invitation,
LineItem,
Locale,
@@ -1557,6 +1561,66 @@ export class AdminClient {
this.request<void>('DELETE', `/exports/${id}`, options),
}
+ // ============================================
+ // Imports (CSV: products, customers, …)
+ // ============================================
+
+ /**
+ * Queues asynchronous CSV imports and drives the mapping flow. Upload the
+ * file via `directUploads.create()` first, then `create()` the import with
+ * the returned `signed_id` — the response is in the `mapping` state and
+ * carries `schema_fields`, `csv_headers`, a `sample_row` and the
+ * auto-assigned `mappings`. Adjust mappings if needed and call
+ * `completeMapping(id)` to start processing, then poll `get(id)` while
+ * `status` is `completed_mapping`/`processing` (`completed`/`failed` are
+ * terminal). Failed rows are listed via `rows.list(id, { q: { status_eq:
+ * 'failed' } })` and can be re-processed with `retryFailedRows(id)`.
+ */
+ readonly imports = {
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Import>> =>
+ this.request<PaginatedResponse<Import>>('GET', '/imports', {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+
+ get: (id: string, options?: RequestOptions): Promise<Import> =>
+ this.request<Import>('GET', `/imports/${id}`, options),
+
+ create: (params: ImportCreateParams, options?: RequestOptions): Promise<Import> =>
+ this.request<Import>('POST', '/imports', { ...options, body: params }),
+
+ completeMapping: (
+ id: string,
+ params?: ImportCompleteMappingParams,
+ options?: RequestOptions,
+ ): Promise<Import> =>
+ this.request<Import>('PATCH', `/imports/${id}/complete_mapping`, {
+ ...options,
+ body: params ?? {},
+ }),
+
+ retryFailedRows: (id: string, options?: RequestOptions): Promise<Import> =>
+ this.request<Import>('PATCH', `/imports/${id}/retry_failed_rows`, options),
+
+ delete: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/imports/${id}`, options),
+
+ rows: {
+ list: (
+ importId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<ImportRow>> =>
+ this.request<PaginatedResponse<ImportRow>>('GET', `/imports/${importId}/rows`, {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ }),
+ },
+ }
+
// ============================================
// Customers
// ============================================
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index bd2a0e0240..071e497617 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -1105,6 +1105,39 @@ export interface ExportCreateParams {
record_selection?: 'filtered' | 'all'
}
+export type ImportType =
+ | 'Spree::Imports::Products'
+ | 'Spree::Imports::Customers'
+ | 'Spree::Imports::ProductTranslations'
+ | (string & {})
+
+export interface ImportCreateParams {
+ /** Which dataset to import. Server validates against `Spree::Import.available_types`. */
+ type: ImportType
+ /**
+ * ActiveStorage signed blob id of the uploaded CSV, obtained from
+ * `client.directUploads.create()` (or the `useDirectUpload` hook).
+ */
+ attachment: string
+ /** CSV column separator. Defaults to a comma on the server. */
+ preferred_delimiter?: ',' | ';' | '|' | '\t'
+}
+
+export interface ImportMappingParam {
+ /** Canonical schema field name (see `Import.schema_fields[].name`). */
+ schema_field: string
+ /** CSV header to read the field from; `null` unmaps the field. */
+ file_column: string | null
+}
+
+export interface ImportCompleteMappingParams {
+ /**
+ * Column assignments to apply before processing starts. Omit to accept
+ * the auto-assigned mappings from the create response.
+ */
+ mappings?: ImportMappingParam[]
+}
+
/**
* Owner type passed to the generic `client.customFields(ownerType, ownerId)`
* escape hatch. The first-class six (products, variants, orders, customers,
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 8f57f54847..adf76ac6ab 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -31,6 +31,9 @@ export type { default as Export } from './generated/Export'
export type { default as Fulfillment } from './generated/Fulfillment'
export type { default as GiftCard } from './generated/GiftCard'
export type { default as GiftCardBatch } from './generated/GiftCardBatch'
+export type { default as Import } from './generated/Import'
+export type { default as ImportMapping } from './generated/ImportMapping'
+export type { default as ImportRow } from './generated/ImportRow'
export type { default as Invitation } from './generated/Invitation'
export type { default as LineItem } from './generated/LineItem'
export type { default as Market } from './generated/Market'
diff --git a/packages/admin-sdk/tests/imports.test.ts b/packages/admin-sdk/tests/imports.test.ts
new file mode 100644
index 0000000000..b0c8bc378b
--- /dev/null
+++ b/packages/admin-sdk/tests/imports.test.ts
@@ -0,0 +1,214 @@
+import { HttpResponse, http } from 'msw'
+import { describe, expect, it } from 'vitest'
+import { API_PREFIX, createTestClient } from './helpers'
+import { server } from './mocks/server'
+
+const sampleImport = {
+ id: 'imp_abc123',
+ number: 'IM000001',
+ type: 'Spree::Imports::Products',
+ status: 'mapping',
+ rows_count: 0,
+ completed_rows_count: 0,
+ failed_rows_count: 0,
+ owner_type: 'Spree::Store',
+ owner_id: 'store_1',
+ user_id: 'usr_admin',
+ processing_errors: null,
+ preferred_delimiter: ',',
+ schema_fields: [
+ { name: 'slug', label: 'Slug', required: true },
+ { name: 'price', label: 'Price', required: true },
+ ],
+ csv_headers: ['Product Handle', 'price'],
+ sample_row: { 'Product Handle': 'widget', price: '10.00' },
+ mappings: [
+ { id: 'immap_1', schema_field: 'slug', file_column: null, required: true },
+ { id: 'immap_2', schema_field: 'price', file_column: 'price', required: true },
+ ],
+ created_at: '2026-07-10T12:00:00Z',
+ updated_at: '2026-07-10T12:00:00Z',
+}
+
+describe('imports', () => {
+ describe('list', () => {
+ it('GETs /imports and returns paginated data', async () => {
+ server.use(
+ http.get(`${API_PREFIX}/imports`, () =>
+ HttpResponse.json({
+ data: [sampleImport],
+ meta: { page: 1, limit: 25, count: 1, pages: 1 },
+ }),
+ ),
+ )
+
+ const client = createTestClient()
+ const res = await client.imports.list()
+
+ expect(res.data).toHaveLength(1)
+ expect(res.data[0]?.id).toBe('imp_abc123')
+ })
+
+ it('passes ListParams through transformListParams (q[...] wrapping)', async () => {
+ let url: URL | null = null
+ server.use(
+ http.get(`${API_PREFIX}/imports`, ({ request }) => {
+ url = new URL(request.url)
+ return HttpResponse.json({ data: [], meta: { page: 1, limit: 25, count: 0, pages: 0 } })
+ }),
+ )
+
+ const client = createTestClient()
+ await client.imports.list({ status_eq: 'completed' })
+
+ expect(url!.searchParams.get('q[status_eq]')).toBe('completed')
+ })
+ })
+
+ describe('get', () => {
+ it('GETs /imports/:id', async () => {
+ server.use(
+ http.get(`${API_PREFIX}/imports/imp_abc123`, () =>
+ HttpResponse.json({ ...sampleImport, status: 'processing', rows_count: 100 }),
+ ),
+ )
+
+ const client = createTestClient()
+ const res = await client.imports.get('imp_abc123')
+
+ expect(res.status).toBe('processing')
+ expect(res.rows_count).toBe(100)
+ })
+ })
+
+ describe('create', () => {
+ it('POSTs /imports with type, attachment signed id and delimiter', async () => {
+ let body: unknown = null
+ server.use(
+ http.post(`${API_PREFIX}/imports`, async ({ request }) => {
+ body = await request.json()
+ return HttpResponse.json(sampleImport, { status: 201 })
+ }),
+ )
+
+ const client = createTestClient()
+ const res = await client.imports.create({
+ type: 'Spree::Imports::Products',
+ attachment: 'signed-blob-id',
+ preferred_delimiter: ';',
+ })
+
+ expect(body).toEqual({
+ type: 'Spree::Imports::Products',
+ attachment: 'signed-blob-id',
+ preferred_delimiter: ';',
+ })
+ expect(res.status).toBe('mapping')
+ expect(res.mappings).toHaveLength(2)
+ })
+ })
+
+ describe('completeMapping', () => {
+ it('PATCHes /imports/:id/complete_mapping with submitted mappings', async () => {
+ let body: unknown = null
+ server.use(
+ http.patch(`${API_PREFIX}/imports/imp_abc123/complete_mapping`, async ({ request }) => {
+ body = await request.json()
+ return HttpResponse.json({ ...sampleImport, status: 'completed_mapping' })
+ }),
+ )
+
+ const client = createTestClient()
+ const res = await client.imports.completeMapping('imp_abc123', {
+ mappings: [{ schema_field: 'slug', file_column: 'Product Handle' }],
+ })
+
+ expect(body).toEqual({
+ mappings: [{ schema_field: 'slug', file_column: 'Product Handle' }],
+ })
+ expect(res.status).toBe('completed_mapping')
+ })
+
+ it('sends an empty body when mappings are omitted', async () => {
+ let body: unknown = null
+ server.use(
+ http.patch(`${API_PREFIX}/imports/imp_abc123/complete_mapping`, async ({ request }) => {
+ body = await request.json()
+ return HttpResponse.json({ ...sampleImport, status: 'completed_mapping' })
+ }),
+ )
+
+ const client = createTestClient()
+ await client.imports.completeMapping('imp_abc123')
+
+ expect(body).toEqual({})
+ })
+ })
+
+ describe('retryFailedRows', () => {
+ it('PATCHes /imports/:id/retry_failed_rows', async () => {
+ server.use(
+ http.patch(`${API_PREFIX}/imports/imp_abc123/retry_failed_rows`, () =>
+ HttpResponse.json({ ...sampleImport, status: 'processing' }),
+ ),
+ )
+
+ const client = createTestClient()
+ const res = await client.imports.retryFailedRows('imp_abc123')
+
+ expect(res.status).toBe('processing')
+ })
+ })
+
+ describe('delete', () => {
+ it('DELETEs /imports/:id', async () => {
+ let called = false
+ server.use(
+ http.delete(`${API_PREFIX}/imports/imp_abc123`, () => {
+ called = true
+ return new HttpResponse(null, { status: 204 })
+ }),
+ )
+
+ const client = createTestClient()
+ await client.imports.delete('imp_abc123')
+
+ expect(called).toBe(true)
+ })
+ })
+
+ describe('rows.list', () => {
+ it('GETs /imports/:id/rows with a status filter', async () => {
+ let url: URL | null = null
+ server.use(
+ http.get(`${API_PREFIX}/imports/imp_abc123/rows`, ({ request }) => {
+ url = new URL(request.url)
+ return HttpResponse.json({
+ data: [
+ {
+ id: 'imrow_1',
+ import_id: 'imp_abc123',
+ row_number: 2,
+ status: 'failed',
+ validation_errors: "Price can't be blank",
+ item_type: null,
+ item_id: null,
+ data: { slug: 'widget', price: '' },
+ created_at: '2026-07-10T12:00:00Z',
+ updated_at: '2026-07-10T12:00:00Z',
+ },
+ ],
+ meta: { page: 1, limit: 25, count: 1, pages: 1 },
+ })
+ }),
+ )
+
+ const client = createTestClient()
+ const res = await client.imports.rows.list('imp_abc123', { status_eq: 'failed' })
+
+ expect(url!.searchParams.get('q[status_eq]')).toBe('failed')
+ expect(res.data[0]?.validation_errors).toBe("Price can't be blank")
+ expect(res.data[0]?.data).toEqual({ slug: 'widget', price: '' })
+ })
+ })
+})