@aglyn/plugins-commerce 1.0.0-beta.263 → 1.0.0-beta.266

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 (29) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/product-editor-dialog.component.js +10 -1
  3. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  4. package/src/lib/components/console/products-hub-card.component.js +11 -10
  5. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  6. package/src/lib/server/billing-webhook.js +3 -1
  7. package/src/lib/server/billing-webhook.js.map +1 -1
  8. package/src/lib/server/pos-payment.js +9 -5
  9. package/src/lib/server/pos-payment.js.map +1 -1
  10. package/src/lib/server/pos-terminal.d.ts +12 -1
  11. package/src/lib/server/pos-terminal.js +82 -3
  12. package/src/lib/server/pos-terminal.js.map +1 -1
  13. package/src/lib/server/printers.js +33 -5
  14. package/src/lib/server/printers.js.map +1 -1
  15. package/src/lib/server/product-drafts.js +3 -2
  16. package/src/lib/server/product-drafts.js.map +1 -1
  17. package/src/lib/server/product-writer.js +3 -1
  18. package/src/lib/server/product-writer.js.map +1 -1
  19. package/src/lib/server/products-write.js +3 -2
  20. package/src/lib/server/products-write.js.map +1 -1
  21. package/src/lib/server/returns.js +3 -1
  22. package/src/lib/server/returns.js.map +1 -1
  23. package/src/lib/tenant-emails.js +264 -84
  24. package/src/lib/tenant-emails.js.map +1 -1
  25. package/src/lib/testing/memory-firestore.d.ts +5 -3
  26. package/src/lib/testing/memory-firestore.js +6 -3
  27. package/src/lib/testing/memory-firestore.js.map +1 -1
  28. package/src/lib/transfer/products.server.js +3 -2
  29. package/src/lib/transfer/products.server.js.map +1 -1
@@ -57,7 +57,7 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
57
57
  const action = String((_body_action = body['action']) != null ? _body_action : '');
58
58
  const orderId = String((_body_orderId = body['orderId']) != null ? _body_orderId : '');
59
59
  try {
60
- var _body_paymentId, _body_amountCents, _body_tipCents;
60
+ var _body_paymentId, _body_amountCents, _body_tipCents, _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
61
61
  if (action === 'gift-card-balance') {
62
62
  return await giftCardBalance(staff, body, res);
63
63
  }
@@ -65,7 +65,7 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
65
65
  return await creditLookup(staff, body, res);
66
66
  }
67
67
  if (action === 'context') {
68
- var _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY;
68
+ var _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY1;
69
69
  // What the register needs to draw its tenders: the site's tip and
70
70
  // receipt settings, whether card readers are offered at all, and the
71
71
  // key the typed-card form loads Stripe with.
@@ -93,7 +93,7 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
93
93
  testMode: posStripeTestMode()
94
94
  },
95
95
  readers,
96
- publishableKey: String((_process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) != null ? _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY : ''),
96
+ publishableKey: String((_process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY1 = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) != null ? _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY1 : ''),
97
97
  // A text receipt is offered only when an SMS provider is on (AGL-3610).
98
98
  smsReceipts: pluginSmsAvailable(),
99
99
  // Store credit other plugins keep — rewards (AGL-3640) — offered here.
@@ -197,7 +197,7 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
197
197
  });
198
198
  break;
199
199
  case 'card-keyed':
200
- outcome = await startCardKeyedPayment({
200
+ outcome = await startCardKeyedPayment(_extends({
201
201
  hostId,
202
202
  orderId,
203
203
  paymentId,
@@ -205,7 +205,9 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
205
205
  tipCents,
206
206
  cashierId: staff.uid,
207
207
  org: staff.org
208
- });
208
+ }, body['paymentMethodId'] ? {
209
+ paymentMethodId: String(body['paymentMethodId'])
210
+ } : {}));
209
211
  break;
210
212
  case 'card-link':
211
213
  outcome = await startCardLinkPayment({
@@ -274,6 +276,8 @@ import { cancelPosCardPayment, createCardPresentIntent, refreshPosCardPayment, r
274
276
  clientSecret: outcome.clientSecret
275
277
  } : {}, outcome.paymentIntentId ? {
276
278
  paymentIntentId: outcome.paymentIntentId
279
+ } : {}, action === 'card-keyed' && outcome.clientSecret ? {
280
+ publishableKey: String((_process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY = process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) != null ? _process_env_NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY : '')
277
281
  } : {}));
