@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.
- package/package.json +13 -13
- package/src/lib/components/console/invoice-send.component.d.ts +9 -2
- package/src/lib/components/console/invoice-send.component.js +58 -30
- package/src/lib/components/console/invoice-send.component.js.map +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +84 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js +164 -0
- package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +7 -8
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +3 -0
- package/src/lib/components/console/quote-pay-link.component.js +9 -0
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.d.ts +3 -0
- package/src/lib/components/console/quote-send.component.js +9 -0
- package/src/lib/components/console/quote-send.component.js.map +1 -1
- package/src/lib/components/quote-page-body.js +5 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +45 -5
- package/src/lib/model/commerce-invoices.js +46 -9
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +110 -6
- package/src/lib/model/commerce-quote-pay.js +182 -23
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/server/billing-webhook.js +4 -1
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/commerce-pdf.js +2 -1
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/invoice-email.js +2 -1
- package/src/lib/server/invoice-email.js.map +1 -1
- package/src/lib/server/order-invoice-send.js +1 -1
- package/src/lib/server/order-invoice-send.js.map +1 -1
- package/src/lib/server/order-status.d.ts +5 -1
- package/src/lib/server/order-status.js +19 -5
- package/src/lib/server/order-status.js.map +1 -1
- package/src/lib/server/quote-email.js +2 -1
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +39 -0
- package/src/lib/server/quote-pay.js +103 -43
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.js +13 -9
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/utils/invoice-email-content.d.ts +3 -1
- package/src/lib/utils/invoice-email-content.js +1 -1
- package/src/lib/utils/invoice-email-content.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +3 -1
- package/src/lib/utils/quote-email-content.js +3 -3
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -192,7 +192,8 @@ export function defaultCommercePdfBrandDeps() {
|
|
|
192
192
|
orderId: input.quoteId,
|
|
193
193
|
storeName: brand.businessName,
|
|
194
194
|
currency: String((_ref = (_input_store = input.store) == null ? void 0 : _input_store['currency']) != null ? _ref : 'USD'),
|
|
195
|
-
receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId)
|
|
195
|
+
receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),
|
|
196
|
+
store: CommerceModel.payLinkStoreOf(input.store)
|
|
196
197
|
});
|
|
197
198
|
return {
|
|
198
199
|
bytes: renderQuotePdf({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.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 type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (the\n * one line Setup → Business profile saves, or an older one-block address a line per\n * line), the email visitors write to, its phone, and its web address without\n * the scheme. The address and email are the host tokens' (AGL-4136), so the\n * document says what the site's pages and emails say.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","revision","Number","quote","payUrl","filename","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gB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GAAG;YAAC,IAAI;YAClDqC;QACF;QACA,OAAO;YAAEO,QAAQ;YAAKY;QAAI;IAC5B;IACA,MAAMA,MAAM,MAAMrD,KAAKwD,QAAQ,CAAC;QAC9BrE;QACAsC;QACAF;QACAtF;QACA2F,KAAK,GAAGA,cAAAA,MAAM2B,IAAI,cAAV3B,cAAgB;QACxB3B,OAAOA,QAAQ;YAAEL,IAAIK,MAAML,EAAE;YAAEC,KAAKI,MAAMJ,GAAG;QAAC,IAAI;QAClDqC;IACF;IACA,OAAO;QAAEO,QAAQ;QAAKY;IAAI;AAC5B;AAEA,mCAAmC,GACnC,OAAO,MAAMI,kBAAoC,OAAOlB,KAAKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK1H;YAAuB4I,UAAUrC;YAAgBoB;QAC3F,IAAI,SAASU,SAAS,OAAOvI,QAAQgJ,KAAKT,QAAQI,GAAG;QACrD,OAAOrI,qBAAqB0I,KAAKT;IACnC,EAAE,OAAO1D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB0I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAEnD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.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 type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (the\n * one line Setup → Business profile saves, or an older one-block address a line per\n * line), the email visitors write to, its phone, and its web address without\n * the scheme. The address and email are the host tokens' (AGL-4136), so the\n * document says what the site's pages and emails say.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","payLinkStoreOf","revision","Number","quote","payUrl","filename","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBAAgB,EAAEC,gBAAgB,QAA8B,qCAAoC;AAC7G,SAASC,gBA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GAAG;YAAC,IAAI;YAClDsC;QACF;QACA,OAAO;YAAEO,QAAQ;YAAKY;QAAI;IAC5B;IACA,MAAMA,MAAM,MAAMtD,KAAKyD,QAAQ,CAAC;QAC9BtE;QACAsC;QACAF;QACAtF;QACA2F,KAAK,GAAGA,cAAAA,MAAM4B,IAAI,cAAV5B,cAAgB;QACxB3B,OAAOA,QAAQ;YAAEL,IAAIK,MAAML,EAAE;YAAEC,KAAKI,MAAMJ,GAAG;QAAC,IAAI;QAClDsC;IACF;IACA,OAAO;QAAEO,QAAQ;QAAKY;IAAI;AAC5B;AAEA,mCAAmC,GACnC,OAAO,MAAMI,kBAAoC,OAAOlB,KAAKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK3H;YAAuB6I,UAAUtC;YAAgBqB;QAC3F,IAAI,SAASU,SAAS,OAAOxI,QAAQiJ,KAAKT,QAAQI,GAAG;QACrD,OAAOtI,qBAAqB2I,KAAKT;IACnC,EAAE,OAAO3D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB2I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAEpD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
@@ -95,7 +95,8 @@ export function defaultInvoiceMailerDeps() {
|
|
|
95
95
|
subject,
|
|
96
96
|
message: input.message,
|
|
97
97
|
payUrl: input.payUrl,
|
|
98
|
-
timeZone: resolveSiteTimeZone(org, host)
|
|
98
|
+
timeZone: resolveSiteTimeZone(org, host),
|
|
99
|
+
store: CommerceModel.payLinkStoreOf(input.store)
|
|
99
100
|
});
|
|
100
101
|
// The PDF is what the email says is attached; without it nothing goes.
|
|
101
102
|
let pdf;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/invoice-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 { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n readEmailThread,\n sendEmail,\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 transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { INVOICE_EMAIL_KEY, invoiceEmailContent } from '../utils/invoice-email-content'\nimport type { orderInvoicePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\nimport { quoteBusinessName, quoteReplyTo } from './quote-email'\n\n/*==========================================\n * SENDING THE INVOICE EMAIL (AGL-4099). Loaded only by the console's Send\n * invoice (`POST commerce/order-invoice-send`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `order-invoice` catalog key in the site's theme and its\n * header and footer (or the site's own design of it), with the invoice's PDF\n * attached, sent as the quote email is (`quote-email.ts`):\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email, else the person sending;\n * - IN THE CUSTOMER'S CONVERSATION: a quote's invoice replies into the\n * quote's conversation (`quote.emailThread`: its emails, or a request's\n * confirmation before them), and any other order's into its own\n * (`emailThread`), which its first invoice starts;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam: an invoice is transactional, as a receipt is.\n *\n * The route decides everything about the order (who may send, the link,\n * whether it can be paid); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface InvoiceDeliveryInput {\n hostId: string\n orderId: string\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 /** The order's pay link, for an invoice still to be paid; null for a paid one. */\n payUrl: string | null\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 InvoiceDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n paid: boolean\n totalCents: number\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface InvoiceMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The invoice's PDF; loads the PDF writer and sharp only here. */\n invoicePdf(input: Parameters<typeof orderInvoicePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: an invoice is transactional. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultInvoiceMailerDeps(): InvoiceMailerDeps {\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 invoicePdf: async (input) => (await import('./commerce-pdf')).orderInvoicePdfFile(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 invoice reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface InvoiceMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: InvoiceDeliveryInput): Promise<InvoiceDeliveryResult>\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 invoice 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 invoice wasn’t sent.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the invoice wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the invoice 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 invoice email could not be sent. Try again.' }\n }\n}\n\n/** The invoice email, said and sent. */\nexport function invoiceMailer(deps: InvoiceMailerDeps = defaultInvoiceMailerDeps()): InvoiceMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, orderId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.invoiceEmailDefaultSubject(order, businessName, orderId)\n const identity = await deps.sendingIdentity(hostId)\n const org = (input.owner?.org ?? null) as { timeZone?: string } | null\n const content = invoiceEmailContent({\n order,\n orderId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n timeZone: resolveSiteTimeZone(org, host as { timeZone?: string }),\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.invoicePdf({\n hostId,\n orderId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: content.paid ? null : input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/invoice-email] the PDF could not be made', { hostId, orderId, error })\n return { sent: false, status: 500, error: 'The invoice’s PDF could not be made, so nothing was sent. Try again.' }\n }\n\n const rendered = await deps.render(hostId, INVOICE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(CommerceModel.invoiceEmailThread(order))\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'invoice',\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: 'invoice',\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/invoice-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 paid: content.paid,\n totalCents: content.totalCents,\n }\n },\n }\n}\n"],"names":["resolveSiteTimeZone","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","readEmailThread","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","transactionalAddressSuppression","CommerceModel","INVOICE_EMAIL_KEY","invoiceEmailContent","quoteBusinessName","quoteReplyTo","defaultInvoiceMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","invoicePdf","input","orderInvoicePdfFile","send","options","meter","suppression","email","refusalOf","result","reason","status","error","detail","invoiceMailer","deps","deliver","host","orderId","order","businessName","subject","invoiceEmailDefaultSubject","identity","org","owner","content","currency","String","store","message","payUrl","timeZone","pdf","paid","console","sent","rendered","thread","invoiceEmailThread","siteHost","trim","messageId","domain","from","label","atMs","replyTo","senderEmail","to","text","html","headers","fromName","audience","context","attachments","filename","contentType","Buffer","bytes","toString","catch","providerId","id","totalCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,eAAe,EACfC,SAAS,QAKJ,2BAA0B;AACjC,SACEC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,+BAA+B,QAC1B,2BAA0B;AACjC,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,iBAAiB,EAAEC,mBAAmB,QAAQ,oCAAgC;AAGvF,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,mBAAe;AAsE/D,OAAO,SAASC;IACd,MAAMC,YAAY,IAAMX,cAAcY,GAAG,GAAGD,SAAS;IACrD,OAAO;QACLE,YAAY,IAAMlB;QAClBmB,iBAAiB,CAACC,SAAWd,oBAAoBc;QACjDC,QAAQ,CAACD,QAAQE,KAAKC,SAAWf,0BAA0BQ,aAAaI,QAAQE,KAAKC;QACrFC,YAAY,OAAOC,QAAU,AAAC,CAAA,MAAM,MAAM,CAAC,oBAAgB,EAAGC,mBAAmB,CAACD;QAClFE,MAAM,CAACC,UAAYxB,UAAUwB;QAC7BC,OAAO,OAAOT;YACZ,MAAMb,eAAea;QACvB;QACAU,aAAa,CAACC,QAAUtB,gCAAgCsB;IAC1D;AACF;AASA,mDAAmD,GACnD,S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EA,MAAMd,SAASc,IAAI;YAAC,IAAI,CAAC;gBAChDC,SAAS1E,kBAAkB4D,QAAQI;eAC/BK,UAAU;gBAAEA;YAAQ,IAAI,CAAC;gBAC7BM,UAAU/E,wBAAuB2B,gBAAAA,MAAMwB,KAAK,qBAAXxB,cAAauB,GAAG,EAAW6B,QAAQ;gBACpE1D,iBAAiB4B;gBACjB+B,UAAU;gBACVC,SAAS;gBACTC,aAAa;oBACX;wBACEC,UAAUxB,IAAIwB,QAAQ;wBACtBC,aAAa;wBACbhC,SAASiC,OAAOf,IAAI,CAACX,IAAI2B,KAAK,EAAEC,QAAQ,CAAC;oBAC3C;iBACD;;YAEH,IAAI,CAACpD,OAAO2B,IAAI,EAAE,OAAO;gBAAEA,MAAM;eAAU5B,UAAUC;YACrD,4DAA4D;YAC5D,MAAMM,KAAKV,KAAK,CAACT,QAAQkE,KAAK,CAAC,CAAClD,QAAUuB,QAAQvB,KAAK,CAAC,wCAAwCA;YAChG,OAAO;gBACLwB,MAAM;gBACNM;gBACAqB,UAAU,GAAE,aAAA,AAACtD,OAAoDuD,EAAE,YAAvD,aAA2D;gBACvE3C;gBACA0B;gBACAT,QAAQ/D,qBAAqB+D,QAAQ;oBAAEI;oBAAWrB;gBAAQ;gBAC1Da,MAAMR,QAAQQ,IAAI;gBAClB+B,YAAYvC,QAAQuC,UAAU;YAChC;QACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/invoice-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 { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { resolveBrandingProfile } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n emailThreadAfterSend,\n isEmailConfigured,\n mintEmailMessageId,\n nextThreadHeaders,\n readEmailThread,\n sendEmail,\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 transactionalAddressSuppression,\n} from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { INVOICE_EMAIL_KEY, invoiceEmailContent } from '../utils/invoice-email-content'\nimport type { orderInvoicePdfFile } from './commerce-pdf'\nimport type { CommercePdfFile } from './pdf-response'\nimport { quoteBusinessName, quoteReplyTo } from './quote-email'\n\n/*==========================================\n * SENDING THE INVOICE EMAIL (AGL-4099). Loaded only by the console's Send\n * invoice (`POST commerce/order-invoice-send`), so the renderer, the PDF\n * writer and sharp stay out of every other request.\n *\n * One email, the `order-invoice` catalog key in the site's theme and its\n * header and footer (or the site's own design of it), with the invoice's PDF\n * attached, sent as the quote email is (`quote-email.ts`):\n *\n * - FROM the site's sending identity, under the site's name;\n * - REPLY-TO the site's contact email, else the person sending;\n * - IN THE CUSTOMER'S CONVERSATION: a quote's invoice replies into the\n * quote's conversation (`quote.emailThread`: its emails, or a request's\n * confirmation before them), and any other order's into its own\n * (`emailThread`), which its first invoice starts;\n * - METERED as a site's transactional email;\n * - REFUSED only for an address that bounced for good or reported mail as\n * spam: an invoice is transactional, as a receipt is.\n *\n * The route decides everything about the order (who may send, the link,\n * whether it can be paid); this module only says the email and sends it.\n *=========================================*/\n\n/** What the route hands over for one send. */\nexport interface InvoiceDeliveryInput {\n hostId: string\n orderId: string\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 /** The order's pay link, for an invoice still to be paid; null for a paid one. */\n payUrl: string | null\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 InvoiceDeliveryResult =\n | {\n sent: true\n messageId: string\n providerId: string | null\n subject: string\n replyTo: string | null\n thread: CommerceModel.QuoteEmailThread\n paid: boolean\n totalCents: number\n }\n | { sent: false; status: number; error: string }\n\n/** The calls the send makes, injectable for specs. */\nexport interface InvoiceMailerDeps {\n configured(): boolean\n sendingIdentity(hostId: string): Promise<SendingIdentityVerdict>\n render(hostId: string, key: string, tokens: Record<string, string>): Promise<RenderedHostEmail | null>\n /** The invoice's PDF; loads the PDF writer and sharp only here. */\n invoicePdf(input: Parameters<typeof orderInvoicePdfFile>[0]): Promise<CommercePdfFile>\n send(options: SendEmailOptions): Promise<SendEmailResult>\n meter(hostId: string): Promise<void>\n /** The bounce and complaint list only: an invoice is transactional. */\n suppression(email: string): Promise<'suppressed-platform' | null>\n}\n\nexport function defaultInvoiceMailerDeps(): InvoiceMailerDeps {\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 invoicePdf: async (input) => (await import('./commerce-pdf')).orderInvoicePdfFile(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 invoice reaches: whether mail can go, whether this address may be mailed, and the send. */\nexport interface InvoiceMailer {\n configured(): boolean\n suppression(email: string): Promise<'suppressed-platform' | null>\n deliver(input: InvoiceDeliveryInput): Promise<InvoiceDeliveryResult>\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 invoice 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 invoice wasn’t sent.' }\n case 'unverified-domain':\n return { status: 409, error: 'This site’s sending domain isn’t verified, so the invoice wasn’t sent. Check Email settings.' }\n case 'suspended':\n return { status: 423, error: 'This site can’t send email right now, so the invoice 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 invoice email could not be sent. Try again.' }\n }\n}\n\n/** The invoice email, said and sent. */\nexport function invoiceMailer(deps: InvoiceMailerDeps = defaultInvoiceMailerDeps()): InvoiceMailer {\n return {\n configured: () => deps.configured(),\n suppression: (email) => deps.suppression(email),\n deliver: async (input) => {\n const { hostId, orderId, order, host } = input\n const businessName = quoteBusinessName(host)\n const subject = input.subject || CommerceModel.invoiceEmailDefaultSubject(order, businessName, orderId)\n const identity = await deps.sendingIdentity(hostId)\n const org = (input.owner?.org ?? null) as { timeZone?: string } | null\n const content = invoiceEmailContent({\n order,\n orderId,\n businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n subject,\n message: input.message,\n payUrl: input.payUrl,\n timeZone: resolveSiteTimeZone(org, host as { timeZone?: string }),\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.invoicePdf({\n hostId,\n orderId,\n order,\n host,\n store: input.store,\n owner: input.owner,\n payUrl: content.paid ? null : input.payUrl,\n })\n } catch (error) {\n console.error('[commerce/invoice-email] the PDF could not be made', { hostId, orderId, error })\n return { sent: false, status: 500, error: 'The invoice’s PDF could not be made, so nothing was sent. Try again.' }\n }\n\n const rendered = await deps.render(hostId, INVOICE_EMAIL_KEY, content.tokens)\n const thread = readEmailThread(CommerceModel.invoiceEmailThread(order))\n const siteHost = String(host['cname'] ?? '').trim() || null\n const messageId = mintEmailMessageId([identity?.domain, identity?.from, siteHost], {\n label: 'invoice',\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: 'invoice',\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/invoice-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 paid: content.paid,\n totalCents: content.totalCents,\n }\n },\n }\n}\n"],"names":["resolveSiteTimeZone","resolveBrandingProfile","emailThreadAfterSend","isEmailConfigured","mintEmailMessageId","nextThreadHeaders","readEmailThread","sendEmail","firebaseAdmin","hostSendingIdentity","meterHostEmail","renderHostEmailWithTokens","transactionalAddressSuppression","CommerceModel","INVOICE_EMAIL_KEY","invoiceEmailContent","quoteBusinessName","quoteReplyTo","defaultInvoiceMailerDeps","firestore","app","configured","sendingIdentity","hostId","render","key","tokens","invoicePdf","input","orderInvoicePdfFile","send","options","meter","suppression","email","refusalOf","result","reason","status","error","detail","invoiceMailer","deps","deliver","host","orderId","order","businessName","subject","invoiceEmailDefaultSubject","identity","org","owner","content","currency","String","store","message","payUrl","timeZone","payLinkStoreOf","pdf","paid","console","sent","rendered","thread","invoiceEmailThread","siteHost","trim","messageId","domain","from","label","atMs","replyTo","senderEmail","to","text","html","headers","fromName","audience","context","attachments","filename","contentType","Buffer","bytes","toString","catch","providerId","id","totalCents"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,sBAAsB,QAAQ,2CAA0C;AACjF,SACEC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,eAAe,EACfC,SAAS,QAKJ,2BAA0B;AACjC,SACEC,aAAa,EACbC,mBAAmB,EACnBC,cAAc,EACdC,yBAAyB,EACzBC,+BAA+B,QAC1B,2BAA0B;AACjC,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,iBAAiB,EAAEC,mBAAmB,QAAQ,oCAAgC;AAGvF,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,mBAAe;AAsE/D,OAAO,SAASC;IACd,MAAMC,YAAY,IAAMX,cAAcY,GAAG,GAAGD,SAAS;IACrD,OAAO;QACLE,YAAY,IAAMlB;QAClBmB,iBAAiB,CAACC,SAAWd,oBAAoBc;QACjDC,QAAQ,CAACD,QAAQE,KAAKC,SAAWf,0BAA0BQ,aAAaI,QAAQE,KAAKC;QACrFC,YAAY,OAAOC,QAAU,AAAC,CAAA,MAAM,MAAM,CAAC,oBAAgB,EAAGC,mBAAmB,CAACD;QAClFE,MAAM,CAACC,UAAYxB,UAAUwB;QAC7BC,OAAO,OAAOT;YACZ,MAAMb,eAAea;QACvB;QACAU,aAAa,CAACC,QAAUtB,gCAAgCsB;IAC1D;AACF;AASA,mDAAmD,GACnD,SAASC,UAAUC,MAAiD;IAClE,OAAQA,OAAOC,MAAM;QACnB,KAAK;YACH,OAAO;gBAAEC,QAAQ;gBAAKC,OAAO;YAAuD;QACtF,KAAK;YACH,OAAO;gBAAED,QAAQ;gBAAKC,OAAO;YAAkE;QACjG,KAAK;QACL,KAAK;YACH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2B,gBAAAA,MAAMwB,KAAK,qBAAXxB,cAAauB,GAAG,EAAW8B,QAAQ;gBACpE3D,iBAAiB4B;gBACjBgC,UAAU;gBACVC,SAAS;gBACTC,aAAa;oBACX;wBACEC,UAAUxB,IAAIwB,QAAQ;wBACtBC,aAAa;wBACbjC,SAASkC,OAAOf,IAAI,CAACX,IAAI2B,KAAK,EAAEC,QAAQ,CAAC;oBAC3C;iBACD;;YAEH,IAAI,CAACrD,OAAO4B,IAAI,EAAE,OAAO;gBAAEA,MAAM;eAAU7B,UAAUC;YACrD,4DAA4D;YAC5D,MAAMM,KAAKV,KAAK,CAACT,QAAQmE,KAAK,CAAC,CAACnD,QAAUwB,QAAQxB,KAAK,CAAC,wCAAwCA;YAChG,OAAO;gBACLyB,MAAM;gBACNM;gBACAqB,UAAU,GAAE,aAAA,AAACvD,OAAoDwD,EAAE,YAAvD,aAA2D;gBACvE5C;gBACA2B;gBACAT,QAAQhE,qBAAqBgE,QAAQ;oBAAEI;oBAAWtB;gBAAQ;gBAC1Dc,MAAMT,QAAQS,IAAI;gBAClB+B,YAAYxC,QAAQwC,UAAU;YAChC;QACF;IACF;AACF"}
|
|
@@ -100,7 +100,7 @@ export async function handleOrderInvoiceSend(deps, req) {
|
|
|
100
100
|
]);
|
|
101
101
|
const order = snapshot.exists ? snapshot.data() : null;
|
|
102
102
|
const to = CommerceModel.invoiceSendRecipient(order, parsed.input.to);
|
|
103
|
-
const refused = CommerceModel.invoiceSendRefusal(order, orderId, to);
|
|
103
|
+
const refused = CommerceModel.invoiceSendRefusal(order, orderId, to, CommerceModel.payLinkStoreOf(store.data()));
|
|
104
104
|
if (refused) {
|
|
105
105
|
return refuse(CommerceModel.invoiceSendRefusalStatus(refused), CommerceModel.invoiceSendRefusalMessage(refused));
|
|
106
106
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-invoice-send.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 { checkEntitlement, claimAttempt, type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport * as CommerceModel from '../model'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport type { InvoiceMailer } from './invoice-email'\nimport { quotePayLinkUrl } from './quote-link-token'\n\n/*==========================================\n * SEND INVOICE (AGL-4099): `POST /api/commerce/order-invoice-send`.\n *\n * { hostId, orderId, to?, subject?, message? } + Idempotency-Key\n * → { sent: true, to, atMs, paid, linkVersion }\n *\n * Emails the invoice for an order or a quote, under \"Send quotes and\n * invoices to customers\" (`commerce.quotes.send`), the key a quote's send\n * already asks: its label names invoices, and an invoice for an order is the\n * same act toward the same customer.\n *\n * - UNPAID (a draft order, or a quote), the email asks for payment with one\n * button to the order's lasting pay link (`/pay-quote`, its version on\n * `quote.linkVersion` for a quote and `payLink.version` otherwise); the\n * link opens a fresh payment from the stored order whenever it is pressed.\n * - PAID, the email is the record: no button.\n *\n * Refused, in the console's words: an unknown order, a canceled or refunded\n * one, one with nothing on it, an unpaid one its link cannot take payment\n * for (a register sale still open, a quote waiting on the proof's approval,\n * tax not set up, under 50 cents, a draft older than invoices), no address\n * or a bad one, a site with no web address for the link, selling not on,\n * email not set up, and an address that bounced or complained.\n *\n * The send is recorded on the order (`invoiceSends`), on its timeline, and as\n * the conversation it moved on: the quote's for a quote, the order's own\n * otherwise. One attempt per Idempotency-Key, so a retried press is answered\n * from the first and the customer never gets two.\n *=========================================*/\n\nexport interface OrderInvoiceSendDeps {\n verifyIdToken(token: string): Promise<{ uid: string; email?: string | null }>\n firestore(): FirebaseFirestore.Firestore\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n /** The order's pay link at a link version, or null when the site has no address or no signing secret. */\n payLinkUrl(host: Record<string, unknown>, hostId: string, orderId: string, version: number): string | null\n /** The invoice email: the renderer, the PDF and sharp, loaded only by a send. */\n mailer(): Promise<InvoiceMailer>\n now(): number\n}\n\nexport function defaultOrderInvoiceSendDeps(): OrderInvoiceSendDeps {\n return {\n verifyIdToken: (token) => firebaseAdmin.app().auth().verifyIdToken(token),\n firestore: () => firebaseAdmin.app().firestore(),\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n payLinkUrl: (host, hostId, orderId, version) => quotePayLinkUrl(host, hostId, orderId, version),\n mailer: async () => (await import('./invoice-email')).invoiceMailer(),\n now: () => Date.now(),\n }\n}\n\ntype Outcome = { status: number; body: Record<string, unknown> }\n\nconst refuse = (status: number, error: string): Outcome => ({ status, body: { error } })\n\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\nfunction headerOf(req: PluginApiRequest, name: string): string {\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const value = headers[name.toLowerCase()] ?? headers[name]\n return String(Array.isArray(value) ? (value[0] ?? '') : (value ?? '')).trim()\n}\n\nconst NO_ADDRESS = 'This site has no web address yet, so its invoices have no pay link. Publish the site first.'\n\nexport async function handleOrderInvoiceSend(deps: OrderInvoiceSendDeps, req: PluginApiRequest): Promise<Outcome> {\n if (req.method !== 'POST') return refuse(405, 'Method not allowed')\n const authorization = headerOf(req, 'authorization')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!idToken) return refuse(401, 'Unauthenticated')\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const orderId = String(body['orderId'] ?? '')\n if (!DOC_ID.test(hostId)) return refuse(400, 'Missing hostId')\n if (!DOC_ID.test(orderId)) return refuse(400, 'Missing orderId')\n\n let decoded: { uid: string; email?: string | null }\n try {\n decoded = await deps.verifyIdToken(idToken)\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return refuse(401, 'Unauthenticated')\n }\n const firestore = deps.firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return refuse(404, 'Unknown site')\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.quotes.send')) {\n return refuse(403, commerceSitePermissionRefusal('commerce.quotes.send'))\n }\n const host = (hostSnapshot.data() ?? {}) as Record<string, unknown>\n const actor = String(decoded.email || decoded.uid)\n\n const parsed = CommerceModel.parseQuoteSendInput(body)\n if ('error' in parsed) return refuse(400, parsed.error)\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return refuse(400, 'Sending an invoice needs an Idempotency-Key header.')\n\n const ref = hostRef.collection('orders').doc(orderId)\n const [snapshot, store] = await Promise.all([ref.get(), hostRef.collection('settings').doc('store').get()])\n const order = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n const to = CommerceModel.invoiceSendRecipient(order, parsed.input.to)\n const refused = CommerceModel.invoiceSendRefusal(order, orderId, to)\n if (refused) {\n return refuse(CommerceModel.invoiceSendRefusalStatus(refused), CommerceModel.invoiceSendRefusalMessage(refused))\n }\n const current = order as CommerceModel.HostOrder\n const paid = CommerceModel.invoiceIsPaid(current)\n const linkVersion = paid ? null : CommerceModel.orderPayLinkVersion(current)\n const payUrl = linkVersion === null ? null : deps.payLinkUrl(host, hostId, orderId, linkVersion)\n if (linkVersion !== null && !payUrl) return refuse(409, NO_ADDRESS)\n\n const owner = await deps.orgForHost(hostId)\n if (!checkEntitlement(owner?.org as never, 'commerce')) return refuse(403, 'Selling is not enabled')\n const mailer = await deps.mailer()\n if (!mailer.configured()) {\n return refuse(503, 'Email isn’t set up here, so invoices can’t be emailed.')\n }\n // The bounce and complaint list only: an invoice is transactional, so an\n // unsubscribe from the site's newsletter does not stop it, as it does not\n // stop a receipt.\n if (await mailer.suppression(to)) {\n return refuse(409, `${to} bounced or reported an email as spam, so it can’t be emailed. Send the invoice another way.`)\n }\n\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-order-invoice-send',\n scopeId: `${hostId}:${orderId}`,\n orgId: owner?.id ?? '',\n key: idempotencyKey,\n busyMessage: 'This invoice is already being sent',\n })\n if ('replay' in claimed) {\n return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n }\n const claim = claimed.claim\n const now = deps.now()\n\n let delivered: Awaited<ReturnType<InvoiceMailer['deliver']>>\n try {\n delivered = await mailer.deliver({\n hostId,\n orderId,\n order: current,\n host,\n store: (store.data() ?? null) as Record<string, unknown> | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n to,\n subject: parsed.input.subject,\n message: parsed.input.message,\n payUrl,\n senderEmail: decoded.email ? String(decoded.email) : null,\n atMs: now,\n })\n } catch (error) {\n console.error('commerce invoice send failed', error)\n await claim.release()\n return refuse(502, 'The invoice email could not be sent. Try again.')\n }\n // `strictNullChecks` is off, so the result does not narrow on `sent`.\n if ('error' in delivered) {\n await claim.release()\n return refuse(delivered.status, delivered.error)\n }\n const done = delivered as Extract<typeof delivered, { sent: true }>\n\n // The email is out: from here a failure is logged, never answered as one,\n // so a retry does not send it twice.\n const send: CommerceModel.OrderInvoiceSendRecord = {\n to,\n subject: done.subject,\n atMs: now,\n by: actor,\n messageId: done.messageId,\n providerId: done.providerId,\n paid: done.paid,\n linkVersion: done.paid ? null : linkVersion,\n totalCents: done.totalCents,\n }\n try {\n await firestore.runTransaction(async (transaction) => {\n const latest = await transaction.get(ref)\n if (!latest.exists) return\n const fresh = latest.data() as CommerceModel.HostOrder\n transaction.set(ref, CommerceModel.invoiceSendPatch(fresh, send, done.thread), { merge: true })\n })\n } catch (error) {\n console.error('commerce invoice sent but not recorded', { hostId, orderId, messageId: done.messageId, error })\n }\n const outcome: Outcome = {\n status: 200,\n body: { sent: true, to, atMs: now, paid: done.paid, linkVersion: send.linkVersion },\n }\n await claim.record(outcome.status, outcome.body)\n return outcome\n}\n\n/** `POST /api/commerce/order-invoice-send`. */\nexport const orderInvoiceSendHandler: PluginApiHandler = async (req, res) => {\n const outcome = await handleOrderInvoiceSend(defaultOrderInvoiceSendDeps(), req)\n return res.status(outcome.status).json(outcome.body)\n}\n"],"names":["checkEntitlement","claimAttempt","firebaseAdmin","getOrgForHost","isRefusedIdToken","CommerceModel","commerceSitePermissionRefusal","holdsCommerceSiteKey","quotePayLinkUrl","defaultOrderInvoiceSendDeps","verifyIdToken","token","app","auth","firestore","orgForHost","hostId","found","id","orgId","org","payLinkUrl","host","orderId","version","mailer","invoiceMailer","now","Date","refuse","status","error","body","DOC_ID","bodyOf","req","raw","parsed","JSON","parse","headerOf","name","headers","value","toLowerCase","String","Array","isArray","trim","NO_ADDRESS","handleOrderInvoiceSend","deps","hostSnapshot","method","authorization","idToken","startsWith","slice","length","test","decoded","hostRef","collection","doc","get","exists","uid","data","actor","email","parseQuoteSendInput","idempotencyKey","ref","snapshot","store","Promise","all","order","to","invoiceSendRecipient","input","refused","invoiceSendRefusal","invoiceSendRefusalStatus","invoiceSendRefusalMessage","current","paid","invoiceIsPaid","linkVersion","orderPayLinkVersion","payUrl","owner","configured","suppression","claimed","kind","scopeId","key","busyMessage","replay","claim","delivered","deliver","subject","message","senderEmail","atMs","console","release","done","send","by","messageId","providerId","totalCents","runTransaction","transaction","latest","fresh","set","invoiceSendPatch","thread","merge","outcome","sent","record","orderInvoiceSendHandler","res","json"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,YAAY,QAAsD,sBAAqB;AAClH,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,SAASC,oBAAoB,QAAQ,0BAAsB;AAE3D,SAASC,eAAe,QAAQ,wBAAoB;AA2CpD,OAAO,SAASC;IACd,OAAO;QACLC,eAAe,CAACC,QAAUT,cAAcU,GAAG,GAAGC,IAAI,GAAGH,aAAa,CAACC;QACnEG,WAAW,IAAMZ,cAAcU,GAAG,GAAGE,SAAS;QAC9CC,YAAY,OAAOC;YACjB,MAAMC,QAAQ,MAAMd,cAAca;YAClC,OAAOC,QAAQ;gBAAEC,IAAID,MAAME,KAAK;gBAAEC,KAAKH,MAAMG,GAAG;YAAC,IAAI;QACvD;QACAC,YAAY,CAACC,MAAMN,QAAQO,SAASC,UAAYhB,gBAAgBc,MAAMN,QAAQO,SAASC;QACvFC,QAAQ,UAAY,AAAC,CAAA,MAAM,MAAM,CAAC,qBAAiB,EAAGC,aAAa;QACnEC,KAAK,IAAMC,KAAKD,GAAG;IACrB;AACF;AAIA,MAAME,SAAS,CAACC,QAAgBC,QAA4B,CAAA;QAAED;QAAQE,MAAM;YAAED;QAAM;IAAE,CAAA;AAEtF,MAAME,SAAS;AAEf,SAASC,OAAOC,GAAqB;IACnC,MAAMC,MAAMD,IAAIH,IAAI;IACpB,IAAI,OAAOI,QAAQ,UAAU;QAC3B,IAAI;YACF,MAAMC,SAASC,KAAKC,KAAK,CAACH;YAC1B,OAAOC,UAAU,OAAOA,WAAW,WAAWA,SAAS,CAAC;QAC1D,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,O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F,QAAQ;QACRE,MAAM;YAAE4F,MAAM;YAAM9C;YAAI4B,MAAM/E;YAAK2D,MAAMuB,KAAKvB,IAAI;YAAEE,aAAasB,KAAKtB,WAAW;QAAC;IACpF;IACA,MAAMY,MAAMyB,MAAM,CAACF,QAAQ7F,MAAM,EAAE6F,QAAQ3F,IAAI;IAC/C,OAAO2F;AACT;AAEA,6CAA6C,GAC7C,OAAO,MAAMG,0BAA4C,OAAO3F,KAAK4F;IACnE,MAAMJ,UAAU,MAAMzE,uBAAuBzC,+BAA+B0B;IAC5E,OAAO4F,IAAIjG,MAAM,CAAC6F,QAAQ7F,MAAM,EAAEkG,IAAI,CAACL,QAAQ3F,IAAI;AACrD,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-invoice-send.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 { checkEntitlement, claimAttempt, type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport * as CommerceModel from '../model'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport type { InvoiceMailer } from './invoice-email'\nimport { quotePayLinkUrl } from './quote-link-token'\n\n/*==========================================\n * SEND INVOICE (AGL-4099): `POST /api/commerce/order-invoice-send`.\n *\n * { hostId, orderId, to?, subject?, message? } + Idempotency-Key\n * → { sent: true, to, atMs, paid, linkVersion }\n *\n * Emails the invoice for an order or a quote, under \"Send quotes and\n * invoices to customers\" (`commerce.quotes.send`), the key a quote's send\n * already asks: its label names invoices, and an invoice for an order is the\n * same act toward the same customer.\n *\n * - UNPAID (a draft order, or a quote), the email asks for payment with one\n * button to the order's lasting pay link (`/pay-quote`, its version on\n * `quote.linkVersion` for a quote and `payLink.version` otherwise); the\n * link opens a fresh payment from the stored order whenever it is pressed.\n * - PAID, the email is the record: no button.\n *\n * Refused, in the console's words: an unknown order, a canceled or refunded\n * one, one with nothing on it, an unpaid one its link cannot take payment\n * for (a register sale still open, a quote waiting on the proof's approval,\n * tax not set up, under 50 cents, a draft older than invoices), no address\n * or a bad one, a site with no web address for the link, selling not on,\n * email not set up, and an address that bounced or complained.\n *\n * The send is recorded on the order (`invoiceSends`), on its timeline, and as\n * the conversation it moved on: the quote's for a quote, the order's own\n * otherwise. One attempt per Idempotency-Key, so a retried press is answered\n * from the first and the customer never gets two.\n *=========================================*/\n\nexport interface OrderInvoiceSendDeps {\n verifyIdToken(token: string): Promise<{ uid: string; email?: string | null }>\n firestore(): FirebaseFirestore.Firestore\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n /** The order's pay link at a link version, or null when the site has no address or no signing secret. */\n payLinkUrl(host: Record<string, unknown>, hostId: string, orderId: string, version: number): string | null\n /** The invoice email: the renderer, the PDF and sharp, loaded only by a send. */\n mailer(): Promise<InvoiceMailer>\n now(): number\n}\n\nexport function defaultOrderInvoiceSendDeps(): OrderInvoiceSendDeps {\n return {\n verifyIdToken: (token) => firebaseAdmin.app().auth().verifyIdToken(token),\n firestore: () => firebaseAdmin.app().firestore(),\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n payLinkUrl: (host, hostId, orderId, version) => quotePayLinkUrl(host, hostId, orderId, version),\n mailer: async () => (await import('./invoice-email')).invoiceMailer(),\n now: () => Date.now(),\n }\n}\n\ntype Outcome = { status: number; body: Record<string, unknown> }\n\nconst refuse = (status: number, error: string): Outcome => ({ status, body: { error } })\n\nconst DOC_ID = /^(?!__.*__$)[^/]{1,200}$/\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\nfunction headerOf(req: PluginApiRequest, name: string): string {\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const value = headers[name.toLowerCase()] ?? headers[name]\n return String(Array.isArray(value) ? (value[0] ?? '') : (value ?? '')).trim()\n}\n\nconst NO_ADDRESS = 'This site has no web address yet, so its invoices have no pay link. Publish the site first.'\n\nexport async function handleOrderInvoiceSend(deps: OrderInvoiceSendDeps, req: PluginApiRequest): Promise<Outcome> {\n if (req.method !== 'POST') return refuse(405, 'Method not allowed')\n const authorization = headerOf(req, 'authorization')\n const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!idToken) return refuse(401, 'Unauthenticated')\n const body = bodyOf(req)\n const hostId = String(body['hostId'] ?? '')\n const orderId = String(body['orderId'] ?? '')\n if (!DOC_ID.test(hostId)) return refuse(400, 'Missing hostId')\n if (!DOC_ID.test(orderId)) return refuse(400, 'Missing orderId')\n\n let decoded: { uid: string; email?: string | null }\n try {\n decoded = await deps.verifyIdToken(idToken)\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return refuse(401, 'Unauthenticated')\n }\n const firestore = deps.firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return refuse(404, 'Unknown site')\n if (!holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.quotes.send')) {\n return refuse(403, commerceSitePermissionRefusal('commerce.quotes.send'))\n }\n const host = (hostSnapshot.data() ?? {}) as Record<string, unknown>\n const actor = String(decoded.email || decoded.uid)\n\n const parsed = CommerceModel.parseQuoteSendInput(body)\n if ('error' in parsed) return refuse(400, parsed.error)\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return refuse(400, 'Sending an invoice needs an Idempotency-Key header.')\n\n const ref = hostRef.collection('orders').doc(orderId)\n const [snapshot, store] = await Promise.all([ref.get(), hostRef.collection('settings').doc('store').get()])\n const order = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n const to = CommerceModel.invoiceSendRecipient(order, parsed.input.to)\n const refused = CommerceModel.invoiceSendRefusal(order, orderId, to, CommerceModel.payLinkStoreOf(store.data()))\n if (refused) {\n return refuse(CommerceModel.invoiceSendRefusalStatus(refused), CommerceModel.invoiceSendRefusalMessage(refused))\n }\n const current = order as CommerceModel.HostOrder\n const paid = CommerceModel.invoiceIsPaid(current)\n const linkVersion = paid ? null : CommerceModel.orderPayLinkVersion(current)\n const payUrl = linkVersion === null ? null : deps.payLinkUrl(host, hostId, orderId, linkVersion)\n if (linkVersion !== null && !payUrl) return refuse(409, NO_ADDRESS)\n\n const owner = await deps.orgForHost(hostId)\n if (!checkEntitlement(owner?.org as never, 'commerce')) return refuse(403, 'Selling is not enabled')\n const mailer = await deps.mailer()\n if (!mailer.configured()) {\n return refuse(503, 'Email isn’t set up here, so invoices can’t be emailed.')\n }\n // The bounce and complaint list only: an invoice is transactional, so an\n // unsubscribe from the site's newsletter does not stop it, as it does not\n // stop a receipt.\n if (await mailer.suppression(to)) {\n return refuse(409, `${to} bounced or reported an email as spam, so it can’t be emailed. Send the invoice another way.`)\n }\n\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-order-invoice-send',\n scopeId: `${hostId}:${orderId}`,\n orgId: owner?.id ?? '',\n key: idempotencyKey,\n busyMessage: 'This invoice is already being sent',\n })\n if ('replay' in claimed) {\n return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n }\n const claim = claimed.claim\n const now = deps.now()\n\n let delivered: Awaited<ReturnType<InvoiceMailer['deliver']>>\n try {\n delivered = await mailer.deliver({\n hostId,\n orderId,\n order: current,\n host,\n store: (store.data() ?? null) as Record<string, unknown> | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n to,\n subject: parsed.input.subject,\n message: parsed.input.message,\n payUrl,\n senderEmail: decoded.email ? String(decoded.email) : null,\n atMs: now,\n })\n } catch (error) {\n console.error('commerce invoice send failed', error)\n await claim.release()\n return refuse(502, 'The invoice email could not be sent. Try again.')\n }\n // `strictNullChecks` is off, so the result does not narrow on `sent`.\n if ('error' in delivered) {\n await claim.release()\n return refuse(delivered.status, delivered.error)\n }\n const done = delivered as Extract<typeof delivered, { sent: true }>\n\n // The email is out: from here a failure is logged, never answered as one,\n // so a retry does not send it twice.\n const send: CommerceModel.OrderInvoiceSendRecord = {\n to,\n subject: done.subject,\n atMs: now,\n by: actor,\n messageId: done.messageId,\n providerId: done.providerId,\n paid: done.paid,\n linkVersion: done.paid ? null : linkVersion,\n totalCents: done.totalCents,\n }\n try {\n await firestore.runTransaction(async (transaction) => {\n const latest = await transaction.get(ref)\n if (!latest.exists) return\n const fresh = latest.data() as CommerceModel.HostOrder\n transaction.set(ref, CommerceModel.invoiceSendPatch(fresh, send, done.thread), { merge: true })\n })\n } catch (error) {\n console.error('commerce invoice sent but not recorded', { hostId, orderId, messageId: done.messageId, error })\n }\n const outcome: Outcome = {\n status: 200,\n body: { sent: true, to, atMs: now, paid: done.paid, linkVersion: send.linkVersion },\n }\n await claim.record(outcome.status, outcome.body)\n return outcome\n}\n\n/** `POST /api/commerce/order-invoice-send`. */\nexport const orderInvoiceSendHandler: PluginApiHandler = async (req, res) => {\n const outcome = await handleOrderInvoiceSend(defaultOrderInvoiceSendDeps(), req)\n return res.status(outcome.status).json(outcome.body)\n}\n"],"names":["checkEntitlement","claimAttempt","firebaseAdmin","getOrgForHost","isRefusedIdToken","CommerceModel","commerceSitePermissionRefusal","holdsCommerceSiteKey","quotePayLinkUrl","defaultOrderInvoiceSendDeps","verifyIdToken","token","app","auth","firestore","orgForHost","hostId","found","id","orgId","org","payLinkUrl","host","orderId","version","mailer","invoiceMailer","now","Date","refuse","status","error","body","DOC_ID","bodyOf","req","raw","parsed","JSON","parse","headerOf","name","headers","value","toLowerCase","String","Array","isArray","trim","NO_ADDRESS","handleOrderInvoiceSend","deps","hostSnapshot","method","authorization","idToken","startsWith","slice","length","test","decoded","hostRef","collection","doc","get","exists","uid","data","actor","email","parseQuoteSendInput","idempotencyKey","ref","snapshot","store","Promise","all","order","to","invoiceSendRecipient","input","refused","invoiceSendRefusal","payLinkStoreOf","invoiceSendRefusalStatus","invoiceSendRefusalMessage","current","paid","invoiceIsPaid","linkVersion","orderPayLinkVersion","payUrl","owner","configured","suppression","claimed","kind","scopeId","key","busyMessage","replay","claim","delivered","deliver","subject","message","senderEmail","atMs","console","release","done","send","by","messageId","providerId","totalCents","runTransaction","transaction","latest","fresh","set","invoiceSendPatch","thread","merge","outcome","sent","record","orderInvoiceSendHandler","res","json"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,YAAY,QAAsD,sBAAqB;AAClH,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,SAASC,oBAAoB,QAAQ,0BAAsB;AAE3D,SAASC,eAAe,QAAQ,wBAAoB;AA2CpD,OAAO,SAASC;IACd,OAAO;QACLC,eAAe,CAACC,QAAUT,cAAcU,GAAG,GAAGC,IAAI,GAAGH,aAAa,CAACC;QACnEG,WAAW,IAAMZ,cAAcU,GAAG,GAAGE,SAAS;QAC9CC,YAAY,OAAOC;YACjB,MAAMC,QAAQ,MAAMd,cAAca;YAClC,OAAOC,QAAQ;gBAAEC,IAAID,MAAME,KAAK;gBAAEC,KAAKH,MAAM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;QACJ6C,WAAWH,KAAKG,SAAS;QACzBC,YAAYJ,KAAKI,UAAU;QAC3B3B,MAAMuB,KAAKvB,IAAI;QACfE,aAAaqB,KAAKvB,IAAI,GAAG,OAAOE;QAChC0B,YAAYL,KAAKK,UAAU;IAC7B;IACA,IAAI;QACF,MAAMrG,UAAUsG,cAAc,CAAC,OAAOC;YACpC,MAAMC,SAAS,MAAMD,YAAYrD,GAAG,CAACQ;YACrC,IAAI,CAAC8C,OAAOrD,MAAM,EAAE;YACpB,MAAMsD,QAAQD,OAAOnD,IAAI;YACzBkD,YAAYG,GAAG,CAAChD,KAAKnE,cAAcoH,gBAAgB,CAACF,OAAOR,MAAMD,KAAKY,MAAM,GAAG;gBAAEC,OAAO;YAAK;QAC/F;IACF,EAAE,OAAO5F,OAAO;QACd6E,QAAQ7E,KAAK,CAAC,0CAA0C;YAAEf;YAAQO;YAAS0F,WAAWH,KAAKG,SAAS;YAAElF;QAAM;IAC9G;IACA,MAAM6F,UAAmB;QACvB9F,QAAQ;QACRE,MAAM;YAAE6F,MAAM;YAAM/C;YAAI6B,MAAMhF;YAAK4D,MAAMuB,KAAKvB,IAAI;YAAEE,aAAasB,KAAKtB,WAAW;QAAC;IACpF;IACA,MAAMY,MAAMyB,MAAM,CAACF,QAAQ9F,MAAM,EAAE8F,QAAQ5F,IAAI;IAC/C,OAAO4F;AACT;AAEA,6CAA6C,GAC7C,OAAO,MAAMG,0BAA4C,OAAO5F,KAAK6F;IACnE,MAAMJ,UAAU,MAAM1E,uBAAuBzC,+BAA+B0B;IAC5E,OAAO6F,IAAIlG,MAAM,CAAC8F,QAAQ9F,MAAM,EAAEmG,IAAI,CAACL,QAAQ5F,IAAI;AACrD,EAAC"}
|
|
@@ -42,13 +42,17 @@ export declare function clearOrderStatusActions(): void;
|
|
|
42
42
|
/**
|
|
43
43
|
* Pay, on the status page of an order still to be paid that its lasting pay
|
|
44
44
|
* link can take payment for (AGL-4099): a draft order or a quote, opening the
|
|
45
|
-
* same `/pay-quote` page its invoice links to. None for anything else
|
|
45
|
+
* same `/pay-quote` page its invoice links to. None for anything else, nor
|
|
46
|
+
* where that page would offer no Pay (AGL-4162): the store's tax choice and
|
|
47
|
+
* its payments are read as the page reads them.
|
|
46
48
|
*/
|
|
47
49
|
export declare function orderStatusPayAction(input: {
|
|
48
50
|
hostId: string;
|
|
49
51
|
orderId: string;
|
|
50
52
|
order: CommerceModel.HostOrder;
|
|
51
53
|
currency: string;
|
|
54
|
+
store?: CommerceModel.PayLinkStore | null;
|
|
55
|
+
paymentsReady?: boolean;
|
|
52
56
|
}): CommerceModel.OrderStatusAction | null;
|
|
53
57
|
/**
|
|
54
58
|
* The guest order-status page's data (AGL-3610): `GET
|
|
@@ -19,6 +19,7 @@ import { consumeRateLimit, firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
|
19
19
|
import * as CommerceModel from "../model/index.js";
|
|
20
20
|
import { verifyOrderStatusToken } from "./order-status-token.js";
|
|
21
21
|
import { mintQuoteLinkToken } from "./quote-link-token.js";
|
|
22
|
+
import { defaultQuotePayDeps, payLinkPayments } from "./quote-pay.js";
|
|
22
23
|
import { quotePageHref } from "../constants/quote-page.js";
|
|
23
24
|
import { resolvePluginTrackingPages } from "@aglyn/aglyn/plugin-manager/plugin-tracking-pages";
|
|
24
25
|
/** How long the page waits for a tracking service's own page link (AGL-3635). */ export const TRACKING_PAGE_TIMEOUT_MS = 1500;
|
|
@@ -46,14 +47,18 @@ async function actionsFor(input) {
|
|
|
46
47
|
/**
|
|
47
48
|
* Pay, on the status page of an order still to be paid that its lasting pay
|
|
48
49
|
* link can take payment for (AGL-4099): a draft order or a quote, opening the
|
|
49
|
-
* same `/pay-quote` page its invoice links to. None for anything else
|
|
50
|
+
* same `/pay-quote` page its invoice links to. None for anything else, nor
|
|
51
|
+
* where that page would offer no Pay (AGL-4162): the store's tax choice and
|
|
52
|
+
* its payments are read as the page reads them.
|
|
50
53
|
*/ export function orderStatusPayAction(input) {
|
|
51
|
-
const { hostId, orderId, order } = input;
|
|
54
|
+
const { hostId, orderId, order, store } = input;
|
|
52
55
|
if (order.status !== 'pending' || !CommerceModel.orderPayLinkKind(order)) return null;
|
|
53
|
-
if (CommerceModel.invoicePayRefusal(order, orderId))
|
|
56
|
+
if (CommerceModel.payLinkRefusalWithPayments(CommerceModel.invoicePayRefusal(order, orderId, store), input.paymentsReady)) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
54
59
|
const token = mintQuoteLinkToken(hostId, orderId, CommerceModel.orderPayLinkVersion(order));
|
|
55
60
|
if (!token) return null;
|
|
56
|
-
const charge = CommerceModel.invoiceCheckoutCharge(order, orderId);
|
|
61
|
+
const charge = CommerceModel.invoiceCheckoutCharge(order, orderId, store);
|
|
57
62
|
const later = [
|
|
58
63
|
charge.shippingOptions.length > 0 ? 'shipping' : '',
|
|
59
64
|
charge.taxAtPayment ? 'tax' : ''
|
|
@@ -127,11 +132,20 @@ async function actionsFor(input) {
|
|
|
127
132
|
if (!hostSnapshot.exists || !orderSnapshot.exists) return notFound();
|
|
128
133
|
const order = CommerceModel.liftLegacyOrder((_orderSnapshot_data = orderSnapshot.data()) != null ? _orderSnapshot_data : {});
|
|
129
134
|
const currency = String((_settingsSnapshot_get = settingsSnapshot.get('currency')) != null ? _settingsSnapshot_get : 'USD');
|
|
135
|
+
const linked = order.status === 'pending' ? CommerceModel.orderPayLinkKind(order) : null;
|
|
130
136
|
const pay = orderStatusPayAction({
|
|
131
137
|
hostId,
|
|
132
138
|
orderId,
|
|
133
139
|
order,
|
|
134
|
-
currency
|
|
140
|
+
currency,
|
|
141
|
+
store: CommerceModel.payLinkStoreOf({
|
|
142
|
+
tax: settingsSnapshot.get('tax')
|
|
143
|
+
}),
|
|
144
|
+
paymentsReady: linked ? (await payLinkPayments(defaultQuotePayDeps(), {
|
|
145
|
+
hostId,
|
|
146
|
+
orderId,
|
|
147
|
+
kind: linked
|
|
148
|
+
})).ready : undefined
|
|
135
149
|
});
|
|
136
150
|
const view = CommerceModel.buildOrderStatusView({
|
|
137
151
|
order,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-status.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 { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport {\n resolveHostToken,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { consumeRateLimit, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { verifyOrderStatusToken } from './order-status-token'\nimport { mintQuoteLinkToken } from './quote-link-token'\nimport { quotePageHref } from '../constants/quote-page'\nimport { resolvePluginTrackingPages } from '@aglyn/aglyn/plugin-manager/plugin-tracking-pages'\n\n/** How long the page waits for a tracking service's own page link (AGL-3635). */\nexport const TRACKING_PAGE_TIMEOUT_MS = 1_500\n\n/** Status lookups one address may make per site, per ten minutes. */\nexport const ORDER_STATUS_LOOKUPS_PER_WINDOW = 60\nexport const ORDER_STATUS_WINDOW_MS = 10 * 60_000\n\n/**\n * Adds buyer actions to the status page (AGL-3610) — the typed extension\n * point for \"Request a return\", which the order-processing work (AGL-3611)\n * owns. A provider sees the verified order and answers the actions that apply\n * to it (none, usually); the page draws each as a button to its `url`. Kept\n * inside commerce: returns are this plugin's, so no cross-plugin seam is\n * needed, and a provider that throws costs the page its buttons, not the page.\n */\nexport type OrderStatusActionsProvider = (input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n /** The verified status token, for a provider building a signed follow-up link. */\n token: string\n}) => CommerceModel.OrderStatusAction[] | Promise<CommerceModel.OrderStatusAction[]>\n\nconst actionProviders: OrderStatusActionsProvider[] = []\n\nexport function registerOrderStatusActions(provider: OrderStatusActionsProvider): void {\n if (!actionProviders.includes(provider)) actionProviders.push(provider)\n}\n\n/** Specs only. */\nexport function clearOrderStatusActions(): void {\n actionProviders.length = 0\n}\n\nasync function actionsFor(\n input: Parameters<OrderStatusActionsProvider>[0],\n): Promise<CommerceModel.OrderStatusAction[]> {\n const answers = await Promise.all(\n actionProviders.map(async (provider) => {\n try {\n return (await provider(input)) ?? []\n } catch (error) {\n console.error('[order-status] actions provider failed', error)\n return []\n }\n }),\n )\n return answers\n .flat()\n .filter(\n (action) =>\n action && action.id && action.label && /^(https:\\/\\/|\\/)/.test(String(action.url)),\n )\n}\n\n/**\n * Pay, on the status page of an order still to be paid that its lasting pay\n * link can take payment for (AGL-4099): a draft order or a quote, opening the\n * same `/pay-quote` page its invoice links to. None for anything else.\n */\nexport function orderStatusPayAction(input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n currency: string\n}): CommerceModel.OrderStatusAction | null {\n const { hostId, orderId, order } = input\n if (order.status !== 'pending' || !CommerceModel.orderPayLinkKind(order)) return null\n if (CommerceModel.invoicePayRefusal(order, orderId)) return null\n const token = mintQuoteLinkToken(hostId, orderId, CommerceModel.orderPayLinkVersion(order))\n if (!token) return null\n const charge = CommerceModel.invoiceCheckoutCharge(order, orderId)\n const later = [charge.shippingOptions.length > 0 ? 'shipping' : '', charge.taxAtPayment ? 'tax' : '']\n .filter(Boolean)\n .join(' and ')\n const amount = CommerceModel.formatOrderMoney(charge.totalCents, input.currency)\n return { id: 'pay', label: later ? `Pay ${amount} plus ${later}` : `Pay ${amount}`, url: quotePageHref(orderId, token) }\n}\n\n/**\n * The guest order-status page's data (AGL-3610): `GET\n * /api/commerce/order-status?hostId=…&o=<orderId>&t=<token>` on the store.\n *\n * The token is the whole credential — `verifyOrderStatusToken`, constant\n * time — and a wrong one answers exactly as a missing order does (404), so\n * the route cannot be used to learn which order ids exist. Rate-limited per\n * address per site, durable, BEFORE the token check so guessing costs the\n * same as looking. The answer is `buildOrderStatusView`, an allow-listed\n * projection, never the order document; `Cache-Control: private, no-store`\n * and `X-Robots-Tag: noindex` keep it out of shared caches and search.\n *\n * Registered as a `recipientLink` route: an emailed link has to keep working\n * for the buyer it was sent to, so the per-site enablement gates do not\n * stand between them and their order.\n */\nexport const orderStatusHandler: PluginApiHandler = async (req, res) => {\n res.setHeader('Cache-Control', 'private, no-store')\n res.setHeader('X-Robots-Tag', 'noindex, nofollow')\n if (req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query.hostId ?? '')\n const orderId = String(req.query.o ?? '').slice(0, 200)\n const token = String(req.query.t ?? '').slice(0, 200)\n if (!hostId || !orderId || !token || /^__.*__$/.test(hostId) || /^__.*__$/.test(orderId) || orderId.includes('/')) {\n return res.status(400).json({ error: 'This link is incomplete.' })\n }\n const ip =\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n 'no-address'\n const rate = await consumeRateLimit(`commerce-order-status:${hostId}:${ip}`, {\n limit: ORDER_STATUS_LOOKUPS_PER_WINDOW,\n windowMs: ORDER_STATUS_WINDOW_MS,\n })\n if (!rate.allowed) {\n res.setHeader(\n 'Retry-After',\n String(Math.max(1, Math.ceil((rate.resetMs - Date.now()) / 1000))),\n )\n return res.status(429).json({ error: 'Too many lookups. Try again in a few minutes.' })\n }\n const notFound = () =>\n res.status(404).json({ error: 'We could not find that order. Check the link in your email.' })\n if (!verifyOrderStatusToken(hostId, orderId, token)) return notFound()\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, settingsSnapshot, orderSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('settings').doc('store').get(),\n hostRef.collection('orders').doc(orderId).get(),\n ])\n if (!hostSnapshot.exists || !orderSnapshot.exists) return notFound()\n const order = CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never)\n const currency = String(settingsSnapshot.get('currency') ?? 'USD')\n const pay = orderStatusPayAction({ hostId, orderId, order, currency })\n const view = CommerceModel.buildOrderStatusView({\n order,\n orderId,\n storeName: String(\n resolveHostToken('businessName', hostSnapshot.data() as HostTokenSource) ?? '',\n ),\n currency,\n number: CommerceModel.formatOrderNumber(order, orderId),\n actions: [...(pay ? [pay] : []), ...(await actionsFor({ hostId, orderId, order, token }))],\n })\n // A tracking service's own page for each parcel, where the merchant\n // follows them through one (AGL-3635); the carrier's link otherwise.\n const pages = await resolvePluginTrackingPages(\n view.shipments\n .filter((shipment) => shipment.trackingNumber)\n .map((shipment) => ({\n hostId,\n recordId: orderId,\n carrier: shipment.carrier,\n trackingNumber: String(shipment.trackingNumber),\n })),\n { timeoutMs: TRACKING_PAGE_TIMEOUT_MS },\n )\n for (const shipment of view.shipments) {\n const page = shipment.trackingNumber ? pages.get(shipment.trackingNumber) : undefined\n if (page) shipment.trackingUrl = page\n }\n return res.status(200).json(view)\n } catch (error) {\n console.error('orderStatus failed', error)\n return res.status(500).json({ error: 'Your order could not be loaded. Try again.' })\n }\n}\n"],"names":["resolveHostToken","readClientIp","consumeRateLimit","firebaseAdmin","CommerceModel","verifyOrderStatusToken","mintQuoteLinkToken","quotePageHref","resolvePluginTrackingPages","TRACKING_PAGE_TIMEOUT_MS","ORDER_STATUS_LOOKUPS_PER_WINDOW","ORDER_STATUS_WINDOW_MS","actionProviders","registerOrderStatusActions","provider","includes","push","clearOrderStatusActions","length","actionsFor","input","answers","Promise","all","map","error","console","flat","filter","action","id","label","test","String","url","orderStatusPayAction","hostId","orderId","order","status","orderPayLinkKind","invoicePayRefusal","token","orderPayLinkVersion","charge","invoiceCheckoutCharge","later","shippingOptions","taxAtPayment","Boolean","join","amount","formatOrderMoney","totalCents","currency","orderStatusHandler","req","res","setHeader","method","json","query","o","slice","t","ip","headers","remoteAddress","socket","rate","limit","windowMs","allowed","Math","max","ceil","resetMs","Date","now","notFound","orderSnapshot","settingsSnapshot","firestore","app","hostRef","collection","doc","hostSnapshot","get","exists","liftLegacyOrder","data","pay","view","buildOrderStatusView","storeName","number","formatOrderNumber","actions","pages","shipments","shipment","trackingNumber","recordId","carrier","timeoutMs","page","undefined","trackingUrl"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SACEA,gBAAgB,QAEX,qCAAoC;AAC3C,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,2BAA0B;AAC1E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,sBAAsB,QAAQ,0BAAsB;AAC7D,SAASC,kBAAkB,QAAQ,wBAAoB;AACvD,SAASC,aAAa,QAAQ,6BAAyB;AACvD,SAASC,0BAA0B,QAAQ,oDAAmD;AAE9F,+EAA+E,GAC/E,OAAO,MAAMC,2BAA2B,KAAK;AAE7C,mEAAmE,GACnE,OAAO,MAAMC,kCAAkC,GAAE;AACjD,OAAO,MAAMC,yBAAyB,KAAK,MAAM;AAkBjD,MAAMC,kBAAgD,EAAE;AAExD,OAAO,SAASC,2BAA2BC,QAAoC;IAC7E,IAAI,CAACF,gBAAgBG,QAAQ,CAACD,WAAWF,gBAAgBI,IAAI,CAACF;AAChE;AAEA,gBAAgB,GAChB,OAAO,SAASG;IACdL,gBAAgBM,MAAM,GAAG;AAC3B;AAEA,eAAeC,WACbC,KAAgD;IAEhD,MAAMC,UAAU,MAAMC,QAAQC,GAAG,CAC/BX,gBAAgBY,GAAG,CAAC,OAAOV;QACzB,IAAI;gBACM;YAAR,QAAQ,OAAA,MAAMA,SAASM,kBAAf,OAA0B,EAAE;QACtC,EAAE,OAAOK,OAAO;YACdC,QAAQD,KAAK,CAAC,0CAA0CA;YACxD,OAAO,EAAE;QACX;IACF;IAEF,OAAOJ,QACJM,IAAI,GACJC,MAAM,CACL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F;YAAEG,WAAWhG;QAAyB;QAExC,KAAK,MAAM4F,YAAYR,KAAKO,SAAS,CAAE;YACrC,MAAMM,OAAOL,SAASC,cAAc,GAAGH,MAAMX,GAAG,CAACa,SAASC,cAAc,IAAIK;YAC5E,IAAID,MAAML,SAASO,WAAW,GAAGF;QACnC;QACA,OAAOjD,IAAIlB,MAAM,CAAC,KAAKqB,IAAI,CAACiC;IAC9B,EAAE,OAAOpE,OAAO;QACdC,QAAQD,KAAK,CAAC,sBAAsBA;QACpC,OAAOgC,IAAIlB,MAAM,CAAC,KAAKqB,IAAI,CAAC;YAAEnC,OAAO;QAA6C;IACpF;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/order-status.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 { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport {\n resolveHostToken,\n type HostTokenSource,\n} from '@aglyn/aglyn/app-utils/host-tokens'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { consumeRateLimit, firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { verifyOrderStatusToken } from './order-status-token'\nimport { mintQuoteLinkToken } from './quote-link-token'\nimport { defaultQuotePayDeps, payLinkPayments } from './quote-pay'\nimport { quotePageHref } from '../constants/quote-page'\nimport { resolvePluginTrackingPages } from '@aglyn/aglyn/plugin-manager/plugin-tracking-pages'\n\n/** How long the page waits for a tracking service's own page link (AGL-3635). */\nexport const TRACKING_PAGE_TIMEOUT_MS = 1_500\n\n/** Status lookups one address may make per site, per ten minutes. */\nexport const ORDER_STATUS_LOOKUPS_PER_WINDOW = 60\nexport const ORDER_STATUS_WINDOW_MS = 10 * 60_000\n\n/**\n * Adds buyer actions to the status page (AGL-3610) — the typed extension\n * point for \"Request a return\", which the order-processing work (AGL-3611)\n * owns. A provider sees the verified order and answers the actions that apply\n * to it (none, usually); the page draws each as a button to its `url`. Kept\n * inside commerce: returns are this plugin's, so no cross-plugin seam is\n * needed, and a provider that throws costs the page its buttons, not the page.\n */\nexport type OrderStatusActionsProvider = (input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n /** The verified status token, for a provider building a signed follow-up link. */\n token: string\n}) => CommerceModel.OrderStatusAction[] | Promise<CommerceModel.OrderStatusAction[]>\n\nconst actionProviders: OrderStatusActionsProvider[] = []\n\nexport function registerOrderStatusActions(provider: OrderStatusActionsProvider): void {\n if (!actionProviders.includes(provider)) actionProviders.push(provider)\n}\n\n/** Specs only. */\nexport function clearOrderStatusActions(): void {\n actionProviders.length = 0\n}\n\nasync function actionsFor(\n input: Parameters<OrderStatusActionsProvider>[0],\n): Promise<CommerceModel.OrderStatusAction[]> {\n const answers = await Promise.all(\n actionProviders.map(async (provider) => {\n try {\n return (await provider(input)) ?? []\n } catch (error) {\n console.error('[order-status] actions provider failed', error)\n return []\n }\n }),\n )\n return answers\n .flat()\n .filter(\n (action) =>\n action && action.id && action.label && /^(https:\\/\\/|\\/)/.test(String(action.url)),\n )\n}\n\n/**\n * Pay, on the status page of an order still to be paid that its lasting pay\n * link can take payment for (AGL-4099): a draft order or a quote, opening the\n * same `/pay-quote` page its invoice links to. None for anything else, nor\n * where that page would offer no Pay (AGL-4162): the store's tax choice and\n * its payments are read as the page reads them.\n */\nexport function orderStatusPayAction(input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n currency: string\n store?: CommerceModel.PayLinkStore | null\n paymentsReady?: boolean\n}): CommerceModel.OrderStatusAction | null {\n const { hostId, orderId, order, store } = input\n if (order.status !== 'pending' || !CommerceModel.orderPayLinkKind(order)) return null\n if (CommerceModel.payLinkRefusalWithPayments(CommerceModel.invoicePayRefusal(order, orderId, store), input.paymentsReady)) {\n return null\n }\n const token = mintQuoteLinkToken(hostId, orderId, CommerceModel.orderPayLinkVersion(order))\n if (!token) return null\n const charge = CommerceModel.invoiceCheckoutCharge(order, orderId, store)\n const later = [charge.shippingOptions.length > 0 ? 'shipping' : '', charge.taxAtPayment ? 'tax' : '']\n .filter(Boolean)\n .join(' and ')\n const amount = CommerceModel.formatOrderMoney(charge.totalCents, input.currency)\n return { id: 'pay', label: later ? `Pay ${amount} plus ${later}` : `Pay ${amount}`, url: quotePageHref(orderId, token) }\n}\n\n/**\n * The guest order-status page's data (AGL-3610): `GET\n * /api/commerce/order-status?hostId=…&o=<orderId>&t=<token>` on the store.\n *\n * The token is the whole credential — `verifyOrderStatusToken`, constant\n * time — and a wrong one answers exactly as a missing order does (404), so\n * the route cannot be used to learn which order ids exist. Rate-limited per\n * address per site, durable, BEFORE the token check so guessing costs the\n * same as looking. The answer is `buildOrderStatusView`, an allow-listed\n * projection, never the order document; `Cache-Control: private, no-store`\n * and `X-Robots-Tag: noindex` keep it out of shared caches and search.\n *\n * Registered as a `recipientLink` route: an emailed link has to keep working\n * for the buyer it was sent to, so the per-site enablement gates do not\n * stand between them and their order.\n */\nexport const orderStatusHandler: PluginApiHandler = async (req, res) => {\n res.setHeader('Cache-Control', 'private, no-store')\n res.setHeader('X-Robots-Tag', 'noindex, nofollow')\n if (req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query.hostId ?? '')\n const orderId = String(req.query.o ?? '').slice(0, 200)\n const token = String(req.query.t ?? '').slice(0, 200)\n if (!hostId || !orderId || !token || /^__.*__$/.test(hostId) || /^__.*__$/.test(orderId) || orderId.includes('/')) {\n return res.status(400).json({ error: 'This link is incomplete.' })\n }\n const ip =\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n 'no-address'\n const rate = await consumeRateLimit(`commerce-order-status:${hostId}:${ip}`, {\n limit: ORDER_STATUS_LOOKUPS_PER_WINDOW,\n windowMs: ORDER_STATUS_WINDOW_MS,\n })\n if (!rate.allowed) {\n res.setHeader(\n 'Retry-After',\n String(Math.max(1, Math.ceil((rate.resetMs - Date.now()) / 1000))),\n )\n return res.status(429).json({ error: 'Too many lookups. Try again in a few minutes.' })\n }\n const notFound = () =>\n res.status(404).json({ error: 'We could not find that order. Check the link in your email.' })\n if (!verifyOrderStatusToken(hostId, orderId, token)) return notFound()\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const [hostSnapshot, settingsSnapshot, orderSnapshot] = await Promise.all([\n hostRef.get(),\n hostRef.collection('settings').doc('store').get(),\n hostRef.collection('orders').doc(orderId).get(),\n ])\n if (!hostSnapshot.exists || !orderSnapshot.exists) return notFound()\n const order = CommerceModel.liftLegacyOrder((orderSnapshot.data() ?? {}) as never)\n const currency = String(settingsSnapshot.get('currency') ?? 'USD')\n const linked = order.status === 'pending' ? CommerceModel.orderPayLinkKind(order) : null\n const pay = orderStatusPayAction({\n hostId,\n orderId,\n order,\n currency,\n store: CommerceModel.payLinkStoreOf({ tax: settingsSnapshot.get('tax') }),\n paymentsReady: linked\n ? (await payLinkPayments(defaultQuotePayDeps(), { hostId, orderId, kind: linked })).ready\n : undefined,\n })\n const view = CommerceModel.buildOrderStatusView({\n order,\n orderId,\n storeName: String(\n resolveHostToken('businessName', hostSnapshot.data() as HostTokenSource) ?? '',\n ),\n currency,\n number: CommerceModel.formatOrderNumber(order, orderId),\n actions: [...(pay ? [pay] : []), ...(await actionsFor({ hostId, orderId, order, token }))],\n })\n // A tracking service's own page for each parcel, where the merchant\n // follows them through one (AGL-3635); the carrier's link otherwise.\n const pages = await resolvePluginTrackingPages(\n view.shipments\n .filter((shipment) => shipment.trackingNumber)\n .map((shipment) => ({\n hostId,\n recordId: orderId,\n carrier: shipment.carrier,\n trackingNumber: String(shipment.trackingNumber),\n })),\n { timeoutMs: TRACKING_PAGE_TIMEOUT_MS },\n )\n for (const shipment of view.shipments) {\n const page = shipment.trackingNumber ? pages.get(shipment.trackingNumber) : undefined\n if (page) shipment.trackingUrl = page\n }\n return res.status(200).json(view)\n } catch (error) {\n console.error('orderStatus failed', error)\n return res.status(500).json({ error: 'Your order could not be loaded. Try again.' })\n }\n}\n"],"names":["resolveHostToken","readClientIp","consumeRateLimit","firebaseAdmin","CommerceModel","verifyOrderStatusToken","mintQuoteLinkToken","defaultQuotePayDeps","payLinkPayments","quotePageHref","resolvePluginTrackingPages","TRACKING_PAGE_TIMEOUT_MS","ORDER_STATUS_LOOKUPS_PER_WINDOW","ORDER_STATUS_WINDOW_MS","actionProviders","registerOrderStatusActions","provider","includes","push","clearOrderStatusActions","length","actionsFor","input","answers","Promise","all","map","error","console","flat","filter","action","id","label","test","String","url","orderStatusPayAction","hostId","orderId","order","store","status","orderPayLinkKind","payLinkRefusalWithPayments","invoicePayRefusal","paymentsReady","token","orderPayLinkVersion","charge","invoiceCheckoutCharge","later","shippingOptions","taxAtPayment","Boolean","join","amount","formatOrderMoney","totalCents","currency","orderStatusHandler","req","res","setHeader","method","json","query","o","slice","t","ip","headers","remoteAddress","socket","rate","limit","windowMs","allowed","Math","max","ceil","resetMs","Date","now","notFound","orderSnapshot","settingsSnapshot","firestore","app","hostRef","collection","doc","hostSnapshot","get","exists","liftLegacyOrder","data","linked","pay","payLinkStoreOf","tax","kind","ready","undefined","view","buildOrderStatusView","storeName","number","formatOrderNumber","actions","pages","shipments","shipment","trackingNumber","recordId","carrier","timeoutMs","page","trackingUrl"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD,SACEA,gBAAgB,QAEX,qCAAoC;AAC3C,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,2BAA0B;AAC1E,YAAYC,mBAAmB,oBAA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zG;QAAyB;QAExC,KAAK,MAAMqG,YAAYR,KAAKO,SAAS,CAAE;YACrC,MAAMM,OAAOL,SAASC,cAAc,GAAGH,MAAMjB,GAAG,CAACmB,SAASC,cAAc,IAAIV;YAC5E,IAAIc,MAAML,SAASM,WAAW,GAAGD;QACnC;QACA,OAAOvD,IAAIpB,MAAM,CAAC,KAAKuB,IAAI,CAACuC;IAC9B,EAAE,OAAO7E,OAAO;QACdC,QAAQD,KAAK,CAAC,sBAAsBA;QACpC,OAAOmC,IAAIpB,MAAM,CAAC,KAAKuB,IAAI,CAAC;YAAEtC,OAAO;QAA6C;IACpF;AACF,EAAC"}
|
|
@@ -125,7 +125,8 @@ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
|
125
125
|
proofUrl: input.proofUrl,
|
|
126
126
|
linkReplaced: input.linkReplaced,
|
|
127
127
|
colors: proofColors(theme),
|
|
128
|
-
radius: theme == null ? void 0 : theme.buttonRadius
|
|
128
|
+
radius: theme == null ? void 0 : theme.buttonRadius,
|
|
129
|
+
store: CommerceModel.payLinkStoreOf(input.store)
|
|
129
130
|
});
|
|
130
131
|
// The PDF is what the email says is attached; without it nothing goes.
|
|
131
132
|
let pdf;
|