@aglyn/plugins-commerce 1.13.0 → 1.15.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 (152) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/account-subscriptions.d.ts +51 -0
  3. package/src/lib/components/account-subscriptions.js +168 -0
  4. package/src/lib/components/account-subscriptions.js.map +1 -0
  5. package/src/lib/components/account.js +12 -48
  6. package/src/lib/components/account.js.map +1 -1
  7. package/src/lib/components/cart.js +30 -6
  8. package/src/lib/components/cart.js.map +1 -1
  9. package/src/lib/components/commerce-console-page.js +6 -0
  10. package/src/lib/components/commerce-console-page.js.map +1 -1
  11. package/src/lib/components/commerce-console-sections.d.ts +1 -1
  12. package/src/lib/components/commerce-console-sections.js +5 -0
  13. package/src/lib/components/commerce-console-sections.js.map +1 -1
  14. package/src/lib/components/console/paid-media.d.ts +1 -0
  15. package/src/lib/components/console/paid-media.js +15 -4
  16. package/src/lib/components/console/paid-media.js.map +1 -1
  17. package/src/lib/components/console/payments-settings-card.component.js +1 -1
  18. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  19. package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
  20. package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
  21. package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
  22. package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
  23. package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
  24. package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
  25. package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
  26. package/src/lib/components/console/pos-cellular-control.component.js +5 -5
  27. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  28. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  29. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  30. package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
  31. package/src/lib/components/console/pos-hardware-card.component.js +77 -8
  32. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  33. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
  34. package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
  35. package/src/lib/components/console/pos-page.component.js +19 -2
  36. package/src/lib/components/console/pos-page.component.js.map +1 -1
  37. package/src/lib/components/console/product-editor-dialog.component.js +21 -2
  38. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  39. package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
  40. package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
  41. package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
  42. package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
  43. package/src/lib/components/console/subscriptions-card.component.js +280 -0
  44. package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
  45. package/src/lib/components/hardware-terms-consent.d.ts +22 -0
  46. package/src/lib/components/hardware-terms-consent.js +85 -0
  47. package/src/lib/components/hardware-terms-consent.js.map +1 -0
  48. package/src/lib/components/product-detail.js +25 -5
  49. package/src/lib/components/product-detail.js.map +1 -1
  50. package/src/lib/constants/operator-alerts.d.ts +1 -1
  51. package/src/lib/constants/operator-alerts.js +4 -4
  52. package/src/lib/constants/operator-alerts.js.map +1 -1
  53. package/src/lib/model/commerce-orders.d.ts +6 -2
  54. package/src/lib/model/commerce-orders.js.map +1 -1
  55. package/src/lib/model/commerce-payment-methods.d.ts +24 -0
  56. package/src/lib/model/commerce-payment-methods.js +35 -0
  57. package/src/lib/model/commerce-payment-methods.js.map +1 -1
  58. package/src/lib/model/commerce.d.ts +6 -0
  59. package/src/lib/model/commerce.js.map +1 -1
  60. package/src/lib/model/index.d.ts +1 -0
  61. package/src/lib/model/index.js +1 -0
  62. package/src/lib/model/index.js.map +1 -1
  63. package/src/lib/model/paid-media.d.ts +8 -0
  64. package/src/lib/model/paid-media.js +13 -0
  65. package/src/lib/model/paid-media.js.map +1 -1
  66. package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
  67. package/src/lib/model/pos-hardware-in-person.js +52 -20
  68. package/src/lib/model/pos-hardware-in-person.js.map +1 -1
  69. package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
  70. package/src/lib/model/pos-hardware-tax-summary.js +2 -1
  71. package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
  72. package/src/lib/model/pos-hardware-terms.d.ts +37 -2
  73. package/src/lib/model/pos-hardware-terms.js +68 -3
  74. package/src/lib/model/pos-hardware-terms.js.map +1 -1
  75. package/src/lib/model/pos-hardware.d.ts +101 -15
  76. package/src/lib/model/pos-hardware.js +128 -18
  77. package/src/lib/model/pos-hardware.js.map +1 -1
  78. package/src/lib/model/pos-reader-splash.js +2 -2
  79. package/src/lib/model/pos-reader-splash.js.map +1 -1
  80. package/src/lib/model/product-write.d.ts +3 -0
  81. package/src/lib/model/subscription-view.d.ts +90 -0
  82. package/src/lib/model/subscription-view.js +176 -0
  83. package/src/lib/model/subscription-view.js.map +1 -0
  84. package/src/lib/server/billing-webhook.d.ts +4 -6
  85. package/src/lib/server/billing-webhook.js +109 -51
  86. package/src/lib/server/billing-webhook.js.map +1 -1
  87. package/src/lib/server/cart-checkout.js +45 -10
  88. package/src/lib/server/cart-checkout.js.map +1 -1
  89. package/src/lib/server/cart.js +15 -3
  90. package/src/lib/server/cart.js.map +1 -1
  91. package/src/lib/server/checkout.js +58 -16
  92. package/src/lib/server/checkout.js.map +1 -1
  93. package/src/lib/server/draft-order.js +7 -3
  94. package/src/lib/server/draft-order.js.map +1 -1
  95. package/src/lib/server/membership-account.d.ts +22 -0
  96. package/src/lib/server/membership-account.js +52 -8
  97. package/src/lib/server/membership-account.js.map +1 -1
  98. package/src/lib/server/pos-auth.d.ts +3 -3
  99. package/src/lib/server/pos-auth.js +3 -3
  100. package/src/lib/server/pos-auth.js.map +1 -1
  101. package/src/lib/server/pos-cellular-billing.js +1 -1
  102. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  103. package/src/lib/server/pos-cellular-notify.js +1 -1
  104. package/src/lib/server/pos-cellular-notify.js.map +1 -1
  105. package/src/lib/server/pos-cellular.js +1 -1
  106. package/src/lib/server/pos-cellular.js.map +1 -1
  107. package/src/lib/server/pos-hardware-admin.js +86 -13
  108. package/src/lib/server/pos-hardware-admin.js.map +1 -1
  109. package/src/lib/server/pos-hardware-attach.js +5 -5
  110. package/src/lib/server/pos-hardware-attach.js.map +1 -1
  111. package/src/lib/server/pos-hardware-cancel.js +65 -0
  112. package/src/lib/server/pos-hardware-cancel.js.map +1 -1
  113. package/src/lib/server/pos-hardware-closure-notices.js +2 -5
  114. package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
  115. package/src/lib/server/pos-hardware-closure.js +5 -8
  116. package/src/lib/server/pos-hardware-closure.js.map +1 -1
  117. package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
  118. package/src/lib/server/pos-hardware-in-person.js +72 -17
  119. package/src/lib/server/pos-hardware-in-person.js.map +1 -1
  120. package/src/lib/server/pos-hardware-notify.d.ts +2 -0
  121. package/src/lib/server/pos-hardware-notify.js +30 -5
  122. package/src/lib/server/pos-hardware-notify.js.map +1 -1
  123. package/src/lib/server/pos-hardware-readers.d.ts +25 -0
  124. package/src/lib/server/pos-hardware-readers.js +206 -85
  125. package/src/lib/server/pos-hardware-readers.js.map +1 -1
  126. package/src/lib/server/pos-hardware-returns.d.ts +8 -3
  127. package/src/lib/server/pos-hardware-returns.js +39 -7
  128. package/src/lib/server/pos-hardware-returns.js.map +1 -1
  129. package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
  130. package/src/lib/server/pos-hardware-sale-fields.js +114 -1
  131. package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
  132. package/src/lib/server/pos-hardware-sale.d.ts +2 -0
  133. package/src/lib/server/pos-hardware-sale.js +1 -0
  134. package/src/lib/server/pos-hardware-sale.js.map +1 -1
  135. package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
  136. package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
  137. package/src/lib/server/pos-hardware-webhook.js +16 -3
  138. package/src/lib/server/pos-hardware-webhook.js.map +1 -1
  139. package/src/lib/server/pos-hardware.d.ts +14 -3
  140. package/src/lib/server/pos-hardware.js +83 -18
  141. package/src/lib/server/pos-hardware.js.map +1 -1
  142. package/src/lib/server/pos-ops-routes.js +2 -10
  143. package/src/lib/server/pos-ops-routes.js.map +1 -1
  144. package/src/lib/server/quote-pay.js +8 -4
  145. package/src/lib/server/quote-pay.js.map +1 -1
  146. package/src/lib/server/stream.d.ts +2 -0
  147. package/src/lib/server/stream.js +22 -2
  148. package/src/lib/server/stream.js.map +1 -1
  149. package/src/lib/server/tax-return-source.js +5 -1
  150. package/src/lib/server/tax-return-source.js.map +1 -1
  151. package/src/lib/server.js +2 -2
  152. package/src/lib/server.js.map +1 -1
@@ -32,6 +32,8 @@ import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
32
32
  import { useFirestoreCollection } from "@aglyn/tenant-feature-instance";
33
33
  import { listQueryConstraints } from "@aglyn/tenant-feature-instance/hooks/use-list-query";
34
34
  import { useOrgPlan } from "@aglyn/tenant-feature-instance";
35
+ import { resolvePlanFeatureLock } from "@aglyn/tenant-feature-instance/hooks/plan-feature-lock";
36
+ import { EntitlementUpsell } from "./entitlement-gate.component.js";
35
37
  import { newAttemptKey, openPosSale, posRegisterContext, posTender, PosRequestError, usd } from "./pos/pos-api.js";
36
38
  import { PosCartPanel } from "./pos/pos-cart-panel.component.js";
37
39
  import { ScanAdornment } from "../../barcode/scan-button.component.js";
@@ -46,7 +48,7 @@ import { posDisplayTipCents, usePosDisplay } from "./pos/use-pos-display.js";
46
48
  import { posRegistersSettingsHref, usePosPairing } from "./pos/pos-pairing.component.js";
47
49
  import { useConsoleWidgetSlot } from "@aglyn/aglyn/app-utils/console-widget-slot-context";
48
50
  import { POS_ORDERS_ZONE } from "./pos-zones.js";
