@aglyn/plugins-commerce 1.29.3 → 1.31.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.
Files changed (72) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart.js +11 -5
  3. package/src/lib/components/cart.js.map +1 -1
  4. package/src/lib/components/console/pos/pos-item-dialog.component.js +12 -0
  5. package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
  6. package/src/lib/components/console/pos-kiosk-page.component.js +3 -5
  7. package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
  8. package/src/lib/components/console/product-add-ons-fields.component.d.ts +11 -0
  9. package/src/lib/components/console/product-add-ons-fields.component.js +229 -13
  10. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  11. package/src/lib/components/console/product-editor-dialog.component.js +5 -0
  12. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  13. package/src/lib/components/console/product-traffic-card.component.d.ts +24 -0
  14. package/src/lib/components/console/product-traffic-card.component.js +172 -0
  15. package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
  16. package/src/lib/components/console/products-hub-card.component.js +181 -59
  17. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  18. package/src/lib/components/console/quote-editor-dialog.component.js +38 -0
  19. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  20. package/src/lib/components/console/shipping-settings-card.component.js +31 -9
  21. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  22. package/src/lib/components/product-add-ons.d.ts +21 -0
  23. package/src/lib/components/product-add-ons.js +77 -1
  24. package/src/lib/components/product-add-ons.js.map +1 -1
  25. package/src/lib/components/product-builder-mockup.d.ts +1 -1
  26. package/src/lib/components/product-builder-mockup.js +17 -5
  27. package/src/lib/components/product-builder-mockup.js.map +1 -1
  28. package/src/lib/components/product-choice-cards.js +14 -2
  29. package/src/lib/components/product-choice-cards.js.map +1 -1
  30. package/src/lib/model/commerce-pos-kiosk.js +8 -2
  31. package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
  32. package/src/lib/model/commerce-pos-offline.d.ts +1 -1
  33. package/src/lib/model/commerce-pos-offline.js +8 -2
  34. package/src/lib/model/commerce-pos-offline.js.map +1 -1
  35. package/src/lib/model/commerce-quote-request.d.ts +1 -0
  36. package/src/lib/model/commerce-quote-request.js +6 -2
  37. package/src/lib/model/commerce-quote-request.js.map +1 -1
  38. package/src/lib/model/commerce-quotes.js +10 -5
  39. package/src/lib/model/commerce-quotes.js.map +1 -1
  40. package/src/lib/model/commerce-record-routes.js +31 -0
  41. package/src/lib/model/commerce-record-routes.js.map +1 -1
  42. package/src/lib/model/commerce-shipping.d.ts +39 -16
  43. package/src/lib/model/commerce-shipping.js +315 -30
  44. package/src/lib/model/commerce-shipping.js.map +1 -1
  45. package/src/lib/model/commerce.js +1 -1
  46. package/src/lib/model/commerce.js.map +1 -1
  47. package/src/lib/model/product-modifiers.d.ts +53 -2
  48. package/src/lib/model/product-modifiers.js +127 -27
  49. package/src/lib/model/product-modifiers.js.map +1 -1
  50. package/src/lib/model/product-write.d.ts +10 -1
  51. package/src/lib/model/product-write.js +13 -2
  52. package/src/lib/model/product-write.js.map +1 -1
  53. package/src/lib/server/carrier-shipping.js +3 -2
  54. package/src/lib/server/carrier-shipping.js.map +1 -1
  55. package/src/lib/server/cart-checkout.js +10 -4
  56. package/src/lib/server/cart-checkout.js.map +1 -1
  57. package/src/lib/server/cart.js +2 -2
  58. package/src/lib/server/cart.js.map +1 -1
  59. package/src/lib/server/checkout.js +6 -4
  60. package/src/lib/server/checkout.js.map +1 -1
  61. package/src/lib/server/draft-order.js +3 -3
  62. package/src/lib/server/draft-order.js.map +1 -1
  63. package/src/lib/server/pos-kiosk.js +1 -4
  64. package/src/lib/server/pos-kiosk.js.map +1 -1
  65. package/src/lib/server/product.d.ts +5 -0
  66. package/src/lib/server/product.js +10 -2
  67. package/src/lib/server/product.js.map +1 -1
  68. package/src/lib/server/products-write.js +10 -2
  69. package/src/lib/server/products-write.js.map +1 -1
  70. package/src/lib/transfer/product-register-cells.d.ts +7 -0
  71. package/src/lib/transfer/product-register-cells.js +88 -10
  72. package/src/lib/transfer/product-register-cells.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/product-choice-cards.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 Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Chip from '@mui/material/Chip'\nimport Collapse from '@mui/material/Collapse'\nimport List from '@mui/material/List'\nimport ListItem from '@mui/material/ListItem'\nimport ListItemText from '@mui/material/ListItemText'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport { useId, useState, type ReactNode } from 'react'\nimport {\n modifierGroupRequired,\n modifierOptionIsCombo,\n modifierOptionPriceCents,\n type ModifierSelection,\n type ProductModifierGroup,\n type ProductModifierOption,\n} from '../model/product-modifiers'\nimport { addOnGroupHint, withGroupAnswer } from './product-add-ons'\n\n/*\n * THE PRODUCT BUILDER'S PICTURE CARDS (AGL-4205).\n *\n * A Product detail block set to show its choices as picture cards draws each\n * of the product's options (size, style) and each of its add-on groups as a\n * row of cards: the choice's picture, its name, what it costs, and the\n * owner's short note. A combo's card folds out what it includes. A group\n * that takes one choice behaves as radio buttons, one that takes several as\n * check boxes up to its maximum, and a required group is marked and cannot\n * be emptied. Its own chunk: only a page that shows cards downloads it.\n */\n\n/** A variant as the cards read it. */\nexport interface CardVariant {\n id: string\n options?: Record<string, string>\n priceUsd: number | null\n soldOut?: boolean\n imageUrl?: string\n note?: string\n}\n\n/**\n * The variant a card for one option value stands for: the one the shopper's\n * other picks make with this value, else the first that carries the value.\n */\nexport function variantForOptionValue<V extends CardVariant>(\n variants: readonly V[],\n selections: Readonly<Record<string, string>>,\n optionName: string,\n value: string,\n): V | undefined {\n const wanted = { ...selections, [optionName]: value }\n return (\n variants.find((variant) =>\n Object.entries(wanted).every(([name, picked]) => (variant.options?.[name] ?? picked) === picked),\n ) ?? variants.find((variant) => variant.options?.[optionName] === value)\n )\n}\n\n/**\n * A group's answer after a card is pressed. One-choice groups act as radio\n * buttons (an optional one can be cleared by pressing its pick again); a\n * several-choice group adds or removes the choice, never past its maximum.\n * The answer keeps the group's own order.\n */\nexport function pressChoice(\n group: Pick<ProductModifierGroup, 'min' | 'max' | 'options'>,\n chosen: readonly string[],\n optionId: string,\n): string[] {\n const picked = chosen.includes(optionId)\n if (group.max === 1) {\n if (picked) return group.min > 0 ? [...chosen] : []\n return [optionId]\n }\n if (picked) return chosen.filter((id) => id !== optionId)\n if (chosen.length >= group.max) return [...chosen]\n return group.options.map((option) => option.id).filter((id) => id === optionId || chosen.includes(id))\n}\n\n/** What a card says a choice adds: its price, or that it adds nothing. */\nexport function addOnPriceLabel(cents: number, formatCents: (cents: number) => string): string {\n return cents > 0 ? `+${formatCents(cents)}` : 'No extra charge'\n}\n\ninterface ChoiceCardProps {\n name: string\n price: string\n note?: string\n imageUrl?: string\n selected: boolean\n disabled?: boolean\n role: 'radio' | 'checkbox'\n onPress: () => void\n badge?: ReactNode\n includes?: readonly string[]\n}\n\n/** One card: picture, name, price and note, pressed to pick; a combo's contents fold out below. */\nfunction ChoiceCard(props: ChoiceCardProps) {\n const { name, price, note, imageUrl, selected, disabled, role, onPress, badge, includes } = props\n const { hostId } = Aglyn.useSite()\n const [open, setOpen] = useState(false)\n const contentsId = useId()\n const src = imageUrl ? Aglyn.siteRelativeMediaSrc(imageUrl, { hostId }) : undefined\n return (\n <Card\n variant=\"outlined\"\n sx={{\n display: 'flex',\n flexDirection: 'column',\n borderWidth: 2,\n borderColor: selected ? 'primary.main' : 'divider',\n bgcolor: selected ? 'action.selected' : 'background.paper',\n opacity: disabled && !selected ? 0.6 : 1,\n }}\n >\n <CardActionArea\n role={role}\n aria-checked={selected}\n disabled={disabled}\n onClick={onPress}\n sx={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'stretch' }}\n >\n {src ? (\n <CardMedia\n component=\"img\"\n image={src}\n alt=\"\"\n sx={{ aspectRatio: '4 / 3', objectFit: 'cover' }}\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : null}\n <CardContent sx={{ flex: 1, p: 1.5, '&:last-child': { pb: 1.5 } }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start', justifyContent: 'space-between' }}>\n <Typography variant=\"subtitle2\" component=\"span\">\n {name}\n </Typography>\n {badge}\n </Stack>\n <Typography variant=\"body2\" color={selected ? 'primary' : 'text.primary'} sx={{ fontWeight: 600 }}>\n {price}\n </Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"p\">\n {note}\n </Typography>\n ) : null}\n </CardContent>\n </CardActionArea>\n {includes?.length ? (\n <Box sx={{ px: 1, pb: 1 }}>\n <Button\n size=\"small\"\n aria-expanded={open}\n aria-controls={contentsId}\n onClick={() => setOpen((was) => !was)}\n >\n {open ? 'Hide what’s included' : 'What’s included'}\n </Button>\n <Collapse in={open} id={contentsId}>\n <List dense disablePadding aria-label={`${name} includes`}>\n {includes.map((item) => (\n <ListItem key={item} disableGutters sx={{ py: 0 }}>\n <ListItemText primary={item} slotProps={{ primary: { variant: 'body2' } }} />\n </ListItem>\n ))}\n </List>\n </Collapse>\n </Box>\n ) : null}\n </Card>\n )\n}\n\n/** A heading, its hint, and the grid of cards under it. */\nfunction CardGroup(props: {\n label: string\n hint: string\n required: boolean\n role: 'radiogroup' | 'group'\n children: ReactNode\n}) {\n const { label, hint, required, role, children } = props\n const labelId = useId()\n return (\n <Box component=\"section\" aria-labelledby={labelId}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', mb: 1 }}>\n <Typography id={labelId} variant=\"subtitle1\" component=\"h2\">\n {label}\n </Typography>\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={required ? 'primary' : 'default'}\n label={hint}\n />\n </Stack>\n <Box\n role={role}\n aria-labelledby={labelId}\n aria-required={required || undefined}\n sx={{\n display: 'grid',\n gridTemplateColumns: (theme) => `repeat(auto-fill, minmax(${theme.spacing(19)}, 1fr))`,\n gap: 1.5,\n }}\n >\n {children}\n </Box>\n </Box>\n )\n}\n\nexport interface ProductChoiceCardsProps {\n /** The options the shopper chooses among (size, style), with their values. */\n options: ReadonlyArray<{ name: string; values: readonly string[] }>\n variants: readonly CardVariant[]\n selections: Readonly<Record<string, string>>\n onSelect: (optionName: string, value: string) => void\n /** The add-on groups the website offers; empty draws none. */\n groups: readonly ProductModifierGroup[]\n /** The variant picked: a choice priced by variant shows its price on it. */\n variantId?: string\n value: readonly ModifierSelection[]\n onChange: (next: ModifierSelection[]) => void\n /** The store's money, e.g. `$1,250.00`. */\n formatCents: (cents: number) => string\n /** What a card says where a variant has no price yet. */\n unpricedLabel: string\n disabled?: boolean\n}\n\n/** The product's options and add-ons as picture cards (AGL-4205). */\nexport function ProductChoiceCards(props: ProductChoiceCardsProps) {\n const {\n options,\n variants,\n selections,\n onSelect,\n groups,\n variantId,\n value,\n onChange,\n formatCents,\n unpricedLabel,\n disabled,\n } = props\n const addOnCard = (group: ProductModifierGroup, option: ProductModifierOption, chosen: string[]) => {\n const selected = chosen.includes(option.id)\n const full = group.max > 1 && chosen.length >= group.max\n return (\n <ChoiceCard\n key={option.id}\n name={option.name}\n price={addOnPriceLabel(modifierOptionPriceCents(option, variantId), formatCents)}\n note={option.note}\n imageUrl={option.imageUrl}\n selected={selected}\n disabled={disabled || (!selected && full)}\n role={group.max === 1 ? 'radio' : 'checkbox'}\n badge={modifierOptionIsCombo(option) ? <Chip size=\"small\" color=\"secondary\" label=\"Combo\" /> : null}\n includes={modifierOptionIsCombo(option) ? option.includes : undefined}\n onPress={() => onChange(withGroupAnswer(groups, value, group.id, pressChoice(group, chosen, option.id)))}\n />\n )\n }\n return (\n <Stack spacing={3} sx={{ mb: 2 }}>\n {options.map((option) => (\n <CardGroup key={option.name} label={option.name} hint=\"Choose one\" required role=\"radiogroup\">\n {option.values.map((choice) => {\n const variant = variantForOptionValue(variants, selections, option.name, choice)\n return (\n <ChoiceCard\n key={choice}\n name={choice}\n price={\n typeof variant?.priceUsd === 'number'\n ? formatCents(Math.round(variant.priceUsd * 100))\n : unpricedLabel\n }\n note={variant?.note}\n imageUrl={variant?.imageUrl}\n selected={selections[option.name] === choice}\n role=\"radio\"\n badge={variant?.soldOut ? <Chip size=\"small\" variant=\"outlined\" label=\"Sold out\" /> : null}\n onPress={() => onSelect(option.name, choice)}\n />\n )\n })}\n </CardGroup>\n ))}\n {groups.map((group) => {\n const chosen = value.filter((pick) => pick.groupId === group.id).map((pick) => pick.optionId)\n return (\n <CardGroup\n key={group.id}\n label={group.name}\n hint={addOnGroupHint(group)}\n required={modifierGroupRequired(group)}\n role={group.max === 1 ? 'radiogroup' : 'group'}\n >\n {group.options.map((option) => addOnCard(group, option, chosen))}\n </CardGroup>\n )\n })}\n </Stack>\n )\n}\n\nProductChoiceCards.displayName = 'ProductChoiceCards'\n\nexport default ProductChoiceCards\n"],"names":["Aglyn","Box","Button","Card","CardActionArea","CardContent","CardMedia","Chip","Collapse","List","ListItem","ListItemText","Stack","Typography","useId","useState","modifierGroupRequired","modifierOptionIsCombo","modifierOptionPriceCents","addOnGroupHint","withGroupAnswer","variantForOptionValue","variants","selections","optionName","value","wanted","find","variant","Object","entries","every","name","picked","options","pressChoice","group","chosen","optionId","includes","max","min","filter","id","length","map","option","addOnPriceLabel","cents","formatCents","ChoiceCard","props","price","note","imageUrl","selected","disabled","role","onPress","badge","hostId","useSite","open","setOpen","contentsId","src","siteRelativeMediaSrc","undefined","sx","display","flexDirection","borderWidth","borderColor","bgcolor","opacity","aria-checked","onClick","flex","alignItems","component","image","alt","aspectRatio","objectFit","DEFERRED_IMAGE_ATTRIBUTES","p","pb","direction","spacing","justifyContent","color","fontWeight","px","size","aria-expanded","aria-controls","was","in","dense","disablePadding","aria-label","item","disableGutters","py","primary","slotProps","CardGroup","label","hint","required","children","labelId","aria-labelledby","mb","aria-required","gridTemplateColumns","theme","gap","ProductChoiceCards","onSelect","groups","variantId","onChange","unpricedLabel","addOnCard","full","values","choice","priceUsd","Math","round","soldOut","pick","groupId","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+BAA8B;AACzD,OAAOC,iBAAiB,4BAA2B;AACnD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,kBAAkB,6BAA4B;AACrD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,KAAK,EAAEC,QAAQ,QAAwB,QAAO;AACvD,SACEC,qBAAqB,EACrBC,qBAAqB,EACrBC,wBAAwB,QAInB,gCAA4B;AACnC,SAASC,cAAc,EAAEC,eAAe,QAAQ,uBAAmB;AAwBnE;;;CAGC,GACD,OAAO,SAASC,sBACdC,QAAsB,EACtBC,UAA4C,EAC5CC,UAAkB,EAClBC,KAAa;QAIXH;IAF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cesContent":["/**\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 Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Card from '@mui/material/Card'\nimport CardActionArea from '@mui/material/CardActionArea'\nimport CardContent from '@mui/material/CardContent'\nimport CardMedia from '@mui/material/CardMedia'\nimport Chip from '@mui/material/Chip'\nimport Collapse from '@mui/material/Collapse'\nimport List from '@mui/material/List'\nimport ListItem from '@mui/material/ListItem'\nimport ListItemText from '@mui/material/ListItemText'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport { useId, useState, type ReactNode } from 'react'\nimport {\n modifierGroupIsWriteIn,\n modifierGroupRequired,\n modifierOptionIsCombo,\n modifierOptionPriceCents,\n type ModifierSelection,\n type ProductModifierGroup,\n type ProductModifierOption,\n} from '../model/product-modifiers'\nimport { addOnGroupHint, ProductWriteInField, withGroupAnswer } from './product-add-ons'\n\n/*\n * THE PRODUCT BUILDER'S PICTURE CARDS (AGL-4205).\n *\n * A Product detail block set to show its choices as picture cards draws each\n * of the product's options (size, style) and each of its add-on groups as a\n * row of cards: the choice's picture, its name, what it costs, and the\n * owner's short note. A combo's card folds out what it includes. A group\n * that takes one choice behaves as radio buttons, one that takes several as\n * check boxes up to its maximum, and a required group is marked and cannot\n * be emptied. Its own chunk: only a page that shows cards downloads it.\n */\n\n/** A variant as the cards read it. */\nexport interface CardVariant {\n id: string\n options?: Record<string, string>\n priceUsd: number | null\n soldOut?: boolean\n imageUrl?: string\n note?: string\n}\n\n/**\n * The variant a card for one option value stands for: the one the shopper's\n * other picks make with this value, else the first that carries the value.\n */\nexport function variantForOptionValue<V extends CardVariant>(\n variants: readonly V[],\n selections: Readonly<Record<string, string>>,\n optionName: string,\n value: string,\n): V | undefined {\n const wanted = { ...selections, [optionName]: value }\n return (\n variants.find((variant) =>\n Object.entries(wanted).every(([name, picked]) => (variant.options?.[name] ?? picked) === picked),\n ) ?? variants.find((variant) => variant.options?.[optionName] === value)\n )\n}\n\n/**\n * A group's answer after a card is pressed. One-choice groups act as radio\n * buttons (an optional one can be cleared by pressing its pick again); a\n * several-choice group adds or removes the choice, never past its maximum.\n * The answer keeps the group's own order.\n */\nexport function pressChoice(\n group: Pick<ProductModifierGroup, 'min' | 'max' | 'options'>,\n chosen: readonly string[],\n optionId: string,\n): string[] {\n const picked = chosen.includes(optionId)\n if (group.max === 1) {\n if (picked) return group.min > 0 ? [...chosen] : []\n return [optionId]\n }\n if (picked) return chosen.filter((id) => id !== optionId)\n if (chosen.length >= group.max) return [...chosen]\n return group.options.map((option) => option.id).filter((id) => id === optionId || chosen.includes(id))\n}\n\n/** What a card says a choice adds: its price, or that it adds nothing. */\nexport function addOnPriceLabel(cents: number, formatCents: (cents: number) => string): string {\n return cents > 0 ? `+${formatCents(cents)}` : 'No extra charge'\n}\n\ninterface ChoiceCardProps {\n name: string\n price: string\n note?: string\n imageUrl?: string\n selected: boolean\n disabled?: boolean\n role: 'radio' | 'checkbox'\n onPress: () => void\n badge?: ReactNode\n includes?: readonly string[]\n}\n\n/** One card: picture, name, price and note, pressed to pick; a combo's contents fold out below. */\nfunction ChoiceCard(props: ChoiceCardProps) {\n const { name, price, note, imageUrl, selected, disabled, role, onPress, badge, includes } = props\n const { hostId } = Aglyn.useSite()\n const [open, setOpen] = useState(false)\n const contentsId = useId()\n const src = imageUrl ? Aglyn.siteRelativeMediaSrc(imageUrl, { hostId }) : undefined\n return (\n <Card\n variant=\"outlined\"\n sx={{\n display: 'flex',\n flexDirection: 'column',\n borderWidth: 2,\n borderColor: selected ? 'primary.main' : 'divider',\n bgcolor: selected ? 'action.selected' : 'background.paper',\n opacity: disabled && !selected ? 0.6 : 1,\n }}\n >\n <CardActionArea\n role={role}\n aria-checked={selected}\n disabled={disabled}\n onClick={onPress}\n sx={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'stretch' }}\n >\n {src ? (\n <CardMedia\n component=\"img\"\n image={src}\n alt=\"\"\n sx={{ aspectRatio: '4 / 3', objectFit: 'cover' }}\n {...Aglyn.DEFERRED_IMAGE_ATTRIBUTES}\n />\n ) : null}\n <CardContent sx={{ flex: 1, p: 1.5, '&:last-child': { pb: 1.5 } }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start', justifyContent: 'space-between' }}>\n <Typography variant=\"subtitle2\" component=\"span\">\n {name}\n </Typography>\n {badge}\n </Stack>\n <Typography variant=\"body2\" color={selected ? 'primary' : 'text.primary'} sx={{ fontWeight: 600 }}>\n {price}\n </Typography>\n {note ? (\n <Typography variant=\"caption\" color=\"text.secondary\" component=\"p\">\n {note}\n </Typography>\n ) : null}\n </CardContent>\n </CardActionArea>\n {includes?.length ? (\n <Box sx={{ px: 1, pb: 1 }}>\n <Button\n size=\"small\"\n aria-expanded={open}\n aria-controls={contentsId}\n onClick={() => setOpen((was) => !was)}\n >\n {open ? 'Hide what’s included' : 'What’s included'}\n </Button>\n <Collapse in={open} id={contentsId}>\n <List dense disablePadding aria-label={`${name} includes`}>\n {includes.map((item) => (\n <ListItem key={item} disableGutters sx={{ py: 0 }}>\n <ListItemText primary={item} slotProps={{ primary: { variant: 'body2' } }} />\n </ListItem>\n ))}\n </List>\n </Collapse>\n </Box>\n ) : null}\n </Card>\n )\n}\n\n/** A heading, its hint, and the grid of cards under it. */\nfunction CardGroup(props: {\n label: string\n hint: string\n required: boolean\n role: 'radiogroup' | 'group'\n children: ReactNode\n}) {\n const { label, hint, required, role, children } = props\n const labelId = useId()\n return (\n <Box component=\"section\" aria-labelledby={labelId}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center', mb: 1 }}>\n <Typography id={labelId} variant=\"subtitle1\" component=\"h2\">\n {label}\n </Typography>\n <Chip\n size=\"small\"\n variant=\"outlined\"\n color={required ? 'primary' : 'default'}\n label={hint}\n />\n </Stack>\n <Box\n role={role}\n aria-labelledby={labelId}\n aria-required={required || undefined}\n sx={{\n display: 'grid',\n gridTemplateColumns: (theme) => `repeat(auto-fill, minmax(${theme.spacing(19)}, 1fr))`,\n gap: 1.5,\n }}\n >\n {children}\n </Box>\n </Box>\n )\n}\n\nexport interface ProductChoiceCardsProps {\n /** The options the shopper chooses among (size, style), with their values. */\n options: ReadonlyArray<{ name: string; values: readonly string[] }>\n variants: readonly CardVariant[]\n selections: Readonly<Record<string, string>>\n onSelect: (optionName: string, value: string) => void\n /** The add-on groups the website offers; empty draws none. */\n groups: readonly ProductModifierGroup[]\n /** The variant picked: a choice priced by variant shows its price on it. */\n variantId?: string\n value: readonly ModifierSelection[]\n onChange: (next: ModifierSelection[]) => void\n /** The store's money, e.g. `$1,250.00`. */\n formatCents: (cents: number) => string\n /** What a card says where a variant has no price yet. */\n unpricedLabel: string\n disabled?: boolean\n}\n\n/** The product's options and add-ons as picture cards (AGL-4205). */\nexport function ProductChoiceCards(props: ProductChoiceCardsProps) {\n const {\n options,\n variants,\n selections,\n onSelect,\n groups,\n variantId,\n value,\n onChange,\n formatCents,\n unpricedLabel,\n disabled,\n } = props\n const addOnCard = (group: ProductModifierGroup, option: ProductModifierOption, chosen: string[]) => {\n const selected = chosen.includes(option.id)\n const full = group.max > 1 && chosen.length >= group.max\n return (\n <ChoiceCard\n key={option.id}\n name={option.name}\n price={addOnPriceLabel(modifierOptionPriceCents(option, variantId), formatCents)}\n note={option.note}\n imageUrl={option.imageUrl}\n selected={selected}\n disabled={disabled || (!selected && full)}\n role={group.max === 1 ? 'radio' : 'checkbox'}\n badge={modifierOptionIsCombo(option) ? <Chip size=\"small\" color=\"secondary\" label=\"Combo\" /> : null}\n includes={modifierOptionIsCombo(option) ? option.includes : undefined}\n onPress={() => onChange(withGroupAnswer(groups, value, group.id, pressChoice(group, chosen, option.id)))}\n />\n )\n }\n return (\n <Stack spacing={3} sx={{ mb: 2 }}>\n {options.map((option) => (\n <CardGroup key={option.name} label={option.name} hint=\"Choose one\" required role=\"radiogroup\">\n {option.values.map((choice) => {\n const variant = variantForOptionValue(variants, selections, option.name, choice)\n return (\n <ChoiceCard\n key={choice}\n name={choice}\n price={\n typeof variant?.priceUsd === 'number'\n ? formatCents(Math.round(variant.priceUsd * 100))\n : unpricedLabel\n }\n note={variant?.note}\n imageUrl={variant?.imageUrl}\n selected={selections[option.name] === choice}\n role=\"radio\"\n badge={variant?.soldOut ? <Chip size=\"small\" variant=\"outlined\" label=\"Sold out\" /> : null}\n onPress={() => onSelect(option.name, choice)}\n />\n )\n })}\n </CardGroup>\n ))}\n {groups.map((group) => {\n // A write-in (write-ins) is a text field among the cards: there is nothing to picture.\n if (modifierGroupIsWriteIn(group)) {\n return (\n <ProductWriteInField\n key={group.id}\n group={group}\n groups={groups}\n variantId={variantId}\n value={value}\n onChange={onChange}\n formatCents={formatCents}\n disabled={disabled}\n />\n )\n }\n const chosen = value.filter((pick) => pick.groupId === group.id).map((pick) => pick.optionId)\n return (\n <CardGroup\n key={group.id}\n label={group.name}\n hint={addOnGroupHint(group)}\n required={modifierGroupRequired(group)}\n role={group.max === 1 ? 'radiogroup' : 'group'}\n >\n {group.options.map((option) => addOnCard(group, option, chosen))}\n </CardGroup>\n )\n })}\n </Stack>\n )\n}\n\nProductChoiceCards.displayName = 'ProductChoiceCards'\n\nexport default ProductChoiceCards\n"],"names":["Aglyn","Box","Button","Card","CardActionArea","CardContent","CardMedia","Chip","Collapse","List","ListItem","ListItemText","Stack","Typography","useId","useState","modifierGroupIsWriteIn","modifierGroupRequired","modifierOptionIsCombo","modifierOptionPriceCents","addOnGroupHint","ProductWriteInField","withGroupAnswer","variantForOptionValue","variants","selections","optionName","value","wanted","find","variant","Object","entries","every","name","picked","options","pressChoice","group","chosen","optionId","includes","max","min","filter","id","length","map","option","addOnPriceLabel","cents","formatCents","ChoiceCard","props","price","note","imageUrl","selected","disabled","role","onPress","badge","hostId","useSite","open","setOpen","contentsId","src","siteRelativeMediaSrc","undefined","sx","display","flexDirection","borderWidth","borderColor","bgcolor","opacity","aria-checked","onClick","flex","alignItems","component","image","alt","aspectRatio","objectFit","DEFERRED_IMAGE_ATTRIBUTES","p","pb","direction","spacing","justifyContent","color","fontWeight","px","size","aria-expanded","aria-controls","was","in","dense","disablePadding","aria-label","item","disableGutters","py","primary","slotProps","CardGroup","label","hint","required","children","labelId","aria-labelledby","mb","aria-required","gridTemplateColumns","theme","gap","ProductChoiceCards","onSelect","groups","variantId","onChange","unpricedLabel","addOnCard","full","values","choice","priceUsd","Math","round","soldOut","pick","groupId","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AACrC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,oBAAoB,+BAA8B;AACzD,OAAOC,iBAAiB,4BAA2B;AACnD,OAAOC,eAAe,0BAAyB;AAC/C,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,cAAc,yBAAwB;AAC7C,OAAOC,kBAAkB,6BAA4B;AACrD,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,gBAAgB,2BAA0B;AACjD,SAASC,KAAK,EAAEC,QAAQ,QAAwB,QAAO;AACvD,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,qBAAqB,EACrBC,wBAAwB,QAInB,gCAA4B;AACnC,SAASC,cAAc,EAAEC,mBAAmB,EAAEC,eAAe,QAAQ,uBAAmB;AAwBxF;;;CAGC,GACD,OAAO,SAASC,sBACdC,QAAsB,EACtBC,UA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,IAAI,eAAe;8BAEtCJ,MAAMF,OAAO,CAACW,GAAG,CAAC,CAACC,SAAW8E,UAAUxF,OAAOU,QAAQT;mBANnDD,MAAMO,EAAE;YASnB;;;AAGN;AAEA2E,mBAAmBgB,WAAW,GAAG;AAEjC,eAAehB,mBAAkB"}
@@ -15,7 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { posTipFromPercent, posTipProblem } from "./commerce-pos.js";
18
- import { modifierOptionPriceCents } from "./product-modifiers.js";
18
+ import { cleanWriteIn, modifierOptionPriceCents } from "./product-modifiers.js";
19
19
  /** Seconds without a touch before the kiosk asks "Still there?", by default. */ export const POS_KIOSK_IDLE_SECONDS_DEFAULT = 90;
20
20
  export const POS_KIOSK_IDLE_SECONDS_MIN = 30;
21
21
  export const POS_KIOSK_IDLE_SECONDS_MAX = 600;
@@ -78,7 +78,13 @@ const ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
78
78
  error: 'A choice on an item is no longer offered.'
79
79
  };
80
80
  }
