@aglyn/plugins-commerce 1.22.2 → 1.22.4
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.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-commerce",
|
|
3
|
-
"version": "1.22.
|
|
3
|
+
"version": "1.22.4",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,18 +25,18 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.22.
|
|
29
|
-
"@aglyn/shared-data-mdi": "1.22.
|
|
30
|
-
"@aglyn/shared-ui-jsx": "1.22.
|
|
31
|
-
"@aglyn/shared-ui-next": "1.22.
|
|
32
|
-
"@aglyn/shared-ui-snackstack": "1.22.
|
|
33
|
-
"@aglyn/shared-util-email": "1.22.
|
|
34
|
-
"@aglyn/shared-util-http": "1.22.
|
|
35
|
-
"@aglyn/shared-util-timestamp": "1.22.
|
|
36
|
-
"@aglyn/shared-util-tools": "1.22.
|
|
37
|
-
"@aglyn/tenant-data-admin": "1.22.
|
|
38
|
-
"@aglyn/tenant-feature-instance": "1.22.
|
|
39
|
-
"@aglyn/tenant-runtime": "1.22.
|
|
28
|
+
"@aglyn/aglyn": "1.22.4",
|
|
29
|
+
"@aglyn/shared-data-mdi": "1.22.4",
|
|
30
|
+
"@aglyn/shared-ui-jsx": "1.22.4",
|
|
31
|
+
"@aglyn/shared-ui-next": "1.22.4",
|
|
32
|
+
"@aglyn/shared-ui-snackstack": "1.22.4",
|
|
33
|
+
"@aglyn/shared-util-email": "1.22.4",
|
|
34
|
+
"@aglyn/shared-util-http": "1.22.4",
|
|
35
|
+
"@aglyn/shared-util-timestamp": "1.22.4",
|
|
36
|
+
"@aglyn/shared-util-tools": "1.22.4",
|
|
37
|
+
"@aglyn/tenant-data-admin": "1.22.4",
|
|
38
|
+
"@aglyn/tenant-feature-instance": "1.22.4",
|
|
39
|
+
"@aglyn/tenant-runtime": "1.22.4",
|
|
40
40
|
"@stripe/react-stripe-js": "^7.0.1",
|
|
41
41
|
"@stripe/stripe-js": "^10.2.1",
|
|
42
42
|
"@swc/helpers": "0.5.24",
|
|
@@ -363,7 +363,7 @@ const STATUS_COLOR = {
|
|
|
363
363
|
})
|
|
364
364
|
]
|
|
365
365
|
}) : null,
|
|
366
|
-
payment.status === 'failed' && payment.method === 'card_present' && !paid ? /*#__PURE__*/ _jsx(Button, {
|
|
366
|
+
payment.status === 'failed' && payment.method === 'card_present' && payment.readerId && !paid ? /*#__PURE__*/ _jsx(Button, {
|
|
367
367
|
size: "small",
|
|
368
368
|
onClick: ()=>void run('retry', {
|
|
369
369
|
paymentId: payment.id
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos/pos-tender-panel.component.tsx"],"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'use client'\n\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Divider,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useMerchantPayments } from '@aglyn/tenant-feature-instance'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport * as CommerceModel from '../../../model'\nimport {\n centsFromInput,\n newAttemptKey,\n posCreditLookup,\n posGiftCardBalance,\n posNativeBridge,\n posTender,\n PosRequestError,\n usd,\n type PosRegisterContext,\n type PosSaleSummary,\n type PosTenderAction,\n type PosTenderResult,\n} from './pos-api'\nimport { POS_TOUCH_PX } from './pos-product-grid.component'\nimport {\n PosCashDialog,\n PosCreditDialog,\n PosFolioDialog,\n PosGiftCardDialog,\n PosKeyedCardDialog,\n PosQrDialog,\n} from './pos-tender-dialogs.component'\nimport type { PosDisplayControl } from './use-pos-display'\n\ntype User = Parameters<typeof posTender>[0]\n\nconst STATUS_LABEL: Record<CommerceModel.OrderPaymentStatus, string> = {\n pending: 'Waiting',\n succeeded: 'Approved',\n failed: 'Declined',\n canceled: 'Canceled',\n reversed: 'Returned',\n}\n\nconst STATUS_COLOR: Record<\n CommerceModel.OrderPaymentStatus,\n 'default' | 'success' | 'error' | 'warning' | 'info'\n> = {\n pending: 'info',\n succeeded: 'success',\n failed: 'error',\n canceled: 'default',\n reversed: 'warning',\n}\n\nexport interface PosTenderPanelProps {\n user: User\n hostId: string\n registerId: string\n sale: PosSaleSummary\n context: PosRegisterContext | null\n stays: any[]\n display: PosDisplayControl\n onSale: (sale: PosSaleSummary) => void\n /** The sale is voided: the basket is the cashier's again. */\n onVoided: () => void\n /** The tip chosen for the next payment, before it is taken. */\n onTipChange?: (tipCents: number) => void\n /** A PIN-switched cashier (AGL-3609) takes each payment they start. */\n cashierAssertion?: string\n notify: (message: string, variant: 'success' | 'error' | 'warning' | 'info') => void\n /**\n * The register is offline (AGL-3625). Every tender here is the server's —\n * the card reader, the typed card, the QR link, the gift card, the room\n * charge and this sale's own cash — so each is off until it returns.\n */\n offline?: boolean\n /** Rings this basket as an offline cash sale instead; offered while nothing is paid. */\n onSellOffline?: () => void\n}\n\n/**\n * Taking payment on an open sale (AGL-3607): the balance due, every payment\n * taken so far with its live status, and the tenders. A sale can take as many\n * payments as it needs; it is paid when the balance reaches zero, and only\n * then does the server take the stock and complete it.\n */\nexport function PosTenderPanel(props: PosTenderPanelProps) {\n const { user, hostId, sale, context, display, onSale, notify } = props\n const settings = context?.settings\n // Card tenders all charge through the workspace's Stripe account. They stay\n // on screen without one, disabled with the reason, so the register says\n // what to set up instead of losing the buttons or refusing after a tap.\n const payments = useMerchantPayments(hostId)\n const cardsBlocked = payments.blocked\n const cardsReason = payments.reason ?? ''\n const [amount, setAmount] = useState('')\n const [tipCents, setTipCents] = useState(0)\n const [busy, setBusy] = useState(false)\n const [dialog, setDialog] = useState<'cash' | 'gift' | 'folio' | 'credit' | null>(null)\n // The store-credit provider whose dialog is open (AGL-3640).\n const [creditProvider, setCreditProvider] = useState<{ providerId: string; label: string; lookup: boolean } | null>(\n null,\n )\n const [qr, setQr] = useState<{ url: string; amountCents: number } | null>(null)\n const [keyed, setKeyed] = useState<{\n clientSecret: string\n amountCents: number\n paymentId: string\n stripeAccount?: string\n } | null>(null)\n const [readerId, setReaderId] = useState('')\n const inFlight = useRef(false)\n const { confirm } = useConfirmationContext()\n const { onTipChange } = props\n useEffect(() => {\n onTipChange?.(tipCents)\n }, [onTipChange, tipCents])\n\n const readers = (context?.readers ?? []).filter(\n (reader) => !reader.registerId || reader.registerId === props.registerId,\n )\n useEffect(() => {\n if (!readerId && readers.length) {\n setReaderId(readers.find((reader) => reader.registerId === props.registerId)?.id ?? readers[0].id)\n }\n }, [readerId, readers, props.registerId])\n\n // The amount defaults to whatever is still open; a split is the cashier\n // typing less than that.\n const typedCents = centsFromInput(amount)\n const chargeCents = typedCents > 0 ? Math.min(typedCents, sale.tenderableCents) : sale.tenderableCents\n const paid = sale.status === 'paid'\n const offline = props.offline === true\n\n const run = useCallback(\n async (\n action: PosTenderAction,\n body: Record<string, unknown> = {},\n starts = false,\n ): Promise<PosTenderResult | null> => {\n if (inFlight.current) return null\n inFlight.current = true\n setBusy(true)\n try {\n const result = await posTender(\n user,\n hostId,\n sale.orderId,\n action,\n starts && props.cashierAssertion ? { ...body, cashierAssertion: props.cashierAssertion } : body,\n starts ? newAttemptKey() : undefined,\n )\n onSale(result.sale)\n if (starts) {\n setAmount('')\n setTipCents(0)\n }\n return result\n } catch (error) {\n notify(error instanceof PosRequestError ? error.message : 'Something went wrong', 'error')\n return null\n } finally {\n inFlight.current = false\n setBusy(false)\n }\n },\n [user, hostId, sale.orderId, onSale, notify, props.cashierAssertion],\n )\n\n // Card payments still waiting are checked every two seconds: the reader,\n // the QR page and the typed card all settle on the server, and this is the\n // register's view of it (the webhook does the same thing when it lands).\n const pending = sale.payments.filter(\n (payment) => payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method),\n )\n const pendingKey = pending.map((payment) => payment.id).join(',')\n const latest = useRef({ user, onSale })\n latest.current = { user, onSale }\n useEffect(() => {\n if (!pendingKey) return undefined\n const timer = setInterval(async () => {\n for (const id of pendingKey.split(',')) {\n try {\n const result = await posTender(latest.current.user, hostId, sale.orderId, 'status', {\n paymentId: id,\n })\n latest.current.onSale(result.sale)\n } catch {\n // The next tick asks again.\n }\n }\n }, 2000)\n return () => clearInterval(timer)\n }, [pendingKey, hostId, sale.orderId])\n\n // The display shows \"tap your card\" while a reader payment waits, and the\n // running balance otherwise.\n const readerWaiting = pending.some((payment) => payment.method === 'card_present')\n useEffect(() => {\n if (!display.connected || display.asking) return\n if (readerWaiting) {\n void display.show({ mode: 'processing', processing: { message: 'Tap, insert or swipe your card on the reader.' } })\n }\n }, [readerWaiting, display])\n\n const askTip = useCallback(async () => {\n const base = chargeCents\n if (!(base > 0) || !settings) return\n const answer = await display.ask({\n mode: 'tip',\n tip: { baseCents: base, percentages: settings.tipPercentages, allowCustom: true },\n })\n if (answer) {\n setTipCents(answer.tipCents ?? 0)\n notify(answer.tipCents ? `Tip: ${usd(answer.tipCents)}` : 'No tip', 'info')\n }\n }, [chargeCents, settings, display, notify])\n\n const startCardPresent = useCallback(async () => {\n if (!readerId) return\n await run('card-present', { amountCents: chargeCents, tipCents, readerId }, true)\n }, [run, chargeCents, tipCents, readerId])\n\n const startBridge = useCallback(async () => {\n const bridge = posNativeBridge()\n if (!bridge) return\n const amountCents = chargeCents\n const result = await run('card-present-sdk', { amountCents, tipCents }, true)\n if (!result?.paymentIntentId || !result.clientSecret || !result.paymentId) return\n try {\n const collected = await bridge.collectCardPayment({\n paymentIntentId: result.paymentIntentId,\n clientSecret: result.clientSecret,\n amountCents: amountCents + tipCents,\n })\n if (collected.status !== 'collected') {\n notify(collected.message ?? 'The card was not taken.', 'warning')\n }\n } finally {\n // Settled by the server either way: the status poll captures an\n // authorized tap and records a decline or a cancel.\n await run('status', { paymentId: result.paymentId })\n }\n }, [run, chargeCents, tipCents, notify])\n\n const startKeyed = useCallback(async () => {\n const amountCents = chargeCents\n const result = await run('card-keyed', { amountCents, tipCents }, true)\n if (result?.clientSecret && result.paymentId) {\n setKeyed({\n clientSecret: result.clientSecret,\n amountCents: amountCents + tipCents,\n paymentId: result.paymentId,\n ...(result.stripeAccount ? { stripeAccount: result.stripeAccount } : {}),\n })\n }\n }, [run, chargeCents, tipCents])\n\n const startLink = useCallback(async () => {\n const amountCents = chargeCents\n const result = await run('card-link', { amountCents, tipCents }, true)\n const url = result?.sale.payments.find((payment) => payment.id === result.paymentId)?.checkoutUrl\n if (url) setQr({ url, amountCents: amountCents + tipCents })\n }, [run, chargeCents, tipCents])\n\n const tipOn = Boolean(settings?.tippingEnabled) && !paid\n\n return (\n <Stack spacing={1.5} sx={{ minHeight: 0 }}>\n <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>\n <Typography variant=\"h6\">{paid ? 'Paid' : 'Balance due'}</Typography>\n <Typography variant=\"h4\" component=\"p\">\n {usd(paid ? sale.totalCents : sale.dueCents)}\n </Typography>\n </Box>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Total ${usd(sale.totalCents)} · paid ${usd(sale.paidCents)}` +\n (sale.tipCents ? ` · tips ${usd(sale.tipCents)}` : '')}\n </Typography>\n\n {sale.payments.length ? (\n <Stack spacing={1} aria-label=\"Payments\">\n {sale.payments.map((payment) => (\n <Box key={payment.id} sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>\n <Typography variant=\"body2\" sx={{ flex: 1, minWidth: 140 }}>\n {CommerceModel.describeOrderPayment({ ...payment, atMs: 0 })}\n {payment.changeCents ? ` · change ${usd(payment.changeCents)}` : ''}\n </Typography>\n <Chip size=\"small\" label={STATUS_LABEL[payment.status]} color={STATUS_COLOR[payment.status]} />\n {payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method) ? (\n <>\n {payment.method === 'card_link' && payment.checkoutUrl ? (\n <Button\n size=\"small\"\n onClick={() => setQr({ url: payment.checkoutUrl as string, amountCents: payment.amountCents })}\n >\n {'Show QR'}\n </Button>\n ) : null}\n {payment.method === 'card_present' && payment.livemode === false && context?.terminal?.testMode ? (\n <Button size=\"small\" onClick={() => void run('simulate', { paymentId: payment.id })}>\n {'Simulate tap'}\n </Button>\n ) : null}\n <Button size=\"small\" color=\"error\" onClick={() => void run('cancel', { paymentId: payment.id })}>\n {'Cancel'}\n </Button>\n </>\n ) : null}\n {payment.status === 'failed' && payment.method === 'card_present' && !paid ? (\n <Button size=\"small\" onClick={() => void run('retry', { paymentId: payment.id })}>\n {'Retry'}\n </Button>\n ) : null}\n {payment.failureMessage && payment.status === 'failed' ? (\n <Typography variant=\"caption\" color=\"error\" sx={{ width: 1 }}>\n {payment.failureMessage}\n </Typography>\n ) : null}\n </Box>\n ))}\n </Stack>\n ) : null}\n\n {offline && !paid ? (\n <Alert\n severity=\"warning\"\n action={\n props.onSellOffline && sale.payments.length === 0 ? (\n <Button color=\"inherit\" size=\"small\" onClick={props.onSellOffline}>\n {'Sell for cash offline'}\n </Button>\n ) : null\n }\n >\n {sale.payments.length === 0\n ? 'Offline: card readers, typed cards, the QR link, gift cards, store credit and room charges are off. ' +\n 'Take this basket as an offline cash sale, or wait for the connection.'\n : 'Offline: this sale has a payment on it and finishes when the connection returns. ' +\n 'Card readers, typed cards, the QR link, gift cards, store credit and room charges are off.'}\n </Alert>\n ) : null}\n {!paid && !offline && cardsBlocked ? (\n <PrerequisiteNotice href={payments.href ?? undefined} actionLabel=\"Open Payments\">\n {`${cardsReason} Cash, gift cards and store credit work without it.`}\n </PrerequisiteNotice>\n ) : null}\n {!paid ? (\n <>\n <Divider />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n label=\"Amount to charge ($)\"\n placeholder={(sale.tenderableCents / 100).toFixed(2)}\n value={amount}\n onChange={(event) => setAmount(event.target.value.replace(/[^0-9.]/g, ''))}\n sx={{ flex: 1 }}\n helperText={\n typedCents > 0 && typedCents < sale.tenderableCents\n ? `Split: ${usd(sale.tenderableCents - typedCents)} stays open`\n : ' '\n }\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n </Stack>\n {tipOn ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"body2\" sx={{ mr: 1 }}>\n {`Tip ${usd(tipCents)}`}\n </Typography>\n {display.connected ? (\n <Button\n variant=\"outlined\"\n onClick={() => void askTip()}\n disabled={offline || busy || Boolean(display.asking)}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {display.asking === 'tip' ? 'Waiting for customer…' : 'Ask on display'}\n </Button>\n ) : null}\n {(settings?.tipPercentages ?? []).map((pct) => (\n <Button\n key={pct}\n variant={tipCents === CommerceModel.posTipFromPercent(chargeCents, pct) && tipCents > 0 ? 'contained' : 'outlined'}\n onClick={() => setTipCents(CommerceModel.posTipFromPercent(chargeCents, pct))}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {`${pct}%`}\n </Button>\n ))}\n <Button onClick={() => setTipCents(0)} sx={{ minHeight: POS_TOUCH_PX }}>\n {'No tip'}\n </Button>\n </Stack>\n ) : null}\n <Box\n sx={{\n display: 'grid',\n gap: 1,\n gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',\n }}\n >\n <Button\n variant=\"contained\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => setDialog('cash')}\n sx={{ minHeight: 56 }}\n >\n {'Cash'}\n </Button>\n {context?.terminal?.available && readers.length ? (\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"contained\"\n disabled={offline || busy || chargeCents <= 0 || !readerId}\n onClick={() => void startCardPresent()}\n sx={{ minHeight: 56 }}\n >\n {'Card reader'}\n </Button>\n </BlockedControl>\n ) : null}\n {posNativeBridge() ? (\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"contained\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => void startBridge()}\n sx={{ minHeight: 56 }}\n >\n {'Tap to Pay / Bluetooth reader'}\n </Button>\n </BlockedControl>\n ) : null}\n {context?.publishableKey ? (\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => void startKeyed()}\n sx={{ minHeight: 56 }}\n >\n {'Type card'}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => void startLink()}\n sx={{ minHeight: 56 }}\n >\n {'Card (QR)'}\n </Button>\n </BlockedControl>\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => setDialog('gift')}\n sx={{ minHeight: 56 }}\n >\n {'Gift card'}\n </Button>\n {(context?.credits ?? []).map((credit) => (\n <Button\n key={credit.providerId}\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => {\n setCreditProvider(credit)\n setDialog('credit')\n }}\n sx={{ minHeight: 56 }}\n >\n {credit.label}\n </Button>\n ))}\n {props.stays.length ? (\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => setDialog('folio')}\n sx={{ minHeight: 56 }}\n >\n {'Room'}\n </Button>\n ) : null}\n </Box>\n {context?.terminal?.available && readers.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Card reader\"\n value={readerId}\n onChange={(event) => setReaderId(event.target.value)}\n >\n {readers.map((reader) => (\n <MenuItem key={reader.id} value={reader.id}>\n {`${reader.label}${reader.status === 'online' ? '' : ' (offline)'}`}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {readers.some((reader) => reader.id === readerId && reader.status !== 'online') ? (\n <Alert severity=\"warning\">{'The selected card reader looks offline.'}</Alert>\n ) : null}\n <Button\n color=\"error\"\n disabled={offline || busy}\n onClick={async () => {\n const confirmed = await confirm({\n title: 'Void this sale?',\n description:\n 'Every payment taken on it is handed back: cards are refunded, gift ' +\n 'cards and store credit re-credited and room charges removed. Hand back any cash.',\n confirmationText: 'Void sale',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n const result = await run('void')\n if (result) {\n notify('Sale voided', 'info')\n props.onVoided()\n }\n }}\n sx={{ minHeight: POS_TOUCH_PX, alignSelf: 'flex-start' }}\n >\n {'Void sale'}\n </Button>\n </>\n ) : null}\n\n <PosCashDialog\n open={dialog === 'cash'}\n dueCents={chargeCents}\n tipCents={tipCents}\n busy={busy}\n onClose={() => setDialog(null)}\n onTake={async (tenderedCents) => {\n const result = await run(\n 'cash',\n {\n tenderedCents,\n ...(typedCents > 0 ? { amountCents: chargeCents } : {}),\n tipCents,\n },\n true,\n )\n if (result) {\n setDialog(null)\n const change = result.sale.payments.find((payment) => payment.id === result.paymentId)?.changeCents\n if (change) notify(`Change due: ${usd(change)}`, 'success')\n }\n }}\n />\n <PosGiftCardDialog\n open={dialog === 'gift'}\n busy={busy}\n onClose={() => setDialog(null)}\n onCheck={async (code) => {\n try {\n return await posGiftCardBalance(user, hostId, code)\n } catch (error) {\n notify(error instanceof PosRequestError ? error.message : 'Could not read that card', 'warning')\n return null\n }\n }}\n onApply={async (code) => {\n const result = await run('gift-card', { code, ...(typedCents > 0 ? { amountCents: chargeCents } : {}) }, true)\n if (result) setDialog(null)\n }}\n />\n <PosCreditDialog\n open={dialog === 'credit' && Boolean(creditProvider)}\n label={creditProvider?.label ?? 'Store credit'}\n canLookup={Boolean(creditProvider?.lookup)}\n busy={busy}\n onClose={() => setDialog(null)}\n onLookup={async (query) => {\n if (!creditProvider) return null\n try {\n return (await posCreditLookup(user, hostId, creditProvider.providerId, query)).accounts\n } catch (error) {\n notify(error instanceof PosRequestError ? error.message : 'Could not look that up', 'warning')\n return null\n }\n }}\n onApplyCode={async (code) => {\n const result = await run('credit', { code, ...(typedCents > 0 ? { amountCents: chargeCents } : {}) }, true)\n if (result) setDialog(null)\n }}\n onApplyAccount={async (account) => {\n if (!creditProvider) return\n const result = await run(\n 'credit',\n {\n providerId: creditProvider.providerId,\n reference: account.reference,\n ...(typedCents > 0 ? { amountCents: chargeCents } : {}),\n },\n true,\n )\n if (result) setDialog(null)\n }}\n />\n <PosFolioDialog\n open={dialog === 'folio'}\n amountCents={chargeCents}\n stays={props.stays}\n busy={busy}\n onClose={() => setDialog(null)}\n onCharge={async (reservationId) => {\n const result = await run(\n 'folio',\n { reservationId, ...(typedCents > 0 ? { amountCents: chargeCents } : {}) },\n true,\n )\n if (result) setDialog(null)\n }}\n />\n <PosQrDialog url={qr?.url ?? ''} amountCents={qr?.amountCents ?? 0} onClose={() => setQr(null)} />\n <PosKeyedCardDialog\n clientSecret={keyed?.clientSecret ?? ''}\n publishableKey={context?.publishableKey ?? ''}\n stripeAccount={keyed?.stripeAccount ?? ''}\n amountCents={keyed?.amountCents ?? 0}\n onClose={async () => {\n const open = keyed\n setKeyed(null)\n // Closing without paying releases the amount for another tender.\n if (open) await run('cancel', { paymentId: open.paymentId })\n }}\n onConfirmed={async () => {\n const open = keyed\n setKeyed(null)\n if (open) await run('status', { paymentId: open.paymentId })\n }}\n />\n </Stack>\n )\n}\nPosTenderPanel.displayName = 'PosTenderPanel'\n"],"names":["Alert","Box","Button","Chip","Divider","MenuItem","Stack","TextField","Typography","useConfirmationContext","BlockedControl","PrerequisiteNotice","useMerchantPayments","useCallback","useEffect","useRef","useState","CommerceModel","centsFromInput","newAttemptKey","posCreditLookup","posGiftCardBalance","posNativeBridge","posTender","PosRequestError","usd","POS_TOUCH_PX","PosCashDialog","PosCreditDialog","PosFolioDialog","PosGiftCardDialog","PosKeyedCardDialog","PosQrDialog","STATUS_LABEL","pending","succeeded","failed","canceled","reversed","STATUS_COLOR","PosTenderPanel","props","payments","context","user","hostId","sale","display","onSale","notify","settings","cardsBlocked","blocked","cardsReason","reason","amount","setAmount","tipCents","setTipCents","busy","setBusy","dialog","setDialog","creditProvider","setCreditProvider","qr","setQr","keyed","setKeyed","readerId","setReaderId","inFlight","confirm","onTipChange","readers","filter","reader","registerId","length","find","id","typedCents","chargeCents","Math","min","tenderableCents","paid","status","offline","run","action","body","starts","current","result","orderId","cashierAssertion","undefined","error","message","payment","isCardPaymentMethod","method","pendingKey","map","join","latest","timer","setInterval","split","paymentId","clearInterval","readerWaiting","some","connected","asking","show","mode","processing","askTip","base","answer","ask","tip","baseCents","percentages","tipPercentages","allowCustom","startCardPresent","amountCents","startBridge","bridge","paymentIntentId","clientSecret","collected","collectCardPayment","startKeyed","stripeAccount","startLink","url","checkoutUrl","tipOn","Boolean","tippingEnabled","spacing","sx","minHeight","justifyContent","alignItems","variant","component","totalCents","dueCents","color","paidCents","aria-label","gap","flexWrap","flex","minWidth","describeOrderPayment","atMs","changeCents","size","label","onClick","livemode","terminal","testMode","failureMessage","width","severity","onSellOffline","href","actionLabel","direction","placeholder","toFixed","value","onChange","event","target","replace","helperText","slotProps","htmlInput","inputMode","rowGap","mr","disabled","pct","posTipFromPercent","gridTemplateColumns","available","fullWidth","publishableKey","credits","credit","providerId","stays","select","confirmed","title","description","confirmationText","confirmationButtonProps","then","catch","onVoided","alignSelf","open","onClose","onTake","tenderedCents","change","onCheck","code","onApply","canLookup","lookup","onLookup","query","accounts","onApplyCode","onApplyAccount","account","reference","onCharge","reservationId","onConfirmed","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAChE,YAAYC,mBAAmB,0BAAgB;AAC/C,SACEC,cAAc,EACdC,aAAa,EACbC,eAAe,EACfC,kBAAkB,EAClBC,eAAe,EACfC,SAAS,EACTC,eAAe,EACfC,GAAG,QAKE,eAAW;AAClB,SAASC,YAAY,QAAQ,kCAA8B;AAC3D,SACEC,aAAa,EACbC,eAAe,EACfC,cAAc,EACdC,iBAAiB,EACjBC,kBAAkB,EAClBC,WAAW,QACN,oCAAgC;AAKvC,MAAMC,eAAiE;IACrEC,SAAS;IACTC,WAAW;IACXC,QAAQ;IACRC,UAAU;IACVC,UAAU;AACZ;AAEA,MAAMC,eAGF;IACFL,SAAS;IACTC,WAAW;IACXC,QAAQ;IACRC,UAAU;IACVC,UAAU;AACZ;AA4BA;;;;;CAKC,GACD,OAAO,SAASE,eAAeC,KAA0B;QAQnCC,wBAyPYA;QAmErBC,mBA+EFA;IAlZT,MAAM,EAAEC,IAAI,EAAEC,MAAM,EAAEC,IAAI,EAAEH,OAAO,EAAEI,OAAO,EAAEC,MAAM,EAAEC,MAAM,EAAE,GAAGR;IACjE,MAAMS,WAAWP,2BAAAA,QAASO,QAAQ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,KAAK;gBAClB5I,MAAMA;gBACNwJ,SAAS,IAAMrJ,UAAU;gBACzBqK,UAAU,OAAOC;oBACf,MAAMtI,SAAS,MAAML,IACnB,SACA;wBAAE2I;uBAAmBnJ,aAAa,IAAI;wBAAEgD,aAAa/C;oBAAY,IAAI,CAAC,IACtE;oBAEF,IAAIY,QAAQhC,UAAU;gBACxB;;0BAEF,KAAC9B;gBAAY2G,GAAG,WAAE1E,sBAAAA,GAAI0E,GAAG,oBAAI;gBAAIV,WAAW,WAAEhE,sBAAAA,GAAIgE,WAAW,oBAAI;gBAAGkF,SAAS,IAAMjJ,MAAM;;0BACzF,KAACnC;gBACCsG,YAAY,WAAElE,yBAAAA,MAAOkE,YAAY,oBAAI;gBACrC8D,cAAc,WAAExJ,2BAAAA,QAASwJ,cAAc,oBAAI;gBAC3C1D,aAAa,WAAEtE,yBAAAA,MAAOsE,aAAa,oBAAI;gBACvCR,WAAW,WAAE9D,yBAAAA,MAAO8D,WAAW,oBAAI;gBACnCkF,SAAS;oBACP,MAAMD,OAAO/I;oBACbC,SAAS;oBACT,iEAAiE;oBACjE,IAAI8I,MAAM,MAAMzH,IAAI,UAAU;wBAAEqB,WAAWoG,KAAKpG,SAAS;oBAAC;gBAC5D;gBACAuH,aAAa;oBACX,MAAMnB,OAAO/I;oBACbC,SAAS;oBACT,IAAI8I,MAAM,MAAMzH,IAAI,UAAU;wBAAEqB,WAAWoG,KAAKpG,SAAS;oBAAC;gBAC5D;;;;AAIR;AACAtE,eAAe8L,WAAW,GAAG"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos/pos-tender-panel.component.tsx"],"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'use client'\n\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Divider,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport { useMerchantPayments } from '@aglyn/tenant-feature-instance'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport * as CommerceModel from '../../../model'\nimport {\n centsFromInput,\n newAttemptKey,\n posCreditLookup,\n posGiftCardBalance,\n posNativeBridge,\n posTender,\n PosRequestError,\n usd,\n type PosRegisterContext,\n type PosSaleSummary,\n type PosTenderAction,\n type PosTenderResult,\n} from './pos-api'\nimport { POS_TOUCH_PX } from './pos-product-grid.component'\nimport {\n PosCashDialog,\n PosCreditDialog,\n PosFolioDialog,\n PosGiftCardDialog,\n PosKeyedCardDialog,\n PosQrDialog,\n} from './pos-tender-dialogs.component'\nimport type { PosDisplayControl } from './use-pos-display'\n\ntype User = Parameters<typeof posTender>[0]\n\nconst STATUS_LABEL: Record<CommerceModel.OrderPaymentStatus, string> = {\n pending: 'Waiting',\n succeeded: 'Approved',\n failed: 'Declined',\n canceled: 'Canceled',\n reversed: 'Returned',\n}\n\nconst STATUS_COLOR: Record<\n CommerceModel.OrderPaymentStatus,\n 'default' | 'success' | 'error' | 'warning' | 'info'\n> = {\n pending: 'info',\n succeeded: 'success',\n failed: 'error',\n canceled: 'default',\n reversed: 'warning',\n}\n\nexport interface PosTenderPanelProps {\n user: User\n hostId: string\n registerId: string\n sale: PosSaleSummary\n context: PosRegisterContext | null\n stays: any[]\n display: PosDisplayControl\n onSale: (sale: PosSaleSummary) => void\n /** The sale is voided: the basket is the cashier's again. */\n onVoided: () => void\n /** The tip chosen for the next payment, before it is taken. */\n onTipChange?: (tipCents: number) => void\n /** A PIN-switched cashier (AGL-3609) takes each payment they start. */\n cashierAssertion?: string\n notify: (message: string, variant: 'success' | 'error' | 'warning' | 'info') => void\n /**\n * The register is offline (AGL-3625). Every tender here is the server's —\n * the card reader, the typed card, the QR link, the gift card, the room\n * charge and this sale's own cash — so each is off until it returns.\n */\n offline?: boolean\n /** Rings this basket as an offline cash sale instead; offered while nothing is paid. */\n onSellOffline?: () => void\n}\n\n/**\n * Taking payment on an open sale (AGL-3607): the balance due, every payment\n * taken so far with its live status, and the tenders. A sale can take as many\n * payments as it needs; it is paid when the balance reaches zero, and only\n * then does the server take the stock and complete it.\n */\nexport function PosTenderPanel(props: PosTenderPanelProps) {\n const { user, hostId, sale, context, display, onSale, notify } = props\n const settings = context?.settings\n // Card tenders all charge through the workspace's Stripe account. They stay\n // on screen without one, disabled with the reason, so the register says\n // what to set up instead of losing the buttons or refusing after a tap.\n const payments = useMerchantPayments(hostId)\n const cardsBlocked = payments.blocked\n const cardsReason = payments.reason ?? ''\n const [amount, setAmount] = useState('')\n const [tipCents, setTipCents] = useState(0)\n const [busy, setBusy] = useState(false)\n const [dialog, setDialog] = useState<'cash' | 'gift' | 'folio' | 'credit' | null>(null)\n // The store-credit provider whose dialog is open (AGL-3640).\n const [creditProvider, setCreditProvider] = useState<{ providerId: string; label: string; lookup: boolean } | null>(\n null,\n )\n const [qr, setQr] = useState<{ url: string; amountCents: number } | null>(null)\n const [keyed, setKeyed] = useState<{\n clientSecret: string\n amountCents: number\n paymentId: string\n stripeAccount?: string\n } | null>(null)\n const [readerId, setReaderId] = useState('')\n const inFlight = useRef(false)\n const { confirm } = useConfirmationContext()\n const { onTipChange } = props\n useEffect(() => {\n onTipChange?.(tipCents)\n }, [onTipChange, tipCents])\n\n const readers = (context?.readers ?? []).filter(\n (reader) => !reader.registerId || reader.registerId === props.registerId,\n )\n useEffect(() => {\n if (!readerId && readers.length) {\n setReaderId(readers.find((reader) => reader.registerId === props.registerId)?.id ?? readers[0].id)\n }\n }, [readerId, readers, props.registerId])\n\n // The amount defaults to whatever is still open; a split is the cashier\n // typing less than that.\n const typedCents = centsFromInput(amount)\n const chargeCents = typedCents > 0 ? Math.min(typedCents, sale.tenderableCents) : sale.tenderableCents\n const paid = sale.status === 'paid'\n const offline = props.offline === true\n\n const run = useCallback(\n async (\n action: PosTenderAction,\n body: Record<string, unknown> = {},\n starts = false,\n ): Promise<PosTenderResult | null> => {\n if (inFlight.current) return null\n inFlight.current = true\n setBusy(true)\n try {\n const result = await posTender(\n user,\n hostId,\n sale.orderId,\n action,\n starts && props.cashierAssertion ? { ...body, cashierAssertion: props.cashierAssertion } : body,\n starts ? newAttemptKey() : undefined,\n )\n onSale(result.sale)\n if (starts) {\n setAmount('')\n setTipCents(0)\n }\n return result\n } catch (error) {\n notify(error instanceof PosRequestError ? error.message : 'Something went wrong', 'error')\n return null\n } finally {\n inFlight.current = false\n setBusy(false)\n }\n },\n [user, hostId, sale.orderId, onSale, notify, props.cashierAssertion],\n )\n\n // Card payments still waiting are checked every two seconds: the reader,\n // the QR page and the typed card all settle on the server, and this is the\n // register's view of it (the webhook does the same thing when it lands).\n const pending = sale.payments.filter(\n (payment) => payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method),\n )\n const pendingKey = pending.map((payment) => payment.id).join(',')\n const latest = useRef({ user, onSale })\n latest.current = { user, onSale }\n useEffect(() => {\n if (!pendingKey) return undefined\n const timer = setInterval(async () => {\n for (const id of pendingKey.split(',')) {\n try {\n const result = await posTender(latest.current.user, hostId, sale.orderId, 'status', {\n paymentId: id,\n })\n latest.current.onSale(result.sale)\n } catch {\n // The next tick asks again.\n }\n }\n }, 2000)\n return () => clearInterval(timer)\n }, [pendingKey, hostId, sale.orderId])\n\n // The display shows \"tap your card\" while a reader payment waits, and the\n // running balance otherwise.\n const readerWaiting = pending.some((payment) => payment.method === 'card_present')\n useEffect(() => {\n if (!display.connected || display.asking) return\n if (readerWaiting) {\n void display.show({ mode: 'processing', processing: { message: 'Tap, insert or swipe your card on the reader.' } })\n }\n }, [readerWaiting, display])\n\n const askTip = useCallback(async () => {\n const base = chargeCents\n if (!(base > 0) || !settings) return\n const answer = await display.ask({\n mode: 'tip',\n tip: { baseCents: base, percentages: settings.tipPercentages, allowCustom: true },\n })\n if (answer) {\n setTipCents(answer.tipCents ?? 0)\n notify(answer.tipCents ? `Tip: ${usd(answer.tipCents)}` : 'No tip', 'info')\n }\n }, [chargeCents, settings, display, notify])\n\n const startCardPresent = useCallback(async () => {\n if (!readerId) return\n await run('card-present', { amountCents: chargeCents, tipCents, readerId }, true)\n }, [run, chargeCents, tipCents, readerId])\n\n const startBridge = useCallback(async () => {\n const bridge = posNativeBridge()\n if (!bridge) return\n const amountCents = chargeCents\n const result = await run('card-present-sdk', { amountCents, tipCents }, true)\n if (!result?.paymentIntentId || !result.clientSecret || !result.paymentId) return\n try {\n const collected = await bridge.collectCardPayment({\n paymentIntentId: result.paymentIntentId,\n clientSecret: result.clientSecret,\n amountCents: amountCents + tipCents,\n })\n if (collected.status !== 'collected') {\n notify(collected.message ?? 'The card was not taken.', 'warning')\n }\n } finally {\n // Settled by the server either way: the status poll captures an\n // authorized tap and records a decline or a cancel.\n await run('status', { paymentId: result.paymentId })\n }\n }, [run, chargeCents, tipCents, notify])\n\n const startKeyed = useCallback(async () => {\n const amountCents = chargeCents\n const result = await run('card-keyed', { amountCents, tipCents }, true)\n if (result?.clientSecret && result.paymentId) {\n setKeyed({\n clientSecret: result.clientSecret,\n amountCents: amountCents + tipCents,\n paymentId: result.paymentId,\n ...(result.stripeAccount ? { stripeAccount: result.stripeAccount } : {}),\n })\n }\n }, [run, chargeCents, tipCents])\n\n const startLink = useCallback(async () => {\n const amountCents = chargeCents\n const result = await run('card-link', { amountCents, tipCents }, true)\n const url = result?.sale.payments.find((payment) => payment.id === result.paymentId)?.checkoutUrl\n if (url) setQr({ url, amountCents: amountCents + tipCents })\n }, [run, chargeCents, tipCents])\n\n const tipOn = Boolean(settings?.tippingEnabled) && !paid\n\n return (\n <Stack spacing={1.5} sx={{ minHeight: 0 }}>\n <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>\n <Typography variant=\"h6\">{paid ? 'Paid' : 'Balance due'}</Typography>\n <Typography variant=\"h4\" component=\"p\">\n {usd(paid ? sale.totalCents : sale.dueCents)}\n </Typography>\n </Box>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Total ${usd(sale.totalCents)} · paid ${usd(sale.paidCents)}` +\n (sale.tipCents ? ` · tips ${usd(sale.tipCents)}` : '')}\n </Typography>\n\n {sale.payments.length ? (\n <Stack spacing={1} aria-label=\"Payments\">\n {sale.payments.map((payment) => (\n <Box key={payment.id} sx={{ display: 'flex', alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>\n <Typography variant=\"body2\" sx={{ flex: 1, minWidth: 140 }}>\n {CommerceModel.describeOrderPayment({ ...payment, atMs: 0 })}\n {payment.changeCents ? ` · change ${usd(payment.changeCents)}` : ''}\n </Typography>\n <Chip size=\"small\" label={STATUS_LABEL[payment.status]} color={STATUS_COLOR[payment.status]} />\n {payment.status === 'pending' && CommerceModel.isCardPaymentMethod(payment.method) ? (\n <>\n {payment.method === 'card_link' && payment.checkoutUrl ? (\n <Button\n size=\"small\"\n onClick={() => setQr({ url: payment.checkoutUrl as string, amountCents: payment.amountCents })}\n >\n {'Show QR'}\n </Button>\n ) : null}\n {payment.method === 'card_present' && payment.livemode === false && context?.terminal?.testMode ? (\n <Button size=\"small\" onClick={() => void run('simulate', { paymentId: payment.id })}>\n {'Simulate tap'}\n </Button>\n ) : null}\n <Button size=\"small\" color=\"error\" onClick={() => void run('cancel', { paymentId: payment.id })}>\n {'Cancel'}\n </Button>\n </>\n ) : null}\n {/* Retry asks the payment's own smart reader again; a card a native app's reader took has none. */}\n {payment.status === 'failed' && payment.method === 'card_present' && payment.readerId && !paid ? (\n <Button size=\"small\" onClick={() => void run('retry', { paymentId: payment.id })}>\n {'Retry'}\n </Button>\n ) : null}\n {payment.failureMessage && payment.status === 'failed' ? (\n <Typography variant=\"caption\" color=\"error\" sx={{ width: 1 }}>\n {payment.failureMessage}\n </Typography>\n ) : null}\n </Box>\n ))}\n </Stack>\n ) : null}\n\n {offline && !paid ? (\n <Alert\n severity=\"warning\"\n action={\n props.onSellOffline && sale.payments.length === 0 ? (\n <Button color=\"inherit\" size=\"small\" onClick={props.onSellOffline}>\n {'Sell for cash offline'}\n </Button>\n ) : null\n }\n >\n {sale.payments.length === 0\n ? 'Offline: card readers, typed cards, the QR link, gift cards, store credit and room charges are off. ' +\n 'Take this basket as an offline cash sale, or wait for the connection.'\n : 'Offline: this sale has a payment on it and finishes when the connection returns. ' +\n 'Card readers, typed cards, the QR link, gift cards, store credit and room charges are off.'}\n </Alert>\n ) : null}\n {!paid && !offline && cardsBlocked ? (\n <PrerequisiteNotice href={payments.href ?? undefined} actionLabel=\"Open Payments\">\n {`${cardsReason} Cash, gift cards and store credit work without it.`}\n </PrerequisiteNotice>\n ) : null}\n {!paid ? (\n <>\n <Divider />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <TextField\n label=\"Amount to charge ($)\"\n placeholder={(sale.tenderableCents / 100).toFixed(2)}\n value={amount}\n onChange={(event) => setAmount(event.target.value.replace(/[^0-9.]/g, ''))}\n sx={{ flex: 1 }}\n helperText={\n typedCents > 0 && typedCents < sale.tenderableCents\n ? `Split: ${usd(sale.tenderableCents - typedCents)} stays open`\n : ' '\n }\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n </Stack>\n {tipOn ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"body2\" sx={{ mr: 1 }}>\n {`Tip ${usd(tipCents)}`}\n </Typography>\n {display.connected ? (\n <Button\n variant=\"outlined\"\n onClick={() => void askTip()}\n disabled={offline || busy || Boolean(display.asking)}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {display.asking === 'tip' ? 'Waiting for customer…' : 'Ask on display'}\n </Button>\n ) : null}\n {(settings?.tipPercentages ?? []).map((pct) => (\n <Button\n key={pct}\n variant={tipCents === CommerceModel.posTipFromPercent(chargeCents, pct) && tipCents > 0 ? 'contained' : 'outlined'}\n onClick={() => setTipCents(CommerceModel.posTipFromPercent(chargeCents, pct))}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {`${pct}%`}\n </Button>\n ))}\n <Button onClick={() => setTipCents(0)} sx={{ minHeight: POS_TOUCH_PX }}>\n {'No tip'}\n </Button>\n </Stack>\n ) : null}\n <Box\n sx={{\n display: 'grid',\n gap: 1,\n gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',\n }}\n >\n <Button\n variant=\"contained\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => setDialog('cash')}\n sx={{ minHeight: 56 }}\n >\n {'Cash'}\n </Button>\n {context?.terminal?.available && readers.length ? (\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"contained\"\n disabled={offline || busy || chargeCents <= 0 || !readerId}\n onClick={() => void startCardPresent()}\n sx={{ minHeight: 56 }}\n >\n {'Card reader'}\n </Button>\n </BlockedControl>\n ) : null}\n {posNativeBridge() ? (\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"contained\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => void startBridge()}\n sx={{ minHeight: 56 }}\n >\n {'Tap to Pay / Bluetooth reader'}\n </Button>\n </BlockedControl>\n ) : null}\n {context?.publishableKey ? (\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => void startKeyed()}\n sx={{ minHeight: 56 }}\n >\n {'Type card'}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={cardsBlocked} reason={cardsReason} fullWidth>\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => void startLink()}\n sx={{ minHeight: 56 }}\n >\n {'Card (QR)'}\n </Button>\n </BlockedControl>\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => setDialog('gift')}\n sx={{ minHeight: 56 }}\n >\n {'Gift card'}\n </Button>\n {(context?.credits ?? []).map((credit) => (\n <Button\n key={credit.providerId}\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => {\n setCreditProvider(credit)\n setDialog('credit')\n }}\n sx={{ minHeight: 56 }}\n >\n {credit.label}\n </Button>\n ))}\n {props.stays.length ? (\n <Button\n variant=\"outlined\"\n disabled={offline || busy || chargeCents <= 0}\n onClick={() => setDialog('folio')}\n sx={{ minHeight: 56 }}\n >\n {'Room'}\n </Button>\n ) : null}\n </Box>\n {context?.terminal?.available && readers.length > 1 ? (\n <TextField\n select\n size=\"small\"\n label=\"Card reader\"\n value={readerId}\n onChange={(event) => setReaderId(event.target.value)}\n >\n {readers.map((reader) => (\n <MenuItem key={reader.id} value={reader.id}>\n {`${reader.label}${reader.status === 'online' ? '' : ' (offline)'}`}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {readers.some((reader) => reader.id === readerId && reader.status !== 'online') ? (\n <Alert severity=\"warning\">{'The selected card reader looks offline.'}</Alert>\n ) : null}\n <Button\n color=\"error\"\n disabled={offline || busy}\n onClick={async () => {\n const confirmed = await confirm({\n title: 'Void this sale?',\n description:\n 'Every payment taken on it is handed back: cards are refunded, gift ' +\n 'cards and store credit re-credited and room charges removed. Hand back any cash.',\n confirmationText: 'Void sale',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n const result = await run('void')\n if (result) {\n notify('Sale voided', 'info')\n props.onVoided()\n }\n }}\n sx={{ minHeight: POS_TOUCH_PX, alignSelf: 'flex-start' }}\n >\n {'Void sale'}\n </Button>\n </>\n ) : null}\n\n <PosCashDialog\n open={dialog === 'cash'}\n dueCents={chargeCents}\n tipCents={tipCents}\n busy={busy}\n onClose={() => setDialog(null)}\n onTake={async (tenderedCents) => {\n const result = await run(\n 'cash',\n {\n tenderedCents,\n ...(typedCents > 0 ? { amountCents: chargeCents } : {}),\n tipCents,\n },\n true,\n )\n if (result) {\n setDialog(null)\n const change = result.sale.payments.find((payment) => payment.id === result.paymentId)?.changeCents\n if (change) notify(`Change due: ${usd(change)}`, 'success')\n }\n }}\n />\n <PosGiftCardDialog\n open={dialog === 'gift'}\n busy={busy}\n onClose={() => setDialog(null)}\n onCheck={async (code) => {\n try {\n return await posGiftCardBalance(user, hostId, code)\n } catch (error) {\n notify(error instanceof PosRequestError ? error.message : 'Could not read that card', 'warning')\n return null\n }\n }}\n onApply={async (code) => {\n const result = await run('gift-card', { code, ...(typedCents > 0 ? { amountCents: chargeCents } : {}) }, true)\n if (result) setDialog(null)\n }}\n />\n <PosCreditDialog\n open={dialog === 'credit' && Boolean(creditProvider)}\n label={creditProvider?.label ?? 'Store credit'}\n canLookup={Boolean(creditProvider?.lookup)}\n busy={busy}\n onClose={() => setDialog(null)}\n onLookup={async (query) => {\n if (!creditProvider) return null\n try {\n return (await posCreditLookup(user, hostId, creditProvider.providerId, query)).accounts\n } catch (error) {\n notify(error instanceof PosRequestError ? error.message : 'Could not look that up', 'warning')\n return null\n }\n }}\n onApplyCode={async (code) => {\n const result = await run('credit', { code, ...(typedCents > 0 ? { amountCents: chargeCents } : {}) }, true)\n if (result) setDialog(null)\n }}\n onApplyAccount={async (account) => {\n if (!creditProvider) return\n const result = await run(\n 'credit',\n {\n providerId: creditProvider.providerId,\n reference: account.reference,\n ...(typedCents > 0 ? { amountCents: chargeCents } : {}),\n },\n true,\n )\n if (result) setDialog(null)\n }}\n />\n <PosFolioDialog\n open={dialog === 'folio'}\n amountCents={chargeCents}\n stays={props.stays}\n busy={busy}\n onClose={() => setDialog(null)}\n onCharge={async (reservationId) => {\n const result = await run(\n 'folio',\n { reservationId, ...(typedCents > 0 ? { amountCents: chargeCents } : {}) },\n true,\n )\n if (result) setDialog(null)\n }}\n />\n <PosQrDialog url={qr?.url ?? ''} amountCents={qr?.amountCents ?? 0} onClose={() => setQr(null)} />\n <PosKeyedCardDialog\n clientSecret={keyed?.clientSecret ?? ''}\n publishableKey={context?.publishableKey ?? ''}\n stripeAccount={keyed?.stripeAccount ?? ''}\n amountCents={keyed?.amountCents ?? 0}\n onClose={async () => {\n const open = keyed\n setKeyed(null)\n // Closing without paying releases the amount for another tender.\n if (open) await run('cancel', { paymentId: open.paymentId })\n }}\n onConfirmed={async () => {\n const open = keyed\n setKeyed(null)\n if (open) await run('status', { paymentId: open.paymentId })\n }}\n />\n </Stack>\n )\n}\nPosTenderPanel.displayName = 'PosTenderPanel'\n"],"names":["Alert","Box","Button","Chip","Divider","MenuItem","Stack","TextField","Typography","useConfirmationContext","BlockedControl","PrerequisiteNotice","useMerchantPayments","useCallback","useEffect","useRef","useState","CommerceModel","centsFromInput","newAttemptKey","posCreditLookup","posGiftCardBalance","posNativeBridge","posTender","PosRequestError","usd","POS_TOUCH_PX","PosCashDialog","PosCreditDialog","PosFolioDialog","PosGiftCardDialog","PosKeyedCardDialog","PosQrDialog","STATUS_LABEL","pending","succeeded","failed","canceled","reversed","STATUS_COLOR","PosTenderPanel","props","payments","context","user","hostId","sale","display","onSale","notify","settings","cardsBlocked","blocked","cardsReason","reason","amount","setAmount","tipCents","setTipCents","busy","setBusy","dialog","setDialog","creditProvider","setCreditProvider","qr","setQr","keyed","setKeyed","readerId","setReaderId","inFlight","confirm","onTipChange","readers","filter","reader","registerId","length","find","id","typedCents","chargeCents","Math","min","tenderableCents","paid","status","offline","run","action","body","starts","current","result","orderId","cashierAssertion","undefined","error","message","payment","isCardPaymentMethod","method","pendingKey","map","join","latest","timer","setInterval","split","paymentId","clearInterval","readerWaiting","some","connected","asking","show","mode","processing","askTip","base","answer","ask","tip","baseCents","percentages","tipPercentages","allowCustom","startCardPresent","amountCents","startBridge","bridge","paymentIntentId","clientSecret","collected","collectCardPayment","startKeyed","stripeAccount","startLink","url","checkoutUrl","tipOn","Boolean","tippingEnabled","spacing","sx","minHeight","justifyContent","alignItems","variant","component","totalCents","dueCents","color","paidCents","aria-label","gap","flexWrap","flex","minWidth","describeOrderPayment","atMs","changeCents","size","label","onClick","livemode","terminal","testMode","failureMessage","width","severity","onSellOffline","href","actionLabel","direction","placeholder","toFixed","value","onChange","event","target","replace","helperText","slotProps","htmlInput","inputMode","rowGap","mr","disabled","pct","posTipFromPercent","gridTemplateColumns","available","fullWidth","publishableKey","credits","credit","providerId","stays","select","confirmed","title","description","confirmationText","confirmationButtonProps","then","catch","onVoided","alignSelf","open","onClose","onTake","tenderedCents","change","onCheck","code","onApply","canLookup","lookup","onLookup","query","accounts","onApplyCode","onApplyAccount","account","reference","onCharge","reservationId","onConfirmed","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,sBAAsB,QAAQ,uBAAsB;AAC7D,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SAASC,mBAAmB,QAAQ,iCAAgC;AACpE,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAChE,YAAYC,mBAAmB,0BAAgB;AAC/C,SACEC,cAAc,EACdC,aAAa,EACbC,eAAe,EACfC,kBAAkB,EAClBC,eAAe,EACfC,SAAS,EACTC,eAAe,EACfC,GAAG,QAKE,eAAW;AAClB,SAASC,YAAY,QAAQ,kCAA8B;AAC3D,SACEC,aAAa,EACbC,eAAe,EACfC,cAAc,EACdC,iBAAiB,EACjBC,kBAAkB,EAClBC,WAAW,QACN,oCAA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oBACX,MAAMnB,OAAO/I;oBACbC,SAAS;oBACT,IAAI8I,MAAM,MAAMzH,IAAI,UAAU;wBAAEqB,WAAWoG,KAAKpG,SAAS;oBAAC;gBAC5D;;;;AAIR;AACAtE,eAAe8L,WAAW,GAAG"}
|
|
@@ -1288,10 +1288,11 @@ async function sendToReader(input) {
|
|
|
1288
1288
|
var _ref1;
|
|
1289
1289
|
var _intent_last_payment_error;
|
|
1290
1290
|
const message = String((_ref1 = (_intent_last_payment_error = intent.last_payment_error) == null ? void 0 : _intent_last_payment_error.message) != null ? _ref1 : 'The card was declined.');
|
|
1291
|
+
// The declined charge names the card, so the sale and the declined card's receipt can say which card it was.
|
|
1291
1292
|
return await patchCardPayment(input.hostId, input.orderId, payment.id, (current)=>current.status === 'pending' ? _extends({}, current, {
|
|
1292
1293
|
status: 'failed',
|
|
1293
1294
|
failureMessage: message
|
|
1294
|
-
}) : null);
|
|
1295
|
+
}, cardDetailsOf(intent)) : null);
|
|
1295
1296
|
}
|
|
1296
1297
|
// Still waiting on the customer. A reader action that already failed (a
|
|
1297
1298
|
// card removed, a cancel on the reader) says so on the reader, not the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-terminal.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 { createHash } from 'node:crypto'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n merchantAccountIsReady,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { sellerPaymentAccount } from '@aglyn/tenant-data-admin/server/seller-payment-account'\nimport {\n cardAuthenticationParams,\n checkoutSessionCardAuthenticationParams,\n} from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport * as CommerceModel from '../model'\nimport type { PosRegisterSettings } from '../plugin-config'\nimport {\n POS_CURRENCY,\n posCardApplicationFeeCents,\n posStripe,\n posStripeErrorMessage,\n posStripeTestMode,\n posTerminalAvailable,\n} from './pos-stripe'\nimport { applyPosPayment, readPosSale, type PosLiftedOrder, type PosPaymentOutcome } from './pos-sale'\n\n/*==========================================\n * STRIPE TERMINAL AND THE REGISTER'S OTHER CARD TENDERS (AGL-3607).\n *\n * ## Where the readers live\n *\n * Two shapes, decided by the store's selling account\n * ({@link posMerchantAccount}, which asks `sellerPaymentAccount`):\n *\n * - DESTINATION (every Express account, so every store before the switch):\n * the charge is made on the PLATFORM account and transferred on, so\n * Stripe's rule for that model applies: Locations and Readers are created\n * on the platform with the platform key, and identify their merchant by\n * metadata.\n * - DIRECT (a store on its own full Stripe account, ToS v24 section\n * 10.2(a)): EVERY Terminal object, the Location, its Configuration, the\n * Readers, each connection token and each PaymentIntent, is made ON the\n * store's account with the `Stripe-Account` header. A connection token\n * sees only its own account's readers and locations, so nothing may mix.\n *\n * One Location per site (`hosts/{hostId}/terminal/config`), and one\n * `hosts/{hostId}/terminalReaders/{readerId}` document per reader, written\n * only here. Each records the account it was made on\n * (`stripeLocationAccount`, `stripeAccount`; absent = the platform), and an\n * id made on another account than the store sells on now is never used: a\n * Location is made again on the store's account, and a reader must be\n * registered again. The reader document is what makes a reader THIS site's: every call that\n * names a reader reads it under the caller's own site first, so one store can\n * never drive, rename or remove another's reader, and the reader's own\n * `metadata.hostId` is checked again before a payment is sent to it.\n *\n * ## Why the reader charges with MANUAL capture\n *\n * On-reader tipping changes the amount after the PaymentIntent exists: the\n * reader adds the tip on confirmation and reports it in\n * `amount_details.tip.amount`. `application_fee_amount` set at creation was\n * sized on the pre-tip amount, and the platform's take must exclude the tip\n * while Stripe's processing cost (debited from the platform) is on the whole\n * charge. So the reader only AUTHORIZES; {@link refreshPosCardPayment} reads\n * the tip, re-prices the fee as\n *\n * take share (of the sale, never of the tip) + card processing (whole charge)\n *\n * and captures with that exact `application_fee_amount`. Stripe's own Connect\n * guidance for Terminal is the same: inspect, fix the application fee, then\n * capture. An authorization expires after two days, and a register capture\n * happens seconds after the tap.\n *=========================================*/\n\nconst NOT_A_SALE = { ok: false as const, status: 409, error: 'This sale is no longer open' }\n\n/** `hosts/{hostId}/terminalReaders/{readerId}`. */\nexport interface PosTerminalReader {\n label: string\n registerId?: string\n stripeLocationId: string\n deviceType?: string\n serialNumber?: string\n status?: 'online' | 'offline' | string\n livemode: boolean\n createdAtMs: number\n createdBy?: string\n lastSeenAtMs?: number\n /**\n * The store's own Stripe account the reader is registered on, for a\n * direct-charge store. Absent: registered on the platform.\n */\n stripeAccount?: string\n}\n\n/**\n * The payment without its failure reason. Removed, never set to `undefined`:\n * Firestore refuses an undefined field inside the `payments` array.\n */\nfunction withoutFailure(payment: CommerceModel.OrderPayment): CommerceModel.OrderPayment {\n const next = { ...payment }\n delete next.failureMessage\n return next\n}\n\n/** The store's selling account for an in-person card, and how it sells. */\nexport interface PosMerchant {\n accountId: string\n chargeModel: SaleChargeModel\n}\n\n/**\n * The merchant's connected account and its charge model, when it can take\n * card payments now. The ONE door every in-person card route reads the\n * store's account through; where the account is recorded is\n * `sellerPaymentAccount`'s business, not this file's.\n */\nexport async function posMerchantAccount(\n hostId: string,\n org: Record<string, any> | null,\n): Promise<PosMerchant | null> {\n const seller = await sellerPaymentAccount(hostId, org)\n if (!seller) return null\n if (\n !merchantAccountIsReady(\n {\n accountId: seller.accountId,\n chargesEnabled: seller.chargesEnabled,\n accountLivemode: seller.accountLivemode,\n },\n { subject: `POS card payment host ${hostId}` },\n )\n ) {\n return null\n }\n return { accountId: seller.accountId, chargeModel: seller.chargeModel }\n}\n\n/**\n * The account the site's Terminal objects belong on NOW: the store's own for\n * a direct-charge store, null (the platform) for every other. Not gated on\n * readiness: a Location or a reader belongs where the store will sell.\n */\nexport async function posTerminalAccount(\n hostId: string,\n org?: Record<string, any> | null,\n): Promise<string | null> {\n const seller = await sellerPaymentAccount(hostId, org)\n return seller?.chargeModel === 'direct' ? seller.accountId : null\n}\n\n/** The account a stored Terminal id was made on; null for the platform. */\nfunction recordedAccount(value: unknown): string | null {\n const id = typeof value === 'string' ? value.trim() : ''\n return id || null\n}\n\n/** The account a card payment's Stripe objects live on; null for the platform. */\nexport function posPaymentAccount(\n payment: Pick<CommerceModel.OrderPayment, 'chargeModel' | 'stripeAccountId'>,\n): string | null {\n return payment.chargeModel === 'direct' ? recordedAccount(payment.stripeAccountId) : null\n}\n\n/** The account a reader is registered on; null for the platform. */\nexport function posReaderAccount(reader: Pick<PosTerminalReader, 'stripeAccount'>): string | null {\n return recordedAccount(reader.stripeAccount)\n}\n\n/** What a cashier reads when a reader sits on another account than the store sells on. */\nexport const POS_READER_ON_OTHER_ACCOUNT =\n 'This card reader was set up before the store started taking payments on its own Stripe account. Remove it in Registers and devices, then add it again with the new code it shows.'\n\n/**\n * The site's Location, when it was made on `account` (null: the platform).\n * A Location made on another account is no Location for this one.\n */\nfunction locationOnAccount(\n config: { get(field: string): unknown },\n account: string | null,\n): string | null {\n const locationId = String(config.get('stripeLocationId') ?? '')\n if (!locationId) return null\n return recordedAccount(config.get('stripeLocationAccount')) === account ? locationId : null\n}\n\n/**\n * Everything on the site's terminal document that describes the Location's\n * ONE Configuration. Cleared when the Location is made again on another\n * account, so tipping, offline mode, the start-up screen and 4G are written\n * onto a configuration on the new account rather than answered from flags\n * that describe the old one.\n */\nconst LOCATION_BOUND_FIELDS = [\n 'stripeConfigurationId',\n 'stripeConfigurationAssigned',\n 'tippingKey',\n 'offlineEnabled',\n 'offlineConfigurationId',\n 'splashAppliedKey',\n 'splashAppliedAtMs',\n] as const\n\nfunction terminalConfigRef(hostId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminal')\n .doc('config')\n}\n\nfunction readerRef(hostId: string, readerId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminalReaders')\n .doc(readerId)\n}\n\n/** A reader id as Stripe mints them; anything else never reaches Stripe. */\nexport function isTerminalReaderId(value: unknown): value is string {\n return typeof value === 'string' && /^tmr_[A-Za-z0-9]{6,64}$/.test(value)\n}\n\n/** The reader, when it is THIS site's; null for anyone else's or none. */\nexport async function ownedTerminalReader(\n hostId: string,\n readerId: unknown,\n): Promise<(PosTerminalReader & { id: string }) | null> {\n if (!isTerminalReaderId(readerId)) return null\n const snapshot = await readerRef(hostId, readerId).get()\n if (!snapshot.exists) return null\n return { ...(snapshot.data() as PosTerminalReader), id: readerId }\n}\n\n/** A Terminal Location's address, as the console sends it. */\nexport interface PosTerminalAddress {\n line1: string\n line2?: string\n city: string\n state?: string\n postalCode: string\n country: string\n}\n\nexport function posTerminalAddressProblem(address: Partial<PosTerminalAddress> | undefined): string | null {\n if (!address?.line1 || !address?.city || !address?.postalCode || !address?.country) {\n return 'Enter the street, city, postal code and country where the reader is used.'\n }\n if (!/^[A-Z]{2}$/.test(String(address.country))) return 'Choose a two-letter country code, like US.'\n return null\n}\n\n/**\n * The idempotency key of a site's Location request. Two presses with the same\n * address share it, so a double tap makes one Location; a corrected address\n * gets its own, since Stripe refuses a key reused with other parameters for a\n * day (a merchant fixing a typo would otherwise read that refusal).\n */\nexport function posTerminalLocationKey(hostId: string, displayName: string, address: PosTerminalAddress): string {\n const fingerprint = createHash('sha256')\n .update(\n JSON.stringify([\n displayName.slice(0, 100),\n address.line1,\n address.line2 ?? '',\n address.city,\n address.state ?? '',\n address.postalCode,\n address.country,\n ]),\n )\n .digest('hex')\n .slice(0, 16)\n return `pos-location:${hostId}:${fingerprint}`\n}\n\n/** A Location's address as Stripe returns it, in the console's shape. */\nfunction locationAddressOf(location: any): PosTerminalAddress | undefined {\n const address = location?.address\n if (!address || typeof address !== 'object') return undefined\n const text = (value: unknown) => (typeof value === 'string' ? value : '')\n return {\n line1: text(address.line1),\n ...(text(address.line2) ? { line2: text(address.line2) } : {}),\n city: text(address.city),\n ...(text(address.state) ? { state: text(address.state) } : {}),\n postalCode: text(address.postal_code),\n country: text(address.country),\n }\n}\n\n/**\n * The site's Terminal Location, created on first use, on the account the\n * store sells on ({@link posTerminalAccount}): the PLATFORM for a destination\n * store, with the merchant named in metadata, or the store's OWN account for\n * a direct-charge store. Its address is the store's, because Stripe uses it\n * to configure the reader for the right country.\n *\n * A Location recorded on another account (a store that sold through the\n * platform before it moved to its own account) is made again on the store's\n * account, at the address given or else the old Location's own, and the\n * configuration it carried is set up again there.\n */\nexport async function ensurePosTerminalLocation(options: {\n hostId: string\n orgId: string\n displayName: string\n address?: PosTerminalAddress\n /** The account to make it on, when the caller already asked; else asked here. */\n account?: string | null\n}): Promise<{ ok: true; locationId: string } | { ok: false; status: number; error: string }> {\n const account =\n options.account !== undefined ? options.account : await posTerminalAccount(options.hostId)\n const ref = terminalConfigRef(options.hostId)\n const existing = await ref.get()\n const known = String(existing.get('stripeLocationId') ?? '')\n const knownAccount = recordedAccount(existing.get('stripeLocationAccount'))\n if (known && knownAccount === account) return { ok: true, locationId: known }\n let addressGiven = options.address\n if (known && !addressGiven) {\n const previous = await posStripe('GET', `terminal/locations/${known}`, { stripeAccount: knownAccount })\n if (previous.ok) addressGiven = locationAddressOf(previous.body)\n }\n const problem = posTerminalAddressProblem(addressGiven)\n if (problem) return { ok: false, status: 400, error: problem }\n const address = addressGiven as PosTerminalAddress\n const locationKey = posTerminalLocationKey(options.hostId, options.displayName, address)\n const created = await posStripe('POST', 'terminal/locations', {\n // A direct store's key names its account: the same address once made on\n // the platform must never replay the platform's Location.\n idempotencyKey: account ? `${locationKey}:${account}` : locationKey,\n ...(account ? { stripeAccount: account } : {}),\n params: {\n display_name: options.displayName.slice(0, 100) || 'Store',\n 'address[line1]': address.line1,\n 'address[line2]': address.line2 || undefined,\n 'address[city]': address.city,\n 'address[state]': address.state || undefined,\n 'address[postal_code]': address.postalCode,\n 'address[country]': address.country,\n 'metadata[orgId]': options.orgId,\n 'metadata[hostId]': options.hostId,\n },\n })\n if (!created.ok || !created.body?.id) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(created.body, 'The reader location could not be set up.'),\n }\n }\n const replaced = Boolean(known)\n await ref.set(\n {\n stripeLocationId: String(created.body.id),\n livemode: Boolean(created.body.livemode),\n createdAtMs: Date.now(),\n ...(account ? { stripeLocationAccount: account } : {}),\n ...(replaced\n ? {\n ...(account ? {} : { stripeLocationAccount: firebaseAdmin.firestore.FieldValue.delete() }),\n ...Object.fromEntries(\n LOCATION_BOUND_FIELDS.map((field) => [field, firebaseAdmin.firestore.FieldValue.delete()]),\n ),\n replacedLocation: { id: known, account: knownAccount ?? 'platform', atMs: Date.now() },\n }\n : {}),\n },\n { merge: true },\n )\n // 4G was on for the old Location's readers: it is turned on again on the\n // new one's configuration, so readers registered there keep it (AGL-4038).\n if (replaced && existing.get('cellularEnabled') === true) {\n const saved = await savePosReaderConfiguration(options.hostId, { 'cellular[enabled]': true }, 'cellular-on')\n if ('error' in saved) {\n console.error('[pos-terminal] 4G not turned on for the new location', options.hostId, saved.error)\n } else {\n await ref.set({ cellularConfigurationId: saved.configurationId }, { merge: true })\n await import('./pos-cellular')\n .then((cellular) => cellular.syncPosCellularReaders({ hostId: options.hostId, orgId: options.orgId }))\n .catch((error) => console.error('[pos-terminal] 4G records not moved', options.hostId, error))\n }\n }\n // A new Location starts with the store's reader start-up screen (AGL-4048).\n // Never fatal, and loaded only here: it draws images.\n await import('./pos-reader-splash')\n .then((splash) => splash.applyPosReaderSplash(options.hostId))\n .catch((error) => console.error('[pos-terminal] start-up screen not applied', options.hostId, error))\n return { ok: true, locationId: String(created.body.id) }\n}\n\n/** The tipping a reader shows: Stripe offers three buttons, so three presets. */\nexport function posReaderTippingKey(settings: PosRegisterSettings): string {\n return settings.tippingEnabled ? settings.tipPercentages.slice(0, 3).join(',') : 'off'\n}\n\ntype PosStripeParams = Record<string, string | number | boolean | undefined | null | readonly string[]>\n\n/**\n * Writes `params` onto the site's ONE Terminal Configuration, creating it and\n * assigning it to the site's Location on first use. Reader tipping and the\n * start-up screen (AGL-4048) both live on it, because a Location takes one\n * configuration override: a second configuration assigned for the screen\n * would silently drop the tipping presets, and the other way round. Stripe\n * leaves every parameter an update does not name as it was, so each caller\n * sends only its own.\n *\n * The first write is the only race. Tipping's runs as a payment starts, the\n * screen's when the POS devices card saves, and two at once would each make a\n * configuration. So the new id is CLAIMED in a transaction: the loser writes\n * its parameters onto the winner's configuration and deletes its own.\n *\n * `createKey` keys only the create (`pos-configuration:{hostId}:{createKey}`),\n * so a retried first write makes one configuration. An update is not keyed:\n * it sets values, and repeating it changes nothing.\n */\nexport async function savePosReaderConfiguration(\n hostId: string,\n params: PosStripeParams,\n createKey: string,\n): Promise<{ ok: true; configurationId: string } | { ok: false; error: string }> {\n const ref = terminalConfigRef(hostId)\n const config = await ref.get()\n const locationId = String(config.get('stripeLocationId') ?? '')\n if (!locationId) return { ok: false, error: 'no-location' }\n // The configuration lives where its Location does: the store's own account\n // for a direct-charge store's Location, the platform otherwise.\n const account = recordedAccount(config.get('stripeLocationAccount'))\n const onAccount = account ? { stripeAccount: account } : {}\n const known = String(config.get('stripeConfigurationId') ?? '')\n if (known) {\n const updated = await posStripe('POST', `terminal/configurations/${known}`, { params, ...onAccount })\n if (!updated.ok) return { ok: false, error: String(updated.body?.error?.code ?? updated.status) }\n // A configuration recorded before AGL-4048 was only ever recorded once\n // it was assigned, so only an explicit `false` still owes the assignment.\n if (config.get('stripeConfigurationAssigned') === false) {\n const assigned = await assignPosReaderConfiguration(hostId, locationId, known, account)\n if (!assigned) return { ok: false, error: 'assignment' }\n }\n return { ok: true, configurationId: known }\n }\n const created = await posStripe('POST', 'terminal/configurations', {\n params,\n idempotencyKey: account\n ? `pos-configuration:${hostId}:${account}:${createKey}`\n : `pos-configuration:${hostId}:${createKey}`,\n ...onAccount,\n })\n if (!created.ok || !created.body?.id) {\n return { ok: false, error: String(created.body?.error?.code ?? created.status) }\n }\n const createdId = String(created.body.id)\n const winner: string = await firebaseAdmin\n .app()\n .firestore()\n .runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n const existing = String(fresh.get('stripeConfigurationId') ?? '')\n if (existing) return existing\n transaction.set(\n ref,\n { stripeConfigurationId: createdId, stripeConfigurationAssigned: false },\n { merge: true },\n )\n return createdId\n })\n if (winner !== createdId) {\n const updated = await posStripe('POST', `terminal/configurations/${winner}`, { params, ...onAccount })\n await posStripe('DELETE', `terminal/configurations/${createdId}`, onAccount).catch(() => undefined)\n if (!updated.ok) return { ok: false, error: String(updated.body?.error?.code ?? updated.status) }\n return { ok: true, configurationId: winner }\n }\n const assigned = await assignPosReaderConfiguration(hostId, locationId, createdId, account)\n return assigned ? { ok: true, configurationId: createdId } : { ok: false, error: 'assignment' }\n}\n\nasync function assignPosReaderConfiguration(\n hostId: string,\n locationId: string,\n configurationId: string,\n account: string | null,\n): Promise<boolean> {\n const assigned = await posStripe('POST', `terminal/locations/${locationId}`, {\n params: { configuration_overrides: configurationId },\n ...(account ? { stripeAccount: account } : {}),\n })\n if (!assigned.ok) {\n console.error('[pos-terminal] configuration assignment failed', hostId, assigned.body?.error)\n return false\n }\n await terminalConfigRef(hostId).set({ stripeConfigurationAssigned: true }, { merge: true })\n return true\n}\n\n/**\n * Keeps the site's reader tipping in step with the merchant's settings, on\n * the site's one Terminal Configuration ({@link savePosReaderConfiguration}),\n * rewritten only when the presets changed. Never fatal: a reader that keeps\n * the previous presets still takes the payment.\n */\nexport async function syncPosReaderTipping(\n hostId: string,\n settings: PosRegisterSettings,\n): Promise<void> {\n if (!settings.tippingEnabled) return\n const ref = terminalConfigRef(hostId)\n const config = await ref.get()\n if (!config.get('stripeLocationId')) return\n const key = posReaderTippingKey(settings)\n if (config.get('tippingKey') === key) return\n const percentages = settings.tipPercentages.slice(0, 3)\n const saved = await savePosReaderConfiguration(\n hostId,\n { [`tipping[${POS_CURRENCY}][percentages]`]: percentages.map(String) },\n key,\n )\n if ('error' in saved) {\n console.error('[pos-terminal] tipping configuration failed', hostId, saved.error)\n return\n }\n await ref.set({ tippingKey: key }, { merge: true })\n}\n\n/** Reads a reader from Stripe and keeps its status on the site's document. */\nexport async function refreshPosReaderStatus(\n hostId: string,\n readerId: string,\n /** The account the reader is registered on ({@link posReaderAccount}); null for the platform. */\n account: string | null = null,\n): Promise<{ status: string; action: any } | null> {\n const fetched = await posStripe('GET', `terminal/readers/${readerId}`, account ? { stripeAccount: account } : {})\n if (!fetched.ok) return null\n const status = String(fetched.body?.status ?? 'offline')\n await readerRef(hostId, readerId)\n .set({ status, lastSeenAtMs: Date.now() }, { merge: true })\n .catch(() => undefined)\n return { status, action: fetched.body?.action ?? null }\n}\n\n/*==========================================\n * TAKING A CARD PAYMENT.\n *=========================================*/\n\ninterface CardStart {\n hostId: string\n orderId: string\n paymentId: string\n amountCents: number\n /** A tip already chosen (on the customer display or by the cashier). */\n tipCents: number\n cashierId: string\n org: Record<string, any> | null\n}\n\n/** Reserves a pending card payment in the ledger, or finds the one this attempt made. */\nasync function reserveCardPayment(\n start: CardStart,\n method: CommerceModel.OrderPaymentMethod,\n extra: Partial<CommerceModel.OrderPayment>,\n): Promise<PosPaymentOutcome> {\n return await applyPosPayment({\n hostId: start.hostId,\n orderId: start.orderId,\n paymentId: start.paymentId,\n decide: ({ order, payments, existing }) => {\n if (existing) {\n // The same attempt again: hand back what it started. A failed card\n // is re-armed by `retry`, not by pressing the tender a second time.\n return { kind: 'keep' }\n }\n if (order.status !== 'pending') return { kind: 'refuse', ...NOT_A_SALE }\n const total = Number(order.totals?.totalCents ?? 0)\n const tenderable = CommerceModel.posTenderableCents(total, payments)\n if (!(start.amountCents > 0)) {\n return { kind: 'refuse', status: 400, error: 'Enter an amount to charge.' }\n }\n if (start.amountCents > tenderable) {\n return {\n kind: 'refuse',\n status: 409,\n error:\n tenderable > 0\n ? `Only $${(tenderable / 100).toFixed(2)} is left to pay on this sale.`\n : 'Nothing is left to pay on this sale.',\n }\n }\n const tipProblem = CommerceModel.posTipProblem(start.tipCents, start.amountCents)\n if (tipProblem) return { kind: 'refuse', status: 400, error: tipProblem }\n const takeFeeCents = CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: total,\n amountCents: start.amountCents,\n })\n return {\n kind: 'put',\n payment: {\n id: start.paymentId,\n method,\n amountCents: start.amountCents,\n ...(start.tipCents > 0 ? { tipCents: start.tipCents } : {}),\n status: 'pending',\n atMs: Date.now(),\n takeFeeCents,\n cashierId: start.cashierId,\n ...extra,\n },\n }\n },\n })\n}\n\n/** Writes Stripe's answer onto a pending card payment. */\nasync function patchCardPayment(\n hostId: string,\n orderId: string,\n paymentId: string,\n patch: (payment: CommerceModel.OrderPayment) => CommerceModel.OrderPayment | null,\n event?: { event: string; detail?: string },\n): Promise<PosPaymentOutcome> {\n return await applyPosPayment({\n hostId,\n orderId,\n paymentId,\n decide: ({ existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n const next = patch(existing)\n if (!next) return { kind: 'keep' }\n return { kind: 'put', payment: next, ...(event ? { event } : {}) }\n },\n })\n}\n\n/** Whether a store sells by direct charge, for the fee and the request. */\nfunction isDirect(merchant: PosMerchant): boolean {\n return merchant.chargeModel === 'direct'\n}\n\n/** The `posStripe` option that puts a request on a direct store's account. */\nfunction onMerchant(merchant: PosMerchant): { stripeAccount?: string } {\n return isDirect(merchant) ? { stripeAccount: merchant.accountId } : {}\n}\n\n/** The `posStripe` option for a recorded account (null: the platform). */\nfunction onAccount(account: string | null): { stripeAccount?: string } {\n return account ? { stripeAccount: account } : {}\n}\n\n/** What a direct card payment records about where it lives; nothing for a destination one. */\nfunction directPaymentFields(merchant: PosMerchant): Partial<CommerceModel.OrderPayment> {\n return isDirect(merchant) ? { chargeModel: 'direct', stripeAccountId: merchant.accountId } : {}\n}\n\nfunction paymentIntentParams(\n start: CardStart,\n payment: CommerceModel.OrderPayment,\n merchant: PosMerchant,\n extra: Record<string, string | number | boolean | undefined | readonly string[]>,\n) {\n const chargeCents = start.amountCents + start.tipCents\n const methodTypes = extra['payment_method_types']\n const fee = posCardApplicationFeeCents({\n takeShareCents: Number(payment.takeFeeCents ?? 0),\n chargeCents,\n // A reader's card is in person; a typed card is an online card (AGL-4198).\n inPerson: Array.isArray(methodTypes) && methodTypes.includes('card_present'),\n ...(isDirect(merchant) ? { direct: true } : {}),\n })\n return {\n amount: chargeCents,\n currency: POS_CURRENCY,\n // A DESTINATION charge is made on the platform and transferred on; a\n // DIRECT one is made on the store's own account (the request's\n // `Stripe-Account`), whose money it already is, so nothing is transferred.\n ...(isDirect(merchant) ? {} : { 'transfer_data[destination]': merchant.accountId }),\n ...(fee > 0 ? { application_fee_amount: fee } : {}),\n 'metadata[kind]': 'pos',\n 'metadata[hostId]': start.hostId,\n 'metadata[orderId]': start.orderId,\n 'metadata[paymentId]': start.paymentId,\n 'metadata[tipCents]': String(start.tipCents),\n // Lets the Connect delivery of this intent's events through the webhook's\n // direct-sale gate (`connectEventIsForDirectSale`).\n ...(isDirect(merchant) ? { 'metadata[chargeModel]': 'direct' } : {}),\n ...extra,\n }\n}\n\n/**\n * Creates (or finds) the card-present PaymentIntent for one payment WITHOUT\n * choosing how the card is collected: reserves the amount in the ledger and\n * creates a manual-capture charge, keyed by the payment so a retry returns\n * the same intent. For a destination store it is a destination charge to the\n * merchant (settled on Aglyn's platform account, with no `on_behalf_of`, as\n * ToS §10.7 states); for a direct-charge store it is made ON the store's own\n * account (ToS v24 §10.2(a)) with Aglyn's take as the application fee.\n *\n * Two collectors use it. {@link startCardPresentPayment} pushes the intent\n * to a smart reader the site owns; a native companion app (AGL-3618)\n * collects it with the Stripe Terminal SDK (Tap to Pay, Bluetooth readers)\n * using the returned `clientSecret`. However the card is collected, the\n * payment is recorded by {@link refreshPosCardPayment}, keyed on the intent's\n * metadata, from the register's poll or the webhook alike.\n */\nexport async function createCardPresentIntent(\n start: CardStart & { readerId?: string; readerAccount?: string | null },\n): Promise<PosPaymentOutcome & { clientSecret?: string; paymentIntentId?: string }> {\n // Live card-present payments wait for Terminal to be switched on for the\n // platform (`STRIPE_TERMINAL_LIVE_ENABLED`); the hidden controls are not\n // the only gate.\n if (!posTerminalAvailable()) {\n return { ok: false, status: 409, error: 'Card readers are not available for this store yet.' }\n }\n const merchant = await posMerchantAccount(start.hostId, start.org)\n if (!merchant) return { ok: false, status: 409, error: 'Card payments not set up' }\n // A reader answers only to the account it is registered on, and the intent\n // is made on the store's: a reader registered on the platform cannot take\n // a direct store's card. Refused before anything is reserved.\n if (start.readerId && (start.readerAccount ?? null) !== (isDirect(merchant) ? merchant.accountId : null)) {\n return { ok: false, status: 409, error: POS_READER_ON_OTHER_ACCOUNT }\n }\n const reserved = await reserveCardPayment(start, 'card_present', {\n ...(start.readerId ? { readerId: start.readerId } : {}),\n ...directPaymentFields(merchant),\n })\n if (!reserved.ok || !reserved.payment) return reserved\n const payment = reserved.payment\n if (payment.status !== 'pending') return reserved\n // Keyed by the payment: a second call for the same payment replays the\n // intent Stripe already made rather than opening another.\n const intent = await posStripe('POST', 'payment_intents', {\n idempotencyKey: `pos-pi:${payment.id}`,\n ...onMerchant(merchant),\n params: paymentIntentParams(start, payment, merchant, {\n payment_method_types:\n POS_CURRENCY === 'usd' ? ['card_present'] : ['card_present', 'interac_present'],\n capture_method: 'manual',\n ...(start.readerId ? { 'metadata[readerId]': start.readerId } : {}),\n description: 'In-store purchase',\n }),\n })\n if (!intent.ok || !intent.body?.id) {\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(intent.body, 'The card payment could not be started.'),\n }))\n }\n const paymentIntentId = String(intent.body.id)\n const recorded = payment.paymentIntentId\n ? reserved\n : await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n paymentIntentId,\n livemode: Boolean(intent.body.livemode),\n }))\n return {\n ...recorded,\n paymentIntentId,\n ...(intent.body.client_secret ? { clientSecret: String(intent.body.client_secret) } : {}),\n }\n}\n\n/**\n * A smart-reader payment: the card-present intent from\n * {@link createCardPresentIntent}, pushed to a reader THIS site owns. The\n * register then polls {@link refreshPosCardPayment} until the reader answers;\n * webhooks land on the same function.\n */\nexport async function startCardPresentPayment(\n start: CardStart & { readerId: string; settings: PosRegisterSettings },\n): Promise<PosPaymentOutcome> {\n const reader = await ownedTerminalReader(start.hostId, start.readerId)\n if (!reader) return { ok: false, status: 404, error: 'That card reader is not on this site.' }\n await syncPosReaderTipping(start.hostId, start.settings).catch((error) =>\n console.error('[pos-terminal] tipping sync failed', error),\n )\n const created = await createCardPresentIntent({\n ...start,\n readerId: reader.id,\n readerAccount: posReaderAccount(reader),\n })\n if (!created.ok || !created.payment || !created.paymentIntentId) return created\n if (created.payment.status !== 'pending') return created\n return await sendToReader({\n hostId: start.hostId,\n orderId: start.orderId,\n paymentId: created.payment.id,\n readerId: reader.id,\n account: posPaymentAccount(created.payment),\n paymentIntentId: created.paymentIntentId,\n // A tip the customer already chose on the display is in the amount;\n // asking again on the reader would ask twice.\n skipTipping: !start.settings.tippingEnabled || start.tipCents > 0,\n attempt: 0,\n })\n}\n\n/** The site's recorded Location id on any account, or null before a reader was ever set up. */\nexport async function posTerminalRecordedLocationId(hostId: string): Promise<string | null> {\n const config = await terminalConfigRef(hostId).get()\n return String(config.get('stripeLocationId') ?? '') || null\n}\n\n/**\n * The site's Terminal Location id on the account the store sells on now, or\n * null before a reader was ever set up there. A Location made on another\n * account (the platform, for a store now on its own) is not this store's\n * Location any more: {@link ensurePosTerminalLocation} makes it again.\n */\nexport async function posTerminalLocationId(\n hostId: string,\n account?: string | null,\n): Promise<string | null> {\n const [config, current] = await Promise.all([\n terminalConfigRef(hostId).get(),\n account !== undefined ? Promise.resolve(account) : posTerminalAccount(hostId),\n ])\n return locationOnAccount(config, current)\n}\n\n/**\n * A Terminal SDK connection token scoped to the site's own Location, for a\n * native companion app's SDK (AGL-3618). Scoping it to the Location is what\n * keeps one store's app from discovering another store's readers: Stripe\n * only lets a location-scoped token connect to readers in that Location.\n * Null when the site has no Location yet, never an unscoped token.\n *\n * A direct-charge store's token is minted ON its own account (the\n * `Stripe-Account` header), as Stripe's Terminal-with-direct-charges guide\n * asks: the SDK then sees that account's Location and readers, collects the\n * intents this server made there, and creates any intent of its own (a card\n * taken offline) on that account too.\n */\nexport async function createPosTerminalConnectionToken(\n hostId: string,\n): Promise<{ secret: string; locationId: string } | null> {\n const account = await posTerminalAccount(hostId)\n const locationId = await posTerminalLocationId(hostId, account)\n if (!locationId) return null\n const token = await posStripe('POST', 'terminal/connection_tokens', {\n params: { location: locationId },\n ...onAccount(account),\n })\n if (!token.ok || !token.body?.secret) return null\n return { secret: String(token.body.secret), locationId }\n}\n\nasync function sendToReader(input: {\n hostId: string\n orderId: string\n paymentId: string\n readerId: string\n /** The account the payment (and so its reader) is on; null for the platform. */\n account: string | null\n paymentIntentId: string\n skipTipping: boolean\n attempt: number\n}): Promise<PosPaymentOutcome> {\n const processed = await posStripe(\n 'POST',\n `terminal/readers/${input.readerId}/process_payment_intent`,\n {\n idempotencyKey: `pos-process:${input.paymentId}:${input.attempt}`,\n ...onAccount(input.account),\n params: {\n payment_intent: input.paymentIntentId,\n 'process_config[enable_customer_cancellation]': true,\n ...(input.skipTipping ? { 'process_config[skip_tipping]': true } : {}),\n },\n },\n )\n if (!processed.ok) {\n return await patchCardPayment(input.hostId, input.orderId, input.paymentId, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(processed.body, 'The card reader could not start the payment.'),\n }))\n }\n return await patchCardPayment(input.hostId, input.orderId, input.paymentId, (current) => {\n if (!current.failureMessage) return null\n return withoutFailure(current)\n })\n}\n\n/**\n * Re-arms a declined or failed reader payment on the SAME PaymentIntent, as\n * Stripe asks (a new one per attempt risks a double charge).\n */\nexport async function retryCardPresentPayment(input: {\n hostId: string\n orderId: string\n paymentId: string\n settings: PosRegisterSettings\n}): Promise<PosPaymentOutcome> {\n const order = await readPosSale(input.hostId, input.orderId)\n if (!order || order.status !== 'pending') return NOT_A_SALE\n const payment = CommerceModel.orderPayments(order).find((entry) => entry.id === input.paymentId)\n if (!payment || payment.method !== 'card_present' || !payment.paymentIntentId || !payment.readerId) {\n return { ok: false, status: 404, error: 'Unknown payment' }\n }\n if (payment.status === 'succeeded') return { ok: true, order, payment, completed: false, changed: false }\n const reader = await ownedTerminalReader(input.hostId, payment.readerId)\n if (!reader) return { ok: false, status: 404, error: 'That card reader is not on this site.' }\n if (posReaderAccount(reader) !== posPaymentAccount(payment)) {\n return { ok: false, status: 409, error: POS_READER_ON_OTHER_ACCOUNT }\n }\n // Back to pending first, so the amount is reserved again before the reader\n // is asked; a sale paid meanwhile by another tender refuses here.\n const rearmed = await applyPosPayment({\n hostId: input.hostId,\n orderId: input.orderId,\n paymentId: input.paymentId,\n decide: ({ order: fresh, payments, existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n if (existing.status === 'pending') return { kind: 'keep' }\n if (existing.status !== 'failed' && existing.status !== 'canceled') {\n return { kind: 'refuse', status: 409, error: 'This payment cannot be retried.' }\n }\n const tenderable = CommerceModel.posTenderableCents(\n Number(fresh.totals?.totalCents ?? 0),\n payments.filter((entry) => entry.id !== existing.id),\n )\n if (existing.amountCents > tenderable) {\n return { kind: 'refuse', status: 409, error: 'The balance changed. Start a new card payment.' }\n }\n return { kind: 'put', payment: { ...withoutFailure(existing), status: 'pending' } }\n },\n })\n if (!rearmed.ok) return rearmed\n const attempt = Date.now()\n return await sendToReader({\n hostId: input.hostId,\n orderId: input.orderId,\n paymentId: input.paymentId,\n readerId: reader.id,\n account: posPaymentAccount(payment),\n paymentIntentId: payment.paymentIntentId,\n skipTipping: !input.settings.tippingEnabled || Number(payment.tipCents ?? 0) > 0,\n attempt,\n })\n}\n\n/**\n * A typed card (card not present): a PaymentIntent the console confirms with\n * the Payment Element. No MOTO: the card is keyed into Stripe's own field and\n * goes through Stripe's normal online checks, 3-D Secure included.\n */\nexport async function startCardKeyedPayment(\n start: CardStart & { paymentMethodId?: string },\n): Promise<PosPaymentOutcome & { clientSecret?: string; stripeAccount?: string }> {\n const paymentMethodId = start.paymentMethodId ?? ''\n if (paymentMethodId && !isPaymentMethodId(paymentMethodId)) {\n return { ok: false, status: 400, error: 'The card could not be read. Enter it again.' }\n }\n const merchant = await posMerchantAccount(start.hostId, start.org)\n if (!merchant) return { ok: false, status: 409, error: 'Card payments not set up' }\n const reserved = await reserveCardPayment(start, 'card_keyed', directPaymentFields(merchant))\n if (!reserved.ok || !reserved.payment) return reserved\n const payment = reserved.payment\n if (payment.status !== 'pending') return reserved\n const intent = await posStripe('POST', 'payment_intents', {\n idempotencyKey: `pos-pi:${payment.id}`,\n ...onMerchant(merchant),\n params: paymentIntentParams(start, payment, merchant, {\n payment_method_types: ['card'],\n description: 'In-store purchase (typed card)',\n // 3-D Secure from the one seam every card payment shares (AGL-3360).\n ...cardAuthenticationParams('one-time'),\n }),\n })\n if (!intent.ok || !intent.body?.id || !intent.body?.client_secret) {\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(intent.body, 'The card payment could not be started.'),\n }))\n }\n const updated = payment.paymentIntentId\n ? reserved\n : await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n paymentIntentId: String(intent.body.id),\n livemode: Boolean(intent.body.livemode),\n }))\n if (!paymentMethodId) {\n // A direct store's intent lives on its own account, so the console's\n // Payment Element must load Stripe for that account to confirm it.\n return {\n ...updated,\n clientSecret: String(intent.body.client_secret),\n ...(isDirect(merchant) ? { stripeAccount: merchant.accountId } : {}),\n }\n }\n return await confirmKeyedCard(\n start,\n payment.id,\n String(intent.body.id),\n paymentMethodId,\n isDirect(merchant) ? merchant.accountId : null,\n )\n}\n\n/** A PaymentMethod id as Stripe mints them; anything else never reaches Stripe. */\nfunction isPaymentMethodId(value: string): boolean {\n return /^pm_[A-Za-z0-9]{8,64}$/.test(value)\n}\n\n/** What a typed card that needs the cardholder's bank to approve it says. */\nexport const KEYED_CARD_NEEDS_AUTHENTICATION =\n '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.'\n\n/**\n * A card typed into the register's own card fields (AGL-3848): the device\n * sent the number to Stripe alone, which answered with a PaymentMethod, and\n * hands this route only its id. The server confirms the intent with it, with\n * the platform's secret key, and records the payment from Stripe's answer as\n * every card payment is. The device made that PaymentMethod with the\n * PLATFORM's publishable key, so for a direct-charge store's intent it is\n * first cloned onto the store's account (Stripe's PaymentMethod cloning for\n * direct charges) and the clone confirms it. A card whose bank asks for the cardholder's approval\n * (3-D Secure) cannot be approved at the register, so that intent is released\n * and the payment fails with words that point at Card (QR).\n */\nasync function confirmKeyedCard(\n start: CardStart,\n paymentId: string,\n intentId: string,\n paymentMethodId: string,\n account: string | null,\n): Promise<PosPaymentOutcome> {\n const input = { hostId: start.hostId, orderId: start.orderId, paymentId }\n let method = paymentMethodId\n if (account) {\n const cloned = await posStripe('POST', 'payment_methods', {\n idempotencyKey: `pos-keyed-clone:${account}:${paymentMethodId}`,\n stripeAccount: account,\n params: { payment_method: paymentMethodId },\n })\n if (!cloned.ok || !cloned.body?.id) {\n const message = posStripeErrorMessage(cloned.body, 'The card was not accepted.')\n await posStripe('POST', `payment_intents/${intentId}/cancel`, {\n idempotencyKey: `pos-cancel:${intentId}`,\n stripeAccount: account,\n })\n return await patchCardPayment(start.hostId, start.orderId, paymentId, (current) =>\n current.status === 'pending' ? { ...current, status: 'failed', failureMessage: message } : null,\n )\n }\n method = String(cloned.body.id)\n }\n const confirmed = await posStripe('POST', `payment_intents/${intentId}/confirm`, {\n idempotencyKey: `pos-keyed-confirm:${intentId}:${paymentMethodId}`,\n params: { payment_method: method },\n ...onAccount(account),\n })\n const status = String(confirmed.body?.status ?? confirmed.body?.error?.payment_intent?.status ?? '')\n if (status === 'requires_action') {\n await posStripe('POST', `payment_intents/${intentId}/cancel`, {\n idempotencyKey: `pos-cancel:${intentId}`,\n ...onAccount(account),\n })\n return await patchCardPayment(start.hostId, start.orderId, paymentId, (current) =>\n current.status === 'pending'\n ? { ...current, status: 'failed', failureMessage: KEYED_CARD_NEEDS_AUTHENTICATION }\n : null,\n )\n }\n if (!confirmed.ok && confirmed.body?.error && !confirmed.body.error.payment_intent) {\n // Refused before the card was tried (a stale method, a bad request): say so, leave nothing pending.\n const message = posStripeErrorMessage(confirmed.body, 'The card was not accepted.')\n await posStripe('POST', `payment_intents/${intentId}/cancel`, {\n idempotencyKey: `pos-cancel:${intentId}`,\n ...onAccount(account),\n })\n return await patchCardPayment(start.hostId, start.orderId, paymentId, (current) =>\n current.status === 'pending' ? { ...current, status: 'failed', failureMessage: message } : null,\n )\n }\n // Approved, declined or still processing: Stripe's own read of the intent decides.\n return await refreshPosCardPayment(input)\n}\n\n/**\n * The customer pays on their own phone from a QR code: a Stripe payment page\n * for this payment's amount (and tip, as its own line). Settled by\n * `checkout.session.completed` or by the register's poll.\n */\nexport async function startCardLinkPayment(\n start: CardStart & { returnUrl: string },\n): Promise<PosPaymentOutcome> {\n const merchant = await posMerchantAccount(start.hostId, start.org)\n if (!merchant) return { ok: false, status: 409, error: 'Card payments not set up' }\n const reserved = await reserveCardPayment(start, 'card_link', directPaymentFields(merchant))\n if (!reserved.ok || !reserved.payment) return reserved\n const payment = reserved.payment\n if (payment.checkoutSessionId || payment.status !== 'pending') return reserved\n const fee = posCardApplicationFeeCents({\n takeShareCents: Number(payment.takeFeeCents ?? 0),\n chargeCents: start.amountCents + start.tipCents,\n // A card link is paid online, on the customer's own phone (AGL-4198).\n inPerson: false,\n ...(isDirect(merchant) ? { direct: true } : {}),\n })\n const session = await posStripe('POST', 'checkout/sessions', {\n idempotencyKey: `pos-link:${payment.id}`,\n ...onMerchant(merchant),\n params: {\n mode: 'payment',\n ...checkoutSessionCardAuthenticationParams('payment'),\n 'payment_method_types': ['card'],\n 'line_items[0][quantity]': 1,\n 'line_items[0][price_data][currency]': POS_CURRENCY,\n 'line_items[0][price_data][unit_amount]': start.amountCents,\n 'line_items[0][price_data][product_data][name]': 'In-store purchase',\n ...(start.tipCents > 0\n ? {\n 'line_items[1][quantity]': 1,\n 'line_items[1][price_data][currency]': POS_CURRENCY,\n 'line_items[1][price_data][unit_amount]': start.tipCents,\n 'line_items[1][price_data][product_data][name]': 'Tip',\n }\n : {}),\n ...(isDirect(merchant) ? {} : { 'payment_intent_data[transfer_data][destination]': merchant.accountId }),\n ...(fee > 0 ? { 'payment_intent_data[application_fee_amount]': fee } : {}),\n ...(isDirect(merchant) ? { 'payment_intent_data[metadata][chargeModel]': 'direct' } : {}),\n 'payment_intent_data[metadata][kind]': 'pos',\n 'payment_intent_data[metadata][hostId]': start.hostId,\n 'payment_intent_data[metadata][orderId]': start.orderId,\n 'payment_intent_data[metadata][paymentId]': payment.id,\n 'payment_intent_data[metadata][tipCents]': String(start.tipCents),\n success_url: `${start.returnUrl}?paid=1`,\n cancel_url: `${start.returnUrl}?paid=0`,\n 'metadata[type]': 'pos-payment',\n 'metadata[hostId]': start.hostId,\n 'metadata[orderId]': start.orderId,\n 'metadata[paymentId]': payment.id,\n ...(isDirect(merchant) ? { 'metadata[chargeModel]': 'direct' } : {}),\n },\n })\n if (!session.ok || !session.body?.url) {\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(session.body, 'The payment page could not be created.'),\n }))\n }\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n checkoutSessionId: String(session.body.id),\n checkoutUrl: String(session.body.url),\n livemode: Boolean(session.body.livemode),\n }))\n}\n\n/*==========================================\n * SETTLING A CARD PAYMENT.\n *=========================================*/\n\n/** The card's brand and last four, off the charge Stripe made. */\nfunction cardDetailsOf(intent: any): { cardBrand?: string; last4?: string } {\n const charge = typeof intent?.latest_charge === 'object' ? intent.latest_charge : null\n const details =\n charge?.payment_method_details?.card_present ??\n charge?.payment_method_details?.interac_present ??\n charge?.payment_method_details?.card ??\n null\n return {\n ...(details?.brand ? { cardBrand: String(details.brand) } : {}),\n ...(details?.last4 ? { last4: String(details.last4) } : {}),\n }\n}\n\n/** The tip on an intent: what the display chose plus what the reader added. */\nexport function posIntentTipCents(intent: any): number {\n const preset = Math.max(0, Math.round(Number(intent?.metadata?.tipCents ?? 0)) || 0)\n const onReader = Math.max(0, Math.round(Number(intent?.amount_details?.tip?.amount ?? 0)) || 0)\n return preset + onReader\n}\n\n/**\n * The fee a register card charge is captured with: the payment's share of the\n * take (fixed at reservation, the sale's share and never the tip's) plus the\n * card processing cost on the whole amount, tip included.\n */\nexport function posCaptureFeeCents(payment: CommerceModel.OrderPayment, intent: any): number {\n const methodTypes: unknown = intent?.payment_method_types\n return posCardApplicationFeeCents({\n takeShareCents: Number(payment.takeFeeCents ?? 0),\n chargeCents: Math.max(0, Math.round(Number(intent?.amount ?? 0))),\n // The intent says how it was paid: a reader's card is in person (AGL-4198).\n inPerson: !Array.isArray(methodTypes) || methodTypes.includes('card_present'),\n // On a direct store's own account Stripe bills the store its card fee,\n // so the fee is the take alone (a tip never adds to it).\n ...(payment.chargeModel === 'direct' ? { direct: true } : {}),\n })\n}\n\n/**\n * Brings one card payment up to date with Stripe, from a webhook or the\n * register's poll alike: captures an authorized reader payment with its final\n * fee, records a success, a decline or a cancellation. Idempotent: the\n * capture is keyed by the intent, and the ledger change is a no-op when the\n * payment already says what Stripe says.\n */\nexport async function refreshPosCardPayment(input: {\n hostId: string\n orderId: string\n paymentId: string\n}): Promise<PosPaymentOutcome> {\n const order = await readPosSale(input.hostId, input.orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n const payment = CommerceModel.orderPayments(order).find((entry) => entry.id === input.paymentId)\n if (!payment) return { ok: false, status: 404, error: 'Unknown payment' }\n if (!CommerceModel.isCardPaymentMethod(payment.method)) {\n return { ok: true, order, payment, completed: false, changed: false }\n }\n // Every object of this payment lives where it was made (null: the platform).\n const on = onAccount(posPaymentAccount(payment))\n let paymentIntentId = payment.paymentIntentId ?? ''\n if (!paymentIntentId && payment.checkoutSessionId) {\n const session = await posStripe('GET', `checkout/sessions/${payment.checkoutSessionId}`, on)\n if (session.ok && session.body?.status === 'expired' && payment.status === 'pending') {\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' ? { ...current, status: 'canceled' } : null,\n )\n }\n paymentIntentId = String(session.body?.payment_intent ?? '')\n }\n if (!paymentIntentId) return { ok: true, order, payment, completed: false, changed: false }\n let intent = (\n await posStripe('GET', `payment_intents/${paymentIntentId}`, {\n params: { 'expand[]': 'latest_charge' },\n ...on,\n })\n ).body\n if (!intent?.id) return { ok: true, order, payment, completed: false, changed: false }\n if (intent.metadata?.hostId !== input.hostId || intent.metadata?.paymentId !== payment.id) {\n console.error('[pos-terminal] intent does not belong to this payment', paymentIntentId)\n return { ok: false, status: 409, error: 'This payment does not match its card charge.' }\n }\n if (intent.status === 'requires_capture') {\n if (order.status !== 'pending' && payment.status !== 'pending') {\n // Nothing to capture into: the sale is gone. Release the hold.\n await posStripe('POST', `payment_intents/${intent.id}/cancel`, {\n idempotencyKey: `pos-release:${intent.id}`,\n ...on,\n })\n return { ok: true, order, payment, completed: false, changed: false }\n }\n const fee = posCaptureFeeCents(payment, intent)\n const captured = await posStripe('POST', `payment_intents/${intent.id}/capture`, {\n idempotencyKey: `pos-capture:${intent.id}`,\n params: {\n ...(fee > 0 ? { application_fee_amount: fee } : {}),\n 'expand[]': 'latest_charge',\n },\n ...on,\n })\n if (captured.ok && captured.body?.id) intent = captured.body\n else {\n console.error('[pos-terminal] capture failed', intent.id, captured.body?.error)\n return { ok: true, order, payment, completed: false, changed: false }\n }\n }\n if (intent.status === 'succeeded') {\n const tipCents = posIntentTipCents(intent)\n const amountCents = Math.max(0, Math.round(Number(intent.amount ?? 0))) - tipCents\n return await patchCardPayment(\n input.hostId,\n input.orderId,\n payment.id,\n (current) => {\n if (current.status === 'succeeded' && current.paymentIntentId === intent.id) return null\n return {\n ...withoutFailure(current),\n status: 'succeeded',\n settledAtMs: Date.now(),\n paymentIntentId: String(intent.id),\n // What the charge actually put toward the sale. Equal to the\n // reserved amount; restated from Stripe so the ledger records the\n // money that moved rather than the money that was asked for.\n amountCents: amountCents > 0 ? amountCents : current.amountCents,\n ...(tipCents > 0 ? { tipCents } : {}),\n feeCents: Math.max(0, Math.round(Number(intent.application_fee_amount ?? 0))),\n livemode: Boolean(intent.livemode),\n ...cardDetailsOf(intent),\n }\n },\n )\n }\n if (intent.status === 'canceled') {\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' || current.status === 'failed'\n ? { ...current, status: 'canceled' }\n : null,\n )\n }\n if (intent.status === 'requires_payment_method' && intent.last_payment_error) {\n const message = String(intent.last_payment_error?.message ?? 'The card was declined.')\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' ? { ...current, status: 'failed', failureMessage: message } : null,\n )\n }\n // Still waiting on the customer. A reader action that already failed (a\n // card removed, a cancel on the reader) says so on the reader, not the\n // intent, so ask the reader too.\n if (payment.method === 'card_present' && payment.readerId && payment.status === 'pending') {\n const reader = await refreshPosReaderStatus(input.hostId, payment.readerId, posPaymentAccount(payment))\n const action = reader?.action\n if (\n action?.type === 'process_payment_intent' &&\n action?.process_payment_intent?.payment_intent === intent.id &&\n action?.status === 'failed'\n ) {\n const message = String(action.failure_message ?? 'The reader could not take the card.')\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' ? { ...current, status: 'failed', failureMessage: message } : null,\n )\n }\n }\n const fresh = await readPosSale(input.hostId, input.orderId)\n return {\n ok: true,\n order: fresh ?? order,\n payment:\n CommerceModel.orderPayments(fresh ?? order).find((entry) => entry.id === payment.id) ?? payment,\n completed: false,\n changed: false,\n }\n}\n\n/**\n * Stops a card payment that has not been paid: clears the reader, cancels the\n * intent, expires the payment page. A charge that already went through is\n * left alone and recorded as paid, never cancelled under the customer.\n */\nexport async function cancelPosCardPayment(input: {\n hostId: string\n orderId: string\n paymentId: string\n}): Promise<PosPaymentOutcome> {\n const refreshed = await refreshPosCardPayment(input)\n if (!refreshed.ok || !refreshed.payment) return refreshed\n const payment = refreshed.payment\n if (payment.status === 'succeeded' || payment.status === 'canceled') return refreshed\n const on = onAccount(posPaymentAccount(payment))\n if (payment.method === 'card_present' && payment.readerId) {\n const cleared = await posStripe('POST', `terminal/readers/${payment.readerId}/cancel_action`, on)\n if (!cleared.ok && cleared.body?.error?.code === 'terminal_reader_busy') {\n return {\n ok: false,\n status: 409,\n error: 'The customer is mid-payment on the reader. Wait for it to finish.',\n }\n }\n }\n if (payment.paymentIntentId) {\n await posStripe('POST', `payment_intents/${payment.paymentIntentId}/cancel`, {\n idempotencyKey: `pos-cancel:${payment.paymentIntentId}`,\n ...on,\n })\n }\n if (payment.checkoutSessionId) {\n await posStripe('POST', `checkout/sessions/${payment.checkoutSessionId}/expire`, {\n idempotencyKey: `pos-expire:${payment.checkoutSessionId}`,\n ...on,\n })\n }\n // Re-read: a payment that completed in the gap is recorded as paid.\n const settled = await refreshPosCardPayment(input)\n if (settled.ok && settled.payment?.status === 'succeeded') return settled\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' || current.status === 'failed'\n ? { ...current, status: 'canceled' }\n : null,\n )\n}\n\n/**\n * TEST MODE ONLY: Stripe's simulated reader is \"tapped\" with a test card.\n * Refused outright on a live key, whatever the request says.\n */\nexport async function simulatePosReaderTap(input: {\n hostId: string\n orderId: string\n paymentId: string\n /** `4000000000000002` declines; anything else Stripe's default approves. */\n cardNumber?: string\n}): Promise<PosPaymentOutcome> {\n if (!posStripeTestMode()) return { ok: false, status: 403, error: 'Only in test mode' }\n const order = await readPosSale(input.hostId, input.orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n const payment = CommerceModel.orderPayments(order).find((entry) => entry.id === input.paymentId)\n if (!payment?.readerId || payment.method !== 'card_present') {\n return { ok: false, status: 404, error: 'Unknown payment' }\n }\n const reader = await ownedTerminalReader(input.hostId, payment.readerId)\n if (!reader) return { ok: false, status: 404, error: 'That card reader is not on this site.' }\n const presented = await posStripe(\n 'POST',\n `test_helpers/terminal/readers/${reader.id}/present_payment_method`,\n {\n ...onAccount(posReaderAccount(reader)),\n params: {\n type: 'card_present',\n ...(input.cardNumber && /^[0-9]{12,19}$/.test(input.cardNumber)\n ? { 'card_present[number]': input.cardNumber }\n : {}),\n },\n },\n )\n if (!presented.ok) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(presented.body, 'The simulated tap failed.'),\n }\n }\n return await refreshPosCardPayment(input)\n}\n\n/*==========================================\n * WEBHOOKS (the small branch `billing-webhook.ts` calls).\n *=========================================*/\n\n/** Where a Stripe object says a register payment lives, or null. */\nfunction posPaymentRef(\n metadata: Record<string, unknown> | undefined,\n): { hostId: string; orderId: string; paymentId: string } | null {\n const hostId = String(metadata?.['hostId'] ?? '')\n const orderId = String(metadata?.['orderId'] ?? '')\n const paymentId = String(metadata?.['paymentId'] ?? '')\n if (!hostId || !orderId || !paymentId) return null\n return { hostId, orderId, paymentId }\n}\n\n/**\n * The register's Stripe events: a reader finished or failed an action, a\n * register PaymentIntent was authorized, paid, declined or cancelled, or a\n * register QR page was paid or expired. Each resolves to ONE payment and is\n * answered by re-reading Stripe through {@link refreshPosCardPayment}, never\n * by trusting the event's own copy (whose API version predates the tip\n * fields). Returns the site when the event was the register's, so the\n * dispatcher can count it as claimed; null for every other event.\n *\n * `account` is the connected account a Connect-delivered event came from\n * (`connectEventAccount`): a direct-charge store's reader and intents live\n * there, so the reader event's intent is read there. The settlement itself\n * reads the account the payment recorded, never the event's word.\n */\nexport async function handlePosStripeEvent(input: {\n type: string\n object: any\n account?: string | null\n}): Promise<{ hostId: string } | null> {\n const { type, object } = input\n let ref: { hostId: string; orderId: string; paymentId: string } | null = null\n if (type === 'terminal.reader.action_succeeded' || type === 'terminal.reader.action_failed') {\n const intentId = String(object?.action?.process_payment_intent?.payment_intent ?? '')\n if (object?.action?.type !== 'process_payment_intent' || !intentId) return null\n const intent = await posStripe('GET', `payment_intents/${intentId}`, onAccount(input.account ?? null))\n if (!intent.ok || intent.body?.metadata?.kind !== 'pos') return null\n ref = posPaymentRef(intent.body.metadata)\n } else if (\n type === 'payment_intent.amount_capturable_updated' ||\n type === 'payment_intent.succeeded' ||\n type === 'payment_intent.payment_failed' ||\n type === 'payment_intent.canceled'\n ) {\n if (object?.metadata?.kind !== 'pos') return null\n ref = posPaymentRef(object.metadata)\n } else if (\n (type === 'checkout.session.completed' || type === 'checkout.session.expired') &&\n object?.metadata?.type === 'pos-payment'\n ) {\n ref = posPaymentRef(object.metadata)\n } else {\n return null\n }\n if (!ref) return null\n // A reader can be re-registered by nobody else, but an event is only a\n // claim: the intent's own metadata must name a reader this site owns.\n await refreshPosCardPayment(ref).catch((error) => {\n console.error('[pos-terminal] webhook settle failed', ref, error)\n // Rethrown so the delivery is retried: a lost settlement is a sale the\n // register cannot complete without its poll.\n throw error\n })\n return { hostId: ref.hostId }\n}\n\nexport type { PosLiftedOrder }\n\n/*==========================================\n * CARDS TAKEN OFFLINE ON THE APP'S OWN READER (AGL-4039).\n *\n * The Aglyn POS app creates these PaymentIntents itself (Stripe stores the\n * card on the device and forwards it once a connection returns), so the\n * server meets them only at the sale's sync: it reads the intent, checks it\n * is the sale's, and captures it with the platform fee, the same capture an\n * online reader payment gets after its tip is known.\n *=========================================*/\n\n/** A PaymentIntent the offline sync reads, reduced to what it checks. */\nexport interface PosOfflineCardIntent {\n id: string\n status: string\n amount: number\n currency: string\n metadata: Record<string, string>\n destination: string\n applicationFeeCents: number\n livemode: boolean\n brand?: string\n last4?: string\n failureMessage?: string\n}\n\nfunction offlineCardIntent(body: any): PosOfflineCardIntent {\n const charge = body?.latest_charge && typeof body.latest_charge === 'object' ? body.latest_charge : null\n const present = charge?.payment_method_details?.card_present ?? {}\n const error = body?.last_payment_error ?? null\n return {\n id: String(body?.id ?? ''),\n status: String(body?.status ?? ''),\n amount: Number(body?.amount ?? 0),\n currency: String(body?.currency ?? ''),\n metadata: (body?.metadata ?? {}) as Record<string, string>,\n destination: String(body?.transfer_data?.destination ?? ''),\n applicationFeeCents: Number(body?.application_fee_amount ?? 0),\n livemode: Boolean(body?.livemode),\n ...(present.brand ? { brand: String(present.brand) } : {}),\n ...(present.last4 ? { last4: String(present.last4) } : {}),\n ...(error ? { failureMessage: String(error.message ?? error.decline_code ?? 'The card was declined.') } : {}),\n }\n}\n\n/**\n * Reads one offline card's PaymentIntent, with its charge's card details, on\n * `account` (a direct-charge store's own, where its app's SDK made it) or\n * the platform.\n */\nexport async function retrievePosOfflineCardIntent(\n paymentIntentId: string,\n account: string | null = null,\n): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string; status: number }> {\n const fetched = await posStripe('GET', `payment_intents/${encodeURIComponent(paymentIntentId)}`, {\n params: { expand: ['latest_charge'] },\n ...onAccount(account),\n })\n // The status tells the sync whether Stripe definitely has no such intent on that account (AGL-4219).\n if (!fetched.ok) {\n return {\n ok: false,\n status: fetched.status,\n error: posStripeErrorMessage(fetched.body, 'The card payment could not be read.'),\n }\n }\n return { ok: true, intent: offlineCardIntent(fetched.body) }\n}\n\n/**\n * Captures one authorized offline card with the platform's fee, on `account`\n * (a direct-charge store's own, where its app's SDK made it, AGL-4219) or the\n * platform; a repeat finds the first capture. Stripe takes the application\n * fee at capture on a direct charge too, from the store's account to the\n * platform, which is how an online direct reader payment is captured.\n */\nexport async function capturePosOfflineCardIntent(\n paymentIntentId: string,\n applicationFeeCents: number,\n idempotencyKey: string,\n account: string | null = null,\n): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string; status: number }> {\n const captured = await posStripe('POST', `payment_intents/${encodeURIComponent(paymentIntentId)}/capture`, {\n idempotencyKey,\n ...onAccount(account),\n params: {\n ...(applicationFeeCents > 0 ? { application_fee_amount: applicationFeeCents } : {}),\n expand: ['latest_charge'],\n },\n })\n // The status tells the sync whether this attempt definitely failed (AGL-4039).\n if (!captured.ok) {\n return {\n ok: false,\n status: captured.status,\n error: posStripeErrorMessage(captured.body, 'The card payment could not be captured.'),\n }\n }\n return { ok: true, intent: offlineCardIntent(captured.body) }\n}\n\n/**\n * Cancels one offline card's authorization on `account` (a direct-charge\n * store's own, or another the device recorded) or the platform, so the\n * customer's hold is released (AGL-4219). The sync asks only for an intent\n * it read as `requires_capture`; Stripe refuses to cancel a captured one.\n */\nexport async function cancelPosOfflineCardIntent(\n paymentIntentId: string,\n account: string | null,\n idempotencyKey: string,\n): Promise<{ ok: true } | { ok: false; error: string; status: number }> {\n const cancelled = await posStripe('POST', `payment_intents/${encodeURIComponent(paymentIntentId)}/cancel`, {\n idempotencyKey,\n ...onAccount(account),\n params: { cancellation_reason: 'abandoned' },\n })\n if (!cancelled.ok) {\n return {\n ok: false,\n status: cancelled.status,\n error: posStripeErrorMessage(cancelled.body, 'The card payment could not be cancelled.'),\n }\n }\n return { ok: true }\n}\n\n/**\n * Turns Stripe's offline mode on for the site's readers, on the site's ONE\n * Terminal Configuration through {@link savePosReaderConfiguration}, like\n * reader tipping and the start-up screen (AGL-4048). That helper claims a\n * first create in a transaction, so offline mode racing tipping or the\n * start-up screen to the first write lands on one configuration with both\n * settings, never two configurations of which only one is assigned; and it\n * finishes an assignment a previous first write left owing.\n *\n * Done once per configuration: `offlineConfigurationId` records which one\n * carries `offline[enabled]`, so a site whose configuration was replaced or\n * is still owed its assignment is set again rather than answered from a flag\n * that no longer describes what its readers use. A reader picks the setting\n * up the next time it connects online. False when Stripe refused it.\n */\nexport async function ensurePosOfflineCardConfiguration(hostId: string): Promise<boolean> {\n const ref = terminalConfigRef(hostId)\n const config = await ref.get()\n if (!config.get('stripeLocationId')) return false\n const configurationId = String(config.get('stripeConfigurationId') ?? '')\n if (\n config.get('offlineEnabled') === true &&\n configurationId &&\n config.get('offlineConfigurationId') === configurationId &&\n config.get('stripeConfigurationAssigned') !== false\n ) {\n return true\n }\n const saved = await savePosReaderConfiguration(hostId, { 'offline[enabled]': true }, 'offline')\n if ('error' in saved) {\n console.error('[pos-terminal] offline configuration failed', hostId, saved.error)\n return false\n }\n await ref.set({ offlineEnabled: true, offlineConfigurationId: saved.configurationId }, { merge: true })\n return true\n}\n"],"names":["createHash","firebaseAdmin","merchantAccountIsReady","sellerPaymentAccount","cardAuthenticationParams","checkoutSessionCardAuthenticationParams","CommerceModel","POS_CURRENCY","posCardApplicationFeeCents","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","applyPosPayment","readPosSale","NOT_A_SALE","ok","status","error","withoutFailure","payment","next","failureMessage","posMerchantAccount","hostId","org","seller","accountId","chargesEnabled","accountLivemode","subject","chargeModel","posTerminalAccount","recordedAccount","value","id","trim","posPaymentAccount","stripeAccountId","posReaderAccount","reader","stripeAccount","POS_READER_ON_OTHER_ACCOUNT","locationOnAccount","config","account","locationId","String","get","LOCATION_BOUND_FIELDS","terminalConfigRef","app","firestore","collection","doc","readerRef","readerId","isTerminalReaderId","test","ownedTerminalReader","snapshot","exists","data","posTerminalAddressProblem","address","line1","city","postalCode","country","posTerminalLocationKey","displayName","fingerprint","update","JSON","stringify","slice","line2","state","digest","locationAddressOf","location","undefined","text","postal_code","ensurePosTerminalLocation","options","existing","created","ref","known","knownAccount","addressGiven","previous","body","problem","locationKey","idempotencyKey","params","display_name","orgId","replaced","Boolean","set","stripeLocationId","livemode","createdAtMs","Date","now","stripeLocationAccount","FieldValue","delete","Object","fromEntries","map","field","replacedLocation","atMs","merge","saved","savePosReaderConfiguration","console","cellularConfigurationId","configurationId","then","cellular","syncPosCellularReaders","catch","splash","applyPosReaderSplash","posReaderTippingKey","settings","tippingEnabled","tipPercentages","join","createKey","onAccount","updated","code","assigned","assignPosReaderConfiguration","createdId","winner","runTransaction","transaction","fresh","stripeConfigurationId","stripeConfigurationAssigned","configuration_overrides","syncPosReaderTipping","key","percentages","tippingKey","refreshPosReaderStatus","fetched","lastSeenAtMs","action","reserveCardPayment","start","method","extra","orderId","paymentId","decide","order","payments","kind","total","Number","totals","totalCents","tenderable","posTenderableCents","amountCents","toFixed","tipProblem","posTipProblem","tipCents","takeFeeCents","posTakeShareCents","posTakeFeeCents","cashierId","patchCardPayment","patch","event","isDirect","merchant","onMerchant","directPaymentFields","paymentIntentParams","chargeCents","methodTypes","fee","takeShareCents","inPerson","Array","isArray","includes","direct","amount","currency","application_fee_amount","createCardPresentIntent","intent","readerAccount","reserved","payment_method_types","capture_method","description","current","paymentIntentId","recorded","client_secret","clientSecret","startCardPresentPayment","sendToReader","skipTipping","attempt","posTerminalRecordedLocationId","posTerminalLocationId","Promise","all","resolve","createPosTerminalConnectionToken","token","secret","input","processed","payment_intent","retryCardPresentPayment","orderPayments","find","entry","completed","changed","rearmed","filter","startCardKeyedPayment","paymentMethodId","isPaymentMethodId","confirmKeyedCard","KEYED_CARD_NEEDS_AUTHENTICATION","intentId","confirmed","cloned","payment_method","message","refreshPosCardPayment","startCardLinkPayment","session","checkoutSessionId","mode","success_url","returnUrl","cancel_url","url","checkoutUrl","cardDetailsOf","charge","latest_charge","details","payment_method_details","card_present","interac_present","card","brand","cardBrand","last4","posIntentTipCents","preset","Math","max","round","metadata","onReader","amount_details","tip","posCaptureFeeCents","isCardPaymentMethod","on","captured","settledAtMs","feeCents","last_payment_error","type","process_payment_intent","failure_message","cancelPosCardPayment","settled","refreshed","cleared","simulatePosReaderTap","presented","cardNumber","posPaymentRef","handlePosStripeEvent","object","offlineCardIntent","present","destination","transfer_data","applicationFeeCents","decline_code","retrievePosOfflineCardIntent","encodeURIComponent","expand","capturePosOfflineCardIntent","cancelPosOfflineCardIntent","cancelled","cancellation_reason","ensurePosOffline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AE;QACzGjH;OACGuC,UAAU1F;QACboD,QAAQ;YAAEmN,qBAAqB;QAAY;;IAE7C,IAAI,CAACD,UAAUnS,EAAE,EAAE;QACjB,OAAO;YACLA,IAAI;YACJC,QAAQkS,UAAUlS,MAAM;YACxBC,OAAOR,sBAAsByS,UAAUtN,IAAI,EAAE;QAC/C;IACF;IACA,OAAO;QAAE7E,IAAI;IAAK;AACpB;AAEA;;;;;;;;;;;;;;CAcC,GACD,OAAO,eAAeqS,kCAAkC7R,MAAc;QAIrCoB;IAH/B,MAAM4C,MAAMtC,kBAAkB1B;IAC9B,MAAMoB,SAAS,MAAM4C,IAAIxC,GAAG;IAC5B,IAAI,CAACJ,OAAOI,GAAG,CAAC,qBAAqB,OAAO;IAC5C,MAAM0E,kBAAkB3E,QAAOH,cAAAA,OAAOI,GAAG,CAAC,oCAAXJ,cAAuC;IACtE,IACEA,OAAOI,GAAG,CAAC,sBAAsB,QACjC0E,mBACA9E,OAAOI,GAAG,CAAC,8BAA8B0E,mBACzC9E,OAAOI,GAAG,CAAC,mCAAmC,OAC9C;QACA,OAAO;IACT;IACA,MAAMsE,QAAQ,MAAMC,2BAA2B/F,QAAQ;QAAE,oBAAoB;IAAK,GAAG;IACrF,IAAI,WAAW8F,OAAO;QACpBE,QAAQtG,KAAK,CAAC,+CAA+CM,QAAQ8F,MAAMpG,KAAK;QAChF,OAAO;IACT;IACA,MAAMsE,IAAIc,GAAG,CAAC;QAAEgN,gBAAgB;QAAMC,wBAAwBjM,MAAMI,eAAe;IAAC,GAAG;QAAEL,OAAO;IAAK;IACrG,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-terminal.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 { createHash } from 'node:crypto'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport {\n merchantAccountIsReady,\n type SaleChargeModel,\n} from '@aglyn/tenant-data-admin/server/payment-provider'\nimport { sellerPaymentAccount } from '@aglyn/tenant-data-admin/server/seller-payment-account'\nimport {\n cardAuthenticationParams,\n checkoutSessionCardAuthenticationParams,\n} from '@aglyn/tenant-data-admin/server/stripe-card-authentication'\nimport * as CommerceModel from '../model'\nimport type { PosRegisterSettings } from '../plugin-config'\nimport {\n POS_CURRENCY,\n posCardApplicationFeeCents,\n posStripe,\n posStripeErrorMessage,\n posStripeTestMode,\n posTerminalAvailable,\n} from './pos-stripe'\nimport { applyPosPayment, readPosSale, type PosLiftedOrder, type PosPaymentOutcome } from './pos-sale'\n\n/*==========================================\n * STRIPE TERMINAL AND THE REGISTER'S OTHER CARD TENDERS (AGL-3607).\n *\n * ## Where the readers live\n *\n * Two shapes, decided by the store's selling account\n * ({@link posMerchantAccount}, which asks `sellerPaymentAccount`):\n *\n * - DESTINATION (every Express account, so every store before the switch):\n * the charge is made on the PLATFORM account and transferred on, so\n * Stripe's rule for that model applies: Locations and Readers are created\n * on the platform with the platform key, and identify their merchant by\n * metadata.\n * - DIRECT (a store on its own full Stripe account, ToS v24 section\n * 10.2(a)): EVERY Terminal object, the Location, its Configuration, the\n * Readers, each connection token and each PaymentIntent, is made ON the\n * store's account with the `Stripe-Account` header. A connection token\n * sees only its own account's readers and locations, so nothing may mix.\n *\n * One Location per site (`hosts/{hostId}/terminal/config`), and one\n * `hosts/{hostId}/terminalReaders/{readerId}` document per reader, written\n * only here. Each records the account it was made on\n * (`stripeLocationAccount`, `stripeAccount`; absent = the platform), and an\n * id made on another account than the store sells on now is never used: a\n * Location is made again on the store's account, and a reader must be\n * registered again. The reader document is what makes a reader THIS site's: every call that\n * names a reader reads it under the caller's own site first, so one store can\n * never drive, rename or remove another's reader, and the reader's own\n * `metadata.hostId` is checked again before a payment is sent to it.\n *\n * ## Why the reader charges with MANUAL capture\n *\n * On-reader tipping changes the amount after the PaymentIntent exists: the\n * reader adds the tip on confirmation and reports it in\n * `amount_details.tip.amount`. `application_fee_amount` set at creation was\n * sized on the pre-tip amount, and the platform's take must exclude the tip\n * while Stripe's processing cost (debited from the platform) is on the whole\n * charge. So the reader only AUTHORIZES; {@link refreshPosCardPayment} reads\n * the tip, re-prices the fee as\n *\n * take share (of the sale, never of the tip) + card processing (whole charge)\n *\n * and captures with that exact `application_fee_amount`. Stripe's own Connect\n * guidance for Terminal is the same: inspect, fix the application fee, then\n * capture. An authorization expires after two days, and a register capture\n * happens seconds after the tap.\n *=========================================*/\n\nconst NOT_A_SALE = { ok: false as const, status: 409, error: 'This sale is no longer open' }\n\n/** `hosts/{hostId}/terminalReaders/{readerId}`. */\nexport interface PosTerminalReader {\n label: string\n registerId?: string\n stripeLocationId: string\n deviceType?: string\n serialNumber?: string\n status?: 'online' | 'offline' | string\n livemode: boolean\n createdAtMs: number\n createdBy?: string\n lastSeenAtMs?: number\n /**\n * The store's own Stripe account the reader is registered on, for a\n * direct-charge store. Absent: registered on the platform.\n */\n stripeAccount?: string\n}\n\n/**\n * The payment without its failure reason. Removed, never set to `undefined`:\n * Firestore refuses an undefined field inside the `payments` array.\n */\nfunction withoutFailure(payment: CommerceModel.OrderPayment): CommerceModel.OrderPayment {\n const next = { ...payment }\n delete next.failureMessage\n return next\n}\n\n/** The store's selling account for an in-person card, and how it sells. */\nexport interface PosMerchant {\n accountId: string\n chargeModel: SaleChargeModel\n}\n\n/**\n * The merchant's connected account and its charge model, when it can take\n * card payments now. The ONE door every in-person card route reads the\n * store's account through; where the account is recorded is\n * `sellerPaymentAccount`'s business, not this file's.\n */\nexport async function posMerchantAccount(\n hostId: string,\n org: Record<string, any> | null,\n): Promise<PosMerchant | null> {\n const seller = await sellerPaymentAccount(hostId, org)\n if (!seller) return null\n if (\n !merchantAccountIsReady(\n {\n accountId: seller.accountId,\n chargesEnabled: seller.chargesEnabled,\n accountLivemode: seller.accountLivemode,\n },\n { subject: `POS card payment host ${hostId}` },\n )\n ) {\n return null\n }\n return { accountId: seller.accountId, chargeModel: seller.chargeModel }\n}\n\n/**\n * The account the site's Terminal objects belong on NOW: the store's own for\n * a direct-charge store, null (the platform) for every other. Not gated on\n * readiness: a Location or a reader belongs where the store will sell.\n */\nexport async function posTerminalAccount(\n hostId: string,\n org?: Record<string, any> | null,\n): Promise<string | null> {\n const seller = await sellerPaymentAccount(hostId, org)\n return seller?.chargeModel === 'direct' ? seller.accountId : null\n}\n\n/** The account a stored Terminal id was made on; null for the platform. */\nfunction recordedAccount(value: unknown): string | null {\n const id = typeof value === 'string' ? value.trim() : ''\n return id || null\n}\n\n/** The account a card payment's Stripe objects live on; null for the platform. */\nexport function posPaymentAccount(\n payment: Pick<CommerceModel.OrderPayment, 'chargeModel' | 'stripeAccountId'>,\n): string | null {\n return payment.chargeModel === 'direct' ? recordedAccount(payment.stripeAccountId) : null\n}\n\n/** The account a reader is registered on; null for the platform. */\nexport function posReaderAccount(reader: Pick<PosTerminalReader, 'stripeAccount'>): string | null {\n return recordedAccount(reader.stripeAccount)\n}\n\n/** What a cashier reads when a reader sits on another account than the store sells on. */\nexport const POS_READER_ON_OTHER_ACCOUNT =\n 'This card reader was set up before the store started taking payments on its own Stripe account. Remove it in Registers and devices, then add it again with the new code it shows.'\n\n/**\n * The site's Location, when it was made on `account` (null: the platform).\n * A Location made on another account is no Location for this one.\n */\nfunction locationOnAccount(\n config: { get(field: string): unknown },\n account: string | null,\n): string | null {\n const locationId = String(config.get('stripeLocationId') ?? '')\n if (!locationId) return null\n return recordedAccount(config.get('stripeLocationAccount')) === account ? locationId : null\n}\n\n/**\n * Everything on the site's terminal document that describes the Location's\n * ONE Configuration. Cleared when the Location is made again on another\n * account, so tipping, offline mode, the start-up screen and 4G are written\n * onto a configuration on the new account rather than answered from flags\n * that describe the old one.\n */\nconst LOCATION_BOUND_FIELDS = [\n 'stripeConfigurationId',\n 'stripeConfigurationAssigned',\n 'tippingKey',\n 'offlineEnabled',\n 'offlineConfigurationId',\n 'splashAppliedKey',\n 'splashAppliedAtMs',\n] as const\n\nfunction terminalConfigRef(hostId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminal')\n .doc('config')\n}\n\nfunction readerRef(hostId: string, readerId: string) {\n return firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('terminalReaders')\n .doc(readerId)\n}\n\n/** A reader id as Stripe mints them; anything else never reaches Stripe. */\nexport function isTerminalReaderId(value: unknown): value is string {\n return typeof value === 'string' && /^tmr_[A-Za-z0-9]{6,64}$/.test(value)\n}\n\n/** The reader, when it is THIS site's; null for anyone else's or none. */\nexport async function ownedTerminalReader(\n hostId: string,\n readerId: unknown,\n): Promise<(PosTerminalReader & { id: string }) | null> {\n if (!isTerminalReaderId(readerId)) return null\n const snapshot = await readerRef(hostId, readerId).get()\n if (!snapshot.exists) return null\n return { ...(snapshot.data() as PosTerminalReader), id: readerId }\n}\n\n/** A Terminal Location's address, as the console sends it. */\nexport interface PosTerminalAddress {\n line1: string\n line2?: string\n city: string\n state?: string\n postalCode: string\n country: string\n}\n\nexport function posTerminalAddressProblem(address: Partial<PosTerminalAddress> | undefined): string | null {\n if (!address?.line1 || !address?.city || !address?.postalCode || !address?.country) {\n return 'Enter the street, city, postal code and country where the reader is used.'\n }\n if (!/^[A-Z]{2}$/.test(String(address.country))) return 'Choose a two-letter country code, like US.'\n return null\n}\n\n/**\n * The idempotency key of a site's Location request. Two presses with the same\n * address share it, so a double tap makes one Location; a corrected address\n * gets its own, since Stripe refuses a key reused with other parameters for a\n * day (a merchant fixing a typo would otherwise read that refusal).\n */\nexport function posTerminalLocationKey(hostId: string, displayName: string, address: PosTerminalAddress): string {\n const fingerprint = createHash('sha256')\n .update(\n JSON.stringify([\n displayName.slice(0, 100),\n address.line1,\n address.line2 ?? '',\n address.city,\n address.state ?? '',\n address.postalCode,\n address.country,\n ]),\n )\n .digest('hex')\n .slice(0, 16)\n return `pos-location:${hostId}:${fingerprint}`\n}\n\n/** A Location's address as Stripe returns it, in the console's shape. */\nfunction locationAddressOf(location: any): PosTerminalAddress | undefined {\n const address = location?.address\n if (!address || typeof address !== 'object') return undefined\n const text = (value: unknown) => (typeof value === 'string' ? value : '')\n return {\n line1: text(address.line1),\n ...(text(address.line2) ? { line2: text(address.line2) } : {}),\n city: text(address.city),\n ...(text(address.state) ? { state: text(address.state) } : {}),\n postalCode: text(address.postal_code),\n country: text(address.country),\n }\n}\n\n/**\n * The site's Terminal Location, created on first use, on the account the\n * store sells on ({@link posTerminalAccount}): the PLATFORM for a destination\n * store, with the merchant named in metadata, or the store's OWN account for\n * a direct-charge store. Its address is the store's, because Stripe uses it\n * to configure the reader for the right country.\n *\n * A Location recorded on another account (a store that sold through the\n * platform before it moved to its own account) is made again on the store's\n * account, at the address given or else the old Location's own, and the\n * configuration it carried is set up again there.\n */\nexport async function ensurePosTerminalLocation(options: {\n hostId: string\n orgId: string\n displayName: string\n address?: PosTerminalAddress\n /** The account to make it on, when the caller already asked; else asked here. */\n account?: string | null\n}): Promise<{ ok: true; locationId: string } | { ok: false; status: number; error: string }> {\n const account =\n options.account !== undefined ? options.account : await posTerminalAccount(options.hostId)\n const ref = terminalConfigRef(options.hostId)\n const existing = await ref.get()\n const known = String(existing.get('stripeLocationId') ?? '')\n const knownAccount = recordedAccount(existing.get('stripeLocationAccount'))\n if (known && knownAccount === account) return { ok: true, locationId: known }\n let addressGiven = options.address\n if (known && !addressGiven) {\n const previous = await posStripe('GET', `terminal/locations/${known}`, { stripeAccount: knownAccount })\n if (previous.ok) addressGiven = locationAddressOf(previous.body)\n }\n const problem = posTerminalAddressProblem(addressGiven)\n if (problem) return { ok: false, status: 400, error: problem }\n const address = addressGiven as PosTerminalAddress\n const locationKey = posTerminalLocationKey(options.hostId, options.displayName, address)\n const created = await posStripe('POST', 'terminal/locations', {\n // A direct store's key names its account: the same address once made on\n // the platform must never replay the platform's Location.\n idempotencyKey: account ? `${locationKey}:${account}` : locationKey,\n ...(account ? { stripeAccount: account } : {}),\n params: {\n display_name: options.displayName.slice(0, 100) || 'Store',\n 'address[line1]': address.line1,\n 'address[line2]': address.line2 || undefined,\n 'address[city]': address.city,\n 'address[state]': address.state || undefined,\n 'address[postal_code]': address.postalCode,\n 'address[country]': address.country,\n 'metadata[orgId]': options.orgId,\n 'metadata[hostId]': options.hostId,\n },\n })\n if (!created.ok || !created.body?.id) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(created.body, 'The reader location could not be set up.'),\n }\n }\n const replaced = Boolean(known)\n await ref.set(\n {\n stripeLocationId: String(created.body.id),\n livemode: Boolean(created.body.livemode),\n createdAtMs: Date.now(),\n ...(account ? { stripeLocationAccount: account } : {}),\n ...(replaced\n ? {\n ...(account ? {} : { stripeLocationAccount: firebaseAdmin.firestore.FieldValue.delete() }),\n ...Object.fromEntries(\n LOCATION_BOUND_FIELDS.map((field) => [field, firebaseAdmin.firestore.FieldValue.delete()]),\n ),\n replacedLocation: { id: known, account: knownAccount ?? 'platform', atMs: Date.now() },\n }\n : {}),\n },\n { merge: true },\n )\n // 4G was on for the old Location's readers: it is turned on again on the\n // new one's configuration, so readers registered there keep it (AGL-4038).\n if (replaced && existing.get('cellularEnabled') === true) {\n const saved = await savePosReaderConfiguration(options.hostId, { 'cellular[enabled]': true }, 'cellular-on')\n if ('error' in saved) {\n console.error('[pos-terminal] 4G not turned on for the new location', options.hostId, saved.error)\n } else {\n await ref.set({ cellularConfigurationId: saved.configurationId }, { merge: true })\n await import('./pos-cellular')\n .then((cellular) => cellular.syncPosCellularReaders({ hostId: options.hostId, orgId: options.orgId }))\n .catch((error) => console.error('[pos-terminal] 4G records not moved', options.hostId, error))\n }\n }\n // A new Location starts with the store's reader start-up screen (AGL-4048).\n // Never fatal, and loaded only here: it draws images.\n await import('./pos-reader-splash')\n .then((splash) => splash.applyPosReaderSplash(options.hostId))\n .catch((error) => console.error('[pos-terminal] start-up screen not applied', options.hostId, error))\n return { ok: true, locationId: String(created.body.id) }\n}\n\n/** The tipping a reader shows: Stripe offers three buttons, so three presets. */\nexport function posReaderTippingKey(settings: PosRegisterSettings): string {\n return settings.tippingEnabled ? settings.tipPercentages.slice(0, 3).join(',') : 'off'\n}\n\ntype PosStripeParams = Record<string, string | number | boolean | undefined | null | readonly string[]>\n\n/**\n * Writes `params` onto the site's ONE Terminal Configuration, creating it and\n * assigning it to the site's Location on first use. Reader tipping and the\n * start-up screen (AGL-4048) both live on it, because a Location takes one\n * configuration override: a second configuration assigned for the screen\n * would silently drop the tipping presets, and the other way round. Stripe\n * leaves every parameter an update does not name as it was, so each caller\n * sends only its own.\n *\n * The first write is the only race. Tipping's runs as a payment starts, the\n * screen's when the POS devices card saves, and two at once would each make a\n * configuration. So the new id is CLAIMED in a transaction: the loser writes\n * its parameters onto the winner's configuration and deletes its own.\n *\n * `createKey` keys only the create (`pos-configuration:{hostId}:{createKey}`),\n * so a retried first write makes one configuration. An update is not keyed:\n * it sets values, and repeating it changes nothing.\n */\nexport async function savePosReaderConfiguration(\n hostId: string,\n params: PosStripeParams,\n createKey: string,\n): Promise<{ ok: true; configurationId: string } | { ok: false; error: string }> {\n const ref = terminalConfigRef(hostId)\n const config = await ref.get()\n const locationId = String(config.get('stripeLocationId') ?? '')\n if (!locationId) return { ok: false, error: 'no-location' }\n // The configuration lives where its Location does: the store's own account\n // for a direct-charge store's Location, the platform otherwise.\n const account = recordedAccount(config.get('stripeLocationAccount'))\n const onAccount = account ? { stripeAccount: account } : {}\n const known = String(config.get('stripeConfigurationId') ?? '')\n if (known) {\n const updated = await posStripe('POST', `terminal/configurations/${known}`, { params, ...onAccount })\n if (!updated.ok) return { ok: false, error: String(updated.body?.error?.code ?? updated.status) }\n // A configuration recorded before AGL-4048 was only ever recorded once\n // it was assigned, so only an explicit `false` still owes the assignment.\n if (config.get('stripeConfigurationAssigned') === false) {\n const assigned = await assignPosReaderConfiguration(hostId, locationId, known, account)\n if (!assigned) return { ok: false, error: 'assignment' }\n }\n return { ok: true, configurationId: known }\n }\n const created = await posStripe('POST', 'terminal/configurations', {\n params,\n idempotencyKey: account\n ? `pos-configuration:${hostId}:${account}:${createKey}`\n : `pos-configuration:${hostId}:${createKey}`,\n ...onAccount,\n })\n if (!created.ok || !created.body?.id) {\n return { ok: false, error: String(created.body?.error?.code ?? created.status) }\n }\n const createdId = String(created.body.id)\n const winner: string = await firebaseAdmin\n .app()\n .firestore()\n .runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n const existing = String(fresh.get('stripeConfigurationId') ?? '')\n if (existing) return existing\n transaction.set(\n ref,\n { stripeConfigurationId: createdId, stripeConfigurationAssigned: false },\n { merge: true },\n )\n return createdId\n })\n if (winner !== createdId) {\n const updated = await posStripe('POST', `terminal/configurations/${winner}`, { params, ...onAccount })\n await posStripe('DELETE', `terminal/configurations/${createdId}`, onAccount).catch(() => undefined)\n if (!updated.ok) return { ok: false, error: String(updated.body?.error?.code ?? updated.status) }\n return { ok: true, configurationId: winner }\n }\n const assigned = await assignPosReaderConfiguration(hostId, locationId, createdId, account)\n return assigned ? { ok: true, configurationId: createdId } : { ok: false, error: 'assignment' }\n}\n\nasync function assignPosReaderConfiguration(\n hostId: string,\n locationId: string,\n configurationId: string,\n account: string | null,\n): Promise<boolean> {\n const assigned = await posStripe('POST', `terminal/locations/${locationId}`, {\n params: { configuration_overrides: configurationId },\n ...(account ? { stripeAccount: account } : {}),\n })\n if (!assigned.ok) {\n console.error('[pos-terminal] configuration assignment failed', hostId, assigned.body?.error)\n return false\n }\n await terminalConfigRef(hostId).set({ stripeConfigurationAssigned: true }, { merge: true })\n return true\n}\n\n/**\n * Keeps the site's reader tipping in step with the merchant's settings, on\n * the site's one Terminal Configuration ({@link savePosReaderConfiguration}),\n * rewritten only when the presets changed. Never fatal: a reader that keeps\n * the previous presets still takes the payment.\n */\nexport async function syncPosReaderTipping(\n hostId: string,\n settings: PosRegisterSettings,\n): Promise<void> {\n if (!settings.tippingEnabled) return\n const ref = terminalConfigRef(hostId)\n const config = await ref.get()\n if (!config.get('stripeLocationId')) return\n const key = posReaderTippingKey(settings)\n if (config.get('tippingKey') === key) return\n const percentages = settings.tipPercentages.slice(0, 3)\n const saved = await savePosReaderConfiguration(\n hostId,\n { [`tipping[${POS_CURRENCY}][percentages]`]: percentages.map(String) },\n key,\n )\n if ('error' in saved) {\n console.error('[pos-terminal] tipping configuration failed', hostId, saved.error)\n return\n }\n await ref.set({ tippingKey: key }, { merge: true })\n}\n\n/** Reads a reader from Stripe and keeps its status on the site's document. */\nexport async function refreshPosReaderStatus(\n hostId: string,\n readerId: string,\n /** The account the reader is registered on ({@link posReaderAccount}); null for the platform. */\n account: string | null = null,\n): Promise<{ status: string; action: any } | null> {\n const fetched = await posStripe('GET', `terminal/readers/${readerId}`, account ? { stripeAccount: account } : {})\n if (!fetched.ok) return null\n const status = String(fetched.body?.status ?? 'offline')\n await readerRef(hostId, readerId)\n .set({ status, lastSeenAtMs: Date.now() }, { merge: true })\n .catch(() => undefined)\n return { status, action: fetched.body?.action ?? null }\n}\n\n/*==========================================\n * TAKING A CARD PAYMENT.\n *=========================================*/\n\ninterface CardStart {\n hostId: string\n orderId: string\n paymentId: string\n amountCents: number\n /** A tip already chosen (on the customer display or by the cashier). */\n tipCents: number\n cashierId: string\n org: Record<string, any> | null\n}\n\n/** Reserves a pending card payment in the ledger, or finds the one this attempt made. */\nasync function reserveCardPayment(\n start: CardStart,\n method: CommerceModel.OrderPaymentMethod,\n extra: Partial<CommerceModel.OrderPayment>,\n): Promise<PosPaymentOutcome> {\n return await applyPosPayment({\n hostId: start.hostId,\n orderId: start.orderId,\n paymentId: start.paymentId,\n decide: ({ order, payments, existing }) => {\n if (existing) {\n // The same attempt again: hand back what it started. A failed card\n // is re-armed by `retry`, not by pressing the tender a second time.\n return { kind: 'keep' }\n }\n if (order.status !== 'pending') return { kind: 'refuse', ...NOT_A_SALE }\n const total = Number(order.totals?.totalCents ?? 0)\n const tenderable = CommerceModel.posTenderableCents(total, payments)\n if (!(start.amountCents > 0)) {\n return { kind: 'refuse', status: 400, error: 'Enter an amount to charge.' }\n }\n if (start.amountCents > tenderable) {\n return {\n kind: 'refuse',\n status: 409,\n error:\n tenderable > 0\n ? `Only $${(tenderable / 100).toFixed(2)} is left to pay on this sale.`\n : 'Nothing is left to pay on this sale.',\n }\n }\n const tipProblem = CommerceModel.posTipProblem(start.tipCents, start.amountCents)\n if (tipProblem) return { kind: 'refuse', status: 400, error: tipProblem }\n const takeFeeCents = CommerceModel.posTakeShareCents({\n takeFeeCents: Number(order.posTakeFeeCents ?? 0),\n totalCents: total,\n amountCents: start.amountCents,\n })\n return {\n kind: 'put',\n payment: {\n id: start.paymentId,\n method,\n amountCents: start.amountCents,\n ...(start.tipCents > 0 ? { tipCents: start.tipCents } : {}),\n status: 'pending',\n atMs: Date.now(),\n takeFeeCents,\n cashierId: start.cashierId,\n ...extra,\n },\n }\n },\n })\n}\n\n/** Writes Stripe's answer onto a pending card payment. */\nasync function patchCardPayment(\n hostId: string,\n orderId: string,\n paymentId: string,\n patch: (payment: CommerceModel.OrderPayment) => CommerceModel.OrderPayment | null,\n event?: { event: string; detail?: string },\n): Promise<PosPaymentOutcome> {\n return await applyPosPayment({\n hostId,\n orderId,\n paymentId,\n decide: ({ existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n const next = patch(existing)\n if (!next) return { kind: 'keep' }\n return { kind: 'put', payment: next, ...(event ? { event } : {}) }\n },\n })\n}\n\n/** Whether a store sells by direct charge, for the fee and the request. */\nfunction isDirect(merchant: PosMerchant): boolean {\n return merchant.chargeModel === 'direct'\n}\n\n/** The `posStripe` option that puts a request on a direct store's account. */\nfunction onMerchant(merchant: PosMerchant): { stripeAccount?: string } {\n return isDirect(merchant) ? { stripeAccount: merchant.accountId } : {}\n}\n\n/** The `posStripe` option for a recorded account (null: the platform). */\nfunction onAccount(account: string | null): { stripeAccount?: string } {\n return account ? { stripeAccount: account } : {}\n}\n\n/** What a direct card payment records about where it lives; nothing for a destination one. */\nfunction directPaymentFields(merchant: PosMerchant): Partial<CommerceModel.OrderPayment> {\n return isDirect(merchant) ? { chargeModel: 'direct', stripeAccountId: merchant.accountId } : {}\n}\n\nfunction paymentIntentParams(\n start: CardStart,\n payment: CommerceModel.OrderPayment,\n merchant: PosMerchant,\n extra: Record<string, string | number | boolean | undefined | readonly string[]>,\n) {\n const chargeCents = start.amountCents + start.tipCents\n const methodTypes = extra['payment_method_types']\n const fee = posCardApplicationFeeCents({\n takeShareCents: Number(payment.takeFeeCents ?? 0),\n chargeCents,\n // A reader's card is in person; a typed card is an online card (AGL-4198).\n inPerson: Array.isArray(methodTypes) && methodTypes.includes('card_present'),\n ...(isDirect(merchant) ? { direct: true } : {}),\n })\n return {\n amount: chargeCents,\n currency: POS_CURRENCY,\n // A DESTINATION charge is made on the platform and transferred on; a\n // DIRECT one is made on the store's own account (the request's\n // `Stripe-Account`), whose money it already is, so nothing is transferred.\n ...(isDirect(merchant) ? {} : { 'transfer_data[destination]': merchant.accountId }),\n ...(fee > 0 ? { application_fee_amount: fee } : {}),\n 'metadata[kind]': 'pos',\n 'metadata[hostId]': start.hostId,\n 'metadata[orderId]': start.orderId,\n 'metadata[paymentId]': start.paymentId,\n 'metadata[tipCents]': String(start.tipCents),\n // Lets the Connect delivery of this intent's events through the webhook's\n // direct-sale gate (`connectEventIsForDirectSale`).\n ...(isDirect(merchant) ? { 'metadata[chargeModel]': 'direct' } : {}),\n ...extra,\n }\n}\n\n/**\n * Creates (or finds) the card-present PaymentIntent for one payment WITHOUT\n * choosing how the card is collected: reserves the amount in the ledger and\n * creates a manual-capture charge, keyed by the payment so a retry returns\n * the same intent. For a destination store it is a destination charge to the\n * merchant (settled on Aglyn's platform account, with no `on_behalf_of`, as\n * ToS §10.7 states); for a direct-charge store it is made ON the store's own\n * account (ToS v24 §10.2(a)) with Aglyn's take as the application fee.\n *\n * Two collectors use it. {@link startCardPresentPayment} pushes the intent\n * to a smart reader the site owns; a native companion app (AGL-3618)\n * collects it with the Stripe Terminal SDK (Tap to Pay, Bluetooth readers)\n * using the returned `clientSecret`. However the card is collected, the\n * payment is recorded by {@link refreshPosCardPayment}, keyed on the intent's\n * metadata, from the register's poll or the webhook alike.\n */\nexport async function createCardPresentIntent(\n start: CardStart & { readerId?: string; readerAccount?: string | null },\n): Promise<PosPaymentOutcome & { clientSecret?: string; paymentIntentId?: string }> {\n // Live card-present payments wait for Terminal to be switched on for the\n // platform (`STRIPE_TERMINAL_LIVE_ENABLED`); the hidden controls are not\n // the only gate.\n if (!posTerminalAvailable()) {\n return { ok: false, status: 409, error: 'Card readers are not available for this store yet.' }\n }\n const merchant = await posMerchantAccount(start.hostId, start.org)\n if (!merchant) return { ok: false, status: 409, error: 'Card payments not set up' }\n // A reader answers only to the account it is registered on, and the intent\n // is made on the store's: a reader registered on the platform cannot take\n // a direct store's card. Refused before anything is reserved.\n if (start.readerId && (start.readerAccount ?? null) !== (isDirect(merchant) ? merchant.accountId : null)) {\n return { ok: false, status: 409, error: POS_READER_ON_OTHER_ACCOUNT }\n }\n const reserved = await reserveCardPayment(start, 'card_present', {\n ...(start.readerId ? { readerId: start.readerId } : {}),\n ...directPaymentFields(merchant),\n })\n if (!reserved.ok || !reserved.payment) return reserved\n const payment = reserved.payment\n if (payment.status !== 'pending') return reserved\n // Keyed by the payment: a second call for the same payment replays the\n // intent Stripe already made rather than opening another.\n const intent = await posStripe('POST', 'payment_intents', {\n idempotencyKey: `pos-pi:${payment.id}`,\n ...onMerchant(merchant),\n params: paymentIntentParams(start, payment, merchant, {\n payment_method_types:\n POS_CURRENCY === 'usd' ? ['card_present'] : ['card_present', 'interac_present'],\n capture_method: 'manual',\n ...(start.readerId ? { 'metadata[readerId]': start.readerId } : {}),\n description: 'In-store purchase',\n }),\n })\n if (!intent.ok || !intent.body?.id) {\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(intent.body, 'The card payment could not be started.'),\n }))\n }\n const paymentIntentId = String(intent.body.id)\n const recorded = payment.paymentIntentId\n ? reserved\n : await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n paymentIntentId,\n livemode: Boolean(intent.body.livemode),\n }))\n return {\n ...recorded,\n paymentIntentId,\n ...(intent.body.client_secret ? { clientSecret: String(intent.body.client_secret) } : {}),\n }\n}\n\n/**\n * A smart-reader payment: the card-present intent from\n * {@link createCardPresentIntent}, pushed to a reader THIS site owns. The\n * register then polls {@link refreshPosCardPayment} until the reader answers;\n * webhooks land on the same function.\n */\nexport async function startCardPresentPayment(\n start: CardStart & { readerId: string; settings: PosRegisterSettings },\n): Promise<PosPaymentOutcome> {\n const reader = await ownedTerminalReader(start.hostId, start.readerId)\n if (!reader) return { ok: false, status: 404, error: 'That card reader is not on this site.' }\n await syncPosReaderTipping(start.hostId, start.settings).catch((error) =>\n console.error('[pos-terminal] tipping sync failed', error),\n )\n const created = await createCardPresentIntent({\n ...start,\n readerId: reader.id,\n readerAccount: posReaderAccount(reader),\n })\n if (!created.ok || !created.payment || !created.paymentIntentId) return created\n if (created.payment.status !== 'pending') return created\n return await sendToReader({\n hostId: start.hostId,\n orderId: start.orderId,\n paymentId: created.payment.id,\n readerId: reader.id,\n account: posPaymentAccount(created.payment),\n paymentIntentId: created.paymentIntentId,\n // A tip the customer already chose on the display is in the amount;\n // asking again on the reader would ask twice.\n skipTipping: !start.settings.tippingEnabled || start.tipCents > 0,\n attempt: 0,\n })\n}\n\n/** The site's recorded Location id on any account, or null before a reader was ever set up. */\nexport async function posTerminalRecordedLocationId(hostId: string): Promise<string | null> {\n const config = await terminalConfigRef(hostId).get()\n return String(config.get('stripeLocationId') ?? '') || null\n}\n\n/**\n * The site's Terminal Location id on the account the store sells on now, or\n * null before a reader was ever set up there. A Location made on another\n * account (the platform, for a store now on its own) is not this store's\n * Location any more: {@link ensurePosTerminalLocation} makes it again.\n */\nexport async function posTerminalLocationId(\n hostId: string,\n account?: string | null,\n): Promise<string | null> {\n const [config, current] = await Promise.all([\n terminalConfigRef(hostId).get(),\n account !== undefined ? Promise.resolve(account) : posTerminalAccount(hostId),\n ])\n return locationOnAccount(config, current)\n}\n\n/**\n * A Terminal SDK connection token scoped to the site's own Location, for a\n * native companion app's SDK (AGL-3618). Scoping it to the Location is what\n * keeps one store's app from discovering another store's readers: Stripe\n * only lets a location-scoped token connect to readers in that Location.\n * Null when the site has no Location yet, never an unscoped token.\n *\n * A direct-charge store's token is minted ON its own account (the\n * `Stripe-Account` header), as Stripe's Terminal-with-direct-charges guide\n * asks: the SDK then sees that account's Location and readers, collects the\n * intents this server made there, and creates any intent of its own (a card\n * taken offline) on that account too.\n */\nexport async function createPosTerminalConnectionToken(\n hostId: string,\n): Promise<{ secret: string; locationId: string } | null> {\n const account = await posTerminalAccount(hostId)\n const locationId = await posTerminalLocationId(hostId, account)\n if (!locationId) return null\n const token = await posStripe('POST', 'terminal/connection_tokens', {\n params: { location: locationId },\n ...onAccount(account),\n })\n if (!token.ok || !token.body?.secret) return null\n return { secret: String(token.body.secret), locationId }\n}\n\nasync function sendToReader(input: {\n hostId: string\n orderId: string\n paymentId: string\n readerId: string\n /** The account the payment (and so its reader) is on; null for the platform. */\n account: string | null\n paymentIntentId: string\n skipTipping: boolean\n attempt: number\n}): Promise<PosPaymentOutcome> {\n const processed = await posStripe(\n 'POST',\n `terminal/readers/${input.readerId}/process_payment_intent`,\n {\n idempotencyKey: `pos-process:${input.paymentId}:${input.attempt}`,\n ...onAccount(input.account),\n params: {\n payment_intent: input.paymentIntentId,\n 'process_config[enable_customer_cancellation]': true,\n ...(input.skipTipping ? { 'process_config[skip_tipping]': true } : {}),\n },\n },\n )\n if (!processed.ok) {\n return await patchCardPayment(input.hostId, input.orderId, input.paymentId, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(processed.body, 'The card reader could not start the payment.'),\n }))\n }\n return await patchCardPayment(input.hostId, input.orderId, input.paymentId, (current) => {\n if (!current.failureMessage) return null\n return withoutFailure(current)\n })\n}\n\n/**\n * Re-arms a declined or failed reader payment on the SAME PaymentIntent, as\n * Stripe asks (a new one per attempt risks a double charge).\n */\nexport async function retryCardPresentPayment(input: {\n hostId: string\n orderId: string\n paymentId: string\n settings: PosRegisterSettings\n}): Promise<PosPaymentOutcome> {\n const order = await readPosSale(input.hostId, input.orderId)\n if (!order || order.status !== 'pending') return NOT_A_SALE\n const payment = CommerceModel.orderPayments(order).find((entry) => entry.id === input.paymentId)\n if (!payment || payment.method !== 'card_present' || !payment.paymentIntentId || !payment.readerId) {\n return { ok: false, status: 404, error: 'Unknown payment' }\n }\n if (payment.status === 'succeeded') return { ok: true, order, payment, completed: false, changed: false }\n const reader = await ownedTerminalReader(input.hostId, payment.readerId)\n if (!reader) return { ok: false, status: 404, error: 'That card reader is not on this site.' }\n if (posReaderAccount(reader) !== posPaymentAccount(payment)) {\n return { ok: false, status: 409, error: POS_READER_ON_OTHER_ACCOUNT }\n }\n // Back to pending first, so the amount is reserved again before the reader\n // is asked; a sale paid meanwhile by another tender refuses here.\n const rearmed = await applyPosPayment({\n hostId: input.hostId,\n orderId: input.orderId,\n paymentId: input.paymentId,\n decide: ({ order: fresh, payments, existing }) => {\n if (!existing) return { kind: 'refuse', status: 404, error: 'Unknown payment' }\n if (existing.status === 'pending') return { kind: 'keep' }\n if (existing.status !== 'failed' && existing.status !== 'canceled') {\n return { kind: 'refuse', status: 409, error: 'This payment cannot be retried.' }\n }\n const tenderable = CommerceModel.posTenderableCents(\n Number(fresh.totals?.totalCents ?? 0),\n payments.filter((entry) => entry.id !== existing.id),\n )\n if (existing.amountCents > tenderable) {\n return { kind: 'refuse', status: 409, error: 'The balance changed. Start a new card payment.' }\n }\n return { kind: 'put', payment: { ...withoutFailure(existing), status: 'pending' } }\n },\n })\n if (!rearmed.ok) return rearmed\n const attempt = Date.now()\n return await sendToReader({\n hostId: input.hostId,\n orderId: input.orderId,\n paymentId: input.paymentId,\n readerId: reader.id,\n account: posPaymentAccount(payment),\n paymentIntentId: payment.paymentIntentId,\n skipTipping: !input.settings.tippingEnabled || Number(payment.tipCents ?? 0) > 0,\n attempt,\n })\n}\n\n/**\n * A typed card (card not present): a PaymentIntent the console confirms with\n * the Payment Element. No MOTO: the card is keyed into Stripe's own field and\n * goes through Stripe's normal online checks, 3-D Secure included.\n */\nexport async function startCardKeyedPayment(\n start: CardStart & { paymentMethodId?: string },\n): Promise<PosPaymentOutcome & { clientSecret?: string; stripeAccount?: string }> {\n const paymentMethodId = start.paymentMethodId ?? ''\n if (paymentMethodId && !isPaymentMethodId(paymentMethodId)) {\n return { ok: false, status: 400, error: 'The card could not be read. Enter it again.' }\n }\n const merchant = await posMerchantAccount(start.hostId, start.org)\n if (!merchant) return { ok: false, status: 409, error: 'Card payments not set up' }\n const reserved = await reserveCardPayment(start, 'card_keyed', directPaymentFields(merchant))\n if (!reserved.ok || !reserved.payment) return reserved\n const payment = reserved.payment\n if (payment.status !== 'pending') return reserved\n const intent = await posStripe('POST', 'payment_intents', {\n idempotencyKey: `pos-pi:${payment.id}`,\n ...onMerchant(merchant),\n params: paymentIntentParams(start, payment, merchant, {\n payment_method_types: ['card'],\n description: 'In-store purchase (typed card)',\n // 3-D Secure from the one seam every card payment shares (AGL-3360).\n ...cardAuthenticationParams('one-time'),\n }),\n })\n if (!intent.ok || !intent.body?.id || !intent.body?.client_secret) {\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(intent.body, 'The card payment could not be started.'),\n }))\n }\n const updated = payment.paymentIntentId\n ? reserved\n : await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n paymentIntentId: String(intent.body.id),\n livemode: Boolean(intent.body.livemode),\n }))\n if (!paymentMethodId) {\n // A direct store's intent lives on its own account, so the console's\n // Payment Element must load Stripe for that account to confirm it.\n return {\n ...updated,\n clientSecret: String(intent.body.client_secret),\n ...(isDirect(merchant) ? { stripeAccount: merchant.accountId } : {}),\n }\n }\n return await confirmKeyedCard(\n start,\n payment.id,\n String(intent.body.id),\n paymentMethodId,\n isDirect(merchant) ? merchant.accountId : null,\n )\n}\n\n/** A PaymentMethod id as Stripe mints them; anything else never reaches Stripe. */\nfunction isPaymentMethodId(value: string): boolean {\n return /^pm_[A-Za-z0-9]{8,64}$/.test(value)\n}\n\n/** What a typed card that needs the cardholder's bank to approve it says. */\nexport const KEYED_CARD_NEEDS_AUTHENTICATION =\n '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.'\n\n/**\n * A card typed into the register's own card fields (AGL-3848): the device\n * sent the number to Stripe alone, which answered with a PaymentMethod, and\n * hands this route only its id. The server confirms the intent with it, with\n * the platform's secret key, and records the payment from Stripe's answer as\n * every card payment is. The device made that PaymentMethod with the\n * PLATFORM's publishable key, so for a direct-charge store's intent it is\n * first cloned onto the store's account (Stripe's PaymentMethod cloning for\n * direct charges) and the clone confirms it. A card whose bank asks for the cardholder's approval\n * (3-D Secure) cannot be approved at the register, so that intent is released\n * and the payment fails with words that point at Card (QR).\n */\nasync function confirmKeyedCard(\n start: CardStart,\n paymentId: string,\n intentId: string,\n paymentMethodId: string,\n account: string | null,\n): Promise<PosPaymentOutcome> {\n const input = { hostId: start.hostId, orderId: start.orderId, paymentId }\n let method = paymentMethodId\n if (account) {\n const cloned = await posStripe('POST', 'payment_methods', {\n idempotencyKey: `pos-keyed-clone:${account}:${paymentMethodId}`,\n stripeAccount: account,\n params: { payment_method: paymentMethodId },\n })\n if (!cloned.ok || !cloned.body?.id) {\n const message = posStripeErrorMessage(cloned.body, 'The card was not accepted.')\n await posStripe('POST', `payment_intents/${intentId}/cancel`, {\n idempotencyKey: `pos-cancel:${intentId}`,\n stripeAccount: account,\n })\n return await patchCardPayment(start.hostId, start.orderId, paymentId, (current) =>\n current.status === 'pending' ? { ...current, status: 'failed', failureMessage: message } : null,\n )\n }\n method = String(cloned.body.id)\n }\n const confirmed = await posStripe('POST', `payment_intents/${intentId}/confirm`, {\n idempotencyKey: `pos-keyed-confirm:${intentId}:${paymentMethodId}`,\n params: { payment_method: method },\n ...onAccount(account),\n })\n const status = String(confirmed.body?.status ?? confirmed.body?.error?.payment_intent?.status ?? '')\n if (status === 'requires_action') {\n await posStripe('POST', `payment_intents/${intentId}/cancel`, {\n idempotencyKey: `pos-cancel:${intentId}`,\n ...onAccount(account),\n })\n return await patchCardPayment(start.hostId, start.orderId, paymentId, (current) =>\n current.status === 'pending'\n ? { ...current, status: 'failed', failureMessage: KEYED_CARD_NEEDS_AUTHENTICATION }\n : null,\n )\n }\n if (!confirmed.ok && confirmed.body?.error && !confirmed.body.error.payment_intent) {\n // Refused before the card was tried (a stale method, a bad request): say so, leave nothing pending.\n const message = posStripeErrorMessage(confirmed.body, 'The card was not accepted.')\n await posStripe('POST', `payment_intents/${intentId}/cancel`, {\n idempotencyKey: `pos-cancel:${intentId}`,\n ...onAccount(account),\n })\n return await patchCardPayment(start.hostId, start.orderId, paymentId, (current) =>\n current.status === 'pending' ? { ...current, status: 'failed', failureMessage: message } : null,\n )\n }\n // Approved, declined or still processing: Stripe's own read of the intent decides.\n return await refreshPosCardPayment(input)\n}\n\n/**\n * The customer pays on their own phone from a QR code: a Stripe payment page\n * for this payment's amount (and tip, as its own line). Settled by\n * `checkout.session.completed` or by the register's poll.\n */\nexport async function startCardLinkPayment(\n start: CardStart & { returnUrl: string },\n): Promise<PosPaymentOutcome> {\n const merchant = await posMerchantAccount(start.hostId, start.org)\n if (!merchant) return { ok: false, status: 409, error: 'Card payments not set up' }\n const reserved = await reserveCardPayment(start, 'card_link', directPaymentFields(merchant))\n if (!reserved.ok || !reserved.payment) return reserved\n const payment = reserved.payment\n if (payment.checkoutSessionId || payment.status !== 'pending') return reserved\n const fee = posCardApplicationFeeCents({\n takeShareCents: Number(payment.takeFeeCents ?? 0),\n chargeCents: start.amountCents + start.tipCents,\n // A card link is paid online, on the customer's own phone (AGL-4198).\n inPerson: false,\n ...(isDirect(merchant) ? { direct: true } : {}),\n })\n const session = await posStripe('POST', 'checkout/sessions', {\n idempotencyKey: `pos-link:${payment.id}`,\n ...onMerchant(merchant),\n params: {\n mode: 'payment',\n ...checkoutSessionCardAuthenticationParams('payment'),\n 'payment_method_types': ['card'],\n 'line_items[0][quantity]': 1,\n 'line_items[0][price_data][currency]': POS_CURRENCY,\n 'line_items[0][price_data][unit_amount]': start.amountCents,\n 'line_items[0][price_data][product_data][name]': 'In-store purchase',\n ...(start.tipCents > 0\n ? {\n 'line_items[1][quantity]': 1,\n 'line_items[1][price_data][currency]': POS_CURRENCY,\n 'line_items[1][price_data][unit_amount]': start.tipCents,\n 'line_items[1][price_data][product_data][name]': 'Tip',\n }\n : {}),\n ...(isDirect(merchant) ? {} : { 'payment_intent_data[transfer_data][destination]': merchant.accountId }),\n ...(fee > 0 ? { 'payment_intent_data[application_fee_amount]': fee } : {}),\n ...(isDirect(merchant) ? { 'payment_intent_data[metadata][chargeModel]': 'direct' } : {}),\n 'payment_intent_data[metadata][kind]': 'pos',\n 'payment_intent_data[metadata][hostId]': start.hostId,\n 'payment_intent_data[metadata][orderId]': start.orderId,\n 'payment_intent_data[metadata][paymentId]': payment.id,\n 'payment_intent_data[metadata][tipCents]': String(start.tipCents),\n success_url: `${start.returnUrl}?paid=1`,\n cancel_url: `${start.returnUrl}?paid=0`,\n 'metadata[type]': 'pos-payment',\n 'metadata[hostId]': start.hostId,\n 'metadata[orderId]': start.orderId,\n 'metadata[paymentId]': payment.id,\n ...(isDirect(merchant) ? { 'metadata[chargeModel]': 'direct' } : {}),\n },\n })\n if (!session.ok || !session.body?.url) {\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n status: 'failed',\n failureMessage: posStripeErrorMessage(session.body, 'The payment page could not be created.'),\n }))\n }\n return await patchCardPayment(start.hostId, start.orderId, payment.id, (current) => ({\n ...current,\n checkoutSessionId: String(session.body.id),\n checkoutUrl: String(session.body.url),\n livemode: Boolean(session.body.livemode),\n }))\n}\n\n/*==========================================\n * SETTLING A CARD PAYMENT.\n *=========================================*/\n\n/** The card's brand and last four, off the charge Stripe made. */\nfunction cardDetailsOf(intent: any): { cardBrand?: string; last4?: string } {\n const charge = typeof intent?.latest_charge === 'object' ? intent.latest_charge : null\n const details =\n charge?.payment_method_details?.card_present ??\n charge?.payment_method_details?.interac_present ??\n charge?.payment_method_details?.card ??\n null\n return {\n ...(details?.brand ? { cardBrand: String(details.brand) } : {}),\n ...(details?.last4 ? { last4: String(details.last4) } : {}),\n }\n}\n\n/** The tip on an intent: what the display chose plus what the reader added. */\nexport function posIntentTipCents(intent: any): number {\n const preset = Math.max(0, Math.round(Number(intent?.metadata?.tipCents ?? 0)) || 0)\n const onReader = Math.max(0, Math.round(Number(intent?.amount_details?.tip?.amount ?? 0)) || 0)\n return preset + onReader\n}\n\n/**\n * The fee a register card charge is captured with: the payment's share of the\n * take (fixed at reservation, the sale's share and never the tip's) plus the\n * card processing cost on the whole amount, tip included.\n */\nexport function posCaptureFeeCents(payment: CommerceModel.OrderPayment, intent: any): number {\n const methodTypes: unknown = intent?.payment_method_types\n return posCardApplicationFeeCents({\n takeShareCents: Number(payment.takeFeeCents ?? 0),\n chargeCents: Math.max(0, Math.round(Number(intent?.amount ?? 0))),\n // The intent says how it was paid: a reader's card is in person (AGL-4198).\n inPerson: !Array.isArray(methodTypes) || methodTypes.includes('card_present'),\n // On a direct store's own account Stripe bills the store its card fee,\n // so the fee is the take alone (a tip never adds to it).\n ...(payment.chargeModel === 'direct' ? { direct: true } : {}),\n })\n}\n\n/**\n * Brings one card payment up to date with Stripe, from a webhook or the\n * register's poll alike: captures an authorized reader payment with its final\n * fee, records a success, a decline or a cancellation. Idempotent: the\n * capture is keyed by the intent, and the ledger change is a no-op when the\n * payment already says what Stripe says.\n */\nexport async function refreshPosCardPayment(input: {\n hostId: string\n orderId: string\n paymentId: string\n}): Promise<PosPaymentOutcome> {\n const order = await readPosSale(input.hostId, input.orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n const payment = CommerceModel.orderPayments(order).find((entry) => entry.id === input.paymentId)\n if (!payment) return { ok: false, status: 404, error: 'Unknown payment' }\n if (!CommerceModel.isCardPaymentMethod(payment.method)) {\n return { ok: true, order, payment, completed: false, changed: false }\n }\n // Every object of this payment lives where it was made (null: the platform).\n const on = onAccount(posPaymentAccount(payment))\n let paymentIntentId = payment.paymentIntentId ?? ''\n if (!paymentIntentId && payment.checkoutSessionId) {\n const session = await posStripe('GET', `checkout/sessions/${payment.checkoutSessionId}`, on)\n if (session.ok && session.body?.status === 'expired' && payment.status === 'pending') {\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' ? { ...current, status: 'canceled' } : null,\n )\n }\n paymentIntentId = String(session.body?.payment_intent ?? '')\n }\n if (!paymentIntentId) return { ok: true, order, payment, completed: false, changed: false }\n let intent = (\n await posStripe('GET', `payment_intents/${paymentIntentId}`, {\n params: { 'expand[]': 'latest_charge' },\n ...on,\n })\n ).body\n if (!intent?.id) return { ok: true, order, payment, completed: false, changed: false }\n if (intent.metadata?.hostId !== input.hostId || intent.metadata?.paymentId !== payment.id) {\n console.error('[pos-terminal] intent does not belong to this payment', paymentIntentId)\n return { ok: false, status: 409, error: 'This payment does not match its card charge.' }\n }\n if (intent.status === 'requires_capture') {\n if (order.status !== 'pending' && payment.status !== 'pending') {\n // Nothing to capture into: the sale is gone. Release the hold.\n await posStripe('POST', `payment_intents/${intent.id}/cancel`, {\n idempotencyKey: `pos-release:${intent.id}`,\n ...on,\n })\n return { ok: true, order, payment, completed: false, changed: false }\n }\n const fee = posCaptureFeeCents(payment, intent)\n const captured = await posStripe('POST', `payment_intents/${intent.id}/capture`, {\n idempotencyKey: `pos-capture:${intent.id}`,\n params: {\n ...(fee > 0 ? { application_fee_amount: fee } : {}),\n 'expand[]': 'latest_charge',\n },\n ...on,\n })\n if (captured.ok && captured.body?.id) intent = captured.body\n else {\n console.error('[pos-terminal] capture failed', intent.id, captured.body?.error)\n return { ok: true, order, payment, completed: false, changed: false }\n }\n }\n if (intent.status === 'succeeded') {\n const tipCents = posIntentTipCents(intent)\n const amountCents = Math.max(0, Math.round(Number(intent.amount ?? 0))) - tipCents\n return await patchCardPayment(\n input.hostId,\n input.orderId,\n payment.id,\n (current) => {\n if (current.status === 'succeeded' && current.paymentIntentId === intent.id) return null\n return {\n ...withoutFailure(current),\n status: 'succeeded',\n settledAtMs: Date.now(),\n paymentIntentId: String(intent.id),\n // What the charge actually put toward the sale. Equal to the\n // reserved amount; restated from Stripe so the ledger records the\n // money that moved rather than the money that was asked for.\n amountCents: amountCents > 0 ? amountCents : current.amountCents,\n ...(tipCents > 0 ? { tipCents } : {}),\n feeCents: Math.max(0, Math.round(Number(intent.application_fee_amount ?? 0))),\n livemode: Boolean(intent.livemode),\n ...cardDetailsOf(intent),\n }\n },\n )\n }\n if (intent.status === 'canceled') {\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' || current.status === 'failed'\n ? { ...current, status: 'canceled' }\n : null,\n )\n }\n if (intent.status === 'requires_payment_method' && intent.last_payment_error) {\n const message = String(intent.last_payment_error?.message ?? 'The card was declined.')\n // The declined charge names the card, so the sale and the declined card's receipt can say which card it was.\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending'\n ? { ...current, status: 'failed', failureMessage: message, ...cardDetailsOf(intent) }\n : null,\n )\n }\n // Still waiting on the customer. A reader action that already failed (a\n // card removed, a cancel on the reader) says so on the reader, not the\n // intent, so ask the reader too.\n if (payment.method === 'card_present' && payment.readerId && payment.status === 'pending') {\n const reader = await refreshPosReaderStatus(input.hostId, payment.readerId, posPaymentAccount(payment))\n const action = reader?.action\n if (\n action?.type === 'process_payment_intent' &&\n action?.process_payment_intent?.payment_intent === intent.id &&\n action?.status === 'failed'\n ) {\n const message = String(action.failure_message ?? 'The reader could not take the card.')\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' ? { ...current, status: 'failed', failureMessage: message } : null,\n )\n }\n }\n const fresh = await readPosSale(input.hostId, input.orderId)\n return {\n ok: true,\n order: fresh ?? order,\n payment:\n CommerceModel.orderPayments(fresh ?? order).find((entry) => entry.id === payment.id) ?? payment,\n completed: false,\n changed: false,\n }\n}\n\n/**\n * Stops a card payment that has not been paid: clears the reader, cancels the\n * intent, expires the payment page. A charge that already went through is\n * left alone and recorded as paid, never cancelled under the customer.\n */\nexport async function cancelPosCardPayment(input: {\n hostId: string\n orderId: string\n paymentId: string\n}): Promise<PosPaymentOutcome> {\n const refreshed = await refreshPosCardPayment(input)\n if (!refreshed.ok || !refreshed.payment) return refreshed\n const payment = refreshed.payment\n if (payment.status === 'succeeded' || payment.status === 'canceled') return refreshed\n const on = onAccount(posPaymentAccount(payment))\n if (payment.method === 'card_present' && payment.readerId) {\n const cleared = await posStripe('POST', `terminal/readers/${payment.readerId}/cancel_action`, on)\n if (!cleared.ok && cleared.body?.error?.code === 'terminal_reader_busy') {\n return {\n ok: false,\n status: 409,\n error: 'The customer is mid-payment on the reader. Wait for it to finish.',\n }\n }\n }\n if (payment.paymentIntentId) {\n await posStripe('POST', `payment_intents/${payment.paymentIntentId}/cancel`, {\n idempotencyKey: `pos-cancel:${payment.paymentIntentId}`,\n ...on,\n })\n }\n if (payment.checkoutSessionId) {\n await posStripe('POST', `checkout/sessions/${payment.checkoutSessionId}/expire`, {\n idempotencyKey: `pos-expire:${payment.checkoutSessionId}`,\n ...on,\n })\n }\n // Re-read: a payment that completed in the gap is recorded as paid.\n const settled = await refreshPosCardPayment(input)\n if (settled.ok && settled.payment?.status === 'succeeded') return settled\n return await patchCardPayment(input.hostId, input.orderId, payment.id, (current) =>\n current.status === 'pending' || current.status === 'failed'\n ? { ...current, status: 'canceled' }\n : null,\n )\n}\n\n/**\n * TEST MODE ONLY: Stripe's simulated reader is \"tapped\" with a test card.\n * Refused outright on a live key, whatever the request says.\n */\nexport async function simulatePosReaderTap(input: {\n hostId: string\n orderId: string\n paymentId: string\n /** `4000000000000002` declines; anything else Stripe's default approves. */\n cardNumber?: string\n}): Promise<PosPaymentOutcome> {\n if (!posStripeTestMode()) return { ok: false, status: 403, error: 'Only in test mode' }\n const order = await readPosSale(input.hostId, input.orderId)\n if (!order) return { ok: false, status: 404, error: 'Unknown sale' }\n const payment = CommerceModel.orderPayments(order).find((entry) => entry.id === input.paymentId)\n if (!payment?.readerId || payment.method !== 'card_present') {\n return { ok: false, status: 404, error: 'Unknown payment' }\n }\n const reader = await ownedTerminalReader(input.hostId, payment.readerId)\n if (!reader) return { ok: false, status: 404, error: 'That card reader is not on this site.' }\n const presented = await posStripe(\n 'POST',\n `test_helpers/terminal/readers/${reader.id}/present_payment_method`,\n {\n ...onAccount(posReaderAccount(reader)),\n params: {\n type: 'card_present',\n ...(input.cardNumber && /^[0-9]{12,19}$/.test(input.cardNumber)\n ? { 'card_present[number]': input.cardNumber }\n : {}),\n },\n },\n )\n if (!presented.ok) {\n return {\n ok: false,\n status: 502,\n error: posStripeErrorMessage(presented.body, 'The simulated tap failed.'),\n }\n }\n return await refreshPosCardPayment(input)\n}\n\n/*==========================================\n * WEBHOOKS (the small branch `billing-webhook.ts` calls).\n *=========================================*/\n\n/** Where a Stripe object says a register payment lives, or null. */\nfunction posPaymentRef(\n metadata: Record<string, unknown> | undefined,\n): { hostId: string; orderId: string; paymentId: string } | null {\n const hostId = String(metadata?.['hostId'] ?? '')\n const orderId = String(metadata?.['orderId'] ?? '')\n const paymentId = String(metadata?.['paymentId'] ?? '')\n if (!hostId || !orderId || !paymentId) return null\n return { hostId, orderId, paymentId }\n}\n\n/**\n * The register's Stripe events: a reader finished or failed an action, a\n * register PaymentIntent was authorized, paid, declined or cancelled, or a\n * register QR page was paid or expired. Each resolves to ONE payment and is\n * answered by re-reading Stripe through {@link refreshPosCardPayment}, never\n * by trusting the event's own copy (whose API version predates the tip\n * fields). Returns the site when the event was the register's, so the\n * dispatcher can count it as claimed; null for every other event.\n *\n * `account` is the connected account a Connect-delivered event came from\n * (`connectEventAccount`): a direct-charge store's reader and intents live\n * there, so the reader event's intent is read there. The settlement itself\n * reads the account the payment recorded, never the event's word.\n */\nexport async function handlePosStripeEvent(input: {\n type: string\n object: any\n account?: string | null\n}): Promise<{ hostId: string } | null> {\n const { type, object } = input\n let ref: { hostId: string; orderId: string; paymentId: string } | null = null\n if (type === 'terminal.reader.action_succeeded' || type === 'terminal.reader.action_failed') {\n const intentId = String(object?.action?.process_payment_intent?.payment_intent ?? '')\n if (object?.action?.type !== 'process_payment_intent' || !intentId) return null\n const intent = await posStripe('GET', `payment_intents/${intentId}`, onAccount(input.account ?? null))\n if (!intent.ok || intent.body?.metadata?.kind !== 'pos') return null\n ref = posPaymentRef(intent.body.metadata)\n } else if (\n type === 'payment_intent.amount_capturable_updated' ||\n type === 'payment_intent.succeeded' ||\n type === 'payment_intent.payment_failed' ||\n type === 'payment_intent.canceled'\n ) {\n if (object?.metadata?.kind !== 'pos') return null\n ref = posPaymentRef(object.metadata)\n } else if (\n (type === 'checkout.session.completed' || type === 'checkout.session.expired') &&\n object?.metadata?.type === 'pos-payment'\n ) {\n ref = posPaymentRef(object.metadata)\n } else {\n return null\n }\n if (!ref) return null\n // A reader can be re-registered by nobody else, but an event is only a\n // claim: the intent's own metadata must name a reader this site owns.\n await refreshPosCardPayment(ref).catch((error) => {\n console.error('[pos-terminal] webhook settle failed', ref, error)\n // Rethrown so the delivery is retried: a lost settlement is a sale the\n // register cannot complete without its poll.\n throw error\n })\n return { hostId: ref.hostId }\n}\n\nexport type { PosLiftedOrder }\n\n/*==========================================\n * CARDS TAKEN OFFLINE ON THE APP'S OWN READER (AGL-4039).\n *\n * The Aglyn POS app creates these PaymentIntents itself (Stripe stores the\n * card on the device and forwards it once a connection returns), so the\n * server meets them only at the sale's sync: it reads the intent, checks it\n * is the sale's, and captures it with the platform fee, the same capture an\n * online reader payment gets after its tip is known.\n *=========================================*/\n\n/** A PaymentIntent the offline sync reads, reduced to what it checks. */\nexport interface PosOfflineCardIntent {\n id: string\n status: string\n amount: number\n currency: string\n metadata: Record<string, string>\n destination: string\n applicationFeeCents: number\n livemode: boolean\n brand?: string\n last4?: string\n failureMessage?: string\n}\n\nfunction offlineCardIntent(body: any): PosOfflineCardIntent {\n const charge = body?.latest_charge && typeof body.latest_charge === 'object' ? body.latest_charge : null\n const present = charge?.payment_method_details?.card_present ?? {}\n const error = body?.last_payment_error ?? null\n return {\n id: String(body?.id ?? ''),\n status: String(body?.status ?? ''),\n amount: Number(body?.amount ?? 0),\n currency: String(body?.currency ?? ''),\n metadata: (body?.metadata ?? {}) as Record<string, string>,\n destination: String(body?.transfer_data?.destination ?? ''),\n applicationFeeCents: Number(body?.application_fee_amount ?? 0),\n livemode: Boolean(body?.livemode),\n ...(present.brand ? { brand: String(present.brand) } : {}),\n ...(present.last4 ? { last4: String(present.last4) } : {}),\n ...(error ? { failureMessage: String(error.message ?? error.decline_code ?? 'The card was declined.') } : {}),\n }\n}\n\n/**\n * Reads one offline card's PaymentIntent, with its charge's card details, on\n * `account` (a direct-charge store's own, where its app's SDK made it) or\n * the platform.\n */\nexport async function retrievePosOfflineCardIntent(\n paymentIntentId: string,\n account: string | null = null,\n): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string; status: number }> {\n const fetched = await posStripe('GET', `payment_intents/${encodeURIComponent(paymentIntentId)}`, {\n params: { expand: ['latest_charge'] },\n ...onAccount(account),\n })\n // The status tells the sync whether Stripe definitely has no such intent on that account (AGL-4219).\n if (!fetched.ok) {\n return {\n ok: false,\n status: fetched.status,\n error: posStripeErrorMessage(fetched.body, 'The card payment could not be read.'),\n }\n }\n return { ok: true, intent: offlineCardIntent(fetched.body) }\n}\n\n/**\n * Captures one authorized offline card with the platform's fee, on `account`\n * (a direct-charge store's own, where its app's SDK made it, AGL-4219) or the\n * platform; a repeat finds the first capture. Stripe takes the application\n * fee at capture on a direct charge too, from the store's account to the\n * platform, which is how an online direct reader payment is captured.\n */\nexport async function capturePosOfflineCardIntent(\n paymentIntentId: string,\n applicationFeeCents: number,\n idempotencyKey: string,\n account: string | null = null,\n): Promise<{ ok: true; intent: PosOfflineCardIntent } | { ok: false; error: string; status: number }> {\n const captured = await posStripe('POST', `payment_intents/${encodeURIComponent(paymentIntentId)}/capture`, {\n idempotencyKey,\n ...onAccount(account),\n params: {\n ...(applicationFeeCents > 0 ? { application_fee_amount: applicationFeeCents } : {}),\n expand: ['latest_charge'],\n },\n })\n // The status tells the sync whether this attempt definitely failed (AGL-4039).\n if (!captured.ok) {\n return {\n ok: false,\n status: captured.status,\n error: posStripeErrorMessage(captured.body, 'The card payment could not be captured.'),\n }\n }\n return { ok: true, intent: offlineCardIntent(captured.body) }\n}\n\n/**\n * Cancels one offline card's authorization on `account` (a direct-charge\n * store's own, or another the device recorded) or the platform, so the\n * customer's hold is released (AGL-4219). The sync asks only for an intent\n * it read as `requires_capture`; Stripe refuses to cancel a captured one.\n */\nexport async function cancelPosOfflineCardIntent(\n paymentIntentId: string,\n account: string | null,\n idempotencyKey: string,\n): Promise<{ ok: true } | { ok: false; error: string; status: number }> {\n const cancelled = await posStripe('POST', `payment_intents/${encodeURIComponent(paymentIntentId)}/cancel`, {\n idempotencyKey,\n ...onAccount(account),\n params: { cancellation_reason: 'abandoned' },\n })\n if (!cancelled.ok) {\n return {\n ok: false,\n status: cancelled.status,\n error: posStripeErrorMessage(cancelled.body, 'The card payment could not be cancelled.'),\n }\n }\n return { ok: true }\n}\n\n/**\n * Turns Stripe's offline mode on for the site's readers, on the site's ONE\n * Terminal Configuration through {@link savePosReaderConfiguration}, like\n * reader tipping and the start-up screen (AGL-4048). That helper claims a\n * first create in a transaction, so offline mode racing tipping or the\n * start-up screen to the first write lands on one configuration with both\n * settings, never two configurations of which only one is assigned; and it\n * finishes an assignment a previous first write left owing.\n *\n * Done once per configuration: `offlineConfigurationId` records which one\n * carries `offline[enabled]`, so a site whose configuration was replaced or\n * is still owed its assignment is set again rather than answered from a flag\n * that no longer describes what its readers use. A reader picks the setting\n * up the next time it connects online. False when Stripe refused it.\n */\nexport async function ensurePosOfflineCardConfiguration(hostId: string): Promise<boolean> {\n const ref = terminalConfigRef(hostId)\n const config = await ref.get()\n if (!config.get('stripeLocationId')) return false\n const configurationId = String(config.get('stripeConfigurationId') ?? '')\n if (\n config.get('offlineEnabled') === true &&\n configurationId &&\n config.get('offlineConfigurationId') === configurationId &&\n config.get('stripeConfigurationAssigned') !== false\n ) {\n return true\n }\n const saved = await savePosReaderConfiguration(hostId, { 'offline[enabled]': true }, 'offline')\n if ('error' in saved) {\n console.error('[pos-terminal] offline configuration failed', hostId, saved.error)\n return false\n }\n await ref.set({ offlineEnabled: true, offlineConfigurationId: saved.configurationId }, { merge: true })\n return true\n}\n"],"names":["createHash","firebaseAdmin","merchantAccountIsReady","sellerPaymentAccount","cardAuthenticationParams","checkoutSessionCardAuthenticationParams","CommerceModel","POS_CURRENCY","posCardApplicationFeeCents","posStripe","posStripeErrorMessage","posStripeTestMode","posTerminalAvailable","applyPosPayment","readPosSale","NOT_A_SALE","ok","status","error","withoutFailure","payment","next","failureMessage","posMerchantAccount","hostId","org","seller","accountId","chargesEnabled","accountLivemode","subject","chargeModel","posTerminalAccount","recordedAccount","value","id","trim","posPaymentAccount","stripeAccountId","posReaderAccount","reader","stripeAccount","POS_READER_ON_OTHER_ACCOUNT","locationOnAccount","config","account","locationId","String","get","LOCATION_BOUND_FIELDS","terminalConfigRef","app","firestore","collection","doc","readerRef","readerId","isTerminalReaderId","test","ownedTerminalReader","snapshot","exists","data","posTerminalAddressProblem","address","line1","city","postalCode","country","posTerminalLocationKey","displayName","fingerprint","update","JSON","stringify","slice","line2","state","digest","locationAddressOf","location","undefined","text","postal_code","ensurePosTerminalLocation","options","existing","created","ref","known","knownAccount","addressGiven","previous","body","problem","locationKey","idempotencyKey","params","display_name","orgId","replaced","Boolean","set","stripeLocationId","livemode","createdAtMs","Date","now","stripeLocationAccount","FieldValue","delete","Object","fromEntries","map","field","replacedLocation","atMs","merge","saved","savePosReaderConfiguration","console","cellularConfigurationId","configurationId","then","cellular","syncPosCellularReaders","catch","splash","applyPosReaderSplash","posReaderTippingKey","settings","tippingEnabled","tipPercentages","join","createKey","onAccount","updated","code","assigned","assignPosReaderConfiguration","createdId","winner","runTransaction","transaction","fresh","stripeConfigurationId","stripeConfigurationAssigned","configuration_overrides","syncPosReaderTipping","key","percentages","tippingKey","refreshPosReaderStatus","fetched","lastSeenAtMs","action","reserveCardPayment","start","method","extra","orderId","paymentId","decide","order","payments","kind","total","Number","totals","totalCents","tenderable","posTenderableCents","amountCents","toFixed","tipProblem","posTipProblem","tipCents","takeFeeCents","posTakeShareCents","posTakeFeeCents","cashierId","patchCardPayment","patch","event","isDirect","merchant","onMerchant","directPaymentFields","paymentIntentParams","chargeCents","methodTypes","fee","takeShareCents","inPerson","Array","isArray","includes","direct","amount","currency","application_fee_amount","createCardPresentIntent","intent","readerAccount","reserved","payment_method_types","capture_method","description","current","paymentIntentId","recorded","client_secret","clientSecret","startCardPresentPayment","sendToReader","skipTipping","attempt","posTerminalRecordedLocationId","posTerminalLocationId","Promise","all","resolve","createPosTerminalConnectionToken","token","secret","input","processed","payment_intent","retryCardPresentPayment","orderPayments","find","entry","completed","changed","rearmed","filter","startCardKeyedPayment","paymentMethodId","isPaymentMethodId","confirmKeyedCard","KEYED_CARD_NEEDS_AUTHENTICATION","intentId","confirmed","cloned","payment_method","message","refreshPosCardPayment","startCardLinkPayment","session","checkoutSessionId","mode","success_url","returnUrl","cancel_url","url","checkoutUrl","cardDetailsOf","charge","latest_charge","details","payment_method_details","card_present","interac_present","card","brand","cardBrand","last4","posIntentTipCents","preset","Math","max","round","metadata","onReader","amount_details","tip","posCaptureFeeCents","isCardPaymentMethod","on","captured","settledAtMs","feeCents","last_payment_error","type","process_payment_intent","failure_message","cancelPosCardPayment","settled","refreshed","cleared","simulatePosReaderTap","presented","cardNumber","posPaymentRef","handlePosStripeEvent","object","offlineCardIntent","present","destination","transfer_data","applicationFeeCents","decline_code","retrievePosOfflineCardIntent","encodeURIComponent","expand","capturePosOfflineCardIntent","cancelPosOfflineCardIntent","cancelled","cancellation_reason","ensurePosOfflineCardConfiguration","offlineEnabled","offlineConfigurationId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,QAAQ,cAAa;AACxC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SACEC,sBAAsB,QAEjB,mDAAkD;AACzD,SAASC,oBAAoB,QAAQ,yDAAwD;AAC7F,SACEC,wBAAwB,EACxBC,uCAAuC,QAClC,6DAA4D;AACnE,YAAYC,mBAAmB,oBAAU;AAEzC,SACEC,YAAY,EACZC,0BAA0B,EAC1BC,SAAS,EACTC,qBAAqB,EACrBC,iBAAiB,EACjBC,oBAAoB,QACf,kBAAc;AACrB,SAASC,eAAe,EAAEC,WAAW,QAAqD,gBAAY;AAEtG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA8C2C,GAE3C,MAAMC,aAAa;IAAEC,IAAI;IAAgBC,QAAQ;IAAKC,OAAO;AAA8B;AAqB3F;;;CAGC,GACD,SAASC,eAAeC,OAAmC;IACzD,MAAMC,OAAO,aAAKD;IAClB,OAAOC,KAAKC,cAAc;IAC1B,OAAOD;AACT;AAQA;;;;;CAKC,GACD,OAAO,eAAeE,mBACpBC,MAAc,EACdC,GAA+B;IAE/B,MAAMC,SAAS,MAAMvB,qBAAqBqB,QAAQC;IAClD,IAAI,CAACC,QAAQ,OAAO;IACpB,IACE,CAACxB,uBACC;QACEyB,WAAWD,OAAOC,SAAS;QAC3BC,gBAAgBF,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