Skip to content
Closed
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 generates one per attempt and reuses it if the request fails before the provider answers, so a retry uses the same provider idempotency key.
- `refundOrder` returns the recorded refund for a repeated request id instead of calling the provider again. This covers providers whose refund key is a comment tag and whose refund-list endpoint may be unavailable.
- 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.
58 changes: 45 additions & 13 deletions packages/core/src/admin/pages/OrderDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,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 @@ -328,6 +336,10 @@ function RefundCard({
const [reason, setReason] = useState("");
const [restock, setRestock] = useState(false);
const [pending, setPending] = useState(false);
// Reused if the request fails before the provider answers, so a retry
// cannot create a second refund. Editing the amount or reason starts a
// new attempt.
const [refundRequestId, setRefundRequestId] = useState(newRefundRequestId);

const fullRefund = useMemo(() => {
return typeof amountMajor === "number" && amountMajor >= remainingMajor;
Expand All @@ -350,30 +362,44 @@ function RefundCard({
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.",
? "The payment provider will return the remaining balance to the customer immediately. This cannot be undone."
: "The payment provider will return the specified amount to the customer. This cannot be undone.",
confirmLabel: "Issue refund",
destructive: true,
});
if (!ok) return;

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.`,
const result = await api.post<{ refund: Refund }>(
`admin/orders/refund?id=${encodeURIComponent(order.id)}`,
{
amount: amt,
currency: order.currency,
reason: reason || undefined,
restock: restock || undefined,
refundRequestId,
},
);
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 {
toast.success(
fullRefund ? "Full refund issued" : "Refund issued",
`${(amt / 100).toFixed(2)} ${order.currency} returned to customer.`,
);
}
setAmountMajor(undefined);
setReason("");
setRestock(false);
setRefundRequestId(newRefundRequestId());
await onRefunded();
} catch (err) {
// Keep the same request id: the provider may have accepted the
// refund before the response was lost.
toast.error(
"Refund failed",
err instanceof Error ? err.message : String(err),
Expand Down Expand Up @@ -406,7 +432,10 @@ function RefundCard({
<FormField label={`Amount (${order.currency})`} required>
<NumberInput
value={amountMajor}
onChange={setAmountMajor}
onChange={(value) => {
setAmountMajor(value);
setRefundRequestId(newRefundRequestId());
}}
min={0}
max={remainingMajor}
step={0.01}
Expand All @@ -417,7 +446,10 @@ function RefundCard({
<FormField label="Reason" description="Optional, shown in refund history.">
<Input
value={reason}
onChange={(e) => setReason(e.currentTarget.value)}
onChange={(e) => {
setReason(e.currentTarget.value);
setRefundRequestId(newRefundRequestId());
}}
placeholder="e.g. Damaged on arrival"
disabled={pending}
/>
Expand Down
32 changes: 31 additions & 1 deletion packages/core/src/orders/refund.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,27 @@ 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);
}
Expand All @@ -80,6 +97,19 @@ export async function refundOrder(ctx: PluginContext, input: RefundOrderInput):
throw new Error(`Refund ${input.amount.amount} exceeds remaining refundable ${remaining}`);
}

// A retry with the same request id must not call the provider again.
// Stripe caches its idempotency key; this covers providers whose key is
// a comment tag and whose refund list may be unavailable.
const existing = await findRefundByRequestId(ctx, refundRequestId);
if (existing) {
ctx.log.info("Refund already recorded for this request id; returning it", {
refundId: existing.id,
orderId: order.id,
refundRequestId,
});
return existing;
}

// Provider call first — if this fails, we don't write anything.
const stripeRefund = await providerRefundWithDedup(ctx, order, input);

Expand All @@ -97,7 +127,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
114 changes: 114 additions & 0 deletions packages/core/test/refund-idempotency.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* A stable refund request id is the provider idempotency key. Retrying with
* the same id must return the recorded refund and must not call the provider
* again; a new attempt needs a new id.
*/

import { afterEach, describe, expect, it } from "bun:test";
import type { PluginContext } from "emdash";
import { refundOrder } from "../src/orders/refund";
import {
type PaymentProvider,
createMockPaymentProvider,
registerPaymentProvider,
resetPaymentProviders,
} from "../src/payment-provider";
import type { Order } from "../src/types";
import { deliverWebhook, makeRouteContext, startCheckout } from "./helpers/route-harness";

afterEach(() => resetPaymentProviders());

const settings = {
"settings:paymentProvider": "acme",
"settings:checkoutMode": "hosted",
"settings:acmeSecretKey": "acme-key",
"settings:acmeWebhookSecret": "test-secret",
};
const headers = { "x-acme-signature": "signed" };

async function paidOrder(): Promise<{
ctx: PluginContext;
getCol: (name: string) => Map<string, Record<string, unknown>>;
calls: () => number;
order: Order;
}> {
let calls = 0;
const base = createMockPaymentProvider({ id: "acme" });
const provider: PaymentProvider = {
...base,
async refund(ctx, input, credentials) {
calls += 1;
if (!base.refund) throw new Error("mock refund missing");
return base.refund(ctx, input, credentials);
},
};
registerPaymentProvider(provider);

const { ctx, getCol } = makeRouteContext(settings);
const draftId = await startCheckout(ctx, `sess_${Math.random()}`);
const paid = await deliverWebhook(
ctx,
JSON.stringify({
id: `evt_${draftId}`,
type: "charge.succeeded",
orderDraftId: draftId,
paymentReference: `pay_${draftId}`,
amount: 150000,
currency: "KES",
}),
headers,
);
expect(paid.status).toBe(200);
const order = Array.from(getCol("orders").values())[0] as unknown as Order;
return { ctx, getCol, calls: () => calls, order };
}

describe("refund idempotency", () => {
it("returns the recorded refund and does not call the provider again", async () => {
const { ctx, getCol, calls, order } = await paidOrder();

const first = await refundOrder(ctx, {
orderId: order.id,
amount: { amount: 10_000, currency: "KES" },
idempotencyKey: "refund:stable:1",
});
const second = await refundOrder(ctx, {
orderId: order.id,
amount: { amount: 10_000, currency: "KES" },
idempotencyKey: "refund:stable:1",
});

expect(calls()).toBe(1);
expect(second.id).toBe(first.id);
expect(getCol("refunds").size).toBe(1);
});

it("treats a different request id as a new refund", async () => {
const { ctx, getCol, calls, order } = await paidOrder();

await refundOrder(ctx, {
orderId: order.id,
amount: { amount: 10_000, currency: "KES" },
idempotencyKey: "refund:stable:1",
});
await refundOrder(ctx, {
orderId: order.id,
amount: { amount: 10_000, currency: "KES" },
idempotencyKey: "refund:stable:2",
});

expect(calls()).toBe(2);
expect(getCol("refunds").size).toBe(2);
});

it("rejects an empty request id", async () => {
const { ctx, order } = await paidOrder();
await expect(
refundOrder(ctx, {
orderId: order.id,
amount: { amount: 10_000, currency: "KES" },
idempotencyKey: " ",
}),
).rejects.toThrow(/refundRequestId/i);
});
});