@aglyn/plugins-commerce 1.0.0-beta.199 → 1.0.0-beta.201

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 (111) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/catalog-organization-card.component.js +48 -3
  3. package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
  4. package/src/lib/components/console/gift-cards-card.component.d.ts +9 -0
  5. package/src/lib/components/console/gift-cards-card.component.js +53 -28
  6. package/src/lib/components/console/gift-cards-card.component.js.map +1 -1
  7. package/src/lib/components/console/host-orders-card.component.d.ts +26 -0
  8. package/src/lib/components/console/host-orders-card.component.js +264 -194
  9. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  10. package/src/lib/components/console/order-detail-dialog.component.js +12 -0
  11. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  12. package/src/lib/components/console/pos-page.component.d.ts +14 -0
  13. package/src/lib/components/console/pos-page.component.js +86 -45
  14. package/src/lib/components/console/pos-page.component.js.map +1 -1
  15. package/src/lib/components/console/product-editor-dialog.component.js +30 -6
  16. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  17. package/src/lib/components/console/product-slugs.d.ts +43 -0
  18. package/src/lib/components/console/product-slugs.js +60 -0
  19. package/src/lib/components/console/product-slugs.js.map +1 -0
  20. package/src/lib/components/console/products-hub-card.component.d.ts +2 -2
  21. package/src/lib/components/console/products-hub-card.component.js +229 -282
  22. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  23. package/src/lib/components/console/products-hub-zone.component.d.ts +10 -5
  24. package/src/lib/components/console/products-hub-zone.component.js +32 -9
  25. package/src/lib/components/console/products-hub-zone.component.js.map +1 -1
  26. package/src/lib/components/console/recovery-queue-card.component.d.ts +37 -5
  27. package/src/lib/components/console/recovery-queue-card.component.js +107 -86
  28. package/src/lib/components/console/recovery-queue-card.component.js.map +1 -1
  29. package/src/lib/components/console/reservations-card.component.js +15 -3
  30. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  31. package/src/lib/components/console/smart-collections.d.ts +32 -0
  32. package/src/lib/components/console/smart-collections.js +57 -0
  33. package/src/lib/components/console/smart-collections.js.map +1 -0
  34. package/src/lib/components/console/stock-movements-card.component.d.ts +13 -4
  35. package/src/lib/components/console/stock-movements-card.component.js +142 -180
  36. package/src/lib/components/console/stock-movements-card.component.js.map +1 -1
  37. package/src/lib/components/product-grid.d.ts +5 -0
  38. package/src/lib/components/product-grid.js +95 -34
  39. package/src/lib/components/product-grid.js.map +1 -1
  40. package/src/lib/constants/orders-list-query.d.ts +40 -0
  41. package/src/lib/constants/orders-list-query.js +205 -0
  42. package/src/lib/constants/orders-list-query.js.map +1 -0
  43. package/src/lib/constants/product-list-query.d.ts +42 -0
  44. package/src/lib/constants/product-list-query.js +217 -0
  45. package/src/lib/constants/product-list-query.js.map +1 -0
  46. package/src/lib/constants/stock-movement-query.d.ts +27 -0
  47. package/src/lib/constants/stock-movement-query.js +110 -0
  48. package/src/lib/constants/stock-movement-query.js.map +1 -0
  49. package/src/lib/constants/storefront-catalog-query.d.ts +103 -0
  50. package/src/lib/constants/storefront-catalog-query.js +312 -0
  51. package/src/lib/constants/storefront-catalog-query.js.map +1 -0
  52. package/src/lib/model/checkout-recovery.d.ts +37 -0
  53. package/src/lib/model/checkout-recovery.js +44 -0
  54. package/src/lib/model/checkout-recovery.js.map +1 -0
  55. package/src/lib/model/commerce-orders.d.ts +7 -0
  56. package/src/lib/model/commerce-orders.js.map +1 -1
  57. package/src/lib/model/commerce.d.ts +80 -0
  58. package/src/lib/model/commerce.js +67 -6
  59. package/src/lib/model/commerce.js.map +1 -1
  60. package/src/lib/model/gift-card-search.d.ts +24 -0
  61. package/src/lib/model/gift-card-search.js +48 -0
  62. package/src/lib/model/gift-card-search.js.map +1 -0
  63. package/src/lib/model/index.d.ts +1 -0
  64. package/src/lib/model/index.js +1 -0
  65. package/src/lib/model/index.js.map +1 -1
  66. package/src/lib/model/order-list-fields.d.ts +80 -0
  67. package/src/lib/model/order-list-fields.js +112 -0
  68. package/src/lib/model/order-list-fields.js.map +1 -0
  69. package/src/lib/server/billing-webhook.js +180 -99
  70. package/src/lib/server/billing-webhook.js.map +1 -1
  71. package/src/lib/server/cancel-order.js +6 -6
  72. package/src/lib/server/cancel-order.js.map +1 -1
  73. package/src/lib/server/cart-checkout.js +9 -2
  74. package/src/lib/server/cart-checkout.js.map +1 -1
  75. package/src/lib/server/catalog.d.ts +46 -30
  76. package/src/lib/server/catalog.js +507 -170
  77. package/src/lib/server/catalog.js.map +1 -1
  78. package/src/lib/server/checkout.js +3 -1
  79. package/src/lib/server/checkout.js.map +1 -1
  80. package/src/lib/server/collection-membership.d.ts +35 -0
  81. package/src/lib/server/collection-membership.js +172 -0
  82. package/src/lib/server/collection-membership.js.map +1 -0
  83. package/src/lib/server/draft-order.js +5 -3
  84. package/src/lib/server/draft-order.js.map +1 -1
  85. package/src/lib/server/gift-cards.js +7 -1
  86. package/src/lib/server/gift-cards.js.map +1 -1
  87. package/src/lib/server/member-name-search.d.ts +17 -0
  88. package/src/lib/server/member-name-search.js +23 -1
  89. package/src/lib/server/member-name-search.js.map +1 -1
  90. package/src/lib/server/membership-account.js +7 -3
  91. package/src/lib/server/membership-account.js.map +1 -1
  92. package/src/lib/server/membership-admin-password.js +8 -2
  93. package/src/lib/server/membership-admin-password.js.map +1 -1
  94. package/src/lib/server/membership-recover.js +4 -1
  95. package/src/lib/server/membership-recover.js.map +1 -1
  96. package/src/lib/server/membership-register.js +3 -1
  97. package/src/lib/server/membership-register.js.map +1 -1
  98. package/src/lib/server/pos-order.js +9 -5
  99. package/src/lib/server/pos-order.js.map +1 -1
  100. package/src/lib/server/process-abandoned.js +20 -7
  101. package/src/lib/server/process-abandoned.js.map +1 -1
  102. package/src/lib/server/process-restock.js +6 -2
  103. package/src/lib/server/process-restock.js.map +1 -1
  104. package/src/lib/server/reserve-stock.js +3 -4
  105. package/src/lib/server/reserve-stock.js.map +1 -1
  106. package/src/lib/server/reserve.js +3 -1
  107. package/src/lib/server/reserve.js.map +1 -1
  108. package/src/lib/server/site-page-enricher.js +3 -3
  109. package/src/lib/server/site-page-enricher.js.map +1 -1
  110. package/src/lib/server.js +4 -0
  111. package/src/lib/server.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/order-detail-dialog.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 CommerceModel from '../../model'\nimport { escapeHtml } from '../../utils/escape-html'\n// The CRM's address from the SHARED builder, not the plugin (AGL-2622): the\n// CRM already reaches marketing, and marketing reaches commerce, so an\n// import of the CRM from here would close a cycle between the three\n// plugins. The shared builder is pinned against the CRM's own routes by a\n// spec, so the address is the same one the hub resolves.\nimport { crmContactByEmailHref } from '@aglyn/aglyn'\nimport { AppLink, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { doc, runTransaction, updateDoc } from 'firebase/firestore'\nimport { useParams } from 'next/navigation'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nexport interface OrderDetailDialogProps {\n hostId: string\n order: (CommerceModel.HostOrder & { $id: string }) | null\n onClose: () => void\n}\n\nconst STATUS_COLOR: Record<\n string,\n 'default' | 'success' | 'warning' | 'error' | 'info'\n> = {\n pending: 'warning',\n paid: 'info',\n partially_fulfilled: 'info',\n fulfilled: 'success',\n delivered: 'success',\n cancelled: 'default',\n refunded: 'error',\n}\n\n/**\n * The dispute chip's colour (AGL-1796).\n *\n * `open` is WARNING rather than error because it is the case that still has a\n * deadline on it — the merchant can still act, and a red chip on a case they\n * might win says the money is gone when it is not. `lost` is the one that took\n * the money, and shares `refunded`'s red for that reason.\n */\nexport const DISPUTE_COLOR: Record<\n CommerceModel.OrderDisputeTone,\n 'default' | 'success' | 'warning' | 'error'\n> = {\n open: 'warning',\n lost: 'error',\n won: 'success',\n settled: 'default',\n}\n\nconst usd = (cents: number | undefined) =>\n `$${((cents ?? 0) / 100).toFixed(2)}`\n\n/**\n * Order detail (AGL-287): timeline, line items, totals, and the actions\n * the status machine allows — fulfill with tracking, refund, cancel, mark\n * delivered (each a server route that re-asks the transition under the\n * write), notes, printable packing slip.\n */\nexport function OrderDetailDialog(props: OrderDetailDialogProps) {\n const { hostId, order: rawOrder, onClose } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const [tracking, setTracking] = useState<{ carrier: string; number: string } | null>(null)\n const [note, setNote] = useState('')\n const [busy, setBusy] = useState(false)\n\n const order = rawOrder ? CommerceModel.liftLegacyOrder(rawOrder) : null\n const orderId = rawOrder?.$id\n /*\n * Where the buyer's CONTACT is (AGL-2622). A checkout that carried an\n * address updated a person in the CRM — a customer, with this order on\n * their timeline — and the dialog links there by the address, because\n * the contact's id is minted at capture and nothing on the order holds\n * it. The Contacts list is the lookup and opens the record on one match.\n * A guest checkout with no address updated nobody, so there is no link.\n * Built from the route params already in the URL — no document is read\n * to draw a link — and absent until they settle, so the dialog never\n * offers a link to a half-built address.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const customerCrmHref =\n params?.orgSlug && params?.host && order?.customerEmail\n ? crmContactByEmailHref(\n { orgSlug: String(params.orgSlug), host: String(params.host) },\n String(order.customerEmail),\n )\n : null\n\n /**\n * The one client write left in this dialog, and it is timeline-only ON\n * PURPOSE: notes carry no status, so `ORDER_TRANSITIONS` has nothing to say\n * about them and they stay out of the server routes' way. Every status\n * write goes through a route that re-asks the transition under the write —\n * cancel (AGL-1818), fulfil and mark-delivered (AGL-1819), refund\n * (AGL-1696). The moment a status rides along with a note, it must move\n * too; `order-fulfill-wiring.spec.tsx` pins the patch to `timeline` alone.\n */\n const write = useCallback(\n async (patch: Record<string, unknown>) => {\n if (!orderId) return\n await updateDoc(doc(firestore, 'hosts', hostId, 'orders', orderId), patch)\n },\n [firestore, hostId, orderId],\n )\n\n /**\n * Fulfil and mark-delivered go through `/api/commerce/fulfill-order`\n * (AGL-1819), not a client write — the same stale-dialog hole the cancel\n * swap (AGL-1818) closed: `can(…)` below only decides whether to RENDER\n * the buttons, so a dialog held open while the order was refunded in\n * another tab used to write `fulfilled` straight onto it. The route\n * re-asks `canTransitionOrder` inside the transaction that writes the\n * status, and that race now comes back as a 409 carrying the state that\n * refused.\n *\n * The messages follow the AGL-1784/1786 contract — say what happened: a\n * 409 is the guard refusing, not the machinery failing; the route's own\n * 500 is a rolled-back transaction (nothing landed, retry is safe and\n * correct); an answer with no JSON word from the handler, or no answer at\n * all, is NOT KNOWN — never \"nothing happened\". A retry is safe in every\n * case because the route writes once: a repeat finds the order already in\n * the target status and returns `already` without appending a second copy\n * of the same fulfillment.\n */\n const transition = useCallback(\n async (\n to: 'fulfilled' | 'delivered',\n extra: Record<string, string>,\n copy: { done: string; already: string; subject: string; action: string },\n ) => {\n if (!orderId) return false\n setBusy(true)\n try {\n let response: Response\n try {\n response = await authorizedFetch(\n user,\n '/api/commerce/fulfill-order',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, orderId, to, ...extra }),\n },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n `The request did not complete, so it is NOT known whether ${copy.subject}. ` +\n 'Reopen the order to check — retrying is safe, the server ' +\n 'writes it once.',\n { variant: 'error', allowDuplicate: true },\n )\n return false\n }\n const payload: any = await response.json().catch(() => ({}))\n if (!response.ok) {\n if (response.status === 409) {\n // The transition guard refusing: the order moved on (refunded,\n // cancelled) while this dialog was open. The route's message\n // names the state that refused it, and nothing was written.\n enqueueSnackbar(\n payload?.error ?? `This order can no longer be ${to}`,\n {\n variant: 'warning',\n allowDuplicate: true,\n },\n )\n } else if (payload?.error && response.status < 500) {\n // A refusal that wrote nothing — session, role, or an order that\n // is not there. The route's own word, verbatim.\n enqueueSnackbar(payload.error, {\n variant: 'error',\n allowDuplicate: true,\n })\n } else if (payload?.error) {\n // The route's 500 is a rolled-back transaction: nothing landed.\n // Only the handler's own JSON word licenses saying so.\n enqueueSnackbar(\n `${payload.error} — nothing changed, the order is as it was. Retrying is safe.`,\n { variant: 'error', allowDuplicate: true },\n )\n } else {\n // No JSON word from the handler (a gateway page, a proxy\n // timeout): whether the write landed is NOT known.\n enqueueSnackbar(\n `The ${copy.action} failed (${response.status}) and it is NOT ` +\n 'known whether it landed. Reopen the order to check — ' +\n 'retrying is safe, the server writes it once.',\n { variant: 'error', allowDuplicate: true },\n )\n }\n return false\n }\n enqueueSnackbar(payload?.already ? copy.already : copy.done, {\n variant: 'success',\n persist: false,\n })\n return true\n } finally {\n setBusy(false)\n }\n },\n [orderId, user, hostId, enqueueSnackbar],\n )\n\n const handleFulfill = useCallback(async () => {\n if (!order || !tracking) return\n const done = await transition(\n 'fulfilled',\n {\n ...(tracking.carrier ? { carrier: tracking.carrier } : {}),\n ...(tracking.number ? { trackingNumber: tracking.number } : {}),\n },\n {\n done: 'Order fulfilled',\n already: 'Order was already fulfilled',\n subject: 'the order was fulfilled',\n action: 'fulfillment',\n },\n )\n // The refused or unknown case keeps the form open — there is nothing to\n // celebrate, and the tracking is not yet recorded anywhere.\n if (done) setTracking(null)\n }, [order, tracking, transition])\n\n const handleDelivered = useCallback(async () => {\n if (!order) return\n await transition(\n 'delivered',\n {},\n {\n done: 'Order marked delivered',\n already: 'Order was already marked delivered',\n subject: 'the order was marked delivered',\n action: 'delivery update',\n },\n )\n }, [order, transition])\n\n /**\n * Cancel goes through `/api/commerce/cancel-order` (AGL-1818), not a client\n * write. The status flip and the stock release are one transaction there,\n * and the route re-asks `canTransitionOrder` under the same lock — the\n * `can('cancelled')` gate below only decides whether to RENDER the button,\n * so a dialog held open while the order ships in another tab used to write\n * `cancelled` straight onto a `fulfilled` order. Now that race comes back\n * as a 409 carrying the state that refused it.\n *\n * The messages follow the AGL-1784/1786 contract — say what happened:\n * a 409 is the guard refusing, not the cancel machinery failing; the\n * route's own 500 is a rolled-back transaction (nothing landed, retry is\n * safe and correct); an answer with no JSON word from the handler, or no\n * answer at all, is NOT KNOWN — never \"nothing happened\". A retry is safe\n * in every case because the route cancels once: a second cancel finds\n * `cancelled` and returns success without touching stock.\n */\n const handleCancel = useCallback(async () => {\n if (!order || !orderId) return\n const confirmed = await confirm({\n title: 'Cancel this order?',\n description:\n 'The buyer is NOT refunded automatically — refund first if they paid.',\n confirmationText: 'Cancel order',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setBusy(true)\n try {\n let response: Response\n try {\n response = await authorizedFetch(user, '/api/commerce/cancel-order', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, orderId }),\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n 'The request did not complete, so it is NOT known whether the ' +\n 'order was canceled. Reopen the order to check — retrying is ' +\n 'safe, the server cancels once.',\n { variant: 'error', allowDuplicate: true },\n )\n return\n }\n const payload: any = await response.json().catch(() => ({}))\n if (!response.ok) {\n if (response.status === 409) {\n // The transition guard refusing: the order moved on (shipped,\n // refunded) while this dialog was open. The route's message names\n // the state that refused it, and nothing was written.\n enqueueSnackbar(\n payload?.error ?? 'This order can no longer be canceled',\n {\n variant: 'warning',\n allowDuplicate: true,\n },\n )\n } else if (payload?.error && response.status < 500) {\n // A refusal that wrote nothing — session, role, or an order that\n // is not there. The route's own word, verbatim.\n enqueueSnackbar(payload.error, {\n variant: 'error',\n allowDuplicate: true,\n })\n } else if (payload?.error) {\n // The route's 500 is a rolled-back transaction: nothing landed and\n // the order is still open. Only the handler's own JSON word\n // licenses saying so.\n enqueueSnackbar(\n `${payload.error} — nothing changed, the order is still open. Retrying is safe.`,\n { variant: 'error', allowDuplicate: true },\n )\n } else {\n // No JSON word from the handler (a gateway page, a proxy timeout):\n // whether the cancel landed is NOT known.\n enqueueSnackbar(\n `The cancel failed (${response.status}) and it is NOT known ` +\n 'whether it landed. Reopen the order to check — retrying is ' +\n 'safe, the server cancels once.',\n { variant: 'error', allowDuplicate: true },\n )\n }\n return\n }\n const units = Number(payload?.units ?? 0)\n enqueueSnackbar(\n payload?.alreadyCancelled\n ? 'Order was already canceled'\n : units > 0\n ? `Order canceled — ${units} ${units === 1 ? 'unit' : 'units'} returned to stock`\n : 'Order canceled',\n { variant: 'success', persist: false },\n )\n } finally {\n setBusy(false)\n }\n }, [order, orderId, user, hostId, confirm, enqueueSnackbar])\n\n /**\n * Idempotency key for ONE refund attempt (AGL-1696), the same shape the POS\n * register uses for a sale (AGL-1691).\n *\n * Minted lazily so a retry of this attempt — a lost response, a second\n * click, the admin reopening the dialog after a timeout — reuses it and the\n * server replays instead of sending the money again. Retired on a definitive\n * answer, which makes the NEXT refund a new attempt: two partial refunds of\n * the same amount on the same order are two real refunds, and keying on the\n * order (or the amount) would silently swallow the second.\n *\n * NOT retired on a network failure or a 5xx — that is precisely the window\n * the key exists to cover.\n */\n const attemptKey = useRef('')\n useEffect(() => {\n attemptKey.current = ''\n }, [orderId])\n\n /**\n * `lineItemIds` scopes the refund to named lines (AGL-2454).\n *\n * Without it a partial refund is an AMOUNT and nothing else, so the product\n * cannot know which goods came back and revokes nothing — a 99%-refunded\n * order kept its downloads, licence keys, gated pages and verified review.\n * Naming the lines is the only way that question gets an honest answer, and\n * the route derives the amount FROM the lines rather than trusting a figure\n * typed beside them.\n */\n const handleRefund = useCallback(async (lineItemIds?: number[]) => {\n if (!order || !orderId) return\n const lines = order.lineItems ?? []\n const scoped = (lineItemIds ?? []).length > 0\n // The SERVER's figure, not a second derivation of it. This was\n // the list value `unitAmountCents x quantity`, which on a discounted order\n // is more than the buyer paid — so the dialog quoted one number and the\n // route refunded another. One function answers both.\n const scopedCents = CommerceModel.orderLineRefundCents(\n order,\n lineItemIds ?? [],\n )\n const confirmed = await confirm({\n title: scoped ? 'Refund this line?' : 'Refund this order?',\n description:\n (scoped\n ? `Refunds ${usd(scopedCents)} for ${(lineItemIds ?? [])\n .map((index) => lines[index]?.name ?? `line ${index}`)\n .join(', ')} through Stripe, and withdraws that line's ` +\n 'downloads, license keys and gated content. A license key already ' +\n 'sent to the buyer is retired, not returned to your pool — they ' +\n 'still hold the string, so reissuing it would give two people one ' +\n 'working key.'\n : `Refunds ${usd(\n (order.totals?.totalCents ?? order.amountCents ?? 0) -\n (order.refundedCents ?? 0),\n )} to the buyer through Stripe.`) +\n // An open INQUIRY keeps this button live on purpose (AGL-1820):\n // Stripe names a full refund as the way to resolve one before it\n // escalates to a chargeback. Said here so the admin reads the refund\n // as the documented exit, not a risk taken against the badge.\n (CommerceModel.orderHasOpenDispute(order) &&\n !CommerceModel.orderDisputeBlocksRefund(order)\n ? ' An inquiry is open on this charge — a full refund resolves it' +\n ' before it can become a chargeback.'\n : ''),\n confirmationText: 'Refund',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setBusy(true)\n // `randomUUID` needs a secure context, which the console always is, but\n // fall back rather than throw on a refund.\n if (!attemptKey.current) {\n attemptKey.current =\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n }\n try {\n const response = await authorizedFetch(user, '/api/commerce/refund', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': attemptKey.current,\n },\n body: JSON.stringify({\n hostId,\n orderId,\n ...(scoped ? { lineItemIds } : {}),\n }),\n })\n const payload = await response.json()\n // A definitive answer ends this attempt either way: the next refund is a\n // new one and must get a new key. A 5xx or a thrown fetch keeps the key,\n // so pressing Refund again dedupes rather than sends a second transfer.\n if (response.status < 500) attemptKey.current = ''\n if (!response.ok) {\n // A 409 is a guard REFUSING — the status machine, or the open-dispute\n // block (AGL-1809), whose body explains what to do instead — not the\n // refund machinery failing. The route wrote nothing, so it surfaces\n // verbatim as a warning, same as the cancel path's 409 (AGL-1818).\n enqueueSnackbar(payload?.error ?? 'Refund failed', {\n variant: response.status === 409 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n } else {\n enqueueSnackbar('Refund issued', { variant: 'success', persist: false })\n }\n } finally {\n setBusy(false)\n }\n }, [order, orderId, user, hostId, confirm, enqueueSnackbar])\n\n /**\n * Answer the restock question a reversal flagged (AGL-1806).\n *\n * The answer MOVES NO STOCK, which is AGL-1797's ledger argument and it is\n * binding: the products hub's \"Adjust stock\" is the one stock writer (it\n * writes the counts AND the `InventoryAdjustment` row the hub renders as\n * history), so \"Restocked\" here is clicked AFTER the merchant used it, and\n * \"No restock\" says the goods are not recoverable. Either answer only sets\n * the `resolution` triple `OrderRestockCheck` declares and says so on the\n * timeline.\n *\n * A TRANSACTION rather than the dialog's plain `write`, keyed on the\n * rendered `flaggedAtMs`, because an answer must land ONCE. The flag writer\n * re-asks an ANSWERED question after the next reversal, and the cancel\n * route (AGL-1808) answers an open one itself when it returns the stock —\n * so a stale dialog writing blind would either re-answer a settled question\n * or replace a brand-new one with a resolved copy of the old. The\n * transaction re-reads on the server (the web SDK will not run one from\n * cache — the products hub's `writeGuardedBySeed` refusal of unconfirmed\n * data, by other means) and refuses both cases with the truth: nothing was\n * written.\n */\n const handleRestockAnswer = useCallback(\n async (resolution: 'restocked' | 'dismissed') => {\n const check = order?.restockCheck\n if (!order || !orderId || !check || check.resolution) return\n setBusy(true)\n try {\n const reference = doc(firestore, 'hosts', hostId, 'orders', orderId)\n const verdict = await runTransaction(firestore, async (transaction) => {\n const snapshot = await transaction.get(reference)\n if (!snapshot.exists()) return 'gone'\n const current = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n const fresh = current.restockCheck\n if (!fresh || fresh.resolution) return 'answered'\n if (fresh.flaggedAtMs !== check.flaggedAtMs) return 'changed'\n const resolvedAtMs = Date.now()\n const uid = String((user as any)?.uid ?? '')\n transaction.update(reference, {\n restockCheck: {\n ...fresh,\n resolution,\n resolvedAtMs,\n ...(uid ? { resolvedBy: uid } : {}),\n } satisfies CommerceModel.OrderRestockCheck,\n // The SERVER's timeline, not the dialog's — a note landed from\n // another tab must survive the append.\n timeline: CommerceModel.appendOrderEvent(\n current,\n 'restock-check',\n resolution === 'restocked'\n ? 'answered — restocked'\n : 'answered — no restock',\n resolvedAtMs,\n ),\n })\n return 'recorded'\n })\n if (verdict === 'recorded') {\n enqueueSnackbar(\n resolution === 'restocked'\n ? 'Recorded as restocked'\n : 'Recorded — no restock',\n { variant: 'success', persist: false },\n )\n } else if (verdict === 'answered') {\n // The cancel route, or another admin, got there first.\n enqueueSnackbar(\n 'This restock question was already answered — nothing changed.',\n { variant: 'info', persist: false },\n )\n } else if (verdict === 'changed') {\n // A later reversal re-asked; this dialog shows the OLD question.\n enqueueSnackbar(\n 'The restock question changed while this dialog was open — ' +\n 'nothing was written. Reopen the order to see the current one.',\n { variant: 'warning', allowDuplicate: true },\n )\n } else {\n enqueueSnackbar('This order no longer exists — nothing was written.', {\n variant: 'warning',\n allowDuplicate: true,\n })\n }\n } catch (error) {\n // A transaction is all-or-nothing, and a thrown one did not commit.\n console.error(error)\n enqueueSnackbar(\n 'The answer was not recorded — it needs a live connection and the ' +\n 'editor or admin role. Nothing changed; answering again is safe.',\n { variant: 'error', allowDuplicate: true },\n )\n } finally {\n setBusy(false)\n }\n },\n [order, orderId, firestore, hostId, user, enqueueSnackbar],\n )\n\n const handleNote = useCallback(async () => {\n if (!order || !note.trim()) return\n await write({\n timeline: CommerceModel.appendOrderEvent(order, 'note', note.trim().slice(0, 500)),\n })\n setNote('')\n }, [order, note, write])\n\n const handlePackingSlip = useCallback(() => {\n if (!order) return\n const win = window.open('', '_blank', 'width=600,height=800')\n if (!win) return\n // ESCAPED (AGL-2283). This is `document.write` into an `about:blank`\n // popup, which INHERITS the console's origin — and `order.shippingAddress`\n // is copied verbatim from Stripe's `shipping_details`, i.e. typed by the\n // SHOPPER. A name of `<img src=x onerror=…>` ran script against the\n // merchant's own authenticated session. React guards nothing here because\n // none of this is React. Line names and SKUs are merchant-authored and\n // lower severity, but they are the same construction and get the same\n // treatment rather than a case-by-case argument.\n const rows = (order.lineItems ?? [])\n .map(\n (line) =>\n `<tr><td>${escapeHtml(line.quantity)}×</td><td>${escapeHtml(\n line.name,\n )}${\n line.variantLabel ? ` — ${escapeHtml(line.variantLabel)}` : ''\n }</td><td>${escapeHtml(line.sku ?? '')}</td></tr>`,\n )\n .join('')\n const address = order.shippingAddress\n win.document.write(\n `<h2>Packing slip ${escapeHtml(\n CommerceModel.formatOrderNumber(order, orderId),\n )}</h2>` +\n (address\n ? `<p>${[address.name, address.line1, address.line2, `${address.city ?? ''} ${address.state ?? ''} ${address.postalCode ?? ''}`, address.country].filter(Boolean).map((part) => escapeHtml(part)).join('<br/>')}</p>`\n : '') +\n `<table border=\"0\" cellpadding=\"6\">${rows}</table>`,\n )\n win.document.close()\n // Print from the opener, not from an injected inline script (AGL-523) —\n // the popup inherits this document's CSP, where an un-nonced inline\n // script is blocked under the enforcing policy. Same reasoning as the POS\n // receipt.\n win.focus()\n win.print()\n }, [order, orderId])\n\n if (!order) return null\n const totals = order.totals\n const can = (to: CommerceModel.OrderStatus) => CommerceModel.canTransitionOrder(order.status, to)\n // A lost chargeback leaves `status: 'refunded'` (AGL-1787), so the status\n // chip alone tells the merchant they chose this. The badge is the correction.\n const dispute = CommerceModel.describeOrderDispute(order)\n const reversal = CommerceModel.splitOrderReversal(order)\n // The restock question a reversal flagged, while it is still open\n // (AGL-1806). Absent `resolution` IS the open state — the writer only ever\n // re-flags an answered check (AGL-1797).\n const restock =\n order.restockCheck && !order.restockCheck.resolution\n ? order.restockCheck\n : null\n // Whether the reversal NAMED the lines this question is about (AGL-2325).\n // AGL-2454 gave a refund a line selection, and `flagOrderRestock` now scopes\n // the question to it — so the \"we cannot tell which goods came back\" caveat\n // below is true of an amount-only reversal and false of this one. Asked of\n // the order's own withdrawal record rather than of a flag on the check, so a\n // prompt written before line indexes existed reads as the amount-only case\n // it was.\n const restockLinesNamed = Boolean(\n restock?.lines?.length &&\n restock.lines.every(\n (line) =>\n line.lineIndex != null &&\n CommerceModel.orderLineRefunded(order, line.lineIndex),\n ),\n )\n\n return (\n <Dialog open onClose={onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <span>{`Order ${CommerceModel.formatOrderNumber(order, orderId)}`}</span>\n <Chip\n label={order.status.replace('_', ' ')}\n size=\"small\"\n color={STATUS_COLOR[order.status] ?? 'default'}\n variant=\"outlined\"\n />\n {dispute ? (\n <Tooltip title={dispute.detail}>\n <Chip\n label={dispute.label}\n size=\"small\"\n color={DISPUTE_COLOR[dispute.tone]}\n variant=\"filled\"\n />\n </Tooltip>\n ) : null}\n {order.channel && order.channel !== 'online' ? (\n <Chip label={order.channel} size=\"small\" variant=\"outlined\" />\n ) : null}\n </Stack>\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {[order.customerName, order.customerEmail]\n .filter(Boolean)\n .join(' · ') || 'Guest buyer'}\n </Typography>\n {(order.lineItems ?? []).map((line, index) => {\n // WHAT THIS LINE IS STILL ENTITLED TO, per line (AGL-2454). A refund\n // used to be a number on the order and nothing more, so the merchant\n // could not see — and the product could not enforce — which goods had\n // come back.\n const withdrawn = CommerceModel.orderLineRefunded(order, index)\n return (\n <Stack key={index} direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography\n variant=\"body2\"\n sx={{\n flex: 1,\n ...(withdrawn ? { textDecoration: 'line-through' } : {}),\n }}\n color={withdrawn ? 'text.secondary' : 'text.primary'}\n >\n {`${line.quantity}× ${line.name}` +\n (line.variantLabel ? ` — ${line.variantLabel}` : '')}\n </Typography>\n {withdrawn ? (\n <Chip label=\"refunded\" size=\"small\" color=\"error\" variant=\"outlined\" />\n ) : can('refunded') &&\n !CommerceModel.orderDisputeBlocksRefund(order) ? (\n <Button\n size=\"small\"\n color=\"error\"\n disabled={busy}\n onClick={() => handleRefund([index])}\n >\n {'Refund line'}\n </Button>\n ) : null}\n <Typography variant=\"body2\">\n {usd(line.unitAmountCents * line.quantity)}\n </Typography>\n </Stack>\n )\n })}\n {CommerceModel.orderRefundState(order) !== 'none' ? (\n // The state, said in words (AGL-2454). \"Partially refunded, no lines\n // withdrawn\" is the honest reading of an amount-only refund, and it\n // is what tells a merchant their buyer still has the downloads.\n <Typography variant=\"caption\" color=\"error\">\n {CommerceModel.orderRefundSummary(order)}\n </Typography>\n ) : null}\n {totals ? (\n <>\n <Divider />\n {(\n [\n ['Items', totals.itemsCents],\n ['Shipping', totals.shippingCents],\n ['Tax', totals.taxCents],\n ['Discount', -totals.discountCents],\n ['Total', totals.totalCents],\n ] as Array<[string, number]>\n ).map(([label, cents]) => (\n <Stack key={label} direction=\"row\">\n <Typography\n variant=\"body2\"\n sx={{ flex: 1 }}\n color={label === 'Total' ? 'text.primary' : 'text.secondary'}\n >\n {label}\n </Typography>\n <Typography\n variant=\"body2\"\n sx={{ fontWeight: label === 'Total' ? 600 : 400 }}\n >\n {`${cents < 0 ? '-' : ''}${usd(Math.abs(cents))}`}\n </Typography>\n </Stack>\n ))}\n {/*\n HOW the tax on this order was computed (AGL-2451). The `Tax` row\n above states an amount and nothing about which machinery produced\n it, and a merchant reading one order could not tell Stripe Tax\n (computed against Aglyn's registrations) from their own configured\n rate. Those are different facts about whose registration the money\n is held under, and the order is where a merchant looks.\n\n Describes the mechanism and makes NO remittance determination —\n the constraint AGL-2440's report ships under. An order written\n before the stamp existed says so, rather than being rendered as\n \"no tax\": absent means NOT RECORDED, and `describeOrderTaxMode`\n is where that distinction is kept.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {CommerceModel.describeOrderTaxMode(order.taxMode)}\n </Typography>\n {/*\n Both figures live in `refundedCents` (AGL-1787), so a lost\n chargeback used to render as \"Refunded $62.00\" — the merchant's\n own decision, spelled the same as money taken from them. Split by\n door, and show BOTH when a partial refund and a chargeback each\n took a piece.\n */}\n {reversal.refundedCents ? (\n <Typography variant=\"caption\" color=\"error\">\n {`Refunded ${usd(reversal.refundedCents)}`}\n </Typography>\n ) : null}\n {reversal.chargedBackCents ? (\n <Typography variant=\"caption\" color=\"error\">\n {`Charged back ${usd(reversal.chargedBackCents)}`}\n </Typography>\n ) : null}\n </>\n ) : null}\n {restock ? (\n <>\n <Divider />\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Restock check'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${restock.units} ${\n restock.units === 1 ? 'unit' : 'units'\n } may need restocking after this ${\n restock.kind === 'chargeback' ? 'chargeback' : 'refund'\n }.` +\n // The chargeback default is NO, same as the timeline's\n // wording: the shopper kept the item and took the money.\n (restock.kind === 'chargeback'\n ? ' The shopper kept the goods unless they actually came back.'\n : '') +\n // On a partial the flagged units are the MOST it could be —\n // UNLESS the refund named its lines (AGL-2325), in which\n // case the question is scoped to exactly those and the\n // merchant is only being asked whether the goods came back.\n (restock.fullyReversed\n ? ''\n : restockLinesNamed\n ? ' Only part of the money came back: these are the lines withdrawn by this refund, so the units are theirs — only you know whether the goods came back.'\n : ' Only part of the money came back, so these units are an upper bound — only you know which goods returned.')}\n </Typography>\n {restock.lines.map((line, index) => (\n <Typography key={index} variant=\"caption\" color=\"text.secondary\">\n {`${line.quantity}× ${line.name ?? line.productId}` +\n (line.variantLabel ? ` — ${line.variantLabel}` : '')}\n </Typography>\n ))}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'If goods came back, put them on the shelf with \"Adjust ' +\n 'stock\" in the products hub first — these answers move no ' +\n 'stock, they only clear this question.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy}\n onClick={() => handleRestockAnswer('restocked')}\n >\n {'Restocked'}\n </Button>\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() => handleRestockAnswer('dismissed')}\n >\n {'No restock'}\n </Button>\n </Stack>\n </Stack>\n </>\n ) : null}\n <Divider />\n <Typography variant=\"subtitle2\">{'Timeline'}</Typography>\n {(order.timeline ?? [])\n .slice()\n .reverse()\n .map((event, index) => (\n <Typography key={index} variant=\"caption\" color=\"text.secondary\">\n {`${new Date(event.atMs).toLocaleString()} — ${event.event}` +\n (event.detail ? `: ${event.detail}` : '')}\n </Typography>\n ))}\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Add note\"\n value={note}\n onChange={(event) => setNote(event.target.value)}\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <Button size=\"small\" disabled={!note.trim()} onClick={handleNote}>\n {'Add'}\n </Button>\n </Stack>\n {tracking ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Carrier\"\n value={tracking.carrier}\n onChange={(event) =>\n setTracking({ ...tracking, carrier: event.target.value })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"UPS\"\n />\n <TextField\n label=\"Tracking number\"\n value={tracking.number}\n onChange={(event) =>\n setTracking({ ...tracking, number: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n disabled={busy}\n onClick={handleFulfill}\n >\n {'Fulfill'}\n </Button>\n </Stack>\n ) : null}\n {order.paymentLinkUrl && order.status === 'pending' ? (\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => {\n navigator.clipboard.writeText(String(order.paymentLinkUrl))\n enqueueSnackbar('Payment link copied', {\n variant: 'success',\n persist: false,\n })\n }}\n >\n {'Copy payment link'}\n </Button>\n ) : null}\n </DialogContent>\n <DialogActions>\n {customerCrmHref ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={customerCrmHref}\n >\n {'View customer in CRM'}\n </Button>\n ) : null}\n <Button onClick={handlePackingSlip}>{'Packing slip'}</Button>\n {can('cancelled') ? (\n <Button color=\"error\" disabled={busy} onClick={handleCancel}>\n {'Cancel order'}\n </Button>\n ) : null}\n {can('refunded') ? (\n // Disabled on `orderDisputeBlocksRefund`, NOT the badge's broader\n // `orderHasOpenDispute` (AGL-1820): a formal open dispute means the\n // bank already pulled the funds and the route answers 409\n // (AGL-1809), while an open INQUIRY shows the badge but must keep\n // this button live — a full refund is how an inquiry is resolved.\n CommerceModel.orderDisputeBlocksRefund(order) ? (\n <Tooltip\n title={\n 'A chargeback is open on this order, and refunding would not' +\n ' withdraw it — the bank has already taken the disputed' +\n ' amount, so a refund on top would pay the shopper twice.' +\n ' Respond to the dispute or accept it in the Stripe' +\n ' dashboard; refund any remainder once it settles.'\n }\n >\n {/* A disabled button fires no pointer events; the wrapper\n carries the hover for the tooltip. */}\n <span>\n <Button color=\"error\" disabled>\n {'Refund'}\n </Button>\n </span>\n </Tooltip>\n ) : (\n <Button\n color=\"error\"\n disabled={busy}\n onClick={() => handleRefund()}\n >\n {'Refund'}\n </Button>\n )\n ) : null}\n {(can('fulfilled') || can('partially_fulfilled')) && !tracking ? (\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setTracking({ carrier: '', number: '' })}\n >\n {'Fulfill…'}\n </Button>\n ) : null}\n {can('delivered') ? (\n <Button disabled={busy} onClick={handleDelivered}>\n {'Mark delivered'}\n </Button>\n ) : null}\n <Button onClick={onClose}>{'Close'}</Button>\n </DialogActions>\n </Dialog>\n )\n}\nOrderDetailDialog.displayName = 'OrderDetailDialog'\n\nexport default OrderDetailDialog\n"],"names":["CommerceModel","escapeHtml","crmContactByEmailHref","AppLink","useConfirmationContext","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Stack","TextField","Tooltip","Typography","doc","runTransaction","updateDoc","useParams","useCallback","useEffect","useRef","useState","useFirestore","useUser","authorizedFetch","STATUS_COLOR","pending","paid","partially_fulfilled","fulfilled","delivered","cancelled","refunded","DISPUTE_COLOR","open","lost","won","settled","usd","cents","toFixed","OrderDetailDialog","props","order","restock","hostId","rawOrder","onClose","firestore","data","user","enqueueSnackbar","confirm","tracking","setTracking","note","setNote","busy","setBusy","liftLegacyOrder","orderId","$id","params","customerCrmHref","orgSlug","host","customerEmail","String","write","patch","transition","to","extra","copy","response","method","headers","body","JSON","stringify","error","console","subject","variant","allowDuplicate","payload","json","catch","ok","status","action","already","done","persist","handleFulfill","carrier","number","trackingNumber","handleDelivered","handleCancel","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","units","Number","alreadyCancelled","attemptKey","current","handleRefund","lineItemIds","lines","lineItems","scoped","length","scopedCents","orderLineRefundCents","map","index","name","join","totals","totalCents","amountCents","refundedCents","orderHasOpenDispute","orderDisputeBlocksRefund","globalThis","crypto","randomUUID","Date","now","Math","random","toString","slice","handleRestockAnswer","resolution","check","restockCheck","reference","verdict","transaction","snapshot","get","exists","fresh","flaggedAtMs","resolvedAtMs","uid","update","resolvedBy","timeline","appendOrderEvent","handleNote","trim","handlePackingSlip","address","win","window","rows","line","quantity","variantLabel","sku","shippingAddress","document","formatOrderNumber","line1","line2","city","state","postalCode","country","filter","Boolean","part","close","focus","print","can","canTransitionOrder","dispute","describeOrderDispute","reversal","splitOrderReversal","restockLinesNamed","every","lineIndex","orderLineRefunded","maxWidth","fullWidth","direction","spacing","sx","alignItems","span","label","replace","size","detail","tone","channel","display","flexDirection","gap","customerName","withdrawn","flex","textDecoration","disabled","onClick","unitAmountCents","orderRefundState","orderRefundSummary","itemsCents","shippingCents","taxCents","discountCents","fontWeight","abs","describeOrderTaxMode","taxMode","chargedBackCents","kind","fullyReversed","productId","reverse","event","atMs","toLocaleString","value","onChange","target","width","placeholder","paymentLinkUrl","alignSelf","navigator","clipboard","writeText","component","componentVariant","nativeButton","href","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,UAAU,QAAQ,6BAAyB;AACpD,4EAA4E;AAC5E,uEAAuE;AACvE,oEAAoE;AACpE,0EAA0E;AAC1E,yDAAyD;AACzD,SAASC,qBAAqB,QAAQ,eAAc;AACpD,SAASC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AACtE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,cAAc,EAAEC,SAAS,QAAQ,qBAAoB;AACnE,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAChE,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,eAAe,QAAQ,2CAA0C;AAQ1E,MAAMC,eAGF;IACFC,SAAS;IACTC,MAAM;IACNC,qBAAqB;IACrBC,WAAW;IACXC,WAAW;IACXC,WAAW;IACXC,UAAU;AACZ;AAEA;;;;;;;CAOC,GACD,OAAO,MAAMC,gBAGT;IACFC,MAAM;IACNC,MAAM;IACNC,KAAK;IACLC,SAAS;AACX,EAAC;AAED,MAAMC,MAAM,CAACC,QACX,CA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,gBAAgBA,IAAI,sBAAqB,KAAM,CAAClI,yBACpD,KAAClD;wBACCgF,SAAQ;wBACRsB,OAAM;wBACN6G,SAAS,IAAMhK,YAAY;gCAAEyC,SAAS;gCAAIC,QAAQ;4BAAG;kCAEpD;yBAED;oBACHuF,IAAI,6BACH,KAACpL;wBAAOkN,UAAU5J;wBAAM6J,SAASpH;kCAC9B;yBAED;kCACJ,KAAC/F;wBAAOmN,SAASvK;kCAAU;;;;;;AAInC;AACAN,kBAAkB+M,WAAW,GAAG;AAEhC,eAAe/M,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/order-detail-dialog.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 CommerceModel from '../../model'\nimport { escapeHtml } from '../../utils/escape-html'\n// The CRM's address from the SHARED builder, not the plugin (AGL-2622): the\n// CRM already reaches marketing, and marketing reaches commerce, so an\n// import of the CRM from here would close a cycle between the three\n// plugins. The shared builder is pinned against the CRM's own routes by a\n// spec, so the address is the same one the hub resolves.\nimport { crmContactByEmailHref } from '@aglyn/aglyn'\nimport { describePaymentRisk } from '@aglyn/aglyn/app-utils/payment-risk'\nimport { AppLink, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Divider,\n Stack,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { doc, runTransaction, updateDoc } from 'firebase/firestore'\nimport { useParams } from 'next/navigation'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\n\nexport interface OrderDetailDialogProps {\n hostId: string\n order: (CommerceModel.HostOrder & { $id: string }) | null\n onClose: () => void\n}\n\nconst STATUS_COLOR: Record<\n string,\n 'default' | 'success' | 'warning' | 'error' | 'info'\n> = {\n pending: 'warning',\n paid: 'info',\n partially_fulfilled: 'info',\n fulfilled: 'success',\n delivered: 'success',\n cancelled: 'default',\n refunded: 'error',\n}\n\n/**\n * The dispute chip's colour (AGL-1796).\n *\n * `open` is WARNING rather than error because it is the case that still has a\n * deadline on it — the merchant can still act, and a red chip on a case they\n * might win says the money is gone when it is not. `lost` is the one that took\n * the money, and shares `refunded`'s red for that reason.\n */\nexport const DISPUTE_COLOR: Record<\n CommerceModel.OrderDisputeTone,\n 'default' | 'success' | 'warning' | 'error'\n> = {\n open: 'warning',\n lost: 'error',\n won: 'success',\n settled: 'default',\n}\n\nconst usd = (cents: number | undefined) =>\n `$${((cents ?? 0) / 100).toFixed(2)}`\n\n/**\n * Order detail (AGL-287): timeline, line items, totals, and the actions\n * the status machine allows — fulfill with tracking, refund, cancel, mark\n * delivered (each a server route that re-asks the transition under the\n * write), notes, printable packing slip.\n */\nexport function OrderDetailDialog(props: OrderDetailDialogProps) {\n const { hostId, order: rawOrder, onClose } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const [tracking, setTracking] = useState<{ carrier: string; number: string } | null>(null)\n const [note, setNote] = useState('')\n const [busy, setBusy] = useState(false)\n\n const order = rawOrder ? CommerceModel.liftLegacyOrder(rawOrder) : null\n const orderId = rawOrder?.$id\n /*\n * Where the buyer's CONTACT is (AGL-2622). A checkout that carried an\n * address updated a person in the CRM — a customer, with this order on\n * their timeline — and the dialog links there by the address, because\n * the contact's id is minted at capture and nothing on the order holds\n * it. The Contacts list is the lookup and opens the record on one match.\n * A guest checkout with no address updated nobody, so there is no link.\n * Built from the route params already in the URL — no document is read\n * to draw a link — and absent until they settle, so the dialog never\n * offers a link to a half-built address.\n */\n const params = useParams<{ orgSlug?: string; host?: string }>()\n const customerCrmHref =\n params?.orgSlug && params?.host && order?.customerEmail\n ? crmContactByEmailHref(\n { orgSlug: String(params.orgSlug), host: String(params.host) },\n String(order.customerEmail),\n )\n : null\n\n /**\n * The one client write left in this dialog, and it is timeline-only ON\n * PURPOSE: notes carry no status, so `ORDER_TRANSITIONS` has nothing to say\n * about them and they stay out of the server routes' way. Every status\n * write goes through a route that re-asks the transition under the write —\n * cancel (AGL-1818), fulfil and mark-delivered (AGL-1819), refund\n * (AGL-1696). The moment a status rides along with a note, it must move\n * too; `order-fulfill-wiring.spec.tsx` pins the patch to `timeline` alone.\n */\n const write = useCallback(\n async (patch: Record<string, unknown>) => {\n if (!orderId) return\n await updateDoc(doc(firestore, 'hosts', hostId, 'orders', orderId), patch)\n },\n [firestore, hostId, orderId],\n )\n\n /**\n * Fulfil and mark-delivered go through `/api/commerce/fulfill-order`\n * (AGL-1819), not a client write — the same stale-dialog hole the cancel\n * swap (AGL-1818) closed: `can(…)` below only decides whether to RENDER\n * the buttons, so a dialog held open while the order was refunded in\n * another tab used to write `fulfilled` straight onto it. The route\n * re-asks `canTransitionOrder` inside the transaction that writes the\n * status, and that race now comes back as a 409 carrying the state that\n * refused.\n *\n * The messages follow the AGL-1784/1786 contract — say what happened: a\n * 409 is the guard refusing, not the machinery failing; the route's own\n * 500 is a rolled-back transaction (nothing landed, retry is safe and\n * correct); an answer with no JSON word from the handler, or no answer at\n * all, is NOT KNOWN — never \"nothing happened\". A retry is safe in every\n * case because the route writes once: a repeat finds the order already in\n * the target status and returns `already` without appending a second copy\n * of the same fulfillment.\n */\n const transition = useCallback(\n async (\n to: 'fulfilled' | 'delivered',\n extra: Record<string, string>,\n copy: { done: string; already: string; subject: string; action: string },\n ) => {\n if (!orderId) return false\n setBusy(true)\n try {\n let response: Response\n try {\n response = await authorizedFetch(\n user,\n '/api/commerce/fulfill-order',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, orderId, to, ...extra }),\n },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n `The request did not complete, so it is NOT known whether ${copy.subject}. ` +\n 'Reopen the order to check — retrying is safe, the server ' +\n 'writes it once.',\n { variant: 'error', allowDuplicate: true },\n )\n return false\n }\n const payload: any = await response.json().catch(() => ({}))\n if (!response.ok) {\n if (response.status === 409) {\n // The transition guard refusing: the order moved on (refunded,\n // cancelled) while this dialog was open. The route's message\n // names the state that refused it, and nothing was written.\n enqueueSnackbar(\n payload?.error ?? `This order can no longer be ${to}`,\n {\n variant: 'warning',\n allowDuplicate: true,\n },\n )\n } else if (payload?.error && response.status < 500) {\n // A refusal that wrote nothing — session, role, or an order that\n // is not there. The route's own word, verbatim.\n enqueueSnackbar(payload.error, {\n variant: 'error',\n allowDuplicate: true,\n })\n } else if (payload?.error) {\n // The route's 500 is a rolled-back transaction: nothing landed.\n // Only the handler's own JSON word licenses saying so.\n enqueueSnackbar(\n `${payload.error} — nothing changed, the order is as it was. Retrying is safe.`,\n { variant: 'error', allowDuplicate: true },\n )\n } else {\n // No JSON word from the handler (a gateway page, a proxy\n // timeout): whether the write landed is NOT known.\n enqueueSnackbar(\n `The ${copy.action} failed (${response.status}) and it is NOT ` +\n 'known whether it landed. Reopen the order to check — ' +\n 'retrying is safe, the server writes it once.',\n { variant: 'error', allowDuplicate: true },\n )\n }\n return false\n }\n enqueueSnackbar(payload?.already ? copy.already : copy.done, {\n variant: 'success',\n persist: false,\n })\n return true\n } finally {\n setBusy(false)\n }\n },\n [orderId, user, hostId, enqueueSnackbar],\n )\n\n const handleFulfill = useCallback(async () => {\n if (!order || !tracking) return\n const done = await transition(\n 'fulfilled',\n {\n ...(tracking.carrier ? { carrier: tracking.carrier } : {}),\n ...(tracking.number ? { trackingNumber: tracking.number } : {}),\n },\n {\n done: 'Order fulfilled',\n already: 'Order was already fulfilled',\n subject: 'the order was fulfilled',\n action: 'fulfillment',\n },\n )\n // The refused or unknown case keeps the form open — there is nothing to\n // celebrate, and the tracking is not yet recorded anywhere.\n if (done) setTracking(null)\n }, [order, tracking, transition])\n\n const handleDelivered = useCallback(async () => {\n if (!order) return\n await transition(\n 'delivered',\n {},\n {\n done: 'Order marked delivered',\n already: 'Order was already marked delivered',\n subject: 'the order was marked delivered',\n action: 'delivery update',\n },\n )\n }, [order, transition])\n\n /**\n * Cancel goes through `/api/commerce/cancel-order` (AGL-1818), not a client\n * write. The status flip and the stock release are one transaction there,\n * and the route re-asks `canTransitionOrder` under the same lock — the\n * `can('cancelled')` gate below only decides whether to RENDER the button,\n * so a dialog held open while the order ships in another tab used to write\n * `cancelled` straight onto a `fulfilled` order. Now that race comes back\n * as a 409 carrying the state that refused it.\n *\n * The messages follow the AGL-1784/1786 contract — say what happened:\n * a 409 is the guard refusing, not the cancel machinery failing; the\n * route's own 500 is a rolled-back transaction (nothing landed, retry is\n * safe and correct); an answer with no JSON word from the handler, or no\n * answer at all, is NOT KNOWN — never \"nothing happened\". A retry is safe\n * in every case because the route cancels once: a second cancel finds\n * `cancelled` and returns success without touching stock.\n */\n const handleCancel = useCallback(async () => {\n if (!order || !orderId) return\n const confirmed = await confirm({\n title: 'Cancel this order?',\n description:\n 'The buyer is NOT refunded automatically — refund first if they paid.',\n confirmationText: 'Cancel order',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setBusy(true)\n try {\n let response: Response\n try {\n response = await authorizedFetch(user, '/api/commerce/cancel-order', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, orderId }),\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar(\n 'The request did not complete, so it is NOT known whether the ' +\n 'order was canceled. Reopen the order to check — retrying is ' +\n 'safe, the server cancels once.',\n { variant: 'error', allowDuplicate: true },\n )\n return\n }\n const payload: any = await response.json().catch(() => ({}))\n if (!response.ok) {\n if (response.status === 409) {\n // The transition guard refusing: the order moved on (shipped,\n // refunded) while this dialog was open. The route's message names\n // the state that refused it, and nothing was written.\n enqueueSnackbar(\n payload?.error ?? 'This order can no longer be canceled',\n {\n variant: 'warning',\n allowDuplicate: true,\n },\n )\n } else if (payload?.error && response.status < 500) {\n // A refusal that wrote nothing — session, role, or an order that\n // is not there. The route's own word, verbatim.\n enqueueSnackbar(payload.error, {\n variant: 'error',\n allowDuplicate: true,\n })\n } else if (payload?.error) {\n // The route's 500 is a rolled-back transaction: nothing landed and\n // the order is still open. Only the handler's own JSON word\n // licenses saying so.\n enqueueSnackbar(\n `${payload.error} — nothing changed, the order is still open. Retrying is safe.`,\n { variant: 'error', allowDuplicate: true },\n )\n } else {\n // No JSON word from the handler (a gateway page, a proxy timeout):\n // whether the cancel landed is NOT known.\n enqueueSnackbar(\n `The cancel failed (${response.status}) and it is NOT known ` +\n 'whether it landed. Reopen the order to check — retrying is ' +\n 'safe, the server cancels once.',\n { variant: 'error', allowDuplicate: true },\n )\n }\n return\n }\n const units = Number(payload?.units ?? 0)\n enqueueSnackbar(\n payload?.alreadyCancelled\n ? 'Order was already canceled'\n : units > 0\n ? `Order canceled — ${units} ${units === 1 ? 'unit' : 'units'} returned to stock`\n : 'Order canceled',\n { variant: 'success', persist: false },\n )\n } finally {\n setBusy(false)\n }\n }, [order, orderId, user, hostId, confirm, enqueueSnackbar])\n\n /**\n * Idempotency key for ONE refund attempt (AGL-1696), the same shape the POS\n * register uses for a sale (AGL-1691).\n *\n * Minted lazily so a retry of this attempt — a lost response, a second\n * click, the admin reopening the dialog after a timeout — reuses it and the\n * server replays instead of sending the money again. Retired on a definitive\n * answer, which makes the NEXT refund a new attempt: two partial refunds of\n * the same amount on the same order are two real refunds, and keying on the\n * order (or the amount) would silently swallow the second.\n *\n * NOT retired on a network failure or a 5xx — that is precisely the window\n * the key exists to cover.\n */\n const attemptKey = useRef('')\n useEffect(() => {\n attemptKey.current = ''\n }, [orderId])\n\n /**\n * `lineItemIds` scopes the refund to named lines (AGL-2454).\n *\n * Without it a partial refund is an AMOUNT and nothing else, so the product\n * cannot know which goods came back and revokes nothing — a 99%-refunded\n * order kept its downloads, licence keys, gated pages and verified review.\n * Naming the lines is the only way that question gets an honest answer, and\n * the route derives the amount FROM the lines rather than trusting a figure\n * typed beside them.\n */\n const handleRefund = useCallback(async (lineItemIds?: number[]) => {\n if (!order || !orderId) return\n const lines = order.lineItems ?? []\n const scoped = (lineItemIds ?? []).length > 0\n // The SERVER's figure, not a second derivation of it. This was\n // the list value `unitAmountCents x quantity`, which on a discounted order\n // is more than the buyer paid — so the dialog quoted one number and the\n // route refunded another. One function answers both.\n const scopedCents = CommerceModel.orderLineRefundCents(\n order,\n lineItemIds ?? [],\n )\n const confirmed = await confirm({\n title: scoped ? 'Refund this line?' : 'Refund this order?',\n description:\n (scoped\n ? `Refunds ${usd(scopedCents)} for ${(lineItemIds ?? [])\n .map((index) => lines[index]?.name ?? `line ${index}`)\n .join(', ')} through Stripe, and withdraws that line's ` +\n 'downloads, license keys and gated content. A license key already ' +\n 'sent to the buyer is retired, not returned to your pool — they ' +\n 'still hold the string, so reissuing it would give two people one ' +\n 'working key.'\n : `Refunds ${usd(\n (order.totals?.totalCents ?? order.amountCents ?? 0) -\n (order.refundedCents ?? 0),\n )} to the buyer through Stripe.`) +\n // An open INQUIRY keeps this button live on purpose (AGL-1820):\n // Stripe names a full refund as the way to resolve one before it\n // escalates to a chargeback. Said here so the admin reads the refund\n // as the documented exit, not a risk taken against the badge.\n (CommerceModel.orderHasOpenDispute(order) &&\n !CommerceModel.orderDisputeBlocksRefund(order)\n ? ' An inquiry is open on this charge — a full refund resolves it' +\n ' before it can become a chargeback.'\n : ''),\n confirmationText: 'Refund',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n setBusy(true)\n // `randomUUID` needs a secure context, which the console always is, but\n // fall back rather than throw on a refund.\n if (!attemptKey.current) {\n attemptKey.current =\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(2)}`\n }\n try {\n const response = await authorizedFetch(user, '/api/commerce/refund', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Idempotency-Key': attemptKey.current,\n },\n body: JSON.stringify({\n hostId,\n orderId,\n ...(scoped ? { lineItemIds } : {}),\n }),\n })\n const payload = await response.json()\n // A definitive answer ends this attempt either way: the next refund is a\n // new one and must get a new key. A 5xx or a thrown fetch keeps the key,\n // so pressing Refund again dedupes rather than sends a second transfer.\n if (response.status < 500) attemptKey.current = ''\n if (!response.ok) {\n // A 409 is a guard REFUSING — the status machine, or the open-dispute\n // block (AGL-1809), whose body explains what to do instead — not the\n // refund machinery failing. The route wrote nothing, so it surfaces\n // verbatim as a warning, same as the cancel path's 409 (AGL-1818).\n enqueueSnackbar(payload?.error ?? 'Refund failed', {\n variant: response.status === 409 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n } else {\n enqueueSnackbar('Refund issued', { variant: 'success', persist: false })\n }\n } finally {\n setBusy(false)\n }\n }, [order, orderId, user, hostId, confirm, enqueueSnackbar])\n\n /**\n * Answer the restock question a reversal flagged (AGL-1806).\n *\n * The answer MOVES NO STOCK, which is AGL-1797's ledger argument and it is\n * binding: the products hub's \"Adjust stock\" is the one stock writer (it\n * writes the counts AND the `InventoryAdjustment` row the hub renders as\n * history), so \"Restocked\" here is clicked AFTER the merchant used it, and\n * \"No restock\" says the goods are not recoverable. Either answer only sets\n * the `resolution` triple `OrderRestockCheck` declares and says so on the\n * timeline.\n *\n * A TRANSACTION rather than the dialog's plain `write`, keyed on the\n * rendered `flaggedAtMs`, because an answer must land ONCE. The flag writer\n * re-asks an ANSWERED question after the next reversal, and the cancel\n * route (AGL-1808) answers an open one itself when it returns the stock —\n * so a stale dialog writing blind would either re-answer a settled question\n * or replace a brand-new one with a resolved copy of the old. The\n * transaction re-reads on the server (the web SDK will not run one from\n * cache — the products hub's `writeGuardedBySeed` refusal of unconfirmed\n * data, by other means) and refuses both cases with the truth: nothing was\n * written.\n */\n const handleRestockAnswer = useCallback(\n async (resolution: 'restocked' | 'dismissed') => {\n const check = order?.restockCheck\n if (!order || !orderId || !check || check.resolution) return\n setBusy(true)\n try {\n const reference = doc(firestore, 'hosts', hostId, 'orders', orderId)\n const verdict = await runTransaction(firestore, async (transaction) => {\n const snapshot = await transaction.get(reference)\n if (!snapshot.exists()) return 'gone'\n const current = CommerceModel.liftLegacyOrder(\n (snapshot.data() ?? {}) as never,\n )\n const fresh = current.restockCheck\n if (!fresh || fresh.resolution) return 'answered'\n if (fresh.flaggedAtMs !== check.flaggedAtMs) return 'changed'\n const resolvedAtMs = Date.now()\n const uid = String((user as any)?.uid ?? '')\n transaction.update(reference, {\n restockCheck: {\n ...fresh,\n resolution,\n resolvedAtMs,\n ...(uid ? { resolvedBy: uid } : {}),\n } satisfies CommerceModel.OrderRestockCheck,\n // The SERVER's timeline, not the dialog's — a note landed from\n // another tab must survive the append.\n timeline: CommerceModel.appendOrderEvent(\n current,\n 'restock-check',\n resolution === 'restocked'\n ? 'answered — restocked'\n : 'answered — no restock',\n resolvedAtMs,\n ),\n })\n return 'recorded'\n })\n if (verdict === 'recorded') {\n enqueueSnackbar(\n resolution === 'restocked'\n ? 'Recorded as restocked'\n : 'Recorded — no restock',\n { variant: 'success', persist: false },\n )\n } else if (verdict === 'answered') {\n // The cancel route, or another admin, got there first.\n enqueueSnackbar(\n 'This restock question was already answered — nothing changed.',\n { variant: 'info', persist: false },\n )\n } else if (verdict === 'changed') {\n // A later reversal re-asked; this dialog shows the OLD question.\n enqueueSnackbar(\n 'The restock question changed while this dialog was open — ' +\n 'nothing was written. Reopen the order to see the current one.',\n { variant: 'warning', allowDuplicate: true },\n )\n } else {\n enqueueSnackbar('This order no longer exists — nothing was written.', {\n variant: 'warning',\n allowDuplicate: true,\n })\n }\n } catch (error) {\n // A transaction is all-or-nothing, and a thrown one did not commit.\n console.error(error)\n enqueueSnackbar(\n 'The answer was not recorded — it needs a live connection and the ' +\n 'editor or admin role. Nothing changed; answering again is safe.',\n { variant: 'error', allowDuplicate: true },\n )\n } finally {\n setBusy(false)\n }\n },\n [order, orderId, firestore, hostId, user, enqueueSnackbar],\n )\n\n const handleNote = useCallback(async () => {\n if (!order || !note.trim()) return\n await write({\n timeline: CommerceModel.appendOrderEvent(order, 'note', note.trim().slice(0, 500)),\n })\n setNote('')\n }, [order, note, write])\n\n const handlePackingSlip = useCallback(() => {\n if (!order) return\n const win = window.open('', '_blank', 'width=600,height=800')\n if (!win) return\n // ESCAPED (AGL-2283). This is `document.write` into an `about:blank`\n // popup, which INHERITS the console's origin — and `order.shippingAddress`\n // is copied verbatim from Stripe's `shipping_details`, i.e. typed by the\n // SHOPPER. A name of `<img src=x onerror=…>` ran script against the\n // merchant's own authenticated session. React guards nothing here because\n // none of this is React. Line names and SKUs are merchant-authored and\n // lower severity, but they are the same construction and get the same\n // treatment rather than a case-by-case argument.\n const rows = (order.lineItems ?? [])\n .map(\n (line) =>\n `<tr><td>${escapeHtml(line.quantity)}×</td><td>${escapeHtml(\n line.name,\n )}${\n line.variantLabel ? ` — ${escapeHtml(line.variantLabel)}` : ''\n }</td><td>${escapeHtml(line.sku ?? '')}</td></tr>`,\n )\n .join('')\n const address = order.shippingAddress\n win.document.write(\n `<h2>Packing slip ${escapeHtml(\n CommerceModel.formatOrderNumber(order, orderId),\n )}</h2>` +\n (address\n ? `<p>${[address.name, address.line1, address.line2, `${address.city ?? ''} ${address.state ?? ''} ${address.postalCode ?? ''}`, address.country].filter(Boolean).map((part) => escapeHtml(part)).join('<br/>')}</p>`\n : '') +\n `<table border=\"0\" cellpadding=\"6\">${rows}</table>`,\n )\n win.document.close()\n // Print from the opener, not from an injected inline script (AGL-523) —\n // the popup inherits this document's CSP, where an un-nonced inline\n // script is blocked under the enforcing policy. Same reasoning as the POS\n // receipt.\n win.focus()\n win.print()\n }, [order, orderId])\n\n if (!order) return null\n const totals = order.totals\n const can = (to: CommerceModel.OrderStatus) => CommerceModel.canTransitionOrder(order.status, to)\n // A lost chargeback leaves `status: 'refunded'` (AGL-1787), so the status\n // chip alone tells the merchant they chose this. The badge is the correction.\n const dispute = CommerceModel.describeOrderDispute(order)\n // An early fraud warning or a Radar review on the payment (AGL-3360).\n const paymentRisk = describePaymentRisk(order.paymentRisk)\n const reversal = CommerceModel.splitOrderReversal(order)\n // The restock question a reversal flagged, while it is still open\n // (AGL-1806). Absent `resolution` IS the open state — the writer only ever\n // re-flags an answered check (AGL-1797).\n const restock =\n order.restockCheck && !order.restockCheck.resolution\n ? order.restockCheck\n : null\n // Whether the reversal NAMED the lines this question is about (AGL-2325).\n // AGL-2454 gave a refund a line selection, and `flagOrderRestock` now scopes\n // the question to it — so the \"we cannot tell which goods came back\" caveat\n // below is true of an amount-only reversal and false of this one. Asked of\n // the order's own withdrawal record rather than of a flag on the check, so a\n // prompt written before line indexes existed reads as the amount-only case\n // it was.\n const restockLinesNamed = Boolean(\n restock?.lines?.length &&\n restock.lines.every(\n (line) =>\n line.lineIndex != null &&\n CommerceModel.orderLineRefunded(order, line.lineIndex),\n ),\n )\n\n return (\n <Dialog open onClose={onClose} maxWidth=\"sm\" fullWidth>\n <DialogTitle>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <span>{`Order ${CommerceModel.formatOrderNumber(order, orderId)}`}</span>\n <Chip\n label={order.status.replace('_', ' ')}\n size=\"small\"\n color={STATUS_COLOR[order.status] ?? 'default'}\n variant=\"outlined\"\n />\n {dispute ? (\n <Tooltip title={dispute.detail}>\n <Chip\n label={dispute.label}\n size=\"small\"\n color={DISPUTE_COLOR[dispute.tone]}\n variant=\"filled\"\n />\n </Tooltip>\n ) : null}\n {paymentRisk ? (\n <Tooltip title={paymentRisk.detail}>\n <Chip\n label={paymentRisk.label}\n size=\"small\"\n color=\"warning\"\n variant=\"filled\"\n />\n </Tooltip>\n ) : null}\n {order.channel && order.channel !== 'online' ? (\n <Chip label={order.channel} size=\"small\" variant=\"outlined\" />\n ) : null}\n </Stack>\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {[order.customerName, order.customerEmail]\n .filter(Boolean)\n .join(' · ') || 'Guest buyer'}\n </Typography>\n {(order.lineItems ?? []).map((line, index) => {\n // WHAT THIS LINE IS STILL ENTITLED TO, per line (AGL-2454). A refund\n // used to be a number on the order and nothing more, so the merchant\n // could not see — and the product could not enforce — which goods had\n // come back.\n const withdrawn = CommerceModel.orderLineRefunded(order, index)\n return (\n <Stack key={index} direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Typography\n variant=\"body2\"\n sx={{\n flex: 1,\n ...(withdrawn ? { textDecoration: 'line-through' } : {}),\n }}\n color={withdrawn ? 'text.secondary' : 'text.primary'}\n >\n {`${line.quantity}× ${line.name}` +\n (line.variantLabel ? ` — ${line.variantLabel}` : '')}\n </Typography>\n {withdrawn ? (\n <Chip label=\"refunded\" size=\"small\" color=\"error\" variant=\"outlined\" />\n ) : can('refunded') &&\n !CommerceModel.orderDisputeBlocksRefund(order) ? (\n <Button\n size=\"small\"\n color=\"error\"\n disabled={busy}\n onClick={() => handleRefund([index])}\n >\n {'Refund line'}\n </Button>\n ) : null}\n <Typography variant=\"body2\">\n {usd(line.unitAmountCents * line.quantity)}\n </Typography>\n </Stack>\n )\n })}\n {CommerceModel.orderRefundState(order) !== 'none' ? (\n // The state, said in words (AGL-2454). \"Partially refunded, no lines\n // withdrawn\" is the honest reading of an amount-only refund, and it\n // is what tells a merchant their buyer still has the downloads.\n <Typography variant=\"caption\" color=\"error\">\n {CommerceModel.orderRefundSummary(order)}\n </Typography>\n ) : null}\n {totals ? (\n <>\n <Divider />\n {(\n [\n ['Items', totals.itemsCents],\n ['Shipping', totals.shippingCents],\n ['Tax', totals.taxCents],\n ['Discount', -totals.discountCents],\n ['Total', totals.totalCents],\n ] as Array<[string, number]>\n ).map(([label, cents]) => (\n <Stack key={label} direction=\"row\">\n <Typography\n variant=\"body2\"\n sx={{ flex: 1 }}\n color={label === 'Total' ? 'text.primary' : 'text.secondary'}\n >\n {label}\n </Typography>\n <Typography\n variant=\"body2\"\n sx={{ fontWeight: label === 'Total' ? 600 : 400 }}\n >\n {`${cents < 0 ? '-' : ''}${usd(Math.abs(cents))}`}\n </Typography>\n </Stack>\n ))}\n {/*\n HOW the tax on this order was computed (AGL-2451). The `Tax` row\n above states an amount and nothing about which machinery produced\n it, and a merchant reading one order could not tell Stripe Tax\n (computed against Aglyn's registrations) from their own configured\n rate. Those are different facts about whose registration the money\n is held under, and the order is where a merchant looks.\n\n Describes the mechanism and makes NO remittance determination —\n the constraint AGL-2440's report ships under. An order written\n before the stamp existed says so, rather than being rendered as\n \"no tax\": absent means NOT RECORDED, and `describeOrderTaxMode`\n is where that distinction is kept.\n */}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {CommerceModel.describeOrderTaxMode(order.taxMode)}\n </Typography>\n {/*\n Both figures live in `refundedCents` (AGL-1787), so a lost\n chargeback used to render as \"Refunded $62.00\" — the merchant's\n own decision, spelled the same as money taken from them. Split by\n door, and show BOTH when a partial refund and a chargeback each\n took a piece.\n */}\n {reversal.refundedCents ? (\n <Typography variant=\"caption\" color=\"error\">\n {`Refunded ${usd(reversal.refundedCents)}`}\n </Typography>\n ) : null}\n {reversal.chargedBackCents ? (\n <Typography variant=\"caption\" color=\"error\">\n {`Charged back ${usd(reversal.chargedBackCents)}`}\n </Typography>\n ) : null}\n </>\n ) : null}\n {restock ? (\n <>\n <Divider />\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Restock check'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${restock.units} ${\n restock.units === 1 ? 'unit' : 'units'\n } may need restocking after this ${\n restock.kind === 'chargeback' ? 'chargeback' : 'refund'\n }.` +\n // The chargeback default is NO, same as the timeline's\n // wording: the shopper kept the item and took the money.\n (restock.kind === 'chargeback'\n ? ' The shopper kept the goods unless they actually came back.'\n : '') +\n // On a partial the flagged units are the MOST it could be —\n // UNLESS the refund named its lines (AGL-2325), in which\n // case the question is scoped to exactly those and the\n // merchant is only being asked whether the goods came back.\n (restock.fullyReversed\n ? ''\n : restockLinesNamed\n ? ' Only part of the money came back: these are the lines withdrawn by this refund, so the units are theirs — only you know whether the goods came back.'\n : ' Only part of the money came back, so these units are an upper bound — only you know which goods returned.')}\n </Typography>\n {restock.lines.map((line, index) => (\n <Typography key={index} variant=\"caption\" color=\"text.secondary\">\n {`${line.quantity}× ${line.name ?? line.productId}` +\n (line.variantLabel ? ` — ${line.variantLabel}` : '')}\n </Typography>\n ))}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'If goods came back, put them on the shelf with \"Adjust ' +\n 'stock\" in the products hub first — these answers move no ' +\n 'stock, they only clear this question.'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy}\n onClick={() => handleRestockAnswer('restocked')}\n >\n {'Restocked'}\n </Button>\n <Button\n size=\"small\"\n disabled={busy}\n onClick={() => handleRestockAnswer('dismissed')}\n >\n {'No restock'}\n </Button>\n </Stack>\n </Stack>\n </>\n ) : null}\n <Divider />\n <Typography variant=\"subtitle2\">{'Timeline'}</Typography>\n {(order.timeline ?? [])\n .slice()\n .reverse()\n .map((event, index) => (\n <Typography key={index} variant=\"caption\" color=\"text.secondary\">\n {`${new Date(event.atMs).toLocaleString()} — ${event.event}` +\n (event.detail ? `: ${event.detail}` : '')}\n </Typography>\n ))}\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Add note\"\n value={note}\n onChange={(event) => setNote(event.target.value)}\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <Button size=\"small\" disabled={!note.trim()} onClick={handleNote}>\n {'Add'}\n </Button>\n </Stack>\n {tracking ? (\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Carrier\"\n value={tracking.carrier}\n onChange={(event) =>\n setTracking({ ...tracking, carrier: event.target.value })\n }\n size=\"small\"\n sx={{ width: 140 }}\n placeholder=\"UPS\"\n />\n <TextField\n label=\"Tracking number\"\n value={tracking.number}\n onChange={(event) =>\n setTracking({ ...tracking, number: event.target.value })\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n <Button\n size=\"small\"\n variant=\"contained\"\n color=\"primary\"\n disabled={busy}\n onClick={handleFulfill}\n >\n {'Fulfill'}\n </Button>\n </Stack>\n ) : null}\n {order.paymentLinkUrl && order.status === 'pending' ? (\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => {\n navigator.clipboard.writeText(String(order.paymentLinkUrl))\n enqueueSnackbar('Payment link copied', {\n variant: 'success',\n persist: false,\n })\n }}\n >\n {'Copy payment link'}\n </Button>\n ) : null}\n </DialogContent>\n <DialogActions>\n {customerCrmHref ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={customerCrmHref}\n >\n {'View customer in CRM'}\n </Button>\n ) : null}\n <Button onClick={handlePackingSlip}>{'Packing slip'}</Button>\n {can('cancelled') ? (\n <Button color=\"error\" disabled={busy} onClick={handleCancel}>\n {'Cancel order'}\n </Button>\n ) : null}\n {can('refunded') ? (\n // Disabled on `orderDisputeBlocksRefund`, NOT the badge's broader\n // `orderHasOpenDispute` (AGL-1820): a formal open dispute means the\n // bank already pulled the funds and the route answers 409\n // (AGL-1809), while an open INQUIRY shows the badge but must keep\n // this button live — a full refund is how an inquiry is resolved.\n CommerceModel.orderDisputeBlocksRefund(order) ? (\n <Tooltip\n title={\n 'A chargeback is open on this order, and refunding would not' +\n ' withdraw it — the bank has already taken the disputed' +\n ' amount, so a refund on top would pay the shopper twice.' +\n ' Respond to the dispute or accept it in the Stripe' +\n ' dashboard; refund any remainder once it settles.'\n }\n >\n {/* A disabled button fires no pointer events; the wrapper\n carries the hover for the tooltip. */}\n <span>\n <Button color=\"error\" disabled>\n {'Refund'}\n </Button>\n </span>\n </Tooltip>\n ) : (\n <Button\n color=\"error\"\n disabled={busy}\n onClick={() => handleRefund()}\n >\n {'Refund'}\n </Button>\n )\n ) : null}\n {(can('fulfilled') || can('partially_fulfilled')) && !tracking ? (\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setTracking({ carrier: '', number: '' })}\n >\n {'Fulfill…'}\n </Button>\n ) : null}\n {can('delivered') ? (\n <Button disabled={busy} onClick={handleDelivered}>\n {'Mark delivered'}\n </Button>\n ) : null}\n <Button onClick={onClose}>{'Close'}</Button>\n </DialogActions>\n </Dialog>\n )\n}\nOrderDetailDialog.displayName = 'OrderDetailDialog'\n\nexport default OrderDetailDialog\n"],"names":["CommerceModel","escapeHtml","crmContactByEmailHref","describePaymentRisk","AppLink","useConfirmationContext","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Stack","TextField","Tooltip","Typography","doc","runTransaction","updateDoc","useParams","useCallback","useEffect","useRef","useState","useFirestore","useUser","authorizedFetch","STATUS_COLOR","pending","paid","partially_fulfilled","fulfilled","delivered","cancelled","refunded","DISPUTE_COLOR","open","lost","won","settled","usd","cents","toFixed","OrderDetailDialog","props","order","restock","hostId","rawOrder","onClose","firestore","data","user","enqueueSnackbar","confirm","tracking","setTracking","note","setNote","busy","setBusy","liftLegacyOrder","orderId","$id","params","customerCrmHref","orgSlug","host","customerEmail","String","write","patch","transition","to","extra","copy","response","method","headers","body","JSON","stringify","error","console","subject","variant","allowDuplicate","payload","json","catch","ok","status","action","already","done","persist","handleFulfill","carrier","number","trackingNumber","handleDelivered","handleCancel","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","units","Number","alreadyCancelled","attemptKey","current","handleRefund","lineItemIds","lines","lineItems","scoped","length","scopedCents","orderLineRefundCents","map","index","name","join","totals","totalCents","amountCents","refundedCents","orderHasOpenDispute","orderDisputeBlocksRefund","globalThis","crypto","randomUUID","Date","now","Math","random","toString","slice","handleRestockAnswer","resolution","check","restockCheck","reference","verdict","transaction","snapshot","get","exists","fresh","flaggedAtMs","resolvedAtMs","uid","update","resolvedBy","timeline","appendOrderEvent","handleNote","trim","handlePackingSlip","address","win","window","rows","line","quantity","variantLabel","sku","shippingAddress","document","formatOrderNumber","line1","line2","city","state","postalCode","country","filter","Boolean","part","close","focus","print","can","canTransitionOrder","dispute","describeOrderDispute","paymentRisk","reversal","splitOrderReversal","restockLinesNamed","every","lineIndex","orderLineRefunded","maxWidth","fullWidth","direction","spacing","sx","alignItems","span","label","replace","size","detail","tone","channel","display","flexDirection","gap","customerName","withdrawn","flex","textDecoration","disabled","onClick","unitAmountCents","orderRefundState","orderRefundSummary","itemsCents","shippingCents","taxCents","discountCents","fontWeight","abs","describeOrderTaxMode","taxMode","chargedBackCents","kind","fullyReversed","productId","reverse","event","atMs","toLocaleString","value","onChange","target","width","placeholder","paymentLinkUrl","alignSelf","navigator","clipboard","writeText","component","componentVariant","nativeButton","href","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,UAAU,QAAQ,6BAAyB;AACpD,4EAA4E;AAC5E,uEAAuE;AACvE,oEAAoE;AACpE,0EAA0E;AAC1E,yDAAyD;AACzD,SAASC,qBAAqB,QAAQ,eAAc;AACpD,SAASC,mBAAmB,QAAQ,sCAAqC;AACzE,SAASC,OAAO,EAAEC,sBAAsB,QAAQ,uBAAsB;AACtE,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,OAAO,EACPC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,cAAc,EAAEC,SAAS,QAAQ,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S;gCACTU,SAAS;4BACX;wBACF;kCAEC;yBAED;;;0BAEN,MAACvF;;oBACEyD,gCACC,KAAC5D;wBACCkP,WAAWrP;uBACN;wBAAEsP,kBAAkB;wBAASC,cAAc;oBAAM;wBACtDC,MAAMzL;kCAEL;0BAED;kCACJ,KAAC5D;wBAAOoN,SAASxD;kCAAoB;;oBACpCwB,IAAI,6BACH,KAACpL;wBAAOsG,OAAM;wBAAQ6G,UAAU7J;wBAAM8J,SAASpH;kCAC5C;yBAED;oBACHoF,IAAI,cACH,kEAAkE;oBAClE,oEAAoE;oBACpE,0DAA0D;oBAC1D,kEAAkE;oBAClE,kEAAkE;oBAClE3L,cAAcqI,wBAAwB,CAACtF,uBACrC,KAAC/B;wBACCyF,OACE,gEACA,2DACA,6DACA,uDACA;kCAKF,cAAA,KAACmG;sCACC,cAAA,KAACrM;gCAAOsG,OAAM;gCAAQ6G,QAAQ;0CAC3B;;;uCAKP,KAACnN;wBACCsG,OAAM;wBACN6G,UAAU7J;wBACV8J,SAAS,IAAMvG;kCAEd;yBAGH;oBACFuE,CAAAA,IAAI,gBAAgBA,IAAI,sBAAqB,KAAM,CAAClI,yBACpD,KAAClD;wBACCgF,SAAQ;wBACRsB,OAAM;wBACN8G,SAAS,IAAMjK,YAAY;gCAAEyC,SAAS;gCAAIC,QAAQ;4BAAG;kCAEpD;yBAED;oBACHuF,IAAI,6BACH,KAACpL;wBAAOmN,UAAU7J;wBAAM8J,SAASrH;kCAC9B;yBAED;kCACJ,KAAC/F;wBAAOoN,SAASxK;kCAAU;;;;;;AAInC;AACAN,kBAAkBgN,WAAW,GAAG;AAEhC,eAAehN,kBAAiB"}
