import { getErrorCode } from '@/core/lib/add-to-cart-error'; /** * `POST /checkout` refuses a cart in which a line costs something else now than when it was added * (`400 PRICE_DRIFT`, even by a small amount). The body names each line: * `{ code: 'PRICE_DRIFT', details: { items: [{ itemId, oldUnitPrice, newUnitPrice, ... }] } }`, and the * SDK hands that whole body back as `BrainerceError.details`, so the lines sit at * `err.details.details.items`. The API's `message` is English whatever the shopper's language, so the * page shows its own sentence and these numbers. */ export interface PriceDriftLine { itemId: string; /** What the cart holds for the line (a price per unit, plain decimal). */ from: string; /** What the shop charges now. */ to: string; } const DECIMAL = /^\d{1,12}(\.\d{1,6})?$/; const MAX_LINES = 50; /** * The lines of a `PRICE_DRIFT` refusal, or `null` when `err` is anything else. A refusal whose * lines cannot be read still answers `[]` (it IS a price change): the page then says so without a * list, and the shopper can still accept the new prices. */ export function parsePriceDrift(err: unknown): PriceDriftLine[] | null { if (getErrorCode(err) !== 'PRICE_DRIFT') return null; const items = (err as { details?: { details?: { items?: unknown } } } | null)?.details?.details ?.items; if (!Array.isArray(items)) return []; const lines: PriceDriftLine[] = []; for (const entry of items.slice(0, MAX_LINES)) { if (typeof entry !== 'object' || entry === null) continue; const row = entry as Record; const itemId = row.itemId; const from = row.oldUnitPrice; const to = row.newUnitPrice; if ( typeof itemId !== 'string' || itemId.length === 0 || itemId.length > 64 || typeof from !== 'string' || typeof to !== 'string' || !DECIMAL.test(from) || !DECIMAL.test(to) ) { continue; } lines.push({ itemId, from, to }); } return lines; } /** The part of a cart line the agreement check needs (what `getCart` and `refreshCartSnapshots` return). */ export interface PricedCartLine { id: string; /** What the cart holds for the line. */ unitPrice: string; /** What the shop charges now. */ currentUnitPrice: string; priceChanged?: boolean; } const samePrice = (a: string, b: string): boolean => Math.abs(Number(a) - Number(b)) < 1e-6; const above = (a: string, b: string): boolean => Number(a) - Number(b) > 1e-6; /** * What the shopper agreed to is a CEILING per line: the price the cart ends up holding must not be * higher than the price they were shown. The server enforces the same rule when the page sends the * prices (`refreshCartSnapshots(cartId, { expectedItems })`, `409 PRICES_CHANGED`); this copy is the * check the page runs itself, so a server that does not know the rule yet is never trusted with a price * the shopper did not see. * * - A line the shopper agreed to ends at that price or LOWER (100 against an agreement to 80 is refused, * 101 against an agreement to 102 passes: they pay less). * - A line whose price moved and that was NOT shown is refused, even when it got cheaper. * - A line that did not move and was not shown is left alone and never asked about. * * `shown` is what the screen listed (`parsePriceDrift`). `lines` is every line that moved or is now * above its agreement, as `from -> to` (for a line above its agreement `from` is the price they agreed * to), and it always lists ALL of them: a list that held only the line that moved again would swap * between two lines on every click. */ export function judgeAgreement( shown: PriceDriftLine[], items: PricedCartLine[] ): { breaks: boolean; lines: PriceDriftLine[] } { const agreed = new Map(shown.map((line) => [line.itemId, line.to])); let breaks = false; const lines: PriceDriftLine[] = []; for (const item of items) { const moved = !samePrice(item.currentUnitPrice, item.unitPrice); const price = agreed.get(item.id); const broken = price === undefined ? moved : above(item.currentUnitPrice, price); if (!moved && !broken) continue; if (broken) breaks = true; lines.push({ itemId: item.id, from: broken && price !== undefined ? price : item.unitPrice, to: item.currentUnitPrice, }); } return { breaks, lines }; } /** * After the prices were taken: every line of the cart now holding a price above its ceiling, which is * the agreed price or, for a line that was not shown, the price it held `before` the take (a line that * moved in the gap, shown or not). A line that appeared in between has no ceiling and is ignored. */ export function judgeTaken( before: PricedCartLine[], after: PricedCartLine[], shown: PriceDriftLine[] ): { breaks: boolean; lines: PriceDriftLine[] } { const agreed = new Map(shown.map((line) => [line.itemId, line.to])); const was = new Map(before.map((item) => [item.id, item.unitPrice])); let breaks = false; const lines: PriceDriftLine[] = []; for (const item of after) { const prior = was.get(item.id); if (prior === undefined) continue; const limit = agreed.get(item.id) ?? prior; const broken = above(item.unitPrice, limit); const moved = !samePrice(item.unitPrice, prior); if (!moved && !broken) continue; if (broken) breaks = true; lines.push({ itemId: item.id, from: broken ? limit : prior, to: item.unitPrice }); } return { breaks, lines }; } /** * The lines of a `409 PRICES_CHANGED` refusal (the server saw the prices the shopper agreed to and one * is above them; NOTHING was changed in the cart), as `from -> to`, or `null` when `err` is anything * else. Same lines the page shows again, so the shopper answers about what the server found. */ export function parsePricesChanged(err: unknown): PriceDriftLine[] | null { if (getErrorCode(err) !== 'PRICES_CHANGED') return null; const items = (err as { details?: { details?: { items?: unknown } } } | null)?.details?.details ?.items; if (!Array.isArray(items)) return []; const lines: PriceDriftLine[] = []; for (const entry of items.slice(0, MAX_LINES)) { if (typeof entry !== 'object' || entry === null) continue; const row = entry as Record; const itemId = row.itemId; const approved = row.approvedUnitPrice; const from = row.reason === 'ABOVE_APPROVED' && typeof approved === 'string' ? approved : row.oldUnitPrice; const to = row.newUnitPrice; if ( typeof itemId !== 'string' || itemId.length === 0 || itemId.length > 64 || typeof from !== 'string' || typeof to !== 'string' || !DECIMAL.test(from) || !DECIMAL.test(to) ) { continue; } lines.push({ itemId, from, to }); } return lines; } /** * What `refreshCartSnapshots` is called through. `options` is the SDK's `expectedItems` (3.26): an * older SDK ignores the second argument (the checks above still run), so the starter does not need a * newer SDK than the one it pins. */ export interface PriceTakingClient { refreshCartSnapshots( cartId: string, options?: { expectedItems: Array<{ itemId: string; unitPrice: string }> } ): Promise<{ items?: PricedCartLine[] }>; } /** Take the prices the shopper was shown: the server refuses (`409 PRICES_CHANGED`) if one is above them. */ export function takeAgreedPrices( client: PriceTakingClient, cartId: string, shown: PriceDriftLine[] ): Promise<{ items?: PricedCartLine[] }> { return client.refreshCartSnapshots( cartId, shown.length > 0 ? { expectedItems: shown.map((line) => ({ itemId: line.itemId, unitPrice: line.to })) } : undefined ); }