@aglyn/plugins-commerce 1.10.0 → 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 (47) 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/commerce-pdf.js +2 -1
  27. package/src/lib/server/commerce-pdf.js.map +1 -1
  28. package/src/lib/server/invoice-email.js +2 -1
  29. package/src/lib/server/invoice-email.js.map +1 -1
  30. package/src/lib/server/order-invoice-send.js +1 -1
  31. package/src/lib/server/order-invoice-send.js.map +1 -1
  32. package/src/lib/server/order-status.d.ts +5 -1
  33. package/src/lib/server/order-status.js +19 -5
  34. package/src/lib/server/order-status.js.map +1 -1
  35. package/src/lib/server/quote-email.js +2 -1
  36. package/src/lib/server/quote-email.js.map +1 -1
  37. package/src/lib/server/quote-pay.d.ts +39 -0
  38. package/src/lib/server/quote-pay.js +103 -43
  39. package/src/lib/server/quote-pay.js.map +1 -1
  40. package/src/lib/server/quote-proofs.js +13 -9
  41. package/src/lib/server/quote-proofs.js.map +1 -1
  42. package/src/lib/utils/invoice-email-content.d.ts +3 -1
  43. package/src/lib/utils/invoice-email-content.js +1 -1
  44. package/src/lib/utils/invoice-email-content.js.map +1 -1
  45. package/src/lib/utils/quote-email-content.d.ts +3 -1
  46. package/src/lib/utils/quote-email-content.js +3 -3
  47. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-email.ts"],"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 { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n PLATFORM_EMAIL_PALETTE,\n readEmailThread,\n resolveEmailColor,\n sendEmail,\n type EmailTheme,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n siteEmailFrame,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { QUOTE_EMAIL_KEY, quoteEmailContent, type QuoteEmailColors } from '../utils/quote-email-content'\nimport type { quotePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\n\n/*==========================================\n * SENDING THE QUOTE EMAIL (AGL-4097). Loaded only by the console's Send\n * quote (`POST commerce/quote { action: 'send' }`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `quote-sent` catalog key in the site's theme and its header\n * and footer (or the site's own design of it), with the quote's PDF attached:\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email (its listing's, else its support\n * email), else the email of the person sending, so a reply reaches the\n * business either way, as an inbox reply's does;\n * - IN THE CUSTOMER'S CONVERSATION: a `Message-ID` minted on the sending\n * domain, and, when the quote already has a conversation (an earlier\n * send, or a request's confirmation), `In-Reply-To` and `References`\n * from it, else the root of the one it starts in `References`\n * (`nextThreadHeaders`). The provider's own id is returned beside ours,\n * because a provider may replace a caller's `Message-ID` (in production\n * one does), and a replaced one can then be traced;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam (`transactionalAddressSuppression`): the customer asked for the\n * quote, so an unsubscribe from the site's newsletter does not stop it,\n * as it does not stop a receipt (AGL-4098).\n *\n * The route decides everything about the quote (who may send, the link, the\n * stage); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface QuoteDeliveryInput {\n hostId: string\n quoteId: string\n /** The quote as it stands, after any pay link replacement this send made. */\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n store: Record<string, unknown> | null\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The subject as typed; empty takes the default. */\n subject: string\n message: string\n payUrl: string\n proofUrl: (proofId: string) => string | null\n linkReplaced: boolean\n /** The sending member's email: the Reply-To when the site has no contact email. */\n senderEmail: string | null\n atMs: number\n}\n\nexport type QuoteDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface QuoteMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The site's email theme, for the colors the composed proof markup draws with. */\n theme(hostId: string): Promise<EmailTheme | null>\n /** The quote's PDF; loads the PDF writer and sharp only here. */\n quotePdf(input: Parameters<typeof quotePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: a quote is mail the customer asked for. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultQuoteMailerDeps(): QuoteMailerDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) => renderHostEmailWithTokens(firestore(), hostId, key, tokens),\n theme: async (hostId) => (await siteEmailFrame(firestore(), hostId, QUOTE_EMAIL_KEY)).theme,\n quotePdf: async (input) => (await import('./commerce-pdf')).quotePdfFile(input),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n }\n}\n\n/** What the console's Send quote reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface QuoteMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: QuoteDeliveryInput): Promise<QuoteDeliveryResult>\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The business's name as its documents print it. */\nexport function quoteBusinessName(host: Record<string, unknown>): string {\n const named = resolveHostToken('businessName', host as HostTokenSource)\n return String(named ?? '').trim() || String(host['name'] ?? '').trim()\n}\n\n/**\n * Who a reply reaches: the site's contact email, else the person sending, as\n * an inbox reply answers to them. Null only when neither is an address.\n */\nexport function quoteReplyTo(host: Record<string, unknown>, senderEmail: string | null | undefined): string | null {\n const contact = siteContactEmail(host as never)\n if (contact && EMAIL.test(contact)) return contact\n const sender = String(senderEmail ?? '').trim()\n return EMAIL.test(sender) ? sender : null\n}\n\n/** The theme's colors for the composed proof markup, the platform's where the site's cannot answer. */\nfunction proofColors(theme: EmailTheme | null): QuoteEmailColors {\n const read = (token: string) =>\n resolveEmailColor(token, theme?.palette) ?? resolveEmailColor(token, PLATFORM_EMAIL_PALETTE) ?? 'inherit'\n return { border: read('divider'), muted: read('text.secondary') }\n}\n\n/** A refused send in the words the console shows. */\nfunction refusalOf(result: Extract<SendEmailResult, { sent: false }>): { status: number; error: string } {\n switch (result.reason) {\n case 'unconfigured':\n return { status: 503, error: 'Email isn’t set up here, so the quote wasn’t sent.' }\n case 'rate-limited':\n return { status: 429, error: 'Too many emails are going out right now. Try again in a minute.' }\n case 'suppressed':\n case 'undeliverable':\n return { status: 409, error: 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the quote wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the quote wasn’t sent.' }\n case 'held-for-review':\n return { status: 409, error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}` }\n default:\n return { status: 502, error: 'The quote email could not be sent. Try again.' }\n }\n}\n\n/** The quote email, said and sent. */\nexport function quoteMailer(deps: QuoteMailerDeps = defaultQuoteMailerDeps()): QuoteMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, quoteId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId)\n const [identity, theme] = await Promise.all([\n deps.sendingIdentity(hostId),\n deps.theme(hostId).catch(() => null),\n ])\n\n const content = quoteEmailContent({\n order,\n quoteId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n proofUrl: input.proofUrl,\n linkReplaced: input.linkReplaced,\n colors: proofColors(theme),\n radius: theme?.buttonRadius,\n })\n\n // The PDF is what the email says is attached; without it nothing goes.\n let pdf: CommercePdfFile\n try {\n pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/quote-email] the PDF could not be made', { hostId, quoteId, error })\n return { sent: false, status: 500, error: 'The quote’s PDF could not be made, so nothing was sent. Try again.' }\n }\n\n const rendered = await deps.render(hostId, QUOTE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(order.quote?.emailThread)\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'quote',\n atMs: input.atMs,\n })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n\n const result = await deps.send({\n to: input.to,\n // The subject as sent, whatever a design's own says: it is what keeps\n // the conversation together, and it was typed for this send.\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'quote',\n attachments: [\n {\n filename: pdf.filename,\n contentType: 'application/pdf',\n content: Buffer.from(pdf.bytes).toString('base64'),\n },\n ],\n })\n if (!result.sent) return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>) }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(hostId).catch((error) => console.error('[commerce/quote-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n }\n },\n }\n}\n"],"names":["siteContactEmail","resolveHostToken","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","PLATFORM_EMAIL_PALETTE","readEmailThread","resolveEmailColor","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","siteEmailFrame","transactionalAddressSuppression","CommerceModel","QUOTE_EMAIL_KEY","quoteEmailContent","defaultQuoteMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","theme","quotePdf","input","quotePdfFile","send","options","meter","suppression","email","EMAIL","quoteBusinessName","host","named","String","trim","quoteReplyTo","senderEmail","contact","test","sender","proofColors","read","token","palette","border","muted","refusalOf","result","reason","status","error","detail","quoteMailer","deps","deliver","order","quoteId","businessName","subject","quoteEmailDefaultSubject","identity","Promise","all","catch","content","currency","store","message","payUrl","proofUrl","linkReplaced","colors","radius","buttonRadius","pdf","owner","console","sent","rendered","thread","quote","emailThread","siteHost","messageId","domain","from","label","atMs","replyTo","to","text","html","headers","fromName","org","audience","context","attachments","filename","contentType","Buffer","bytes","toString","providerId","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,EACfC,iBAAiB,EACjBC,SAAS,QAMJ,2BAA0B;AACjC,SACEC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,cAAc,EACdC,+BAA+B,QAC1B,2BAA0B;AACjC,YAAYC,mBAAmB,oBAAU;AACzC,SAASC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MAAMT,MAAMc,WAAW;YAEpD,MAAMW,SAAS,MAAMM,KAAK7B,IAAI,CAAC;gBAC7BiE,IAAInE,MAAMmE,EAAE;gBACZ,sEAAsE;gBACtE,6DAA6D;gBAC7D/B;gBACAgC,MAAMZ,CAAAA,4BAAAA,SAAUY,IAAI,KAAI1B,QAAQ0B,IAAI;eAChCZ,CAAAA,4BAAAA,SAAUa,IAAI,IAAG;gBAAEA,MAAMb,SAASa,IAAI;YAAC,IAAI,CAAC;gBAChDC,SAAS/F,kBAAkBkF,QAAQI;eAC/BK,UAAU;gBAAEA;YAAQ,IAAI,CAAC;gBAC7BK,UAAUpG,wBAAuB6B,eAAAA,MAAMqD,KAAK,qBAAXrD,aAAawE,GAAG,EAAWD,QAAQ;gBACpE9E,iBAAiB6C;gBACjBmC,UAAU;gBACVC,SAAS;gBACTC,aAAa;oBACX;wBACEC,UAAUxB,IAAIwB,QAAQ;wBACtBC,aAAa;wBACbnC,SAASoC,OAAOf,IAAI,CAACX,IAAI2B,KAAK,EAAEC,QAAQ,CAAC;oBAC3C;iBACD;;YAEH,IAAI,CAACvD,OAAO8B,IAAI,EAAE,OAAO;gBAAEA,MAAM;eAAU/B,UAAUC;YACrD,4DAA4D;YAC5D,MAAMM,KAAK3B,KAAK,CAACV,QAAQ+C,KAAK,CAAC,CAACb,QAAU0B,QAAQ1B,KAAK,CAAC,sCAAsCA;YAC9F,OAAO;gBACL2B,MAAM;gBACNM;gBACAoB,UAAU,GAAE,aAAA,AAACxD,OAAoDyD,EAAE,YAAvD,aAA2D;gBACvE9C;gBACA8B;gBACAT,QAAQrF,qBAAqBqF,QAAQ;oBAAEI;oBAAWzB;gBAAQ;YAC5D;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-email.ts"],"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 { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n PLATFORM_EMAIL_PALETTE,\n readEmailThread,\n resolveEmailColor,\n sendEmail,\n type EmailTheme,\n type RenderedHostEmail,\n type SendEmailOptions,\n type SendEmailResult,\n type SendingIdentityVerdict,\n} from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostSendingIdentity,\n meterHostEmail,\n renderHostEmailWithTokens,\n siteEmailFrame,\n transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { QUOTE_EMAIL_KEY, quoteEmailContent, type QuoteEmailColors } from '../utils/quote-email-content'\nimport type { quotePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\n\n/*==========================================\n * SENDING THE QUOTE EMAIL (AGL-4097). Loaded only by the console's Send\n * quote (`POST commerce/quote { action: 'send' }`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `quote-sent` catalog key in the site's theme and its header\n * and footer (or the site's own design of it), with the quote's PDF attached:\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email (its listing's, else its support\n * email), else the email of the person sending, so a reply reaches the\n * business either way, as an inbox reply's does;\n * - IN THE CUSTOMER'S CONVERSATION: a `Message-ID` minted on the sending\n * domain, and, when the quote already has a conversation (an earlier\n * send, or a request's confirmation), `In-Reply-To` and `References`\n * from it, else the root of the one it starts in `References`\n * (`nextThreadHeaders`). The provider's own id is returned beside ours,\n * because a provider may replace a caller's `Message-ID` (in production\n * one does), and a replaced one can then be traced;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam (`transactionalAddressSuppression`): the customer asked for the\n * quote, so an unsubscribe from the site's newsletter does not stop it,\n * as it does not stop a receipt (AGL-4098).\n *\n * The route decides everything about the quote (who may send, the link, the\n * stage); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface QuoteDeliveryInput {\n hostId: string\n quoteId: string\n /** The quote as it stands, after any pay link replacement this send made. */\n order: CommerceModel.HostOrder\n host: Record<string, unknown>\n store: Record<string, unknown> | null\n owner: { id?: string; org?: unknown } | null\n to: string\n /** The subject as typed; empty takes the default. */\n subject: string\n message: string\n payUrl: string\n proofUrl: (proofId: string) => string | null\n linkReplaced: boolean\n /** The sending member's email: the Reply-To when the site has no contact email. */\n senderEmail: string | null\n atMs: number\n}\n\nexport type QuoteDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface QuoteMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The site's email theme, for the colors the composed proof markup draws with. */\n theme(hostId: string): Promise<EmailTheme | null>\n /** The quote's PDF; loads the PDF writer and sharp only here. */\n quotePdf(input: Parameters<typeof quotePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: a quote is mail the customer asked for. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultQuoteMailerDeps(): QuoteMailerDeps {\n const firestore = () => firebaseAdmin.app().firestore()\n return {\n configured: () => isEmailConfigured(),\n sendingIdentity: (hostId) => hostSendingIdentity(hostId),\n render: (hostId, key, tokens) => renderHostEmailWithTokens(firestore(), hostId, key, tokens),\n theme: async (hostId) => (await siteEmailFrame(firestore(), hostId, QUOTE_EMAIL_KEY)).theme,\n quotePdf: async (input) => (await import('./commerce-pdf')).quotePdfFile(input),\n send: (options) => sendEmail(options),\n meter: async (hostId) => {\n await meterHostEmail(hostId)\n },\n suppression: (email) => transactionalAddressSuppression(email),\n }\n}\n\n/** What the console's Send quote reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface QuoteMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: QuoteDeliveryInput): Promise<QuoteDeliveryResult>\n}\n\nconst EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/** The business's name as its documents print it. */\nexport function quoteBusinessName(host: Record<string, unknown>): string {\n const named = resolveHostToken('businessName', host as HostTokenSource)\n return String(named ?? '').trim() || String(host['name'] ?? '').trim()\n}\n\n/**\n * Who a reply reaches: the site's contact email, else the person sending, as\n * an inbox reply answers to them. Null only when neither is an address.\n */\nexport function quoteReplyTo(host: Record<string, unknown>, senderEmail: string | null | undefined): string | null {\n const contact = siteContactEmail(host as never)\n if (contact && EMAIL.test(contact)) return contact\n const sender = String(senderEmail ?? '').trim()\n return EMAIL.test(sender) ? sender : null\n}\n\n/** The theme's colors for the composed proof markup, the platform's where the site's cannot answer. */\nfunction proofColors(theme: EmailTheme | null): QuoteEmailColors {\n const read = (token: string) =>\n resolveEmailColor(token, theme?.palette) ?? resolveEmailColor(token, PLATFORM_EMAIL_PALETTE) ?? 'inherit'\n return { border: read('divider'), muted: read('text.secondary') }\n}\n\n/** A refused send in the words the console shows. */\nfunction refusalOf(result: Extract<SendEmailResult, { sent: false }>): { status: number; error: string } {\n switch (result.reason) {\n case 'unconfigured':\n return { status: 503, error: 'Email isn’t set up here, so the quote wasn’t sent.' }\n case 'rate-limited':\n return { status: 429, error: 'Too many emails are going out right now. Try again in a minute.' }\n case 'suppressed':\n case 'undeliverable':\n return { status: 409, error: 'This address can’t receive email, so the quote wasn’t sent. Copy the pay link and send it another way.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the quote wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the quote wasn’t sent.' }\n case 'held-for-review':\n return { status: 409, error: `The email was held for review, so it hasn’t gone out yet.${result.detail ? ` ${result.detail}` : ''}` }\n default:\n return { status: 502, error: 'The quote email could not be sent. Try again.' }\n }\n}\n\n/** The quote email, said and sent. */\nexport function quoteMailer(deps: QuoteMailerDeps = defaultQuoteMailerDeps()): QuoteMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, quoteId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.quoteEmailDefaultSubject(order, businessName, quoteId)\n const [identity, theme] = await Promise.all([\n deps.sendingIdentity(hostId),\n deps.theme(hostId).catch(() => null),\n ])\n\n const content = quoteEmailContent({\n order,\n quoteId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n proofUrl: input.proofUrl,\n linkReplaced: input.linkReplaced,\n colors: proofColors(theme),\n radius: theme?.buttonRadius,\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n\n // The PDF is what the email says is attached; without it nothing goes.\n let pdf: CommercePdfFile\n try {\n pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/quote-email] the PDF could not be made', { hostId, quoteId, error })\n return { sent: false, status: 500, error: 'The quote’s PDF could not be made, so nothing was sent. Try again.' }\n }\n\n const rendered = await deps.render(hostId, QUOTE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(order.quote?.emailThread)\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'quote',\n atMs: input.atMs,\n })\n const replyTo = quoteReplyTo(host, input.senderEmail)\n\n const result = await deps.send({\n to: input.to,\n // The subject as sent, whatever a design's own says: it is what keeps\n // the conversation together, and it was typed for this send.\n subject,\n text: rendered?.text || content.text,\n ...(rendered?.html ? { html: rendered.html } : {}),\n headers: nextThreadHeaders(thread, messageId),\n ...(replyTo ? { replyTo } : {}),\n fromName: resolveBrandingProfile(input.owner?.org as never).fromName,\n sendingIdentity: identity,\n audience: 'tenant',\n context: 'quote',\n attachments: [\n {\n filename: pdf.filename,\n contentType: 'application/pdf',\n content: Buffer.from(pdf.bytes).toString('base64'),\n },\n ],\n })\n if (!result.sent) return { sent: false, ...refusalOf(result as Extract<SendEmailResult, { sent: false }>) }\n // Cost meter (AGL-1438), as every transactional site email.\n await deps.meter(hostId).catch((error) => console.error('[commerce/quote-email] not metered', error))\n return {\n sent: true,\n messageId,\n providerId: (result as Extract<SendEmailResult, { sent: true }>).id ?? null,\n subject,\n replyTo,\n thread: emailThreadAfterSend(thread, { messageId, subject }),\n }\n },\n }\n}\n"],"names":["siteContactEmail","resolveHostToken","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","PLATFORM_EMAIL_PALETTE","readEmailThread","resolveEmailColor","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","siteEmailFrame","transactionalAddressSuppression","CommerceModel","QUOTE_EMAIL_KEY","quoteEmailContent","defaultQuoteMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","theme","quotePdf","input","quotePdfFile","send","options","meter","suppression","email","EMAIL","quoteBusinessName","host","named","String","trim","quoteReplyTo","senderEmail","contact","test","sender","proofColors","read","token","palette","border","muted","refusalOf","result","reason","status","error","detail","quoteMailer","deps","deliver","order","quoteId","businessName","subject","quoteEmailDefaultSubject","identity","Promise","all","catch","content","currency","store","message","payUrl","proofUrl","linkReplaced","colors","radius","buttonRadius","payLinkStoreOf","pdf","owner","console","sent","rendered","thread","quote","emailThread","siteHost","messageId","domain","from","label","atMs","replyTo","to","text","html","headers","fromName","org","audience","context","attachments","filename","contentType","Buffer","bytes","toString","providerId","id"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,EACfC,iBAAiB,EACjBC,SAAS,QAMJ,2BAA0B;AACjC,SACEC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,cAAc,EACdC,+BAA+B,QAC1B,2BAA0B;AACjC,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,eAAe,EAAEC,iBAAiB,QAA+B,kCAA8B;AAgFxG,OAAO,SAASC;IACd,MAAMC,YAAY,IAAMV,cAAcW,GAAG,GAAGD,SAAS;IACrD,OAAO;QACLE,YAAY,IAAMnB;QAClBoB,iBAAiB,CAACC,SAAWb,oBAAoBa;QACjDC,QAAQ,CAACD,QAAQE,KAAKC,SAAWd,0BAA0BO,aAAaI,QAAQE,KAAKC;QACrFC,OAAO,OAAOJ,SAAW,AAAC,CAAA,MAAMV,eAAeM,aAAaI,QAAQP,gBAAe,EAAGW,KAAK;QAC3FC,UAAU,OAAOC,QAAU,AAAC,CAAA,MAAM,MAAM,CAAC,oBAAgB,EAAGC,YAAY,CAACD;QACzEE,MAAM,CAACC,UAAYxB,UAAUwB;QAC7BC,OAAO,OAAOV;YACZ,MAAMZ,eAAeY;QACvB;QACAW,aAAa,CAACC,QAAUrB,gCAAgCqB;IAC1D;AACF;AASA,MAAMC,QAAQ;AAEd,mDAAmD,GACnD,OAAO,SAASC,kBAAkBC,IAA6B;QAEjBA;IAD5C,MAAMC,QAAQxC,iBAA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AAI2B,KAAK,EAAEC,QAAQ,CAAC;oBAC3C;iBACD;;YAEH,IAAI,CAACxD,OAAO+B,IAAI,EAAE,OAAO;gBAAEA,MAAM;eAAUhC,UAAUC;YACrD,4DAA4D;YAC5D,MAAMM,KAAK3B,KAAK,CAACV,QAAQ+C,KAAK,CAAC,CAACb,QAAU2B,QAAQ3B,KAAK,CAAC,sCAAsCA;YAC9F,OAAO;gBACL4B,MAAM;gBACNM;gBACAoB,UAAU,GAAE,aAAA,AAACzD,OAAoD0D,EAAE,YAAvD,aAA2D;gBACvE/C;gBACA+B;gBACAT,QAAQtF,qBAAqBsF,QAAQ;oBAAEI;oBAAW1B;gBAAQ;YAC5D;QACF;IACF;AACF"}
@@ -95,6 +95,39 @@ export declare function quoteLinkParams(source: Record<string, unknown>): {
95
95
  token: string;
96
96
  complete: boolean;
97
97
  };
98
+ /** Whether the business behind a pay link can take a card payment now, and with what. */
99
+ export interface PayLinkPayments {
100
+ ready: boolean;
101
+ /** The site's workspace, for the platform fee and the attempt's record. */
102
+ owner: {
103
+ id?: string;
104
+ org?: any;
105
+ } | null;
106
+ /** The owner's payment account; empty unless `ready`. */
107
+ accountId: string;
108
+ }
109
+ /**
110
+ * The one payments check a pay link answers on: the workspace's plan
111
+ * includes commerce, and the workspace OWNER's payment account can take
112
+ * charges (`merchantAccountIsReady`, the check every money route makes). The
113
+ * page asks it before offering Pay and Pay asks it before charging, so the
114
+ * two never disagree.
115
+ */
116
+ export declare function payLinkPayments(deps: QuotePayDeps, input: {
117
+ hostId: string;
118
+ orderId: string;
119
+ kind: CommerceModel.OrderPayLinkKind;
120
+ }): Promise<PayLinkPayments>;
121
+ /**
122
+ * The page's view of a linked quote or invoice: the allow-listed projection,
123
+ * priced under the store's tax choice and with Pay only where the business
124
+ * can take it. A paid one asks nothing about payments.
125
+ */
126
+ export declare function payLinkPageView(deps: QuotePayDeps, input: {
127
+ hostId: string;
128
+ orderId: string;
129
+ loaded: Pick<LoadedQuote, 'host' | 'order' | 'storeName' | 'store' | 'kind'>;
130
+ }): Promise<CommerceModel.QuotePageView>;
98
131
  /** `GET /api/commerce/quote-view`: the quote page's data. */
99
132
  export declare function handleQuoteView(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome>;
100
133
  /** The Checkout Session a quote's (or an invoice's) Pay opens, as form params. Pure over its inputs. */
@@ -108,6 +141,12 @@ export declare function buildQuoteSessionParams(input: {
108
141
  taxRateId: string;
109
142
  returnUrl: string;
110
143
  paymentMethods: CommerceModel.StorefrontPaymentMethodControls;
144
+ /**
145
+ * The tax basis charged when it is not the quote's stored one: a quote
146
+ * saved before the store chose its sales tax, priced under the choice now
147
+ * (`quotePayTax`, AGL-4162). The webhook records it on the paid order.
148
+ */
149
+ chargedTax?: CommerceModel.QuoteTaxBasis | null;
111
150
  }): URLSearchParams;
112
151
  /** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */
113
152
  export declare function handleQuotePay(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome>;
@@ -55,6 +55,13 @@ import { verifyQuoteLinkToken } from "./quote-link-token.js";
55
55
  * The payment completes in `billing-webhook.ts`, which turns this same
56
56
  * document into the order (`paidQuoteOrder`); nothing here marks it paid.
57
57
  *
58
+ * THE PAGE OFFERS ONLY A PAY THAT WORKS (AGL-4162). The view asks the same
59
+ * payments check Pay refuses on ({@link payLinkPayments}) and prices the tax
60
+ * the same way (`quotePayTax`): a quote saved before the store chose its
61
+ * sales tax is shown and charged under the store's choice now, and Pay
62
+ * refuses when that choice is not the one the page showed (`tax`). The
63
+ * session carries that basis (`quoteTax`) so the paid order records it.
64
+ *
58
65
  * AN INVOICE'S LINK IS THIS ONE (AGL-4099). A draft order the business sent
59
66
  * an invoice for opens on the same page from the same kind of link (its
60
67
  * version on `payLink.version`, `commerce-invoices.ts`), as "Invoice #N" with
@@ -224,8 +231,67 @@ function headerOf(req, name) {
224
231
  complete
225
232
  };
226
233
  }
234
+ /**
235
+ * The one payments check a pay link answers on: the workspace's plan
236
+ * includes commerce, and the workspace OWNER's payment account can take
237
+ * charges (`merchantAccountIsReady`, the check every money route makes). The
238
+ * page asks it before offering Pay and Pay asks it before charging, so the
239
+ * two never disagree.
240
+ */ export async function payLinkPayments(deps, input) {
241
+ var _owner_org;
242
+ const owner = await deps.orgForHost(input.hostId);
243
+ if (!checkEntitlement(owner == null ? void 0 : owner.org, 'commerce')) return {
244
+ ready: false,
245
+ owner,
246
+ accountId: ''
247
+ };
248
+ const ownerUid = owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.ownerUid;
249
+ const profile = ownerUid ? await deps.firestore().collection('profiles').doc(String(ownerUid)).get() : null;
250
+ const accountId = profile == null ? void 0 : profile.get('stripeAccountId');
251
+ const ready = merchantAccountIsReady({
252
+ accountId,
253
+ chargesEnabled: profile == null ? void 0 : profile.get('stripeChargesEnabled'),
254
+ accountLivemode: profile == null ? void 0 : profile.get('stripeAccountLivemode')
255
+ }, {
256
+ subject: `${nounOf(input.kind)} ${input.orderId} on host ${input.hostId}`
257
+ });
258
+ return {
259
+ ready,
260
+ owner,
261
+ accountId: ready ? String(accountId) : ''
262
+ };
263
+ }
264
+ /**
265
+ * The page's view of a linked quote or invoice: the allow-listed projection,
266
+ * priced under the store's tax choice and with Pay only where the business
267
+ * can take it. A paid one asks nothing about payments.
268
+ */ export async function payLinkPageView(deps, input) {
269
+ var _store_get;
270
+ const { hostId, orderId } = input;
271
+ const { host, order, storeName, store, kind } = input.loaded;
272
+ const currency = String((_store_get = store.get('currency')) != null ? _store_get : 'USD');
273
+ const unpaid = order.status === 'pending';
274
+ const receiptUrl = unpaid ? null : orderStatusUrl(host, hostId, orderId);
275
+ const paymentsReady = unpaid ? (await payLinkPayments(deps, {
276
+ hostId,
277
+ orderId,
278
+ kind
279
+ })).ready : undefined;
280
+ const view = {
281
+ order,
282
+ orderId,
283
+ storeName,
284
+ currency,
285
+ receiptUrl,
286
+ store: CommerceModel.payLinkStoreOf({
287
+ tax: store.get('tax')
288
+ }),
289
+ paymentsReady
290
+ };
291
+ return kind === 'quote' ? CommerceModel.buildQuotePageView(view) : CommerceModel.buildInvoicePageView(view);
292
+ }
227
293
  /** `GET /api/commerce/quote-view`: the quote page's data. */ export async function handleQuoteView(deps, req) {
228
- var _req_query, _store_get;
294
+ var _req_query;
229
295
  if (req.method !== 'GET') return {
230
296
  status: 405,
231
297
  body: {
@@ -259,21 +325,10 @@ function headerOf(req, name) {
259
325
  }
260
326
  return linked.outcome;
261
327
  }
262
- const { host, order, storeName, store, kind } = linked.loaded;
263
- const currency = String((_store_get = store.get('currency')) != null ? _store_get : 'USD');
264
- const receiptUrl = order.status === 'pending' ? null : orderStatusUrl(host, hostId, quoteId);
265
- const view = kind === 'quote' ? CommerceModel.buildQuotePageView({
266
- order,
267
- orderId: quoteId,
268
- storeName,
269
- currency,
270
- receiptUrl
271
- }) : CommerceModel.buildInvoicePageView({
272
- order,
328
+ const view = await payLinkPageView(deps, {
329
+ hostId,
273
330
  orderId: quoteId,
274
- storeName,
275
- currency,
276
- receiptUrl
331
+ loaded: linked.loaded
277
332
  });
278
333
  return {
279
334
  status: 200,
@@ -359,6 +414,7 @@ function headerOf(req, name) {
359
414
  params.set('metadata[quoteId]', input.quoteId);
360
415
  params.set('metadata[quoteLinkVersion]', String(CommerceModel.quoteLinkVersion(quote)));
361
416
  params.set('metadata[quoteUpdatedAtMs]', String(Number(quote.updatedAtMs) || 0));
417
+ if (input.chargedTax) params.set('metadata[quoteTax]', CommerceModel.quoteTaxBasisKey(input.chargedTax));
362
418
  }
363
419
  params.set('metadata[feeCents]', String(input.feeCents));
364
420
  // A tax charged as its own line is invisible to Stripe's tax total; this
@@ -386,8 +442,8 @@ const refusal = (status, reason, error, extra = {})=>({
386
442
  }, extra)
387
443
  });
388
444
  /** `POST /api/commerce/quote-pay`: a fresh Checkout Session for the quote. */ export async function handleQuotePay(deps, req) {
389
- var _store_get, _ref, _order_checkoutSessionId, _ref1;
390
- var _order_quote, _owner_org, _order_quote1;
445
+ var _ref, _order_checkoutSessionId, _ref1;
446
+ var _order_quote, _order_quote1;
391
447
  if (req.method !== 'POST') return {
392
448
  status: 405,
393
449
  body: {
@@ -425,34 +481,38 @@ const refusal = (status, reason, error, extra = {})=>({
425
481
  // Every refusal the customer can be given is above the claim, so none of
426
482
  // them spends the press. `v` is the edit of the quote the page showed: a
427
483
  // quote changed since is shown again before it is paid, never charged unseen.
428
- // An invoice is not edited, so it sends none.
429
- const seen = Number(bodyOf(req)['v']);
484
+ // An invoice is not edited, so it sends none. `tax` is the tax the page
485
+ // priced it under: a quote saved before the store chose its sales tax is
486
+ // priced under the choice as it stands, so one the store changed since, or
487
+ // a page that did not say, is shown again too.
488
+ const body = bodyOf(req);
489
+ const seen = Number(body['v']);
430
490
  if (kind === 'quote' && Number.isFinite(seen) && seen > 0 && seen !== (Number((_order_quote = order.quote) == null ? void 0 : _order_quote.updatedAtMs) || 0)) {
431
491
  return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE);
432
492
  }
433
- const blocked = CommerceModel.invoicePayRefusal(order, quoteId);
434
- if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind));
435
- const owner = await deps.orgForHost(hostId);
436
- const unavailable = refusal(409, 'payments-unavailable', `${storeName || 'This business'} can’t take payments online right now. Contact them to pay this ${noun}.`);
437
- if (!checkEntitlement(owner == null ? void 0 : owner.org, 'commerce')) return unavailable;
438
- const ownerUid = owner == null ? void 0 : (_owner_org = owner.org) == null ? void 0 : _owner_org.ownerUid;
439
- const profile = ownerUid ? await deps.firestore().collection('profiles').doc(String(ownerUid)).get() : null;
440
- const accountId = profile == null ? void 0 : profile.get('stripeAccountId');
441
- const ready = merchantAccountIsReady({
442
- accountId,
443
- chargesEnabled: profile == null ? void 0 : profile.get('stripeChargesEnabled'),
444
- accountLivemode: profile == null ? void 0 : profile.get('stripeAccountLivemode')
445
- }, {
446
- subject: `${noun} ${quoteId} on host ${hostId}`
493
+ const payStore = CommerceModel.payLinkStoreOf({
494
+ tax: store.get('tax')
447
495
  });
448
- if (!ready) return unavailable;
449
- const taxSettings = (_store_get = store.get('tax')) != null ? _store_get : {};
450
- if (CommerceModel.storefrontTaxDecision({
451
- settings: taxSettings
452
- }).kind === 'undecided') {
453
- return refusal(409, 'tax-undecided', CommerceModel.invoicePayRefusalMessage('tax-undecided', storeName, kind));
496
+ const payTax = CommerceModel.quotePayTax(order.quote, payStore);
497
+ if (kind === 'quote') {
498
+ const shownTax = typeof body['tax'] === 'string' ? body['tax'] : null;
499
+ const taxKey = CommerceModel.quoteTaxBasisKey(payTax.basis);
500
+ if (shownTax !== null ? shownTax !== taxKey : payTax.source === 'current') {
501
+ return refusal(409, 'updated', QUOTE_UPDATED_MESSAGE);
502
+ }
454
503
  }
455
- const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId);
504
+ const payments = await payLinkPayments(deps, {
505
+ hostId,
506
+ orderId: quoteId,
507
+ kind
508
+ });
509
+ const blocked = CommerceModel.payLinkRefusalWithPayments(CommerceModel.invoicePayRefusal(order, quoteId, payStore), payments.ready);
510
+ if (blocked === 'payments-unavailable') {
511
+ return refusal(409, blocked, CommerceModel.payLinkPaymentsUnavailableMessage(storeName, kind));
512
+ }
513
+ if (blocked) return refusal(409, blocked, CommerceModel.invoicePayRefusalMessage(blocked, storeName, kind));
514
+ const { owner, accountId } = payments;
515
+ const charge = CommerceModel.invoiceCheckoutCharge(order, quoteId, payStore);
456
516
  // The fee is sized on the most the buyer can pay, as a draft's first link
457
517
  // sized it on its dearest rate.
458
518
  const dearestRateCents = charge.shippingOptions.reduce((most, rate)=>Math.max(most, rate.amountCents), 0);
@@ -519,8 +579,7 @@ const refusal = (status, reason, error, extra = {})=>({
519
579
  let taxRateId = '';
520
580
  if (charge.taxPct !== null && charge.taxableCents > 0) {
521
581
  var _ref2;
522
- var _order_quote2;
523
- const basis = (_order_quote2 = order.quote) == null ? void 0 : _order_quote2.tax;
582
+ const basis = kind === 'quote' ? payTax.basis : null;
524
583
  taxRateId = (_ref2 = await deps.taxRateId({
525
584
  hostRef,
526
585
  taxPct: charge.taxPct,
@@ -548,7 +607,8 @@ const refusal = (status, reason, error, extra = {})=>({
548
607
  feeCents,
549
608
  taxRateId,
550
609
  returnUrl,
551
- paymentMethods
610
+ paymentMethods,
611
+ chargedTax: kind === 'quote' && payTax.source === 'current' ? payTax.basis : null
552
612
  });
553
613
  if (nativeMode.native) {
554
614
  var _params_get;