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.

Let a seller export their orders and products as CSV (#14507)

Damian Legawiecb3379158f039
diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yaml
index b1f38858e5..6028dedc8e 100644
--- a/docs/api-reference/seller.yaml
+++ b/docs/api-reference/seller.yaml
@@ -304,7 +304,7 @@ paths:
avatar_url:
sellers:
- id: sel_UkLWZg9DAJ
- name: Seller 13
+ name: Seller 21
status: approved
schema:
"$ref": "#/components/schemas/AuthResponse"
@@ -420,7 +420,7 @@ paths:
avatar_url:
sellers:
- id: sel_UkLWZg9DAJ
- name: Seller 34
+ name: Seller 42
status: approved
schema:
"$ref": "#/components/schemas/AuthResponse"
@@ -489,8 +489,8 @@ paths:
avatar_url:
sellers:
- id: sel_UkLWZg9DAJ
- name: Seller 22
- slug: seller-22
+ name: Seller 30
+ slug: seller-30
status: approved
permissions:
- allow: true
@@ -12730,8 +12730,8 @@ paths:
example:
data:
- id: prod_UkLWZg9DAJ
- name: Product 1303250
- slug: product-1303250
+ name: Product 1363250
+ slug: product-1363250
meta_title:
meta_description:
meta_keywords:
@@ -12970,8 +12970,8 @@ paths:
application/json:
example:
id: prod_UkLWZg9DAJ
- name: Product 1336710
- slug: product-1336710
+ name: Product 1396710
+ slug: product-1396710
meta_title:
meta_description:
meta_keywords:
@@ -13048,7 +13048,7 @@ paths:
example:
id: prod_UkLWZg9DAJ
name: Hand-thrown mug, large
- slug: product-1368212
+ slug: product-1428212
meta_title:
meta_description:
meta_keywords:
@@ -13159,8 +13159,8 @@ paths:
application/json:
example:
id: sel_UkLWZg9DAJ
- name: Seller 49
- slug: seller-49
+ name: Seller 57
+ slug: seller-57
about: ''
about_html: ''
logo_url:
@@ -13237,7 +13237,7 @@ paths:
example:
id: sel_UkLWZg9DAJ
name: Acme Supplies
- slug: seller-51
+ slug: seller-59
about: ''
about_html: ''
logo_url:
@@ -13990,10 +13990,10 @@ paths:
application/json:
example:
direct_upload:
- url: http://www.example.com/rails/active_storage/disk/eyJfcmFpbHMiOnsiZGF0YSI6eyJrZXkiOiJuem5oOGdra3VxendvbDc1ODBxNHNwZmpmMjVxIiwiY29udGVudF90eXBlIjoiYXBwbGljYXRpb24vcGRmIiwiY29udGVudF9sZW5ndGgiOjUxMjM0LCJjaGVja3N1bSI6IlZqaHowNGxRdUVHdXY0bkR2aHNhTlE9PSIsInNlcnZpY2VfbmFtZSI6InRlc3QifSwiZXhwIjoiMjAyNi0wMS0xNVQxMjowNTowMC4wMDBaIiwicHVyIjoiYmxvYl90b2tlbiJ9fQ==--311a89dbec20c3fe56e7a6c41ab308c4c2b97da1
+ url: http://www.example.com/rails/active_storage/disk/eyJfcmFpbHMiOnsiZGF0YSI6eyJrZXkiOiJuem5oOGdra3VxendvbDc1ODBxNHNwZmpmMjVxIiwiY29udGVudF90eXBlIjoiYXBwbGljYXRpb24vcGRmIiwiY29udGVudF9sZW5ndGgiOjUxMjM0LCJjaGVja3N1bSI6IlZqaHowNGxRdUVHdXY0bkR2aHNhTlE9PSIsInNlcnZpY2VfbmFtZSI6InRlc3QifSwiZXhwIjoiMjAyNi0wMS0xNVQxMjowNTowMC4wMDBaIiwicHVyIjoiYmxvYl90b2tlbiJ9fQ==--2a4d3e0e073bd846d1357c13814cf6ff08840d7b
headers:
Content-Type: application/pdf
- signed_id: eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoiYmxvYl9pZCJ9fQ==--b38bec91ebe8d3e7adb4b91a2d3fc6beb8e2be1c
+ signed_id: eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoiYmxvYl9pZCJ9fQ==--b53f9c256f3c52381fe08a385048b9020f2ee9fa
schema:
"$ref": "#/components/schemas/DirectUploadResponse"
requestBody:
@@ -14025,6 +14025,188 @@ paths:
- content_type
required:
- blob
+ "/api/v3/seller/exports":
+ post:
+ summary: Create an export
+ tags:
+ - Exports
+ security:
+ - bearer_auth: []
+ description: |
+ Queues a CSV of this seller's own records.
+
+ Only datasets that can be narrowed to a single seller are offered, so
+ an export can never contain another seller's rows however it is
+ filtered. The seller and the store come from the request context
+ whatever the payload says.
+
+ Generation runs in the background: poll `GET /api/v3/seller/exports/{id}`
+ until `done` is true, then fetch `download_url`.
+ parameters:
+ - name: X-Spree-Seller-Id
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '201':
+ description: export queued
+ content:
+ application/json:
+ example:
+ id: exp_UkLWZg9DAJ
+ number: EF1001
+ format: csv
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ type: orders
+ user_id: adm_UkLWZg9DAJ
+ done: false
+ filename:
+ byte_size:
+ download_url:
+ schema:
+ "$ref": "#/components/schemas/Export"
+ '422':
+ description: type cannot be scoped to one seller
+ content:
+ application/json:
+ example:
+ error:
+ code: validation_error
+ message: 'Unsupported export type. Supported types: orders, products'
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - orders
+ - products
+ description: Which dataset to export.
+ record_selection:
+ type: string
+ enum:
+ - filtered
+ - all
+ description: "`filtered` (default) honours `search_params`; `all`
+ exports everything this seller owns."
+ search_params:
+ type: object
+ description: Ransack predicates, the same shape the list endpoints
+ take. Ignored when `record_selection` is `all`.
+ additionalProperties: true
+ results_url:
+ type: string
+ description: Panel URL the export-done email links back to. Honoured
+ only when it matches one of the store's allowed origins.
+ required:
+ - type
+ "/api/v3/seller/exports/{id}":
+ parameters:
+ - name: id
+ in: path
+ description: Export ID
+ required: true
+ schema:
+ type: string
+ get:
+ summary: Get an export
+ tags:
+ - Exports
+ security:
+ - bearer_auth: []
+ description: |
+ Reads one of this seller's exports. Poll this until `done` is true,
+ then fetch `download_url`.
+ parameters:
+ - name: X-Spree-Seller-Id
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: export found
+ content:
+ application/json:
+ example:
+ id: exp_UkLWZg9DAJ
+ number: EF1001
+ format: csv
+ created_at: '2026-01-15T12:00:00.000Z'
+ updated_at: '2026-01-15T12:00:00.000Z'
+ type: orders
+ user_id: adm_UkLWZg9DAJ
+ done: false
+ filename:
+ byte_size:
+ download_url:
+ schema:
+ "$ref": "#/components/schemas/Export"
+ '404':
+ description: another seller's export
+ content:
+ application/json:
+ example:
+ error:
+ code: record_not_found
+ message: Export not found
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ "/api/v3/seller/exports/{id}/download":
+ parameters:
+ - name: id
+ in: path
+ description: Export ID
+ required: true
+ schema:
+ type: string
+ get:
+ summary: Download an export
+ tags:
+ - Exports
+ security:
+ - bearer_auth: []
+ description: |
+ Streams the finished CSV.
+
+ The bytes are served by this endpoint rather than through a redirect,
+ so the seller's own session authorizes every download.
+ parameters:
+ - name: X-Spree-Seller-Id
+ in: header
+ required: true
+ schema:
+ type: string
+ responses:
+ '422':
+ description: export is still being written
+ content:
+ application/json:
+ example:
+ error:
+ code: export_not_ready
+ message: Export is not ready yet
+ text/csv:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '404':
+ description: another seller's export
+ content:
+ application/json:
+ example:
+ error:
+ code: record_not_found
+ message: Export not found
+ text/csv:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
"/api/v3/seller/orders/{order_id}/fulfillments":
parameters:
- name: order_id
@@ -14075,8 +14257,8 @@ paths:
- id: fi_UkLWZg9DAJ
quantity: 1
line_item_id: li_UkLWZg9DAJ
- name: Product 1239315
- sku: SKU-155
+ name: Product 1299315
+ sku: SKU-161
options_text: ''
schema:
type: object
@@ -14145,8 +14327,8 @@ paths:
- id: fi_UkLWZg9DAJ
quantity: 1
line_item_id: li_UkLWZg9DAJ
- name: Product 124961
- sku: SKU-156
+ name: Product 130961
+ sku: SKU-162
options_text: ''
schema:
"$ref": "#/components/schemas/Fulfillment"
@@ -14246,7 +14428,7 @@ paths:
display_total: "$110.00"
items:
- id: li_UkLWZg9DAJ
- name: Product 12595
+ name: Product 13195
options_text: ''
quantity: 1
currency: USD
@@ -14255,7 +14437,7 @@ paths:
total: '10.0'
display_total: "$10.00"
variant_id: variant_UkLWZg9DAJ
- sku: SKU-157
+ sku: SKU-163
thumbnail_url:
fulfillments:
- id: ful_UkLWZg9DAJ
@@ -14275,8 +14457,8 @@ paths:
- id: fi_UkLWZg9DAJ
quantity: 1
line_item_id: li_UkLWZg9DAJ
- name: Product 12595
- sku: SKU-157
+ name: Product 13195
+ sku: SKU-163
options_text: ''
shipping_address:
id: addr_gbHJdmfrXB
@@ -14284,7 +14466,7 @@ paths:
first_name: John
last_name: Doe
full_name: John Doe
- address1: 105 Lovely Street
+ address1: 117 Lovely Street
address2: Northwest
postal_code: '10118'
city: New York
@@ -14306,7 +14488,7 @@ paths:
first_name: John
last_name: Doe
full_name: John Doe
- address1: 104 Lovely Street
+ address1: 116 Lovely Street
address2: Northwest
postal_code: '10118'
city: New York
@@ -14395,7 +14577,7 @@ paths:
display_total: "$110.00"
items:
- id: li_UkLWZg9DAJ
- name: Product 1269755
+ name: Product 1329755
options_text: ''
quantity: 1
currency: USD
@@ -14404,7 +14586,7 @@ paths:
total: '10.0'
display_total: "$10.00"
variant_id: variant_UkLWZg9DAJ
- sku: SKU-158
+ sku: SKU-164
thumbnail_url:
fulfillments:
- id: ful_UkLWZg9DAJ
@@ -14424,8 +14606,8 @@ paths:
- id: fi_UkLWZg9DAJ
quantity: 1
line_item_id: li_UkLWZg9DAJ
- name: Product 1269755
- sku: SKU-158
+ name: Product 1329755
+ sku: SKU-164
options_text: ''
shipping_address:
id: addr_gbHJdmfrXB
@@ -14433,7 +14615,7 @@ paths:
first_name: John
last_name: Doe
full_name: John Doe
- address1: 107 Lovely Street
+ address1: 119 Lovely Street
address2: Northwest
postal_code: '10118'
city: New York
@@ -14455,7 +14637,7 @@ paths:
first_name: John
last_name: Doe
full_name: John Doe
- address1: 106 Lovely Street
+ address1: 118 Lovely Street
address2: Northwest
postal_code: '10118'
city: New York
@@ -14533,7 +14715,7 @@ paths:
display_total: "$110.00"
items:
- id: li_UkLWZg9DAJ
- name: Product 1296554
+ name: Product 1356554
options_text: ''
quantity: 1
currency: USD
@@ -14542,7 +14724,7 @@ paths:
total: '10.0'
display_total: "$10.00"
variant_id: variant_UkLWZg9DAJ
- sku: SKU-161
+ sku: SKU-167
thumbnail_url:
fulfillments:
- id: ful_UkLWZg9DAJ
@@ -14562,8 +14744,8 @@ paths:
- id: fi_UkLWZg9DAJ
quantity: 1
line_item_id: li_UkLWZg9DAJ
- name: Product 1296554
- sku: SKU-161
+ name: Product 1356554
+ sku: SKU-167
options_text: ''
shipping_address:
id: addr_gbHJdmfrXB
@@ -14571,7 +14753,7 @@ paths:
first_name: John
last_name: Doe
full_name: John Doe
- address1: 113 Lovely Street
+ address1: 125 Lovely Street
address2: Northwest
postal_code: '10118'
city: New York
@@ -14593,7 +14775,7 @@ paths:
first_name: John
last_name: Doe
full_name: John Doe
- address1: 112 Lovely Street
+ address1: 124 Lovely Street
address2: Northwest
postal_code: '10118'
city: New York
@@ -15457,6 +15639,50 @@ components:
- display_compare_at_amount
- price_list_id
x-typelizer: true
+ Export:
+ type: object
+ properties:
+ id:
+ type: string
+ number:
+ type: string
+ format:
+ type: string
+ nullable: true
+ created_at:
+ type: string
+ updated_at:
+ type: string
+ type:
+ type: string
+ nullable: true
+ user_id:
+ type: string
+ nullable: true
+ done:
+ type: boolean
+ filename:
+ type: string
+ nullable: true
+ byte_size:
+ type: number
+ nullable: true
+ download_url:
+ type: string
+ nullable: true
+ required:
+ - id
+ - number
+ - format
+ - created_at
+ - updated_at
+ - type
+ - user_id
+ - done
+ - filename
+ - byte_size
+ - download_url
+ x-typelizer: true
FulfillmentItem:
type: object
properties:
diff --git a/docs/plans/6.1-marketplace-message-relay.md b/docs/plans/6.1-marketplace-message-relay.md
index 57c2fcdc79..53ed9afd3d 100644
--- a/docs/plans/6.1-marketplace-message-relay.md
+++ b/docs/plans/6.1-marketplace-message-relay.md
@@ -144,9 +144,13 @@ would mask nothing, whatever `reply_to` said.
## Constraints on Current Work
-- **Do not add the buyer's email back to any seller-facing serializer.** The
+- **Do not add the buyer's email back to any seller-facing surface.** The
relay is the replacement for it; putting the address back makes the relay
- pointless.
+ pointless. This covers bulk surfaces as much as serializers — a seller's CSV
+ export of their orders omits the `Email` column
+ (`Spree::Exports::Orders#omitted_headers`), since a spreadsheet of every
+ buyer's address is the leak the relay exists to prevent, only larger. A new
+ seller-facing export or report is subject to the same rule.
- **Nothing in fulfillment may require a thread to exist.** Relay is optional
and a seller must be able to ship without it.
- A relay alias is never derived from anything guessable.
diff --git a/packages/dashboard-core/src/api-client.ts b/packages/dashboard-core/src/api-client.ts
index a89dad5110..daf7af6a5e 100644
--- a/packages/dashboard-core/src/api-client.ts
+++ b/packages/dashboard-core/src/api-client.ts
@@ -9,9 +9,9 @@
* builds its own and registers it here at boot.
*
* Only the surface both panels share is typed. Anything admin-only
- * (`customFieldDefinitions`, `exports`, `imports`, store switching) stays on
- * the admin client, imported directly by the code that needs it — typing it
- * here would promise the seller panel methods its API does not have.
+ * (`customFieldDefinitions`, `imports`, store switching) stays on the admin
+ * client, imported directly by the code that needs it — typing it here would
+ * promise the seller panel methods its API does not have.
*/
import type { PermissionRule } from '@spree/admin-sdk'
@@ -146,6 +146,32 @@ export interface PanelApiClient {
deliveryProfiles?: {
list(params?: Record<string, unknown>): Promise<{ data: PanelDeliveryProfile[] }>
}
+ /**
+ * Headers a file download must carry beyond the bearer token.
+ *
+ * A download is a bare `fetch`, not an SDK call, so it bypasses whatever
+ * the client normally attaches — which on the seller panel is
+ * `X-Spree-Seller-Id`, and without it every Seller API request is refused
+ * before the action runs. The admin panel needs none, so it registers none.
+ */
+ downloadHeaders?(): Record<string, string>
+ /**
+ * Queuing a CSV export and reading it back.
+ *
+ * Registered rather than imported for the same reason as everything else
+ * here: the export dialog is one component serving both panels, and
+ * reaching for `adminClient` inside it would make a seller's export request
+ * go out against an API they hold no key for.
+ *
+ * Which datasets may be exported is the API's business, not this
+ * contract's — each panel offers its own list, and the server refuses the
+ * rest. A panel that offers no export simply registers none, and the button
+ * hides.
+ */
+ exports?: {
+ create(params: PanelExportCreateParams): Promise<PanelExport>
+ get(id: string): Promise<PanelExport>
+ }
/** Removing a file already on a product. */
deleteProductMedia?(productId: string, mediaId: string): Promise<void>
/**
@@ -188,6 +214,31 @@ export interface PanelMarket {
default_locale?: string | null
}
+/**
+ * What either panel sends to queue an export.
+ *
+ * `type` stays a plain string: the operator's registry and a seller's
+ * allowlist are different sets, and each SDK narrows it to its own.
+ */
+export interface PanelExportCreateParams {
+ type: string
+ search_params?: Record<string, unknown>
+ record_selection?: 'filtered' | 'all'
+ results_url?: string
+}
+
+/**
+ * An export as the dialog polls it. Structural rather than either SDK's
+ * type — both serializers carry exactly this, and what only one of them adds
+ * is not the dialog's business.
+ */
+export interface PanelExport {
+ id: string
+ done: boolean
+ download_url?: string | null
+ filename?: string | null
+}
+
/** A library file, as the picker lists it. */
export interface PanelMediaRecord {
id: string
diff --git a/packages/dashboard-core/src/components/export-button.tsx b/packages/dashboard-core/src/components/export-button.tsx
index 3d53a05c55..9b4c8c37e4 100644
--- a/packages/dashboard-core/src/components/export-button.tsx
+++ b/packages/dashboard-core/src/components/export-button.tsx
@@ -1,4 +1,3 @@
-import type { ExportType } from '@spree/admin-sdk'
import {
Button,
Dialog,
@@ -25,8 +24,12 @@ import { filtersToRansack } from '../lib/filters-to-ransack'
import type { ResourceActionsContext } from './resource-table'
interface ExportButtonProps extends ResourceActionsContext {
- /** Which dataset to export. Server validates against `Spree::Export.available_types`. */
- type: ExportType
+ /**
+ * Which dataset to export. A plain string rather than either SDK's union:
+ * the operator's registry and a seller's allowlist are different sets, and
+ * the server is what validates the value in both panels.
+ */
+ type: string
/** Label shown on the button. Defaults to the translated "Export" action. */
label?: string
}
@@ -59,6 +62,13 @@ export function ExportButton({
type,
record_selection: selection,
search_params: selection === 'filtered' ? search_params : undefined,
+ // Where the done email sends the user back to, for an export too slow to
+ // wait on. Read off the live location rather than built from a
+ // configured host: a panel may be mounted under a path (`/sellers`,
+ // `/dashboard`) as easily as on a host of its own, and only the page
+ // itself knows which. The store's allowed origins decide whether the
+ // server trusts it.
+ results_url: window.location.href,
})
setOpen(false)
}
diff --git a/packages/dashboard-core/src/hooks/use-export.ts b/packages/dashboard-core/src/hooks/use-export.ts
index bfe09674bd..3e45d265af 100644
--- a/packages/dashboard-core/src/hooks/use-export.ts
+++ b/packages/dashboard-core/src/hooks/use-export.ts
@@ -1,11 +1,30 @@
-import type { Export, ExportCreateParams } from '@spree/admin-sdk'
import { toastManager } from '@spree/dashboard-ui'
import { useMutation } from '@tanstack/react-query'
-import { adminClient } from '../client'
+import { getApiClient, type PanelExport, type PanelExportCreateParams } from '../api-client'
import { downloadFromApi } from '../lib/download'
import { i18n } from '../lib/i18n'
import { useAuth } from './use-auth'
+/**
+ * The registered client's export methods.
+ *
+ * Throws rather than returning undefined: reaching here means a panel rendered
+ * the export dialog without registering the methods behind it, and every call
+ * would otherwise fail further away with a less useful message.
+ */
+function exportsApi() {
+ const api = getApiClient().exports
+
+ if (!api) {
+ throw new Error(
+ '@spree/dashboard-core: this panel registered no `exports` on its API client, so it ' +
+ 'cannot queue an export. Register one, or do not render <ExportButton>.',
+ )
+ }
+
+ return api
+}
+
const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 5 * 60 * 1000
@@ -16,11 +35,11 @@ class ExportTimeoutError extends Error {
}
}
-async function pollUntilDone(id: string): Promise<Export> {
+async function pollUntilDone(id: string): Promise<PanelExport> {
const deadline = Date.now() + POLL_TIMEOUT_MS
while (Date.now() < deadline) {
- const exp = await adminClient.exports.get(id)
+ const exp = await exportsApi().get(id)
if (exp.done) return exp
await new Promise<void>((resolve) => setTimeout(resolve, POLL_INTERVAL_MS))
}
@@ -28,10 +47,15 @@ async function pollUntilDone(id: string): Promise<Export> {
throw new ExportTimeoutError()
}
-async function downloadExportFile(exp: Export, token: string | null): Promise<void> {
+async function downloadExportFile(exp: PanelExport, token: string | null): Promise<void> {
if (!exp.download_url) throw new Error('Export has no download_url')
- await downloadFromApi(token, exp.download_url, exp.filename ?? 'export.csv')
+ await downloadFromApi(
+ token,
+ exp.download_url,
+ exp.filename ?? 'export.csv',
+ getApiClient().downloadHeaders?.() ?? {},
+ )
}
/**
@@ -43,7 +67,7 @@ export function useExport() {
const { token } = useAuth()
return useMutation({
- mutationFn: async (params: ExportCreateParams) => {
+ mutationFn: async (params: PanelExportCreateParams) => {
// Per-invocation id so concurrent exports don't collide on a single
// sticky toast.
const toastId = `export-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
@@ -54,7 +78,7 @@ export function useExport() {
})
try {
- const created = await adminClient.exports.create(params)
+ const created = await exportsApi().create(params)
const finished = await pollUntilDone(created.id)
await downloadExportFile(finished, token)
toastManager.add({
diff --git a/packages/dashboard-core/src/lib/download.ts b/packages/dashboard-core/src/lib/download.ts
index e91c281445..981ff747bb 100644
--- a/packages/dashboard-core/src/lib/download.ts
+++ b/packages/dashboard-core/src/lib/download.ts
@@ -18,15 +18,27 @@ function resolveApiUrl(urlOrPath: string): { url: string; sameOrigin: boolean }
* origin get the `Authorization` header and cookies, so the token can't leak
* to a third-party host (e.g. a URL echoed back by the server). The filename
* comes from `Content-Disposition` when present, else `fallbackName`.
+ *
+ * `extraHeaders` carries whatever else the panel's API needs to identify the
+ * request — the seller panel's `X-Spree-Seller-Id`, without which every Seller
+ * API request is refused before the action runs. Prefer
+ * `useDownloadHeaders()`, which reads them off the registered client.
*/
export async function downloadFromApi(
token: string | null,
urlOrPath: string,
fallbackName: string,
+ extraHeaders: Record<string, string> = {},
): Promise<void> {
const { url, sameOrigin } = resolveApiUrl(urlOrPath)
const headers: Record<string, string> = {}
- if (sameOrigin && token) headers.Authorization = `Bearer ${token}`
+ if (sameOrigin && token) {
+ headers.Authorization = `Bearer ${token}`
+ // Tenant headers ride only to the API origin, for the same reason the
+ // token does — a URL echoed back by the server must not carry them
+ // anywhere else.
+ Object.assign(headers, extraHeaders)
+ }
const response = await fetch(url, {
headers,
diff --git a/packages/dashboard/src/api-client-setup.ts b/packages/dashboard/src/api-client-setup.ts
index 2d1306a5e7..b2a6428d81 100644
--- a/packages/dashboard/src/api-client-setup.ts
+++ b/packages/dashboard/src/api-client-setup.ts
@@ -40,6 +40,14 @@ setApiClient({
list: (params) => adminClient.productTypes.list(params),
get: (id) => adminClient.productTypes.get(id),
},
+ // Backs the shared export dialog. `type` is widened to a string by the
+ // contract, since a seller's allowlist is a different set from the
+ // operator's registry — the API validates it either way.
+ exports: {
+ create: (params) =>
+ adminClient.exports.create(params as Parameters<typeof adminClient.exports.create>[0]),
+ get: (id) => adminClient.exports.get(id),
+ },
taxCategories: { list: (params) => adminClient.taxCategories.list(params) },
deliveryProfiles: { list: (params) => adminClient.deliveryProfiles.list(params) },
deleteProductMedia: (productId, mediaId) => adminClient.products.media.delete(productId, mediaId),
diff --git a/packages/seller-dashboard/src/api-client.ts b/packages/seller-dashboard/src/api-client.ts
index 1ccaa7729b..ebc4c0197a 100644
--- a/packages/seller-dashboard/src/api-client.ts
+++ b/packages/seller-dashboard/src/api-client.ts
@@ -1,5 +1,5 @@
import { setApiClient } from '@spree/dashboard-core'
-import type { SellerApiClient } from '@spree/seller-sdk'
+import type { SellerApiClient, SellerExportCreateParams } from '@spree/seller-sdk'
import { createSellerClient } from '@spree/seller-sdk'
/**
@@ -14,6 +14,18 @@ const SELLER_STORAGE_KEY = 'spree.seller.id'
let client: SellerApiClient | null = null
+/**
+ * The seller the client is currently sending, mirrored here because the SDK
+ * keeps it in a closure with no reader.
+ *
+ * Not the same thing as the stored choice: a browser that blocks storage
+ * (private mode, sandboxed iframe) still runs the panel perfectly well, and
+ * `rememberSeller` sets the client either way. Reading `localStorage` to
+ * answer "who are we acting as" would come back empty in exactly those
+ * sessions and drop the header off every file download.
+ */
+let activeSellerId: string | null = null
+
/**
* Builds the Seller API client and registers it with the shared framework.
*
@@ -34,7 +46,7 @@ export function createSellerApiClient({
client = createSellerClient({ baseUrl })
const remembered = rememberedSeller()
- if (remembered) client.setSeller(remembered)
+ if (remembered) setActiveSeller(remembered)
setApiClient({
auth: client.auth,
@@ -56,6 +68,19 @@ export function createSellerApiClient({
// so it works in a panel that has no admin credential.
listCountries: () => sellerClient().countries.list(),
createDirectUpload: (params) => sellerClient().directUploads.create(params),
+ // A file download is a bare fetch, so it does not go through the client
+ // and picks up none of its headers. Without the seller header the Seller
+ // API refuses the request before the action runs, so an export would
+ // generate fine and then fail to download.
+ downloadHeaders: (): Record<string, string> =>
+ activeSellerId ? { 'X-Spree-Seller-Id': activeSellerId } : {},
+ // Backs the shared export dialog, the same one the operator's dashboard
+ // renders. The Seller API narrows what may be exported to records that
+ // can be scoped to one seller, and refuses anything else.
+ exports: {
+ create: (params) => sellerClient().exports.create(params as SellerExportCreateParams),
+ get: (id) => sellerClient().exports.get(id),
+ },
// Backs the shared stock-locations page. No `delete`: a location holds
// stock levels and is named on historical fulfillments, so the Seller API
// does not offer it and the page hides the action accordingly.
@@ -94,6 +119,7 @@ export function sellerClient(): SellerApiClient {
/** Points subsequent requests at a seller, without persisting the choice. */
export function setActiveSeller(sellerId: string): void {
+ activeSellerId = sellerId
sellerClient().setSeller(sellerId)
}
@@ -121,6 +147,7 @@ export function forgetSeller(): void {
} catch {
// Nothing to forget; clearing the header below is what matters for logout.
}
+ activeSellerId = null
client?.setSeller('')
}
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index 123968a407..bbe815e838 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -12,6 +12,15 @@
"subtitle": "You were invited as {{email}}. Set a password to finish.",
"title": "Join the team"
},
+ "admin": {
+ "components": {
+ "export_button": {
+ "all": {
+ "description": "Ignore filters and export all of your records."
+ }
+ }
+ }
+ },
"app": {
"name": "Seller panel"
},
diff --git a/packages/seller-dashboard/src/pages/orders.tsx b/packages/seller-dashboard/src/pages/orders.tsx
index 0fcd5e48f4..c533f9e572 100644
--- a/packages/seller-dashboard/src/pages/orders.tsx
+++ b/packages/seller-dashboard/src/pages/orders.tsx
@@ -1,4 +1,4 @@
-import { type ResourceSearch, ResourceTable } from '@spree/dashboard-core'
+import { ExportButton, type ResourceSearch, ResourceTable } from '@spree/dashboard-core'
import { useRowClickBridge } from '@spree/dashboard-ui'
import type { Order } from '@spree/seller-sdk'
import { useNavigate, useParams } from '@tanstack/react-router'
@@ -25,6 +25,7 @@ export function OrdersPage({ search }: { search: ResourceSearch }) {
queryKey="seller-orders"
queryFn={(params) => sellerClient().orders.list(params)}
searchParams={search}
+ actions={(ctx) => <ExportButton type="orders" {...ctx} />}
/>
</div>
)
diff --git a/packages/seller-dashboard/src/pages/products.tsx b/packages/seller-dashboard/src/pages/products.tsx
index ab83233fa5..846437a7c3 100644
--- a/packages/seller-dashboard/src/pages/products.tsx
+++ b/packages/seller-dashboard/src/pages/products.tsx
@@ -4,7 +4,7 @@ import type {
BulkActionOutcome,
ResourceSearch,
} from '@spree/dashboard-core'
-import { ResourceTable, Subject } from '@spree/dashboard-core'
+import { ExportButton, ResourceTable, Subject } from '@spree/dashboard-core'
import {
BulkDialog,
Button,
@@ -136,12 +136,17 @@ export function ProductsPage({ search }: { search: ResourceSearch }) {
queryFn={(params) => sellerClient().products.list(params)}
searchParams={search}
bulkActions={bulkActions}
- actions={
- <Button onClick={() => navigate({ to: '/$sellerId/products/new', params: { sellerId } })}>
- <PlusIcon className="size-4" />
- {t('products.add')}
- </Button>
- }
+ actions={(ctx) => (
+ <>
+ <ExportButton type="products" {...ctx} />
+ <Button
+ onClick={() => navigate({ to: '/$sellerId/products/new', params: { sellerId } })}
+ >
+ <PlusIcon className="size-4" />
+ {t('products.add')}
+ </Button>
+ </>
+ )}
/>
</div>
)
diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.ts
index 5dd0ca3503..f582984ab3 100644
--- a/packages/seller-sdk/src/index.ts
+++ b/packages/seller-sdk/src/index.ts
@@ -16,6 +16,8 @@ export type {
RequirementSubmissionParams,
SellerAddressParams,
SellerCountry,
+ SellerExportCreateParams,
+ SellerExportType,
StockLocationParams,
} from './seller-client'
// Client class, for advanced use and subclassing
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index 1773517c2f..f173a247b4 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -2,6 +2,7 @@ import type { ListParams, PaginatedResponse, RequestFn, RequestOptions } from '@
import { transformListParams } from '@spree/sdk-core'
import type {
AuthTokens,
+ Export,
Fulfillment,
Invitation,
Order,
@@ -377,6 +378,24 @@ export class SellerClient {
}> => this.request('POST', '/direct_uploads', { ...options, body: params }),
}
+ /**
+ * CSV of this seller's own records — what they sold, or their catalogue.
+ *
+ * Created, polled until `done`, then downloaded. There is no list: a seller
+ * has no export history page, and no delete: how long a file is kept is the
+ * marketplace's business.
+ *
+ * Scoped server-side to the acting seller, so an export can only ever
+ * contain their own rows however the request is filtered.
+ */
+ readonly exports = {
+ create: (params: SellerExportCreateParams, options?: RequestOptions): Promise<Export> =>
+ this.request<Export>('POST', '/exports', { ...options, body: params }),
+
+ get: (id: string, options?: RequestOptions): Promise<Export> =>
+ this.request<Export>('GET', `/exports/${id}`, options),
+ }
+
/**
* Where this seller keeps stock, and so where their returns are sent.
*
@@ -481,6 +500,39 @@ export interface StockLocationParams {
kind?: string
}
+/**
+ * The datasets a seller may export.
+ *
+ * Deliberately narrower than the operator's list: only records that can be
+ * narrowed to one seller are offered, since that narrowing is what keeps one
+ * seller's file free of another's rows.
+ */
+export type SellerExportType = 'orders' | 'products'
+
+export interface SellerExportCreateParams {
+ type: SellerExportType
+ /**
+ * Ransack query hash, the same predicate shape the list endpoints take
+ * (`{ number_cont: 'R12' }`). Ignored when `record_selection` is `'all'`.
+ */
+ search_params?: Record<string, unknown>
+ /**
+ * `'filtered'` (default) keeps `search_params`; `'all'` clears them on the
+ * server and exports everything this seller owns.
+ */
+ record_selection?: 'filtered' | 'all'
+ /**
+ * Absolute URL of the panel view to send the seller back to; the
+ * export-done email uses it as the download button's target. Honored only
+ * when it matches one of the store's allowed origins.
+ *
+ * Passed by the panel rather than derived server-side, because only the
+ * panel knows where it is mounted — a seller panel is served from a path
+ * under the store as often as from a host of its own.
+ */
+ results_url?: string
+}
+
/** A country as the address form needs it. */
export interface SellerCountry {
iso: string
diff --git a/packages/seller-sdk/src/types/generated/Export.ts b/packages/seller-sdk/src/types/generated/Export.ts
new file mode 100644
index 0000000000..1f266adcd7
--- /dev/null
+++ b/packages/seller-sdk/src/types/generated/Export.ts
@@ -0,0 +1,19 @@
+// Typelizer digest 3d6bb62aad0b746f7fbb73eec87ee9a5
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+type Export = {
+ id: string;
+ number: string;
+ format: string | null;
+ created_at: string;
+ updated_at: string;
+ type: string | null;
+ user_id: string | null;
+ done: boolean;
+ filename: string | null;
+ byte_size: number | null;
+ download_url: string | null;
+}
+
+export default Export;
diff --git a/packages/seller-sdk/src/types/generated/index.ts b/packages/seller-sdk/src/types/generated/index.ts
index a18fad80c2..19d2230533 100644
--- a/packages/seller-sdk/src/types/generated/index.ts
+++ b/packages/seller-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest a3718cbfeb2b8e37b99f74a4b7e1c048
+// Typelizer digest a6a5a8f7f87196388bca3bfbed4ab37c
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -8,6 +8,7 @@ export type { default as OptionType } from './OptionType'
export type { default as OptionValue } from './OptionValue'
export type { default as PriceHistory } from './PriceHistory'
export type { default as Price } from './Price'
+export type { default as Export } from './Export'
export type { default as FulfillmentItem } from './FulfillmentItem'
export type { default as Fulfillment } from './Fulfillment'
export type { default as Invitation } from './Invitation'
diff --git a/spree/api/app/controllers/spree/api/v3/seller/exports_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/exports_controller.rb
new file mode 100644
index 0000000000..5544216ade
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/exports_controller.rb
@@ -0,0 +1,195 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A seller's own CSV exports.
+ #
+ # The operator's counterpart offers whatever the registry holds; this
+ # branch offers only the datasets that can be narrowed to one seller,
+ # because tenancy here is the narrowing. `Spree::Export#scope` refuses
+ # a model without `for_seller` rather than writing a file spanning the
+ # marketplace, and ALLOWED_TYPES is the front door onto the same rule —
+ # a type added to the registry is not reachable from a seller's panel
+ # until someone has decided it can be scoped.
+ #
+ # No index: a seller creates an export, polls it and downloads it, so
+ # there is no history page to list. No destroy either — retention is
+ # the marketplace's business.
+ class ExportsController < Seller::ResourceController
+ include ActiveStorage::SetCurrent
+
+ # Exports of records a seller genuinely owns. Both narrow by their own
+ # `seller_id`, which is the same answer `current_seller.orders` and
+ # `current_seller.products` give the list endpoints.
+ ALLOWED_TYPES = %w[orders products].freeze
+
+ scoped_resource :exports
+
+ # POST /api/v3/seller/exports
+ #
+ # Refused before the record is built when the type is not one a
+ # seller may run — `build_resource` would otherwise have no class to
+ # instantiate.
+ def create
+ return render_unsupported_type if resolve_export_type(params[:type]).nil?
+
+ super
+ end
+
+ # GET /api/v3/seller/exports/:id/download
+ #
+ # Streamed inline rather than redirected to ActiveStorage's signed
+ # URL: the panel is served under a path-based mount and proxies only
+ # `/api/*`, so a cross-origin redirect would strip the Authorization
+ # header and fail silently.
+ def download
+ @resource = find_resource
+ authorize_resource!(@resource, :show)
+
+ unless @resource.done?
+ return render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:export_not_ready],
+ message: 'Export is not ready yet',
+ status: :unprocessable_content
+ )
+ end
+
+ attachment = @resource.attachment
+ send_data(
+ attachment.download,
+ filename: attachment.filename.to_s,
+ type: attachment.content_type || 'text/csv',
+ disposition: 'attachment'
+ )
+ end
+
+ protected
+
+ def model_class
+ Spree::Export
+ end
+
+ def serializer_class
+ Spree.api.seller_export_serializer
+ end
+
+ def scope_includes
+ [{ attachment_attachment: :blob }]
+ end
+
+ # Rooted in the seller's own exports, so another seller's id reads as
+ # missing rather than denied — the same shape every endpoint on this
+ # branch has.
+ def seller_association
+ :exports
+ end
+
+ # Loaded by both the scope gate and the member actions — memoize so
+ # the record is fetched once.
+ def find_resource
+ @find_resource ||= super
+ end
+
+ # An export is a bulk read of the records it contains, so creating
+ # and downloading one both check the read-level key.
+ def action_kind
+ 'read'
+ end
+
+ def read_actions
+ %w[show create download]
+ end
+
+ # Gated by the scope of what is being exported, not by an "exports"
+ # scope of its own: an orders export needs `read_orders`.
+ def scoped_resource_name
+ export_class&.required_scope || :all
+ end
+
+ # Authorized against the records being exported rather than the
+ # export row.
+ #
+ # An export is a bulk read of its contents, so "may this seller read
+ # orders" is the real question — and it is the same one
+ # `scoped_resource_name` asks the key gate. `Spree::Export` is not a
+ # catalog subject in its own right, so authorizing the row itself
+ # would deny every principal that is not a full-access admin.
+ def authorize_resource!(resource = @resource, _action = action_name.to_sym)
+ model = resource.is_a?(Spree::Export) ? resource.model_class : resource
+
+ authorize!(:show, model)
+ end
+
+ # The seller and the store both come from the session rather than the
+ # payload — a seller cannot file an export against anyone else.
+ def build_resource
+ klass = resolve_export_type(permitted_params[:type])
+
+ klass.new(
+ permitted_params.except(:type).merge(
+ store: current_store,
+ seller: current_seller,
+ user: try_spree_current_user,
+ results_url: validated_results_url(permitted_params[:results_url])
+ )
+ )
+ end
+
+ # `search_params` carries an arbitrary Ransack hash with nested
+ # groupings, which Rails' `permit(k: {})` rejects — extract via
+ # `to_unsafe_h`. `:format` is deliberately dropped: only CSV exists,
+ # and Rails' request format would otherwise overwrite the enum.
+ def permitted_params
+ attrs = params.permit(*model_additional_permitted_attributes, :type, :record_selection, :results_url)
+ raw = params[:search_params]
+ attrs[:search_params] = raw.respond_to?(:to_unsafe_h) ? raw.to_unsafe_h : raw if raw.present?
+ attrs
+ end
+
+ # Resolves the API shorthand (`"orders"`) against the allowlist.
+ #
+ # The class comes from the in-process registry, never from the
+ # request — the parameter only selects an entry, so no user input is
+ # ever constantized.
+ def resolve_export_type(name)
+ return nil if name.blank?
+
+ name = name.to_s
+ return nil unless ALLOWED_TYPES.include?(name)
+
+ Spree::Export.available_types.find { |type| type.api_type == name || type.to_s == name }
+ end
+
+ private
+
+ def export_class
+ action_name == 'create' ? resolve_export_type(params[:type]) : find_resource.class
+ end
+
+ # Where the done email sends the seller back to. The panel passes its
+ # own location, since only it knows where it is mounted — this
+ # branch is served from a path under the store as often as from a
+ # host of its own — and the store's allowed origins decide whether to
+ # trust it.
+ def validated_results_url(url)
+ return if url.blank?
+ return unless current_store.allowed_origin?(url)
+
+ url
+ end
+
+ def render_unsupported_type
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:validation_error],
+ message: Spree.t(
+ 'api.errors.unsupported_export_type',
+ default: "Unsupported export type. Supported types: #{ALLOWED_TYPES.join(', ')}"
+ ),
+ status: :unprocessable_content
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/export_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/export_serializer.rb
new file mode 100644
index 0000000000..ffe0061337
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/seller/export_serializer.rb
@@ -0,0 +1,44 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # Seller API serializer for {Spree::Export}.
+ #
+ # Mirrors the operator's, pointed at the seller branch's own download
+ # endpoint: the bytes are streamed by that action rather than handed
+ # over as a pre-signed ActiveStorage URL, so the seller's own session
+ # is what authorizes every download.
+ #
+ # `user_id` is inherited but names the seller's own staff member, and
+ # the marketplace's `results_url` is not exposed — a seller reads the
+ # file, not the operator's bookkeeping about it.
+ class ExportSerializer < V3::ExportSerializer
+ typelize done: :boolean,
+ download_url: [:string, nullable: true],
+ filename: [:string, nullable: true],
+ byte_size: [:number, nullable: true]
+
+ attribute(:done) { |export| export.done? }
+
+ # Safe-nav on `blob` — `attachment.attached?` can stay true while a
+ # background job purges the underlying blob (e.g. retention sweeps).
+ attribute :filename do |export|
+ export.attachment.blob&.filename&.to_s if export.done?
+ end
+
+ attribute :byte_size do |export|
+ export.attachment.blob&.byte_size if export.done?
+ end
+
+ attribute :download_url do |export|
+ next nil unless export.done?
+
+ Spree::Core::Engine.routes.url_helpers.download_api_v3_seller_export_path(
+ id: export.prefixed_id
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 2039e1c2fe..dbc685a072 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -778,6 +778,15 @@ Spree::Core::Engine.add_routes do
resources :direct_uploads, only: [:create]
+ # CSV of what this seller sold, or of their catalogue. Created, polled
+ # and downloaded — no index, since a seller has no history page to
+ # list, and no destroy, since retention is the marketplace's business.
+ resources :exports, only: [:create, :show] do
+ member do
+ get :download
+ end
+ end
+
# No destroy: a location holds stock levels and is named on historical
# fulfillments, so a seller retires one by deactivating it.
resources :stock_locations, only: [:index, :show, :create, :update]
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 4d15499a94..cc4a527cb2 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -181,6 +181,7 @@ module Spree
product_submission_serializer: 'Spree::Api::V3::Seller::ProductSubmissionSerializer',
admin_product_submission_serializer: 'Spree::Api::V3::Admin::ProductSubmissionSerializer',
seller_requirement_submission_serializer: 'Spree::Api::V3::Seller::RequirementSubmissionSerializer',
+ seller_export_serializer: 'Spree::Api::V3::Seller::ExportSerializer',
admin_seller_serializer: 'Spree::Api::V3::Admin::SellerSerializer',
admin_seller_requirement_serializer: 'Spree::Api::V3::Admin::SellerRequirementSerializer',
admin_seller_requirement_submission_serializer: 'Spree::Api::V3::Admin::SellerRequirementSubmissionSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/exports_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/exports_controller_spec.rb
new file mode 100644
index 0000000000..58a89373b3
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/seller/exports_controller_spec.rb
@@ -0,0 +1,190 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Seller::ExportsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Seller'
+
+ # `read_orders` and `read_products` are what the export gate asks for, and
+ # the ability resolves them from a role held on the seller.
+ let(:seller_role) do
+ create(:role, name: 'Seller', resource: seller, permissions: %w[read_orders read_products])
+ end
+
+ let!(:mine) { create(:completed_order_with_totals, store: store, seller: seller) }
+ let(:other_seller) { create(:seller, :approved, store: store) }
+ let!(:theirs) { create(:completed_order_with_totals, store: store, seller: other_seller) }
+
+ before do
+ request.headers['Authorization'] = "Bearer #{seller_jwt_token}"
+ request.headers['X-Spree-Seller-Id'] = seller.prefixed_id
+ end
+
+ describe 'POST #create' do
+ it 'queues an export owned by the acting seller' do
+ post :create, params: { type: 'orders' }, as: :json
+
+ expect(response).to have_http_status(:created)
+
+ export = Spree::Export.find_by(number: json_response['number'])
+ expect(export.seller).to eq(seller)
+ expect(export.store).to eq(store)
+ expect(export.user).to eq(seller_user)
+ end
+
+ # The whole point of the branch: tenancy is the scope narrowing, not the
+ # ability, which grants the model class store-wide.
+ it "writes only this seller's orders into the file" do
+ post :create, params: { type: 'orders' }, as: :json
+
+ export = Spree::Export.find_by(number: json_response['number'])
+ expect(export.records_to_export).to include(mine)
+ expect(export.records_to_export).not_to include(theirs)
+ end
+
+ it 'ignores a seller named in the payload' do
+ post :create, params: { type: 'orders', seller_id: other_seller.prefixed_id }, as: :json
+
+ export = Spree::Export.find_by(number: json_response['number'])
+ expect(export.seller).to eq(seller)
+ end
+
+ it 'leaves drafts out' do
+ draft = create(:order, store: store, seller: seller, status: 'draft', cart: nil)
+
+ post :create, params: { type: 'orders' }, as: :json
+
+ export = Spree::Export.find_by(number: json_response['number'])
+ expect(export.records_to_export).not_to include(draft)
+ end
+
+ # Creating one is not proof it works: generation runs in a background job,
+ # so a scope that raises there returns 201 here and only surfaces as a
+ # download that never arrives.
+ it 'accepts a products export and can actually generate it' do
+ mine = create(:product, store: store, seller: seller)
+ theirs = create(:product, store: store, seller: other_seller)
+
+ post :create, params: { type: 'products' }, as: :json
+
+ expect(response).to have_http_status(:created)
+
+ export = Spree::Export.find_by(number: json_response['number'])
+ expect { export.generate }.not_to raise_error
+ expect(export.attachment.download).to include(mine.name)
+ expect(export.attachment.download).not_to include(theirs.name)
+ end
+
+ # A type the operator can export but which cannot be narrowed to one
+ # seller must never be reachable here.
+ it 'refuses a type outside the seller allowlist' do
+ post :create, params: { type: 'customers' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(Spree::Export.count).to eq(0)
+ end
+
+ it 'refuses an unknown type' do
+ post :create, params: { type: 'nonsense' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it 'keeps a results_url the store allows' do
+ create(:allowed_origin, store: store, origin: 'https://shop.test')
+
+ post :create, params: { type: 'orders', results_url: 'https://shop.test/sellers' }, as: :json
+
+ export = Spree::Export.find_by(number: json_response['number'])
+ expect(export.results_url).to eq('https://shop.test/sellers')
+ end
+
+ it 'drops a results_url pointing somewhere else' do
+ post :create, params: { type: 'orders', results_url: 'https://evil.test/steal' }, as: :json
+
+ export = Spree::Export.find_by(number: json_response['number'])
+ expect(export.results_url).to be_nil
+ end
+ end
+
+ describe 'GET #show' do
+ let!(:own_export) { create(:order_export, store: store, seller: seller, user: seller_user) }
+ let!(:other_export) do
+ create(:order_export, store: store, seller: other_seller)
+ end
+
+ it 'reads its own' do
+ get :show, params: { id: own_export.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(own_export.prefixed_id)
+ end
+
+ # Missing rather than denied — the scope is rooted in the seller's own
+ # exports, so another seller's id simply is not there.
+ it "cannot read another seller's" do
+ get :show, params: { id: other_export.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'GET #download' do
+ let(:export) { create(:order_export, store: store, seller: seller, user: seller_user) }
+
+ it 'refuses while the file is still being written' do
+ get :download, params: { id: export.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('export_not_ready')
+ end
+
+ it 'streams the file once it is ready' do
+ export.generate
+
+ get :download, params: { id: export.reload.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.headers['Content-Disposition']).to include('attachment')
+ expect(response.body).to include(mine.number)
+ expect(response.body).not_to include(theirs.number)
+ end
+
+ # The seller order page withholds the buyer's email, so the bulk download
+ # of the same orders must not hand it over instead.
+ it "withholds the buyer's email while keeping the shipping address" do
+ export.generate
+
+ get :download, params: { id: export.reload.prefixed_id }
+
+ expect(response.body).not_to include(mine.email)
+ expect(response.body).to include(mine.ship_address.address1)
+ end
+
+ it "cannot download another seller's" do
+ other = create(:order_export, store: store, seller: other_seller)
+
+ get :download, params: { id: other.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'authorization' do
+ it 'refuses a seller whose role does not read orders' do
+ seller_role.update!(permissions: %w[read_products])
+
+ post :create, params: { type: 'orders' }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it 'refuses a request naming no seller' do
+ request.headers['X-Spree-Seller-Id'] = nil
+
+ post :create, params: { type: 'orders' }, as: :json
+
+ expect(response).to have_http_status(:forbidden)
+ end
+ end
+end
diff --git a/spree/api/spec/integration/spree/api/v3/seller/exports_spec.rb b/spree/api/spec/integration/spree/api/v3/seller/exports_spec.rb
new file mode 100644
index 0000000000..04ea72357a
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/seller/exports_spec.rb
@@ -0,0 +1,166 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Seller Exports API', type: :request, swagger_doc: 'api-reference/seller.yaml' do
+ include_context 'API v3 Seller'
+
+ # The shared context's role reads products only; an orders export is gated on
+ # `read_orders`, which is the scope of what it contains.
+ let(:seller_role) do
+ create(:role, name: 'Seller', resource: seller, permissions: %w[read_orders read_products])
+ end
+
+ let!(:order) { create(:completed_order_with_totals, store: store, seller: seller) }
+
+ path '/api/v3/seller/exports' do
+ post 'Create an export' do
+ tags 'Exports'
+ consumes 'application/json'
+ produces 'application/json'
+ security [bearer_auth: []]
+ description <<~DESC
+ Queues a CSV of this seller's own records.
+
+ Only datasets that can be narrowed to a single seller are offered, so
+ an export can never contain another seller's rows however it is
+ filtered. The seller and the store come from the request context
+ whatever the payload says.
+
+ Generation runs in the background: poll `GET /api/v3/seller/exports/{id}`
+ until `done` is true, then fetch `download_url`.
+ DESC
+
+ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ type: {
+ type: :string,
+ enum: %w[orders products],
+ description: 'Which dataset to export.'
+ },
+ record_selection: {
+ type: :string,
+ enum: %w[filtered all],
+ description: '`filtered` (default) honours `search_params`; `all` exports everything this seller owns.'
+ },
+ search_params: {
+ type: :object,
+ description: 'Ransack predicates, the same shape the list endpoints take. Ignored when `record_selection` is `all`.',
+ additionalProperties: true
+ },
+ results_url: {
+ type: :string,
+ description: 'Panel URL the export-done email links back to. Honoured only when it matches one of the store\'s allowed origins.'
+ }
+ },
+ required: %w[type]
+ }
+
+ response '201', 'export queued' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:body) { { type: 'orders' } }
+
+ schema '$ref' => '#/components/schemas/Export'
+
+ run_test! do |response|
+ expect(JSON.parse(response.body)['type']).to eq('orders')
+ end
+ end
+
+ response '422', 'type cannot be scoped to one seller' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:body) { { type: 'customers' } }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/seller/exports/{id}' do
+ parameter name: :id, in: :path, type: :string, description: 'Export ID'
+
+ get 'Get an export' do
+ tags 'Exports'
+ produces 'application/json'
+ security [bearer_auth: []]
+ description <<~DESC
+ Reads one of this seller's exports. Poll this until `done` is true,
+ then fetch `download_url`.
+ DESC
+
+ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true
+
+ response '200', 'export found' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:export) { create(:order_export, store: store, seller: seller, user: seller_user) }
+ let(:id) { export.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/Export'
+
+ run_test!
+ end
+
+ response '404', "another seller's export" do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:id) do
+ create(:order_export, store: store, seller: create(:seller, :approved, store: store)).
+ prefixed_id
+ end
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/seller/exports/{id}/download' do
+ parameter name: :id, in: :path, type: :string, description: 'Export ID'
+
+ get 'Download an export' do
+ tags 'Exports'
+ produces 'text/csv'
+ security [bearer_auth: []]
+ description <<~DESC
+ Streams the finished CSV.
+
+ The bytes are served by this endpoint rather than through a redirect,
+ so the seller's own session authorizes every download.
+ DESC
+
+ parameter name: 'X-Spree-Seller-Id', in: :header, type: :string, required: true
+
+ response '422', 'export is still being written' do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:export) { create(:order_export, store: store, seller: seller, user: seller_user) }
+ let(:id) { export.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+
+ response '404', "another seller's export" do
+ let(:Authorization) { "Bearer #{seller_jwt_token}" }
+ let(:'X-Spree-Seller-Id') { seller.prefixed_id }
+ let(:id) do
+ create(:order_export, store: store, seller: create(:seller, :approved, store: store)).
+ prefixed_id
+ end
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/export.rb b/spree/core/app/models/spree/export.rb
index baad1a911f..52a02fee49 100644
--- a/spree/core/app/models/spree/export.rb
+++ b/spree/core/app/models/spree/export.rb
@@ -6,6 +6,16 @@ module Spree
SUPPORTED_FILE_FORMATS = %i[csv].freeze
+ # Raised when a seller-owned export names a model that cannot be narrowed
+ # to one seller. Failing loudly beats writing a file that silently spans
+ # the whole marketplace.
+ class SellerScopeUnavailable < StandardError
+ def initialize(model_class)
+ super("#{model_class} does not define `for_seller`, so a seller-scoped export of it " \
+ 'would contain every seller\'s records.')
+ end
+ end
+
include Spree::SingleStoreResource
include Spree::NumberIdentifier
@@ -31,6 +41,15 @@ module Spree
# Validations
#
validates :format, :type, presence: true
+ # Refuse before the job runs rather than at generate. `scope` raises for a
+ # seller-owned export of a model it cannot narrow, and that raise would
+ # otherwise land inside the background job, where nothing records it — the
+ # export simply never becomes `done` and the caller waits out its poll. A
+ # validation makes it a 422 the caller reads straight away.
+ #
+ # Not `on: :create`: an export born without a seller passes, and assigning
+ # one afterwards would reach the same raise.
+ validate :seller_scope_must_be_available, if: -> { seller_id.present? }
#
# Enums
@@ -93,11 +112,11 @@ module Spree
records_to_export.includes(scope_includes).find_in_batches do |batch|
batch.each do |record|
if multi_line_csv?
- record.to_csv(store).each do |line|
+ record.to_csv(store, **to_csv_options).each do |line|
csv << Spree::CSV::FormulaSanitizer.row(line)
end
else
- csv << Spree::CSV::FormulaSanitizer.row(record.to_csv(store))
+ csv << Spree::CSV::FormulaSanitizer.row(record.to_csv(store, **to_csv_options))
end
end
end
@@ -108,6 +127,15 @@ module Spree
false
end
+ # Keyword arguments passed to each record's `to_csv`. Subclasses override
+ # to narrow what a particular export writes — see Spree::Exports::Orders,
+ # which drops columns a seller may not read.
+ #
+ # @return [Hash]
+ def to_csv_options
+ {}
+ end
+
def csv_headers
raise NotImplementedError, 'csv_headers must be implemented'
end
@@ -129,10 +157,26 @@ module Spree
::File.delete(export_tmp_file_path) if ::File.exist?(export_tmp_file_path)
end
+ # The records this export may contain.
+ #
+ # Tenancy is these scope narrowings, never the ability: a seller holding
+ # `read_orders` is granted the model class, not their own subset (see
+ # Spree::Ability), so dropping `for_seller` here would put every seller's
+ # rows in one seller's file.
def scope
scope = model_class
scope = scope.for_store(store) if model_class.respond_to?(:for_store)
- scope = scope.for_seller(seller) if model_class.respond_to?(:for_seller) && seller.present?
+
+ if seller.present?
+ raise SellerScopeUnavailable, model_class unless model_class.respond_to?(:for_seller)
+
+ scope = scope.for_seller(seller)
+ # A draft is either a checkout in flight or the operator's working
+ # document, and is not this seller's sale — the same exclusion every
+ # endpoint on the seller branch applies.
+ scope = scope.not_drafts if model_class.respond_to?(:not_drafts)
+ end
+
# A staff-created export only contains what its creator may read; a
# userless export (console, system jobs) is unfiltered.
scope = scope.accessible_by(current_ability) if user.present?
@@ -211,8 +255,11 @@ module Spree
end
end
+ # Capability is read against whatever granted it: a seller's roles are held
+ # on the seller, not the store, so an ability built from the store alone
+ # would answer "no rules" and empty the file.
def current_ability
- @current_ability ||= Spree.ability_class.new(user, { store: store })
+ @current_ability ||= Spree.ability_class.new(user, { store: store, resource: seller || store })
end
# eg. Spree::Exports::Products => products-store-my-store-code-20241030133348.csv
@@ -280,6 +327,15 @@ module Spree
private
+ def seller_scope_must_be_available
+ return if model_class.respond_to?(:for_seller)
+
+ errors.add(:type, :seller_scope_unavailable)
+ rescue NameError
+ # An unresolvable `type` is the presence/registry validation's business.
+ nil
+ end
+
def set_default_format
self.format = SUPPORTED_FILE_FORMATS.first if format.blank?
end
diff --git a/spree/core/app/models/spree/exports/orders.rb b/spree/core/app/models/spree/exports/orders.rb
index d99e3dd3c1..399883b71f 100644
--- a/spree/core/app/models/spree/exports/orders.rb
+++ b/spree/core/app/models/spree/exports/orders.rb
@@ -1,13 +1,15 @@
module Spree
module Exports
class Orders < Spree::Export
+ SELLER_OMITTED_HEADERS = ['Email'].freeze
+
def scope_includes
[
:store,
:payments,
:shipments,
- { bill_address: [:state, :country] },
- { ship_address: [:state, :country] },
+ :bill_address,
+ :ship_address,
{ line_items: { variant: { product: [:categories] } } },
{ custom_fields: :custom_field_definition }
]
@@ -18,7 +20,35 @@ module Spree
end
def csv_headers
- Spree::CSV::OrderLineItemPresenter::HEADERS + custom_fields_headers
+ Spree::CSV::OrderLineItemPresenter.headers(omit_headers: omitted_headers) + custom_fields_headers
+ end
+
+ def to_csv_options
+ { omit_headers: omitted_headers }
+ end
+
+ # Columns a seller's own export leaves out.
+ #
+ # The buyer's email is withheld from every seller-facing surface — it is
+ # the one contact detail that lets a marketplace's customer be taken off
+ # the marketplace, and `Spree::Api::V3::Seller::OrderSerializer` already
+ # withholds it. A bulk CSV that carried it would hand over in a
+ # spreadsheet exactly what the order page refuses to show, and would
+ # undo the message relay this is the counterpart to
+ # (docs/plans/6.1-marketplace-message-relay.md).
+ #
+ # The addresses stay, phones included, and deliberately so: a seller is
+ # merchant of record for their own child order, so they ship to one and
+ # invoice against the other, and until the relay ships the phone on the
+ # shipping address is a seller's only way to reach a buyer about a
+ # delivery (docs/plans/6.1-marketplace-message-relay.md). Email is
+ # withheld where the phone is not because email is the channel that
+ # takes a customer off the marketplace, while a delivery phone number is
+ # what makes the parcel arrive.
+ #
+ # @return [Array<String>]
+ def omitted_headers
+ seller.present? ? SELLER_OMITTED_HEADERS : []
end
end
end
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 59d9ef4524..de8053be12 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -124,6 +124,10 @@ module Spree
attribute :status, :string, default: 'draft'
validates :status, inclusion: { in: STATUSES }
+ # Orders belonging to the given seller. Passing nil selects the
+ # operator's own sales, which on a store with no sellers is every order.
+ scope :for_seller, ->(seller) { where(seller_id: seller.respond_to?(:id) ? seller.id : seller) }
+
scope :drafts, -> { where(status: 'draft') }
scope :not_drafts, -> { where.not(status: 'draft') }
scope :placed_orders, -> { where(status: 'placed') }
@@ -1062,14 +1066,19 @@ module Spree
discounts.promotion.for_fulfillments.exists?
end
- def to_csv(_store = nil)
+ # @param omit_headers [Array<String>] columns to leave out, named by their
+ # header. A seller's export drops the buyer's email this way — see
+ # Spree::Exports::Orders.
+ def to_csv(_store = nil, omit_headers: [])
custom_fields_for_csv ||= Spree::CustomFieldDefinition.for_resource_type('Spree::Order').order(:namespace, :key).map do |mf_def|
custom_fields.find { |mf| mf.custom_field_definition_id == mf_def.id }&.csv_value
end
csv_lines = []
line_items.each_with_index do |line_item, index|
- csv_lines << Spree::CSV::OrderLineItemPresenter.new(self, line_item, index, custom_fields_for_csv).call
+ csv_lines << Spree::CSV::OrderLineItemPresenter.new(
+ self, line_item, index, custom_fields_for_csv, omit_headers: omit_headers
+ ).call
end
csv_lines
end
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 0432adfdfb..753df47627 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -259,6 +259,10 @@ module Spree
validate :discontinue_on_must_be_later_than_make_active_at, if: -> { make_active_at && discontinue_on }
scope :for_store, ->(store) { where(store_id: store.id) }
+ # Products belonging to the given seller. Passing nil selects the
+ # operator's own catalog, which on a store with no sellers is everything.
+ # The same answer `Seller#products` gives, as a scope a bulk read can chain.
+ scope :for_seller, ->(seller) { where(seller_id: seller.respond_to?(:id) ? seller.id : seller) }
scope :not_archived, -> { where.not(status: 'archived') }
scope :on_sale, lambda { |currency = nil|
currency ||= Spree::Store.default.default_currency
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index 57ac17ab90..80a34c4307 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -134,6 +134,11 @@ module Spree
has_many :orders, class_name: 'Spree::Order', dependent: nil
has_many :payment_splits, through: :orders, class_name: 'Spree::PaymentSplit', source: :payment_splits
+ # CSV files this seller asked for. Destroyed with the seller: an export is
+ # a copy of records held elsewhere, so nothing is lost by dropping it, and
+ # a file of one seller's orders should not outlive them.
+ has_many :exports, class_name: 'Spree::Export', dependent: :destroy_async, inverse_of: :seller
+
# What this seller has done about the marketplace's requirements — their
# attestations, the documents they uploaded, what the operator made of
# them. Goes with the seller, since it means nothing without them.
diff --git a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
index a1be00a7b6..647561698e 100644
--- a/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/order_line_item_presenter.rb
@@ -59,14 +59,36 @@ module Spree
'Notes'
].freeze
- def initialize(order, line_item, index, custom_fields = [])
+ # Columns a caller may leave out, and the headers naming them.
+ #
+ # Filtering both the header list and the row through the same names is
+ # what keeps them aligned: dropping a cell by hand would silently shift
+ # every value after it into the wrong column.
+ #
+ # @param order [Spree::Order]
+ # @param line_item [Spree::LineItem]
+ # @param index [Integer] position within the order's line items; only
+ # the first row carries the order-level values
+ # @param custom_fields [Array]
+ # @param omit_headers [Array<String>] headers to leave out of this row
+ def initialize(order, line_item, index, custom_fields = [], omit_headers: [])
@order = order
@line_item = line_item
@index = index
@custom_fields = custom_fields
+ @omit_headers = Array(omit_headers)
end
attr_accessor :order, :line_item, :index, :custom_fields
+ attr_reader :omit_headers
+
+ # The headers this presenter emits, minus the omitted ones.
+ #
+ # @param omit_headers [Array<String>]
+ # @return [Array<String>]
+ def self.headers(omit_headers: [])
+ HEADERS - Array(omit_headers)
+ end
def call
csv = [
@@ -127,6 +149,8 @@ module Spree
index.zero? ? order.customer_note : nil
]
+ csv = reject_omitted(csv)
+
if index.zero?
csv += custom_fields
end
@@ -136,6 +160,14 @@ module Spree
private
+ # Drops the cells whose headers were omitted, matching each value to its
+ # header by position so the row and the header list stay aligned.
+ def reject_omitted(csv)
+ return csv if omit_headers.empty?
+
+ csv.reject.with_index { |_value, position| omit_headers.include?(HEADERS[position]) }
+ end
+
def taxon_dict(taxon)
return [] if taxon.blank?
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 3a32e3035f..a50222f1cd 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -287,6 +287,10 @@ en:
attributes:
new_variant:
must_differ_from_original: must be different from the item being returned
+ spree/export:
+ attributes:
+ type:
+ seller_scope_unavailable: cannot be narrowed to a single seller
spree/gift_card:
attributes:
base:
diff --git a/spree/core/db/migrate/20260827000001_add_seller_to_spree_exports.rb b/spree/core/db/migrate/20260827000001_add_seller_to_spree_exports.rb
new file mode 100644
index 0000000000..e87307f843
--- /dev/null
+++ b/spree/core/db/migrate/20260827000001_add_seller_to_spree_exports.rb
@@ -0,0 +1,5 @@
+class AddSellerToSpreeExports < ActiveRecord::Migration[8.1]
+ def change
+ add_reference :spree_exports, :seller, null: true, index: true
+ end
+end
diff --git a/spree/core/spec/models/spree/export_spec.rb b/spree/core/spec/models/spree/export_spec.rb
index 40bf2fd6e8..d4ab035075 100644
--- a/spree/core/spec/models/spree/export_spec.rb
+++ b/spree/core/spec/models/spree/export_spec.rb
@@ -78,6 +78,118 @@ RSpec.describe Spree::Export, :job, type: :model do
end
end
+ describe '#scope' do
+ let(:seller) { create(:seller, :approved, store: store) }
+ let(:other_seller) { create(:seller, :approved, store: store) }
+
+ context 'when the export belongs to a seller' do
+ let(:export) { build(:order_export, store: store, seller: seller, user: nil) }
+
+ let!(:mine) { create(:completed_order_with_totals, store: store, seller: seller) }
+ let!(:theirs) { create(:completed_order_with_totals, store: store, seller: other_seller) }
+
+ it "narrows to that seller's own records" do
+ expect(export.scope).to include(mine)
+ expect(export.scope).not_to include(theirs)
+ end
+
+ it 'leaves out drafts' do
+ draft = create(:order, store: store, seller: seller, status: 'draft', cart: nil)
+
+ expect(export.scope).not_to include(draft)
+ end
+
+ # The ability grants the model class, never a subset, so a seller export
+ # of something with no `for_seller` would quietly span the marketplace.
+ it 'refuses a model it cannot narrow' do
+ export = build(:customer_export, store: store, seller: seller, user: nil)
+
+ expect { export.scope }.to raise_error(Spree::Export::SellerScopeUnavailable)
+ end
+
+ # Caught at create so the caller reads a 422, rather than in the job
+ # where the raise goes unrecorded and the export never becomes `done`.
+ it 'is refused before it can be queued' do
+ export = build(:customer_export, store: store, seller: seller, user: nil)
+
+ expect(export).not_to be_valid
+ expect(export.errors[:type]).to be_present
+ end
+
+ it 'allows a model it can narrow' do
+ expect(build(:order_export, store: store, seller: seller, user: nil)).to be_valid
+ expect(build(:product_export, store: store, seller: seller, user: nil)).to be_valid
+ end
+
+ # Not `on: :create` — an export born without a seller passes, and
+ # assigning one afterwards reaches the same raise in the job.
+ it 'is refused when a seller is assigned to an existing export' do
+ export = create(:customer_export, store: store, user: nil)
+
+ expect { export.update!(seller: seller) }.
+ to raise_error(ActiveRecord::RecordInvalid, /single seller/)
+ end
+ end
+
+ context 'when the export has no seller' do
+ let(:export) { build(:order_export, store: store, user: nil) }
+
+ let!(:sellers_order) { create(:completed_order_with_totals, store: store, seller: seller) }
+
+ it 'spans the store' do
+ expect(export.scope).to include(sellers_order)
+ end
+ end
+ end
+
+ # The buyer's email is withheld from every seller-facing surface; a bulk CSV
+ # is the one most likely to leave the building.
+ describe 'a seller export of orders' do
+ let(:seller) { create(:seller, :approved, store: store) }
+ let!(:order) { create(:completed_order_with_totals, store: store, seller: seller) }
+
+ let(:seller_export) { create(:order_export, store: store, seller: seller, user: nil) }
+ let(:operator_export) { create(:order_export, store: store, user: nil) }
+
+ def rows_for(export)
+ export.generate
+ ::CSV.parse(export.attachment.download, headers: true)
+ end
+
+ it 'leaves the buyer email out of the headers' do
+ expect(seller_export.csv_headers).not_to include('Email')
+ end
+
+ it "does not write the buyer's email anywhere in the file" do
+ seller_export.generate
+
+ expect(seller_export.attachment.download).not_to include(order.email)
+ end
+
+ # The row and the header list are filtered separately, so a mismatch would
+ # shift every later value into the wrong column while still looking valid.
+ it 'keeps the remaining columns aligned with their headers' do
+ row = rows_for(seller_export).first
+
+ expect(row['Number']).to eq(order.number)
+ expect(row['Shipping Name']).to eq(order.ship_address.full_name)
+ expect(row['Billing Name']).to eq(order.bill_address.full_name)
+ end
+
+ it 'still gives the seller the addresses they ship and invoice against' do
+ headers = seller_export.csv_headers
+
+ expect(headers).to include('Shipping Address 1', 'Shipping Phone')
+ expect(headers).to include('Billing Address 1')
+ expect(headers).to include('Notes')
+ end
+
+ it "leaves the operator's own export untouched" do
+ expect(operator_export.csv_headers).to include('Email')
+ expect(rows_for(operator_export).first['Email']).to eq(order.email)
+ end
+ end
+
describe '#records_to_export' do
let!(:matching_products) { create_list(:product, 3, name: 'test') }
let!(:non_matching_products) { create_list(:product, 3, name: 'something else') }