@aglyn/plugins-commerce 1.29.2 → 1.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/console/pos/pos-item-dialog.component.js +12 -0
- package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.js +3 -5
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +11 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +229 -13
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +51 -14
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +38 -0
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/product-add-ons.d.ts +21 -0
- package/src/lib/components/product-add-ons.js +77 -1
- package/src/lib/components/product-add-ons.js.map +1 -1
- package/src/lib/components/product-builder-mockup.d.ts +1 -1
- package/src/lib/components/product-builder-mockup.js +17 -5
- package/src/lib/components/product-builder-mockup.js.map +1 -1
- package/src/lib/components/product-choice-cards.js +14 -2
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/model/commerce-pos-kiosk.js +8 -2
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/commerce-pos-offline.d.ts +1 -1
- package/src/lib/model/commerce-pos-offline.js +8 -2
- package/src/lib/model/commerce-pos-offline.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +1 -0
- package/src/lib/model/commerce-quote-request.js +6 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.js +10 -5
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce-record-routes.d.ts +13 -1
- package/src/lib/model/commerce-record-routes.js +22 -2
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce.js +1 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +53 -2
- package/src/lib/model/product-modifiers.js +127 -27
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/plan-entitlements.d.ts +1 -2
- package/src/lib/plan-entitlements.js +3 -12
- package/src/lib/plan-entitlements.js.map +1 -1
- package/src/lib/server/pos-kiosk.js +1 -4
- package/src/lib/server/pos-kiosk.js.map +1 -1
- package/src/lib/server/product.d.ts +5 -0
- package/src/lib/server/product.js +10 -2
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/site-page-resolver.d.ts +12 -1
- package/src/lib/server/site-page-resolver.js +100 -9
- package/src/lib/server/site-page-resolver.js.map +1 -1
- package/src/lib/server.js +4 -2
- package/src/lib/server.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +7 -0
- package/src/lib/transfer/product-register-cells.js +88 -10
- package/src/lib/transfer/product-register-cells.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/quote-editor-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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport { posMoney } from '../../model/commerce-pos-ops'\nimport { commerceSitePermissionRefusal } from '../../model/plugin-permissions'\nimport { useMediaPicker, type PickedMedia } from '@aglyn/aglyn/app-utils/media-picker-context'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useFirestore, useFirestoreDoc, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogContentText,\n DialogTitle,\n Divider,\n FormControlLabel,\n FormHelperText,\n List,\n ListItemButton,\n ListItemText,\n MenuItem,\n Paper,\n Stack,\n Switch,\n TextField,\n Typography,\n type Theme,\n} from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { downloadCommercePdf } from './commerce-pdf-download'\nimport { PayLinkReadinessNoticeFor } from './pay-link-readiness-notice.component'\nimport { QuotePayLinkSection } from './quote-pay-link.component'\nimport { QuoteMessagesSection } from './quote-messages.component'\nimport { QuoteProofsSection, QuoteRequestFilesSection } from './quote-proofs.component'\nimport { QuoteSendSection } from './quote-send.component'\n\n/** A quote as the list reads it: the order document and its id. */\nexport type QuoteRow = CommerceModel.HostOrder & { $id: string }\n\nexport interface QuoteEditorDialogProps {\n hostId: string\n /** The quote to edit, or `null` for a new one. */\n quote: QuoteRow | null\n /** The store's products, for the product picker. */\n products: readonly Record<string, any>[]\n /** Holds \"Create and edit quotes\" (`commerce.quotes`). */\n canEdit: boolean\n /** Holds \"Send quotes and invoices to customers\" (`commerce.quotes.send`). */\n canSend: boolean\n /**\n * What a NEW quote opens with when it is started from a request or a\n * contact (AGL-4098). The editable fields are filled in; a request's own\n * parts (which request, its files, its conversation) are stamped by the\n * server from `from` when the quote is created, never from here.\n */\n start?: QuoteEditorStart | null\n onClose: () => void\n}\n\n/** A new quote's start: from a request (with what it carried) or from a contact. */\nexport interface QuoteEditorStart {\n /** The request it is started from, which the server reads again on create; null for a contact. */\n from: { kind: 'submission'; id: string } | null\n prefill: CommerceModel.QuoteStartPrefill\n /** The request, as the editor says where the quote came from. */\n request?: { formName: string; receivedAtMs: number | null } | null\n files?: ReadonlyArray<{ id: string; name: string; contentType: string; size: number }>\n /** Whether the request started an email conversation the quote's first email will reply into. */\n threaded?: boolean\n}\n\nconst REFUSAL = commerceSitePermissionRefusal('commerce.quotes')\nconst SEARCH_DEBOUNCE_MS = 250\n\nconst money = (cents: number): string => posMoney(cents)\n\n/** Field widths on a wide screen, from the theme's spacing; full width on a phone. */\nconst narrowField = (theme: Theme) => ({ maxWidth: { sm: theme.spacing(16) } })\nconst mediumField = (theme: Theme) => ({ minWidth: { sm: theme.spacing(20) }, maxWidth: { sm: theme.spacing(24) } })\n\n/** Dollars typed into a field, as whole cents, or `null` when it is not an amount. */\nfunction centsOf(text: string): number | null {\n const trimmed = text.trim()\n if (!trimmed) return 0\n if (!/^\\d+(\\.\\d{0,2})?$/.test(trimmed)) return null\n return Math.round(Number(trimmed) * 100)\n}\n\nconst dollarsOf = (cents: number | undefined): string =>\n cents ? (cents / 100).toFixed(2).replace(/\\.00$/, '') : ''\n\ntype AddressForm = Record<'name' | 'line1' | 'line2' | 'city' | 'state' | 'postalCode' | 'country', string>\n\nfunction addressForm(address: CommerceModel.OrderAddress | null | undefined): AddressForm {\n return {\n name: address?.name ?? '',\n line1: address?.line1 ?? '',\n line2: address?.line2 ?? '',\n city: address?.city ?? '',\n state: address?.state ?? '',\n postalCode: address?.postalCode ?? '',\n country: address?.country ?? '',\n }\n}\n\ntype LineForm =\n | {\n key: string\n kind: 'catalog'\n productId: string\n variantId: string\n quantity: string\n modifiers: CommerceModel.ModifierSelection[]\n description: string\n included: boolean\n }\n | {\n key: string\n kind: 'custom'\n name: string\n description: string\n sku: string\n price: string\n quantity: string\n ships: boolean\n included: boolean\n }\n\ninterface QuoteForm {\n lines: LineForm[]\n customer: { record: { kind: string; id: string } | null; name: string; company: string; email: string; phone: string }\n shipTo: AddressForm\n billTo: AddressForm\n discountKind: 'none' | 'amount' | 'percent'\n discountValue: string\n shipping: string\n notes: string\n terms: string\n requireProofApproval: boolean\n /** A customer with a site account signs in to see the proof (AGL-4206). */\n requireProofSignIn: boolean\n}\n\nlet lineSequence = 0\nconst nextLineKey = () => `line-${++lineSequence}`\n\nfunction formFromQuote(quote: QuoteRow | null, requireProofApproval: boolean): QuoteForm {\n const section = quote?.quote\n const discount = section?.discount ?? null\n return {\n lines: (quote?.lineItems ?? []).map((line): LineForm => {\n const request = CommerceModel.quoteLineRequestFromLine(line)\n return request.kind === 'custom'\n ? {\n key: nextLineKey(),\n kind: 'custom',\n name: request.name,\n description: request.description ?? '',\n sku: request.sku ?? '',\n price: dollarsOf(request.unitAmountCents),\n quantity: String(request.quantity),\n ships: request.ships !== false,\n included: request.included === true,\n }\n : {\n key: nextLineKey(),\n kind: 'catalog',\n productId: request.productId,\n variantId: request.variantId ?? '',\n quantity: String(request.quantity),\n modifiers: request.modifiers ?? [],\n description: request.description ?? '',\n included: request.included === true,\n }\n }),\n customer: {\n record: section?.customer?.record ?? null,\n name: section?.customer?.name ?? '',\n company: section?.customer?.company ?? '',\n email: section?.customer?.email ?? '',\n phone: section?.customer?.phone ?? '',\n },\n shipTo: addressForm(section?.shipTo),\n billTo: addressForm(section?.billTo),\n discountKind: discount?.kind ?? 'none',\n discountValue:\n discount?.kind === 'amount' ? dollarsOf(discount.amountCents) : discount?.kind === 'percent' ? String(discount.pct) : '',\n shipping: dollarsOf(section?.shipping?.amountCents),\n notes: section?.notes ?? '',\n terms: section?.terms ?? '',\n requireProofApproval: section ? section.requireProofApproval === true : requireProofApproval,\n // A new quote takes the store's default where the dialog applies it (below).\n requireProofSignIn: section?.requireProofSignIn === true,\n }\n}\n\n/** A new quote's form, filled in from where it was started (AGL-4098). */\nfunction formFromStart(start: QuoteEditorStart, requireProofApproval: boolean): QuoteForm {\n const blank = formFromQuote(null, requireProofApproval)\n const { customer, lines, notes } = start.prefill\n return {\n ...blank,\n customer: {\n record: customer.record ?? null,\n name: customer.name ?? '',\n company: customer.company ?? '',\n email: customer.email ?? '',\n phone: customer.phone ?? '',\n },\n lines: lines.map(\n (line): LineForm => ({\n key: nextLineKey(),\n kind: 'catalog',\n productId: line.productId,\n variantId: line.variantId ?? '',\n quantity: String(line.quantity || 1),\n modifiers: line.modifiers ?? [],\n description: line.description ?? '',\n included: line.included === true,\n }),\n ),\n notes: notes ?? '',\n }\n}\n\nfunction lineRequest(line: LineForm): CommerceModel.QuoteLineRequest {\n const quantity = Number(line.quantity)\n if (line.kind === 'catalog') {\n return {\n kind: 'catalog',\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n quantity,\n ...(line.modifiers.length ? { modifiers: line.modifiers } : {}),\n ...(line.included ? { included: true } : {}),\n ...(line.description.trim() ? { description: line.description.trim() } : {}),\n }\n }\n return {\n kind: 'custom',\n name: line.name.trim(),\n ...(line.description.trim() ? { description: line.description.trim() } : {}),\n ...(line.sku.trim() ? { sku: line.sku.trim() } : {}),\n unitAmountCents: line.included ? 0 : (centsOf(line.price) ?? Number.NaN),\n quantity,\n ships: line.ships,\n ...(line.included ? { included: true } : {}),\n }\n}\n\nfunction addressBody(address: AddressForm): Partial<AddressForm> | null {\n const entries = Object.entries(address).filter(([, value]) => value.trim())\n return entries.length ? Object.fromEntries(entries.map(([key, value]) => [key, value.trim()])) : null\n}\n\n/** What the server is sent: choices, never what a product costs. */\nfunction quoteBody(form: QuoteForm): Record<string, unknown> {\n const discountCents = centsOf(form.discountValue)\n // With no lines there is nothing to discount or ship (AGL-4184).\n const priced = form.lines.length > 0\n return {\n lines: form.lines.map(lineRequest),\n customer: {\n ...(form.customer.record ? { record: form.customer.record } : {}),\n name: form.customer.name,\n company: form.customer.company,\n email: form.customer.email,\n phone: form.customer.phone,\n },\n shipTo: addressBody(form.shipTo),\n billTo: addressBody(form.billTo),\n discount: !priced\n ? null\n : form.discountKind === 'amount'\n ? { kind: 'amount', amountCents: discountCents ?? Number.NaN }\n : form.discountKind === 'percent'\n ? { kind: 'percent', pct: Number(form.discountValue || 0) }\n : null,\n shipping: priced && form.shipping.trim() ? { amountCents: centsOf(form.shipping) ?? Number.NaN } : null,\n notes: form.notes,\n terms: form.terms,\n requireProofApproval: form.requireProofApproval,\n requireProofSignIn: form.requireProofSignIn,\n }\n}\n\ninterface FoundCustomer {\n record: { kind: string; id: string }\n name: string\n company: string\n email: string | null\n phone: string | null\n}\n\n/**\n * The quote editor (AGL-4093): who it is for, its lines (products with their\n * options and add-ons, typed items, things included at no charge), discount,\n * shipping, notes and terms, with the totals worked out as it is edited. The\n * server prices and saves it; the totals here are the same function's answer\n * over the same inputs, and a connected tax service's figure arrives on save.\n * A saved quote left as it is shows what its customer's page shows instead\n * (AGL-4162): that is what the customer is charged until a save re-prices it.\n *\n * A quote may be saved with no items when it has a proof (AGL-4184), which is\n * how a design goes out before it has a price: the editor then has no money to\n * show, and an item added later makes it a normal quote. A new quote has\n * nothing to upload a proof for yet, so it takes its first from the media library.\n */\nexport function QuoteEditorDialog(props: QuoteEditorDialogProps) {\n const { hostId, quote, products, canEdit, canSend, onClose } = props\n const start = quote ? null : (props.start ?? null)\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { pickMedia } = useMediaPicker()\n /** A new quote's proofs, chosen from the media library and kept when it is created. */\n const [libraryProofs, setLibraryProofs] = useState<PickedMedia[]>([])\n const { data: store } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const storeDefault = CommerceModel.quoteRequiresProofApprovalByDefault(store?.quotes)\n const [form, setForm] = useState<QuoteForm>(() =>\n start ? formFromStart(start, storeDefault) : formFromQuote(quote, storeDefault),\n )\n // The version this form was opened on. A change saved elsewhere while it is\n // open arrives on `quote`; the save still names this one, so the server\n // refuses rather than overwrite that change. A proof added or a revision\n // started here (AGL-4096) moves it, and the save names the new one.\n const [baseUpdatedAtMs, setBaseUpdatedAtMs] = useState(() => quote?.quote?.updatedAtMs)\n const [busy, setBusy] = useState(false)\n const [confirmingDelete, setConfirmingDelete] = useState(false)\n /** Whether anything has been changed since the dialog opened. */\n const [edited, setEdited] = useState(false)\n /** Whether the proof-approval switch was set by hand. */\n const [approvalSet, setApprovalSet] = useState(false)\n // A new quote starts with the store's default, which may arrive after the\n // dialog opens; a switch set by hand keeps its setting.\n const requireProofApproval = quote || approvalSet ? form.requireProofApproval : storeDefault\n /** Whether the sign-in switch was set by hand (AGL-4206); until then a new quote shows the store's default. */\n const [signInSet, setSignInSet] = useState(false)\n const signInDefault = CommerceModel.quoteRequiresProofSignInByDefault(store?.quotes)\n const requireProofSignIn = quote || signInSet ? form.requireProofSignIn : signInDefault\n\n const update = useCallback((patch: Partial<QuoteForm>) => {\n setEdited(true)\n if ('requireProofApproval' in patch) setApprovalSet(true)\n if ('requireProofSignIn' in patch) setSignInSet(true)\n setForm((prev) => ({ ...prev, ...patch }))\n }, [])\n const updateLine = useCallback((key: string, patch: Partial<LineForm>) => {\n setEdited(true)\n setForm((prev) => ({\n ...prev,\n lines: prev.lines.map((line) => (line.key === key ? ({ ...line, ...patch } as LineForm) : line)),\n }))\n }, [])\n\n /*\n * One attempt per change (AGL-1697's rule): a retried Save presents the same\n * key and is answered from the first, an edited quote is a new attempt.\n */\n const attemptKey = useRef('')\n useEffect(() => {\n attemptKey.current = ''\n }, [form, libraryProofs])\n\n const proofOnly =\n form.lines.length === 0 && (libraryProofs.length > 0 || CommerceModel.currentQuoteProofs(quote?.quote).length > 0)\n\n const chooseLibraryProof = useCallback(async () => {\n const picked = await pickMedia?.({ allowPrivate: true })\n if (!picked) return\n const problem = CommerceModel.quoteLibraryProofProblem(picked)\n if (problem) return void enqueueSnackbar(problem, { variant: 'error', allowDuplicate: true })\n setEdited(true)\n setLibraryProofs((prev) =>\n prev.some((entry) => entry.mediaId === picked.mediaId && entry.mediaScope === picked.mediaScope) ? prev : [...prev, picked],\n )\n }, [pickMedia, enqueueSnackbar])\n\n const productsById = useMemo(\n () => new Map(products.map((product) => [String(product.$id), product])),\n [products],\n )\n\n /** Each line priced as the server will price it, or why it cannot be. */\n const priced = useMemo(\n () =>\n form.lines.map((line) => {\n const request = lineRequest(line)\n if (request.kind === 'custom') {\n if (!request.name) return { error: 'Name the item.' }\n if (!Number.isInteger(request.unitAmountCents)) return { error: 'Enter a price.' }\n if (!(request.quantity >= 1)) return { error: 'Enter a quantity.' }\n return { line: CommerceModel.priceQuoteCustomLine(request) }\n }\n if (!request.productId) return { error: 'Choose a product.' }\n if (!(request.quantity >= 1)) return { error: 'Enter a quantity.' }\n const answer = CommerceModel.priceQuoteCatalogLine(productsById.get(request.productId) as never, request)\n return 'error' in answer ? { error: answer.error } : { line: answer.line }\n }),\n [form.lines, productsById],\n )\n\n const discountCents = centsOf(form.discountValue)\n const discount: CommerceModel.QuoteDiscount | null =\n form.discountKind === 'amount' && discountCents\n ? { kind: 'amount', amountCents: discountCents }\n : form.discountKind === 'percent' && Number(form.discountValue) > 0\n ? { kind: 'percent', pct: Math.min(100, Number(form.discountValue)) }\n : null\n const shippingCents = centsOf(form.shipping) ?? 0\n const taxBasis = CommerceModel.quoteTaxBasisFromSettings(store?.tax, {\n country: form.shipTo.country.trim().toUpperCase(),\n state: form.shipTo.state.trim(),\n })\n const pricedLines = priced.flatMap((entry) => ('line' in entry && entry.line ? [entry.line] : []))\n const totals = CommerceModel.computeQuoteTotals({ lines: pricedLines, discount, shippingCents, tax: taxBasis })\n const problems = priced.some((entry) => 'error' in entry)\n // Every save re-prices the lines and re-bases the tax on the store's settings\n // (`priceQuote` in `server/quote.ts`), so any edit shows what that save will\n // store. Until then a saved quote is what its customer's page says, from the\n // stored lines under `quotePayTax`, and a paid one its recorded totals.\n const asSaved =\n quote && !edited\n ? CommerceModel.buildQuotePageView({\n order: quote,\n orderId: quote.$id,\n storeName: '',\n currency: '',\n store: CommerceModel.payLinkStoreOf(store),\n })\n : null\n\n const save = useCallback(async () => {\n setBusy(true)\n try {\n if (!attemptKey.current) {\n attemptKey.current = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n }\n const response = await authorizedFetch(user, '/api/commerce/quote', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey.current },\n body: JSON.stringify({\n action: quote ? 'update' : 'create',\n hostId,\n ...(quote ? { quoteId: quote.$id, baseUpdatedAtMs } : {}),\n // A request's parts are read again by the server from here (AGL-4098).\n ...(!quote && start?.from ? { from: start.from } : {}),\n quote: quoteBody({ ...form, requireProofApproval, requireProofSignIn }),\n ...(!quote && libraryProofs.length\n ? { libraryProofs: libraryProofs.map(({ mediaScope, mediaId }) => ({ mediaScope, mediaId })) }\n : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'The quote could not be saved', { variant: 'error', allowDuplicate: true })\n }\n enqueueSnackbar(`${CommerceModel.formatQuoteNumber({ number: payload.number ?? undefined }, payload.quoteId)} saved`, {\n variant: 'success',\n persist: false,\n })\n onClose()\n } finally {\n setBusy(false)\n }\n }, [user, quote, hostId, baseUpdatedAtMs, start, form, requireProofApproval, requireProofSignIn, libraryProofs, enqueueSnackbar, onClose])\n\n const remove = useCallback(async () => {\n if (!quote) return\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/quote', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ action: 'delete', hostId, quoteId: quote.$id }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'The quote could not be deleted', { variant: 'error', allowDuplicate: true })\n }\n enqueueSnackbar(`${CommerceModel.formatQuoteNumber(quote, quote.$id)} deleted`, { variant: 'success', persist: false })\n setConfirmingDelete(false)\n onClose()\n } finally {\n setBusy(false)\n }\n }, [user, quote, hostId, enqueueSnackbar, onClose])\n\n const [downloading, setDownloading] = useState(false)\n const downloadPdf = useCallback(async () => {\n if (!quote) return\n setDownloading(true)\n try {\n const refused = await downloadCommercePdf(\n user,\n '/api/commerce/quote',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ action: 'pdf', hostId, quoteId: quote.$id }),\n },\n `quote-${quote.number ?? quote.$id.slice(-6)}.pdf`,\n )\n if (refused) enqueueSnackbar(refused, { variant: 'error', allowDuplicate: true })\n } finally {\n setDownloading(false)\n }\n }, [user, quote, hostId, enqueueSnackbar])\n\n const readOnly = !canEdit || busy\n const paid = quote ? !CommerceModel.isUnpaidQuote(quote) : false\n const title = quote ? CommerceModel.formatQuoteNumber(quote, quote.$id) : 'New quote'\n const status = quote ? CommerceModel.quoteDisplayStatus(quote) : null\n const deletable = Boolean(quote) && !paid && (quote?.quote?.stage ?? 'draft') === 'draft'\n\n return (\n <Dialog open onClose={busy ? undefined : onClose} maxWidth=\"md\" fullWidth scroll=\"paper\" aria-labelledby=\"quote-editor-title\">\n <DialogTitle id=\"quote-editor-title\">\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <span>{title}</span>\n {status ? (\n <Chip size=\"small\" variant=\"outlined\" label={status.label} color={CommerceModel.QUOTE_STATUS_COLOR[status.key]} />\n ) : null}\n {proofOnly ? <Chip size=\"small\" variant=\"outlined\" label=\"Proof only\" /> : null}\n </Stack>\n </DialogTitle>\n <DialogContent dividers>\n <Stack spacing={3}>\n {paid ? (\n <Alert severity=\"success\">\n {quote?.quote?.paidAtMs\n ? `Paid ${new Date(quote.quote.paidAtMs).toLocaleDateString()}. It is an order now and can no longer be changed.`\n : 'This quote has been paid, so it is an order now and can no longer be changed.'}\n </Alert>\n ) : null}\n {quote ? (\n <QuoteSendSection hostId={hostId} quoteId={quote.$id} quote={quote} canSend={canSend} edited={edited} />\n ) : null}\n {quote ? (\n <QuotePayLinkSection hostId={hostId} quoteId={quote.$id} quote={quote} canSend={canSend} edited={edited} />\n ) : null}\n {quote ? (\n <QuoteProofsSection\n hostId={hostId}\n quoteId={quote.$id}\n quote={quote}\n canEdit={canEdit}\n onEdited={(updatedAtMs) => {\n if (updatedAtMs) setBaseUpdatedAtMs(updatedAtMs)\n }}\n />\n ) : null}\n {/* The conversation with the customer (AGL-4207), kept with the quote through every revision. */}\n {quote ? <QuoteMessagesSection hostId={hostId} quoteId={quote.$id} quote={quote} canSend={canSend} /> : null}\n {/* Where it came from (AGL-4098): the request, its files and its conversation. */}\n {start?.request ? (\n <QuoteStartedFromRequest\n formName={start.request.formName}\n receivedAtMs={start.request.receivedAtMs}\n files={start.files ?? []}\n threaded={start.threaded === true}\n />\n ) : null}\n {quote?.quote?.request ? (\n <QuoteRequestFilesSection hostId={hostId} quoteId={quote.$id} quote={quote} />\n ) : null}\n {/* A saved quote's notice sits with its pay link, above; a new one's here. */}\n {quote || proofOnly ? null : <PayLinkReadinessNoticeFor hostId={hostId} order={null} noun=\"quote\" />}\n\n <QuoteCustomerSection\n hostId={hostId}\n form={form}\n disabled={readOnly || paid}\n onChange={(customer) => update({ customer })}\n />\n\n {!quote && pickMedia ? (\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Proofs'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Sending a design before it has a price? Choose a proof and leave the items empty. ' +\n 'Your customer sees the proof with no prices, and can approve it or reject it with changes. Add items whenever you’re ready.'}\n </Typography>\n {libraryProofs.length ? (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {libraryProofs.map((proof) => (\n <Chip\n key={`${proof.mediaScope}-${proof.mediaId}`}\n size=\"small\"\n variant=\"outlined\"\n label={proof.fileName || 'Proof'}\n onDelete={readOnly ? undefined : () => setLibraryProofs((prev) => prev.filter((entry) => entry !== proof))}\n />\n ))}\n </Stack>\n ) : null}\n <BlockedControl blocked={!canEdit} reason={REFUSAL}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy || libraryProofs.length >= CommerceModel.QUOTE_MAX_PROOFS}\n onClick={() => void chooseLibraryProof()}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'From media library'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : null}\n\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Items'}</Typography>\n {form.lines.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Add products from your catalog, or type an item that is made to order.'}\n </Typography>\n ) : null}\n {form.lines.map((line, index) => (\n <QuoteLineEditor\n key={line.key}\n line={line}\n priced={priced[index]}\n products={products}\n disabled={readOnly || paid}\n onChange={(patch) => updateLine(line.key, patch)}\n onRemove={() => update({ lines: form.lines.filter((entry) => entry.key !== line.key) })}\n />\n ))}\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <Button\n size=\"small\"\n disabled={readOnly || paid || products.length === 0}\n onClick={() =>\n update({\n lines: [\n ...form.lines,\n { key: nextLineKey(), kind: 'catalog', productId: '', variantId: '', quantity: '1', modifiers: [], description: '', included: false },\n ],\n })\n }\n >\n {'Add product'}\n </Button>\n <Button\n size=\"small\"\n disabled={readOnly || paid}\n onClick={() =>\n update({\n lines: [\n ...form.lines,\n { key: nextLineKey(), kind: 'custom', name: '', description: '', sku: '', price: '', quantity: '1', ships: true, included: false },\n ],\n })\n }\n >\n {'Add custom item'}\n </Button>\n </Stack>\n </Stack>\n\n {proofOnly ? null : (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField\n label=\"Discount\"\n select\n size=\"small\"\n value={form.discountKind}\n disabled={readOnly || paid}\n onChange={(event) => update({ discountKind: event.target.value as QuoteForm['discountKind'] })}\n sx={mediumField}\n >\n <MenuItem value=\"none\">{'None'}</MenuItem>\n <MenuItem value=\"amount\">{'Amount off'}</MenuItem>\n <MenuItem value=\"percent\">{'Percent off'}</MenuItem>\n </TextField>\n {form.discountKind !== 'none' ? (\n <TextField\n label={form.discountKind === 'amount' ? 'Amount ($)' : 'Percent (%)'}\n size=\"small\"\n value={form.discountValue}\n disabled={readOnly || paid}\n onChange={(event) => update({ discountValue: event.target.value })}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n error={form.discountKind === 'amount' ? centsOf(form.discountValue) === null : !(Number(form.discountValue) >= 0 && Number(form.discountValue) <= 100)}\n />\n ) : null}\n <TextField\n label=\"Shipping ($)\"\n size=\"small\"\n value={form.shipping}\n disabled={readOnly || paid}\n onChange={(event) => update({ shipping: event.target.value })}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n error={centsOf(form.shipping) === null}\n helperText=\"Leave empty when nothing ships.\"\n />\n </Stack>\n )}\n\n <QuoteAddressFields\n label=\"Ship to\"\n value={form.shipTo}\n disabled={readOnly || paid}\n helperText=\"Where the order goes. Store tax rates use its state and country.\"\n onChange={(shipTo) => update({ shipTo })}\n />\n <QuoteAddressFields\n label=\"Bill to\"\n value={form.billTo}\n disabled={readOnly || paid}\n onChange={(billTo) => update({ billTo })}\n />\n\n <Stack spacing={2}>\n <TextField\n label=\"Notes for the customer\"\n multiline\n minRows={2}\n value={form.notes}\n disabled={readOnly || paid}\n onChange={(event) => update({ notes: event.target.value })}\n />\n <TextField\n label=\"Terms\"\n multiline\n minRows={2}\n value={form.terms}\n disabled={readOnly || paid}\n onChange={(event) => update({ terms: event.target.value })}\n />\n {proofOnly ? null : (\n <FormControlLabel\n control={\n <Switch\n checked={requireProofApproval}\n disabled={readOnly || paid}\n onChange={(event) => update({ requireProofApproval: event.target.checked })}\n />\n }\n label=\"Customers approve the proof before they can pay\"\n />\n )}\n <Stack spacing={0}>\n <FormControlLabel\n control={\n <Switch\n checked={requireProofSignIn}\n disabled={readOnly || paid}\n onChange={(event) => update({ requireProofSignIn: event.target.checked })}\n />\n }\n label=\"Customers sign in to see and approve proofs\"\n />\n <FormHelperText sx={{ mt: 0 }}>\n {'For a customer with an account on your site. A customer without one keeps using the private link.'}\n </FormHelperText>\n </Stack>\n </Stack>\n\n {proofOnly ? null : (\n <>\n <Divider />\n <QuoteTotalsSummary\n totals={asSaved?.totals ?? totals}\n taxLabel={asSaved?.taxLabel ?? CommerceModel.describeQuoteTax(taxBasis)}\n taxAtPayment={asSaved?.taxAtPayment ?? totals.taxAtPayment}\n />\n </>\n )}\n </Stack>\n </DialogContent>\n <DialogActions sx={{ flexWrap: 'wrap', rowGap: 1 }}>\n {deletable ? (\n <BlockedControl blocked={!canEdit} reason={REFUSAL}>\n <Button color=\"error\" disabled={busy} onClick={() => setConfirmingDelete(true)} sx={{ mr: 'auto' }}>\n {'Delete'}\n </Button>\n </BlockedControl>\n ) : null}\n {quote && !proofOnly ? (\n <BlockedControl\n blocked={!canEdit || edited}\n reason={edited ? 'Save your changes first: the PDF shows the quote as it was last saved.' : REFUSAL}\n >\n <Button disabled={busy || downloading} onClick={() => void downloadPdf()}>\n {downloading ? 'Making PDF…' : 'Download PDF'}\n </Button>\n </BlockedControl>\n ) : null}\n <Button onClick={onClose} disabled={busy}>\n {paid || !canEdit ? 'Close' : 'Cancel'}\n </Button>\n {paid ? null : (\n <BlockedControl blocked={!canEdit} reason={REFUSAL}>\n <Button\n variant=\"contained\"\n disabled={busy || (form.lines.length === 0 && !proofOnly) || problems}\n onClick={() => void save()}\n >\n {quote ? 'Save' : proofOnly ? 'Create proof' : 'Create quote'}\n </Button>\n </BlockedControl>\n )}\n </DialogActions>\n <Dialog open={confirmingDelete} onClose={() => setConfirmingDelete(false)} maxWidth=\"xs\" fullWidth>\n <DialogTitle>{`Delete ${title}?`}</DialogTitle>\n <DialogContent>\n <DialogContentText>{'The quote and everything on it is removed. This can’t be undone.'}</DialogContentText>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setConfirmingDelete(false)} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button color=\"error\" variant=\"contained\" disabled={busy} onClick={() => void remove()}>\n {'Delete'}\n </Button>\n </DialogActions>\n </Dialog>\n </Dialog>\n )\n}\nQuoteEditorDialog.displayName = 'QuoteEditorDialog'\n\n/** A new quote's request (AGL-4098): which form sent it and when, its files by name, and its conversation. */\nfunction QuoteStartedFromRequest(props: {\n formName: string\n receivedAtMs: number | null\n files: ReadonlyArray<{ id: string; name: string; size: number }>\n threaded: boolean\n}) {\n const { formName, receivedAtMs, files, threaded } = props\n const when = receivedAtMs\n ? ` on ${new Date(receivedAtMs).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}`\n : ''\n return (\n <Alert severity=\"info\">\n <Stack spacing={1}>\n <Typography variant=\"body2\">{`From a request sent through “${formName}”${when}.`}</Typography>\n {files.length ? (\n <Stack spacing={0.5}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Their files, kept on the quote as the customer’s:'}\n </Typography>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {files.map((file) => (\n <Chip key={file.id} size=\"small\" variant=\"outlined\" label={file.name} />\n ))}\n </Stack>\n </Stack>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {threaded\n ? 'When you email the quote, it replies to the confirmation they were sent, in the same conversation.'\n : 'They weren’t sent a confirmation, so the quote’s email starts the conversation.'}\n </Typography>\n </Stack>\n </Alert>\n )\n}\n\n/** Who the quote is for: a person the workspace keeps, or details typed here. */\nfunction QuoteCustomerSection(props: {\n hostId: string\n form: QuoteForm\n disabled: boolean\n onChange: (customer: QuoteForm['customer']) => void\n}) {\n const { hostId, form, disabled, onChange } = props\n const { data: user } = useUser()\n const [text, setText] = useState('')\n const [found, setFound] = useState<FoundCustomer[]>([])\n const [available, setAvailable] = useState(true)\n const ticket = useRef(0)\n const customer = form.customer\n\n useEffect(() => {\n const typed = text.trim()\n if (typed.length < 2 || !user) {\n // Only when something is listed, so an effect that re-runs settles.\n setFound((prev) => (prev.length ? [] : prev))\n return\n }\n const mine = ++ticket.current\n const timer = window.setTimeout(() => {\n void authorizedFetch(user, '/api/commerce/quote', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ action: 'search-customers', hostId, text: typed }),\n })\n .then((response) => response.json().catch(() => ({})))\n .then((payload) => {\n if (mine !== ticket.current) return\n setAvailable(payload?.available !== false)\n setFound(Array.isArray(payload?.customers) ? payload.customers : [])\n })\n .catch(() => undefined)\n }, SEARCH_DEBOUNCE_MS)\n return () => window.clearTimeout(timer)\n }, [text, user, hostId])\n\n const pick = (person: FoundCustomer) => {\n onChange({\n record: person.record,\n name: person.name,\n company: person.company,\n email: person.email ?? '',\n phone: person.phone ?? '',\n })\n setText('')\n setFound([])\n }\n\n return (\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Customer'}</Typography>\n {customer.record ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Chip\n color=\"primary\"\n variant=\"outlined\"\n label={customer.name || customer.email || 'Contact'}\n onDelete={disabled ? undefined : () => onChange({ ...customer, record: null })}\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'From your contacts'}\n </Typography>\n </Stack>\n ) : available ? (\n <Box>\n <TextField\n size=\"small\"\n fullWidth\n label=\"Find a contact\"\n placeholder=\"Name, email or phone\"\n value={text}\n disabled={disabled}\n onChange={(event) => setText(event.target.value)}\n />\n {found.length ? (\n <Paper variant=\"outlined\" sx={{ mt: 0.5 }}>\n <List dense disablePadding>\n {found.map((person) => (\n <ListItemButton key={`${person.record.kind}:${person.record.id}`} onClick={() => pick(person)}>\n <ListItemText\n primary={person.name || person.email || 'Contact'}\n secondary={[person.company, person.email, person.phone].filter(Boolean).join(' · ')}\n />\n </ListItemButton>\n ))}\n </List>\n </Paper>\n ) : null}\n </Box>\n ) : null}\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField size=\"small\" fullWidth label=\"Name\" value={customer.name} disabled={disabled} onChange={(event) => onChange({ ...customer, name: event.target.value })} />\n <TextField size=\"small\" fullWidth label=\"Company\" value={customer.company} disabled={disabled} onChange={(event) => onChange({ ...customer, company: event.target.value })} />\n </Stack>\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField size=\"small\" fullWidth label=\"Email\" type=\"email\" value={customer.email} disabled={disabled} onChange={(event) => onChange({ ...customer, email: event.target.value })} />\n <TextField size=\"small\" fullWidth label=\"Phone\" value={customer.phone} disabled={disabled} onChange={(event) => onChange({ ...customer, phone: event.target.value })} />\n </Stack>\n </Stack>\n )\n}\n\n/** One address on the quote. */\nfunction QuoteAddressFields(props: {\n label: string\n value: AddressForm\n disabled: boolean\n helperText?: string\n onChange: (value: AddressForm) => void\n}) {\n const { label, value, disabled, helperText, onChange } = props\n const field = (key: keyof AddressForm, fieldLabel: string, extra: Record<string, unknown> = {}) => (\n <TextField\n size=\"small\"\n fullWidth\n label={fieldLabel}\n value={value[key]}\n disabled={disabled}\n onChange={(event) => onChange({ ...value, [key]: event.target.value })}\n {...extra}\n />\n )\n return (\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{label}</Typography>\n {helperText ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {helperText}\n </Typography>\n ) : null}\n {field('name', 'Name')}\n {field('line1', 'Address')}\n {field('line2', 'Apartment, suite, unit')}\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n {field('city', 'City')}\n {field('state', 'State or region')}\n {field('postalCode', 'Postal code')}\n {field('country', 'Country code', { placeholder: 'US', slotProps: { htmlInput: { maxLength: 2 } } })}\n </Stack>\n </Stack>\n )\n}\n\n/** One line of the quote: a product with its options and add-ons, or a typed item. */\nfunction QuoteLineEditor(props: {\n line: LineForm\n priced: { line?: CommerceModel.PricedQuoteLine; error?: string } | undefined\n products: readonly Record<string, any>[]\n disabled: boolean\n onChange: (patch: Partial<LineForm>) => void\n onRemove: () => void\n}) {\n const { line, priced, products, disabled, onChange, onRemove } = props\n const product = line.kind === 'catalog' ? products.find((entry) => String(entry.$id) === line.productId) : undefined\n const lifted = product ? CommerceModel.liftLegacyProduct(product) : null\n const groups = lifted ? CommerceModel.productModifierGroups(lifted) : []\n const lineCents = priced?.line ? CommerceModel.quoteLineCents(priced.line) : 0\n\n return (\n <Paper variant=\"outlined\" sx={{ p: 2 }}>\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <Stack spacing={1.5} sx={{ flex: 1, minWidth: 0 }}>\n {line.kind === 'catalog' ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField\n label=\"Product\"\n select\n size=\"small\"\n fullWidth\n value={line.productId}\n disabled={disabled}\n onChange={(event) => onChange({ productId: event.target.value, variantId: '', modifiers: [] })}\n >\n {products.map((entry) => (\n <MenuItem key={String(entry.$id)} value={String(entry.$id)}>\n {String(entry.name ?? entry.$id)}\n </MenuItem>\n ))}\n </TextField>\n {lifted && lifted.variants.length > 1 ? (\n <TextField\n label=\"Option\"\n select\n size=\"small\"\n fullWidth\n value={line.variantId || lifted.variants[0]?.id || ''}\n disabled={disabled}\n onChange={(event) => onChange({ variantId: event.target.value })}\n >\n {lifted.variants.map((variant) => (\n <MenuItem key={variant.id} value={variant.id}>\n {Object.values(variant.options ?? {}).join(' / ') || 'Default'}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n </Stack>\n ) : (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField\n label=\"Item\"\n size=\"small\"\n fullWidth\n value={line.name}\n disabled={disabled}\n onChange={(event) => onChange({ name: event.target.value })}\n />\n <TextField\n label=\"SKU (optional)\"\n size=\"small\"\n value={line.sku}\n disabled={disabled}\n onChange={(event) => onChange({ sku: event.target.value })}\n />\n </Stack>\n )}\n {groups.map((group) => {\n const chosen = line.kind === 'catalog' ? line.modifiers.filter((pick) => pick.groupId === group.id).map((pick) => pick.optionId) : []\n return (\n <TextField\n key={group.id}\n label={CommerceModel.modifierGroupRequired(group) ? group.name : `${group.name} (optional)`}\n select\n size=\"small\"\n fullWidth\n value={group.max > 1 ? chosen : (chosen[0] ?? '')}\n disabled={disabled}\n slotProps={{ select: { multiple: group.max > 1 } }}\n onChange={(event) => {\n const raw = event.target.value as unknown\n const picked = (Array.isArray(raw) ? raw : raw ? [raw] : []).map(String)\n if (line.kind !== 'catalog') return\n onChange({\n modifiers: [\n ...line.modifiers.filter((pick) => pick.groupId !== group.id),\n ...picked.map((optionId) => ({ groupId: group.id, optionId })),\n ],\n })\n }}\n >\n {group.max > 1 ? null : <MenuItem value=\"\">{'None'}</MenuItem>}\n {group.options.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {CommerceModel.quoteModifierOptionLabel(option, line.kind === 'catalog' ? line.variantId : null, money)}\n </MenuItem>\n ))}\n </TextField>\n )\n })}\n <TextField\n label=\"Description (optional)\"\n size=\"small\"\n fullWidth\n multiline\n value={line.description}\n disabled={disabled}\n onChange={(event) => onChange({ description: event.target.value })}\n />\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ alignItems: { sm: 'center' } }}>\n <TextField\n label=\"Quantity\"\n size=\"small\"\n value={line.quantity}\n disabled={disabled}\n onChange={(event) => onChange({ quantity: event.target.value.replace(/[^0-9]/g, '') })}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n sx={narrowField}\n />\n {line.kind === 'custom' ? (\n <TextField\n label=\"Unit price ($)\"\n size=\"small\"\n value={line.included ? '' : line.price}\n disabled={disabled || line.included}\n onChange={(event) => onChange({ price: event.target.value })}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n error={!line.included && centsOf(line.price) === null}\n sx={mediumField}\n />\n ) : null}\n {line.kind === 'custom' ? (\n <FormControlLabel\n control={<Switch checked={line.ships} disabled={disabled} onChange={(event) => onChange({ ships: event.target.checked })} />}\n label=\"Ships\"\n />\n ) : null}\n <FormControlLabel\n control={\n <Switch checked={line.included} disabled={disabled} onChange={(event) => onChange({ included: event.target.checked })} />\n }\n label=\"Included at no charge\"\n />\n </Stack>\n </Stack>\n <Stack sx={{ alignItems: 'flex-end', flexShrink: 0 }}>\n <Button size=\"small\" color=\"inherit\" disabled={disabled} onClick={onRemove}>\n {'Remove'}\n </Button>\n <Typography variant=\"body2\" sx={{ fontWeight: 'fontWeightMedium' }}>\n {line.included ? 'Included' : money(lineCents)}\n </Typography>\n {priced?.line && !line.included && priced.line.quantity > 1 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`${money(priced.line.unitAmountCents)} each`}\n </Typography>\n ) : null}\n </Stack>\n </Stack>\n {priced?.error ? (\n <Typography variant=\"caption\" color=\"error\">\n {priced.error}\n </Typography>\n ) : null}\n </Stack>\n </Paper>\n )\n}\n\n/** The quote's totals, as the customer will read them. */\nfunction QuoteTotalsSummary(props: {\n totals: CommerceModel.QuotePageView['totals']\n taxLabel: string\n /** Stripe Tax works the tax out when the customer pays, so there is no figure yet. */\n taxAtPayment: boolean\n}) {\n const { totals, taxLabel, taxAtPayment } = props\n const row = (label: string, value: string, strong = false) => (\n <Stack direction=\"row\" sx={{ justifyContent: 'space-between' }}>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'}>{value}</Typography>\n </Stack>\n )\n return (\n <Stack spacing={0.5} sx={(theme) => ({ alignSelf: { sm: 'flex-end' }, minWidth: { sm: theme.spacing(40) } })}>\n {row('Items', money(totals.itemsCents))}\n {totals.discountCents ? row('Discount', `−${money(totals.discountCents)}`) : null}\n {totals.shippingCents ? row('Shipping', money(totals.shippingCents)) : null}\n {taxAtPayment ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {taxLabel}\n </Typography>\n ) : (\n row(taxLabel, money(totals.taxCents))\n )}\n {row(taxAtPayment ? 'Total before tax' : 'Total', money(totals.totalCents), true)}\n </Stack>\n )\n}\n\nexport default QuoteEditorDialog\n"],"names":["CommerceModel","posMoney","commerceSitePermissionRefusal","useMediaPicker","BlockedControl","useSnackbar","authorizedFetch","useFirestore","useFirestoreDoc","useUser","Alert","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogContentText","DialogTitle","Divider","FormControlLabel","FormHelperText","List","ListItemButton","ListItemText","MenuItem","Paper","Stack","Switch","TextField","Typography","doc","useCallback","useEffect","useMemo","useRef","useState","downloadCommercePdf","PayLinkReadinessNoticeFor","QuotePayLinkSection","QuoteMessagesSection","QuoteProofsSection","QuoteRequestFilesSection","QuoteSendSection","REFUSAL","SEARCH_DEBOUNCE_MS","money","cents","narrowField","theme","maxWidth","sm","spacing","mediumField","minWidth","centsOf","text","trimmed","trim","test","Math","round","Number","dollarsOf","toFixed","replace","addressForm","address","name","line1","line2","city","state","postalCode","country","lineSequence","nextLineKey","formFromQuote","quote","requireProofApproval","section","discount","lines","lineItems","map","line","request","quoteLineRequestFromLine","kind","key","description","sku","price","unitAmountCents","quantity","String","ships","included","productId","variantId","modifiers","customer","record","company","email","phone","shipTo","billTo","discountKind","discountValue","amountCents","pct","shipping","notes","terms","requireProofSignIn","formFromStart","start","blank","prefill","lineRequest","length","NaN","addressBody","entries","Object","filter","value","fromEntries","quoteBody","form","discountCents","priced","QuoteEditorDialog","props","hostId","products","canEdit","canSend","onClose","firestore","data","user","enqueueSnackbar","pickMedia","libraryProofs","setLibraryProofs","store","storeDefault","quoteRequiresProofApprovalByDefault","quotes","setForm","baseUpdatedAtMs","setBaseUpdatedAtMs","updatedAtMs","busy","setBusy","confirmingDelete","setConfirmingDelete","edited","setEdited","approvalSet","setApprovalSet","signInSet","setSignInSet","signInDefault","quoteRequiresProofSignInByDefault","update","patch","prev","updateLine","attemptKey","current","proofOnly","currentQuoteProofs","chooseLibraryProof","picked","allowPrivate","problem","quoteLibraryProofProblem","variant","allowDuplicate","some","entry","mediaId","mediaScope","productsById","Map","product","$id","error","isInteger","priceQuoteCustomLine","answer","priceQuoteCatalogLine","get","min","shippingCents","taxBasis","quoteTaxBasisFromSettings","tax","toUpperCase","pricedLines","flatMap","totals","computeQuoteTotals","problems","asSaved","buildQuotePageView","order","orderId","storeName","currency","payLinkStoreOf","save","payload","globalThis","crypto","randomUUID","Date","now","random","toString","slice","response","method","headers","body","JSON","stringify","action","quoteId","from","json","catch","ok","formatQuoteNumber","number","undefined","persist","remove","downloading","setDownloading","downloadPdf","refused","readOnly","paid","isUnpaidQuote","title","status","quoteDisplayStatus","deletable","Boolean","stage","open","fullWidth","scroll","aria-labelledby","id","direction","sx","alignItems","span","size","label","color","QUOTE_STATUS_COLOR","dividers","severity","paidAtMs","toLocaleDateString","onEdited","QuoteStartedFromRequest","formName","receivedAtMs","files","threaded","noun","QuoteCustomerSection","disabled","onChange","useFlexGap","flexWrap","proof","fileName","onDelete","blocked","reason","QUOTE_MAX_PROOFS","onClick","alignSelf","index","QuoteLineEditor","onRemove","xs","select","event","target","slotProps","htmlInput","inputMode","helperText","QuoteAddressFields","multiline","minRows","control","checked","mt","QuoteTotalsSummary","taxLabel","describeQuoteTax","taxAtPayment","rowGap","mr","displayName","when","toLocaleString","dateStyle","timeStyle","file","setText","found","setFound","available","setAvailable","ticket","typed","mine","timer","window","setTimeout","then","Array","isArray","customers","clearTimeout","pick","person","placeholder","dense","disablePadding","primary","secondary","join","type","field","fieldLabel","extra","maxLength","lifted","find","liftLegacyProduct","groups","productModifierGroups","lineCents","quoteLineCents","p","flex","variants","values","options","group","chosen","groupId","optionId","modifierGroupRequired","max","multiple","raw","option","quoteModifierOptionLabel","flexShrink","fontWeight","row","strong","justifyContent","itemsCents","taxCents","totalCents"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,QAAQ,QAAQ,kCAA8B;AACvD,SAASC,6BAA6B,QAAQ,oCAAgC;AAC9E,SAASC,cAAc,QAA0B,8CAA6C;AAC9F,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,YAAY,EAAEC,eAAe,EAAEC,OAAO,QAAQ,iCAAgC;AACvF,SACEC,KAAK,EACLC,GAAG,EACHC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,iBAAiB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AAa,GAAGkP,IAAI,YAAY,CAAC,CAAC,EAAEvU,MAAM8J,OAAOzE,aAAa,GAAG,IAAI;YAC5EyE,OAAOP,aAAa,GAAGgL,IAAI,YAAYvU,MAAM8J,OAAOP,aAAa,KAAK;YACtEkH,6BACC,KAACzR;gBAAWsJ,SAAQ;gBAAQqF,OAAM;0BAC/B4C;iBAGHgE,IAAIhE,UAAUvQ,MAAM8J,OAAO6K,QAAQ;YAEpCJ,IAAI9D,eAAe,qBAAqB,SAASzQ,MAAM8J,OAAO8K,UAAU,GAAG;;;AAGlF;AAEA,eAAerP,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/quote-editor-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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport { posMoney } from '../../model/commerce-pos-ops'\nimport { commerceSitePermissionRefusal } from '../../model/plugin-permissions'\nimport { useMediaPicker, type PickedMedia } from '@aglyn/aglyn/app-utils/media-picker-context'\nimport { BlockedControl } from '@aglyn/shared-ui-jsx/components/blocked-control.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { useFirestore, useFirestoreDoc, useUser } from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Box,\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogContentText,\n DialogTitle,\n Divider,\n FormControlLabel,\n FormHelperText,\n List,\n ListItemButton,\n ListItemText,\n MenuItem,\n Paper,\n Stack,\n Switch,\n TextField,\n Typography,\n type Theme,\n} from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { downloadCommercePdf } from './commerce-pdf-download'\nimport { PayLinkReadinessNoticeFor } from './pay-link-readiness-notice.component'\nimport { QuotePayLinkSection } from './quote-pay-link.component'\nimport { QuoteMessagesSection } from './quote-messages.component'\nimport { QuoteProofsSection, QuoteRequestFilesSection } from './quote-proofs.component'\nimport { QuoteSendSection } from './quote-send.component'\n\n/** A quote as the list reads it: the order document and its id. */\nexport type QuoteRow = CommerceModel.HostOrder & { $id: string }\n\nexport interface QuoteEditorDialogProps {\n hostId: string\n /** The quote to edit, or `null` for a new one. */\n quote: QuoteRow | null\n /** The store's products, for the product picker. */\n products: readonly Record<string, any>[]\n /** Holds \"Create and edit quotes\" (`commerce.quotes`). */\n canEdit: boolean\n /** Holds \"Send quotes and invoices to customers\" (`commerce.quotes.send`). */\n canSend: boolean\n /**\n * What a NEW quote opens with when it is started from a request or a\n * contact (AGL-4098). The editable fields are filled in; a request's own\n * parts (which request, its files, its conversation) are stamped by the\n * server from `from` when the quote is created, never from here.\n */\n start?: QuoteEditorStart | null\n onClose: () => void\n}\n\n/** A new quote's start: from a request (with what it carried) or from a contact. */\nexport interface QuoteEditorStart {\n /** The request it is started from, which the server reads again on create; null for a contact. */\n from: { kind: 'submission'; id: string } | null\n prefill: CommerceModel.QuoteStartPrefill\n /** The request, as the editor says where the quote came from. */\n request?: { formName: string; receivedAtMs: number | null } | null\n files?: ReadonlyArray<{ id: string; name: string; contentType: string; size: number }>\n /** Whether the request started an email conversation the quote's first email will reply into. */\n threaded?: boolean\n}\n\nconst REFUSAL = commerceSitePermissionRefusal('commerce.quotes')\nconst SEARCH_DEBOUNCE_MS = 250\n\nconst money = (cents: number): string => posMoney(cents)\n\n/** Field widths on a wide screen, from the theme's spacing; full width on a phone. */\nconst narrowField = (theme: Theme) => ({ maxWidth: { sm: theme.spacing(16) } })\nconst mediumField = (theme: Theme) => ({ minWidth: { sm: theme.spacing(20) }, maxWidth: { sm: theme.spacing(24) } })\n\n/** Dollars typed into a field, as whole cents, or `null` when it is not an amount. */\nfunction centsOf(text: string): number | null {\n const trimmed = text.trim()\n if (!trimmed) return 0\n if (!/^\\d+(\\.\\d{0,2})?$/.test(trimmed)) return null\n return Math.round(Number(trimmed) * 100)\n}\n\nconst dollarsOf = (cents: number | undefined): string =>\n cents ? (cents / 100).toFixed(2).replace(/\\.00$/, '') : ''\n\ntype AddressForm = Record<'name' | 'line1' | 'line2' | 'city' | 'state' | 'postalCode' | 'country', string>\n\nfunction addressForm(address: CommerceModel.OrderAddress | null | undefined): AddressForm {\n return {\n name: address?.name ?? '',\n line1: address?.line1 ?? '',\n line2: address?.line2 ?? '',\n city: address?.city ?? '',\n state: address?.state ?? '',\n postalCode: address?.postalCode ?? '',\n country: address?.country ?? '',\n }\n}\n\ntype LineForm =\n | {\n key: string\n kind: 'catalog'\n productId: string\n variantId: string\n quantity: string\n modifiers: CommerceModel.ModifierSelection[]\n description: string\n included: boolean\n }\n | {\n key: string\n kind: 'custom'\n name: string\n description: string\n sku: string\n price: string\n quantity: string\n ships: boolean\n included: boolean\n }\n\ninterface QuoteForm {\n lines: LineForm[]\n customer: { record: { kind: string; id: string } | null; name: string; company: string; email: string; phone: string }\n shipTo: AddressForm\n billTo: AddressForm\n discountKind: 'none' | 'amount' | 'percent'\n discountValue: string\n shipping: string\n notes: string\n terms: string\n requireProofApproval: boolean\n /** A customer with a site account signs in to see the proof (AGL-4206). */\n requireProofSignIn: boolean\n}\n\nlet lineSequence = 0\nconst nextLineKey = () => `line-${++lineSequence}`\n\nfunction formFromQuote(quote: QuoteRow | null, requireProofApproval: boolean): QuoteForm {\n const section = quote?.quote\n const discount = section?.discount ?? null\n return {\n lines: (quote?.lineItems ?? []).map((line): LineForm => {\n const request = CommerceModel.quoteLineRequestFromLine(line)\n return request.kind === 'custom'\n ? {\n key: nextLineKey(),\n kind: 'custom',\n name: request.name,\n description: request.description ?? '',\n sku: request.sku ?? '',\n price: dollarsOf(request.unitAmountCents),\n quantity: String(request.quantity),\n ships: request.ships !== false,\n included: request.included === true,\n }\n : {\n key: nextLineKey(),\n kind: 'catalog',\n productId: request.productId,\n variantId: request.variantId ?? '',\n quantity: String(request.quantity),\n modifiers: request.modifiers ?? [],\n description: request.description ?? '',\n included: request.included === true,\n }\n }),\n customer: {\n record: section?.customer?.record ?? null,\n name: section?.customer?.name ?? '',\n company: section?.customer?.company ?? '',\n email: section?.customer?.email ?? '',\n phone: section?.customer?.phone ?? '',\n },\n shipTo: addressForm(section?.shipTo),\n billTo: addressForm(section?.billTo),\n discountKind: discount?.kind ?? 'none',\n discountValue:\n discount?.kind === 'amount' ? dollarsOf(discount.amountCents) : discount?.kind === 'percent' ? String(discount.pct) : '',\n shipping: dollarsOf(section?.shipping?.amountCents),\n notes: section?.notes ?? '',\n terms: section?.terms ?? '',\n requireProofApproval: section ? section.requireProofApproval === true : requireProofApproval,\n // A new quote takes the store's default where the dialog applies it (below).\n requireProofSignIn: section?.requireProofSignIn === true,\n }\n}\n\n/** A new quote's form, filled in from where it was started (AGL-4098). */\nfunction formFromStart(start: QuoteEditorStart, requireProofApproval: boolean): QuoteForm {\n const blank = formFromQuote(null, requireProofApproval)\n const { customer, lines, notes } = start.prefill\n return {\n ...blank,\n customer: {\n record: customer.record ?? null,\n name: customer.name ?? '',\n company: customer.company ?? '',\n email: customer.email ?? '',\n phone: customer.phone ?? '',\n },\n lines: lines.map(\n (line): LineForm => ({\n key: nextLineKey(),\n kind: 'catalog',\n productId: line.productId,\n variantId: line.variantId ?? '',\n quantity: String(line.quantity || 1),\n modifiers: line.modifiers ?? [],\n description: line.description ?? '',\n included: line.included === true,\n }),\n ),\n notes: notes ?? '',\n }\n}\n\nfunction lineRequest(line: LineForm): CommerceModel.QuoteLineRequest {\n const quantity = Number(line.quantity)\n if (line.kind === 'catalog') {\n return {\n kind: 'catalog',\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n quantity,\n ...(line.modifiers.length ? { modifiers: line.modifiers } : {}),\n ...(line.included ? { included: true } : {}),\n ...(line.description.trim() ? { description: line.description.trim() } : {}),\n }\n }\n return {\n kind: 'custom',\n name: line.name.trim(),\n ...(line.description.trim() ? { description: line.description.trim() } : {}),\n ...(line.sku.trim() ? { sku: line.sku.trim() } : {}),\n unitAmountCents: line.included ? 0 : (centsOf(line.price) ?? Number.NaN),\n quantity,\n ships: line.ships,\n ...(line.included ? { included: true } : {}),\n }\n}\n\nfunction addressBody(address: AddressForm): Partial<AddressForm> | null {\n const entries = Object.entries(address).filter(([, value]) => value.trim())\n return entries.length ? Object.fromEntries(entries.map(([key, value]) => [key, value.trim()])) : null\n}\n\n/** What the server is sent: choices, never what a product costs. */\nfunction quoteBody(form: QuoteForm): Record<string, unknown> {\n const discountCents = centsOf(form.discountValue)\n // With no lines there is nothing to discount or ship (AGL-4184).\n const priced = form.lines.length > 0\n return {\n lines: form.lines.map(lineRequest),\n customer: {\n ...(form.customer.record ? { record: form.customer.record } : {}),\n name: form.customer.name,\n company: form.customer.company,\n email: form.customer.email,\n phone: form.customer.phone,\n },\n shipTo: addressBody(form.shipTo),\n billTo: addressBody(form.billTo),\n discount: !priced\n ? null\n : form.discountKind === 'amount'\n ? { kind: 'amount', amountCents: discountCents ?? Number.NaN }\n : form.discountKind === 'percent'\n ? { kind: 'percent', pct: Number(form.discountValue || 0) }\n : null,\n shipping: priced && form.shipping.trim() ? { amountCents: centsOf(form.shipping) ?? Number.NaN } : null,\n notes: form.notes,\n terms: form.terms,\n requireProofApproval: form.requireProofApproval,\n requireProofSignIn: form.requireProofSignIn,\n }\n}\n\ninterface FoundCustomer {\n record: { kind: string; id: string }\n name: string\n company: string\n email: string | null\n phone: string | null\n}\n\n/**\n * The quote editor (AGL-4093): who it is for, its lines (products with their\n * options and add-ons, typed items, things included at no charge), discount,\n * shipping, notes and terms, with the totals worked out as it is edited. The\n * server prices and saves it; the totals here are the same function's answer\n * over the same inputs, and a connected tax service's figure arrives on save.\n * A saved quote left as it is shows what its customer's page shows instead\n * (AGL-4162): that is what the customer is charged until a save re-prices it.\n *\n * A quote may be saved with no items when it has a proof (AGL-4184), which is\n * how a design goes out before it has a price: the editor then has no money to\n * show, and an item added later makes it a normal quote. A new quote has\n * nothing to upload a proof for yet, so it takes its first from the media library.\n */\nexport function QuoteEditorDialog(props: QuoteEditorDialogProps) {\n const { hostId, quote, products, canEdit, canSend, onClose } = props\n const start = quote ? null : (props.start ?? null)\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { pickMedia } = useMediaPicker()\n /** A new quote's proofs, chosen from the media library and kept when it is created. */\n const [libraryProofs, setLibraryProofs] = useState<PickedMedia[]>([])\n const { data: store } = useFirestoreDoc<any>(\n () => doc(firestore, 'hosts', hostId, 'settings', 'store'),\n [firestore, hostId],\n )\n const storeDefault = CommerceModel.quoteRequiresProofApprovalByDefault(store?.quotes)\n const [form, setForm] = useState<QuoteForm>(() =>\n start ? formFromStart(start, storeDefault) : formFromQuote(quote, storeDefault),\n )\n // The version this form was opened on. A change saved elsewhere while it is\n // open arrives on `quote`; the save still names this one, so the server\n // refuses rather than overwrite that change. A proof added or a revision\n // started here (AGL-4096) moves it, and the save names the new one.\n const [baseUpdatedAtMs, setBaseUpdatedAtMs] = useState(() => quote?.quote?.updatedAtMs)\n const [busy, setBusy] = useState(false)\n const [confirmingDelete, setConfirmingDelete] = useState(false)\n /** Whether anything has been changed since the dialog opened. */\n const [edited, setEdited] = useState(false)\n /** Whether the proof-approval switch was set by hand. */\n const [approvalSet, setApprovalSet] = useState(false)\n // A new quote starts with the store's default, which may arrive after the\n // dialog opens; a switch set by hand keeps its setting.\n const requireProofApproval = quote || approvalSet ? form.requireProofApproval : storeDefault\n /** Whether the sign-in switch was set by hand (AGL-4206); until then a new quote shows the store's default. */\n const [signInSet, setSignInSet] = useState(false)\n const signInDefault = CommerceModel.quoteRequiresProofSignInByDefault(store?.quotes)\n const requireProofSignIn = quote || signInSet ? form.requireProofSignIn : signInDefault\n\n const update = useCallback((patch: Partial<QuoteForm>) => {\n setEdited(true)\n if ('requireProofApproval' in patch) setApprovalSet(true)\n if ('requireProofSignIn' in patch) setSignInSet(true)\n setForm((prev) => ({ ...prev, ...patch }))\n }, [])\n const updateLine = useCallback((key: string, patch: Partial<LineForm>) => {\n setEdited(true)\n setForm((prev) => ({\n ...prev,\n lines: prev.lines.map((line) => (line.key === key ? ({ ...line, ...patch } as LineForm) : line)),\n }))\n }, [])\n\n /*\n * One attempt per change (AGL-1697's rule): a retried Save presents the same\n * key and is answered from the first, an edited quote is a new attempt.\n */\n const attemptKey = useRef('')\n useEffect(() => {\n attemptKey.current = ''\n }, [form, libraryProofs])\n\n const proofOnly =\n form.lines.length === 0 && (libraryProofs.length > 0 || CommerceModel.currentQuoteProofs(quote?.quote).length > 0)\n\n const chooseLibraryProof = useCallback(async () => {\n const picked = await pickMedia?.({ allowPrivate: true })\n if (!picked) return\n const problem = CommerceModel.quoteLibraryProofProblem(picked)\n if (problem) return void enqueueSnackbar(problem, { variant: 'error', allowDuplicate: true })\n setEdited(true)\n setLibraryProofs((prev) =>\n prev.some((entry) => entry.mediaId === picked.mediaId && entry.mediaScope === picked.mediaScope) ? prev : [...prev, picked],\n )\n }, [pickMedia, enqueueSnackbar])\n\n const productsById = useMemo(\n () => new Map(products.map((product) => [String(product.$id), product])),\n [products],\n )\n\n /** Each line priced as the server will price it, or why it cannot be. */\n const priced = useMemo(\n () =>\n form.lines.map((line) => {\n const request = lineRequest(line)\n if (request.kind === 'custom') {\n if (!request.name) return { error: 'Name the item.' }\n if (!Number.isInteger(request.unitAmountCents)) return { error: 'Enter a price.' }\n if (!(request.quantity >= 1)) return { error: 'Enter a quantity.' }\n return { line: CommerceModel.priceQuoteCustomLine(request) }\n }\n if (!request.productId) return { error: 'Choose a product.' }\n if (!(request.quantity >= 1)) return { error: 'Enter a quantity.' }\n const answer = CommerceModel.priceQuoteCatalogLine(productsById.get(request.productId) as never, request)\n return 'error' in answer ? { error: answer.error } : { line: answer.line }\n }),\n [form.lines, productsById],\n )\n\n const discountCents = centsOf(form.discountValue)\n const discount: CommerceModel.QuoteDiscount | null =\n form.discountKind === 'amount' && discountCents\n ? { kind: 'amount', amountCents: discountCents }\n : form.discountKind === 'percent' && Number(form.discountValue) > 0\n ? { kind: 'percent', pct: Math.min(100, Number(form.discountValue)) }\n : null\n const shippingCents = centsOf(form.shipping) ?? 0\n const taxBasis = CommerceModel.quoteTaxBasisFromSettings(store?.tax, {\n country: form.shipTo.country.trim().toUpperCase(),\n state: form.shipTo.state.trim(),\n })\n const pricedLines = priced.flatMap((entry) => ('line' in entry && entry.line ? [entry.line] : []))\n const totals = CommerceModel.computeQuoteTotals({ lines: pricedLines, discount, shippingCents, tax: taxBasis })\n const problems = priced.some((entry) => 'error' in entry)\n // Every save re-prices the lines and re-bases the tax on the store's settings\n // (`priceQuote` in `server/quote.ts`), so any edit shows what that save will\n // store. Until then a saved quote is what its customer's page says, from the\n // stored lines under `quotePayTax`, and a paid one its recorded totals.\n const asSaved =\n quote && !edited\n ? CommerceModel.buildQuotePageView({\n order: quote,\n orderId: quote.$id,\n storeName: '',\n currency: '',\n store: CommerceModel.payLinkStoreOf(store),\n })\n : null\n\n const save = useCallback(async () => {\n setBusy(true)\n try {\n if (!attemptKey.current) {\n attemptKey.current = globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n }\n const response = await authorizedFetch(user, '/api/commerce/quote', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey.current },\n body: JSON.stringify({\n action: quote ? 'update' : 'create',\n hostId,\n ...(quote ? { quoteId: quote.$id, baseUpdatedAtMs } : {}),\n // A request's parts are read again by the server from here (AGL-4098).\n ...(!quote && start?.from ? { from: start.from } : {}),\n quote: quoteBody({ ...form, requireProofApproval, requireProofSignIn }),\n ...(!quote && libraryProofs.length\n ? { libraryProofs: libraryProofs.map(({ mediaScope, mediaId }) => ({ mediaScope, mediaId })) }\n : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'The quote could not be saved', { variant: 'error', allowDuplicate: true })\n }\n enqueueSnackbar(`${CommerceModel.formatQuoteNumber({ number: payload.number ?? undefined }, payload.quoteId)} saved`, {\n variant: 'success',\n persist: false,\n })\n onClose()\n } finally {\n setBusy(false)\n }\n }, [user, quote, hostId, baseUpdatedAtMs, start, form, requireProofApproval, requireProofSignIn, libraryProofs, enqueueSnackbar, onClose])\n\n const remove = useCallback(async () => {\n if (!quote) return\n setBusy(true)\n try {\n const response = await authorizedFetch(user, '/api/commerce/quote', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ action: 'delete', hostId, quoteId: quote.$id }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'The quote could not be deleted', { variant: 'error', allowDuplicate: true })\n }\n enqueueSnackbar(`${CommerceModel.formatQuoteNumber(quote, quote.$id)} deleted`, { variant: 'success', persist: false })\n setConfirmingDelete(false)\n onClose()\n } finally {\n setBusy(false)\n }\n }, [user, quote, hostId, enqueueSnackbar, onClose])\n\n const [downloading, setDownloading] = useState(false)\n const downloadPdf = useCallback(async () => {\n if (!quote) return\n setDownloading(true)\n try {\n const refused = await downloadCommercePdf(\n user,\n '/api/commerce/quote',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ action: 'pdf', hostId, quoteId: quote.$id }),\n },\n `quote-${quote.number ?? quote.$id.slice(-6)}.pdf`,\n )\n if (refused) enqueueSnackbar(refused, { variant: 'error', allowDuplicate: true })\n } finally {\n setDownloading(false)\n }\n }, [user, quote, hostId, enqueueSnackbar])\n\n const readOnly = !canEdit || busy\n const paid = quote ? !CommerceModel.isUnpaidQuote(quote) : false\n const title = quote ? CommerceModel.formatQuoteNumber(quote, quote.$id) : 'New quote'\n const status = quote ? CommerceModel.quoteDisplayStatus(quote) : null\n const deletable = Boolean(quote) && !paid && (quote?.quote?.stage ?? 'draft') === 'draft'\n\n return (\n <Dialog open onClose={busy ? undefined : onClose} maxWidth=\"md\" fullWidth scroll=\"paper\" aria-labelledby=\"quote-editor-title\">\n <DialogTitle id=\"quote-editor-title\">\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <span>{title}</span>\n {status ? (\n <Chip size=\"small\" variant=\"outlined\" label={status.label} color={CommerceModel.QUOTE_STATUS_COLOR[status.key]} />\n ) : null}\n {proofOnly ? <Chip size=\"small\" variant=\"outlined\" label=\"Proof only\" /> : null}\n </Stack>\n </DialogTitle>\n <DialogContent dividers>\n <Stack spacing={3}>\n {paid ? (\n <Alert severity=\"success\">\n {quote?.quote?.paidAtMs\n ? `Paid ${new Date(quote.quote.paidAtMs).toLocaleDateString()}. It is an order now and can no longer be changed.`\n : 'This quote has been paid, so it is an order now and can no longer be changed.'}\n </Alert>\n ) : null}\n {quote ? (\n <QuoteSendSection hostId={hostId} quoteId={quote.$id} quote={quote} canSend={canSend} edited={edited} />\n ) : null}\n {quote ? (\n <QuotePayLinkSection hostId={hostId} quoteId={quote.$id} quote={quote} canSend={canSend} edited={edited} />\n ) : null}\n {quote ? (\n <QuoteProofsSection\n hostId={hostId}\n quoteId={quote.$id}\n quote={quote}\n canEdit={canEdit}\n onEdited={(updatedAtMs) => {\n if (updatedAtMs) setBaseUpdatedAtMs(updatedAtMs)\n }}\n />\n ) : null}\n {/* The conversation with the customer (AGL-4207), kept with the quote through every revision. */}\n {quote ? <QuoteMessagesSection hostId={hostId} quoteId={quote.$id} quote={quote} canSend={canSend} /> : null}\n {/* Where it came from (AGL-4098): the request, its files and its conversation. */}\n {start?.request ? (\n <QuoteStartedFromRequest\n formName={start.request.formName}\n receivedAtMs={start.request.receivedAtMs}\n files={start.files ?? []}\n threaded={start.threaded === true}\n />\n ) : null}\n {quote?.quote?.request ? (\n <QuoteRequestFilesSection hostId={hostId} quoteId={quote.$id} quote={quote} />\n ) : null}\n {/* A saved quote's notice sits with its pay link, above; a new one's here. */}\n {quote || proofOnly ? null : <PayLinkReadinessNoticeFor hostId={hostId} order={null} noun=\"quote\" />}\n\n <QuoteCustomerSection\n hostId={hostId}\n form={form}\n disabled={readOnly || paid}\n onChange={(customer) => update({ customer })}\n />\n\n {!quote && pickMedia ? (\n <Stack spacing={1}>\n <Typography variant=\"subtitle2\">{'Proofs'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Sending a design before it has a price? Choose a proof and leave the items empty. ' +\n 'Your customer sees the proof with no prices, and can approve it or reject it with changes. Add items whenever you’re ready.'}\n </Typography>\n {libraryProofs.length ? (\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {libraryProofs.map((proof) => (\n <Chip\n key={`${proof.mediaScope}-${proof.mediaId}`}\n size=\"small\"\n variant=\"outlined\"\n label={proof.fileName || 'Proof'}\n onDelete={readOnly ? undefined : () => setLibraryProofs((prev) => prev.filter((entry) => entry !== proof))}\n />\n ))}\n </Stack>\n ) : null}\n <BlockedControl blocked={!canEdit} reason={REFUSAL}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy || libraryProofs.length >= CommerceModel.QUOTE_MAX_PROOFS}\n onClick={() => void chooseLibraryProof()}\n sx={{ alignSelf: 'flex-start' }}\n >\n {'From media library'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : null}\n\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Items'}</Typography>\n {form.lines.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Add products from your catalog, or type an item that is made to order.'}\n </Typography>\n ) : null}\n {form.lines.map((line, index) => (\n <QuoteLineEditor\n key={line.key}\n line={line}\n priced={priced[index]}\n products={products}\n disabled={readOnly || paid}\n onChange={(patch) => updateLine(line.key, patch)}\n onRemove={() => update({ lines: form.lines.filter((entry) => entry.key !== line.key) })}\n />\n ))}\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n <Button\n size=\"small\"\n disabled={readOnly || paid || products.length === 0}\n onClick={() =>\n update({\n lines: [\n ...form.lines,\n { key: nextLineKey(), kind: 'catalog', productId: '', variantId: '', quantity: '1', modifiers: [], description: '', included: false },\n ],\n })\n }\n >\n {'Add product'}\n </Button>\n <Button\n size=\"small\"\n disabled={readOnly || paid}\n onClick={() =>\n update({\n lines: [\n ...form.lines,\n { key: nextLineKey(), kind: 'custom', name: '', description: '', sku: '', price: '', quantity: '1', ships: true, included: false },\n ],\n })\n }\n >\n {'Add custom item'}\n </Button>\n </Stack>\n </Stack>\n\n {proofOnly ? null : (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField\n label=\"Discount\"\n select\n size=\"small\"\n value={form.discountKind}\n disabled={readOnly || paid}\n onChange={(event) => update({ discountKind: event.target.value as QuoteForm['discountKind'] })}\n sx={mediumField}\n >\n <MenuItem value=\"none\">{'None'}</MenuItem>\n <MenuItem value=\"amount\">{'Amount off'}</MenuItem>\n <MenuItem value=\"percent\">{'Percent off'}</MenuItem>\n </TextField>\n {form.discountKind !== 'none' ? (\n <TextField\n label={form.discountKind === 'amount' ? 'Amount ($)' : 'Percent (%)'}\n size=\"small\"\n value={form.discountValue}\n disabled={readOnly || paid}\n onChange={(event) => update({ discountValue: event.target.value })}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n error={form.discountKind === 'amount' ? centsOf(form.discountValue) === null : !(Number(form.discountValue) >= 0 && Number(form.discountValue) <= 100)}\n />\n ) : null}\n <TextField\n label=\"Shipping ($)\"\n size=\"small\"\n value={form.shipping}\n disabled={readOnly || paid}\n onChange={(event) => update({ shipping: event.target.value })}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n error={centsOf(form.shipping) === null}\n helperText=\"Leave empty when nothing ships.\"\n />\n </Stack>\n )}\n\n <QuoteAddressFields\n label=\"Ship to\"\n value={form.shipTo}\n disabled={readOnly || paid}\n helperText=\"Where the order goes. Store tax rates use its state and country.\"\n onChange={(shipTo) => update({ shipTo })}\n />\n <QuoteAddressFields\n label=\"Bill to\"\n value={form.billTo}\n disabled={readOnly || paid}\n onChange={(billTo) => update({ billTo })}\n />\n\n <Stack spacing={2}>\n <TextField\n label=\"Notes for the customer\"\n multiline\n minRows={2}\n value={form.notes}\n disabled={readOnly || paid}\n onChange={(event) => update({ notes: event.target.value })}\n />\n <TextField\n label=\"Terms\"\n multiline\n minRows={2}\n value={form.terms}\n disabled={readOnly || paid}\n onChange={(event) => update({ terms: event.target.value })}\n />\n {proofOnly ? null : (\n <FormControlLabel\n control={\n <Switch\n checked={requireProofApproval}\n disabled={readOnly || paid}\n onChange={(event) => update({ requireProofApproval: event.target.checked })}\n />\n }\n label=\"Customers approve the proof before they can pay\"\n />\n )}\n <Stack spacing={0}>\n <FormControlLabel\n control={\n <Switch\n checked={requireProofSignIn}\n disabled={readOnly || paid}\n onChange={(event) => update({ requireProofSignIn: event.target.checked })}\n />\n }\n label=\"Customers sign in to see and approve proofs\"\n />\n <FormHelperText sx={{ mt: 0 }}>\n {'For a customer with an account on your site. A customer without one keeps using the private link.'}\n </FormHelperText>\n </Stack>\n </Stack>\n\n {proofOnly ? null : (\n <>\n <Divider />\n <QuoteTotalsSummary\n totals={asSaved?.totals ?? totals}\n taxLabel={asSaved?.taxLabel ?? CommerceModel.describeQuoteTax(taxBasis)}\n taxAtPayment={asSaved?.taxAtPayment ?? totals.taxAtPayment}\n />\n </>\n )}\n </Stack>\n </DialogContent>\n <DialogActions sx={{ flexWrap: 'wrap', rowGap: 1 }}>\n {deletable ? (\n <BlockedControl blocked={!canEdit} reason={REFUSAL}>\n <Button color=\"error\" disabled={busy} onClick={() => setConfirmingDelete(true)} sx={{ mr: 'auto' }}>\n {'Delete'}\n </Button>\n </BlockedControl>\n ) : null}\n {quote && !proofOnly ? (\n <BlockedControl\n blocked={!canEdit || edited}\n reason={edited ? 'Save your changes first: the PDF shows the quote as it was last saved.' : REFUSAL}\n >\n <Button disabled={busy || downloading} onClick={() => void downloadPdf()}>\n {downloading ? 'Making PDF…' : 'Download PDF'}\n </Button>\n </BlockedControl>\n ) : null}\n <Button onClick={onClose} disabled={busy}>\n {paid || !canEdit ? 'Close' : 'Cancel'}\n </Button>\n {paid ? null : (\n <BlockedControl blocked={!canEdit} reason={REFUSAL}>\n <Button\n variant=\"contained\"\n disabled={busy || (form.lines.length === 0 && !proofOnly) || problems}\n onClick={() => void save()}\n >\n {quote ? 'Save' : proofOnly ? 'Create proof' : 'Create quote'}\n </Button>\n </BlockedControl>\n )}\n </DialogActions>\n <Dialog open={confirmingDelete} onClose={() => setConfirmingDelete(false)} maxWidth=\"xs\" fullWidth>\n <DialogTitle>{`Delete ${title}?`}</DialogTitle>\n <DialogContent>\n <DialogContentText>{'The quote and everything on it is removed. This can’t be undone.'}</DialogContentText>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setConfirmingDelete(false)} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button color=\"error\" variant=\"contained\" disabled={busy} onClick={() => void remove()}>\n {'Delete'}\n </Button>\n </DialogActions>\n </Dialog>\n </Dialog>\n )\n}\nQuoteEditorDialog.displayName = 'QuoteEditorDialog'\n\n/** A new quote's request (AGL-4098): which form sent it and when, its files by name, and its conversation. */\nfunction QuoteStartedFromRequest(props: {\n formName: string\n receivedAtMs: number | null\n files: ReadonlyArray<{ id: string; name: string; size: number }>\n threaded: boolean\n}) {\n const { formName, receivedAtMs, files, threaded } = props\n const when = receivedAtMs\n ? ` on ${new Date(receivedAtMs).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}`\n : ''\n return (\n <Alert severity=\"info\">\n <Stack spacing={1}>\n <Typography variant=\"body2\">{`From a request sent through “${formName}”${when}.`}</Typography>\n {files.length ? (\n <Stack spacing={0.5}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Their files, kept on the quote as the customer’s:'}\n </Typography>\n <Stack direction=\"row\" spacing={1} useFlexGap sx={{ flexWrap: 'wrap' }}>\n {files.map((file) => (\n <Chip key={file.id} size=\"small\" variant=\"outlined\" label={file.name} />\n ))}\n </Stack>\n </Stack>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {threaded\n ? 'When you email the quote, it replies to the confirmation they were sent, in the same conversation.'\n : 'They weren’t sent a confirmation, so the quote’s email starts the conversation.'}\n </Typography>\n </Stack>\n </Alert>\n )\n}\n\n/** Who the quote is for: a person the workspace keeps, or details typed here. */\nfunction QuoteCustomerSection(props: {\n hostId: string\n form: QuoteForm\n disabled: boolean\n onChange: (customer: QuoteForm['customer']) => void\n}) {\n const { hostId, form, disabled, onChange } = props\n const { data: user } = useUser()\n const [text, setText] = useState('')\n const [found, setFound] = useState<FoundCustomer[]>([])\n const [available, setAvailable] = useState(true)\n const ticket = useRef(0)\n const customer = form.customer\n\n useEffect(() => {\n const typed = text.trim()\n if (typed.length < 2 || !user) {\n // Only when something is listed, so an effect that re-runs settles.\n setFound((prev) => (prev.length ? [] : prev))\n return\n }\n const mine = ++ticket.current\n const timer = window.setTimeout(() => {\n void authorizedFetch(user, '/api/commerce/quote', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ action: 'search-customers', hostId, text: typed }),\n })\n .then((response) => response.json().catch(() => ({})))\n .then((payload) => {\n if (mine !== ticket.current) return\n setAvailable(payload?.available !== false)\n setFound(Array.isArray(payload?.customers) ? payload.customers : [])\n })\n .catch(() => undefined)\n }, SEARCH_DEBOUNCE_MS)\n return () => window.clearTimeout(timer)\n }, [text, user, hostId])\n\n const pick = (person: FoundCustomer) => {\n onChange({\n record: person.record,\n name: person.name,\n company: person.company,\n email: person.email ?? '',\n phone: person.phone ?? '',\n })\n setText('')\n setFound([])\n }\n\n return (\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{'Customer'}</Typography>\n {customer.record ? (\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Chip\n color=\"primary\"\n variant=\"outlined\"\n label={customer.name || customer.email || 'Contact'}\n onDelete={disabled ? undefined : () => onChange({ ...customer, record: null })}\n />\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'From your contacts'}\n </Typography>\n </Stack>\n ) : available ? (\n <Box>\n <TextField\n size=\"small\"\n fullWidth\n label=\"Find a contact\"\n placeholder=\"Name, email or phone\"\n value={text}\n disabled={disabled}\n onChange={(event) => setText(event.target.value)}\n />\n {found.length ? (\n <Paper variant=\"outlined\" sx={{ mt: 0.5 }}>\n <List dense disablePadding>\n {found.map((person) => (\n <ListItemButton key={`${person.record.kind}:${person.record.id}`} onClick={() => pick(person)}>\n <ListItemText\n primary={person.name || person.email || 'Contact'}\n secondary={[person.company, person.email, person.phone].filter(Boolean).join(' · ')}\n />\n </ListItemButton>\n ))}\n </List>\n </Paper>\n ) : null}\n </Box>\n ) : null}\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField size=\"small\" fullWidth label=\"Name\" value={customer.name} disabled={disabled} onChange={(event) => onChange({ ...customer, name: event.target.value })} />\n <TextField size=\"small\" fullWidth label=\"Company\" value={customer.company} disabled={disabled} onChange={(event) => onChange({ ...customer, company: event.target.value })} />\n </Stack>\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField size=\"small\" fullWidth label=\"Email\" type=\"email\" value={customer.email} disabled={disabled} onChange={(event) => onChange({ ...customer, email: event.target.value })} />\n <TextField size=\"small\" fullWidth label=\"Phone\" value={customer.phone} disabled={disabled} onChange={(event) => onChange({ ...customer, phone: event.target.value })} />\n </Stack>\n </Stack>\n )\n}\n\n/** One address on the quote. */\nfunction QuoteAddressFields(props: {\n label: string\n value: AddressForm\n disabled: boolean\n helperText?: string\n onChange: (value: AddressForm) => void\n}) {\n const { label, value, disabled, helperText, onChange } = props\n const field = (key: keyof AddressForm, fieldLabel: string, extra: Record<string, unknown> = {}) => (\n <TextField\n size=\"small\"\n fullWidth\n label={fieldLabel}\n value={value[key]}\n disabled={disabled}\n onChange={(event) => onChange({ ...value, [key]: event.target.value })}\n {...extra}\n />\n )\n return (\n <Stack spacing={1.5}>\n <Typography variant=\"subtitle2\">{label}</Typography>\n {helperText ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {helperText}\n </Typography>\n ) : null}\n {field('name', 'Name')}\n {field('line1', 'Address')}\n {field('line2', 'Apartment, suite, unit')}\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n {field('city', 'City')}\n {field('state', 'State or region')}\n {field('postalCode', 'Postal code')}\n {field('country', 'Country code', { placeholder: 'US', slotProps: { htmlInput: { maxLength: 2 } } })}\n </Stack>\n </Stack>\n )\n}\n\n/** One line of the quote: a product with its options and add-ons, or a typed item. */\nfunction QuoteLineEditor(props: {\n line: LineForm\n priced: { line?: CommerceModel.PricedQuoteLine; error?: string } | undefined\n products: readonly Record<string, any>[]\n disabled: boolean\n onChange: (patch: Partial<LineForm>) => void\n onRemove: () => void\n}) {\n const { line, priced, products, disabled, onChange, onRemove } = props\n const product = line.kind === 'catalog' ? products.find((entry) => String(entry.$id) === line.productId) : undefined\n const lifted = product ? CommerceModel.liftLegacyProduct(product) : null\n const groups = lifted ? CommerceModel.productModifierGroups(lifted) : []\n const lineCents = priced?.line ? CommerceModel.quoteLineCents(priced.line) : 0\n\n return (\n <Paper variant=\"outlined\" sx={{ p: 2 }}>\n <Stack spacing={1.5}>\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <Stack spacing={1.5} sx={{ flex: 1, minWidth: 0 }}>\n {line.kind === 'catalog' ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField\n label=\"Product\"\n select\n size=\"small\"\n fullWidth\n value={line.productId}\n disabled={disabled}\n onChange={(event) => onChange({ productId: event.target.value, variantId: '', modifiers: [] })}\n >\n {products.map((entry) => (\n <MenuItem key={String(entry.$id)} value={String(entry.$id)}>\n {String(entry.name ?? entry.$id)}\n </MenuItem>\n ))}\n </TextField>\n {lifted && lifted.variants.length > 1 ? (\n <TextField\n label=\"Option\"\n select\n size=\"small\"\n fullWidth\n value={line.variantId || lifted.variants[0]?.id || ''}\n disabled={disabled}\n onChange={(event) => onChange({ variantId: event.target.value })}\n >\n {lifted.variants.map((variant) => (\n <MenuItem key={variant.id} value={variant.id}>\n {Object.values(variant.options ?? {}).join(' / ') || 'Default'}\n </MenuItem>\n ))}\n </TextField>\n ) : null}\n </Stack>\n ) : (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>\n <TextField\n label=\"Item\"\n size=\"small\"\n fullWidth\n value={line.name}\n disabled={disabled}\n onChange={(event) => onChange({ name: event.target.value })}\n />\n <TextField\n label=\"SKU (optional)\"\n size=\"small\"\n value={line.sku}\n disabled={disabled}\n onChange={(event) => onChange({ sku: event.target.value })}\n />\n </Stack>\n )}\n {groups.map((group) => {\n // A write-in (write-ins): the answer the customer gave, typed into the quote.\n if (CommerceModel.modifierGroupIsWriteIn(group)) {\n const option = group.options[0]\n const text =\n line.kind === 'catalog' ? (line.modifiers.find((pick) => pick.groupId === group.id)?.text ?? '') : ''\n const problem = CommerceModel.writeInProblem(group, text)\n return (\n <TextField\n key={group.id}\n label={CommerceModel.modifierGroupRequired(group) ? group.name : `${group.name} (optional)`}\n size=\"small\"\n fullWidth\n value={text}\n disabled={disabled || !option}\n error={Boolean(problem)}\n helperText={problem ?? undefined}\n slotProps={{ htmlInput: { maxLength: CommerceModel.writeInMaxLength(group) } }}\n onChange={(event) => {\n if (line.kind !== 'catalog' || !option) return\n const typed = event.target.value\n onChange({\n modifiers: [\n ...line.modifiers.filter((pick) => pick.groupId !== group.id),\n ...(typed.trim() ? [{ groupId: group.id, optionId: option.id, text: typed }] : []),\n ],\n })\n }}\n />\n )\n }\n const chosen = line.kind === 'catalog' ? line.modifiers.filter((pick) => pick.groupId === group.id).map((pick) => pick.optionId) : []\n return (\n <TextField\n key={group.id}\n label={CommerceModel.modifierGroupRequired(group) ? group.name : `${group.name} (optional)`}\n select\n size=\"small\"\n fullWidth\n value={group.max > 1 ? chosen : (chosen[0] ?? '')}\n disabled={disabled}\n slotProps={{ select: { multiple: group.max > 1 } }}\n onChange={(event) => {\n const raw = event.target.value as unknown\n const picked = (Array.isArray(raw) ? raw : raw ? [raw] : []).map(String)\n if (line.kind !== 'catalog') return\n onChange({\n modifiers: [\n ...line.modifiers.filter((pick) => pick.groupId !== group.id),\n ...picked.map((optionId) => ({ groupId: group.id, optionId })),\n ],\n })\n }}\n >\n {group.max > 1 ? null : <MenuItem value=\"\">{'None'}</MenuItem>}\n {group.options.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {CommerceModel.quoteModifierOptionLabel(option, line.kind === 'catalog' ? line.variantId : null, money)}\n </MenuItem>\n ))}\n </TextField>\n )\n })}\n <TextField\n label=\"Description (optional)\"\n size=\"small\"\n fullWidth\n multiline\n value={line.description}\n disabled={disabled}\n onChange={(event) => onChange({ description: event.target.value })}\n />\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ alignItems: { sm: 'center' } }}>\n <TextField\n label=\"Quantity\"\n size=\"small\"\n value={line.quantity}\n disabled={disabled}\n onChange={(event) => onChange({ quantity: event.target.value.replace(/[^0-9]/g, '') })}\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n sx={narrowField}\n />\n {line.kind === 'custom' ? (\n <TextField\n label=\"Unit price ($)\"\n size=\"small\"\n value={line.included ? '' : line.price}\n disabled={disabled || line.included}\n onChange={(event) => onChange({ price: event.target.value })}\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n error={!line.included && centsOf(line.price) === null}\n sx={mediumField}\n />\n ) : null}\n {line.kind === 'custom' ? (\n <FormControlLabel\n control={<Switch checked={line.ships} disabled={disabled} onChange={(event) => onChange({ ships: event.target.checked })} />}\n label=\"Ships\"\n />\n ) : null}\n <FormControlLabel\n control={\n <Switch checked={line.included} disabled={disabled} onChange={(event) => onChange({ included: event.target.checked })} />\n }\n label=\"Included at no charge\"\n />\n </Stack>\n </Stack>\n <Stack sx={{ alignItems: 'flex-end', flexShrink: 0 }}>\n <Button size=\"small\" color=\"inherit\" disabled={disabled} onClick={onRemove}>\n {'Remove'}\n </Button>\n <Typography variant=\"body2\" sx={{ fontWeight: 'fontWeightMedium' }}>\n {line.included ? 'Included' : money(lineCents)}\n </Typography>\n {priced?.line && !line.included && priced.line.quantity > 1 ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {`${money(priced.line.unitAmountCents)} each`}\n </Typography>\n ) : null}\n </Stack>\n </Stack>\n {priced?.error ? (\n <Typography variant=\"caption\" color=\"error\">\n {priced.error}\n </Typography>\n ) : null}\n </Stack>\n </Paper>\n )\n}\n\n/** The quote's totals, as the customer will read them. */\nfunction QuoteTotalsSummary(props: {\n totals: CommerceModel.QuotePageView['totals']\n taxLabel: string\n /** Stripe Tax works the tax out when the customer pays, so there is no figure yet. */\n taxAtPayment: boolean\n}) {\n const { totals, taxLabel, taxAtPayment } = props\n const row = (label: string, value: string, strong = false) => (\n <Stack direction=\"row\" sx={{ justifyContent: 'space-between' }}>\n <Typography variant={strong ? 'subtitle1' : 'body2'} color={strong ? 'text.primary' : 'text.secondary'}>\n {label}\n </Typography>\n <Typography variant={strong ? 'subtitle1' : 'body2'}>{value}</Typography>\n </Stack>\n )\n return (\n <Stack spacing={0.5} sx={(theme) => ({ alignSelf: { sm: 'flex-end' }, minWidth: { sm: theme.spacing(40) } })}>\n {row('Items', money(totals.itemsCents))}\n {totals.discountCents ? row('Discount', `−${money(totals.discountCents)}`) : null}\n {totals.shippingCents ? row('Shipping', money(totals.shippingCents)) : null}\n {taxAtPayment ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {taxLabel}\n </Typography>\n ) : (\n row(taxLabel, money(totals.taxCents))\n )}\n {row(taxAtPayment ? 'Total before tax' : 'Total', money(totals.totalCents), true)}\n </Stack>\n )\n}\n\nexport default QuoteEditorDialog\n"],"names":["CommerceModel","posMoney","commerceSitePermissionRefusal","useMediaPicker","BlockedControl","useSnackbar","authorizedFetch","useFirestore","useFirestoreDoc","useUser","Alert","Box","Button","Chip","Dialog","DialogActions","DialogContent","DialogContentText","DialogTitle","Divider","FormControlLabel","FormHelperText","List","ListItemButton","ListItemText","MenuItem","Paper","Stack","Switch","TextField","Typography","doc","useCallback","useEffect","useMemo","useRef","useState","downloadCommercePdf","PayLinkReadinessNoticeFor","QuotePayLinkSection","QuoteMessagesSection","QuoteProofsSection","QuoteRequestFilesSection","QuoteSendSection","REFUSAL","SEARCH_DEBOUNCE_MS","money","cents","narrowField","theme","maxWidth","sm","spacing","mediumField","minWidth","centsOf","text","trimmed","trim","test","Math","round","Number","dollarsOf","toFixed","replace","addressForm","address","name","line1","line2","city","state","postalCode","country","lineSequence","nextLineKey","formFromQuote","quote","requireProofApproval","section","discount","lines","lineItems","map","line","request","quoteLineRequestFromLine","kind","key","description","sku","price","unitAmountCents","quantity","String","ships","included","productId","variantId","modifiers","customer","record","company","email","phone","shipTo","billTo","discountKind","discountValue","amountCents","pct","shipping","notes","terms","requireProofSignIn","formFromStart","start","blank","prefill","lineRequest","length","NaN","addressBody","entries","Object","filter","value","fromEntries","quoteBody","form","discountCents","priced","QuoteEditorDialog","props","hostId","products","canEdit","canSend","onClose","firestore","data","user","enqueueSnackbar","pickMedia","libraryProofs","setLibraryProofs","store","storeDefault","quoteRequiresProofApprovalByDefault","quotes","setForm","baseUpdatedAtMs","setBaseUpdatedAtMs","updatedAtMs","busy","setBusy","confirmingDelete","setConfirmingDelete","edited","setEdited","approvalSet","setApprovalSet","signInSet","setSignInSet","signInDefault","quoteRequiresProofSignInByDefault","update","patch","prev","updateLine","attemptKey","current","proofOnly","currentQuoteProofs","chooseLibraryProof","picked","allowPrivate","problem","quoteLibraryProofProblem","variant","allowDuplicate","some","entry","mediaId","mediaScope","productsById","Map","product","$id","error","isInteger","priceQuoteCustomLine","answer","priceQuoteCatalogLine","get","min","shippingCents","taxBasis","quoteTaxBasisFromSettings","tax","toUpperCase","pricedLines","flatMap","totals","computeQuoteTotals","problems","asSaved","buildQuotePageView","order","orderId","storeName","currency","payLinkStoreOf","save","payload","globalThis","crypto","randomUUID","Date","now","random","toString","slice","response","method","headers","body","JSON","stringify","action","quoteId","from","json","catch","ok","formatQuoteNumber","number","undefined","persist","remove","downloading","setDownloading","downloadPdf","refused","readOnly","paid","isUnpaidQuote","title","status","quoteDisplayStatus","deletable","Boolean","stage","open","fullWidth","scroll","aria-labelledby","id","direction","sx","alignItems","span","size","label","color","QUOTE_STATUS_COLOR","dividers","severity","paidAtMs","toLocaleDateString","onEdited","QuoteStartedFromRequest","formName","receivedAtMs","files","threaded","noun","QuoteCustomerSection","disabled","onChange","useFlexGap","flexWrap","proof","fileName","onDelete","blocked","reason","QUOTE_MAX_PROOFS","onClick","alignSelf","index","QuoteLineEditor","onRemove","xs","select","event","target","slotProps","htmlInput","inputMode","helperText","QuoteAddressFields","multiline","minRows","control","checked","mt","QuoteTotalsSummary","taxLabel","describeQuoteTax","taxAtPayment","rowGap","mr","displayName","when","toLocaleString","dateStyle","timeStyle","file","setText","found","setFound","available","setAvailable","ticket","typed","mine","timer","window","setTimeout","then","Array","isArray","customers","clearTimeout","pick","person","placeholder","dense","disablePadding","primary","secondary","join","type","field","fieldLabel","extra","maxLength","lifted","find","liftLegacyProduct","groups","productModifierGroups","lineCents","quoteLineCents","p","flex","variants","values","options","group","chosen","modifierGroupIsWriteIn","option","groupId","writeInProblem","modifierGroupRequired","writeInMaxLength","optionId","max","multiple","raw","quoteModifierOptionLabel","flexShrink","fontWeight","row","strong","justifyContent","itemsCents","taxCents","totalCents"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,QAAQ,QAAQ,kCAA8B;AACvD,SAASC,6BAA6B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M,SAAS,cAAc;8BAAU1P;;;;IAG1D,qBACE,MAACpG;QAAMyB,SAAS;QAAKgN,IAAI,CAACnN,QAAW,CAAA;gBAAEiP,WAAW;oBAAE/O,IAAI;gBAAW;gBAAGG,UAAU;oBAAEH,IAAIF,MAAMG,OAAO,CAAC;gBAAI;YAAE,CAAA;;YACvGoU,IAAI,SAAS1U,MAAM8J,OAAO+K,UAAU;YACpC/K,OAAOzE,aAAa,GAAGqP,IAAI,YAAY,CAAC,CAAC,EAAE1U,MAAM8J,OAAOzE,aAAa,GAAG,IAAI;YAC5EyE,OAAOP,aAAa,GAAGmL,IAAI,YAAY1U,MAAM8J,OAAOP,aAAa,KAAK;YACtEkH,6BACC,KAACzR;gBAAWsJ,SAAQ;gBAAQqF,OAAM;0BAC/B4C;iBAGHmE,IAAInE,UAAUvQ,MAAM8J,OAAOgL,QAAQ;YAEpCJ,IAAIjE,eAAe,qBAAqB,SAASzQ,MAAM8J,OAAOiL,UAAU,GAAG;;;AAGlF;AAEA,eAAexP,kBAAiB"}
|
|
@@ -12,6 +12,27 @@ export interface ProductAddOnsProps {
|
|
|
12
12
|
}
|
|
13
13
|
/** The picks with one group's answer replaced, in the groups' own order. */
|
|
14
14
|
export declare function withGroupAnswer(groups: readonly ProductModifierGroup[], value: readonly ModifierSelection[], groupId: string, optionIds: readonly string[]): ModifierSelection[];
|
|
15
|
+
/**
|
|
16
|
+
* The picks with a write-in's answer replaced (write-ins): the
|
|
17
|
+
* text as typed so far, kept while it is being typed; an empty answer leaves
|
|
18
|
+
* the group unanswered. The server cleans and checks it.
|
|
19
|
+
*/
|
|
20
|
+
export declare function withWriteInAnswer(groups: readonly ProductModifierGroup[], value: readonly ModifierSelection[], group: ProductModifierGroup, text: string): ModifierSelection[];
|
|
21
|
+
export interface ProductWriteInFieldProps {
|
|
22
|
+
group: ProductModifierGroup;
|
|
23
|
+
groups: readonly ProductModifierGroup[];
|
|
24
|
+
variantId?: string;
|
|
25
|
+
value: readonly ModifierSelection[];
|
|
26
|
+
onChange: (next: ModifierSelection[]) => void;
|
|
27
|
+
formatCents: (cents: number) => string;
|
|
28
|
+
disabled?: boolean;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* One write-in on a product's page: a text field named after the group, with
|
|
32
|
+
* the merchant's note, what a filled answer adds and a count of characters
|
|
33
|
+
* under it, or what is wrong with what was typed.
|
|
34
|
+
*/
|
|
35
|
+
export declare function ProductWriteInField(props: ProductWriteInFieldProps): import("react").JSX.Element;
|
|
15
36
|
/** What a group asks for, said under it. */
|
|
16
37
|
export declare function addOnGroupHint(group: Pick<ProductModifierGroup, 'min' | 'max'>): string;
|
|
17
38
|
/**
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ 'use client';
|
|
17
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
18
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
18
19
|
import Checkbox from "@mui/material/Checkbox";
|
|
19
20
|
import FormControl from "@mui/material/FormControl";
|
|
@@ -24,7 +25,7 @@ import FormLabel from "@mui/material/FormLabel";
|
|
|
24
25
|
import MenuItem from "@mui/material/MenuItem";
|
|
25
26
|
import Stack from "@mui/material/Stack";
|
|
26
27
|
import TextField from "@mui/material/TextField";
|
|
27
|
-
import { modifierGroupRequired, modifierOptionPriceCents } from "../model/product-modifiers.js";
|
|
28
|
+
import { modifierGroupIsWriteIn, modifierGroupRequired, modifierOptionPriceCents, writeInMaxLength, writeInProblem } from "../model/product-modifiers.js";
|
|
28
29
|
/** The picks with one group's answer replaced, in the groups' own order. */ export function withGroupAnswer(groups, value, groupId, optionIds) {
|
|
29
30
|
const others = value.filter((pick)=>pick.groupId !== groupId);
|
|
30
31
|
const answer = optionIds.map((optionId)=>({
|
|
@@ -43,6 +44,70 @@ import { modifierGroupRequired, modifierOptionPriceCents } from "../model/produc
|
|
|
43
44
|
return ((_order_get = order.get(a.groupId)) != null ? _order_get : 0) - ((_order_get1 = order.get(b.groupId)) != null ? _order_get1 : 0);
|
|
44
45
|
});
|
|
45
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* The picks with a write-in's answer replaced (write-ins): the
|
|
49
|
+
* text as typed so far, kept while it is being typed; an empty answer leaves
|
|
50
|
+
* the group unanswered. The server cleans and checks it.
|
|
51
|
+
*/ export function withWriteInAnswer(groups, value, group, text) {
|
|
52
|
+
const option = group.options[0];
|
|
53
|
+
const others = value.filter((pick)=>pick.groupId !== group.id);
|
|
54
|
+
const answer = option && text.trim() ? [
|
|
55
|
+
{
|
|
56
|
+
groupId: group.id,
|
|
57
|
+
optionId: option.id,
|
|
58
|
+
text
|
|
59
|
+
}
|
|
60
|
+
] : [];
|
|
61
|
+
const order = new Map(groups.map((entry, index)=>[
|
|
62
|
+
entry.id,
|
|
63
|
+
index
|
|
64
|
+
]));
|
|
65
|
+
return [
|
|
66
|
+
...others,
|
|
67
|
+
...answer
|
|
68
|
+
].sort((x, y)=>{
|
|
69
|
+
var _order_get, _order_get1;
|
|
70
|
+
return ((_order_get = order.get(x.groupId)) != null ? _order_get : 0) - ((_order_get1 = order.get(y.groupId)) != null ? _order_get1 : 0);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* One write-in on a product's page: a text field named after the group, with
|
|
75
|
+
* the merchant's note, what a filled answer adds and a count of characters
|
|
76
|
+
* under it, or what is wrong with what was typed.
|
|
77
|
+
*/ export function ProductWriteInField(props) {
|
|
78
|
+
var _ref;
|
|
79
|
+
var _value_find;
|
|
80
|
+
const { group, groups, variantId, value, onChange, formatCents, disabled } = props;
|
|
81
|
+
const option = group.options[0];
|
|
82
|
+
const text = (_ref = (_value_find = value.find((pick)=>pick.groupId === group.id)) == null ? void 0 : _value_find.text) != null ? _ref : '';
|
|
83
|
+
const limit = writeInMaxLength(group);
|
|
84
|
+
const problem = writeInProblem(group, text);
|
|
85
|
+
const cents = option ? modifierOptionPriceCents(option, variantId) : 0;
|
|
86
|
+
const hint = [
|
|
87
|
+
option == null ? void 0 : option.note,
|
|
88
|
+
cents > 0 ? `Adds ${formatCents(cents)}` : null,
|
|
89
|
+
`${Array.from(text).length}/${limit}`
|
|
90
|
+
].filter(Boolean).join(' · ');
|
|
91
|
+
return /*#__PURE__*/ _jsx(TextField, {
|
|
92
|
+
size: "small",
|
|
93
|
+
fullWidth: true,
|
|
94
|
+
required: modifierGroupRequired(group),
|
|
95
|
+
disabled: disabled,
|
|
96
|
+
label: group.name,
|
|
97
|
+
value: text,
|
|
98
|
+
error: Boolean(problem),
|
|
99
|
+
onChange: (event)=>onChange(withWriteInAnswer(groups, value, group, event.target.value)),
|
|
100
|
+
helperText: problem != null ? problem : hint,
|
|
101
|
+
slotProps: {
|
|
102
|
+
htmlInput: _extends({
|
|
103
|
+
maxLength: limit
|
|
104
|
+
}, group.digitsOnly ? {
|
|
105
|
+
inputMode: 'numeric',
|
|
106
|
+
pattern: '[0-9]*'
|
|
107
|
+
} : {})
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
46
111
|
/** What a group asks for, said under it. */ export function addOnGroupHint(group) {
|
|
47
112
|
if (group.max === 1) return group.min > 0 ? 'Choose one' : 'Optional';
|
|
48
113
|
if (group.min > 0 && group.min === group.max) return `Choose ${group.min}`;
|
|
@@ -67,6 +132,17 @@ import { modifierGroupRequired, modifierOptionPriceCents } from "../model/produc
|
|
|
67
132
|
mb: 1.5
|
|
68
133
|
},
|
|
69
134
|
children: groups.map((group)=>{
|
|
135
|
+
if (modifierGroupIsWriteIn(group)) {
|
|
136
|
+
return /*#__PURE__*/ _jsx(ProductWriteInField, {
|
|
137
|
+
group: group,
|
|
138
|
+
groups: groups,
|
|
139
|
+
variantId: variantId,
|
|
140
|
+
value: value,
|
|
141
|
+
onChange: onChange,
|
|
142
|
+
formatCents: formatCents,
|
|
143
|
+
disabled: disabled
|
|
144
|
+
}, group.id);
|
|
145
|
+
}
|
|
70
146
|
const chosen = value.filter((pick)=>pick.groupId === group.id).map((pick)=>pick.optionId);
|
|
71
147
|
const required = modifierGroupRequired(group);
|
|
72
148
|
if (group.max === 1) {
|