@@ -1,4 +1,18 @@
1
1
  import type { ConsolePluginPageProps } from '@aglyn/aglyn';
2
+ /**
3
+ * The products hub's query (AGL-3321), narrowed to what the till may sell:
4
+ * live products (`deletedAt == null`, the list's scope), `status == active`,
5
+ * and any typed word as the search on `nameTokens` — or, for a scan, the
6
+ * whole scanned code as a SKU or barcode clause. Every shape is one the hub's
7
+ * composites already serve.
8
+ */
9
+ export declare function posProductPlan(options: {
10
+ search?: string;
11
+ code?: {
12
+ field: 'barcodes' | 'skus';
13
+ value: string;
14
+ };
15
+ }): import("@aglyn/shared-ui-jsx/const/list-query-plan").ListQueryPlan;
2
16
  /**
3
17
  * POS register (AGL-312): touch-first full-screen sale surface —
4
18
  * product grid with search/barcode (keyboard-wedge scanners type into
@@ -18,19 +18,58 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
19
19
  import * as Aglyn from "@aglyn/aglyn";
20
20
  import * as CommerceModel from "../../model/index.js";
21
- import { PRODUCT_LIST_FILTER_FIELDS } from "../../constants/product-filters.js";
21
+ import { PRODUCT_LIST_BASE, PRODUCT_LIST_QUERY } from "../../constants/product-list-query.js";
22
22
  import { escapeHtml } from "../../utils/escape-html.js";
23
23
  import { NextPageTitle } from "@aglyn/shared-ui-next/contexts/next-page-title-provider";
24
24
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
25
+ import { ListQueryNotices } from "@aglyn/shared-ui-jsx/components/list-query-notices.component";
26
+ import { planListQuery } from "@aglyn/shared-ui-jsx/const/list-query-plan";
27
+ import { nameSearchNormalizers } from "@aglyn/aglyn/app-utils/name-search";
25
28
  import { Alert, Box, Button, Card, CardActionArea, Chip, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from "@mui/material";
26
29
  import { QRCodeSVG } from "qrcode.react";
27
- import { collection, documentId, getDocs, limit, orderBy, query, where } from "firebase/firestore";
30
+ import { collection, getDocs, limit, query, where } from "firebase/firestore";
28
31
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
29
32
  import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
30
- import { listFilterConstraints, useFirestoreCollection } from "@aglyn/tenant-feature-instance";
33
+ import { useFirestoreCollection } from "@aglyn/tenant-feature-instance";
34
+ import { listQueryConstraints } from "@aglyn/tenant-feature-instance/hooks/use-list-query";
31
35
  import { useOrgPlan } from "@aglyn/tenant-feature-instance";
32
36
  import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
33
37
  const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
38
+ /** The till sells active products only; every read of the catalog asks it. */ const SELLABLE = {
39
+ field: 'status',
40
+ op: 'equals',
41
+ value: 'active'
42
+ };
43
+ /**
44
+ * How many products the till's grid shows. The grid is a picker, not the
45
+ * catalog: typing narrows it on the query, so a name reaches every product.
46
+ */ const POS_GRID_CEILING = 500;
47
+ /**
48
+ * The products hub's query (AGL-3321), narrowed to what the till may sell:
49
+ * live products (`deletedAt == null`, the list's scope), `status == active`,
50
+ * and any typed word as the search on `nameTokens` — or, for a scan, the
51
+ * whole scanned code as a SKU or barcode clause. Every shape is one the hub's
52
+ * composites already serve.
53
+ */ export function posProductPlan(options) {
54
+ var _options_search;
55
+ const typed = (_options_search = options.search) == null ? void 0 : _options_search.trim();
56
+ return planListQuery(PRODUCT_LIST_QUERY, {
57
+ base: PRODUCT_LIST_BASE,
58
+ clauses: [
59
+ SELLABLE,
60
+ ...options.code ? [
61
+ {
62
+ field: options.code.field,
63
+ op: 'contains',
64
+ value: options.code.value
65
+ }
66
+ ] : []
67
+ ],
68
+ search: typed ? [
69
+ typed
70
+ ] : []
71
+ }, nameSearchNormalizers);
72
+ }
34
73
  /**
35
74
  * POS register (AGL-312): touch-first full-screen sale surface —
36
75
  * product grid with search/barcode (keyboard-wedge scanners type into
@@ -55,41 +94,26 @@ const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
55
94
  const { data: user } = useUser();
56
95
  const { enqueueSnackbar } = useSnackbar();
57
96
  const [search, setSearch] = useState('');
58
- const { data: productDocs } = useFirestoreCollection(()=>{
59
- /*
60
- * The till's grid, narrowed by the QUERY rather than by the rows it
61
- * happened to fetch (AGL-2501, AGL-2292).
62
- *
63
- * `limit(500)` with no `orderBy` is document-id order over
64
- * `createResourceUid()` — an arbitrary five hundred. Both filters then
65
- * ran over that sample: `status === 'active'` below, and the search.
66
- * The status one is the quieter of the two, because a catalog of five
67
- * hundred archived products and a hundred live ones would fill the
68
- * window with the archived and leave the register showing almost
69
- * nothing to sell.
70
- *
71
- * Status moves into the query, so the window is five hundred SELLABLE
72
- * products; the typed search moves in beside it, so a name reaches the
73
- * whole catalog. The scan does not come through here at all — see
74
- * `handleSearchEnter`, which is a lookup rather than a filter.
75
- */ const typed = listFilterConstraints(PRODUCT_LIST_FILTER_FIELDS, search.trim() ? {
76
- field: 'name',
77
- op: 'contains',
78
- value: search.trim()
79
- } : null, // Status is already an equality on this query, so the translator must
80
- // not add an ordering that would have to be the first `orderBy`.
81
- {
82
- fixedOrderBy: 'nameLower'
83
- });
84
- return query(collection(firestore, 'hosts', hostId, 'products'), where('status', '==', 'active'), ...typed != null ? typed : [], ...typed ? [
85
- orderBy('nameLower')
86
- ] : [
87
- orderBy(documentId())
88
- ], limit(500));
89
- }, [
97
+ const gridPlan = useMemo(()=>posProductPlan({
98
+ search
99
+ }), [
100
+ search
101
+ ]);
102
+ const { data: productDocs } = useFirestoreCollection(/*
103
+ * The till's grid, narrowed by the QUERY rather than by the rows it
104
+ * happened to fetch (AGL-2501, AGL-2292, AGL-3321).
105
+ *
106
+ * `limit(500)` with no `orderBy` was document-id order over
107
+ * `createResourceUid()` — an arbitrary five hundred, filtered afterwards
108
+ * for status, deletion and the typed search. All three are the query's
109
+ * now (`posProductPlan`), so the window is the first five hundred
110
+ * SELLABLE products by name and a typed name reaches the whole catalog.
111
+ * The scan does not come through here at all — see `handleSearchEnter`,
112
+ * which is a lookup rather than a filter.
113
+ */ ()=>query(collection(firestore, 'hosts', hostId, 'products'), ...listQueryConstraints(gridPlan), limit(POS_GRID_CEILING)), [
90
114
  firestore,
91
115
  hostId,
92
- search
116
+ gridPlan
93
117
  ], {
94
118
  idField: '$id'
95
119
  });
@@ -125,13 +149,18 @@ const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
125
149
  const registerCap = Aglyn.checkHostRegisterQuota(org, hostId, registers.length).limit;
126
150
  const withinCap = CommerceModel.registersWithinCap(registers, registerCap);
127
151
  const usableRegisters = planReady ? registers.filter((r)=>withinCap.has(r.$id)) : [];
128
- const { data: reservationDocs } = useFirestoreCollection(()=>query(collection(firestore, 'hosts', hostId, 'reservations'), limit(100)), [
152
+ /*
153
+ * The stays a sale can be charged to, asked for BY STATUS (AGL-3321). This
154
+ * read the first hundred reservations in document-id order and kept the
155
+ * checked-in ones, so a guest in the house was missing from the folio
156
+ * picker whenever a hundred other bookings sorted before theirs.
157
+ */ const { data: reservationDocs } = useFirestoreCollection(()=>query(collection(firestore, 'hosts', hostId, 'reservations'), where('status', '==', 'checked_in'), limit(100)), [
129
158
  firestore,
130
159
  hostId
131
160
  ], {
132
161
  idField: '$id'
133
162
  });
134
- const openStays = (reservationDocs != null ? reservationDocs : []).filter((reservation)=>reservation.status === 'checked_in');
163
+ const openStays = reservationDocs != null ? reservationDocs : [];
135
164
  const [lines, setLines] = useState([]);
136
165
  const [discountPct, setDiscountPct] = useState(0);
137
166
  const [customerEmail, setCustomerEmail] = useState('');
@@ -194,11 +223,10 @@ const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
194
223
  discountPct
195
224
  ]);
196
225
  const [lastReceipt, setLastReceipt] = useState(null);
197
- const products = useMemo(()=>[
226
+ const products = useMemo(()=>// Status, deletion and the search are all the query's (`posProductPlan`).
227
+ [
198
228
  ...productDocs != null ? productDocs : []
199
- ]// `status` is now the query's; `deletedAt` stays here because
200
- // Firestore cannot ask for documents that LACK a field.
201
- .filter((product)=>!product.deletedAt).map((product)=>_extends({}, CommerceModel.liftLegacyProduct(product), {
229
+ ].map((product)=>_extends({}, CommerceModel.liftLegacyProduct(product), {
202
230
  $id: product.$id
203
231
  })), [
204
232
  productDocs
@@ -296,11 +324,15 @@ const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
296
324
  * had not fired — the cashier's only signal was that nothing happened.
297
325
  */ const handleSearchEnter = useCallback(async ()=>{
298
326
  var _product_variants_find;
299
- var _hit_data;
300
327
  const needle = search.trim().toLowerCase();
301
328
  if (!needle) return;
302
329
  const lookup = async (field)=>{
303
- const found = await getDocs(query(collection(firestore, 'hosts', hostId, 'products'), where('status', '==', 'active'), where(field, 'array-contains', needle), limit(1)));
330
+ const found = await getDocs(query(collection(firestore, 'hosts', hostId, 'products'), ...listQueryConstraints(posProductPlan({
331
+ code: {
332
+ field,
333
+ value: needle
334
+ }
335
+ })), limit(1)));
304
336
  return found.docs[0];
305
337
  };
306
338
  let hit;
@@ -314,7 +346,7 @@ const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
314
346
  persist: false
315
347
  });
316
348
  }
317
- if (!hit || ((_hit_data = hit.data()) == null ? void 0 : _hit_data['deletedAt'])) {
349
+ if (!hit) {
318
350
  return void enqueueSnackbar(`No product matches “${search.trim()}”`, {
319
351
  variant: 'warning',
320
352
  persist: false
@@ -494,6 +526,15 @@ const usd = (cents)=>`$${(cents / 100).toFixed(2)}`;
494
526
  mb: 2
495
527
  }
496
528
  }),
529
+ /*#__PURE__*/ _jsx(Box, {
530
+ sx: {
531
+ mb: gridPlan.notices.length ? 2 : 0
532
+ },
533
+ children: /*#__PURE__*/ _jsx(ListQueryNotices, {
534
+ refused: [],
535
+ notices: gridPlan.notices
536
+ })
537
+ }),
497
538
  /*#__PURE__*/ _jsx(Box, {
498
539
  sx: {
499
540
  display: 'grid',