@aglyn/plugins-commerce 1.9.1 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/checkout.d.ts +7 -0
- package/src/lib/server/checkout.js +15 -4
- package/src/lib/server/checkout.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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-proofs.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 { claimAttempt, type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { VISITOR_UPLOAD_HONEYPOT_FIELD, visitorUploadFileView, visitorUploadFolder } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport { notifyHostManagers } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport { orderStatusUrl } from './order-status-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { keepSentQuoteUploads, quoteUploadKeyRef, recordPendingQuoteUpload } from './quote-upload-keys'\nimport { quoteUploadCalls, type QuoteUploadCalls } from './quote-uploads'\n\n/*==========================================\n * THE CUSTOMER'S SIDE OF A PROOF (AGL-4096), on the business's site, behind\n * the quote's signed pay link like the page itself:\n *\n * GET /api/commerce/quote-proof?hostId=&q=&t=&file=<proofId>\n * → a proof from any revision, for a link to any version of this quote\n * (a picture inline, anything else as a download) | 404 | 429\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'ticket', file: { name, contentType, size } }\n * → { ticket, upload: { url, fields }, file }\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'finalize', ticket }\n * → { file: { id, name, contentType, size, uploadedAtMs } }\n * POST /api/commerce/quote-respond { hostId, q, t, v, action: 'approve', name }\n * { hostId, q, t, v, action: 'changes', comment, fileIds? }\n * + Idempotency-Key → 200 { view } | 409 { error, reason } | 410 { replaced } | 404 | 400 | 429\n *\n * Every route spends a per-address rate limit on the site BEFORE the token is\n * checked, answers a wrong token exactly as a missing quote, and (but for a\n * proof, which an earlier email still draws) answers a link to an older\n * version as replaced. The uploads are the shared visitor\n * upload (`@aglyn/tenant-data-admin/server/visitor-upload`), scoped to this\n * quote's artwork; the answer names the files by id and the server reads\n * them back from that scope, so nothing else can be attached.\n *\n * `v` is the edit of the quote the page showed, as Pay sends it: an answer to\n * proofs the customer has not seen is refused and the page is shown again.\n *\n * A file goes up before the answer does, so each one is recorded as pending\n * under its quote from its ticket on, and the answer that sends it takes it\n * off; one never sent is deleted a day later (`quote-upload-keys.ts`).\n *=========================================*/\n\n/** Proofs one address may load per site, per ten minutes: every thumbnail of a few visits. */\nexport const QUOTE_PROOF_LOADS_PER_WINDOW = 120\n/** Upload calls (tickets and finalizes) one address may make per site, per ten minutes, before the upload's own limits. */\nexport const QUOTE_UPLOAD_CALLS_PER_WINDOW = 80\n/** Answers one address may send per site, per ten minutes. */\nexport const QUOTE_RESPONSES_PER_WINDOW = 20\n\nexport interface QuoteProofDeps extends QuotePayDeps {\n uploads(): Promise<QuoteUploadCalls>\n notify(...args: Parameters<typeof notifyHostManagers>): Promise<void>\n}\n\nexport function defaultQuoteProofDeps(): QuoteProofDeps {\n return {\n ...defaultQuotePayDeps(),\n uploads: async () => quoteUploadCalls(),\n notify: (...args) => notifyHostManagers(...args),\n }\n}\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 clientIp = (req: PluginApiRequest): string | null =>\n readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress })\n\nconst reasonRefusal = (status: number, reason: string, error: string): QuoteLinkOutcome => ({\n status,\n body: { error, reason },\n})\n\n/** What a proof route answers: a JSON outcome, or a file to stream. */\nexport type QuoteProofOutcome = QuoteLinkOutcome & { file?: { path: string; name: string; contentType: string } }\n\nconst PROOF_GONE: QuoteProofOutcome = { status: 404, body: { error: 'That proof is no longer on this quote.' } }\n\n/**\n * `GET /api/commerce/quote-proof`: one of the proofs in the quote's history\n * (AGL-4097). An email is a record the customer keeps, so the proof it draws\n * keeps showing after the business starts the next revision or replaces the\n * link: any link signed for this quote, an older version's too, is served the\n * current revision's proofs and every earlier revision's as its snapshot kept\n * them. A proof taken off its revision, another quote's file and a wrong token\n * are not found.\n */\nexport async function handleQuoteProof(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteProofOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const query = (req.query ?? {}) as Record<string, unknown>\n const { hostId, quoteId, token, complete } = quoteLinkParams(query)\n const fileId = String(query['file'] ?? '').slice(0, 200)\n if (!complete || !fileId) return { status: 400, body: { error: 'This link is incomplete.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-proof:${hostId}`, QUOTE_PROOF_LOADS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { history: true })\n if ('outcome' in linked) return linked.outcome\n const quote = linked.loaded.order.quote\n // The earlier revisions are read only when the current one lacks the proof.\n let proof = CommerceModel.quoteProofInHistory(quote, [], fileId)\n if (!proof) {\n const listed = await linked.loaded.hostRef.collection('orders').doc(quoteId).collection('revisions').get()\n const snapshots = listed.docs.map((entry) => entry.data() as Partial<CommerceModel.QuoteRevisionSnapshot>)\n proof = CommerceModel.quoteProofInHistory(quote, snapshots, fileId)\n }\n // A proof is kept under this quote's own folder; a path anywhere else is never served.\n const folder = visitorUploadFolder({ hostId, purpose: CommerceModel.QUOTE_PROOF_PURPOSE, purposeId: quoteId })\n if (!proof?.path || !proof.path.startsWith(folder)) return PROOF_GONE\n return { status: 200, body: {}, file: { path: proof.path, name: proof.name, contentType: proof.contentType } }\n}\n\n/** `POST /api/commerce/quote-upload`: a ticket for one of the customer's files, or its finalize. */\nexport async function handleQuoteUpload(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n // A form a person fills never fills this; a bot that did learns nothing.\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-upload:${hostId}`, QUOTE_UPLOAD_CALLS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { order, storeName } = linked.loaded\n // Artwork rides an answer; a quote that cannot be answered takes none.\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const caller = { ip: clientIp(req) ?? 'no-address' }\n const uploads = await deps.uploads()\n if (body['action'] === 'ticket') {\n const minted = await uploads.mint({ scope, request: body['file'], caller })\n if ('error' in minted) {\n return {\n status: minted.status,\n body: { error: minted.error, code: minted.code },\n ...(minted.retryAfterSeconds ? { headers: { 'Retry-After': String(minted.retryAfterSeconds) } } : {}),\n }\n }\n // Pending before a byte can arrive, so a file kept and never sent is always swept.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: minted.file.id, nowMs: deps.now() })\n return { status: 200, body: { ticket: minted.ticket, upload: minted.upload, file: minted.file } }\n }\n if (body['action'] === 'finalize') {\n const kept = await uploads.finalize({ scope, ticket: body['ticket'], caller })\n if ('error' in kept) return { status: kept.status, body: { error: kept.error, code: kept.code } }\n // Its day starts again from the latest file.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: kept.file.id, nowMs: deps.now() })\n return { status: 200, body: { file: visitorUploadFileView(kept.file) } }\n }\n return { status: 400, body: { error: 'Unknown action' } }\n}\n\nconst UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it over again before you answer.'\n\n/**\n * The managers' notice of an answer (AGL-4096): who, which quote and\n * revision, what they said, and what to do next.\n *\n * It rides `content.order`, so whoever is told about orders (in the feed, by\n * email, by push) is told about the quotes that become them, and it names\n * itself as what it is rather than as that type: \"Proof approved\" or\n * \"Changes requested\" where the feed and the email's eyebrow would say \"New\n * order\", the customer and the quote as its heading, and \"View quote\" on the\n * email's button, which opens the quote's dialog on the Orders page.\n */\nfunction noticeOf(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n response: CommerceModel.QuoteCustomerResponse\n currency: string\n}) {\n const { hostId, quoteId, order, response } = input\n const quote = order.quote as CommerceModel.OrderQuote\n const number = CommerceModel.formatQuoteNumber(order, quoteId)\n const customer = quote.customer?.name || quote.customer?.company || quote.customer?.email || 'The customer'\n const revision = response.revision\n const files = response.files ?? []\n const approving = response.action === 'approve'\n const money = CommerceModel.formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = quote.tax?.kind === 'at-payment' ? `${money} before tax` : money\n const filesSent = `${files.length} file${files.length === 1 ? '' : 's'}`\n const details = [\n { label: 'Quote', value: number },\n { label: 'Customer', value: [quote.customer?.name, quote.customer?.company, quote.customer?.email].filter(Boolean).join(', ') },\n { label: 'Revision', value: String(revision) },\n { label: 'Total', value: total },\n ...(approving\n ? [{ label: 'Approved as', value: response.name ?? '' }]\n : [\n { label: 'What to change', value: response.comment ?? '' },\n ...(files.length ? [{ label: 'Files sent', value: files.map((file) => file.name).join(', ') }] : []),\n ]),\n ]\n const email = String(quote.customer?.email ?? '').trim()\n return {\n payload: {\n type: 'content.order' as const,\n // Good news for an approval; a change request is work to read.\n level: approving ? ('success' as const) : ('info' as const),\n label: approving ? 'Proof approved' : 'Changes requested',\n actionLabel: 'View quote',\n title: approving\n ? `${customer} approved the proof for ${number} on {site}`\n : `${customer} asked for changes to ${number} on {site}`,\n body: approving\n ? (quote.requireProofApproval === true\n ? `Revision ${revision} is approved, so they can pay the quote now. It becomes an order when they do.`\n : `Revision ${revision} is approved. The quote becomes an order when they pay.`) +\n ' The approval, with the name, time and address it was given from, is on the quote.'\n : files.length\n ? `What they want changed on revision ${revision}, and the ${filesSent} they sent, are on the quote. ` +\n `Read them, then start revision ${revision + 1} with new proofs and send it.`\n : `What they want changed on revision ${revision} is on the quote. ` +\n `Read it, then start revision ${revision + 1} with new proofs and send it.`,\n link: `/${hostId}/products/orders?quote=${encodeURIComponent(quoteId)}`,\n },\n options: {\n emailDetails: details,\n ...(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { replyTo: email } : {}),\n },\n }\n}\n\n/** `POST /api/commerce/quote-respond`: the customer approves the proof or asks for changes. */\nexport async function handleQuoteRespond(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'An answer needs an Idempotency-Key header.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-respond:${hostId}`, QUOTE_RESPONSES_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store } = linked.loaded\n\n // Everything the customer can be refused is decided before the claim, so\n // none of it spends the attempt.\n const seen = Number(body['v'])\n const version = Number(order.quote?.updatedAtMs) || 0\n if (!Number.isFinite(seen) || seen !== version) return reasonRefusal(409, 'updated', UPDATED_MESSAGE)\n const parsed = CommerceModel.parseQuoteResponseInput(body)\n if ('error' in parsed) return { status: 400, body: { error: parsed.error } }\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n // The files are read back from this quote's artwork, by id: nothing the\n // browser says about a file is believed, and no other record's file can\n // be named.\n let files: CommerceModel.QuoteResponseFile[] = []\n if (parsed.input.action === 'changes' && parsed.input.fileIds.length) {\n const uploads = await deps.uploads()\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const read = await Promise.all(parsed.input.fileIds.map((id) => uploads.read(scope, id)))\n if (read.some((file) => !file)) {\n return { status: 400, body: { error: 'One of your files did not finish sending. Send it again.' } }\n }\n files = read.map((file) => ({\n id: file!.id,\n name: file!.name,\n contentType: file!.contentType,\n size: file!.size,\n path: file!.path,\n }))\n }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-respond',\n scopeId: `${hostId}:${quoteId}`,\n orgId: '',\n key: idempotencyKey,\n busyMessage: 'Your answer 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 try {\n const ref = hostRef.collection('orders').doc(quoteId)\n const pendingRef = quoteUploadKeyRef(deps.firestore(), hostId, quoteId)\n const settled = await deps.firestore().runTransaction(\n async (transaction): Promise<{ outcome: QuoteLinkOutcome; order?: CommerceModel.HostOrder; response?: CommerceModel.QuoteCustomerResponse }> => {\n const snapshot = await transaction.get(ref)\n // The files this answer sends leave the pending record with it.\n const pending = files.length ? await transaction.get(pendingRef) : null\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || !CommerceModel.isQuote(current) || !current.quote) {\n return { outcome: { status: 404, body: { error: 'We could not find that quote. Check the link you were sent.' } } }\n }\n if (CommerceModel.quoteLinkVersion(current.quote) !== CommerceModel.quoteLinkVersion(order.quote)) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This quote was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n }\n }\n if ((Number(current.quote.updatedAtMs) || 0) !== version) {\n return { outcome: reasonRefusal(409, 'updated', UPDATED_MESSAGE) }\n }\n const answered = CommerceModel.applyQuoteResponse(\n current,\n { ...parsed.input, ...(files.length ? { files } : {}) },\n { atMs: now, ip: clientIp(req), userAgent: headerOf(req, 'user-agent') || null },\n )\n if ('reason' in answered) {\n return {\n outcome: reasonRefusal(409, answered.reason, CommerceModel.quoteRespondRefusalMessage(answered.reason, storeName)),\n }\n }\n transaction.set(ref, answered.order)\n if (pending) keepSentQuoteUploads(transaction, pending, pendingRef, files.map((file) => file.id))\n return { outcome: { status: 200, body: {} }, order: answered.order, response: answered.response }\n },\n )\n if (!settled.order || !settled.response) {\n await claim.release()\n return settled.outcome\n }\n const view = CommerceModel.buildQuotePageView({\n order: settled.order,\n orderId: quoteId,\n storeName,\n currency: String(store.get('currency') ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(settled.order) ? null : orderStatusUrl(host, hostId, quoteId),\n })\n const outcome = { status: 200, body: { view } as Record<string, unknown> }\n await claim.record(200, outcome.body)\n const notice = noticeOf({\n hostId,\n quoteId,\n order: settled.order,\n response: settled.response,\n currency: String(store.get('currency') ?? 'USD'),\n })\n void deps.notify(hostId, notice.payload, notice.options)\n return outcome\n } catch (error) {\n console.error('quote respond failed', error)\n await claim.release()\n return { status: 500, body: { error: 'Your answer could not be sent. Try again.' } }\n }\n}\n\n/** `GET /api/commerce/quote-proof`. */\nexport const quoteProofHandler: PluginApiHandler = async (req, res) => {\n const deps = defaultQuoteProofDeps()\n try {\n const outcome = await handleQuoteProof(deps, req)\n if (!outcome.file) return sendQuoteLinkOutcome(res, outcome)\n const uploads = await deps.uploads()\n return await uploads.send(res as never, outcome.file)\n } catch (error) {\n console.error('quote proof failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This proof could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-upload`. */\nexport const quoteUploadHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteUpload(defaultQuoteProofDeps(), req))\n } catch (error) {\n console.error('quote upload failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'The file could not be sent. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-respond`. */\nexport const quoteRespondHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuoteRespond(defaultQuoteProofDeps(), req))\n"],"names":["claimAttempt","readClientIp","VISITOR_UPLOAD_HONEYPOT_FIELD","visitorUploadFileView","visitorUploadFolder","notifyHostManagers","CommerceModel","orderStatusUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","keepSentQuoteUploads","quoteUploadKeyRef","recordPendingQuoteUpload","quoteUploadCalls","QUOTE_PROOF_LOADS_PER_WINDOW","QUOTE_UPLOAD_CALLS_PER_WINDOW","QUOTE_RESPONSES_PER_WINDOW","defaultQuoteProofDeps","uploads","notify","args","bodyOf","req","raw","body","parsed","JSON","parse","headerOf","name","headers","value","toLowerCase","String","Array","isArray","trim","clientIp","remoteAddress","socket","reasonRefusal","status","reason","error","PROOF_GONE","handleQuoteProof","deps","query","method","hostId","quoteId","token","complete","fileId","slice","limited","linked","history","outcome","quote","loaded","order","proof","quoteProofInHistory","listed","hostRef","collection","doc","get","snapshots","docs","map","entry","data","folder","purpose","QUOTE_PROOF_PURPOSE","purposeId","path","startsWith","file","contentType","handleQuoteUpload","honeypot","received","storeName","refused","quoteRespondRefusal","quoteRespondRefusalMessage","scope","QUOTE_ARTWORK_PURPOSE","caller","ip","minted","mint","request","code","retryAfterSeconds","firestore","id","nowMs","now","ticket","upload","kept","finalize","UPDATED_MESSAGE","noticeOf","input","response","number","formatQuoteNumber","customer","company","email","revision","files","approving","action","money","formatOrderMoney","Number","totals","totalCents","currency","total","tax","kind","filesSent","length","details","label","filter","Boolean","join","comment","payload","type","level","actionLabel","title","requireProofApproval","link","encodeURIComponent","options","emailDetails","test","replyTo","handleQuoteRespond","idempotencyKey","host","store","seen","version","updatedAtMs","isFinite","parseQuoteResponseInput","fileIds","read","Promise","all","some","size","claimed","scopeId","orgId","key","busyMessage","replay","claim","ref","pendingRef","settled","runTransaction","transaction","snapshot","pending","current","exists","isQuote","quoteLinkVersion","replaced","answered","applyQuoteResponse","atMs","userAgent","set","release","view","buildQuotePageView","orderId","receiptUrl","isUnpaidQuote","record","notice","console","quoteProofHandler","res","send","quoteUploadHandler","quoteRespondHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAsD,sBAAqB;AAChG,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,6BAA6B,EAAEC,qBAAqB,EAAEC,mBAAmB,QAAQ,wCAAuC;AACjI,SAASC,kBAAkB,QAAQ,2BAA0B;AAC7D,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,cAAc,QAAQ,0BAAsB;AACrD,SACEC,mBAAmB,EACnBC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,oBAAoB,QAGf,iBAAa;AACpB,SAASC,oBAAoB,EAAEC,iBAAiB,EAAEC,wBAAwB,QAAQ,yBAAqB;AACvG,SAASC,gBAAgB,QAA+B,qBAAiB;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA6B2C,GAE3C,4FAA4F,GAC5F,OAAO,MAAMC,+BAA+B,IAAG;AAC/C,yHAAyH,GACzH,OAAO,MAAMC,gCAAgC,GAAE;AAC/C,4DAA4D,GAC5D,OAAO,MAAMC,6BAA6B,GAAE;AAO5C,OAAO,SAASC;IACd,OAAO,aACFZ;QACHa,SAAS,UAAYL;QACrBM,QAAQ,CAAC,GAAGC,OAASlB,sBAAsBkB;;AAE/C;AAEA,SAASC,OAAOC,GAAqB;IACnC,MAAMC,MAAMD,IAAIE,IAAI;IACpB,IAAI,OAAOD,QAAQ,UAAU;QAC3B,IAAI;YACF,MAAME,SAASC,KAAKC,KAAK,CAACJ;YAC1B,OAAOE,UAAU,OAAOA,WAAW,WAAWA,SAAS,CAAC;QAC1D,EAAE,eAAM;YACN,OAAO,CAAC;QACV;IACF;IACA,OAAOF,OAAO,OAAOA,QAAQ,WAAYA,MAAkC,CAAC;AAC9E;AAEA,SAASK,SAASN,GAAqB,EAAEO,IAAY;QAClCP,cACHQ,2BACwBC;IAFtC,MAAMD,WA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OAAO,MAAM4J,qBAAuC,OAAOjL,KAAK+K;IAC9D,IAAI;QACF,OAAO5L,qBAAqB4L,KAAK,MAAMnH,kBAAkBjE,yBAAyBK;IACpF,EAAE,OAAOqB,OAAO;QACdwJ,QAAQxJ,KAAK,CAAC,uBAAuBA;QACrC,OAAOlC,qBAAqB4L,KAAK;YAAE5J,QAAQ;YAAKjB,MAAM;gBAAEmB,OAAO;YAAyC;QAAE;IAC5G;AACF,EAAC;AAED,wCAAwC,GACxC,OAAO,MAAM6J,sBAAwC,OAAOlL,KAAK+K,MAC/D5L,qBAAqB4L,KAAK,MAAMjD,mBAAmBnI,yBAAyBK,MAAK"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-proofs.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 { claimAttempt, type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { VISITOR_UPLOAD_HONEYPOT_FIELD, visitorUploadFileView, visitorUploadFolder } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport { notifyHostManagers } from '@aglyn/tenant-data-admin'\nimport * as CommerceModel from '../model'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n payLinkPageView,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { keepSentQuoteUploads, quoteUploadKeyRef, recordPendingQuoteUpload } from './quote-upload-keys'\nimport { quoteUploadCalls, type QuoteUploadCalls } from './quote-uploads'\n\n/*==========================================\n * THE CUSTOMER'S SIDE OF A PROOF (AGL-4096), on the business's site, behind\n * the quote's signed pay link like the page itself:\n *\n * GET /api/commerce/quote-proof?hostId=&q=&t=&file=<proofId>\n * → a proof from any revision, for a link to any version of this quote\n * (a picture inline, anything else as a download) | 404 | 429\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'ticket', file: { name, contentType, size } }\n * → { ticket, upload: { url, fields }, file }\n * POST /api/commerce/quote-upload { hostId, q, t, action: 'finalize', ticket }\n * → { file: { id, name, contentType, size, uploadedAtMs } }\n * POST /api/commerce/quote-respond { hostId, q, t, v, action: 'approve', name }\n * { hostId, q, t, v, action: 'changes', comment, fileIds? }\n * + Idempotency-Key → 200 { view } | 409 { error, reason } | 410 { replaced } | 404 | 400 | 429\n *\n * Every route spends a per-address rate limit on the site BEFORE the token is\n * checked, answers a wrong token exactly as a missing quote, and (but for a\n * proof, which an earlier email still draws) answers a link to an older\n * version as replaced. The uploads are the shared visitor\n * upload (`@aglyn/tenant-data-admin/server/visitor-upload`), scoped to this\n * quote's artwork; the answer names the files by id and the server reads\n * them back from that scope, so nothing else can be attached.\n *\n * `v` is the edit of the quote the page showed, as Pay sends it: an answer to\n * proofs the customer has not seen is refused and the page is shown again.\n *\n * A file goes up before the answer does, so each one is recorded as pending\n * under its quote from its ticket on, and the answer that sends it takes it\n * off; one never sent is deleted a day later (`quote-upload-keys.ts`).\n *=========================================*/\n\n/** Proofs one address may load per site, per ten minutes: every thumbnail of a few visits. */\nexport const QUOTE_PROOF_LOADS_PER_WINDOW = 120\n/** Upload calls (tickets and finalizes) one address may make per site, per ten minutes, before the upload's own limits. */\nexport const QUOTE_UPLOAD_CALLS_PER_WINDOW = 80\n/** Answers one address may send per site, per ten minutes. */\nexport const QUOTE_RESPONSES_PER_WINDOW = 20\n\nexport interface QuoteProofDeps extends QuotePayDeps {\n uploads(): Promise<QuoteUploadCalls>\n notify(...args: Parameters<typeof notifyHostManagers>): Promise<void>\n}\n\nexport function defaultQuoteProofDeps(): QuoteProofDeps {\n return {\n ...defaultQuotePayDeps(),\n uploads: async () => quoteUploadCalls(),\n notify: (...args) => notifyHostManagers(...args),\n }\n}\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 clientIp = (req: PluginApiRequest): string | null =>\n readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress })\n\nconst reasonRefusal = (status: number, reason: string, error: string): QuoteLinkOutcome => ({\n status,\n body: { error, reason },\n})\n\n/** What a proof route answers: a JSON outcome, or a file to stream. */\nexport type QuoteProofOutcome = QuoteLinkOutcome & { file?: { path: string; name: string; contentType: string } }\n\nconst PROOF_GONE: QuoteProofOutcome = { status: 404, body: { error: 'That proof is no longer on this quote.' } }\n\n/**\n * `GET /api/commerce/quote-proof`: one of the proofs in the quote's history\n * (AGL-4097). An email is a record the customer keeps, so the proof it draws\n * keeps showing after the business starts the next revision or replaces the\n * link: any link signed for this quote, an older version's too, is served the\n * current revision's proofs and every earlier revision's as its snapshot kept\n * them. A proof taken off its revision, another quote's file and a wrong token\n * are not found.\n */\nexport async function handleQuoteProof(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteProofOutcome> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const query = (req.query ?? {}) as Record<string, unknown>\n const { hostId, quoteId, token, complete } = quoteLinkParams(query)\n const fileId = String(query['file'] ?? '').slice(0, 200)\n if (!complete || !fileId) return { status: 400, body: { error: 'This link is incomplete.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-proof:${hostId}`, QUOTE_PROOF_LOADS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { history: true })\n if ('outcome' in linked) return linked.outcome\n const quote = linked.loaded.order.quote\n // The earlier revisions are read only when the current one lacks the proof.\n let proof = CommerceModel.quoteProofInHistory(quote, [], fileId)\n if (!proof) {\n const listed = await linked.loaded.hostRef.collection('orders').doc(quoteId).collection('revisions').get()\n const snapshots = listed.docs.map((entry) => entry.data() as Partial<CommerceModel.QuoteRevisionSnapshot>)\n proof = CommerceModel.quoteProofInHistory(quote, snapshots, fileId)\n }\n // A proof is kept under this quote's own folder; a path anywhere else is never served.\n const folder = visitorUploadFolder({ hostId, purpose: CommerceModel.QUOTE_PROOF_PURPOSE, purposeId: quoteId })\n if (!proof?.path || !proof.path.startsWith(folder)) return PROOF_GONE\n return { status: 200, body: {}, file: { path: proof.path, name: proof.name, contentType: proof.contentType } }\n}\n\n/** `POST /api/commerce/quote-upload`: a ticket for one of the customer's files, or its finalize. */\nexport async function handleQuoteUpload(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n // A form a person fills never fills this; a bot that did learns nothing.\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-upload:${hostId}`, QUOTE_UPLOAD_CALLS_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { order, storeName } = linked.loaded\n // Artwork rides an answer; a quote that cannot be answered takes none.\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const caller = { ip: clientIp(req) ?? 'no-address' }\n const uploads = await deps.uploads()\n if (body['action'] === 'ticket') {\n const minted = await uploads.mint({ scope, request: body['file'], caller })\n if ('error' in minted) {\n return {\n status: minted.status,\n body: { error: minted.error, code: minted.code },\n ...(minted.retryAfterSeconds ? { headers: { 'Retry-After': String(minted.retryAfterSeconds) } } : {}),\n }\n }\n // Pending before a byte can arrive, so a file kept and never sent is always swept.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: minted.file.id, nowMs: deps.now() })\n return { status: 200, body: { ticket: minted.ticket, upload: minted.upload, file: minted.file } }\n }\n if (body['action'] === 'finalize') {\n const kept = await uploads.finalize({ scope, ticket: body['ticket'], caller })\n if ('error' in kept) return { status: kept.status, body: { error: kept.error, code: kept.code } }\n // Its day starts again from the latest file.\n await recordPendingQuoteUpload(deps.firestore(), { hostId, quoteId, fileId: kept.file.id, nowMs: deps.now() })\n return { status: 200, body: { file: visitorUploadFileView(kept.file) } }\n }\n return { status: 400, body: { error: 'Unknown action' } }\n}\n\nconst UPDATED_MESSAGE = 'This quote was updated since you opened it. Look it over again before you answer.'\n\n/**\n * The managers' notice of an answer (AGL-4096): who, which quote and\n * revision, what they said, and what to do next.\n *\n * It rides `content.order`, so whoever is told about orders (in the feed, by\n * email, by push) is told about the quotes that become them, and it names\n * itself as what it is rather than as that type: \"Proof approved\" or\n * \"Changes requested\" where the feed and the email's eyebrow would say \"New\n * order\", the customer and the quote as its heading, and \"View quote\" on the\n * email's button, which opens the quote's dialog on the Orders page.\n */\nfunction noticeOf(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n response: CommerceModel.QuoteCustomerResponse\n currency: string\n}) {\n const { hostId, quoteId, order, response } = input\n const quote = order.quote as CommerceModel.OrderQuote\n const number = CommerceModel.formatQuoteNumber(order, quoteId)\n const customer = quote.customer?.name || quote.customer?.company || quote.customer?.email || 'The customer'\n const revision = response.revision\n const files = response.files ?? []\n const approving = response.action === 'approve'\n const money = CommerceModel.formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = quote.tax?.kind === 'at-payment' ? `${money} before tax` : money\n const filesSent = `${files.length} file${files.length === 1 ? '' : 's'}`\n const details = [\n { label: 'Quote', value: number },\n { label: 'Customer', value: [quote.customer?.name, quote.customer?.company, quote.customer?.email].filter(Boolean).join(', ') },\n { label: 'Revision', value: String(revision) },\n { label: 'Total', value: total },\n ...(approving\n ? [{ label: 'Approved as', value: response.name ?? '' }]\n : [\n { label: 'What to change', value: response.comment ?? '' },\n ...(files.length ? [{ label: 'Files sent', value: files.map((file) => file.name).join(', ') }] : []),\n ]),\n ]\n const email = String(quote.customer?.email ?? '').trim()\n return {\n payload: {\n type: 'content.order' as const,\n // Good news for an approval; a change request is work to read.\n level: approving ? ('success' as const) : ('info' as const),\n label: approving ? 'Proof approved' : 'Changes requested',\n actionLabel: 'View quote',\n title: approving\n ? `${customer} approved the proof for ${number} on {site}`\n : `${customer} asked for changes to ${number} on {site}`,\n body: approving\n ? (quote.requireProofApproval === true\n ? `Revision ${revision} is approved, so they can pay the quote now. It becomes an order when they do.`\n : `Revision ${revision} is approved. The quote becomes an order when they pay.`) +\n ' The approval, with the name, time and address it was given from, is on the quote.'\n : files.length\n ? `What they want changed on revision ${revision}, and the ${filesSent} they sent, are on the quote. ` +\n `Read them, then start revision ${revision + 1} with new proofs and send it.`\n : `What they want changed on revision ${revision} is on the quote. ` +\n `Read it, then start revision ${revision + 1} with new proofs and send it.`,\n link: `/${hostId}/products/orders?quote=${encodeURIComponent(quoteId)}`,\n },\n options: {\n emailDetails: details,\n ...(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { replyTo: email } : {}),\n },\n }\n}\n\n/** `POST /api/commerce/quote-respond`: the customer approves the proof or asks for changes. */\nexport async function handleQuoteRespond(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'An answer needs an Idempotency-Key header.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-respond:${hostId}`, QUOTE_RESPONSES_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { hostRef, host, order, storeName, store } = linked.loaded\n\n // Everything the customer can be refused is decided before the claim, so\n // none of it spends the attempt.\n const seen = Number(body['v'])\n const version = Number(order.quote?.updatedAtMs) || 0\n if (!Number.isFinite(seen) || seen !== version) return reasonRefusal(409, 'updated', UPDATED_MESSAGE)\n const parsed = CommerceModel.parseQuoteResponseInput(body)\n if ('error' in parsed) return { status: 400, body: { error: parsed.error } }\n const refused = CommerceModel.quoteRespondRefusal(order)\n if (refused) return reasonRefusal(409, refused, CommerceModel.quoteRespondRefusalMessage(refused, storeName))\n\n // The files are read back from this quote's artwork, by id: nothing the\n // browser says about a file is believed, and no other record's file can\n // be named.\n let files: CommerceModel.QuoteResponseFile[] = []\n if (parsed.input.action === 'changes' && parsed.input.fileIds.length) {\n const uploads = await deps.uploads()\n const scope = { hostId, purpose: CommerceModel.QUOTE_ARTWORK_PURPOSE, purposeId: quoteId }\n const read = await Promise.all(parsed.input.fileIds.map((id) => uploads.read(scope, id)))\n if (read.some((file) => !file)) {\n return { status: 400, body: { error: 'One of your files did not finish sending. Send it again.' } }\n }\n files = read.map((file) => ({\n id: file!.id,\n name: file!.name,\n contentType: file!.contentType,\n size: file!.size,\n path: file!.path,\n }))\n }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-respond',\n scopeId: `${hostId}:${quoteId}`,\n orgId: '',\n key: idempotencyKey,\n busyMessage: 'Your answer 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 try {\n const ref = hostRef.collection('orders').doc(quoteId)\n const pendingRef = quoteUploadKeyRef(deps.firestore(), hostId, quoteId)\n const settled = await deps.firestore().runTransaction(\n async (transaction): Promise<{ outcome: QuoteLinkOutcome; order?: CommerceModel.HostOrder; response?: CommerceModel.QuoteCustomerResponse }> => {\n const snapshot = await transaction.get(ref)\n // The files this answer sends leave the pending record with it.\n const pending = files.length ? await transaction.get(pendingRef) : null\n const current = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!current || !CommerceModel.isQuote(current) || !current.quote) {\n return { outcome: { status: 404, body: { error: 'We could not find that quote. Check the link you were sent.' } } }\n }\n if (CommerceModel.quoteLinkVersion(current.quote) !== CommerceModel.quoteLinkVersion(order.quote)) {\n return {\n outcome: {\n status: 410,\n body: { replaced: true, error: `This quote was updated, and ${storeName || 'the business'} sent you a newer link.` },\n },\n }\n }\n if ((Number(current.quote.updatedAtMs) || 0) !== version) {\n return { outcome: reasonRefusal(409, 'updated', UPDATED_MESSAGE) }\n }\n const answered = CommerceModel.applyQuoteResponse(\n current,\n { ...parsed.input, ...(files.length ? { files } : {}) },\n { atMs: now, ip: clientIp(req), userAgent: headerOf(req, 'user-agent') || null },\n )\n if ('reason' in answered) {\n return {\n outcome: reasonRefusal(409, answered.reason, CommerceModel.quoteRespondRefusalMessage(answered.reason, storeName)),\n }\n }\n transaction.set(ref, answered.order)\n if (pending) keepSentQuoteUploads(transaction, pending, pendingRef, files.map((file) => file.id))\n return { outcome: { status: 200, body: {} }, order: answered.order, response: answered.response }\n },\n )\n if (!settled.order || !settled.response) {\n await claim.release()\n return settled.outcome\n }\n // The page's own view, so an approval brings Pay back only where Pay would work.\n const view = await payLinkPageView(deps, {\n hostId,\n orderId: quoteId,\n loaded: { host, order: settled.order, storeName, store, kind: 'quote' },\n })\n const outcome = { status: 200, body: { view } as Record<string, unknown> }\n await claim.record(200, outcome.body)\n const notice = noticeOf({\n hostId,\n quoteId,\n order: settled.order,\n response: settled.response,\n currency: String(store.get('currency') ?? 'USD'),\n })\n void deps.notify(hostId, notice.payload, notice.options)\n return outcome\n } catch (error) {\n console.error('quote respond failed', error)\n await claim.release()\n return { status: 500, body: { error: 'Your answer could not be sent. Try again.' } }\n }\n}\n\n/** `GET /api/commerce/quote-proof`. */\nexport const quoteProofHandler: PluginApiHandler = async (req, res) => {\n const deps = defaultQuoteProofDeps()\n try {\n const outcome = await handleQuoteProof(deps, req)\n if (!outcome.file) return sendQuoteLinkOutcome(res, outcome)\n const uploads = await deps.uploads()\n return await uploads.send(res as never, outcome.file)\n } catch (error) {\n console.error('quote proof failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This proof could not be loaded. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-upload`. */\nexport const quoteUploadHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteUpload(defaultQuoteProofDeps(), req))\n } catch (error) {\n console.error('quote upload failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'The file could not be sent. Try again.' } })\n }\n}\n\n/** `POST /api/commerce/quote-respond`. */\nexport const quoteRespondHandler: PluginApiHandler = async (req, res) =>\n sendQuoteLinkOutcome(res, await handleQuoteRespond(defaultQuoteProofDeps(), req))\n"],"names":["claimAttempt","readClientIp","VISITOR_UPLOAD_HONEYPOT_FIELD","visitorUploadFileView","visitorUploadFolder","notifyHostManagers","CommerceModel","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","payLinkPageView","quoteLinkParams","sendQuoteLinkOutcome","keepSentQuoteUploads","quoteUploadKeyRef","recordPendingQuoteUpload","quoteUploadCalls","QUOTE_PROOF_LOADS_PER_WINDOW","QUOTE_UPLOAD_CALLS_PER_WINDOW","QUOTE_RESPONSES_PER_WINDOW","defaultQuoteProofDeps","uploads","notify","args","bodyOf","req","raw","body","parsed","JSON","parse","headerOf","name","headers","value","toLowerCase","String","Array","isArray","trim","clientIp","remoteAddress","socket","reasonRefusal","status","reason","error","PROOF_GONE","handleQuoteProof","deps","query","method","hostId","quoteId","token","complete","fileId","slice","limited","linked","history","outcome","quote","loaded","order","proof","quoteProofInHistory","listed","hostRef","collection","doc","get","snapshots","docs","map","entry","data","folder","purpose","QUOTE_PROOF_PURPOSE","purposeId","path","startsWith","file","contentType","handleQuoteUpload","honeypot","received","storeName","refused","quoteRespondRefusal","quoteRespondRefusalMessage","scope","QUOTE_ARTWORK_PURPOSE","caller","ip","minted","mint","request","code","retryAfterSeconds","firestore","id","nowMs","now","ticket","upload","kept","finalize","UPDATED_MESSAGE","noticeOf","input","response","number","formatQuoteNumber","customer","company","email","revision","files","approving","action","money","formatOrderMoney","Number","totals","totalCents","currency","total","tax","kind","filesSent","length","details","label","filter","Boolean","join","comment","payload","type","level","actionLabel","title","requireProofApproval","link","encodeURIComponent","options","emailDetails","test","replyTo","handleQuoteRespond","idempotencyKey","host","store","seen","version","updatedAtMs","isFinite","parseQuoteResponseInput","fileIds","read","Promise","all","some","size","claimed","scopeId","orgId","key","busyMessage","replay","claim","ref","pendingRef","settled","runTransaction","transaction","snapshot","pending","current","exists","isQuote","quoteLinkVersion","replaced","answered","applyQuoteResponse","atMs","userAgent","set","release","view","orderId","record","notice","console","quoteProofHandler","res","send","quoteUploadHandler","quoteRespondHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,QAAsD,sBAAqB;AAChG,SAASC,YAAY,QAAQ,oCAAm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,GACxC,OAAO,MAAM0J,sBAAwC,OAAO/K,KAAK4K,MAC/DzL,qBAAqByL,KAAK,MAAM9C,mBAAmBnI,yBAAyBK,MAAK"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type HostOrder } from '../model';
|
|
17
|
+
import { type HostOrder, type PayLinkStore } from '../model';
|
|
18
18
|
/** The catalog key the invoice email is sent and designed under. */
|
|
19
19
|
export declare const INVOICE_EMAIL_KEY = "order-invoice";
|
|
20
20
|
export interface InvoiceEmailContentInput {
|
|
@@ -30,6 +30,8 @@ export interface InvoiceEmailContentInput {
|
|
|
30
30
|
payUrl: string | null;
|
|
31
31
|
/** The site's time zone, for the dates. */
|
|
32
32
|
timeZone?: string | null;
|
|
33
|
+
/** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */
|
|
34
|
+
store?: PayLinkStore | null;
|
|
33
35
|
}
|
|
34
36
|
export interface InvoiceEmailContent {
|
|
35
37
|
/** The catalog email's merge tokens. */
|
|
@@ -74,7 +74,7 @@ function capitalize(value) {
|
|
|
74
74
|
const dateMs = orderCreatedAtMs(order) || Number((_ref = quoteSection == null ? void 0 : quoteSection.updatedAtMs) != null ? _ref : quoteSection == null ? void 0 : quoteSection.createdAtMs) || 0;
|
|
75
75
|
const date = longDate(dateMs, timeZone);
|
|
76
76
|
// What it shows: what the link charges while it is unpaid, the order's own figures once paid.
|
|
77
|
-
const charge = paid ? null : invoiceCheckoutCharge(order, orderId);
|
|
77
|
+
const charge = paid ? null : invoiceCheckoutCharge(order, orderId, input.store);
|
|
78
78
|
const totalCents = charge ? charge.totalCents : Math.max(0, Math.round(Number((_ref1 = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref1 : 0)));
|
|
79
79
|
const money = formatOrderMoney(totalCents, input.currency);
|
|
80
80
|
const later = charge ? laterParts(charge.shippingOptions.length > 0, charge.taxAtPayment) : '';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/invoice-email-content.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 {\n formatOrderMoney,\n formatOrderNumber,\n invoiceCheckoutCharge,\n invoiceIsPaid,\n orderCreatedAtMs,\n orderPaidAtMs,\n type HostOrder,\n} from '../model'\n\n/*==========================================\n * WHAT THE INVOICE EMAIL SAYS (AGL-4099).\n *\n * The `order-invoice` catalog email's tokens, composed per send, curated for\n * the two things an invoice can be:\n *\n * - UNPAID: \"Invoice #1042 from Acme Signs\", what it is for, the business's\n * own message, the number, date, total and what is due, how to pay, and\n * one button, \"Pay $1,250.00\", to the order's lasting pay link on the\n * business's site.\n * - PAID: the same heading and details with the date it was paid, \"This\n * invoice is paid; keep it for your records\", and no button.\n *\n * The invoice itself is attached as a PDF by the sender. The figures are the\n * ones the pay link charges (`invoiceCheckoutCharge`) while it is unpaid, and\n * the order's own once paid, so the email, the page and the PDF agree.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the invoice email is sent and designed under. */\nexport const INVOICE_EMAIL_KEY = 'order-invoice'\n\nexport interface InvoiceEmailContentInput {\n order: HostOrder\n orderId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\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 site's time zone, for the dates. */\n timeZone?: string | null\n}\n\nexport interface InvoiceEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The invoice says it is paid: no button. */\n paid: boolean\n /** The total it shows. */\n totalCents: number\n}\n\n/** A date the American way, in the site's time zone: `October 28, 2026`. */\nfunction longDate(ms: number | null | undefined, timeZone?: string | null): string {\n if (!ms || !Number.isFinite(ms)) return ''\n const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' }\n try {\n return new Intl.DateTimeFormat('en-US', { ...options, ...(timeZone ? { timeZone } : {}) }).format(new Date(ms))\n } catch {\n return new Intl.DateTimeFormat('en-US', { ...options, timeZone: 'UTC' }).format(new Date(ms))\n }\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n\n/** `before tax`, `before shipping`, `before shipping and tax`, or nothing. */\nfunction laterParts(shipping: boolean, tax: boolean): string {\n if (shipping && tax) return 'shipping and tax'\n if (shipping) return 'shipping'\n if (tax) return 'tax'\n return ''\n}\n\n/** The invoice email's tokens and its plain-text twin. */\nexport function invoiceEmailContent(input: InvoiceEmailContentInput): InvoiceEmailContent {\n const { order, orderId, timeZone } = input\n const name = input.businessName.trim()\n const business = name || 'the business'\n const number = formatOrderNumber(order, orderId)\n const paid = invoiceIsPaid(order)\n const payUrl = paid ? '' : String(input.payUrl ?? '').trim()\n const forWhat = order.quote ? 'your quote' : 'your order'\n const quoteSection = order.quote\n const dateMs =\n orderCreatedAtMs(order as never) || Number(quoteSection?.updatedAtMs ?? quoteSection?.createdAtMs) || 0\n const date = longDate(dateMs, timeZone)\n\n // What it shows: what the link charges while it is unpaid, the order's own figures once paid.\n const charge = paid ? null : invoiceCheckoutCharge(order, orderId)\n const totalCents = charge ? charge.totalCents : Math.max(0, Math.round(Number(order.totals?.totalCents ?? 0)))\n const money = formatOrderMoney(totalCents, input.currency)\n const later = charge ? laterParts(charge.shippingOptions.length > 0, charge.taxAtPayment) : ''\n const total = later ? `${money} before ${later}` : money\n const refundedCents = Math.max(0, Math.round(Number(order.refundedCents ?? 0)))\n const paidOn = longDate(orderPaidAtMs(order), timeZone)\n const status = paid\n ? `${paidOn ? `Paid on ${paidOn}` : 'Paid'}` +\n (refundedCents > 0 ? `, ${formatOrderMoney(refundedCents, input.currency)} refunded` : '')\n : `Unpaid, ${money}${later ? ` plus ${later}` : ''} due`\n\n const heading = name ? `Invoice ${number} from ${name}` : `Invoice ${number}`\n const intro = paid\n ? `Here is the invoice for ${forWhat} with ${business}` +\n (paidOn ? `, paid on ${paidOn}` : ', which is paid') +\n '. It is attached as a PDF for your records.'\n : `${capitalize(business)} sent you an invoice for ${forWhat}. The details are below, and the invoice is attached as a PDF.`\n const nextStep = paid\n ? 'This invoice is paid; keep it for your records.'\n : payUrl\n ? 'Use the button below to pay it securely by card.' +\n (later ? ` ${capitalize(later)} ${later === 'shipping and tax' ? 'are' : 'is'} added when you pay.` : '') +\n ' The button keeps working until the invoice is paid.'\n : `Reply to this email to arrange payment with ${business}.`\n const buttonLabel = payUrl ? `Pay ${money}${later ? ` plus ${later}` : ''}` : ''\n const message = input.message.trim()\n const details = [`Invoice: ${number}`, date ? `Date: ${date}` : '', `Total: ${total}`, `Status: ${status}`]\n .filter(Boolean)\n .join('\\n')\n\n const tokens: Record<string, string> = {\n 'invoice.subject': input.subject,\n 'invoice.number': number,\n 'invoice.date': date,\n 'invoice.total': total,\n 'invoice.status': status,\n 'invoice.heading': heading,\n 'invoice.intro': intro,\n 'invoice.message': message,\n 'invoice.nextStep': nextStep,\n 'invoice.buttonLabel': buttonLabel,\n 'invoice.url': payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n details,\n nextStep,\n buttonLabel ? `${buttonLabel}: ${payUrl}` : '',\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, paid, totalCents }\n}\n"],"names":["formatOrderMoney","formatOrderNumber","invoiceCheckoutCharge","invoiceIsPaid","orderCreatedAtMs","orderPaidAtMs","INVOICE_EMAIL_KEY","longDate","ms","timeZone","Number","isFinite","options","year","month","day","Intl","DateTimeFormat","format","Date","capitalize","value","toUpperCase","slice","laterParts","shipping","tax","invoiceEmailContent","input","order","orderId","name","businessName","trim","business","number","paid","payUrl","String","forWhat","quote","quoteSection","dateMs","updatedAtMs","createdAtMs","date","charge","totalCents","Math","max","round","totals","money","currency","later","shippingOptions","length","taxAtPayment","total","refundedCents","paidOn","status","heading","intro","nextStep","buttonLabel","message","details","filter","Boolean","join","tokens","subject","text"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,qBAAqB,EACrBC,aAAa,EACbC,gBAAgB,EAChBC,aAAa,QAER,oBAAU;AAEjB;;;;;;;;;;;;;;;;;;2CAkB2C,GAE3C,kEAAkE,GAClE,OAAO,MAAMC,oBAAoB,gBAAe;AA4BhD,0EAA0E,GAC1E,SAASC,SAASC,EAA6B,EAAEC,QAAwB;IACvE,IAAI,CAACD,MAAM,CAACE,OAAOC,QAAQ,CAACH,KAAK,OAAO;IACxC,MAAMI,UAAsC;QAAEC,MAAM;QAAWC,OAAO;QAAQC,KAAK;IAAU;IAC7F,IAAI;QACF,OAAO,IAAIC,KAAKC,cAAc,CAAC,SAAS,aAAKL,SAAaH,WAAW;YAAEA;QAAS,IAAI,CAAC,IAAMS,MAAM,CAAC,IAAIC,KAAKX;IAC7G,EAAE,eAAM;QACN,OAAO,IAAIQ,KAAKC,cAAc,CAAC,SAAS,aAAKL;YAASH,UAAU;YAASS,MAAM,CAAC,IAAIC,KAAKX;IAC3F;AACF;AAEA,SAASY,WAAWC,KAAa;IAC/B,OAAOA,QAAQA,KAAK,CAAC,EAAE,CAACC,WAAW,KAAKD,MAAME,KAAK,CAAC,KAAKF;AAC3D;AAEA,4EAA4E,GAC5E,SAASG,WAAWC,QAAiB,EAAEC,GAAY;IACjD,IAAID,YAAYC,KAAK,OAAO;IAC5B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,CAAC;IAER,MAAMC,SAAiC;QACrC,mBAAmB3C,MAAM4C,OAAO;QAChC,kBAAkBrC;QAClB,gBAAgBU;QAChB,iBAAiBa;QACjB,kBAAkBG;QAClB,mBAAmBC;QACnB,iBAAiBC;QACjB,mBAAmBG;QACnB,oBAAoBF;QACpB,uBAAuBC;QACvB,eAAe5B;IACjB;IAEA,MAAMoC,OAAO;QACXX;QACAC;QACAG;QACAC;QACAH;QACAC,cAAc,GAAGA,YAAY,EAAE,EAAE5B,QAAQ,GAAG;QAC5C,CAAC,6BAA6B,EAAEH,SAAS,CAAC,CAAC;KAC5C,CACEkC,MAAM,CAACC,SACPC,IAAI,CAAC;IAER,OAAO;QAAEC;QAAQE;QAAMrC;QAAMW;IAAW;AAC1C"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/invoice-email-content.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 {\n formatOrderMoney,\n formatOrderNumber,\n invoiceCheckoutCharge,\n invoiceIsPaid,\n orderCreatedAtMs,\n orderPaidAtMs,\n type HostOrder,\n type PayLinkStore,\n} from '../model'\n\n/*==========================================\n * WHAT THE INVOICE EMAIL SAYS (AGL-4099).\n *\n * The `order-invoice` catalog email's tokens, composed per send, curated for\n * the two things an invoice can be:\n *\n * - UNPAID: \"Invoice #1042 from Acme Signs\", what it is for, the business's\n * own message, the number, date, total and what is due, how to pay, and\n * one button, \"Pay $1,250.00\", to the order's lasting pay link on the\n * business's site.\n * - PAID: the same heading and details with the date it was paid, \"This\n * invoice is paid; keep it for your records\", and no button.\n *\n * The invoice itself is attached as a PDF by the sender. The figures are the\n * ones the pay link charges (`invoiceCheckoutCharge`) while it is unpaid, and\n * the order's own once paid, so the email, the page and the PDF agree.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the invoice email is sent and designed under. */\nexport const INVOICE_EMAIL_KEY = 'order-invoice'\n\nexport interface InvoiceEmailContentInput {\n order: HostOrder\n orderId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\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 site's time zone, for the dates. */\n timeZone?: string | null\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null\n}\n\nexport interface InvoiceEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The invoice says it is paid: no button. */\n paid: boolean\n /** The total it shows. */\n totalCents: number\n}\n\n/** A date the American way, in the site's time zone: `October 28, 2026`. */\nfunction longDate(ms: number | null | undefined, timeZone?: string | null): string {\n if (!ms || !Number.isFinite(ms)) return ''\n const options: Intl.DateTimeFormatOptions = { year: 'numeric', month: 'long', day: 'numeric' }\n try {\n return new Intl.DateTimeFormat('en-US', { ...options, ...(timeZone ? { timeZone } : {}) }).format(new Date(ms))\n } catch {\n return new Intl.DateTimeFormat('en-US', { ...options, timeZone: 'UTC' }).format(new Date(ms))\n }\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n\n/** `before tax`, `before shipping`, `before shipping and tax`, or nothing. */\nfunction laterParts(shipping: boolean, tax: boolean): string {\n if (shipping && tax) return 'shipping and tax'\n if (shipping) return 'shipping'\n if (tax) return 'tax'\n return ''\n}\n\n/** The invoice email's tokens and its plain-text twin. */\nexport function invoiceEmailContent(input: InvoiceEmailContentInput): InvoiceEmailContent {\n const { order, orderId, timeZone } = input\n const name = input.businessName.trim()\n const business = name || 'the business'\n const number = formatOrderNumber(order, orderId)\n const paid = invoiceIsPaid(order)\n const payUrl = paid ? '' : String(input.payUrl ?? '').trim()\n const forWhat = order.quote ? 'your quote' : 'your order'\n const quoteSection = order.quote\n const dateMs =\n orderCreatedAtMs(order as never) || Number(quoteSection?.updatedAtMs ?? quoteSection?.createdAtMs) || 0\n const date = longDate(dateMs, timeZone)\n\n // What it shows: what the link charges while it is unpaid, the order's own figures once paid.\n const charge = paid ? null : invoiceCheckoutCharge(order, orderId, input.store)\n const totalCents = charge ? charge.totalCents : Math.max(0, Math.round(Number(order.totals?.totalCents ?? 0)))\n const money = formatOrderMoney(totalCents, input.currency)\n const later = charge ? laterParts(charge.shippingOptions.length > 0, charge.taxAtPayment) : ''\n const total = later ? `${money} before ${later}` : money\n const refundedCents = Math.max(0, Math.round(Number(order.refundedCents ?? 0)))\n const paidOn = longDate(orderPaidAtMs(order), timeZone)\n const status = paid\n ? `${paidOn ? `Paid on ${paidOn}` : 'Paid'}` +\n (refundedCents > 0 ? `, ${formatOrderMoney(refundedCents, input.currency)} refunded` : '')\n : `Unpaid, ${money}${later ? ` plus ${later}` : ''} due`\n\n const heading = name ? `Invoice ${number} from ${name}` : `Invoice ${number}`\n const intro = paid\n ? `Here is the invoice for ${forWhat} with ${business}` +\n (paidOn ? `, paid on ${paidOn}` : ', which is paid') +\n '. It is attached as a PDF for your records.'\n : `${capitalize(business)} sent you an invoice for ${forWhat}. The details are below, and the invoice is attached as a PDF.`\n const nextStep = paid\n ? 'This invoice is paid; keep it for your records.'\n : payUrl\n ? 'Use the button below to pay it securely by card.' +\n (later ? ` ${capitalize(later)} ${later === 'shipping and tax' ? 'are' : 'is'} added when you pay.` : '') +\n ' The button keeps working until the invoice is paid.'\n : `Reply to this email to arrange payment with ${business}.`\n const buttonLabel = payUrl ? `Pay ${money}${later ? ` plus ${later}` : ''}` : ''\n const message = input.message.trim()\n const details = [`Invoice: ${number}`, date ? `Date: ${date}` : '', `Total: ${total}`, `Status: ${status}`]\n .filter(Boolean)\n .join('\\n')\n\n const tokens: Record<string, string> = {\n 'invoice.subject': input.subject,\n 'invoice.number': number,\n 'invoice.date': date,\n 'invoice.total': total,\n 'invoice.status': status,\n 'invoice.heading': heading,\n 'invoice.intro': intro,\n 'invoice.message': message,\n 'invoice.nextStep': nextStep,\n 'invoice.buttonLabel': buttonLabel,\n 'invoice.url': payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n details,\n nextStep,\n buttonLabel ? `${buttonLabel}: ${payUrl}` : '',\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, paid, totalCents }\n}\n"],"names":["formatOrderMoney","formatOrderNumber","invoiceCheckoutCharge","invoiceIsPaid","orderCreatedAtMs","orderPaidAtMs","INVOICE_EMAIL_KEY","longDate","ms","timeZone","Number","isFinite","options","year","month","day","Intl","DateTimeFormat","format","Date","capitalize","value","toUpperCase","slice","laterParts","shipping","tax","invoiceEmailContent","input","order","orderId","name","businessName","trim","business","number","paid","payUrl","String","forWhat","quote","quoteSection","dateMs","updatedAtMs","createdAtMs","date","charge","store","totalCents","Math","max","round","totals","money","currency","later","shippingOptions","length","taxAtPayment","total","refundedCents","paidOn","status","heading","intro","nextStep","buttonLabel","message","details","filter","Boolean","join","tokens","subject","text"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,qBAAqB,EACrBC,aAAa,EACbC,gBAAgB,EAChBC,aAAa,QAGR,oBAAU;AAEjB;;;;;;;;;;;;;;;;;;2CAkB2C,GAE3C,kEAAkE,GAClE,OAAO,MAAMC,oBAAoB,gBAAe;AA8BhD,0EAA0E,GAC1E,SAASC,SAASC,EAA6B,EAAEC,QAAwB;IACvE,IAAI,CAACD,MAAM,CAACE,OAAOC,QAAQ,CAACH,KAAK,OAAO;IACxC,MAAMI,UAAsC;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,SACE,qDACCkB,CAAAA,QAAQ,CAAC,CAAC,EAAEnC,WAAWmC,OAAO,CAAC,EAAEA,UAAU,qBAAqB,QAAQ,KAAK,oBAAoB,CAAC,GAAG,EAAC,IACvG,yDACA,CAAC,4CAA4C,EAAErB,SAAS,CAAC,CAAC;IAChE,MAAMgC,cAAc7B,SAAS,CAAC,IAAI,EAAEgB,QAAQE,QAAQ,CAAC,MAAM,EAAEA,OAAO,GAAG,IAAI,GAAG;IAC9E,MAAMY,UAAUvC,MAAMuC,OAAO,CAAClC,IAAI;IAClC,MAAMmC,UAAU;QAAC,CAAC,SAAS,EAAEjC,QAAQ;QAAEU,OAAO,CAAC,MAAM,EAAEA,MAAM,GAAG;QAAI,CAAC,OAAO,EAAEc,OAAO;QAAE,CAAC,QAAQ,EAAEG,QAAQ;KAAC,CACxGO,MAAM,CAACC,SACPC,IAAI,CAAC;IAER,MAAMC,SAAiC;QACrC,mBAAmB5C,MAAM6C,OAAO;QAChC,kBAAkBtC;QAClB,gBAAgBU;QAChB,iBAAiBc;QACjB,kBAAkBG;QAClB,mBAAmBC;QACnB,iBAAiBC;QACjB,mBAAmBG;QACnB,oBAAoBF;QACpB,uBAAuBC;QACvB,eAAe7B;IACjB;IAEA,MAAMqC,OAAO;QACXX;QACAC;QACAG;QACAC;QACAH;QACAC,cAAc,GAAGA,YAAY,EAAE,EAAE7B,QAAQ,GAAG;QAC5C,CAAC,6BAA6B,EAAEH,SAAS,CAAC,CAAC;KAC5C,CACEmC,MAAM,CAACC,SACPC,IAAI,CAAC;IAER,OAAO;QAAEC;QAAQE;QAAMtC;QAAMY;IAAW;AAC1C"}
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
|
-
import { type HostOrder } from '../model';
|
|
17
|
+
import { type HostOrder, type PayLinkStore } from '../model';
|
|
18
18
|
/** The catalog key the quote email is sent and designed under. */
|
|
19
19
|
export declare const QUOTE_EMAIL_KEY = "quote-sent";
|
|
20
20
|
/** The most proof images drawn in the email; the rest are named. */
|
|
@@ -50,6 +50,8 @@ export interface QuoteEmailContentInput {
|
|
|
50
50
|
colors: QuoteEmailColors;
|
|
51
51
|
/** The theme's corner radius in px, for the images. */
|
|
52
52
|
radius?: number;
|
|
53
|
+
/** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */
|
|
54
|
+
store?: PayLinkStore | null;
|
|
53
55
|
}
|
|
54
56
|
export interface QuoteEmailContent {
|
|
55
57
|
/** The catalog email's merge tokens. */
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
|
-
*/ import { currentQuoteProofs, formatOrderMoney, formatQuoteNumber, quotePaymentBlockedByApproval, quoteSendIsNewRevision } from "../model/index.js";
|
|
16
|
+
*/ import { currentQuoteProofs, formatOrderMoney, formatQuoteNumber, quotePaymentBlockedByApproval, quotePayTax, quoteSendIsNewRevision } from "../model/index.js";
|
|
17
17
|
import { escapeHtml } from "./escape-html.js";
|
|
18
18
|
/*==========================================
|
|
19
19
|
* WHAT THE QUOTE EMAIL SAYS (AGL-4097).
|
|
@@ -57,13 +57,13 @@ import { escapeHtml } from "./escape-html.js";
|
|
|
57
57
|
const plural = (count, one, many)=>`${count} ${count === 1 ? one : many}`;
|
|
58
58
|
/** The quote email's tokens and its plain-text twin. */ export function quoteEmailContent(input) {
|
|
59
59
|
var _order_quote, _quote_revision, _ref, _input_radius;
|
|
60
|
-
var
|
|
60
|
+
var _order_totals;
|
|
61
61
|
const { order, businessName } = input;
|
|
62
62
|
const quote = (_order_quote = order.quote) != null ? _order_quote : {};
|
|
63
63
|
const business = businessName.trim() || 'the business';
|
|
64
64
|
const revision = Math.max(1, Math.floor(Number((_quote_revision = quote.revision) != null ? _quote_revision : 1)) || 1);
|
|
65
65
|
const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\s+/, '');
|
|
66
|
-
const taxAtPayment = (
|
|
66
|
+
const taxAtPayment = quotePayTax(quote, input.store).basis.kind === 'at-payment';
|
|
67
67
|
const money = formatOrderMoney(Number((_ref = (_order_totals = order.totals) == null ? void 0 : _order_totals.totalCents) != null ? _ref : 0), input.currency);
|
|
68
68
|
const total = taxAtPayment ? `${money} before tax` : money;
|
|
69
69
|
const approvalFirst = quotePaymentBlockedByApproval(quote);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/quote-email-content.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 {\n currentQuoteProofs,\n formatOrderMoney,\n formatQuoteNumber,\n quotePaymentBlockedByApproval,\n quoteSendIsNewRevision,\n type HostOrder,\n type OrderQuote,\n} from '../model'\nimport { escapeHtml } from './escape-html'\n\n/*==========================================\n * WHAT THE QUOTE EMAIL SAYS (AGL-4097).\n *\n * The `quote-sent` catalog email's tokens, composed per send: its heading,\n * what this email is (a quote, or an updated revision of one the customer was\n * already emailed: `quoteSendIsNewRevision`, read off the sends on record\n * before this one, so a first email or a resend never says \"updated\"), the business's\n * own message, the quote's number, revision and total, up to three proof\n * images, the other proof files by name, what to do next and the button. The\n * next step and the button follow the business's approval control\n * (`quotePaymentBlockedByApproval`): while the customer must approve the\n * proof first, the button is \"Review and approve\"; otherwise it is \"View and\n * pay\" with the total. Both go to the quote's pay link, where the customer\n * does either.\n *\n * Prices appear only in the tokens the catalog names for them\n * (`quote.total`, `quote.buttonLabel`); the composed markup\n * (`quote.proofImages`) carries pictures and file names, nothing else.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the quote email is sent and designed under. */\nexport const QUOTE_EMAIL_KEY = 'quote-sent'\n\n/** The most proof images drawn in the email; the rest are named. */\nexport const QUOTE_EMAIL_MAX_IMAGES = 3\n\n/**\n * The column's inner width in the built-in copy: the 600px column less the\n * section's padding on each side.\n */\nexport const QUOTE_EMAIL_IMAGE_WIDTH = 552\n\n/**\n * Pictures every inbox draws. WebP is left to the quote page, where it shows:\n * Outlook for Windows draws no WebP.\n */\nconst EMAIL_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif'])\n\n/** The most file names listed before \"and N more\". */\nconst MAX_NAMED_FILES = 5\n\n/** The theme's colors the composed markup draws with, resolved by the sender. */\nexport interface QuoteEmailColors {\n /** The images' outline: the theme's divider. */\n border: string\n /** The caption under each image: the theme's secondary text. */\n muted: string\n}\n\nexport interface QuoteEmailContentInput {\n /** The quote as this email finds it: its `quote.sends` are the emails before this one. */\n order: HostOrder\n quoteId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The quote's pay link, at the version this email carries. */\n payUrl: string\n /** A proof's address behind that link, or null when it has none. */\n proofUrl: (proofId: string) => string | null\n /** This email gives the customer a new pay link, and the earlier email's no longer opens the quote. */\n linkReplaced: boolean\n colors: QuoteEmailColors\n /** The theme's corner radius in px, for the images. */\n radius?: number\n}\n\nexport interface QuoteEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The customer approves the proof before they can pay: the button reads \"Review and approve\". */\n approvalFirst: boolean\n}\n\n/** `a`, `a and b`, `a, b and c`. */\nfunction joinNames(names: readonly string[]): string {\n if (names.length <= 1) return names.join('')\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`\n\n/** The quote email's tokens and its plain-text twin. */\nexport function quoteEmailContent(input: QuoteEmailContentInput): QuoteEmailContent {\n const { order, businessName } = input\n const quote = (order.quote ?? {}) as OrderQuote\n const business = businessName.trim() || 'the business'\n const revision = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\\s+/, '')\n const taxAtPayment = quote.tax?.kind === 'at-payment'\n const money = formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = taxAtPayment ? `${money} before tax` : money\n const approvalFirst = quotePaymentBlockedByApproval(quote)\n\n // The proofs: pictures an inbox draws, up to three, then every other file by name.\n const proofs = currentQuoteProofs(quote)\n const pictured: Array<{ name: string; url: string }> = []\n const named: string[] = []\n let morePictures = 0\n for (const proof of proofs) {\n const url = EMAIL_IMAGE_TYPES.has(String(proof.contentType ?? '').toLowerCase()) ? input.proofUrl(proof.id) : null\n if (url && pictured.length < QUOTE_EMAIL_MAX_IMAGES) pictured.push({ name: proof.name, url })\n else if (url) morePictures += 1\n else named.push(proof.name)\n }\n const listed = named.slice(0, MAX_NAMED_FILES)\n const overflow = named.length - listed.length + morePictures\n const parts = [...listed, ...(overflow > 0 ? [`${plural(overflow, 'more file', 'more files')}`] : [])]\n const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs'\n const seeIt = named.length + morePictures === 1 ? 'See it on your quote page.' : 'See them on your quote page.'\n const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : ''\n\n const radius = Math.max(0, Math.round(Number(input.radius ?? 4)) || 0)\n const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius)\n\n const updated = quoteSendIsNewRevision(quote)\n const heading = updated ? 'Your updated quote' : businessName.trim() ? `Your quote from ${businessName.trim()}` : 'Your quote'\n const intro = updated\n ? `${capitalize(business)} updated your quote. This is revision ${revision}, and it replaces the one sent before.` +\n (input.linkReplaced ? ' The link in the earlier email no longer opens the quote, so use the button below.' : '') +\n ' The new version is attached as a PDF.'\n : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`\n\n const proofed = proofs.length > 0\n const approved = proofed && Number(quote.approvedRevision) === revision\n const nextStep = approvalFirst\n ? 'Look over the proof, then approve it on your quote page. Once you approve it, you can pay there.'\n : approved\n ? 'You approved the proof. Pay on your quote page whenever you’re ready.'\n : proofed\n ? 'Look over your quote and the proof. On your quote page you can approve the proof or ask for changes, and pay whenever you’re ready.'\n : 'Look over your quote, and pay it on your quote page whenever you’re ready.'\n const buttonLabel = approvalFirst ? 'Review and approve' : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`\n const message = input.message.trim()\n\n const tokens: Record<string, string> = {\n 'quote.subject': input.subject,\n 'quote.number': number,\n 'quote.revision': String(revision),\n 'quote.total': total,\n 'quote.heading': heading,\n 'quote.intro': intro,\n 'quote.message': message,\n 'quote.proofImages': proofImages,\n 'quote.proofFiles': proofFiles,\n 'quote.nextStep': nextStep,\n 'quote.buttonLabel': buttonLabel,\n 'quote.url': input.payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n `Quote: ${number}\\nRevision: ${revision}\\nTotal: ${total}`,\n pictured.length ? `Proof: ${joinNames(pictured.map((proof) => proof.name))}` : '',\n proofFiles,\n nextStep,\n `${buttonLabel}: ${input.payUrl}`,\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, approvalFirst }\n}\n\n/** The space between two pictures side by side, in px. */\nconst IMAGE_GAP = 12\n\n/**\n * The proof pictures, each linked to the quote page with its file name under\n * it: one across the column, or two or three side by side, so the button\n * stays near. A table, the layout every inbox keeps.\n */\nfunction proofImagesHtml(\n pictured: ReadonlyArray<{ name: string; url: string }>,\n payUrl: string,\n colors: QuoteEmailColors,\n radius: number,\n): string {\n if (!pictured.length) return ''\n const count = pictured.length\n const width = Math.floor((QUOTE_EMAIL_IMAGE_WIDTH - IMAGE_GAP * (count - 1)) / count)\n const cells = pictured.map((proof, index) => {\n const left = index === 0 ? 0 : IMAGE_GAP / 2\n const right = index === count - 1 ? 0 : IMAGE_GAP / 2\n return (\n `<td style=\"width:${Math.round(100 / count)}%;vertical-align:top;padding:4px ${right}px 12px ${left}px;\">` +\n `<a href=\"${escapeHtml(payUrl)}\">` +\n `<img src=\"${escapeHtml(proof.url)}\" alt=\"${escapeHtml(`Proof: ${proof.name}`)}\" width=\"${width}\" ` +\n `style=\"display:block;width:100%;max-width:${width}px;height:auto;box-sizing:border-box;` +\n `border:1px solid ${colors.border};border-radius:${radius}px;\" />` +\n `</a>` +\n `<div style=\"font-size:13px;line-height:1.4;color:${colors.muted};padding-top:6px;word-break:break-word;\">${escapeHtml(proof.name)}</div>` +\n `</td>`\n )\n })\n return (\n `<table role=\"presentation\" style=\"width:100%;border-collapse:collapse;\">` +\n `<tr>${cells.join('')}</tr>` +\n `</table>`\n )\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n"],"names":["currentQuoteProofs","formatOrderMoney","formatQuoteNumber","quotePaymentBlockedByApproval","quoteSendIsNewRevision","escapeHtml","QUOTE_EMAIL_KEY","QUOTE_EMAIL_MAX_IMAGES","QUOTE_EMAIL_IMAGE_WIDTH","EMAIL_IMAGE_TYPES","Set","MAX_NAMED_FILES","joinNames","names","length","join","slice","plural","count","one","many","quoteEmailContent","input","order","quote","businessName","business","trim","revision","Math","max","floor","Number","number","quoteId","replace","taxAtPayment","tax","kind","money","totals","totalCents","currency","total","approvalFirst","proofs","pictured","named","morePictures","proof","url","has","String","contentType","toLowerCase","proofUrl","id","push","name","listed","overflow","parts","lead","seeIt","proofFiles","radius","round","proofImages","proofImagesHtml","payUrl","colors","updated","heading","intro","capitalize","linkReplaced","proofed","approved","approvedRevision","nextStep","buttonLabel","message","tokens","subject","text","map","filter","Boolean","IMAG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CAAqC,CAAC,GACzF,CAAC,iBAAiB,EAAEnB,OAAOwB,MAAM,CAAC,eAAe,EAAE7B,OAAO,OAAO,CAAC,GAClE,CAAC,IAAI,CAAC,GACN,CAAC,iDAAiD,EAAEK,OAAOyB,KAAK,CAAC,yCAAyC,EAAE1F,WAAW4C,MAAMS,IAAI,EAAE,MAAM,CAAC,GAC1I,CAAC,KAAK,CAAC;IAEX;IACA,OACE,CAAC,wEAAwE,CAAC,GAC1E,CAAC,IAAI,EAAEgC,MAAM3E,IAAI,CAAC,IAAI,KAAK,CAAC,GAC5B,CAAC,QAAQ,CAAC;AAEd;AAEA,SAAS2D,WAAWsB,KAAa;IAC/B,OAAOA,QAAQA,KAAK,CAAC,EAAE,CAACC,WAAW,KAAKD,MAAMhF,KAAK,CAAC,KAAKgF;AAC3D"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/utils/quote-email-content.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 {\n currentQuoteProofs,\n formatOrderMoney,\n formatQuoteNumber,\n quotePaymentBlockedByApproval,\n quotePayTax,\n quoteSendIsNewRevision,\n type HostOrder,\n type OrderQuote,\n type PayLinkStore,\n} from '../model'\nimport { escapeHtml } from './escape-html'\n\n/*==========================================\n * WHAT THE QUOTE EMAIL SAYS (AGL-4097).\n *\n * The `quote-sent` catalog email's tokens, composed per send: its heading,\n * what this email is (a quote, or an updated revision of one the customer was\n * already emailed: `quoteSendIsNewRevision`, read off the sends on record\n * before this one, so a first email or a resend never says \"updated\"), the business's\n * own message, the quote's number, revision and total, up to three proof\n * images, the other proof files by name, what to do next and the button. The\n * next step and the button follow the business's approval control\n * (`quotePaymentBlockedByApproval`): while the customer must approve the\n * proof first, the button is \"Review and approve\"; otherwise it is \"View and\n * pay\" with the total. Both go to the quote's pay link, where the customer\n * does either.\n *\n * Prices appear only in the tokens the catalog names for them\n * (`quote.total`, `quote.buttonLabel`); the composed markup\n * (`quote.proofImages`) carries pictures and file names, nothing else.\n *\n * Pure: the send route and the sample renders call the same function.\n *=========================================*/\n\n/** The catalog key the quote email is sent and designed under. */\nexport const QUOTE_EMAIL_KEY = 'quote-sent'\n\n/** The most proof images drawn in the email; the rest are named. */\nexport const QUOTE_EMAIL_MAX_IMAGES = 3\n\n/**\n * The column's inner width in the built-in copy: the 600px column less the\n * section's padding on each side.\n */\nexport const QUOTE_EMAIL_IMAGE_WIDTH = 552\n\n/**\n * Pictures every inbox draws. WebP is left to the quote page, where it shows:\n * Outlook for Windows draws no WebP.\n */\nconst EMAIL_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif'])\n\n/** The most file names listed before \"and N more\". */\nconst MAX_NAMED_FILES = 5\n\n/** The theme's colors the composed markup draws with, resolved by the sender. */\nexport interface QuoteEmailColors {\n /** The images' outline: the theme's divider. */\n border: string\n /** The caption under each image: the theme's secondary text. */\n muted: string\n}\n\nexport interface QuoteEmailContentInput {\n /** The quote as this email finds it: its `quote.sends` are the emails before this one. */\n order: HostOrder\n quoteId: string\n businessName: string\n currency: string\n /** The subject the email goes under. */\n subject: string\n /** The business's message, as typed; may be empty. */\n message: string\n /** The quote's pay link, at the version this email carries. */\n payUrl: string\n /** A proof's address behind that link, or null when it has none. */\n proofUrl: (proofId: string) => string | null\n /** This email gives the customer a new pay link, and the earlier email's no longer opens the quote. */\n linkReplaced: boolean\n colors: QuoteEmailColors\n /** The theme's corner radius in px, for the images. */\n radius?: number\n /** The store's sales tax choice, which a quote saved before it was made takes (`quotePayTax`). */\n store?: PayLinkStore | null\n}\n\nexport interface QuoteEmailContent {\n /** The catalog email's merge tokens. */\n tokens: Record<string, string>\n /** The same email as plain text, for a send whose design cannot be rendered. */\n text: string\n /** The customer approves the proof before they can pay: the button reads \"Review and approve\". */\n approvalFirst: boolean\n}\n\n/** `a`, `a and b`, `a, b and c`. */\nfunction joinNames(names: readonly string[]): string {\n if (names.length <= 1) return names.join('')\n return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`\n\n/** The quote email's tokens and its plain-text twin. */\nexport function quoteEmailContent(input: QuoteEmailContentInput): QuoteEmailContent {\n const { order, businessName } = input\n const quote = (order.quote ?? {}) as OrderQuote\n const business = businessName.trim() || 'the business'\n const revision = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const number = formatQuoteNumber(order, input.quoteId).replace(/^Quote\\s+/, '')\n const taxAtPayment = quotePayTax(quote, input.store).basis.kind === 'at-payment'\n const money = formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n const total = taxAtPayment ? `${money} before tax` : money\n const approvalFirst = quotePaymentBlockedByApproval(quote)\n\n // The proofs: pictures an inbox draws, up to three, then every other file by name.\n const proofs = currentQuoteProofs(quote)\n const pictured: Array<{ name: string; url: string }> = []\n const named: string[] = []\n let morePictures = 0\n for (const proof of proofs) {\n const url = EMAIL_IMAGE_TYPES.has(String(proof.contentType ?? '').toLowerCase()) ? input.proofUrl(proof.id) : null\n if (url && pictured.length < QUOTE_EMAIL_MAX_IMAGES) pictured.push({ name: proof.name, url })\n else if (url) morePictures += 1\n else named.push(proof.name)\n }\n const listed = named.slice(0, MAX_NAMED_FILES)\n const overflow = named.length - listed.length + morePictures\n const parts = [...listed, ...(overflow > 0 ? [`${plural(overflow, 'more file', 'more files')}`] : [])]\n const lead = pictured.length ? 'Also with this revision' : named.length === 1 ? 'Proof' : 'Proofs'\n const seeIt = named.length + morePictures === 1 ? 'See it on your quote page.' : 'See them on your quote page.'\n const proofFiles = parts.length ? `${lead}: ${joinNames(parts)}. ${seeIt}` : ''\n\n const radius = Math.max(0, Math.round(Number(input.radius ?? 4)) || 0)\n const proofImages = proofImagesHtml(pictured, input.payUrl, input.colors, radius)\n\n const updated = quoteSendIsNewRevision(quote)\n const heading = updated ? 'Your updated quote' : businessName.trim() ? `Your quote from ${businessName.trim()}` : 'Your quote'\n const intro = updated\n ? `${capitalize(business)} updated your quote. This is revision ${revision}, and it replaces the one sent before.` +\n (input.linkReplaced ? ' The link in the earlier email no longer opens the quote, so use the button below.' : '') +\n ' The new version is attached as a PDF.'\n : `${capitalize(business)} put together a quote for you. The details are below, and the quote is attached as a PDF.`\n\n const proofed = proofs.length > 0\n const approved = proofed && Number(quote.approvedRevision) === revision\n const nextStep = approvalFirst\n ? 'Look over the proof, then approve it on your quote page. Once you approve it, you can pay there.'\n : approved\n ? 'You approved the proof. Pay on your quote page whenever you’re ready.'\n : proofed\n ? 'Look over your quote and the proof. On your quote page you can approve the proof or ask for changes, and pay whenever you’re ready.'\n : 'Look over your quote, and pay it on your quote page whenever you’re ready.'\n const buttonLabel = approvalFirst ? 'Review and approve' : `View and pay ${money}${taxAtPayment ? ' plus tax' : ''}`\n const message = input.message.trim()\n\n const tokens: Record<string, string> = {\n 'quote.subject': input.subject,\n 'quote.number': number,\n 'quote.revision': String(revision),\n 'quote.total': total,\n 'quote.heading': heading,\n 'quote.intro': intro,\n 'quote.message': message,\n 'quote.proofImages': proofImages,\n 'quote.proofFiles': proofFiles,\n 'quote.nextStep': nextStep,\n 'quote.buttonLabel': buttonLabel,\n 'quote.url': input.payUrl,\n }\n\n const text = [\n heading,\n intro,\n message,\n `Quote: ${number}\\nRevision: ${revision}\\nTotal: ${total}`,\n pictured.length ? `Proof: ${joinNames(pictured.map((proof) => proof.name))}` : '',\n proofFiles,\n nextStep,\n `${buttonLabel}: ${input.payUrl}`,\n `Reply to this email to reach ${business}.`,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n\n return { tokens, text, approvalFirst }\n}\n\n/** The space between two pictures side by side, in px. */\nconst IMAGE_GAP = 12\n\n/**\n * The proof pictures, each linked to the quote page with its file name under\n * it: one across the column, or two or three side by side, so the button\n * stays near. A table, the layout every inbox keeps.\n */\nfunction proofImagesHtml(\n pictured: ReadonlyArray<{ name: string; url: string }>,\n payUrl: string,\n colors: QuoteEmailColors,\n radius: number,\n): string {\n if (!pictured.length) return ''\n const count = pictured.length\n const width = Math.floor((QUOTE_EMAIL_IMAGE_WIDTH - IMAGE_GAP * (count - 1)) / count)\n const cells = pictured.map((proof, index) => {\n const left = index === 0 ? 0 : IMAGE_GAP / 2\n const right = index === count - 1 ? 0 : IMAGE_GAP / 2\n return (\n `<td style=\"width:${Math.round(100 / count)}%;vertical-align:top;padding:4px ${right}px 12px ${left}px;\">` +\n `<a href=\"${escapeHtml(payUrl)}\">` +\n `<img src=\"${escapeHtml(proof.url)}\" alt=\"${escapeHtml(`Proof: ${proof.name}`)}\" width=\"${width}\" ` +\n `style=\"display:block;width:100%;max-width:${width}px;height:auto;box-sizing:border-box;` +\n `border:1px solid ${colors.border};border-radius:${radius}px;\" />` +\n `</a>` +\n `<div style=\"font-size:13px;line-height:1.4;color:${colors.muted};padding-top:6px;word-break:break-word;\">${escapeHtml(proof.name)}</div>` +\n `</td>`\n )\n })\n return (\n `<table role=\"presentation\" style=\"width:100%;border-collapse:collapse;\">` +\n `<tr>${cells.join('')}</tr>` +\n `</table>`\n )\n}\n\nfunction capitalize(value: string): string {\n return value ? value[0].toUpperCase() + value.slice(1) : value\n}\n"],"names":["currentQuoteProofs","formatOrderMoney","formatQuoteNumber","quotePaymentBlockedByApproval","quotePayTax","quoteSendIsNewRevision","escapeHtml","QUOTE_EMAIL_KEY","QUOTE_EMAIL_MAX_IMAGES","QUOTE_EMAIL_IMAGE_WIDTH","EMAIL_IMAGE_TYPES","Set","MAX_NAMED_FILES","joinNames","names","length","join","slice","plural","count","one","many","quoteEmailContent","input","order","quote","businessName","business","trim","revision","Math","max","floor","Number","number","quoteId","replace","taxAtPayment","store","basis","kind","money","totals","totalCents","currency","total","approvalFirst","proofs","pictured","named","morePictures","proof","url","has","String","contentType","toLowerCase","proofUrl","id","push","name","listed","overflow","parts","lead","seeIt","proofFiles","radius","round","proofImages","proofImagesHtml","payUrl","colors","updated","heading","intro","capitalize","linkReplaced","proofed","approved","approvedRevision","nextStep","buttonLabel","message","tokens","subject","text","map","filter","Boolean","IMAGE_GAP","width","cells","index","left","right","border","muted","value","toUpperCase"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,6BAA6B,EAC7BC,WAAW,EACXC,sBAAsB,QAIjB,oBAAU;AACjB,SAASC,UAAU,QAAQ,mBAAe;AAE1C;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,gEAAgE,GAChE,OAAO,MAAMC,kBAAkB,aAAY;AAE3C,kEAAkE,GAClE,OAAO,MAAMC,yBAAyB,EAAC;AAEvC;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C;;;CAGC,GACD,MAAMC,oBAAoB,IAAIC,IAAI;IAAC;IAAa;IAAc;CAAY;AAE1E,oDAAoD,GACpD,MAAMC,kBAAkB;AA0CxB,kCAAkC,GAClC,SAASC,UAAUC,KAAwB;IACzC,IAAIA,MAAMC,MAAM,IAAI,GAAG,OAAOD,MAAME,IAAI,CAAC;IACzC,OAAO,GAAGF,MAAMG,KAAK,CAAC,GAAG,CAAC,GAAGD,IAAI,CAAC,MAAM,KAAK,EAAEF,KAAK,CAACA,MAAMC,MAAM,GAAG,EAAE,EAAE;AAC1E;AAEA,MAAMG,SAAS,CAACC,OAAeC,KAAaC,OAAiB,GAAGF,MAAM,CAAC,EAAEA,UAAU,IAAIC,MAAMC,MAAM;AAEnG,sDAAsD,GACtD,OAAO,SAASC,kBAAkBC,KAA6B;QAE9CC,cAEgCC,uBAyBFF;QAtBPC;IAN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