/** * When the final "place the order" call fails in a way that does NOT tell us whether the order was * created. * * `POST /checkout/:id/complete` can create the order and still answer with a 502/503/504 (the * gateway or the BFF timed out while the server finished), or drop the connection. The cart is * emptied by the server at that point, so a "payment error" screen leaves the shopper believing no * order exists, and they may order and pay a second time. Before showing a failure for such an * error, ask the server what happened to the checkout. * * Pure on purpose (no SDK import): the caller passes the read, so this is easy to test. */ /** How many times the checkout is read before giving up. */ export const COMPLETE_RECOVERY_TRIES = 3; /** Pause between two reads. */ export const COMPLETE_RECOVERY_DELAY_MS = 1500; function statusCodeOf(err: unknown): number | null { // The SDK wraps a failed place-order call (PaymentFlowError.cause), so look one or two levels in. let current: unknown = err; for (let depth = 0; depth < 3 && current && typeof current === 'object'; depth++) { const status = (current as { statusCode?: unknown }).statusCode; if (typeof status === 'number') return status; current = (current as { cause?: unknown }).cause; } return null; } /** * True for a failure that leaves the outcome unknown: a network error (the SDK reports it as status * 0), a timeout (408) or any 5xx. A 4xx is the server saying no, and nothing was created. */ export function isUncertainCompleteFailure(err: unknown): boolean { const status = statusCodeOf(err); return status !== null && (status === 0 || status === 408 || status >= 500); } /** * Reads the checkout up to `tries` times, `delayMs` apart, and resolves true as soon as it is * COMPLETED (the order exists: go to the confirmation page exactly as after a success). Resolves * false when it never is, or when every read failed: then show the error with "try again". A retry * is safe, because completing a checkout is idempotent on the server (it returns the order that * already exists). */ export async function confirmCheckoutCompleted( readCheckout: () => Promise<{ status?: string }>, options: { tries?: number; delayMs?: number; sleep?: (ms: number) => Promise; } = {} ): Promise { const tries = options.tries ?? COMPLETE_RECOVERY_TRIES; const delayMs = options.delayMs ?? COMPLETE_RECOVERY_DELAY_MS; const sleep = options.sleep ?? ((ms: number) => new Promise((r) => setTimeout(r, ms))); for (let attempt = 0; attempt < tries; attempt++) { if (attempt > 0) await sleep(delayMs); try { const checkout = await readCheckout(); if (checkout?.status === 'COMPLETED') return true; } catch { // The same outage may still be on: the next try asks again. } } return false; }