Handle already-paid orders gracefully in checkout

When create-session is called for an order that's already paid (e.g.
free order with page refresh, duplicate submit, or browser retry),
return a success redirect instead of 404. Prevents confusing
"Payment Not Confirmed" errors on the success page.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
justin 2026-05-22 01:07:27 -05:00
parent 316d4a4912
commit 7bb08f3493

View file

@ -645,6 +645,36 @@ router.post("/api/v1/checkout/create-session", async (req, res) => {
throw err;
}
if (!orderData) {
// Check if the order exists but is already paid (e.g. free order, duplicate submit)
try {
const tables: Record<string, {table: string; col: string}> = {
canada_crtc: { table: "canada_crtc_orders", col: "order_number" },
formation: { table: "formation_orders", col: "order_number" },
bundle: { table: "bundle_orders", col: "order_number" },
compliance: { table: "compliance_orders", col: "order_number" },
compliance_batch: { table: "compliance_orders", col: "batch_id" },
};
const t = tables[order_type];
if (t) {
const { rows } = await pool.query(
`SELECT payment_status, payment_method FROM ${t.table} WHERE ${t.col} = $1 LIMIT 1`,
[order_id],
);
if (rows.length > 0 && rows[0].payment_status === "paid") {
// Already paid — redirect to success
const isFree = rows[0].payment_method === "free";
console.log(`[checkout] Order ${order_id} already paid (${rows[0].payment_method}) — returning success redirect`);
res.json({
checkout_url: `${DOMAIN}/order/success?order_id=${order_id}&order_type=${order_type}${isFree ? "&free=1" : ""}`,
session_id: null,
total_cents: 0,
surcharge_cents: 0,
surcharge_pct: 0,
});
return;
}
}
} catch { /* fall through to 404 */ }
res.status(404).json({ error: "Order not found or not in pending_payment state" });
return;
}