@aglyn/plugins-commerce 1.9.1 → 1.11.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.
Files changed (50) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/invoice-send.component.d.ts +9 -2
  3. package/src/lib/components/console/invoice-send.component.js +58 -30
  4. package/src/lib/components/console/invoice-send.component.js.map +1 -1
  5. package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +84 -0
  6. package/src/lib/components/console/pay-link-readiness-notice.component.js +164 -0
  7. package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -0
  8. package/src/lib/components/console/quote-editor-dialog.component.js +7 -8
  9. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  10. package/src/lib/components/console/quote-pay-link.component.d.ts +3 -0
  11. package/src/lib/components/console/quote-pay-link.component.js +9 -0
  12. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  13. package/src/lib/components/console/quote-send.component.d.ts +3 -0
  14. package/src/lib/components/console/quote-send.component.js +9 -0
  15. package/src/lib/components/console/quote-send.component.js.map +1 -1
  16. package/src/lib/components/quote-page-body.js +5 -3
  17. package/src/lib/components/quote-page-body.js.map +1 -1
  18. package/src/lib/model/commerce-invoices.d.ts +45 -5
  19. package/src/lib/model/commerce-invoices.js +46 -9
  20. package/src/lib/model/commerce-invoices.js.map +1 -1
  21. package/src/lib/model/commerce-quote-pay.d.ts +110 -6
  22. package/src/lib/model/commerce-quote-pay.js +182 -23
  23. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  24. package/src/lib/server/billing-webhook.js +4 -1
  25. package/src/lib/server/billing-webhook.js.map +1 -1
  26. package/src/lib/server/checkout.d.ts +7 -0
  27. package/src/lib/server/checkout.js +15 -4
  28. package/src/lib/server/checkout.js.map +1 -1
  29. package/src/lib/server/commerce-pdf.js +2 -1
  30. package/src/lib/server/commerce-pdf.js.map +1 -1
  31. package/src/lib/server/invoice-email.js +2 -1
  32. package/src/lib/server/invoice-email.js.map +1 -1
  33. package/src/lib/server/order-invoice-send.js +1 -1
  34. package/src/lib/server/order-invoice-send.js.map +1 -1
  35. package/src/lib/server/order-status.d.ts +5 -1
  36. package/src/lib/server/order-status.js +19 -5
  37. package/src/lib/server/order-status.js.map +1 -1
  38. package/src/lib/server/quote-email.js +2 -1
  39. package/src/lib/server/quote-email.js.map +1 -1
  40. package/src/lib/server/quote-pay.d.ts +39 -0
  41. package/src/lib/server/quote-pay.js +103 -43
  42. package/src/lib/server/quote-pay.js.map +1 -1
  43. package/src/lib/server/quote-proofs.js +13 -9
  44. package/src/lib/server/quote-proofs.js.map +1 -1
  45. package/src/lib/utils/invoice-email-content.d.ts +3 -1
  46. package/src/lib/utils/invoice-email-content.js +1 -1
  47. package/src/lib/utils/invoice-email-content.js.map +1 -1
  48. package/src/lib/utils/quote-email-content.d.ts +3 -1
  49. package/src/lib/utils/quote-email-content.js +3 -3
  50. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/quote-send.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 { commerceSitePermissionRefusal } from '../../model/plugin-permissions'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\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 Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { InvoiceSendDialog, invoiceSentLine } from './invoice-send.component'\n\nconst SEND_REFUSAL = commerceSitePermissionRefusal('commerce.quotes.send')\n\nexport interface QuoteSendSectionProps {\n hostId: string\n quoteId: string\n quote: CommerceModel.HostOrder\n /** Holds \"Send quotes and invoices to customers\" (`commerce.quotes.send`). */\n canSend: boolean\n /** The editor holds changes not saved yet, which the email would not show. */\n edited: boolean\n}\n\n/** `Oct 29, 2026, 3:04 PM`. */\nconst sentAt = (atMs: number) =>\n new Date(atMs).toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' })\n\n/**\n * Emailing the quote to the customer (AGL-4097): when it was last sent and to\n * whom, and Send quote, Send again or Send revision N, which opens a short\n * form (To, Subject, Message). The server writes the email in the site's\n * look with the proof, the PDF and the pay button, in the customer's\n * conversation with the business.\n *\n * Send invoice (AGL-4099) sits beside it: for an unpaid quote, an invoice for\n * a customer who needs one to pay (with the same pay link); for a paid one,\n * the invoice as their record. Both reply into the quote's conversation.\n */\nexport function QuoteSendSection(props: QuoteSendSectionProps) {\n const { hostId, quoteId, quote, canSend, edited } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { data: host } = useFirestoreDoc<Record<string, unknown>>(\n () => doc(firestore, 'hosts', hostId),\n [firestore, hostId],\n )\n const businessName = String(resolveHostToken('businessName', (host ?? {}) as HostTokenSource) ?? '').trim()\n const section = quote.quote\n const unpaid = CommerceModel.isUnpaidQuote(quote)\n const last = CommerceModel.lastQuoteSend(section)\n const revision = Number(section?.revision ?? 1)\n const label = CommerceModel.quoteSendLabel(section)\n const replacesLink = CommerceModel.quoteSendReplacesLink(section)\n const approvalFirst = CommerceModel.quotePaymentBlockedByApproval(section)\n const proofCount = CommerceModel.currentQuoteProofs(section).length\n const listed = siteContactEmail(host as never)\n const contact = listed && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(listed) ? listed : null\n\n const [open, setOpen] = useState(false)\n const [invoicing, setInvoicing] = useState(false)\n const invoiceLine = invoiceSentLine(quote)\n const closed = quote.status === 'cancelled' || quote.status === 'refunded'\n const [busy, setBusy] = useState(false)\n const [to, setTo] = useState('')\n const [subject, setSubject] = useState('')\n const [message, setMessage] = useState('')\n\n /*\n * One attempt per form (AGL-1697's rule): a retried Send presents the same\n * key and is answered from the first, so the customer never gets two; a\n * changed form is a new attempt.\n */\n const attemptKey = useRef('')\n useEffect(() => {\n attemptKey.current = ''\n }, [to, subject, message])\n\n const openForm = useCallback(() => {\n setTo(CommerceModel.quoteSendPrefill(quote))\n setSubject(CommerceModel.quoteEmailDefaultSubject(quote, businessName, quoteId))\n setMessage('')\n setOpen(true)\n }, [quote, businessName, quoteId])\n\n const send = 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({ action: 'send', hostId, quoteId, to, subject, message }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'The quote could not be sent', { variant: 'error', allowDuplicate: true })\n }\n enqueueSnackbar(\n `${CommerceModel.formatQuoteNumber(quote, quoteId)} sent to ${String(payload.to ?? to)}` +\n (payload.linkReplaced ? '. The link in your earlier email no longer opens the quote.' : ''),\n { variant: 'success', persist: false },\n )\n setOpen(false)\n } finally {\n setBusy(false)\n }\n }, [user, hostId, quoteId, to, subject, message, quote, enqueueSnackbar])\n\n const status = last\n ? `Sent ${sentAt(Number(last.atMs))} to ${last.to || 'the customer'}` +\n (Number(last.revision) < revision ? ` (revision ${last.revision})` : '') +\n '.'\n : 'Not sent yet. Email it with your message, the proof and the PDF, or copy the pay link below and send it yourself.'\n\n return (\n <Stack spacing={1.5}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Email to customer'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {unpaid ? status : last ? status : 'This quote was paid without being emailed.'}\n </Typography>\n {unpaid && replacesLink ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Sending revision ${revision} gives your customer a new pay link. The link in your earlier email will say the quote was updated.`}\n </Typography>\n ) : null}\n {unpaid && edited ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Save your changes first: the email shows the quote as it was last saved.'}\n </Typography>\n ) : null}\n {invoiceLine ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {invoiceLine}\n </Typography>\n ) : null}\n </Stack>\n {!closed ? (\n <Stack direction=\"row\" spacing={1}>\n {unpaid ? (\n <BlockedControl blocked={!canSend} reason={SEND_REFUSAL}>\n <Button variant=\"contained\" size=\"small\" disabled={busy || edited} onClick={openForm}>\n {label}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={!canSend} reason={SEND_REFUSAL}>\n <Button\n variant={unpaid ? 'outlined' : 'contained'}\n size=\"small\"\n disabled={busy || (unpaid && edited)}\n onClick={() => setInvoicing(true)}\n >\n {'Send invoice'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : null}\n <InvoiceSendDialog\n open={invoicing}\n onClose={() => setInvoicing(false)}\n hostId={hostId}\n orderId={quoteId}\n order={quote}\n />\n <Dialog open={open} onClose={busy ? undefined : () => setOpen(false)} maxWidth=\"sm\" fullWidth aria-labelledby=\"quote-send-title\">\n <DialogTitle id=\"quote-send-title\">{`${label}: ${CommerceModel.formatQuoteNumber(quote, quoteId)}`}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <TextField\n label=\"To\"\n type=\"email\"\n value={to}\n onChange={(event) => setTo(event.target.value)}\n required\n fullWidth\n disabled={busy}\n />\n <TextField\n label=\"Subject\"\n value={subject}\n onChange={(event) => setSubject(event.target.value)}\n fullWidth\n disabled={busy}\n slotProps={{ htmlInput: { maxLength: CommerceModel.QUOTE_MAX_SEND_SUBJECT } }}\n helperText={\n section?.emailThread\n ? 'Keep the subject the same to keep these emails in one conversation in your customer’s inbox.'\n : undefined\n }\n />\n <TextField\n label=\"Message\"\n value={message}\n onChange={(event) => setMessage(event.target.value)}\n multiline\n minRows={4}\n fullWidth\n disabled={busy}\n slotProps={{ htmlInput: { maxLength: CommerceModel.QUOTE_MAX_SEND_MESSAGE } }}\n helperText=\"Shown at the top of the email, in your words.\"\n />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`The email shows the quote number, revision ${revision} and total` +\n (proofCount ? ', the proof' : '') +\n `, with the quote attached as a PDF and a button to ${approvalFirst ? 'approve the proof' : 'pay'} on your site. ` +\n `Replies go to ${contact || 'your email'}.`}\n </Typography>\n {replacesLink ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This sends a new pay link. The link in your earlier email will say the quote was updated.'}\n </Typography>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setOpen(false)} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" disabled={busy || !to.trim()} onClick={() => void send()}>\n {busy ? 'Sending…' : 'Send'}\n </Button>\n </DialogActions>\n </Dialog>\n </Stack>\n )\n}\nQuoteSendSection.displayName = 'QuoteSendSection'\n\nexport default QuoteSendSection\n"],"names":["CommerceModel","commerceSitePermissionRefusal","siteContactEmail","resolveHostToken","BlockedControl","useSnackbar","authorizedFetch","useFirestore","useFirestoreDoc","useUser","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","TextField","Typography","doc","useCallback","useEffect","useRef","useState","InvoiceSendDialog","invoiceSentLine","SEND_REFUSAL","sentAt","atMs","Date","toLocaleString","dateStyle","timeStyle","QuoteSendSection","props","hostId","quoteId","quote","canSend","edited","firestore","data","user","enqueueSnackbar","host","businessName","String","trim","section","unpaid","isUnpaidQuote","last","lastQuoteSend","revision","Number","label","quoteSendLabel","replacesLink","quoteSendReplacesLink","approvalFirst","quotePaymentBlockedByApproval","proofCount","currentQuoteProofs","length","listed","contact","test","open","setOpen","invoicing","setInvoicing","invoiceLine","closed","status","busy","setBusy","to","setTo","subject","setSubject","message","setMessage","attemptKey","current","openForm","quoteSendPrefill","quoteEmailDefaultSubject","send","payload","globalThis","crypto","randomUUID","now","Math","random","toString","slice","response","method","headers","body","JSON","stringify","action","json","catch","ok","error","variant","allowDuplicate","formatQuoteNumber","linkReplaced","persist","spacing","color","direction","blocked","reason","size","disabled","onClick","onClose","orderId","order","undefined","maxWidth","fullWidth","aria-labelledby","id","sx","pt","type","value","onChange","event","target","required","slotProps","htmlInput","maxLength","QUOTE_MAX_SEND_SUBJECT","helperText","emailThread","multiline","minRows","QUOTE_MAX_SEND_MESSAGE","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,6BAA6B,QAAQ,oCAAgC;AAC9E,SAASC,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,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,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,QAAQ,qBAAoB;AACxC,SAASC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAA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C,WAAW;4CAAEC,WAAW1I,cAAc2I,sBAAsB;wCAAC;oCAAE;oCAC5EC,YACE7F,CAAAA,2BAAAA,QAAS8F,WAAW,IAChB,iGACAlB;;8CAGR,KAAC3G;oCACCsC,OAAM;oCACN6E,OAAOpD;oCACPqD,UAAU,CAACC,QAAUrD,WAAWqD,MAAMC,MAAM,CAACH,KAAK;oCAClDW,SAAS;oCACTC,SAAS;oCACTlB,SAAS;oCACTP,UAAU7C;oCACV+D,WAAW;wCAAEC,WAAW;4CAAEC,WAAW1I,cAAcgJ,sBAAsB;wCAAC;oCAAE;oCAC5EJ,YAAW;;8CAEb,KAAC3H;oCAAW0F,SAAQ;oCAAQM,OAAM;8CAC/B,CAAC,2CAA2C,EAAE7D,SAAS,UAAU,CAAC,GAChEQ,CAAAA,aAAa,gBAAgB,EAAC,IAC/B,CAAC,mDAAmD,EAAEF,gBAAgB,sBAAsB,MAAM,eAAe,CAAC,GAClH,CAAC,cAAc,EAAEM,WAAW,aAAa,CAAC,CAAC;;gCAE9CR,6BACC,KAACvC;oCAAW0F,SAAQ;oCAAQM,OAAM;8CAC/B;qCAED;;;;kCAGR,MAACrG;;0CACC,KAACF;gCAAO6G,SAAS,IAAMpD,QAAQ;gCAAQmD,UAAU7C;0CAC9C;;0CAEH,KAAC/D;gCAAOiG,SAAQ;gCAAYW,UAAU7C,QAAQ,CAACE,GAAG7B,IAAI;gCAAIyE,SAAS,IAAM,KAAKjC;0CAC3Eb,OAAO,aAAa;;;;;;;;AAMjC;AACAzC,iBAAiBiH,WAAW,GAAG;AAE/B,eAAejH,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/quote-send.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 { commerceSitePermissionRefusal } from '../../model/plugin-permissions'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\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 Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport { doc } from 'firebase/firestore'\nimport { useCallback, useEffect, useRef, useState } from 'react'\nimport { InvoiceSendDialog, invoiceSentLine } from './invoice-send.component'\nimport { PayLinkReadinessNoticeFor } from './pay-link-readiness-notice.component'\n\nconst SEND_REFUSAL = commerceSitePermissionRefusal('commerce.quotes.send')\n\nexport interface QuoteSendSectionProps {\n hostId: string\n quoteId: string\n quote: CommerceModel.HostOrder\n /** Holds \"Send quotes and invoices to customers\" (`commerce.quotes.send`). */\n canSend: boolean\n /** The editor holds changes not saved yet, which the email would not show. */\n edited: boolean\n}\n\n/** `Oct 29, 2026, 3:04 PM`. */\nconst sentAt = (atMs: number) =>\n new Date(atMs).toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' })\n\n/**\n * Emailing the quote to the customer (AGL-4097): when it was last sent and to\n * whom, and Send quote, Send again or Send revision N, which opens a short\n * form (To, Subject, Message). The server writes the email in the site's\n * look with the proof, the PDF and the pay button, in the customer's\n * conversation with the business.\n *\n * Send invoice (AGL-4099) sits beside it: for an unpaid quote, an invoice for\n * a customer who needs one to pay (with the same pay link); for a paid one,\n * the invoice as their record. Both reply into the quote's conversation.\n *\n * The form says what the customer's Pay waits on, if anything (AGL-4162),\n * and sends all the same.\n */\nexport function QuoteSendSection(props: QuoteSendSectionProps) {\n const { hostId, quoteId, quote, canSend, edited } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { data: host } = useFirestoreDoc<Record<string, unknown>>(\n () => doc(firestore, 'hosts', hostId),\n [firestore, hostId],\n )\n const businessName = String(resolveHostToken('businessName', (host ?? {}) as HostTokenSource) ?? '').trim()\n const section = quote.quote\n const unpaid = CommerceModel.isUnpaidQuote(quote)\n const last = CommerceModel.lastQuoteSend(section)\n const revision = Number(section?.revision ?? 1)\n const label = CommerceModel.quoteSendLabel(section)\n const replacesLink = CommerceModel.quoteSendReplacesLink(section)\n const approvalFirst = CommerceModel.quotePaymentBlockedByApproval(section)\n const proofCount = CommerceModel.currentQuoteProofs(section).length\n const listed = siteContactEmail(host as never)\n const contact = listed && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(listed) ? listed : null\n\n const [open, setOpen] = useState(false)\n const [invoicing, setInvoicing] = useState(false)\n const invoiceLine = invoiceSentLine(quote)\n const closed = quote.status === 'cancelled' || quote.status === 'refunded'\n const [busy, setBusy] = useState(false)\n const [to, setTo] = useState('')\n const [subject, setSubject] = useState('')\n const [message, setMessage] = useState('')\n\n /*\n * One attempt per form (AGL-1697's rule): a retried Send presents the same\n * key and is answered from the first, so the customer never gets two; a\n * changed form is a new attempt.\n */\n const attemptKey = useRef('')\n useEffect(() => {\n attemptKey.current = ''\n }, [to, subject, message])\n\n const openForm = useCallback(() => {\n setTo(CommerceModel.quoteSendPrefill(quote))\n setSubject(CommerceModel.quoteEmailDefaultSubject(quote, businessName, quoteId))\n setMessage('')\n setOpen(true)\n }, [quote, businessName, quoteId])\n\n const send = 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({ action: 'send', hostId, quoteId, to, subject, message }),\n })\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'The quote could not be sent', { variant: 'error', allowDuplicate: true })\n }\n enqueueSnackbar(\n `${CommerceModel.formatQuoteNumber(quote, quoteId)} sent to ${String(payload.to ?? to)}` +\n (payload.linkReplaced ? '. The link in your earlier email no longer opens the quote.' : ''),\n { variant: 'success', persist: false },\n )\n setOpen(false)\n } finally {\n setBusy(false)\n }\n }, [user, hostId, quoteId, to, subject, message, quote, enqueueSnackbar])\n\n const status = last\n ? `Sent ${sentAt(Number(last.atMs))} to ${last.to || 'the customer'}` +\n (Number(last.revision) < revision ? ` (revision ${last.revision})` : '') +\n '.'\n : 'Not sent yet. Email it with your message, the proof and the PDF, or copy the pay link below and send it yourself.'\n\n return (\n <Stack spacing={1.5}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Email to customer'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {unpaid ? status : last ? status : 'This quote was paid without being emailed.'}\n </Typography>\n {unpaid && replacesLink ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Sending revision ${revision} gives your customer a new pay link. The link in your earlier email will say the quote was updated.`}\n </Typography>\n ) : null}\n {unpaid && edited ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Save your changes first: the email shows the quote as it was last saved.'}\n </Typography>\n ) : null}\n {invoiceLine ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {invoiceLine}\n </Typography>\n ) : null}\n </Stack>\n {!closed ? (\n <Stack direction=\"row\" spacing={1}>\n {unpaid ? (\n <BlockedControl blocked={!canSend} reason={SEND_REFUSAL}>\n <Button variant=\"contained\" size=\"small\" disabled={busy || edited} onClick={openForm}>\n {label}\n </Button>\n </BlockedControl>\n ) : null}\n <BlockedControl blocked={!canSend} reason={SEND_REFUSAL}>\n <Button\n variant={unpaid ? 'outlined' : 'contained'}\n size=\"small\"\n disabled={busy || (unpaid && edited)}\n onClick={() => setInvoicing(true)}\n >\n {'Send invoice'}\n </Button>\n </BlockedControl>\n </Stack>\n ) : null}\n <InvoiceSendDialog\n open={invoicing}\n onClose={() => setInvoicing(false)}\n hostId={hostId}\n orderId={quoteId}\n order={quote}\n />\n <Dialog open={open} onClose={busy ? undefined : () => setOpen(false)} maxWidth=\"sm\" fullWidth aria-labelledby=\"quote-send-title\">\n <DialogTitle id=\"quote-send-title\">{`${label}: ${CommerceModel.formatQuoteNumber(quote, quoteId)}`}</DialogTitle>\n <DialogContent>\n <Stack spacing={2} sx={{ pt: 1 }}>\n <PayLinkReadinessNoticeFor hostId={hostId} order={quote} noun=\"quote\" />\n <TextField\n label=\"To\"\n type=\"email\"\n value={to}\n onChange={(event) => setTo(event.target.value)}\n required\n fullWidth\n disabled={busy}\n />\n <TextField\n label=\"Subject\"\n value={subject}\n onChange={(event) => setSubject(event.target.value)}\n fullWidth\n disabled={busy}\n slotProps={{ htmlInput: { maxLength: CommerceModel.QUOTE_MAX_SEND_SUBJECT } }}\n helperText={\n section?.emailThread\n ? 'Keep the subject the same to keep these emails in one conversation in your customer’s inbox.'\n : undefined\n }\n />\n <TextField\n label=\"Message\"\n value={message}\n onChange={(event) => setMessage(event.target.value)}\n multiline\n minRows={4}\n fullWidth\n disabled={busy}\n slotProps={{ htmlInput: { maxLength: CommerceModel.QUOTE_MAX_SEND_MESSAGE } }}\n helperText=\"Shown at the top of the email, in your words.\"\n />\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`The email shows the quote number, revision ${revision} and total` +\n (proofCount ? ', the proof' : '') +\n `, with the quote attached as a PDF and a button to ${approvalFirst ? 'approve the proof' : 'pay'} on your site. ` +\n `Replies go to ${contact || 'your email'}.`}\n </Typography>\n {replacesLink ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'This sends a new pay link. The link in your earlier email will say the quote was updated.'}\n </Typography>\n ) : null}\n </Stack>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setOpen(false)} disabled={busy}>\n {'Cancel'}\n </Button>\n <Button variant=\"contained\" disabled={busy || !to.trim()} onClick={() => void send()}>\n {busy ? 'Sending…' : 'Send'}\n </Button>\n </DialogActions>\n </Dialog>\n </Stack>\n )\n}\nQuoteSendSection.displayName = 'QuoteSendSection'\n\nexport default QuoteSendSection\n"],"names":["CommerceModel","commerceSitePermissionRefusal","siteContactEmail","resolveHostToken","BlockedControl","useSnackbar","authorizedFetch","useFirestore","useFirestoreDoc","useUser","Button","Dialog","DialogActions","DialogContent","DialogTitle","Stack","TextField","Typography","doc","useCallback","useEffect","useRef","useState","InvoiceSendDialog","invoiceSentLine","PayLinkReadinessNoticeFor","SEND_REFUSAL","sentAt","atMs","Date","toLocaleString","dateStyle","timeStyle","QuoteSendSection","props","hostId","quoteId","quote","canSend","edited","firestore","data","user","enqueueSnackbar","host","businessName","String","trim","section","unpaid","isUnpaidQuote","last","lastQuoteSend","revision","Number","label","quoteSendLabel","replacesLink","quoteSendReplacesLink","approvalFirst","quotePaymentBlockedByApproval","proofCount","currentQuoteProofs","length","listed","contact","test","open","setOpen","invoicing","setInvoicing","invoiceLine","closed","status","busy","setBusy","to","setTo","subject","setSubject","message","setMessage","attemptKey","current","openForm","quoteSendPrefill","quoteEmailDefaultSubject","send","payload","globalThis","crypto","randomUUID","now","Math","random","toString","slice","response","method","headers","body","JSON","stringify","action","json","catch","ok","error","variant","allowDuplicate","formatQuoteNumber","linkReplaced","persist","spacing","color","direction","blocked","reason","size","disabled","onClick","onClose","orderId","order","undefined","maxWidth","fullWidth","aria-labelledby","id","sx","pt","noun","type","value","onChange","event","target","required","slotProps","htmlInput","maxLength","QUOTE_MAX_SEND_SUBJECT","helperText","emailThread","multiline","minRows","QUOTE_MAX_SEND_MESSAGE","displayName"],"mappings":"AAAA;;;;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,EAAEM,WAAW,aAAa,CAAC,CAAC;;gCAE9CR,6BACC,KAACxC;oCAAW2F,SAAQ;oCAAQM,OAAM;8CAC/B;qCAED;;;;kCAGR,MAACtG;;0CACC,KAACF;gCAAO8G,SAAS,IAAMpD,QAAQ;gCAAQmD,UAAU7C;0CAC9C;;0CAEH,KAAChE;gCAAOkG,SAAQ;gCAAYW,UAAU7C,QAAQ,CAACE,GAAG7B,IAAI;gCAAIyE,SAAS,IAAM,KAAKjC;0CAC3Eb,OAAO,aAAa;;;;;;;;AAMjC;AACAzC,iBAAiBkH,WAAW,GAAG;AAE/B,eAAelH,iBAAgB"}
