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.

Address review findings on the seller order work

Damian Legawiec38b91d4bf80f
diff --git a/packages/dashboard-core/src/lib/label-upload-form.ts b/packages/dashboard-core/src/lib/label-upload-form.ts
index c037e868da..c2f5bde1cd 100644
--- a/packages/dashboard-core/src/lib/label-upload-form.ts
+++ b/packages/dashboard-core/src/lib/label-upload-form.ts
@@ -8,7 +8,10 @@ import { z } from 'zod'
* number.
*/
export const labelUploadFormSchema = z.object({
- tracking_number: z.string().min(1),
+ // Trimmed before the length check: every consumer trims before sending, so
+ // validating the raw value would let a field of spaces pass and submit
+ // blank.
+ tracking_number: z.string().trim().min(1),
carrier: z.string(),
cost: z.string(),
})
diff --git a/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsx b/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsx
index dadcf11b69..883663c6c3 100644
--- a/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsx
+++ b/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsx
@@ -195,10 +195,11 @@ export function ClaimResolveDialog({
)}
</DialogBody>
<DialogFooter>
- <Button variant="outline" onClick={onClose} disabled={pending}>
+ <Button type="button" variant="outline" onClick={onClose} disabled={pending}>
{t('admin.actions.cancel')}
</Button>
<Button
+ type="button"
disabled={!ready || pending}
onClick={() =>
onSubmit({
diff --git a/packages/dashboard-ui/src/spree/editable-note-card.tsx b/packages/dashboard-ui/src/spree/editable-note-card.tsx
index ed2ee102d6..c3bdc31b32 100644
--- a/packages/dashboard-ui/src/spree/editable-note-card.tsx
+++ b/packages/dashboard-ui/src/spree/editable-note-card.tsx
@@ -39,6 +39,9 @@ export function EditableNoteCard({
<CardTitle>{title}</CardTitle>
<CardAction>
<Button
+ // Explicit: a card on the order page sits inside that page's own
+ // form, and a button with no type submits it.
+ type="button"
variant="ghost"
size="icon-sm"
onClick={() => onEditingChange(!editing)}
diff --git a/packages/dashboard-ui/src/spree/fulfill-items-form.tsx b/packages/dashboard-ui/src/spree/fulfill-items-form.tsx
index 6738b08562..0321d36958 100644
--- a/packages/dashboard-ui/src/spree/fulfill-items-form.tsx
+++ b/packages/dashboard-ui/src/spree/fulfill-items-form.tsx
@@ -154,6 +154,10 @@ export function FulfillItemsForm({
)
const totalAvailable = rows.reduce((sum, row) => sum + row.quantity, 0)
const shipsEverything = totalSelected === totalAvailable
+ // A parcel whose items cannot be addressed by line item has nothing to pick
+ // from, but it still ships — the workflow reads an empty selection as
+ // "everything". Blocking submit would leave it unshippable.
+ const shipsWholeParcel = rows.length === 0
return (
<form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col">
@@ -255,7 +259,11 @@ export function FulfillItemsForm({
<Button type="button" size="sm" variant="outline" onClick={onCancel}>
{t('admin.actions.cancel')}
</Button>
- <Button type="submit" size="sm" disabled={totalSelected === 0 || pending}>
+ <Button
+ type="submit"
+ size="sm"
+ disabled={(totalSelected === 0 && !shipsWholeParcel) || pending}
+ >
{pending ? t('admin.actions.saving') : t('admin.orders.fulfill.submit')}
</Button>
</div>
diff --git a/packages/dashboard-ui/src/spree/return-dialogs.tsx b/packages/dashboard-ui/src/spree/return-dialogs.tsx
index edc879bdb4..164299d91e 100644
--- a/packages/dashboard-ui/src/spree/return-dialogs.tsx
+++ b/packages/dashboard-ui/src/spree/return-dialogs.tsx
@@ -80,7 +80,12 @@ export function ReturnReceiveDialog({
setRows((current) => ({
...current,
[line.id]: {
- quantity: Math.min(Number(event.target.value), line.quantity),
+ // `min`/`max` bind the stepper only — a typed value
+ // reaches onChange unclamped.
+ quantity: Math.max(
+ 0,
+ Math.min(Number(event.target.value) || 0, line.quantity),
+ ),
resellable: current[line.id]?.resellable ?? true,
},
}))
@@ -110,10 +115,11 @@ export function ReturnReceiveDialog({
))}
</DialogBody>
<DialogFooter>
- <Button variant="outline" onClick={onClose} disabled={pending}>
+ <Button type="button" variant="outline" onClick={onClose} disabled={pending}>
{t('admin.actions.cancel')}
</Button>
<Button
+ type="button"
disabled={pending}
onClick={() =>
onSubmit(
@@ -215,10 +221,14 @@ export function ReturnRefundDialog({
</Field>
</DialogBody>
<DialogFooter>
- <Button variant="outline" onClick={onClose} disabled={pending}>
+ <Button type="button" variant="outline" onClick={onClose} disabled={pending}>
{t('admin.actions.cancel')}
</Button>
- <Button disabled={pending} onClick={() => onSubmit({ refundMethod, amount })}>
+ <Button
+ type="button"
+ disabled={pending}
+ onClick={() => onSubmit({ refundMethod, amount })}
+ >
{t('admin.pages.orders.detail.returns.actions.refund')}
</Button>
</DialogFooter>
diff --git a/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx b/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx
index 3084c58ebb..910701aa1f 100644
--- a/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx
+++ b/packages/dashboard/src/components/spree/orders/fulfillment-fulfill-form.tsx
@@ -90,7 +90,10 @@ export function FulfillmentFulfillForm({
const items = values.items
.filter((item) => item.selected && item.quantity > 0)
.map((item) => ({ item_id: item.item_id, quantity: item.quantity }))
- if (items.length === 0) return
+ // Nothing addressable by line item means the whole parcel goes, which is
+ // what an omitted `items` asks for. Only a partial pick that came out
+ // empty is a no-op worth refusing.
+ if (items.length === 0 && rows.length > 0) return
// Recomputed from the submitted values rather than a watched total, so the
// branch is decided by exactly what is being sent.
diff --git a/packages/dashboard/src/components/spree/orders/shipping-label-row.tsx b/packages/dashboard/src/components/spree/orders/shipping-label-row.tsx
index 0f0e93dc10..f12fa65ec2 100644
--- a/packages/dashboard/src/components/spree/orders/shipping-label-row.tsx
+++ b/packages/dashboard/src/components/spree/orders/shipping-label-row.tsx
@@ -8,6 +8,7 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
+ toastManager,
useConfirm,
} from '@spree/dashboard-ui'
import { EllipsisVerticalIcon, PrinterIcon, ReceiptIcon, TrashIcon } from 'lucide-react'
@@ -51,12 +52,21 @@ export function ShippingLabelRow({
async function print() {
if (!label.download_url) return
- await downloadFromApi(
- token,
- label.download_url,
- `${label.tracking_number ?? 'label'}.${label.format ?? 'pdf'}`,
- getApiClient().downloadHeaders?.() ?? {},
- )
+ // A rejected download inside a click handler is otherwise unhandled, so
+ // the file silently never arrives.
+ try {
+ await downloadFromApi(
+ token,
+ label.download_url,
+ `${label.tracking_number ?? 'label'}.${label.format ?? 'pdf'}`,
+ getApiClient().downloadHeaders?.() ?? {},
+ )
+ } catch (error) {
+ toastManager.add({
+ type: 'error',
+ title: error instanceof Error ? error.message : t('admin.errors.unexpected'),
+ })
+ }
}
return (
diff --git a/packages/seller-dashboard/src/components/orders/fulfillment-fulfill-form.tsx b/packages/seller-dashboard/src/components/orders/fulfillment-fulfill-form.tsx
index 068fca57eb..dbcf3bf0e3 100644
--- a/packages/seller-dashboard/src/components/orders/fulfillment-fulfill-form.tsx
+++ b/packages/seller-dashboard/src/components/orders/fulfillment-fulfill-form.tsx
@@ -89,7 +89,10 @@ export function FulfillmentFulfillForm({
const items = values.items
.filter((item) => item.selected && item.quantity > 0)
.map((item) => ({ item_id: item.item_id, quantity: item.quantity }))
- if (items.length === 0) return
+ // Nothing addressable by line item means the whole parcel goes, which is
+ // what an omitted `items` asks for. Only a partial pick that came out
+ // empty is a no-op worth refusing.
+ if (items.length === 0 && rows.length > 0) return
const everything = items.reduce((sum, item) => sum + item.quantity, 0) === totalAvailable
const tracking = values.tracking.trim()
diff --git a/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx b/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx
index 90290f41a0..610637711e 100644
--- a/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx
+++ b/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx
@@ -118,7 +118,10 @@ export function FulfillmentSplitDialog({
min={1}
max={selected?.quantity ?? 1}
value={quantity}
- onChange={(event) => setQuantity(Number(event.target.value))}
+ // Clearing the field yields NaN, which fails every comparison
+ // below — so `invalid` would read false and the split would
+ // send a null quantity.
+ onChange={(event) => setQuantity(Number(event.target.value) || 0)}
/>
{wouldEmpty && <FieldError>{t('orders.fulfillments.split_would_empty')}</FieldError>}
</Field>
diff --git a/packages/seller-dashboard/src/components/orders/order-cards.tsx b/packages/seller-dashboard/src/components/orders/order-cards.tsx
index c2dc5b95e1..65f6101154 100644
--- a/packages/seller-dashboard/src/components/orders/order-cards.tsx
+++ b/packages/seller-dashboard/src/components/orders/order-cards.tsx
@@ -15,6 +15,7 @@ import {
} from '@spree/dashboard-ui'
import { EllipsisVerticalIcon, PencilIcon } from '@spree/dashboard-ui/icons'
import type { Order, OrderAddressParams } from '@spree/seller-sdk'
+import i18n from 'i18next'
import { type ReactNode, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { sellerClient } from '../../api-client'
@@ -49,7 +50,15 @@ function SummaryRow({
function formatDate(iso: string | null | undefined) {
if (!iso) return '—'
- return new Date(iso).toLocaleString()
+ // The panel's own locale, not the browser's — otherwise a seller reading
+ // German sees day and month in the other order.
+ return new Date(iso).toLocaleDateString(i18n.language, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ })
}
/**
diff --git a/packages/seller-dashboard/src/components/orders/shipping-label-row.tsx b/packages/seller-dashboard/src/components/orders/shipping-label-row.tsx
index a4a7b7d57a..637f3ef5d3 100644
--- a/packages/seller-dashboard/src/components/orders/shipping-label-row.tsx
+++ b/packages/seller-dashboard/src/components/orders/shipping-label-row.tsx
@@ -7,6 +7,7 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
+ toastManager,
useConfirm,
} from '@spree/dashboard-ui'
import {
@@ -46,12 +47,21 @@ export function ShippingLabelRow({
async function print() {
if (!label.download_url) return
- await downloadFromApi(
- token,
- label.download_url,
- `${label.tracking_number ?? 'label'}.${label.format ?? 'pdf'}`,
- getApiClient().downloadHeaders?.() ?? {},
- )
+ // A rejected download inside a click handler is otherwise unhandled, so
+ // the file silently never arrives.
+ try {
+ await downloadFromApi(
+ token,
+ label.download_url,
+ `${label.tracking_number ?? 'label'}.${label.format ?? 'pdf'}`,
+ getApiClient().downloadHeaders?.() ?? {},
+ )
+ } catch (error) {
+ toastManager.add({
+ type: 'error',
+ title: error instanceof Error ? error.message : t('admin.errors.unexpected'),
+ })
+ }
}
async function handleDelete() {
diff --git a/packages/seller-dashboard/src/pages/order.tsx b/packages/seller-dashboard/src/pages/order.tsx
index 5dc4e66fe3..28e60a528c 100644
--- a/packages/seller-dashboard/src/pages/order.tsx
+++ b/packages/seller-dashboard/src/pages/order.tsx
@@ -2,6 +2,7 @@ import { PageHeader } from '@spree/dashboard-core'
import { DropdownMenuItem, ResourceLayout, StatusBadge } from '@spree/dashboard-ui'
import { XCircleIcon } from '@spree/dashboard-ui/icons'
import { useParams } from '@tanstack/react-router'
+import i18n from 'i18next'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { CenteredMessage } from '../components/centered-message'
@@ -50,7 +51,15 @@ export function OrderPage() {
title={order.number}
backTo="orders"
subtitle={
- order.completed_at ? new Date(order.completed_at).toLocaleString() : undefined
+ order.completed_at
+ ? new Date(order.completed_at).toLocaleDateString(i18n.language, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit',
+ })
+ : undefined
}
badges={
<>
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/exchange_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/exchange_actions.rb
index a3fe1acc3b..035cf2cdc5 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/orders/exchange_actions.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/exchange_actions.rb
@@ -80,11 +80,10 @@ module Spree
end
def items_for_receive
- # `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)
+ sent = received_items([:exchange_line_item_id, :quantity, :resellable])
+ return nil if sent.nil?
- params.permit(items: [:exchange_line_item_id, :quantity, :resellable])[:items].map do |item|
+ sent.map do |item|
{
exchange_line_item: @resource.exchange_line_items.find_by_prefix_id!(item[:exchange_line_item_id]),
quantity: item[:quantity].to_i,
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb
index 018b3e0393..9d07e36d2b 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/post_sale_actions.rb
@@ -17,6 +17,15 @@ module Spree
module PostSaleActions
extend ActiveSupport::Concern
+ # A payload whose `items` is not a list. Raised out of the params
+ # helper so it cannot be mistaken for a workflow rejection, and
+ # answered as the client mistake it is rather than a 500.
+ class InvalidItems < StandardError; end
+
+ included do
+ rescue_from InvalidItems, with: :render_invalid_items
+ end
+
protected
# Runs one of the record's status workflows and renders the result.
@@ -39,6 +48,33 @@ module Spree
raise NotImplementedError, "#{self.class} must implement #workflow_record_key"
end
+ def render_invalid_items
+ errors = ActiveModel::Errors.new(@resource || model_class.new)
+ errors.add(:items, :invalid)
+ render_validation_error(errors)
+ end
+
+ # The units a receive request named, or nil when it named none.
+ #
+ # An omitted `items` means "receive it all as requested". Naming an
+ # empty list — or an explicit `null`, which is the same statement —
+ # means the caller named no units, and must not fall through to
+ # receive-all. Anything else that is not a list is refused rather
+ # than iterated, which would answer a 500 to a client mistake.
+ #
+ # @param keys [Array<Symbol>] the per-item keys to permit
+ # @return [Array<ActionController::Parameters>, nil]
+ def received_items(keys)
+ return nil unless params.key?(:items)
+
+ sent = params.permit(items: keys)[:items]
+ return [] if sent.nil?
+
+ raise InvalidItems unless sent.respond_to?(:map) && !sent.is_a?(Hash)
+
+ sent
+ end
+
# Opens the record against the order, through the entity's create
# workflow.
def create_post_sale_record(workflow, subject, **arguments)
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/orders/return_actions.rb b/spree/api/app/controllers/concerns/spree/api/v3/orders/return_actions.rb
index 40389efcbf..e13d1a933c 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/orders/return_actions.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/orders/return_actions.rb
@@ -81,11 +81,10 @@ module Spree
# What the warehouse counted, resolved through the return itself.
def items_for_receive
- # `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)
+ sent = received_items([:return_line_item_id, :quantity, :resellable])
+ return nil if sent.nil?
- params.permit(items: [:return_line_item_id, :quantity, :resellable])[:items].map do |item|
+ sent.map do |item|
{
return_line_item: @resource.return_line_items.find_by_prefix_id!(item[:return_line_item_id]),
quantity: item[:quantity].to_i,
diff --git a/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
index 6974211324..33570486fc 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/orders_controller.rb
@@ -68,13 +68,20 @@ module Spree
# the marketplace's, and a write that took whatever the serializer
# permits would quietly grow into one a seller could reprice with.
def address
- attributes = address_params
- return render_validation_error(missing_address_errors) if attributes.blank?
-
- if @resource.update(attributes)
- render json: serialize_resource(@resource.reload)
- else
- render_validation_error(@resource.errors)
+ # Checked before the lock: an empty payload needs no serialization,
+ # and returning out of a locked block is worth avoiding.
+ return render_validation_error(missing_address_errors) if sent_addresses.blank?
+
+ # The merge reads the address it is about to replace, so it runs
+ # under the order's lock: two corrections landing together would
+ # each lay their fields over the same snapshot, and the later one
+ # would undo the earlier one's lines.
+ with_order_lock do
+ if @resource.update(address_params)
+ render json: serialize_resource(@resource.reload)
+ else
+ render_validation_error(@resource.errors)
+ end
end
end
@@ -111,11 +118,15 @@ module Spree
# postcode beside it. The nested writer builds a fresh address row
# either way, which is what keeps a shared customer address book
# entry from being rewritten by an order-level fix.
- def address_params
- permitted = params.permit(
+ def sent_addresses
+ @sent_addresses ||= params.permit(
shipping_address: address_permitted_keys,
billing_address: address_permitted_keys
- )
+ ).slice(:shipping_address, :billing_address).reject { |_key, value| value.blank? }
+ end
+
+ def address_params
+ permitted = sent_addresses
{}.tap do |attributes|
if permitted[:shipping_address].present?
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
index 08cba5edca..142edde87c 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
@@ -116,6 +116,27 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ReturnsController, type: :controll
expect(line.reload.received_quantity).to eq(0)
end
+ # A present-but-null `items` is the same statement as an empty list, and
+ # must not be iterated — that answered a 500 to a client mistake.
+ it 'treats an explicit null item list as naming no units' do
+ line = return_record.return_line_items.first
+
+ patch :receive, params: {
+ order_id: order.prefixed_id, id: return_record.prefixed_id, items: nil
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(line.reload.received_quantity).to eq(0)
+ end
+
+ it 'refuses an item list that is not a list' do
+ patch :receive, params: {
+ order_id: order.prefixed_id, id: return_record.prefixed_id, items: 'everything'
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
it 'records a partial, non-resellable receipt' do
line = return_record.return_line_items.first
diff --git a/spree/core/app/workflows/spree/refunds/create.rb b/spree/core/app/workflows/spree/refunds/create.rb
index 766f975919..4c3797c63e 100644
--- a/spree/core/app/workflows/spree/refunds/create.rb
+++ b/spree/core/app/workflows/spree/refunds/create.rb
@@ -81,8 +81,16 @@ module Spree
# so creation serializes on the payment's row lock. Without it the
# balance validation is check-then-act, and two concurrent refunds would
# both validate against the pre-refund balance and both credit.
+ #
+ # The per-order share is re-read inside the lock for the same reason.
+ # `Spree::Refund` validates against `credit_allowed`, which is the whole
+ # payment's balance and says nothing about whose money it is — so on a
+ # shared payment the model cannot catch two refunds that each fit the
+ # payment but together overdraw one child's share.
def create_refund
payment.with_lock do
+ ensure_share_still_available
+
@refund = payment.refunds.create!(
amount: @amount_to_refund,
order: order || payment.order,
@@ -93,6 +101,16 @@ module Spree
end
end
+ # Re-reads the named order's remaining share now that the payment's row
+ # is locked, so a sibling refund that landed since the pre-flight check
+ # is counted.
+ def ensure_share_still_available
+ return unless payment.grouped?
+
+ payment.payment_splits.reload
+ failure(payment, :refund_amount_exceeds_balance) if @amount_to_refund.to_d > refundable_share
+ end
+
# The store the default reason belongs to. A payment shared by a split
# checkout has no order of its own, so it is asked through whichever
# order is being refunded — and failing that the current store, since a
diff --git a/spree/core/spec/workflows/spree/refunds/create_spec.rb b/spree/core/spec/workflows/spree/refunds/create_spec.rb
index 5c0ff3c10f..28f83040bb 100644
--- a/spree/core/spec/workflows/spree/refunds/create_spec.rb
+++ b/spree/core/spec/workflows/spree/refunds/create_spec.rb
@@ -110,4 +110,66 @@ RSpec.describe Spree::Refunds::Create do
expect(seen.amount).to eq(5)
end
end
+ # A marketplace basket is taken with one charge against the order group, so
+ # a child order holds no payment of its own — only its share. The
+ # whole-payment balance says nothing about whose money it is, which is what
+ # these cover.
+ describe 'a payment shared by a split checkout' do
+ let(:store) { @default_store }
+ let(:group) { create(:order_group, store: store) }
+ let!(:order) { grouped_order(1) }
+ let!(:sibling) { grouped_order(2) }
+
+ let!(:shared_payment) do
+ create(:payment, order: nil, cart: nil, order_group: group, amount: 200, status: 'completed')
+ end
+ let!(:split) do
+ create(:payment_split, payment: shared_payment, order: order,
+ authorized_amount: 100, captured_amount: 100)
+ end
+ let!(:sibling_split) do
+ create(:payment_split, payment: shared_payment, order: sibling,
+ authorized_amount: 100, captured_amount: 100)
+ end
+
+ def grouped_order(suffix)
+ create(:completed_order_with_totals, store: store).tap do |placed|
+ placed.update_columns(order_group_id: group.id, number: "#{group.number}-#{suffix}")
+ placed.reload
+ end
+ end
+
+ it "refunds up to the named order's own share" do
+ result = described_class.call(payment: shared_payment, order: order, amount: 100)
+
+ expect(result).to be_success
+ expect(result.value.amount).to eq(100)
+ end
+
+ it "refuses an amount above the named order's share, even though the payment covers it" do
+ result = described_class.call(payment: shared_payment, order: order, amount: 150)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq(:refund_amount_exceeds_balance)
+ expect(shared_payment.refunds).to be_empty
+ end
+
+ # The pre-flight check reads the share before the payment row is locked, so
+ # a sibling refund landing in between would otherwise let both commit and
+ # together overdraw this child. `Spree::Refund` cannot catch it: it
+ # validates `credit_allowed`, which is the whole payment's balance.
+ it 'refuses when another refund claimed the share after the pre-flight check' do
+ allow(shared_payment).to receive(:with_lock).and_wrap_original do |original, &block|
+ create(:refund, payment: shared_payment, order: order, amount: 100)
+ original.call(&block)
+ end
+
+ result = described_class.call(payment: shared_payment, order: order, amount: 100)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq(:refund_amount_exceeds_balance)
+ # Only the refund that got there first survives.
+ expect(Spree::Refund.where(order_id: order.id).sum(:amount)).to eq(100)
+ end
+ end
end