81
- modifiers.push({
81
+ // A write-in's answer (write-ins), checked against its group when the order is priced.
82
+ const text = cleanWriteIn(pick == null ? void 0 : pick['text']);
83
+ modifiers.push(text ? {
84
+ groupId,
85
+ optionId,
86
+ text
87
+ } : {
82
88
  groupId,
83
89
  optionId
84
90
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-pos-kiosk.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 { posTipFromPercent, posTipProblem, type PosReceiptChannel } from './commerce-pos'\nimport { modifierOptionPriceCents, type ModifierSelection, type ProductModifierGroup } from './product-modifiers'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623).\n *\n * A register's second kind of paired screen: where the customer display\n * (AGL-3608) mirrors the cashier's basket, a kiosk lets the customer build\n * their own order — a product grid with categories and modifiers, a cart, a\n * tip, payment on the register's card reader or Tap to Pay, or \"pay at\n * counter\", which sends the order to the register's queue for a cashier.\n *\n * It pairs exactly like a display (the same six-digit code and the same\n * hashed device token, with `mode: 'kiosk'` on both), and it never holds a\n * staff session: every request carries the device token and the server\n * prices everything. These are the shapes the kiosk route and every client\n * of it — the web kiosk and the native POS app — agree on.\n *=========================================*/\n\n/** Which kind of paired screen a device token opens. */\nexport type PosDeviceMode = 'display' | 'kiosk'\n\n/** A product as the kiosk grid shows it: no cost, no stock count, no supplier. */\nexport interface PosKioskProduct {\n id: string\n name: string\n description?: string\n imageUrl?: string\n categoryIds: string[]\n /** The product's option axes (\"Size\": S, M, L), for the variant picker. */\n options: Array<{ name: string; values: string[] }>\n variants: PosKioskVariant[]\n modifierGroups: ProductModifierGroup[]\n}\n\nexport interface PosKioskVariant {\n id: string\n /** Option selections keyed by option name; empty for the default variant. */\n options: Record<string, string>\n priceCents: number\n /** A tracked variant at or below zero whose product refuses to oversell. */\n soldOut: boolean\n}\n\nexport interface PosKioskCategory {\n id: string\n name: string\n}\n\nexport interface PosKioskCatalog {\n products: PosKioskProduct[]\n categories: PosKioskCategory[]\n /** The store's currency, lower case (`usd`). */\n currency: string\n /**\n * Set when the store has more to offer than this answer lists, so the menu\n * offers a search that reaches the rest. Absent on an answer that lists\n * everything, which is every catalog the menu can show whole.\n */\n truncated?: boolean\n}\n\n/** What the kiosk offers, resolved on the server for one paired register. */\nexport interface PosKioskContext {\n branding: {\n name: string\n logoUrl: string | null\n logoDarkUrl: string | null\n message: string\n }\n currency: string\n tipping: { enabled: boolean; percentages: number[] }\n payments: {\n /** A Stripe Terminal smart reader is assigned to this register. */\n reader: boolean\n /** Card-present payments are switched on for the platform (Tap to Pay needs the native app too). */\n cardPresent: boolean\n /** \"Pay at counter\" sends the order to the register's queue. */\n payAtCounter: boolean\n }\n receipts: PosReceiptChannel[]\n offerMarketing: boolean\n /** Seconds without a touch before the kiosk asks \"Still there?\". */\n idleSeconds: number\n /** Stripe test mode: a test card can be tapped from the payment screen. */\n testMode: boolean\n}\n\n/** One cart line as the kiosk sends it: ids and a count, never a price. */\nexport interface PosKioskLine {\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n}\n\n/** A line of a priced kiosk order, as the customer's screen shows it. */\nexport interface PosKioskSaleLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport type PosKioskSaleStatus =\n /** Priced and waiting for a card at the kiosk. */\n | 'open'\n /** Sent to the register's queue; a cashier takes payment. */\n | 'queued'\n | 'paid'\n | 'voided'\n\n/** A kiosk order as its own screen reads it back. */\nexport interface PosKioskSale {\n orderId: string\n /** The order number the customer is called by. */\n number: number\n status: PosKioskSaleStatus\n lines: PosKioskSaleLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n paidCents: number\n dueCents: number\n /** The card payment in flight, if any. */\n payment: { id: string; status: string; failureMessage?: string } | null\n}\n\n/** Seconds without a touch before the kiosk asks \"Still there?\", by default. */\nexport const POS_KIOSK_IDLE_SECONDS_DEFAULT = 90\nexport const POS_KIOSK_IDLE_SECONDS_MIN = 30\nexport const POS_KIOSK_IDLE_SECONDS_MAX = 600\n\n/** How long \"Still there?\" waits before the kiosk clears itself. */\nexport const POS_KIOSK_IDLE_WARNING_SECONDS = 20\n\n/** The order-number screen returns to the start after this long. */\nexport const POS_KIOSK_DONE_SECONDS = 15\n\n/** Most lines one kiosk order carries. */\nexport const POS_KIOSK_MAX_LINES = 40\n\n/** Most of one line a customer may order at a kiosk. */\nexport const POS_KIOSK_MAX_QUANTITY = 20\n\n/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */\nexport const POS_KIOSK_CATALOG_LIMIT = 200\n\n/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */\nexport const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5\n\n/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */\nexport const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000\n\n/** How long a staff unlock keeps the kiosk's settings open. */\nexport const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000\n\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The cart as the kiosk may send it, or why not. Ids are shape-checked and\n * quantities bounded here; everything else — whether the product exists, is\n * for sale, what it costs and whether its modifiers are valid — is the sale\n * route's to decide from the product documents.\n */\nexport function sanitizePosKioskLines(\n raw: unknown,\n): { ok: true; lines: PosKioskLine[] } | { ok: false; error: string } {\n if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: 'Your cart is empty.' }\n if (raw.length > POS_KIOSK_MAX_LINES) {\n return { ok: false, error: `An order can have at most ${POS_KIOSK_MAX_LINES} items.` }\n }\n const lines: PosKioskLine[] = []\n for (const entry of raw as Array<Record<string, unknown>>) {\n const productId = String(entry?.['productId'] ?? '')\n const variantId = entry?.['variantId'] == null ? '' : String(entry['variantId'])\n const quantity = Number(entry?.['quantity'])\n if (!ID_PATTERN.test(productId) || (variantId && !ID_PATTERN.test(variantId))) {\n return { ok: false, error: 'An item in your cart is no longer available.' }\n }\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_KIOSK_MAX_QUANTITY) {\n return { ok: false, error: `Order 1 to ${POS_KIOSK_MAX_QUANTITY} of each item.` }\n }\n const rawModifiers = Array.isArray(entry?.['modifiers']) ? (entry['modifiers'] as unknown[]) : []\n if (rawModifiers.length > 200) return { ok: false, error: 'Too many choices on one item.' }\n const modifiers: ModifierSelection[] = []\n for (const pick of rawModifiers as Array<Record<string, unknown>>) {\n const groupId = String(pick?.['groupId'] ?? '')\n const optionId = String(pick?.['optionId'] ?? '')\n if (!ID_PATTERN.test(groupId) || !ID_PATTERN.test(optionId)) {\n return { ok: false, error: 'A choice on an item is no longer offered.' }\n }\n modifiers.push({ groupId, optionId })\n }\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n return { ok: true, lines }\n}\n\n/**\n * The tip a kiosk customer chose, recomputed from the server's own figure\n * for what is being paid: a percentage only from the store's presets, a\n * custom amount bounded like every register tip. Null when the choice is\n * not one the store offers.\n */\nexport function posKioskTipCents(\n choice: unknown,\n input: { baseCents: number; enabled: boolean; percentages: readonly number[]; percent?: unknown; cents?: unknown },\n): number | null {\n if (choice === undefined || choice === null || choice === 'none') return 0\n if (!input.enabled) return null\n if (choice === 'percent') {\n const percent = Math.round(Number(input.percent))\n if (!input.percentages.includes(percent)) return null\n return posTipFromPercent(input.baseCents, percent)\n }\n if (choice === 'custom') {\n const cents = Math.round(Number(input.cents))\n return posTipProblem(cents, input.baseCents) ? null : cents\n }\n return null\n}\n\n/** The idle timeout a merchant set, bounded. */\nexport function posKioskIdleSeconds(raw: unknown): number {\n const value = Math.round(Number(raw))\n if (!Number.isFinite(value) || value <= 0) return POS_KIOSK_IDLE_SECONDS_DEFAULT\n return Math.min(POS_KIOSK_IDLE_SECONDS_MAX, Math.max(POS_KIOSK_IDLE_SECONDS_MIN, value))\n}\n\n/**\n * The kiosk's estimate of its cart, from the catalog prices it was given —\n * shown while the customer shops and never sent. The order is priced again,\n * with tax, by the server when they check out.\n */\nexport function posKioskEstimateCents(\n lines: readonly PosKioskLine[],\n products: readonly PosKioskProduct[],\n): number {\n let total = 0\n for (const line of lines) {\n const product = products.find((candidate) => candidate.id === line.productId)\n if (!product) continue\n const variant =\n product.variants.find((candidate) => candidate.id === line.variantId) ?? product.variants[0]\n if (!variant) continue\n const extra = (line.modifiers ?? []).reduce((sum, pick) => {\n const group = product.modifierGroups.find((candidate) => candidate.id === pick.groupId)\n const option = group?.options.find((candidate) => candidate.id === pick.optionId)\n // A choice priced by variant adds its price on this one (AGL-4100).\n return sum + (option ? modifierOptionPriceCents(option, variant.id) : 0)\n }, 0)\n total += (variant.priceCents + extra) * line.quantity\n }\n return total\n}\n"],"names":["posTipFromPercent","posTipProblem","modifierOptionPriceCents","POS_KIOSK_IDLE_SECONDS_DEFAULT","POS_KIOSK_IDLE_SECONDS_MIN","POS_KIOSK_IDLE_SECONDS_MAX","POS_KIOSK_IDLE_WARNING_SECONDS","POS_KIOSK_DONE_SECONDS","POS_KIOSK_MAX_LINES","POS_KIOSK_MAX_QUANTITY","POS_KIOSK_CATALOG_LIMIT","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","POS_KIOSK_UNLOCK_LOCKOUT_MS","POS_KIOSK_UNLOCK_TTL_MS","ID_PATTERN","sanitizePosKioskLines","raw","Array","isArray","length","ok","error","lines","entry","productId","String","variantId","quantity","Number","test","isInteger","rawModifiers","modifiers","pick","groupId","optionId","push","posKioskTipCents","choice","input","undefined","enabled","percent","Math","round","percentages","includes","baseCents","cents","posKioskIdleSeconds","value","isFinite","min","max","posKioskEstimateCents","products","total","line","product","find","candidate","id","variant","variants","extra","reduce","sum","group","modifierGroups","option","options","priceCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,EAAEC,aAAa,QAAgC,oBAAgB;AACzF,SAASC,wBAAwB,QAA2D,yBAAqB;AAiIjH,8EAA8E,GAC9E,OAAO,MAAMC,iCAAiC,GAAE;AAChD,OAAO,MAAMC,6BAA6B,GAAE;AAC5C,OAAO,MAAMC,6BAA6B,IAAG;AAE7C,kEAAkE,GAClE,OAAO,MAAMC,iCAAiC,GAAE;AAEhD,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,GAAE;AAExC,wCAAwC,GACxC,OAAO,MAAMC,sBAAsB,GAAE;AAErC,sDAAsD,GACtD,OAAO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],"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 { posTipFromPercent, posTipProblem, type PosReceiptChannel } from './commerce-pos'\nimport { cleanWriteIn, modifierOptionPriceCents, type ModifierSelection, type ProductModifierGroup } from './product-modifiers'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623).\n *\n * A register's second kind of paired screen: where the customer display\n * (AGL-3608) mirrors the cashier's basket, a kiosk lets the customer build\n * their own order — a product grid with categories and modifiers, a cart, a\n * tip, payment on the register's card reader or Tap to Pay, or \"pay at\n * counter\", which sends the order to the register's queue for a cashier.\n *\n * It pairs exactly like a display (the same six-digit code and the same\n * hashed device token, with `mode: 'kiosk'` on both), and it never holds a\n * staff session: every request carries the device token and the server\n * prices everything. These are the shapes the kiosk route and every client\n * of it — the web kiosk and the native POS app — agree on.\n *=========================================*/\n\n/** Which kind of paired screen a device token opens. */\nexport type PosDeviceMode = 'display' | 'kiosk'\n\n/** A product as the kiosk grid shows it: no cost, no stock count, no supplier. */\nexport interface PosKioskProduct {\n id: string\n name: string\n description?: string\n imageUrl?: string\n categoryIds: string[]\n /** The product's option axes (\"Size\": S, M, L), for the variant picker. */\n options: Array<{ name: string; values: string[] }>\n variants: PosKioskVariant[]\n modifierGroups: ProductModifierGroup[]\n}\n\nexport interface PosKioskVariant {\n id: string\n /** Option selections keyed by option name; empty for the default variant. */\n options: Record<string, string>\n priceCents: number\n /** A tracked variant at or below zero whose product refuses to oversell. */\n soldOut: boolean\n}\n\nexport interface PosKioskCategory {\n id: string\n name: string\n}\n\nexport interface PosKioskCatalog {\n products: PosKioskProduct[]\n categories: PosKioskCategory[]\n /** The store's currency, lower case (`usd`). */\n currency: string\n /**\n * Set when the store has more to offer than this answer lists, so the menu\n * offers a search that reaches the rest. Absent on an answer that lists\n * everything, which is every catalog the menu can show whole.\n */\n truncated?: boolean\n}\n\n/** What the kiosk offers, resolved on the server for one paired register. */\nexport interface PosKioskContext {\n branding: {\n name: string\n logoUrl: string | null\n logoDarkUrl: string | null\n message: string\n }\n currency: string\n tipping: { enabled: boolean; percentages: number[] }\n payments: {\n /** A Stripe Terminal smart reader is assigned to this register. */\n reader: boolean\n /** Card-present payments are switched on for the platform (Tap to Pay needs the native app too). */\n cardPresent: boolean\n /** \"Pay at counter\" sends the order to the register's queue. */\n payAtCounter: boolean\n }\n receipts: PosReceiptChannel[]\n offerMarketing: boolean\n /** Seconds without a touch before the kiosk asks \"Still there?\". */\n idleSeconds: number\n /** Stripe test mode: a test card can be tapped from the payment screen. */\n testMode: boolean\n}\n\n/** One cart line as the kiosk sends it: ids and a count, never a price. */\nexport interface PosKioskLine {\n productId: string\n variantId?: string\n quantity: number\n modifiers?: ModifierSelection[]\n}\n\n/** A line of a priced kiosk order, as the customer's screen shows it. */\nexport interface PosKioskSaleLine {\n name: string\n variantLabel?: string\n quantity: number\n amountCents: number\n}\n\nexport type PosKioskSaleStatus =\n /** Priced and waiting for a card at the kiosk. */\n | 'open'\n /** Sent to the register's queue; a cashier takes payment. */\n | 'queued'\n | 'paid'\n | 'voided'\n\n/** A kiosk order as its own screen reads it back. */\nexport interface PosKioskSale {\n orderId: string\n /** The order number the customer is called by. */\n number: number\n status: PosKioskSaleStatus\n lines: PosKioskSaleLine[]\n itemsCents: number\n discountCents: number\n taxCents: number\n totalCents: number\n tipCents: number\n paidCents: number\n dueCents: number\n /** The card payment in flight, if any. */\n payment: { id: string; status: string; failureMessage?: string } | null\n}\n\n/** Seconds without a touch before the kiosk asks \"Still there?\", by default. */\nexport const POS_KIOSK_IDLE_SECONDS_DEFAULT = 90\nexport const POS_KIOSK_IDLE_SECONDS_MIN = 30\nexport const POS_KIOSK_IDLE_SECONDS_MAX = 600\n\n/** How long \"Still there?\" waits before the kiosk clears itself. */\nexport const POS_KIOSK_IDLE_WARNING_SECONDS = 20\n\n/** The order-number screen returns to the start after this long. */\nexport const POS_KIOSK_DONE_SECONDS = 15\n\n/** Most lines one kiosk order carries. */\nexport const POS_KIOSK_MAX_LINES = 40\n\n/** Most of one line a customer may order at a kiosk. */\nexport const POS_KIOSK_MAX_QUANTITY = 20\n\n/** Most products the kiosk grid lists at once, for the whole menu, a category or a search. */\nexport const POS_KIOSK_CATALOG_LIMIT = 200\n\n/** Wrong staff PINs a kiosk takes before it locks its unlock screen. */\nexport const POS_KIOSK_UNLOCK_MAX_ATTEMPTS = 5\n\n/** How long a kiosk's unlock screen stays locked after too many wrong PINs. */\nexport const POS_KIOSK_UNLOCK_LOCKOUT_MS = 15 * 60 * 1000\n\n/** How long a staff unlock keeps the kiosk's settings open. */\nexport const POS_KIOSK_UNLOCK_TTL_MS = 5 * 60 * 1000\n\nconst ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The cart as the kiosk may send it, or why not. Ids are shape-checked and\n * quantities bounded here; everything else — whether the product exists, is\n * for sale, what it costs and whether its modifiers are valid — is the sale\n * route's to decide from the product documents.\n */\nexport function sanitizePosKioskLines(\n raw: unknown,\n): { ok: true; lines: PosKioskLine[] } | { ok: false; error: string } {\n if (!Array.isArray(raw) || raw.length === 0) return { ok: false, error: 'Your cart is empty.' }\n if (raw.length > POS_KIOSK_MAX_LINES) {\n return { ok: false, error: `An order can have at most ${POS_KIOSK_MAX_LINES} items.` }\n }\n const lines: PosKioskLine[] = []\n for (const entry of raw as Array<Record<string, unknown>>) {\n const productId = String(entry?.['productId'] ?? '')\n const variantId = entry?.['variantId'] == null ? '' : String(entry['variantId'])\n const quantity = Number(entry?.['quantity'])\n if (!ID_PATTERN.test(productId) || (variantId && !ID_PATTERN.test(variantId))) {\n return { ok: false, error: 'An item in your cart is no longer available.' }\n }\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_KIOSK_MAX_QUANTITY) {\n return { ok: false, error: `Order 1 to ${POS_KIOSK_MAX_QUANTITY} of each item.` }\n }\n const rawModifiers = Array.isArray(entry?.['modifiers']) ? (entry['modifiers'] as unknown[]) : []\n if (rawModifiers.length > 200) return { ok: false, error: 'Too many choices on one item.' }\n const modifiers: ModifierSelection[] = []\n for (const pick of rawModifiers as Array<Record<string, unknown>>) {\n const groupId = String(pick?.['groupId'] ?? '')\n const optionId = String(pick?.['optionId'] ?? '')\n if (!ID_PATTERN.test(groupId) || !ID_PATTERN.test(optionId)) {\n return { ok: false, error: 'A choice on an item is no longer offered.' }\n }\n // A write-in's answer (write-ins), checked against its group when the order is priced.\n const text = cleanWriteIn(pick?.['text'])\n modifiers.push(text ? { groupId, optionId, text } : { groupId, optionId })\n }\n lines.push({\n productId,\n ...(variantId ? { variantId } : {}),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n })\n }\n return { ok: true, lines }\n}\n\n/**\n * The tip a kiosk customer chose, recomputed from the server's own figure\n * for what is being paid: a percentage only from the store's presets, a\n * custom amount bounded like every register tip. Null when the choice is\n * not one the store offers.\n */\nexport function posKioskTipCents(\n choice: unknown,\n input: { baseCents: number; enabled: boolean; percentages: readonly number[]; percent?: unknown; cents?: unknown },\n): number | null {\n if (choice === undefined || choice === null || choice === 'none') return 0\n if (!input.enabled) return null\n if (choice === 'percent') {\n const percent = Math.round(Number(input.percent))\n if (!input.percentages.includes(percent)) return null\n return posTipFromPercent(input.baseCents, percent)\n }\n if (choice === 'custom') {\n const cents = Math.round(Number(input.cents))\n return posTipProblem(cents, input.baseCents) ? null : cents\n }\n return null\n}\n\n/** The idle timeout a merchant set, bounded. */\nexport function posKioskIdleSeconds(raw: unknown): number {\n const value = Math.round(Number(raw))\n if (!Number.isFinite(value) || value <= 0) return POS_KIOSK_IDLE_SECONDS_DEFAULT\n return Math.min(POS_KIOSK_IDLE_SECONDS_MAX, Math.max(POS_KIOSK_IDLE_SECONDS_MIN, value))\n}\n\n/**\n * The kiosk's estimate of its cart, from the catalog prices it was given —\n * shown while the customer shops and never sent. The order is priced again,\n * with tax, by the server when they check out.\n */\nexport function posKioskEstimateCents(\n lines: readonly PosKioskLine[],\n products: readonly PosKioskProduct[],\n): number {\n let total = 0\n for (const line of lines) {\n const product = products.find((candidate) => candidate.id === line.productId)\n if (!product) continue\n const variant =\n product.variants.find((candidate) => candidate.id === line.variantId) ?? product.variants[0]\n if (!variant) continue\n const extra = (line.modifiers ?? []).reduce((sum, pick) => {\n const group = product.modifierGroups.find((candidate) => candidate.id === pick.groupId)\n const option = group?.options.find((candidate) => candidate.id === pick.optionId)\n // A choice priced by variant adds its price on this one (AGL-4100).\n return sum + (option ? modifierOptionPriceCents(option, variant.id) : 0)\n }, 0)\n total += (variant.priceCents + extra) * line.quantity\n }\n return total\n}\n"],"names":["posTipFromPercent","posTipProblem","cleanWriteIn","modifierOptionPriceCents","POS_KIOSK_IDLE_SECONDS_DEFAULT","POS_KIOSK_IDLE_SECONDS_MIN","POS_KIOSK_IDLE_SECONDS_MAX","POS_KIOSK_IDLE_WARNING_SECONDS","POS_KIOSK_DONE_SECONDS","POS_KIOSK_MAX_LINES","POS_KIOSK_MAX_QUANTITY","POS_KIOSK_CATALOG_LIMIT","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","POS_KIOSK_UNLOCK_LOCKOUT_MS","POS_KIOSK_UNLOCK_TTL_MS","ID_PATTERN","sanitizePosKioskLines","raw","Array","isArray","length","ok","error","lines","entry","productId","String","variantId","quantity","Number","test","isInteger","rawModifiers","modifiers","pick","groupId","optionId","text","push","posKioskTipCents","choice","input","undefined","enabled","percent","Math","round","percentages","includes","baseCents","cents","posKioskIdleSeconds","value","isFinite","min","max","posKioskEstimateCents","products","total","line","product","find","candidate","id","variant","variants","extra","reduce","sum","group","modifierGroups","option","options","priceCents"],"mappings":";AAAA;;;;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EAAEQ,MAAM,CAAC,CAACC,KAAKlC;YAChD,MAAMmC,QAAQT,QAAQU,cAAc,CAACT,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAK7B,KAAKC,OAAO;YACtF,MAAMoC,SAASF,yBAAAA,MAAOG,OAAO,CAACX,IAAI,CAAC,CAACC,YAAcA,UAAUC,EAAE,KAAK7B,KAAKE,QAAQ;YAChF,oEAAoE;YACpE,OAAOgC,MAAOG,CAAAA,SAASpE,yBAAyBoE,QAAQP,QAAQD,EAAE,IAAI,CAAA;QACxE,GAAG;QACHL,SAAS,AAACM,CAAAA,QAAQS,UAAU,GAAGP,KAAI,IAAKP,KAAK/B,QAAQ;IACvD;IACA,OAAO8B;AACT"}
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  import { type OrderTotals } from './commerce-orders';
18
- import type { ModifierSelection } from './product-modifiers';
18
+ import { type ModifierSelection } from './product-modifiers';
19
19
  /** The route both register clients sync through. */
20
20
  export declare const POS_OFFLINE_SYNC_ROUTE = "/api/commerce/pos-offline-sync";
21
21
  /** The most sales one sync request carries; a longer queue sends in batches. */
@@ -16,6 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
16
16
  * limitations under the License.
17
17
  */ import { computeOrderTotals } from "./commerce-orders.js";
18
18
  import { computeTaxCents } from "./commerce-tax.js";
19
+ import { cleanWriteIn } from "./product-modifiers.js";
19
20
  import { POS_OFFLINE_CARD_MAX_SALE_CENTS_LIMIT } from "./pos-offline-card-limits.js";
20
21
  /*==========================================
21
22
  * THE OFFLINE REGISTER (AGL-3625): the contract every register client — the
@@ -217,10 +218,15 @@ function wholeCents(value) {
217
218
  'digital',
218
219
  'service'
219
220
  ].includes(line == null ? void 0 : line.productType) ? line.productType : undefined;
220
- const modifiers = Array.isArray(line == null ? void 0 : line.modifiers) ? line.modifiers.slice(0, 50).map((pick)=>({
221
+ const modifiers = Array.isArray(line == null ? void 0 : line.modifiers) ? line.modifiers.slice(0, 50).map((pick)=>{
222
+ const text = cleanWriteIn(pick == null ? void 0 : pick.text);
223
+ return _extends({
221
224
  groupId: cleanId(pick == null ? void 0 : pick.groupId),
222
225
  optionId: cleanId(pick == null ? void 0 : pick.optionId)
223
- })).filter((pick)=>pick.groupId && pick.optionId) : [];
226
+ }, text ? {
227
+ text
228
+ } : {});
229
+ }).filter((pick)=>pick.groupId && pick.optionId) : [];
224
230
  lines.push(_extends({
225
231
  productId
226
232
  }, variantId ? {
@@ -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 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,4EAA4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EnF,OAAOkF,MAAME,QAAQ,CAAC,GAAG,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 { cleanWriteIn, 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) => {\n const text = cleanWriteIn(pick?.text)\n return { groupId: cleanId(pick?.groupId), optionId: cleanId(pick?.optionId), ...(text ? { text } : {}) }\n })\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","cleanWriteIn","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","text","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;AAChD,SAASC,YAAY,QAAgC,yBAAqB;AAC1E,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,O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38,7 @@ export interface ProductFieldValue {
38
38
  modifiers?: Array<{
39
39
  groupId: string;
40
40
  optionId: string;
41
+ text?: string;
41
42
  }>;
42
43
  /** How many the shopper asked about, 1 to {@link PRODUCT_FIELD_MAX_QUANTITY}. Absent: one. */
43
44
  quantity?: number;
@@ -15,6 +15,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { QUOTE_MAX_QUANTITY } from "./commerce-quotes.js";
18
+ import { cleanWriteIn } from "./product-modifiers.js";
18
19
  /*==========================================
19
20
  * A QUOTE STARTED FROM A REQUEST (AGL-4098).
20
21
  *
@@ -89,10 +90,13 @@ const text = (value, max = 200)=>typeof value === 'string' ? value.trim().slice(
89
90
  }
90
91
  const modifiers = Array.isArray(source['modifiers']) ? source['modifiers'].slice(0, MAX_MODIFIERS).map((entry)=>{
91
92
  const pick = entry != null ? entry : {};
92
- return {
93
+ const answer = cleanWriteIn(pick['text']);
94
+ return _extends({
93
95
  groupId: text(pick['groupId']),
94
96
  optionId: text(pick['optionId'])
95
- };
97
+ }, answer ? {
98
+ text: answer
99
+ } : {});
96
100
  }).filter((pick)=>pick.groupId && pick.optionId) : [];
97
101
  const quantity = fieldQuantity(source['quantity']);
98
102
  return _extends({