@aglyn/plugins-commerce 1.0.0-beta.261 → 1.0.0-beta.262

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 (46) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/order-detail-dialog.component.js +17 -45
  3. package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
  4. package/src/lib/components/console/order-fulfillment-panel.component.js +12 -25
  5. package/src/lib/components/console/order-fulfillment-panel.component.js.map +1 -1
  6. package/src/lib/components/console/order-invoice.component.js +2 -10
  7. package/src/lib/components/console/order-invoice.component.js.map +1 -1
  8. package/src/lib/components/console/order-shipping-actions.component.d.ts +1 -15
  9. package/src/lib/components/console/order-shipping-actions.component.js +3 -23
  10. package/src/lib/components/console/order-shipping-actions.component.js.map +1 -1
  11. package/src/lib/components/console/product-labels-dialog.component.d.ts +2 -5
  12. package/src/lib/components/console/product-labels-dialog.component.js +6 -24
  13. package/src/lib/components/console/product-labels-dialog.component.js.map +1 -1
  14. package/src/lib/components/console/products-hub-card.component.js +7 -20
  15. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  16. package/src/lib/model/commerce-shipping.d.ts +2 -0
  17. package/src/lib/model/commerce-shipping.js +1 -0
  18. package/src/lib/model/commerce-shipping.js.map +1 -1
  19. package/src/lib/model/order-dialog.d.ts +52 -0
  20. package/src/lib/model/order-dialog.js +85 -0
  21. package/src/lib/model/order-dialog.js.map +1 -0
  22. package/src/lib/model/product-write.d.ts +71 -0
  23. package/src/lib/model/product-write.js +28 -0
  24. package/src/lib/model/product-write.js.map +1 -1
  25. package/src/lib/printing/product-labels.d.ts +22 -0
  26. package/src/lib/printing/product-labels.js +39 -2
  27. package/src/lib/printing/product-labels.js.map +1 -1
  28. package/src/lib/server/order-figures.js +31 -0
  29. package/src/lib/server/order-figures.js.map +1 -1
  30. package/src/lib/server/order-print.d.ts +40 -0
  31. package/src/lib/server/order-print.js +113 -0
  32. package/src/lib/server/order-print.js.map +1 -0
  33. package/src/lib/server/products-write.d.ts +26 -0
  34. package/src/lib/server/products-write.js +184 -1
  35. package/src/lib/server/products-write.js.map +1 -1
  36. package/src/lib/server.js +8 -0
  37. package/src/lib/server.js.map +1 -1
  38. package/src/lib/transfer/shipping-presets.d.ts +16 -0
  39. package/src/lib/transfer/shipping-presets.js +34 -1
  40. package/src/lib/transfer/shipping-presets.js.map +1 -1
  41. package/src/lib/utils/order-invoice.d.ts +5 -0
  42. package/src/lib/utils/order-invoice.js +14 -0
  43. package/src/lib/utils/order-invoice.js.map +1 -1
  44. package/src/lib/utils/order-packing-slip.d.ts +31 -0
  45. package/src/lib/utils/order-packing-slip.js +46 -0
  46. package/src/lib/utils/order-packing-slip.js.map +1 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-commerce",
3
- "version": "1.0.0-beta.261",
3
+ "version": "1.0.0-beta.262",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,18 +25,18 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.261",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.261",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.261",
31
- "@aglyn/shared-ui-next": "1.0.0-beta.261",
32
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.261",
33
- "@aglyn/shared-util-email": "1.0.0-beta.261",
34
- "@aglyn/shared-util-http": "1.0.0-beta.261",
35
- "@aglyn/shared-util-timestamp": "1.0.0-beta.261",
36
- "@aglyn/shared-util-tools": "1.0.0-beta.261",
37
- "@aglyn/tenant-data-admin": "1.0.0-beta.261",
38
- "@aglyn/tenant-feature-instance": "1.0.0-beta.261",
39
- "@aglyn/tenant-runtime": "1.0.0-beta.261",
28
+ "@aglyn/aglyn": "1.0.0-beta.262",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.262",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.262",
31
+ "@aglyn/shared-ui-next": "1.0.0-beta.262",
32
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.262",
33
+ "@aglyn/shared-util-email": "1.0.0-beta.262",
34
+ "@aglyn/shared-util-http": "1.0.0-beta.262",
35
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.262",
36
+ "@aglyn/shared-util-tools": "1.0.0-beta.262",
37
+ "@aglyn/tenant-data-admin": "1.0.0-beta.262",
38
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.262",
39
+ "@aglyn/tenant-runtime": "1.0.0-beta.262",
40
40
  "@stripe/react-stripe-js": "^6.12.0",
