@aglyn/plugins-commerce 1.21.0 → 1.22.0
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 +16 -16
- package/src/lib/components/cart-fulfillment.js +19 -8
- package/src/lib/components/cart-fulfillment.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +28 -9
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +13 -4
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/local-delivery-settings-card.component.js +13 -4
- package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +13 -4
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +13 -4
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.js +13 -4
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +13 -4
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/return-settings-card.component.js +13 -4
- package/src/lib/components/console/return-settings-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +13 -4
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +13 -4
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +13 -4
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/console/tax-settings-card.component.js +13 -4
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/model/commerce-pos-offline.d.ts +21 -3
- package/src/lib/model/commerce-pos-offline.js +17 -5
- package/src/lib/model/commerce-pos-offline.js.map +1 -1
- package/src/lib/server/pos-offline-card-order.d.ts +2 -0
- package/src/lib/server/pos-offline-card-order.js +6 -2
- package/src/lib/server/pos-offline-card-order.js.map +1 -1
- package/src/lib/server/pos-offline-card-reconcile.d.ts +5 -1
- package/src/lib/server/pos-offline-card-reconcile.js +42 -10
- package/src/lib/server/pos-offline-card-reconcile.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +48 -6
- package/src/lib/server/pos-offline-sync.js +142 -31
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +11 -0
- package/src/lib/server/pos-stripe.js +14 -0
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +21 -1
- package/src/lib/server/pos-terminal.js +39 -5
- package/src/lib/server/pos-terminal.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/tax-settings-card.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 * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n isSeedChecking,\n seedCheckingText,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\n\nexport interface TaxSettingsCardProps {\n hostId: string\n}\n\n/**\n * Tax settings (AGL-285): manual per-region rates (most-specific wins)\n * or Stripe Tax automatic calculation, stored on\n * `hosts/{hostId}/settings/store` under `tax`. The legacy quick-buy\n * checkout taxes by the store origin; Checkout v2 taxes by destination.\n */\nexport function TaxSettingsCard(props: TaxSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? store?.tax ?? {mode: 'manual'}` and\n * the save writes `{tax: current}`, so `merge: true` protects the doc's\n * other maps and nothing inside this one. `mode` is the field that costs\n * money: a cached seed flipping `stripe` back to `manual` stops automatic\n * tax calculation — `resolveTaxRate` returns null in stripe mode — and\n * the store under-collects with nothing anywhere reporting it.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n // What was typed, kept as edits over the stored settings, and Save held\n // until the server has confirmed them (AGL-4047).\n const form = useSeedEdits<CommerceModel.TaxSettings>(store?.tax ?? { mode: 'manual' })\n const current = form.values\n const checking = isSeedChecking({ fromCache: storeFromCache, unreadable: storeStatus === 'error' })\n /**\n * Whether anyone has ever answered the tax question for this store\n * (AGL-1999). Read from the SAVED document, never from `current` — the\n * `{ mode: 'manual' }` seed above is local state that has never reached\n * Firestore, and it is exactly what made this invisible: the card looked\n * configured while the server saw `mode: undefined`, took no branch, and\n * sold untaxed. Every storefront path now refuses that state, so the card\n * has to show it rather than paper over it.\n */\n const decided =\n storeStatus !== 'loading' && typeof store?.tax?.mode === 'string'\n const update = (patch: Partial<CommerceModel.TaxSettings>) =>\n form.edit(patch)\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.TaxRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else rates[index] = { country: '', pct: 0, ...rates[index], ...patch }\n update({ rates })\n }\n /**\n * One of the flat, per-regime rates (AGL-1969 lodging, AGL-2028 services).\n *\n * A blank field clears the rate rather than storing `NaN`: clearing is how a\n * merchant turns the regime back off, and `Number('')` is 0 while\n * `Number(' ')` is also 0 — neither of which should ever reach the document\n * as a \"rate\".\n */\n const updateFlat = (\n key: 'lodging' | 'service',\n patch: Partial<CommerceModel.FlatTaxRate>,\n ) => update({ [key]: { ...current[key], ...patch } })\n const flatPctText = (key: 'lodging' | 'service') => {\n const pct = current[key]?.pct\n return pct === undefined || pct === null ? '' : String(pct)\n }\n /**\n * Shown under a typed rate this will NOT apply. Silence here would be the\n * failure: `resolveFlatTaxCents` treats an out-of-range percentage as off,\n * so a decimal-point typo would otherwise save cleanly and collect nothing.\n */\n const flatPctProblem = (key: 'lodging' | 'service'): string | null => {\n const raw = current[key]?.pct\n if (raw === undefined || raw === null || String(raw) === '') return null\n if (Number(raw) === 0) return null\n return CommerceModel.isUsableFlatTaxPct(raw)\n ? null\n : `Enter a percentage between 0 and ${CommerceModel.FLAT_TAX_MAX_PCT}. ` +\n 'This rate is not being applied.'\n }\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * No create path to exempt: this is a FIXED document path, so the\n * `{mode: 'manual'}` default produced when the cache has never seen the\n * map is not the harmless blank a fresh uid would be — writing it turns\n * automatic tax calculation off on a store that had it on.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const written = form.edits\n const verdict = await writeGuardedBySeed(\n {\n subject: 'tax settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n listen: storeListen,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n { tax: current },\n { merge: true },\n )\n },\n )\n // Before `settle`, so a refusal keeps every typed rate on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n form.settle(written)\n enqueueSnackbar('Tax settings saved', { variant: 'success', persist: false })\n }, [current, form, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache, storeListen])\n\n return (\n <CardDisplay\n // Another plugin's card scrolls here (the tax service's \"Go to Taxes\",\n // AGL-3693), restating this id rather than importing this package.\n id=\"commerce-store-taxes\"\n header={'Taxes'}\n help={pluginDocsHelp('commerce', { anchor: '#tax-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n {decided ? null : (\n // The store is not selling. Saying so here is the whole point: the\n // silent version of this state charged shoppers an untaxed total.\n <Alert severity=\"warning\">\n {'Choose how this store handles sales tax and save. Until you ' +\n 'do, checkout is turned off — we won’t take an order we can’t ' +\n 'tax correctly.'}\n </Alert>\n )}\n <TextField\n label=\"Calculation\"\n value={current.mode ?? 'manual'}\n onChange={(event) =>\n update({\n mode: event.target.value as 'manual' | 'stripe' | 'none',\n })\n }\n size=\"small\"\n select\n sx={{ maxWidth: 280 }}\n >\n <MenuItem value=\"manual\">{'Manual rates (below)'}</MenuItem>\n <MenuItem value=\"stripe\">{'Stripe Tax (automatic)'}</MenuItem>\n {/* An explicit decision, not an omission (AGL-1999) — the option a\n merchant under a nexus threshold, or selling non-taxable goods,\n needs in order to sell at all. */}\n <MenuItem value=\"none\">{'Don’t collect sales tax'}</MenuItem>\n </TextField>\n {current.mode === 'none' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This store adds no sales tax to any order. Orders still go ' +\n 'through — the decision is recorded, not the tax.'}\n </Typography>\n ) : current.mode === 'stripe' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Stripe Tax calculates per buyer location at checkout. ' +\n 'Activate Stripe Tax in your Stripe dashboard first.'}\n </Typography>\n ) : (\n <>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.pricesIncludeTax)}\n onChange={(event) =>\n update({ pricesIncludeTax: event.target.checked })\n }\n />\n }\n label=\"Prices include tax (VAT-style)\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Origin country\"\n value={current.origin?.country ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n country: event.target.value.toUpperCase().slice(0, 2),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"US\"\n />\n <TextField\n label=\"Origin state\"\n value={current.origin?.state ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n state: event.target.value.toUpperCase().slice(0, 3),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"TX\"\n />\n </Stack>\n {/* Which of the product's three addresses this is. A merchant\n who reads an unlabeled origin as \"our address\" may set it\n from the wrong one: the address the workspace pays Aglyn\n from is a different jurisdiction question, and the payout\n identity is a third. Naming the two it is NOT costs a line\n and prevents a mis-taxed order. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Where this store ships or sells FROM — the jurisdiction the ' +\n 'manual rates below are applied from. Not the address your ' +\n 'workspace is billed at by Aglyn, and not where your payouts ' +\n 'are sent.'}\n </Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={index} direction=\"row\" spacing={1}>\n <TextField\n label=\"Country\"\n value={rate.country}\n onChange={(event) =>\n updateRate(index, {\n country: event.target.value.toUpperCase().slice(0, 2),\n })\n }\n size=\"small\"\n sx={{ width: 90 }}\n />\n <TextField\n label=\"State\"\n value={rate.state ?? ''}\n onChange={(event) =>\n updateRate(index, {\n state:\n event.target.value.toUpperCase().slice(0, 3) ||\n undefined,\n })\n }\n size=\"small\"\n sx={{ width: 80 }}\n />\n <TextField\n label=\"%\"\n value={rate.pct}\n onChange={(event) =>\n updateRate(index, { pct: Number(event.target.value) || 0 })\n }\n size=\"small\"\n sx={{ width: 80 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={rate.label ?? ''}\n onChange={(event) =>\n updateRate(index, { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Sales tax\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n </>\n )}\n {/*\n LODGING TAX (AGL-1969) — deliberately OUTSIDE the calculation branch\n above, and deliberately not a `rates[]` row.\n\n The setting above is a goods SALES rate resolved against an address.\n Occupancy tax is a different regime with its own rates, registration\n and return, and it applies to reservations, which sell nights rather\n than goods. Nesting it under \"Manual rates\" would have said the two\n are the same machinery; putting it here says a store on Stripe Tax —\n which cannot compute occupancy tax from these sessions at all — can\n still set one.\n\n It is off until the merchant fills it in, so nothing an existing\n store charges moves.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Lodging tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on reservations, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because occupancy tax is its own regime with its own rates ' +\n 'and its own return. Leave it blank to charge none — that is ' +\n 'the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('lodging')}\n onChange={(event) =>\n updateFlat('lodging', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('lodging'))}\n helperText={flatPctProblem('lodging') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.lodging?.label ?? ''}\n onChange={(event) =>\n updateFlat('lodging', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Occupancy tax\"\n helperText=\"Shown to the guest on the receipt\"\n />\n </Stack>\n {/*\n MECHANISM ONLY, AND NO REMITTANCE DETERMINATION.\n\n Whether a jurisdiction imposes occupancy tax, who must register for\n it and who must remit it are legal conclusions that attach by\n operation of law (AGL-1904/AGL-1956) and are the merchant's under\n the Terms. This copy says what the software DOES and what it does\n not do, and stops there — including the deposit basis, which is a\n real limitation rather than an answer this product has taken.\n */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'On a reservation that takes a deposit, the rate is applied to ' +\n 'the deposit — the amount actually charged here — not to the ' +\n 'whole stay. If tax is due on the full stay, collect the ' +\n 'difference the same way you collect the rest of the balance.'}\n </Typography>\n </Stack>\n {/*\n SERVICE TAX (AGL-2028) — the bookings sibling of the block above,\n and here for the same reason it is not in the bookings plugin's own\n settings: this is the one card a merchant comes to with a tax\n question, and a second tax surface elsewhere is how one of them ends\n up unanswered.\n\n Its EXISTENCE is also the opt-in AGL-2000 wanted. That issue\n declined to apply the goods rate to an appointment partly because\n nothing said the merchant meant these settings to cover bookings; a\n field labelled for services, blank until they fill it in, is them\n saying so.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Service tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on paid bookings, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because whether a service is taxable is often a different ' +\n 'question from whether goods are. Leave it blank to charge ' +\n 'none — that is the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('service')}\n onChange={(event) =>\n updateFlat('service', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('service'))}\n helperText={flatPctProblem('service') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.service?.label ?? ''}\n onChange={(event) =>\n updateFlat('service', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Service tax\"\n helperText=\"Shown to the client on the receipt\"\n />\n </Stack>\n {/* MECHANISM ONLY, AND NO REMITTANCE DETERMINATION — see the\n lodging block above. */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n </Stack>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n // An undecided store saves the choice on screen as it stands. The\n // select fires no change for the option already shown, so waiting\n // for an edit left \"Manual rates\" unsaveable and checkout off.\n disabled={storeStatus === 'loading' || (decided && !form.dirty) || checking}\n onClick={handleSave}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'Save tax settings'}\n </Button>\n {(!decided || form.dirty) && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('tax settings')}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nTaxSettingsCard.displayName = 'TaxSettingsCard'\n\nexport default TaxSettingsCard\n"],"names":["CommerceModel","PLATFORM_BRAND_NAME","CardDisplay","useSnackbar","Alert","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","setDoc","useCallback","useFirestore","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","isSeedChecking","seedCheckingText","useSeedEdits","TaxSettingsCard","props","current","flatPctProblem","store","hostId","firestore","enqueueSnackbar","data","status","storeStatus","fromCache","storeFromCache","listen","storeListen","form","tax","mode","values","checking","unreadable","decided","update","patch","edit","updateRate","index","rates","splice","country","pct","updateFlat","key","flatPctText","undefined","String","raw","Number","isUsableFlatTaxPct","FLAT_TAX_MAX_PCT","handleSave","written","edits","verdict","subject","merge","ok","message","variant","persist","settle","id","header","help","anchor","contentGutterX","contentGutterY","spacing","severity","label","value","onChange","event","target","size","select","sx","maxWidth","color","control","checked","Boolean","pricesIncludeTax","direction","origin","toUpperCase","slice","width","placeholder","state","map","rate","slotProps","htmlInput","inputMode","flex","onClick","alignSelf","length","my","error","helperText","lodging","service","disabled","dirty","role","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,eAAc;AAC7C,SACEC,cAAc,EACdC,gBAAgB,EAChBC,YAAY,QACP,sDAAqD;AAM5D;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,KAA2B;cA6I1CC,6BAqFHA,gBAyGYC,wBA6EAA;QAnXcC,YAoJjBF,iBAeAA,kBAwIFA,kBA6EAA;IA5ZnB,MAAM,EAAEG,MAAM,EAAE,GAAGJ;IACnB,MAAMK,YAAYb;IAClB,MAAM,EAAEc,eAAe,EAAE,GAAG3B;IAC5B,MAAM,EACJ4B,MAAMJ,KAAK,EACXK,QAAQC,WAA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CACLE,IAAI;wCAAEmB,MAAM;oCAAE;oCACdP,aAAY;oCACZa,YAAW;;;;sCAKf,KAAC9G;4BAAM6E,UAAS;sCACb,GAAGhF,oBAAoB,wCAAwC,CAAC,GAC/D,8DACA,gEACA;;;;8BAGN,KAACI;oBACCkE,SAAQ;oBACRoB,OAAM;oBACNJ,MAAK;oBACL,kEAAkE;oBAClE,kEAAkE;oBAClE,+DAA+D;oBAC/D8B,UAAUpF,gBAAgB,aAAcW,WAAW,CAACN,KAAKgF,KAAK,IAAK5E;oBACnEmE,SAAS9C;oBACT0B,IAAI;wBAAEqB,WAAW;oBAAa;8BAE7B;;gBAED,CAAA,CAAClE,WAAWN,KAAKgF,KAAK,AAAD,KAAM5E,yBAC3B,KAAC9B;oBAAW2D,SAAQ;oBAAQoB,OAAM;oBAAiB4B,MAAK;8BACrDlG,iBAAiB;qBAElB;;;;AAIZ;AACAE,gBAAgBiG,WAAW,GAAG;AAE9B,eAAejG,gBAAe"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/tax-settings-card.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 * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Alert,\n Button,\n Divider,\n FormControlLabel,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback } from 'react'\nimport { useFirestore } from '@aglyn/tenant-feature-instance'\nimport {\n useFirestoreDoc,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\n\nexport interface TaxSettingsCardProps {\n hostId: string\n}\n\n/**\n * Tax settings (AGL-285): manual per-region rates (most-specific wins)\n * or Stripe Tax automatic calculation, stored on\n * `hosts/{hostId}/settings/store` under `tax`. The legacy quick-buy\n * checkout taxes by the store origin; Checkout v2 taxes by destination.\n */\nexport function TaxSettingsCard(props: TaxSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status: storeStatus,\n /**\n * The settings doc this form is seeded from is unconfirmed by the server\n * (AGL-1358). `current` is `draft ?? store?.tax ?? {mode: 'manual'}` and\n * the save writes `{tax: current}`, so `merge: true` protects the doc's\n * other maps and nothing inside this one. `mode` is the field that costs\n * money: a cached seed flipping `stripe` back to `manual` stops automatic\n * tax calculation — `resolveTaxRate` returns null in stripe mode — and\n * the store under-collects with nothing anywhere reporting it.\n */\n fromCache: storeFromCache,\n listen: storeListen,\n } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n // What was typed, kept as edits over the stored settings, and Save held\n // until the server has confirmed them (AGL-4047).\n const form = useSeedEdits<CommerceModel.TaxSettings>(store?.tax ?? { mode: 'manual' })\n const current = form.values\n const checking = isSeedChecking({ fromCache: storeFromCache, unreadable: storeStatus === 'error' })\n /**\n * Whether anyone has ever answered the tax question for this store\n * (AGL-1999). Read from the SAVED document, never from `current` — the\n * `{ mode: 'manual' }` seed above is local state that has never reached\n * Firestore, and it is exactly what made this invisible: the card looked\n * configured while the server saw `mode: undefined`, took no branch, and\n * sold untaxed. Every storefront path now refuses that state, so the card\n * has to show it rather than paper over it.\n */\n const decided =\n storeStatus !== 'loading' && typeof store?.tax?.mode === 'string'\n const update = (patch: Partial<CommerceModel.TaxSettings>) =>\n form.edit(patch)\n const updateRate = (\n index: number,\n patch: Partial<CommerceModel.TaxRate> | null,\n ) => {\n const rates = [...(current.rates ?? [])]\n if (patch === null) rates.splice(index, 1)\n else rates[index] = { country: '', pct: 0, ...rates[index], ...patch }\n update({ rates })\n }\n /**\n * One of the flat, per-regime rates (AGL-1969 lodging, AGL-2028 services).\n *\n * A blank field clears the rate rather than storing `NaN`: clearing is how a\n * merchant turns the regime back off, and `Number('')` is 0 while\n * `Number(' ')` is also 0 — neither of which should ever reach the document\n * as a \"rate\".\n */\n const updateFlat = (\n key: 'lodging' | 'service',\n patch: Partial<CommerceModel.FlatTaxRate>,\n ) => update({ [key]: { ...current[key], ...patch } })\n const flatPctText = (key: 'lodging' | 'service') => {\n const pct = current[key]?.pct\n return pct === undefined || pct === null ? '' : String(pct)\n }\n /**\n * Shown under a typed rate this will NOT apply. Silence here would be the\n * failure: `resolveFlatTaxCents` treats an out-of-range percentage as off,\n * so a decimal-point typo would otherwise save cleanly and collect nothing.\n */\n const flatPctProblem = (key: 'lodging' | 'service'): string | null => {\n const raw = current[key]?.pct\n if (raw === undefined || raw === null || String(raw) === '') return null\n if (Number(raw) === 0) return null\n return CommerceModel.isUsableFlatTaxPct(raw)\n ? null\n : `Enter a percentage between 0 and ${CommerceModel.FLAT_TAX_MAX_PCT}. ` +\n 'This rate is not being applied.'\n }\n\n const handleSave = useCallback(async () => {\n /**\n * Refuse a save whose seed the server never confirmed (AGL-1358).\n *\n * No create path to exempt: this is a FIXED document path, so the\n * `{mode: 'manual'}` default produced when the cache has never seen the\n * map is not the harmless blank a fresh uid would be — writing it turns\n * automatic tax calculation off on a store that had it on.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const written = form.edits\n const verdict = await writeGuardedBySeed(\n {\n subject: 'tax settings',\n unreadable: storeStatus === 'error',\n fromCache: storeFromCache,\n listen: storeListen,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'settings', 'store'),\n { tax: current },\n { merge: true },\n )\n },\n )\n // Before `settle`, so a refusal keeps every typed rate on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n form.settle(written)\n enqueueSnackbar('Tax settings saved', { variant: 'success', persist: false })\n }, [current, form, firestore, hostId, enqueueSnackbar, storeStatus, storeFromCache, storeListen])\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const held = useHeldSave(handleSave, {\n checking,\n subject: 'tax settings',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n // Another plugin's card scrolls here (the tax service's \"Go to Taxes\",\n // AGL-3693), restating this id rather than importing this package.\n id=\"commerce-store-taxes\"\n header={'Taxes'}\n help={pluginDocsHelp('commerce', { anchor: '#tax-settings' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1.5}>\n {decided ? null : (\n // The store is not selling. Saying so here is the whole point: the\n // silent version of this state charged shoppers an untaxed total.\n <Alert severity=\"warning\">\n {'Choose how this store handles sales tax and save. Until you ' +\n 'do, checkout is turned off — we won’t take an order we can’t ' +\n 'tax correctly.'}\n </Alert>\n )}\n <TextField\n label=\"Calculation\"\n value={current.mode ?? 'manual'}\n onChange={(event) =>\n update({\n mode: event.target.value as 'manual' | 'stripe' | 'none',\n })\n }\n size=\"small\"\n select\n sx={{ maxWidth: 280 }}\n >\n <MenuItem value=\"manual\">{'Manual rates (below)'}</MenuItem>\n <MenuItem value=\"stripe\">{'Stripe Tax (automatic)'}</MenuItem>\n {/* An explicit decision, not an omission (AGL-1999) — the option a\n merchant under a nexus threshold, or selling non-taxable goods,\n needs in order to sell at all. */}\n <MenuItem value=\"none\">{'Don’t collect sales tax'}</MenuItem>\n </TextField>\n {current.mode === 'none' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This store adds no sales tax to any order. Orders still go ' +\n 'through — the decision is recorded, not the tax.'}\n </Typography>\n ) : current.mode === 'stripe' ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Stripe Tax calculates per buyer location at checkout. ' +\n 'Activate Stripe Tax in your Stripe dashboard first.'}\n </Typography>\n ) : (\n <>\n <FormControlLabel\n control={\n <Switch\n size=\"small\"\n checked={Boolean(current.pricesIncludeTax)}\n onChange={(event) =>\n update({ pricesIncludeTax: event.target.checked })\n }\n />\n }\n label=\"Prices include tax (VAT-style)\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Origin country\"\n value={current.origin?.country ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n country: event.target.value.toUpperCase().slice(0, 2),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"US\"\n />\n <TextField\n label=\"Origin state\"\n value={current.origin?.state ?? ''}\n onChange={(event) =>\n update({\n origin: {\n ...current.origin,\n state: event.target.value.toUpperCase().slice(0, 3),\n },\n })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"TX\"\n />\n </Stack>\n {/* Which of the product's three addresses this is. A merchant\n who reads an unlabeled origin as \"our address\" may set it\n from the wrong one: the address the workspace pays Aglyn\n from is a different jurisdiction question, and the payout\n identity is a third. Naming the two it is NOT costs a line\n and prevents a mis-taxed order. */}\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Where this store ships or sells FROM — the jurisdiction the ' +\n 'manual rates below are applied from. Not the address your ' +\n 'workspace is billed at by Aglyn, and not where your payouts ' +\n 'are sent.'}\n </Typography>\n {(current.rates ?? []).map((rate, index) => (\n <Stack key={index} direction=\"row\" spacing={1}>\n <TextField\n label=\"Country\"\n value={rate.country}\n onChange={(event) =>\n updateRate(index, {\n country: event.target.value.toUpperCase().slice(0, 2),\n })\n }\n size=\"small\"\n sx={{ width: 90 }}\n />\n <TextField\n label=\"State\"\n value={rate.state ?? ''}\n onChange={(event) =>\n updateRate(index, {\n state:\n event.target.value.toUpperCase().slice(0, 3) ||\n undefined,\n })\n }\n size=\"small\"\n sx={{ width: 80 }}\n />\n <TextField\n label=\"%\"\n value={rate.pct}\n onChange={(event) =>\n updateRate(index, { pct: Number(event.target.value) || 0 })\n }\n size=\"small\"\n sx={{ width: 80 }}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={rate.label ?? ''}\n onChange={(event) =>\n updateRate(index, { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Sales tax\"\n />\n <Button\n size=\"small\"\n color=\"error\"\n onClick={() => updateRate(index, null)}\n >\n {'✕'}\n </Button>\n </Stack>\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => updateRate(current.rates?.length ?? 0, {})}\n >\n {'Add rate'}\n </Button>\n </>\n )}\n {/*\n LODGING TAX (AGL-1969) — deliberately OUTSIDE the calculation branch\n above, and deliberately not a `rates[]` row.\n\n The setting above is a goods SALES rate resolved against an address.\n Occupancy tax is a different regime with its own rates, registration\n and return, and it applies to reservations, which sell nights rather\n than goods. Nesting it under \"Manual rates\" would have said the two\n are the same machinery; putting it here says a store on Stripe Tax —\n which cannot compute occupancy tax from these sessions at all — can\n still set one.\n\n It is off until the merchant fills it in, so nothing an existing\n store charges moves.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Lodging tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on reservations, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because occupancy tax is its own regime with its own rates ' +\n 'and its own return. Leave it blank to charge none — that is ' +\n 'the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('lodging')}\n onChange={(event) =>\n updateFlat('lodging', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('lodging'))}\n helperText={flatPctProblem('lodging') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.lodging?.label ?? ''}\n onChange={(event) =>\n updateFlat('lodging', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Occupancy tax\"\n helperText=\"Shown to the guest on the receipt\"\n />\n </Stack>\n {/*\n MECHANISM ONLY, AND NO REMITTANCE DETERMINATION.\n\n Whether a jurisdiction imposes occupancy tax, who must register for\n it and who must remit it are legal conclusions that attach by\n operation of law (AGL-1904/AGL-1956) and are the merchant's under\n the Terms. This copy says what the software DOES and what it does\n not do, and stops there — including the deposit basis, which is a\n real limitation rather than an answer this product has taken.\n */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'On a reservation that takes a deposit, the rate is applied to ' +\n 'the deposit — the amount actually charged here — not to the ' +\n 'whole stay. If tax is due on the full stay, collect the ' +\n 'difference the same way you collect the rest of the balance.'}\n </Typography>\n </Stack>\n {/*\n SERVICE TAX (AGL-2028) — the bookings sibling of the block above,\n and here for the same reason it is not in the bookings plugin's own\n settings: this is the one card a merchant comes to with a tax\n question, and a second tax surface elsewhere is how one of them ends\n up unanswered.\n\n Its EXISTENCE is also the opt-in AGL-2000 wanted. That issue\n declined to apply the goods rate to an appointment partly because\n nothing said the merchant meant these settings to cover bookings; a\n field labelled for services, blank until they fill it in, is them\n saying so.\n */}\n <Divider sx={{ my: 0.5 }} />\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Service tax'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Charged on paid bookings, on top of the price, using the rate ' +\n 'you enter here. It is separate from the sales tax above ' +\n 'because whether a service is taxable is often a different ' +\n 'question from whether goods are. Leave it blank to charge ' +\n 'none — that is the default.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Rate %\"\n value={flatPctText('service')}\n onChange={(event) =>\n updateFlat('service', {\n pct:\n event.target.value === ''\n ? undefined\n : Number(event.target.value),\n })\n }\n size=\"small\"\n sx={{ width: 110 }}\n placeholder=\"0\"\n error={Boolean(flatPctProblem('service'))}\n helperText={flatPctProblem('service') ?? ' '}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Label\"\n value={current.service?.label ?? ''}\n onChange={(event) =>\n updateFlat('service', { label: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n placeholder=\"Service tax\"\n helperText=\"Shown to the client on the receipt\"\n />\n </Stack>\n {/* MECHANISM ONLY, AND NO REMITTANCE DETERMINATION — see the\n lodging block above. */}\n <Alert severity=\"info\">\n {`${PLATFORM_BRAND_NAME} applies the rate you enter and records ` +\n 'what was charged. It does not determine whether this tax ' +\n 'applies to you, at what rate, or where it should be paid — ' +\n 'that is yours to decide.'}\n </Alert>\n </Stack>\n <Button\n variant=\"contained\"\n color=\"primary\"\n size=\"small\"\n // An undecided store saves the choice on screen as it stands. The\n // select fires no change for the option already shown, so waiting\n // for an edit left \"Manual rates\" unsaveable and checkout off.\n disabled={storeStatus === 'loading' || (decided && !form.dirty) || held.saving}\n onClick={held.press}\n sx={{ alignSelf: 'flex-start' }}\n >\n {heldSaveLabel(held, 'Save tax settings')}\n </Button>\n {(!decided || form.dirty) && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('tax settings')}\n </Typography>\n ) : null}\n </Stack>\n </CardDisplay>\n )\n}\nTaxSettingsCard.displayName = 'TaxSettingsCard'\n\nexport default TaxSettingsCard\n"],"names":["CommerceModel","PLATFORM_BRAND_NAME","CardDisplay","useSnackbar","Alert","Button","Divider","FormControlLabel","MenuItem","Stack","Switch","TextField","Typography","doc","setDoc","useCallback","useFirestore","useFirestoreDoc","writeGuardedBySeed","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedEdits","TaxSettingsCard","props","current","flatPctProblem","store","hostId","firestore","enqueueSnackbar","data","status","storeStatus","fromCache","storeFromCache","listen","storeListen","form","tax","mode","values","checking","unreadable","decided","update","patch","edit","updateRate","index","rates","splice","country","pct","updateFlat","key","flatPctText","undefined","String","raw","Number","isUsableFlatTaxPct","FLAT_TAX_MAX_PCT","handleSave","written","edits","verdict","subject","merge","ok","message","variant","persist","settle","held","onRefused","id","header","help","anchor","contentGutterX","contentGutterY","spacing","severity","label","value","onChange","event","target","size","select","sx","maxWidth","color","control","checked","Boolean","pricesIncludeTax","direction","origin","toUpperCase","slice","width","placeholder","state","map","rate","slotProps","htmlInput","inputMode","flex","onClick","alignSelf","length","my","error","helperText","lodging","service","disabled","dirty","saving","press","role","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAGA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,KAAK,EACLC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,YAAY,QAAQ,iCAAgC;AAC7D,SACEC,eAAe,EACfC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,e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@ export interface PosOfflineSaleCard {
|
|
|
53
53
|
last4?: string;
|
|
54
54
|
/** The bank's or Stripe's words for a decline or failure. */
|
|
55
55
|
declineMessage?: string;
|
|
56
|
+
/**
|
|
57
|
+
* The store's own Stripe account the device made the intent on, from the
|
|
58
|
+
* kit it sold with (a direct charge, AGL-4219). Absent: a destination
|
|
59
|
+
* charge made on the platform. The server reads the intent there, and
|
|
60
|
+
* captures it only when it is still the store's account.
|
|
61
|
+
*/
|
|
62
|
+
account?: string;
|
|
56
63
|
}
|
|
57
64
|
/** Every tender the register turns off while offline, and why, in its words. */
|
|
58
65
|
export declare const POS_OFFLINE_DISABLED_TENDERS: Readonly<Record<string, string>>;
|
|
@@ -183,8 +190,15 @@ export interface PosOfflineKitCard {
|
|
|
183
190
|
available: boolean;
|
|
184
191
|
/** Why not, in the cashier's words, when it is not. */
|
|
185
192
|
unavailableReason?: string;
|
|
186
|
-
/** The connected account the charge transfers to (a destination charge, as online). */
|
|
193
|
+
/** The connected account the charge transfers to (a destination charge, as online); '' for a direct charge. */
|
|
187
194
|
destination: string;
|
|
195
|
+
/**
|
|
196
|
+
* Set for a store on its own Stripe account (direct charges, AGL-4219):
|
|
197
|
+
* the device makes the intent with no transfer and no destination, on the
|
|
198
|
+
* account its connection token belongs to, which is this one. Offered only
|
|
199
|
+
* to an app that says it can (`cardChargeModels=direct` on the kit's GET).
|
|
200
|
+
*/
|
|
201
|
+
account?: string;
|
|
188
202
|
currency: string;
|
|
189
203
|
/** The limit of one card sale rung offline, in cents: the store's, or Stripe's own ceiling when it set none. */
|
|
190
204
|
maxSaleCents: number;
|
|
@@ -291,6 +305,10 @@ export declare function posOfflineCardRefusal(input: {
|
|
|
291
305
|
* What the app writes on the PaymentIntent it creates for a card rung
|
|
292
306
|
* offline: the sale key (the order's id once it syncs) and where it was rung,
|
|
293
307
|
* so the server can match the charge to the sale even if the sale's own sync
|
|
294
|
-
* never arrives.
|
|
308
|
+
* never arrives. An intent made on the store's own account (`direct`,
|
|
309
|
+
* AGL-4219) also says `chargeModel: direct`, as every direct sale's objects
|
|
310
|
+
* do, so its Connect-delivered events are read as the store's own.
|
|
295
311
|
*/
|
|
296
|
-
export declare function posOfflineCardIntentMetadata(sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'>
|
|
312
|
+
export declare function posOfflineCardIntentMetadata(sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'> & {
|
|
313
|
+
direct?: boolean;
|
|
314
|
+
}): Record<string, string>;
|
|
@@ -28,8 +28,11 @@ import { POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT } from "./pos-offline-card-limits
|
|
|
28
28
|
* - A card, only on the native Aglyn POS app's own Stripe Terminal reader
|
|
29
29
|
* (AGL-4039): Stripe's SDK stores the card on the device ("store and
|
|
30
30
|
* forward") and forwards it once a connection returns. The app creates
|
|
31
|
-
* the PaymentIntent itself
|
|
32
|
-
*
|
|
31
|
+
* the PaymentIntent itself with MANUAL capture and NO application fee:
|
|
32
|
+
* a destination charge for a store on Aglyn's account, or, for a store on
|
|
33
|
+
* its own Stripe account (direct charges), an intent made ON that account
|
|
34
|
+
* (the connection token's) with no transfer at all (AGL-4219). The
|
|
35
|
+
* server captures it when the sale syncs and
|
|
33
36
|
* sizes the platform fee then, exactly as for an online card sale. A bank
|
|
34
37
|
* can still decline it at that point, after the customer left: the order
|
|
35
38
|
* is then recorded unpaid and flagged, and the register says so.
|
|
@@ -330,6 +333,7 @@ function wholeCents(value) {
|
|
|
330
333
|
return (_POS_OFFLINE_FLAG_LABELS_flag = POS_OFFLINE_FLAG_LABELS[flag]) != null ? _POS_OFFLINE_FLAG_LABELS_flag : flag;
|
|
331
334
|
});
|
|
332
335
|
}
|
|
336
|
+
/** A Stripe account id as Stripe mints them. */ const POS_OFFLINE_CARD_ACCOUNT = /^acct_[A-Za-z0-9]{8,64}$/;
|
|
333
337
|
const CARD_FORWARDS = [
|
|
334
338
|
'stored',
|
|
335
339
|
'forwarded',
|
|
@@ -347,6 +351,8 @@ const CARD_FORWARDS = [
|
|
|
347
351
|
const brand = bounded(input['brand'], 24);
|
|
348
352
|
const last4 = typeof input['last4'] === 'string' && /^\d{4}$/.test(input['last4']) ? input['last4'] : '';
|
|
349
353
|
const declineMessage = bounded(input['declineMessage'], 300);
|
|
354
|
+
const account = typeof input['account'] === 'string' ? input['account'].trim() : '';
|
|
355
|
+
if (account && !POS_OFFLINE_CARD_ACCOUNT.test(account)) return null;
|
|
350
356
|
return _extends({
|
|
351
357
|
forward
|
|
352
358
|
}, intent ? {
|
|
@@ -357,6 +363,8 @@ const CARD_FORWARDS = [
|
|
|
357
363
|
last4
|
|
358
364
|
} : {}, declineMessage ? {
|
|
359
365
|
declineMessage
|
|
366
|
+
} : {}, account ? {
|
|
367
|
+
account
|
|
360
368
|
} : {});
|
|
361
369
|
}
|
|
362
370
|
/**
|
|
@@ -384,15 +392,19 @@ const CARD_FORWARDS = [
|
|
|
384
392
|
* What the app writes on the PaymentIntent it creates for a card rung
|
|
385
393
|
* offline: the sale key (the order's id once it syncs) and where it was rung,
|
|
386
394
|
* so the server can match the charge to the sale even if the sale's own sync
|
|
387
|
-
* never arrives.
|
|
395
|
+
* never arrives. An intent made on the store's own account (`direct`,
|
|
396
|
+
* AGL-4219) also says `chargeModel: direct`, as every direct sale's objects
|
|
397
|
+
* do, so its Connect-delivered events are read as the store's own.
|
|
388
398
|
*/ export function posOfflineCardIntentMetadata(sale) {
|
|
389
|
-
return {
|
|
399
|
+
return _extends({
|
|
390
400
|
kind: POS_OFFLINE_CARD_INTENT_KIND,
|
|
391
401
|
saleKey: sale.saleKey,
|
|
392
402
|
hostId: sale.hostId,
|
|
393
403
|
orgId: sale.orgId,
|
|
394
404
|
registerId: sale.registerId
|
|
395
|
-
}
|
|
405
|
+
}, sale.direct ? {
|
|
406
|
+
chargeModel: 'direct'
|
|
407
|
+
} : {});
|
|
396
408
|
}
|
|
397
409
|
function dollars(cents) {
|
|
398
410
|
const whole = Math.floor(cents / 100);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-offline.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 { computeOrderTotals, type OrderLineItem, type OrderTotals } from './commerce-orders'\nimport { computeTaxCents } from './commerce-tax'\nimport type { ModifierSelection } from './product-modifiers'\nimport { POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT } from './pos-offline-card-limits'\n\n/*==========================================\n * THE OFFLINE REGISTER (AGL-3625): the contract every register client — the\n * web register and the native Aglyn POS app — shares with\n * `POST /api/commerce/pos-offline-sync`.\n *\n * WHAT SELLS OFFLINE IS CASH, AND A CARD ON THE NATIVE APP'S OWN READER.\n *\n * - Cash, on every register client.\n * - A card, only on the native Aglyn POS app's own Stripe Terminal reader\n * (AGL-4039): Stripe's SDK stores the card on the device (\"store and\n * forward\") and forwards it once a connection returns. The app creates\n * the PaymentIntent itself, a destination charge with MANUAL capture and\n * NO application fee; the server captures it when the sale syncs and\n * sizes the platform fee then, exactly as for an online card sale. A bank\n * can still decline it at that point, after the customer left: the order\n * is then recorded unpaid and flagged, and the register says so.\n * Off until the store turns it on, then within the store's two limits:\n * per sale, and per device per day (as Shopify POS words it).\n * - Every other card tender cannot: Tap to Pay on Android, the server's\n * smart readers, the typed card and the QR link are server-driven, and\n * Stripe does not take a server-driven card payment without the server.\n * - Gift cards DO NOT, deliberately. A balance cannot be checked without the\n * server, and a capped \"allow it anyway\" (Square's offer for cards) turns a\n * short balance into a sale whose money nobody collected — discovered at\n * sync, after the customer left. Square itself does not redeem gift cards\n * offline. A gift card is never over-redeemed silently because it is never\n * redeemed offline at all.\n * - Room charges do not: the stay is validated on the server.\n * - Store credit and rewards do not, for the gift card's reason: a balance\n * is the server's to check.\n * - Codes and store promotions do not: a redemption cap is counted on the\n * server. The cashier's own discount, bounded by the site's ceiling, does.\n *\n * WHAT THE SALE IS: the register prices the basket from its cached catalog and\n * the store's own tax rate, takes the cash and queues the sale with a key it\n * minted. That key is the order's id on the server, so the receipt printed\n * offline carries the barcode the real order answers to, and a sale sent twice\n * — a flapping connection, a retry after a lost answer — lands once.\n *\n * WHAT THE SERVER DOES WITH IT: records it as it happened, never re-prices the\n * money the customer handed over, and FLAGS what does not match — a price\n * that changed, stock that went short, a shift that closed first — on the\n * order and back to the register. A sale is never dropped for a flag.\n *=========================================*/\n\n/** The route both register clients sync through. */\nexport const POS_OFFLINE_SYNC_ROUTE = '/api/commerce/pos-offline-sync'\n\n/** The most sales one sync request carries; a longer queue sends in batches. */\nexport const POS_OFFLINE_SYNC_BATCH_MAX = 25\n\n/** Lines one offline sale may carry, the same bound the register's basket has. */\nexport const POS_OFFLINE_SALE_MAX_LINES = 100\n\n/** A sale synced later than this after it was rung is flagged `late-sync`. */\nexport const POS_OFFLINE_LATE_SYNC_MS = 24 * 60 * 60 * 1000\n\n/**\n * How far back a sale's own clock is believed. Older, and the server stamps\n * the sale at this bound and flags it, rather than letting a device clock\n * place a sale anywhere in history.\n */\nexport const POS_OFFLINE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\n/** How far ahead of the server a device clock may run before it is clamped. */\nexport const POS_OFFLINE_CLOCK_SKEW_MS = 10 * 60 * 1000\n\n/** What an offline sale was paid with. A sale with no tender is cash (the shape before AGL-4039). */\nexport type PosOfflineTender = 'cash' | 'card'\n\nexport {\n POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT,\n POS_OFFLINE_CARD_RECONNECT_WITHIN_MS,\n} from './pos-offline-card-limits'\n\n/** The `metadata[kind]` of a PaymentIntent the app created for a card rung offline. */\nexport const POS_OFFLINE_CARD_INTENT_KIND = 'pos-offline'\n\n/**\n * Where a card rung offline stands. `stored`: on the device, not yet sent to\n * Stripe. `forwarded`: Stripe has it and it is authorized, waiting for the\n * sync to capture it. `declined`: the bank refused it when it was forwarded.\n * `failed`: Stripe could not take it at all (no PaymentIntent was made).\n */\nexport type PosOfflineCardForward = 'stored' | 'forwarded' | 'declined' | 'failed'\n\n/** The card side of a sale rung offline on the app's own reader. */\nexport interface PosOfflineSaleCard {\n forward: PosOfflineCardForward\n /** Stripe's PaymentIntent id, once the SDK forwarded it. */\n paymentIntentId?: string | null\n brand?: string\n last4?: string\n /** The bank's or Stripe's words for a decline or failure. */\n declineMessage?: string\n}\n\n/** Every tender the register turns off while offline, and why, in its words. */\nexport const POS_OFFLINE_DISABLED_TENDERS: Readonly<Record<string, string>> = {\n card_present: 'Card readers need the connection.',\n card_keyed: 'Typed cards need the connection.',\n card_link: 'The QR card link needs the connection.',\n gift_card: 'A gift card balance can only be checked online.',\n folio: 'Room charges are checked against the stay online.',\n credit: 'Store credit and rewards balances can only be checked online.',\n}\n\n/** One basket line as the register rang it. */\nexport interface PosOfflineSaleLine {\n productId: string\n variantId?: string\n name: string\n /** Variant options and modifier choices, as the receipt printed them. */\n variantLabel?: string\n sku?: string\n productType?: 'physical' | 'digital' | 'service'\n quantity: number\n /** Per unit, modifiers included, from the cached catalog. */\n unitAmountCents: number\n modifiers?: ModifierSelection[]\n}\n\n/** The customer the register attached: only what the sale and its receipt need. */\nexport interface PosOfflineSaleCustomer {\n email?: string\n name?: string\n kind?: string\n id?: string\n}\n\n/** One sale rung while offline, exactly as the register queued it. */\nexport interface PosOfflineSale {\n v: 1\n /** The register's key for this sale, minted once; the order's id on the server. */\n saleKey: string\n hostId: string\n /** The workspace the register was signed in to. */\n orgId: string\n /** Who was signed in on the device: the only member who may sync it. */\n signedInUid: string\n registerId: string\n /** The shift open on the register when the sale was rung. */\n shiftId?: string | null\n locationId?: string\n /** A PIN-switched cashier's assertion, valid when the sale was rung. */\n cashierAssertion?: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n lines: PosOfflineSaleLine[]\n /** The cashier's discount, a percentage of the goods. */\n discountPct: number\n /** The totals the receipt printed and the customer paid. */\n totals: OrderTotals\n /** Cash handed over; 0 for a card sale. */\n cashTenderedCents: number\n changeCents: number\n customer?: PosOfflineSaleCustomer\n /** `card` only on the native app's own reader (AGL-4039); absent means cash. */\n tender?: PosOfflineTender\n /** The card, when `tender` is `card`. */\n card?: PosOfflineSaleCard\n}\n\n/** What does not match, said on the order and back to the register. */\nexport type PosOfflineFlag =\n | 'price-changed'\n | 'unknown-product'\n | 'tax-differs'\n | 'totals-restated'\n | 'discount-over-limit'\n | 'discount-not-permitted'\n | 'cash-short'\n | 'stock-short'\n | 'shift-closed'\n | 'no-shift'\n | 'unknown-register'\n | 'register-over-cap'\n | 'late-sync'\n | 'clock-adjusted'\n | 'cashier-unverified'\n | 'card-declined'\n | 'card-not-charged'\n | 'card-amount-differs'\n | 'card-fee-short'\n\n/** Each flag in the words the order and the register show. */\nexport const POS_OFFLINE_FLAG_LABELS: Record<PosOfflineFlag, string> = {\n 'price-changed': 'A price changed after the register cached it; the sale kept the price it was rung at',\n 'unknown-product': 'A product was deleted before the sale synced; the line kept what the receipt printed',\n 'tax-differs': 'The tax rung differs from the store’s rate now; the sale kept the tax it collected',\n 'totals-restated': 'The register’s totals did not add up; the server restated them from the lines',\n 'discount-over-limit': 'The discount is above this register’s limit',\n // Names the permission by its label in `plugin-permissions.ts` (AGL-4047);\n // `pos-offline-sync.spec.ts` holds the two to the same words.\n 'discount-not-permitted': 'The discount was given by a member whose role does not include “Give discounts at the register”',\n 'cash-short': 'The cash recorded is less than the total',\n 'stock-short': 'Stock went short: more was sold than the shelf held',\n 'shift-closed': 'Rung in a shift that closed before the sale synced; its Z report does not include it',\n 'no-shift': 'Rung with no shift open, on a site that requires one',\n 'unknown-register': 'The register it was rung on no longer exists',\n 'register-over-cap': 'The register it was rung on is over the plan’s register limit',\n 'late-sync': 'Synced more than a day after it was rung',\n 'clock-adjusted': 'The device clock was off; the sale is dated when it synced',\n 'cashier-unverified': 'The PIN-switched cashier could not be confirmed; the sale is under the signed-in member',\n 'card-declined': 'The card taken offline was declined when it was charged; the order is unpaid',\n 'card-not-charged': 'The card taken offline could not be charged; the order is unpaid',\n 'card-amount-differs': 'The card was charged a different amount than the sale’s total; the payment records what Stripe took',\n 'card-fee-short': 'Stripe took less than the platform fee from this card’s payout; the rest goes on the workspace’s monthly invoice',\n}\n\n/** A line whose stock went short when the sale synced. */\nexport interface PosOfflineStockConflict {\n productId: string\n variantId?: string\n name: string\n /** Units sold. */\n requested: number\n /** Units the shelf actually gave up. */\n applied: number\n /** Units sold that the shelf did not hold. */\n shortUnits: number\n}\n\n/** What the order records about having been rung offline. */\nexport interface PosOfflineOrderStamp {\n saleKey: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n syncedAtMs: number\n /** Who synced it: always the member who was signed in when it was rung. */\n syncedBy: string\n flags: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n /** The server's own price per line where it differed, for the merchant to compare. */\n priceDrift?: Array<{ index: number; rungCents: number; currentCents: number }>\n}\n\n/** Why a sale was refused, and whether the register should keep trying. */\nexport type PosOfflineRefusal =\n | 'wrong-staff'\n | 'wrong-site'\n | 'wrong-workspace'\n | 'invalid'\n | 'conflict'\n | 'failed'\n\n/** What became of one sale the register sent. */\nexport type PosOfflineOutcomeStatus = 'recorded' | 'replayed' | 'refused'\n\n/**\n * One sale's answer, in the order the request sent them. `recorded` and\n * `replayed` carry the order; `refused` carries the reason, the sentence and\n * whether to keep trying. One flat shape, so every register client — the web\n * register and the native apps — decodes it the same way.\n */\nexport interface PosOfflineSaleOutcome {\n saleKey: string\n status: PosOfflineOutcomeStatus\n orderId?: string\n number?: number | null\n flags?: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n reason?: PosOfflineRefusal\n error?: string\n /** Keep it queued and try again later (a transient failure). */\n retry?: boolean\n}\n\nexport interface PosOfflineSyncRequest {\n hostId: string\n sales: PosOfflineSale[]\n}\n\nexport interface PosOfflineSyncResponse {\n results: PosOfflineSaleOutcome[]\n}\n\n/** One register as the offline kit lists it. */\nexport interface PosOfflineKitRegister {\n id: string\n name: string\n locationId?: string\n openShiftId: string | null\n}\n\n/** What the native app needs to take a card offline on its own reader (AGL-4039). */\nexport interface PosOfflineKitCard {\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The connected account the charge transfers to (a destination charge, as online). */\n destination: string\n currency: string\n /** The limit of one card sale rung offline, in cents: the store's, or Stripe's own ceiling when it set none. */\n maxSaleCents: number\n /** The limit of every card one device takes offline in a day, in cents; 0 is no daily limit. */\n maxDeviceDailyCents: number\n}\n\n/**\n * Everything a register needs to sell offline besides the catalog, from\n * `GET /api/commerce/pos-offline-sync?hostId=`: the server's own answers, so\n * the register and the sync agree about the rate and the rules.\n */\nexport interface PosOfflineKit {\n v: 1\n hostId: string\n orgId: string\n issuedAtMs: number\n /** Offline selling is possible for this site right now. */\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The store's own in-person rate; `null` pct is no tax. */\n tax: { pct: number | null; pricesIncludeTax: boolean }\n maxDiscountPct: number\n requireOpenShift: boolean\n registers: PosOfflineKitRegister[]\n /** Card sales on the app's own reader while offline; absent from a server that does not take them. */\n card?: PosOfflineKitCard\n /** What the receipt prints at its head and foot. `logo` is the stored value. */\n receipt: {\n name: string\n logo?: string\n address?: string\n footer?: string\n returnPolicy?: string\n }\n}\n\n/**\n * The totals of an offline sale: the cashier's discount on the goods, then\n * the store's in-person tax on what is left — exactly the arithmetic the\n * online register's sale route uses for the same basket with no promotion.\n * `pricesIncludeTax` adds nothing, as at the online till.\n */\nexport function posOfflineSaleTotals(input: {\n lines: ReadonlyArray<Pick<PosOfflineSaleLine, 'unitAmountCents' | 'quantity'>>\n discountPct: number\n tax: { pct: number | null; pricesIncludeTax: boolean }\n}): OrderTotals {\n const lines = input.lines.map((line) => ({\n unitAmountCents: wholeCents(line.unitAmountCents),\n quantity: Math.max(1, Math.round(Number(line.quantity) || 1)),\n }))\n const itemsCents = lines.reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n const pct = Number.isFinite(input.discountPct) ? Math.min(100, Math.max(0, input.discountPct)) : 0\n const discountCents = Math.min(itemsCents, Math.round((itemsCents * pct) / 100))\n const taxPct = Number(input.tax.pct)\n const taxCents =\n taxPct > 0 && !input.tax.pricesIncludeTax ? computeTaxCents(itemsCents - discountCents, taxPct) : 0\n return computeOrderTotals(lines as unknown as OrderLineItem[], { discountCents, taxCents, feeCents: 0 })\n}\n\n/** Change for cash handed over, never negative. */\nexport function posOfflineChangeCents(totalCents: number, tenderedCents: number): number {\n return Math.max(0, wholeCents(tenderedCents) - wholeCents(totalCents))\n}\n\n/** A key the register minted: an id the order can take, and nothing else. */\nexport function posOfflineSaleKeyIsValid(key: unknown): key is string {\n return typeof key === 'string' && /^[A-Za-z0-9_-]{16,64}$/.test(key) && !/^__.*__$/.test(key)\n}\n\n/**\n * The sale's time as the server records it: the device's clock when it is\n * believable, clamped to now when it runs ahead, and to the oldest believable\n * moment when it claims to be older.\n */\nexport function posOfflineSoldAt(\n soldAtMs: number,\n nowMs: number,\n): { atMs: number; adjusted: boolean } {\n const at = Number(soldAtMs)\n if (!Number.isFinite(at) || at <= 0) return { atMs: nowMs, adjusted: true }\n if (at > nowMs + POS_OFFLINE_CLOCK_SKEW_MS) return { atMs: nowMs, adjusted: true }\n if (at < nowMs - POS_OFFLINE_MAX_AGE_MS) return { atMs: nowMs, adjusted: true }\n return { atMs: Math.min(at, nowMs), adjusted: false }\n}\n\nconst bounded = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n\nconst cleanId = (value: unknown): string => {\n const id = String(value ?? '').trim()\n return /^[A-Za-z0-9_-]{1,128}$/.test(id) && !/^__.*__$/.test(id) ? id : ''\n}\n\nfunction wholeCents(value: unknown): number {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/**\n * A queued sale read off the wire, every field typed and bounded — or the\n * sentence that says why it cannot be read at all. Pure, so the server and\n * any client that wants to check its own queue answer the same.\n */\nexport function sanitizePosOfflineSale(\n raw: unknown,\n): { ok: true; sale: PosOfflineSale } | { ok: false; error: string } {\n if (!raw || typeof raw !== 'object') return { ok: false, error: 'Not a sale' }\n const input = raw as Record<string, any>\n const saleKey = input['saleKey']\n if (!posOfflineSaleKeyIsValid(saleKey)) return { ok: false, error: 'The sale has no valid key' }\n const hostId = cleanId(input['hostId'])\n const registerId = cleanId(input['registerId'])\n const signedInUid = bounded(input['signedInUid'], 128)\n if (!hostId || !registerId || !signedInUid) {\n return { ok: false, error: 'The sale is missing its site, register or member' }\n }\n const rawLines = Array.isArray(input['lines']) ? input['lines'] : []\n if (rawLines.length === 0 || rawLines.length > POS_OFFLINE_SALE_MAX_LINES) {\n return { ok: false, error: 'The sale has no lines' }\n }\n const lines: PosOfflineSaleLine[] = []\n for (const line of rawLines) {\n const productId = cleanId(line?.productId)\n const name = bounded(line?.name, 200)\n const unit = Math.round(Number(line?.unitAmountCents))\n const quantity = Math.round(Number(line?.quantity))\n if (!productId || !name || !Number.isFinite(unit) || unit < 0 || !(quantity >= 1 && quantity <= 99)) {\n return { ok: false, error: 'A line of the sale cannot be read' }\n }\n const variantId = cleanId(line?.variantId)\n const variantLabel = bounded(line?.variantLabel, 200)\n const sku = bounded(line?.sku, 100)\n const productType = ['physical', 'digital', 'service'].includes(line?.productType)\n ? (line.productType as PosOfflineSaleLine['productType'])\n : undefined\n const modifiers = Array.isArray(line?.modifiers)\n ? (line.modifiers as unknown[])\n .slice(0, 50)\n .map((pick: any) => ({ groupId: cleanId(pick?.groupId), optionId: cleanId(pick?.optionId) }))\n .filter((pick) => pick.groupId && pick.optionId)\n : []\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n name,\n ...(variantLabel ? { variantLabel } : {}),\n ...(sku ? { sku } : {}),\n ...(productType ? { productType } : {}),\n quantity,\n unitAmountCents: unit,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n const discountPct = Number(input['discountPct'] ?? 0)\n if (!Number.isFinite(discountPct) || discountPct < 0 || discountPct > 100) {\n return { ok: false, error: 'The sale’s discount cannot be read' }\n }\n const totals = (input['totals'] ?? {}) as Record<string, unknown>\n const customerRaw = input['customer']\n const customer: PosOfflineSaleCustomer = {}\n if (customerRaw && typeof customerRaw === 'object') {\n const email = bounded((customerRaw as any).email, 254).toLowerCase()\n if (email && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) customer.email = email\n const name = bounded((customerRaw as any).name, 200)\n if (name) customer.name = name\n const kind = bounded((customerRaw as any).kind, 40)\n const id = cleanId((customerRaw as any).id)\n if (kind && kind !== 'none' && id) {\n customer.kind = kind\n customer.id = id\n }\n }\n const shiftId = cleanId(input['shiftId'])\n const locationId = cleanId(input['locationId'])\n const assertion = bounded(input['cashierAssertion'], 2000)\n const orgId = bounded(input['orgId'], 128)\n let card: PosOfflineSaleCard | undefined\n if (input['tender'] === 'card') {\n const read = sanitizePosOfflineSaleCard(input['card'])\n if (!read) return { ok: false, error: 'The card of the sale cannot be read' }\n card = read\n }\n return {\n ok: true,\n sale: {\n v: 1,\n saleKey,\n hostId,\n orgId,\n signedInUid,\n registerId,\n shiftId: shiftId || null,\n ...(locationId ? { locationId } : {}),\n ...(assertion ? { cashierAssertion: assertion } : {}),\n soldAtMs: Number(input['soldAtMs']) || 0,\n lines,\n discountPct,\n totals: {\n itemsCents: wholeCents(totals['itemsCents']),\n shippingCents: 0,\n taxCents: wholeCents(totals['taxCents']),\n discountCents: wholeCents(totals['discountCents']),\n totalCents: wholeCents(totals['totalCents']),\n feeCents: 0,\n },\n cashTenderedCents: card ? 0 : wholeCents(input['cashTenderedCents']),\n changeCents: card ? 0 : wholeCents(input['changeCents']),\n ...(Object.keys(customer).length ? { customer } : {}),\n ...(card ? { tender: 'card' as const, card } : {}),\n },\n }\n}\n\n/**\n * Whether the register's totals are the arithmetic of its own lines: the\n * goods are the lines' sum, the discount is the percentage of them, and the\n * total is goods less discount plus the tax it rang. The tax itself is the\n * register's, and checked against the store's rate separately.\n */\nexport function posOfflineTotalsAddUp(sale: Pick<PosOfflineSale, 'lines' | 'discountPct' | 'totals'>): boolean {\n const expected = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: null, pricesIncludeTax: false },\n })\n return (\n expected.itemsCents === sale.totals.itemsCents &&\n expected.discountCents === sale.totals.discountCents &&\n sale.totals.taxCents <= sale.totals.itemsCents &&\n sale.totals.totalCents === expected.itemsCents - expected.discountCents + sale.totals.taxCents\n )\n}\n\n/** The flags in the order and words the register lists them. */\nexport function posOfflineFlagLabels(flags: readonly PosOfflineFlag[]): string[] {\n return flags.map((flag) => POS_OFFLINE_FLAG_LABELS[flag] ?? flag)\n}\n\nconst CARD_FORWARDS: readonly PosOfflineCardForward[] = ['stored', 'forwarded', 'declined', 'failed']\n\n/** The card side of a queued sale, typed and bounded, or `null` when it cannot be read. */\nexport function sanitizePosOfflineSaleCard(raw: unknown): PosOfflineSaleCard | null {\n if (!raw || typeof raw !== 'object') return null\n const input = raw as Record<string, unknown>\n const forward = input['forward'] as PosOfflineCardForward\n if (!CARD_FORWARDS.includes(forward)) return null\n const intent = typeof input['paymentIntentId'] === 'string' ? input['paymentIntentId'].trim() : ''\n if (intent && !/^pi_[A-Za-z0-9]{8,64}$/.test(intent)) return null\n if (forward === 'forwarded' && !intent) return null\n const brand = bounded(input['brand'], 24)\n const last4 = typeof input['last4'] === 'string' && /^\\d{4}$/.test(input['last4']) ? input['last4'] : ''\n const declineMessage = bounded(input['declineMessage'], 300)\n return {\n forward,\n ...(intent ? { paymentIntentId: intent } : {}),\n ...(brand ? { brand } : {}),\n ...(last4 ? { last4 } : {}),\n ...(declineMessage ? { declineMessage } : {}),\n }\n}\n\n/**\n * Why a card cannot be taken offline for `totalCents`, in the cashier's\n * words, or `null` when it can: the store has not turned it on, the sale is\n * over the store's (or Stripe's) limit per sale, or the cards this device\n * has taken offline today would pass the store's daily limit per device (a\n * daily limit of 0 is none: the store did not set one).\n */\nexport function posOfflineCardRefusal(input: {\n card: Pick<PosOfflineKitCard, 'available' | 'unavailableReason' | 'maxSaleCents' | 'maxDeviceDailyCents'> | null | undefined\n totalCents: number\n /** Every card this device took offline today, in cents. */\n takenTodayCents: number\n}): string | null {\n const card = input.card\n if (!card) return 'Card sales offline need the register to connect once first.'\n if (!card.available) return card.unavailableReason || 'Card sales offline are not turned on for this store.'\n const total = wholeCents(input.totalCents)\n if (total <= 0) return 'There is nothing to charge.'\n const perSale = Math.min(wholeCents(card.maxSaleCents), POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT)\n if (total > perSale) return `Offline, a card sale can be up to ${dollars(perSale)}. Take cash, or charge it when you are back online.`\n const today = wholeCents(input.takenTodayCents)\n const daily = wholeCents(card.maxDeviceDailyCents)\n if (daily > 0 && today + total > daily) {\n return `This device has taken ${dollars(today)} in cards offline today, and its daily limit is ${dollars(daily)}. Take cash, or wait for the connection.`\n }\n return null\n}\n\n/**\n * What the app writes on the PaymentIntent it creates for a card rung\n * offline: the sale key (the order's id once it syncs) and where it was rung,\n * so the server can match the charge to the sale even if the sale's own sync\n * never arrives.\n */\nexport function posOfflineCardIntentMetadata(\n sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'>,\n): Record<string, string> {\n return {\n kind: POS_OFFLINE_CARD_INTENT_KIND,\n saleKey: sale.saleKey,\n hostId: sale.hostId,\n orgId: sale.orgId,\n registerId: sale.registerId,\n }\n}\n\nfunction dollars(cents: number): string {\n const whole = Math.floor(cents / 100)\n const rest = cents % 100\n return `$${whole.toLocaleString('en-US')}.${String(rest).padStart(2, '0')}`\n}\n"],"names":["computeOrderTotals","computeTaxCents","POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT","POS_OFFLINE_SYNC_ROUTE","POS_OFFLINE_SYNC_BATCH_MAX","POS_OFFLINE_SALE_MAX_LINES","POS_OFFLINE_LATE_SYNC_MS","POS_OFFLINE_MAX_AGE_MS","POS_OFFLINE_CLOCK_SKEW_MS","POS_OFFLINE_CARD_RECONNECT_WITHIN_MS","POS_OFFLINE_CARD_INTENT_KIND","POS_OFFLINE_DISABLED_TENDERS","card_present","card_keyed","card_link","gift_card","folio","credit","POS_OFFLINE_FLAG_LABELS","posOfflineSaleTotals","input","lines","map","line","unitAmountCents","wholeCents","quantity","Math","max","round","Number","itemsCents","reduce","sum","pct","isFinite","discountPct","min","discountCents","taxPct","tax","taxCents","pricesIncludeTax","feeCents","posOfflineChangeCents","totalCents","tenderedCents","posOfflineSaleKeyIsValid","key","test","posOfflineSoldAt","soldAtMs","nowMs","at","atMs","adjusted","bounded","value","trim","slice","cleanId","id","String","number","sanitizePosOfflineSale","raw","ok","error","saleKey","hostId","registerId","signedInUid","rawLines","Array","isArray","length","productId","name","unit","variantId","variantLabel","sku","productType","includes","undefined","modifiers","pick","groupId","optionId","filter","push","totals","customerRaw","customer","email","toLowerCase","kind","shiftId","locationId","assertion","orgId","card","read","sanitizePosOfflineSaleCard","sale","v","cashierAssertion","shippingCents","cashTenderedCents","changeCents","Object","keys","tender","posOfflineTotalsAddUp","expected","posOfflineFlagLabels","flags","flag","CARD_FORWARDS","forward","intent","brand","last4","declineMessage","paymentIntentId","posOfflineCardRefusal","available","unavailableReason","total","perSale","maxSaleCents","dollars","today","takenTodayCents","daily","maxDeviceDailyCents","posOfflineCardIntentMetadata","cents","whole","floor","rest","toLocaleString","padStart"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAA8C,uBAAmB;AAC5F,SAASC,eAAe,QAAQ,oBAAgB;AAEhD,SAAS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AG,MAAM;AAC7E"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-offline.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 { computeOrderTotals, type OrderLineItem, type OrderTotals } from './commerce-orders'\nimport { computeTaxCents } from './commerce-tax'\nimport type { ModifierSelection } from './product-modifiers'\nimport { POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT } from './pos-offline-card-limits'\n\n/*==========================================\n * THE OFFLINE REGISTER (AGL-3625): the contract every register client — the\n * web register and the native Aglyn POS app — shares with\n * `POST /api/commerce/pos-offline-sync`.\n *\n * WHAT SELLS OFFLINE IS CASH, AND A CARD ON THE NATIVE APP'S OWN READER.\n *\n * - Cash, on every register client.\n * - A card, only on the native Aglyn POS app's own Stripe Terminal reader\n * (AGL-4039): Stripe's SDK stores the card on the device (\"store and\n * forward\") and forwards it once a connection returns. The app creates\n * the PaymentIntent itself with MANUAL capture and NO application fee:\n * a destination charge for a store on Aglyn's account, or, for a store on\n * its own Stripe account (direct charges), an intent made ON that account\n * (the connection token's) with no transfer at all (AGL-4219). The\n * server captures it when the sale syncs and\n * sizes the platform fee then, exactly as for an online card sale. A bank\n * can still decline it at that point, after the customer left: the order\n * is then recorded unpaid and flagged, and the register says so.\n * Off until the store turns it on, then within the store's two limits:\n * per sale, and per device per day (as Shopify POS words it).\n * - Every other card tender cannot: Tap to Pay on Android, the server's\n * smart readers, the typed card and the QR link are server-driven, and\n * Stripe does not take a server-driven card payment without the server.\n * - Gift cards DO NOT, deliberately. A balance cannot be checked without the\n * server, and a capped \"allow it anyway\" (Square's offer for cards) turns a\n * short balance into a sale whose money nobody collected — discovered at\n * sync, after the customer left. Square itself does not redeem gift cards\n * offline. A gift card is never over-redeemed silently because it is never\n * redeemed offline at all.\n * - Room charges do not: the stay is validated on the server.\n * - Store credit and rewards do not, for the gift card's reason: a balance\n * is the server's to check.\n * - Codes and store promotions do not: a redemption cap is counted on the\n * server. The cashier's own discount, bounded by the site's ceiling, does.\n *\n * WHAT THE SALE IS: the register prices the basket from its cached catalog and\n * the store's own tax rate, takes the cash and queues the sale with a key it\n * minted. That key is the order's id on the server, so the receipt printed\n * offline carries the barcode the real order answers to, and a sale sent twice\n * — a flapping connection, a retry after a lost answer — lands once.\n *\n * WHAT THE SERVER DOES WITH IT: records it as it happened, never re-prices the\n * money the customer handed over, and FLAGS what does not match — a price\n * that changed, stock that went short, a shift that closed first — on the\n * order and back to the register. A sale is never dropped for a flag.\n *=========================================*/\n\n/** The route both register clients sync through. */\nexport const POS_OFFLINE_SYNC_ROUTE = '/api/commerce/pos-offline-sync'\n\n/** The most sales one sync request carries; a longer queue sends in batches. */\nexport const POS_OFFLINE_SYNC_BATCH_MAX = 25\n\n/** Lines one offline sale may carry, the same bound the register's basket has. */\nexport const POS_OFFLINE_SALE_MAX_LINES = 100\n\n/** A sale synced later than this after it was rung is flagged `late-sync`. */\nexport const POS_OFFLINE_LATE_SYNC_MS = 24 * 60 * 60 * 1000\n\n/**\n * How far back a sale's own clock is believed. Older, and the server stamps\n * the sale at this bound and flags it, rather than letting a device clock\n * place a sale anywhere in history.\n */\nexport const POS_OFFLINE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000\n\n/** How far ahead of the server a device clock may run before it is clamped. */\nexport const POS_OFFLINE_CLOCK_SKEW_MS = 10 * 60 * 1000\n\n/** What an offline sale was paid with. A sale with no tender is cash (the shape before AGL-4039). */\nexport type PosOfflineTender = 'cash' | 'card'\n\nexport {\n POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT,\n POS_OFFLINE_CARD_RECONNECT_WITHIN_MS,\n} from './pos-offline-card-limits'\n\n/** The `metadata[kind]` of a PaymentIntent the app created for a card rung offline. */\nexport const POS_OFFLINE_CARD_INTENT_KIND = 'pos-offline'\n\n/**\n * Where a card rung offline stands. `stored`: on the device, not yet sent to\n * Stripe. `forwarded`: Stripe has it and it is authorized, waiting for the\n * sync to capture it. `declined`: the bank refused it when it was forwarded.\n * `failed`: Stripe could not take it at all (no PaymentIntent was made).\n */\nexport type PosOfflineCardForward = 'stored' | 'forwarded' | 'declined' | 'failed'\n\n/** The card side of a sale rung offline on the app's own reader. */\nexport interface PosOfflineSaleCard {\n forward: PosOfflineCardForward\n /** Stripe's PaymentIntent id, once the SDK forwarded it. */\n paymentIntentId?: string | null\n brand?: string\n last4?: string\n /** The bank's or Stripe's words for a decline or failure. */\n declineMessage?: string\n /**\n * The store's own Stripe account the device made the intent on, from the\n * kit it sold with (a direct charge, AGL-4219). Absent: a destination\n * charge made on the platform. The server reads the intent there, and\n * captures it only when it is still the store's account.\n */\n account?: string\n}\n\n/** Every tender the register turns off while offline, and why, in its words. */\nexport const POS_OFFLINE_DISABLED_TENDERS: Readonly<Record<string, string>> = {\n card_present: 'Card readers need the connection.',\n card_keyed: 'Typed cards need the connection.',\n card_link: 'The QR card link needs the connection.',\n gift_card: 'A gift card balance can only be checked online.',\n folio: 'Room charges are checked against the stay online.',\n credit: 'Store credit and rewards balances can only be checked online.',\n}\n\n/** One basket line as the register rang it. */\nexport interface PosOfflineSaleLine {\n productId: string\n variantId?: string\n name: string\n /** Variant options and modifier choices, as the receipt printed them. */\n variantLabel?: string\n sku?: string\n productType?: 'physical' | 'digital' | 'service'\n quantity: number\n /** Per unit, modifiers included, from the cached catalog. */\n unitAmountCents: number\n modifiers?: ModifierSelection[]\n}\n\n/** The customer the register attached: only what the sale and its receipt need. */\nexport interface PosOfflineSaleCustomer {\n email?: string\n name?: string\n kind?: string\n id?: string\n}\n\n/** One sale rung while offline, exactly as the register queued it. */\nexport interface PosOfflineSale {\n v: 1\n /** The register's key for this sale, minted once; the order's id on the server. */\n saleKey: string\n hostId: string\n /** The workspace the register was signed in to. */\n orgId: string\n /** Who was signed in on the device: the only member who may sync it. */\n signedInUid: string\n registerId: string\n /** The shift open on the register when the sale was rung. */\n shiftId?: string | null\n locationId?: string\n /** A PIN-switched cashier's assertion, valid when the sale was rung. */\n cashierAssertion?: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n lines: PosOfflineSaleLine[]\n /** The cashier's discount, a percentage of the goods. */\n discountPct: number\n /** The totals the receipt printed and the customer paid. */\n totals: OrderTotals\n /** Cash handed over; 0 for a card sale. */\n cashTenderedCents: number\n changeCents: number\n customer?: PosOfflineSaleCustomer\n /** `card` only on the native app's own reader (AGL-4039); absent means cash. */\n tender?: PosOfflineTender\n /** The card, when `tender` is `card`. */\n card?: PosOfflineSaleCard\n}\n\n/** What does not match, said on the order and back to the register. */\nexport type PosOfflineFlag =\n | 'price-changed'\n | 'unknown-product'\n | 'tax-differs'\n | 'totals-restated'\n | 'discount-over-limit'\n | 'discount-not-permitted'\n | 'cash-short'\n | 'stock-short'\n | 'shift-closed'\n | 'no-shift'\n | 'unknown-register'\n | 'register-over-cap'\n | 'late-sync'\n | 'clock-adjusted'\n | 'cashier-unverified'\n | 'card-declined'\n | 'card-not-charged'\n | 'card-amount-differs'\n | 'card-fee-short'\n\n/** Each flag in the words the order and the register show. */\nexport const POS_OFFLINE_FLAG_LABELS: Record<PosOfflineFlag, string> = {\n 'price-changed': 'A price changed after the register cached it; the sale kept the price it was rung at',\n 'unknown-product': 'A product was deleted before the sale synced; the line kept what the receipt printed',\n 'tax-differs': 'The tax rung differs from the store’s rate now; the sale kept the tax it collected',\n 'totals-restated': 'The register’s totals did not add up; the server restated them from the lines',\n 'discount-over-limit': 'The discount is above this register’s limit',\n // Names the permission by its label in `plugin-permissions.ts` (AGL-4047);\n // `pos-offline-sync.spec.ts` holds the two to the same words.\n 'discount-not-permitted': 'The discount was given by a member whose role does not include “Give discounts at the register”',\n 'cash-short': 'The cash recorded is less than the total',\n 'stock-short': 'Stock went short: more was sold than the shelf held',\n 'shift-closed': 'Rung in a shift that closed before the sale synced; its Z report does not include it',\n 'no-shift': 'Rung with no shift open, on a site that requires one',\n 'unknown-register': 'The register it was rung on no longer exists',\n 'register-over-cap': 'The register it was rung on is over the plan’s register limit',\n 'late-sync': 'Synced more than a day after it was rung',\n 'clock-adjusted': 'The device clock was off; the sale is dated when it synced',\n 'cashier-unverified': 'The PIN-switched cashier could not be confirmed; the sale is under the signed-in member',\n 'card-declined': 'The card taken offline was declined when it was charged; the order is unpaid',\n 'card-not-charged': 'The card taken offline could not be charged; the order is unpaid',\n 'card-amount-differs': 'The card was charged a different amount than the sale’s total; the payment records what Stripe took',\n 'card-fee-short': 'Stripe took less than the platform fee from this card’s payout; the rest goes on the workspace’s monthly invoice',\n}\n\n/** A line whose stock went short when the sale synced. */\nexport interface PosOfflineStockConflict {\n productId: string\n variantId?: string\n name: string\n /** Units sold. */\n requested: number\n /** Units the shelf actually gave up. */\n applied: number\n /** Units sold that the shelf did not hold. */\n shortUnits: number\n}\n\n/** What the order records about having been rung offline. */\nexport interface PosOfflineOrderStamp {\n saleKey: string\n /** The device's clock when the cash was taken. */\n soldAtMs: number\n syncedAtMs: number\n /** Who synced it: always the member who was signed in when it was rung. */\n syncedBy: string\n flags: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n /** The server's own price per line where it differed, for the merchant to compare. */\n priceDrift?: Array<{ index: number; rungCents: number; currentCents: number }>\n}\n\n/** Why a sale was refused, and whether the register should keep trying. */\nexport type PosOfflineRefusal =\n | 'wrong-staff'\n | 'wrong-site'\n | 'wrong-workspace'\n | 'invalid'\n | 'conflict'\n | 'failed'\n\n/** What became of one sale the register sent. */\nexport type PosOfflineOutcomeStatus = 'recorded' | 'replayed' | 'refused'\n\n/**\n * One sale's answer, in the order the request sent them. `recorded` and\n * `replayed` carry the order; `refused` carries the reason, the sentence and\n * whether to keep trying. One flat shape, so every register client — the web\n * register and the native apps — decodes it the same way.\n */\nexport interface PosOfflineSaleOutcome {\n saleKey: string\n status: PosOfflineOutcomeStatus\n orderId?: string\n number?: number | null\n flags?: PosOfflineFlag[]\n stockConflicts?: PosOfflineStockConflict[]\n reason?: PosOfflineRefusal\n error?: string\n /** Keep it queued and try again later (a transient failure). */\n retry?: boolean\n}\n\nexport interface PosOfflineSyncRequest {\n hostId: string\n sales: PosOfflineSale[]\n}\n\nexport interface PosOfflineSyncResponse {\n results: PosOfflineSaleOutcome[]\n}\n\n/** One register as the offline kit lists it. */\nexport interface PosOfflineKitRegister {\n id: string\n name: string\n locationId?: string\n openShiftId: string | null\n}\n\n/** What the native app needs to take a card offline on its own reader (AGL-4039). */\nexport interface PosOfflineKitCard {\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The connected account the charge transfers to (a destination charge, as online); '' for a direct charge. */\n destination: string\n /**\n * Set for a store on its own Stripe account (direct charges, AGL-4219):\n * the device makes the intent with no transfer and no destination, on the\n * account its connection token belongs to, which is this one. Offered only\n * to an app that says it can (`cardChargeModels=direct` on the kit's GET).\n */\n account?: string\n currency: string\n /** The limit of one card sale rung offline, in cents: the store's, or Stripe's own ceiling when it set none. */\n maxSaleCents: number\n /** The limit of every card one device takes offline in a day, in cents; 0 is no daily limit. */\n maxDeviceDailyCents: number\n}\n\n/**\n * Everything a register needs to sell offline besides the catalog, from\n * `GET /api/commerce/pos-offline-sync?hostId=`: the server's own answers, so\n * the register and the sync agree about the rate and the rules.\n */\nexport interface PosOfflineKit {\n v: 1\n hostId: string\n orgId: string\n issuedAtMs: number\n /** Offline selling is possible for this site right now. */\n available: boolean\n /** Why not, in the cashier's words, when it is not. */\n unavailableReason?: string\n /** The store's own in-person rate; `null` pct is no tax. */\n tax: { pct: number | null; pricesIncludeTax: boolean }\n maxDiscountPct: number\n requireOpenShift: boolean\n registers: PosOfflineKitRegister[]\n /** Card sales on the app's own reader while offline; absent from a server that does not take them. */\n card?: PosOfflineKitCard\n /** What the receipt prints at its head and foot. `logo` is the stored value. */\n receipt: {\n name: string\n logo?: string\n address?: string\n footer?: string\n returnPolicy?: string\n }\n}\n\n/**\n * The totals of an offline sale: the cashier's discount on the goods, then\n * the store's in-person tax on what is left — exactly the arithmetic the\n * online register's sale route uses for the same basket with no promotion.\n * `pricesIncludeTax` adds nothing, as at the online till.\n */\nexport function posOfflineSaleTotals(input: {\n lines: ReadonlyArray<Pick<PosOfflineSaleLine, 'unitAmountCents' | 'quantity'>>\n discountPct: number\n tax: { pct: number | null; pricesIncludeTax: boolean }\n}): OrderTotals {\n const lines = input.lines.map((line) => ({\n unitAmountCents: wholeCents(line.unitAmountCents),\n quantity: Math.max(1, Math.round(Number(line.quantity) || 1)),\n }))\n const itemsCents = lines.reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n const pct = Number.isFinite(input.discountPct) ? Math.min(100, Math.max(0, input.discountPct)) : 0\n const discountCents = Math.min(itemsCents, Math.round((itemsCents * pct) / 100))\n const taxPct = Number(input.tax.pct)\n const taxCents =\n taxPct > 0 && !input.tax.pricesIncludeTax ? computeTaxCents(itemsCents - discountCents, taxPct) : 0\n return computeOrderTotals(lines as unknown as OrderLineItem[], { discountCents, taxCents, feeCents: 0 })\n}\n\n/** Change for cash handed over, never negative. */\nexport function posOfflineChangeCents(totalCents: number, tenderedCents: number): number {\n return Math.max(0, wholeCents(tenderedCents) - wholeCents(totalCents))\n}\n\n/** A key the register minted: an id the order can take, and nothing else. */\nexport function posOfflineSaleKeyIsValid(key: unknown): key is string {\n return typeof key === 'string' && /^[A-Za-z0-9_-]{16,64}$/.test(key) && !/^__.*__$/.test(key)\n}\n\n/**\n * The sale's time as the server records it: the device's clock when it is\n * believable, clamped to now when it runs ahead, and to the oldest believable\n * moment when it claims to be older.\n */\nexport function posOfflineSoldAt(\n soldAtMs: number,\n nowMs: number,\n): { atMs: number; adjusted: boolean } {\n const at = Number(soldAtMs)\n if (!Number.isFinite(at) || at <= 0) return { atMs: nowMs, adjusted: true }\n if (at > nowMs + POS_OFFLINE_CLOCK_SKEW_MS) return { atMs: nowMs, adjusted: true }\n if (at < nowMs - POS_OFFLINE_MAX_AGE_MS) return { atMs: nowMs, adjusted: true }\n return { atMs: Math.min(at, nowMs), adjusted: false }\n}\n\nconst bounded = (value: unknown, max: number): string =>\n typeof value === 'string' ? value.trim().slice(0, max) : ''\n\nconst cleanId = (value: unknown): string => {\n const id = String(value ?? '').trim()\n return /^[A-Za-z0-9_-]{1,128}$/.test(id) && !/^__.*__$/.test(id) ? id : ''\n}\n\nfunction wholeCents(value: unknown): number {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\n/**\n * A queued sale read off the wire, every field typed and bounded — or the\n * sentence that says why it cannot be read at all. Pure, so the server and\n * any client that wants to check its own queue answer the same.\n */\nexport function sanitizePosOfflineSale(\n raw: unknown,\n): { ok: true; sale: PosOfflineSale } | { ok: false; error: string } {\n if (!raw || typeof raw !== 'object') return { ok: false, error: 'Not a sale' }\n const input = raw as Record<string, any>\n const saleKey = input['saleKey']\n if (!posOfflineSaleKeyIsValid(saleKey)) return { ok: false, error: 'The sale has no valid key' }\n const hostId = cleanId(input['hostId'])\n const registerId = cleanId(input['registerId'])\n const signedInUid = bounded(input['signedInUid'], 128)\n if (!hostId || !registerId || !signedInUid) {\n return { ok: false, error: 'The sale is missing its site, register or member' }\n }\n const rawLines = Array.isArray(input['lines']) ? input['lines'] : []\n if (rawLines.length === 0 || rawLines.length > POS_OFFLINE_SALE_MAX_LINES) {\n return { ok: false, error: 'The sale has no lines' }\n }\n const lines: PosOfflineSaleLine[] = []\n for (const line of rawLines) {\n const productId = cleanId(line?.productId)\n const name = bounded(line?.name, 200)\n const unit = Math.round(Number(line?.unitAmountCents))\n const quantity = Math.round(Number(line?.quantity))\n if (!productId || !name || !Number.isFinite(unit) || unit < 0 || !(quantity >= 1 && quantity <= 99)) {\n return { ok: false, error: 'A line of the sale cannot be read' }\n }\n const variantId = cleanId(line?.variantId)\n const variantLabel = bounded(line?.variantLabel, 200)\n const sku = bounded(line?.sku, 100)\n const productType = ['physical', 'digital', 'service'].includes(line?.productType)\n ? (line.productType as PosOfflineSaleLine['productType'])\n : undefined\n const modifiers = Array.isArray(line?.modifiers)\n ? (line.modifiers as unknown[])\n .slice(0, 50)\n .map((pick: any) => ({ groupId: cleanId(pick?.groupId), optionId: cleanId(pick?.optionId) }))\n .filter((pick) => pick.groupId && pick.optionId)\n : []\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n name,\n ...(variantLabel ? { variantLabel } : {}),\n ...(sku ? { sku } : {}),\n ...(productType ? { productType } : {}),\n quantity,\n unitAmountCents: unit,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n const discountPct = Number(input['discountPct'] ?? 0)\n if (!Number.isFinite(discountPct) || discountPct < 0 || discountPct > 100) {\n return { ok: false, error: 'The sale’s discount cannot be read' }\n }\n const totals = (input['totals'] ?? {}) as Record<string, unknown>\n const customerRaw = input['customer']\n const customer: PosOfflineSaleCustomer = {}\n if (customerRaw && typeof customerRaw === 'object') {\n const email = bounded((customerRaw as any).email, 254).toLowerCase()\n if (email && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)) customer.email = email\n const name = bounded((customerRaw as any).name, 200)\n if (name) customer.name = name\n const kind = bounded((customerRaw as any).kind, 40)\n const id = cleanId((customerRaw as any).id)\n if (kind && kind !== 'none' && id) {\n customer.kind = kind\n customer.id = id\n }\n }\n const shiftId = cleanId(input['shiftId'])\n const locationId = cleanId(input['locationId'])\n const assertion = bounded(input['cashierAssertion'], 2000)\n const orgId = bounded(input['orgId'], 128)\n let card: PosOfflineSaleCard | undefined\n if (input['tender'] === 'card') {\n const read = sanitizePosOfflineSaleCard(input['card'])\n if (!read) return { ok: false, error: 'The card of the sale cannot be read' }\n card = read\n }\n return {\n ok: true,\n sale: {\n v: 1,\n saleKey,\n hostId,\n orgId,\n signedInUid,\n registerId,\n shiftId: shiftId || null,\n ...(locationId ? { locationId } : {}),\n ...(assertion ? { cashierAssertion: assertion } : {}),\n soldAtMs: Number(input['soldAtMs']) || 0,\n lines,\n discountPct,\n totals: {\n itemsCents: wholeCents(totals['itemsCents']),\n shippingCents: 0,\n taxCents: wholeCents(totals['taxCents']),\n discountCents: wholeCents(totals['discountCents']),\n totalCents: wholeCents(totals['totalCents']),\n feeCents: 0,\n },\n cashTenderedCents: card ? 0 : wholeCents(input['cashTenderedCents']),\n changeCents: card ? 0 : wholeCents(input['changeCents']),\n ...(Object.keys(customer).length ? { customer } : {}),\n ...(card ? { tender: 'card' as const, card } : {}),\n },\n }\n}\n\n/**\n * Whether the register's totals are the arithmetic of its own lines: the\n * goods are the lines' sum, the discount is the percentage of them, and the\n * total is goods less discount plus the tax it rang. The tax itself is the\n * register's, and checked against the store's rate separately.\n */\nexport function posOfflineTotalsAddUp(sale: Pick<PosOfflineSale, 'lines' | 'discountPct' | 'totals'>): boolean {\n const expected = posOfflineSaleTotals({\n lines: sale.lines,\n discountPct: sale.discountPct,\n tax: { pct: null, pricesIncludeTax: false },\n })\n return (\n expected.itemsCents === sale.totals.itemsCents &&\n expected.discountCents === sale.totals.discountCents &&\n sale.totals.taxCents <= sale.totals.itemsCents &&\n sale.totals.totalCents === expected.itemsCents - expected.discountCents + sale.totals.taxCents\n )\n}\n\n/** The flags in the order and words the register lists them. */\nexport function posOfflineFlagLabels(flags: readonly PosOfflineFlag[]): string[] {\n return flags.map((flag) => POS_OFFLINE_FLAG_LABELS[flag] ?? flag)\n}\n\n/** A Stripe account id as Stripe mints them. */\nconst POS_OFFLINE_CARD_ACCOUNT = /^acct_[A-Za-z0-9]{8,64}$/\n\nconst CARD_FORWARDS: readonly PosOfflineCardForward[] = ['stored', 'forwarded', 'declined', 'failed']\n\n/** The card side of a queued sale, typed and bounded, or `null` when it cannot be read. */\nexport function sanitizePosOfflineSaleCard(raw: unknown): PosOfflineSaleCard | null {\n if (!raw || typeof raw !== 'object') return null\n const input = raw as Record<string, unknown>\n const forward = input['forward'] as PosOfflineCardForward\n if (!CARD_FORWARDS.includes(forward)) return null\n const intent = typeof input['paymentIntentId'] === 'string' ? input['paymentIntentId'].trim() : ''\n if (intent && !/^pi_[A-Za-z0-9]{8,64}$/.test(intent)) return null\n if (forward === 'forwarded' && !intent) return null\n const brand = bounded(input['brand'], 24)\n const last4 = typeof input['last4'] === 'string' && /^\\d{4}$/.test(input['last4']) ? input['last4'] : ''\n const declineMessage = bounded(input['declineMessage'], 300)\n const account = typeof input['account'] === 'string' ? input['account'].trim() : ''\n if (account && !POS_OFFLINE_CARD_ACCOUNT.test(account)) return null\n return {\n forward,\n ...(intent ? { paymentIntentId: intent } : {}),\n ...(brand ? { brand } : {}),\n ...(last4 ? { last4 } : {}),\n ...(declineMessage ? { declineMessage } : {}),\n ...(account ? { account } : {}),\n }\n}\n\n/**\n * Why a card cannot be taken offline for `totalCents`, in the cashier's\n * words, or `null` when it can: the store has not turned it on, the sale is\n * over the store's (or Stripe's) limit per sale, or the cards this device\n * has taken offline today would pass the store's daily limit per device (a\n * daily limit of 0 is none: the store did not set one).\n */\nexport function posOfflineCardRefusal(input: {\n card: Pick<PosOfflineKitCard, 'available' | 'unavailableReason' | 'maxSaleCents' | 'maxDeviceDailyCents'> | null | undefined\n totalCents: number\n /** Every card this device took offline today, in cents. */\n takenTodayCents: number\n}): string | null {\n const card = input.card\n if (!card) return 'Card sales offline need the register to connect once first.'\n if (!card.available) return card.unavailableReason || 'Card sales offline are not turned on for this store.'\n const total = wholeCents(input.totalCents)\n if (total <= 0) return 'There is nothing to charge.'\n const perSale = Math.min(wholeCents(card.maxSaleCents), POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT)\n if (total > perSale) return `Offline, a card sale can be up to ${dollars(perSale)}. Take cash, or charge it when you are back online.`\n const today = wholeCents(input.takenTodayCents)\n const daily = wholeCents(card.maxDeviceDailyCents)\n if (daily > 0 && today + total > daily) {\n return `This device has taken ${dollars(today)} in cards offline today, and its daily limit is ${dollars(daily)}. Take cash, or wait for the connection.`\n }\n return null\n}\n\n/**\n * What the app writes on the PaymentIntent it creates for a card rung\n * offline: the sale key (the order's id once it syncs) and where it was rung,\n * so the server can match the charge to the sale even if the sale's own sync\n * never arrives. An intent made on the store's own account (`direct`,\n * AGL-4219) also says `chargeModel: direct`, as every direct sale's objects\n * do, so its Connect-delivered events are read as the store's own.\n */\nexport function posOfflineCardIntentMetadata(\n sale: Pick<PosOfflineSale, 'saleKey' | 'hostId' | 'orgId' | 'registerId'> & { direct?: boolean },\n): Record<string, string> {\n return {\n kind: POS_OFFLINE_CARD_INTENT_KIND,\n saleKey: sale.saleKey,\n hostId: sale.hostId,\n orgId: sale.orgId,\n registerId: sale.registerId,\n ...(sale.direct ? { chargeModel: 'direct' } : {}),\n }\n}\n\nfunction dollars(cents: number): string {\n const whole = Math.floor(cents / 100)\n const rest = cents % 100\n return `$${whole.toLocaleString('en-US')}.${String(rest).padStart(2, '0')}`\n}\n"],"names":["computeOrderTotals","computeTaxCents","POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT","POS_OFFLINE_SYNC_ROUTE","POS_OFFLINE_SYNC_BATCH_MAX","POS_OFFLINE_SALE_MAX_LINES","POS_OFFLINE_LATE_SYNC_MS","POS_OFFLINE_MAX_AGE_MS","POS_OFFLINE_CLOCK_SKEW_MS","POS_OFFLINE_CARD_RECONNECT_WITHIN_MS","POS_OFFLINE_CARD_INTENT_KIND","POS_OFFLINE_DISABLED_TENDERS","card_present","card_keyed","card_link","gift_card","folio","credit","POS_OFFLINE_FLAG_LABELS","posOfflineSaleTotals","input","lines","map","line","unitAmountCents","wholeCents","quantity","Math","max","round","Number","itemsCents","reduce","sum","pct","isFinite","discountPct","min","discountCents","taxPct","tax","taxCents","pricesIncludeTax","feeCents","posOfflineChangeCents","totalCents","tenderedCents","posOfflineSaleKeyIsValid","key","test","posOfflineSoldAt","soldAtMs","nowMs","at","atMs","adjusted","bounded","value","trim","slice","cleanId","id","String","number","sanitizePosOfflineSale","raw","ok","error","saleKey","hostId","registerId","signedInUid","rawLines","Array","isArray","length","productId","name","unit","variantId","variantLabel","sku","productType","includes","undefined","modifiers","pick","groupId","optionId","filter","push","totals","customerRaw","customer","email","toLowerCase","kind","shiftId","locationId","assertion","orgId","card","read","sanitizePosOfflineSaleCard","sale","v","cashierAssertion","shippingCents","cashTenderedCents","changeCents","Object","keys","tender","posOfflineTotalsAddUp","expected","posOfflineFlagLabels","flags","flag","POS_OFFLINE_CARD_ACCOUNT","CARD_FORWARDS","forward","intent","brand","last4","declineMessage","account","paymentIntentId","posOfflineCardRefusal","available","unavailableReason","total","perSale","maxSaleCents","dollars","today","takenTodayCents","daily","maxDeviceDailyCents","posOfflineCardIntentMetadata","direct","chargeModel","cents","whole","floor","rest","toLocaleString","padStart"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,QAA8C,uBAAmB;AAC5F,SAASC,eAAe,QAAQ,oBAAgB;AAEhD,SAASC,qCAAqC,QAAQ,+BAA2B;AAEjF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA8C2C,GAE3C,kDAAkD,GAClD,OAAO,MAAMC,yBAAyB,iCAAgC;AAEtE,8EAA8E,GAC9E,OAAO,MAAMC,6BAA6B,GAAE;AAE5C,gFAAgF,GAChF,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,4EAA4E,GAC5E,OAAO,MAAMC,2BAA2B,KAAK,KAAK,KAAK,KAAI;AAE3D;;;;CAIC,GACD,OAAO,MAAMC,yBAAyB,KAAK,KAAK,KAAK,KAAK,KAAI;AAE9D,6EAA6E,GAC7E,OAAO,MAAMC,4BAA4B,KAAK,KAAK,KAAI;AAKvD,SACEN,qCAAqC,EACrCO,oCAAoC,QAC/B,+BAA2B;AAElC,qFAAqF,GACrF,OAAO,MAAMC,+BAA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B,KAAK4B,iBAAiB,IAAI;IACtD,MAAMC,QAAQzG,WAAWL,MAAMyB,UAAU;IACzC,IAAIqF,SAAS,GAAG,OAAO;IACvB,MAAMC,UAAUxG,KAAKU,GAAG,CAACZ,WAAW4E,KAAK+B,YAAY,GAAGlI;IACxD,IAAIgI,QAAQC,SAAS,OAAO,CAAC,kCAAkC,EAAEE,QAAQF,SAAS,mDAAmD,CAAC;IACtI,MAAMG,QAAQ7G,WAAWL,MAAMmH,eAAe;IAC9C,MAAMC,QAAQ/G,WAAW4E,KAAKoC,mBAAmB;IACjD,IAAID,QAAQ,KAAKF,QAAQJ,QAAQM,OAAO;QACtC,OAAO,CAAC,sBAAsB,EAAEH,QAAQC,OAAO,gDAAgD,EAAED,QAAQG,OAAO,wCAAwC,CAAC;IAC3J;IACA,OAAO;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,SAASE,6BACdlC,IAAgG;IAEhG,OAAO;QACLR,MAAMtF;QACN0D,SAASoC,KAAKpC,OAAO;QACrBC,QAAQmC,KAAKnC,MAAM;QACnB+B,OAAOI,KAAKJ,KAAK;QACjB9B,YAAYkC,KAAKlC,UAAU;OACvBkC,KAAKmC,MAAM,GAAG;QAAEC,aAAa;IAAS,IAAI,CAAC;AAEnD;AAEA,SAASP,QAAQQ,KAAa;IAC5B,MAAMC,QAAQnH,KAAKoH,KAAK,CAACF,QAAQ;IACjC,MAAMG,OAAOH,QAAQ;IACrB,OAAO,CAAC,CAAC,EAAEC,MAAMG,cAAc,CAAC,SAAS,CAAC,EAAEnF,OAAOkF,MAAME,QAAQ,CAAC,GAAG,MAAM;AAC7E"}
|
|
@@ -28,6 +28,8 @@ export type PosOfflineCardSettled = {
|
|
|
28
28
|
/** The card tender's share of the plan's take. */
|
|
29
29
|
takeShareCents: number;
|
|
30
30
|
livemode: boolean;
|
|
31
|
+
/** The store's own account the intent was made and captured on (a direct charge); absent for a destination one. */
|
|
32
|
+
account?: string;
|
|
31
33
|
brand?: string;
|
|
32
34
|
last4?: string;
|
|
33
35
|
} | {
|
|
@@ -65,6 +65,10 @@ export function posOfflineCardOrderMoney(input) {
|
|
|
65
65
|
if (shortfallCents > 0) flags.push('card-fee-short');
|
|
66
66
|
const invoiceCents = feeOrgId ? shortfallCents : 0;
|
|
67
67
|
const feeCents = nettedCents + invoiceCents;
|
|
68
|
+
const direct = settled.account ? {
|
|
69
|
+
chargeModel: 'direct',
|
|
70
|
+
stripeAccountId: settled.account
|
|
71
|
+
} : {};
|
|
68
72
|
return {
|
|
69
73
|
status: 'paid',
|
|
70
74
|
totals: _extends({}, input.totals, {
|
|
@@ -80,10 +84,10 @@ export function posOfflineCardOrderMoney(input) {
|
|
|
80
84
|
takeFeeCents: whole(settled.takeShareCents),
|
|
81
85
|
feeCents: nettedCents,
|
|
82
86
|
livemode: settled.livemode
|
|
83
|
-
}, card, {
|
|
87
|
+
}, card, direct, {
|
|
84
88
|
cashierId
|
|
85
89
|
}),
|
|
86
|
-
fields: _extends({}, feeCents > 0 ? {
|
|
90
|
+
fields: _extends({}, direct, feeCents > 0 ? {
|
|
87
91
|
feeCollection: invoiceCents > 0 ? nettedCents > 0 ? 'split' : 'invoice' : 'payout'
|
|
88
92
|
} : {}, {
|
|
89
93
|
paymentIntentId: settled.intentId,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-card-order.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 type { OrderPayment, OrderTotals } from '../model'\nimport type { PosOfflineFlag } from '../model/commerce-pos-offline'\n\n/*==========================================\n * THE MONEY ON AN ORDER FOR A CARD TAKEN OFFLINE (AGL-4039).\n *\n * Pure: the offline sync settles the card with Stripe first, then hands the\n * result here and writes what comes back in the transaction that creates the\n * order. Kept out of `pos-offline-sync.ts` so the refund, dispute and\n * register-collection specs can build an order exactly as the sync writes it\n * without loading the sync's Firestore and Stripe dependencies.\n *\n * What a CAPTURED card writes, and why each field:\n *\n * - `paymentIntentId`, `paymentIntentIds` and `paidAtMs` at the ORDER level,\n * as the online register's completion writes them (`posCompletionPatch`).\n * The refund route and the dispute lookup read the order-level fields; an\n * intent kept only inside `payments[0]` leaves the order unrefundable and\n * its chargeback matched to no order.\n * - The payment's `amountCents` is what Stripe took (`intent.amount`), not\n * the server's restated total. Where they differ the order is flagged\n * `card-amount-differs` for the merchant to check against the receipt.\n * - `totals.feeCents` is the whole fee the sale settled: the card's\n * `application_fee_amount` (the take share plus Stripe's processing cost)\n * as the online completion counts it, plus any shortfall invoiced below.\n * - A FEE SHORTFALL: an intent the server first meets already `succeeded`\n * (captured on the device, with no application fee) netted less than the\n * tender rule's fee from the payout. The difference accrues to the org's\n * month ledger (`orgs/{id}/offlineFees`), the same ledger a room charge's\n * take accrues to, and the order is flagged `card-fee-short`.\n *\n * What an UNPAID card writes: `status: 'pending'` with the failed payment,\n * and the sale's plan take on `posTakeFeeCents` with the org it accrues to.\n * Collecting it later at the register reads that take, exactly as an open\n * sale does, so a later card, room charge or cash collection is charged by\n * the same tender rule as any other sale.\n *=========================================*/\n\nexport type PosOfflineCardSettled =\n | {\n kind: 'captured'\n intentId: string\n /** What Stripe charged, `intent.amount`. */\n amountCents: number\n /** What Stripe kept for the platform, `intent.application_fee_amount`. */\n feeCents: number\n /** What the tender rule says the platform's fee is on this charge. */\n expectedFeeCents: number\n /** The card tender's share of the plan's take. */\n takeShareCents: number\n livemode: boolean\n brand?: string\n last4?: string\n }\n | {\n kind: 'unpaid'\n flag: 'card-declined' | 'card-not-charged'\n intentId?: string\n message: string\n brand?: string\n last4?: string\n }\n\nexport interface PosOfflineCardOrderMoney {\n status: 'paid' | 'pending'\n /** The server's totals with the fee the sale settled. */\n totals: OrderTotals\n payment: OrderPayment\n /** Written at the order's top level beside the payment. */\n fields: Record<string, unknown>\n /** Cents to accrue to the org's month ledger with the order, 0 for none. */\n invoiceCents: number\n /** What the money adds to the sale's flags. */\n flags: PosOfflineFlag[]\n}\n\nconst whole = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\nexport function posOfflineCardOrderMoney(input: {\n settled: PosOfflineCardSettled\n /** The server's totals for the sale, restated where the register's did not add up. */\n totals: OrderTotals\n /** The plan's take on the goods, before the tender rule. */\n planTakeCents: number\n soldAtMs: number\n nowMs: number\n cashierId: string\n /** The org the fees accrue to; '' when the site has none, and nothing accrues. */\n feeOrgId: string\n}): PosOfflineCardOrderMoney {\n const { settled, soldAtMs, nowMs, cashierId, feeOrgId } = input\n const card = {\n ...(settled.intentId ? { paymentIntentId: settled.intentId } : {}),\n ...(settled.brand ? { cardBrand: settled.brand } : {}),\n ...(settled.last4 ? { last4: settled.last4 } : {}),\n }\n if (settled.kind === 'unpaid') {\n const planTakeCents = whole(input.planTakeCents)\n return {\n status: 'pending',\n totals: { ...input.totals, feeCents: 0 },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents: whole(input.totals.totalCents),\n status: 'failed',\n atMs: soldAtMs,\n takeFeeCents: 0,\n feeCents: 0,\n failureMessage: settled.message.slice(0, 300),\n ...card,\n cashierId,\n },\n fields: {\n posTakeFeeCents: planTakeCents,\n ...(feeOrgId ? { posFeeOrgId: feeOrgId } : {}),\n },\n invoiceCents: 0,\n flags: [settled.flag],\n }\n }\n const flags: PosOfflineFlag[] = []\n const amountCents = whole(settled.amountCents)\n if (amountCents !== whole(input.totals.totalCents)) flags.push('card-amount-differs')\n const nettedCents = whole(settled.feeCents)\n const shortfallCents = Math.max(0, whole(settled.expectedFeeCents) - nettedCents)\n if (shortfallCents > 0) flags.push('card-fee-short')\n const invoiceCents = feeOrgId ? shortfallCents : 0\n const feeCents = nettedCents + invoiceCents\n return {\n status: 'paid',\n totals: { ...input.totals, feeCents },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents,\n status: 'succeeded',\n atMs: soldAtMs,\n settledAtMs: nowMs,\n takeFeeCents: whole(settled.takeShareCents),\n feeCents: nettedCents,\n livemode: settled.livemode,\n ...card,\n cashierId,\n },\n fields: {\n ...(feeCents > 0\n ? { feeCollection: invoiceCents > 0 ? (nettedCents > 0 ? 'split' : 'invoice') : 'payout' }\n : {}),\n paymentIntentId: settled.intentId,\n paymentIntentIds: [settled.intentId],\n paidAtMs: soldAtMs,\n ...(settled.livemode === false ? { livemode: false } : {}),\n },\n invoiceCents,\n flags,\n }\n}\n"],"names":["whole","value","number","Math","round","Number","isFinite","posOfflineCardOrderMoney","input","settled","soldAtMs","nowMs","cashierId","feeOrgId","card","intentId","paymentIntentId","brand","cardBrand","last4","kind","planTakeCents","status","totals","feeCents","payment","id","method","amountCents","totalCents","atMs","takeFeeCents","failureMessage","message","slice","fields","posTakeFeeCents","posFeeOrgId","invoiceCents","flags","flag","push","nettedCents","shortfallCents","max","expectedFeeCents","settledAtMs","takeShareCents","livemode","feeCollection","paymentIntentIds","paidAtMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AA8ED,MAAMA,QAAQ,CAACC;IACb,MAAMC,SAASC,KAAKC,KAAK,CAACC,OAAOJ;IACjC,OAAOI,OAAOC,QAAQ,CAACJ,WAAWA,SAAS,IAAIA,SAAS;AAC1D;AAEA,OAAO,SAASK,yBAAyBC,KAWxC;IACC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,EAAE,GAAGL;IAC1D,MAAMM,OAAO,aACPL,QAAQM,QAAQ,GAAG;QAAEC,iBAAiBP,QAAQM,QAAQ;IAAC,IAAI,CAA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;YACNoC,aAAanC;YACboB,cAAc/B,MAAMS,QAAQsC,cAAc;YAC1CvB,UAAUkB;YACVM,UAAUvC,QAAQuC,QAAQ;WACvBlC;YACHF;;QAEFuB,QAAQ,aACFX,WAAW,IACX;YAAEyB,eAAeX,eAAe,IAAKI,cAAc,IAAI,UAAU,YAAa;QAAS,IACvF,CAAC;YACL1B,iBAAiBP,QAAQM,QAAQ;YACjCmC,kBAAkB;gBAACzC,QAAQM,QAAQ;aAAC;YACpCoC,UAAUzC;WACND,QAAQuC,QAAQ,KAAK,QAAQ;YAAEA,UAAU;QAAM,IAAI,CAAC;QAE1DV;QACAC;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-offline-card-order.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 type { OrderPayment, OrderTotals } from '../model'\nimport type { PosOfflineFlag } from '../model/commerce-pos-offline'\n\n/*==========================================\n * THE MONEY ON AN ORDER FOR A CARD TAKEN OFFLINE (AGL-4039).\n *\n * Pure: the offline sync settles the card with Stripe first, then hands the\n * result here and writes what comes back in the transaction that creates the\n * order. Kept out of `pos-offline-sync.ts` so the refund, dispute and\n * register-collection specs can build an order exactly as the sync writes it\n * without loading the sync's Firestore and Stripe dependencies.\n *\n * What a CAPTURED card writes, and why each field:\n *\n * - `paymentIntentId`, `paymentIntentIds` and `paidAtMs` at the ORDER level,\n * as the online register's completion writes them (`posCompletionPatch`).\n * The refund route and the dispute lookup read the order-level fields; an\n * intent kept only inside `payments[0]` leaves the order unrefundable and\n * its chargeback matched to no order.\n * - The payment's `amountCents` is what Stripe took (`intent.amount`), not\n * the server's restated total. Where they differ the order is flagged\n * `card-amount-differs` for the merchant to check against the receipt.\n * - `totals.feeCents` is the whole fee the sale settled: the card's\n * `application_fee_amount` (the take share plus Stripe's processing cost)\n * as the online completion counts it, plus any shortfall invoiced below.\n * - A FEE SHORTFALL: an intent the server first meets already `succeeded`\n * (captured on the device, with no application fee) netted less than the\n * tender rule's fee from the payout. The difference accrues to the org's\n * month ledger (`orgs/{id}/offlineFees`), the same ledger a room charge's\n * take accrues to, and the order is flagged `card-fee-short`.\n * - A card made on the store's OWN Stripe account (a direct charge,\n * AGL-4219) says so on the payment and the order (`chargeModel: direct`,\n * `stripeAccountId`), as an online direct sale does, so its refund, its\n * return at the register and its chargeback are made on that account.\n *\n * What an UNPAID card writes: `status: 'pending'` with the failed payment,\n * and the sale's plan take on `posTakeFeeCents` with the org it accrues to.\n * Collecting it later at the register reads that take, exactly as an open\n * sale does, so a later card, room charge or cash collection is charged by\n * the same tender rule as any other sale.\n *=========================================*/\n\nexport type PosOfflineCardSettled =\n | {\n kind: 'captured'\n intentId: string\n /** What Stripe charged, `intent.amount`. */\n amountCents: number\n /** What Stripe kept for the platform, `intent.application_fee_amount`. */\n feeCents: number\n /** What the tender rule says the platform's fee is on this charge. */\n expectedFeeCents: number\n /** The card tender's share of the plan's take. */\n takeShareCents: number\n livemode: boolean\n /** The store's own account the intent was made and captured on (a direct charge); absent for a destination one. */\n account?: string\n brand?: string\n last4?: string\n }\n | {\n kind: 'unpaid'\n flag: 'card-declined' | 'card-not-charged'\n intentId?: string\n message: string\n brand?: string\n last4?: string\n }\n\nexport interface PosOfflineCardOrderMoney {\n status: 'paid' | 'pending'\n /** The server's totals with the fee the sale settled. */\n totals: OrderTotals\n payment: OrderPayment\n /** Written at the order's top level beside the payment. */\n fields: Record<string, unknown>\n /** Cents to accrue to the org's month ledger with the order, 0 for none. */\n invoiceCents: number\n /** What the money adds to the sale's flags. */\n flags: PosOfflineFlag[]\n}\n\nconst whole = (value: unknown): number => {\n const number = Math.round(Number(value))\n return Number.isFinite(number) && number > 0 ? number : 0\n}\n\nexport function posOfflineCardOrderMoney(input: {\n settled: PosOfflineCardSettled\n /** The server's totals for the sale, restated where the register's did not add up. */\n totals: OrderTotals\n /** The plan's take on the goods, before the tender rule. */\n planTakeCents: number\n soldAtMs: number\n nowMs: number\n cashierId: string\n /** The org the fees accrue to; '' when the site has none, and nothing accrues. */\n feeOrgId: string\n}): PosOfflineCardOrderMoney {\n const { settled, soldAtMs, nowMs, cashierId, feeOrgId } = input\n const card = {\n ...(settled.intentId ? { paymentIntentId: settled.intentId } : {}),\n ...(settled.brand ? { cardBrand: settled.brand } : {}),\n ...(settled.last4 ? { last4: settled.last4 } : {}),\n }\n if (settled.kind === 'unpaid') {\n const planTakeCents = whole(input.planTakeCents)\n return {\n status: 'pending',\n totals: { ...input.totals, feeCents: 0 },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents: whole(input.totals.totalCents),\n status: 'failed',\n atMs: soldAtMs,\n takeFeeCents: 0,\n feeCents: 0,\n failureMessage: settled.message.slice(0, 300),\n ...card,\n cashierId,\n },\n fields: {\n posTakeFeeCents: planTakeCents,\n ...(feeOrgId ? { posFeeOrgId: feeOrgId } : {}),\n },\n invoiceCents: 0,\n flags: [settled.flag],\n }\n }\n const flags: PosOfflineFlag[] = []\n const amountCents = whole(settled.amountCents)\n if (amountCents !== whole(input.totals.totalCents)) flags.push('card-amount-differs')\n const nettedCents = whole(settled.feeCents)\n const shortfallCents = Math.max(0, whole(settled.expectedFeeCents) - nettedCents)\n if (shortfallCents > 0) flags.push('card-fee-short')\n const invoiceCents = feeOrgId ? shortfallCents : 0\n const feeCents = nettedCents + invoiceCents\n const direct = settled.account ? { chargeModel: 'direct' as const, stripeAccountId: settled.account } : {}\n return {\n status: 'paid',\n totals: { ...input.totals, feeCents },\n payment: {\n id: 'pay_card_offline',\n method: 'card_present',\n amountCents,\n status: 'succeeded',\n atMs: soldAtMs,\n settledAtMs: nowMs,\n takeFeeCents: whole(settled.takeShareCents),\n feeCents: nettedCents,\n livemode: settled.livemode,\n ...card,\n ...direct,\n cashierId,\n },\n fields: {\n ...direct,\n ...(feeCents > 0\n ? { feeCollection: invoiceCents > 0 ? (nettedCents > 0 ? 'split' : 'invoice') : 'payout' }\n : {}),\n paymentIntentId: settled.intentId,\n paymentIntentIds: [settled.intentId],\n paidAtMs: soldAtMs,\n ...(settled.livemode === false ? { livemode: false } : {}),\n },\n invoiceCents,\n flags,\n }\n}\n"],"names":["whole","value","number","Math","round","Number","isFinite","posOfflineCardOrderMoney","input","settled","soldAtMs","nowMs","cashierId","feeOrgId","card","intentId","paymentIntentId","brand","cardBrand","last4","kind","planTakeCents","status","totals","feeCents","payment","id","method","amountCents","totalCents","atMs","takeFeeCents","failureMessage","message","slice","fields","posTakeFeeCents","posFeeOrgId","invoiceCents","flags","flag","push","nettedCents","shortfallCents","max","expectedFeeCents","direct","account","chargeModel","stripeAccountId","settledAtMs","takeShareCents","livemode","feeCollection","paymentIntentIds","paidAtMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAoFD,MAAMA,QAAQ,CAACC;IACb,MAAMC,SAASC,KAAKC,KAAK,CAACC,OAAOJ;IACjC,OAAOI,OAAOC,QAAQ,CAACJ,WAAWA,SAAS,IAAIA,SAAS;AAC1D;AAEA,OAAO,SAASK,yBAAyBC,KAWxC;IACC,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,QAAQ,EAAE,GAAGL;IAC1D,MAAMM,OAAO,aACPL,QAAQM,QAAQ,GAAG;QAAEC,iBAAiBP,QAAQM,QAAQ;IAAC,IAAI,CAAC,GAC5DN,QAAQQ,KAAK,GAAG;QAAEC,WAAWT,QAAQQ,KAAK;IAAC,IAAI,CAAC,GAChDR,QAAQU,KAAK,GAAG;QAAEA,OAAOV,QAAQU,KAAK;I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/B,MAAMS,QAAQ0C,cAAc;YAC1C3B,UAAUkB;YACVU,UAAU3C,QAAQ2C,QAAQ;WACvBtC,MACAgC;YACHlC;;QAEFuB,QAAQ,aACHW,QACCtB,WAAW,IACX;YAAE6B,eAAef,eAAe,IAAKI,cAAc,IAAI,UAAU,YAAa;QAAS,IACvF,CAAC;YACL1B,iBAAiBP,QAAQM,QAAQ;YACjCuC,kBAAkB;gBAAC7C,QAAQM,QAAQ;aAAC;YACpCwC,UAAU7C;WACND,QAAQ2C,QAAQ,KAAK,QAAQ;YAAEA,UAAU;QAAM,IAAI,CAAC;QAE1Dd;QACAC;IACF;AACF"}
|
|
@@ -52,7 +52,11 @@ export declare function reconcilePosOfflineCardEvent(input: {
|
|
|
52
52
|
}, firestore?: FirebaseFirestore.Firestore, now?: () => number): Promise<{
|
|
53
53
|
hostId: string;
|
|
54
54
|
} | null>;
|
|
55
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* The platform webhook's handler for offline card intents: claims only its
|
|
57
|
+
* own. A Connect-delivered event counts only for the site's own account.
|
|
58
|
+
*/
|
|
59
|
+
export declare function createPosOfflineCardBillingWebhookHandler(directAccount?: (hostId: string) => Promise<string | null>): BillingWebhookHandler;
|
|
56
60
|
export declare const posOfflineCardBillingWebhookHandler: BillingWebhookHandler;
|
|
57
61
|
export interface UnsyncedOfflineCardReport {
|
|
58
62
|
hostId: string;
|