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: returns and claims refund discounted items at what the customer paid (#14776)
Łukasz Adamczyk9335e9f694df
diff --git a/.changeset/dashboard-claim-discounted-refund.md b/.changeset/dashboard-claim-discounted-refund.mdnew file mode 100644index 0000000000..4d32087c57--- /dev/null+++ b/.changeset/dashboard-claim-discounted-refund.md@@ -0,0 +1,7 @@+---+"@spree/dashboard": patch+"@spree/dashboard-ui": patch+"@spree/seller-dashboard": patch+---++The New claim dialog now pre-fills each line's refund with what the customer paid for those items after discounts, instead of their list price, which the claim would refuse to refund on a discounted order. The amount follows the claimed quantity until the merchant types one of their own. Code that builds the dialog's lines itself passes `discountedAmount` (the line's `discounted_amount`) in place of `price`, which `ClaimableLine` no longer accepts.diff --git a/.changeset/dashboard-complete-return.md b/.changeset/dashboard-complete-return.mdnew file mode 100644index 0000000000..07424bb60e--- /dev/null+++ b/.changeset/dashboard-complete-return.md@@ -0,0 +1,7 @@+---+"@spree/dashboard": patch+"@spree/dashboard-ui": patch+"@spree/seller-dashboard": patch+---++A received return that is owed nothing, such as a free gift sent back, now offers "Complete return" instead of "Refund". The dialog explains that no money goes back and closes the return without asking for an amount or a refund method.diff --git a/.changeset/seller-sdk-line-discounted-amount.md b/.changeset/seller-sdk-line-discounted-amount.mdnew file mode 100644index 0000000000..e01a1f3099--- /dev/null+++ b/.changeset/seller-sdk-line-discounted-amount.md@@ -0,0 +1,5 @@+---+"@spree/seller-sdk": minor+---++Order line items now carry `discounted_amount` and `display_discounted_amount`: what the customer paid for the line after discounts, which is also the most a claim on it can refund.diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yamlindex 58e4e685bb..749dbeecd8 100644--- a/docs/api-reference/seller.yaml+++ b/docs/api-reference/seller.yaml@@ -16316,6 +16316,8 @@ paths:currency: USDprice: '10.0'display_price: "$10.00"+ discounted_amount: '10.0'+ display_discounted_amount: "$10.00"total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ@@ -16517,6 +16519,8 @@ paths:currency: USDprice: '10.0'display_price: "$10.00"+ discounted_amount: '10.0'+ display_discounted_amount: "$10.00"total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ@@ -16714,6 +16718,8 @@ paths:currency: USDprice: '10.0'display_price: "$10.00"+ discounted_amount: '10.0'+ display_discounted_amount: "$10.00"total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ@@ -16918,6 +16924,8 @@ paths:currency: USDprice: '10.0'display_price: "$10.00"+ discounted_amount: '10.0'+ display_discounted_amount: "$10.00"total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ@@ -17185,6 +17193,8 @@ paths:currency: USDprice: '10.0'display_price: "$10.00"+ discounted_amount: '10.0'+ display_discounted_amount: "$10.00"total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ@@ -17358,6 +17368,8 @@ paths:currency: USDprice: '10.0'display_price: "$10.00"+ discounted_amount: '10.0'+ display_discounted_amount: "$10.00"total: '10.0'display_total: "$10.00"variant_id: variant_UkLWZg9DAJ@@ -20714,6 +20726,12 @@ components:display_price:type: stringnullable: true+ discounted_amount:+ type: string+ nullable: true+ display_discounted_amount:+ type: string+ nullable: truetotal:type: stringnullable: true@@ -20737,6 +20755,8 @@ components:- currency- price- display_price+ - discounted_amount+ - display_discounted_amount- total- display_total- variant_iddiff --git a/docs/developer/core-concepts/returns-exchanges-claims.mdx b/docs/developer/core-concepts/returns-exchanges-claims.mdxindex 681f23283f..ebfbeec6be 100644--- a/docs/developer/core-concepts/returns-exchanges-claims.mdx+++ b/docs/developer/core-concepts/returns-exchanges-claims.mdx@@ -118,7 +118,7 @@ curl -X PATCH 'https://api.mystore.com/api/v3/admin/orders/or_xxx/returns/ret_xxReceiving takes the quantities the warehouse actually counted, because partial and damaged returns are normal rather than exceptional. A customer says three items are coming; two arrive; one of those can't be sold again. Only resellable goods go back into stock.-Leave `items` out to receive everything as requested. Refunds default to whatever the return is still owed, and can go back to the original payment method or to store credit.+Leave `items` out to receive everything as requested. Refunds default to whatever the return is still owed, and can go back to the original payment method or to store credit. A returned item is worth what the customer paid for it after discounts, not its list price, so a free gift sent back refunds nothing. Refunding a return that is owed nothing completes it with no money moved and no refund email; an amount of zero is refused on any return the customer is still owed money on.### Where the goods come back to@@ -201,6 +201,8 @@ A replacement creates a new [fulfillment](/developer/core-concepts/fulfillments)The replacement is filed under the order line it replaces, but it doesn't count toward that line's quantity. Editing the line later, from a claim or an [exchange](#exchanges), adds or removes only the goods the customer paid for and leaves the replacement where it is.+A claim never refunds more than the customer paid for the claimed items after discounts. Each claim line reports that ceiling as `paid_amount`.+## ExchangesAn exchange works like a return, but ends by sending different items instead of refunding:diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.mdindex aebfa11da2..a2825e132f 100644--- a/docs/plans/6.0-returns-exchanges-claims.md+++ b/docs/plans/6.0-returns-exchanges-claims.md@@ -5,7 +5,7 @@**Depends on:** Fulfillment & Delivery rework (6.0-fulfillment-and-delivery.md), Split Adjustments (6.0-6.1-split-adjustments.md), Normalize state→status (6.0-normalize-state-to-status.md), Service Workflows (6.0-service-workflows.md)**Successor:** 6.1-order-change-substrate.md — the mutation half of these flows moves onto the shared OrderChange substrate in 6.1 (additive; the models and statuses below do not change)**Author:** Damian + Claude-**Last updated:** 2026-08-05+**Last updated:** 2026-09-29## Summary@@ -366,8 +366,8 @@ class Spree::ReturnLineItem < Spree.base_class# quantity (default 1), received_quantity (default 0, written by# Returns::Receive), pre_tax_amount and resellable carry DB defaults.# pre_tax_amount defaults to this item's share of what the customer- # actually paid after discounts — refunding list price would give back- # more than was taken.+ # actually paid after discounts (LineItem#discounted_amount_for) —+ # refunding list price would give back more than was taken.before_validation :set_defaults_from_line_item, on: :createdelegate :order, :currency, to: :return@@ -398,6 +398,15 @@ as `Claim#refund_total` over `ClaimLineItem#refund_amount`. Keeping it in oneplace is what stops the offered amount and the amount actually owed driftingapart (2026-09-18).+What the announced units are worth comes from `LineItem#discounted_amount_for`,+which `ClaimLineItem#paid_amount` shares: the line's `discounted_amount` (price+× quantity plus every discount row on the line, promotions and manual ones+alike) spread over its units, multiplied before dividing and rounded to the+currency. It is not the stored `LineItem#pre_tax_amount`: only a tax estimate+writes that column, it defaults to zero, and it takes VAT out of a+tax-inclusive price. Neither tax added on top of the price nor the line's own+fees are part of it — refunding tax is V-3725 (2026-09-29).+### Exchange (as shipped)A customer returns items and gets different items in return (different size, different product).@@ -558,9 +567,9 @@ class Spree::ClaimLineItem < Spree.base_class# quantity (1), send_replacement (false) and refund_amount (0) carry DB# defaults; description holds the customer's account of the problem.- # #paid_amount (what was actually paid after discounts) is the ceiling- # for a refund on this line; #variant_to_send is what ships on a- # replacement resolution.+ # #paid_amount (what was actually paid after discounts, from+ # LineItem#discounted_amount_for) is the ceiling for a refund on this line;+ # #variant_to_send is what ships on a replacement resolution.end```@@ -683,6 +692,15 @@ external_step :refund_at_gateway, on_flow_failure: :revert_refunded unless interpayments differently from gateway payments. `Claims::Resolve` and`Exchanges::Fulfill` use the same branch when settling money.+A return owed nothing — a free gift sent back, or one where nothing that+arrived was worth anything — closes through the same workflow at zero: it moves+to `refunded` with no refund row, no store credit and no tax credit, and still+publishes `return.refunded`. Zero is accepted only when zero is owed; on a+return the customer is still owed money it is refused with+`refund_amount_required`, so a mistyped amount cannot close a return unpaid. The emails engine sends no+refund email when `refunded_total` is zero, and the dashboard names the action+"Complete return" instead of "Refund" (2026-09-30).+### Exchanges| Workflow | Hooks | Notes |@@ -945,6 +963,10 @@ DELETE /api/v3/admin/return_reasons/:id- **Don't add new ReimbursementType subtypes.** The STI hierarchy is being dropped.- **New return/exchange logic uses the three-model pattern.** Think "Return with ReturnLineItems" not "ReturnAuthorization with ReturnItems through CustomerReturn."- **Refund stays as-is.** It's the payment-level primitive. Returns, Exchanges, and Claims create Refunds when money needs to go back.+- **What a returned or claimed unit is worth is `LineItem#discounted_amount_for`.**+ Don't recompute it from `price × quantity`, which ignores every discount on+ the line, and don't read `LineItem#pre_tax_amount`, which only a tax+ estimate writes.- **No state machine on any new model in this area.** Plain `status` string,inclusion validation, transitions through workflows. This generalizes beyondreturns — see `6.0-service-workflows.md` → "State machines".diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex ebe19f41c2..9b9e244218 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,27 @@+## 2026-09-30: A return owed nothing completes at zero++**Context:** Once a returned free gift was valued at what the customer paid for it (entry below), its return could never be closed. Reproduced on R1009: a Tee with a free pink Polo, the Polo returned alone, approved and received with a refund total of $0.00. `Returns::Refund` refused any amount that was not positive ("There is nothing left to refund on this return."), and `Returns::Cancel` only accepts requested or approved returns, so the return sat at `received` for good. It kept counting in the dashboard's open-returns counter and the open filter, the customer's return page never showed it finished, and `return.refunded` never reached webhooks. Any return whose refund works out to zero was caught the same way, including one where nothing that arrived was worth anything. Money was never at stake.++**Decision:** `Returns::Refund` accepts zero when zero is owed. It skips the money steps and the tax credit and moves the return to `refunded` with no `Spree::Refund` row and no store credit, runs the hooks, and publishes `return.refunded`. The tax credit is skipped because the run moved nothing: a return whose money already went back but that was never marked refunded completes the same way, and crediting its tax again at zero would be wrong. Zero on a return the customer is still owed money on is refused with `refund_amount_required`, and a negative amount with `refund_amount_negative`. The status stays `refunded`; `refunded_total` of zero tells the two apart. `ReturnEmailSubscriber` sends no refund email when nothing was refunded. The shared refund dialog in `@spree/dashboard-ui` reads "Complete return", with a note that no money goes back and no amount or method to pick, and both returns cards label the menu action the same way.++Rejected: accepting zero on any return, which would let "refund nothing" close a return the customer is owed money on — a mistyped amount would close it unpaid, and a deliberate refusal to refund deserves its own action if it is ever wanted. Also rejected: a separate completed status, which touches the status list, the counters, the serializers and every filter to rename an outcome the existing status already describes.++**Consequences:** A received return always has a way to close. Integrations that treat `return.refunded` as "money went back" now see it for returns that refunded nothing; the event payload's `refund_total` reads `0.0` for them, so no second lookup is needed. The zero refusal on an owed return names what to do instead of claiming there is nothing to refund. `Claims::Resolve` still refuses a zero refund, which does not strand a claim, since it can be resolved with a replacement. A return still cannot be refunded in two steps: the first refund marks it `refunded` and a second is refused as not received. The comment on `Return#refunded_total` says a return can be refunded in more than one step, which the workflow does not allow; the two are left to be reconciled in their own change.++**Plans amended:** `6.0-returns-exchanges-claims.md` (Refunding: internal vs gateway).++## 2026-09-29: A returned or claimed unit is worth what the customer paid for it after discounts++**Context:** A return refunded a discounted line at its list price (V-3721). Reproduced on `main`: two orders of 2 × Shirt ($25.00) and 1 × Mug ($5.00) with a 10% whole-order coupon, items $55.00, discount −$5.50, paid $54.50. Returning everything on R1001 offered $55.00; returning the two shirts on R1002 refunded $50.00 for goods the customer paid $45.00 for. On a marketplace order the seller would be charged back the same excess, since `SellerTransfers::Reverse` scales its clawback by the refund. `ReturnLineItem#default_pre_tax_amount` and `ClaimLineItem#paid_amount` both took `line_item.amount / quantity`, which is `price × quantity` and ignores every discount, under comments and a plan that said "after discounts". Every discount recorded on the line was affected: whole-order and per-item promotions, free gifts and manual discounts; free shipping was not, since it discounts the delivery. It is a regression from the 5.x chain, whose refund calculator read the line's discounted `pre_tax_amount`. The dashboard and seller panel claim dialogs pre-filled each line's refund with list price × quantity as well.++**Decision:** `LineItem#discounted_amount_for(units)` is the one answer to what some of a line's units cost the customer: `discounted_amount` (price × quantity plus the line's discount rows), spread over its units, multiplied before dividing so every unit together comes to the whole line, rounded to the currency and never negative. `ReturnLineItem`'s default and `ClaimLineItem#paid_amount` both read it. The claim dialog in `@spree/dashboard-ui` pre-fills its refund from the line's `discounted_amount`, which the Admin API already served; the Seller API's `OrderLineItemSerializer` gains `discounted_amount` / `display_discounted_amount` so the seller panel can do the same.++Rejected: the stored `LineItem#pre_tax_amount`, which the 5.x calculator read. Only a tax estimate writes it and it defaults to zero, so an order never estimated, or a tax service that does not write it, would default to refunding nothing; and on tax-inclusive prices it takes the VAT out, so VAT stores would refund less than they do today. Also rejected for now: the line's full total, which adds tax charged on top of the price and the line's own fees. Refunding tax is its own defect (V-3725) and keeps its own decision; line fees stay out of this change.++**Consequences:** Returns still refund no tax charged on top of the price, exactly as before; on a VAT-inclusive store the built-in VAT is still refunded, now minus the discount. A return keeps the amount stored when it was opened, so returns already open on beta4 or earlier keep their list-price figure; they are deliberately not recalculated. A claim's ceiling is computed when it is read, so open claims move to the new figure at once, and a claim opened with a per-line amount above it is now refused at resolution with `refund_exceeds_paid`. Refunds already issued stay as they were. `ExchangeLineItem#original_price` still reads the list price and is not changed here.++**Plans amended:** `6.0-returns-exchanges-claims.md` (ReturnLineItem and ClaimLineItem design notes, Constraints on Current Work).+## 2026-09-29: A batch coupon code is held from the moment it is saved, and discounts only its holder**Context:** A single-use batch code applied before the cart reached the promotion's minimum was never used up (V-3724). Reproduced on `main`: a $10-off code with a $60 minimum, applied to a $50 cart, answered 201 with `coupon_code_not_eligible`; raising the cart to $100 discounted it and order R1001 was placed at $95.00, while the code still read `unused` with no order. A second guest then applied the same code and got the discount too (R1002), two guests who both saved a code below the minimum both placed discounted orders (R1003, R1004), and a guest who saved a code another cart already held was discounted alongside it (R1005, R1006). The cause is a gap between two decisions. The 2026-07-29 coupon wiring saves a real but not-yet-eligible code on the cart and lets recalculation activate it, and the V-3680 fix (7335a712f1) moved "hold the code on the cart" into the handler's claim, which runs only when the code applies straight away. Recalculation activated the saved code from its text alone (`Adjusters::Promotion#coupon_promotions`), so no code record was ever held, and completion spends only the codes the cart holds. Separately, a saved code that had not applied yet could not be removed: `DELETE /carts/:id/discount_codes/:code` answered 422 "doesn't exist", because removal looked only at promotions already attached to the cart.diff --git a/packages/dashboard-ui/src/spree/post-sale-create-dialogs.tsx b/packages/dashboard-ui/src/spree/post-sale-create-dialogs.tsxindex 9564c1b5c7..7cd0f605ac 100644--- a/packages/dashboard-ui/src/spree/post-sale-create-dialogs.tsx+++ b/packages/dashboard-ui/src/spree/post-sale-create-dialogs.tsx@@ -98,10 +98,18 @@ export function CreateReturnDialog({)}-/** A line the claim can name, with what one unit of it cost. */+/** A line the claim can name, with what the customer paid for it. */export type ClaimableLine = PostSaleUnit & {- /** Unit price, used to default the refund to what was actually paid. */- price?: string | null+ /** The whole line after discounts, used to default the refund to what was actually paid. */+ discountedAmount?: string | null+}++/** What the customer paid for `quantity` units of the line, or blank when that is unknown. */+function paidForUnits(line: ClaimableLine, quantity: number): string {+ const paid = Number(line.discountedAmount)+ if (quantity <= 0 || line.discountedAmount == null || !Number.isFinite(paid)) return ''++ return ((paid * quantity) / line.quantity).toFixed(2)}/**@@ -138,6 +146,7 @@ export function CreateClaimDialog({const { t } = useTranslation()const [selection, setSelection] = useState<PostSaleSelection>({})const [amounts, setAmounts] = useState<Record<string, string>>({})+ const [typedAmounts, setTypedAmounts] = useState<Record<string, boolean>>({})const [memo, setMemo] = useState('')const chosen = selectedUnits(selection)@@ -173,16 +182,13 @@ export function CreateClaimDialog({Math.min(Number(event.target.value), line.quantity),)setSelection({ ...selection, [line.id]: quantity })- // Default the refund to what was paid for those units;- // the merchant can still overwrite it.- if (quantity > 0 && !amounts[line.id]) {- const unitPrice = Number(line.price)- if (Number.isFinite(unitPrice)) {- setAmounts((current) => ({- ...current,- [line.id]: (unitPrice * quantity).toFixed(2),- }))- }+ // The refund follows what was paid for the chosen units+ // until the merchant types an amount of their own.+ if (!typedAmounts[line.id]) {+ setAmounts((current) => ({+ ...current,+ [line.id]: paidForUnits(line, quantity),+ }))}}}/>@@ -202,9 +208,14 @@ export function CreateClaimDialog({step="0.01"min="0"value={amounts[line.id] ?? ''}- onChange={(event) =>+ onChange={(event) => {setAmounts({ ...amounts, [line.id]: event.target.value })- }+ // Clearing the field hands it back to the quantity.+ setTypedAmounts({+ ...typedAmounts,+ [line.id]: event.target.value !== '',+ })+ }}/></InputGroup></Field>diff --git a/packages/dashboard-ui/src/spree/return-dialogs.tsx b/packages/dashboard-ui/src/spree/return-dialogs.tsxindex 164299d91e..fd07a24648 100644--- a/packages/dashboard-ui/src/spree/return-dialogs.tsx+++ b/packages/dashboard-ui/src/spree/return-dialogs.tsx@@ -139,8 +139,14 @@ export function ReturnReceiveDialog({)}+/** True when a received return is owed nothing, so completing it moves no money. */+export function returnOwesNothing(refundableTotal: string): boolean {+ return Number(refundableTotal) === 0+}+/**- * Gives the money back: how much, and by what means.+ * Gives the money back: how much, and by what means. A return owed nothing+ * (a free gift sent back) is completed instead, with nothing to choose.** The currency symbol comes from the caller — the operator's panel reads it* from the store it is looking at, and a seller has no currency of their own.@@ -161,6 +167,7 @@ export function ReturnRefundDialog({const { t } = useTranslation()const [refundMethod, setRefundMethod] = useState<RefundMethod>('original_payment')const [amount, setAmount] = useState(refundableTotal)+ const owesNothing = returnOwesNothing(refundableTotal)const methodOptions = [{@@ -177,48 +184,60 @@ export function ReturnRefundDialog({<Dialog open onOpenChange={(open) => !open && onClose()}><DialogContent><DialogHeader>- <DialogTitle>{t('admin.pages.orders.detail.returns.refund_title')}</DialogTitle>+ <DialogTitle>+ {owesNothing+ ? t('admin.pages.orders.detail.returns.complete_title')+ : t('admin.pages.orders.detail.returns.refund_title')}+ </DialogTitle></DialogHeader><DialogBody className="flex flex-col gap-4">- <Field>- <FieldLabel htmlFor="refund-amount">- {t('admin.pages.orders.detail.returns.refund_amount')}- </FieldLabel>- <InputGroup>- <InputGroupAddon>- <InputGroupText>{currencySymbol}</InputGroupText>- </InputGroupAddon>- <InputGroupInput- id="refund-amount"- type="number"- step="0.01"- min="0"- value={amount}- onChange={(event) => setAmount(event.target.value)}- />- </InputGroup>- </Field>- <Field>- <FieldLabel htmlFor="refund-method">- {t('admin.pages.orders.detail.returns.refund_method')}- </FieldLabel>- <Select- items={methodOptions}- value={refundMethod}- onValueChange={(value) => setRefundMethod(value as RefundMethod)}- >- <SelectTrigger id="refund-method">- <SelectValue />- </SelectTrigger>- <SelectContent>- {methodOptions.map((option) => (- <SelectItem key={option.value} value={option.value}>- {option.label}- </SelectItem>- ))}- </SelectContent>- </Select>- </Field>+ {owesNothing ? (+ <p className="text-muted-foreground text-sm">+ {t('admin.pages.orders.detail.returns.nothing_owed')}+ </p>+ ) : (+ <>+ <Field>+ <FieldLabel htmlFor="refund-amount">+ {t('admin.pages.orders.detail.returns.refund_amount')}+ </FieldLabel>+ <InputGroup>+ <InputGroupAddon>+ <InputGroupText>{currencySymbol}</InputGroupText>+ </InputGroupAddon>+ <InputGroupInput+ id="refund-amount"+ type="number"+ step="0.01"+ min="0"+ value={amount}+ onChange={(event) => setAmount(event.target.value)}+ />+ </InputGroup>+ </Field>+ <Field>+ <FieldLabel htmlFor="refund-method">+ {t('admin.pages.orders.detail.returns.refund_method')}+ </FieldLabel>+ <Select+ items={methodOptions}+ value={refundMethod}+ onValueChange={(value) => setRefundMethod(value as RefundMethod)}+ >+ <SelectTrigger id="refund-method">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {methodOptions.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </Field>+ </>+ )}</DialogBody><DialogFooter><Button type="button" variant="outline" onClick={onClose} disabled={pending}>@@ -227,9 +246,11 @@ export function ReturnRefundDialog({<Buttontype="button"disabled={pending}- onClick={() => onSubmit({ refundMethod, amount })}+ onClick={() => onSubmit({ refundMethod, amount: owesNothing ? undefined : amount })}>- {t('admin.pages.orders.detail.returns.actions.refund')}+ {owesNothing+ ? t('admin.pages.orders.detail.returns.actions.complete')+ : t('admin.pages.orders.detail.returns.actions.refund')}</Button></DialogFooter></DialogContent>diff --git a/packages/dashboard/src/components/spree/order-returns-card.tsx b/packages/dashboard/src/components/spree/order-returns-card.tsxindex 557da79d10..96aaf28c78 100644--- a/packages/dashboard/src/components/spree/order-returns-card.tsx+++ b/packages/dashboard/src/components/spree/order-returns-card.tsx@@ -17,12 +17,14 @@ import {type RefundMethod,ReturnReceiveDialog,ReturnRefundDialog,+ returnOwesNothing,StatusBadge,useConfirm,} from '@spree/dashboard-ui'import {BanknoteIcon,CheckCircleIcon,+ ClipboardCheckIcon,EllipsisVerticalIcon,PackageCheckIcon,PlusIcon,@@ -126,8 +128,17 @@ export function OrderReturnsCard({ order }: { order: Order }) {)}{returnRecord.status === 'received' && (<DropdownMenuItem onClick={() => setRefunding(returnRecord)}>- <BanknoteIcon className="size-4" />- {t('admin.pages.orders.detail.returns.actions.refund')}+ {returnOwesNothing(returnRecord.refundable_total) ? (+ <>+ <ClipboardCheckIcon className="size-4" />+ {t('admin.pages.orders.detail.returns.actions.complete')}+ </>+ ) : (+ <>+ <BanknoteIcon className="size-4" />+ {t('admin.pages.orders.detail.returns.actions.refund')}+ </>+ )}</DropdownMenuItem>)}{['requested', 'approved'].includes(returnRecord.status) && (diff --git a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsxindex dddf5641b8..7359d86da4 100644--- a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx+++ b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx@@ -304,7 +304,7 @@ export function CreateClaimDialog({id: item.id,label: [item.name, item.options_text].filter(Boolean).join(' — ') || item.id,quantity: item.quantity,- price: item.price,+ discountedAmount: item.discounted_amount,}))}currencySymbol={currencySymbol}reasonField={<ReasonField kind="claim-reasons" value={reasonId} onChange={setReasonId} />}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex fdd460fe16..2e0aa5047d 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -3366,7 +3366,8 @@"approve": "موافقة","create": "مرتجع جديد","receive": "استلام العناصر",- "refund": "استرداد"+ "refund": "استرداد",+ "complete": "إكمال المرتجع"},"buy_label": "شراء ملصق إرجاع","buy_label_confirm": "شراء ملصق إرجاع مدفوع مسبقًا؟ سيُخصم من حساب شركة الشحن فور إصداره.",@@ -3395,6 +3396,8 @@"store_credit": "رصيد المتجر"},"refund_title": "استرداد المرتجع",+ "complete_title": "إكمال المرتجع",+ "nothing_owed": "لا يوجد أي مبلغ مستحق على هذا المرتجع، لذلك لن يُسترد أي مبلغ. يؤدي إكماله إلى إغلاق المرتجع.","refund_total": "إجمالي الاسترداد","resellable": "قابل لإعادة البيع","returning_to": "الإرجاع إلى {{name}}"diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 393a964edd..236d266a62 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -3338,7 +3338,8 @@"approve": "Genehmigen","create": "Neue Retoure","receive": "Artikel annehmen",- "refund": "Erstatten"+ "refund": "Erstatten",+ "complete": "Retoure abschließen"},"buy_label": "Rücksendeetikett kaufen","buy_label_confirm": "Ein vorfrankiertes Rücksendeetikett kaufen? Ihr Konto wird belastet, sobald das Etikett ausgestellt ist.",@@ -3367,6 +3368,8 @@"store_credit": "Guthaben"},"refund_title": "Retoure erstatten",+ "complete_title": "Retoure abschließen",+ "nothing_owed": "Für diese Retoure ist nichts geschuldet, daher wird kein Geld erstattet. Mit dem Abschließen wird die Retoure geschlossen.","refund_total": "Erstattungssumme","resellable": "Wiederverkäuflich","returning_to": "Rücksendung an {{name}}"diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 407c0a9fb2..167c6c0dc4 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -3338,7 +3338,8 @@"approve": "Approve","create": "New return","receive": "Receive items",- "refund": "Refund"+ "refund": "Refund",+ "complete": "Complete return"},"buy_label": "Buy return label","buy_label_confirm": "Buy a prepaid return label? Your carrier account is charged as soon as the label is issued.",@@ -3367,6 +3368,8 @@"store_credit": "Store credit"},"refund_title": "Refund return",+ "complete_title": "Complete return",+ "nothing_owed": "Nothing is owed on this return, so no money goes back. Completing it closes the return.","refund_total": "Refund total","resellable": "Resellable","returning_to": "Returning to {{name}}"diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 7c5e4c241e..4e15f68f45 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -285,7 +285,8 @@"approve": "Aprobar","create": "Nueva devolución","receive": "Recibir artículos",- "refund": "Reembolsar"+ "refund": "Reembolsar",+ "complete": "Completar devolución"},"buy_label": "Comprar etiqueta de devolución","buy_label_confirm": "¿Comprar una etiqueta de devolución prepagada? Tu cuenta de transportista se cobra en cuanto se emite la etiqueta.",@@ -314,6 +315,8 @@"store_credit": "Crédito de tienda"},"refund_title": "Reembolsar devolución",+ "complete_title": "Completar devolución",+ "nothing_owed": "No se debe nada en esta devolución, así que no se reembolsa dinero. Al completarla, la devolución se cierra.","refund_total": "Total del reembolso","resellable": "Revendible","returning_to": "Devolviendo a {{name}}"diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 39edaa4e3c..b8f8e2baea 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -3338,7 +3338,8 @@"approve": "Approuver","create": "Nouveau retour","receive": "Réceptionner les articles",- "refund": "Rembourser"+ "refund": "Rembourser",+ "complete": "Clôturer le retour"},"buy_label": "Acheter une étiquette de retour","buy_label_confirm": "Acheter une étiquette de retour prépayée ? Votre compte transporteur est débité dès son émission.",@@ -3367,6 +3368,8 @@"store_credit": "Avoir"},"refund_title": "Rembourser le retour",+ "complete_title": "Clôturer le retour",+ "nothing_owed": "Rien n'est dû sur ce retour, donc aucun remboursement n'est effectué. Le clôturer ferme le retour.","refund_total": "Total du remboursement","resellable": "Revendable","returning_to": "Retour vers {{name}}"diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex b10e30988e..fdfc2c6426 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -3376,7 +3376,8 @@"approve": "Zatwierdź","create": "Nowy zwrot","receive": "Przyjmij produkty",- "refund": "Zwróć płatność"+ "refund": "Zwróć płatność",+ "complete": "Zakończ zwrot"},"buy_label": "Kup etykietę zwrotną","buy_label_confirm": "Kupić opłaconą etykietę zwrotną? Twoje konto zostanie obciążone w momencie jej wystawienia.",@@ -3405,6 +3406,8 @@"store_credit": "Kredyt sklepowy"},"refund_title": "Zwrot płatności",+ "complete_title": "Zakończ zwrot",+ "nothing_owed": "Z tytułu tego zwrotu nic nie jest należne, więc pieniądze nie zostaną zwrócone. Zakończenie zamyka zwrot.","refund_total": "Kwota zwrotu","resellable": "Nadaje się do sprzedaży","returning_to": "Zwrot do {{name}}"diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 88c6559bcd..a6d4d2dd85 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -3328,7 +3328,8 @@"approve": "批准","create": "新建退货","receive": "接收商品",- "refund": "退款"+ "refund": "退款",+ "complete": "完成退货"},"buy_label": "购买退货面单","buy_label_confirm": "购买预付退货面单?面单一经出具即从您的承运商账户扣款。",@@ -3357,6 +3358,8 @@"store_credit": "商店积分"},"refund_title": "退货退款",+ "complete_title": "完成退货",+ "nothing_owed": "此退货没有应退金额,因此不会退款。完成后该退货将关闭。","refund_total": "退款总额","resellable": "可再销售","returning_to": "退回至 {{name}}"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.tsxindex bc401b2594..bcc5d59d4d 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@@ -137,7 +137,7 @@ export function CreateClaimDialog({id: item.id,label: unitLabel(item),quantity: item.quantity,- price: item.price,+ discountedAmount: item.discounted_amount,}))}currencySymbol={currencySymbol}reasonField={<ClaimReasonField value={reasonId} onChange={setReasonId} />}diff --git a/packages/seller-dashboard/src/components/orders/returns-card.tsx b/packages/seller-dashboard/src/components/orders/returns-card.tsxindex b88e9bff9c..c29632cfd0 100644--- a/packages/seller-dashboard/src/components/orders/returns-card.tsx+++ b/packages/seller-dashboard/src/components/orders/returns-card.tsx@@ -14,6 +14,7 @@ import {DropdownMenuTrigger,ReturnReceiveDialog,ReturnRefundDialog,+ returnOwesNothing,StatusBadge,useConfirm,} from '@spree/dashboard-ui'@@ -114,7 +115,9 @@ export function ReturnsCard({ order }: { order: Order }) {)}{returnRecord.status === 'received' && (<DropdownMenuItem onClick={() => setRefunding(returnRecord)}>- {t('orders.post_sale.returns.refund')}+ {returnOwesNothing(returnRecord.refundable_total)+ ? t('admin.pages.orders.detail.returns.actions.complete')+ : t('orders.post_sale.returns.refund')}</DropdownMenuItem>)}<DropdownMenuSeparator />diff --git a/packages/seller-dashboard/src/locales/ar.json b/packages/seller-dashboard/src/locales/ar.jsonindex 5e091b250a..da760d52f8 100644--- a/packages/seller-dashboard/src/locales/ar.json+++ b/packages/seller-dashboard/src/locales/ar.json@@ -136,7 +136,8 @@"returns": {"actions": {"receive": "استلام العناصر",- "refund": "رد المبلغ"+ "refund": "رد المبلغ",+ "complete": "إكمال المرتجع"},"create_title": "إرجاع جديد","location": "الإرجاع إلى",@@ -153,6 +154,8 @@"store_credit": "رصيد المتجر"},"refund_title": "رد مبلغ الإرجاع",+ "complete_title": "إكمال المرتجع",+ "nothing_owed": "لا يوجد أي مبلغ مستحق على هذا المرتجع، لذلك لن يُسترد أي مبلغ. يؤدي إكماله إلى إغلاق المرتجع.","resellable": "قابل لإعادة البيع"}}diff --git a/packages/seller-dashboard/src/locales/de.json b/packages/seller-dashboard/src/locales/de.jsonindex 5f9d9895d2..37ea0c63a2 100644--- a/packages/seller-dashboard/src/locales/de.json+++ b/packages/seller-dashboard/src/locales/de.json@@ -136,7 +136,8 @@"returns": {"actions": {"receive": "Artikel annehmen",- "refund": "Erstatten"+ "refund": "Erstatten",+ "complete": "Retoure abschließen"},"create_title": "Neue Rücksendung","location": "Zurück an",@@ -153,6 +154,8 @@"store_credit": "Guthaben"},"refund_title": "Rücksendung erstatten",+ "complete_title": "Retoure abschließen",+ "nothing_owed": "Für diese Retoure ist nichts geschuldet, daher wird kein Geld erstattet. Mit dem Abschließen wird die Retoure geschlossen.","resellable": "Wiederverkäuflich"}}diff --git a/packages/seller-dashboard/src/locales/en.json b/packages/seller-dashboard/src/locales/en.jsonindex 3ec506315d..960338374f 100644--- a/packages/seller-dashboard/src/locales/en.json+++ b/packages/seller-dashboard/src/locales/en.json@@ -155,9 +155,12 @@"resellable": "Resellable","actions": {"receive": "Receive items",- "refund": "Refund"+ "refund": "Refund",+ "complete": "Complete return"},"refund_title": "Refund return",+ "complete_title": "Complete return",+ "nothing_owed": "Nothing is owed on this return, so no money goes back. Completing it closes the return.","refund_amount": "Amount","refund_method": "Refund to","refund_methods": {diff --git a/packages/seller-dashboard/src/locales/fr.json b/packages/seller-dashboard/src/locales/fr.jsonindex 0b0986961c..a64cce9b10 100644--- a/packages/seller-dashboard/src/locales/fr.json+++ b/packages/seller-dashboard/src/locales/fr.json@@ -136,7 +136,8 @@"returns": {"actions": {"receive": "Réceptionner les articles",- "refund": "Rembourser"+ "refund": "Rembourser",+ "complete": "Clôturer le retour"},"create_title": "Nouveau retour","location": "Retourner à",@@ -153,6 +154,8 @@"store_credit": "Avoir"},"refund_title": "Rembourser le retour",+ "complete_title": "Clôturer le retour",+ "nothing_owed": "Rien n'est dû sur ce retour, donc aucun remboursement n'est effectué. Le clôturer ferme le retour.","resellable": "Revendable"}}diff --git a/packages/seller-dashboard/src/locales/pl.json b/packages/seller-dashboard/src/locales/pl.jsonindex 9c15dd2459..34d963ea4e 100644--- a/packages/seller-dashboard/src/locales/pl.json+++ b/packages/seller-dashboard/src/locales/pl.json@@ -136,7 +136,8 @@"returns": {"actions": {"receive": "Przyjmij pozycje",- "refund": "Zwrot pieniędzy"+ "refund": "Zwrot pieniędzy",+ "complete": "Zakończ zwrot"},"create_title": "Nowy zwrot","location": "Zwrot do",@@ -153,6 +154,8 @@"store_credit": "Kredyt sklepowy"},"refund_title": "Zwrot pieniędzy za zwrot",+ "complete_title": "Zakończ zwrot",+ "nothing_owed": "Z tytułu tego zwrotu nic nie jest należne, więc pieniądze nie zostaną zwrócone. Zakończenie zamyka zwrot.","resellable": "Do ponownej sprzedaży"}}diff --git a/packages/seller-dashboard/src/locales/zh-CN.json b/packages/seller-dashboard/src/locales/zh-CN.jsonindex b1a0c2c514..558e214247 100644--- a/packages/seller-dashboard/src/locales/zh-CN.json+++ b/packages/seller-dashboard/src/locales/zh-CN.json@@ -136,7 +136,8 @@"returns": {"actions": {"receive": "接收商品",- "refund": "退款"+ "refund": "退款",+ "complete": "完成退货"},"create_title": "新建退货","location": "退回至",@@ -153,6 +154,8 @@"store_credit": "店铺余额"},"refund_title": "退货退款",+ "complete_title": "完成退货",+ "nothing_owed": "此退货没有应退金额,因此不会退款。完成后该退货将关闭。","resellable": "可再次销售"}}diff --git a/packages/seller-sdk/src/types/generated/OrderLineItem.ts b/packages/seller-sdk/src/types/generated/OrderLineItem.tsindex a6f4e59a9c..2b070f1284 100644--- a/packages/seller-sdk/src/types/generated/OrderLineItem.ts+++ b/packages/seller-sdk/src/types/generated/OrderLineItem.ts@@ -1,4 +1,4 @@-// Typelizer digest f5cd2d99ff8cf72ea5d0916fcd86fa92+// Typelizer digest 1da229feb3bbb66489d256a82f109b43//// DO NOT MODIFY: This file was automatically generated by Typelizer.@@ -10,6 +10,8 @@ type OrderLineItem = {currency: string;price: string | null;display_price: string | null;+ discounted_amount: string | null;+ display_discounted_amount: string | null;total: string | null;display_total: string | null;variant_id: string | null;diff --git a/packages/seller-sdk/src/zod/generated/OrderLineItem.ts b/packages/seller-sdk/src/zod/generated/OrderLineItem.tsindex 1d749a2962..c38deddaa1 100644--- a/packages/seller-sdk/src/zod/generated/OrderLineItem.ts+++ b/packages/seller-sdk/src/zod/generated/OrderLineItem.ts@@ -9,6 +9,8 @@ export const OrderLineItemSchema = z.object({currency: z.string(),price: z.string().nullable(),display_price: z.string().nullable(),+ discounted_amount: z.string().nullable(),+ display_discounted_amount: z.string().nullable(),total: z.string().nullable(),display_total: z.string().nullable(),variant_id: z.string().nullable(),diff --git a/spree/api/app/serializers/spree/api/v3/seller/order_line_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/seller/order_line_item_serializer.rbindex f8cb6aadc1..7b5e77cb34 100644--- a/spree/api/app/serializers/spree/api/v3/seller/order_line_item_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/seller/order_line_item_serializer.rb@@ -19,11 +19,13 @@ module Spreevariant_id: [:string, nullable: true],thumbnail_url: [:string, nullable: true],price: [:string, nullable: true], display_price: [:string, nullable: true],+ discounted_amount: [:string, nullable: true], display_discounted_amount: [:string, nullable: true],total: [:string, nullable: true], display_total: [:string, nullable: true]attributes :name, :options_text, :quantity, :currency- money_attributes :price, :display_price, :total, :display_total+ money_attributes :price, :display_price, :discounted_amount, :display_discounted_amount,+ :total, :display_totalattribute :variant_id do |line_item|line_item.variant&.prefixed_iddiff --git a/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rbindex 5d14f71b1a..629054225f 100644--- a/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/seller/orders_controller_spec.rb@@ -242,6 +242,18 @@ RSpec.describe Spree::Api::V3::Seller::OrdersController, type: :controller doexpect(row.keys).not_to include('payment_id', 'payment_number', 'payment_method')end+ # What a claim on the line can refund at most, so the seller panel can+ # offer it.+ it 'renders what each line sold for after discounts' do+ line_item = mine.line_items.first+ line_item.update_columns(price: 10, quantity: 1, taxable_adjustment_total: -2)++ get :show, params: { id: mine.prefixed_id }, as: :json++ item = json_response['items'].find { |row| row['id'] == line_item.prefixed_id }+ expect(item).to include('discounted_amount' => '8.0', 'display_discounted_amount' => '$8.00')+ end+it 'leaves the shares out unless asked' doget :show, params: { id: mine.prefixed_id }, as: :jsondiff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex db67a837a6..2efb11c200 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -156,7 +156,8 @@ module Spreewhere(Spree::ProductCategory.table_name => { category_id: taxon_ids }).select("#{Product.table_name}.*", "#{min_position_sql} AS min_taxon_position").group("#{Product.table_name}.id").- order(Arel.sql("#{min_position_sql} ASC"))+ # Ties fall back to id, so the order holds across queries and pages.+ order(Arel.sql("#{min_position_sql} ASC"), arel_table[:id].asc)}scope :with_option_value, ->(option, value) {diff --git a/spree/core/app/models/spree/claim_line_item.rb b/spree/core/app/models/spree/claim_line_item.rbindex 5d0d8c33d3..0f46e48a8f 100644--- a/spree/core/app/models/spree/claim_line_item.rb+++ b/spree/core/app/models/spree/claim_line_item.rb@@ -23,9 +23,7 @@ module Spree# What the customer paid for the affected units, after discounts — the# ceiling for a refund on this line.def paid_amount- return 0 if line_item.nil? || line_item.quantity.to_i.zero?-- (line_item.amount / line_item.quantity) * quantity.to_i+ line_item&.discounted_amount_for(quantity) || 0enddef display_refund_amountdiff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex 9003db067d..e59d588974 100644--- a/spree/core/app/models/spree/line_item.rb+++ b/spree/core/app/models/spree/line_item.rb@@ -260,6 +260,17 @@ module Spreealias discounted_money display_discounted_amountalias discounted_amount taxable_amount+ # What +units+ of this line cost the customer after discounts. Multiplied+ # before dividing, so all of a line's units together come to the whole line.+ #+ # @param units [Integer]+ # @return [BigDecimal] rounded to the currency, never negative+ def discounted_amount_for(units)+ return BigDecimal(0) if quantity.to_i.zero?++ Spree::Money::Rounding.to_currency([discounted_amount, 0].max * units.to_i / quantity, currency)+ end+# Returns the amount this line item is taxed on. Whole-order promotions# are distributed to line-item Discount rows at application time, so the# discounted amount already carries the line's share. Never negative.diff --git a/spree/core/app/models/spree/return_line_item.rb b/spree/core/app/models/spree/return_line_item.rbindex 2c87b05107..4ef62f4975 100644--- a/spree/core/app/models/spree/return_line_item.rb+++ b/spree/core/app/models/spree/return_line_item.rb@@ -53,9 +53,7 @@ module Spreeenddef default_pre_tax_amount- return 0 if line_item.nil? || line_item.quantity.to_i.zero?-- (line_item.amount / line_item.quantity) * quantity.to_i+ line_item&.discounted_amount_for(quantity) || 0endendenddiff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rbindex 5d1c62624e..1d6141b23d 100644--- a/spree/core/app/workflows/spree/returns/refund.rb+++ b/spree/core/app/workflows/spree/returns/refund.rb@@ -30,7 +30,11 @@ module Spreerun_hooks :validaterun_hooks :before_refund- if internal_refund?+ # Nothing is owed (a free gift sent back), so the return closes+ # without a refund row, store credit or tax credit.+ if @amount_to_refund.zero?+ step :mark_refunded+ elsif internal_refund?ApplicationRecord.transaction dostep :issue_store_creditstep :mark_refunded@@ -40,7 +44,7 @@ module Spreestep :mark_refundedend- external_step :refund_tax+ external_step :refund_tax unless @amount_to_refund.zero?run_hooks :after_refundreturn_record.publish_event('return.refunded')success(return_record.reload)@@ -85,12 +89,15 @@ module Spree# Only what actually came back is refundable — a customer who sent two of# three items gets two items' worth. One figure serves as both the# default and the ceiling, so a caller naming an amount cannot ask for- # more than a caller who names none would get.+ # more than a caller who names none would get. Zero is accepted only when+ # zero is owed, so a return the customer is owed money on cannot be+ # closed without paying them.def resolve_amountrefundable = return_record.refundable_total.to_d@amount_to_refund = amount ? amount.to_d : refundable- failure(return_record, :nothing_to_refund) unless @amount_to_refund.positive?+ failure(return_record, :refund_amount_negative) if @amount_to_refund.negative?+ failure(return_record, :refund_amount_required) if @amount_to_refund.zero? && refundable.positive?failure(return_record, :refund_exceeds_balance) if @amount_to_refund > refundableenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex f0cfe631a3..2b10588618 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -1593,6 +1593,8 @@ en:reference: Referencerefund: Refundrefund_amount: Refund Amount+ refund_amount_negative: The refund amount cannot be negative.+ refund_amount_required: Enter an amount greater than zero, because the customer is still owed money on this return.refund_exceeds_balance: That is more than the amount still refundable.refunds: Refundsregister: Registerdiff --git a/spree/core/spec/models/spree/claim_spec.rb b/spree/core/spec/models/spree/claim_spec.rbindex fa6c1f8b5e..b572ca953f 100644--- a/spree/core/spec/models/spree/claim_spec.rb+++ b/spree/core/spec/models/spree/claim_spec.rb@@ -38,10 +38,10 @@ RSpec.describe Spree::Claim dolet(:claim) { create(:claim, store: store) }let(:line) { claim.claim_line_items.first }- it 'caps a refund at what the customer paid for the units' do- line_item = line.line_item+ it 'caps a refund at what the customer paid for the units after discounts' do+ line.line_item.update_columns(price: 10, taxable_adjustment_total: -2)- expect(line.paid_amount).to eq(line_item.amount / line_item.quantity)+ expect(line.paid_amount).to eq(8)endit 'sends the original variant when no replacement is named' dodiff --git a/spree/core/spec/models/spree/line_item_spec.rb b/spree/core/spec/models/spree/line_item_spec.rbindex 67a003878a..ba82095a7d 100644--- a/spree/core/spec/models/spree/line_item_spec.rb+++ b/spree/core/spec/models/spree/line_item_spec.rb@@ -375,6 +375,28 @@ describe Spree::LineItem, type: :model doendend+ describe '#discounted_amount_for' do+ before do+ line_item.price = 10+ line_item.quantity = 3+ line_item.taxable_adjustment_total = -10+ end++ it 'rounds a share that does not divide evenly to the currency' do+ expect(line_item.discounted_amount_for(1)).to eq(6.67)+ end++ it 'comes to the whole discounted line for every unit' do+ expect(line_item.discounted_amount_for(3)).to eq(20)+ end++ it 'is never negative' do+ line_item.taxable_adjustment_total = -40++ expect(line_item.discounted_amount_for(1)).to eq(0)+ end+ end+describe '.currency' doit 'returns the globally configured currency' doline_item.currency == 'USD'diff --git a/spree/core/spec/models/spree/return_spec.rb b/spree/core/spec/models/spree/return_spec.rbindex ca57d5c453..126ca3ac8c 100644--- a/spree/core/spec/models/spree/return_spec.rb+++ b/spree/core/spec/models/spree/return_spec.rb@@ -116,12 +116,23 @@ RSpec.describe Spree::Return dolet(:return_record) { create(:return, store: store) }let(:line) { return_record.return_line_items.first }- # Refunding the list price would give back more than the customer paid- # on a discounted line.- it 'defaults the refundable amount to the paid share of the line' do- line_item = line.line_item+ context 'when the line was discounted' do+ let(:order) { create(:shipped_order, store: store) }+ let(:return_record) { create(:return, order: order, store: store) }+ let(:line_item) { order.line_items.first }- expect(line.pre_tax_amount).to eq(line_item.amount / line_item.quantity)+ # Refunding the list price would give back more than the customer paid.+ it 'defaults the refundable amount to what the customer paid after the discount' do+ line_item.update_columns(price: 10, taxable_adjustment_total: -2)++ expect(line.pre_tax_amount).to eq(8)+ end++ it 'refunds nothing for a unit the customer got for free' do+ line_item.update_columns(price: 10, taxable_adjustment_total: -10)++ expect(line.pre_tax_amount).to eq(0)+ endendit 'requires a positive quantity' dodiff --git a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rbindex eddc455158..76117c1418 100644--- a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb@@ -197,6 +197,64 @@ RSpec.describe 'Spree::Returns workflows' doexpect(result.error.value).to eq(:refund_exceeds_balance)end+ it 'refuses zero while the customer is still owed money' do+ result = Spree::Returns::Refund.call(return_record: return_record, amount: 0)++ expect(result).to be_failure+ expect(result.error.value).to eq(:refund_amount_required)+ expect(return_record.reload).to be_received+ end++ it 'refuses a negative amount' do+ result = Spree::Returns::Refund.call(return_record: return_record, amount: -1)++ expect(result).to be_failure+ expect(result.error.value).to eq(:refund_amount_negative)+ end++ # A free gift sent back is owed nothing, and refusing to refund it left the+ # return received for good, with no step that could close it.+ context 'when nothing is owed' do+ before do+ return_record.return_line_items.each { |line| line.update!(pre_tax_amount: 0) }+ return_record.reload+ end++ %w[original_payment store_credit].each do |refund_method|+ it "closes the return without moving any money when asked for #{refund_method}", :events do+ allow(Spree::Events).to receive(:publish)+ order = return_record.order+ provider = instance_double(Spree::TaxProvider::Internal, refund: nil, estimate: nil)+ allow(order).to receive(:tax_provider).and_return(provider)+ allow_any_instance_of(Spree::Return).to receive(:order).and_return(order)++ result = Spree::Returns::Refund.call(return_record: return_record, refund_method: refund_method)++ expect(result).to be_success+ expect(result.value).to be_refunded+ expect(return_record.refunds).to be_empty+ expect(Spree::StoreCredit.where(originator: return_record)).to be_empty+ expect(provider).not_to have_received(:refund)+ expect(Spree::Events).to have_received(:publish).with('return.refunded', any_args)+ end+ end+ end++ # Completing a return whose money already went back moves nothing, so there+ # is no tax to credit a second time.+ it 'credits no tax when the money already went back' do+ create(:store_credit, originator: return_record, amount: return_record.refund_total)+ order = return_record.order+ provider = instance_double(Spree::TaxProvider::Internal, refund: nil, estimate: nil)+ allow(order).to receive(:tax_provider).and_return(provider)+ allow_any_instance_of(Spree::Return).to receive(:order).and_return(order)++ result = Spree::Returns::Refund.call(return_record: return_record)++ expect(result.value).to be_refunded+ expect(provider).not_to have_received(:refund)+ end+context 'to store credit' doit 'issues credit inside the transaction and marks the return refunded' doresult = Spree::Returns::Refund.call(return_record: return_record, refund_method: 'store_credit')diff --git a/spree/emails/app/subscribers/spree/return_email_subscriber.rb b/spree/emails/app/subscribers/spree/return_email_subscriber.rbindex 913d023b84..309e0f18a2 100644--- a/spree/emails/app/subscribers/spree/return_email_subscriber.rb+++ b/spree/emails/app/subscribers/spree/return_email_subscriber.rb@@ -10,6 +10,8 @@ module Spreestore = return_record.storereturn unless store.prefers_send_consumer_transactional_emails?+ # A return owed nothing closes without a refund, so there is none to announce.+ return if return_record.refunded_total.zero?ReturnMailer.refunded_email(return_record.id).deliver_laterenddiff --git a/spree/emails/spec/subscribers/spree/return_email_subscriber_spec.rb b/spree/emails/spec/subscribers/spree/return_email_subscriber_spec.rbnew file mode 100644index 0000000000..d012d670e5--- /dev/null+++ b/spree/emails/spec/subscribers/spree/return_email_subscriber_spec.rb@@ -0,0 +1,25 @@+require 'spec_helper'++describe Spree::ReturnEmailSubscriber do+ let(:store) { @default_store }+ let(:return_record) { create(:received_return, store: store) }++ def handle(return_record)+ event = instance_double(Spree::Event, payload: { 'id' => return_record.prefixed_id })+ described_class.new.handle(event)+ end++ it 'mails the customer when money went back' do+ create(:store_credit, originator: return_record, amount: 10)++ expect {+ handle(return_record)+ }.to have_enqueued_job(ActionMailer::MailDeliveryJob).with(+ 'Spree::ReturnMailer', 'refunded_email', 'deliver_now', args: [return_record.id]+ )+ end++ it 'stays silent when the return closed with nothing refunded' do+ expect { handle(return_record) }.not_to have_enqueued_job(ActionMailer::MailDeliveryJob)+ end+end