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 bulk product actions to the seller panel (#14508)

Damian Legawiec771c915025d5
diff --git a/packages/dashboard-core/src/components/bulk-action-bar.tsx b/packages/dashboard-core/src/components/bulk-action-bar.tsx
index 1bd871fb28..f47b0ab22f 100644
--- a/packages/dashboard-core/src/components/bulk-action-bar.tsx
+++ b/packages/dashboard-core/src/components/bulk-action-bar.tsx
@@ -31,6 +31,25 @@ export interface BulkActionFormProps<TFormValues = unknown> {
onCancel: () => void
}
+/**
+ * What a bulk action actually did, when that differs from what was selected.
+ *
+ * `count` is the number of records the action really affected. Reporting the
+ * selection size instead is wrong wherever the server skips rows it cannot
+ * move: the merchant is told fifteen products were submitted while a second
+ * toast says twelve were left alone.
+ */
+export interface BulkActionOutcome {
+ count: number
+}
+
+function outcomeCount(result: unknown): number | null {
+ if (typeof result !== 'object' || result === null) return null
+
+ const count = (result as BulkActionOutcome).count
+ return typeof count === 'number' ? count : null
+}
+
/**
* Declarative bulk action passed to `<ResourceTable>`. Three shapes:
*
@@ -62,7 +81,19 @@ export interface BulkAction<TFormValues = unknown> {
}
/** Render-prop for actions that need to collect form values before running. */
form?: (props: BulkActionFormProps<TFormValues>) => ReactNode
- /** The mutation. Resolves with anything; errors surface a toast. */
+ /**
+ * The mutation. Errors surface a toast.
+ *
+ * Resolve with a `BulkActionOutcome` when the server may act on fewer rows
+ * than were selected — a bulk endpoint that skips what it cannot move
+ * returns its own count, and `{n}` in `successMessage` is then that count
+ * rather than the size of the selection. Resolving with anything else (the
+ * common case) leaves `{n}` as the number of selected rows.
+ *
+ * Typed `unknown` rather than the union, which a narrower type cannot
+ * express: most actions resolve with their raw mutation payload, so the
+ * outcome shape is recognised at runtime, not enforced here.
+ */
run: (ctx: BulkActionRunContext<TFormValues>) => Promise<unknown>
/**
* Extra query keys to invalidate after `run` succeeds. The table's own
@@ -127,7 +158,7 @@ export function BulkActionBar({ selectedIds, actions, onDone }: BulkActionBarPro
async function execute(action: BulkAction<any>, formValues?: unknown) {
setRunning(true)
try {
- await action.run({ ids: selectedIds, formValues })
+ const result = await action.run({ ids: selectedIds, formValues })
// Invalidate the action's declared cross-resource keys BEFORE `onDone`
// (which invalidates the host table's own key). Without this, pages
// like Customer Groups that cache `customers_count` won't refresh
@@ -140,7 +171,8 @@ export function BulkActionBar({ selectedIds, actions, onDone }: BulkActionBarPro
type: 'success',
title: interpolate(
action.successMessage ?? t('admin.components.bulk_action_bar.default_success'),
- count,
+ // What the server did, when it said — otherwise what was selected.
+ outcomeCount(result) ?? count,
),
})
onDone()
diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.json
index 06dfbf025d..7fb833a304 100644
--- a/packages/seller-dashboard/src/locales/en.json
+++ b/packages/seller-dashboard/src/locales/en.json
@@ -16,7 +16,9 @@
"name": "Seller panel"
},
"common": {
+ "apply": "Apply",
"cancel": "Cancel",
+ "delete": "Delete",
"error": "Something went wrong.",
"loading": "Loading…",
"remove": "Remove",
@@ -135,6 +137,25 @@
"archive": "Archive",
"archive_confirm_description": "It comes off sale and out of your active listings.",
"archive_confirm_title": "Archive this product?",
+ "bulk": {
+ "delete_confirm_description": "This removes {n} from your catalogue. Shoppers will no longer see them.",
+ "delete_confirm_title": "Delete the selected products?",
+ "delete_failed": "Those products could not be deleted.",
+ "deleted": "Deleted {n} products",
+ "set_status_action": "Set status",
+ "skipped_one": "{{count}} was left alone. {{message}}",
+ "skipped_other": "{{count}} were left alone. {{message}}",
+ "skipped_refused": "The marketplace would not let them move. Open one to see why.",
+ "skipped_submit": "Only draft listings and ones the marketplace asked you to change can be submitted.",
+ "status_dialog_description": "Take these listings down while you work on them, or archive them for good. Putting a product on sale is the marketplace’s decision — submit it for review instead.",
+ "status_dialog_title": "Set status",
+ "status_update_failed": "Those products could not be updated.",
+ "status_updated": "Updated {n} products",
+ "submit_confirm_description": "The marketplace will review {n} products and decide whether to put them on sale.",
+ "submit_confirm_title": "Submit the selected products for review?",
+ "submit_failed": "Those products could not be submitted.",
+ "submitted": "Submitted {n} products for review"
+ },
"columns": {
"name": "Product",
"price": "Price",
diff --git a/packages/seller-dashboard/src/pages/products.tsx b/packages/seller-dashboard/src/pages/products.tsx
index 9f29c6b707..ab83233fa5 100644
--- a/packages/seller-dashboard/src/pages/products.tsx
+++ b/packages/seller-dashboard/src/pages/products.tsx
@@ -1,12 +1,43 @@
-import { type ResourceSearch, ResourceTable } from '@spree/dashboard-core'
-import { Button, useRowClickBridge } from '@spree/dashboard-ui'
-import type { Product } from '@spree/seller-sdk'
+import type {
+ BulkAction,
+ BulkActionFormProps,
+ BulkActionOutcome,
+ ResourceSearch,
+} from '@spree/dashboard-core'
+import { ResourceTable, Subject } from '@spree/dashboard-core'
+import {
+ BulkDialog,
+ Button,
+ Field,
+ FieldLabel,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ toastManager,
+ useRowClickBridge,
+} from '@spree/dashboard-ui'
+import type { BulkProductResult, Product } from '@spree/seller-sdk'
import { useNavigate, useParams } from '@tanstack/react-router'
-import { PlusIcon } from 'lucide-react'
+import { ArchiveIcon, PlusIcon, SendIcon, Trash2Icon } from 'lucide-react'
+import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { sellerClient } from '../api-client'
import '../tables/products'
+/**
+ * The statuses a seller may move a selection to.
+ *
+ * `active` is absent by design: a listing goes on sale when the marketplace
+ * approves it, so the only moves offered here are the two a seller makes
+ * alone (docs/plans/6.0-seller-product-submission.md).
+ */
+const BULK_STATUSES = ['draft', 'archived'] as const
+
+type BulkStatus = (typeof BULK_STATUSES)[number]
+type StatusFormValues = { status: BulkStatus }
+
/** This seller's own catalog. */
export function ProductsPage({ search }: { search: ResourceSearch }) {
const { t } = useTranslation()
@@ -18,6 +49,83 @@ export function ProductsPage({ search }: { search: ResourceSearch }) {
useRowClickBridge('data-product-id', open)
+ const bulkActions = useMemo<BulkAction<unknown>[]>(() => {
+ // These endpoints move what they can and leave the rest, so the selection
+ // size is not the outcome. The success toast is told what the server
+ // actually did, and anything it left alone gets a second toast saying so —
+ // otherwise "15 submitted" sits next to "12 were left alone".
+ const report = (result: BulkProductResult, skippedMessage: string): BulkActionOutcome => {
+ if (result.skipped_count) {
+ toastManager.add({
+ type: 'info',
+ title: t('products.bulk.skipped', {
+ count: result.skipped_count,
+ message: skippedMessage,
+ }),
+ })
+ }
+
+ return { count: result.product_count }
+ }
+
+ const submitAction: BulkAction<unknown> = {
+ key: 'submit-for-review',
+ label: t('products.submit_for_review'),
+ icon: <SendIcon className="size-4" />,
+ subject: Subject.Product,
+ confirm: {
+ title: t('products.bulk.submit_confirm_title'),
+ message: t('products.bulk.submit_confirm_description'),
+ confirmLabel: t('products.submit_for_review'),
+ },
+ run: async ({ ids }) =>
+ report(
+ await sellerClient().products.bulkSubmit({ ids }),
+ t('products.bulk.skipped_submit'),
+ ),
+ successMessage: t('products.bulk.submitted'),
+ errorMessage: t('products.bulk.submit_failed'),
+ }
+
+ const statusAction: BulkAction<StatusFormValues> = {
+ key: 'set-status',
+ label: t('products.bulk.set_status_action'),
+ icon: <ArchiveIcon className="size-4" />,
+ subject: Subject.Product,
+ form: (props) => <StatusPickerDialog {...props} />,
+ run: async ({ ids, formValues }) =>
+ report(
+ await sellerClient().products.bulkStatusUpdate({ ids, status: formValues!.status }),
+ t('products.bulk.skipped_refused'),
+ ),
+ successMessage: t('products.bulk.status_updated'),
+ errorMessage: t('products.bulk.status_update_failed'),
+ }
+
+ const deleteAction: BulkAction<unknown> = {
+ key: 'delete',
+ label: t('common.delete'),
+ icon: <Trash2Icon className="size-4" />,
+ subject: Subject.Product,
+ action: 'destroy',
+ confirm: {
+ title: t('products.bulk.delete_confirm_title'),
+ message: t('products.bulk.delete_confirm_description'),
+ confirmLabel: t('common.delete'),
+ variant: 'destructive',
+ },
+ run: async ({ ids }) =>
+ report(
+ await sellerClient().products.bulkDestroy({ ids }),
+ t('products.bulk.skipped_refused'),
+ ),
+ successMessage: t('products.bulk.deleted'),
+ errorMessage: t('products.bulk.delete_failed'),
+ }
+
+ return [submitAction, statusAction, deleteAction] as BulkAction<unknown>[]
+ }, [t])
+
return (
<div className="flex flex-col gap-4">
<h1 className="font-medium text-2xl">{t('products.title')}</h1>
@@ -27,6 +135,7 @@ export function ProductsPage({ search }: { search: ResourceSearch }) {
queryKey="seller-products"
queryFn={(params) => sellerClient().products.list(params)}
searchParams={search}
+ bulkActions={bulkActions}
actions={
<Button onClick={() => navigate({ to: '/$sellerId/products/new', params: { sellerId } })}>
<PlusIcon className="size-4" />
@@ -37,3 +146,43 @@ export function ProductsPage({ search }: { search: ResourceSearch }) {
</div>
)
}
+
+function StatusPickerDialog({ onSubmit, onCancel }: BulkActionFormProps<StatusFormValues>) {
+ const { t } = useTranslation()
+ const [status, setStatus] = useState<BulkStatus>('draft')
+
+ const statusItems = BULK_STATUSES.map((value) => ({
+ value,
+ label: t(`products.statuses.${value}`),
+ }))
+
+ return (
+ <BulkDialog
+ title={t('products.bulk.status_dialog_title')}
+ description={t('products.bulk.status_dialog_description')}
+ submitLabel={t('common.apply')}
+ onCancel={onCancel}
+ onSubmit={() => onSubmit({ status })}
+ >
+ <Field>
+ <FieldLabel>{t('products.fields.status')}</FieldLabel>
+ <Select
+ items={statusItems}
+ value={status}
+ onValueChange={(value) => setStatus(value as BulkStatus)}
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {statusItems.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ </BulkDialog>
+ )
+}
diff --git a/packages/seller-sdk/src/index.ts b/packages/seller-sdk/src/index.ts
index f5af2c7a91..5dd0ca3503 100644
--- a/packages/seller-sdk/src/index.ts
+++ b/packages/seller-sdk/src/index.ts
@@ -7,6 +7,7 @@ export { SpreeError } from '@spree/sdk-core'
export type { Client, Client as SellerApiClient, SellerClientConfig } from './client'
export { createSellerClient } from './client'
export type {
+ BulkProductResult,
MeResponse,
OnboardingResponse,
PermissionRule,
diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.ts
index c89558b6fc..c8ce6e5e98 100644
--- a/packages/seller-sdk/src/seller-client.ts
+++ b/packages/seller-sdk/src/seller-client.ts
@@ -271,6 +271,36 @@ export class SellerClient {
archive: (id: string, options?: RequestOptions): Promise<Product> =>
this.request<Product>('PATCH', `/products/${id}/archive`, options),
+
+ /**
+ * Submit a selection for review.
+ *
+ * Only a draft or a rejected listing can be submitted, so a mixed
+ * selection moves what it can: `product_count` is what was submitted and
+ * `skipped_count` — present only when something was skipped — is what was
+ * already on sale, already in review, or archived.
+ */
+ bulkSubmit: (params: { ids: string[] }, options?: RequestOptions): Promise<BulkProductResult> =>
+ this.request('POST', '/products/bulk_submit', { ...options, body: params }),
+
+ /**
+ * Move a selection to `draft` or `archived`.
+ *
+ * There is no bulk route onto `active`: a listing goes on sale when the
+ * marketplace approves it, one at a time.
+ */
+ bulkStatusUpdate: (
+ params: { ids: string[]; status: 'draft' | 'archived' },
+ options?: RequestOptions,
+ ): Promise<BulkProductResult> =>
+ this.request('POST', '/products/bulk_status_update', { ...options, body: params }),
+
+ /** Delete a selection. Ids outside this seller's catalog are ignored. */
+ bulkDestroy: (
+ params: { ids: string[] },
+ options?: RequestOptions,
+ ): Promise<BulkProductResult> =>
+ this.request('DELETE', '/products/bulk_destroy', { ...options, body: params }),
}
/**
@@ -429,6 +459,16 @@ export interface RequirementSubmissionParams {
}
/** The fields a seller may set on their own product. */
+/**
+ * What a bulk product action did. `skipped_count` is present only when the
+ * action left something alone — a key on every response would tell a caller
+ * that never skips anything that nothing was skipped.
+ */
+export interface BulkProductResult {
+ product_count: number
+ skipped_count?: number
+}
+
export interface ProductParams {
name?: string
description?: string
diff --git a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
index 6406218b84..4f96041d7f 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/products_controller.rb
@@ -27,9 +27,20 @@ module Spree
# labelling their product
# (docs/plans/6.0-multi-vendor-marketplace.md).
class ProductsController < Seller::ResourceController
+ # The statuses a seller may move a selection to, each paired with the
+ # workflow that gets it there. A map rather than a status list
+ # because these moves are not attribute writes: taking a listing down
+ # settles the submission the seller had open, which `update_all`
+ # would leave sitting as `pending` forever.
+ SELLER_BULK_STATUS_WORKFLOWS = {
+ 'draft' => -> { Spree.product_draft_workflow },
+ 'archived' => -> { Spree.product_archive_workflow }
+ }.freeze
+
scoped_resource :products
before_action :set_status_resource, only: [:submit, :draft, :archive]
+ before_action :require_ids!, only: [:bulk_submit, :bulk_status_update, :bulk_destroy]
# PATCH /api/v3/seller/products/:id/submit
#
@@ -52,6 +63,75 @@ module Spree
run_status_workflow(Spree.product_archive_workflow)
end
+ # POST /api/v3/seller/products/bulk_submit
+ # Body: { ids: [...] }
+ #
+ # Asking the marketplace to review a selection.
+ def bulk_submit
+ authorize! :update, model_class
+
+ # Judged on whether the product moved, not on the result: where a
+ # store auto-approves, Propose commits the submission and then
+ # chains into Approve, returning *its* result. A product that went
+ # into review and then failed to go on sale was still submitted,
+ # and counting it as skipped would tell the seller their draft was
+ # not eligible when it is now sitting in review.
+ render json: run_bulk(seller_bulk_scope(:update)) { |product|
+ was = product.status
+
+ Spree.product_propose_workflow.call(product: product,
+ submitted_by: try_spree_current_user)
+
+ # A product Propose refused is untouched; one it accepted is in
+ # review or already through it.
+ product.reload.status != was
+ }
+ end
+
+ # POST /api/v3/seller/products/bulk_status_update
+ # Body: { ids: [...], status: 'draft' | 'archived' }
+ #
+ # The two moves a seller makes alone. `active` is absent by design:
+ # a listing goes on sale when the operator approves it, so there is
+ # no status a seller can assign that reaches it
+ # (docs/plans/6.0-seller-product-submission.md).
+ def bulk_status_update
+ authorize! :update, model_class
+
+ resolve_workflow = SELLER_BULK_STATUS_WORKFLOWS[params[:status].to_s]
+
+ if resolve_workflow.nil?
+ return render_error(
+ code: 'invalid_status',
+ message: Spree.t(:invalid_status, scope: 'errors.messages', default: 'Invalid status'),
+ status: :unprocessable_content
+ )
+ end
+
+ # Resolved at call time, not at load: the workflow is a
+ # configurable dependency, so a host that swaps it must be honoured
+ # rather than frozen into the constant at boot.
+ run_bulk_workflow(resolve_workflow.call)
+ end
+
+ # DELETE /api/v3/seller/products/bulk_destroy
+ # Body: { ids: [...] }
+ def bulk_destroy
+ authorize! :destroy, model_class
+
+ # Scoped by `:destroy` rather than reusing `bulk_collection`,
+ # which is `:update`-scoped: a seller who may edit their catalog
+ # but not delete from it must not delete through the bulk route.
+ #
+ # `Products::Destroy` exists so a store can refuse a deletion, so
+ # this reports refusals like the status actions do — a product that
+ # survives while the response says it was deleted is the one
+ # outcome a merchant must never be shown.
+ render json: run_bulk(seller_bulk_scope(:destroy)) { |product|
+ Spree.product_destroy_workflow.call(product: product)
+ }
+ end
+
protected
def model_class
@@ -158,6 +238,107 @@ module Spree
private
+ # 422s when the caller omits `ids` entirely, matching the operator's
+ # bulk endpoints. An explicit empty array is a no-op, which is what a
+ # UI whose selection was cleared between render and submit sends.
+ def require_ids!
+ return if params.key?(:ids)
+
+ render_error(
+ code: 'missing_ids',
+ message: 'ids is required (send an empty array to no-op).',
+ status: :unprocessable_content
+ )
+ end
+
+ # The selection, rooted in this seller's own catalog.
+ #
+ # Deliberately not the shared `BulkOperations#bulk_collection`, which
+ # roots at `for_store(current_store)` — on a marketplace that is
+ # every seller's catalog, so one seller's ids param would reach
+ # another's products. Ids outside this seller's rows are dropped
+ # silently, exactly as the operator's endpoints drop ids from
+ # another store.
+ #
+ # @param action [Symbol] the ability action to scope by
+ # @return [ActiveRecord::Relation]
+ def seller_bulk_scope(action)
+ current_seller.products.accessible_by(current_ability, action).
+ where(id: decode_bulk_ids(params[:ids]))
+ end
+
+ # Runs a status workflow over the selection, one record at a time.
+ #
+ # A loop rather than `update_all`: each of these moves has side
+ # effects the column write does not carry — settling an open
+ # submission, announcing the change — and every workflow refuses a
+ # product it cannot legally move. A refusal is skipped rather than
+ # fatal, so a mixed selection still moves the rows that can move and
+ # the response says how many did not
+ # (docs/plans/6.0-seller-product-submission.md).
+ def run_bulk_workflow(workflow, **arguments)
+ render json: run_bulk(seller_bulk_scope(:update)) { |product|
+ workflow.call(product: product, **arguments)
+ }
+ end
+
+ # Runs a per-record operation over a selection and counts what
+ # happened.
+ #
+ # Each record is rescued on its own. Every one of these workflows
+ # opens its own transaction, so a raise partway through leaves the
+ # records before it committed — letting it escape would answer a
+ # half-done batch with "none of them worked", which is the one
+ # description of the outcome that is certainly false. A record that
+ # raises is counted as skipped, exactly like one that refused.
+ #
+ # @return [Hash] the response payload
+ def run_bulk(records)
+ done = 0
+ skipped = 0
+
+ records.each do |record|
+ begin
+ bulk_succeeded?(yield(record)) ? done += 1 : skipped += 1
+ rescue StandardError => error
+ # Surfaced rather than swallowed: a raise here is a bug or a
+ # host hook misbehaving, and the count alone would never lead
+ # anyone to it.
+ Rails.error.report(error, handled: true, context: { product_id: record.id })
+ skipped += 1
+ end
+ end
+
+ payload = { product_count: done }
+ # Only when it happened: a key on every response would tell clients
+ # that never skip anything that nothing was skipped.
+ payload[:skipped_count] = skipped if skipped.positive?
+ payload
+ end
+
+ # A block may answer with the workflow's own Result, or with a plain
+ # boolean where the caller decides what counts as done by looking at
+ # the record rather than the result.
+ def bulk_succeeded?(outcome)
+ outcome.respond_to?(:success?) ? outcome.success? : !!outcome
+ end
+
+ # Inbound ids are a mix of prefixed (`prod_…`) and raw.
+ #
+ # Decoded through the model rather than `PrefixedId` directly, so the
+ # prefix class is checked: a `variant_…` id decodes to a bare integer
+ # that would otherwise match whichever product happens to carry it.
+ # A mismatched prefix drops out and matches nothing, which is what a
+ # mistyped id should do. Raw ids pass through for callers that send
+ # them.
+ def decode_bulk_ids(ids)
+ Array(ids).filter_map do |id|
+ next id unless Spree::PrefixedId.prefixed_id?(id)
+
+ model_class.decode_own_prefixed_id(id)
+ end
+ end
+
# Named apart from the base class's own resource lookup: overriding
# that one changes every action, and these three are the only ones
# that move a status.
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 3708b5d833..2bf14d2eaa 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -746,6 +746,15 @@ Spree::Core::Engine.add_routes do
patch :draft
patch :archive
end
+
+ # The same three moves over a selection. Only the ones a seller may
+ # make alone: there is no bulk route onto `active`, because reaching
+ # it is the operator's decision on one listing at a time.
+ collection do
+ post :bulk_submit
+ post :bulk_status_update
+ delete :bulk_destroy
+ end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
index c58ad2db26..e798b645ad 100644
--- a/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/seller/products_controller_spec.rb
@@ -384,4 +384,205 @@ RSpec.describe Spree::Api::V3::Seller::ProductsController, type: :controller do
expect(response).to have_http_status(:forbidden)
end
end
+
+ describe 'bulk actions' do
+ let!(:unlisted) { create(:product, name: 'Unlisted', seller: seller, store: store, status: 'draft') }
+ let!(:theirs_draft) { create(:product, seller: other_seller, store: store, status: 'draft') }
+
+ describe 'POST #bulk_submit' do
+ it 'submits the selection for review' do
+ post :bulk_submit, params: { ids: [unlisted.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['product_count']).to eq(1)
+ expect(unlisted.reload).to be_proposed
+ end
+
+ # The point of skipping rather than refusing: a merchant selecting a
+ # page of products should still submit the ones that can move.
+ it 'skips products it cannot submit and reports how many' do
+ post :bulk_submit, params: { ids: [unlisted.prefixed_id, mine.prefixed_id] }, as: :json
+
+ expect(json_response['product_count']).to eq(1)
+ expect(json_response['skipped_count']).to eq(1)
+ expect(unlisted.reload).to be_proposed
+ expect(mine.reload).to be_active
+ end
+
+ it 'omits the skipped count when everything moved' do
+ post :bulk_submit, params: { ids: [unlisted.prefixed_id] }, as: :json
+
+ expect(json_response).not_to have_key('skipped_count')
+ end
+
+ # The whole reason this endpoint cannot reuse the shared
+ # `bulk_collection`: on a marketplace that relation spans every seller.
+ it "ignores another seller's ids" do
+ post :bulk_submit, params: { ids: [theirs_draft.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['product_count']).to eq(0)
+ expect(theirs_draft.reload).to be_draft
+ end
+
+ it 'ignores the marketplace\'s own products' do
+ first_party.update!(status: 'draft')
+
+ post :bulk_submit, params: { ids: [first_party.prefixed_id] }, as: :json
+
+ expect(json_response['product_count']).to eq(0)
+ expect(first_party.reload).to be_draft
+ end
+
+ it '422s when ids is missing entirely' do
+ post :bulk_submit, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ # A prefixed id names its own class. Decoding one from another model
+ # yields a bare integer that would otherwise match whichever product
+ # happens to carry it.
+ it "ignores an id from another model that decodes onto a product's row" do
+ variant_id = Spree::Variant.new(id: unlisted.id).prefixed_id
+
+ post :bulk_submit, params: { ids: [variant_id] }, as: :json
+
+ expect(json_response['product_count']).to eq(0)
+ expect(unlisted.reload).to be_draft
+ end
+
+ it 'accepts an empty selection as a no-op' do
+ post :bulk_submit, params: { ids: [] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['product_count']).to eq(0)
+ end
+
+ # Each workflow opens its own transaction, so a raise partway through
+ # leaves the products before it committed. Reporting the whole batch as
+ # failed would be the one description of that outcome that is false.
+ it 'keeps counting after a product raises' do
+ second = create(:product, seller: seller, store: store, status: 'draft')
+ allow(Spree.product_propose_workflow).to receive(:call).and_call_original
+ allow(Spree.product_propose_workflow).to receive(:call).
+ with(hash_including(product: second)).and_raise(StandardError, 'boom')
+
+ post :bulk_submit, params: { ids: [unlisted.prefixed_id, second.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['product_count']).to eq(1)
+ expect(json_response['skipped_count']).to eq(1)
+ expect(unlisted.reload).to be_proposed
+ end
+
+ # With auto-approval on, Propose commits the submission and then chains
+ # into Approve, returning *its* result. A product that reached review
+ # was submitted, whatever happened next.
+ context 'when the store approves seller products automatically' do
+ before { stub_store_preferences(store, auto_approve_seller_products: true) }
+
+ it 'counts a product whose approval failed as submitted' do
+ allow(Spree.product_approve_workflow).to receive(:call).
+ and_return(Spree::ServiceModule::Result.new(false, unlisted, 'nope'))
+
+ post :bulk_submit, params: { ids: [unlisted.prefixed_id] }, as: :json
+
+ expect(json_response['product_count']).to eq(1)
+ expect(json_response).not_to have_key('skipped_count')
+ expect(unlisted.reload).to be_proposed
+ end
+ end
+ end
+
+ describe 'POST #bulk_status_update' do
+ it 'takes listings back down' do
+ post :bulk_status_update, params: { ids: [mine.prefixed_id], status: 'draft' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload).to be_draft
+ end
+
+ it 'archives listings' do
+ post :bulk_status_update, params: { ids: [mine.prefixed_id], status: 'archived' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(mine.reload).to be_archived
+ end
+
+ # Reaching `active` is the operator's decision on one listing at a time,
+ # so there is no seller-side bulk route onto it.
+ it 'refuses active' do
+ post :bulk_status_update, params: { ids: [unlisted.prefixed_id], status: 'active' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(unlisted.reload).to be_draft
+ end
+
+ it 'refuses the review statuses' do
+ post :bulk_status_update, params: { ids: [unlisted.prefixed_id], status: 'proposed' }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(unlisted.reload).to be_draft
+ end
+
+ it "ignores another seller's ids" do
+ post :bulk_status_update, params: { ids: [theirs_draft.prefixed_id], status: 'archived' }, as: :json
+
+ expect(json_response['product_count']).to eq(0)
+ expect(theirs_draft.reload).to be_draft
+ end
+
+ # Taking a listing down settles the submission the seller had open —
+ # the reason this loops the workflow instead of writing the column.
+ it 'withdraws an open submission' do
+ unlisted.update!(status: 'proposed')
+ submission = unlisted.submissions.create!(status: 'pending')
+
+ post :bulk_status_update, params: { ids: [unlisted.prefixed_id], status: 'draft' }, as: :json
+
+ expect(unlisted.reload).to be_draft
+ expect(submission.reload).not_to be_pending
+ end
+ end
+
+ describe 'DELETE #bulk_destroy' do
+ it 'deletes the selection' do
+ delete :bulk_destroy, params: { ids: [mine.prefixed_id, unlisted.prefixed_id] }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['product_count']).to eq(2)
+ expect(Spree::Product.where(id: [mine.id, unlisted.id])).to be_empty
+ end
+
+ it "leaves another seller's products alone" do
+ delete :bulk_destroy, params: { ids: [theirs_draft.prefixed_id] }, as: :json
+
+ expect(json_response['product_count']).to eq(0)
+ expect(theirs_draft.reload).to be_persisted
+ end
+
+ it '422s when ids is missing entirely' do
+ delete :bulk_destroy, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ # `Products::Destroy` exists so a store can refuse a deletion. A product
+ # that survives while the response says it was deleted is the one
+ # outcome a merchant must never be shown.
+ it 'reports a refused deletion as skipped' do
+ allow(Spree.product_destroy_workflow).to receive(:call).and_call_original
+ allow(Spree.product_destroy_workflow).to receive(:call).
+ with(hash_including(product: mine)).
+ and_return(Spree::ServiceModule::Result.new(false, mine, 'nope'))
+
+ delete :bulk_destroy, params: { ids: [mine.prefixed_id, unlisted.prefixed_id] }, as: :json
+
+ expect(json_response['product_count']).to eq(1)
+ expect(json_response['skipped_count']).to eq(1)
+ expect(mine.reload).to be_persisted
+ end
+ end
+ end
end