49
- import { isPosHardwareSkuId } from "../../model/pos-hardware.js";
51
+ import { isPosHardwareSkuId, posPlanPrompt } from "../../model/pos-hardware.js";
50
52
  /**
51
53
  * Card reader sales at the platform's own store (AGL-4038): attaching the
52
54
  * buyer and the To attach list. Its own chunk, and it draws nothing on any
@@ -195,7 +197,7 @@ import { PosOfflineBanner, PosOfflineCheckout, usePosOffline } from "./pos-offli
195
197
  });
196
198
  export function PosConsolePage({ hostId, basePath, permissions }) {
197
199
  var _ref, _ref1, _ref2, _liveRegister_openShiftId, _ref3, _ref4, _ref5;
198
- var _usableRegisters_find, _usableRegisters_, _offline_totalsFor;
200
+ var _exec, _usableRegisters_find, _usableRegisters_, _offline_totalsFor;
199
201
  /*
200
202
  * The register's FINER keys (AGL-4047) — discounts, returns, the drawer —
201
203
  * are read here, unlike `managePos` above: the shell admits anyone who may
@@ -285,6 +287,15 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
285
287
  const registerCap = Aglyn.checkHostRegisterQuota(org, hostId, registers.length).limit;
286
288
  const withinCap = CommerceModel.registersWithinCap(registers, registerCap);
287
289
  const usableRegisters = planReady ? registers.filter((r)=>withinCap.has(r.$id)) : [];
290
+ // A workspace that bought a reader without the point of sale (AGL-4038)
291
+ // is told what adding it gives it, from the org doc already held and the
292
+ // workspace in this page's own path (`/{org}/hosts/{host}/pos`): no read.
293
+ const posPlan = resolvePlanFeatureLock({
294
+ org,
295
+ ready: planReady,
296
+ feature: 'pos',
297
+ orgSlug: (_exec = /^\/([^/]+)\/hosts\//.exec(basePath != null ? basePath : '')) == null ? void 0 : _exec[1]
298
+ });
288
299
  /*
289
300
  * The stays a sale can be charged to, asked for BY STATUS (AGL-3321).
290
301
  */ const { data: reservationDocs } = useFirestoreCollection(()=>query(collection(firestore, 'hosts', hostId, 'reservations'), where('status', '==', 'checked_in'), limit(100)), [
@@ -735,6 +746,12 @@ export function PosConsolePage({ hostId, basePath, permissions }) {
735
746
  variant: "body2",
736
747
  color: "text.secondary",
737
748
  children: 'Checking your plan…'
749
+ }) : posPlan.locked ? /*#__PURE__*/ _jsx(EntitlementUpsell, {
750
+ planLabel: posPlan.planLabel,
751
+ upgradeHref: posPlan.upgradeHref,
752
+ children: posPlanPrompt({
753
+ atRegister: true
754
+ })
738
755
  }) : usableRegisters.length === 0 ? registers.length > 0 ? /*#__PURE__*/ _jsx(Typography, {
739
756
  variant: "body2",
740
757
  color: "warning.main",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos-page.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport type { ConsolePluginPageProps } from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { posPermissionRefusal, type PosPermission } from '../../model/plugin-permissions'\nimport {\n PRODUCT_LIST_BASE,\n PRODUCT_LIST_QUERY,\n} from '../../constants/product-list-query'\nimport { NextPageTitle } from '@aglyn/shared-ui-next/contexts/next-page-title-provider'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport type { ListFilterRequest } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { planListQuery } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useViewportFill } from '@aglyn/shared-ui-jsx/hooks/use-viewport-fill'\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n Badge,\n Box,\n Button,\n Drawer,\n MenuItem,\n Stack,\n TextField,\n Typography,\n useMediaQuery,\n useTheme,\n} from '@mui/material'\nimport {\n collection,\n getDocs,\n limit,\n query,\n where,\n} from 'firebase/firestore'\nimport { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreCollection } from '@aglyn/tenant-feature-instance'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport {\n newAttemptKey,\n openPosSale,\n posRegisterContext,\n posTender,\n PosRequestError,\n usd,\n type PosRegisterContext,\n type PosSaleSummary,\n} from './pos/pos-api'\nimport { PosCartPanel, type RegisterLine } from './pos/pos-cart-panel.component'\nimport { ScanAdornment } from '../../barcode/scan-button.component'\nimport { useScannerWedge } from '../../barcode/scanner-wedge'\nimport {\n PosCustomerLookup,\n PosLastReceipt,\n PosOperationsBar,\n usePosCashier,\n usePosOpsSettings,\n type PosSelectedCustomer,\n} from './pos-ops/register-ops'\nimport { POS_QUICK_KEYS, POS_TOUCH_PX, PosProductGrid } from './pos/pos-product-grid.component'\nimport { PosItemDialog, posItemNeedsChoice, type PosItemChoice } from './pos/pos-item-dialog.component'\nimport { PosReceiptPanel } from './pos/pos-receipt-panel.component'\nimport { PosTenderPanel } from './pos/pos-tender-panel.component'\nimport { PosKioskQueue } from './pos/pos-kiosk-queue.component'\nimport { posDisplayTipCents, usePosDisplay } from './pos/use-pos-display'\nimport { posRegistersSettingsHref, usePosPairing } from './pos/pos-pairing.component'\nimport {\n type ConsoleWidgetSlotRenderer,\n useConsoleWidgetSlot,\n} from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { POS_ORDERS_ZONE } from './pos-zones'\nimport { isPosHardwareSkuId } from '../../model/pos-hardware'\n\n/**\n * Card reader sales at the platform's own store (AGL-4038): attaching the\n * buyer and the To attach list. Its own chunk, and it draws nothing on any\n * store but that one.\n */\nconst PosHardwareBuyer = lazy(() => import('./pos/pos-hardware-buyer.component'))\nimport { PosOfflineBanner, PosOfflineCheckout, usePosOffline } from './pos-offline/register-offline'\n\n/** The till sells active products only; every read of the catalog asks it. */\nconst SELLABLE: ListFilterRequest = { field: 'status', op: 'equals', value: 'active' }\n\n/**\n * How many products the till's grid shows. The grid is a picker, not the\n * catalog: typing narrows it on the query, so a name reaches every product.\n */\nconst POS_GRID_CEILING = 500\n\n/**\n * The products hub's query (AGL-3321), narrowed to what the till may sell:\n * live products (`deletedAt == null`, the list's scope), `status == active`,\n * and any typed word as the search on `nameTokens` — or, for a scan, the\n * whole scanned code as a SKU or barcode clause. Every shape is one the hub's\n * composites already serve.\n */\nexport function posProductPlan(options: {\n search?: string\n code?: { field: 'barcodes' | 'skus'; value: string }\n /** A category chip (AGL-3607): served by the storefront's own composite. */\n categoryId?: string\n /** The Quick keys chip (AGL-3607): products marked `posQuickKey`. */\n quickKeys?: boolean\n}) {\n const typed = options.search?.trim()\n const plan = planListQuery(\n POS_GRID_QUERY,\n {\n base: PRODUCT_LIST_BASE,\n clauses: [\n SELLABLE,\n ...(options.code\n ? [{ field: options.code.field, op: 'contains', value: options.code.value }]\n : []),\n ...(options.categoryId\n ? [{ field: 'categoryIds', op: 'contains', value: options.categoryId }]\n : []),\n ],\n // A chip and a typed word are both array clauses, and Firestore takes\n // one: with a chip on, the word narrows by name prefix instead.\n search: typed && !options.categoryId ? [typed] : [],\n },\n nameSearchNormalizers,\n )\n // The Quick keys chip (AGL-3607) is a boolean equality the list planner\n // does not model, added beside the scope and status it composes with —\n // `deletedAt ==, status ==, posQuickKey ==, nameLower ASC` is declared in\n // the index file. A typed word searches the whole catalog instead: a\n // cashier who types is looking past the quick keys.\n if (options.quickKeys && !typed && !options.code) {\n return {\n ...plan,\n filters: [...plan.filters, { path: 'posQuickKey', op: '==', value: true }],\n } as typeof plan\n }\n return plan\n}\n\n/**\n * The grid's query: the products hub's, plus the category a chip picks\n * (AGL-3607). `categoryIds CONTAINS, nameLower ASC` is a composite the\n * storefront catalog already declares.\n */\nexport const POS_GRID_QUERY = {\n ...PRODUCT_LIST_QUERY,\n fields: [\n ...PRODUCT_LIST_QUERY.fields,\n {\n column: 'categoryIds',\n kind: 'exact' as const,\n path: 'categoryIds',\n tokensPath: 'categoryIds',\n operators: ['contains'],\n },\n ],\n} as typeof PRODUCT_LIST_QUERY\n\n/**\n * POS register (AGL-312, AGL-3607): a tablet-first sale surface — the\n * product grid with search, scan and category chips, the basket, and a\n * tender panel that takes one or more payments against an open sale (cash,\n * card reader, a native Tap to Pay bridge, a typed card, the QR link, gift\n * cards and room charges) until the balance is zero. A paired customer\n * display mirrors the basket and takes the tip and the receipt (AGL-3608).\n *\n * On a wide screen (900px and up) the grid and the register sit side by\n * side; below that the register is a bottom sheet behind a sticky total bar.\n */\n/*\n * `managePos` is NOT read here. The nav item in `plugin.ts` declares it and\n * the shell refuses the route before this component is constructed, so a\n * reader without the key never reaches this file and there is no unpermitted\n * state for it to render — the same arrangement the entitlement gate has.\n *\n * Re-adding a check off the `permissions` prop would be a second answer to a\n * settled question, and a laxer one: a prop absent because the map has not\n * landed reads as permitted here, while the shell holds the route on that\n * same condition rather than guessing. The server routes remain the\n * enforcement point for every sale and every payment.\n */\n/** Where a register device remembers the category chip it was left on. */\nconst POS_CATEGORY_KEY = 'aglyn.pos.category'\n\n/** The basket line an item-sheet choice makes: label and estimate from the product. */\nexport function registerLineFor(\n product: any,\n choice: PosItemChoice,\n): RegisterLine {\n const { variant, modifiers, quantity } = choice\n const resolved = CommerceModel.resolveLineModifiers(product, modifiers, variant?.id)\n const picked = resolved.ok ? resolved.modifiers : []\n const label = CommerceModel.lineLabelWithModifiers(\n Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined,\n picked,\n )\n return {\n productId: product.$id,\n ...(variant.id !== 'default' ? { variantId: variant.id } : {}),\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents:\n Math.round(Number(variant.priceUsd) * 100) + (resolved.ok ? resolved.extraCents : 0),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n }\n}\n\n/** Same product, variant and choices: the lines that merge into one. */\nfunction lineKey(line: Pick<RegisterLine, 'productId' | 'variantId' | 'modifiers'>): string {\n return `${line.productId}:${line.variantId ?? ''}:${CommerceModel.modifierSelectionKey(line.modifiers)}`\n}\n\n/**\n * The register's zone (AGL-3644), drawn again only when what it is handed\n * changes: the till redraws on every tap, and the shell's renderer is not\n * memoized (the order dialog's reasoning).\n */\nconst PosOrdersZone = memo(function PosOrdersZone(props: {\n renderer: ConsoleWidgetSlotRenderer\n hostId: string\n registerId: string | null\n}) {\n const { renderer: Renderer, hostId, registerId } = props\n return <Renderer slot={POS_ORDERS_ZONE.id} hostId={hostId} orgId={undefined} registerId={registerId} />\n})\n\nexport function PosConsolePage({ hostId, basePath, permissions }: ConsolePluginPageProps) {\n /*\n * The register's FINER keys (AGL-4047) — discounts, returns, the drawer —\n * are read here, unlike `managePos` above: the shell admits anyone who may\n * use the register, and these say which of its controls are theirs. Only an\n * explicit refusal disables one; a map without the key follows `managePos`,\n * which the shell already confirmed. The routes refuse either way.\n */\n const refusedReason = (key: PosPermission): string | undefined =>\n permissions?.[key] === false ? posPermissionRefusal(key) : undefined\n const blockedControls = {\n returns: refusedReason('posRefund'),\n shift: refusedReason('posCashDrawer'),\n }\n const discountBlocked = refusedReason('posDiscount')\n const WidgetSlot = useConsoleWidgetSlot()\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const theme = useTheme()\n const wide = useMediaQuery(theme.breakpoints.up('md'))\n\n const [search, setSearch] = useState('')\n // The chip a register opens on is remembered per device: a counter that\n // rings from its quick keys reopens on them.\n const [categoryId, setCategoryIdState] = useState(() => {\n try {\n return window.localStorage.getItem(POS_CATEGORY_KEY) ?? ''\n } catch {\n return ''\n }\n })\n const setCategoryId = useCallback((id: string) => {\n setCategoryIdState(id)\n try {\n window.localStorage.setItem(POS_CATEGORY_KEY, id)\n } catch {\n // Storage blocked: the chip still works for this visit.\n }\n }, [])\n const gridPlan = useMemo(\n () =>\n categoryId === POS_QUICK_KEYS\n ? posProductPlan({ search, quickKeys: true })\n : posProductPlan({ search, categoryId }),\n [search, categoryId],\n )\n const { data: productDocs } = useFirestoreCollection<any>(\n /*\n * The till's grid, narrowed by the QUERY rather than by the rows it\n * happened to fetch (AGL-2501, AGL-2292, AGL-3321): the first five\n * hundred SELLABLE products by name, and a typed name reaches the whole\n * catalog. The scan does not come through here — see `handleSearchEnter`.\n */\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'products'),\n ...listQueryConstraints(gridPlan),\n limit(POS_GRID_CEILING),\n ),\n [firestore, hostId, gridPlan],\n { idField: '$id' },\n )\n const { data: categoryDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'productCategories'), limit(30)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { data: locationDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'locations'), limit(25)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { data: registerDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'registers'), limit(25)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { org, ready: planReady } = useOrgPlan(hostId)\n const registers = [...(registerDocs ?? [])].sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n )\n // Only registers within the plan cap can transact (AGL-482), and not until\n // the org doc has arrived (AGL-1064). Per SITE (AGL-1775).\n const registerCap = Aglyn.checkHostRegisterQuota(org, hostId, registers.length).limit\n const withinCap = CommerceModel.registersWithinCap(registers, registerCap)\n const usableRegisters = planReady ? registers.filter((r: any) => withinCap.has(r.$id)) : []\n /*\n * The stays a sale can be charged to, asked for BY STATUS (AGL-3321).\n */\n const { data: reservationDocs } = useFirestoreCollection<any>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n where('status', '==', 'checked_in'),\n limit(100),\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const openStays = reservationDocs ?? []\n\n const [lines, setLines] = useState<RegisterLine[]>([])\n const [discountPct, setDiscountPct] = useState(0)\n // The customer the lookup attached (AGL-3609); their email is the sale's.\n const [customer, setCustomer] = useState<PosSelectedCustomer | null>(null)\n const customerEmail = customer?.email ?? ''\n const [locationId, setLocationId] = useState('')\n const [registerId, setRegisterId] = useState('')\n useEffect(() => {\n if (registerId || usableRegisters.length === 0) return\n const first = usableRegisters[0]\n setRegisterId(first.$id)\n if (first.locationId) setLocationId(first.locationId)\n }, [usableRegisters, registerId])\n const registerName = String(\n usableRegisters.find((register: any) => register.$id === registerId)?.name ?? '',\n )\n // Who is ringing (AGL-3609): a PIN-switched cashier, and the idle lock.\n const opsSettings = usePosOpsSettings(hostId)\n const cashier = usePosCashier({\n hostId,\n registerId,\n autoLockMinutes: opsSettings.autoLockMinutes,\n })\n // The last completed sale, whose receipt can still be printed (AGL-3609).\n const [lastReceipt, setLastReceipt] = useState<{ orderId: string } | null>(null)\n\n const [context, setContext] = useState<PosRegisterContext | null>(null)\n // Keyed on the uid, not the user object: a session refresh hands back a\n // new object for the same person, and re-reading the context on every one\n // would re-render the register in a loop.\n const userRef = useRef(user)\n userRef.current = user\n const uid = user?.uid ?? ''\n useEffect(() => {\n const signedIn = userRef.current\n if (!signedIn) return\n let active = true\n posRegisterContext(signedIn, hostId)\n .then((answer) => {\n // Only a whole answer: a register that half-knows its tenders would\n // offer one the server then refuses.\n if (active && answer?.settings && answer?.terminal) setContext(answer)\n })\n .catch(() => undefined)\n return () => {\n active = false\n }\n }, [uid, hostId])\n\n /** The open sale, once the basket has been priced and payment started. */\n const [sale, setSale] = useState<PosSaleSummary | null>(null)\n const [saleLines, setSaleLines] = useState<RegisterLine[]>([])\n const [opening, setOpening] = useState(false)\n const [sheetOpen, setSheetOpen] = useState(false)\n const display = usePosDisplay(user, hostId, registerId)\n\n /**\n * One key per basket (AGL-1691): minted on the first Charge and retired\n * whenever the basket changes, so a retried Charge finds the same sale and\n * ringing the same coffee twice is two sales.\n */\n const attemptKey = useRef('')\n const fill = useViewportFill({ min: 480 })\n useEffect(() => {\n attemptKey.current = ''\n }, [lines, discountPct])\n\n const products = useMemo(\n () =>\n [...(productDocs ?? [])].map((product: any) => ({\n ...CommerceModel.liftLegacyProduct(product),\n $id: product.$id,\n })),\n [productDocs],\n )\n /*\n * THE OFFLINE REGISTER (AGL-3625): the catalog and the site's offline rules\n * kept on this device, the queue of cash sales rung without a connection,\n * and the sync that records them once it returns.\n */\n const loadCatalog = useCallback(\n async () =>\n (\n await getDocs(\n query(\n collection(firestore, 'hosts', hostId, 'products'),\n ...listQueryConstraints(posProductPlan({})),\n limit(POS_GRID_CEILING),\n ),\n )\n ).docs.map((snapshot) => ({ ...(snapshot.data() as Record<string, unknown>), $id: snapshot.id })),\n [firestore, hostId],\n )\n const liveRegister = usableRegisters.find((register: any) => register.$id === registerId)\n const offline = usePosOffline({\n hostId,\n user,\n registerId,\n openShiftId: liveRegister ? (liveRegister.openShiftId ?? null) : undefined,\n locationId,\n ...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {}),\n liveProducts: products,\n loadCatalog,\n })\n const [offlineCheckout, setOfflineCheckout] = useState(false)\n /** Open sales left unpaid when the connection dropped, voided once it returns. */\n const strandedSales = useRef<string[]>([])\n useEffect(() => {\n if (offline.offline || !user || !strandedSales.current.length) return\n const orderIds = strandedSales.current.splice(0)\n for (const orderId of orderIds) {\n void posTender(user, hostId, orderId, 'void').catch(() => undefined)\n }\n }, [offline.offline, user, hostId])\n const sellProducts = useMemo(\n () => (offline.offline && offline.ready ? offline.gridProducts(search, categoryId, POS_QUICK_KEYS) : products),\n [offline, search, categoryId, products],\n )\n const productsById = useMemo(\n () => new Map<string, any>(sellProducts.map((product: any) => [product.$id, product] as const)),\n [sellProducts],\n )\n // Whether the sale on the register sells a card reader (AGL-4038): only\n // the platform's own store names hardware on a product, and only there\n // does the buyer step draw.\n const saleSellsHardware = useMemo(\n () =>\n (sale ? saleLines : lines).some((line) => isPosHardwareSkuId(productsById.get(line.productId)?.hardwareSku)),\n [sale, saleLines, lines, productsById],\n )\n // Only a store whose catalog names hardware asks whether it is the seller.\n const storeSellsHardware = useMemo(\n () => products.some((product: { hardwareSku?: unknown }) => isPosHardwareSkuId(product.hardwareSku)),\n [products],\n )\n /** AGL-2357: warns, never blocks. */\n const shortfalls = useMemo(\n () =>\n lines.map((line) => {\n const product: any = productsById.get(line.productId)\n if (!product) return null\n return CommerceModel.stockShortfall(\n product,\n line.variantId ?? product.variants?.[0]?.id,\n line.quantity,\n )\n }),\n [lines, productsById],\n )\n\n const itemsCents = lines.reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n const discountCents = Math.round((itemsCents * discountPct) / 100)\n const estimateCents = itemsCents - discountCents\n const units = lines.reduce((sum, line) => sum + line.quantity, 0)\n\n const notify = useCallback(\n (message: string, variant: 'success' | 'error' | 'warning' | 'info') => {\n enqueueSnackbar(message, { variant, persist: false, allowDuplicate: true })\n },\n [enqueueSnackbar],\n )\n\n /**\n * A pairing code for a customer display or a self-service kiosk (AGL-3623),\n * through the same flow the POS devices card offers (AGL-3712).\n */\n const onPairingError = useCallback((message: string) => notify(message, 'error'), [notify])\n const pairingFlow = usePosPairing({ user, hostId, onError: onPairingError })\n\n /**\n * Adds a line, or more of an identical one: the same product, variant and\n * modifiers merge, so two oat lattes are one line of two and an oat latte\n * beside a whole-milk one stays two lines.\n */\n const addProduct = useCallback(\n (product: any, variant?: any, modifiers: CommerceModel.ModifierSelection[] = [], quantity = 1) => {\n const next = registerLineFor(product, {\n variant: variant ?? product.variants[0],\n modifiers,\n quantity,\n })\n setLines((prev) => {\n const existing = prev.find((line) => lineKey(line) === lineKey(next))\n if (existing) {\n return prev.map((line) =>\n line === existing\n ? { ...line, quantity: Math.min(99, line.quantity + next.quantity) }\n : line,\n )\n }\n return [...prev, next]\n })\n },\n [],\n )\n\n /** The item sheet: a product to add, or a basket line to change. */\n const [itemSheet, setItemSheet] = useState<{\n product: any\n editIndex?: number\n initial?: { variantId?: string; modifiers?: CommerceModel.ModifierSelection[]; quantity: number }\n } | null>(null)\n // Every product rung up this sale, so a line can be reopened after the\n // grid has moved on to another category or search.\n const productCache = useRef(new Map<string, any>())\n const tapProduct = useCallback(\n (product: any, variant?: any) => {\n productCache.current.set(product.$id, product)\n if (posItemNeedsChoice(product) && !(variant && CommerceModel.productModifierGroups(product).length === 0)) {\n setItemSheet({\n product,\n ...(variant ? { initial: { variantId: variant.id, quantity: 1 } } : {}),\n })\n return\n }\n addProduct(product, variant)\n },\n [addProduct],\n )\n const basketCounts = useMemo(() => {\n const counts = new Map<string, number>()\n for (const line of lines) counts.set(line.productId, (counts.get(line.productId) ?? 0) + line.quantity)\n return counts\n }, [lines])\n\n /**\n * The barcode wedge: a LOOKUP against the whole catalog (AGL-2501),\n * barcode first, and a miss says so.\n */\n const lookupCode = useCallback(async (scanned: string) => {\n const needle = scanned.trim().toLowerCase()\n if (!needle || sale) return\n if (offline.offline) {\n const found = offline.findByCode(needle)\n if (!found) return void notify(`No product matches “${scanned.trim()}”`, 'warning')\n tapProduct(found.product, found.variant)\n setSearch('')\n return\n }\n const lookup = async (field: 'barcodes' | 'skus') => {\n const found = await getDocs(\n query(\n collection(firestore, 'hosts', hostId, 'products'),\n ...listQueryConstraints(posProductPlan({ code: { field, value: needle } })),\n limit(1),\n ),\n )\n return found.docs[0]\n }\n let hit: Awaited<ReturnType<typeof lookup>>\n try {\n hit = (await lookup('barcodes')) ?? (await lookup('skus'))\n } catch (error) {\n console.error(error)\n offline.reportNetworkFailure()\n return void notify('Could not reach the catalog — try again', 'warning')\n }\n if (!hit) return void notify(`No product matches “${scanned.trim()}”`, 'warning')\n const product = { ...CommerceModel.liftLegacyProduct(hit.data() as any), $id: hit.id }\n const variant =\n product.variants.find(\n (item: any) =>\n item.barcode?.trim().toLowerCase() === needle || item.sku?.trim().toLowerCase() === needle,\n ) ?? product.variants[0]\n // A scanned variant is the variant; a product with modifiers still asks\n // for them, with that variant already picked.\n tapProduct(product, variant)\n setSearch('')\n }, [sale, firestore, hostId, tapProduct, notify, offline])\n const handleSearchEnter = useCallback(() => lookupCode(search), [lookupCode, search])\n // A scanner fired while focus is on a product or a button (AGL-3619), and\n // the camera; neither while a sale is taking payment or an item is open.\n useScannerWedge((code) => void lookupCode(code), !sale && !itemSheet)\n const scanAdornment = useMemo(\n () => <ScanAdornment label=\"Scan a barcode with the camera\" onScan={(code) => void lookupCode(code)} />,\n [lookupCode],\n )\n\n /** Prices the basket on the server and opens the sale for payment. */\n // A ref, not `opening`: two taps inside one React batch both read the\n // pre-click state, and only a ref is written before the second reads it\n // (the AGL-1682 lesson).\n const chargeInFlight = useRef(false)\n const charge = useCallback(async () => {\n if (chargeInFlight.current || lines.length === 0 || !user) return\n if (!registerId) return void notify('Select a register before taking payment', 'warning')\n // Offline, the basket rings as a cash sale kept on this register (AGL-3625).\n if (offline.offline) {\n if (!offline.ready) return void notify(offline.unavailableReason ?? 'Offline selling is unavailable', 'warning')\n setOfflineCheckout(true)\n return\n }\n if (!attemptKey.current) attemptKey.current = newAttemptKey()\n chargeInFlight.current = true\n setOpening(true)\n try {\n const opened = await openPosSale(user, attemptKey.current, {\n hostId,\n registerId,\n lines,\n discountPct,\n ...(customerEmail ? { customerEmail } : {}),\n ...(customer ? { customer } : {}),\n ...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {}),\n ...(locationId ? { locationId } : {}),\n })\n setSaleLines(lines)\n setSale({\n orderId: opened.orderId,\n status: 'pending',\n totalCents: opened.totals.totalCents,\n paidCents: 0,\n dueCents: opened.totals.totalCents,\n tenderableCents: opened.totals.totalCents,\n tipCents: 0,\n payments: [],\n })\n setSheetOpen(true)\n } catch (error) {\n if (error instanceof PosRequestError) {\n notify(error.message, 'error')\n } else {\n // The request never reached the server: the register is offline.\n offline.reportNetworkFailure()\n notify('The register lost its connection. Charge again to take cash offline.', 'warning')\n }\n } finally {\n chargeInFlight.current = false\n setOpening(false)\n }\n }, [lines, user, registerId, hostId, discountPct, customerEmail, customer, cashier.assertion, locationId, notify, offline])\n\n const resetSale = useCallback(() => {\n if (sale?.status === 'paid') setLastReceipt({ orderId: sale.orderId })\n setSale(null)\n setSaleLines([])\n setLines([])\n setDiscountPct(0)\n setCustomer(null)\n setSheetOpen(false)\n }, [sale])\n\n // The customer display mirrors the basket while nothing else is on it.\n const mirrored = sale ? saleLines : lines\n // Whether the display was last left showing a basket. A paid sale leaves it\n // on the thank-you the server wrote, which an empty new basket must not\n // cut short with the idle screen; the next item added takes it over.\n // True at first, so a register that opens empty clears whatever a previous\n // session left on the screen.\n const displayShowsBasket = useRef(true)\n // The tip picked for the payment about to be taken; the ledger has it only\n // once that payment is recorded. Gone with the sale.\n const [pendingTipCents, setPendingTipCents] = useState(0)\n useEffect(() => {\n if (!sale || sale.status === 'paid') setPendingTipCents(0)\n }, [sale])\n useEffect(() => {\n if (sale?.status === 'paid') displayShowsBasket.current = false\n }, [sale?.status])\n useEffect(() => {\n if (!display.connected || display.asking) return\n if (sale?.payments.some((payment) => payment.status === 'pending' && payment.method === 'card_present')) {\n return\n }\n if (sale?.status === 'paid') return\n if (!mirrored.length && !displayShowsBasket.current) return\n const timer = setTimeout(() => {\n displayShowsBasket.current = mirrored.length > 0\n void display.show(\n mirrored.length\n ? {\n mode: 'cart',\n cart: {\n lines: mirrored.map((line) => ({\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n quantity: line.quantity,\n amountCents: line.unitAmountCents * line.quantity,\n })),\n itemsCents,\n discountCents,\n taxCents: sale ? Math.max(0, sale.totalCents - estimateCents) : 0,\n totalCents: sale ? sale.totalCents : estimateCents,\n ...(sale\n ? {\n paidCents: sale.paidCents,\n dueCents: sale.dueCents,\n tipCents: posDisplayTipCents(sale, pendingTipCents),\n }\n : {}),\n },\n }\n : { mode: 'idle' },\n )\n }, 400)\n return () => clearTimeout(timer)\n }, [display, mirrored, sale, itemsCents, discountCents, estimateCents, pendingTipCents])\n\n const registersHref = posRegistersSettingsHref(basePath)\n const registerPicker = !planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : usableRegisters.length === 0 ? (\n registers.length > 0 ? (\n <Typography variant=\"body2\" color=\"warning.main\">\n {'Your registers exceed your plan — remove extras or upgrade in Billing to take payments.'}\n </Typography>\n ) : (\n // A way there, not a path to follow by hand (AGL-3712).\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"warning.main\">\n {'No POS register yet. Add one before taking payments.'}\n </Typography>\n {registersHref ? (\n <Button size=\"small\" variant=\"outlined\" href={registersHref}>\n {'Add a register'}\n </Button>\n ) : null}\n </Stack>\n )\n ) : usableRegisters.length > 1 ? (\n <TextField\n label=\"Register\"\n value={registerId}\n onChange={(event) => setRegisterId(event.target.value)}\n size=\"small\"\n select\n disabled={Boolean(sale)}\n >\n {usableRegisters.map((register: any) => (\n <MenuItem key={register.$id} value={register.$id}>\n {register.name}\n </MenuItem>\n ))}\n </TextField>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {usableRegisters[0]?.name}\n </Typography>\n )\n\n /**\n * On a narrow screen the register's bar owns the bottom edge, so it moves\n * the console's floating launchers clear of itself through the shell's\n * `--aglyn-dock-inset-bottom` seam; a launcher left in the corner sat on\n * top of Charge.\n */\n const bottomBarRef = useRef<HTMLDivElement | null>(null)\n useEffect(() => {\n const node = bottomBarRef.current\n if (wide || !node) return undefined\n const root = document.documentElement\n const property = '--aglyn-dock-inset-bottom'\n const publish = () => {\n root.style.setProperty(property, `${Math.round(node.getBoundingClientRect().height) + 20}px`)\n }\n publish()\n const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(publish)\n observer?.observe(node)\n return () => {\n observer?.disconnect()\n root.style.removeProperty(property)\n }\n }, [wide])\n\n const registerPanel = (\n <Stack spacing={1.5} sx={{ minHeight: 0, flex: 1 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"h6\" sx={{ flex: 1 }}>\n {'Register'}\n </Typography>\n {registerId ? (\n <Button\n size=\"small\"\n onClick={() => void pairingFlow.open(registerId, 'display')}\n >\n {display.connected ? 'Display connected' : 'Pair display'}\n </Button>\n ) : null}\n </Stack>\n {registerPicker}\n {(locationDocs?.length ?? 0) > 1 ? (\n <TextField\n label=\"Location\"\n value={locationId}\n onChange={(event) => setLocationId(event.target.value)}\n size=\"small\"\n select\n disabled={Boolean(sale)}\n >\n {(locationDocs ?? []).map((location: any) => (\n <MenuItem key={location.$id} value={location.$id}>\n {location.name}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {registerId ? (\n <PosOperationsBar\n hostId={hostId}\n registerId={registerId}\n {...(registerName ? { registerName } : {})}\n cashier={cashier}\n blocked={blockedControls}\n onExchange={(returned) =>\n setCustomer(\n returned.email || returned.name\n ? { kind: 'none', id: '', name: returned.name ?? '', email: returned.email, phone: null }\n : null,\n )\n }\n />\n ) : null}\n <PosCartPanel\n {...(discountBlocked ? { discountBlocked } : {})}\n lines={sale ? saleLines : lines}\n shortfalls={sale ? [] : shortfalls}\n onQuantity={(index, quantity) =>\n setLines((prev) =>\n quantity <= 0\n ? prev.filter((_line, at) => at !== index)\n : prev.map((line, at) => (at === index ? { ...line, quantity: Math.min(99, quantity) } : line)),\n )\n }\n onRemove={(index) => setLines((prev) => prev.filter((_line, at) => at !== index))}\n onEdit={(index) => {\n const line = lines[index]\n const product = line\n ? (productCache.current.get(line.productId) ?? productsById.get(line.productId))\n : undefined\n if (!line || !product) return\n setItemSheet({\n product,\n editIndex: index,\n initial: {\n ...(line.variantId ? { variantId: line.variantId } : {}),\n ...(line.modifiers ? { modifiers: line.modifiers } : {}),\n quantity: line.quantity,\n },\n })\n }}\n discountPct={discountPct}\n onDiscountPct={setDiscountPct}\n customer={\n <>\n {sale ? null : (\n <PosCustomerLookup\n hostId={hostId}\n value={customer}\n onChange={setCustomer}\n registerId={registerId}\n {...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {})}\n />\n )}\n {user && storeSellsHardware ? (\n <Suspense fallback={null}>\n <PosHardwareBuyer\n user={user}\n hostId={hostId}\n saleOrderId={sale && saleSellsHardware ? sale.orderId : null}\n notify={notify}\n />\n </Suspense>\n ) : null}\n </>\n }\n locked={Boolean(sale)}\n />\n {sale && user ? (\n sale.status === 'paid' ? (\n <PosReceiptPanel\n user={user}\n hostId={hostId}\n sale={sale}\n context={context}\n display={display}\n onNewSale={resetSale}\n registerId={registerId}\n {...(registerName ? { registerName } : {})}\n {...(cashier.cashier ? { cashierName: cashier.cashier.name } : {})}\n notify={notify}\n />\n ) : (\n <PosTenderPanel\n user={user}\n hostId={hostId}\n registerId={registerId}\n sale={sale}\n context={context}\n stays={openStays}\n display={display}\n onSale={setSale}\n onVoided={() => {\n setSale(null)\n setSaleLines([])\n }}\n onTipChange={setPendingTipCents}\n {...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {})}\n notify={notify}\n offline={offline.offline}\n {...(offline.ready\n ? {\n onSellOffline: () => {\n // The server's open sale took no payment; it is voided once\n // the connection returns, and the basket rings offline.\n strandedSales.current.push(sale.orderId)\n setSale(null)\n setSaleLines([])\n setOfflineCheckout(true)\n },\n }\n : {})}\n />\n )\n ) : (\n <>\n <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>\n <Typography variant=\"h6\">{'Due'}</Typography>\n <Typography variant=\"h6\">{usd(estimateCents)}</Typography>\n </Box>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Tax is added when you charge.'}\n </Typography>\n <Button\n variant=\"contained\"\n size=\"large\"\n disabled={opening || lines.length === 0 || !registerId}\n onClick={() => void charge()}\n sx={{ minHeight: 56 }}\n >\n {opening\n ? 'Pricing…'\n : offline.offline\n ? `Cash ${usd(offline.totalsFor(lines, discountPct)?.totalCents ?? estimateCents)} (offline)`\n : `Charge ${usd(estimateCents)}`}\n </Button>\n {lastReceipt ? (\n <PosLastReceipt\n hostId={hostId}\n orderId={lastReceipt.orderId}\n {...(registerName ? { registerName } : {})}\n {...(cashier.cashier ? { cashierName: cashier.cashier.name } : {})}\n />\n ) : null}\n </>\n )}\n </Stack>\n )\n\n return (\n <>\n <NextPageTitle screen={'POS'} />\n <Box\n ref={fill.ref}\n sx={{\n display: 'flex',\n // From under the console's header, nav and page title down to\n // where the page's padding and footer begin, so the whole page fits\n // the window (AGL-3679, AGL-3710).\n height: fill.height,\n overflow: 'hidden',\n }}\n >\n <Box sx={{ flex: 1, p: 2, overflowY: 'auto', pb: wide ? 2 : 12 }}>\n <Box sx={{ mb: 2, '&:empty': { display: 'none' } }}>\n <PosOfflineBanner offline={offline} />\n </Box>\n {/* \"Pay at counter\" orders from this register's kiosks (AGL-3623). */}\n {registerId ? (\n <PosKioskQueue\n user={user}\n hostId={hostId}\n registerId={registerId}\n disabled={Boolean(sale)}\n onTake={(next, nextLines) => {\n setSaleLines(nextLines)\n setSale(next)\n setSheetOpen(true)\n }}\n notify={notify}\n />\n ) : null}\n {/* Orders other channels send to the counter (AGL-3644). */}\n {WidgetSlot ? <PosOrdersZone renderer={WidgetSlot} hostId={hostId} registerId={registerId || null} /> : null}\n <PosProductGrid\n search={search}\n onSearch={setSearch}\n onSearchEnter={() => void handleSearchEnter()}\n scanAdornment={scanAdornment}\n categories={(categoryDocs ?? []).map((category: any) => ({\n $id: category.$id,\n name: String(category.name ?? 'Category'),\n }))}\n categoryId={categoryId}\n onCategory={setCategoryId}\n notices={gridPlan.notices}\n hostId={hostId}\n products={sellProducts}\n basketCounts={basketCounts}\n onTap={(product) => {\n if (sale) return void notify('Finish or void the open sale first', 'info')\n tapProduct(product)\n }}\n />\n </Box>\n {wide ? (\n <Box\n sx={{\n width: { md: 400, lg: 440 },\n borderLeft: 1,\n borderColor: 'divider',\n display: 'flex',\n flexDirection: 'column',\n p: 2,\n overflowY: 'auto',\n }}\n >\n {registerPanel}\n </Box>\n ) : null}\n </Box>\n {!wide ? (\n <>\n <Box\n ref={bottomBarRef}\n sx={{\n position: 'fixed',\n left: 0,\n right: 0,\n bottom: 0,\n p: 1.5,\n bgcolor: 'background.paper',\n borderTop: 1,\n borderColor: 'divider',\n display: 'flex',\n gap: 1,\n alignItems: 'center',\n zIndex: theme.zIndex.appBar,\n }}\n >\n <Badge badgeContent={units} color=\"primary\">\n <Button\n variant=\"outlined\"\n onClick={() => setSheetOpen(true)}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {sale ? 'Payment' : 'Cart'}\n </Button>\n </Badge>\n <Typography variant=\"h6\" sx={{ flex: 1, textAlign: 'right' }}>\n {usd(sale ? sale.dueCents : estimateCents)}\n </Typography>\n {!sale ? (\n <Button\n variant=\"contained\"\n disabled={opening || lines.length === 0 || !registerId}\n onClick={() => void charge()}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {'Charge'}\n </Button>\n ) : null}\n </Box>\n <Drawer\n anchor=\"bottom\"\n open={sheetOpen}\n onClose={() => setSheetOpen(false)}\n slotProps={{ paper: { sx: { maxHeight: '90dvh', p: 2, borderTopLeftRadius: 16, borderTopRightRadius: 16 } } }}\n >\n {registerPanel}\n </Drawer>\n </>\n ) : null}\n <PosItemDialog\n product={itemSheet?.product ?? null}\n initial={itemSheet?.initial}\n onClose={() => setItemSheet(null)}\n onConfirm={(choice) => {\n const sheet = itemSheet\n setItemSheet(null)\n if (!sheet) return\n if (sheet.editIndex === undefined) {\n addProduct(sheet.product, choice.variant, choice.modifiers, choice.quantity)\n return\n }\n const at = sheet.editIndex\n setLines((prev) =>\n prev.map((line, index) => (index === at ? registerLineFor(sheet.product, choice) : line)),\n )\n }}\n {...(itemSheet?.editIndex !== undefined\n ? {\n onRemove: () => {\n const at = itemSheet.editIndex\n setItemSheet(null)\n setLines((prev) => prev.filter((_line, index) => index !== at))\n },\n }\n : {})}\n />\n <PosOfflineCheckout\n open={offlineCheckout}\n offline={offline}\n hostId={hostId}\n lines={lines}\n discountPct={discountPct}\n customer={customer}\n {...(registerName ? { registerName } : {})}\n {...(cashier.cashier ? { cashierName: cashier.cashier.name } : {})}\n onClose={() => setOfflineCheckout(false)}\n onRung={() => undefined}\n onDone={() => {\n setOfflineCheckout(false)\n setLines([])\n setDiscountPct(0)\n setCustomer(null)\n setSheetOpen(false)\n }}\n />\n {pairingFlow.dialog}\n </>\n )\n}\nPosConsolePage.displayName = 'PosConsolePage'\n\nexport default PosConsolePage\n"],"names":["Aglyn","CommerceModel","posPermissionRefusal","PRODUCT_LIST_BASE","PRODUCT_LIST_QUERY","NextPageTitle","useSnackbar","planListQuery","useViewportFill","nameSearchNormalizers","Badge","Box","Button","Drawer","MenuItem","Stack","TextField","Typography","useMediaQuery","useTheme","collection","getDocs","limit","query","where","lazy","memo","Suspense","useCallback","useEffect","useMemo","useRef","useState","useFirestore","useUser","useFirestoreCollection","listQueryConstraints","useOrgPlan","newAttemptKey","openPosSale","posRegisterContext","posTender","PosRequestError","usd","PosCartPanel","ScanAdornment","useScannerWedge","PosCustomerLookup","PosLastReceipt","PosOperationsBar","usePosCashier","usePosOpsSettings","POS_QUICK_KEYS","POS_TOUCH_PX","PosProductGrid","PosItemDialog","posItemNeedsChoice","PosReceiptPanel","PosTenderPanel","PosKioskQueue","posDisplayTipCents","usePosDisplay","posRegistersSettingsHref","usePosPairing","useConsoleWidgetSlot","POS_ORDERS_ZONE","isPosHardwareSkuId","PosHardwareBuyer","PosOfflineBanner","PosOfflineCheckout","usePosOffline","SELLABLE","field","op","value","POS_GRID_CEILING","posProductPlan","options","typed","search","trim","plan","POS_GRID_QUERY","base","clauses","code","categoryId","quickKeys","filters","path","fields","column","kind","tokensPath","operators","POS_CATEGORY_KEY","registerLineFor","product","choice","variant","modifiers","quantity","resolved","resolveLineModifiers","id","picked","ok","label","lineLabelWithModifiers","Object","keys","length","values","join","undefined","productId","$id","variantId","name","variantLabel","unitAmountCents","Math","round","Number","priceUsd","extraCents","lineKey","line","modifierSelectionKey","PosOrdersZone","props","renderer","Renderer","hostId","registerId","slot","orgId","PosConsolePage","basePath","permissions","liveRegister","usableRegisters","offline","refusedReason","key","blockedControls","returns","shift","discountBlocked","WidgetSlot","firestore","data","user","enqueueSnackbar","theme","wide","breakpoints","up","setSearch","setCategoryIdState","window","localStorage","getItem","setCategoryId","setItem","gridPlan","productDocs","idField","categoryDocs","locationDocs","registerDocs","org","ready","planReady","registers","sort","a","b","String","localeCompare","registerCap","checkHostRegisterQuota","withinCap","registersWithinCap","filter","r","has","reservationDocs","openStays","lines","setLines","discountPct","setDiscountPct","customer","setCustomer","customerEmail","email","locationId","setLocationId","setRegisterId","first","registerName","find","register","opsSettings","cashier","autoLockMinutes","lastReceipt","setLastReceipt","context","setContext","userRef","current","uid","signedIn","active","then","answer","settings","terminal","catch","sale","setSale","saleLines","setSaleLines","opening","setOpening","sheetOpen","setSheetOpen","display","attemptKey","fill","min","products","map","liftLegacyProduct","loadCatalog","docs","snapshot","openShiftId","assertion","cashierAssertion","liveProducts","offlineCheckout","setOfflineCheckout","strandedSales","orderIds","splice","orderId","sellProducts","gridProducts","productsById","Map","saleSellsHardware","some","get","hardwareSku","storeSellsHardware","shortfalls","stockShortfall","variants","itemsCents","reduce","sum","discountCents","estimateCents","units","notify","message","persist","allowDuplicate","onPairingError","pairingFlow","onError","addProduct","next","prev","existing","itemSheet","setItemSheet","productCache","tapProduct","set","productModifierGroups","initial","basketCounts","counts","lookupCode","scanned","needle","toLowerCase","found","findByCode","lookup","hit","error","console","reportNetworkFailure","item","barcode","sku","handleSearchEnter","scanAdornment","onScan","chargeInFlight","charge","unavailableReason","opened","status","totalCents","totals","paidCents","dueCents","tenderableCents","tipCents","payments","resetSale","mirrored","displayShowsBasket","pendingTipCents","setPendingTipCents","connected","asking","payment","method","timer","setTimeout","show","mode","cart","amountCents","taxCents","max","clearTimeout","registersHref","registerPicker","color","spacing","sx","alignItems","size","href","onChange","event","target","select","disabled","Boolean","bottomBarRef","node","root","document","documentElement","property","publish","style","setProperty","getBoundingClientRect","height","observer","ResizeObserver","observe","disconnect","removeProperty","registerPanel","minHeight","flex","direction","onClick","open","location","blocked","onExchange","returned","phone","onQuantity","index","_line","at","onRemove","onEdit","editIndex","onDiscountPct","fallback","saleOrderId","locked","onNewSale","cashierName","stays","onSale","onVoided","onTipChange","onSellOffline","push","justifyContent","totalsFor","screen","ref","overflow","p","overflowY","pb","mb","onTake","nextLines","onSearch","onSearchEnter","categories","category","onCategory","notices","onTap","width","md","lg","borderLeft","borderColor","flexDirection","position","left","right","bottom","bgcolor","borderTop","gap","zIndex","appBar","badgeContent","textAlign","anchor","onClose","slotProps","paper","maxHeight","borderTopLeftRadius","borderTopRightRadius","onConfirm","sheet","onRung","onDone","dialog","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AAErC,YAAYC,mBAAmB,uBAAa;AAC5C,SAASC,oBAAoB,QAA4B,oCAAgC;AACzF,SACEC,iBAAiB,EACjBC,kBAAkB,QACb,wCAAoC;AAC3C,SAASC,aAAa,QAAQ,0DAAyD;AACvF,SAASC,WAAW,QAAQ,8BAA6B;AAEzD,SAASC,aAAa,QAAQ,6CAA4C;AAC1E,SAASC,eAAe,QAAQ,+CAA8C;AAC9E,SAASC,qBAAqB,QAAQ,qCAAoC;AAC1E,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,EACVC,aAAa,EACbC,QAAQ,QACH,gBAAe;AACtB,SACEC,UAAU,EACVC,OAAO,EACPC,KAAK,EACLC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,IAAI,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAC/F,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,sBAAsB,QAAQ,iCAAgC;AACvE,SAASC,oBAAoB,Q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AED4C,YAAYwK,MAAM;;;AAGzB;AACA/S,eAAegT,WAAW,GAAG;AAE7B,eAAehT,eAAc"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/pos-page.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport type { ConsolePluginPageProps } from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { posPermissionRefusal, type PosPermission } from '../../model/plugin-permissions'\nimport {\n PRODUCT_LIST_BASE,\n PRODUCT_LIST_QUERY,\n} from '../../constants/product-list-query'\nimport { NextPageTitle } from '@aglyn/shared-ui-next/contexts/next-page-title-provider'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport type { ListFilterRequest } from '@aglyn/shared-ui-jsx/const/list-filter'\nimport { planListQuery } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport { useViewportFill } from '@aglyn/shared-ui-jsx/hooks/use-viewport-fill'\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n Badge,\n Box,\n Button,\n Drawer,\n MenuItem,\n Stack,\n TextField,\n Typography,\n useMediaQuery,\n useTheme,\n} from '@mui/material'\nimport {\n collection,\n getDocs,\n limit,\n query,\n where,\n} from 'firebase/firestore'\nimport { lazy, memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { useFirestoreCollection } from '@aglyn/tenant-feature-instance'\nimport { listQueryConstraints } from '@aglyn/tenant-feature-instance/hooks/use-list-query'\nimport { useOrgPlan } from '@aglyn/tenant-feature-instance'\nimport { resolvePlanFeatureLock } from '@aglyn/tenant-feature-instance/hooks/plan-feature-lock'\nimport { EntitlementUpsell } from './entitlement-gate.component'\nimport {\n newAttemptKey,\n openPosSale,\n posRegisterContext,\n posTender,\n PosRequestError,\n usd,\n type PosRegisterContext,\n type PosSaleSummary,\n} from './pos/pos-api'\nimport { PosCartPanel, type RegisterLine } from './pos/pos-cart-panel.component'\nimport { ScanAdornment } from '../../barcode/scan-button.component'\nimport { useScannerWedge } from '../../barcode/scanner-wedge'\nimport {\n PosCustomerLookup,\n PosLastReceipt,\n PosOperationsBar,\n usePosCashier,\n usePosOpsSettings,\n type PosSelectedCustomer,\n} from './pos-ops/register-ops'\nimport { POS_QUICK_KEYS, POS_TOUCH_PX, PosProductGrid } from './pos/pos-product-grid.component'\nimport { PosItemDialog, posItemNeedsChoice, type PosItemChoice } from './pos/pos-item-dialog.component'\nimport { PosReceiptPanel } from './pos/pos-receipt-panel.component'\nimport { PosTenderPanel } from './pos/pos-tender-panel.component'\nimport { PosKioskQueue } from './pos/pos-kiosk-queue.component'\nimport { posDisplayTipCents, usePosDisplay } from './pos/use-pos-display'\nimport { posRegistersSettingsHref, usePosPairing } from './pos/pos-pairing.component'\nimport {\n type ConsoleWidgetSlotRenderer,\n useConsoleWidgetSlot,\n} from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { POS_ORDERS_ZONE } from './pos-zones'\nimport { isPosHardwareSkuId, posPlanPrompt } from '../../model/pos-hardware'\n\n/**\n * Card reader sales at the platform's own store (AGL-4038): attaching the\n * buyer and the To attach list. Its own chunk, and it draws nothing on any\n * store but that one.\n */\nconst PosHardwareBuyer = lazy(() => import('./pos/pos-hardware-buyer.component'))\nimport { PosOfflineBanner, PosOfflineCheckout, usePosOffline } from './pos-offline/register-offline'\n\n/** The till sells active products only; every read of the catalog asks it. */\nconst SELLABLE: ListFilterRequest = { field: 'status', op: 'equals', value: 'active' }\n\n/**\n * How many products the till's grid shows. The grid is a picker, not the\n * catalog: typing narrows it on the query, so a name reaches every product.\n */\nconst POS_GRID_CEILING = 500\n\n/**\n * The products hub's query (AGL-3321), narrowed to what the till may sell:\n * live products (`deletedAt == null`, the list's scope), `status == active`,\n * and any typed word as the search on `nameTokens` — or, for a scan, the\n * whole scanned code as a SKU or barcode clause. Every shape is one the hub's\n * composites already serve.\n */\nexport function posProductPlan(options: {\n search?: string\n code?: { field: 'barcodes' | 'skus'; value: string }\n /** A category chip (AGL-3607): served by the storefront's own composite. */\n categoryId?: string\n /** The Quick keys chip (AGL-3607): products marked `posQuickKey`. */\n quickKeys?: boolean\n}) {\n const typed = options.search?.trim()\n const plan = planListQuery(\n POS_GRID_QUERY,\n {\n base: PRODUCT_LIST_BASE,\n clauses: [\n SELLABLE,\n ...(options.code\n ? [{ field: options.code.field, op: 'contains', value: options.code.value }]\n : []),\n ...(options.categoryId\n ? [{ field: 'categoryIds', op: 'contains', value: options.categoryId }]\n : []),\n ],\n // A chip and a typed word are both array clauses, and Firestore takes\n // one: with a chip on, the word narrows by name prefix instead.\n search: typed && !options.categoryId ? [typed] : [],\n },\n nameSearchNormalizers,\n )\n // The Quick keys chip (AGL-3607) is a boolean equality the list planner\n // does not model, added beside the scope and status it composes with —\n // `deletedAt ==, status ==, posQuickKey ==, nameLower ASC` is declared in\n // the index file. A typed word searches the whole catalog instead: a\n // cashier who types is looking past the quick keys.\n if (options.quickKeys && !typed && !options.code) {\n return {\n ...plan,\n filters: [...plan.filters, { path: 'posQuickKey', op: '==', value: true }],\n } as typeof plan\n }\n return plan\n}\n\n/**\n * The grid's query: the products hub's, plus the category a chip picks\n * (AGL-3607). `categoryIds CONTAINS, nameLower ASC` is a composite the\n * storefront catalog already declares.\n */\nexport const POS_GRID_QUERY = {\n ...PRODUCT_LIST_QUERY,\n fields: [\n ...PRODUCT_LIST_QUERY.fields,\n {\n column: 'categoryIds',\n kind: 'exact' as const,\n path: 'categoryIds',\n tokensPath: 'categoryIds',\n operators: ['contains'],\n },\n ],\n} as typeof PRODUCT_LIST_QUERY\n\n/**\n * POS register (AGL-312, AGL-3607): a tablet-first sale surface — the\n * product grid with search, scan and category chips, the basket, and a\n * tender panel that takes one or more payments against an open sale (cash,\n * card reader, a native Tap to Pay bridge, a typed card, the QR link, gift\n * cards and room charges) until the balance is zero. A paired customer\n * display mirrors the basket and takes the tip and the receipt (AGL-3608).\n *\n * On a wide screen (900px and up) the grid and the register sit side by\n * side; below that the register is a bottom sheet behind a sticky total bar.\n */\n/*\n * `managePos` is NOT read here. The nav item in `plugin.ts` declares it and\n * the shell refuses the route before this component is constructed, so a\n * reader without the key never reaches this file and there is no unpermitted\n * state for it to render — the same arrangement the entitlement gate has.\n *\n * Re-adding a check off the `permissions` prop would be a second answer to a\n * settled question, and a laxer one: a prop absent because the map has not\n * landed reads as permitted here, while the shell holds the route on that\n * same condition rather than guessing. The server routes remain the\n * enforcement point for every sale and every payment.\n */\n/** Where a register device remembers the category chip it was left on. */\nconst POS_CATEGORY_KEY = 'aglyn.pos.category'\n\n/** The basket line an item-sheet choice makes: label and estimate from the product. */\nexport function registerLineFor(\n product: any,\n choice: PosItemChoice,\n): RegisterLine {\n const { variant, modifiers, quantity } = choice\n const resolved = CommerceModel.resolveLineModifiers(product, modifiers, variant?.id)\n const picked = resolved.ok ? resolved.modifiers : []\n const label = CommerceModel.lineLabelWithModifiers(\n Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined,\n picked,\n )\n return {\n productId: product.$id,\n ...(variant.id !== 'default' ? { variantId: variant.id } : {}),\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents:\n Math.round(Number(variant.priceUsd) * 100) + (resolved.ok ? resolved.extraCents : 0),\n quantity,\n ...(modifiers.length ? { modifiers } : {}),\n }\n}\n\n/** Same product, variant and choices: the lines that merge into one. */\nfunction lineKey(line: Pick<RegisterLine, 'productId' | 'variantId' | 'modifiers'>): string {\n return `${line.productId}:${line.variantId ?? ''}:${CommerceModel.modifierSelectionKey(line.modifiers)}`\n}\n\n/**\n * The register's zone (AGL-3644), drawn again only when what it is handed\n * changes: the till redraws on every tap, and the shell's renderer is not\n * memoized (the order dialog's reasoning).\n */\nconst PosOrdersZone = memo(function PosOrdersZone(props: {\n renderer: ConsoleWidgetSlotRenderer\n hostId: string\n registerId: string | null\n}) {\n const { renderer: Renderer, hostId, registerId } = props\n return <Renderer slot={POS_ORDERS_ZONE.id} hostId={hostId} orgId={undefined} registerId={registerId} />\n})\n\nexport function PosConsolePage({ hostId, basePath, permissions }: ConsolePluginPageProps) {\n /*\n * The register's FINER keys (AGL-4047) — discounts, returns, the drawer —\n * are read here, unlike `managePos` above: the shell admits anyone who may\n * use the register, and these say which of its controls are theirs. Only an\n * explicit refusal disables one; a map without the key follows `managePos`,\n * which the shell already confirmed. The routes refuse either way.\n */\n const refusedReason = (key: PosPermission): string | undefined =>\n permissions?.[key] === false ? posPermissionRefusal(key) : undefined\n const blockedControls = {\n returns: refusedReason('posRefund'),\n shift: refusedReason('posCashDrawer'),\n }\n const discountBlocked = refusedReason('posDiscount')\n const WidgetSlot = useConsoleWidgetSlot()\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const theme = useTheme()\n const wide = useMediaQuery(theme.breakpoints.up('md'))\n\n const [search, setSearch] = useState('')\n // The chip a register opens on is remembered per device: a counter that\n // rings from its quick keys reopens on them.\n const [categoryId, setCategoryIdState] = useState(() => {\n try {\n return window.localStorage.getItem(POS_CATEGORY_KEY) ?? ''\n } catch {\n return ''\n }\n })\n const setCategoryId = useCallback((id: string) => {\n setCategoryIdState(id)\n try {\n window.localStorage.setItem(POS_CATEGORY_KEY, id)\n } catch {\n // Storage blocked: the chip still works for this visit.\n }\n }, [])\n const gridPlan = useMemo(\n () =>\n categoryId === POS_QUICK_KEYS\n ? posProductPlan({ search, quickKeys: true })\n : posProductPlan({ search, categoryId }),\n [search, categoryId],\n )\n const { data: productDocs } = useFirestoreCollection<any>(\n /*\n * The till's grid, narrowed by the QUERY rather than by the rows it\n * happened to fetch (AGL-2501, AGL-2292, AGL-3321): the first five\n * hundred SELLABLE products by name, and a typed name reaches the whole\n * catalog. The scan does not come through here — see `handleSearchEnter`.\n */\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'products'),\n ...listQueryConstraints(gridPlan),\n limit(POS_GRID_CEILING),\n ),\n [firestore, hostId, gridPlan],\n { idField: '$id' },\n )\n const { data: categoryDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'productCategories'), limit(30)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { data: locationDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'locations'), limit(25)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { data: registerDocs } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'registers'), limit(25)),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { org, ready: planReady } = useOrgPlan(hostId)\n const registers = [...(registerDocs ?? [])].sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n )\n // Only registers within the plan cap can transact (AGL-482), and not until\n // the org doc has arrived (AGL-1064). Per SITE (AGL-1775).\n const registerCap = Aglyn.checkHostRegisterQuota(org, hostId, registers.length).limit\n const withinCap = CommerceModel.registersWithinCap(registers, registerCap)\n const usableRegisters = planReady ? registers.filter((r: any) => withinCap.has(r.$id)) : []\n // A workspace that bought a reader without the point of sale (AGL-4038)\n // is told what adding it gives it, from the org doc already held and the\n // workspace in this page's own path (`/{org}/hosts/{host}/pos`): no read.\n const posPlan = resolvePlanFeatureLock({\n org,\n ready: planReady,\n feature: 'pos',\n orgSlug: /^\\/([^/]+)\\/hosts\\//.exec(basePath ?? '')?.[1],\n })\n /*\n * The stays a sale can be charged to, asked for BY STATUS (AGL-3321).\n */\n const { data: reservationDocs } = useFirestoreCollection<any>(\n () =>\n query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n where('status', '==', 'checked_in'),\n limit(100),\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const openStays = reservationDocs ?? []\n\n const [lines, setLines] = useState<RegisterLine[]>([])\n const [discountPct, setDiscountPct] = useState(0)\n // The customer the lookup attached (AGL-3609); their email is the sale's.\n const [customer, setCustomer] = useState<PosSelectedCustomer | null>(null)\n const customerEmail = customer?.email ?? ''\n const [locationId, setLocationId] = useState('')\n const [registerId, setRegisterId] = useState('')\n useEffect(() => {\n if (registerId || usableRegisters.length === 0) return\n const first = usableRegisters[0]\n setRegisterId(first.$id)\n if (first.locationId) setLocationId(first.locationId)\n }, [usableRegisters, registerId])\n const registerName = String(\n usableRegisters.find((register: any) => register.$id === registerId)?.name ?? '',\n )\n // Who is ringing (AGL-3609): a PIN-switched cashier, and the idle lock.\n const opsSettings = usePosOpsSettings(hostId)\n const cashier = usePosCashier({\n hostId,\n registerId,\n autoLockMinutes: opsSettings.autoLockMinutes,\n })\n // The last completed sale, whose receipt can still be printed (AGL-3609).\n const [lastReceipt, setLastReceipt] = useState<{ orderId: string } | null>(null)\n\n const [context, setContext] = useState<PosRegisterContext | null>(null)\n // Keyed on the uid, not the user object: a session refresh hands back a\n // new object for the same person, and re-reading the context on every one\n // would re-render the register in a loop.\n const userRef = useRef(user)\n userRef.current = user\n const uid = user?.uid ?? ''\n useEffect(() => {\n const signedIn = userRef.current\n if (!signedIn) return\n let active = true\n posRegisterContext(signedIn, hostId)\n .then((answer) => {\n // Only a whole answer: a register that half-knows its tenders would\n // offer one the server then refuses.\n if (active && answer?.settings && answer?.terminal) setContext(answer)\n })\n .catch(() => undefined)\n return () => {\n active = false\n }\n }, [uid, hostId])\n\n /** The open sale, once the basket has been priced and payment started. */\n const [sale, setSale] = useState<PosSaleSummary | null>(null)\n const [saleLines, setSaleLines] = useState<RegisterLine[]>([])\n const [opening, setOpening] = useState(false)\n const [sheetOpen, setSheetOpen] = useState(false)\n const display = usePosDisplay(user, hostId, registerId)\n\n /**\n * One key per basket (AGL-1691): minted on the first Charge and retired\n * whenever the basket changes, so a retried Charge finds the same sale and\n * ringing the same coffee twice is two sales.\n */\n const attemptKey = useRef('')\n const fill = useViewportFill({ min: 480 })\n useEffect(() => {\n attemptKey.current = ''\n }, [lines, discountPct])\n\n const products = useMemo(\n () =>\n [...(productDocs ?? [])].map((product: any) => ({\n ...CommerceModel.liftLegacyProduct(product),\n $id: product.$id,\n })),\n [productDocs],\n )\n /*\n * THE OFFLINE REGISTER (AGL-3625): the catalog and the site's offline rules\n * kept on this device, the queue of cash sales rung without a connection,\n * and the sync that records them once it returns.\n */\n const loadCatalog = useCallback(\n async () =>\n (\n await getDocs(\n query(\n collection(firestore, 'hosts', hostId, 'products'),\n ...listQueryConstraints(posProductPlan({})),\n limit(POS_GRID_CEILING),\n ),\n )\n ).docs.map((snapshot) => ({ ...(snapshot.data() as Record<string, unknown>), $id: snapshot.id })),\n [firestore, hostId],\n )\n const liveRegister = usableRegisters.find((register: any) => register.$id === registerId)\n const offline = usePosOffline({\n hostId,\n user,\n registerId,\n openShiftId: liveRegister ? (liveRegister.openShiftId ?? null) : undefined,\n locationId,\n ...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {}),\n liveProducts: products,\n loadCatalog,\n })\n const [offlineCheckout, setOfflineCheckout] = useState(false)\n /** Open sales left unpaid when the connection dropped, voided once it returns. */\n const strandedSales = useRef<string[]>([])\n useEffect(() => {\n if (offline.offline || !user || !strandedSales.current.length) return\n const orderIds = strandedSales.current.splice(0)\n for (const orderId of orderIds) {\n void posTender(user, hostId, orderId, 'void').catch(() => undefined)\n }\n }, [offline.offline, user, hostId])\n const sellProducts = useMemo(\n () => (offline.offline && offline.ready ? offline.gridProducts(search, categoryId, POS_QUICK_KEYS) : products),\n [offline, search, categoryId, products],\n )\n const productsById = useMemo(\n () => new Map<string, any>(sellProducts.map((product: any) => [product.$id, product] as const)),\n [sellProducts],\n )\n // Whether the sale on the register sells a card reader (AGL-4038): only\n // the platform's own store names hardware on a product, and only there\n // does the buyer step draw.\n const saleSellsHardware = useMemo(\n () =>\n (sale ? saleLines : lines).some((line) => isPosHardwareSkuId(productsById.get(line.productId)?.hardwareSku)),\n [sale, saleLines, lines, productsById],\n )\n // Only a store whose catalog names hardware asks whether it is the seller.\n const storeSellsHardware = useMemo(\n () => products.some((product: { hardwareSku?: unknown }) => isPosHardwareSkuId(product.hardwareSku)),\n [products],\n )\n /** AGL-2357: warns, never blocks. */\n const shortfalls = useMemo(\n () =>\n lines.map((line) => {\n const product: any = productsById.get(line.productId)\n if (!product) return null\n return CommerceModel.stockShortfall(\n product,\n line.variantId ?? product.variants?.[0]?.id,\n line.quantity,\n )\n }),\n [lines, productsById],\n )\n\n const itemsCents = lines.reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n const discountCents = Math.round((itemsCents * discountPct) / 100)\n const estimateCents = itemsCents - discountCents\n const units = lines.reduce((sum, line) => sum + line.quantity, 0)\n\n const notify = useCallback(\n (message: string, variant: 'success' | 'error' | 'warning' | 'info') => {\n enqueueSnackbar(message, { variant, persist: false, allowDuplicate: true })\n },\n [enqueueSnackbar],\n )\n\n /**\n * A pairing code for a customer display or a self-service kiosk (AGL-3623),\n * through the same flow the POS devices card offers (AGL-3712).\n */\n const onPairingError = useCallback((message: string) => notify(message, 'error'), [notify])\n const pairingFlow = usePosPairing({ user, hostId, onError: onPairingError })\n\n /**\n * Adds a line, or more of an identical one: the same product, variant and\n * modifiers merge, so two oat lattes are one line of two and an oat latte\n * beside a whole-milk one stays two lines.\n */\n const addProduct = useCallback(\n (product: any, variant?: any, modifiers: CommerceModel.ModifierSelection[] = [], quantity = 1) => {\n const next = registerLineFor(product, {\n variant: variant ?? product.variants[0],\n modifiers,\n quantity,\n })\n setLines((prev) => {\n const existing = prev.find((line) => lineKey(line) === lineKey(next))\n if (existing) {\n return prev.map((line) =>\n line === existing\n ? { ...line, quantity: Math.min(99, line.quantity + next.quantity) }\n : line,\n )\n }\n return [...prev, next]\n })\n },\n [],\n )\n\n /** The item sheet: a product to add, or a basket line to change. */\n const [itemSheet, setItemSheet] = useState<{\n product: any\n editIndex?: number\n initial?: { variantId?: string; modifiers?: CommerceModel.ModifierSelection[]; quantity: number }\n } | null>(null)\n // Every product rung up this sale, so a line can be reopened after the\n // grid has moved on to another category or search.\n const productCache = useRef(new Map<string, any>())\n const tapProduct = useCallback(\n (product: any, variant?: any) => {\n productCache.current.set(product.$id, product)\n if (posItemNeedsChoice(product) && !(variant && CommerceModel.productModifierGroups(product).length === 0)) {\n setItemSheet({\n product,\n ...(variant ? { initial: { variantId: variant.id, quantity: 1 } } : {}),\n })\n return\n }\n addProduct(product, variant)\n },\n [addProduct],\n )\n const basketCounts = useMemo(() => {\n const counts = new Map<string, number>()\n for (const line of lines) counts.set(line.productId, (counts.get(line.productId) ?? 0) + line.quantity)\n return counts\n }, [lines])\n\n /**\n * The barcode wedge: a LOOKUP against the whole catalog (AGL-2501),\n * barcode first, and a miss says so.\n */\n const lookupCode = useCallback(async (scanned: string) => {\n const needle = scanned.trim().toLowerCase()\n if (!needle || sale) return\n if (offline.offline) {\n const found = offline.findByCode(needle)\n if (!found) return void notify(`No product matches “${scanned.trim()}”`, 'warning')\n tapProduct(found.product, found.variant)\n setSearch('')\n return\n }\n const lookup = async (field: 'barcodes' | 'skus') => {\n const found = await getDocs(\n query(\n collection(firestore, 'hosts', hostId, 'products'),\n ...listQueryConstraints(posProductPlan({ code: { field, value: needle } })),\n limit(1),\n ),\n )\n return found.docs[0]\n }\n let hit: Awaited<ReturnType<typeof lookup>>\n try {\n hit = (await lookup('barcodes')) ?? (await lookup('skus'))\n } catch (error) {\n console.error(error)\n offline.reportNetworkFailure()\n return void notify('Could not reach the catalog — try again', 'warning')\n }\n if (!hit) return void notify(`No product matches “${scanned.trim()}”`, 'warning')\n const product = { ...CommerceModel.liftLegacyProduct(hit.data() as any), $id: hit.id }\n const variant =\n product.variants.find(\n (item: any) =>\n item.barcode?.trim().toLowerCase() === needle || item.sku?.trim().toLowerCase() === needle,\n ) ?? product.variants[0]\n // A scanned variant is the variant; a product with modifiers still asks\n // for them, with that variant already picked.\n tapProduct(product, variant)\n setSearch('')\n }, [sale, firestore, hostId, tapProduct, notify, offline])\n const handleSearchEnter = useCallback(() => lookupCode(search), [lookupCode, search])\n // A scanner fired while focus is on a product or a button (AGL-3619), and\n // the camera; neither while a sale is taking payment or an item is open.\n useScannerWedge((code) => void lookupCode(code), !sale && !itemSheet)\n const scanAdornment = useMemo(\n () => <ScanAdornment label=\"Scan a barcode with the camera\" onScan={(code) => void lookupCode(code)} />,\n [lookupCode],\n )\n\n /** Prices the basket on the server and opens the sale for payment. */\n // A ref, not `opening`: two taps inside one React batch both read the\n // pre-click state, and only a ref is written before the second reads it\n // (the AGL-1682 lesson).\n const chargeInFlight = useRef(false)\n const charge = useCallback(async () => {\n if (chargeInFlight.current || lines.length === 0 || !user) return\n if (!registerId) return void notify('Select a register before taking payment', 'warning')\n // Offline, the basket rings as a cash sale kept on this register (AGL-3625).\n if (offline.offline) {\n if (!offline.ready) return void notify(offline.unavailableReason ?? 'Offline selling is unavailable', 'warning')\n setOfflineCheckout(true)\n return\n }\n if (!attemptKey.current) attemptKey.current = newAttemptKey()\n chargeInFlight.current = true\n setOpening(true)\n try {\n const opened = await openPosSale(user, attemptKey.current, {\n hostId,\n registerId,\n lines,\n discountPct,\n ...(customerEmail ? { customerEmail } : {}),\n ...(customer ? { customer } : {}),\n ...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {}),\n ...(locationId ? { locationId } : {}),\n })\n setSaleLines(lines)\n setSale({\n orderId: opened.orderId,\n status: 'pending',\n totalCents: opened.totals.totalCents,\n paidCents: 0,\n dueCents: opened.totals.totalCents,\n tenderableCents: opened.totals.totalCents,\n tipCents: 0,\n payments: [],\n })\n setSheetOpen(true)\n } catch (error) {\n if (error instanceof PosRequestError) {\n notify(error.message, 'error')\n } else {\n // The request never reached the server: the register is offline.\n offline.reportNetworkFailure()\n notify('The register lost its connection. Charge again to take cash offline.', 'warning')\n }\n } finally {\n chargeInFlight.current = false\n setOpening(false)\n }\n }, [lines, user, registerId, hostId, discountPct, customerEmail, customer, cashier.assertion, locationId, notify, offline])\n\n const resetSale = useCallback(() => {\n if (sale?.status === 'paid') setLastReceipt({ orderId: sale.orderId })\n setSale(null)\n setSaleLines([])\n setLines([])\n setDiscountPct(0)\n setCustomer(null)\n setSheetOpen(false)\n }, [sale])\n\n // The customer display mirrors the basket while nothing else is on it.\n const mirrored = sale ? saleLines : lines\n // Whether the display was last left showing a basket. A paid sale leaves it\n // on the thank-you the server wrote, which an empty new basket must not\n // cut short with the idle screen; the next item added takes it over.\n // True at first, so a register that opens empty clears whatever a previous\n // session left on the screen.\n const displayShowsBasket = useRef(true)\n // The tip picked for the payment about to be taken; the ledger has it only\n // once that payment is recorded. Gone with the sale.\n const [pendingTipCents, setPendingTipCents] = useState(0)\n useEffect(() => {\n if (!sale || sale.status === 'paid') setPendingTipCents(0)\n }, [sale])\n useEffect(() => {\n if (sale?.status === 'paid') displayShowsBasket.current = false\n }, [sale?.status])\n useEffect(() => {\n if (!display.connected || display.asking) return\n if (sale?.payments.some((payment) => payment.status === 'pending' && payment.method === 'card_present')) {\n return\n }\n if (sale?.status === 'paid') return\n if (!mirrored.length && !displayShowsBasket.current) return\n const timer = setTimeout(() => {\n displayShowsBasket.current = mirrored.length > 0\n void display.show(\n mirrored.length\n ? {\n mode: 'cart',\n cart: {\n lines: mirrored.map((line) => ({\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n quantity: line.quantity,\n amountCents: line.unitAmountCents * line.quantity,\n })),\n itemsCents,\n discountCents,\n taxCents: sale ? Math.max(0, sale.totalCents - estimateCents) : 0,\n totalCents: sale ? sale.totalCents : estimateCents,\n ...(sale\n ? {\n paidCents: sale.paidCents,\n dueCents: sale.dueCents,\n tipCents: posDisplayTipCents(sale, pendingTipCents),\n }\n : {}),\n },\n }\n : { mode: 'idle' },\n )\n }, 400)\n return () => clearTimeout(timer)\n }, [display, mirrored, sale, itemsCents, discountCents, estimateCents, pendingTipCents])\n\n const registersHref = posRegistersSettingsHref(basePath)\n const registerPicker = !planReady ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Checking your plan…'}\n </Typography>\n ) : posPlan.locked ? (\n <EntitlementUpsell planLabel={posPlan.planLabel} upgradeHref={posPlan.upgradeHref}>\n {posPlanPrompt({ atRegister: true })}\n </EntitlementUpsell>\n ) : usableRegisters.length === 0 ? (\n registers.length > 0 ? (\n <Typography variant=\"body2\" color=\"warning.main\">\n {'Your registers exceed your plan — remove extras or upgrade in Billing to take payments.'}\n </Typography>\n ) : (\n // A way there, not a path to follow by hand (AGL-3712).\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"warning.main\">\n {'No POS register yet. Add one before taking payments.'}\n </Typography>\n {registersHref ? (\n <Button size=\"small\" variant=\"outlined\" href={registersHref}>\n {'Add a register'}\n </Button>\n ) : null}\n </Stack>\n )\n ) : usableRegisters.length > 1 ? (\n <TextField\n label=\"Register\"\n value={registerId}\n onChange={(event) => setRegisterId(event.target.value)}\n size=\"small\"\n select\n disabled={Boolean(sale)}\n >\n {usableRegisters.map((register: any) => (\n <MenuItem key={register.$id} value={register.$id}>\n {register.name}\n </MenuItem>\n ))}\n </TextField>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {usableRegisters[0]?.name}\n </Typography>\n )\n\n /**\n * On a narrow screen the register's bar owns the bottom edge, so it moves\n * the console's floating launchers clear of itself through the shell's\n * `--aglyn-dock-inset-bottom` seam; a launcher left in the corner sat on\n * top of Charge.\n */\n const bottomBarRef = useRef<HTMLDivElement | null>(null)\n useEffect(() => {\n const node = bottomBarRef.current\n if (wide || !node) return undefined\n const root = document.documentElement\n const property = '--aglyn-dock-inset-bottom'\n const publish = () => {\n root.style.setProperty(property, `${Math.round(node.getBoundingClientRect().height) + 20}px`)\n }\n publish()\n const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(publish)\n observer?.observe(node)\n return () => {\n observer?.disconnect()\n root.style.removeProperty(property)\n }\n }, [wide])\n\n const registerPanel = (\n <Stack spacing={1.5} sx={{ minHeight: 0, flex: 1 }}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography variant=\"h6\" sx={{ flex: 1 }}>\n {'Register'}\n </Typography>\n {registerId ? (\n <Button\n size=\"small\"\n onClick={() => void pairingFlow.open(registerId, 'display')}\n >\n {display.connected ? 'Display connected' : 'Pair display'}\n </Button>\n ) : null}\n </Stack>\n {registerPicker}\n {(locationDocs?.length ?? 0) > 1 ? (\n <TextField\n label=\"Location\"\n value={locationId}\n onChange={(event) => setLocationId(event.target.value)}\n size=\"small\"\n select\n disabled={Boolean(sale)}\n >\n {(locationDocs ?? []).map((location: any) => (\n <MenuItem key={location.$id} value={location.$id}>\n {location.name}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n {registerId ? (\n <PosOperationsBar\n hostId={hostId}\n registerId={registerId}\n {...(registerName ? { registerName } : {})}\n cashier={cashier}\n blocked={blockedControls}\n onExchange={(returned) =>\n setCustomer(\n returned.email || returned.name\n ? { kind: 'none', id: '', name: returned.name ?? '', email: returned.email, phone: null }\n : null,\n )\n }\n />\n ) : null}\n <PosCartPanel\n {...(discountBlocked ? { discountBlocked } : {})}\n lines={sale ? saleLines : lines}\n shortfalls={sale ? [] : shortfalls}\n onQuantity={(index, quantity) =>\n setLines((prev) =>\n quantity <= 0\n ? prev.filter((_line, at) => at !== index)\n : prev.map((line, at) => (at === index ? { ...line, quantity: Math.min(99, quantity) } : line)),\n )\n }\n onRemove={(index) => setLines((prev) => prev.filter((_line, at) => at !== index))}\n onEdit={(index) => {\n const line = lines[index]\n const product = line\n ? (productCache.current.get(line.productId) ?? productsById.get(line.productId))\n : undefined\n if (!line || !product) return\n setItemSheet({\n product,\n editIndex: index,\n initial: {\n ...(line.variantId ? { variantId: line.variantId } : {}),\n ...(line.modifiers ? { modifiers: line.modifiers } : {}),\n quantity: line.quantity,\n },\n })\n }}\n discountPct={discountPct}\n onDiscountPct={setDiscountPct}\n customer={\n <>\n {sale ? null : (\n <PosCustomerLookup\n hostId={hostId}\n value={customer}\n onChange={setCustomer}\n registerId={registerId}\n {...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {})}\n />\n )}\n {user && storeSellsHardware ? (\n <Suspense fallback={null}>\n <PosHardwareBuyer\n user={user}\n hostId={hostId}\n saleOrderId={sale && saleSellsHardware ? sale.orderId : null}\n notify={notify}\n />\n </Suspense>\n ) : null}\n </>\n }\n locked={Boolean(sale)}\n />\n {sale && user ? (\n sale.status === 'paid' ? (\n <PosReceiptPanel\n user={user}\n hostId={hostId}\n sale={sale}\n context={context}\n display={display}\n onNewSale={resetSale}\n registerId={registerId}\n {...(registerName ? { registerName } : {})}\n {...(cashier.cashier ? { cashierName: cashier.cashier.name } : {})}\n notify={notify}\n />\n ) : (\n <PosTenderPanel\n user={user}\n hostId={hostId}\n registerId={registerId}\n sale={sale}\n context={context}\n stays={openStays}\n display={display}\n onSale={setSale}\n onVoided={() => {\n setSale(null)\n setSaleLines([])\n }}\n onTipChange={setPendingTipCents}\n {...(cashier.assertion ? { cashierAssertion: cashier.assertion } : {})}\n notify={notify}\n offline={offline.offline}\n {...(offline.ready\n ? {\n onSellOffline: () => {\n // The server's open sale took no payment; it is voided once\n // the connection returns, and the basket rings offline.\n strandedSales.current.push(sale.orderId)\n setSale(null)\n setSaleLines([])\n setOfflineCheckout(true)\n },\n }\n : {})}\n />\n )\n ) : (\n <>\n <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>\n <Typography variant=\"h6\">{'Due'}</Typography>\n <Typography variant=\"h6\">{usd(estimateCents)}</Typography>\n </Box>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Tax is added when you charge.'}\n </Typography>\n <Button\n variant=\"contained\"\n size=\"large\"\n disabled={opening || lines.length === 0 || !registerId}\n onClick={() => void charge()}\n sx={{ minHeight: 56 }}\n >\n {opening\n ? 'Pricing…'\n : offline.offline\n ? `Cash ${usd(offline.totalsFor(lines, discountPct)?.totalCents ?? estimateCents)} (offline)`\n : `Charge ${usd(estimateCents)}`}\n </Button>\n {lastReceipt ? (\n <PosLastReceipt\n hostId={hostId}\n orderId={lastReceipt.orderId}\n {...(registerName ? { registerName } : {})}\n {...(cashier.cashier ? { cashierName: cashier.cashier.name } : {})}\n />\n ) : null}\n </>\n )}\n </Stack>\n )\n\n return (\n <>\n <NextPageTitle screen={'POS'} />\n <Box\n ref={fill.ref}\n sx={{\n display: 'flex',\n // From under the console's header, nav and page title down to\n // where the page's padding and footer begin, so the whole page fits\n // the window (AGL-3679, AGL-3710).\n height: fill.height,\n overflow: 'hidden',\n }}\n >\n <Box sx={{ flex: 1, p: 2, overflowY: 'auto', pb: wide ? 2 : 12 }}>\n <Box sx={{ mb: 2, '&:empty': { display: 'none' } }}>\n <PosOfflineBanner offline={offline} />\n </Box>\n {/* \"Pay at counter\" orders from this register's kiosks (AGL-3623). */}\n {registerId ? (\n <PosKioskQueue\n user={user}\n hostId={hostId}\n registerId={registerId}\n disabled={Boolean(sale)}\n onTake={(next, nextLines) => {\n setSaleLines(nextLines)\n setSale(next)\n setSheetOpen(true)\n }}\n notify={notify}\n />\n ) : null}\n {/* Orders other channels send to the counter (AGL-3644). */}\n {WidgetSlot ? <PosOrdersZone renderer={WidgetSlot} hostId={hostId} registerId={registerId || null} /> : null}\n <PosProductGrid\n search={search}\n onSearch={setSearch}\n onSearchEnter={() => void handleSearchEnter()}\n scanAdornment={scanAdornment}\n categories={(categoryDocs ?? []).map((category: any) => ({\n $id: category.$id,\n name: String(category.name ?? 'Category'),\n }))}\n categoryId={categoryId}\n onCategory={setCategoryId}\n notices={gridPlan.notices}\n hostId={hostId}\n products={sellProducts}\n basketCounts={basketCounts}\n onTap={(product) => {\n if (sale) return void notify('Finish or void the open sale first', 'info')\n tapProduct(product)\n }}\n />\n </Box>\n {wide ? (\n <Box\n sx={{\n width: { md: 400, lg: 440 },\n borderLeft: 1,\n borderColor: 'divider',\n display: 'flex',\n flexDirection: 'column',\n p: 2,\n overflowY: 'auto',\n }}\n >\n {registerPanel}\n </Box>\n ) : null}\n </Box>\n {!wide ? (\n <>\n <Box\n ref={bottomBarRef}\n sx={{\n position: 'fixed',\n left: 0,\n right: 0,\n bottom: 0,\n p: 1.5,\n bgcolor: 'background.paper',\n borderTop: 1,\n borderColor: 'divider',\n display: 'flex',\n gap: 1,\n alignItems: 'center',\n zIndex: theme.zIndex.appBar,\n }}\n >\n <Badge badgeContent={units} color=\"primary\">\n <Button\n variant=\"outlined\"\n onClick={() => setSheetOpen(true)}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {sale ? 'Payment' : 'Cart'}\n </Button>\n </Badge>\n <Typography variant=\"h6\" sx={{ flex: 1, textAlign: 'right' }}>\n {usd(sale ? sale.dueCents : estimateCents)}\n </Typography>\n {!sale ? (\n <Button\n variant=\"contained\"\n disabled={opening || lines.length === 0 || !registerId}\n onClick={() => void charge()}\n sx={{ minHeight: POS_TOUCH_PX }}\n >\n {'Charge'}\n </Button>\n ) : null}\n </Box>\n <Drawer\n anchor=\"bottom\"\n open={sheetOpen}\n onClose={() => setSheetOpen(false)}\n slotProps={{ paper: { sx: { maxHeight: '90dvh', p: 2, borderTopLeftRadius: 16, borderTopRightRadius: 16 } } }}\n >\n {registerPanel}\n </Drawer>\n </>\n ) : null}\n <PosItemDialog\n product={itemSheet?.product ?? null}\n initial={itemSheet?.initial}\n onClose={() => setItemSheet(null)}\n onConfirm={(choice) => {\n const sheet = itemSheet\n setItemSheet(null)\n if (!sheet) return\n if (sheet.editIndex === undefined) {\n addProduct(sheet.product, choice.variant, choice.modifiers, choice.quantity)\n return\n }\n const at = sheet.editIndex\n setLines((prev) =>\n prev.map((line, index) => (index === at ? registerLineFor(sheet.product, choice) : line)),\n )\n }}\n {...(itemSheet?.editIndex !== undefined\n ? {\n onRemove: () => {\n const at = itemSheet.editIndex\n setItemSheet(null)\n setLines((prev) => prev.filter((_line, index) => index !== at))\n },\n }\n : {})}\n />\n <PosOfflineCheckout\n open={offlineCheckout}\n offline={offline}\n hostId={hostId}\n lines={lines}\n discountPct={discountPct}\n customer={customer}\n {...(registerName ? { registerName } : {})}\n {...(cashier.cashier ? { cashierName: cashier.cashier.name } : {})}\n onClose={() => setOfflineCheckout(false)}\n onRung={() => undefined}\n onDone={() => {\n setOfflineCheckout(false)\n setLines([])\n setDiscountPct(0)\n setCustomer(null)\n setSheetOpen(false)\n }}\n />\n {pairingFlow.dialog}\n </>\n )\n}\nPosConsolePage.displayName = 'PosConsolePage'\n\nexport default PosConsolePage\n"],"names":["Aglyn","CommerceModel","posPermissionRefusal","PRODUCT_LIST_BASE","PRODUCT_LIST_QUERY","NextPageTitle","useSnackbar","planListQuery","useViewportFill","nameSearchNormalizers","Badge","Box","Button","Drawer","MenuItem","Stack","TextField","Typography","useMediaQuery","useTheme","collection","getDocs","limit","query","where","lazy","memo","Suspense","useCallback","useEffect","useMemo","useRef","useState","useFirestore","useUser","useFirestoreCollection","listQueryConstraints","useOrgPlan","resolvePlanFeatureLock","EntitlementUpsell","newAttemptKey","openPosSale","posRegisterContext","posTender","PosRequestError","usd","PosCartPanel","ScanAdornment","useScannerWedge","PosCustomerLookup","PosLastReceipt","PosOperationsBar","usePosCashier","usePosOpsSettings","POS_QUICK_KEYS","POS_TOUCH_PX","PosProductGrid","PosItemDialog","posItemNeedsChoice","PosReceiptPanel","PosTenderPanel","PosKioskQueue","posDisplayTipCents","usePosDisplay","posRegistersSettingsHref","usePosPairing","useConsoleWidgetSlot","POS_ORDERS_ZONE","isPosHardwareSkuId","posPlanPrompt","PosHardwareBuyer","PosOfflineBanner","PosOfflineCheckout","usePosOffline","SELLABLE","field","op","value","POS_GRID_CEILING","posProductPlan","options","typed","search","trim","plan","POS_GRID_QUERY","base","clauses","code","categoryId","quickKeys","filters","path","fields","column","kind","tokensPath","operators","POS_CATEGORY_KEY","registerLineFor","product","choice","variant","modifiers","quantity","resolved","resolveLineModifiers","id","picked","ok","label","lineLabelWithModifiers","Object","keys","length","values","join","undefined","productId","$id","variantId","name","variantLabel","unitAmountCents","Math","round","Number","priceUsd","extraCents","lineKey","line","modifierSelectionKey","PosOrdersZone","props","renderer","Renderer","hostId","registerId","slot","orgId","PosConsolePage","basePath","permissions","liveRegister","usableRegisters","offline","refusedReason","key","blockedControls","returns","shift","discountBlocked","WidgetSlot","firestore","data","user","enqueueSnackbar","theme","wide","breakpoints","up","setSearch","setCategoryIdState","window","localStorage","getItem","setCategoryId","setItem","gridPlan","productDocs","idField","categoryDocs","locationDocs","registerDocs","org","ready","planReady","registers","sort","a","b","String","localeCompare","registerCap","checkHostRegisterQuota","withinCap","registersWithinCap","filter","r","has","posPlan","feature","orgSlug","exec","reservationDocs","openStays","lines","setLines","discountPct","setDiscountPct","customer","setCustomer","customerEmail","email","locationId","setLocationId","setRegisterId","first","registerName","find","register","opsSettings","cashier","autoLockMinutes","lastReceipt","setLastReceipt","context","setContext","userRef","current","uid","signedIn","active","then","answer","settings","terminal","catch","sale","setSale","saleLines","setSaleLines","opening","setOpening","sheetOpen","setSheetOpen","display","attemptKey","fill","min","products","map","liftLegacyProduct","loadCatalog","docs","snapshot","openShiftId","assertion","cashierAssertion","liveProducts","offlineCheckout","setOfflineCheckout","strandedSales","orderIds","splice","orderId","sellProducts","gridProducts","productsById","Map","saleSellsHardware","some","get","hardwareSku","storeSellsHardware","shortfalls","stockShortfall","variants","itemsCents","reduce","sum","discountCents","estimateCents","units","notify","message","persist","allowDuplicate","onPairingError","pairingFlow","onError","addProduct","next","prev","existing","itemSheet","setItemSheet","productCache","tapProduct","set","productModifierGroups","initial","basketCounts","counts","lookupCode","scanned","needle","toLowerCase","found","findByCode","lookup","hit","error","console","reportNetworkFailure","item","barcode","sku","handleSearchEnter","scanAdornment","onScan","chargeInFlight","charge","unavailableReason","opened","status","totalCents","totals","paidCents","dueCents","tenderableCents","tipCents","payments","resetSale","mirrored","displayShowsBasket","pendingTipCents","setPendingTipCents","connected","asking","payment","method","timer","setTimeout","show","mode","cart","amountCents","taxCents","max","clearTimeout","registersHref","registerPicker","color","locked","planLabel","upgradeHref","atRegister","spacing","sx","alignItems","size","href","onChange","event","target","select","disabled","Boolean","bottomBarRef","node","root","document","documentElement","property","publish","style","setProperty","getBoundingClientRect","height","observer","ResizeObserver","observe","disconnect","removeProperty","registerPanel","minHeight","flex","direction","onClick","open","location","blocked","onExchange","returned","phone","onQuantity","index","_line","at","onRemove","onEdit","editIndex","onDiscountPct","fallback","saleOrderId","onNewSale","cashierName","stays","onSale","onVoided","onTipChange","onSellOffline","push","justifyContent","totalsFor","screen","ref","overflow","p","overflowY","pb","mb","onTake","nextLines","onSearch","onSearchEnter","categories","category","onCategory","notices","onTap","width","md","lg","borderLeft","borderColor","flexDirection","position","left","right","bottom","bgcolor","borderTop","gap","zIndex","appBar","badgeContent","textAlign","anchor","onClose","slotProps","paper","maxHeight","borderTopLeftRadius","borderTopRightRadius","onConfirm","sheet","onRung","onDone","dialog","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,WAAW,eAAc;AAErC,YAAYC,mBAAmB,uBAAa;AAC5C,SAASC,oBAAoB,QAA4B,oCAAgC;AACzF,SACEC,iBAAiB,EACjBC,kBAAkB,QACb,wCAAoC;AAC3C,SAASC,aAAa,QAAQ,0DAAyD;AACvF,SAASC,WAAW,QAAQ,8BAA6B;AAEzD,SAASC,aAAa,QAAQ,6CAA4C;AAC1E,SAASC,eAAe,QAAQ,+CAA8C;AAC9E,SAASC,qBAAqB,QAAQ,qCAAoC;AAC1E,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,EACVC,aAAa,EACbC,QAAQ,QACH,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,SAAS;oBAC1BnM,SAAS,CAACsF,OACRA,KAAK1C,GAAG,CAAC,CAAC/G,MAAMiQ,QAAWA,UAAUE,KAAKlS,gBAAgB4V,MAAM3V,OAAO,EAAEC,UAAU6B;gBAEvF;eACK2J,CAAAA,6BAAAA,UAAW2G,SAAS,MAAKnR,YAC1B;gBACEiR,UAAU;oBACR,MAAMD,KAAKxG,UAAU2G,SAAS;oBAC9B1G,aAAa;oBACbzF,SAAS,CAACsF,OAASA,KAAKhG,MAAM,CAAC,CAACyM,OAAOD,QAAUA,UAAUE;gBAC7D;YACF,IACA,CAAC;0BAEP,KAAC7T;gBACCoT,MAAMlI;gBACNzG,SAASA;gBACTT,QAAQA;gBACR4D,OAAOA;gBACPE,aAAaA;gBACbE,UAAUA;eACLQ,eAAe;gBAAEA;YAAa,IAAI,CAAC,GACnCI,QAAQA,OAAO,GAAG;gBAAEyL,aAAazL,QAAQA,OAAO,CAAC3F,IAAI;YAAC,IAAI,CAAC;gBAChE+T,SAAS,IAAM7L,mBAAmB;gBAClCqM,QAAQ,IAAM3U;gBACd4U,QAAQ;oBACNtM,mBAAmB;oBACnBtD,SAAS,EAAE;oBACXE,eAAe;oBACfE,YAAY;oBACZkC,aAAa;gBACf;;YAED4C,YAAY2K,MAAM;;;AAGzB;AACAtT,eAAeuT,WAAW,GAAG;AAE7B,eAAevT,eAAc"}
@@ -1104,8 +1104,8 @@ const MemoPaidDownloadAddButton = /*#__PURE__*/ memo(PaidDownloadAddButton);
1104
1104
  * first variant so the legacy Product block + checkout API (AGL-90) keep
1105
1105
  * charging correctly without reading the variants array.
1106
1106
  */ export function ProductEditorDialog(props) {
1107
- var _ref, _ref1, _current_description, _current_tags, _current_categoryIds, _current_options, _current_mediaUrls, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _ref13, _ref14, _current_description1, _ref15, _ref16, _current_description2, _current_tags1, _current_mediaUrls1, _current_options1, _subs_planLabel, _gifts_planLabel, _subs_planLabel1, _gifts_planLabel1, _current_oversellPolicy, _current_modifierGroups, _current_options2, _current_digitalFiles, _current_gatedVideos;
1108
- var _current_seo, _current_seo1, _current_shipping, _current_shipping1, _current_shipping2, _current_shipping3, _current_shipping4, _current_channel, _current_channel1, _current_channel2, _current_channel3, _current_channel4, _current_seo2, _current_seo3, _current_seo4, _current_seo5, _current_seo6, _current_seo7;
1107
+ var _ref, _ref1, _current_description, _current_tags, _current_categoryIds, _current_options, _current_mediaUrls, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9, _ref10, _ref11, _ref12, _ref13, _ref14, _current_description1, _ref15, _ref16, _current_description2, _current_tags1, _current_mediaUrls1, _current_options1, _subs_planLabel, _gifts_planLabel, _subs_planLabel1, _gifts_planLabel1, _current_oversellPolicy, _current_modifierGroups, _current_options2, _current_digitalFiles, _current_gatedVideos, _ref17;
1108
+ var _current_seo, _current_seo1, _current_shipping, _current_shipping1, _current_shipping2, _current_shipping3, _current_shipping4, _current_channel, _current_channel1, _current_channel2, _current_channel3, _current_channel4, _current_seo2, _current_seo3, _current_gatedVideos1, _current_seo4, _current_seo5, _current_seo6, _current_seo7;
1109
1109
  const { hostId, product, seedFromCache, seedUnreadable, seedListen, open, onClose } = props;
1110
1110
  /**
1111
1111
  * Field-level entitlement gates (AGL-2080). Both of these were fully
@@ -1258,6 +1258,16 @@ const MemoPaidDownloadAddButton = /*#__PURE__*/ memo(PaidDownloadAddButton);
1258
1258
  categories.rows,
1259
1259
  categoryIds
1260
1260
  ]);
1261
+ const setVideoAccessProducts = useCallback((picked)=>update({
1262
+ videoAccessProductIds: picked.map((item)=>item.$id)
1263
+ }), [
1264
+ update
1265
+ ]);
1266
+ const videoAccessProductIds = current.videoAccessProductIds;
1267
+ const pickedVideoAccess = useMemo(()=>relatedProducts.rows.filter((item)=>(videoAccessProductIds != null ? videoAccessProductIds : []).includes(item.$id)), [
1268
+ relatedProducts.rows,
1269
+ videoAccessProductIds
1270
+ ]);
1261
1271
  const relatedProductIds = current.relatedProductIds;
1262
1272
  const productId = product == null ? void 0 : product.$id;
1263
1273
  const relatedOptions = useMemo(()=>relatedProducts.rows.filter((item)=>!item.deletedAt && item.$id !== productId), [
@@ -1809,6 +1819,15 @@ const MemoPaidDownloadAddButton = /*#__PURE__*/ memo(PaidDownloadAddButton);
1809
1819
  gatedVideos: (_current_gatedVideos = current.gatedVideos) != null ? _current_gatedVideos : NO_VIDEOS,
1810
1820
  update: update
1811
1821
  }) : null,
1822
+ current.type === 'digital' && (((_ref17 = (_current_gatedVideos1 = current.gatedVideos) == null ? void 0 : _current_gatedVideos1.length) != null ? _ref17 : 0) > 0 || pickedVideoAccess.length > 0) ? /*#__PURE__*/ _jsx(ProductChipsField, {
1823
+ label: "Members videos are also open to buyers of",
1824
+ helperText: "Their buyers and active subscribers can watch this product's members videos too. Use it to share one video library across several plans.",
1825
+ options: relatedOptions,
1826
+ getOptionLabel: recordLabel,
1827
+ isOptionEqualToValue: sameRecord,
1828
+ value: pickedVideoAccess,
1829
+ onChange: setVideoAccessProducts
1830
+ }) : null,
1812
1831
  /*#__PURE__*/ _jsx(ProductChipsField, {
1813
1832
  label: "Related products (upsells)",
1814
1833
  helperText: "Shown by the Related products block; blank falls back to frequently-bought-together",