Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix the expand parameter, and other review findings
Damian Legawiec99cfdf7da9d0
diff --git a/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx b/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsxindex 3d8cd9eafc..90290f41a0 100644--- a/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx+++ b/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx@@ -45,11 +45,14 @@ export function FulfillmentSplitDialog({const confirm = useConfirm()const { split } = useFulfillmentActions(orderId)- const units = (fulfillment.fulfillment_items ?? []).map((item) => ({- value: item.variant_id ?? item.id,- label: unitLabel(item),- quantity: item.quantity,- }))+ // The endpoint addresses what to move by variant, so a row without one is+ // not splittable — offering it would 404 on a unit the seller just picked+ // out of their own parcel.+ const units = (fulfillment.fulfillment_items ?? []).flatMap((item) =>+ item.variant_id+ ? [{ value: item.variant_id, label: unitLabel(item), quantity: item.quantity }]+ : [],+ )const [variantId, setVariantId] = useState(units[0]?.value ?? '')const [quantity, setQuantity] = useState(1)diff --git a/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx b/packages/seller-dashboard/src/components/orders/fulfillments-card.tsxindex 3038ab591f..f1dee5436b 100644--- a/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx+++ b/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx@@ -199,12 +199,18 @@ function FulfillmentRow({ orderId, fulfillment }: { orderId: string; fulfillment)}</CardContent>- <FulfillmentTrackingDialog- orderId={orderId}- fulfillment={fulfillment}- open={trackingOpen}- onOpenChange={setTrackingOpen}- />+ {/* Mounted only while open, so the form seeds from the parcel as it is+ now. Left mounted, its defaults froze at first render — and after+ shipping through the fulfil form, "Edit tracking" would open empty+ and save that emptiness over a real number. */}+ {trackingOpen && (+ <FulfillmentTrackingDialog+ orderId={orderId}+ fulfillment={fulfillment}+ open+ onOpenChange={setTrackingOpen}+ />+ )}{splittable && (<FulfillmentSplitDialogorderId={orderId}diff --git a/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx b/packages/seller-dashboard/src/components/orders/post-sale-cards.tsxindex 4ed8bbbac6..c698059bb5 100644--- a/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx+++ b/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx@@ -175,6 +175,17 @@ export function ClaimsCard({ order }: { order: Order }) {const claims = data?.data ?? []const canCreate = (order.items ?? []).length > 0+ async function handleCancel(id: string) {+ const ok = await confirm({+ title: t('orders.post_sale.claims.cancel_title'),+ message: t('orders.post_sale.claims.cancel_message'),+ variant: 'destructive',+ confirmLabel: t('orders.post_sale.cancel'),+ })+ if (!ok) return+ cancel.mutate(id)+ }+async function handleDeny(id: string) {const ok = await confirm({title: t('orders.post_sale.claims.deny_title'),@@ -245,7 +256,7 @@ export function ClaimsCard({ order }: { order: Order }) {<DropdownMenuSeparator /><DropdownMenuItemvariant="destructive"- onClick={() => cancel.mutate(claim.id)}+ onClick={() => handleCancel(claim.id)}>{t('orders.post_sale.cancel')}</DropdownMenuItem>@@ -307,13 +318,23 @@ function ResolveClaimDialog({const [amount, setAmount] = useState('')const [method, setMethod] = useState<'original_payment' | 'store_credit'>('store_credit')+ // A replacement resolution only works when a line was opened asking for+ // one, and nothing on this branch flags a line yet — so offering it would+ // guarantee a 422 for a choice the seller made in good faith. The options+ // follow what the claim actually carries.+ const replaceable = (claim.claim_line_items ?? []).some((line) => line.send_replacement)+const resolutionOptions = [{ value: 'refund', label: t('orders.post_sale.claims.resolutions.refund') },- { value: 'replacement', label: t('orders.post_sale.claims.resolutions.replacement') },- {- value: 'refund_and_replacement',- label: t('orders.post_sale.claims.resolutions.refund_and_replacement'),- },+ ...(replaceable+ ? [+ { value: 'replacement', label: t('orders.post_sale.claims.resolutions.replacement') },+ {+ value: 'refund_and_replacement',+ label: t('orders.post_sale.claims.resolutions.refund_and_replacement'),+ },+ ]+ : []),]const methodOptions = [{ value: 'store_credit', label: t('orders.post_sale.returns.store_credit') },diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.jsonindex ebba8797db..6ce0063caa 100644--- a/packages/seller-dashboard/src/locales/en.json+++ b/packages/seller-dashboard/src/locales/en.json@@ -384,7 +384,9 @@},"deny": "Deny","deny_title": "Deny this claim?",- "deny_message": "The customer is told the claim was not upheld."+ "deny_message": "The customer is told the claim was not upheld.",+ "cancel_title": "Cancel this claim?",+ "cancel_message": "The customer is told it will not go ahead."}}},diff --git a/packages/seller-sdk/src/seller-client.ts b/packages/seller-sdk/src/seller-client.tsindex 640c97622b..c06abf5046 100644--- a/packages/seller-sdk/src/seller-client.ts+++ b/packages/seller-sdk/src/seller-client.ts@@ -577,13 +577,13 @@ export class SellerClient {...options,// The nested collections are expand-gated server-side, so a bare// list answers with the record and none of its contents.- params: { expand: ['return_line_items', 'return_line_items.variant', 'reason'] },+ params: { expand: 'return_line_items,return_line_items.variant,reason' },}),get: (orderId: string, id: string, options?: RequestOptions): Promise<Return> =>this.request<Return>('GET', `/orders/${orderId}/returns/${id}`, {...options,- params: { expand: ['return_line_items', 'return_line_items.variant', 'reason'] },+ params: { expand: 'return_line_items,return_line_items.variant,reason' },}),create: (@@ -647,12 +647,8 @@ export class SellerClient {// The nested collections are expand-gated server-side, so a bare// list answers with the record and none of its contents.params: {- expand: [- 'exchange_line_items',- 'exchange_line_items.original_variant',- 'exchange_line_items.new_variant',- 'reason',- ],+ expand:+ 'exchange_line_items,exchange_line_items.original_variant,exchange_line_items.new_variant,reason',},}),@@ -660,12 +656,8 @@ export class SellerClient {this.request<Exchange>('GET', `/orders/${orderId}/exchanges/${id}`, {...options,params: {- expand: [- 'exchange_line_items',- 'exchange_line_items.original_variant',- 'exchange_line_items.new_variant',- 'reason',- ],+ expand:+ 'exchange_line_items,exchange_line_items.original_variant,exchange_line_items.new_variant,reason',},}),@@ -734,13 +726,13 @@ export class SellerClient {...options,// The nested collections are expand-gated server-side, so a bare// list answers with the record and none of its contents.- params: { expand: ['claim_line_items', 'claim_line_items.variant', 'reason'] },+ params: { expand: 'claim_line_items,claim_line_items.variant,reason' },}),get: (orderId: string, id: string, options?: RequestOptions): Promise<Claim> =>this.request<Claim>('GET', `/orders/${orderId}/claims/${id}`, {...options,- params: { expand: ['claim_line_items', 'claim_line_items.variant', 'reason'] },+ params: { expand: 'claim_line_items,claim_line_items.variant,reason' },}),create: (diff --git a/packages/seller-sdk/tests/mocks/server.ts b/packages/seller-sdk/tests/mocks/server.tsnew file mode 100644index 0000000000..117f526d06--- /dev/null+++ b/packages/seller-sdk/tests/mocks/server.ts@@ -0,0 +1,8 @@+import { setupServer } from 'msw/node'++/**+ * Shared MSW server. Handlers are registered per test with `server.use`, since+ * what these tests assert is the request the client makes rather than any+ * particular response body.+ */+export const server = setupServer()diff --git a/packages/seller-sdk/tests/post-sale-expand.test.ts b/packages/seller-sdk/tests/post-sale-expand.test.tsnew file mode 100644index 0000000000..4af6e91120--- /dev/null+++ b/packages/seller-sdk/tests/post-sale-expand.test.ts@@ -0,0 +1,65 @@+import { HttpResponse, http } from 'msw'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { createSellerClient } from '../src'+import { server } from './mocks/server'++/**+ * The post-sale endpoints gate their line items behind `expand`, so what the+ * client puts in the query string is the difference between a card that+ * renders its contents and one that renders an empty shell.+ *+ * These assert the raw query string rather than the parsed params, because the+ * bug they exist for was a *shape* bug: an array became repeated `expand=`+ * params, and Rack collapses those to the last value — so the server saw only+ * `reason` and every line item silently vanished. A test reading the client's+ * own options object would have passed.+ */+const requested: string[] = []++function record(path: string) {+ return http.get(`http://api.test/api/v3/seller/orders/:orderId/${path}`, ({ request }) => {+ requested.push(new URL(request.url).search)+ return HttpResponse.json({ data: [] })+ })+}++beforeEach(() => {+ server.use(record('returns'), record('exchanges'), record('claims'))+})+afterEach(() => {+ requested.length = 0+})++function client() {+ return createSellerClient({ baseUrl: 'http://api.test', token: 'jwt' })+}++describe('post-sale expand parameters', () => {+ it('asks for a return’s line items as one comma-separated value', async () => {+ await client().orders.returns.list('or_1')++ const search = requested[0]+ expect(search).toContain('expand=')+ // One expand key, not several — repeated params collapse server-side.+ expect(search.match(/expand=/g)).toHaveLength(1)+ expect(decodeURIComponent(search)).toContain('return_line_items')+ expect(decodeURIComponent(search)).toContain('return_line_items.variant')+ })++ it('asks for an exchange’s line items and both variants', async () => {+ await client().orders.exchanges.list('or_1')++ const search = decodeURIComponent(requested[0])+ expect(search.match(/expand=/g)).toHaveLength(1)+ expect(search).toContain('exchange_line_items.original_variant')+ expect(search).toContain('exchange_line_items.new_variant')+ })++ it('asks for a claim’s line items', async () => {+ await client().orders.claims.list('or_1')++ const search = decodeURIComponent(requested[0])+ expect(search.match(/expand=/g)).toHaveLength(1)+ expect(search).toContain('claim_line_items')+ })+})diff --git a/packages/seller-sdk/tests/setup.ts b/packages/seller-sdk/tests/setup.tsnew file mode 100644index 0000000000..e7d6d1a8fe--- /dev/null+++ b/packages/seller-sdk/tests/setup.ts@@ -0,0 +1,6 @@+import { afterAll, afterEach, beforeAll } from 'vitest'+import { server } from './mocks/server'++beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))+afterEach(() => server.resetHandlers())+afterAll(() => server.close())diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rbindex 3b5b14e432..86fa4224b3 100644--- a/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/claims_controller.rb@@ -11,8 +11,6 @@ module Spree# the claimed lines and any replacement variant resolved through the# order and the seller's own catalogue.class ClaimsController < Seller::ResourceController- include Spree::Api::V3::OrderLock-# Claims are a subject of the `orders` catalog resource.scoped_resource :orders@@ -47,14 +45,12 @@ module Spree## Settles the claim: a refund, a replacement shipment, or both.def resolve- with_order_lock do- run_workflow(Spree.claim_resolve_workflow,- resolution: params[:resolution],- refund_method: params[:refund_method] || 'store_credit',- amount: params[:amount],- replacement_line_item_ids: replacement_line_item_ids,- resolver: try_spree_current_user)- end+ run_workflow(Spree.claim_resolve_workflow,+ resolution: params[:resolution],+ refund_method: params[:refund_method] || 'store_credit',+ amount: params[:amount],+ replacement_line_item_ids: replacement_line_item_ids,+ resolver: try_spree_current_user)end# PATCH /api/v3/seller/orders/:order_id/claims/:id/denydiff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rbindex e322c85416..a7d95efeed 100644--- a/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/exchanges_controller.rb@@ -12,8 +12,6 @@ module Spree# catalogue, and reaching a rival's variant here would put that# seller's stock on this seller's order.class ExchangesController < Seller::ResourceController- include Spree::Api::V3::OrderLock-# Exchanges are a subject of the `orders` catalog resource.scoped_resource :orders@@ -57,11 +55,9 @@ module Spree# Sends the replacement. Settles a price difference at the same# time, which is why it takes a refund method.def fulfill- with_order_lock do- run_workflow(Spree.exchange_fulfill_workflow,- refund_method: params[:refund_method] || 'store_credit',- refunder: try_spree_current_user)- end+ run_workflow(Spree.exchange_fulfill_workflow,+ refund_method: params[:refund_method] || 'store_credit',+ refunder: try_spree_current_user)end# PATCH /api/v3/seller/orders/:order_id/exchanges/:id/cancel@@ -124,7 +120,9 @@ module Spreeenddef items_for_receive- return nil if params[:items].blank?+ # `nil` means "receive it all as requested"; an empty list means the+ # caller named no units, which must not fall through to that.+ return nil unless params.key?(:items)params.permit(items: [:exchange_line_item_id, :quantity, :resellable])[:items].map do |item|{diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rbindex fc8e0f55d4..27216f1613 100644--- a/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/fulfillments_controller.rb@@ -67,10 +67,12 @@ module Spree# marketplace's arrangements, so this deliberately does not accept# the origin and rate the operator's endpoint does.def update- if @fulfillment.update(update_params)- render json: serialize(@fulfillment.reload)- else- render_validation_error(@fulfillment.errors)+ with_order_lock do+ render_workflow_result(+ Spree.fulfillment_update_workflow.call(+ fulfillment: @fulfillment, fulfillment_attributes: update_params.to_h+ )+ )endenddiff --git a/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rbindex 961dfae7b4..a04949bee8 100644--- a/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/seller/orders/returns_controller.rb@@ -15,8 +15,6 @@ module Spree# the tax credit, the refund and the ledger reversal all happen# exactly as they do when the marketplace handles the return itself.class ReturnsController < Seller::ResourceController- include Spree::Api::V3::OrderLock-# Returns are a subject of the `orders` catalog resource, so# `read_orders`/`write_orders` gate these endpoints. Naming# `:returns` here would name a key no catalog knows.@@ -67,12 +65,10 @@ module Spree# itself and, on a split checkout, by this order's share of the# group's payment — never a sibling's.def refund- with_order_lock do- run_workflow(Spree.return_refund_workflow,- amount: params[:amount],- refund_method: params[:refund_method] || 'original_payment',- refunder: try_spree_current_user)- end+ run_workflow(Spree.return_refund_workflow,+ amount: params[:amount],+ refund_method: params[:refund_method] || 'original_payment',+ refunder: try_spree_current_user)end# PATCH /api/v3/seller/orders/:order_id/returns/:id/cancel@@ -136,7 +132,9 @@ module Spreeenddef items_for_receive- return nil if params[:items].blank?+ # `nil` means "receive it all as requested"; an empty list means the+ # caller named no units, which must not fall through to that.+ return nil unless params.key?(:items)params.permit(items: [:return_line_item_id, :quantity, :resellable])[:items].map do |item|{diff --git a/spree/core/app/workflows/spree/refunds/order_payments.rb b/spree/core/app/workflows/spree/refunds/order_payments.rbindex bed820e4e4..4a9f182c9e 100644--- a/spree/core/app/workflows/spree/refunds/order_payments.rb+++ b/spree/core/app/workflows/spree/refunds/order_payments.rb@@ -22,30 +22,34 @@ module Spreeprivate- # Puts `amount` back on `order`, newest payment first, until it is+ # Puts `amount` back on `order`, oldest payment first, until it is# covered.## A split-tender order needs more than one refund, so this drains rather- # than picking one payment. Every row goes through- # {Spree::Refunds::Create}, which owns the row-locked balance check, the- # gateway credit, the declined-row compensation, the refund hooks and- # the `payment.refunded` event — so nothing here talks to a gateway- # itself.+ # than picking one payment; oldest first, which is the order the customer+ # paid in and the order both branches below read in.+ #+ # Every row goes through {Spree::Refunds::Create}, which owns the+ # row-locked balance check, the gateway credit, the declined-row+ # compensation, the refund hooks and the `payment.refunded` event — so+ # nothing here talks to a gateway itself.## @param order [Spree::Order] the order being put right# @param amount [BigDecimal] how much to give back# @param record [Spree::Return, Spree::Claim, Spree::Exchange] what asked# for the refund; it originates the rows and carries any failure# @param refunder [Object, nil] whoever is issuing it- # @return [Array<Spree::Refund>] the refunds written, newest payment first+ # @return [Array<Spree::Refund>] the refunds written, in drain orderdef refund_order_payments(order:, amount:, record:, refunder: nil)remaining = amount.to_drefunds = []- # The same for every row in the run, and a find_or_create_by — so it- # is resolved once rather than per payment.- reason = Spree::RefundReason.return_processing_reason(record.store)+ shares = refundable_shares(order)+ # Resolved once rather than per payment — but only once there is+ # something to refund, since it is a find_or_create_by and a run that+ # refunds nothing should leave no reason row behind.+ reason = Spree::RefundReason.return_processing_reason(record.store) if shares.any?- refundable_shares(order).each do |payment, refundable|+ shares.each do |payment, refundable|break unless remaining.positive?creditable = [refundable, remaining].min@@ -83,19 +87,20 @@ module Spree# @return [Hash{Spree::Payment => BigDecimal}]def refundable_shares(order)unless order.grouped?- return order.payments.completed.to_h { |payment| [payment, payment.credit_allowed.to_d] }+ return order.payments.completed.order(:created_at).+ to_h { |payment| [payment, payment.credit_allowed.to_d] }end- # One query for the whole run rather than one per share: this is on- # the refund path inside the order's lock, where every round trip- # holds it longer.+ # One query for the whole run rather than one per share — this runs+ # ahead of a gateway round trip per payment, and there is no reason to+ # add N more of its own.refunded = Spree::Refund.where(order_id: order.id).group(:payment_id).sum(:amount)- order.payment_splits.includes(:payment).each_with_object({}) do |split, shares|+ order.payment_splits.includes(:payment).order(:created_at).each_with_object({}) do |split, found|next unless split.payment&.completed?next if capture_in_flight?(order, split)- shares[split.payment] = split.captured_amount - refunded.fetch(split.payment_id, 0)+ found[split.payment] = split.captured_amount - refunded.fetch(split.payment_id, 0)endend