@aglyn/plugins-commerce 1.21.0 → 1.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/package.json +16 -16
  2. package/src/lib/components/cart-fulfillment.js +19 -8
  3. package/src/lib/components/cart-fulfillment.js.map +1 -1
  4. package/src/lib/components/console/catalog-organization-card.component.js +28 -9
  5. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  6. package/src/lib/components/console/discounts-card.component.js +13 -4
  7. package/src/lib/components/console/discounts-card.component.js.map +1 -1
  8. package/src/lib/components/console/local-delivery-settings-card.component.js +13 -4
  9. package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
  10. package/src/lib/components/console/product-editor-dialog.component.js +13 -4
  11. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  12. package/src/lib/components/console/products-hub-card.component.js +13 -4
  13. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  14. package/src/lib/components/console/quote-settings-card.component.js +13 -4
  15. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  16. package/src/lib/components/console/reservations-card.component.js +13 -4
  17. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  18. package/src/lib/components/console/return-settings-card.component.js +13 -4
  19. package/src/lib/components/console/return-settings-card.component.js.map +1 -1
  20. package/src/lib/components/console/shipping-settings-card.component.js +13 -4
  21. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  22. package/src/lib/components/console/store-settings-card.component.js +13 -4
  23. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  24. package/src/lib/components/console/suppliers-card.component.js +13 -4
  25. package/src/lib/components/console/suppliers-card.component.js.map +1 -1
  26. package/src/lib/components/console/tax-settings-card.component.js +13 -4
  27. package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
  28. package/src/lib/model/commerce-pos-offline.d.ts +21 -3
  29. package/src/lib/model/commerce-pos-offline.js +17 -5
  30. package/src/lib/model/commerce-pos-offline.js.map +1 -1
  31. package/src/lib/server/pos-offline-card-order.d.ts +2 -0
  32. package/src/lib/server/pos-offline-card-order.js +6 -2
  33. package/src/lib/server/pos-offline-card-order.js.map +1 -1
  34. package/src/lib/server/pos-offline-card-reconcile.d.ts +5 -1
  35. package/src/lib/server/pos-offline-card-reconcile.js +42 -10
  36. package/src/lib/server/pos-offline-card-reconcile.js.map +1 -1
  37. package/src/lib/server/pos-offline-sync.d.ts +48 -6
  38. package/src/lib/server/pos-offline-sync.js +142 -31
  39. package/src/lib/server/pos-offline-sync.js.map +1 -1
  40. package/src/lib/server/pos-stripe.d.ts +11 -0
  41. package/src/lib/server/pos-stripe.js +14 -0
  42. package/src/lib/server/pos-stripe.js.map +1 -1
  43. package/src/lib/server/pos-terminal.d.ts +21 -1
  44. package/src/lib/server/pos-terminal.js +39 -5
  45. package/src/lib/server/pos-terminal.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-sync.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport * as CommerceModel from '../model'\nimport {\n posOfflineFlagLabels,\n posOfflineSaleTotals,\n posOfflineSoldAt,\n posOfflineTotalsAddUp,\n POS_OFFLINE_CARD_INTENT_KIND,\n POS_OFFLINE_LATE_SYNC_MS,\n POS_OFFLINE_SYNC_BATCH_MAX,\n sanitizePosOfflineSale,\n type PosOfflineFlag,\n type PosOfflineKit,\n type PosOfflineKitCard,\n type PosOfflineOrderStamp,\n type PosOfflineRefusal,\n type PosOfflineSale,\n type PosOfflineSaleOutcome,\n type PosOfflineStockConflict,\n} from '../model/commerce-pos-offline'\nimport { ORDER_PAID_EVENT } from '../model/order-events'\nimport { holdsPosPermission } from '../model/plugin-permissions'\nimport { posMaxDiscountPct, posOfflineCardSettings } from '../plugin-config'\nimport { alertLowStockCrossing } from './low-stock'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { raiseOrderEvent } from './order-events'\nimport { offlineFeeMonthKey } from './pos-fee-month'\nimport {\n authorizePosOps,\n defaultPosOpsDeps,\n posOpsBody,\n posOpsCleanId,\n resolvePosStaffAssertion,\n type PosOpsDeps,\n type PosOpsStaff,\n} from './pos-ops-gate'\nimport { posOfflineCardChargeRef, reportPosOfflineCardWrongAccount } from './pos-offline-card-reconcile'\nimport { posHardwareSaleFields } from './pos-hardware-sale-fields'\nimport { posOfflineCardOrderMoney, type PosOfflineCardSettled } from './pos-offline-card-order'\nimport { notifyPosSaleCompleted } from './pos-sale'\nimport { POS_CURRENCY, posCardApplicationFeeCents, posTerminalAvailable } from './pos-stripe'\nimport {\n capturePosOfflineCardIntent,\n ensurePosOfflineCardConfiguration,\n posMerchantAccount,\n type PosMerchant,\n posTerminalLocationId,\n retrievePosOfflineCardIntent,\n type PosOfflineCardIntent,\n} from './pos-terminal'\nimport { decrementVariantStock, type StockDecrementOutcome } from './reserve-stock'\n\n/*==========================================\n * THE OFFLINE REGISTER'S SYNC (AGL-3625): `/api/commerce/pos-offline-sync`.\n *\n * GET ?hostId= the offline kit: the store's in-person tax rate, the\n * discount ceiling, the shift rule, the registers and their\n * open shifts, and the receipt's head and foot\n * POST {hostId, sales[]} records each sale rung offline, once: cash,\n * and a card the Aglyn POS app's own reader stored and\n * Stripe has since been sent (AGL-4039), which this\n * captures with the platform fee\n *\n * The register's gate, unchanged (`authorizePosOps`): admin or editor on the\n * site, `managePos`, and the plan's `pos` entitlement — re-read at sync, so a\n * workspace that lost POS cannot sync into it. The plugin dispatcher has\n * already applied the security lockdown before this runs.\n *\n * ONE SALE, ONE ORDER, ONCE. The register's sale key is the order's id and\n * the id of a server-only record beside it (`posOfflineSales/{key}`), both\n * CREATED in one transaction. A sale sent twice — a connection that flapped\n * mid-request, a retry after an answer that never arrived — finds the record\n * and gets the first answer back, and a key that collides with any existing\n * order cannot overwrite it: `create` refuses.\n *\n * NEVER DROPPED. The customer has paid and left. So nothing the server finds\n * at sync refuses the sale: a changed price, short stock, a closed shift, a\n * register over the cap are each FLAGGED — on the order, its timeline and the\n * answer — and the sale is recorded as it happened. The only refusals are the\n * ones that protect somebody else: a sale signed for another member, another\n * site or another workspace stays on the device that rang it.\n *\n * STEPS AFTER THE COMMIT are recorded on the sync record as they finish, so a\n * request that dies between them is finished by the next sync of the same\n * sale rather than skipped (stock) or repeated (the receipt email).\n *=========================================*/\n\n/** The register's sync record: no customer data, only what dedupe and resume need. */\nexport interface PosOfflineSyncRecord {\n saleKey: string\n orderId: string\n number: number | null\n signedInUid: string\n registerId: string\n soldAtMs: number\n syncedAtMs: number\n status: 'recorded' | 'settled'\n flags: PosOfflineFlag[]\n stockConflicts: PosOfflineStockConflict[]\n /** Line indexes whose stock has been taken. */\n stockLines: number[]\n stockDone: boolean\n notified: boolean\n /** A card taken offline that was declined or never charged: no receipt and no \"paid\" for it. */\n unpaid?: boolean\n}\n\nexport interface PosOfflineAfterSale {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n email: string\n name: string\n}\n\nexport interface PosOfflineSyncDeps extends PosOpsDeps {\n /** The plan's take rate for one product type (AGL-2111). */\n feePct(org: Record<string, any> | null, productType: 'physical' | 'digital' | 'service'): number\n /** Whether the register at this creation rank is within the site's cap (AGL-1775). */\n registerWithinCap(org: Record<string, any> | null, hostId: string, rank: number): boolean\n /** Takes one line's units off the shelf, with its ledger row (AGL-2320). */\n decrementStock(input: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n productId: string\n variantId: string\n quantity: number\n locationId?: string\n orderId: string\n }): Promise<StockDecrementOutcome>\n /** What a completed sale tells the rest of the workspace. Never throws. */\n afterSale(input: PosOfflineAfterSale): Promise<void>\n /** Cards taken offline on the app's own reader (AGL-4039); absent, the server takes none. */\n card?: PosOfflineCardDeps\n}\n\n/** The Stripe side of a card taken offline on the app's own reader. */\nexport interface PosOfflineCardDeps {\n /** Whether Terminal readers are offered at all, and the site's Location once one exists. */\n terminal(hostId: string): Promise<{ available: boolean; locationId: string | null }>\n /** The merchant's connected account and how it sells, when it can take card payments. */\n merchantAccount(hostId: string, org: Record<string, any> | null): Promise<PosMerchant | null>\n /** Turns Stripe's offline mode on for the site's readers; false when Stripe refused. */\n enableOffline(hostId: string): Promise<boolean>\n retrieve(paymentIntentId: string): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string }>\n /**\n * Captures with the platform fee. A failure carries Stripe's HTTP status\n * when Stripe answered; a request that never got an answer throws.\n */\n capture(\n paymentIntentId: string,\n applicationFeeCents: number,\n idempotencyKey: string,\n ): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string; status?: number }>\n /** Tells the operator a card was made out to another account. Never throws. */\n wrongAccount(input: {\n hostId: string\n orderId: string\n paymentIntentId: string\n status: string\n amountCents: number\n destination: string\n expected: string\n }): Promise<void>\n}\n\nexport function defaultPosOfflineCardDeps(): PosOfflineCardDeps {\n return {\n terminal: async (hostId) => ({\n available: posTerminalAvailable(),\n locationId: posTerminalAvailable() ? await posTerminalLocationId(hostId) : null,\n }),\n merchantAccount: posMerchantAccount,\n enableOffline: ensurePosOfflineCardConfiguration,\n retrieve: retrievePosOfflineCardIntent,\n capture: capturePosOfflineCardIntent,\n wrongAccount: reportPosOfflineCardWrongAccount,\n }\n}\n\nexport function defaultPosOfflineSyncDeps(): PosOfflineSyncDeps {\n const base = defaultPosOpsDeps()\n return {\n ...base,\n feePct: (org, productType) => Aglyn.resolveTransactionFeePct(org as any, productType),\n registerWithinCap: (org, hostId, rank) =>\n Aglyn.checkHostRegisterQuota(org as any, hostId, rank).allowed,\n decrementStock: async (input) => {\n const moved = await decrementVariantStock({\n firestore: base.firestore(),\n hostRef: input.hostRef,\n hostId: input.hostId,\n productId: input.productId,\n variantId: input.variantId,\n quantity: input.quantity,\n ...(input.locationId ? { locationId: input.locationId } : {}),\n ledger: { reason: 'sale', orderId: input.orderId },\n })\n if (moved.before && moved.after) alertLowStockCrossing(input.hostId, moved.before, moved.after)\n return moved\n },\n afterSale: async (input) => {\n const settle = async (label: string, work: () => Promise<unknown>) => {\n try {\n await work()\n } catch (error) {\n console.error(`[pos-offline-sync] ${label} failed`, input.orderId, error)\n }\n }\n if (input.email) {\n await settle('contact', () =>\n recordCapturedContact({\n orgId: '',\n hostId: input.hostId,\n identity: { email: input.email, ...(input.name ? { name: input.name } : {}) },\n surface: 'relationship',\n lifecycleFloor: 'customer',\n purchaseCents: Number(input.order.totals?.totalCents ?? 0),\n interaction: {\n source: 'order',\n refId: input.orderId,\n summary: `In-store purchase ($${(Number(input.order.totals?.totalCents ?? 0) / 100).toFixed(2)})`,\n },\n }),\n )\n }\n // The sale-completed listeners hear it too, told it was rung offline:\n // the cloud printers must not print a receipt or pop the drawer for a\n // sale the customer walked away with hours ago.\n await settle('sale completed', () =>\n notifyPosSaleCompleted({ hostId: input.hostId, orderId: input.orderId, order: input.order, offline: true }),\n )\n // The emailed receipt sends now, on sync (the printed one went offline).\n await settle('receipt', () =>\n notifyOrderBuyer({ hostId: input.hostId, orderId: input.orderId }, 'receipt', { email: input.email }),\n )\n await settle('paid event', () =>\n raiseOrderEvent(ORDER_PAID_EVENT, { hostId: input.hostId, orderId: input.orderId, key: 'paid' }),\n )\n },\n card: defaultPosOfflineCardDeps(),\n }\n}\n\ntype Outcome = { status: number; body: Record<string, unknown> }\n\nconst money = (cents: number) => `$${(Math.max(0, cents) / 100).toFixed(2)}`\n\n/** The store's in-person tax, as every register sale computes it. */\nexport function posInPersonTax(\n settings: CommerceModel.TaxSettings | undefined,\n):\n | { ok: true; pct: number | null; pricesIncludeTax: boolean; decision: CommerceModel.StorefrontTaxDecision }\n | { ok: false; reason: string } {\n const taxSettings = (settings ?? {}) as CommerceModel.TaxSettings\n const decision = CommerceModel.storefrontTaxDecision({ settings: taxSettings })\n if (decision.kind === 'undecided') {\n return { ok: false, reason: CommerceModel.STOREFRONT_TAX_UNDECIDED_MESSAGE }\n }\n const misconfigured = CommerceModel.storefrontTaxMisconfiguration(taxSettings, { inPerson: true })\n if (misconfigured) return { ok: false, reason: misconfigured }\n const rate =\n decision.kind === 'manual' ? CommerceModel.resolveTaxRate(taxSettings, taxSettings.origin ?? {}) : null\n return {\n ok: true,\n pct: rate && rate.pct > 0 ? rate.pct : null,\n pricesIncludeTax: taxSettings.pricesIncludeTax === true,\n decision,\n }\n}\n\ninterface SyncContext {\n deps: PosOfflineSyncDeps\n staff: PosOpsStaff\n config: Record<string, unknown>\n tax: ReturnType<typeof posInPersonTax>\n /** Registers by id, with their creation rank. */\n registers: Map<string, { rank: number; data: Record<string, any> }>\n}\n\nasync function readRegisters(staff: PosOpsStaff): Promise<SyncContext['registers']> {\n const docs = (await staff.hostRef.collection('registers').get()).docs\n .map((doc) => ({\n id: doc.id,\n data: (doc.data() ?? {}) as Record<string, any>,\n createdAtMs: Number(doc.get('createdAt')?.toMillis?.() ?? doc.get('createdAtMs') ?? 0),\n }))\n .sort((a, b) => a.createdAtMs - b.createdAtMs || a.id.localeCompare(b.id))\n return new Map(docs.map((doc, rank) => [doc.id, { rank, data: doc.data }]))\n}\n\nasync function readStoreTax(staff: PosOpsStaff): Promise<CommerceModel.TaxSettings | undefined> {\n const store = await staff.hostRef.collection('settings').doc('store').get()\n return (store.get('tax') ?? undefined) as CommerceModel.TaxSettings | undefined\n}\n\n/** The kit a register caches to sell offline. */\nexport async function buildPosOfflineKit(\n deps: PosOfflineSyncDeps,\n staff: PosOpsStaff,\n): Promise<PosOfflineKit> {\n const [registers, taxSettings, config, host, store] = await Promise.all([\n readRegisters(staff),\n readStoreTax(staff),\n staff.orgId ? deps.pluginConfig(staff.orgId, staff.hostId).catch(() => ({})) : Promise.resolve({}),\n staff.hostRef.get(),\n staff.hostRef.collection('settings').doc('store').get(),\n ])\n const tax = posInPersonTax(taxSettings)\n const card = await buildPosOfflineKitCard(deps, staff, config)\n return {\n v: 1,\n hostId: staff.hostId,\n orgId: staff.orgId,\n issuedAtMs: deps.now(),\n available: tax.ok,\n ...('reason' in tax ? { unavailableReason: tax.reason } : {}),\n tax: 'decision' in tax ? { pct: tax.pct, pricesIncludeTax: tax.pricesIncludeTax } : { pct: null, pricesIncludeTax: false },\n maxDiscountPct: posMaxDiscountPct(config),\n requireOpenShift: staff.settings.requireOpenShift,\n registers: [...registers.entries()]\n .filter(([, register]) => deps.registerWithinCap(staff.org, staff.hostId, register.rank))\n .map(([id, register]) => ({\n id,\n name: String(register.data['name'] ?? 'Register').slice(0, 120),\n ...(register.data['locationId'] ? { locationId: String(register.data['locationId']) } : {}),\n openShiftId: posOpsCleanId(register.data['openShiftId']) || null,\n })),\n ...(card ? { card } : {}),\n receipt: {\n name: String(host.get('displayName') ?? '') || 'Receipt',\n ...(typeof host.get('logoUrl') === 'string' && host.get('logoUrl') ? { logo: String(host.get('logoUrl')) } : {}),\n ...(staff.settings.receiptAddress ? { address: staff.settings.receiptAddress } : {}),\n ...(store.get('receiptFooter') ? { footer: String(store.get('receiptFooter')).slice(0, 500) } : {}),\n ...(staff.settings.returnPolicy ? { returnPolicy: staff.settings.returnPolicy } : {}),\n },\n }\n}\n\n/**\n * What the app needs to take a card offline on its own reader (AGL-4039), or\n * why it cannot. Absent where this server takes no offline cards.\n */\nasync function buildPosOfflineKitCard(\n deps: PosOfflineSyncDeps,\n staff: PosOpsStaff,\n config: Record<string, unknown>,\n): Promise<PosOfflineKitCard | undefined> {\n if (!deps.card) return undefined\n const settings = posOfflineCardSettings(config)\n const base = {\n destination: '',\n currency: POS_CURRENCY,\n maxSaleCents: settings.maxSaleCents,\n maxDeviceDailyCents: settings.maxDeviceDailyCents,\n }\n const off = (unavailableReason: string): PosOfflineKitCard => ({ ...base, available: false, unavailableReason })\n if (!settings.enabled) return off('Card sales offline are not turned on in this store’s point of sale settings.')\n const terminal = await deps.card.terminal(staff.hostId)\n if (!terminal.available) return off('Card readers are not set up for this store yet.')\n if (!terminal.locationId) return off('Connect a card reader once while online, then cards keep working offline.')\n const merchant = await deps.card.merchantAccount(staff.hostId, staff.org)\n if (!merchant) return off('Finish connecting Stripe to take cards.')\n // The app makes an offline card's intent itself, as a DESTINATION charge\n // to `destination`. A store selling on its own Stripe account needs the\n // intent made on that account with no transfer at all, which the app does\n // not do yet: offline cards stay off there rather than fail at the counter.\n if (merchant.chargeModel === 'direct') {\n return off('Card sales offline are not available for this store’s payment account yet. Take cards while online.')\n }\n const destination = merchant.accountId\n if (!(await deps.card.enableOffline(staff.hostId))) {\n return off('Card sales offline could not be turned on for this store’s readers yet. Try again later.')\n }\n return { ...base, destination, available: true }\n}\n\n/** A card made out to a Stripe account that is not the store's. */\ninterface OfflineCardWrongAccount {\n destination: string\n expected: string\n status: string\n amountCents: number\n}\n\n/** What became of a card taken offline, as the sync settles it. */\ntype OfflineCardSettlement =\n | (PosOfflineCardSettled & { wrongAccount?: OfflineCardWrongAccount })\n | { kind: 'wait'; outcome: PosOfflineSaleOutcome }\n\n/** Statuses in which an intent holds the customer's money or has taken it. */\nconst INTENT_HOLDS_MONEY: ReadonlySet<string> = new Set(['requires_capture', 'processing', 'succeeded'])\n\n/**\n * How long after a capture that Stripe answered with a 5xx the sync waits\n * before reading \"still waiting for capture\" as the definite answer.\n */\nexport const POS_OFFLINE_CAPTURE_SETTLE_MS = 60_000\n\n/**\n * The capture's idempotency key (AGL-4039). Attempt 0 is the key every\n * capture used before attempts existed, so a retry of one already in flight\n * still finds it.\n *\n * WHY AN ATTEMPT. Stripe keeps the answer to an idempotent request for a day,\n * failures included, so a capture that failed once on a per-sale key would\n * fail the same way on every sync for a day, deep into the two days the\n * authorization lasts. The attempt moves on only when the previous one\n * DEFINITELY did not capture: Stripe refused it with a 4xx (not 409, a\n * request with the same key still running, and not 429, rate limited), or it\n * answered 5xx and the intent still waits for capture a minute later. A\n * request that got no answer at all throws before anything is recorded, so it\n * retries on the same key. Every sync reads the intent before it captures,\n * and Stripe captures an intent once, so a new key can never capture twice.\n */\nexport function posOfflineCaptureKey(hostId: string, saleKey: string, attempt: number): string {\n const base = `pos-offline-capture:${hostId}:${saleKey}`\n return attempt > 0 ? `${base}:${attempt}` : base\n}\n\n/** A capture Stripe refused for good: retrying the same key would replay the refusal. */\nexport function posOfflineCaptureRefused(status: number | undefined): boolean {\n return typeof status === 'number' && status >= 400 && status < 500 && status !== 409 && status !== 429\n}\n\n/**\n * Reads the card of a sale rung offline and settles it: captured with the\n * platform fee (the card tender's share of the take, by the one tender rule,\n * plus Stripe's processing cost, exactly as an online reader payment), or\n * unpaid when the bank declined it, Stripe never took it, or it was made out\n * to a Stripe account that is not the store's. Anything Stripe has not\n * finished yet waits on the register for the next sync.\n */\nasync function settleOfflineCard(\n context: SyncContext,\n sale: PosOfflineSale,\n takeFee: number,\n): Promise<OfflineCardSettlement> {\n const { deps, staff } = context\n const { saleKey } = sale\n const card = sale.card!\n const wait = (error: string): OfflineCardSettlement => ({ kind: 'wait', outcome: refused(saleKey, 'failed', error, true) })\n if (card.forward === 'stored') return wait('The card is still on this register. It syncs once Stripe has it.')\n if (!deps.card) return wait('Card sales taken offline cannot sync to this store yet.')\n const details = { ...(card.brand ? { brand: card.brand } : {}), ...(card.last4 ? { last4: card.last4 } : {}) }\n if (!card.paymentIntentId) {\n return {\n kind: 'unpaid',\n flag: card.forward === 'declined' ? 'card-declined' : 'card-not-charged',\n message: card.declineMessage || 'Stripe did not take the card.',\n ...details,\n }\n }\n const read = await deps.card.retrieve(card.paymentIntentId)\n if ('error' in read) return wait(`The card payment could not be checked yet: ${read.error}`)\n let intent = read.intent\n // The amount is NOT checked here: what Stripe took is what the customer\n // paid, and a difference from the server's total is flagged on the order\n // (`posOfflineCardOrderMoney`), never a reason to leave the sale unrecorded.\n if (\n intent.metadata['kind'] !== POS_OFFLINE_CARD_INTENT_KIND ||\n intent.metadata['saleKey'] !== saleKey ||\n intent.metadata['hostId'] !== staff.hostId ||\n intent.currency !== POS_CURRENCY\n ) {\n return { kind: 'wait', outcome: refused(saleKey, 'invalid', 'The card payment does not belong to this sale.', false) }\n }\n const found = { ...details, ...(intent.brand ? { brand: intent.brand } : {}), ...(intent.last4 ? { last4: intent.last4 } : {}) }\n // THE DESTINATION. The device made this intent out to the account its\n // offline kit named, and a kit can be stale (the store reconnected Stripe)\n // or a register tampered with. Money that holds or has moved is only ever\n // captured into, or recorded as paid to, the store's account as it is now.\n if (INTENT_HOLDS_MONEY.has(intent.status)) {\n const merchant = await deps.card.merchantAccount(staff.hostId, staff.org)\n // A direct-charge store is offered no offline kit, so an intent the app\n // made out to a destination is never its account's money: it reads as\n // made out elsewhere, like a kit gone stale.\n const expected = merchant?.accountId ?? null\n if (!expected) {\n return wait('This store’s Stripe account cannot take card payments right now. The card syncs once it can.')\n }\n if (merchant?.chargeModel === 'direct' || intent.destination !== expected) {\n return {\n kind: 'unpaid',\n flag: 'card-not-charged',\n intentId: intent.id,\n message: 'The card was made out to a Stripe account that is not this store’s, so it was not charged here.',\n ...found,\n wrongAccount: { destination: intent.destination, expected, status: intent.status, amountCents: intent.amount },\n }\n }\n }\n const takeShareCents = CommerceModel.posTenderTakeCents('card_present', takeFee)\n const expectedFeeCents = posCardApplicationFeeCents({ takeShareCents, chargeCents: intent.amount })\n if (intent.status === 'requires_capture') {\n const chargeRef = posOfflineCardChargeRef(staff.hostRef, saleKey)\n const charge = ((await chargeRef.get()).data() ?? {}) as Record<string, unknown>\n let attempt = Math.max(0, Math.round(Number(charge['captureAttempt'] ?? 0)) || 0)\n if (\n charge['captureUncertainAttempt'] === attempt &&\n deps.now() - Number(charge['captureUncertainAtMs'] ?? 0) >= POS_OFFLINE_CAPTURE_SETTLE_MS\n ) {\n // The 5xx left the outcome unknown; the intent still waiting for\n // capture a minute later says it did not capture.\n attempt += 1\n await chargeRef.set(\n {\n captureAttempt: attempt,\n captureUncertainAttempt: FieldValue.delete(),\n captureUncertainAtMs: FieldValue.delete(),\n },\n { merge: true },\n )\n }\n const captured = await deps.card.capture(intent.id, expectedFeeCents, posOfflineCaptureKey(staff.hostId, saleKey, attempt))\n if ('error' in captured) {\n const stamp = { hostId: staff.hostId, saleKey, updatedAtMs: deps.now() }\n if (posOfflineCaptureRefused(captured.status)) {\n await chargeRef.set(\n {\n ...stamp,\n captureAttempt: attempt + 1,\n lastCaptureStatus: captured.status,\n lastCaptureError: captured.error.slice(0, 300),\n },\n { merge: true },\n )\n } else if (typeof captured.status === 'number' && captured.status >= 500) {\n await chargeRef.set(\n { ...stamp, captureUncertainAttempt: attempt, captureUncertainAtMs: deps.now() },\n { merge: true },\n )\n }\n return wait(`The card payment could not be captured yet: ${captured.error}`)\n }\n intent = captured.intent\n }\n if (intent.status === 'succeeded') {\n return {\n kind: 'captured',\n intentId: intent.id,\n amountCents: intent.amount,\n feeCents: intent.applicationFeeCents,\n expectedFeeCents,\n takeShareCents,\n livemode: intent.livemode,\n ...found,\n }\n }\n if (intent.status === 'requires_payment_method' || intent.status === 'canceled') {\n return {\n kind: 'unpaid',\n flag: 'card-declined',\n intentId: intent.id,\n message: intent.failureMessage || card.declineMessage || 'The card was declined.',\n ...found,\n }\n }\n return wait('The card payment is still processing. It syncs when Stripe finishes.')\n}\n\nconst refused = (\n saleKey: string,\n reason: PosOfflineRefusal,\n error: string,\n retry: boolean,\n): PosOfflineSaleOutcome => ({ saleKey, status: 'refused', reason, error, retry })\n\nconst replayOf = (record: PosOfflineSyncRecord): PosOfflineSaleOutcome => ({\n saleKey: record.saleKey,\n status: 'replayed',\n orderId: record.orderId,\n number: record.number,\n flags: record.flags,\n stockConflicts: record.stockConflicts,\n})\n\n/** The take the plan owes on the goods after the discount (AGL-2111, AGL-2256). */\nfunction takeFeeCents(\n deps: PosOfflineSyncDeps,\n staff: PosOpsStaff,\n lines: CommerceModel.OrderLineItem[],\n totals: CommerceModel.OrderTotals,\n): number {\n let applies = false\n const gross = lines.reduce((sum, line) => {\n const pct = deps.feePct(staff.org, (line.productType ?? 'physical') as 'physical' | 'digital' | 'service')\n if (pct > 0) applies = true\n return sum + Math.round((line.unitAmountCents * line.quantity * pct) / 100)\n }, 0)\n const charged = Math.max(0, totals.itemsCents - totals.discountCents)\n const scaled = totals.itemsCents > 0 ? Math.round((gross * charged) / totals.itemsCents) : 0\n return applies && charged > 0 ? Math.max(1, scaled) : scaled\n}\n\n/**\n * The steps after the commit, each recorded as it finishes. Run by the sync\n * that recorded the sale, and again by any later sync of it that finds them\n * unfinished.\n */\nasync function finishSale(\n context: SyncContext,\n recordRef: FirebaseFirestore.DocumentReference,\n orderRef: FirebaseFirestore.DocumentReference,\n record: PosOfflineSyncRecord,\n): Promise<PosOfflineSyncRecord> {\n const { deps, staff } = context\n const orderSnapshot = await orderRef.get()\n const order = (orderSnapshot.data() ?? {}) as CommerceModel.HostOrder & Record<string, any>\n let current = record\n if (!current.stockDone) {\n const conflicts = [...current.stockConflicts]\n const done = new Set(current.stockLines)\n const lines = (order.lineItems ?? []) as CommerceModel.OrderLineItem[]\n for (const [index, line] of lines.entries()) {\n if (done.has(index)) continue\n const moved = await deps.decrementStock({\n hostRef: staff.hostRef,\n hostId: staff.hostId,\n productId: line.productId,\n variantId: line.variantId ?? 'default',\n quantity: line.quantity,\n ...(order['locationId'] ? { locationId: String(order['locationId']) } : {}),\n orderId: orderRef.id,\n })\n // A failed commit leaves the line for the next sync to take, rather than\n // marking stock taken that never moved.\n if (moved.failed) continue\n // Untracked stock (or a product gone since) moves nothing and is short of nothing.\n const short = moved.before ? moved.applied - moved.requested : 0\n if (short > 0) {\n conflicts.push({\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n name: [line.name, line.variantLabel].filter(Boolean).join(' — '),\n requested: Math.abs(moved.requested),\n applied: Math.abs(moved.applied),\n shortUnits: short,\n })\n }\n done.add(index)\n await recordRef.update({ stockLines: [...done].sort((a, b) => a - b), stockConflicts: conflicts })\n }\n const stockDone = lines.every((_line, index) => done.has(index))\n const flags: PosOfflineFlag[] =\n conflicts.length && !current.flags.includes('stock-short') ? [...current.flags, 'stock-short'] : current.flags\n current = { ...current, stockLines: [...done], stockConflicts: conflicts, stockDone, flags }\n await recordRef.update({ stockDone, flags, stockConflicts: conflicts })\n if (conflicts.length && conflicts.length !== record.stockConflicts.length) {\n const fresh = (await orderRef.get()).data() as CommerceModel.HostOrder\n const stamp = fresh?.offline\n await orderRef.update({\n ...(stamp ? { offline: { ...stamp, flags, stockConflicts: conflicts } } : {}),\n timeline: CommerceModel.appendOrderEvent(\n fresh ?? {},\n 'offline-stock-short',\n conflicts\n .map((conflict) => `${conflict.shortUnits} of ${conflict.requested}× ${conflict.name} not in stock`)\n .join('; ')\n .slice(0, 500),\n deps.now(),\n ),\n })\n }\n if (!stockDone) return current\n }\n if (!current.notified && current.unpaid) {\n // A card that was never paid gets no receipt and no \"paid\": the order\n // waits, flagged, for the merchant to collect it another way.\n current = { ...current, notified: true, status: 'settled' }\n await recordRef.update({ notified: true, status: 'settled' })\n }\n if (!current.notified) {\n const email = String(order.customerEmail ?? '')\n await deps.afterSale({\n hostId: staff.hostId,\n orderId: orderRef.id,\n order: order as CommerceModel.HostOrder,\n email,\n name: String(order.customerName ?? ''),\n })\n current = { ...current, notified: true, status: 'settled' }\n await recordRef.update({ notified: true, status: 'settled' })\n }\n return current\n}\n\nasync function syncOne(context: SyncContext, raw: unknown): Promise<PosOfflineSaleOutcome> {\n const { deps, staff } = context\n const read = sanitizePosOfflineSale(raw)\n const rawKey = String((raw as Record<string, unknown> | null)?.['saleKey'] ?? '').slice(0, 64)\n if ('error' in read) return refused(rawKey, 'invalid', read.error, false)\n const sale = read.sale\n if (sale.hostId !== staff.hostId) {\n return refused(sale.saleKey, 'wrong-site', 'This sale was rung for another site.', false)\n }\n if (sale.signedInUid !== staff.uid) {\n return refused(\n sale.saleKey,\n 'wrong-staff',\n 'This sale was rung while another member was signed in. It syncs when they sign in on this register.',\n true,\n )\n }\n if (sale.orgId && staff.orgId && sale.orgId !== staff.orgId) {\n return refused(sale.saleKey, 'wrong-workspace', 'This sale was rung in another workspace.', false)\n }\n\n const firestore = deps.firestore()\n const hostRef = staff.hostRef\n const recordRef = hostRef.collection('posOfflineSales').doc(sale.saleKey)\n const orderRef = hostRef.collection('orders').doc(sale.saleKey)\n\n const existing = await recordRef.get()\n if (existing.exists) {\n const record = existing.data() as PosOfflineSyncRecord\n if (record.signedInUid !== staff.uid) {\n return refused(sale.saleKey, 'conflict', 'Another sale already used this key.', false)\n }\n return replayOf(record.status === 'settled' ? record : await finishSale(context, recordRef, orderRef, record))\n }\n\n const now = deps.now()\n const flags = new Set<PosOfflineFlag>()\n const soldAt = posOfflineSoldAt(sale.soldAtMs, now)\n if (soldAt.adjusted) flags.add('clock-adjusted')\n else if (now - soldAt.atMs > POS_OFFLINE_LATE_SYNC_MS) flags.add('late-sync')\n\n // The lines as sold, checked against the catalog as it stands now. The\n // price on the order is the one rung — that is what the customer paid —\n // and the catalog's is kept beside it where they differ.\n const productIds = [...new Set(sale.lines.map((line) => line.productId))]\n const snapshots = await Promise.all(productIds.map((id) => hostRef.collection('products').doc(id).get()))\n const products = new Map(\n snapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const priceDrift: NonNullable<PosOfflineOrderStamp['priceDrift']> = []\n const lineItems: CommerceModel.OrderLineItem[] = sale.lines.map((line, index) => {\n const product = products.get(line.productId)\n if (!product) {\n flags.add('unknown-product')\n return {\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n productType: line.productType ?? 'physical',\n quantity: line.quantity,\n unitAmountCents: line.unitAmountCents,\n }\n }\n const variant = product.variants.find((item) => item.id === line.variantId) ?? product.variants[0]\n const chosen = CommerceModel.resolveLineModifiers(product, line.modifiers, variant?.id)\n const currentCents =\n variant && CommerceModel.variantHasPrice(variant) && chosen.ok\n ? Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents\n : null\n if (currentCents !== line.unitAmountCents) {\n flags.add('price-changed')\n priceDrift.push({ index, rungCents: line.unitAmountCents, currentCents: currentCents ?? 0 })\n }\n return {\n productId: line.productId,\n ...(variant && variant.id !== 'default' ? { variantId: variant.id } : {}),\n name: product.name || line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(variant?.sku ? { sku: variant.sku } : line.sku ? { sku: line.sku } : {}),\n productType: product.type ?? line.productType ?? 'physical',\n quantity: line.quantity,\n unitAmountCents: line.unitAmountCents,\n ...(chosen.ok && chosen.modifiers.length ? { modifiers: chosen.modifiers } : {}),\n }\n })\n\n // The money: what the register rang, when its own arithmetic holds; the\n // arithmetic of its lines, with the tax it rang, when it does not.\n let totals: CommerceModel.OrderTotals\n if (posOfflineTotalsAddUp(sale)) {\n totals = CommerceModel.computeOrderTotals(lineItems, {\n discountCents: sale.totals.discountCents,\n taxCents: sale.totals.taxCents,\n })\n } else {\n flags.add('totals-restated')\n const restated = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: null, pricesIncludeTax: false },\n })\n totals = CommerceModel.computeOrderTotals(lineItems, {\n discountCents: restated.discountCents,\n taxCents: Math.min(sale.totals.taxCents, restated.itemsCents - restated.discountCents),\n })\n }\n if ('decision' in context.tax) {\n const expected = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: context.tax.pct, pricesIncludeTax: context.tax.pricesIncludeTax },\n })\n if (expected.taxCents !== totals.taxCents) flags.add('tax-differs')\n } else if (totals.taxCents > 0) {\n flags.add('tax-differs')\n }\n if (sale.discountPct > posMaxDiscountPct(context.config)) flags.add('discount-over-limit')\n // The cashier's own discount needs `posDiscount` (AGL-4047), as the online\n // register refuses it without. Offline the sale has already happened, so it\n // is recorded and flagged rather than dropped. Read for the member who was\n // signed in, whose membership the gate resolved, as the online check reads it.\n if (sale.discountPct > 0 && !holdsPosPermission(staff.membership.permissions, 'posDiscount')) {\n flags.add('discount-not-permitted')\n }\n const byCard = sale.tender === 'card'\n if (!byCard && sale.cashTenderedCents < totals.totalCents) flags.add('cash-short')\n\n // Where it was rung.\n const register = context.registers.get(sale.registerId)\n if (!register) flags.add('unknown-register')\n else if (!deps.registerWithinCap(staff.org, staff.hostId, register.rank)) flags.add('register-over-cap')\n let shiftId = ''\n if (sale.shiftId && register) {\n const shift = await hostRef\n .collection('registers')\n .doc(sale.registerId)\n .collection('shifts')\n .doc(sale.shiftId)\n .get()\n if (shift.exists) {\n shiftId = sale.shiftId\n if (shift.get('status') !== 'open') flags.add('shift-closed')\n }\n }\n if (!shiftId && staff.settings.requireOpenShift) flags.add('no-shift')\n\n // Who rang it: a PIN-switched cashier's assertion is read as of the moment\n // the cash was taken (it was valid then, and expiring since is the normal\n // case for a sale that waited to sync), and the member is re-checked NOW.\n let cashierId = staff.uid\n if (sale.cashierAssertion) {\n const memberUid = await resolvePosStaffAssertion(\n { ...deps, now: () => soldAt.atMs },\n hostRef,\n sale.cashierAssertion,\n { hostId: staff.hostId, registerId: sale.registerId, purpose: 'cashier' },\n )\n if (memberUid) cashierId = memberUid\n else flags.add('cashier-unverified')\n }\n\n // Cash carries no platform fee (AGL-4036): the plan's take is worked out\n // and then settled by the one predicate every tender answers to, so a sale\n // synced from the queue is charged exactly what the same sale rung online\n // is.\n const planTake = takeFeeCents(deps, staff, lineItems, totals)\n // A card taken offline settles with Stripe BEFORE the order is written: a\n // capture that fails leaves the sale on the register for the next sync,\n // and a repeat after a lost answer finds the first capture (AGL-4039).\n const settled = byCard ? await settleOfflineCard(context, sale, planTake) : null\n if (settled?.kind === 'wait') return settled.outcome\n // The card's money, decided once against the server's totals: the fee it\n // settled, the shortfall to invoice, and the order-level intent the refund\n // and the dispute lookup read.\n const cardMoney = settled\n ? posOfflineCardOrderMoney({\n settled,\n totals,\n planTakeCents: planTake,\n soldAtMs: soldAt.atMs,\n nowMs: now,\n cashierId,\n feeOrgId: staff.orgId ?? '',\n })\n : null\n for (const flag of cardMoney?.flags ?? []) flags.add(flag)\n const cashTake = CommerceModel.posTenderTakeCents('cash', planTake)\n totals = cardMoney ? cardMoney.totals : { ...totals, feeCents: cashTake }\n // What accrues to the org's month with the order: the cash take (none\n // since AGL-4036) or the part of a card's fee its payout did not carry.\n const invoiceCents = cardMoney ? cardMoney.invoiceCents : cashTake\n const changeCents = byCard ? 0 : Math.max(0, sale.cashTenderedCents - totals.totalCents)\n const flagList = [...flags]\n const stamp: PosOfflineOrderStamp = {\n saleKey: sale.saleKey,\n soldAtMs: soldAt.atMs,\n syncedAtMs: now,\n syncedBy: staff.uid,\n flags: flagList,\n ...(priceDrift.length ? { priceDrift } : {}),\n }\n const customer = sale.customer ?? {}\n const feeMonth = offlineFeeMonthKey(new Date(now))\n const feeRef = staff.orgId\n ? firestore.collection('orgs').doc(staff.orgId).collection('offlineFees').doc(feeMonth)\n : null\n const counterRef = hostRef.collection('counters').doc('orders')\n\n const committed = await firestore.runTransaction(async (transaction) => {\n const raced = await transaction.get(recordRef)\n if (raced.exists) return { raced: raced.data() as PosOfflineSyncRecord }\n const taken = await transaction.get(orderRef)\n if (taken.exists) return { collision: true as const }\n const counter = await transaction.get(counterRef)\n const number = Number(counter.get('next') ?? 1)\n transaction.set(counterRef, { next: number + 1 }, { merge: true })\n const cardName = settled\n ? [settled.brand ? settled.brand.toUpperCase() : 'Card', settled.last4 ? `•••• ${settled.last4}` : ''].filter(Boolean).join(' ')\n : ''\n const paidDetail = !settled\n ? `Cash — received ${money(sale.cashTenderedCents)}, change ${money(changeCents)}. ` +\n 'Rung while the register was offline.'\n : settled.kind === 'captured'\n ? `${cardName} — ${money(settled.amountCents)}, taken while the register was offline and charged when it reconnected.`\n : `${cardName} — ${money(totals.totalCents)} taken while the register was offline was not paid: ${settled.message}`.slice(0, 500)\n const timeline: CommerceModel.OrderTimelineEvent[] = [\n { atMs: soldAt.atMs, event: settled?.kind === 'unpaid' ? 'payment-failed' : 'paid', detail: paidDetail },\n {\n atMs: now,\n event: 'offline-synced',\n detail: flagList.length\n ? `Synced. Check: ${posOfflineFlagLabels(flagList).join('; ')}`.slice(0, 1000)\n : 'Synced.',\n },\n ]\n transaction.create(\n orderRef,\n CommerceModel.withOrderListFields(orderRef.id, {\n number,\n status: cardMoney ? cardMoney.status : 'paid',\n channel: 'pos',\n registerId: sale.registerId,\n cashierId,\n ...(shiftId ? { shiftId } : {}),\n ...(customer.name ? { customerName: customer.name } : {}),\n ...(customer.kind && customer.id ? { customerRecord: { kind: customer.kind, id: customer.id } } : {}),\n ...(sale.discountPct > 0 ? { discountPct: sale.discountPct, discountBy: cashierId } : {}),\n ...(sale.locationId ? { locationId: sale.locationId } : {}),\n // A card reader sold offline on the platform's own store (AGL-4038):\n // recorded once synced, with nobody attached, for the To attach list.\n ...posHardwareSaleFields({ hostId: staff.hostId, orgId: staff.orgId, lineItems, products }),\n lineItems,\n totals,\n taxMode: 'decision' in context.tax\n ? CommerceModel.storefrontTaxModeForDecision(context.tax.decision, totals.taxCents)\n : totals.taxCents > 0\n ? 'manual'\n : 'none',\n ...(cardMoney ? cardMoney.fields : cashTake > 0 ? { feeCollection: 'invoice' as const } : {}),\n payments: cardMoney\n ? [cardMoney.payment]\n : [\n {\n id: 'pay_cash',\n method: 'cash',\n amountCents: totals.totalCents,\n status: 'succeeded',\n atMs: soldAt.atMs,\n settledAtMs: soldAt.atMs,\n takeFeeCents: cashTake,\n feeCents: 0,\n cashierId,\n cashTenderedCents: sale.cashTenderedCents,\n changeCents,\n } satisfies CommerceModel.OrderPayment,\n ],\n customerEmail: customer.email || null,\n timeline,\n offline: stamp,\n createdAtMs: soldAt.atMs,\n createdAt: FieldValue.serverTimestamp(),\n }),\n )\n const record: PosOfflineSyncRecord = {\n saleKey: sale.saleKey,\n orderId: orderRef.id,\n number,\n signedInUid: staff.uid,\n registerId: sale.registerId,\n soldAtMs: soldAt.atMs,\n syncedAtMs: now,\n status: 'recorded',\n flags: flagList,\n stockConflicts: [],\n stockLines: [],\n stockDone: false,\n notified: false,\n ...(settled?.kind === 'unpaid' ? { unpaid: true } : {}),\n }\n transaction.create(recordRef, record)\n // The intent's record says its sale synced, in the same commit, so the\n // webhook and the unsynced-card sweep never report a sale that landed.\n if (settled?.intentId) {\n transaction.set(\n posOfflineCardChargeRef(hostRef, sale.saleKey),\n {\n hostId: staff.hostId,\n saleKey: sale.saleKey,\n paymentIntentId: settled.intentId,\n registerId: sale.registerId,\n synced: true,\n orderId: orderRef.id,\n syncedAtMs: now,\n updatedAtMs: now,\n alertDueAtMs: FieldValue.delete(),\n },\n { merge: true },\n )\n }\n // The fee no payout carried accrues with the order, in the same\n // transaction (AGL-2111): a card's share was netted from its payout by\n // the capture, and only a shortfall in that lands here.\n if (invoiceCents > 0 && feeRef) {\n transaction.set(\n feeRef,\n { month: feeMonth, feeCents: FieldValue.increment(invoiceCents), orders: FieldValue.increment(1) },\n { merge: true },\n )\n }\n return { record }\n })\n if ('collision' in committed) {\n return refused(sale.saleKey, 'conflict', 'Another order already has this sale’s key.', false)\n }\n if ('raced' in committed) {\n const record = committed.raced\n if (record.signedInUid !== staff.uid) {\n return refused(sale.saleKey, 'conflict', 'Another sale already used this key.', false)\n }\n return replayOf(record)\n }\n if (settled?.kind === 'unpaid' && settled.wrongAccount && settled.intentId) {\n await deps.card!.wrongAccount({\n hostId: staff.hostId,\n orderId: orderRef.id,\n paymentIntentId: settled.intentId,\n ...settled.wrongAccount,\n })\n }\n const finished = await finishSale(context, recordRef, orderRef, committed.record)\n return {\n saleKey: sale.saleKey,\n status: 'recorded',\n orderId: orderRef.id,\n number: finished.number,\n flags: finished.flags,\n stockConflicts: finished.stockConflicts,\n }\n}\n\nexport async function handlePosOfflineSync(\n deps: PosOfflineSyncDeps,\n req: PluginApiRequest,\n): Promise<Outcome> {\n if (req.method !== 'GET' && req.method !== 'POST') {\n return { status: 405, body: { error: 'Method not allowed' } }\n }\n const body =\n req.method === 'GET'\n ? Object.fromEntries(\n Object.entries(req.query ?? {}).map(([key, value]) => [key, Array.isArray(value) ? value[0] : value]),\n )\n : posOpsBody(req)\n const gate = await authorizePosOps(deps, req, body['hostId'], 'posSell')\n if ('error' in gate) return { status: gate.status, body: { error: gate.error } }\n const staff = gate.staff\n if (req.method === 'GET') {\n return { status: 200, body: { kit: await buildPosOfflineKit(deps, staff) } }\n }\n const sales = Array.isArray(body['sales']) ? (body['sales'] as unknown[]) : null\n if (!sales) return { status: 400, body: { error: 'Missing sales' } }\n if (sales.length > POS_OFFLINE_SYNC_BATCH_MAX) {\n return { status: 400, body: { error: `Send at most ${POS_OFFLINE_SYNC_BATCH_MAX} sales at a time` } }\n }\n if (sales.length === 0) return { status: 200, body: { results: [] } }\n const [registers, taxSettings, config] = await Promise.all([\n readRegisters(staff),\n readStoreTax(staff),\n staff.orgId ? deps.pluginConfig(staff.orgId, staff.hostId).catch(() => ({})) : Promise.resolve({}),\n ])\n const context: SyncContext = { deps, staff, config, tax: posInPersonTax(taxSettings), registers }\n const results: PosOfflineSaleOutcome[] = []\n // One at a time, in the order they were rung, so order numbers follow the\n // till and one sale's failure cannot take the rest with it.\n for (const sale of sales) {\n try {\n results.push(await syncOne(context, sale))\n } catch (error) {\n console.error('[pos-offline-sync] sale failed', error)\n const key = String((sale as Record<string, unknown> | null)?.['saleKey'] ?? '').slice(0, 64)\n results.push(refused(key, 'failed', 'The sale could not be synced yet. It stays on this register.', true))\n }\n }\n return { status: 200, body: { results } }\n}\n\nexport function createPosOfflineSyncHandler(\n deps: () => PosOfflineSyncDeps = defaultPosOfflineSyncDeps,\n): PluginApiHandler {\n return async (req, res) => {\n try {\n const outcome = await handlePosOfflineSync(deps(), req)\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n console.error('[pos-offline-sync] failed', error)\n return res.status(500).json({ error: 'The offline sales could not be synced' })\n }\n }\n}\n\nexport const posOfflineSyncHandler = createPosOfflineSyncHandler()\n"],"names":["Aglyn","recordCapturedContact","FieldValue","CommerceModel","posOfflineFlagLabels","posOfflineSaleTotals","posOfflineSoldAt","posOfflineTotalsAddUp","POS_OFFLINE_CARD_INTENT_KIND","POS_OFFLINE_LATE_SYNC_MS","POS_OFFLINE_SYNC_BATCH_MAX","sanitizePosOfflineSale","ORDER_PAID_EVENT","holdsPosPermission","posMaxDiscountPct","posOfflineCardSettings","alertLowStockCrossing","notifyOrderBuyer","raiseOrderEvent","offlineFeeMonthKey","authorizePosOps","defaultPosOpsDeps","posOpsBody","posOpsCleanId","resolvePosStaffAssertion","posOfflineCardChargeRef","reportPosOfflineCardWrongAccount","posHardwareSaleFields","posOfflineCardOrderMoney","notifyPosSaleCompleted","POS_CURRENCY","posCardApplicationFeeCents","posTerminalAvailable","capturePosOfflineCardIntent","ensurePosOfflineCardConfiguration","posMerchantAccount","posTerminalLocationId","retrievePosOfflineCardIntent","decrementVariantStock","defaultPosOfflineCardDeps","terminal","hostId","available","locationId","merchantAccount","enableOffline","retrieve","capture","wrongAccount","defaultPosOfflineSyncDeps","base","feePct","org","productType","resolveTransactionFeePct","registerWithinCap","rank","checkHostRegisterQuota","allowed","decrementStock","input","moved","firestore","hostRef","productId","variantId","quantity","ledger","reason","orderId","before","after","afterSale","settle","label","work","error","console","email","orgId","identity","name","surface","lifecycleFloor","purchaseCents","Number","order","totals","totalCents","interaction","source","refId","summary","toFixed","offline","key","card","money","cents","Math","max","posInPersonTax","settings","taxSettings","decision","storefrontTaxDecision","kind","ok","STOREFRONT_TAX_UNDECIDED_MESSAGE","misconfigured","storefrontTaxMisconfiguration","inPerson","rate","resolveTaxRate","origin","pct","pricesIncludeTax","readRegisters","staff","docs","collection","get","map","doc","id","data","createdAtMs","toMillis","sort","a","b","localeCompare","Map","readStoreTax","store","undefined","buildPosOfflineKit","deps","host","registers","config","Promise","all","pluginConfig","catch","resolve","tax","buildPosOfflineKitCard","v","issuedAtMs","now","unavailableReason","maxDiscountPct","requireOpenShift","entries","filter","register","String","slice","openShiftId","receipt","logo","receiptAddress","address","footer","returnPolicy","destination","currency","maxSaleCents","maxDeviceDailyCents","off","enabled","merchant","chargeModel","accountId","INTENT_HOLDS_MONEY","Set","POS_OFFLINE_CAPTURE_SETTLE_MS","posOfflineCaptureKey","saleKey","attempt","posOfflineCaptureRefused","status","settleOfflineCard","context","sale","takeFee","wait","outcome","refused","forward","details","brand","last4","paymentIntentId","flag","message","declineMessage","read","intent","metadata","found","has","expected","intentId","amountCents","amount","takeShareCents","posTenderTakeCents","expectedFeeCents","chargeCents","charge","chargeRef","round","set","captureAttempt","captureUncertainAttempt","delete","captureUncertainAtMs","merge","captured","stamp","updatedAtMs","lastCaptureStatus","lastCaptureError","feeCents","applicationFeeCents","livemode","failureMessage","retry","replayOf","record","number","flags","stockConflicts","takeFeeCents","lines","applies","gross","reduce","sum","line","unitAmountCents","charged","itemsCents","discountCents","scaled","finishSale","recordRef","orderRef","orderSnapshot","current","stockDone","conflicts","done","stockLines","lineItems","index","failed","short","applied","requested","push","variantLabel","Boolean","join","abs","shortUnits","add","update","every","_line","length","includes","fresh","timeline","appendOrderEvent","conflict","notified","unpaid","customerEmail","customerName","syncOne","raw","rawKey","signedInUid","uid","existing","exists","soldAt","soldAtMs","adjusted","atMs","productIds","snapshots","products","snapshot","liftLegacyProduct","priceDrift","product","sku","variant","variants","find","item","chosen","resolveLineModifiers","modifiers","currentCents","variantHasPrice","priceUsd","extraCents","rungCents","type","computeOrderTotals","taxCents","restated","discountPct","min","membership","permissions","byCard","tender","cashTenderedCents","registerId","shiftId","shift","cashierId","cashierAssertion","memberUid","purpose","planTake","settled","cardMoney","planTakeCents","nowMs","feeOrgId","cashTake","invoiceCents","changeCents","flagList","syncedAtMs","syncedBy","customer","feeMonth","Date","feeRef","counterRef","committed","runTransaction","transaction","counter","raced","taken","collision","next","cardName","toUpperCase","paidDetail","event","detail","create","withOrderListFields","channel","customerRecord","discountBy","taxMode","storefrontTaxModeForDecision","fields","feeCollection","payments","payment","method","settledAtMs","createdAt","serverTimestamp","synced","alertDueAtMs","month","increment","orders","finished","handlePosOfflineSync","req","body","Object","fromEntries","query","value","Array","isArray","gate","kit","sales","results","createPosOfflineSyncHandler","res","json","posOfflineSyncHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAE5C,OAAOC,2BAA2B,sDAAqD;AACvF,SAASC,UAAU,QAAQ,2BAA0B;AACrD,YAAYC,mBAAmB,oBAAU;AACzC,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,gBAAgB,EAChBC,qBAAqB,EACrBC,4BAA4B,EAC5BC,wBAAwB,EACxBC,0BAA0B,EAC1BC,sBAAsB,QASjB,mCAA+B;AACtC,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,kBAAkB,QAAQ,iCAA6B;AAChE,SAASC,iBAAiB,EAAEC,sBAAsB,QAAQ,sBAAkB;AAC5E,SAASC,qBAAqB,QAAQ,iBAAa;AACnD,SAASC,gBAAgB,QAAQ,2BAAuB;AACxD,SAASC,eAAe,QAAQ,oBAAgB;AAChD,SAASC,kBAAkB,QAAQ,qBAAiB;AACpD,SACEC,eAAe,EACfC,iBAAiB,EACjBC,UAAU,EACVC,aAAa,EACbC,wBAAwB,QAGnB,oBAAgB;AACvB,SAASC,uBAAuB,EAAEC,gCAAgC,QAAQ,kCAA8B;AACxG,SAASC,qBAAqB,QAAQ,gCAA4B;AAClE,SAASC,wBAAwB,QAAoC,8BAA0B;AAC/F,SAASC,sBAAsB,QAAQ,gBAAY;AACn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,CAAC,KAAKuN,IAAI,CAAC;gBAAEjU,OAAO;YAAwC;QAC/E;IACF;AACF;AAEA,OAAO,MAAMkU,wBAAwBH,8BAA6B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-sync.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport * as CommerceModel from '../model'\nimport {\n posOfflineFlagLabels,\n posOfflineSaleTotals,\n posOfflineSoldAt,\n posOfflineTotalsAddUp,\n POS_OFFLINE_CARD_INTENT_KIND,\n POS_OFFLINE_LATE_SYNC_MS,\n POS_OFFLINE_SYNC_BATCH_MAX,\n sanitizePosOfflineSale,\n type PosOfflineFlag,\n type PosOfflineKit,\n type PosOfflineKitCard,\n type PosOfflineOrderStamp,\n type PosOfflineRefusal,\n type PosOfflineSale,\n type PosOfflineSaleOutcome,\n type PosOfflineStockConflict,\n} from '../model/commerce-pos-offline'\nimport { ORDER_PAID_EVENT } from '../model/order-events'\nimport { holdsPosPermission } from '../model/plugin-permissions'\nimport { posMaxDiscountPct, posOfflineCardSettings } from '../plugin-config'\nimport { alertLowStockCrossing } from './low-stock'\nimport { notifyOrderBuyer } from './order-notifications'\nimport { raiseOrderEvent } from './order-events'\nimport { offlineFeeMonthKey } from './pos-fee-month'\nimport {\n authorizePosOps,\n defaultPosOpsDeps,\n posOpsBody,\n posOpsCleanId,\n resolvePosStaffAssertion,\n type PosOpsDeps,\n type PosOpsStaff,\n} from './pos-ops-gate'\nimport { posOfflineCardChargeRef, reportPosOfflineCardWrongAccount } from './pos-offline-card-reconcile'\nimport { posHardwareSaleFields } from './pos-hardware-sale-fields'\nimport { posOfflineCardOrderMoney, type PosOfflineCardSettled } from './pos-offline-card-order'\nimport { notifyPosSaleCompleted } from './pos-sale'\nimport { POS_CURRENCY, posOfflineCardFeeCents, posTerminalAvailable } from './pos-stripe'\nimport {\n cancelPosOfflineCardIntent,\n capturePosOfflineCardIntent,\n ensurePosOfflineCardConfiguration,\n posMerchantAccount,\n type PosMerchant,\n posTerminalLocationId,\n retrievePosOfflineCardIntent,\n type PosOfflineCardIntent,\n} from './pos-terminal'\nimport { decrementVariantStock, type StockDecrementOutcome } from './reserve-stock'\n\n/*==========================================\n * THE OFFLINE REGISTER'S SYNC (AGL-3625): `/api/commerce/pos-offline-sync`.\n *\n * GET ?hostId= the offline kit: the store's in-person tax rate, the\n * discount ceiling, the shift rule, the registers and their\n * open shifts, and the receipt's head and foot. An app\n * that can make a card's intent on a store's own Stripe\n * account adds `cardChargeModels=direct` (AGL-4219)\n * POST {hostId, sales[]} records each sale rung offline, once: cash,\n * and a card the Aglyn POS app's own reader stored and\n * Stripe has since been sent (AGL-4039), which this\n * captures with the platform fee\n *\n * The register's gate, unchanged (`authorizePosOps`): admin or editor on the\n * site, `managePos`, and the plan's `pos` entitlement — re-read at sync, so a\n * workspace that lost POS cannot sync into it. The plugin dispatcher has\n * already applied the security lockdown before this runs.\n *\n * ONE SALE, ONE ORDER, ONCE. The register's sale key is the order's id and\n * the id of a server-only record beside it (`posOfflineSales/{key}`), both\n * CREATED in one transaction. A sale sent twice — a connection that flapped\n * mid-request, a retry after an answer that never arrived — finds the record\n * and gets the first answer back, and a key that collides with any existing\n * order cannot overwrite it: `create` refuses.\n *\n * NEVER DROPPED. The customer has paid and left. So nothing the server finds\n * at sync refuses the sale: a changed price, short stock, a closed shift, a\n * register over the cap are each FLAGGED — on the order, its timeline and the\n * answer — and the sale is recorded as it happened. The only refusals are the\n * ones that protect somebody else: a sale signed for another member, another\n * site or another workspace stays on the device that rang it.\n *\n * STEPS AFTER THE COMMIT are recorded on the sync record as they finish, so a\n * request that dies between them is finished by the next sync of the same\n * sale rather than skipped (stock) or repeated (the receipt email).\n *=========================================*/\n\n/** The register's sync record: no customer data, only what dedupe and resume need. */\nexport interface PosOfflineSyncRecord {\n saleKey: string\n orderId: string\n number: number | null\n signedInUid: string\n registerId: string\n soldAtMs: number\n syncedAtMs: number\n status: 'recorded' | 'settled'\n flags: PosOfflineFlag[]\n stockConflicts: PosOfflineStockConflict[]\n /** Line indexes whose stock has been taken. */\n stockLines: number[]\n stockDone: boolean\n notified: boolean\n /** A card taken offline that was declined or never charged: no receipt and no \"paid\" for it. */\n unpaid?: boolean\n /**\n * A card refused as made out to another account whose authorization still\n * holds the customer's money (AGL-4219): the intent to cancel, and where.\n * `account` null is the platform.\n */\n releaseHold?: { paymentIntentId: string; account: string | null }\n /** Whether that cancel went through; absent until it was tried. */\n holdReleased?: boolean\n holdReleaseError?: string\n}\n\nexport interface PosOfflineAfterSale {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n email: string\n name: string\n}\n\nexport interface PosOfflineSyncDeps extends PosOpsDeps {\n /** The plan's take rate for one product type (AGL-2111). */\n feePct(org: Record<string, any> | null, productType: 'physical' | 'digital' | 'service'): number\n /** Whether the register at this creation rank is within the site's cap (AGL-1775). */\n registerWithinCap(org: Record<string, any> | null, hostId: string, rank: number): boolean\n /** Takes one line's units off the shelf, with its ledger row (AGL-2320). */\n decrementStock(input: {\n hostRef: FirebaseFirestore.DocumentReference\n hostId: string\n productId: string\n variantId: string\n quantity: number\n locationId?: string\n orderId: string\n }): Promise<StockDecrementOutcome>\n /** What a completed sale tells the rest of the workspace. Never throws. */\n afterSale(input: PosOfflineAfterSale): Promise<void>\n /** Cards taken offline on the app's own reader (AGL-4039); absent, the server takes none. */\n card?: PosOfflineCardDeps\n}\n\n/** The Stripe side of a card taken offline on the app's own reader. */\nexport interface PosOfflineCardDeps {\n /** Whether Terminal readers are offered at all, and the site's Location once one exists. */\n terminal(hostId: string): Promise<{ available: boolean; locationId: string | null }>\n /** The merchant's connected account and how it sells, when it can take card payments. */\n merchantAccount(hostId: string, org: Record<string, any> | null): Promise<PosMerchant | null>\n /** Turns Stripe's offline mode on for the site's readers; false when Stripe refused. */\n enableOffline(hostId: string): Promise<boolean>\n /**\n * Reads an intent on `account` (a store's own Stripe account, for a direct\n * charge, AGL-4219) or, with null, the platform. A failure carries Stripe's\n * HTTP status when Stripe answered.\n */\n retrieve(\n paymentIntentId: string,\n account: string | null,\n ): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string; status?: number }>\n /**\n * Captures with the platform fee, on `account` or the platform. A failure\n * carries Stripe's HTTP status when Stripe answered; a request that never\n * got an answer throws.\n */\n capture(\n paymentIntentId: string,\n applicationFeeCents: number,\n idempotencyKey: string,\n account: string | null,\n ): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string; status?: number }>\n /**\n * Cancels an authorized intent on `account` (or the platform, null), so the\n * customer's hold is released (AGL-4219). Only ever asked for an intent the\n * sync read as `requires_capture`; Stripe refuses to cancel a captured one.\n */\n cancel(\n paymentIntentId: string,\n account: string | null,\n idempotencyKey: string,\n ): Promise<{ ok: true } | { ok: false; error: string; status?: number }>\n /**\n * Tells the operator a card was made out to another account. Never throws.\n * `destination` is where the money went: the transfer's account for a\n * destination charge, the account the intent was made on for a direct one.\n */\n wrongAccount(input: {\n hostId: string\n orderId: string\n paymentIntentId: string\n status: string\n amountCents: number\n destination: string\n expected: string\n }): Promise<void>\n}\n\nexport function defaultPosOfflineCardDeps(): PosOfflineCardDeps {\n return {\n terminal: async (hostId) => ({\n available: posTerminalAvailable(),\n locationId: posTerminalAvailable() ? await posTerminalLocationId(hostId) : null,\n }),\n merchantAccount: posMerchantAccount,\n enableOffline: ensurePosOfflineCardConfiguration,\n retrieve: retrievePosOfflineCardIntent,\n capture: capturePosOfflineCardIntent,\n cancel: cancelPosOfflineCardIntent,\n wrongAccount: reportPosOfflineCardWrongAccount,\n }\n}\n\nexport function defaultPosOfflineSyncDeps(): PosOfflineSyncDeps {\n const base = defaultPosOpsDeps()\n return {\n ...base,\n feePct: (org, productType) => Aglyn.resolveTransactionFeePct(org as any, productType),\n registerWithinCap: (org, hostId, rank) =>\n Aglyn.checkHostRegisterQuota(org as any, hostId, rank).allowed,\n decrementStock: async (input) => {\n const moved = await decrementVariantStock({\n firestore: base.firestore(),\n hostRef: input.hostRef,\n hostId: input.hostId,\n productId: input.productId,\n variantId: input.variantId,\n quantity: input.quantity,\n ...(input.locationId ? { locationId: input.locationId } : {}),\n ledger: { reason: 'sale', orderId: input.orderId },\n })\n if (moved.before && moved.after) alertLowStockCrossing(input.hostId, moved.before, moved.after)\n return moved\n },\n afterSale: async (input) => {\n const settle = async (label: string, work: () => Promise<unknown>) => {\n try {\n await work()\n } catch (error) {\n console.error(`[pos-offline-sync] ${label} failed`, input.orderId, error)\n }\n }\n if (input.email) {\n await settle('contact', () =>\n recordCapturedContact({\n orgId: '',\n hostId: input.hostId,\n identity: { email: input.email, ...(input.name ? { name: input.name } : {}) },\n surface: 'relationship',\n lifecycleFloor: 'customer',\n purchaseCents: Number(input.order.totals?.totalCents ?? 0),\n interaction: {\n source: 'order',\n refId: input.orderId,\n summary: `In-store purchase ($${(Number(input.order.totals?.totalCents ?? 0) / 100).toFixed(2)})`,\n },\n }),\n )\n }\n // The sale-completed listeners hear it too, told it was rung offline:\n // the cloud printers must not print a receipt or pop the drawer for a\n // sale the customer walked away with hours ago.\n await settle('sale completed', () =>\n notifyPosSaleCompleted({ hostId: input.hostId, orderId: input.orderId, order: input.order, offline: true }),\n )\n // The emailed receipt sends now, on sync (the printed one went offline).\n await settle('receipt', () =>\n notifyOrderBuyer({ hostId: input.hostId, orderId: input.orderId }, 'receipt', { email: input.email }),\n )\n await settle('paid event', () =>\n raiseOrderEvent(ORDER_PAID_EVENT, { hostId: input.hostId, orderId: input.orderId, key: 'paid' }),\n )\n },\n card: defaultPosOfflineCardDeps(),\n }\n}\n\ntype Outcome = { status: number; body: Record<string, unknown> }\n\nconst money = (cents: number) => `$${(Math.max(0, cents) / 100).toFixed(2)}`\n\n/** The store's in-person tax, as every register sale computes it. */\nexport function posInPersonTax(\n settings: CommerceModel.TaxSettings | undefined,\n):\n | { ok: true; pct: number | null; pricesIncludeTax: boolean; decision: CommerceModel.StorefrontTaxDecision }\n | { ok: false; reason: string } {\n const taxSettings = (settings ?? {}) as CommerceModel.TaxSettings\n const decision = CommerceModel.storefrontTaxDecision({ settings: taxSettings })\n if (decision.kind === 'undecided') {\n return { ok: false, reason: CommerceModel.STOREFRONT_TAX_UNDECIDED_MESSAGE }\n }\n const misconfigured = CommerceModel.storefrontTaxMisconfiguration(taxSettings, { inPerson: true })\n if (misconfigured) return { ok: false, reason: misconfigured }\n const rate =\n decision.kind === 'manual' ? CommerceModel.resolveTaxRate(taxSettings, taxSettings.origin ?? {}) : null\n return {\n ok: true,\n pct: rate && rate.pct > 0 ? rate.pct : null,\n pricesIncludeTax: taxSettings.pricesIncludeTax === true,\n decision,\n }\n}\n\ninterface SyncContext {\n deps: PosOfflineSyncDeps\n staff: PosOpsStaff\n config: Record<string, unknown>\n tax: ReturnType<typeof posInPersonTax>\n /** Registers by id, with their creation rank. */\n registers: Map<string, { rank: number; data: Record<string, any> }>\n}\n\nasync function readRegisters(staff: PosOpsStaff): Promise<SyncContext['registers']> {\n const docs = (await staff.hostRef.collection('registers').get()).docs\n .map((doc) => ({\n id: doc.id,\n data: (doc.data() ?? {}) as Record<string, any>,\n createdAtMs: Number(doc.get('createdAt')?.toMillis?.() ?? doc.get('createdAtMs') ?? 0),\n }))\n .sort((a, b) => a.createdAtMs - b.createdAtMs || a.id.localeCompare(b.id))\n return new Map(docs.map((doc, rank) => [doc.id, { rank, data: doc.data }]))\n}\n\nasync function readStoreTax(staff: PosOpsStaff): Promise<CommerceModel.TaxSettings | undefined> {\n const store = await staff.hostRef.collection('settings').doc('store').get()\n return (store.get('tax') ?? undefined) as CommerceModel.TaxSettings | undefined\n}\n\n/** What the app asking for the kit can do, from the GET's query. */\nexport interface PosOfflineKitClient {\n /** The app makes a card's intent on a store's own Stripe account (AGL-4219). */\n directCards?: boolean\n}\n\n/** The kit a register caches to sell offline. */\nexport async function buildPosOfflineKit(\n deps: PosOfflineSyncDeps,\n staff: PosOpsStaff,\n client: PosOfflineKitClient = {},\n): Promise<PosOfflineKit> {\n const [registers, taxSettings, config, host, store] = await Promise.all([\n readRegisters(staff),\n readStoreTax(staff),\n staff.orgId ? deps.pluginConfig(staff.orgId, staff.hostId).catch(() => ({})) : Promise.resolve({}),\n staff.hostRef.get(),\n staff.hostRef.collection('settings').doc('store').get(),\n ])\n const tax = posInPersonTax(taxSettings)\n const card = await buildPosOfflineKitCard(deps, staff, config, client)\n return {\n v: 1,\n hostId: staff.hostId,\n orgId: staff.orgId,\n issuedAtMs: deps.now(),\n available: tax.ok,\n ...('reason' in tax ? { unavailableReason: tax.reason } : {}),\n tax: 'decision' in tax ? { pct: tax.pct, pricesIncludeTax: tax.pricesIncludeTax } : { pct: null, pricesIncludeTax: false },\n maxDiscountPct: posMaxDiscountPct(config),\n requireOpenShift: staff.settings.requireOpenShift,\n registers: [...registers.entries()]\n .filter(([, register]) => deps.registerWithinCap(staff.org, staff.hostId, register.rank))\n .map(([id, register]) => ({\n id,\n name: String(register.data['name'] ?? 'Register').slice(0, 120),\n ...(register.data['locationId'] ? { locationId: String(register.data['locationId']) } : {}),\n openShiftId: posOpsCleanId(register.data['openShiftId']) || null,\n })),\n ...(card ? { card } : {}),\n receipt: {\n name: String(host.get('displayName') ?? '') || 'Receipt',\n ...(typeof host.get('logoUrl') === 'string' && host.get('logoUrl') ? { logo: String(host.get('logoUrl')) } : {}),\n ...(staff.settings.receiptAddress ? { address: staff.settings.receiptAddress } : {}),\n ...(store.get('receiptFooter') ? { footer: String(store.get('receiptFooter')).slice(0, 500) } : {}),\n ...(staff.settings.returnPolicy ? { returnPolicy: staff.settings.returnPolicy } : {}),\n },\n }\n}\n\n/**\n * What the app needs to take a card offline on its own reader (AGL-4039), or\n * why it cannot. Absent where this server takes no offline cards.\n */\nasync function buildPosOfflineKitCard(\n deps: PosOfflineSyncDeps,\n staff: PosOpsStaff,\n config: Record<string, unknown>,\n client: PosOfflineKitClient,\n): Promise<PosOfflineKitCard | undefined> {\n if (!deps.card) return undefined\n const settings = posOfflineCardSettings(config)\n const base = {\n destination: '',\n currency: POS_CURRENCY,\n maxSaleCents: settings.maxSaleCents,\n maxDeviceDailyCents: settings.maxDeviceDailyCents,\n }\n const off = (unavailableReason: string): PosOfflineKitCard => ({ ...base, available: false, unavailableReason })\n if (!settings.enabled) return off('Card sales offline are not turned on in this store’s point of sale settings.')\n const terminal = await deps.card.terminal(staff.hostId)\n if (!terminal.available) return off('Card readers are not set up for this store yet.')\n if (!terminal.locationId) return off('Connect a card reader once while online, then cards keep working offline.')\n const merchant = await deps.card.merchantAccount(staff.hostId, staff.org)\n if (!merchant) return off('Finish connecting Stripe to take cards.')\n // The app makes an offline card's intent itself. For a store on Aglyn's\n // account it is a DESTINATION charge to `destination`. For a store on its\n // own Stripe account (AGL-4219) it is made ON that account, which is the\n // one the SDK's connection token and the site's Location belong to\n // (`createPosTerminalConnectionToken`), with no transfer at all: Stripe's\n // Terminal-with-direct-charges guide asks a client-side intent for no\n // Connect parameters. An app from before that cannot make one, so it is\n // offered no kit for such a store rather than a card that fails at the\n // counter or lands on the wrong account.\n const direct = merchant.chargeModel === 'direct'\n if (direct && !client.directCards) {\n return off('Card sales offline are not available for this store’s payment account yet. Take cards while online.')\n }\n if (!(await deps.card.enableOffline(staff.hostId))) {\n return off('Card sales offline could not be turned on for this store’s readers yet. Try again later.')\n }\n return direct\n ? { ...base, account: merchant.accountId, available: true }\n : { ...base, destination: merchant.accountId, available: true }\n}\n\n/** A card made out to a Stripe account that is not the store's. */\ninterface OfflineCardWrongAccount {\n destination: string\n expected: string\n status: string\n amountCents: number\n}\n\n/** What became of a card taken offline, as the sync settles it. */\ntype OfflineCardSettlement =\n | (PosOfflineCardSettled & {\n wrongAccount?: OfflineCardWrongAccount\n /** An authorization on another account the sync cancels once the sale is recorded. */\n releaseHold?: { paymentIntentId: string; account: string | null }\n })\n | { kind: 'wait'; outcome: PosOfflineSaleOutcome }\n\n/** Statuses in which an intent holds the customer's money or has taken it. */\nconst INTENT_HOLDS_MONEY: ReadonlySet<string> = new Set(['requires_capture', 'processing', 'succeeded'])\n\n/**\n * How long after a capture that Stripe answered with a 5xx the sync waits\n * before reading \"still waiting for capture\" as the definite answer.\n */\nexport const POS_OFFLINE_CAPTURE_SETTLE_MS = 60_000\n\n/**\n * The capture's idempotency key (AGL-4039). Attempt 0 is the key every\n * capture used before attempts existed, so a retry of one already in flight\n * still finds it.\n *\n * WHY AN ATTEMPT. Stripe keeps the answer to an idempotent request for a day,\n * failures included, so a capture that failed once on a per-sale key would\n * fail the same way on every sync for a day, deep into the two days the\n * authorization lasts. The attempt moves on only when the previous one\n * DEFINITELY did not capture: Stripe refused it with a 4xx (not 409, a\n * request with the same key still running, and not 429, rate limited), or it\n * answered 5xx and the intent still waits for capture a minute later. A\n * request that got no answer at all throws before anything is recorded, so it\n * retries on the same key. Every sync reads the intent before it captures,\n * and Stripe captures an intent once, so a new key can never capture twice.\n */\nexport function posOfflineCaptureKey(hostId: string, saleKey: string, attempt: number): string {\n const base = `pos-offline-capture:${hostId}:${saleKey}`\n return attempt > 0 ? `${base}:${attempt}` : base\n}\n\n/** A capture Stripe refused for good: retrying the same key would replay the refusal. */\nexport function posOfflineCaptureRefused(status: number | undefined): boolean {\n return typeof status === 'number' && status >= 400 && status < 500 && status !== 409 && status !== 429\n}\n\n/**\n * Reads the card of a sale rung offline and settles it: captured with the\n * platform fee (the card tender's share of the take, by the one tender rule,\n * plus Stripe's processing cost, exactly as an online reader payment), or\n * unpaid when the bank declined it, Stripe never took it, or it was made out\n * to a Stripe account that is not the store's. Anything Stripe has not\n * finished yet waits on the register for the next sync.\n */\nasync function settleOfflineCard(\n context: SyncContext,\n sale: PosOfflineSale,\n takeFee: number,\n): Promise<OfflineCardSettlement> {\n const { deps, staff } = context\n const { saleKey } = sale\n const card = sale.card!\n const wait = (error: string): OfflineCardSettlement => ({ kind: 'wait', outcome: refused(saleKey, 'failed', error, true) })\n if (card.forward === 'stored') return wait('The card is still on this register. It syncs once Stripe has it.')\n if (!deps.card) return wait('Card sales taken offline cannot sync to this store yet.')\n const details = { ...(card.brand ? { brand: card.brand } : {}), ...(card.last4 ? { last4: card.last4 } : {}) }\n if (!card.paymentIntentId) {\n return {\n kind: 'unpaid',\n flag: card.forward === 'declined' ? 'card-declined' : 'card-not-charged',\n message: card.declineMessage || 'Stripe did not take the card.',\n ...details,\n }\n }\n // WHERE THE INTENT LIVES. A direct-charge kit has the device make it on\n // the store's own account, and the sale says which (`card.account`); every\n // other card was made on the platform. It is read where the device made\n // it, and judged below against where the store sells NOW.\n const madeOn = card.account ?? null\n const read = await deps.card.retrieve(card.paymentIntentId, madeOn)\n if ('error' in read) {\n // Stripe answering that the account has no such intent (or that it may\n // not be read there) is definite. When that account is not the store's\n // now, the card cannot be this store's money, so the sale is recorded\n // unpaid rather than kept on the register for good.\n if (madeOn && posOfflineCaptureRefused(read.status)) {\n const merchant = await deps.card.merchantAccount(staff.hostId, staff.org)\n if (merchant && !(merchant.chargeModel === 'direct' && merchant.accountId === madeOn)) {\n return {\n kind: 'unpaid',\n flag: 'card-not-charged',\n intentId: card.paymentIntentId,\n message: 'The card was made out to a Stripe account that is not this store’s, so it was not charged here.',\n ...details,\n wrongAccount: { destination: madeOn, expected: merchant.accountId, status: 'unreadable', amountCents: 0 },\n }\n }\n }\n return wait(`The card payment could not be checked yet: ${read.error}`)\n }\n let intent = read.intent\n // The amount is NOT checked here: what Stripe took is what the customer\n // paid, and a difference from the server's total is flagged on the order\n // (`posOfflineCardOrderMoney`), never a reason to leave the sale unrecorded.\n if (\n intent.metadata['kind'] !== POS_OFFLINE_CARD_INTENT_KIND ||\n intent.metadata['saleKey'] !== saleKey ||\n intent.metadata['hostId'] !== staff.hostId ||\n intent.currency !== POS_CURRENCY\n ) {\n return { kind: 'wait', outcome: refused(saleKey, 'invalid', 'The card payment does not belong to this sale.', false) }\n }\n const found = { ...details, ...(intent.brand ? { brand: intent.brand } : {}), ...(intent.last4 ? { last4: intent.last4 } : {}) }\n // THE ACCOUNT. The device made this intent where its offline kit said:\n // out to `destination` on the platform, or on the store's own account for\n // a direct charge. A kit can be stale (the store reconnected Stripe, or\n // moved to its own account) or a register tampered with. Money that holds\n // or has moved is only ever captured into, or recorded as paid to, the\n // store's account as it is now:\n // - DESTINATION store: made on the platform, transferred to its account.\n // - DIRECT store: made ON its current account, transferring nowhere.\n // Anything else reads as made out elsewhere, like a kit gone stale.\n if (INTENT_HOLDS_MONEY.has(intent.status)) {\n const merchant = await deps.card.merchantAccount(staff.hostId, staff.org)\n const expected = merchant?.accountId ?? null\n if (!merchant || !expected) {\n return wait('This store’s Stripe account cannot take card payments right now. The card syncs once it can.')\n }\n const onStoreAccount =\n merchant.chargeModel === 'direct'\n ? madeOn === expected && !intent.destination\n : madeOn === null && intent.destination === expected\n if (!onStoreAccount) {\n return {\n kind: 'unpaid',\n flag: 'card-not-charged',\n intentId: intent.id,\n message: 'The card was made out to a Stripe account that is not this store’s, so it was not charged here.',\n ...found,\n wrongAccount: {\n destination: madeOn ?? intent.destination,\n expected,\n status: intent.status,\n amountCents: intent.amount,\n },\n // Not this store's money, but the customer's card still holds it\n // until the authorization lapses: an intent only authorized (never\n // one captured or processing) is cancelled where the device made it,\n // once the sale is recorded, so the hold is released.\n ...(intent.status === 'requires_capture'\n ? { releaseHold: { paymentIntentId: intent.id, account: madeOn } }\n : {}),\n }\n }\n }\n // The fee, by the one tender rule, exactly as an online reader payment is\n // captured (`posCaptureFeeCents`): the card's share of the take plus\n // Stripe's processing on a destination charge, the take alone on the\n // store's own account, where Stripe bills the store its card fee.\n const takeShareCents = CommerceModel.posTenderTakeCents('card_present', takeFee)\n const expectedFeeCents = posOfflineCardFeeCents({\n takeShareCents,\n chargeCents: intent.amount,\n ...(madeOn ? { direct: true } : {}),\n })\n if (intent.status === 'requires_capture') {\n const chargeRef = posOfflineCardChargeRef(staff.hostRef, saleKey)\n const charge = ((await chargeRef.get()).data() ?? {}) as Record<string, unknown>\n let attempt = Math.max(0, Math.round(Number(charge['captureAttempt'] ?? 0)) || 0)\n if (\n charge['captureUncertainAttempt'] === attempt &&\n deps.now() - Number(charge['captureUncertainAtMs'] ?? 0) >= POS_OFFLINE_CAPTURE_SETTLE_MS\n ) {\n // The 5xx left the outcome unknown; the intent still waiting for\n // capture a minute later says it did not capture.\n attempt += 1\n await chargeRef.set(\n {\n captureAttempt: attempt,\n captureUncertainAttempt: FieldValue.delete(),\n captureUncertainAtMs: FieldValue.delete(),\n },\n { merge: true },\n )\n }\n const captured = await deps.card.capture(\n intent.id,\n expectedFeeCents,\n posOfflineCaptureKey(staff.hostId, saleKey, attempt),\n madeOn,\n )\n if ('error' in captured) {\n const stamp = { hostId: staff.hostId, saleKey, updatedAtMs: deps.now() }\n if (posOfflineCaptureRefused(captured.status)) {\n await chargeRef.set(\n {\n ...stamp,\n captureAttempt: attempt + 1,\n lastCaptureStatus: captured.status,\n lastCaptureError: captured.error.slice(0, 300),\n },\n { merge: true },\n )\n } else if (typeof captured.status === 'number' && captured.status >= 500) {\n await chargeRef.set(\n { ...stamp, captureUncertainAttempt: attempt, captureUncertainAtMs: deps.now() },\n { merge: true },\n )\n }\n return wait(`The card payment could not be captured yet: ${captured.error}`)\n }\n intent = captured.intent\n }\n if (intent.status === 'succeeded') {\n return {\n kind: 'captured',\n intentId: intent.id,\n amountCents: intent.amount,\n feeCents: intent.applicationFeeCents,\n expectedFeeCents,\n takeShareCents,\n livemode: intent.livemode,\n ...(madeOn ? { account: madeOn } : {}),\n ...found,\n }\n }\n if (intent.status === 'requires_payment_method' || intent.status === 'canceled') {\n return {\n kind: 'unpaid',\n flag: 'card-declined',\n intentId: intent.id,\n message: intent.failureMessage || card.declineMessage || 'The card was declined.',\n ...found,\n }\n }\n return wait('The card payment is still processing. It syncs when Stripe finishes.')\n}\n\nconst refused = (\n saleKey: string,\n reason: PosOfflineRefusal,\n error: string,\n retry: boolean,\n): PosOfflineSaleOutcome => ({ saleKey, status: 'refused', reason, error, retry })\n\nconst replayOf = (record: PosOfflineSyncRecord): PosOfflineSaleOutcome => ({\n saleKey: record.saleKey,\n status: 'replayed',\n orderId: record.orderId,\n number: record.number,\n flags: record.flags,\n stockConflicts: record.stockConflicts,\n})\n\n/** The take the plan owes on the goods after the discount (AGL-2111, AGL-2256). */\nfunction takeFeeCents(\n deps: PosOfflineSyncDeps,\n staff: PosOpsStaff,\n lines: CommerceModel.OrderLineItem[],\n totals: CommerceModel.OrderTotals,\n): number {\n let applies = false\n const gross = lines.reduce((sum, line) => {\n const pct = deps.feePct(staff.org, (line.productType ?? 'physical') as 'physical' | 'digital' | 'service')\n if (pct > 0) applies = true\n return sum + Math.round((line.unitAmountCents * line.quantity * pct) / 100)\n }, 0)\n const charged = Math.max(0, totals.itemsCents - totals.discountCents)\n const scaled = totals.itemsCents > 0 ? Math.round((gross * charged) / totals.itemsCents) : 0\n return applies && charged > 0 ? Math.max(1, scaled) : scaled\n}\n\n/**\n * The steps after the commit, each recorded as it finishes. Run by the sync\n * that recorded the sale, and again by any later sync of it that finds them\n * unfinished.\n */\nasync function finishSale(\n context: SyncContext,\n recordRef: FirebaseFirestore.DocumentReference,\n orderRef: FirebaseFirestore.DocumentReference,\n record: PosOfflineSyncRecord,\n): Promise<PosOfflineSyncRecord> {\n const { deps, staff } = context\n const orderSnapshot = await orderRef.get()\n const order = (orderSnapshot.data() ?? {}) as CommerceModel.HostOrder & Record<string, any>\n let current = record\n if (!current.stockDone) {\n const conflicts = [...current.stockConflicts]\n const done = new Set(current.stockLines)\n const lines = (order.lineItems ?? []) as CommerceModel.OrderLineItem[]\n for (const [index, line] of lines.entries()) {\n if (done.has(index)) continue\n const moved = await deps.decrementStock({\n hostRef: staff.hostRef,\n hostId: staff.hostId,\n productId: line.productId,\n variantId: line.variantId ?? 'default',\n quantity: line.quantity,\n ...(order['locationId'] ? { locationId: String(order['locationId']) } : {}),\n orderId: orderRef.id,\n })\n // A failed commit leaves the line for the next sync to take, rather than\n // marking stock taken that never moved.\n if (moved.failed) continue\n // Untracked stock (or a product gone since) moves nothing and is short of nothing.\n const short = moved.before ? moved.applied - moved.requested : 0\n if (short > 0) {\n conflicts.push({\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n name: [line.name, line.variantLabel].filter(Boolean).join(' — '),\n requested: Math.abs(moved.requested),\n applied: Math.abs(moved.applied),\n shortUnits: short,\n })\n }\n done.add(index)\n await recordRef.update({ stockLines: [...done].sort((a, b) => a - b), stockConflicts: conflicts })\n }\n const stockDone = lines.every((_line, index) => done.has(index))\n const flags: PosOfflineFlag[] =\n conflicts.length && !current.flags.includes('stock-short') ? [...current.flags, 'stock-short'] : current.flags\n current = { ...current, stockLines: [...done], stockConflicts: conflicts, stockDone, flags }\n await recordRef.update({ stockDone, flags, stockConflicts: conflicts })\n if (conflicts.length && conflicts.length !== record.stockConflicts.length) {\n const fresh = (await orderRef.get()).data() as CommerceModel.HostOrder\n const stamp = fresh?.offline\n await orderRef.update({\n ...(stamp ? { offline: { ...stamp, flags, stockConflicts: conflicts } } : {}),\n timeline: CommerceModel.appendOrderEvent(\n fresh ?? {},\n 'offline-stock-short',\n conflicts\n .map((conflict) => `${conflict.shortUnits} of ${conflict.requested}× ${conflict.name} not in stock`)\n .join('; ')\n .slice(0, 500),\n deps.now(),\n ),\n })\n }\n if (!stockDone) return current\n }\n if (current.releaseHold && current.holdReleased === undefined) {\n current = await releaseOfflineCardHold(context, recordRef, orderRef, current)\n }\n if (!current.notified && current.unpaid) {\n // A card that was never paid gets no receipt and no \"paid\": the order\n // waits, flagged, for the merchant to collect it another way.\n current = { ...current, notified: true, status: 'settled' }\n await recordRef.update({ notified: true, status: 'settled' })\n }\n if (!current.notified) {\n const email = String(order.customerEmail ?? '')\n await deps.afterSale({\n hostId: staff.hostId,\n orderId: orderRef.id,\n order: order as CommerceModel.HostOrder,\n email,\n name: String(order.customerName ?? ''),\n })\n current = { ...current, notified: true, status: 'settled' }\n await recordRef.update({ notified: true, status: 'settled' })\n }\n return current\n}\n\n/** The cancel's idempotency key: one cancel per sale. */\nexport function posOfflineReleaseKey(hostId: string, saleKey: string): string {\n return `pos-offline-release:${hostId}:${saleKey}`\n}\n\n/**\n * Cancels the authorization of a card refused as made out to another\n * account (AGL-4219), so the customer's card no longer holds the money, and\n * records what happened on the sale and its order. Tried once, after the\n * order exists: a failure (Stripe refused, or no answer) is recorded and\n * never stops the sync. The order stays unpaid and flagged either way.\n */\nasync function releaseOfflineCardHold(\n context: SyncContext,\n recordRef: FirebaseFirestore.DocumentReference,\n orderRef: FirebaseFirestore.DocumentReference,\n record: PosOfflineSyncRecord,\n): Promise<PosOfflineSyncRecord> {\n const { deps, staff } = context\n const hold = record.releaseHold!\n let error = ''\n try {\n const cancelled = deps.card\n ? await deps.card.cancel(hold.paymentIntentId, hold.account, posOfflineReleaseKey(staff.hostId, record.saleKey))\n : { ok: false as const, error: 'Card sales taken offline cannot sync to this store.' }\n if ('error' in cancelled) error = cancelled.error || 'Stripe refused the cancel.'\n } catch (failure) {\n console.error('[pos-offline-sync] hold release failed', staff.hostId, record.saleKey, failure)\n error = 'Stripe did not answer.'\n }\n const released = !error\n const fields = released\n ? { holdReleased: true }\n : { holdReleased: false, holdReleaseError: error.slice(0, 300) }\n await recordRef.update(fields)\n try {\n const fresh = ((await orderRef.get()).data() ?? {}) as CommerceModel.HostOrder\n await orderRef.update({\n timeline: CommerceModel.appendOrderEvent(\n fresh,\n released ? 'offline-card-released' : 'offline-card-release-failed',\n released\n ? 'The card’s authorization was cancelled on Stripe, so the customer’s card no longer holds the money.'\n : `The card’s authorization could not be cancelled on Stripe (${error}). The hold on the customer’s card lapses on its own.`.slice(0, 500),\n deps.now(),\n ),\n })\n await posOfflineCardChargeRef(staff.hostRef, record.saleKey).set(\n { ...fields, updatedAtMs: deps.now() },\n { merge: true },\n )\n } catch (failure) {\n console.error('[pos-offline-sync] hold release note failed', staff.hostId, record.saleKey, failure)\n }\n return { ...record, ...fields }\n}\n\nasync function syncOne(context: SyncContext, raw: unknown): Promise<PosOfflineSaleOutcome> {\n const { deps, staff } = context\n const read = sanitizePosOfflineSale(raw)\n const rawKey = String((raw as Record<string, unknown> | null)?.['saleKey'] ?? '').slice(0, 64)\n if ('error' in read) return refused(rawKey, 'invalid', read.error, false)\n const sale = read.sale\n if (sale.hostId !== staff.hostId) {\n return refused(sale.saleKey, 'wrong-site', 'This sale was rung for another site.', false)\n }\n if (sale.signedInUid !== staff.uid) {\n return refused(\n sale.saleKey,\n 'wrong-staff',\n 'This sale was rung while another member was signed in. It syncs when they sign in on this register.',\n true,\n )\n }\n if (sale.orgId && staff.orgId && sale.orgId !== staff.orgId) {\n return refused(sale.saleKey, 'wrong-workspace', 'This sale was rung in another workspace.', false)\n }\n\n const firestore = deps.firestore()\n const hostRef = staff.hostRef\n const recordRef = hostRef.collection('posOfflineSales').doc(sale.saleKey)\n const orderRef = hostRef.collection('orders').doc(sale.saleKey)\n\n const existing = await recordRef.get()\n if (existing.exists) {\n const record = existing.data() as PosOfflineSyncRecord\n if (record.signedInUid !== staff.uid) {\n return refused(sale.saleKey, 'conflict', 'Another sale already used this key.', false)\n }\n return replayOf(record.status === 'settled' ? record : await finishSale(context, recordRef, orderRef, record))\n }\n\n const now = deps.now()\n const flags = new Set<PosOfflineFlag>()\n const soldAt = posOfflineSoldAt(sale.soldAtMs, now)\n if (soldAt.adjusted) flags.add('clock-adjusted')\n else if (now - soldAt.atMs > POS_OFFLINE_LATE_SYNC_MS) flags.add('late-sync')\n\n // The lines as sold, checked against the catalog as it stands now. The\n // price on the order is the one rung — that is what the customer paid —\n // and the catalog's is kept beside it where they differ.\n const productIds = [...new Set(sale.lines.map((line) => line.productId))]\n const snapshots = await Promise.all(productIds.map((id) => hostRef.collection('products').doc(id).get()))\n const products = new Map(\n snapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const priceDrift: NonNullable<PosOfflineOrderStamp['priceDrift']> = []\n const lineItems: CommerceModel.OrderLineItem[] = sale.lines.map((line, index) => {\n const product = products.get(line.productId)\n if (!product) {\n flags.add('unknown-product')\n return {\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(line.sku ? { sku: line.sku } : {}),\n productType: line.productType ?? 'physical',\n quantity: line.quantity,\n unitAmountCents: line.unitAmountCents,\n }\n }\n const variant = product.variants.find((item) => item.id === line.variantId) ?? product.variants[0]\n const chosen = CommerceModel.resolveLineModifiers(product, line.modifiers, variant?.id)\n const currentCents =\n variant && CommerceModel.variantHasPrice(variant) && chosen.ok\n ? Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents\n : null\n if (currentCents !== line.unitAmountCents) {\n flags.add('price-changed')\n priceDrift.push({ index, rungCents: line.unitAmountCents, currentCents: currentCents ?? 0 })\n }\n return {\n productId: line.productId,\n ...(variant && variant.id !== 'default' ? { variantId: variant.id } : {}),\n name: product.name || line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n ...(variant?.sku ? { sku: variant.sku } : line.sku ? { sku: line.sku } : {}),\n productType: product.type ?? line.productType ?? 'physical',\n quantity: line.quantity,\n unitAmountCents: line.unitAmountCents,\n ...(chosen.ok && chosen.modifiers.length ? { modifiers: chosen.modifiers } : {}),\n }\n })\n\n // The money: what the register rang, when its own arithmetic holds; the\n // arithmetic of its lines, with the tax it rang, when it does not.\n let totals: CommerceModel.OrderTotals\n if (posOfflineTotalsAddUp(sale)) {\n totals = CommerceModel.computeOrderTotals(lineItems, {\n discountCents: sale.totals.discountCents,\n taxCents: sale.totals.taxCents,\n })\n } else {\n flags.add('totals-restated')\n const restated = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: null, pricesIncludeTax: false },\n })\n totals = CommerceModel.computeOrderTotals(lineItems, {\n discountCents: restated.discountCents,\n taxCents: Math.min(sale.totals.taxCents, restated.itemsCents - restated.discountCents),\n })\n }\n if ('decision' in context.tax) {\n const expected = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: context.tax.pct, pricesIncludeTax: context.tax.pricesIncludeTax },\n })\n if (expected.taxCents !== totals.taxCents) flags.add('tax-differs')\n } else if (totals.taxCents > 0) {\n flags.add('tax-differs')\n }\n if (sale.discountPct > posMaxDiscountPct(context.config)) flags.add('discount-over-limit')\n // The cashier's own discount needs `posDiscount` (AGL-4047), as the online\n // register refuses it without. Offline the sale has already happened, so it\n // is recorded and flagged rather than dropped. Read for the member who was\n // signed in, whose membership the gate resolved, as the online check reads it.\n if (sale.discountPct > 0 && !holdsPosPermission(staff.membership.permissions, 'posDiscount')) {\n flags.add('discount-not-permitted')\n }\n const byCard = sale.tender === 'card'\n if (!byCard && sale.cashTenderedCents < totals.totalCents) flags.add('cash-short')\n\n // Where it was rung.\n const register = context.registers.get(sale.registerId)\n if (!register) flags.add('unknown-register')\n else if (!deps.registerWithinCap(staff.org, staff.hostId, register.rank)) flags.add('register-over-cap')\n let shiftId = ''\n if (sale.shiftId && register) {\n const shift = await hostRef\n .collection('registers')\n .doc(sale.registerId)\n .collection('shifts')\n .doc(sale.shiftId)\n .get()\n if (shift.exists) {\n shiftId = sale.shiftId\n if (shift.get('status') !== 'open') flags.add('shift-closed')\n }\n }\n if (!shiftId && staff.settings.requireOpenShift) flags.add('no-shift')\n\n // Who rang it: a PIN-switched cashier's assertion is read as of the moment\n // the cash was taken (it was valid then, and expiring since is the normal\n // case for a sale that waited to sync), and the member is re-checked NOW.\n let cashierId = staff.uid\n if (sale.cashierAssertion) {\n const memberUid = await resolvePosStaffAssertion(\n { ...deps, now: () => soldAt.atMs },\n hostRef,\n sale.cashierAssertion,\n { hostId: staff.hostId, registerId: sale.registerId, purpose: 'cashier' },\n )\n if (memberUid) cashierId = memberUid\n else flags.add('cashier-unverified')\n }\n\n // Cash carries no platform fee (AGL-4036): the plan's take is worked out\n // and then settled by the one predicate every tender answers to, so a sale\n // synced from the queue is charged exactly what the same sale rung online\n // is.\n const planTake = takeFeeCents(deps, staff, lineItems, totals)\n // A card taken offline settles with Stripe BEFORE the order is written: a\n // capture that fails leaves the sale on the register for the next sync,\n // and a repeat after a lost answer finds the first capture (AGL-4039).\n const settled = byCard ? await settleOfflineCard(context, sale, planTake) : null\n if (settled?.kind === 'wait') return settled.outcome\n // The card's money, decided once against the server's totals: the fee it\n // settled, the shortfall to invoice, and the order-level intent the refund\n // and the dispute lookup read.\n const cardMoney = settled\n ? posOfflineCardOrderMoney({\n settled,\n totals,\n planTakeCents: planTake,\n soldAtMs: soldAt.atMs,\n nowMs: now,\n cashierId,\n feeOrgId: staff.orgId ?? '',\n })\n : null\n for (const flag of cardMoney?.flags ?? []) flags.add(flag)\n const cashTake = CommerceModel.posTenderTakeCents('cash', planTake)\n totals = cardMoney ? cardMoney.totals : { ...totals, feeCents: cashTake }\n // What accrues to the org's month with the order: the cash take (none\n // since AGL-4036) or the part of a card's fee its payout did not carry.\n const invoiceCents = cardMoney ? cardMoney.invoiceCents : cashTake\n const changeCents = byCard ? 0 : Math.max(0, sale.cashTenderedCents - totals.totalCents)\n const flagList = [...flags]\n const stamp: PosOfflineOrderStamp = {\n saleKey: sale.saleKey,\n soldAtMs: soldAt.atMs,\n syncedAtMs: now,\n syncedBy: staff.uid,\n flags: flagList,\n ...(priceDrift.length ? { priceDrift } : {}),\n }\n const customer = sale.customer ?? {}\n const feeMonth = offlineFeeMonthKey(new Date(now))\n const feeRef = staff.orgId\n ? firestore.collection('orgs').doc(staff.orgId).collection('offlineFees').doc(feeMonth)\n : null\n const counterRef = hostRef.collection('counters').doc('orders')\n\n const committed = await firestore.runTransaction(async (transaction) => {\n const raced = await transaction.get(recordRef)\n if (raced.exists) return { raced: raced.data() as PosOfflineSyncRecord }\n const taken = await transaction.get(orderRef)\n if (taken.exists) return { collision: true as const }\n const counter = await transaction.get(counterRef)\n const number = Number(counter.get('next') ?? 1)\n transaction.set(counterRef, { next: number + 1 }, { merge: true })\n const cardName = settled\n ? [settled.brand ? settled.brand.toUpperCase() : 'Card', settled.last4 ? `•••• ${settled.last4}` : ''].filter(Boolean).join(' ')\n : ''\n const paidDetail = !settled\n ? `Cash — received ${money(sale.cashTenderedCents)}, change ${money(changeCents)}. ` +\n 'Rung while the register was offline.'\n : settled.kind === 'captured'\n ? `${cardName} — ${money(settled.amountCents)}, taken while the register was offline and charged when it reconnected.`\n : `${cardName} — ${money(totals.totalCents)} taken while the register was offline was not paid: ${settled.message}`.slice(0, 500)\n const timeline: CommerceModel.OrderTimelineEvent[] = [\n { atMs: soldAt.atMs, event: settled?.kind === 'unpaid' ? 'payment-failed' : 'paid', detail: paidDetail },\n {\n atMs: now,\n event: 'offline-synced',\n detail: flagList.length\n ? `Synced. Check: ${posOfflineFlagLabels(flagList).join('; ')}`.slice(0, 1000)\n : 'Synced.',\n },\n ]\n transaction.create(\n orderRef,\n CommerceModel.withOrderListFields(orderRef.id, {\n number,\n status: cardMoney ? cardMoney.status : 'paid',\n channel: 'pos',\n registerId: sale.registerId,\n cashierId,\n ...(shiftId ? { shiftId } : {}),\n ...(customer.name ? { customerName: customer.name } : {}),\n ...(customer.kind && customer.id ? { customerRecord: { kind: customer.kind, id: customer.id } } : {}),\n ...(sale.discountPct > 0 ? { discountPct: sale.discountPct, discountBy: cashierId } : {}),\n ...(sale.locationId ? { locationId: sale.locationId } : {}),\n // A card reader sold offline on the platform's own store (AGL-4038):\n // recorded once synced, with nobody attached, for the To attach list.\n ...posHardwareSaleFields({ hostId: staff.hostId, orgId: staff.orgId, lineItems, products }),\n lineItems,\n totals,\n taxMode: 'decision' in context.tax\n ? CommerceModel.storefrontTaxModeForDecision(context.tax.decision, totals.taxCents)\n : totals.taxCents > 0\n ? 'manual'\n : 'none',\n ...(cardMoney ? cardMoney.fields : cashTake > 0 ? { feeCollection: 'invoice' as const } : {}),\n payments: cardMoney\n ? [cardMoney.payment]\n : [\n {\n id: 'pay_cash',\n method: 'cash',\n amountCents: totals.totalCents,\n status: 'succeeded',\n atMs: soldAt.atMs,\n settledAtMs: soldAt.atMs,\n takeFeeCents: cashTake,\n feeCents: 0,\n cashierId,\n cashTenderedCents: sale.cashTenderedCents,\n changeCents,\n } satisfies CommerceModel.OrderPayment,\n ],\n customerEmail: customer.email || null,\n timeline,\n offline: stamp,\n createdAtMs: soldAt.atMs,\n createdAt: FieldValue.serverTimestamp(),\n }),\n )\n const record: PosOfflineSyncRecord = {\n saleKey: sale.saleKey,\n orderId: orderRef.id,\n number,\n signedInUid: staff.uid,\n registerId: sale.registerId,\n soldAtMs: soldAt.atMs,\n syncedAtMs: now,\n status: 'recorded',\n flags: flagList,\n stockConflicts: [],\n stockLines: [],\n stockDone: false,\n notified: false,\n ...(settled?.kind === 'unpaid' ? { unpaid: true } : {}),\n ...(settled?.kind === 'unpaid' && settled.releaseHold ? { releaseHold: settled.releaseHold } : {}),\n }\n transaction.create(recordRef, record)\n // The intent's record says its sale synced, in the same commit, so the\n // webhook and the unsynced-card sweep never report a sale that landed.\n if (settled?.intentId) {\n transaction.set(\n posOfflineCardChargeRef(hostRef, sale.saleKey),\n {\n hostId: staff.hostId,\n saleKey: sale.saleKey,\n paymentIntentId: settled.intentId,\n registerId: sale.registerId,\n synced: true,\n orderId: orderRef.id,\n syncedAtMs: now,\n updatedAtMs: now,\n alertDueAtMs: FieldValue.delete(),\n },\n { merge: true },\n )\n }\n // The fee no payout carried accrues with the order, in the same\n // transaction (AGL-2111): a card's share was netted from its payout by\n // the capture, and only a shortfall in that lands here.\n if (invoiceCents > 0 && feeRef) {\n transaction.set(\n feeRef,\n { month: feeMonth, feeCents: FieldValue.increment(invoiceCents), orders: FieldValue.increment(1) },\n { merge: true },\n )\n }\n return { record }\n })\n if ('collision' in committed) {\n return refused(sale.saleKey, 'conflict', 'Another order already has this sale’s key.', false)\n }\n if ('raced' in committed) {\n const record = committed.raced\n if (record.signedInUid !== staff.uid) {\n return refused(sale.saleKey, 'conflict', 'Another sale already used this key.', false)\n }\n return replayOf(record)\n }\n if (settled?.kind === 'unpaid' && settled.wrongAccount && settled.intentId) {\n await deps.card!.wrongAccount({\n hostId: staff.hostId,\n orderId: orderRef.id,\n paymentIntentId: settled.intentId,\n ...settled.wrongAccount,\n })\n }\n const finished = await finishSale(context, recordRef, orderRef, committed.record)\n return {\n saleKey: sale.saleKey,\n status: 'recorded',\n orderId: orderRef.id,\n number: finished.number,\n flags: finished.flags,\n stockConflicts: finished.stockConflicts,\n }\n}\n\nexport async function handlePosOfflineSync(\n deps: PosOfflineSyncDeps,\n req: PluginApiRequest,\n): Promise<Outcome> {\n if (req.method !== 'GET' && req.method !== 'POST') {\n return { status: 405, body: { error: 'Method not allowed' } }\n }\n const body =\n req.method === 'GET'\n ? Object.fromEntries(\n Object.entries(req.query ?? {}).map(([key, value]) => [key, Array.isArray(value) ? value[0] : value]),\n )\n : posOpsBody(req)\n const gate = await authorizePosOps(deps, req, body['hostId'], 'posSell')\n if ('error' in gate) return { status: gate.status, body: { error: gate.error } }\n const staff = gate.staff\n if (req.method === 'GET') {\n const models = String(body['cardChargeModels'] ?? '').split(',').map((model) => model.trim())\n return {\n status: 200,\n body: { kit: await buildPosOfflineKit(deps, staff, { directCards: models.includes('direct') }) },\n }\n }\n const sales = Array.isArray(body['sales']) ? (body['sales'] as unknown[]) : null\n if (!sales) return { status: 400, body: { error: 'Missing sales' } }\n if (sales.length > POS_OFFLINE_SYNC_BATCH_MAX) {\n return { status: 400, body: { error: `Send at most ${POS_OFFLINE_SYNC_BATCH_MAX} sales at a time` } }\n }\n if (sales.length === 0) return { status: 200, body: { results: [] } }\n const [registers, taxSettings, config] = await Promise.all([\n readRegisters(staff),\n readStoreTax(staff),\n staff.orgId ? deps.pluginConfig(staff.orgId, staff.hostId).catch(() => ({})) : Promise.resolve({}),\n ])\n const context: SyncContext = { deps, staff, config, tax: posInPersonTax(taxSettings), registers }\n const results: PosOfflineSaleOutcome[] = []\n // One at a time, in the order they were rung, so order numbers follow the\n // till and one sale's failure cannot take the rest with it.\n for (const sale of sales) {\n try {\n results.push(await syncOne(context, sale))\n } catch (error) {\n console.error('[pos-offline-sync] sale failed', error)\n const key = String((sale as Record<string, unknown> | null)?.['saleKey'] ?? '').slice(0, 64)\n results.push(refused(key, 'failed', 'The sale could not be synced yet. It stays on this register.', true))\n }\n }\n return { status: 200, body: { results } }\n}\n\nexport function createPosOfflineSyncHandler(\n deps: () => PosOfflineSyncDeps = defaultPosOfflineSyncDeps,\n): PluginApiHandler {\n return async (req, res) => {\n try {\n const outcome = await handlePosOfflineSync(deps(), req)\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n console.error('[pos-offline-sync] failed', error)\n return res.status(500).json({ error: 'The offline sales could not be synced' })\n }\n }\n}\n\nexport const posOfflineSyncHandler = createPosOfflineSyncHandler()\n"],"names":["Aglyn","recordCapturedContact","FieldValue","CommerceModel","posOfflineFlagLabels","posOfflineSaleTotals","posOfflineSoldAt","posOfflineTotalsAddUp","POS_OFFLINE_CARD_INTENT_KIND","POS_OFFLINE_LATE_SYNC_MS","POS_OFFLINE_SYNC_BATCH_MAX","sanitizePosOfflineSale","ORDER_PAID_EVENT","holdsPosPermission","posMaxDiscountPct","posOfflineCardSettings","alertLowStockCrossing","notifyOrderBuyer","raiseOrderEvent","offlineFeeMonthKey","authorizePosOps","defaultPosOpsDeps","posOpsBody","posOpsCleanId","resolvePosStaffAssertion","posOfflineCardChargeRef","reportPosOfflineCardWrongAccount","posHardwareSaleFields","posOfflineCardOrderMoney","notifyPosSaleCompleted","POS_CURRENCY","posOfflineCardFeeCents","posTerminalAvailable","cancelPosOfflineCardIntent","capturePosOfflineCardIntent","ensurePosOfflineCardConfiguration","posMerchantAccount","posTerminalLocationId","retrievePosOfflineCardIntent","decrementVariantStock","defaultPosOfflineCardDeps","terminal","hostId","available","locationId","merchantAccount","enableOffline","retrieve","capture","cancel","wrongAccount","defaultPosOfflineSyncDeps","base","feePct","org","productType","resolveTransactionFeePct","registerWithinCap","rank","checkHostRegisterQuota","allowed","decrementStock","input","moved","firestore","hostRef","productId","variantId","quantity","ledger","reason","orderId","before","after","afterSale","settle","label","work","error","console","email","orgId","identity","name","surface","lifecycleFloor","purchaseCents","Number","order","totals","totalCents","interaction","source","refId","summary","toFixed","offline","key","card","money","cents","Math","max","posInPersonTax","settings","taxSettings","decision","storefrontTaxDecision","kind","ok","STOREFRONT_TAX_UNDECIDED_MESSAGE","misconfigured","storefrontTaxMisconfiguration","inPerson","rate","resolveTaxRate","origin","pct","pricesIncludeTax","readRegisters","staff","docs","collection","get","map","doc","id","data","createdAtMs","toMillis","sort","a","b","localeCompare","Map","readStoreTax","store","undefined","buildPosOfflineKit","deps","client","host","registers","config","Promise","all","pluginConfig","catch","resolve","tax","buildPosOfflineKitCard","v","issuedAtMs","now","unavailableReason","maxDiscountPct","requireOpenShift","entries","filter","register","String","slice","openShiftId","receipt","logo","receiptAddress","address","footer","returnPolicy","destination","currency","maxSaleCents","maxDeviceDailyCents","off","enabled","merchant","direct","chargeModel","directCards","account","accountId","INTENT_HOLDS_MONEY","Set","POS_OFFLINE_CAPTURE_SETTLE_MS","posOfflineCaptureKey","saleKey","attempt","posOfflineCaptureRefused","status","settleOfflineCard","context","sale","takeFee","wait","outcome","refused","forward","details","brand","last4","paymentIntentId","flag","message","declineMessage","madeOn","read","intentId","expected","amountCents","intent","metadata","found","has","onStoreAccount","amount","releaseHold","takeShareCents","posTenderTakeCents","expectedFeeCents","chargeCents","charge","chargeRef","round","set","captureAttempt","captureUncertainAttempt","delete","captureUncertainAtMs","merge","captured","stamp","updatedAtMs","lastCaptureStatus","lastCaptureError","feeCents","applicationFeeCents","livemode","failureMessage","retry","replayOf","record","number","flags","stockConflicts","takeFeeCents","lines","applies","gross","reduce","sum","line","unitAmountCents","charged","itemsCents","discountCents","scaled","finishSale","recordRef","orderRef","orderSnapshot","current","stockDone","conflicts","done","stockLines","lineItems","index","failed","short","applied","requested","push","variantLabel","Boolean","join","abs","shortUnits","add","update","every","_line","length","includes","fresh","timeline","appendOrderEvent","conflict","holdReleased","releaseOfflineCardHold","notified","unpaid","customerEmail","customerName","posOfflineReleaseKey","hold","cancelled","failure","released","fields","holdReleaseError","syncOne","raw","rawKey","signedInUid","uid","existing","exists","soldAt","soldAtMs","adjusted","atMs","productIds","snapshots","products","snapshot","liftLegacyProduct","priceDrift","product","sku","variant","variants","find","item","chosen","resolveLineModifiers","modifiers","currentCents","variantHasPrice","priceUsd","extraCents","rungCents","type","computeOrderTotals","taxCents","restated","discountPct","min","membership","permissions","byCard","tender","cashTenderedCents","registerId","shiftId","shift","cashierId","cashierAssertion","memberUid","purpose","planTake","settled","cardMoney","planTakeCents","nowMs","feeOrgId","cashTake","invoiceCents","changeCents","flagList","syncedAtMs","syncedBy","customer","feeMonth","Date","feeRef","counterRef","committed","runTransaction","transaction","counter","raced","taken","collision","next","cardName","toUpperCase","paidDetail","event","detail","create","withOrderListFields","channel","customerRecord","discountBy","taxMode","storefrontTaxModeForDecision","feeCollection","payments","payment","method","settledAtMs","createdAt","serverTimestamp","synced","alertDueAtMs","month","increment","orders","finished","handlePosOfflineSync","req","body","Object","fromEntries","query","value","Array","isArray","gate","models","split","model","trim","kit","sales","results","createPosOfflineSyncHandler","res","json","posOfflineSyncHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAE5C,OAAO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zF8P,QAAQhJ,IAAI,CAAC5E,QAAQlG,KAAK,UAAU,gEAAgE;QACtG;IACF;IACA,OAAO;QAAE2F,QAAQ;QAAKqN,MAAM;YAAEc;QAAQ;IAAE;AAC1C;AAEA,OAAO,SAASC,4BACdrR,OAAiCxF,yBAAyB;IAE1D,OAAO,OAAO6V,KAAKiB;QACjB,IAAI;YACF,MAAM/N,UAAU,MAAM6M,qBAAqBpQ,QAAQqQ;YACnD,OAAOiB,IAAIrO,MAAM,CAACM,QAAQN,MAAM,EAAEsO,IAAI,CAAChO,QAAQ+M,IAAI;QACrD,EAAE,OAAOnU,OAAO;YACdC,QAAQD,KAAK,CAAC,6BAA6BA;YAC3C,OAAOmV,IAAIrO,MAAM,CAAC,KAAKsO,IAAI,CAAC;gBAAEpV,OAAO;YAAwC;QAC/E;IACF;AACF;AAEA,OAAO,MAAMqV,wBAAwBH,8BAA6B"}
@@ -96,6 +96,17 @@ export declare function posCardApplicationFeeCents(input: {
96
96
  */
97
97
  direct?: boolean;
98
98
  }): number;
99
+ /**
100
+ * The fee a card taken offline on the app's own reader is captured with
101
+ * (AGL-4039, AGL-4219): a card in person, so the same rule an online reader
102
+ * payment is captured by (`posCaptureFeeCents`). `direct` when the intent
103
+ * was made on the store's own Stripe account, where the fee is the take alone.
104
+ */
105
+ export declare function posOfflineCardFeeCents(input: {
106
+ takeShareCents: number;
107
+ chargeCents: number;
108
+ direct?: boolean;
109
+ }): number;
99
110
  /** A refusal Stripe sent, in words a cashier can read out. */
100
111
  export declare function posStripeErrorMessage(body: {
101
112
  error?: {
@@ -116,6 +116,20 @@ import { NATIVE_CHECKOUT_STRIPE_VERSION } from "./native-checkout.js";
116
116
  direct: true
117
117
  } : {}));
118
118
  }
119
+ /**
120
+ * The fee a card taken offline on the app's own reader is captured with
121
+ * (AGL-4039, AGL-4219): a card in person, so the same rule an online reader
122
+ * payment is captured by (`posCaptureFeeCents`). `direct` when the intent
123
+ * was made on the store's own Stripe account, where the fee is the take alone.
124
+ */ export function posOfflineCardFeeCents(input) {
125
+ return posCardApplicationFeeCents(_extends({
126
+ takeShareCents: input.takeShareCents,
127
+ chargeCents: input.chargeCents,
128
+ inPerson: true
129
+ }, input.direct ? {
130
+ direct: true
131
+ } : {}));
132
+ }
119
133
  /** A refusal Stripe sent, in words a cashier can read out. */ export function posStripeErrorMessage(body, fallback) {
120
134
  var _ref, _ref1;
121
135
  var _body_error, _body_error1;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-stripe.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n saleApplicationFeeCents,\n saleProcessingCostCents,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { NATIVE_CHECKOUT_STRIPE_VERSION } from './native-checkout'\n\n/**\n * The register's Stripe calls (AGL-3607), over raw `fetch` like every other\n * money route in this plugin.\n *\n * ## Pinned to one API version\n *\n * The platform account's default version predates the fields this flow reads\n * — `amount_details.tip` on a PaymentIntent, a reader's `action` — so every\n * request here carries the same `Stripe-Version` the storefront Payment\n * Element pins. Webhook deliveries keep the endpoint's version, which is why\n * the webhook branch never trusts the event's object and re-reads the\n * PaymentIntent through {@link posStripe} instead.\n *\n * ## Every create is keyed\n *\n * A caller passes the idempotency key; Stripe replays the first answer for a\n * repeated key, so a lost response cannot become a second charge.\n */\nexport const POS_STRIPE_VERSION = NATIVE_CHECKOUT_STRIPE_VERSION\n\n/** The currency every register sale is in: the store charges in US dollars. */\nexport const POS_CURRENCY = 'usd'\n\nexport interface PosStripeResult<T = any> {\n ok: boolean\n status: number\n body: T & { error?: { message?: string; code?: string; type?: string } }\n}\n\n/** Form-encodes nested params the way Stripe reads them. */\nexport function posStripeForm(\n params: Record<string, string | number | boolean | undefined | null | readonly string[]>,\n): URLSearchParams {\n const form = new URLSearchParams()\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue\n if (Array.isArray(value)) {\n for (const item of value) form.append(`${key}[]`, String(item))\n } else {\n form.set(key, String(value))\n }\n }\n return form\n}\n\n/** One Stripe API request from the register's server routes. */\nexport async function posStripe<T = any>(\n method: 'GET' | 'POST' | 'DELETE',\n path: string,\n options: {\n params?: Record<string, string | number | boolean | undefined | null | readonly string[]>\n idempotencyKey?: string\n /**\n * The store's own Stripe account, for a store that sells by DIRECT charge\n * (ToS v24 section 10.2(a)): the request is made ON that account with the\n * `Stripe-Account` header, so its Terminal Locations, Readers,\n * Configurations, connection tokens and PaymentIntents all live there.\n * Absent or null, the request is the platform's, exactly as before.\n */\n stripeAccount?: string | null\n } = {},\n): Promise<PosStripeResult<T>> {\n const form = posStripeForm(options.params ?? {})\n const query = method === 'GET' && [...form.keys()].length ? `?${form.toString()}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Stripe-Version': POS_STRIPE_VERSION,\n ...(method === 'POST'\n ? { 'Content-Type': 'application/x-www-form-urlencoded' }\n : {}),\n ...(options.idempotencyKey && method === 'POST'\n ? { 'Idempotency-Key': options.idempotencyKey.slice(0, 255) }\n : {}),\n ...(options.stripeAccount ? { 'Stripe-Account': options.stripeAccount } : {}),\n },\n ...(method === 'POST' ? { body: form.toString() } : {}),\n })\n const body = (await response.json().catch(() => ({}))) as PosStripeResult<T>['body']\n return { ok: response.ok, status: response.status, body }\n}\n\n/** Whether the platform key is a test key: simulated readers only work there. */\nexport function posStripeTestMode(): boolean {\n return String(process.env.STRIPE_SECRET_KEY ?? '').startsWith('sk_test_')\n}\n\n/**\n * Whether Stripe Terminal card readers are offered at all.\n *\n * Always in test mode, where Stripe's simulated reader needs nothing turned\n * on. In live mode only once `STRIPE_TERMINAL_LIVE_ENABLED` is `true`, which\n * is set after Terminal is activated for live payments on the platform's\n * Stripe account. Until then the register and the settings hide every reader\n * control rather than offering hardware that would be refused.\n */\nexport function posTerminalAvailable(): boolean {\n if (!process.env.STRIPE_SECRET_KEY) return false\n return (\n posStripeTestMode() ||\n String(process.env.STRIPE_TERMINAL_LIVE_ENABLED ?? '').toLowerCase() === 'true'\n )\n}\n\n/**\n * The card processing a register CARD payment passes through beside the\n * platform's take (the AGL-2152 rule, on the register's tenders): 2.9% + 30¢,\n * the same online rate a site sale passes through, on a reader's card and a\n * typed card alike (AGL-4198). Every register card payment pins `card` or\n * `card_present`, so no buy-now-pay-later method can be chosen. The base is\n * the whole CHARGE, tip included, because Stripe's own fee is on the whole\n * charge; the platform's take is not.\n */\nexport function posCardProcessingCostCents(chargeCents: number): number {\n return saleProcessingCostCents(chargeCents)\n}\n\n/** The `application_fee_amount` for a register card payment. */\nexport function posCardApplicationFeeCents(input: {\n takeShareCents: number\n chargeCents: number\n /** False for a typed card or a card link, which Stripe prices as online cards. */\n inPerson?: boolean\n /**\n * A DIRECT charge on the store's own account: Stripe bills the store its\n * card fee and charges the platform nothing for the sale, so the fee is the\n * plan's take alone, as on an online direct sale. Never above the charge.\n */\n direct?: boolean\n}): number {\n // The processing half is owed even on a plan whose take is 0%: Stripe debits\n // it from the platform on every destination charge (AGL-2071). The fee never\n // falls below what Stripe charges the platform for the payment (AGL-4198):\n // Terminal's rate for a reader's card, the online rate for a typed card, and\n // the payout either way, all out of the take first.\n return saleApplicationFeeCents(input.takeShareCents, input.chargeCents, {\n inPerson: input.inPerson ?? true,\n ...(input.direct ? { direct: true } : {}),\n })\n}\n\n/** A refusal Stripe sent, in words a cashier can read out. */\nexport function posStripeErrorMessage(\n body: { error?: { message?: string; code?: string } } | undefined,\n fallback: string,\n): string {\n const code = String(body?.error?.code ?? '')\n if (code === 'terminal_reader_offline') {\n return 'The card reader is offline. Check it is on and connected to the internet.'\n }\n if (code === 'terminal_reader_busy') {\n return 'The card reader is busy with another payment. Cancel it on the reader or wait a moment.'\n }\n if (code === 'terminal_reader_timeout') {\n return 'The card reader did not answer in time. Try again.'\n }\n return String(body?.error?.message ?? '') || fallback\n}\n"],"names":["saleApplicationFeeCents","saleProcessingCostCents","NATIVE_CHECKOUT_STRIPE_VERSION","POS_STRIPE_VERSION","POS_CURRENCY","posStripeForm","params","form","URLSearchParams","key","value","Object","entries","undefined","Array","isArray","item","append","String","set","posStripe","method","path","options","query","keys","length","toString","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","idempotencyKey","slice","stripeAccount","body","json","catch","ok","status","posStripeTestMode","startsWith","posTerminalAvailable","STRIPE_TERMINAL_LIVE_ENABLED","toLowerCase","posCardProcessingCostCents","chargeCents","posCardApplicationFeeCents","input","takeShareCents","inPerson","direct","posStripeErrorMessage","fallback","code","error","message"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,uBAAuB,EACvBC,uBAAuB,QAClB,2CAA0C;AACjD,SAASC,8BAA8B,QAAQ,uBAAmB;AAElE;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC,qBAAqBD,+BAA8B;AAEhE,6EAA6E,GAC7E,OAAO,MAAME,eAAe,MAAK;AAQjC,0DAA0D,GAC1D,OAAO,SAASC,cACdC,MAAwF;IAExF,MAAMC,OAAO,IAAIC;IACjB,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACN,QAAS;QACjD,IAAII,UAAUG,aAAaH,UAAU,MAAM;QAC3C,IAAII,MAAMC,OAAO,CAACL,QAAQ;YACxB,KAAK,MAAMM,QAAQN,MAAOH,KAAKU,MAAM,CAAC,GAAGR,IAAI,EAAE,CAAC,EAAES,OAAOF;QAC3D,OAAO;YACLT,KAAKY,GAAG,CAAC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AC3C,OACES,uBACAzB,QAAOc,4CAAAA,QAAQC,GAAG,CAACa,4BAA4B,YAAxCd,4CAA4C,IAAIe,WAAW,OAAO;AAE7E;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,2BAA2BC,WAAmB;IAC5D,OAAOhD,wBAAwBgD;AACjC;AAEA,8DAA8D,GAC9D,OAAO,SAASC,2BAA2BC,KAW1C;QAOaA;IANZ,6EAA6E;IAC7E,6EAA6E;IAC7E,2EAA2E;IAC3E,6EAA6E;IAC7E,oDAAoD;IACpD,OAAOnD,wBAAwBmD,MAAMC,cAAc,EAAED,MAAMF,WAAW,EAAE;QACtEI,QAAQ,GAAEF,kBAAAA,MAAME,QAAQ,YAAdF,kBAAkB;OACxBA,MAAMG,MAAM,GAAG;QAAEA,QAAQ;IAAK,IAAI,CAAC;AAE3C;AAEA,4DAA4D,GAC5D,OAAO,SAASC,sBACdjB,IAAiE,EACjEkB,QAAgB;;QAEIlB,aAUNA;IAVd,MAAMmB,OAAOvC,eAAOoB,yBAAAA,cAAAA,KAAMoB,KAAK,qBAAXpB,YAAamB,IAAI,mBAAI;IACzC,IAAIA,SAAS,2BAA2B;QACtC,OAAO;IACT;IACA,IAAIA,SAAS,wBAAwB;QACnC,OAAO;IACT;IACA,IAAIA,SAAS,2BAA2B;QACtC,OAAO;IACT;IACA,OAAOvC,gBAAOoB,yBAAAA,eAAAA,KAAMoB,KAAK,qBAAXpB,aAAaqB,OAAO,oBAAI,OAAOH;AAC/C"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-stripe.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n saleApplicationFeeCents,\n saleProcessingCostCents,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { NATIVE_CHECKOUT_STRIPE_VERSION } from './native-checkout'\n\n/**\n * The register's Stripe calls (AGL-3607), over raw `fetch` like every other\n * money route in this plugin.\n *\n * ## Pinned to one API version\n *\n * The platform account's default version predates the fields this flow reads\n * — `amount_details.tip` on a PaymentIntent, a reader's `action` — so every\n * request here carries the same `Stripe-Version` the storefront Payment\n * Element pins. Webhook deliveries keep the endpoint's version, which is why\n * the webhook branch never trusts the event's object and re-reads the\n * PaymentIntent through {@link posStripe} instead.\n *\n * ## Every create is keyed\n *\n * A caller passes the idempotency key; Stripe replays the first answer for a\n * repeated key, so a lost response cannot become a second charge.\n */\nexport const POS_STRIPE_VERSION = NATIVE_CHECKOUT_STRIPE_VERSION\n\n/** The currency every register sale is in: the store charges in US dollars. */\nexport const POS_CURRENCY = 'usd'\n\nexport interface PosStripeResult<T = any> {\n ok: boolean\n status: number\n body: T & { error?: { message?: string; code?: string; type?: string } }\n}\n\n/** Form-encodes nested params the way Stripe reads them. */\nexport function posStripeForm(\n params: Record<string, string | number | boolean | undefined | null | readonly string[]>,\n): URLSearchParams {\n const form = new URLSearchParams()\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue\n if (Array.isArray(value)) {\n for (const item of value) form.append(`${key}[]`, String(item))\n } else {\n form.set(key, String(value))\n }\n }\n return form\n}\n\n/** One Stripe API request from the register's server routes. */\nexport async function posStripe<T = any>(\n method: 'GET' | 'POST' | 'DELETE',\n path: string,\n options: {\n params?: Record<string, string | number | boolean | undefined | null | readonly string[]>\n idempotencyKey?: string\n /**\n * The store's own Stripe account, for a store that sells by DIRECT charge\n * (ToS v24 section 10.2(a)): the request is made ON that account with the\n * `Stripe-Account` header, so its Terminal Locations, Readers,\n * Configurations, connection tokens and PaymentIntents all live there.\n * Absent or null, the request is the platform's, exactly as before.\n */\n stripeAccount?: string | null\n } = {},\n): Promise<PosStripeResult<T>> {\n const form = posStripeForm(options.params ?? {})\n const query = method === 'GET' && [...form.keys()].length ? `?${form.toString()}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n 'Stripe-Version': POS_STRIPE_VERSION,\n ...(method === 'POST'\n ? { 'Content-Type': 'application/x-www-form-urlencoded' }\n : {}),\n ...(options.idempotencyKey && method === 'POST'\n ? { 'Idempotency-Key': options.idempotencyKey.slice(0, 255) }\n : {}),\n ...(options.stripeAccount ? { 'Stripe-Account': options.stripeAccount } : {}),\n },\n ...(method === 'POST' ? { body: form.toString() } : {}),\n })\n const body = (await response.json().catch(() => ({}))) as PosStripeResult<T>['body']\n return { ok: response.ok, status: response.status, body }\n}\n\n/** Whether the platform key is a test key: simulated readers only work there. */\nexport function posStripeTestMode(): boolean {\n return String(process.env.STRIPE_SECRET_KEY ?? '').startsWith('sk_test_')\n}\n\n/**\n * Whether Stripe Terminal card readers are offered at all.\n *\n * Always in test mode, where Stripe's simulated reader needs nothing turned\n * on. In live mode only once `STRIPE_TERMINAL_LIVE_ENABLED` is `true`, which\n * is set after Terminal is activated for live payments on the platform's\n * Stripe account. Until then the register and the settings hide every reader\n * control rather than offering hardware that would be refused.\n */\nexport function posTerminalAvailable(): boolean {\n if (!process.env.STRIPE_SECRET_KEY) return false\n return (\n posStripeTestMode() ||\n String(process.env.STRIPE_TERMINAL_LIVE_ENABLED ?? '').toLowerCase() === 'true'\n )\n}\n\n/**\n * The card processing a register CARD payment passes through beside the\n * platform's take (the AGL-2152 rule, on the register's tenders): 2.9% + 30¢,\n * the same online rate a site sale passes through, on a reader's card and a\n * typed card alike (AGL-4198). Every register card payment pins `card` or\n * `card_present`, so no buy-now-pay-later method can be chosen. The base is\n * the whole CHARGE, tip included, because Stripe's own fee is on the whole\n * charge; the platform's take is not.\n */\nexport function posCardProcessingCostCents(chargeCents: number): number {\n return saleProcessingCostCents(chargeCents)\n}\n\n/** The `application_fee_amount` for a register card payment. */\nexport function posCardApplicationFeeCents(input: {\n takeShareCents: number\n chargeCents: number\n /** False for a typed card or a card link, which Stripe prices as online cards. */\n inPerson?: boolean\n /**\n * A DIRECT charge on the store's own account: Stripe bills the store its\n * card fee and charges the platform nothing for the sale, so the fee is the\n * plan's take alone, as on an online direct sale. Never above the charge.\n */\n direct?: boolean\n}): number {\n // The processing half is owed even on a plan whose take is 0%: Stripe debits\n // it from the platform on every destination charge (AGL-2071). The fee never\n // falls below what Stripe charges the platform for the payment (AGL-4198):\n // Terminal's rate for a reader's card, the online rate for a typed card, and\n // the payout either way, all out of the take first.\n return saleApplicationFeeCents(input.takeShareCents, input.chargeCents, {\n inPerson: input.inPerson ?? true,\n ...(input.direct ? { direct: true } : {}),\n })\n}\n\n/**\n * The fee a card taken offline on the app's own reader is captured with\n * (AGL-4039, AGL-4219): a card in person, so the same rule an online reader\n * payment is captured by (`posCaptureFeeCents`). `direct` when the intent\n * was made on the store's own Stripe account, where the fee is the take alone.\n */\nexport function posOfflineCardFeeCents(input: { takeShareCents: number; chargeCents: number; direct?: boolean }): number {\n return posCardApplicationFeeCents({\n takeShareCents: input.takeShareCents,\n chargeCents: input.chargeCents,\n inPerson: true,\n ...(input.direct ? { direct: true } : {}),\n })\n}\n\n/** A refusal Stripe sent, in words a cashier can read out. */\nexport function posStripeErrorMessage(\n body: { error?: { message?: string; code?: string } } | undefined,\n fallback: string,\n): string {\n const code = String(body?.error?.code ?? '')\n if (code === 'terminal_reader_offline') {\n return 'The card reader is offline. Check it is on and connected to the internet.'\n }\n if (code === 'terminal_reader_busy') {\n return 'The card reader is busy with another payment. Cancel it on the reader or wait a moment.'\n }\n if (code === 'terminal_reader_timeout') {\n return 'The card reader did not answer in time. Try again.'\n }\n return String(body?.error?.message ?? '') || fallback\n}\n"],"names":["saleApplicationFeeCents","saleProcessingCostCents","NATIVE_CHECKOUT_STRIPE_VERSION","POS_STRIPE_VERSION","POS_CURRENCY","posStripeForm","params","form","URLSearchParams","key","value","Object","entries","undefined","Array","isArray","item","append","String","set","posStripe","method","path","options","query","keys","length","toString","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","idempotencyKey","slice","stripeAccount","body","json","catch","ok","status","posStripeTestMode","startsWith","posTerminalAvailable","STRIPE_TERMINAL_LIVE_ENABLED","toLowerCase","posCardProcessingCostCents","chargeCents","posCardApplicationFeeCents","input","takeShareCents","inPerson","direct","posOfflineCardFeeCents","posStripeErrorMessage","fallback","code","error","message"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,uBAAuB,EACvBC,uBAAuB,QAClB,2CAA0C;AACjD,SAASC,8BAA8B,QAAQ,uBAAmB;AAElE;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMC,qBAAqBD,+BAA8B;AAEhE,6EAA6E,GAC7E,OAAO,MAAME,eAAe,MAAK;AAQjC,0DAA0D,GAC1D,OAAO,SAASC,cACdC,MAAwF;IAExF,MAAMC,OAAO,IAAIC;IACjB,KAAK,MAAM,CAACC,KAAKC,MAAM,IAAIC,OAAOC,OAAO,CAACN,QAAS;QACjD,IAAII,UAAUG,aAAaH,UAAU,MAAM;QAC3C,IAAII,MAAMC,OAAO,CAACL,QAAQ;YACxB,KAAK,MAAMM,QAAQN,MAAOH,KAAKU,MAAM,CAAC,GAAGR,IAAI,EAAE,CAAC,EAAES,OAAOF;QAC3D,OAAO;YACLT,KAAKY,GAAG,CAACV,KAAKS,OAAOR;QACvB;IACF;IACA,OAAOH;AACT;AAEA,8DAA8D,GAC9D,OAAO,eAAea,UACpBC,MAAiC,EACjCC,IAAY,EACZC,UAWI,CAAC,CAAC;QAEqBA;IAA3B,MAAMhB,OAAOF,eAAckB,kBAAAA,QAAQjB,MAAM,YAAdiB,kBAAkB,CAAC;IAC9C,MAAMC,QAAQH,WAAW,SAAS;WAAId,KAAKkB,IA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IAC7E,6EAA6E;IAC7E,2EAA2E;IAC3E,6EAA6E;IAC7E,oDAAoD;IACpD,OAAOnD,wBAAwBmD,MAAMC,cAAc,EAAED,MAAMF,WAAW,EAAE;QACtEI,QAAQ,GAAEF,kBAAAA,MAAME,QAAQ,YAAdF,kBAAkB;OACxBA,MAAMG,MAAM,GAAG;QAAEA,QAAQ;IAAK,IAAI,CAAC;AAE3C;AAEA;;;;;CAKC,GACD,OAAO,SAASC,uBAAuBJ,KAAwE;IAC7G,OAAOD,2BAA2B;QAChCE,gBAAgBD,MAAMC,cAAc;QACpCH,aAAaE,MAAMF,WAAW;QAC9BI,UAAU;OACNF,MAAMG,MAAM,GAAG;QAAEA,QAAQ;IAAK,IAAI,CAAC;AAE3C;AAEA,4DAA4D,GAC5D,OAAO,SAASE,sBACdlB,IAAiE,EACjEmB,QAAgB;;QAEInB,aAUNA;IAVd,MAAMoB,OAAOxC,eAAOoB,yBAAAA,cAAAA,KAAMqB,KAAK,qBAAXrB,YAAaoB,IAAI,mBAAI;IACzC,IAAIA,SAAS,2BAA2B;QACtC,OAAO;IACT;IACA,IAAIA,SAAS,wBAAwB;QACnC,OAAO;IACT;IACA,IAAIA,SAAS,2BAA2B;QACtC,OAAO;IACT;IACA,OAAOxC,gBAAOoB,yBAAAA,eAAAA,KAAMqB,KAAK,qBAAXrB,aAAasB,OAAO,oBAAI,OAAOH;AAC/C"}
@@ -340,8 +340,15 @@ export declare function retrievePosOfflineCardIntent(paymentIntentId: string, ac
340
340
  } | {
341
341
  ok: false;
342
342
  error: string;
343
+ status: number;
343
344
  }>;
344
- /** Captures one authorized offline card with the platform's fee; a repeat finds the first capture. */
345
+ /**
346
+ * Captures one authorized offline card with the platform's fee, on `account`
347
+ * (a direct-charge store's own, where its app's SDK made it, AGL-4219) or the
348
+ * platform; a repeat finds the first capture. Stripe takes the application
349
+ * fee at capture on a direct charge too, from the store's account to the
350
+ * platform, which is how an online direct reader payment is captured.
351
+ */
345
352
  export declare function capturePosOfflineCardIntent(paymentIntentId: string, applicationFeeCents: number, idempotencyKey: string, account?: string | null): Promise<{
346
353
  ok: true;
347
354
  intent: PosOfflineCardIntent;
@@ -350,6 +357,19 @@ export declare function capturePosOfflineCardIntent(paymentIntentId: string, app
350
357
  error: string;
351
358
  status: number;
352
359
  }>;
360
+ /**
361
+ * Cancels one offline card's authorization on `account` (a direct-charge
362
+ * store's own, or another the device recorded) or the platform, so the
363
+ * customer's hold is released (AGL-4219). The sync asks only for an intent
364
+ * it read as `requires_capture`; Stripe refuses to cancel a captured one.
365
+ */
366
+ export declare function cancelPosOfflineCardIntent(paymentIntentId: string, account: string | null, idempotencyKey: string): Promise<{
367
+ ok: true;
368
+ } | {
369
+ ok: false;
370
+ error: string;
371
+ status: number;
372
+ }>;
353
373
  /**
354
374
  * Turns Stripe's offline mode on for the site's readers, on the site's ONE
355
375
  * Terminal Configuration through {@link savePosReaderConfiguration}, like