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 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.
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.
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
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
56 changes: 56 additions & 0 deletions packages/core/test/provider-tax-guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Stripe Tax is calculated by Stripe at checkout. Core returns zero tax for
* that mode, so a provider that ignores automatic_tax would charge the
* pre-tax total. Checkout must refuse instead of undercharging.
*/

import { afterEach, describe, expect, it } from "bun:test";
import type { RouteContext } from "emdash";
import {
createMockPaymentProvider,
registerPaymentProvider,
resetPaymentProviders,
} from "../src/payment-provider";
import sandbox from "../src/sandbox-entry";
import { makeRouteContext, ticketCart } from "./helpers/route-harness";

afterEach(() => resetPaymentProviders());

async function createSession(settings: Record<string, unknown>) {
const { ctx } = makeRouteContext({
"settings:paymentProvider": "mock",
"settings:checkoutMode": "hosted",
"settings:mockSecretKey": "k",
"settings:mockWebhookSecret": "test-secret",
...settings,
});
const sessionId = `sess_${Math.random()}`;
await ctx.kv.set(`cart:${sessionId}`, ticketCart(sessionId));
const routeCtx = {
...ctx,
request: new Request("http://test/checkout/create-session", {
method: "POST",
headers: { Cookie: `dashcommerce_sid=${sessionId}` },
}),
input: {},
} as unknown as RouteContext;
const res = (await sandbox.routes["checkout/create-session"].handler(routeCtx, ctx)) as Response;
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
}

describe("Stripe Tax with a non-Stripe provider", () => {
it("refuses stripe_tax instead of charging the pre-tax total", async () => {
registerPaymentProvider(createMockPaymentProvider());
const res = await createSession({ "settings:taxMode": "stripe_tax" });
expect(res.status).toBe(409);
expect(res.body.code).toBe("stripe_tax_requires_stripe");
expect(String(res.body.error)).toMatch(/flat or table/i);
});

it("still starts checkout with flat tax", async () => {
registerPaymentProvider(createMockPaymentProvider());
const res = await createSession({ "settings:taxMode": "flat" });
expect(res.status).toBe(200);
expect(res.body.orderDraftId).toBeTruthy();
});
});
Loading