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.

Tidy the seller order work

Damian Legawiec1033f87bf911
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 2dc965059a..fce5d1e671 100644
--- a/packages/seller-dashboard/src/components/orders/fulfillment-fulfill-form.tsx
+++ b/packages/seller-dashboard/src/components/orders/fulfillment-fulfill-form.tsx
@@ -22,6 +22,7 @@ import { useTranslation } from 'react-i18next'
import { useFulfillmentActions } from '../../hooks/use-fulfillments'
import { useTrackingCarriers } from '../../hooks/use-reasons'
import { type FulfillItemsFormValues, fulfillItemsFormSchema } from '../../schemas/fulfillment'
+import { unitLabel } from './line-label'
type Row = { itemId: string; label: string; available: number }
@@ -47,7 +48,7 @@ function fulfillableRows(fulfillment: Fulfillment): Row[] {
} else {
byLineItem.set(itemId, {
itemId,
- label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,
+ label: unitLabel(item),
available: item.quantity,
})
}
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 3bed0be09f..3d8cd9eafc 100644
--- a/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx
+++ b/packages/seller-dashboard/src/components/orders/fulfillment-split-dialog.tsx
@@ -22,6 +22,7 @@ import type { Fulfillment } from '@spree/seller-sdk'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useFulfillmentActions } from '../../hooks/use-fulfillments'
+import { unitLabel } from './line-label'
/**
* Moves part of a parcel onto one of its own, for goods leaving separately.
@@ -46,7 +47,7 @@ export function FulfillmentSplitDialog({
const units = (fulfillment.fulfillment_items ?? []).map((item) => ({
value: item.variant_id ?? item.id,
- label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,
+ label: unitLabel(item),
quantity: item.quantity,
}))
diff --git a/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx b/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx
index 6e0492f3e3..3038ab591f 100644
--- a/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx
+++ b/packages/seller-dashboard/src/components/orders/fulfillments-card.tsx
@@ -21,6 +21,7 @@ import { useFulfillmentActions } from '../../hooks/use-fulfillments'
import { FulfillmentFulfillForm } from './fulfillment-fulfill-form'
import { FulfillmentSplitDialog } from './fulfillment-split-dialog'
import { FulfillmentTrackingDialog } from './fulfillment-tracking-dialog'
+import { unitLabel } from './line-label'
// A parcel that has not gone out is the only one still to ship or cancel;
// one that has is the only one that can be confirmed delivered. Reading
@@ -163,9 +164,7 @@ function FulfillmentRow({ orderId, fulfillment }: { orderId: string; fulfillment
<>
{fulfillment.fulfillment_items?.map((item) => (
<div key={item.id} className="flex items-center justify-between gap-3 text-sm">
- <span className="truncate">
- {[item.name, item.options_text].filter(Boolean).join(' — ')}
- </span>
+ <span className="truncate">{unitLabel(item)}</span>
<span className="shrink-0 text-muted-foreground">× {item.quantity}</span>
</div>
))}
diff --git a/packages/seller-dashboard/src/components/orders/line-label.ts b/packages/seller-dashboard/src/components/orders/line-label.ts
new file mode 100644
index 0000000000..11d056e5ce
--- /dev/null
+++ b/packages/seller-dashboard/src/components/orders/line-label.ts
@@ -0,0 +1,28 @@
+/**
+ * How one unit of an order reads wherever it is listed.
+ *
+ * A variant carries a SKU and its option values but never a name — the name
+ * lives on the product — so the label is built from the line's own name with
+ * the options after it, falling back to the SKU and then the raw id.
+ *
+ * One helper because the same unit appears on the parcel, the fulfil form,
+ * the split dialog and all three post-sale cards: built separately they drift,
+ * and the same goods were reading as "Shirt — Blue" in one card and
+ * "Shirt · Blue" in the next.
+ */
+export function lineLabel(
+ name: string | null | undefined,
+ variant: { sku?: string | null; options_text?: string | null } | null | undefined,
+ fallback: string | null | undefined,
+): string {
+ return [name, variant?.options_text].filter(Boolean).join(' · ') || variant?.sku || fallback || ''
+}
+
+/** The same label for a row that carries its own name and options directly. */
+export function unitLabel(item: {
+ name?: string | null
+ options_text?: string | null
+ id: string
+}): string {
+ return lineLabel(item.name, { options_text: item.options_text }, item.id)
+}
diff --git a/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx b/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx
index 768aa9f483..4ed8bbbac6 100644
--- a/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx
+++ b/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx
@@ -43,21 +43,9 @@ import {
useOrderClaims,
useOrderExchanges,
} from '../../hooks/use-post-sale'
+import { lineLabel } from './line-label'
import { CreateClaimDialog } from './post-sale-create-dialogs'
-/**
- * How a post-sale line reads. The product name comes from the line itself —
- * a variant carries a SKU and its option values but never a name — falling
- * back to the SKU and then the raw id.
- */
-function lineLabel(
- name: string | null | undefined,
- variant: { sku?: string | null; options_text?: string | null } | undefined,
- fallback: string | null | undefined,
-): string {
- return [name, variant?.options_text].filter(Boolean).join(' · ') || variant?.sku || fallback || ''
-}
-
const EXCHANGE_ACTIONABLE = ['requested', 'approved', 'received']
const CLAIM_ACTIONABLE = ['open', 'approved']
diff --git a/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx b/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx
index f29d12347e..b63cd67715 100644
--- a/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx
+++ b/packages/seller-dashboard/src/components/orders/post-sale-create-dialogs.tsx
@@ -21,13 +21,14 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useClaimActions, useReturnActions } from '../../hooks/use-post-sale'
import { type ReasonKind, useReasons } from '../../hooks/use-reasons'
+import { unitLabel } from './line-label'
/** Units that actually went out, which is all that can come back. */
export function fulfilledUnits(order: Order) {
return (order.fulfillments ?? []).flatMap((fulfillment) =>
(fulfillment.fulfillment_items ?? []).map((item) => ({
id: item.id,
- label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,
+ label: unitLabel(item),
quantity: item.quantity,
})),
)
@@ -207,7 +208,7 @@ export function CreateClaimDialog({
// never arrived are exactly what one is for.
const units = (order.items ?? []).map((item) => ({
id: item.id,
- label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,
+ label: unitLabel(item),
quantity: item.quantity,
}))
diff --git a/packages/seller-dashboard/src/components/orders/returns-card.tsx b/packages/seller-dashboard/src/components/orders/returns-card.tsx
index 4f37875206..60d6c50c66 100644
--- a/packages/seller-dashboard/src/components/orders/returns-card.tsx
+++ b/packages/seller-dashboard/src/components/orders/returns-card.tsx
@@ -34,26 +34,13 @@ import type { Order, Return, ReturnLineItem } from '@spree/seller-sdk'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useOrderReturns, useReturnActions } from '../../hooks/use-post-sale'
+import { lineLabel } from './line-label'
import { CreateReturnDialog, fulfilledUnits } from './post-sale-create-dialogs'
// Refunded and canceled returns are finished; offering a menu on them would
// open onto nothing.
const ACTIONABLE = ['requested', 'approved', 'received']
-/**
- * How a returned line reads. The product name comes from the line itself —
- * a variant carries a SKU and its options but never a name — with the
- * option values after it so two sizes of one product are distinguishable.
- */
-function postSaleLabel(line: ReturnLineItem): string {
- return (
- [line.name, line.variant?.options_text].filter(Boolean).join(' · ') ||
- line.variant?.sku ||
- line.variant_id ||
- ''
- )
-}
-
/**
* Goods coming back on this order.
*
@@ -193,7 +180,7 @@ export function ReturnsCard({ order }: { order: Order }) {
function ReturnLineRow({ line }: { line: ReturnLineItem }) {
const { t } = useTranslation()
- const label = postSaleLabel(line)
+ const label = lineLabel(line.name, line.variant, line.variant_id)
return (
<div className="flex items-center justify-between gap-3 text-sm">
@@ -262,7 +249,9 @@ function ReceiveDialog({
<div className="flex flex-col gap-3">
{lines.map((line) => (
<div key={line.id} className="flex items-center justify-between gap-3">
- <span className="min-w-0 truncate text-sm">{postSaleLabel(line)}</span>
+ <span className="min-w-0 truncate text-sm">
+ {lineLabel(line.name, line.variant, line.variant_id)}
+ </span>
<div className="flex shrink-0 items-center gap-3">
<label className="flex items-center gap-2 text-xs" htmlFor={`resell-${line.id}`}>
{t('orders.post_sale.returns.resellable')}
diff --git a/packages/seller-dashboard/src/hooks/use-order.ts b/packages/seller-dashboard/src/hooks/use-order.ts
index f167fccf81..d80d3033e7 100644
--- a/packages/seller-dashboard/src/hooks/use-order.ts
+++ b/packages/seller-dashboard/src/hooks/use-order.ts
@@ -13,9 +13,9 @@ export function useOrder(orderId: string) {
})
}
-/** The key a mutation elsewhere invalidates to refresh this order. */
-export function useOrderKeyBuilder() {
- return useResourceKeyBuilder()
+/** Withdrawing from an order this seller cannot fulfil. */
+export function useCancelOrder(orderId: string) {
+ return useOrderMutation(orderId, () => sellerClient().orders.cancel(orderId))
}
/**
diff --git a/packages/seller-dashboard/src/pages/order.tsx b/packages/seller-dashboard/src/pages/order.tsx
index feadacc608..3b4dc029ee 100644
--- a/packages/seller-dashboard/src/pages/order.tsx
+++ b/packages/seller-dashboard/src/pages/order.tsx
@@ -8,7 +8,6 @@ import {
} from '@spree/dashboard-ui'
import { useParams } from '@tanstack/react-router'
import { useTranslation } from 'react-i18next'
-import { sellerClient } from '../api-client'
import { CenteredMessage } from '../components/centered-message'
import { FulfillmentsCard } from '../components/orders/fulfillments-card'
import {
@@ -20,7 +19,7 @@ import {
import { ClaimsCard, ExchangesCard } from '../components/orders/post-sale-cards'
import { ReturnsCard } from '../components/orders/returns-card'
import { RetryableError } from '../components/retryable-error'
-import { useOrder, useOrderMutation } from '../hooks/use-order'
+import { useCancelOrder, useOrder } from '../hooks/use-order'
/**
* One order, as the seller needs it to pack, post, and put right.
@@ -37,7 +36,7 @@ export function OrderPage() {
const { data: order, isLoading, isError, refetch } = useOrder(orderId)
- const cancel = useOrderMutation(orderId, () => sellerClient().orders.cancel(orderId))
+ const cancel = useCancelOrder(orderId)
if (isLoading) return <CenteredMessage>{t('common.loading')}</CenteredMessage>
if (isError) return <RetryableError onRetry={() => refetch()} />
diff --git a/spree/api/app/controllers/spree/api/v3/seller/claim_reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/claim_reasons_controller.rb
index 7f553cee0f..c3563abaf7 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/claim_reasons_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/claim_reasons_controller.rb
@@ -2,35 +2,16 @@ module Spree
module Api
module V3
module Seller
- # What went wrong with a delivery, as the marketplace defines it.
- #
- # Read-only: the vocabulary is the operator's, and a seller picks from
- # it while filing a return. Gated by `orders` rather than `settings` —
- # a seller reads these to fill in a form on their own order, and
- # `settings` is closed to the seller audience entirely.
- #
- # Store-scoped rather than seller-scoped, because these are the store's
- # own rows; retired reasons are hidden so a seller cannot file against
- # vocabulary the operator has withdrawn.
- class ClaimReasonsController < Seller::ResourceController
- scoped_resource :orders
-
+ # What went wrong with a delivery.
+ class ClaimReasonsController < ReasonsController
protected
def model_class
Spree::ClaimReason
end
- def serializer_class
- Spree.api.seller_reason_serializer
- end
-
- def read_actions
- %w[index]
- end
-
- def scope
- current_store.claim_reasons.active
+ def reasons_association
+ :claim_reasons
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/reasons_controller.rb
new file mode 100644
index 0000000000..0d1f1318fb
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/seller/reasons_controller.rb
@@ -0,0 +1,45 @@
+module Spree
+ module Api
+ module V3
+ module Seller
+ # A marketplace-owned vocabulary a seller picks from — why goods came
+ # back, or what went wrong with a delivery.
+ #
+ # Read-only, because the vocabulary is the operator's to define: a
+ # seller chooses a reason, never adds one. Gated by `orders` rather
+ # than `settings` — a seller reads these to fill in a form on their own
+ # order, and `settings` is closed to the seller audience entirely.
+ #
+ # Store-scoped rather than seller-scoped, since these are the store's
+ # own rows. Retired reasons are left out so a seller cannot file
+ # against vocabulary the operator has withdrawn.
+ #
+ # Subclasses name the model and the association to read it through.
+ class ReasonsController < Seller::ResourceController
+ scoped_resource :orders
+
+ protected
+
+ def serializer_class
+ Spree.api.seller_reason_serializer
+ end
+
+ def read_actions
+ %w[index]
+ end
+
+ def scope
+ current_store.public_send(reasons_association).active
+ end
+
+ # The store association holding this vocabulary.
+ #
+ # @return [Symbol]
+ def reasons_association
+ raise NotImplementedError
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/seller/return_reasons_controller.rb b/spree/api/app/controllers/spree/api/v3/seller/return_reasons_controller.rb
index ba7d228f49..4dd78afb8c 100644
--- a/spree/api/app/controllers/spree/api/v3/seller/return_reasons_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/seller/return_reasons_controller.rb
@@ -2,35 +2,16 @@ module Spree
module Api
module V3
module Seller
- # Why goods come back, as the marketplace defines it.
- #
- # Read-only: the vocabulary is the operator's, and a seller picks from
- # it while filing a return. Gated by `orders` rather than `settings` —
- # a seller reads these to fill in a form on their own order, and
- # `settings` is closed to the seller audience entirely.
- #
- # Store-scoped rather than seller-scoped, because these are the store's
- # own rows; retired reasons are hidden so a seller cannot file against
- # vocabulary the operator has withdrawn.
- class ReturnReasonsController < Seller::ResourceController
- scoped_resource :orders
-
+ # Why goods come back.
+ class ReturnReasonsController < ReasonsController
protected
def model_class
Spree::ReturnReason
end
- def serializer_class
- Spree.api.seller_reason_serializer
- end
-
- def read_actions
- %w[index]
- end
-
- def scope
- current_store.return_reasons.active
+ def reasons_association
+ :return_reasons
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/seller/claim_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/claim_serializer.rb
index c0ba2dfb50..80df34d85c 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/claim_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/claim_serializer.rb
@@ -9,10 +9,9 @@ module Spree
# Built on the shared V3 serializer rather than the admin one, which
# expands the order and the customer behind it.
class ClaimSerializer < V3::ClaimSerializer
- typelize memo: [:string, nullable: true],
- resolution: [:string, nullable: true]
+ typelize memo: [:string, nullable: true]
- attributes :memo, :resolution
+ attributes :memo
many :claim_line_items,
resource: proc { Spree.api.seller_claim_line_item_serializer },
diff --git a/spree/api/app/serializers/spree/api/v3/seller/reason_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/reason_serializer.rb
index 8c06e2dda7..a33b2ad4dc 100644
--- a/spree/api/app/serializers/spree/api/v3/seller/reason_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/seller/reason_serializer.rb
@@ -7,9 +7,12 @@ module Spree
# One entry of a marketplace-owned vocabulary — why goods came back,
# or what went wrong with a delivery.
#
- # One serializer for both: a reason is a name and whether it is still
- # offered, and Spree::ReturnReason and Spree::ClaimReason answer that
- # identically. Read-only on this branch, so nothing here is writable.
+ # One serializer for both, unlike the store and admin branches, which
+ # keep ReturnReason and ClaimReason apart so Typelizer emits a concrete
+ # type per endpoint. Here the two endpoints answer the same shape — a
+ # name and whether it is still offered — and the panel renders them
+ # through one picker, so a single `Reason` type is what the client
+ # actually wants. Read-only, so nothing here is writable.
class ReasonSerializer < V3::BaseSerializer
typelize name: :string, active: :boolean
diff --git a/spree/core/app/models/concerns/spree/refunds_order_payments.rb b/spree/core/app/models/concerns/spree/refunds_order_payments.rb
deleted file mode 100644
index 72553e64b2..0000000000
--- a/spree/core/app/models/concerns/spree/refunds_order_payments.rb
+++ /dev/null
@@ -1,94 +0,0 @@
-# frozen_string_literal: true
-
-module Spree
- # Gives a post-sale workflow one way to put money back on an order.
- #
- # Returns, claims and exchanges all owe the customer money for the same
- # reason — goods that are going back, or were never right — and all three
- # drained `order.payments` to pay it. That reads nothing on a marketplace
- # order: a split checkout takes one charge against the {Spree::OrderGroup},
- # so a child order holds no payments of its own and every one of the three
- # failed with "no refundable payments" on the orders a seller is most likely
- # to be refunding.
- #
- # What a child order holds instead is a {Spree::PaymentSplit} per group
- # payment — its own authorised, captured and refunded share. Refunding
- # through the share is what keeps one seller's refund from spending a
- # sibling's captured money, and it is the same shape
- # {Spree::Orders::Cancel} already settles a canceled child order with.
- module RefundsOrderPayments
- extend ActiveSupport::Concern
-
- private
-
- # Puts `amount` back on `order`, newest 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.
- #
- # @param order [Spree::Order] the order being put right
- # @param amount [BigDecimal] how much to give back
- # @param originator [Spree::Return, Spree::Claim, Spree::Exchange]
- # @param refunder [Object, nil] whoever is issuing it
- # @return [Array<Spree::Refund>] the refunds written, newest payment first
- def refund_order_payments(order:, amount:, originator:, refunder: nil)
- remaining = amount.to_d
- refunds = []
-
- refundable_shares(order).each do |payment, refundable|
- break unless remaining.positive?
-
- creditable = [refundable.to_d, remaining].min
- next unless creditable.positive?
-
- result = Spree.refund_create_workflow.call(
- payment: payment,
- amount: creditable,
- order: order,
- reason: Spree::RefundReason.return_processing_reason(originator.store),
- refunder: refunder,
- originator: originator
- )
- yield(result) if result.failure?
-
- refunds << result.value
- remaining -= creditable
- end
-
- refunds
- end
-
- # What each of the order's completed payments can still give back to *this*
- # order.
- #
- # On an ordinary order that is the payment's own balance. On a child of a
- # split checkout it is that child's share: `credit_allowed` sums the
- # refunds of every child against the whole charge, so measuring one
- # seller's refund by it would let them draw on headroom their sibling's
- # sale is holding.
- #
- # A share mid-capture is skipped rather than guessed at — a parcel reserves
- # what it is about to draw before asking the gateway, so a share can read
- # captured while the charge is still in flight, and refunding through it
- # would hand back money nobody has taken yet. {Spree::Orders::Cancel}
- # leaves the same case for the operator.
- #
- # @param order [Spree::Order]
- # @return [Array<Array(Spree::Payment, BigDecimal)>]
- def refundable_shares(order)
- unless order.grouped?
- return order.payments.completed.map { |payment| [payment, payment.credit_allowed.to_d] }
- end
-
- order.payment_splits.includes(:payment).filter_map do |split|
- next if split.capture_in_flight?
- next unless split.payment&.completed?
-
- [split.payment, split.refundable_amount]
- end
- end
- end
-end
diff --git a/spree/core/app/models/spree/payment_split.rb b/spree/core/app/models/spree/payment_split.rb
index f338cdaf91..50f02d7a32 100644
--- a/spree/core/app/models/spree/payment_split.rb
+++ b/spree/core/app/models/spree/payment_split.rb
@@ -42,19 +42,26 @@ module Spree
extend Spree::DisplayMoney
money_methods :authorized_amount, :captured_amount, :refunded_amount
- # @return [BigDecimal] what this child still has captured against it after
- # refunds — the figure a seller's earnings are computed from
+ # This child's reported position: what it has captured, less the refunds a
+ # subscriber has already written back to {#refunded_amount}.
+ #
+ # The *reported* figure, which is what makes it right for reading — a
+ # seller's earnings, an order's payment total — and wrong for bounding a
+ # refund, since the column trails the rows. Reach for {#refundable_amount}
+ # before moving money.
+ #
+ # @return [BigDecimal]
def net_captured_amount
captured_amount - refunded_amount
end
# The most this child order can still be given back from this payment.
#
- # Counted from the refund rows rather than from {#refunded_amount}, which a
- # subscriber writes after the fact: two refunds landing together would each
- # read a share that still looked unrefunded. {Spree::Refunds::Create}
- # re-checks the same figure under the payment's lock before any money
- # moves — this is what a caller uses to decide how much to ask for.
+ # The same quantity as {#net_captured_amount} counted from the refund rows
+ # instead of the denormalized column, because that column is written by a
+ # subscriber after the fact: two refunds landing together would each read a
+ # share that still looked unrefunded. {Spree::Refunds::Create} bounds every
+ # refund by this under the payment's lock.
#
# @return [BigDecimal]
def refundable_amount
diff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rb
index 15ed1a6ba0..7a44978299 100644
--- a/spree/core/app/workflows/spree/claims/resolve.rb
+++ b/spree/core/app/workflows/spree/claims/resolve.rb
@@ -6,7 +6,7 @@ module Spree
# so the caller's intent is explicit at the call site and an admin can
# decide at resolution time rather than at claim creation.
class Resolve < Spree::Workflow
- include Spree::RefundsOrderPayments
+ include Spree::Refunds::OrderPayments
hooks :validate, :before_settle, :after_resolve
@@ -147,9 +147,9 @@ module Spree
@refunds = refund_order_payments(
order: claim.order,
amount: @amount_to_refund,
- originator: claim,
+ record: claim,
refunder: resolver
- ) { |result| failure(claim, result.error.value) }
+ )
failure(claim, :no_refundable_payments) if @refunds.empty?
end
diff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rb
index a639f793d6..ab17c948cb 100644
--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb
+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb
@@ -8,7 +8,7 @@ module Spree
# for the merchant to collect — charging a stored card without a fresh
# authorization is not something core should do silently.
class Fulfill < Spree::Workflow
- include Spree::RefundsOrderPayments
+ include Spree::Refunds::OrderPayments
hooks :validate, :before_settle, :after_fulfill
@@ -129,9 +129,9 @@ module Spree
@refunds = refund_order_payments(
order: exchange.order,
amount: credit_amount,
- originator: exchange,
+ record: exchange,
refunder: refunder
- ) { |result| failure(exchange, result.error.value) }
+ )
end
def mark_fulfilled
diff --git a/spree/core/app/workflows/spree/refunds/create.rb b/spree/core/app/workflows/spree/refunds/create.rb
index 47ce500077..766f975919 100644
--- a/spree/core/app/workflows/spree/refunds/create.rb
+++ b/spree/core/app/workflows/spree/refunds/create.rb
@@ -74,11 +74,7 @@ module Spree
split = order && payment.payment_splits.find_by(order_id: order.id)
return 0 if split.nil?
- # Refunds already written are counted from the rows rather than from
- # the split's own figure, which a subscriber updates after the fact —
- # two refunds in quick succession must not each see an unrefunded share.
- already_refunded = Spree::Refund.where(payment_id: payment.id, order_id: order.id).sum(:amount)
- split.captured_amount - already_refunded
+ split.refundable_amount
end
# The row is what reserves the balance — credit_allowed sums refund rows —
diff --git a/spree/core/app/workflows/spree/refunds/order_payments.rb b/spree/core/app/workflows/spree/refunds/order_payments.rb
new file mode 100644
index 0000000000..bed820e4e4
--- /dev/null
+++ b/spree/core/app/workflows/spree/refunds/order_payments.rb
@@ -0,0 +1,124 @@
+# frozen_string_literal: true
+
+module Spree
+ module Refunds
+ # Gives a post-sale workflow one way to put money back on an order.
+ #
+ # Returns, claims and exchanges all owe the customer money for the same
+ # reason — goods that are going back, or were never right — and all three
+ # drained `order.payments` to pay it. That reads nothing on a marketplace
+ # order: a split checkout takes one charge against the
+ # {Spree::OrderGroup}, so a child order holds no payments of its own and
+ # every one of the three failed with "no refundable payments" on the
+ # orders a seller is most likely to be refunding.
+ #
+ # What a child order holds instead is a {Spree::PaymentSplit} per group
+ # payment — its own authorised, captured and refunded share. Refunding
+ # through the share is what keeps one seller's refund from spending a
+ # sibling's captured money, and it is the same shape
+ # {Spree::Orders::Cancel} already settles a canceled child order with.
+ module OrderPayments
+ extend ActiveSupport::Concern
+
+ private
+
+ # Puts `amount` back on `order`, newest 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.
+ #
+ # @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
+ def refund_order_payments(order:, amount:, record:, refunder: nil)
+ remaining = amount.to_d
+ refunds = []
+ # 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)
+
+ refundable_shares(order).each do |payment, refundable|
+ break unless remaining.positive?
+
+ creditable = [refundable, remaining].min
+ next unless creditable.positive?
+
+ result = Spree.refund_create_workflow.call(
+ payment: payment,
+ amount: creditable,
+ order: order,
+ reason: reason,
+ refunder: refunder,
+ originator: record
+ )
+ # `failure` raises, so this ends the drain — the caller's own error
+ # vocabulary decorates the 422.
+ failure(record, result.error.value) if result.failure?
+
+ refunds << result.value
+ remaining -= creditable
+ end
+
+ refunds
+ end
+
+ # What each of the order's completed payments can still give back to
+ # *this* order.
+ #
+ # On an ordinary order that is the payment's own balance. On a child of
+ # a split checkout it is that child's share: `credit_allowed` sums the
+ # refunds of every child against the whole charge, so measuring one
+ # seller's refund by it would let them draw on headroom their sibling's
+ # sale is holding.
+ #
+ # @param order [Spree::Order]
+ # @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] }
+ 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.
+ refunded = Spree::Refund.where(order_id: order.id).group(:payment_id).sum(:amount)
+
+ order.payment_splits.includes(:payment).each_with_object({}) do |split, shares|
+ next unless split.payment&.completed?
+ next if capture_in_flight?(order, split)
+
+ shares[split.payment] = split.captured_amount - refunded.fetch(split.payment_id, 0)
+ end
+ end
+
+ # Whether a charge against this share is still in flight.
+ #
+ # A parcel reserves what it is about to draw before asking the gateway,
+ # so a share can read captured while the charge is still landing.
+ # Refunding through it would hand back money nobody has taken yet, so it
+ # is reported for the operator rather than guessed at — the same call
+ # {Spree::Orders::Cancel} makes when it meets one.
+ #
+ # @return [Boolean]
+ def capture_in_flight?(order, split)
+ return false unless split.capture_in_flight?
+
+ Rails.error.report(
+ Spree::Core::GatewayError.new('Payment share is mid-capture; refund left it for manual settlement'),
+ handled: true,
+ context: { order_id: order.id, payment_split_id: split.id },
+ source: 'spree.core'
+ )
+ true
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rb
index 98e186f1ed..02e911f9c0 100644
--- a/spree/core/app/workflows/spree/returns/refund.rb
+++ b/spree/core/app/workflows/spree/returns/refund.rb
@@ -8,7 +8,7 @@ module Spree
# a pure database write outside the transaction would open a window where
# a crash leaves a refunded return with no credit issued.
class Refund < Spree::Workflow
- include Spree::RefundsOrderPayments
+ include Spree::Refunds::OrderPayments
hooks :validate, :before_refund, :after_refund
@@ -119,9 +119,9 @@ module Spree
@refunds = refund_order_payments(
order: return_record.order,
amount: @amount_to_refund,
- originator: return_record,
+ record: return_record,
refunder: refunder
- ) { |result| failure(return_record, result.error.value) }
+ )
failure(return_record, :no_refundable_payments) if @refunds.empty?
end