278
282
  } catch (error) {
279
283
  console.error('[pos-payment]', action, error);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-payment.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 consumeRateLimit,\n firebaseAdmin,\n getPluginConfig,\n} from '@aglyn/tenant-data-admin'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport { pluginSmsAvailable } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport {\n checkoutCreditProvider,\n checkoutCreditProviderForCode,\n normalizeCheckoutCreditAccount,\n normalizeCheckoutCreditCode,\n offeredCheckoutCredits,\n type CheckoutCreditStage,\n} from '@aglyn/aglyn/plugin-manager/plugin-checkout-credits'\nimport { finishPosDisplayReceipt } from './pos-display'\nimport * as CommerceModel from '../model'\nimport { posRegisterSettings } from '../plugin-config'\nimport { posOpsSettings } from '../pos-ops-config'\nimport {\n authorizePosStaff,\n posIdempotencyKey,\n posQueryBody,\n posRequestBody,\n type PosStaff,\n} from './pos-auth'\nimport {\n applyPosPayment,\n deliverChosenPosReceipt,\n posPaymentId,\n posSaleSummary,\n readPosSale,\n releasePosSaleDiscount,\n type PosLiftedOrder,\n type PosPaymentOutcome,\n} from './pos-sale'\nimport { posPaymentCashierId } from './pos-sale-stamp'\nimport { printPosSaleReceipt } from './pos-print'\nimport {\n POS_CURRENCY,\n posStripe,\n posStripeErrorMessage,\n posStripeTestMode,\n posTerminalAvailable,\n} from './pos-stripe'\nimport {\n cancelPosCardPayment,\n createCardPresentIntent,\n refreshPosCardPayment,\n retryCardPresentPayment,\n simulatePosReaderTap,\n startCardKeyedPayment,\n startCardLinkPayment,\n startCardPresentPayment,\n} from './pos-terminal'\n\n/**\n * `POST /api/commerce/pos-payment` (AGL-3607): every tender against an OPEN\n * register sale, one `action` per request.\n *\n * The sale was priced by `pos-order.ts` (`payment: 'open'`); nothing here\n * re-prices it or lets the register name a total. Each payment-starting action\n * needs the register's `Idempotency-Key`, from which the payment's id is\n * derived: pressing a tender twice, or retrying after a lost response, finds\n * the payment the first press started instead of taking the money twice.\n */\nexport const posPaymentHandler: PluginApiHandler = async (req, res) => {\n // `sale` is a read and may be a GET, so a register re-reading its sale does\n // not spend the console's write budget; everything else moves money.\n const body = req.method === 'GET' ? posQueryBody(req) : posRequestBody(req)\n if (\n !(\n req.method === 'POST' ||\n (req.method === 'GET' && (body['action'] === 'sale' || body['action'] === 'context'))\n )\n ) {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(body['hostId'] ?? '')\n const gate = await authorizePosStaff(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n let staff = gate.staff\n const action = String(body['action'] ?? '')\n const orderId = String(body['orderId'] ?? '')\n try {\n if (action === 'gift-card-balance') {\n return await giftCardBalance(staff, body, res)\n }\n if (action === 'credit-lookup') {\n return await creditLookup(staff, body, res)\n }\n if (action === 'context') {\n // What the register needs to draw its tenders: the site's tip and\n // receipt settings, whether card readers are offered at all, and the\n // key the typed-card form loads Stripe with.\n const readers = posTerminalAvailable()\n ? (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminalReaders')\n .limit(50)\n .get()\n ).docs.map((doc: any) => ({\n id: doc.id as string,\n label: String(doc.get('label') ?? 'Card reader'),\n registerId: (doc.get('registerId') as string | undefined) ?? null,\n status: String(doc.get('status') ?? 'offline'),\n livemode: Boolean(doc.get('livemode')),\n }))\n : []\n const config = await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId })\n return res.status(200).json({\n settings: posRegisterSettings(config),\n // The register's own rules (AGL-3609): the shift it requires, the\n // idle lock and the refund limit. The console reads the same config\n // client-side; the native apps read it here.\n ops: posOpsSettings(config),\n terminal: { available: posTerminalAvailable(), testMode: posStripeTestMode() },\n readers,\n publishableKey: String(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ''),\n // A text receipt is offered only when an SMS provider is on (AGL-3610).\n smsReceipts: pluginSmsAvailable(),\n // Store credit other plugins keep — rewards (AGL-3640) — offered here.\n credits: await offeredCheckoutCredits({ hostId, channel: 'pos' }),\n })\n }\n if (!orderId) return res.status(400).json({ error: 'Missing orderId' })\n const startsPayment = [\n 'card-present-sdk',\n 'cash',\n 'gift-card',\n 'credit',\n 'folio',\n 'card-present',\n 'card-keyed',\n 'card-link',\n ].includes(action)\n const attemptKey = posIdempotencyKey(req)\n if (startsPayment && !attemptKey) {\n return res.status(400).json({ error: 'Missing Idempotency-Key' })\n }\n const paymentId = startsPayment\n ? posPaymentId(orderId, attemptKey)\n : String(body['paymentId'] ?? '')\n // The cashier a PIN switched in takes the payment (AGL-3609).\n if (startsPayment && body['cashierAssertion']) {\n staff = {\n ...staff,\n uid: await posPaymentCashierId({\n hostId,\n orderId,\n signedInUid: staff.uid,\n assertion: body['cashierAssertion'],\n }),\n }\n }\n const amountCents = Math.round(Number(body['amountCents'] ?? 0))\n const tipCents = Math.round(Number(body['tipCents'] ?? 0)) || 0\n const settings = posRegisterSettings(\n await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId }),\n )\n let outcome: (PosPaymentOutcome & { clientSecret?: string; paymentIntentId?: string }) | null = null\n switch (action) {\n case 'sale': {\n const order = await readPosSale(hostId, orderId)\n if (!order) return res.status(404).json({ error: 'Unknown sale' })\n outcome = { ok: true, order, payment: null, completed: false, changed: false }\n break\n }\n case 'cash':\n outcome = await takeCash(staff, orderId, paymentId, body, tipCents)\n break\n case 'gift-card':\n outcome = await takeGiftCard(staff, orderId, paymentId, body)\n break\n case 'credit':\n outcome = await takeCredit(staff, orderId, paymentId, body)\n break\n case 'folio':\n outcome = await takeFolio(staff, orderId, paymentId, body)\n break\n case 'card-present':\n outcome = await startCardPresentPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n readerId: String(body['readerId'] ?? ''),\n settings,\n })\n break\n case 'card-present-sdk':\n // Collected by a native app's Stripe Terminal SDK (Tap to Pay or a\n // Bluetooth reader, AGL-3618) against this server-made intent; it\n // settles exactly like a smart-reader payment.\n outcome = await createCardPresentIntent({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n })\n break\n case 'card-keyed':\n outcome = await startCardKeyedPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n })\n break\n case 'card-link':\n outcome = await startCardLinkPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n returnUrl: await registerReturnUrl(req.headers.host, hostId, staff),\n })\n break\n case 'status':\n outcome = await refreshPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'cancel':\n outcome = await cancelPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'retry':\n outcome = await retryCardPresentPayment({ hostId, orderId, paymentId, settings })\n break\n case 'simulate':\n outcome = await simulatePosReaderTap({\n hostId,\n orderId,\n paymentId,\n cardNumber: String(body['cardNumber'] ?? ''),\n })\n break\n case 'void':\n outcome = await voidPosSale(staff, orderId)\n break\n case 'receipt':\n outcome = await recordReceiptChoice(staff, orderId, body)\n break\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n if ('error' in outcome) return res.status(outcome.status).json({ error: outcome.error })\n return res.status(200).json({\n sale: posSaleSummary(outcome.order),\n ...(outcome.payment ? { paymentId: outcome.payment.id } : {}),\n completed: outcome.order.status === 'paid',\n ...(outcome.clientSecret ? { clientSecret: outcome.clientSecret } : {}),\n ...(outcome.paymentIntentId ? { paymentIntentId: outcome.paymentIntentId } : {}),\n })\n } catch (error) {\n console.error('[pos-payment]', action, error)\n return res.status(500).json({ error: 'Payment failed — check the sale before trying again' })\n }\n}\n\n/** Where a QR payment page sends the customer back to: the register. */\nasync function registerReturnUrl(\n requestHost: string | string[] | undefined,\n hostId: string,\n staff: PosStaff,\n): Promise<string> {\n const origin = `https://${String(requestHost ?? '')}`\n const subdomain = (\n await firebaseAdmin.app().firestore().collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const orgSlug = staff.org?.['slug'] as string | undefined\n return orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, { orgSlug, host: subdomain, pluginSlug: 'pos' })}`\n : origin\n}\n\n/** The balance a new tender may take, or a refusal. */\nfunction tenderable(\n order: PosLiftedOrder,\n payments: CommerceModel.OrderPayment[],\n): number {\n return CommerceModel.posTenderableCents(Number(order.totals?.totalCents ?? 0), payments)\n}\n\nconst NOT_OPEN = { kind: 'refuse' as const, status: 409, error: 'This sale is no longer open' }\n\n/**\n * Cash: the amount defaults to whatever is left, the change is what the\n * customer handed over beyond it (and beyond any tip they chose).\n */\nasync function takeCash(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n tipCents: number,\n): Promise<PosPaymentOutcome> {\n const tenderedCents = Math.round(Number(body['tenderedCents'] ?? 0))\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n decide: ({ order, payments, existing }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!Number.isFinite(tenderedCents) || tenderedCents <= 0) {\n return { kind: 'refuse', status: 400, error: 'Enter the cash received.' }\n }\n const open = tenderable(order, payments)\n if (open <= 0) return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n const amountCents =\n askedCents > 0 ? Math.min(askedCents, open) : Math.min(open, Math.max(0, tenderedCents - tipCents))\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 400, error: 'The cash received does not cover the tip.' }\n }\n const tipProblem = CommerceModel.posTipProblem(tipCents, amountCents)\n if (tipProblem) return { kind: 'refuse', status: 400, error: tipProblem }\n if (tenderedCents < amountCents + tipCents) {\n return { kind: 'refuse', status: 400, error: 'Cash received is short' }\n }\n const total = Number(order.totals?.totalCents ?? 0)\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'cash',\n amountCents,\n ...(tipCents > 0 ? { tipCents } : {}),\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n cashTenderedCents: tenderedCents,\n changeCents: tenderedCents - amountCents - tipCents,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: total,\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n })\n}\n\nfunction giftCardRef(hostId: string, code: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('giftCards')\n .doc(code)\n}\n\n/** A gift card's spendable balance, for the cashier to read to the customer. */\nasync function giftCardBalance(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n): Promise<void> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n const rate = await consumeRateLimit(`pos-gift-balance:${staff.uid}`, {\n limit: 30,\n windowMs: 60_000,\n })\n if (!rate.allowed) {\n return res.status(429).json({ error: 'Too many balance checks. Wait a minute and try again.' })\n }\n if (CommerceModel.giftCardCodeProblem(code)) {\n return res.status(404).json({ error: 'No gift card has that code.' })\n }\n const snapshot = await giftCardRef(staff.hostId, code).get()\n if (!snapshot.exists) return res.status(404).json({ error: 'No gift card has that code.' })\n const card = snapshot.data() as CommerceModel.HostGiftCard\n return res.status(200).json({\n availableCents: CommerceModel.giftCardAvailableCents(card, Date.now()),\n frozen: CommerceModel.isGiftCardFrozen(card),\n voided: Number(card.voidedAtMs) > 0,\n last4: code.slice(-4),\n })\n}\n\n/**\n * A gift card: takes the smaller of what the card can give and what is left\n * to pay, in ONE transaction with the sale. The card's spendable balance\n * honours every live hold an online checkout placed on it (AGL-2449), and a\n * frozen card gives nothing (AGL-3363), so the till and the website can\n * never spend the same dollars.\n */\nasync function takeGiftCard(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n if (CommerceModel.giftCardCodeProblem(code)) {\n return { ok: false, status: 404, error: 'No gift card has that code.' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const cardRef = giftCardRef(staff.hostId, code)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => {\n const snapshot = await transaction.get(cardRef)\n return snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null\n },\n decide: ({ order, payments, existing, context: card }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!card) return { kind: 'refuse', status: 404, error: 'No gift card has that code.' }\n const available = CommerceModel.giftCardAvailableCents(card, Date.now())\n if (available <= 0) {\n return {\n kind: 'refuse',\n status: 409,\n error: CommerceModel.isGiftCardFrozen(card)\n ? 'This gift card is on hold and cannot be used right now.'\n : 'This gift card has no balance left.',\n }\n }\n const open = tenderable(order, payments)\n const amountCents = Math.min(available, open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'gift_card',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n giftCardId: code,\n last4: code.slice(-4),\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n write: (transaction, card, payment) => {\n transaction.set(\n cardRef,\n {\n balanceCents: Math.max(0, Number(card?.balanceCents ?? 0) - payment.amountCents),\n lastUsedAtMs: Date.now(),\n },\n { merge: true },\n )\n },\n })\n}\n\n/**\n * Staff search for a store-credit account at the register (AGL-3640): a\n * customer's email or code, answered by the plugin that keeps the account.\n * Only staff reach it — `authorizePosStaff` above — so a provider may look\n * accounts up by email here, which it never does for a shopper.\n */\nasync function creditLookup(staff: PosStaff, body: Record<string, any>, res: any) {\n const entry = checkoutCreditProvider(String(body['providerId'] ?? ''))\n if (!entry?.provider.lookup) return res.status(404).json({ error: 'That kind of credit is not taken here.' })\n const rate = await consumeRateLimit(`pos-credit-lookup:${staff.uid}`, {\n limit: 60,\n windowMs: 60_000,\n })\n if (!rate.allowed) return res.status(429).json({ error: 'Too many lookups. Wait a moment.' })\n if (!(await entry.provider.offered({ hostId: staff.hostId, channel: 'pos' }).catch(() => false))) {\n return res.status(404).json({ error: 'That kind of credit is not taken here.' })\n }\n const found = await entry.provider\n .lookup({ hostId: staff.hostId, query: String(body['query'] ?? '').slice(0, 120) })\n .catch((error: unknown) => {\n console.error('[pos-payment] credit lookup failed', entry.providerId, error)\n return []\n })\n const accounts = found\n .slice(0, 10)\n .map((account) => normalizeCheckoutCreditAccount(account))\n .filter((account) => !('error' in account))\n return res.status(200).json({ providerId: entry.providerId, accounts })\n}\n\n/**\n * Store credit another plugin keeps (AGL-3640) — a rewards balance, a friend's\n * referral credit — by the customer's code, or by the account a staff lookup\n * found. The provider's stage reads the account INSIDE the sale's transaction\n * and its debit writes there, so the credit is taken with the payment or not\n * at all; a retried press finds its own payment and takes nothing more.\n */\nasync function takeCredit(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const code = normalizeCheckoutCreditCode(body['code'])\n const entry = code\n ? checkoutCreditProviderForCode(code)\n : checkoutCreditProvider(String(body['providerId'] ?? ''))\n if (!entry) return { ok: false, status: 404, error: 'That code is not one this store takes.' }\n if (!(await entry.provider.offered({ hostId: staff.hostId, channel: 'pos' }).catch(() => false))) {\n return { ok: false, status: 404, error: 'That kind of credit is not taken here.' }\n }\n const sale = await readPosSale(staff.hostId, orderId)\n if (!sale) return { ok: false, status: 404, error: 'Unknown sale' }\n const account = normalizeCheckoutCreditAccount(\n await entry.provider\n .resolve({\n hostId: staff.hostId,\n ...(code ? { code } : { reference: String(body['reference'] ?? '') }),\n channel: 'pos',\n customerEmail: (sale as { customerEmail?: string | null }).customerEmail ?? null,\n staff: true,\n })\n .catch((error: unknown) => {\n console.error('[pos-payment] credit resolve failed', entry.providerId, error)\n return null\n }),\n )\n if ('error' in account) return { ok: false, status: account.status, error: account.error }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n return await applyPosPayment<CheckoutCreditStage | null>({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) =>\n entry.provider.stage({\n transaction,\n hostId: staff.hostId,\n reference: account.reference,\n orderId,\n nowMs: Date.now(),\n }),\n decide: ({ order, payments, existing, context: stage }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!stage) return { kind: 'refuse', status: 404, error: `That ${account.label.toLowerCase()} account no longer exists.` }\n const open = tenderable(order, payments)\n if (open <= 0) return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n const amountCents = Math.min(stage.availableCents, open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: `This ${account.label.toLowerCase()} account has nothing to spend.` }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'credit',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n creditProviderId: entry.providerId,\n creditReference: account.reference,\n creditLabel: account.label,\n ...(account.last4 ? { last4: account.last4 } : {}),\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n write: (_transaction, stage, payment) => {\n // The stage writes through the sale's own transaction. Taking less than\n // the payment records would leave the sale paid by money that did not\n // move, so a short debit aborts the whole commit instead.\n const taken = stage ? stage.debit({ cents: payment.amountCents, key: payment.id, orderId, channel: 'pos' }) : 0\n if (taken !== payment.amountCents) {\n throw new Error(`credit debit ${taken} short of payment ${payment.amountCents}`)\n }\n },\n })\n}\n\nfunction reservationRef(hostId: string, reservationId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('reservations')\n .doc(reservationId)\n}\n\n/** Charged to a checked-in stay's folio, in the same commit as the payment. */\nasync function takeFolio(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const reservationId = String(body['reservationId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(reservationId)) {\n return { ok: false, status: 400, error: 'Pick a reservation' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const stayRef = reservationRef(staff.hostId, reservationId)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => (await transaction.get(stayRef)).exists as boolean,\n decide: ({ order, payments, existing, context: stayExists }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!stayExists) return { kind: 'refuse', status: 404, error: 'Unknown reservation' }\n const open = tenderable(order, payments)\n const amountCents = Math.min(open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'folio',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n reservationId,\n folioAtMs: now,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n event: { event: 'folio', detail: `Charged to reservation ${reservationId}` },\n }\n },\n write: (transaction, _stay, payment) => {\n // `update`, never a merge-set: a missing stay must not be minted as a\n // stub holding one folio line (AGL-1760). It exists — read above.\n transaction.update(stayRef, {\n folio: firebaseAdmin.firestore.FieldValue.arrayUnion({\n orderId,\n paymentId: payment.id,\n amountCents: payment.amountCents,\n note: 'Register sale',\n atMs: payment.folioAtMs ?? Date.now(),\n }),\n })\n },\n })\n}\n\n/**\n * Abandons an open sale: everything it took is handed back first — cards\n * refunded in full (tip included, fee and transfer reversed), gift cards\n * re-credited, the room charge taken off the folio, cash marked as returned —\n * and only then is the order cancelled. A refund Stripe refuses stops the void\n * with the sale still open and its payment still recorded, never cancelled\n * over money that did not come back.\n */\nexport async function voidPosSale(\n staff: PosStaff,\n orderId: string,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n const order = await readPosSale(hostId, orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.status === 'cancelled') return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status !== 'pending' || !Array.isArray(order.payments)) {\n return {\n ok: false,\n status: 409,\n error: 'This sale is already paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(order)) {\n if (payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method)) {\n const cancelled = await cancelPosCardPayment({ hostId, orderId, paymentId: payment.id })\n if (!cancelled.ok) return cancelled\n }\n }\n // Re-read after the cancels: one may have completed the sale in the gap.\n const current = await readPosSale(hostId, orderId)\n if (!current) return { ok: false, status: 404, error: 'Unknown sale' }\n if (current.status !== 'pending') {\n return {\n ok: false,\n status: 409,\n error: 'The last card payment went through and the sale is paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(current)) {\n if (payment.status !== 'succeeded') continue\n const reversed = await reversePayment(staff, current, payment)\n if (!reversed.ok) return reversed\n }\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(hostId).collection('orders').doc(orderId)\n const cancelled = await firestore.runTransaction(async (transaction: any) => {\n const fresh = {\n ...(CommerceModel.liftLegacyOrder(((await transaction.get(orderRef)).data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.status !== 'pending') return null\n const open = CommerceModel.orderPayments(fresh).some(\n (payment) => payment.status === 'pending' || payment.status === 'succeeded',\n )\n if (open) return null\n const next = {\n ...fresh,\n status: 'cancelled' as const,\n timeline: CommerceModel.appendOrderEvent(fresh, 'pos-sale-voided', 'Voided at the register'),\n }\n transaction.set(\n orderRef,\n {\n status: 'cancelled',\n cancelledAtMs: Date.now(),\n timeline: next.timeline,\n ...CommerceModel.orderListFields(next, orderId),\n },\n { merge: true },\n )\n return next\n })\n if (!cancelled) {\n return { ok: false, status: 409, error: 'A payment on this sale changed. Check it and try again.' }\n }\n await releasePosSaleDiscount(hostId, current)\n return { ok: true, order: cancelled, payment: null, completed: false, changed: true }\n}\n\n/** Hands one settled payment back, recording `reversed` in the same commit. */\nasync function reversePayment(\n staff: PosStaff,\n order: PosLiftedOrder,\n payment: CommerceModel.OrderPayment,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n if (CommerceModel.isCardPaymentMethod(payment.method)) {\n if (!payment.paymentIntentId) {\n return { ok: false, status: 409, error: 'A card payment on this sale has no charge to refund.' }\n }\n const refund = await posStripe('POST', 'refunds', {\n idempotencyKey: `pos-void:${payment.id}`,\n params: {\n payment_intent: payment.paymentIntentId,\n reverse_transfer: true,\n refund_application_fee: true,\n 'metadata[kind]': 'pos-void',\n 'metadata[orderId]': order.$id,\n },\n })\n if (!refund.ok) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(refund.body, 'The card refund failed. The sale is still open.'),\n }\n }\n }\n const cardRef = payment.giftCardId ? giftCardRef(hostId, payment.giftCardId) : null\n const stayRef = payment.reservationId ? reservationRef(hostId, payment.reservationId) : null\n // Store credit goes back to the plugin that keeps it (AGL-3640), in the\n // same commit as the reversal. A provider that is gone cannot take it\n // back, so the void stops with the sale still open rather than cancelling\n // over credit that did not come back.\n const creditEntry =\n payment.method === 'credit' && payment.creditProviderId ? checkoutCreditProvider(payment.creditProviderId) : null\n if (payment.method === 'credit' && (!creditEntry || !payment.creditReference)) {\n return {\n ok: false,\n status: 409,\n error: 'The store credit on this sale cannot be handed back right now. The sale is still open.',\n }\n }\n return await applyPosPayment({\n hostId,\n orderId: order.$id,\n paymentId: payment.id,\n prepare: async (transaction) => {\n if (payment.method === 'gift_card' && cardRef) {\n const snapshot = await transaction.get(cardRef)\n return { card: snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null, folio: null, credit: null }\n }\n if (payment.method === 'folio' && stayRef) {\n const snapshot = await transaction.get(stayRef)\n return { card: null, folio: snapshot.exists ? ((snapshot.get('folio') ?? []) as any[]) : null, credit: null }\n }\n if (payment.method === 'credit' && creditEntry && payment.creditReference) {\n const credit = await creditEntry.provider.stage({\n transaction,\n hostId,\n reference: payment.creditReference,\n orderId: order.$id,\n nowMs: Date.now(),\n })\n return { card: null, folio: null, credit }\n }\n return { card: null, folio: null, credit: null }\n },\n decide: ({ existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n if (existing.status !== 'succeeded') return { kind: 'keep' }\n return {\n kind: 'put',\n payment: { ...existing, status: 'reversed' },\n event: {\n event: 'pos-payment-reversed',\n detail:\n existing.method === 'cash'\n ? `${CommerceModel.describeOrderPayment(existing)} handed back in cash`\n : `${CommerceModel.describeOrderPayment(existing)} returned`,\n },\n }\n },\n write: (transaction, context, reversed) => {\n if (reversed.method === 'gift_card' && cardRef && context.card) {\n transaction.set(\n cardRef,\n { balanceCents: Number(context.card.balanceCents ?? 0) + reversed.amountCents },\n { merge: true },\n )\n }\n if (reversed.method === 'folio' && stayRef && context.folio) {\n transaction.update(stayRef, {\n folio: context.folio.filter((entry) => entry?.paymentId !== reversed.id),\n })\n }\n if (reversed.method === 'credit' && context.credit) {\n context.credit.reverse({ key: reversed.id, orderId: order.$id })\n }\n },\n })\n}\n\n/** A repeat of the same receipt choice inside this window sends nothing more. */\nconst RECEIPT_REPEAT_WINDOW_MS = 2 * 60 * 1000\n\n/**\n * How the customer wants their receipt, from the cashier or the customer\n * display. Kept on the order; an email chosen after the sale is paid is sent\n * at once, and one chosen before is sent when it completes.\n */\nexport async function recordReceiptChoice(\n staff: PosStaff,\n orderId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const channel = String(body['channel'] ?? '') as CommerceModel.PosReceiptChannel\n if (!['email', 'sms', 'print', 'none'].includes(channel)) {\n return { ok: false, status: 400, error: 'Choose email, text, print or no receipt.' }\n }\n const to =\n channel === 'email'\n ? CommerceModel.posDisplayEmail(body['to'])\n : channel === 'sms'\n ? CommerceModel.posDisplayPhone(body['to'])\n : ''\n if ((channel === 'email' || channel === 'sms') && !to) {\n return {\n ok: false,\n status: 400,\n error: channel === 'email' ? 'Enter a valid email address.' : 'Enter a valid phone number.',\n }\n }\n if (channel === 'sms' && !pluginSmsAvailable()) {\n return { ok: false, status: 409, error: 'Text receipts are not set up for this store.' }\n }\n const marketingOptIn = channel === 'email' && body['marketingOptIn'] === true\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(staff.hostId).collection('orders').doc(orderId)\n const order = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return null\n const fresh = {\n ...(CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.channel !== 'pos') return null\n // The same choice twice in a row (a double tap, or the display and the\n // cashier answering together) is one receipt, not two.\n const previous = fresh.receiptRequest\n if (\n fresh.status === 'paid' &&\n previous &&\n previous.channel === channel &&\n String(previous.to ?? '') === to &&\n Date.now() - Number(previous.atMs ?? 0) < RECEIPT_REPEAT_WINDOW_MS\n ) {\n return { ...fresh, repeated: true } as PosLiftedOrder & { repeated?: boolean }\n }\n const receiptRequest = {\n channel,\n ...(to ? { to } : {}),\n ...(marketingOptIn ? { marketingOptIn: true } : {}),\n atMs: Date.now(),\n }\n transaction.set(\n orderRef,\n {\n receiptRequest,\n ...(channel === 'email' && !fresh.customerEmail\n ? {\n customerEmail: to,\n ...CommerceModel.orderListFields({ ...fresh, customerEmail: to }, orderId),\n }\n : {}),\n // The receipt door texts `customerPhone` (AGL-3610).\n ...(channel === 'sms' ? { customerPhone: to } : {}),\n },\n { merge: true },\n )\n return { ...fresh, receiptRequest } as PosLiftedOrder & { repeated?: boolean }\n })\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.repeated) return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status === 'paid' && channel === 'print') {\n // Chosen after the sale completed: printed now on the register's receipt\n // printer, under the sale's own key so it never prints twice (AGL-3609).\n await printPosSaleReceipt(staff.hostId, orderId)\n }\n // A kiosk's own receipt screen (AGL-3623) is not the register's display:\n // the display may be asking the cashier's customer right now.\n if (order.status === 'paid' && order.registerId && order.posSource !== 'kiosk') {\n // The customer has answered (or the cashier for them): the display says\n // thank you and drops the address they typed (AGL-3608).\n await finishPosDisplayReceipt(staff.hostId, order.registerId).catch((error: unknown) =>\n console.error('[pos-payment] display finish failed', error),\n )\n }\n if (order.status === 'paid' && (channel === 'email' || channel === 'sms')) {\n // Chosen after the sale completed: sent now, to where they said.\n const sent = await deliverChosenPosReceipt(\n { hostId: staff.hostId, orderId },\n { channel, to, orderEmail: String(order.customerEmail ?? '') },\n )\n if (channel === 'email') {\n await recordCapturedContact({\n orgId: '',\n hostId: staff.hostId,\n identity: { email: to },\n surface: 'relationship',\n lifecycleFloor: 'customer',\n ...(marketingOptIn ? { marketingConsent: true } : {}),\n interaction: {\n source: 'order',\n refId: orderId,\n summary: `In-store purchase (${CommerceModel.formatReceiptMoney(\n Number(order.totals?.totalCents ?? 0),\n POS_CURRENCY,\n )})`,\n },\n }).catch((error: unknown) => console.error('[pos-payment] contact capture failed', error))\n }\n if (sent !== 'sent') {\n // A failed send is not a repeat: the cashier's retry goes out.\n await orderRef\n .set({ receiptRequest: { atMs: 0 } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-payment] receipt retry reset failed', error))\n }\n if (sent === 'not_configured') {\n return {\n ok: false,\n status: 409,\n error: channel === 'sms' ? 'Text receipts are not set up for this store.' : 'Email is not set up.',\n }\n }\n if (sent !== 'sent') return { ok: false, status: 502, error: 'The receipt could not be sent.' }\n }\n return { ok: true, order, payment: null, completed: false, changed: true }\n}\n"],"names":["consumeRateLimit","firebaseAdmin","getPluginConfig","buildRoute","Route","recordCapturedContact","pluginSmsAvailable","checkoutCreditProvider","checkoutCreditProviderForCode","normalizeCheckoutCreditAccount","normalizeCheckoutCreditCode","offeredCheckoutCredits","finishPosDisplayReceipt","CommerceModel","posRegisterSettings","posOpsSettings","authorizePosStaff","posIdempotencyKey","posQueryBody","posRequestBody","applyPosPayment","deliverChosenPosReceipt","posPaymentId","posSaleSummary","readPosSale","releasePosSaleDiscount","posPaymentCashierId","printPosSaleReceipt","POS_CURRENCY","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","cancelPosCardPayment","createCardPresentIntent","refreshPosCardPayment","retryCardPresentPayment","simulatePosReaderTap","startCardKeyedPayment","startCardLinkPayment","startCardPresentPayment","posPaymentHandler","req","res","body","method","status","json","error","hostId","String","gate","staff","action","orderId","giftCardBalance","creditLookup","process","readers","app","firestore","collection","doc","limit","get","docs","map","id","label","registerId","livemode","Boolean","config","orgId","undefined","settings","ops","terminal","available","testMode","publishableKey","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","smsReceipts","credits","channel","startsPayment","includes","attemptKey","paymentId","uid","signedInUid","assertion","amountCents","Math","round","Number","tipCents","outcome","order","ok","payment","completed","changed","takeCash","takeGiftCard","takeCredit","takeFolio","cashierId","org","readerId","returnUrl","registerReturnUrl","headers","host","cardNumber","voidPosSale","recordReceiptChoice","sale","clientSecret","paymentIntentId","console","requestHost","origin","subdomain","orgSlug","HOST_PLUGIN","pluginSlug","tenderable","payments","posTenderableCents","totals","totalCents","NOT_OPEN","kind","tenderedCents","askedCents","decide","existing","isFinite","open","min","max","tipProblem","posTipProblem","total","now","Date","atMs","settledAtMs","cashTenderedCents","changeCents","takeFeeCents","posTakeShareCents","posTakeFeeCents","feeCents","giftCardRef","code","giftCardCodeOf","rate","windowMs","allowed","giftCardCodeProblem","snapshot","exists","card","data","availableCents","giftCardAvailableCents","frozen","isGiftCardFrozen","voided","voidedAtMs","last4","slice","cardRef","prepare","transaction","context","giftCardId","write","set","balanceCents","lastUsedAtMs","merge","entry","provider","lookup","offered","catch","found","query","providerId","accounts","account","filter","resolve","reference","customerEmail","stage","nowMs","toLowerCase","creditProviderId","creditReference","creditLabel","_transaction","taken","debit","cents","key","Error","reservationRef","reservationId","test","stayRef","stayExists","folioAtMs","event","detail","_stay","update","folio","FieldValue","arrayUnion","note","Array","isArray","orderPayments","isCardPaymentMethod","cancelled","current","reversed","reversePayment","orderRef","runTransaction","fresh","liftLegacyOrder","$id","some","next","timeline","appendOrderEvent","cancelledAtMs","orderListFields","refund","idempotencyKey","params","payment_intent","reverse_transfer","refund_application_fee","creditEntry","credit","describeOrderPayment","reverse","RECEIPT_REPEAT_WINDOW_MS","to","posDisplayEmail","posDisplayPhone","marketingOptIn","previous","receiptRequest","repeated","customerPhone","posSource","sent","orderEmail","identity","email","surface","lifecycleFloor","marketingConsent","interaction","source","refId","summary","formatReceiptMoney"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,aAAa,EACbC,eAAe,QACV,2BAA0B;AACjC,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAC9E,OAAOC,2BAA2B,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SACEC,sBAAsB,EACtBC,6BAA6B,EAC7BC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,sBAAsB,QAEjB,sDAAqD;AAC5D,SAASC,uBAAuB,QAAQ,mBAAe;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,cAAc,QAAQ,uBAAmB;AAClD,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,YAAY,EACZC,cAAc,QAET,gBAAY;AACnB,SACEC,eAAe,EACfC,uBAAuB,EACvBC,YAAY,EACZC,cAAc,EACdC,WAAW,EACXC,sBAAsB,QAGjB,gBAAY;AACnB,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,mBAAmB,QAAQ,iBAAa;AACjD,SACEC,YAAY,EACZC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,oBAAo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/src/lib/server/pos-payment.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 consumeRateLimit,\n firebaseAdmin,\n getPluginConfig,\n} from '@aglyn/tenant-data-admin'\nimport { buildRoute, Route, type PluginApiHandler } from '@aglyn/aglyn/server'\nimport recordCapturedContact from '@aglyn/aglyn/plugin-manager/record-captured-contact'\nimport { pluginSmsAvailable } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport {\n checkoutCreditProvider,\n checkoutCreditProviderForCode,\n normalizeCheckoutCreditAccount,\n normalizeCheckoutCreditCode,\n offeredCheckoutCredits,\n type CheckoutCreditStage,\n} from '@aglyn/aglyn/plugin-manager/plugin-checkout-credits'\nimport { finishPosDisplayReceipt } from './pos-display'\nimport * as CommerceModel from '../model'\nimport { posRegisterSettings } from '../plugin-config'\nimport { posOpsSettings } from '../pos-ops-config'\nimport {\n authorizePosStaff,\n posIdempotencyKey,\n posQueryBody,\n posRequestBody,\n type PosStaff,\n} from './pos-auth'\nimport {\n applyPosPayment,\n deliverChosenPosReceipt,\n posPaymentId,\n posSaleSummary,\n readPosSale,\n releasePosSaleDiscount,\n type PosLiftedOrder,\n type PosPaymentOutcome,\n} from './pos-sale'\nimport { posPaymentCashierId } from './pos-sale-stamp'\nimport { printPosSaleReceipt } from './pos-print'\nimport {\n POS_CURRENCY,\n posStripe,\n posStripeErrorMessage,\n posStripeTestMode,\n posTerminalAvailable,\n} from './pos-stripe'\nimport {\n cancelPosCardPayment,\n createCardPresentIntent,\n refreshPosCardPayment,\n retryCardPresentPayment,\n simulatePosReaderTap,\n startCardKeyedPayment,\n startCardLinkPayment,\n startCardPresentPayment,\n} from './pos-terminal'\n\n/**\n * `POST /api/commerce/pos-payment` (AGL-3607): every tender against an OPEN\n * register sale, one `action` per request.\n *\n * The sale was priced by `pos-order.ts` (`payment: 'open'`); nothing here\n * re-prices it or lets the register name a total. Each payment-starting action\n * needs the register's `Idempotency-Key`, from which the payment's id is\n * derived: pressing a tender twice, or retrying after a lost response, finds\n * the payment the first press started instead of taking the money twice.\n */\nexport const posPaymentHandler: PluginApiHandler = async (req, res) => {\n // `sale` is a read and may be a GET, so a register re-reading its sale does\n // not spend the console's write budget; everything else moves money.\n const body = req.method === 'GET' ? posQueryBody(req) : posRequestBody(req)\n if (\n !(\n req.method === 'POST' ||\n (req.method === 'GET' && (body['action'] === 'sale' || body['action'] === 'context'))\n )\n ) {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(body['hostId'] ?? '')\n const gate = await authorizePosStaff(req, hostId)\n if ('error' in gate) return res.status(gate.status).json({ error: gate.error })\n let staff = gate.staff\n const action = String(body['action'] ?? '')\n const orderId = String(body['orderId'] ?? '')\n try {\n if (action === 'gift-card-balance') {\n return await giftCardBalance(staff, body, res)\n }\n if (action === 'credit-lookup') {\n return await creditLookup(staff, body, res)\n }\n if (action === 'context') {\n // What the register needs to draw its tenders: the site's tip and\n // receipt settings, whether card readers are offered at all, and the\n // key the typed-card form loads Stripe with.\n const readers = posTerminalAvailable()\n ? (\n await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminalReaders')\n .limit(50)\n .get()\n ).docs.map((doc: any) => ({\n id: doc.id as string,\n label: String(doc.get('label') ?? 'Card reader'),\n registerId: (doc.get('registerId') as string | undefined) ?? null,\n status: String(doc.get('status') ?? 'offline'),\n livemode: Boolean(doc.get('livemode')),\n }))\n : []\n const config = await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId })\n return res.status(200).json({\n settings: posRegisterSettings(config),\n // The register's own rules (AGL-3609): the shift it requires, the\n // idle lock and the refund limit. The console reads the same config\n // client-side; the native apps read it here.\n ops: posOpsSettings(config),\n terminal: { available: posTerminalAvailable(), testMode: posStripeTestMode() },\n readers,\n publishableKey: String(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? ''),\n // A text receipt is offered only when an SMS provider is on (AGL-3610).\n smsReceipts: pluginSmsAvailable(),\n // Store credit other plugins keep — rewards (AGL-3640) — offered here.\n credits: await offeredCheckoutCredits({ hostId, channel: 'pos' }),\n })\n }\n if (!orderId) return res.status(400).json({ error: 'Missing orderId' })\n const startsPayment = [\n 'card-present-sdk',\n 'cash',\n 'gift-card',\n 'credit',\n 'folio',\n 'card-present',\n 'card-keyed',\n 'card-link',\n ].includes(action)\n const attemptKey = posIdempotencyKey(req)\n if (startsPayment && !attemptKey) {\n return res.status(400).json({ error: 'Missing Idempotency-Key' })\n }\n const paymentId = startsPayment\n ? posPaymentId(orderId, attemptKey)\n : String(body['paymentId'] ?? '')\n // The cashier a PIN switched in takes the payment (AGL-3609).\n if (startsPayment && body['cashierAssertion']) {\n staff = {\n ...staff,\n uid: await posPaymentCashierId({\n hostId,\n orderId,\n signedInUid: staff.uid,\n assertion: body['cashierAssertion'],\n }),\n }\n }\n const amountCents = Math.round(Number(body['amountCents'] ?? 0))\n const tipCents = Math.round(Number(body['tipCents'] ?? 0)) || 0\n const settings = posRegisterSettings(\n await getPluginConfig(staff.orgId || undefined, 'commerce', { hostId }),\n )\n let outcome: (PosPaymentOutcome & { clientSecret?: string; paymentIntentId?: string }) | null = null\n switch (action) {\n case 'sale': {\n const order = await readPosSale(hostId, orderId)\n if (!order) return res.status(404).json({ error: 'Unknown sale' })\n outcome = { ok: true, order, payment: null, completed: false, changed: false }\n break\n }\n case 'cash':\n outcome = await takeCash(staff, orderId, paymentId, body, tipCents)\n break\n case 'gift-card':\n outcome = await takeGiftCard(staff, orderId, paymentId, body)\n break\n case 'credit':\n outcome = await takeCredit(staff, orderId, paymentId, body)\n break\n case 'folio':\n outcome = await takeFolio(staff, orderId, paymentId, body)\n break\n case 'card-present':\n outcome = await startCardPresentPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n readerId: String(body['readerId'] ?? ''),\n settings,\n })\n break\n case 'card-present-sdk':\n // Collected by a native app's Stripe Terminal SDK (Tap to Pay or a\n // Bluetooth reader, AGL-3618) against this server-made intent; it\n // settles exactly like a smart-reader payment.\n outcome = await createCardPresentIntent({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n })\n break\n case 'card-keyed':\n outcome = await startCardKeyedPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n // The register's own card fields send the PaymentMethod Stripe\n // made from the card, never the card; the server confirms with it.\n ...(body['paymentMethodId'] ? { paymentMethodId: String(body['paymentMethodId']) } : {}),\n })\n break\n case 'card-link':\n outcome = await startCardLinkPayment({\n hostId,\n orderId,\n paymentId,\n amountCents,\n tipCents,\n cashierId: staff.uid,\n org: staff.org,\n returnUrl: await registerReturnUrl(req.headers.host, hostId, staff),\n })\n break\n case 'status':\n outcome = await refreshPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'cancel':\n outcome = await cancelPosCardPayment({ hostId, orderId, paymentId })\n break\n case 'retry':\n outcome = await retryCardPresentPayment({ hostId, orderId, paymentId, settings })\n break\n case 'simulate':\n outcome = await simulatePosReaderTap({\n hostId,\n orderId,\n paymentId,\n cardNumber: String(body['cardNumber'] ?? ''),\n })\n break\n case 'void':\n outcome = await voidPosSale(staff, orderId)\n break\n case 'receipt':\n outcome = await recordReceiptChoice(staff, orderId, body)\n break\n default:\n return res.status(400).json({ error: 'Unknown action' })\n }\n if ('error' in outcome) return res.status(outcome.status).json({ error: outcome.error })\n return res.status(200).json({\n sale: posSaleSummary(outcome.order),\n ...(outcome.payment ? { paymentId: outcome.payment.id } : {}),\n completed: outcome.order.status === 'paid',\n ...(outcome.clientSecret ? { clientSecret: outcome.clientSecret } : {}),\n ...(outcome.paymentIntentId ? { paymentIntentId: outcome.paymentIntentId } : {}),\n // The key the typed-card form loads Stripe with, beside the secret it\n // confirms, so a register whose context read failed can still take it.\n ...(action === 'card-keyed' && outcome.clientSecret\n ? { publishableKey: String(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY ?? '') }\n : {}),\n })\n } catch (error) {\n console.error('[pos-payment]', action, error)\n return res.status(500).json({ error: 'Payment failed — check the sale before trying again' })\n }\n}\n\n/** Where a QR payment page sends the customer back to: the register. */\nasync function registerReturnUrl(\n requestHost: string | string[] | undefined,\n hostId: string,\n staff: PosStaff,\n): Promise<string> {\n const origin = `https://${String(requestHost ?? '')}`\n const subdomain = (\n await firebaseAdmin.app().firestore().collection('hostIndex').doc(hostId).get()\n ).get('subdomain') as string | undefined\n const orgSlug = staff.org?.['slug'] as string | undefined\n return orgSlug && subdomain\n ? `${origin}${buildRoute(Route.HOST_PLUGIN, { orgSlug, host: subdomain, pluginSlug: 'pos' })}`\n : origin\n}\n\n/** The balance a new tender may take, or a refusal. */\nfunction tenderable(\n order: PosLiftedOrder,\n payments: CommerceModel.OrderPayment[],\n): number {\n return CommerceModel.posTenderableCents(Number(order.totals?.totalCents ?? 0), payments)\n}\n\nconst NOT_OPEN = { kind: 'refuse' as const, status: 409, error: 'This sale is no longer open' }\n\n/**\n * Cash: the amount defaults to whatever is left, the change is what the\n * customer handed over beyond it (and beyond any tip they chose).\n */\nasync function takeCash(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n tipCents: number,\n): Promise<PosPaymentOutcome> {\n const tenderedCents = Math.round(Number(body['tenderedCents'] ?? 0))\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n decide: ({ order, payments, existing }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!Number.isFinite(tenderedCents) || tenderedCents <= 0) {\n return { kind: 'refuse', status: 400, error: 'Enter the cash received.' }\n }\n const open = tenderable(order, payments)\n if (open <= 0) return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n const amountCents =\n askedCents > 0 ? Math.min(askedCents, open) : Math.min(open, Math.max(0, tenderedCents - tipCents))\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 400, error: 'The cash received does not cover the tip.' }\n }\n const tipProblem = CommerceModel.posTipProblem(tipCents, amountCents)\n if (tipProblem) return { kind: 'refuse', status: 400, error: tipProblem }\n if (tenderedCents < amountCents + tipCents) {\n return { kind: 'refuse', status: 400, error: 'Cash received is short' }\n }\n const total = Number(order.totals?.totalCents ?? 0)\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'cash',\n amountCents,\n ...(tipCents > 0 ? { tipCents } : {}),\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n cashTenderedCents: tenderedCents,\n changeCents: tenderedCents - amountCents - tipCents,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: total,\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n })\n}\n\nfunction giftCardRef(hostId: string, code: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('giftCards')\n .doc(code)\n}\n\n/** A gift card's spendable balance, for the cashier to read to the customer. */\nasync function giftCardBalance(\n staff: PosStaff,\n body: Record<string, any>,\n res: Parameters<PluginApiHandler>[1],\n): Promise<void> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n const rate = await consumeRateLimit(`pos-gift-balance:${staff.uid}`, {\n limit: 30,\n windowMs: 60_000,\n })\n if (!rate.allowed) {\n return res.status(429).json({ error: 'Too many balance checks. Wait a minute and try again.' })\n }\n if (CommerceModel.giftCardCodeProblem(code)) {\n return res.status(404).json({ error: 'No gift card has that code.' })\n }\n const snapshot = await giftCardRef(staff.hostId, code).get()\n if (!snapshot.exists) return res.status(404).json({ error: 'No gift card has that code.' })\n const card = snapshot.data() as CommerceModel.HostGiftCard\n return res.status(200).json({\n availableCents: CommerceModel.giftCardAvailableCents(card, Date.now()),\n frozen: CommerceModel.isGiftCardFrozen(card),\n voided: Number(card.voidedAtMs) > 0,\n last4: code.slice(-4),\n })\n}\n\n/**\n * A gift card: takes the smaller of what the card can give and what is left\n * to pay, in ONE transaction with the sale. The card's spendable balance\n * honours every live hold an online checkout placed on it (AGL-2449), and a\n * frozen card gives nothing (AGL-3363), so the till and the website can\n * never spend the same dollars.\n */\nasync function takeGiftCard(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const code = CommerceModel.giftCardCodeOf(body['code'])\n if (CommerceModel.giftCardCodeProblem(code)) {\n return { ok: false, status: 404, error: 'No gift card has that code.' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const cardRef = giftCardRef(staff.hostId, code)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => {\n const snapshot = await transaction.get(cardRef)\n return snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null\n },\n decide: ({ order, payments, existing, context: card }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!card) return { kind: 'refuse', status: 404, error: 'No gift card has that code.' }\n const available = CommerceModel.giftCardAvailableCents(card, Date.now())\n if (available <= 0) {\n return {\n kind: 'refuse',\n status: 409,\n error: CommerceModel.isGiftCardFrozen(card)\n ? 'This gift card is on hold and cannot be used right now.'\n : 'This gift card has no balance left.',\n }\n }\n const open = tenderable(order, payments)\n const amountCents = Math.min(available, open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'gift_card',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n giftCardId: code,\n last4: code.slice(-4),\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n write: (transaction, card, payment) => {\n transaction.set(\n cardRef,\n {\n balanceCents: Math.max(0, Number(card?.balanceCents ?? 0) - payment.amountCents),\n lastUsedAtMs: Date.now(),\n },\n { merge: true },\n )\n },\n })\n}\n\n/**\n * Staff search for a store-credit account at the register (AGL-3640): a\n * customer's email or code, answered by the plugin that keeps the account.\n * Only staff reach it — `authorizePosStaff` above — so a provider may look\n * accounts up by email here, which it never does for a shopper.\n */\nasync function creditLookup(staff: PosStaff, body: Record<string, any>, res: any) {\n const entry = checkoutCreditProvider(String(body['providerId'] ?? ''))\n if (!entry?.provider.lookup) return res.status(404).json({ error: 'That kind of credit is not taken here.' })\n const rate = await consumeRateLimit(`pos-credit-lookup:${staff.uid}`, {\n limit: 60,\n windowMs: 60_000,\n })\n if (!rate.allowed) return res.status(429).json({ error: 'Too many lookups. Wait a moment.' })\n if (!(await entry.provider.offered({ hostId: staff.hostId, channel: 'pos' }).catch(() => false))) {\n return res.status(404).json({ error: 'That kind of credit is not taken here.' })\n }\n const found = await entry.provider\n .lookup({ hostId: staff.hostId, query: String(body['query'] ?? '').slice(0, 120) })\n .catch((error: unknown) => {\n console.error('[pos-payment] credit lookup failed', entry.providerId, error)\n return []\n })\n const accounts = found\n .slice(0, 10)\n .map((account) => normalizeCheckoutCreditAccount(account))\n .filter((account) => !('error' in account))\n return res.status(200).json({ providerId: entry.providerId, accounts })\n}\n\n/**\n * Store credit another plugin keeps (AGL-3640) — a rewards balance, a friend's\n * referral credit — by the customer's code, or by the account a staff lookup\n * found. The provider's stage reads the account INSIDE the sale's transaction\n * and its debit writes there, so the credit is taken with the payment or not\n * at all; a retried press finds its own payment and takes nothing more.\n */\nasync function takeCredit(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const code = normalizeCheckoutCreditCode(body['code'])\n const entry = code\n ? checkoutCreditProviderForCode(code)\n : checkoutCreditProvider(String(body['providerId'] ?? ''))\n if (!entry) return { ok: false, status: 404, error: 'That code is not one this store takes.' }\n if (!(await entry.provider.offered({ hostId: staff.hostId, channel: 'pos' }).catch(() => false))) {\n return { ok: false, status: 404, error: 'That kind of credit is not taken here.' }\n }\n const sale = await readPosSale(staff.hostId, orderId)\n if (!sale) return { ok: false, status: 404, error: 'Unknown sale' }\n const account = normalizeCheckoutCreditAccount(\n await entry.provider\n .resolve({\n hostId: staff.hostId,\n ...(code ? { code } : { reference: String(body['reference'] ?? '') }),\n channel: 'pos',\n customerEmail: (sale as { customerEmail?: string | null }).customerEmail ?? null,\n staff: true,\n })\n .catch((error: unknown) => {\n console.error('[pos-payment] credit resolve failed', entry.providerId, error)\n return null\n }),\n )\n if ('error' in account) return { ok: false, status: account.status, error: account.error }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n return await applyPosPayment<CheckoutCreditStage | null>({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) =>\n entry.provider.stage({\n transaction,\n hostId: staff.hostId,\n reference: account.reference,\n orderId,\n nowMs: Date.now(),\n }),\n decide: ({ order, payments, existing, context: stage }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!stage) return { kind: 'refuse', status: 404, error: `That ${account.label.toLowerCase()} account no longer exists.` }\n const open = tenderable(order, payments)\n if (open <= 0) return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n const amountCents = Math.min(stage.availableCents, open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: `This ${account.label.toLowerCase()} account has nothing to spend.` }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'credit',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n creditProviderId: entry.providerId,\n creditReference: account.reference,\n creditLabel: account.label,\n ...(account.last4 ? { last4: account.last4 } : {}),\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n }\n },\n write: (_transaction, stage, payment) => {\n // The stage writes through the sale's own transaction. Taking less than\n // the payment records would leave the sale paid by money that did not\n // move, so a short debit aborts the whole commit instead.\n const taken = stage ? stage.debit({ cents: payment.amountCents, key: payment.id, orderId, channel: 'pos' }) : 0\n if (taken !== payment.amountCents) {\n throw new Error(`credit debit ${taken} short of payment ${payment.amountCents}`)\n }\n },\n })\n}\n\nfunction reservationRef(hostId: string, reservationId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('reservations')\n .doc(reservationId)\n}\n\n/** Charged to a checked-in stay's folio, in the same commit as the payment. */\nasync function takeFolio(\n staff: PosStaff,\n orderId: string,\n paymentId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const reservationId = String(body['reservationId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(reservationId)) {\n return { ok: false, status: 400, error: 'Pick a reservation' }\n }\n const askedCents = Math.round(Number(body['amountCents'] ?? 0))\n const stayRef = reservationRef(staff.hostId, reservationId)\n return await applyPosPayment({\n hostId: staff.hostId,\n orderId,\n paymentId,\n prepare: async (transaction) => (await transaction.get(stayRef)).exists as boolean,\n decide: ({ order, payments, existing, context: stayExists }) => {\n if (existing) return { kind: 'keep' }\n if (order.status !== 'pending') return NOT_OPEN\n if (!stayExists) return { kind: 'refuse', status: 404, error: 'Unknown reservation' }\n const open = tenderable(order, payments)\n const amountCents = Math.min(open, askedCents > 0 ? askedCents : open)\n if (!(amountCents > 0)) {\n return { kind: 'refuse', status: 409, error: 'Nothing is left to pay on this sale.' }\n }\n const now = Date.now()\n return {\n kind: 'put',\n payment: {\n id: paymentId,\n method: 'folio',\n amountCents,\n status: 'succeeded',\n atMs: now,\n settledAtMs: now,\n reservationId,\n folioAtMs: now,\n takeFeeCents: CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n amountCents,\n }),\n feeCents: 0,\n cashierId: staff.uid,\n },\n event: { event: 'folio', detail: `Charged to reservation ${reservationId}` },\n }\n },\n write: (transaction, _stay, payment) => {\n // `update`, never a merge-set: a missing stay must not be minted as a\n // stub holding one folio line (AGL-1760). It exists — read above.\n transaction.update(stayRef, {\n folio: firebaseAdmin.firestore.FieldValue.arrayUnion({\n orderId,\n paymentId: payment.id,\n amountCents: payment.amountCents,\n note: 'Register sale',\n atMs: payment.folioAtMs ?? Date.now(),\n }),\n })\n },\n })\n}\n\n/**\n * Abandons an open sale: everything it took is handed back first — cards\n * refunded in full (tip included, fee and transfer reversed), gift cards\n * re-credited, the room charge taken off the folio, cash marked as returned —\n * and only then is the order cancelled. A refund Stripe refuses stops the void\n * with the sale still open and its payment still recorded, never cancelled\n * over money that did not come back.\n */\nexport async function voidPosSale(\n staff: PosStaff,\n orderId: string,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n const order = await readPosSale(hostId, orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.status === 'cancelled') return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status !== 'pending' || !Array.isArray(order.payments)) {\n return {\n ok: false,\n status: 409,\n error: 'This sale is already paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(order)) {\n if (payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method)) {\n const cancelled = await cancelPosCardPayment({ hostId, orderId, paymentId: payment.id })\n if (!cancelled.ok) return cancelled\n }\n }\n // Re-read after the cancels: one may have completed the sale in the gap.\n const current = await readPosSale(hostId, orderId)\n if (!current) return { ok: false, status: 404, error: 'Unknown sale' }\n if (current.status !== 'pending') {\n return {\n ok: false,\n status: 409,\n error: 'The last card payment went through and the sale is paid. Refund it from the order instead.',\n }\n }\n for (const payment of CommerceModel.orderPayments(current)) {\n if (payment.status !== 'succeeded') continue\n const reversed = await reversePayment(staff, current, payment)\n if (!reversed.ok) return reversed\n }\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(hostId).collection('orders').doc(orderId)\n const cancelled = await firestore.runTransaction(async (transaction: any) => {\n const fresh = {\n ...(CommerceModel.liftLegacyOrder(((await transaction.get(orderRef)).data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.status !== 'pending') return null\n const open = CommerceModel.orderPayments(fresh).some(\n (payment) => payment.status === 'pending' || payment.status === 'succeeded',\n )\n if (open) return null\n const next = {\n ...fresh,\n status: 'cancelled' as const,\n timeline: CommerceModel.appendOrderEvent(fresh, 'pos-sale-voided', 'Voided at the register'),\n }\n transaction.set(\n orderRef,\n {\n status: 'cancelled',\n cancelledAtMs: Date.now(),\n timeline: next.timeline,\n ...CommerceModel.orderListFields(next, orderId),\n },\n { merge: true },\n )\n return next\n })\n if (!cancelled) {\n return { ok: false, status: 409, error: 'A payment on this sale changed. Check it and try again.' }\n }\n await releasePosSaleDiscount(hostId, current)\n return { ok: true, order: cancelled, payment: null, completed: false, changed: true }\n}\n\n/** Hands one settled payment back, recording `reversed` in the same commit. */\nasync function reversePayment(\n staff: PosStaff,\n order: PosLiftedOrder,\n payment: CommerceModel.OrderPayment,\n): Promise<PosPaymentOutcome> {\n const hostId = staff.hostId\n if (CommerceModel.isCardPaymentMethod(payment.method)) {\n if (!payment.paymentIntentId) {\n return { ok: false, status: 409, error: 'A card payment on this sale has no charge to refund.' }\n }\n const refund = await posStripe('POST', 'refunds', {\n idempotencyKey: `pos-void:${payment.id}`,\n params: {\n payment_intent: payment.paymentIntentId,\n reverse_transfer: true,\n refund_application_fee: true,\n 'metadata[kind]': 'pos-void',\n 'metadata[orderId]': order.$id,\n },\n })\n if (!refund.ok) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(refund.body, 'The card refund failed. The sale is still open.'),\n }\n }\n }\n const cardRef = payment.giftCardId ? giftCardRef(hostId, payment.giftCardId) : null\n const stayRef = payment.reservationId ? reservationRef(hostId, payment.reservationId) : null\n // Store credit goes back to the plugin that keeps it (AGL-3640), in the\n // same commit as the reversal. A provider that is gone cannot take it\n // back, so the void stops with the sale still open rather than cancelling\n // over credit that did not come back.\n const creditEntry =\n payment.method === 'credit' && payment.creditProviderId ? checkoutCreditProvider(payment.creditProviderId) : null\n if (payment.method === 'credit' && (!creditEntry || !payment.creditReference)) {\n return {\n ok: false,\n status: 409,\n error: 'The store credit on this sale cannot be handed back right now. The sale is still open.',\n }\n }\n return await applyPosPayment({\n hostId,\n orderId: order.$id,\n paymentId: payment.id,\n prepare: async (transaction) => {\n if (payment.method === 'gift_card' && cardRef) {\n const snapshot = await transaction.get(cardRef)\n return { card: snapshot.exists ? (snapshot.data() as CommerceModel.HostGiftCard) : null, folio: null, credit: null }\n }\n if (payment.method === 'folio' && stayRef) {\n const snapshot = await transaction.get(stayRef)\n return { card: null, folio: snapshot.exists ? ((snapshot.get('folio') ?? []) as any[]) : null, credit: null }\n }\n if (payment.method === 'credit' && creditEntry && payment.creditReference) {\n const credit = await creditEntry.provider.stage({\n transaction,\n hostId,\n reference: payment.creditReference,\n orderId: order.$id,\n nowMs: Date.now(),\n })\n return { card: null, folio: null, credit }\n }\n return { card: null, folio: null, credit: null }\n },\n decide: ({ existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n if (existing.status !== 'succeeded') return { kind: 'keep' }\n return {\n kind: 'put',\n payment: { ...existing, status: 'reversed' },\n event: {\n event: 'pos-payment-reversed',\n detail:\n existing.method === 'cash'\n ? `${CommerceModel.describeOrderPayment(existing)} handed back in cash`\n : `${CommerceModel.describeOrderPayment(existing)} returned`,\n },\n }\n },\n write: (transaction, context, reversed) => {\n if (reversed.method === 'gift_card' && cardRef && context.card) {\n transaction.set(\n cardRef,\n { balanceCents: Number(context.card.balanceCents ?? 0) + reversed.amountCents },\n { merge: true },\n )\n }\n if (reversed.method === 'folio' && stayRef && context.folio) {\n transaction.update(stayRef, {\n folio: context.folio.filter((entry) => entry?.paymentId !== reversed.id),\n })\n }\n if (reversed.method === 'credit' && context.credit) {\n context.credit.reverse({ key: reversed.id, orderId: order.$id })\n }\n },\n })\n}\n\n/** A repeat of the same receipt choice inside this window sends nothing more. */\nconst RECEIPT_REPEAT_WINDOW_MS = 2 * 60 * 1000\n\n/**\n * How the customer wants their receipt, from the cashier or the customer\n * display. Kept on the order; an email chosen after the sale is paid is sent\n * at once, and one chosen before is sent when it completes.\n */\nexport async function recordReceiptChoice(\n staff: PosStaff,\n orderId: string,\n body: Record<string, any>,\n): Promise<PosPaymentOutcome> {\n const channel = String(body['channel'] ?? '') as CommerceModel.PosReceiptChannel\n if (!['email', 'sms', 'print', 'none'].includes(channel)) {\n return { ok: false, status: 400, error: 'Choose email, text, print or no receipt.' }\n }\n const to =\n channel === 'email'\n ? CommerceModel.posDisplayEmail(body['to'])\n : channel === 'sms'\n ? CommerceModel.posDisplayPhone(body['to'])\n : ''\n if ((channel === 'email' || channel === 'sms') && !to) {\n return {\n ok: false,\n status: 400,\n error: channel === 'email' ? 'Enter a valid email address.' : 'Enter a valid phone number.',\n }\n }\n if (channel === 'sms' && !pluginSmsAvailable()) {\n return { ok: false, status: 409, error: 'Text receipts are not set up for this store.' }\n }\n const marketingOptIn = channel === 'email' && body['marketingOptIn'] === true\n const firestore = firebaseAdmin.app().firestore()\n const orderRef = firestore.collection('hosts').doc(staff.hostId).collection('orders').doc(orderId)\n const order = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(orderRef)\n if (!snapshot.exists) return null\n const fresh = {\n ...(CommerceModel.liftLegacyOrder((snapshot.data() ?? {}) as any) as any),\n $id: orderId,\n } as PosLiftedOrder\n if (fresh.channel !== 'pos') return null\n // The same choice twice in a row (a double tap, or the display and the\n // cashier answering together) is one receipt, not two.\n const previous = fresh.receiptRequest\n if (\n fresh.status === 'paid' &&\n previous &&\n previous.channel === channel &&\n String(previous.to ?? '') === to &&\n Date.now() - Number(previous.atMs ?? 0) < RECEIPT_REPEAT_WINDOW_MS\n ) {\n return { ...fresh, repeated: true } as PosLiftedOrder & { repeated?: boolean }\n }\n const receiptRequest = {\n channel,\n ...(to ? { to } : {}),\n ...(marketingOptIn ? { marketingOptIn: true } : {}),\n atMs: Date.now(),\n }\n transaction.set(\n orderRef,\n {\n receiptRequest,\n ...(channel === 'email' && !fresh.customerEmail\n ? {\n customerEmail: to,\n ...CommerceModel.orderListFields({ ...fresh, customerEmail: to }, orderId),\n }\n : {}),\n // The receipt door texts `customerPhone` (AGL-3610).\n ...(channel === 'sms' ? { customerPhone: to } : {}),\n },\n { merge: true },\n )\n return { ...fresh, receiptRequest } as PosLiftedOrder & { repeated?: boolean }\n })\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n if (order.repeated) return { ok: true, order, payment: null, completed: false, changed: false }\n if (order.status === 'paid' && channel === 'print') {\n // Chosen after the sale completed: printed now on the register's receipt\n // printer, under the sale's own key so it never prints twice (AGL-3609).\n await printPosSaleReceipt(staff.hostId, orderId)\n }\n // A kiosk's own receipt screen (AGL-3623) is not the register's display:\n // the display may be asking the cashier's customer right now.\n if (order.status === 'paid' && order.registerId && order.posSource !== 'kiosk') {\n // The customer has answered (or the cashier for them): the display says\n // thank you and drops the address they typed (AGL-3608).\n await finishPosDisplayReceipt(staff.hostId, order.registerId).catch((error: unknown) =>\n console.error('[pos-payment] display finish failed', error),\n )\n }\n if (order.status === 'paid' && (channel === 'email' || channel === 'sms')) {\n // Chosen after the sale completed: sent now, to where they said.\n const sent = await deliverChosenPosReceipt(\n { hostId: staff.hostId, orderId },\n { channel, to, orderEmail: String(order.customerEmail ?? '') },\n )\n if (channel === 'email') {\n await recordCapturedContact({\n orgId: '',\n hostId: staff.hostId,\n identity: { email: to },\n surface: 'relationship',\n lifecycleFloor: 'customer',\n ...(marketingOptIn ? { marketingConsent: true } : {}),\n interaction: {\n source: 'order',\n refId: orderId,\n summary: `In-store purchase (${CommerceModel.formatReceiptMoney(\n Number(order.totals?.totalCents ?? 0),\n POS_CURRENCY,\n )})`,\n },\n }).catch((error: unknown) => console.error('[pos-payment] contact capture failed', error))\n }\n if (sent !== 'sent') {\n // A failed send is not a repeat: the cashier's retry goes out.\n await orderRef\n .set({ receiptRequest: { atMs: 0 } }, { merge: true })\n .catch((error: unknown) => console.error('[pos-payment] receipt retry reset failed', error))\n }\n if (sent === 'not_configured') {\n return {\n ok: false,\n status: 409,\n error: channel === 'sms' ? 'Text receipts are not set up for this store.' : 'Email is not set up.',\n }\n }\n if (sent !== 'sent') return { ok: false, status: 502, error: 'The receipt could not be sent.' }\n }\n return { ok: true, order, payment: null, completed: false, changed: true }\n}\n"],"names":["consumeRateLimit","firebaseAdmin","getPluginConfig","buildRoute","Route","recordCapturedContact","pluginSmsAvailable","checkoutCreditProvider","checkoutCreditProviderForCode","normalizeCheckoutCreditAccount","normalizeCheckoutCreditCode","offeredCheckoutCredits","finishPosDisplayReceipt","CommerceModel","posRegisterSettings","posOpsSettings","authorizePosStaff","posIdempotencyKey","posQueryBody","posRequestBody","applyPosPayment","deliverChosenPosReceipt","posPaymentId","posSaleSummary","readPosSale","releasePosSaleDiscount","posPaymentCashierId","printPosSaleReceipt","POS_CURRENCY","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","cancelPosCardPayment","createCardPresentIntent","refreshPosCardPayment","retryCardPresentPayment","simulatePosReaderTap","startCardKeyedPayment","startCardLinkPayment","startCardPresentPayment","posPaymentHandler","req","res","body","method","status","json","error","hostId","String","gate","staff","action","orderId","process","giftCardBalance","creditLookup","readers","app","firestore","collection","doc","limit","get","docs","map","id","label","registerId","livemode","Boolean","config","orgId","undefined","settings","ops","terminal","available","testMode","publishableKey","env","NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY","smsReceipts","credits","channel","startsPayment","includes","attemptKey","paymentId","uid","signedInUid","assertion","amountCents","Math","round","Number","tipCents","outcome","order","ok","payment","completed","changed","takeCash","takeGiftCard","takeCredit","takeFolio","cashierId","org","readerId","paymentMethodId","returnUrl","registerReturnUrl","headers","host","cardNumber","voidPosSale","recordReceiptChoice","sale","clientSecret","paymentIntentId","console","requestHost","origin","subdomain","orgSlug","HOST_PLUGIN","pluginSlug","tenderable","payments","posTenderableCents","totals","totalCents","NOT_OPEN","kind","tenderedCents","askedCents","decide","existing","isFinite","open","min","max","tipProblem","posTipProblem","total","now","Date","atMs","settledAtMs","cashTenderedCents","changeCents","takeFeeCents","posTakeShareCents","posTakeFeeCents","feeCents","giftCardRef","code","giftCardCodeOf","rate","windowMs","allowed","giftCardCodeProblem","snapshot","exists","card","data","availableCents","giftCardAvailableCents","frozen","isGiftCardFrozen","voided","voidedAtMs","last4","slice","cardRef","prepare","transaction","context","giftCardId","write","set","balanceCents","lastUsedAtMs","merge","entry","provider","lookup","offered","catch","found","query","providerId","accounts","account","filter","resolve","reference","customerEmail","stage","nowMs","toLowerCase","creditProviderId","creditReference","creditLabel","_transaction","taken","debit","cents","key","Error","reservationRef","reservationId","test","stayRef","stayExists","folioAtMs","event","detail","_stay","update","folio","FieldValue","arrayUnion","note","Array","isArray","orderPayments","isCardPaymentMethod","cancelled","current","reversed","reversePayment","orderRef","runTransaction","fresh","liftLegacyOrder","$id","some","next","timeline","appendOrderEvent","cancelledAtMs","orderListFields","refund","idempotencyKey","params","payment_intent","reverse_transfer","refund_application_fee","creditEntry","credit","describeOrderPayment","reverse","RECEIPT_REPEAT_WINDOW_MS","to","posDisplayEmail","posDisplayPhone","marketingOptIn","previous","receiptRequest","repeated","customerPhone","posSource","sent","orderEmail","identity","email","surface","lifecycleFloor","marketingConsent","interaction","source","refId","summary","formatReceiptMoney"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,aAAa,EACbC,eAAe,QACV,2BAA0B;AACjC,SAASC,UAAU,EAAEC,KAAK,QAA+B,sBAAqB;AAC9E,OAAOC,2BAA2B,sDAAqD;AACvF,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SACEC,sBAAsB,EACtBC,6BAA6B,EAC7BC,8BAA8B,EAC9BC,2BAA2B,EAC3BC,sBAAsB,QAEjB,sDAAqD;AAC5D,SAASC,uBAAuB,QAAQ,mBAAe;AACvD,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,cAAc,QAAQ,uBAAmB;AAClD,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,YAAY,EACZC,cAAc,QAET,gBAAY;AACnB,SACEC,eAAe,EACfC,uBAAuB,EACvBC,YAAY,EACZC,cAAc,EACdC,WAAW,EACXC,sBAAsB,QAGjB,gBAAY;AACnB,SAASC,mBAAmB,QAAQ,sBAAkB;AACtD,SAASC,mBAAmB,QAAQ,iBAAa;AACjD,SACEC,YAAY,EACZC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,oBAAoB,QACf,kBAAc;AACrB,SACEC,oBAAoB,EACpBC,uBAAuB,EACvBC,qBAAqB,EACrBC,uBAAuB,EACvBC,oBAAoB,EACpBC,qBAAqB,EACrBC,oBAAoB,EACpBC,uBAAuB,QAClB,oBAAgB;AAEvB;;;;;;;;;CASC,GACD,OAAO,MAAMC,oBAAsC,OAAOC,KAAKC;QAYvCC,cAIAA,cACCA;IAhBvB,4EAA4E;IAC5E,qEAAqE;IACrE,MAAMA,OAAOF,IAAIG,MAAM,KAAK,QAAQ3B,aAAawB,OAAOvB,eAAeuB;IACvE,IACE,CACEA,CAAA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YxN,QAAOiD,uBAAAA,MAAMoG,aAAa,YAAnBpG,uBAAuB;QAAI;QAE/D,IAAId,YAAY,SAAS;;gBAYVc;YAXb,MAAM9F,sBAAsB;gBAC1BoE,OAAO;gBACPxB,QAAQG,MAAMH,MAAM;gBACpB0N,UAAU;oBAAEC,OAAOZ;gBAAG;gBACtBa,SAAS;gBACTC,gBAAgB;eACZX,iBAAiB;gBAAEY,kBAAkB;YAAK,IAAI,CAAC;gBACnDC,aAAa;oBACXC,QAAQ;oBACRC,OAAO5N;oBACP6N,SAAS,CAAC,mBAAmB,EAAEtQ,cAAcuQ,kBAAkB,CAC7DpL,gBAAOG,gBAAAA,MAAMiC,MAAM,qBAAZjC,cAAckC,UAAU,mBAAI,IACnCzG,cACA,CAAC,CAAC;gBACN;gBACCkK,KAAK,CAAC,CAAC9I,QAAmB0E,QAAQ1E,KAAK,CAAC,wCAAwCA;QACrF;QACA,IAAIyN,SAAS,QAAQ;YACnB,+DAA+D;YAC/D,MAAM/B,SACHpD,GAAG,CAAC;gBAAE+E,gBAAgB;oBAAEhH,MAAM;gBAAE;YAAE,GAAG;gBAAEoC,OAAO;YAAK,GACnDK,KAAK,CAAC,CAAC9I,QAAmB0E,QAAQ1E,KAAK,CAAC,4CAA4CA;QACzF;QACA,IAAIyN,SAAS,kBAAkB;YAC7B,OAAO;gBACLrK,IAAI;gBACJtD,QAAQ;gBACRE,OAAOqC,YAAY,QAAQ,iDAAiD;YAC9E;QACF;QACA,IAAIoL,SAAS,QAAQ,OAAO;YAAErK,IAAI;YAAOtD,QAAQ;YAAKE,OAAO;QAAiC;IAChG;IACA,OAAO;QAAEoD,IAAI;QAAMD;QAAOE,SAAS;QAAMC,WAAW;QAAOC,SAAS;IAAK;AAC3E"}
@@ -48,6 +48,13 @@ export interface PosTerminalAddress {
48
48
  country: string;
49
49
  }
50
50
  export declare function posTerminalAddressProblem(address: Partial<PosTerminalAddress> | undefined): string | null;
51
+ /**
52
+ * The idempotency key of a site's Location request. Two presses with the same
53
+ * address share it, so a double tap makes one Location; a corrected address
54
+ * gets its own, since Stripe refuses a key reused with other parameters for a
55
+ * day (a merchant fixing a typo would otherwise read that refusal).
56
+ */
57
+ export declare function posTerminalLocationKey(hostId: string, displayName: string, address: PosTerminalAddress): string;
51
58
  /**
52
59
  * The site's Terminal Location, created on first use (on the PLATFORM, with
53
60
  * the merchant named in metadata). Its address is the store's, because Stripe
@@ -148,9 +155,13 @@ export declare function retryCardPresentPayment(input: {
148
155
  * the Payment Element. No MOTO: the card is keyed into Stripe's own field and
149
156
  * goes through Stripe's normal online checks, 3-D Secure included.
150
157
  */
151
- export declare function startCardKeyedPayment(start: CardStart): Promise<PosPaymentOutcome & {
158
+ export declare function startCardKeyedPayment(start: CardStart & {
159
+ paymentMethodId?: string;
160
+ }): Promise<PosPaymentOutcome & {
152
161
  clientSecret?: string;
153
162
  }>;
163
+ /** What a typed card that needs the cardholder's bank to approve it says. */
164
+ export declare const KEYED_CARD_NEEDS_AUTHENTICATION = "This card needs the cardholder to approve the payment with their bank, which a typed card cannot do. Use Card (QR) so they can approve it on their phone.";
154
165
  /**
155
166
  * The customer pays on their own phone from a QR code: a Stripe payment page
156
167
  * for this payment's amount (and tip, as its own line). Settled by
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
17
+ */ import { createHash } from "node:crypto";
18
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
18
19
  import { merchantAccountIsReady } from "@aglyn/tenant-data-admin/server/payment-provider";
19
20
  import { cardAuthenticationParams, checkoutSessionCardAuthenticationParams } from "@aglyn/tenant-data-admin/server/stripe-card-authentication";
20
21
  import * as CommerceModel from "../model/index.js";
@@ -105,6 +106,24 @@ export function posTerminalAddressProblem(address) {
105
106
  if (!/^[A-Z]{2}$/.test(String(address.country))) return 'Choose a two-letter country code, like US.';
106
107
  return null;
107
108
  }
109
+ /**
110
+ * The idempotency key of a site's Location request. Two presses with the same
111
+ * address share it, so a double tap makes one Location; a corrected address
112
+ * gets its own, since Stripe refuses a key reused with other parameters for a
113
+ * day (a merchant fixing a typo would otherwise read that refusal).
114
+ */ export function posTerminalLocationKey(hostId, displayName, address) {
115
+ var _address_line2, _address_state;
116
+ const fingerprint = createHash('sha256').update(JSON.stringify([
117
+ displayName.slice(0, 100),
118
+ address.line1,
119
+ (_address_line2 = address.line2) != null ? _address_line2 : '',
120
+ address.city,
121
+ (_address_state = address.state) != null ? _address_state : '',
122
+ address.postalCode,
123
+ address.country
124
+ ])).digest('hex').slice(0, 16);
125
+ return `pos-location:${hostId}:${fingerprint}`;
126
+ }
108
127
  /**
109
128
  * The site's Terminal Location, created on first use (on the PLATFORM, with
110
129
  * the merchant named in metadata). Its address is the store's, because Stripe
@@ -127,7 +146,7 @@ export function posTerminalAddressProblem(address) {
127
146
  };
128
147
  const address = options.address;
129
148
  const created = await posStripe('POST', 'terminal/locations', {
130
- idempotencyKey: `pos-location:${options.hostId}`,
149
+ idempotencyKey: posTerminalLocationKey(options.hostId, options.displayName, address),
131
150
  params: {
132
151
  display_name: options.displayName.slice(0, 100) || 'Store',
133
152
  'address[line1]': address.line1,
@@ -570,7 +589,16 @@ async function sendToReader(input) {
570
589
  * the Payment Element. No MOTO: the card is keyed into Stripe's own field and
571
590
  * goes through Stripe's normal online checks, 3-D Secure included.
572
591
  */ export async function startCardKeyedPayment(start) {
592
+ var _start_paymentMethodId;
573
593
  var _intent_body, _intent_body1;
594
+ const paymentMethodId = (_start_paymentMethodId = start.paymentMethodId) != null ? _start_paymentMethodId : '';
595
+ if (paymentMethodId && !isPaymentMethodId(paymentMethodId)) {
596
+ return {
597
+ ok: false,
598
+ status: 400,
599
+ error: 'The card could not be read. Enter it again.'
600
+ };
601
+ }
574
602
  const destination = await posMerchantAccount(start.hostId, start.org);
575
603
  if (!destination) return {
576
604
  ok: false,
@@ -600,9 +628,60 @@ async function sendToReader(input) {
600
628
  paymentIntentId: String(intent.body.id),
601
629
  livemode: Boolean(intent.body.livemode)
602
630
  }));
603
- return _extends({}, updated, {
631
+ if (!paymentMethodId) return _extends({}, updated, {
604
632
  clientSecret: String(intent.body.client_secret)
605
633
  });
634
+ return await confirmKeyedCard(start, payment.id, String(intent.body.id), paymentMethodId);
635
+ }
636
+ /** A PaymentMethod id as Stripe mints them; anything else never reaches Stripe. */ function isPaymentMethodId(value) {
637
+ return /^pm_[A-Za-z0-9]{8,64}$/.test(value);
638
+ }
639
+ /** What a typed card that needs the cardholder's bank to approve it says. */ export const KEYED_CARD_NEEDS_AUTHENTICATION = 'This card needs the cardholder to approve the payment with their bank, which a typed card cannot do. Use Card (QR) so they can approve it on their phone.';
640
+ /**
641
+ * A card typed into the register's own card fields (AGL-3848): the device
642
+ * sent the number to Stripe alone, which answered with a PaymentMethod, and
643
+ * hands this route only its id. The server confirms the intent with it, with
644
+ * the platform's secret key, and records the payment from Stripe's answer as
645
+ * every card payment is. A card whose bank asks for the cardholder's approval
646
+ * (3-D Secure) cannot be approved at the register, so that intent is released
647
+ * and the payment fails with words that point at Card (QR).
648
+ */ async function confirmKeyedCard(start, paymentId, intentId, paymentMethodId) {
649
+ var _ref, _ref1;
650
+ var _confirmed_body, _confirmed_body_error_payment_intent, _confirmed_body_error, _confirmed_body1, _confirmed_body2;
651
+ const input = {
652
+ hostId: start.hostId,
653
+ orderId: start.orderId,
654
+ paymentId
655
+ };
656
+ const confirmed = await posStripe('POST', `payment_intents/${intentId}/confirm`, {
657
+ idempotencyKey: `pos-keyed-confirm:${intentId}:${paymentMethodId}`,
658
+ params: {
659
+ payment_method: paymentMethodId
660
+ }
661
+ });
662
+ const status = String((_ref = (_ref1 = (_confirmed_body = confirmed.body) == null ? void 0 : _confirmed_body.status) != null ? _ref1 : (_confirmed_body1 = confirmed.body) == null ? void 0 : (_confirmed_body_error = _confirmed_body1.error) == null ? void 0 : (_confirmed_body_error_payment_intent = _confirmed_body_error.payment_intent) == null ? void 0 : _confirmed_body_error_payment_intent.status) != null ? _ref : '');
663
+ if (status === 'requires_action') {
664
+ await posStripe('POST', `payment_intents/${intentId}/cancel`, {
665
+ idempotencyKey: `pos-cancel:${intentId}`
666
+ });
667
+ return await patchCardPayment(start.hostId, start.orderId, paymentId, (current)=>current.status === 'pending' ? _extends({}, current, {
668
+ status: 'failed',
669
+ failureMessage: KEYED_CARD_NEEDS_AUTHENTICATION
670
+ }) : null);
671
+ }
672
+ if (!confirmed.ok && ((_confirmed_body2 = confirmed.body) == null ? void 0 : _confirmed_body2.error) && !confirmed.body.error.payment_intent) {
673
+ // Refused before the card was tried (a stale method, a bad request): say so, leave nothing pending.
674
+ const message = posStripeErrorMessage(confirmed.body, 'The card was not accepted.');
675
+ await posStripe('POST', `payment_intents/${intentId}/cancel`, {
676
+ idempotencyKey: `pos-cancel:${intentId}`
677
+ });
678
+ return await patchCardPayment(start.hostId, start.orderId, paymentId, (current)=>current.status === 'pending' ? _extends({}, current, {
679
+ status: 'failed',
680
+ failureMessage: message
681
+ }) : null);
682
+ }
683
+ // Approved, declined or still processing: Stripe's own read of the intent decides.
684
+ return await refreshPosCardPayment(input);
606
685
  }
607
686
  /**
608
687
  * The customer pays on their own phone from a QR code: a Stripe payment page