@@ -259,12 +259,14 @@ function TotalRow({ label, value, strong }) {
259
259
  'Content-Type': 'application/json',
260
260
  'Idempotency-Key': attemptKey
261
261
  },
262
- body: JSON.stringify({
262
+ body: JSON.stringify(_extends({
263
263
  hostId,
264
264
  q: link.current.quoteId,
265
265
  t: link.current.token,
266
266
  v: view.version
267
- })
267
+ }, view.taxKey ? {
268
+ tax: view.taxKey
269
+ } : {}))
268
270
  });
269
271
  const payload = await response.json().catch(()=>({}));
270
272
  // A session with a client secret is the in-page form; checked before the
@@ -699,7 +701,7 @@ function TotalRow({ label, value, strong }) {
699
701
  ]
700
702
  }) : /*#__PURE__*/ _jsx(Alert, {
701
703
  severity: "info",
702
- children: `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`
704
+ children: quote.notPayableMessage || `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`
703
705
  })
704
706
  })
705
707
  }) : /*#__PURE__*/ _jsx(Paper, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/quote-page-body.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\nimport * as Aglyn from '@aglyn/aglyn'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport Paper from '@mui/material/Paper'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport type { StripeCheckoutContact } from '@stripe/stripe-js'\nimport { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'\nimport {\n formatOrderMoney,\n readStorefrontCheckoutWallets,\n type QuotePageAddress,\n type QuotePageView,\n type StorefrontCheckoutWallets,\n} from '../model'\nimport type { QuotePageProps } from './quote-page'\nimport { QuoteProofPanel } from './quote-proof-panel'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\n/** The Payment Element, lazily: Stripe.js loads only when a customer presses Pay. */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\n\ntype LoadState =\n | { kind: 'loading' }\n | { kind: 'missing'; message: string }\n | { kind: 'replaced'; storeName: string; noun: string }\n | { kind: 'ready'; view: QuotePageView }\n\n/** `quote` or `invoice`, as the page says it (AGL-4099). */\nconst nounOf = (kind: unknown) => (kind === 'invoice' ? 'invoice' : 'quote')\n\n/** What is added when the customer pays: `shipping`, `tax`, `shipping and tax`, or nothing. */\nfunction addedAtPayment(view: Pick<QuotePageView, 'shippingAtPayment' | 'taxAtPayment'>): string {\n if (view.shippingAtPayment && view.taxAtPayment) return 'shipping and tax'\n if (view.shippingAtPayment) return 'shipping'\n return view.taxAtPayment ? 'tax' : ''\n}\n\n/** After a payment returns here, how often and how long the page asks whether it landed. */\nconst CONFIRM_POLL_MS = 2_000\nconst CONFIRM_POLLS = 15\n\nfunction dateLabel(atMs: number | null): string {\n if (!atMs) return ''\n return new Date(atMs).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction addressLines(address: QuotePageAddress): string[] {\n const cityLine = [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')]\n .filter(Boolean)\n .join(', ')\n return [address.name, address.line1, address.line2, cityLine, address.country].filter(\n (line): line is string => Boolean(line),\n )\n}\n\nfunction stripeContact(address: QuotePageAddress | null): StripeCheckoutContact | undefined {\n if (!address?.country) return undefined\n return {\n name: address.name,\n address: {\n country: address.country,\n line1: address.line1,\n line2: address.line2,\n city: address.city,\n state: address.state,\n postal_code: address.postalCode,\n },\n }\n}\n\nfunction AddressBlock({ label, lines }: { label: string; lines: string[] }) {\n return (\n <Stack spacing={0.25} sx={{ minWidth: 0, flex: 1 }}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {label}\n </Typography>\n {lines.map((line, index) => (\n <Typography key={index} variant=\"body2\">\n {line}\n </Typography>\n ))}\n </Stack>\n )\n}\n\nfunction TotalRow({ label, value, strong }: { label: string; value: string; strong?: boolean }) {\n return (\n <Stack direction=\"row\" spacing={2} 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'} color={strong ? 'text.primary' : 'text.secondary'}>\n {value}\n </Typography>\n </Stack>\n )\n}\n\n/**\n * The customer's quote page (AGL-4094), loaded when the page draws it (see\n * `quote-page.tsx`): what a customer sees when they open\n * the pay link a business sent them. The commerce page resolver serves it at\n * `/pay-quote` inside the site's own header and footer; a business can also\n * place it on a page of their own design at that address.\n *\n * The quote is read AFTER hydration from `?q=&t=`, so the page itself is the\n * same for every customer and may be cached, and the quote never is. Pay asks\n * the server for a fresh payment for the quote as the page shows it: Stripe's\n * own page, or the payment form here when in-page payments are on. Nothing\n * here decides a quote is paid; after paying, the page reads that from the\n * server like any other visit.\n */\nconst QuotePageBody = forwardRef<HTMLDivElement, QuotePageProps>((props, ref) => {\n const { heading, ...rest } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [state, setState] = useState<LoadState>({ kind: 'loading' })\n const [paying, setPaying] = useState(false)\n const [payError, setPayError] = useState('')\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n wallets?: StorefrontCheckoutWallets\n } | null>(null)\n /** What a return from paying turned out to be: still being confirmed, or not paid. */\n const [returned, setReturned] = useState<'confirming' | 'unconfirmed' | 'failed' | null>(null)\n const link = useRef({ quoteId: '', token: '', sessionId: '' })\n\n const load = useCallback(async (): Promise<LoadState> => {\n const { quoteId, token } = link.current\n try {\n const response = await siteFetch(\n `/api/commerce/quote-view?hostId=${encodeURIComponent(hostId ?? '')}` +\n `&q=${encodeURIComponent(quoteId)}&t=${encodeURIComponent(token)}`,\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return { kind: 'missing', message: String(payload?.error ?? 'We could not find that quote or invoice.') }\n }\n if (payload?.state === 'replaced') {\n return { kind: 'replaced', storeName: String(payload.storeName ?? ''), noun: nounOf(payload.kind) }\n }\n return { kind: 'ready', view: payload as QuotePageView }\n } catch {\n return { kind: 'missing', message: 'This page could not be loaded. Check your connection and try again.' }\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n if (!hostId) return\n const params = new URLSearchParams(window.location.search)\n link.current = {\n quoteId: params.get('q') ?? '',\n token: params.get('t') ?? '',\n sessionId: params.get('session_id') ?? '',\n }\n if (!link.current.quoteId || !link.current.token) {\n setState({ kind: 'missing', message: 'Open this page from the link you were sent with your quote or invoice.' })\n return\n }\n let live = true\n void (async () => {\n const first = await load()\n if (!live) return\n setState(first)\n const sessionId = link.current.sessionId\n if (first.kind !== 'ready' || first.view.status !== 'unpaid' || !sessionId) return\n // Back from paying: the payment may have landed before the record of it.\n const status = await siteFetch(\n `/api/commerce/checkout-status?hostId=${encodeURIComponent(hostId)}` +\n `&sessionId=${encodeURIComponent(sessionId)}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .catch(() => null)\n if (!live) return\n if (status?.status === 'open') {\n setReturned('failed')\n return\n }\n if (status?.status !== 'complete') return\n setReturned('confirming')\n for (let poll = 0; poll < CONFIRM_POLLS && live; poll++) {\n await new Promise((resolve) => setTimeout(resolve, CONFIRM_POLL_MS))\n if (!live) return\n const next = await load()\n if (!live) return\n if (next.kind === 'ready' && next.view.status !== 'unpaid') {\n setState(next)\n setReturned(null)\n return\n }\n }\n if (live) setReturned('unconfirmed')\n })()\n return () => {\n live = false\n }\n }, [hostId, load, siteFetch])\n\n const view = state.kind === 'ready' ? state.view : null\n\n const pay = useCallback(async () => {\n if (!view || paying) return\n setPaying(true)\n setPayError('')\n setReturned(null)\n // One key per press: a press is one attempt, and a retry after a failure is a new one.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await siteFetch('/api/commerce/quote-pay', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey },\n body: JSON.stringify({\n hostId,\n q: link.current.quoteId,\n t: link.current.token,\n v: view.version,\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // A session with a client secret is the in-page form; checked before the\n // redirect, so a form is never navigated away from.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n wallets: readStorefrontCheckoutWallets(payload.wallets),\n })\n setPaying(false)\n return\n }\n if (response.ok && payload?.url) {\n window.location.assign(String(payload.url))\n return\n }\n if (payload?.replaced) {\n setState({ kind: 'replaced', storeName: view.storeName, noun: nounOf(view.kind) })\n return\n }\n if (payload?.reason === 'paid' || payload?.reason === 'updated') {\n const next = await load()\n setState(next)\n }\n setPayError(String(payload?.error ?? 'Your payment could not be set up. Try again.'))\n setPaying(false)\n } catch {\n setPayError('Your payment could not be set up. Check your connection and try again.')\n setPaying(false)\n }\n }, [view, paying, siteFetch, hostId, load])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ p: 3, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }, ...nodeSx]}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Quote — a customer’s quote and its Pay button render here'}\n </Typography>\n </Box>\n )\n }\n\n if (state.kind === 'loading') {\n return (\n <Box ref={ref} {...rest} sx={[{ py: 6, textAlign: 'center' }, ...nodeSx]}>\n <CircularProgress size={28} aria-label=\"Loading\" />\n </Box>\n )\n }\n\n if (state.kind === 'missing') {\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n <Typography variant=\"h4\" component=\"h1\">\n {heading || 'Your quote or invoice'}\n </Typography>\n <Alert severity=\"info\">{state.message}</Alert>\n </Stack>\n </Box>\n )\n }\n\n if (state.kind === 'replaced') {\n const business = state.storeName || 'The business'\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n {state.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {state.storeName}\n </Typography>\n ) : null}\n <Typography variant=\"h4\" component=\"h1\">\n {`This ${state.noun} was updated`}\n </Typography>\n <Typography variant=\"body1\" color=\"text.secondary\">\n {`${business} updated this ${state.noun} and sent you a newer link. Open their most recent message to see it.`}\n </Typography>\n </Stack>\n </Box>\n )\n }\n\n const quote = state.view\n const money = (cents: number) => formatOrderMoney(cents, quote.currency)\n // The same signed link as the page's data; the server makes the PDF from the same view.\n const pdfHref =\n `/api/commerce/quote-pdf?hostId=${encodeURIComponent(hostId)}` +\n `&q=${encodeURIComponent(link.current.quoteId)}&t=${encodeURIComponent(link.current.token)}`\n const unpaid = quote.status === 'unpaid'\n const noun = nounOf(quote.kind)\n const later = addedAtPayment(quote)\n const addresses = [\n quote.customerName || quote.company\n ? { label: 'Prepared for', lines: [quote.customerName, quote.company].filter((line): line is string => Boolean(line)) }\n : null,\n quote.billTo ? { label: 'Bill to', lines: addressLines(quote.billTo) } : null,\n quote.shipTo ? { label: 'Ship to', lines: addressLines(quote.shipTo) } : null,\n ].filter((block): block is { label: string; lines: string[] } => Boolean(block && block.lines.length))\n const totalRows = (\n [\n ['Subtotal', money(quote.totals.itemsCents), true],\n [\n quote.discountLabel ? `Discount (${quote.discountLabel})` : 'Discount',\n `−${money(quote.totals.discountCents)}`,\n quote.totals.discountCents > 0,\n ],\n ['Shipping', money(quote.totals.shippingCents), quote.totals.shippingCents > 0],\n [quote.taxLabel, money(quote.totals.taxCents), quote.totals.taxCents > 0],\n // The rate an invoiced draft's customer picks when they pay (AGL-4099).\n ['Shipping is chosen when you pay', '', quote.shippingAtPayment === true],\n // `Tax is added at payment`, with no figure: Stripe works it out from the address.\n [quote.taxLabel, '', quote.taxAtPayment],\n ] as Array<[string, string, boolean]>\n ).filter(([, , shown]) => shown)\n\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={3}>\n <Stack spacing={1}>\n {quote.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {quote.storeName}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"h4\" component=\"h1\">\n {/* The element's own heading is a quote's; an invoice always says its number. */}\n {(quote.kind !== 'invoice' && heading) || quote.number}\n </Typography>\n <Chip\n label={quote.statusLabel}\n color={quote.status === 'paid' ? 'success' : unpaid ? 'primary' : 'default'}\n size=\"small\"\n />\n </Stack>\n {quote.dateMs ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Dated ${dateLabel(quote.dateMs)}`}\n </Typography>\n ) : null}\n <Box>\n <Button variant=\"outlined\" size=\"small\" href={pdfHref} download>\n {'Download PDF'}\n </Button>\n </Box>\n </Stack>\n\n {addresses.length ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={{ xs: 2, sm: 3 }}>\n {addresses.map((block) => (\n <AddressBlock key={block.label} label={block.label} lines={block.lines} />\n ))}\n </Stack>\n ) : null}\n\n <Stack spacing={1.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Items'}\n </Typography>\n {quote.lines.map((line, index) => (\n <Stack key={index} direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Stack spacing={0.25} sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\">\n {line.name}\n {line.variantLabel ? ` (${line.variantLabel})` : ''}\n </Typography>\n {line.description ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {line.description}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {[\n line.included ? `${line.quantity} included` : `${line.quantity} × ${money(line.unitAmountCents)}`,\n line.sku ? `SKU ${line.sku}` : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Typography variant=\"body2\" sx={{ flexShrink: 0 }}>\n {line.included ? 'Included' : money(line.amountCents)}\n </Typography>\n </Stack>\n ))}\n <Divider />\n {totalRows.map(([label, value]) => (\n <TotalRow key={`${label}-${value}`} label={label} value={value} />\n ))}\n <TotalRow label=\"Total\" value={money(quote.totals.totalCents)} strong />\n </Stack>\n\n {quote.notes ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Notes'}\n </Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.notes}\n </Typography>\n </Stack>\n ) : null}\n {quote.terms ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Terms'}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.terms}\n </Typography>\n </Stack>\n ) : null}\n\n <QuoteProofPanel\n view={quote}\n hostId={hostId}\n quoteId={link.current.quoteId}\n token={link.current.token}\n siteFetch={siteFetch}\n onView={(next) => setState({ kind: 'ready', view: next })}\n onReload={() => void load().then(setState)}\n onReplaced={() => setState({ kind: 'replaced', storeName: quote.storeName, noun })}\n />\n\n {unpaid ? (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={2}>\n {returned === 'confirming' ? (\n <Alert severity=\"info\" icon={<CircularProgress size={20} />}>\n {'Thank you. We’re confirming your payment.'}\n </Alert>\n ) : returned === 'unconfirmed' ? (\n <Alert severity=\"info\">\n {'Your payment is still being confirmed. Your receipt will arrive by email.'}\n </Alert>\n ) : quote.approvalRequired ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} asks you to approve the proof before you pay.`}\n </Alert>\n ) : quote.payable ? (\n <>\n {returned === 'failed' ? (\n <Alert severity=\"warning\">{'Your payment did not go through. Nothing was charged.'}</Alert>\n ) : null}\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n wallets={nativeCheckout.wallets}\n payLabel={later ? 'Pay now' : `Pay ${money(quote.totals.totalCents)}`}\n defaultShippingAddress={stripeContact(quote.shipTo)}\n // An expired or unloadable session is replaced by a new press.\n onRestart={() => {\n setNativeCheckout(null)\n void pay()\n }}\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : (\n <Button\n variant=\"contained\"\n size=\"large\"\n onClick={() => void pay()}\n disabled={paying}\n sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}\n >\n {paying\n ? 'Opening…'\n : later\n ? `Pay ${money(quote.totals.totalCents)} plus ${later}`\n : `Pay ${money(quote.totals.totalCents)}`}\n </Button>\n )}\n {payError ? <Alert severity=\"error\">{payError}</Alert> : null}\n </>\n ) : (\n <Alert severity=\"info\">\n {`Contact ${quote.storeName || 'the business'} to pay this ${noun}.`}\n </Alert>\n )}\n </Stack>\n </Paper>\n ) : (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={1.5} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body1\">\n {quote.status === 'paid'\n ? quote.paidAtMs\n ? `Paid ${dateLabel(quote.paidAtMs)}. Thank you.`\n : 'Paid. Thank you.'\n : `This ${noun} is ${quote.statusLabel.toLowerCase()}.`}\n </Typography>\n {quote.receiptUrl ? (\n <Button variant=\"outlined\" href={quote.receiptUrl}>\n {'View your order'}\n </Button>\n ) : null}\n </Stack>\n </Paper>\n )}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Questions about this ${noun}? Contact ${quote.storeName || 'the business'}.`}\n </Typography>\n </Stack>\n </Box>\n )\n})\nQuotePageBody.displayName = 'QuotePageBody'\n\nexport default QuotePageBody\n\n"],"names":["Aglyn","Alert","Box","Button","Chip","CircularProgress","Divider","Paper","Stack","Typography","forwardRef","lazy","Suspense","useCallback","useEffect","useRef","useState","formatOrderMoney","readStorefrontCheckoutWallets","QuoteProofPanel","StorefrontPaymentElementFallback","StorefrontPaymentElement","then","module","default","nounOf","kind","addedAtPayment","view","shippingAtPayment","taxAtPayment","CONFIRM_POLL_MS","CONFIRM_POLLS","dateLabel","atMs","Date","toLocaleDateString","undefined","month","day","year","addressLines","address","cityLine","city","state","postalCode","filter","Boolean","join","name","line1","line2","country","line","stripeContact","postal_code","AddressBlock","label","lines","spacing","sx","minWidth","flex","variant","color","map","index","TotalRow","value","strong","direction","justifyContent","QuotePageBody","props","ref","heading","rest","nodeSx","Array","isArray","hostId","useSite","siteFetch","useSiteFetch","setState","paying","setPaying","payError","setPayError","nativeCheckout","setNativeCheckout","returned","setReturned","link","quoteId","token","sessionId","load","current","response","encodeURIComponent","payload","json","catch","ok","message","String","error","storeName","noun","params","URLSearchParams","window","location","search","get","live","first","status","poll","Promise","resolve","setTimeout","next","pay","globalThis","attemptKey","crypto","randomUUID","now","Math","random","toString","slice","method","headers","body","JSON","stringify","q","t","v","version","clientSecret","publishableKey","wallets","url","assign","replaced","reason","p","border","borderColor","borderRadius","py","textAlign","size","aria-label","component","severity","business","quote","money","cents","currency","pdfHref","unpaid","later","addresses","customerName","company","billTo","shipTo","block","length","totalRows","totals","itemsCents","discountLabel","discountCents","shippingCents","taxLabel","taxCents","shown","alignItems","flexWrap","rowGap","number","statusLabel","dateMs","href","download","xs","sm","variantLabel","description","whiteSpace","included","quantity","unitAmountCents","sku","flexShrink","amountCents","totalCents","notes","terms","onView","onReload","onReplaced","icon","approvalRequired","payable","fallback","payLabel","defaultShippingAddress","onRestart","onCancel","onClick","disabled","alignSelf","paidAtMs","toLowerCase","receiptUrl","displayName"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,aAAa,wBAAuB;AAC3C,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,gBAAgB,2BAA0B;AAEjD,SAASC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,SAAS,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAC5F,SACEC,gBAAgB,EAChBC,6BAA6B,QAIxB,oBAAU;AAEjB,SAASC,eAAe,QAAQ,yBAAqB;AACrD,SAASC,gCAAgC,QAAQ,2CAAuC;AAExF,mFAAmF,GACnF,MAAMC,yCAA2BV,KAAK,IACpC,MAAM,CAAC,mCAAgCW,IAAI,CAAC,CAACC,SAAY,CAAA;YACvDC,SAASD,OAAOF,wBAAwB;QAC1C,CAAA;AASF,0DAA0D,GAC1D,MAAMI,SAAS,CAACC,OAAmBA,SAAS,YAAY,YAAY;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C,cAAcuJ,WAAW,GAAG;AAE5B,eAAevJ,cAAa"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/components/quote-page-body.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\nimport * as Aglyn from '@aglyn/aglyn'\nimport Alert from '@mui/material/Alert'\nimport Box from '@mui/material/Box'\nimport Button from '@mui/material/Button'\nimport Chip from '@mui/material/Chip'\nimport CircularProgress from '@mui/material/CircularProgress'\nimport Divider from '@mui/material/Divider'\nimport Paper from '@mui/material/Paper'\nimport Stack from '@mui/material/Stack'\nimport Typography from '@mui/material/Typography'\nimport type { StripeCheckoutContact } from '@stripe/stripe-js'\nimport { forwardRef, lazy, Suspense, useCallback, useEffect, useRef, useState } from 'react'\nimport {\n formatOrderMoney,\n readStorefrontCheckoutWallets,\n type QuotePageAddress,\n type QuotePageView,\n type StorefrontCheckoutWallets,\n} from '../model'\nimport type { QuotePageProps } from './quote-page'\nimport { QuoteProofPanel } from './quote-proof-panel'\nimport { StorefrontPaymentElementFallback } from './storefront-payment-element-fallback'\n\n/** The Payment Element, lazily: Stripe.js loads only when a customer presses Pay. */\nconst StorefrontPaymentElement = lazy(() =>\n import('./storefront-payment-element').then((module) => ({\n default: module.StorefrontPaymentElement,\n })),\n)\n\ntype LoadState =\n | { kind: 'loading' }\n | { kind: 'missing'; message: string }\n | { kind: 'replaced'; storeName: string; noun: string }\n | { kind: 'ready'; view: QuotePageView }\n\n/** `quote` or `invoice`, as the page says it (AGL-4099). */\nconst nounOf = (kind: unknown) => (kind === 'invoice' ? 'invoice' : 'quote')\n\n/** What is added when the customer pays: `shipping`, `tax`, `shipping and tax`, or nothing. */\nfunction addedAtPayment(view: Pick<QuotePageView, 'shippingAtPayment' | 'taxAtPayment'>): string {\n if (view.shippingAtPayment && view.taxAtPayment) return 'shipping and tax'\n if (view.shippingAtPayment) return 'shipping'\n return view.taxAtPayment ? 'tax' : ''\n}\n\n/** After a payment returns here, how often and how long the page asks whether it landed. */\nconst CONFIRM_POLL_MS = 2_000\nconst CONFIRM_POLLS = 15\n\nfunction dateLabel(atMs: number | null): string {\n if (!atMs) return ''\n return new Date(atMs).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })\n}\n\nfunction addressLines(address: QuotePageAddress): string[] {\n const cityLine = [address.city, [address.state, address.postalCode].filter(Boolean).join(' ')]\n .filter(Boolean)\n .join(', ')\n return [address.name, address.line1, address.line2, cityLine, address.country].filter(\n (line): line is string => Boolean(line),\n )\n}\n\nfunction stripeContact(address: QuotePageAddress | null): StripeCheckoutContact | undefined {\n if (!address?.country) return undefined\n return {\n name: address.name,\n address: {\n country: address.country,\n line1: address.line1,\n line2: address.line2,\n city: address.city,\n state: address.state,\n postal_code: address.postalCode,\n },\n }\n}\n\nfunction AddressBlock({ label, lines }: { label: string; lines: string[] }) {\n return (\n <Stack spacing={0.25} sx={{ minWidth: 0, flex: 1 }}>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {label}\n </Typography>\n {lines.map((line, index) => (\n <Typography key={index} variant=\"body2\">\n {line}\n </Typography>\n ))}\n </Stack>\n )\n}\n\nfunction TotalRow({ label, value, strong }: { label: string; value: string; strong?: boolean }) {\n return (\n <Stack direction=\"row\" spacing={2} 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'} color={strong ? 'text.primary' : 'text.secondary'}>\n {value}\n </Typography>\n </Stack>\n )\n}\n\n/**\n * The customer's quote page (AGL-4094), loaded when the page draws it (see\n * `quote-page.tsx`): what a customer sees when they open\n * the pay link a business sent them. The commerce page resolver serves it at\n * `/pay-quote` inside the site's own header and footer; a business can also\n * place it on a page of their own design at that address.\n *\n * The quote is read AFTER hydration from `?q=&t=`, so the page itself is the\n * same for every customer and may be cached, and the quote never is. Pay asks\n * the server for a fresh payment for the quote as the page shows it: Stripe's\n * own page, or the payment form here when in-page payments are on. Nothing\n * here decides a quote is paid; after paying, the page reads that from the\n * server like any other visit.\n */\nconst QuotePageBody = forwardRef<HTMLDivElement, QuotePageProps>((props, ref) => {\n const { heading, ...rest } = props\n const nodeSx = Array.isArray(props['sx']) ? props['sx'] : [props['sx']]\n const { hostId } = Aglyn.useSite()\n const siteFetch = Aglyn.useSiteFetch()\n const [state, setState] = useState<LoadState>({ kind: 'loading' })\n const [paying, setPaying] = useState(false)\n const [payError, setPayError] = useState('')\n const [nativeCheckout, setNativeCheckout] = useState<{\n clientSecret: string\n publishableKey: string\n wallets?: StorefrontCheckoutWallets\n } | null>(null)\n /** What a return from paying turned out to be: still being confirmed, or not paid. */\n const [returned, setReturned] = useState<'confirming' | 'unconfirmed' | 'failed' | null>(null)\n const link = useRef({ quoteId: '', token: '', sessionId: '' })\n\n const load = useCallback(async (): Promise<LoadState> => {\n const { quoteId, token } = link.current\n try {\n const response = await siteFetch(\n `/api/commerce/quote-view?hostId=${encodeURIComponent(hostId ?? '')}` +\n `&q=${encodeURIComponent(quoteId)}&t=${encodeURIComponent(token)}`,\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return { kind: 'missing', message: String(payload?.error ?? 'We could not find that quote or invoice.') }\n }\n if (payload?.state === 'replaced') {\n return { kind: 'replaced', storeName: String(payload.storeName ?? ''), noun: nounOf(payload.kind) }\n }\n return { kind: 'ready', view: payload as QuotePageView }\n } catch {\n return { kind: 'missing', message: 'This page could not be loaded. Check your connection and try again.' }\n }\n }, [hostId, siteFetch])\n\n useEffect(() => {\n if (!hostId) return\n const params = new URLSearchParams(window.location.search)\n link.current = {\n quoteId: params.get('q') ?? '',\n token: params.get('t') ?? '',\n sessionId: params.get('session_id') ?? '',\n }\n if (!link.current.quoteId || !link.current.token) {\n setState({ kind: 'missing', message: 'Open this page from the link you were sent with your quote or invoice.' })\n return\n }\n let live = true\n void (async () => {\n const first = await load()\n if (!live) return\n setState(first)\n const sessionId = link.current.sessionId\n if (first.kind !== 'ready' || first.view.status !== 'unpaid' || !sessionId) return\n // Back from paying: the payment may have landed before the record of it.\n const status = await siteFetch(\n `/api/commerce/checkout-status?hostId=${encodeURIComponent(hostId)}` +\n `&sessionId=${encodeURIComponent(sessionId)}`,\n )\n .then((response) => (response.ok ? response.json() : null))\n .catch(() => null)\n if (!live) return\n if (status?.status === 'open') {\n setReturned('failed')\n return\n }\n if (status?.status !== 'complete') return\n setReturned('confirming')\n for (let poll = 0; poll < CONFIRM_POLLS && live; poll++) {\n await new Promise((resolve) => setTimeout(resolve, CONFIRM_POLL_MS))\n if (!live) return\n const next = await load()\n if (!live) return\n if (next.kind === 'ready' && next.view.status !== 'unpaid') {\n setState(next)\n setReturned(null)\n return\n }\n }\n if (live) setReturned('unconfirmed')\n })()\n return () => {\n live = false\n }\n }, [hostId, load, siteFetch])\n\n const view = state.kind === 'ready' ? state.view : null\n\n const pay = useCallback(async () => {\n if (!view || paying) return\n setPaying(true)\n setPayError('')\n setReturned(null)\n // One key per press: a press is one attempt, and a retry after a failure is a new one.\n const attemptKey =\n globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`\n try {\n const response = await siteFetch('/api/commerce/quote-pay', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', 'Idempotency-Key': attemptKey },\n body: JSON.stringify({\n hostId,\n q: link.current.quoteId,\n t: link.current.token,\n v: view.version,\n // The tax the page priced it under; a quote whose tax moved since is shown again.\n ...(view.taxKey ? { tax: view.taxKey } : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n // A session with a client secret is the in-page form; checked before the\n // redirect, so a form is never navigated away from.\n if (response.ok && payload?.clientSecret && payload?.publishableKey) {\n setNativeCheckout({\n clientSecret: String(payload.clientSecret),\n publishableKey: String(payload.publishableKey),\n wallets: readStorefrontCheckoutWallets(payload.wallets),\n })\n setPaying(false)\n return\n }\n if (response.ok && payload?.url) {\n window.location.assign(String(payload.url))\n return\n }\n if (payload?.replaced) {\n setState({ kind: 'replaced', storeName: view.storeName, noun: nounOf(view.kind) })\n return\n }\n if (payload?.reason === 'paid' || payload?.reason === 'updated') {\n const next = await load()\n setState(next)\n }\n setPayError(String(payload?.error ?? 'Your payment could not be set up. Try again.'))\n setPaying(false)\n } catch {\n setPayError('Your payment could not be set up. Check your connection and try again.')\n setPaying(false)\n }\n }, [view, paying, siteFetch, hostId, load])\n\n if (!hostId) {\n return (\n <Box\n ref={ref}\n {...rest}\n sx={[{ p: 3, border: '1px dashed', borderColor: 'divider', borderRadius: 1 }, ...nodeSx]}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Quote — a customer’s quote and its Pay button render here'}\n </Typography>\n </Box>\n )\n }\n\n if (state.kind === 'loading') {\n return (\n <Box ref={ref} {...rest} sx={[{ py: 6, textAlign: 'center' }, ...nodeSx]}>\n <CircularProgress size={28} aria-label=\"Loading\" />\n </Box>\n )\n }\n\n if (state.kind === 'missing') {\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n <Typography variant=\"h4\" component=\"h1\">\n {heading || 'Your quote or invoice'}\n </Typography>\n <Alert severity=\"info\">{state.message}</Alert>\n </Stack>\n </Box>\n )\n }\n\n if (state.kind === 'replaced') {\n const business = state.storeName || 'The business'\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={2}>\n {state.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {state.storeName}\n </Typography>\n ) : null}\n <Typography variant=\"h4\" component=\"h1\">\n {`This ${state.noun} was updated`}\n </Typography>\n <Typography variant=\"body1\" color=\"text.secondary\">\n {`${business} updated this ${state.noun} and sent you a newer link. Open their most recent message to see it.`}\n </Typography>\n </Stack>\n </Box>\n )\n }\n\n const quote = state.view\n const money = (cents: number) => formatOrderMoney(cents, quote.currency)\n // The same signed link as the page's data; the server makes the PDF from the same view.\n const pdfHref =\n `/api/commerce/quote-pdf?hostId=${encodeURIComponent(hostId)}` +\n `&q=${encodeURIComponent(link.current.quoteId)}&t=${encodeURIComponent(link.current.token)}`\n const unpaid = quote.status === 'unpaid'\n const noun = nounOf(quote.kind)\n const later = addedAtPayment(quote)\n const addresses = [\n quote.customerName || quote.company\n ? { label: 'Prepared for', lines: [quote.customerName, quote.company].filter((line): line is string => Boolean(line)) }\n : null,\n quote.billTo ? { label: 'Bill to', lines: addressLines(quote.billTo) } : null,\n quote.shipTo ? { label: 'Ship to', lines: addressLines(quote.shipTo) } : null,\n ].filter((block): block is { label: string; lines: string[] } => Boolean(block && block.lines.length))\n const totalRows = (\n [\n ['Subtotal', money(quote.totals.itemsCents), true],\n [\n quote.discountLabel ? `Discount (${quote.discountLabel})` : 'Discount',\n `−${money(quote.totals.discountCents)}`,\n quote.totals.discountCents > 0,\n ],\n ['Shipping', money(quote.totals.shippingCents), quote.totals.shippingCents > 0],\n [quote.taxLabel, money(quote.totals.taxCents), quote.totals.taxCents > 0],\n // The rate an invoiced draft's customer picks when they pay (AGL-4099).\n ['Shipping is chosen when you pay', '', quote.shippingAtPayment === true],\n // `Tax is added at payment`, with no figure: Stripe works it out from the address.\n [quote.taxLabel, '', quote.taxAtPayment],\n ] as Array<[string, string, boolean]>\n ).filter(([, , shown]) => shown)\n\n return (\n <Box ref={ref} {...rest} sx={nodeSx}>\n <Stack spacing={3}>\n <Stack spacing={1}>\n {quote.storeName ? (\n <Typography variant=\"overline\" color=\"text.secondary\">\n {quote.storeName}\n </Typography>\n ) : null}\n <Stack direction=\"row\" spacing={1.5} sx={{ alignItems: 'center', flexWrap: 'wrap', rowGap: 1 }}>\n <Typography variant=\"h4\" component=\"h1\">\n {/* The element's own heading is a quote's; an invoice always says its number. */}\n {(quote.kind !== 'invoice' && heading) || quote.number}\n </Typography>\n <Chip\n label={quote.statusLabel}\n color={quote.status === 'paid' ? 'success' : unpaid ? 'primary' : 'default'}\n size=\"small\"\n />\n </Stack>\n {quote.dateMs ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Dated ${dateLabel(quote.dateMs)}`}\n </Typography>\n ) : null}\n <Box>\n <Button variant=\"outlined\" size=\"small\" href={pdfHref} download>\n {'Download PDF'}\n </Button>\n </Box>\n </Stack>\n\n {addresses.length ? (\n <Stack direction={{ xs: 'column', sm: 'row' }} spacing={{ xs: 2, sm: 3 }}>\n {addresses.map((block) => (\n <AddressBlock key={block.label} label={block.label} lines={block.lines} />\n ))}\n </Stack>\n ) : null}\n\n <Stack spacing={1.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Items'}\n </Typography>\n {quote.lines.map((line, index) => (\n <Stack key={index} direction=\"row\" spacing={2} sx={{ justifyContent: 'space-between' }}>\n <Stack spacing={0.25} sx={{ minWidth: 0 }}>\n <Typography variant=\"body2\">\n {line.name}\n {line.variantLabel ? ` (${line.variantLabel})` : ''}\n </Typography>\n {line.description ? (\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {line.description}\n </Typography>\n ) : null}\n <Typography variant=\"caption\" color=\"text.secondary\">\n {[\n line.included ? `${line.quantity} included` : `${line.quantity} × ${money(line.unitAmountCents)}`,\n line.sku ? `SKU ${line.sku}` : '',\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Typography variant=\"body2\" sx={{ flexShrink: 0 }}>\n {line.included ? 'Included' : money(line.amountCents)}\n </Typography>\n </Stack>\n ))}\n <Divider />\n {totalRows.map(([label, value]) => (\n <TotalRow key={`${label}-${value}`} label={label} value={value} />\n ))}\n <TotalRow label=\"Total\" value={money(quote.totals.totalCents)} strong />\n </Stack>\n\n {quote.notes ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Notes'}\n </Typography>\n <Typography variant=\"body2\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.notes}\n </Typography>\n </Stack>\n ) : null}\n {quote.terms ? (\n <Stack spacing={0.5}>\n <Typography variant=\"h6\" component=\"h2\">\n {'Terms'}\n </Typography>\n <Typography variant=\"body2\" color=\"text.secondary\" sx={{ whiteSpace: 'pre-line' }}>\n {quote.terms}\n </Typography>\n </Stack>\n ) : null}\n\n <QuoteProofPanel\n view={quote}\n hostId={hostId}\n quoteId={link.current.quoteId}\n token={link.current.token}\n siteFetch={siteFetch}\n onView={(next) => setState({ kind: 'ready', view: next })}\n onReload={() => void load().then(setState)}\n onReplaced={() => setState({ kind: 'replaced', storeName: quote.storeName, noun })}\n />\n\n {unpaid ? (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={2}>\n {returned === 'confirming' ? (\n <Alert severity=\"info\" icon={<CircularProgress size={20} />}>\n {'Thank you. We’re confirming your payment.'}\n </Alert>\n ) : returned === 'unconfirmed' ? (\n <Alert severity=\"info\">\n {'Your payment is still being confirmed. Your receipt will arrive by email.'}\n </Alert>\n ) : quote.approvalRequired ? (\n <Alert severity=\"info\">\n {`${quote.storeName || 'The business'} asks you to approve the proof before you pay.`}\n </Alert>\n ) : quote.payable ? (\n <>\n {returned === 'failed' ? (\n <Alert severity=\"warning\">{'Your payment did not go through. Nothing was charged.'}</Alert>\n ) : null}\n {nativeCheckout ? (\n <Suspense fallback={<StorefrontPaymentElementFallback />}>\n <StorefrontPaymentElement\n clientSecret={nativeCheckout.clientSecret}\n publishableKey={nativeCheckout.publishableKey}\n wallets={nativeCheckout.wallets}\n payLabel={later ? 'Pay now' : `Pay ${money(quote.totals.totalCents)}`}\n defaultShippingAddress={stripeContact(quote.shipTo)}\n // An expired or unloadable session is replaced by a new press.\n onRestart={() => {\n setNativeCheckout(null)\n void pay()\n }}\n onCancel={() => setNativeCheckout(null)}\n />\n </Suspense>\n ) : (\n <Button\n variant=\"contained\"\n size=\"large\"\n onClick={() => void pay()}\n disabled={paying}\n sx={{ alignSelf: { xs: 'stretch', sm: 'flex-start' } }}\n >\n {paying\n ? 'Opening…'\n : later\n ? `Pay ${money(quote.totals.totalCents)} plus ${later}`\n : `Pay ${money(quote.totals.totalCents)}`}\n </Button>\n )}\n {payError ? <Alert severity=\"error\">{payError}</Alert> : null}\n </>\n ) : (\n <Alert severity=\"info\">\n {quote.notPayableMessage || `Contact ${quote.storeName || 'the business'} to pay this ${noun}.`}\n </Alert>\n )}\n </Stack>\n </Paper>\n ) : (\n <Paper variant=\"outlined\" sx={{ p: { xs: 2, sm: 3 } }}>\n <Stack spacing={1.5} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body1\">\n {quote.status === 'paid'\n ? quote.paidAtMs\n ? `Paid ${dateLabel(quote.paidAtMs)}. Thank you.`\n : 'Paid. Thank you.'\n : `This ${noun} is ${quote.statusLabel.toLowerCase()}.`}\n </Typography>\n {quote.receiptUrl ? (\n <Button variant=\"outlined\" href={quote.receiptUrl}>\n {'View your order'}\n </Button>\n ) : null}\n </Stack>\n </Paper>\n )}\n\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Questions about this ${noun}? Contact ${quote.storeName || 'the business'}.`}\n </Typography>\n </Stack>\n </Box>\n )\n})\nQuotePageBody.displayName = 'QuotePageBody'\n\nexport default QuotePageBody\n\n"],"names":["Aglyn","Alert","Box","Button","Chip","CircularProgress","Divider","Paper","Stack","Typography","forwardRef","lazy","Suspense","useCallback","useEffect","useRef","useState","formatOrderMoney","readStorefrontCheckoutWallets","QuoteProofPanel","StorefrontPaymentElementFallback","StorefrontPaymentElement","then","module","default","nounOf","kind","addedAtPayment","view","shippingAtPayment","taxAtPayment","CONFIRM_POLL_MS","CONFIRM_POLLS","dateLabel","atMs","Date","toLocaleDateString","undefined","month","day","year","addressLines","address","cityLine","city","state","postalCode","filter","Boolean","join","name","line1","line2","country","line","stripeContact","postal_code","AddressBlock","label","lines","spacing","sx","minWidth","flex","variant","color","map","index","TotalRow","value","strong","direction","justifyContent","QuotePageBody","props","ref","heading","rest","nodeSx","Array","isArray","hostId","useSite","siteFetch","useSiteFetch","setState","paying","setPaying","payError","setPayError","nativeCheckout","setNativeCheckout","returned","setReturned","link","quoteId","token","sessionId","load","current","response","encodeURIComponent","payload","json","catch","ok","message","String","error","storeName","noun","params","URLSearchParams","window","location","search","get","live","first","status","poll","Promise","resolve","setTimeout","next","pay","globalThis","attemptKey","crypto","randomUUID","now","Math","random","toString","slice","method","headers","body","JSON","stringify","q","t","v","version","taxKey","tax","clientSecret","publishableKey","wallets","url","assign","replaced","reason","p","border","borderColor","borderRadius","py","textAlign","size","aria-label","component","severity","business","quote","money","cents","currency","pdfHref","unpaid","later","addresses","customerName","company","billTo","shipTo","block","length","totalRows","totals","itemsCents","discountLabel","discountCents","shippingCents","taxLabel","taxCents","shown","alignItems","flexWrap","rowGap","number","statusLabel","dateMs","href","download","xs","sm","variantLabel","description","whiteSpace","included","quantity","unitAmountCents","sku","flexShrink","amountCents","totalCents","notes","terms","onView","onReload","onReplaced","icon","approvalRequired","payable","fallback","payLabel","defaultShippingAddress","onRestart","onCancel","onClick","disabled","alignSelf","notPayableMessage","paidAtMs","toLowerCase","receiptUrl","displayName"],"mappings":";;;AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,SAAS,oBAAmB;AACnC,OAAOC,YAAY,uBAAsB;AACzC,OAAOC,UAAU,qBAAoB;AACrC,OAAOC,sBAAsB,iCAAgC;AAC7D,OAAOC,aAAa,wBAAuB;AAC3C,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,WAAW,sBAAqB;AACvC,OAAOC,gBAAgB,2BAA0B;AAEjD,SAASC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,E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,KAAClL;gCAAWuD,SAAQ;0CACjBoG,MAAM7C,MAAM,KAAK,SACd6C,MAAM4D,QAAQ,GACZ,CAAC,KAAK,EAAE/L,UAAUmI,MAAM4D,QAAQ,EAAE,YAAY,CAAC,GAC/C,qBACF,CAAC,KAAK,EAAElH,KAAK,IAAI,EAAEsD,MAAM2B,WAAW,CAACkC,WAAW,GAAG,CAAC,CAAC;;4BAE1D7D,MAAM8D,UAAU,iBACf,KAAC/N;gCAAO6D,SAAQ;gCAAWiI,MAAM7B,MAAM8D,UAAU;0CAC9C;iCAED;;;;8BAKV,KAACzN;oBAAWuD,SAAQ;oBAAQC,OAAM;8BAC/B,CAAC,qBAAqB,EAAE6C,KAAK,UAAU,EAAEsD,MAAMvD,SAAS,IAAI,eAAe,CAAC,CAAC;;;;;AAKxF;AACApC,cAAc0J,WAAW,GAAG;AAE5B,eAAe1J,cAAa"}
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  import { type HostOrder, type OrderTimelineEvent } from './commerce-orders';
18
- import { type QuoteCheckoutCharge, type QuotePageView, type QuotePayRefusal } from './commerce-quote-pay';
18
+ import { type PayLinkStore, type QuoteCheckoutCharge, type QuotePageView, type QuotePayRefusal } from './commerce-quote-pay';
19
19
  import { type OrderInvoiceSendRecord, type QuoteEmailThread, type QuoteTaxBasis } from './commerce-quotes';
20
20
  import type { ResolvedShippingRate } from './commerce-shipping';
21
21
  /** Which page a pay link opens for an order: a quote, an invoice, or none. */
@@ -60,7 +60,9 @@ export declare function invoiceTaxBasis(order: Pick<HostOrder, 'taxMode' | 'tota
60
60
  * rates it offered when it was made (Stripe asks for the address and the
61
61
  * buyer picks one, as on the draft's first link).
62
62
  */
63
- export declare function invoiceCheckoutCharge(order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string): InvoiceCheckoutCharge;
63
+ export declare function invoiceCheckoutCharge(order: Pick<HostOrder, 'number' | 'lineItems' | 'quote' | 'totals' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string,
64
+ /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */
65
+ store?: PayLinkStore | null): InvoiceCheckoutCharge;
64
66
  /**
65
67
  * Why an order cannot be paid through its pay link now: a quote's reasons,
66
68
  * and two of an invoice's own. `not-payable` is an order the link does not
@@ -68,9 +70,41 @@ export declare function invoiceCheckoutCharge(order: Pick<HostOrder, 'number' |
68
70
  * before drafts kept their shipping rates, whose shipping cannot be charged.
69
71
  */
70
72
  export type InvoicePayRefusal = QuotePayRefusal | 'not-payable' | 'shipping-unknown';
71
- export declare function invoicePayRefusal(order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string): InvoicePayRefusal | null;
73
+ export declare function invoicePayRefusal(order: Pick<HostOrder, 'number' | 'status' | 'lineItems' | 'quote' | 'totals' | 'taxMode' | 'channel'> & Partial<Pick<HostOrder, 'draftShipping'>>, orderId: string,
74
+ /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */
75
+ store?: PayLinkStore | null): InvoicePayRefusal | null;
72
76
  /** What the customer is told for a refusal, in the page's words: "quote" or "invoice". */
73
77
  export declare function invoicePayRefusalMessage(reason: InvoicePayRefusal, storeName: string, kind: OrderPayLinkKind): string;
78
+ /**
79
+ * What stands between a pay link and a payment that the business fixes in
80
+ * the console (AGL-4162):
81
+ *
82
+ * - `payments`: the workspace can't take card payments yet.
83
+ * - `tax-undecided`: the store has not chosen how it handles sales tax.
84
+ * - `tax-save`: the quote was saved before the store chose, and the store's
85
+ * choice now prices it only on a save (`quotePayTax`'s `save`).
86
+ */
87
+ export type PayLinkGap = 'payments' | 'tax-undecided' | 'tax-save';
88
+ /**
89
+ * What the console's "Customers can't pay this … online yet" notice names,
90
+ * for an unpaid quote or a draft order's invoice, or a quote not saved yet
91
+ * (`order: null`), which will be saved under the store's choice as it stands.
92
+ * The same answers Pay refuses on: `invoicePayRefusal` with the store, and
93
+ * the payment account check the page and Pay share.
94
+ *
95
+ * Null while either answer is unknown, so the notice waits rather than tell a
96
+ * store that is set up to set up. Empty for anything the pay link does not
97
+ * charge (a paid, closed or unlinked order) or that nothing stands in front of.
98
+ * A refusal that is not the business's setup (approval, an amount too small)
99
+ * is said where it is decided, not here.
100
+ */
101
+ export declare function payLinkGaps(input: {
102
+ order: (Pick<HostOrder, 'status' | 'channel'> & Partial<Pick<HostOrder, 'quote'>>) | null;
103
+ /** The workspace can take card payments; null while that is unknown. */
104
+ paymentsReady: boolean | null;
105
+ /** The store's sales tax choice; undefined while it is being read. */
106
+ store: PayLinkStore | undefined;
107
+ }): PayLinkGap[] | null;
74
108
  /**
75
109
  * The pay link's page for an order that is not a quote: "Invoice #N", its
76
110
  * lines and totals, the customer's addresses, and Pay while it is unpaid. No
@@ -87,6 +121,10 @@ export declare function buildInvoicePageView(input: {
87
121
  currency: string;
88
122
  /** The order's status page, once paid. */
89
123
  receiptUrl?: string | null;
124
+ /** The store's sales tax choice; with it, a store that has not chosen refuses Pay (AGL-1999). */
125
+ store?: PayLinkStore | null;
126
+ /** Whether the business can take a card payment now; absent, it is not judged here. */
127
+ paymentsReady?: boolean;
90
128
  }): QuotePageView;
91
129
  /** The order's invoice sends on record, oldest first. */
92
130
  export declare function invoiceSends(order: Pick<HostOrder, 'invoiceSends'> | null | undefined): OrderInvoiceSendRecord[];
@@ -113,13 +151,15 @@ export declare function invoiceEmailThread(order: Pick<HostOrder, 'quote' | 'ema
113
151
  */
114
152
  export declare function invoiceEmailDefaultSubject(order: Pick<HostOrder, 'number' | 'quote' | 'emailThread'>, businessName: string, orderId?: string): string;
115
153
  /** Why an invoice cannot be emailed now, and what the console says. */
116
- export type InvoiceSendRefusal = 'unknown' | 'closed' | 'empty' | 'not-payable' | 'approval-required' | 'tax-undecided' | 'nothing-to-pay' | 'shipping-unknown' | 'no-address' | 'bad-address';
154
+ export type InvoiceSendRefusal = 'unknown' | 'closed' | 'empty' | 'not-payable' | 'approval-required' | 'tax-undecided' | 'tax-save' | 'nothing-to-pay' | 'shipping-unknown' | 'no-address' | 'bad-address';
117
155
  /**
118
156
  * Why the order's invoice cannot be emailed to `to` now, if it cannot:
119
157
  * a canceled or refunded order, one with nothing on it, an unpaid order its
120
158
  * pay link cannot take payment for (and why), and the address.
121
159
  */
122
- export declare function invoiceSendRefusal(order: (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>) | null | undefined, orderId: string, to: string): InvoiceSendRefusal | null;
160
+ export declare function invoiceSendRefusal(order: (Pick<HostOrder, 'number' | 'status' | 'channel' | 'lineItems' | 'totals' | 'quote' | 'taxMode'> & Partial<Pick<HostOrder, 'draftShipping'>>) | null | undefined, orderId: string, to: string,
161
+ /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */
162
+ store?: PayLinkStore | null): InvoiceSendRefusal | null;
123
163
  /** What the console says for a refused invoice send. */
124
164
  export declare function invoiceSendRefusalMessage(reason: InvoiceSendRefusal): string;
125
165
  /** The HTTP status a refused send answers with. */
@@ -15,9 +15,10 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */ import { appendOrderEvent, formatOrderNumber, orderCreatedAtMs } from "./commerce-orders.js";
18
- import { QUOTE_MIN_CHARGE_CENTS, payLinkCheckoutCharge, quoteCheckoutCharge, quotePageAddress, quotePageLines, quotePageStatus, quotePayRefusal, quotePayRefusalMessage } from "./commerce-quote-pay.js";
18
+ import { QUOTE_MIN_CHARGE_CENTS, payLinkCheckoutCharge, payLinkPaymentsUnavailableMessage, payLinkRefusalWithPayments, quoteCheckoutCharge, quotePageAddress, quotePageLines, quotePageStatus, quotePayRefusal, quotePayRefusalMessage, quotePayTax } from "./commerce-quote-pay.js";
19
19
  import { lastQuoteSend } from "./commerce-quote-email.js";
20
20
  import { isQuote } from "./commerce-quotes.js";
21
+ import { storefrontTaxDecision } from "./commerce-tax-decision.js";
21
22
  import { lineRequiresShipping } from "./order-fulfillment.js";
22
23
  /** The most invoice sends an order keeps on record; the oldest go first. */ export const INVOICE_MAX_SENDS = 50;
23
24
  const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
@@ -104,10 +105,10 @@ const PAID_STATUSES = new Set([
104
105
  * discount, its tax ({@link invoiceTaxBasis}) and, for a draft, the shipping
105
106
  * rates it offered when it was made (Stripe asks for the address and the
106
107
  * buyer picks one, as on the draft's first link).
107
- */ export function invoiceCheckoutCharge(order, orderId) {
108
+ */ export function invoiceCheckoutCharge(order, orderId, /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */ store) {
108
109
  var _order_lineItems, _ref, _ref1;
109
110
  var _order_totals, _order_draftShipping, _order_draftShipping1;
110
- if (order.quote) return _extends({}, quoteCheckoutCharge(order, orderId), {
111
+ if (order.quote) return _extends({}, quoteCheckoutCharge(order, orderId, store), {
111
112
  shippingOptions: [],
112
113
  shippingCountries: []
113
114
  });
@@ -129,13 +130,16 @@ const PAID_STATUSES = new Set([
129
130
  shippingCountries: options.length ? countries : []
130
131
  });
131
132
  }
132
- export function invoicePayRefusal(order, orderId) {
133
+ export function invoicePayRefusal(order, orderId, /** The store's sales tax choice; with it, a store that has not chosen refuses (AGL-1999). */ store) {
133
134
  var _order_lineItems;
134
135
  const kind = orderPayLinkKind(order);
135
- if (kind === 'quote') return quotePayRefusal(order, orderId);
136
+ if (kind === 'quote') return quotePayRefusal(order, orderId, store);
136
137
  if (order.status === 'cancelled' || order.status === 'refunded') return 'closed';
137
138
  if (order.status !== 'pending') return 'paid';
138
139
  if (kind !== 'invoice') return 'not-payable';
140
+ if (store && storefrontTaxDecision({
141
+ settings: store.tax
142
+ }).kind === 'undecided') return 'tax-undecided';
139
143
  const ships = ((_order_lineItems = order.lineItems) != null ? _order_lineItems : []).some((line)=>line && !line.included && lineRequiresShipping(line));
140
144
  if (ships && !order.draftShipping) return 'shipping-unknown';
141
145
  if (invoiceCheckoutCharge(order, orderId).totalCents < QUOTE_MIN_CHARGE_CENTS) return 'nothing-to-pay';
@@ -162,6 +166,30 @@ export function invoicePayRefusal(order, orderId) {
162
166
  return `This invoice can’t be paid online. Contact ${business} to pay it.`;
163
167
  }
164
168
  }
169
+ /**
170
+ * What the console's "Customers can't pay this … online yet" notice names,
171
+ * for an unpaid quote or a draft order's invoice, or a quote not saved yet
172
+ * (`order: null`), which will be saved under the store's choice as it stands.
173
+ * The same answers Pay refuses on: `invoicePayRefusal` with the store, and
174
+ * the payment account check the page and Pay share.
175
+ *
176
+ * Null while either answer is unknown, so the notice waits rather than tell a
177
+ * store that is set up to set up. Empty for anything the pay link does not
178
+ * charge (a paid, closed or unlinked order) or that nothing stands in front of.
179
+ * A refusal that is not the business's setup (approval, an amount too small)
180
+ * is said where it is decided, not here.
181
+ */ export function payLinkGaps(input) {
182
+ const { order, store } = input;
183
+ if (input.paymentsReady === null || store === undefined) return null;
184
+ if (order && (order.status !== 'pending' || orderPayLinkKind(order) === null)) return [];
185
+ const gaps = [];
186
+ if (!input.paymentsReady) gaps.push('payments');
187
+ if (storefrontTaxDecision({
188
+ settings: store.tax
189
+ }).kind === 'undecided') gaps.push('tax-undecided');
190
+ else if ((order == null ? void 0 : order.quote) && quotePayTax(order.quote, store).source === 'save') gaps.push('tax-save');
191
+ return gaps;
192
+ }
165
193
  /*==========================================
166
194
  * THE CUSTOMER'S PAGE FOR AN INVOICE
167
195
  *=========================================*/ /**
@@ -175,7 +203,8 @@ export function invoicePayRefusal(order, orderId) {
175
203
  const { order } = input;
176
204
  const status = quotePageStatus(order.status);
177
205
  const unpaid = status.status === 'unpaid';
178
- const charge = invoiceCheckoutCharge(order, input.orderId);
206
+ const charge = invoiceCheckoutCharge(order, input.orderId, input.store);
207
+ const refused = unpaid ? payLinkRefusalWithPayments(invoicePayRefusal(order, input.orderId, input.store), input.paymentsReady) : null;
179
208
  const stored = order.totals;
180
209
  const totals = unpaid || !stored ? {
181
210
  itemsCents: charge.itemsCents,
@@ -218,7 +247,9 @@ export function invoicePayRefusal(order, orderId) {
218
247
  paidAtMs: orderPaidAtMs(order),
219
248
  receiptUrl: unpaid ? null : (_input_receiptUrl = input.receiptUrl) != null ? _input_receiptUrl : null,
220
249
  approvalRequired: false,
221
- payable: unpaid && invoicePayRefusal(order, input.orderId) === null,
250
+ payable: unpaid && refused === null,
251
+ notPayableMessage: refused === 'payments-unavailable' ? payLinkPaymentsUnavailableMessage(input.storeName, 'invoice') : null,
252
+ taxKey: null,
222
253
  revision: 1,
223
254
  proofs: [],
224
255
  response: null,
@@ -274,7 +305,7 @@ export function invoicePayRefusal(order, orderId) {
274
305
  * Why the order's invoice cannot be emailed to `to` now, if it cannot:
275
306
  * a canceled or refunded order, one with nothing on it, an unpaid order its
276
307
  * pay link cannot take payment for (and why), and the address.
277
- */ export function invoiceSendRefusal(order, orderId, to) {
308
+ */ export function invoiceSendRefusal(order, orderId, to, /** The store's sales tax choice, as the pay link reads it (`invoicePayRefusal`). */ store) {
278
309
  var _order_lineItems;
279
310
  var _order_totals;
280
311
  if (!order) return 'unknown';
@@ -282,8 +313,12 @@ export function invoicePayRefusal(order, orderId) {
282
313
  const lines = ((_order_lineItems = order.lineItems) != null ? _order_lineItems : []).filter(Boolean);
283
314
  if (!lines.length && cents((_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) <= 0) return 'empty';
284
315
  if (!invoiceIsPaid(order)) {
285
- const refused = invoicePayRefusal(order, orderId);
316
+ const refused = invoicePayRefusal(order, orderId, store);
286
317
  if (refused === 'closed') return 'closed';
318
+ // A quote saved before the store chose: the store has chosen, and a save prices it.
319
+ if (refused === 'tax-undecided' && order.quote && quotePayTax(order.quote, store).source === 'save') {
320
+ return 'tax-save';
321
+ }
287
322
  if (refused && refused !== 'paid') return refused;
288
323
  }
289
324
  if (!to) return 'no-address';
@@ -304,6 +339,8 @@ export function invoicePayRefusal(order, orderId) {
304
339
  return 'This quote asks your customer to approve the proof before they pay, and they haven’t yet. Send the quote so they can approve it, then send the invoice.';
305
340
  case 'tax-undecided':
306
341
  return 'Sales tax isn’t set up for this store yet, so the invoice can’t be paid online. Finish the tax settings, then send it.';
342
+ case 'tax-save':
343
+ return 'This quote was saved before your store chose how it handles sales tax. Save the quote again, then send the invoice.';
307
344
  case 'nothing-to-pay':
308
345
  return 'This invoice totals less than $0.50, so it can’t be paid by card.';
309
346
  case 'shipping-unknown':