41
41
  "@stripe/stripe-js": "^9.17.0",
42
42
  "@swc/helpers": "0.5.23",
@@ -18,7 +18,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
18
18
  import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
19
19
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
20
20
  import * as CommerceModel from "../../model/index.js";
21
- import { escapeHtml } from "../../utils/escape-html.js";
21
+ import { buildPackingSlipHtml } from "../../utils/order-packing-slip.js";
22
+ import { orderRefundPrompt, REFUND_BLOCKED_BY_DISPUTE } from "../../model/order-dialog.js";
22
23
  // The CRM's address from the SHARED builder, not the plugin (AGL-2622): the
23
24
  // CRM already reaches marketing, and marketing reaches commerce, so an
24
25
  // import of the CRM from here would close a cycle between the three
@@ -509,27 +510,15 @@ const usd = (cents)=>`$${((cents != null ? cents : 0) / 100).toFixed(2)}`;
509
510
  * the route derives the amount FROM the lines rather than trusting a figure
510
511
  * typed beside them.
511
512
  */ const handleRefund = useCallback(async (lineItemIds)=>{
512
- var _order_lineItems, _ref, _ref1, _order_refundedCents;
513
- var _order_totals;
514
513
  if (!order || !orderId) return;
515
- const lines = (_order_lineItems = order.lineItems) != null ? _order_lineItems : [];
516
514
  const scoped = (lineItemIds != null ? lineItemIds : []).length > 0;
517
- // The SERVER's figure, not a second derivation of it. This was
518
- // the list value `unitAmountCents x quantity`, which on a discounted order
519
- // is more than the buyer paid — so the dialog quoted one number and the
520
- // route refunded another. One function answers both.
521
- const scopedCents = CommerceModel.orderLineRefundCents(order, lineItemIds != null ? lineItemIds : []);
515
+ // The SERVER's figure, not a second derivation of it (`orderLineRefundCents`
516
+ // inside the prompt): the list value `unitAmountCents x quantity` is more
517
+ // than the buyer paid on a discounted order.
518
+ const prompt = orderRefundPrompt(order, lineItemIds != null ? lineItemIds : []);
522
519
  const confirmed = await confirm({
523
- title: scoped ? 'Refund this line?' : 'Refund this order?',
524
- description: (scoped ? `Refunds ${usd(scopedCents)} for ${(lineItemIds != null ? lineItemIds : []).map((index)=>{
525
- var _ref;
526
- var _lines_index;
527
- return (_ref = (_lines_index = lines[index]) == null ? void 0 : _lines_index.name) != null ? _ref : `line ${index}`;
528
- }).join(', ')} through Stripe, and withdraws that line's ` + 'downloads, license keys and gated content. A license key already ' + 'sent to the buyer is retired, not returned to your pool — they ' + 'still hold the string, so reissuing it would give two people one ' + 'working key.' : `Refunds ${usd(((_ref = (_ref1 = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref1 : order.amountCents) != null ? _ref : 0) - ((_order_refundedCents = order.refundedCents) != null ? _order_refundedCents : 0))} to the buyer through Stripe.`) + // An open INQUIRY keeps this button live on purpose (AGL-1820):
529
- // Stripe names a full refund as the way to resolve one before it
530
- // escalates to a chargeback. Said here so the admin reads the refund
531
- // as the documented exit, not a risk taken against the badge.
532
- (CommerceModel.orderHasOpenDispute(order) && !CommerceModel.orderDisputeBlocksRefund(order) ? ' An inquiry is open on this charge — a full refund resolves it' + ' before it can become a chargeback.' : ''),
520
+ title: prompt.title,
521
+ description: prompt.text,
533
522
  confirmationText: 'Refund',
534
523
  confirmationButtonProps: {
535
524
  color: 'error'
@@ -540,9 +529,9 @@ const usd = (cents)=>`$${((cents != null ? cents : 0) / 100).toFixed(2)}`;
540
529
  // `randomUUID` needs a secure context, which the console always is, but
541
530
  // fall back rather than throw on a refund.
542
531
  if (!attemptKey.current) {
543
- var _ref2;
532
+ var _ref;
544
533
  var _globalThis_crypto_randomUUID, _globalThis_crypto;
545
- attemptKey.current = (_ref2 = (_globalThis_crypto = globalThis.crypto) == null ? void 0 : (_globalThis_crypto_randomUUID = _globalThis_crypto.randomUUID) == null ? void 0 : _globalThis_crypto_randomUUID.call(_globalThis_crypto)) != null ? _ref2 : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
534
+ attemptKey.current = (_ref = (_globalThis_crypto = globalThis.crypto) == null ? void 0 : (_globalThis_crypto_randomUUID = _globalThis_crypto.randomUUID) == null ? void 0 : _globalThis_crypto_randomUUID.call(_globalThis_crypto)) != null ? _ref : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
546
535
  }
547
536
  try {
548
537
  const response = await authorizedFetch(user, '/api/commerce/refund', {
@@ -564,12 +553,12 @@ const usd = (cents)=>`$${((cents != null ? cents : 0) / 100).toFixed(2)}`;
564
553
  // so pressing Refund again dedupes rather than sends a second transfer.
565
554
  if (response.status < 500) attemptKey.current = '';
566
555
  if (!response.ok) {
567
- var _ref3;
556
+ var _ref1;
568
557
  // A 409 is a guard REFUSING — the status machine, or the open-dispute
569
558
  // block (AGL-1809), whose body explains what to do instead — not the
570
559
  // refund machinery failing. The route wrote nothing, so it surfaces
571
560
  // verbatim as a warning, same as the cancel path's 409 (AGL-1818).
572
- enqueueSnackbar((_ref3 = payload == null ? void 0 : payload.error) != null ? _ref3 : 'Refund failed', {
561
+ enqueueSnackbar((_ref1 = payload == null ? void 0 : payload.error) != null ? _ref1 : 'Refund failed', {
573
562
  variant: response.status === 409 ? 'warning' : 'error',
574
563
  allowDuplicate: true
575
564
  });
@@ -682,30 +671,13 @@ const usd = (cents)=>`$${((cents != null ? cents : 0) / 100).toFixed(2)}`;
682
671
  write
683
672
  ]);
684
673
  const handlePackingSlip = useCallback(()=>{
685
- var _order_lineItems, _address_city, _address_state, _address_postalCode;
686
674
  if (!order) return;
687
675
  const win = window.open('', '_blank', 'width=600,height=800');
688
676
  if (!win) return;
689
- // ESCAPED (AGL-2283). This is `document.write` into an `about:blank`
690
- // popup, which INHERITS the console's origin — and `order.shippingAddress`
691
- // is copied verbatim from Stripe's `shipping_details`, i.e. typed by the
692
- // SHOPPER. A name of `<img src=x onerror=…>` ran script against the
693
- // merchant's own authenticated session. React guards nothing here because
694
- // none of this is React. Line names and SKUs are merchant-authored and
695
- // lower severity, but they are the same construction and get the same
696
- // treatment rather than a case-by-case argument.
697
- const rows = ((_order_lineItems = order.lineItems) != null ? _order_lineItems : []).map((line)=>{
698
- var _line_sku;
699
- return `<tr><td>${escapeHtml(line.quantity)}×</td><td>${escapeHtml(line.name)}${line.variantLabel ? ` — ${escapeHtml(line.variantLabel)}` : ''}</td><td>${escapeHtml((_line_sku = line.sku) != null ? _line_sku : '')}</td></tr>`;
700
- }).join('');
701
- const address = order.shippingAddress;
702
- win.document.write(`<h2>Packing slip ${escapeHtml(CommerceModel.formatOrderNumber(order, orderId))}</h2>` + (address ? `<p>${[
703
- address.name,
704
- address.line1,
705
- address.line2,
706
- `${(_address_city = address.city) != null ? _address_city : ''} ${(_address_state = address.state) != null ? _address_state : ''} ${(_address_postalCode = address.postalCode) != null ? _address_postalCode : ''}`,
707
- address.country
708
- ].filter(Boolean).map((part)=>escapeHtml(part)).join('<br/>')}</p>` : '') + `<table border="0" cellpadding="6">${rows}</table>`);
677
+ // Every value is escaped by the builder (AGL-2283): this is
678
+ // `document.write` into an `about:blank` popup, which inherits the
679
+ // console's origin, and the address is typed by the shopper.
680
+ win.document.write(buildPackingSlipHtml(order, orderId));
709
681
  win.document.close();
710
682
  // Print from the opener, not from an injected inline script (AGL-523) —
711
683
  // the popup inherits this document's CSP, where an un-nonced inline
@@ -1112,7 +1084,7 @@ const usd = (cents)=>`$${((cents != null ? cents : 0) / 100).toFixed(2)}`;
1112
1084
  // (AGL-1809), while an open INQUIRY shows the badge but must keep
1113
1085
  // this button live — a full refund is how an inquiry is resolved.
1114
1086
  CommerceModel.orderDisputeBlocksRefund(order) ? /*#__PURE__*/ _jsx(Tooltip, {
1115
- title: 'A chargeback is open on this order, and refunding would not' + ' withdraw it — the bank has already taken the disputed' + ' amount, so a refund on top would pay the shopper twice.' + ' Respond to the dispute or accept it in the Stripe' + ' dashboard; refund any remainder once it settles.',
1087
+ title: REFUND_BLOCKED_BY_DISPUTE,
1116
1088
  children: /*#__PURE__*/ _jsx("span", {
1117
1089
  children: /*#__PURE__*/ _jsx(Button, {
1118
1090
  color: "error",
@@ -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, getDoc, 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 // The store's currency, which a hand-entered shipping cost is typed in\n // (AGL-3705). Read when the Fulfill items panel opens, not before.\n const [storeCurrency, setStoreCurrency] = useState<string | undefined>(undefined)\n useEffect(() => {\n if (!fulfilling || storeCurrency) return\n let live = true\n // A failed read leaves the field in US dollars, the store default.\n Promise.resolve()\n .then(() => getDoc(doc(firestore, 'hosts', hostId, 'settings', 'store')))\n .then((snapshot) => {\n const currency = String(snapshot.get('currency') ?? '').trim()\n if (live && currency) setStoreCurrency(currency.toUpperCase())\n })\n .catch(() => undefined)\n return () => {\n live = false\n }\n }, [fulfilling, storeCurrency, firestore, hostId])\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 ...(typeof submission.shippingCostCents === 'number'\n ? { shippingCostCents: submission.shippingCostCents }\n : {}),\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 answer = CommerceModel.restockAnswer(\n current,\n check.flaggedAtMs,\n resolution,\n String((user as any)?.uid ?? ''),\n )\n if (answer.verdict !== 'recorded') return answer.verdict\n // The SERVER's timeline, not the dialog's — a note landed from\n // another tab must survive the append (`restockAnswer` appends to\n // `current`).\n transaction.update(reference, answer.update)\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 const update = order ? CommerceModel.orderNoteUpdate(order, note) : null\n if (!update) return\n await write(update)\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 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 {CommerceModel.describeRestockCheck(restock, order)}\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 currency={storeCurrency}\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","getDoc","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","hostId","rawOrder","onClose","firestore","data","user","enqueueSnackbar","confirm","fulfilling","setFulfilling","storeCurrency","setStoreCurrency","undefined","live","Promise","resolve","then","snapshot","currency","String","get","trim","toUpperCase","catch","WidgetSlot","note","setNote","busy","setBusy","liftLegacyOrder","orderId","$id","params","customerCrmHref","orgSlug","host","customerEmail","write","patch","transition","to","extra","copy","headers","response","method","body","JSON","stringify","error","console","subject","variant","allowDuplicate","payload","json","ok","status","action","already","partial","done","persist","fulfillKey","current","fulfill","submission","key","lineItems","carrier","trackingNumber","trackingUrl","labelUrl","shippingCostCents","notify","handleFulfill","Boolean","handleUpdateTracking","fulfillmentId","next","handleCancelFulfillment","confirmed","title","description","confirmationText","confirmationButtonProps","color","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","exists","answer","restockAnswer","flaggedAtMs","uid","update","handleNote","orderNoteUpdate","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","restock","fulfilledByLine","orderLineFulfillmentStates","fulfilledQuantity","maxWidth","fullWidth","direction","spacing","sx","alignItems","span","label","replace","size","detail","tone","channel","display","flexDirection","gap","customerName","withdrawn","orderLineRefunded","flex","textDecoration","disabled","onClick","unitAmountCents","orderRefundState","orderRefundSummary","itemsCents","shippingCents","extras","taxCents","discountCents","fontWeight","abs","describeOrderTaxMode","taxMode","chargedBackCents","describeRestockCheck","productId","timeline","reverse","event","atMs","toLocaleString","value","onChange","target","onUpdateTracking","onCancelFulfillment","onSubmit","onCancel","renderZone","selection","applyTracking","slot","id","orgId","paymentLinkUrl","alignSelf","navigator","clipboard","writeText","component","componentVariant","nativeButton","href","cloudPrint","displayName"],"mappings":"AAAA;;;;;;;;;;;;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E;oBAClE,kEAAkE;oBAClEzO,cAAckM,wBAAwB,CAACrH,uBACrC,KAAC7D;wBACCgJ,OACE,gEACA,2DACA,6DACA,uDACA;kCAKF,cAAA,KAAC0F;sCACC,cAAA,KAACnP;gCAAO6J,OAAM;gCAAQqG,QAAQ;0CAC3B;;;uCAKP,KAAClQ;wBACC6J,OAAM;wBACNqG,UAAUhK;wBACViK,SAAS,IAAMvF;kCAEd;yBAGH;oBACFsD,CAAAA,IAAI,gBAAgBA,IAAI,sBAAqB,KAAM,CAACnJ,2BACpD,KAAC/E;wBACC2H,SAAQ;wBACRkC,OAAM;wBACNsG,SAAS,IAAMnL,cAAc;kCAE5B;yBAED;oBACHkJ,IAAI,6BACH,KAAClO;wBAAOkQ,UAAUhK;wBAAMiK,SAAS7F;kCAC9B;yBAED;kCACJ,KAACtK;wBAAOmQ,SAAS1L;kCAAU;;;;;;AAInC;AACAJ,kBAAkB0O,WAAW,GAAG;AAEhC,eAAe1O,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 { buildPackingSlipHtml } from '../../utils/order-packing-slip'\nimport { orderRefundPrompt, REFUND_BLOCKED_BY_DISPUTE } from '../../model/order-dialog'\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, getDoc, 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 // The store's currency, which a hand-entered shipping cost is typed in\n // (AGL-3705). Read when the Fulfill items panel opens, not before.\n const [storeCurrency, setStoreCurrency] = useState<string | undefined>(undefined)\n useEffect(() => {\n if (!fulfilling || storeCurrency) return\n let live = true\n // A failed read leaves the field in US dollars, the store default.\n Promise.resolve()\n .then(() => getDoc(doc(firestore, 'hosts', hostId, 'settings', 'store')))\n .then((snapshot) => {\n const currency = String(snapshot.get('currency') ?? '').trim()\n if (live && currency) setStoreCurrency(currency.toUpperCase())\n })\n .catch(() => undefined)\n return () => {\n live = false\n }\n }, [fulfilling, storeCurrency, firestore, hostId])\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 ...(typeof submission.shippingCostCents === 'number'\n ? { shippingCostCents: submission.shippingCostCents }\n : {}),\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 scoped = (lineItemIds ?? []).length > 0\n // The SERVER's figure, not a second derivation of it (`orderLineRefundCents`\n // inside the prompt): the list value `unitAmountCents x quantity` is more\n // than the buyer paid on a discounted order.\n const prompt = orderRefundPrompt(order, lineItemIds ?? [])\n const confirmed = await confirm({\n title: prompt.title,\n description: prompt.text,\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 answer = CommerceModel.restockAnswer(\n current,\n check.flaggedAtMs,\n resolution,\n String((user as any)?.uid ?? ''),\n )\n if (answer.verdict !== 'recorded') return answer.verdict\n // The SERVER's timeline, not the dialog's — a note landed from\n // another tab must survive the append (`restockAnswer` appends to\n // `current`).\n transaction.update(reference, answer.update)\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 const update = order ? CommerceModel.orderNoteUpdate(order, note) : null\n if (!update) return\n await write(update)\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 // Every value is escaped by the builder (AGL-2283): this is\n // `document.write` into an `about:blank` popup, which inherits the\n // console's origin, and the address is typed by the shopper.\n win.document.write(buildPackingSlipHtml(order, orderId))\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 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 {CommerceModel.describeRestockCheck(restock, order)}\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 currency={storeCurrency}\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 title={REFUND_BLOCKED_BY_DISPUTE}>\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","buildPackingSlipHtml","orderRefundPrompt","REFUND_BLOCKED_BY_DISPUTE","pluginRecordByEmailHref","describePaymentRisk","AppLink","useConfirmationContext","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","Divider","Stack","TextField","Tooltip","Typography","doc","getDoc","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","hostId","rawOrder","onClose","firestore","data","user","enqueueSnackbar","confirm","fulfilling","setFulfilling","storeCurrency","setStoreCurrency","undefined","live","Promise","resolve","then","snapshot","currency","String","get","trim","toUpperCase","catch","WidgetSlot","note","setNote","busy","setBusy","liftLegacyOrder","orderId","$id","params","customerCrmHref","orgSlug","host","customerEmail","write","patch","transition","to","extra","copy","headers","response","method","body","JSON","stringify","error","console","subject","variant","allowDuplicate","payload","json","ok","status","action","already","partial","done","persist","fulfillKey","current","fulfill","submission","key","lineItems","carrier","trackingNumber","trackingUrl","labelUrl","shippingCostCents","notify","handleFulfill","Boolean","handleUpdateTracking","fulfillmentId","next","handleCancelFulfillment","confirmed","title","description","confirmationText","confirmationButtonProps","color","recordFulfillment","request","map","entry","idempotencyKey","fulfillment","Error","zoneOrder","handleDelivered","handleCancel","units","Number","alreadyCancelled","attemptKey","handleRefund","lineItemIds","scoped","length","prompt","text","handleRestockAnswer","resolution","check","restockCheck","reference","verdict","transaction","exists","answer","restockAnswer","flaggedAtMs","uid","update","handleNote","orderNoteUpdate","handlePackingSlip","win","window","document","close","focus","print","totals","can","canTransitionOrder","dispute","describeOrderDispute","paymentRisk","reversal","splitOrderReversal","restock","fulfilledByLine","orderLineFulfillmentStates","state","fulfilledQuantity","maxWidth","fullWidth","direction","spacing","sx","alignItems","span","formatOrderNumber","label","replace","size","detail","tone","channel","display","flexDirection","gap","customerName","filter","join","line","index","withdrawn","orderLineRefunded","flex","textDecoration","quantity","name","variantLabel","orderDisputeBlocksRefund","disabled","onClick","unitAmountCents","orderRefundState","orderRefundSummary","itemsCents","shippingCents","extras","amountCents","taxCents","discountCents","totalCents","fontWeight","abs","describeOrderTaxMode","taxMode","refundedCents","chargedBackCents","describeRestockCheck","lines","productId","timeline","reverse","event","atMs","toLocaleString","value","onChange","target","onUpdateTracking","onCancelFulfillment","onSubmit","onCancel","renderZone","selection","applyTracking","slot","id","orgId","paymentLinkUrl","alignSelf","navigator","clipboard","writeText","component","componentVariant","nativeButton","href","cloudPrint","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,oBAAoB,QAAQ,oCAAgC;AACrE,SAASC,iBAAiB,EAAEC,yBAAyB,QAAQ,8BAA0B;AACvF,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,OAAO,EACPC,KAAK,EACLC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EAAEC,MAAM,EAAEC,cAAc,EAAEC,SAAS,QAAQ,qBAAoB;AAC3E,SAASC,SAAS,QAAQ,kBAAiB;AAC3C,SAASC,IAAI,EAAEC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAC/E,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,OAAOC,gCAAgC,+CAA2C;AAClF,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAEEC,oBAAoB,QACf,qDAAoD;AAC3D,SACEC,qBAAqB,EACrBC,iBAAiB,EACjBC,eAAe,EAEfC,iBAAiB,QACZ,yCAAqC;AAC5C,SAGEC,iBAAiB,EACjBC,sBAAsB,QACjB,mBAAe;AACtB,SAASC,kBAAkB,QAAQ,+BAA2B;AAC9D,SAASC,kBAAkB,QAA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