@aglyn/plugins-commerce 1.0.0-beta.232 → 1.0.0-beta.234

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 (228) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/cart-extras.d.ts +6 -0
  3. package/src/lib/components/cart-extras.js +4 -1
  4. package/src/lib/components/cart-extras.js.map +1 -1
  5. package/src/lib/components/cart-fulfillment.d.ts +117 -0
  6. package/src/lib/components/cart-fulfillment.js +367 -0
  7. package/src/lib/components/cart-fulfillment.js.map +1 -0
  8. package/src/lib/components/cart.js +52 -10
  9. package/src/lib/components/cart.js.map +1 -1
  10. package/src/lib/components/commerce-console-page.js +42 -1
  11. package/src/lib/components/commerce-console-page.js.map +1 -1
  12. package/src/lib/components/console/host-orders-card.component.js +38 -10
  13. package/src/lib/components/console/host-orders-card.component.js.map +1 -1
  14. package/src/lib/components/console/local-delivery-settings-card.component.d.ts +37 -0
  15. package/src/lib/components/console/local-delivery-settings-card.component.js +542 -0
  16. package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -0
  17. package/src/lib/components/console/locations-card.component.js +177 -3
  18. package/src/lib/components/console/locations-card.component.js.map +1 -1
  19. package/src/lib/components/console/order-detail-dialog.component.js +10 -0
  20. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  21. package/src/lib/components/console/order-local-fulfillment-panel.component.d.ts +44 -0
  22. package/src/lib/components/console/order-local-fulfillment-panel.component.js +265 -0
  23. package/src/lib/components/console/order-local-fulfillment-panel.component.js.map +1 -0
  24. package/src/lib/components/console/order-offline-notice.component.d.ts +12 -0
  25. package/src/lib/components/console/order-offline-notice.component.js +53 -0
  26. package/src/lib/components/console/order-offline-notice.component.js.map +1 -0
  27. package/src/lib/components/console/pickup-delivery-queue-card.component.d.ts +35 -0
  28. package/src/lib/components/console/pickup-delivery-queue-card.component.js +222 -0
  29. package/src/lib/components/console/pickup-delivery-queue-card.component.js.map +1 -0
  30. package/src/lib/components/console/pos/pos-api.d.ts +24 -1
  31. package/src/lib/components/console/pos/pos-api.js +13 -0
  32. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  33. package/src/lib/components/console/pos/pos-item-dialog.component.d.ts +12 -0
  34. package/src/lib/components/console/pos/pos-item-dialog.component.js +10 -8
  35. package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
  36. package/src/lib/components/console/pos/pos-kiosk-queue.component.d.ts +22 -0
  37. package/src/lib/components/console/pos/pos-kiosk-queue.component.js +168 -0
  38. package/src/lib/components/console/pos/pos-kiosk-queue.component.js.map +1 -0
  39. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +18 -0
  40. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +116 -1
  41. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  42. package/src/lib/components/console/pos/pos-tender-panel.component.d.ts +8 -0
  43. package/src/lib/components/console/pos/pos-tender-panel.component.js +77 -18
  44. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  45. package/src/lib/components/console/pos/use-pos-display.d.ts +5 -2
  46. package/src/lib/components/console/pos/use-pos-display.js +3 -2
  47. package/src/lib/components/console/pos/use-pos-display.js.map +1 -1
  48. package/src/lib/components/console/pos-devices-card.component.js +2 -2
  49. package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
  50. package/src/lib/components/console/pos-display/pairing-screen.d.ts +5 -2
  51. package/src/lib/components/console/pos-display/pairing-screen.js +7 -5
  52. package/src/lib/components/console/pos-display/pairing-screen.js.map +1 -1
  53. package/src/lib/components/console/pos-display/pos-display-api.d.ts +7 -1
  54. package/src/lib/components/console/pos-display/pos-display-api.js +7 -2
  55. package/src/lib/components/console/pos-display/pos-display-api.js.map +1 -1
  56. package/src/lib/components/console/pos-kiosk/kiosk-checkout.d.ts +41 -0
  57. package/src/lib/components/console/pos-kiosk/kiosk-checkout.js +275 -0
  58. package/src/lib/components/console/pos-kiosk/kiosk-checkout.js.map +1 -0
  59. package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +32 -0
  60. package/src/lib/components/console/pos-kiosk/kiosk-menu.js +344 -0
  61. package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -0
  62. package/src/lib/components/console/pos-kiosk/kiosk-staff.d.ts +12 -0
  63. package/src/lib/components/console/pos-kiosk/kiosk-staff.js +257 -0
  64. package/src/lib/components/console/pos-kiosk/kiosk-staff.js.map +1 -0
  65. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +114 -0
  66. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +189 -0
  67. package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -0
  68. package/src/lib/components/console/pos-kiosk/use-kiosk-idle.d.ts +16 -0
  69. package/src/lib/components/console/pos-kiosk/use-kiosk-idle.js +80 -0
  70. package/src/lib/components/console/pos-kiosk/use-kiosk-idle.js.map +1 -0
  71. package/src/lib/components/console/pos-kiosk-page.component.d.ts +28 -0
  72. package/src/lib/components/console/pos-kiosk-page.component.js +791 -0
  73. package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -0
  74. package/src/lib/components/console/pos-offline/pos-offline-api.d.ts +44 -0
  75. package/src/lib/components/console/pos-offline/pos-offline-api.js +69 -0
  76. package/src/lib/components/console/pos-offline/pos-offline-api.js.map +1 -0
  77. package/src/lib/components/console/pos-offline/pos-offline-banner.component.d.ts +7 -0
  78. package/src/lib/components/console/pos-offline/pos-offline-banner.component.js +135 -0
  79. package/src/lib/components/console/pos-offline/pos-offline-banner.component.js.map +1 -0
  80. package/src/lib/components/console/pos-offline/pos-offline-checkout.component.d.ts +32 -0
  81. package/src/lib/components/console/pos-offline/pos-offline-checkout.component.js +287 -0
  82. package/src/lib/components/console/pos-offline/pos-offline-checkout.component.js.map +1 -0
  83. package/src/lib/components/console/pos-offline/pos-offline-store.d.ts +63 -0
  84. package/src/lib/components/console/pos-offline/pos-offline-store.js +145 -0
  85. package/src/lib/components/console/pos-offline/pos-offline-store.js.map +1 -0
  86. package/src/lib/components/console/pos-offline/register-offline.d.ts +24 -0
  87. package/src/lib/components/console/pos-offline/register-offline.js +24 -0
  88. package/src/lib/components/console/pos-offline/register-offline.js.map +1 -0
  89. package/src/lib/components/console/pos-offline/use-pos-offline.d.ts +85 -0
  90. package/src/lib/components/console/pos-offline/use-pos-offline.js +542 -0
  91. package/src/lib/components/console/pos-offline/use-pos-offline.js.map +1 -0
  92. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js +72 -17
  93. package/src/lib/components/console/pos-ops/pos-shift-history-card.component.js.map +1 -1
  94. package/src/lib/components/console/pos-page.component.js +174 -27
  95. package/src/lib/components/console/pos-page.component.js.map +1 -1
  96. package/src/lib/components/console/products-hub-card.component.js +35 -10
  97. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  98. package/src/lib/components/console/shipping-settings-card.component.js +1 -1
  99. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  100. package/src/lib/components/console/stock-movements-card.component.js +48 -16
  101. package/src/lib/components/console/stock-movements-card.component.js.map +1 -1
  102. package/src/lib/components/console/store-zones.d.ts +8 -1
  103. package/src/lib/components/console/store-zones.js +11 -1
  104. package/src/lib/components/console/store-zones.js.map +1 -1
  105. package/src/lib/components/order-status.js +66 -0
  106. package/src/lib/components/order-status.js.map +1 -1
  107. package/src/lib/components/product-detail.js +42 -15
  108. package/src/lib/components/product-detail.js.map +1 -1
  109. package/src/lib/constants/local-fulfillment-list-query.d.ts +48 -0
  110. package/src/lib/constants/local-fulfillment-list-query.js +84 -0
  111. package/src/lib/constants/local-fulfillment-list-query.js.map +1 -0
  112. package/src/lib/constants/orders-list-query.d.ts +7 -2
  113. package/src/lib/constants/orders-list-query.js +89 -8
  114. package/src/lib/constants/orders-list-query.js.map +1 -1
  115. package/src/lib/constants/pos-shift-list-query.d.ts +22 -0
  116. package/src/lib/constants/pos-shift-list-query.js +115 -0
  117. package/src/lib/constants/pos-shift-list-query.js.map +1 -0
  118. package/src/lib/constants/product-list-query.d.ts +6 -1
  119. package/src/lib/constants/product-list-query.js +77 -8
  120. package/src/lib/constants/product-list-query.js.map +1 -1
  121. package/src/lib/constants/stock-movement-query.d.ts +3 -2
  122. package/src/lib/constants/stock-movement-query.js +52 -8
  123. package/src/lib/constants/stock-movement-query.js.map +1 -1
  124. package/src/lib/model/buyer-notifications.d.ts +5 -3
  125. package/src/lib/model/buyer-notifications.js +25 -4
  126. package/src/lib/model/buyer-notifications.js.map +1 -1
  127. package/src/lib/model/commerce-orders.d.ts +59 -0
  128. package/src/lib/model/commerce-orders.js.map +1 -1
  129. package/src/lib/model/commerce-pos-kiosk.d.ts +175 -0
  130. package/src/lib/model/commerce-pos-kiosk.js +147 -0
  131. package/src/lib/model/commerce-pos-kiosk.js.map +1 -0
  132. package/src/lib/model/commerce-pos-offline.d.ts +234 -0
  133. package/src/lib/model/commerce-pos-offline.js +301 -0
  134. package/src/lib/model/commerce-pos-offline.js.map +1 -0
  135. package/src/lib/model/commerce-pos-ops.d.ts +16 -6
  136. package/src/lib/model/commerce-pos-ops.js +12 -4
  137. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  138. package/src/lib/model/commerce-pos.d.ts +13 -1
  139. package/src/lib/model/commerce-pos.js +5 -4
  140. package/src/lib/model/commerce-pos.js.map +1 -1
  141. package/src/lib/model/commerce-stock-holds.d.ts +24 -3
  142. package/src/lib/model/commerce-stock-holds.js +26 -8
  143. package/src/lib/model/commerce-stock-holds.js.map +1 -1
  144. package/src/lib/model/commerce.d.ts +3 -0
  145. package/src/lib/model/commerce.js.map +1 -1
  146. package/src/lib/model/index.d.ts +4 -0
  147. package/src/lib/model/index.js +4 -0
  148. package/src/lib/model/index.js.map +1 -1
  149. package/src/lib/model/local-fulfillment-settings.d.ts +178 -0
  150. package/src/lib/model/local-fulfillment-settings.js +361 -0
  151. package/src/lib/model/local-fulfillment-settings.js.map +1 -0
  152. package/src/lib/model/order-list-fields.d.ts +10 -1
  153. package/src/lib/model/order-list-fields.js +1 -0
  154. package/src/lib/model/order-list-fields.js.map +1 -1
  155. package/src/lib/model/order-local-fulfillment.d.ts +131 -0
  156. package/src/lib/model/order-local-fulfillment.js +125 -0
  157. package/src/lib/model/order-local-fulfillment.js.map +1 -0
  158. package/src/lib/model/order-shipping-export.js +4 -0
  159. package/src/lib/model/order-shipping-export.js.map +1 -1
  160. package/src/lib/model/order-status-view.d.ts +20 -1
  161. package/src/lib/model/order-status-view.js +60 -6
  162. package/src/lib/model/order-status-view.js.map +1 -1
  163. package/src/lib/plugin-config.js +6 -2
  164. package/src/lib/plugin-config.js.map +1 -1
  165. package/src/lib/plugin.js +8 -0
  166. package/src/lib/plugin.js.map +1 -1
  167. package/src/lib/pos-kiosk-config.d.ts +26 -0
  168. package/src/lib/pos-kiosk-config.js +59 -0
  169. package/src/lib/pos-kiosk-config.js.map +1 -0
  170. package/src/lib/server/api-v1/openapi.js +8 -0
  171. package/src/lib/server/api-v1/openapi.js.map +1 -1
  172. package/src/lib/server/api-v1/order-view.d.ts +19 -0
  173. package/src/lib/server/api-v1/order-view.js +35 -0
  174. package/src/lib/server/api-v1/order-view.js.map +1 -1
  175. package/src/lib/server/billing-webhook.js +238 -87
  176. package/src/lib/server/billing-webhook.js.map +1 -1
  177. package/src/lib/server/cart-checkout.d.ts +2 -0
  178. package/src/lib/server/cart-checkout.js +173 -13
  179. package/src/lib/server/cart-checkout.js.map +1 -1
  180. package/src/lib/server/checkout-extras.js +18 -4
  181. package/src/lib/server/checkout-extras.js.map +1 -1
  182. package/src/lib/server/checkout.js +71 -14
  183. package/src/lib/server/checkout.js.map +1 -1
  184. package/src/lib/server/local-fulfillment-status.d.ts +86 -0
  185. package/src/lib/server/local-fulfillment-status.js +379 -0
  186. package/src/lib/server/local-fulfillment-status.js.map +1 -0
  187. package/src/lib/server/local-fulfillment.d.ts +190 -0
  188. package/src/lib/server/local-fulfillment.js +580 -0
  189. package/src/lib/server/local-fulfillment.js.map +1 -0
  190. package/src/lib/server/membership-register.js +3 -1
  191. package/src/lib/server/membership-register.js.map +1 -1
  192. package/src/lib/server/order-notifications.js +61 -0
  193. package/src/lib/server/order-notifications.js.map +1 -1
  194. package/src/lib/server/pos-display.d.ts +27 -1
  195. package/src/lib/server/pos-display.js +50 -9
  196. package/src/lib/server/pos-display.js.map +1 -1
  197. package/src/lib/server/pos-kiosk-principal.d.ts +29 -0
  198. package/src/lib/server/pos-kiosk-principal.js +42 -0
  199. package/src/lib/server/pos-kiosk-principal.js.map +1 -0
  200. package/src/lib/server/pos-kiosk.d.ts +54 -0
  201. package/src/lib/server/pos-kiosk.js +972 -0
  202. package/src/lib/server/pos-kiosk.js.map +1 -0
  203. package/src/lib/server/pos-offline-sync.d.ts +85 -0
  204. package/src/lib/server/pos-offline-sync.js +765 -0
  205. package/src/lib/server/pos-offline-sync.js.map +1 -0
  206. package/src/lib/server/pos-order.js +22 -4
  207. package/src/lib/server/pos-order.js.map +1 -1
  208. package/src/lib/server/pos-payment.d.ts +6 -0
  209. package/src/lib/server/pos-payment.js +225 -6
  210. package/src/lib/server/pos-payment.js.map +1 -1
  211. package/src/lib/server/pos-print.js +5 -0
  212. package/src/lib/server/pos-print.js.map +1 -1
  213. package/src/lib/server/pos-return.js +27 -0
  214. package/src/lib/server/pos-return.js.map +1 -1
  215. package/src/lib/server/pos-sale.d.ts +6 -0
  216. package/src/lib/server/pos-sale.js +2 -0
  217. package/src/lib/server/pos-sale.js.map +1 -1
  218. package/src/lib/server/pos-shift.js +8 -1
  219. package/src/lib/server/pos-shift.js.map +1 -1
  220. package/src/lib/server/refund.js +3 -0
  221. package/src/lib/server/refund.js.map +1 -1
  222. package/src/lib/server/stock-hold.d.ts +9 -1
  223. package/src/lib/server/stock-hold.js +15 -7
  224. package/src/lib/server/stock-hold.js.map +1 -1
  225. package/src/lib/server.js +16 -0
  226. package/src/lib/server.js.map +1 -1
  227. package/src/lib/tenant-emails.js +161 -0
  228. package/src/lib/tenant-emails.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 { pluginRecordByEmailHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\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 { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n type ConsoleWidgetSlotRenderer,\n useConsoleWidgetSlot,\n} from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport {\n consoleOrderZoneOrder,\n FulfillItemsPanel,\n FulfillmentList,\n type FulfillItemsSubmission,\n toZoneFulfillment,\n} from './order-fulfillment-panel.component'\nimport {\n type ConsoleFulfillmentRequest,\n type ConsoleOrderZoneFulfillment,\n ORDER_DETAIL_ZONE,\n ORDER_FULFILLMENT_ZONE,\n} from './order-zones'\nimport { OrderInvoiceButton } from './order-invoice.component'\nimport { OrderReceiptResend } from './order-receipt-resend.component'\nimport { OrderReturns } from './order-returns.component'\nimport { PosReceiptActions } from './pos-ops/pos-receipt-actions.component'\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 * A zone hosted in the dialog, drawn again only when what it is handed\n * changes — the product editor's reasoning (AGL-3423): the shell's renderer\n * is not memoized, and the dialog redraws on every keystroke in its fields.\n */\nconst HostedZone = memo(function HostedZone(\n props: { renderer: ConsoleWidgetSlotRenderer; slot: string } & Record<string, unknown>,\n) {\n const { renderer: Renderer, ...zone } = props\n return <Renderer {...zone} />\n})\n\n/** A fresh key for one attempt at a write the route dedupes on. */\nconst newAttemptKey = () =>\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(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 [fulfilling, setFulfilling] = useState(false)\n const WidgetSlot = useConsoleWidgetSlot()\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 * at the address the plugin that keeps contacts publishes; where none\n * does, there is no link. A guest checkout with no address updated\n * nobody, so there is no link either. Built from the route params already\n * in the URL — no document is read to draw a link — and absent until they\n * settle, so the dialog never 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 ? pluginRecordByEmailHref(\n 'contact',\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' | null,\n extra: Record<string, unknown>,\n copy: {\n done: string\n already: string\n subject: string\n action: string\n partial?: string\n },\n headers: Record<string, string> = {},\n ): Promise<false | Record<string, any>> => {\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', ...headers },\n body: JSON.stringify({ hostId, orderId, ...(to ? { 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 ?? 'changed'}`,\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(\n payload?.already\n ? copy.already\n : payload?.status === 'partially_fulfilled' && copy.partial\n ? copy.partial\n : copy.done,\n {\n variant: 'success',\n persist: false,\n },\n )\n return payload ?? {}\n } finally {\n setBusy(false)\n }\n },\n [orderId, user, hostId, enqueueSnackbar],\n )\n\n /**\n * One key per shipment attempt (AGL-3611), the refund's shape: a partial\n * shipment leaves the order open to more, so \"already in the target\n * status\" cannot catch its retry — the key does. Retired on a definitive\n * answer; kept across a network failure or a 5xx, the window it covers.\n */\n const fulfillKey = useRef('')\n useEffect(() => {\n fulfillKey.current = ''\n }, [orderId])\n\n const fulfill = useCallback(\n async (submission: FulfillItemsSubmission, key: string) => {\n const payload = await transition(\n 'fulfilled',\n {\n ...(submission.lineItems ? { lineItems: submission.lineItems } : {}),\n ...(submission.carrier ? { carrier: submission.carrier } : {}),\n ...(submission.trackingNumber ? { trackingNumber: submission.trackingNumber } : {}),\n ...(submission.trackingUrl ? { trackingUrl: submission.trackingUrl } : {}),\n ...(submission.labelUrl ? { labelUrl: submission.labelUrl } : {}),\n ...(submission.notify ? {} : { notify: false }),\n },\n {\n done: 'Order fulfilled',\n partial: 'Items fulfilled — the rest are still to ship',\n already: 'Order was already fulfilled',\n subject: 'the order was fulfilled',\n action: 'fulfillment',\n },\n { 'Idempotency-Key': key },\n )\n return payload\n },\n [transition],\n )\n\n const handleFulfill = useCallback(\n async (submission: FulfillItemsSubmission) => {\n if (!order) return false\n if (!fulfillKey.current) fulfillKey.current = newAttemptKey()\n const payload = await fulfill(submission, fulfillKey.current)\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 (payload) {\n fulfillKey.current = ''\n setFulfilling(false)\n }\n return Boolean(payload)\n },\n [order, fulfill],\n )\n\n const handleUpdateTracking = useCallback(\n async (\n fulfillmentId: string,\n next: { carrier: string; trackingNumber: string; trackingUrl?: string },\n ) =>\n Boolean(\n await transition(\n null,\n { action: 'update-tracking', fulfillmentId, ...next },\n {\n done: 'Tracking updated',\n already: 'Tracking was already up to date',\n subject: 'the tracking was updated',\n action: 'tracking update',\n },\n ),\n ),\n [transition],\n )\n\n const handleCancelFulfillment = useCallback(\n async (fulfillmentId: string) => {\n const confirmed = await confirm({\n title: 'Cancel this shipment?',\n description:\n 'Its items go back to unfulfilled and can be shipped again. The buyer is not told.',\n confirmationText: 'Cancel shipment',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await transition(\n null,\n { action: 'cancel-fulfillment', fulfillmentId },\n {\n done: 'Shipment canceled',\n already: 'Shipment was already canceled',\n subject: 'the shipment was canceled',\n action: 'shipment cancel',\n },\n )\n },\n [confirm, transition],\n )\n\n /**\n * A widget's shipment (the zones' `recordFulfillment`): the same route,\n * keyed by the widget's own attempt key, and a throw with the route's words\n * when it refuses, so the widget can tell the merchant why.\n */\n const recordFulfillment = useCallback(\n async (request: ConsoleFulfillmentRequest): Promise<ConsoleOrderZoneFulfillment> => {\n const payload = await fulfill(\n {\n ...(request.lineItems ? { lineItems: request.lineItems.map((entry) => ({ ...entry })) } : {}),\n carrier: String(request.carrier ?? ''),\n trackingNumber: String(request.trackingNumber ?? ''),\n ...(request.trackingUrl ? { trackingUrl: request.trackingUrl } : {}),\n ...(request.labelUrl ? { labelUrl: request.labelUrl } : {}),\n notify: request.notify !== false,\n },\n String(request.idempotencyKey || newAttemptKey()),\n )\n if (!payload || !payload.fulfillment || !order) {\n throw new Error('The shipment was not recorded. Check the order and try again.')\n }\n setFulfilling(false)\n return toZoneFulfillment(order, payload.fulfillment)\n },\n [fulfill, order],\n )\n\n const zoneOrder = useMemo(\n () => (order && orderId ? consoleOrderZoneOrder(order, orderId) : null),\n // `rawOrder` is the snapshot; `order` is derived from it on each render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [rawOrder, orderId],\n )\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 fulfilledByLine = CommerceModel.orderLineFulfillmentStates(order).map(\n (state) => state.fulfilledQuantity,\n )\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 {fulfilledByLine[index] ? (\n <Chip\n label={`${fulfilledByLine[index]} of ${line.quantity} fulfilled`}\n size=\"small\"\n variant=\"outlined\"\n />\n ) : null}\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 // Optional lines the buyer took at checkout (AGL-3635), by name.\n ...(order.extras ?? []).map((extra) => [extra.label, extra.amountCents]),\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 <FulfillmentList\n order={order}\n busy={busy}\n onUpdateTracking={handleUpdateTracking}\n onCancelFulfillment={handleCancelFulfillment}\n />\n {fulfilling ? (\n <FulfillItemsPanel\n order={order}\n busy={busy}\n onSubmit={handleFulfill}\n onCancel={() => setFulfilling(false)}\n renderZone={\n WidgetSlot && zoneOrder\n ? (selection, applyTracking) => (\n <HostedZone\n renderer={WidgetSlot}\n slot={ORDER_FULFILLMENT_ZONE.id}\n hostId={hostId}\n orgId={undefined}\n order={zoneOrder}\n recordFulfillment={recordFulfillment}\n selection={selection}\n applyTracking={applyTracking}\n />\n )\n : undefined\n }\n />\n ) : null}\n {/*\n The order zone (AGL-3611): a widget reads the order and records a\n shipment through `recordFulfillment`, this dialog's own route.\n */}\n {WidgetSlot && zoneOrder ? (\n <HostedZone\n renderer={WidgetSlot}\n slot={ORDER_DETAIL_ZONE.id}\n hostId={hostId}\n orgId={undefined}\n order={zoneOrder}\n recordFulfillment={recordFulfillment}\n />\n ) : null}\n {/* The order's returns and \"Start return\" (AGL-3611). */}\n {orderId ? <OrderReturns hostId={hostId} orderId={orderId} order={order} /> : 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 {orderId ? <OrderInvoiceButton hostId={hostId} orderId={orderId} order={order} /> : null}\n {orderId ? <OrderReceiptResend hostId={hostId} orderId={orderId} order={order} /> : null}\n {orderId && order.channel === 'pos' ? (\n // The register's 80mm receipt, its gift receipt and a reprint on\n // the register's cloud printer (AGL-3609).\n <PosReceiptActions hostId={hostId} orderId={orderId} order={order} cloudPrint=\"reprint\" />\n ) : null}\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')) && !fulfilling ? (\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setFulfilling(true)}\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","pluginRecordByEmailHref","describePaymentRisk","AppLink","useConfirmationContext","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Stack","TextField","Tooltip","Typography","doc","runTransaction","updateDoc","useParams","memo","useCallback","useEffect","useMemo","useRef","useState","useFirestore","useUser","authorizedFetch","useConsoleWidgetSlot","consoleOrderZoneOrder","FulfillItemsPanel","FulfillmentList","toZoneFulfillment","ORDER_DETAIL_ZONE","ORDER_FULFILLMENT_ZONE","OrderInvoiceButton","OrderReceiptResend","OrderReturns","PosReceiptActions","STATUS_COLOR","pending","paid","partially_fulfilled","fulfilled","delivered","cancelled","refunded","DISPUTE_COLOR","open","lost","won","settled","usd","cents","toFixed","HostedZone","props","renderer","Renderer","zone","newAttemptKey","globalThis","crypto","randomUUID","Date","now","Math","random","toString","slice","OrderDetailDialog","order","restock","hostId","rawOrder","onClose","firestore","data","user","enqueueSnackbar","confirm","fulfilling","setFulfilling","WidgetSlot","note","setNote","busy","setBusy","liftLegacyOrder","orderId","$id","params","customerCrmHref","orgSlug","host","customerEmail","String","write","patch","transition","to","extra","copy","headers","response","method","body","JSON","stringify","error","console","subject","variant","allowDuplicate","payload","json","catch","ok","status","action","already","partial","done","persist","fulfillKey","current","fulfill","submission","key","lineItems","carrier","trackingNumber","trackingUrl","labelUrl","notify","handleFulfill","Boolean","handleUpdateTracking","fulfillmentId","next","handleCancelFulfillment","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","recordFulfillment","request","map","entry","idempotencyKey","fulfillment","Error","zoneOrder","handleDelivered","handleCancel","units","Number","alreadyCancelled","attemptKey","handleRefund","lineItemIds","lines","scoped","length","scopedCents","orderLineRefundCents","index","name","join","totals","totalCents","amountCents","refundedCents","orderHasOpenDispute","orderDisputeBlocksRefund","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","part","close","focus","print","can","canTransitionOrder","dispute","describeOrderDispute","paymentRisk","reversal","splitOrderReversal","fulfilledByLine","orderLineFulfillmentStates","fulfilledQuantity","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","extras","taxCents","discountCents","fontWeight","abs","describeOrderTaxMode","taxMode","chargedBackCents","kind","fullyReversed","productId","reverse","event","atMs","toLocaleString","value","onChange","target","onUpdateTracking","onCancelFulfillment","onSubmit","onCancel","renderZone","selection","applyTracking","slot","id","orgId","undefined","paymentLinkUrl","alignSelf","navigator","clipboard","writeText","component","componentVariant","nativeButton","href","cloudPrint","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,uBAAuB,QAAQ,mDAAkD;AAC1F,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,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BACH2I,IAAI,6BACH,KAACzN;wBAAO2P,UAAUzK;wBAAM0K,SAASpG;kCAC9B;yBAED;kCACJ,KAACxJ;wBAAO4P,SAASrL;kCAAU;;;;;;AAInC;AACAL,kBAAkBuO,WAAW,GAAG;AAEhC,eAAevO,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 { pluginRecordByEmailHref } from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\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 { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport OrderLocalFulfillmentPanel from './order-local-fulfillment-panel.component'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n type ConsoleWidgetSlotRenderer,\n useConsoleWidgetSlot,\n} from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport {\n consoleOrderZoneOrder,\n FulfillItemsPanel,\n FulfillmentList,\n type FulfillItemsSubmission,\n toZoneFulfillment,\n} from './order-fulfillment-panel.component'\nimport {\n type ConsoleFulfillmentRequest,\n type ConsoleOrderZoneFulfillment,\n ORDER_DETAIL_ZONE,\n ORDER_FULFILLMENT_ZONE,\n} from './order-zones'\nimport { OrderInvoiceButton } from './order-invoice.component'\nimport { OrderReceiptResend } from './order-receipt-resend.component'\nimport { OrderReturns } from './order-returns.component'\nimport { PosReceiptActions } from './pos-ops/pos-receipt-actions.component'\nimport { OrderOfflineNotice } from './order-offline-notice.component'\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 * A zone hosted in the dialog, drawn again only when what it is handed\n * changes — the product editor's reasoning (AGL-3423): the shell's renderer\n * is not memoized, and the dialog redraws on every keystroke in its fields.\n */\nconst HostedZone = memo(function HostedZone(\n props: { renderer: ConsoleWidgetSlotRenderer; slot: string } & Record<string, unknown>,\n) {\n const { renderer: Renderer, ...zone } = props\n return <Renderer {...zone} />\n})\n\n/** A fresh key for one attempt at a write the route dedupes on. */\nconst newAttemptKey = () =>\n globalThis.crypto?.randomUUID?.() ??\n `${Date.now()}-${Math.random().toString(36).slice(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 [fulfilling, setFulfilling] = useState(false)\n const WidgetSlot = useConsoleWidgetSlot()\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 * at the address the plugin that keeps contacts publishes; where none\n * does, there is no link. A guest checkout with no address updated\n * nobody, so there is no link either. Built from the route params already\n * in the URL — no document is read to draw a link — and absent until they\n * settle, so the dialog never 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 ? pluginRecordByEmailHref(\n 'contact',\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' | null,\n extra: Record<string, unknown>,\n copy: {\n done: string\n already: string\n subject: string\n action: string\n partial?: string\n },\n headers: Record<string, string> = {},\n ): Promise<false | Record<string, any>> => {\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', ...headers },\n body: JSON.stringify({ hostId, orderId, ...(to ? { 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 ?? 'changed'}`,\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(\n payload?.already\n ? copy.already\n : payload?.status === 'partially_fulfilled' && copy.partial\n ? copy.partial\n : copy.done,\n {\n variant: 'success',\n persist: false,\n },\n )\n return payload ?? {}\n } finally {\n setBusy(false)\n }\n },\n [orderId, user, hostId, enqueueSnackbar],\n )\n\n /**\n * One key per shipment attempt (AGL-3611), the refund's shape: a partial\n * shipment leaves the order open to more, so \"already in the target\n * status\" cannot catch its retry — the key does. Retired on a definitive\n * answer; kept across a network failure or a 5xx, the window it covers.\n */\n const fulfillKey = useRef('')\n useEffect(() => {\n fulfillKey.current = ''\n }, [orderId])\n\n const fulfill = useCallback(\n async (submission: FulfillItemsSubmission, key: string) => {\n const payload = await transition(\n 'fulfilled',\n {\n ...(submission.lineItems ? { lineItems: submission.lineItems } : {}),\n ...(submission.carrier ? { carrier: submission.carrier } : {}),\n ...(submission.trackingNumber ? { trackingNumber: submission.trackingNumber } : {}),\n ...(submission.trackingUrl ? { trackingUrl: submission.trackingUrl } : {}),\n ...(submission.labelUrl ? { labelUrl: submission.labelUrl } : {}),\n ...(submission.notify ? {} : { notify: false }),\n },\n {\n done: 'Order fulfilled',\n partial: 'Items fulfilled — the rest are still to ship',\n already: 'Order was already fulfilled',\n subject: 'the order was fulfilled',\n action: 'fulfillment',\n },\n { 'Idempotency-Key': key },\n )\n return payload\n },\n [transition],\n )\n\n const handleFulfill = useCallback(\n async (submission: FulfillItemsSubmission) => {\n if (!order) return false\n if (!fulfillKey.current) fulfillKey.current = newAttemptKey()\n const payload = await fulfill(submission, fulfillKey.current)\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 (payload) {\n fulfillKey.current = ''\n setFulfilling(false)\n }\n return Boolean(payload)\n },\n [order, fulfill],\n )\n\n const handleUpdateTracking = useCallback(\n async (\n fulfillmentId: string,\n next: { carrier: string; trackingNumber: string; trackingUrl?: string },\n ) =>\n Boolean(\n await transition(\n null,\n { action: 'update-tracking', fulfillmentId, ...next },\n {\n done: 'Tracking updated',\n already: 'Tracking was already up to date',\n subject: 'the tracking was updated',\n action: 'tracking update',\n },\n ),\n ),\n [transition],\n )\n\n const handleCancelFulfillment = useCallback(\n async (fulfillmentId: string) => {\n const confirmed = await confirm({\n title: 'Cancel this shipment?',\n description:\n 'Its items go back to unfulfilled and can be shipped again. The buyer is not told.',\n confirmationText: 'Cancel shipment',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await transition(\n null,\n { action: 'cancel-fulfillment', fulfillmentId },\n {\n done: 'Shipment canceled',\n already: 'Shipment was already canceled',\n subject: 'the shipment was canceled',\n action: 'shipment cancel',\n },\n )\n },\n [confirm, transition],\n )\n\n /**\n * A widget's shipment (the zones' `recordFulfillment`): the same route,\n * keyed by the widget's own attempt key, and a throw with the route's words\n * when it refuses, so the widget can tell the merchant why.\n */\n const recordFulfillment = useCallback(\n async (request: ConsoleFulfillmentRequest): Promise<ConsoleOrderZoneFulfillment> => {\n const payload = await fulfill(\n {\n ...(request.lineItems ? { lineItems: request.lineItems.map((entry) => ({ ...entry })) } : {}),\n carrier: String(request.carrier ?? ''),\n trackingNumber: String(request.trackingNumber ?? ''),\n ...(request.trackingUrl ? { trackingUrl: request.trackingUrl } : {}),\n ...(request.labelUrl ? { labelUrl: request.labelUrl } : {}),\n notify: request.notify !== false,\n },\n String(request.idempotencyKey || newAttemptKey()),\n )\n if (!payload || !payload.fulfillment || !order) {\n throw new Error('The shipment was not recorded. Check the order and try again.')\n }\n setFulfilling(false)\n return toZoneFulfillment(order, payload.fulfillment)\n },\n [fulfill, order],\n )\n\n const zoneOrder = useMemo(\n () => (order && orderId ? consoleOrderZoneOrder(order, orderId) : null),\n // `rawOrder` is the snapshot; `order` is derived from it on each render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [rawOrder, orderId],\n )\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 fulfilledByLine = CommerceModel.orderLineFulfillmentStates(order).map(\n (state) => state.fulfilledQuantity,\n )\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 {fulfilledByLine[index] ? (\n <Chip\n label={`${fulfilledByLine[index]} of ${line.quantity} fulfilled`}\n size=\"small\"\n variant=\"outlined\"\n />\n ) : null}\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 // Optional lines the buyer took at checkout (AGL-3635), by name.\n ...(order.extras ?? []).map((extra) => [extra.label, extra.amountCents]),\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 {/* A register sale rung offline, and what its sync found (AGL-3625). */}\n <OrderOfflineNotice order={order} />\n {/* Pickup or the store's own delivery, and its next step (AGL-3624). */}\n {orderId ? <OrderLocalFulfillmentPanel hostId={hostId} orderId={orderId} order={order} /> : 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 <FulfillmentList\n order={order}\n busy={busy}\n onUpdateTracking={handleUpdateTracking}\n onCancelFulfillment={handleCancelFulfillment}\n />\n {fulfilling ? (\n <FulfillItemsPanel\n order={order}\n busy={busy}\n onSubmit={handleFulfill}\n onCancel={() => setFulfilling(false)}\n renderZone={\n WidgetSlot && zoneOrder\n ? (selection, applyTracking) => (\n <HostedZone\n renderer={WidgetSlot}\n slot={ORDER_FULFILLMENT_ZONE.id}\n hostId={hostId}\n orgId={undefined}\n order={zoneOrder}\n recordFulfillment={recordFulfillment}\n selection={selection}\n applyTracking={applyTracking}\n />\n )\n : undefined\n }\n />\n ) : null}\n {/*\n The order zone (AGL-3611): a widget reads the order and records a\n shipment through `recordFulfillment`, this dialog's own route.\n */}\n {WidgetSlot && zoneOrder ? (\n <HostedZone\n renderer={WidgetSlot}\n slot={ORDER_DETAIL_ZONE.id}\n hostId={hostId}\n orgId={undefined}\n order={zoneOrder}\n recordFulfillment={recordFulfillment}\n />\n ) : null}\n {/* The order's returns and \"Start return\" (AGL-3611). */}\n {orderId ? <OrderReturns hostId={hostId} orderId={orderId} order={order} /> : 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 {orderId ? <OrderInvoiceButton hostId={hostId} orderId={orderId} order={order} /> : null}\n {orderId ? <OrderReceiptResend hostId={hostId} orderId={orderId} order={order} /> : null}\n {orderId && order.channel === 'pos' ? (\n // The register's 80mm receipt, its gift receipt and a reprint on\n // the register's cloud printer (AGL-3609).\n <PosReceiptActions hostId={hostId} orderId={orderId} order={order} cloudPrint=\"reprint\" />\n ) : null}\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')) && !fulfilling ? (\n <Button\n variant=\"contained\"\n color=\"primary\"\n onClick={() => setFulfilling(true)}\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","pluginRecordByEmailHref","describePaymentRisk","AppLink","useConfirmationContext","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Stack","TextField","Tooltip","Typography","doc","runTransaction","updateDoc","useParams","memo","useCallback","useEffect","useMemo","useRef","useState","useFirestore","useUser","OrderLocalFulfillmentPanel","authorizedFetch","useConsoleWidgetSlot","consoleOrderZoneOrder","FulfillItemsPanel","FulfillmentList","toZoneFulfillment","ORDER_DETAIL_ZONE","ORDER_FULFILLMENT_ZONE","OrderInvoiceButton","OrderReceiptResend","OrderReturns","PosReceiptActions","OrderOfflineNotice","STATUS_COLOR","pending","paid","partially_fulfilled","fulfilled","delivered","cancelled","refunded","DISPUTE_COLOR","open","lost","won","settled","usd","cents","toFixed","HostedZone","props","renderer","Renderer","zone","newAttemptKey","globalThis","crypto","randomUUID","Date","now","Math","random","toString","slice","OrderDetailDialog","order","restock","hostId","rawOrder","onClose","firestore","data","user","enqueueSnackbar","confirm","fulfilling","setFulfilling","WidgetSlot","note","setNote","busy","setBusy","liftLegacyOrder","orderId","$id","params","customerCrmHref","orgSlug","host","customerEmail","String","write","patch","transition","to","extra","copy","headers","response","method","body","JSON","stringify","error","console","subject","variant","allowDuplicate","payload","json","catch","ok","status","action","already","partial","done","persist","fulfillKey","current","fulfill","submission","key","lineItems","carrier","trackingNumber","trackingUrl","labelUrl","notify","handleFulfill","Boolean","handleUpdateTracking","fulfillmentId","next","handleCancelFulfillment","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","recordFulfillment","request","map","entry","idempotencyKey","fulfillment","Error","zoneOrder","handleDelivered","handleCancel","units","Number","alreadyCancelled","attemptKey","handleRefund","lineItemIds","lines","scoped","length","scopedCents","orderLineRefundCents","index","name","join","totals","totalCents","amountCents","refundedCents","orderHasOpenDispute","orderDisputeBlocksRefund","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","part","close","focus","print","can","canTransitionOrder","dispute","describeOrderDispute","paymentRisk","reversal","splitOrderReversal","fulfilledByLine","orderLineFulfillmentStates","fulfilledQuantity","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","extras","taxCents","discountCents","fontWeight","abs","describeOrderTaxMode","taxMode","chargedBackCents","kind","fullyReversed","productId","reverse","event","atMs","toLocaleString","value","onChange","target","onUpdateTracking","onCancelFulfillment","onSubmit","onCancel","renderZone","selection","applyTracking","slot","id","orgId","undefined","paymentLinkUrl","alignSelf","navigator","clipboard","writeText","component","componentVariant","nativeButton","href","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B,OAAOA;wBAAOqO,YAAW;yBAC5E;oBACH/E,IAAI,6BACH,KAAC3N;wBAAOgJ,OAAM;wBAAQ6G,UAAUzK;wBAAM0K,SAASnG;kCAC5C;yBAED;oBACHgE,IAAI,cACH,kEAAkE;oBAClE,oEAAoE;oBACpE,0DAA0D;oBAC1D,kEAAkE;oBAClE,kEAAkE;oBAClElO,cAAcsL,wBAAwB,CAAC1G,uBACrC,KAAC5D;wBACCmI,OACE,gEACA,2DACA,6DACA,uDACA;kCAKF,cAAA,KAACmG;sCACC,cAAA,KAAC/O;gCAAOgJ,OAAM;gCAAQ6G,QAAQ;0CAC3B;;;uCAKP,KAAC7P;wBACCgJ,OAAM;wBACN6G,UAAUzK;wBACV0K,SAAS,IAAM9F;kCAEd;yBAGH;oBACF2D,CAAAA,IAAI,gBAAgBA,IAAI,sBAAqB,KAAM,CAAC5I,2BACpD,KAAC/E;wBACC8G,SAAQ;wBACRkC,OAAM;wBACN8G,SAAS,IAAM9K,cAAc;kCAE5B;yBAED;oBACH2I,IAAI,6BACH,KAAC3N;wBAAO6P,UAAUzK;wBAAM0K,SAASpG;kCAC9B;yBAED;kCACJ,KAAC1J;wBAAO8P,SAASrL;kCAAU;;;;;;AAInC;AACAL,kBAAkBuO,WAAW,GAAG;AAEhC,eAAevO,kBAAiB"}
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import * as CommerceModel from '../../model';
18
+ /**
19
+ * The pickup or local delivery of one order (AGL-3624), and the next step
20
+ * the store can take with it, posted to `/api/commerce/local-fulfillment`.
21
+ * Shared by the order dialog and the pickup and delivery queue, so both say
22
+ * the same thing and take the same steps.
23
+ */
24
+ export type LocalFulfillmentStep = 'ready' | 'preparing' | 'picked_up' | 'out_for_delivery' | 'delivered' | 'delivery_failed';
25
+ /** Posts one step. Resolves `true` when the order moved (or already had). */
26
+ export declare function useLocalFulfillmentStep(hostId: string): {
27
+ run: (orderId: string, action: LocalFulfillmentStep, extra?: Record<string, unknown>) => Promise<boolean>;
28
+ busy: boolean;
29
+ };
30
+ /** The steps an order can take next, in the order a person takes them. */
31
+ export declare function nextLocalFulfillmentSteps(order: Pick<CommerceModel.HostOrder, 'fulfillmentMethod' | 'pickup' | 'localDelivery' | 'status'>): Array<{
32
+ step: LocalFulfillmentStep;
33
+ label: string;
34
+ primary?: boolean;
35
+ }>;
36
+ export declare function OrderLocalFulfillmentPanel(props: {
37
+ hostId: string;
38
+ orderId: string;
39
+ order: CommerceModel.HostOrder;
40
+ }): import("react").JSX.Element;
41
+ export declare namespace OrderLocalFulfillmentPanel {
42
+ var displayName: string;
43
+ }
44
+ export default OrderLocalFulfillmentPanel;