@aglyn/plugins-commerce 1.0.0-beta.290 → 1.0.0-beta.292
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.
- package/README.md +4 -2
- package/package.json +13 -13
- package/src/lib/components/cart-fulfillment.d.ts +3 -0
- package/src/lib/components/cart-fulfillment.js.map +1 -1
- package/src/lib/components/cart.js +14 -4
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +2 -1
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/console/host-orders-card.component.d.ts +6 -0
- package/src/lib/components/console/host-orders-card.component.js +3 -2
- package/src/lib/components/console/host-orders-card.component.js.map +1 -1
- package/src/lib/components/console/invoice-send.component.d.ts +44 -0
- package/src/lib/components/console/invoice-send.component.js +237 -0
- package/src/lib/components/console/invoice-send.component.js.map +1 -0
- package/src/lib/components/console/order-detail-dialog.component.d.ts +5 -0
- package/src/lib/components/console/order-detail-dialog.component.js +9 -2
- package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/order-invoice.component.d.ts +9 -0
- package/src/lib/components/console/order-invoice.component.js +27 -2
- package/src/lib/components/console/order-invoice.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-item-dialog.component.js +3 -2
- package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.js +2 -1
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +1 -1
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +41 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +356 -0
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -0
- package/src/lib/components/console/product-editor-dialog.component.js +31 -5
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-register-fields.component.d.ts +4 -5
- package/src/lib/components/console/product-register-fields.component.js +8 -197
- package/src/lib/components/console/product-register-fields.component.js.map +1 -1
- package/src/lib/components/console/products-hub-zone.component.js +6 -0
- package/src/lib/components/console/products-hub-zone.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +29 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +102 -4
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +8 -1
- package/src/lib/components/console/quote-pay-link.component.js +29 -3
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.d.ts +11 -0
- package/src/lib/components/console/quote-proofs.component.js +68 -0
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.d.ts +42 -0
- package/src/lib/components/console/quote-send.component.js +304 -0
- package/src/lib/components/console/quote-send.component.js.map +1 -0
- package/src/lib/components/console/quote-start.component.d.ts +45 -0
- package/src/lib/components/console/quote-start.component.js +182 -0
- package/src/lib/components/console/quote-start.component.js.map +1 -0
- package/src/lib/components/product-add-ons.d.ts +28 -0
- package/src/lib/components/product-add-ons.js +136 -0
- package/src/lib/components/product-add-ons.js.map +1 -0
- package/src/lib/components/product-detail.d.ts +16 -0
- package/src/lib/components/product-detail.js +112 -19
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +8 -2
- package/src/lib/components/product-grid.js +6 -1
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-options-field-body.d.ts +44 -0
- package/src/lib/components/product-options-field-body.js +260 -0
- package/src/lib/components/product-options-field-body.js.map +1 -0
- package/src/lib/components/product-options-field.d.ts +32 -0
- package/src/lib/components/product-options-field.js +128 -0
- package/src/lib/components/product-options-field.js.map +1 -0
- package/src/lib/components/quote-page-body.js +39 -20
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/model/commerce-cart.d.ts +15 -3
- package/src/lib/model/commerce-cart.js +10 -3
- package/src/lib/model/commerce-cart.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +139 -0
- package/src/lib/model/commerce-invoices.js +343 -0
- package/src/lib/model/commerce-invoices.js.map +1 -0
- package/src/lib/model/commerce-orders.d.ts +35 -5
- package/src/lib/model/commerce-orders.js +3 -0
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-pos-kiosk.d.ts +1 -1
- package/src/lib/model/commerce-pos-kiosk.js +3 -2
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/commerce-product-field.d.ts +23 -0
- package/src/lib/model/commerce-product-field.js +26 -0
- package/src/lib/model/commerce-product-field.js.map +1 -0
- package/src/lib/model/commerce-quote-email.d.ts +81 -0
- package/src/lib/model/commerce-quote-email.js +170 -0
- package/src/lib/model/commerce-quote-email.js.map +1 -0
- package/src/lib/model/commerce-quote-pay.d.ts +49 -6
- package/src/lib/model/commerce-quote-pay.js +69 -36
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +93 -0
- package/src/lib/model/commerce-quote-request.js +207 -0
- package/src/lib/model/commerce-quote-request.js.map +1 -0
- package/src/lib/model/commerce-quotes.d.ts +81 -0
- package/src/lib/model/commerce-quotes.js +1 -1
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce.d.ts +18 -0
- package/src/lib/model/commerce.js +26 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +3 -0
- package/src/lib/model/index.js +3 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +74 -4
- package/src/lib/model/product-modifiers.js +131 -10
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/plugin.js +19 -0
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/billing-webhook.js +164 -98
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cart-checkout.js +14 -2
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.d.ts +5 -0
- package/src/lib/server/cart.js +41 -4
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.d.ts +6 -0
- package/src/lib/server/catalog.js +2 -0
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-extras.js +3 -1
- package/src/lib/server/checkout-extras.js.map +1 -1
- package/src/lib/server/checkout.js +28 -3
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/commerce-pdf.d.ts +5 -1
- package/src/lib/server/commerce-pdf.js +37 -10
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/draft-order.js +23 -3
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/invoice-email.d.ts +76 -0
- package/src/lib/server/invoice-email.js +183 -0
- package/src/lib/server/invoice-email.js.map +1 -0
- package/src/lib/server/local-fulfillment.js +5 -1
- package/src/lib/server/local-fulfillment.js.map +1 -1
- package/src/lib/server/order-invoice-send.d.ts +43 -0
- package/src/lib/server/order-invoice-send.js +218 -0
- package/src/lib/server/order-invoice-send.js.map +1 -0
- package/src/lib/server/order-status.d.ts +11 -0
- package/src/lib/server/order-status.js +44 -8
- package/src/lib/server/order-status.js.map +1 -1
- package/src/lib/server/person-eraser.d.ts +3 -2
- package/src/lib/server/person-eraser.js +25 -6
- package/src/lib/server/person-eraser.js.map +1 -1
- package/src/lib/server/pos-offline-sync.js +1 -1
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-order.js +1 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/product.d.ts +26 -0
- package/src/lib/server/product.js +18 -0
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +5 -2
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server/quote-email.d.ts +85 -0
- package/src/lib/server/quote-email.js +211 -0
- package/src/lib/server/quote-email.js.map +1 -0
- package/src/lib/server/quote-link-token.d.ts +11 -0
- package/src/lib/server/quote-link-token.js +21 -0
- package/src/lib/server/quote-link-token.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +8 -3
- package/src/lib/server/quote-pay.js +105 -43
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +11 -0
- package/src/lib/server/quote.js +309 -12
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/site-page-resolver.js +2 -1
- package/src/lib/server/site-page-resolver.js.map +1 -1
- package/src/lib/server.js +5 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site.js +8 -0
- package/src/lib/site.js.map +1 -1
- package/src/lib/tenant-emails.js +243 -0
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/utils/add-to-cart.d.ts +8 -0
- package/src/lib/utils/add-to-cart.js +10 -2
- package/src/lib/utils/add-to-cart.js.map +1 -1
- package/src/lib/utils/commerce-document-pdf.d.ts +5 -0
- package/src/lib/utils/commerce-document-pdf.js +6 -1
- package/src/lib/utils/commerce-document-pdf.js.map +1 -1
- package/src/lib/utils/invoice-email-content.d.ts +45 -0
- package/src/lib/utils/invoice-email-content.js +126 -0
- package/src/lib/utils/invoice-email-content.js.map +1 -0
- package/src/lib/utils/order-invoice.d.ts +1 -1
- package/src/lib/utils/order-invoice.js +14 -6
- package/src/lib/utils/order-invoice.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +63 -0
- package/src/lib/utils/quote-email-content.js +157 -0
- package/src/lib/utils/quote-email-content.js.map +1 -0
|
@@ -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 { 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 // The day the buyer chose to use a pass (AGL-4043).\n (line.useDayKey ? ` · for ${CommerceModel.checkInDayLabel(line.useDayKey)}` : '')}\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","useDayKey","checkInDayLabel","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;AAC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,OAAOA;wBAAO+N,YAAW;yBAC5E;oBACH5F,IAAI,6BACH,KAACzM;wBAAO6J,OAAM;wBAAQwF,UAAUnJ;wBAAMoJ,SAAS/E;kCAC5C;yBAED;oBACHkC,IAAI,cACH,kEAAkE;oBAClE,oEAAoE;oBACpE,0DAA0D;oBAC1D,kEAAkE;oBAClE,kEAAkE;oBAClElN,cAAc6P,wBAAwB,CAAC9K,uBACrC,KAAC7D;wBAAQgJ,OAAO/J;kCAGd,cAAA,KAACiO;sCACC,cAAA,KAAC3N;gCAAO6J,OAAM;gCAAQwF,QAAQ;0CAC3B;;;uCAKP,KAACrP;wBACC6J,OAAM;wBACNwF,UAAUnJ;wBACVoJ,SAAS,IAAM1E;kCAEd;yBAGH;oBACF6B,CAAAA,IAAI,gBAAgBA,IAAI,sBAAqB,KAAM,CAAC1H,2BACpD,KAAC/E;wBACC2H,SAAQ;wBACRkC,OAAM;wBACNyF,SAAS,IAAMtK,cAAc;kCAE5B;yBAED;oBACHyH,IAAI,6BACH,KAACzM;wBAAOqP,UAAUnJ;wBAAMoJ,SAAShF;kCAC9B;yBAED;kCACJ,KAACtK;wBAAOsP,SAAS7K;kCAAU;;;;;;AAInC;AACAJ,kBAAkBiO,WAAW,GAAG;AAEhC,eAAejO,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 { invoiceSentLine } from './invoice-send.component'\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 * Holds \"Send quotes and invoices to customers\" (`commerce.quotes.send`),\n * for Send invoice (AGL-4099). Absent reads as held: the route decides.\n */\n canSendInvoices?: boolean\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, canSendInvoices = true } = 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 // The day the buyer chose to use a pass (AGL-4043).\n (line.useDayKey ? ` · for ${CommerceModel.checkInDayLabel(line.useDayKey)}` : '')}\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 {/* The last invoice emailed for the order (AGL-4099). */}\n {invoiceSentLine(order) ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {invoiceSentLine(order)}\n </Typography>\n ) : null}\n {order.paymentLinkUrl && order.status === 'pending' ? (\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={() => {\n navigator.clipboard.writeText(String(order.paymentLinkUrl))\n enqueueSnackbar('Payment link copied', {\n variant: 'success',\n persist: false,\n })\n }}\n >\n {'Copy payment link'}\n </Button>\n ) : null}\n </DialogContent>\n <DialogActions>\n {customerCrmHref ? (\n <Button\n component={AppLink as any}\n {...({ componentVariant: 'naked', nativeButton: false } as any)}\n href={customerCrmHref}\n >\n {'View customer in CRM'}\n </Button>\n ) : null}\n <Button onClick={handlePackingSlip}>{'Packing slip'}</Button>\n {orderId ? (\n <OrderInvoiceButton hostId={hostId} orderId={orderId} order={order} canSend={canSendInvoices} />\n ) : 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","invoiceSentLine","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","canSendInvoices","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","useDayKey","checkInDayLabel","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","canSend","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,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erceModel.HostOrder;
|
|
22
|
+
/**
|
|
23
|
+
* Holds "Send quotes and invoices to customers" (`commerce.quotes.send`),
|
|
24
|
+
* which Send invoice asks (AGL-4099). Absent reads as held: the route decides.
|
|
25
|
+
*/
|
|
26
|
+
canSend?: boolean;
|
|
22
27
|
}
|
|
23
28
|
/**
|
|
24
29
|
* "Invoice" (AGL-3611), beside "Packing slip" in the order dialog: a menu of
|
|
@@ -27,6 +32,10 @@ export interface OrderInvoiceButtonProps {
|
|
|
27
32
|
* its logo (`commerce/order-print?kind=invoice-pdf`, "Manage orders"). The
|
|
28
33
|
* store's name, currency and footer are read when one is clicked, not while
|
|
29
34
|
* the dialog is open, so the dialog listens to nothing more.
|
|
35
|
+
*
|
|
36
|
+
* "Send invoice" (AGL-4099) emails it to the customer with the PDF attached:
|
|
37
|
+
* an unpaid order's with a Pay button to its lasting pay link, a paid one's
|
|
38
|
+
* as the record (`invoice-send.component.tsx`).
|
|
30
39
|
*/
|
|
31
40
|
export declare function OrderInvoiceButton(props: OrderInvoiceButtonProps): import("react").JSX.Element;
|
|
32
41
|
export declare namespace OrderInvoiceButton {
|
|
@@ -17,11 +17,13 @@
|
|
|
17
17
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
18
18
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
19
19
|
import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
|
|
20
|
-
import { Button, Menu, MenuItem } from "@mui/material";
|
|
20
|
+
import { Button, ListItemText, Menu, MenuItem } from "@mui/material";
|
|
21
21
|
import { doc, getDoc } from "firebase/firestore";
|
|
22
22
|
import { useCallback, useState } from "react";
|
|
23
|
+
import { commerceSitePermissionRefusal } from "../../model/plugin-permissions.js";
|
|
23
24
|
import { buildOrderInvoiceHtml, invoiceStoreFrom } from "../../utils/order-invoice.js";
|
|
24
25
|
import { downloadCommercePdf } from "./commerce-pdf-download.js";
|
|
26
|
+
import { InvoiceSendDialog } from "./invoice-send.component.js";
|
|
25
27
|
/**
|
|
26
28
|
* "Invoice" (AGL-3611), beside "Packing slip" in the order dialog: a menu of
|
|
27
29
|
* "Print invoice", the order as a printable bill, and "Download PDF"
|
|
@@ -29,13 +31,18 @@ import { downloadCommercePdf } from "./commerce-pdf-download.js";
|
|
|
29
31
|
* its logo (`commerce/order-print?kind=invoice-pdf`, "Manage orders"). The
|
|
30
32
|
* store's name, currency and footer are read when one is clicked, not while
|
|
31
33
|
* the dialog is open, so the dialog listens to nothing more.
|
|
34
|
+
*
|
|
35
|
+
* "Send invoice" (AGL-4099) emails it to the customer with the PDF attached:
|
|
36
|
+
* an unpaid order's with a Pay button to its lasting pay link, a paid one's
|
|
37
|
+
* as the record (`invoice-send.component.tsx`).
|
|
32
38
|
*/ export function OrderInvoiceButton(props) {
|
|
33
|
-
const { hostId, orderId, order } = props;
|
|
39
|
+
const { hostId, orderId, order, canSend = true } = props;
|
|
34
40
|
const firestore = useFirestore();
|
|
35
41
|
const { data: user } = useUser();
|
|
36
42
|
const { enqueueSnackbar } = useSnackbar();
|
|
37
43
|
const [busy, setBusy] = useState(false);
|
|
38
44
|
const [anchor, setAnchor] = useState(null);
|
|
45
|
+
const [sending, setSending] = useState(false);
|
|
39
46
|
const handleDownload = useCallback(async ()=>{
|
|
40
47
|
setAnchor(null);
|
|
41
48
|
setBusy(true);
|
|
@@ -117,8 +124,26 @@ import { downloadCommercePdf } from "./commerce-pdf-download.js";
|
|
|
117
124
|
/*#__PURE__*/ _jsx(MenuItem, {
|
|
118
125
|
onClick: ()=>void handleDownload(),
|
|
119
126
|
children: 'Download PDF'
|
|
127
|
+
}),
|
|
128
|
+
/*#__PURE__*/ _jsx(MenuItem, {
|
|
129
|
+
disabled: !canSend,
|
|
130
|
+
onClick: ()=>{
|
|
131
|
+
setAnchor(null);
|
|
132
|
+
setSending(true);
|
|
133
|
+
},
|
|
134
|
+
children: /*#__PURE__*/ _jsx(ListItemText, {
|
|
135
|
+
primary: "Send invoice",
|
|
136
|
+
secondary: canSend ? undefined : commerceSitePermissionRefusal('commerce.quotes.send')
|
|
137
|
+
})
|
|
120
138
|
})
|
|
121
139
|
]
|
|
140
|
+
}),
|
|
141
|
+
/*#__PURE__*/ _jsx(InvoiceSendDialog, {
|
|
142
|
+
open: sending,
|
|
143
|
+
onClose: ()=>setSending(false),
|
|
144
|
+
hostId: hostId,
|
|
145
|
+
orderId: orderId,
|
|
146
|
+
order: order
|
|
122
147
|
})
|
|
123
148
|
]
|
|
124
149
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/order-invoice.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\n'use client'\n\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { Button, Menu, MenuItem } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport type * as CommerceModel from '../../model'\nimport { buildOrderInvoiceHtml, invoiceStoreFrom } from '../../utils/order-invoice'\nimport { downloadCommercePdf } from './commerce-pdf-download'\n\nexport interface OrderInvoiceButtonProps {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n}\n\n/**\n * \"Invoice\" (AGL-3611), beside \"Packing slip\" in the order dialog: a menu of\n * \"Print invoice\", the order as a printable bill, and \"Download PDF\"\n * (AGL-4095), the branded invoice the server makes in the site's colors with\n * its logo (`commerce/order-print?kind=invoice-pdf`, \"Manage orders\"). The\n * store's name, currency and footer are read when one is clicked, not while\n * the dialog is open, so the dialog listens to nothing more.\n */\nexport function OrderInvoiceButton(props: OrderInvoiceButtonProps) {\n const { hostId, orderId, order } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n const [anchor, setAnchor] = useState<HTMLElement | null>(null)\n\n const handleDownload = useCallback(async () => {\n setAnchor(null)\n setBusy(true)\n try {\n const query = new URLSearchParams({ hostId, orderId, kind: 'invoice-pdf' })\n const refused = await downloadCommercePdf(\n user,\n `/api/commerce/order-print?${query.toString()}`,\n { method: 'GET' },\n `invoice-${order.number ?? orderId.slice(-6)}.pdf`,\n )\n if (refused) enqueueSnackbar(refused, { variant: 'error', allowDuplicate: true })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, orderId, order.number, enqueueSnackbar])\n\n const handleInvoice = useCallback(async () => {\n setAnchor(null)\n // Opened before the reads, inside the click, so a popup blocker sees the\n // user's gesture.\n const win = window.open('', '_blank', 'width=720,height=900')\n if (!win) return\n setBusy(true)\n try {\n const [host, store] = await Promise.all([\n getDoc(doc(firestore, 'hosts', hostId)).catch(() => null),\n getDoc(doc(firestore, 'hosts', hostId, 'settings', 'store')).catch(() => null),\n ])\n const html = buildOrderInvoiceHtml({\n order,\n orderId,\n store: invoiceStoreFrom(\n host?.data() as Record<string, unknown> | undefined,\n store?.data() as Record<string, unknown> | undefined,\n ),\n })\n // Every value in `html` is escaped by the builder (AGL-2283).\n win.document.write(html)\n win.document.close()\n // Print from the opener, not an injected script: the popup inherits\n // the console's CSP (AGL-523).\n win.focus()\n win.print()\n } finally {\n setBusy(false)\n }\n }, [firestore, hostId, orderId, order])\n\n return (\n <>\n <Button\n disabled={busy}\n aria-haspopup=\"menu\"\n aria-expanded={anchor ? 'true' : undefined}\n onClick={(event) => setAnchor(event.currentTarget)}\n >\n {'Invoice'}\n </Button>\n <Menu anchorEl={anchor} open={Boolean(anchor)} onClose={() => setAnchor(null)}>\n <MenuItem onClick={() => void handleInvoice()}>{'Print invoice'}</MenuItem>\n <MenuItem onClick={() => void handleDownload()}>{'Download PDF'}</MenuItem>\n </Menu>\n </>\n )\n}\nOrderInvoiceButton.displayName = 'OrderInvoiceButton'\n\nexport default OrderInvoiceButton\n"],"names":["useSnackbar","useFirestore","useUser","Button","Menu","MenuItem","doc","getDoc","useCallback","useState","buildOrderInvoiceHtml","invoiceStoreFrom","downloadCommercePdf","OrderInvoiceButton","props","hostId","orderId","order","firestore","data","user","enqueueSnackbar","busy","setBusy","anchor","setAnchor","handleDownload","query","URLSearchParams","kind","refused","toString","method","number","slice","variant","allowDuplicate","handleInvoice","win","window","open","host","store","Promise","all","catch","html","document","write","close","focus","print","disabled","aria-haspopup","aria-expanded","undefined","onClick","event","currentTarget","anchorEl","Boolean","onClose","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,MAAM,EAAEC,IAAI,EAAEC,QAAQ,QAAQ,gBAAe;
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/order-invoice.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\n'use client'\n\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useUser } from '@aglyn/tenant-feature-instance'\nimport { Button, ListItemText, Menu, MenuItem } from '@mui/material'\nimport { doc, getDoc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport type * as CommerceModel from '../../model'\nimport { commerceSitePermissionRefusal } from '../../model/plugin-permissions'\nimport { buildOrderInvoiceHtml, invoiceStoreFrom } from '../../utils/order-invoice'\nimport { downloadCommercePdf } from './commerce-pdf-download'\nimport { InvoiceSendDialog } from './invoice-send.component'\n\nexport interface OrderInvoiceButtonProps {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n /**\n * Holds \"Send quotes and invoices to customers\" (`commerce.quotes.send`),\n * which Send invoice asks (AGL-4099). Absent reads as held: the route decides.\n */\n canSend?: boolean\n}\n\n/**\n * \"Invoice\" (AGL-3611), beside \"Packing slip\" in the order dialog: a menu of\n * \"Print invoice\", the order as a printable bill, and \"Download PDF\"\n * (AGL-4095), the branded invoice the server makes in the site's colors with\n * its logo (`commerce/order-print?kind=invoice-pdf`, \"Manage orders\"). The\n * store's name, currency and footer are read when one is clicked, not while\n * the dialog is open, so the dialog listens to nothing more.\n *\n * \"Send invoice\" (AGL-4099) emails it to the customer with the PDF attached:\n * an unpaid order's with a Pay button to its lasting pay link, a paid one's\n * as the record (`invoice-send.component.tsx`).\n */\nexport function OrderInvoiceButton(props: OrderInvoiceButtonProps) {\n const { hostId, orderId, order, canSend = true } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const [busy, setBusy] = useState(false)\n const [anchor, setAnchor] = useState<HTMLElement | null>(null)\n const [sending, setSending] = useState(false)\n\n const handleDownload = useCallback(async () => {\n setAnchor(null)\n setBusy(true)\n try {\n const query = new URLSearchParams({ hostId, orderId, kind: 'invoice-pdf' })\n const refused = await downloadCommercePdf(\n user,\n `/api/commerce/order-print?${query.toString()}`,\n { method: 'GET' },\n `invoice-${order.number ?? orderId.slice(-6)}.pdf`,\n )\n if (refused) enqueueSnackbar(refused, { variant: 'error', allowDuplicate: true })\n } finally {\n setBusy(false)\n }\n }, [user, hostId, orderId, order.number, enqueueSnackbar])\n\n const handleInvoice = useCallback(async () => {\n setAnchor(null)\n // Opened before the reads, inside the click, so a popup blocker sees the\n // user's gesture.\n const win = window.open('', '_blank', 'width=720,height=900')\n if (!win) return\n setBusy(true)\n try {\n const [host, store] = await Promise.all([\n getDoc(doc(firestore, 'hosts', hostId)).catch(() => null),\n getDoc(doc(firestore, 'hosts', hostId, 'settings', 'store')).catch(() => null),\n ])\n const html = buildOrderInvoiceHtml({\n order,\n orderId,\n store: invoiceStoreFrom(\n host?.data() as Record<string, unknown> | undefined,\n store?.data() as Record<string, unknown> | undefined,\n ),\n })\n // Every value in `html` is escaped by the builder (AGL-2283).\n win.document.write(html)\n win.document.close()\n // Print from the opener, not an injected script: the popup inherits\n // the console's CSP (AGL-523).\n win.focus()\n win.print()\n } finally {\n setBusy(false)\n }\n }, [firestore, hostId, orderId, order])\n\n return (\n <>\n <Button\n disabled={busy}\n aria-haspopup=\"menu\"\n aria-expanded={anchor ? 'true' : undefined}\n onClick={(event) => setAnchor(event.currentTarget)}\n >\n {'Invoice'}\n </Button>\n <Menu anchorEl={anchor} open={Boolean(anchor)} onClose={() => setAnchor(null)}>\n <MenuItem onClick={() => void handleInvoice()}>{'Print invoice'}</MenuItem>\n <MenuItem onClick={() => void handleDownload()}>{'Download PDF'}</MenuItem>\n <MenuItem\n disabled={!canSend}\n onClick={() => {\n setAnchor(null)\n setSending(true)\n }}\n >\n <ListItemText\n primary=\"Send invoice\"\n secondary={canSend ? undefined : commerceSitePermissionRefusal('commerce.quotes.send')}\n />\n </MenuItem>\n </Menu>\n <InvoiceSendDialog\n open={sending}\n onClose={() => setSending(false)}\n hostId={hostId}\n orderId={orderId}\n order={order}\n />\n </>\n )\n}\nOrderInvoiceButton.displayName = 'OrderInvoiceButton'\n\nexport default OrderInvoiceButton\n"],"names":["useSnackbar","useFirestore","useUser","Button","ListItemText","Menu","MenuItem","doc","getDoc","useCallback","useState","commerceSitePermissionRefusal","buildOrderInvoiceHtml","invoiceStoreFrom","downloadCommercePdf","InvoiceSendDialog","OrderInvoiceButton","props","hostId","orderId","order","canSend","firestore","data","user","enqueueSnackbar","busy","setBusy","anchor","setAnchor","sending","setSending","handleDownload","query","URLSearchParams","kind","refused","toString","method","number","slice","variant","allowDuplicate","handleInvoice","win","window","open","host","store","Promise","all","catch","html","document","write","close","focus","print","disabled","aria-haspopup","aria-expanded","undefined","onClick","event","currentTarget","anchorEl","Boolean","onClose","primary","secondary","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,SAASA,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,OAAO,QAAQ,iCAAgC;AACtE,SAASC,MAAM,EAAEC,YAAY,EAAEC,IAAI,EAAEC,QAAQ,QAAQ,gBAAe;AACpE,SAASC,GAAG,EAAEC,MAAM,QAAQ,qBAAoB;AAChD,SAASC,WAAW,EAAEC,QAAQ,QAAQ,QAAO;AAE7C,SAASC,6BAA6B,QAAQ,oCAAgC;AAC9E,SAASC,qBAAqB,EAAEC,gBAAgB,QAAQ,+BAA2B;AACnF,SAASC,mBAAmB,QAAQ,6BAAyB;AAC7D,SAASC,iBAAiB,QAAQ,8BAA0B;AAa5D;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,mBAAmBC,KAA8B;IAC/D,MAAM,EAAEC,MAAM,EAAEC,OAAO,EAAEC,KAAK,EAAEC,UAAU,IAAI,EAAE,GAAGJ;IACnD,MAAMK,YAAYrB;IAClB,MAAM,EAAEsB,MAAMC,IAAI,EAAE,GAAGtB;IACvB,MAAM,EAAEuB,eAAe,EAAE,GAAGzB;IAC5B,MAAM,CAAC0B,MAAMC,QAAQ,GAAGjB,SAAS;IACjC,MAAM,CAACkB,QAAQC,UAAU,GAAGnB,SAA6B;IACzD,MAAM,CAACoB,SAASC,WAAW,GAAGrB,SAAS;IAEvC,MAAMsB,iBAAiBvB,YAAY;QACjCoB,UAAU;QACVF,QAAQ;QACR,IAAI;gBAMWP;YALb,MAAMa,QAAQ,IAAIC,gBA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BACViC,iBAAc;gBACdC,iBAAehC,SAAS,SAASiC;gBACjCC,SAAS,CAACC,QAAUlC,UAAUkC,MAAMC,aAAa;0BAEhD;;0BAEH,MAAC3D;gBAAK4D,UAAUrC;gBAAQkB,MAAMoB,QAAQtC;gBAASuC,SAAS,IAAMtC,UAAU;;kCACtE,KAACvB;wBAASwD,SAAS,IAAM,KAAKnB;kCAAkB;;kCAChD,KAACrC;wBAASwD,SAAS,IAAM,KAAK9B;kCAAmB;;kCACjD,KAAC1B;wBACCoD,UAAU,CAACrC;wBACXyC,SAAS;4BACPjC,UAAU;4BACVE,WAAW;wBACb;kCAEA,cAAA,KAAC3B;4BACCgE,SAAQ;4BACRC,WAAWhD,UAAUwC,YAAYlD,8BAA8B;;;;;0BAIrE,KAACI;gBACC+B,MAAMhB;gBACNqC,SAAS,IAAMpC,WAAW;gBAC1Bb,QAAQA;gBACRC,SAASA;gBACTC,OAAOA;;;;AAIf;AACAJ,mBAAmBsD,WAAW,GAAG;AAEjC,eAAetD,mBAAkB"}
|
|
@@ -80,7 +80,7 @@ function soldOut(variant) {
|
|
|
80
80
|
]);
|
|
81
81
|
if (!product) return null;
|
|
82
82
|
const variant = options.length > 0 ? variantFor(product, picked) : product.variants.find((item)=>item.id === variantId);
|
|
83
|
-
const chosen = CommerceModel.resolveLineModifiers(product, modifiers);
|
|
83
|
+
const chosen = CommerceModel.resolveLineModifiers(product, modifiers, variant == null ? void 0 : variant.id);
|
|
84
84
|
const unitCents = variant ? Math.round(Number(variant.priceUsd) * 100) + (chosen.ok ? chosen.extraCents : 0) : 0;
|
|
85
85
|
const missing = groups.find((group)=>modifiers.filter((pick)=>pick.groupId === group.id).length < group.min);
|
|
86
86
|
const canAdd = Boolean(variant) && chosen.ok && quantity >= 1 && !(props.blockSoldOut && soldOut(variant));
|
|
@@ -228,7 +228,8 @@ function soldOut(variant) {
|
|
|
228
228
|
children: group.options.map((option)=>{
|
|
229
229
|
const selected = modifiers.some((pick)=>pick.groupId === group.id && pick.optionId === option.id);
|
|
230
230
|
return /*#__PURE__*/ _jsx(Chip, {
|
|
231
|
-
label:
|
|
231
|
+
label: // A choice priced by variant shows its price on this one (AGL-4100).
|
|
232
|
+
CommerceModel.modifierOptionPriceCents(option, variant == null ? void 0 : variant.id) ? `${option.name} +${money(CommerceModel.modifierOptionPriceCents(option, variant == null ? void 0 : variant.id))}` : option.name,
|
|
232
233
|
color: selected ? 'primary' : 'default',
|
|
233
234
|
variant: selected ? 'filled' : 'outlined',
|
|
234
235
|
"aria-pressed": selected,
|