Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/provider-refund-idempotency.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
"@dashcommerce/core": minor
---

Harden refund idempotency with a local ledger.

- `admin/orders/refund` accepts a `refundRequestId`. The admin UI locks the original details and reuses that ID while the outcome is unknown or pending.
- `refundOrder` returns the recorded refund to the same order for a repeated request ID, including when the original refund exhausted the balance.
- The admin refund panel now says "the payment provider" rather than "Stripe", and shows a failed provider refund as an error instead of a success.
7 changes: 7 additions & 0 deletions .changeset/provider-tax-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@dashcommerce/core": patch
---

Refuse `stripe_tax` checkout with a non-Stripe provider instead of charging the pre-tax total.

Stripe Tax is calculated by Stripe at checkout, so core returns zero tax for `taxMode: "stripe_tax"`. A provider that ignores `automatic_tax` would silently undercharge. `checkout/create-session` now returns `409 stripe_tax_requires_stripe` and asks the merchant to switch to flat/table tax or to Stripe.
147 changes: 105 additions & 42 deletions packages/core/src/admin/pages/OrderDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
* double-clicks don't submit twice.
*/

import { type CSSProperties, useCallback, useEffect, useMemo, useState } from "react";
import { type CSSProperties, useCallback, useEffect, useRef, useState } from "react";
import { format as formatMoney, minorUnitsFactor } from "../../money";
import {
Alert,
Button,
Expand All @@ -28,6 +29,14 @@ import { EmptyState } from "../ui/EmptyState";
import type { Order, OrderItem, OrderStatus, Refund } from "../../types";
import { T } from "../theme";

/** Stable id for one refund attempt, so a retry after a timeout is idempotent. */
function newRefundRequestId(): string {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return `refund:${crypto.randomUUID()}`;
}
return `refund:${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
}

// Allowed forward transitions mirrored from `../../orders/status.ts` so the
// UI can hide impossible targets without round-tripping to the server.
const ALLOWED_TRANSITIONS: Record<OrderStatus, OrderStatus[]> = {
Expand Down Expand Up @@ -130,7 +139,7 @@ export function OrderDetailPage() {
<BackToOrdersLink />
<OrderHeader order={order} onChanged={reload} />
<ItemsCard items={items} />
<RefundCard order={order} items={items} onRefunded={reload} />
<RefundCard key={order.id} order={order} items={items} onRefunded={reload} />
<RefundHistoryCard refunds={refunds} />
</div>
);
Expand Down Expand Up @@ -311,6 +320,17 @@ function ItemsCard({ items }: { items: OrderItem[] }) {
// Refund panel
// ────────────────────────────────────────────────────────────────────────────

interface RefundAttempt {
request: {
amount: number;
currency: string;
reason?: string;
restock?: boolean;
refundRequestId: string;
};
providerPending: boolean;
}

function RefundCard({
order,
items,
Expand All @@ -322,76 +342,113 @@ function RefundCard({
}) {
const api = usePluginAPI();
const remainingMinor = order.paidTotal.amount - order.refundedTotal.amount;
const remainingMajor = remainingMinor / 100;
const factor = minorUnitsFactor(order.currency);
const remainingMajor = remainingMinor / factor;
const decimalPlaces = Math.log10(factor);

const [amountMajor, setAmountMajor] = useState<number | undefined>(undefined);
const [reason, setReason] = useState("");
const [restock, setRestock] = useState(false);
const [pending, setPending] = useState(false);

const fullRefund = useMemo(() => {
return typeof amountMajor === "number" && amountMajor >= remainingMajor;
}, [amountMajor, remainingMajor]);
const [attempt, setAttempt] = useState<RefundAttempt | null>(null);
const submitting = useRef(false);
const fieldsLocked = pending || attempt !== null;

async function issueRefund(): Promise<void> {
if (pending) return;
const amt = typeof amountMajor === "number" ? Math.round(amountMajor * 100) : 0;
if (!Number.isFinite(amt) || amt <= 0) {
if (submitting.current) return;
const amount = attempt?.request.amount ?? Math.round((amountMajor ?? 0) * factor);
if (!Number.isSafeInteger(amount) || amount <= 0) {
toast.error("Enter a positive refund amount");
return;
}
if (amt > remainingMinor) {
if (!attempt && amount > remainingMinor) {
toast.error(
"Refund exceeds refundable balance",
"Reduce the amount to the remaining balance.",
);
return;
}
const ok = await confirm({
title: fullRefund ? "Refund the remaining balance?" : "Issue partial refund?",
description: fullRefund
? "Stripe will return the remaining balance to the customer immediately. This cannot be undone."
: "Stripe will return the specified amount to the customer. This cannot be undone.",
confirmLabel: "Issue refund",
destructive: true,
});
if (!ok) return;

submitting.current = true;
setPending(true);
try {
await api.post(`admin/orders/refund?id=${encodeURIComponent(order.id)}`, {
amount: amt,
currency: order.currency,
reason: reason || undefined,
restock: restock || undefined,
});
toast.success(
fullRefund ? "Full refund issued" : "Refund issued",
`${(amt / 100).toFixed(2)} ${order.currency} returned to customer.`,
let activeAttempt = attempt;
if (!activeAttempt) {
const fullRefund = amount === remainingMinor;
const ok = await confirm({
title: fullRefund ? "Refund the remaining balance?" : "Issue partial refund?",
description: `The payment provider will refund ${formatMoney({ amount, currency: order.currency })} to the customer. This cannot be undone.`,
confirmLabel: "Issue refund",
destructive: true,
});
if (!ok) return;
activeAttempt = {
request: {
amount,
currency: order.currency,
reason: reason || undefined,
restock: restock || undefined,
refundRequestId: newRefundRequestId(),
},
providerPending: false,
};
setAttempt(activeAttempt);
}

const result = await api.post<{ refund: Refund }>(
`admin/orders/refund?id=${encodeURIComponent(order.id)}`,
activeAttempt.request,
);
if (result.refund?.status === "pending") {
setAttempt({ ...activeAttempt, providerPending: true });
toast.info("Refund is pending", "Check its status again for the provider’s final result.");
return;
}
if (result.refund?.status === "failed") {
toast.error(
"Refund failed at the provider",
"The order was not changed. Start a new attempt when you are ready.",
);
} else if (result.refund?.status === "succeeded") {
toast.success(
"Refund issued",
`${formatMoney(result.refund.amount)} returned to customer.`,
);
} else {
throw new Error("The refund response did not include a recognized status.");
}
setAmountMajor(undefined);
setReason("");
setRestock(false);
setAttempt(null);
await onRefunded();
} catch (err) {
toast.error(
"Refund failed",
err instanceof Error ? err.message : String(err),
);
toast.error("Refund status unavailable", err instanceof Error ? err.message : String(err));
} finally {
submitting.current = false;
setPending(false);
}
}

return (
<Card title="Issue refund">
{remainingMinor <= 0 ? (
{remainingMinor <= 0 && !attempt ? (
<Alert type="info" title="No refundable balance">
This order has already been fully refunded or never captured
payment.
</Alert>
) : (
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
{attempt && !pending && (
<Alert
type="info"
title={attempt.providerPending ? "Refund pending" : "Refund status unavailable"}
>
{attempt.providerPending
? "Check again for the provider’s final result."
: "Retry to check or submit the original refund with the same details."}
</Alert>
)}
<div style={{ fontSize: 13, color: T.text }}>
Up to <MoneyDisplay value={{ ...order.paidTotal, amount: remainingMinor }} /> can
still be refunded.
Expand All @@ -409,17 +466,17 @@ function RefundCard({
onChange={setAmountMajor}
min={0}
max={remainingMajor}
step={0.01}
placeholder={remainingMajor.toFixed(2)}
disabled={pending}
step={1 / factor}
placeholder={remainingMajor.toFixed(decimalPlaces)}
disabled={fieldsLocked}
/>
</FormField>
<FormField label="Reason" description="Optional, shown in refund history.">
<Input
value={reason}
onChange={(e) => setReason(e.currentTarget.value)}
placeholder="e.g. Damaged on arrival"
disabled={pending}
disabled={fieldsLocked}
/>
</FormField>
</div>
Expand All @@ -428,20 +485,26 @@ function RefundCard({
label="Restock items"
checked={restock}
onChange={setRestock}
disabled={pending}
disabled={fieldsLocked}
/>
)}
<div style={{ display: "flex", gap: 8 }}>
<Button
variant="danger"
disabled={pending || !amountMajor}
disabled={pending || (!attempt && !amountMajor)}
onClick={issueRefund}
>
{pending ? "Refunding…" : "Issue refund"}
{pending
? "Checking refund…"
: attempt?.providerPending
? "Check refund status"
: attempt
? "Retry refund"
: "Issue refund"}
</Button>
<Button
variant="secondary"
disabled={pending}
disabled={fieldsLocked}
onClick={() => setAmountMajor(remainingMajor)}
>
Fill remaining balance
Expand Down
34 changes: 33 additions & 1 deletion packages/core/src/orders/refund.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,48 @@ export interface RefundOrderInput {
idempotencyKey: string;
}

async function findRefundByRequestId(
ctx: PluginContext,
refundRequestId: string,
): Promise<Refund | null> {
const result = await refundsStore(ctx).query({
where: { refundRequestId },
limit: 1,
});
const row = result.items[0];
return row ? { ...(row.data as Refund), id: row.id } : null;
}

export async function refundOrder(ctx: PluginContext, input: RefundOrderInput): Promise<Refund> {
const order = await loadOrder(ctx, input.orderId);
if (!order) throw new Error(`Order ${input.orderId} not found`);

const refundRequestId = input.idempotencyKey.trim();
if (!refundRequestId) {
throw new Error("Refund requires an explicit refundRequestId / idempotencyKey");
}

if (order.currency !== input.amount.currency) {
throw new CurrencyMismatchError(order.currency, input.amount.currency);
}
if (input.amount.amount <= 0) {
throw new Error("Refund amount must be > 0");
}
// Look up retries before checking the balance, which the original
// request may already have reduced.
const existing = await findRefundByRequestId(ctx, refundRequestId);
if (existing) {
if (existing.orderId !== order.id) {
throw new Error("Refund request id belongs to a different order");
}
ctx.log.info("Refund already recorded for this request id; returning it", {
refundId: existing.id,
orderId: order.id,
refundRequestId,
});
return existing;
}

const remaining = order.paidTotal.amount - order.refundedTotal.amount;
if (input.amount.amount > remaining) {
throw new Error(`Refund ${input.amount.amount} exceeds remaining refundable ${remaining}`);
Expand All @@ -97,7 +129,7 @@ export async function refundOrder(ctx: PluginContext, input: RefundOrderInput):
? "failed"
: "pending",
stripeRefundId: stripeRefund.id,
refundRequestId: input.idempotencyKey,
refundRequestId,
...(input.lineItemRefunds ? { lineItemRefunds: input.lineItemRefunds } : {}),
restocked: Boolean(input.restock) && stripeRefund.status !== "failed",
orderStatusBefore: order.status,
Expand Down
11 changes: 10 additions & 1 deletion packages/core/src/routes/admin-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,11 +313,20 @@ async function postOrderRefund(
currency?: string;
reason?: string;
restock?: boolean;
refundRequestId?: string;
lineItemRefunds?: Array<{ orderItemId: string; quantity: number; amount: number; currency: string }>;
};
if (typeof input.amount !== "number" || !input.currency) {
return json({ error: "amount (minor units) and currency required" }, 400);
}
const requestedRefundId =
typeof input.refundRequestId === "string" ? input.refundRequestId.trim() : "";
if (requestedRefundId && !/^[A-Za-z0-9:_-]{1,200}$/.test(requestedRefundId)) {
return json(
{ error: "refundRequestId must be 1–200 letters, digits, colons, underscores or hyphens" },
400,
);
}
try {
const refund = await refundOrder(ctx, {
orderId,
Expand All @@ -333,7 +342,7 @@ async function postOrderRefund(
})),
}
: {}),
idempotencyKey: `refund:${orderId}:${randomId()}`,
idempotencyKey: requestedRefundId || `refund:${orderId}:${randomId()}`,
});
return json({ refund });
} catch (err) {
Expand Down
13 changes: 13 additions & 0 deletions packages/core/src/routes/checkout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,19 @@ export const checkoutRoutes = {
}

const policy = await readPricingPolicy(ctx);
// Stripe Tax is calculated by Stripe at checkout; core deliberately
// returns zero tax for this mode. A provider that does not implement
// Stripe's automatic_tax would charge the pre-tax total, so fail
// loudly instead of silently undercharging.
if (policy.taxMode === "stripe_tax" && provider.id !== "stripe") {
return new Response(
JSON.stringify({
error: `Stripe Tax is only available with Stripe. Set the tax mode to flat or table in Settings → Tax, or switch to Stripe.`,
code: "stripe_tax_requires_stripe",
}),
{ status: 409, headers: { "Content-Type": "application/json" } },
);
}
const recalculated = await finalizeCheckoutCart(ctx, withContact, items, policy);
if (totalsChanged(withContact, recalculated)) {
await save(ctx, recalculated);
Expand Down
Loading
Loading