@aglyn/plugins-commerce 1.15.2 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/pos-cellular-control.component.d.ts +5 -0
  15. package/src/lib/components/console/pos-cellular-control.component.js +29 -15
  16. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  17. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  18. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  19. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  20. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  21. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  22. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  23. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  24. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  25. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  26. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  27. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  28. package/src/lib/components/console/quote-messages.component.js +185 -0
  29. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  30. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  31. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  32. package/src/lib/components/console/quote-proofs.component.js +30 -3
  33. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  34. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  35. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  36. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  37. package/src/lib/components/product-builder-context.d.ts +22 -0
  38. package/src/lib/components/product-builder-context.js +21 -0
  39. package/src/lib/components/product-builder-context.js.map +1 -0
  40. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  41. package/src/lib/components/product-builder-mockup.js +120 -0
  42. package/src/lib/components/product-builder-mockup.js.map +1 -0
  43. package/src/lib/components/product-builder-sample.d.ts +63 -0
  44. package/src/lib/components/product-builder-sample.js +96 -0
  45. package/src/lib/components/product-builder-sample.js.map +1 -0
  46. package/src/lib/components/product-choice-cards.d.ts +51 -0
  47. package/src/lib/components/product-choice-cards.js +311 -0
  48. package/src/lib/components/product-choice-cards.js.map +1 -0
  49. package/src/lib/components/product-detail-panels.d.ts +42 -0
  50. package/src/lib/components/product-detail-panels.js +185 -0
  51. package/src/lib/components/product-detail-panels.js.map +1 -0
  52. package/src/lib/components/product-detail.d.ts +20 -12
  53. package/src/lib/components/product-detail.js +136 -221
  54. package/src/lib/components/product-detail.js.map +1 -1
  55. package/src/lib/components/product-grid.d.ts +7 -0
  56. package/src/lib/components/product-grid.js +13 -9
  57. package/src/lib/components/product-grid.js.map +1 -1
  58. package/src/lib/components/product-name-lines.d.ts +37 -0
  59. package/src/lib/components/product-name-lines.js +36 -0
  60. package/src/lib/components/product-name-lines.js.map +1 -0
  61. package/src/lib/components/product-options-field-body.d.ts +9 -8
  62. package/src/lib/components/product-options-field-body.js +152 -3
  63. package/src/lib/components/product-options-field-body.js.map +1 -1
  64. package/src/lib/components/product-options-field.js +1 -1
  65. package/src/lib/components/product-options-field.js.map +1 -1
  66. package/src/lib/components/product-photo-fit.d.ts +49 -0
  67. package/src/lib/components/product-photo-fit.js +58 -0
  68. package/src/lib/components/product-photo-fit.js.map +1 -0
  69. package/src/lib/components/product-restock-notify.d.ts +12 -0
  70. package/src/lib/components/product-restock-notify.js +86 -0
  71. package/src/lib/components/product-restock-notify.js.map +1 -0
  72. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  73. package/src/lib/components/quote-messages-panel.js +191 -0
  74. package/src/lib/components/quote-messages-panel.js.map +1 -0
  75. package/src/lib/components/quote-page-body.js +15 -1
  76. package/src/lib/components/quote-page-body.js.map +1 -1
  77. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  78. package/src/lib/components/quote-proof-panel.js +139 -14
  79. package/src/lib/components/quote-proof-panel.js.map +1 -1
  80. package/src/lib/components/related-products.d.ts +7 -0
  81. package/src/lib/components/related-products.js +10 -7
  82. package/src/lib/components/related-products.js.map +1 -1
  83. package/src/lib/constants/quote-page.d.ts +8 -0
  84. package/src/lib/constants/quote-page.js +11 -0
  85. package/src/lib/constants/quote-page.js.map +1 -1
  86. package/src/lib/model/commerce-cart.d.ts +6 -1
  87. package/src/lib/model/commerce-cart.js +5 -1
  88. package/src/lib/model/commerce-cart.js.map +1 -1
  89. package/src/lib/model/commerce-invoices.js +5 -1
  90. package/src/lib/model/commerce-invoices.js.map +1 -1
  91. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  92. package/src/lib/model/commerce-pos-ops.js +3 -0
  93. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  94. package/src/lib/model/commerce-pos.d.ts +8 -0
  95. package/src/lib/model/commerce-pos.js.map +1 -1
  96. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  97. package/src/lib/model/commerce-quote-messages.js +146 -0
  98. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  99. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  100. package/src/lib/model/commerce-quote-pay.js +31 -7
  101. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  102. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  103. package/src/lib/model/commerce-quote-proofs.js +73 -18
  104. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  105. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  106. package/src/lib/model/commerce-quote-request.js +25 -2
  107. package/src/lib/model/commerce-quote-request.js.map +1 -1
  108. package/src/lib/model/commerce-quotes.d.ts +56 -3
  109. package/src/lib/model/commerce-quotes.js +47 -2
  110. package/src/lib/model/commerce-quotes.js.map +1 -1
  111. package/src/lib/model/commerce.d.ts +12 -1
  112. package/src/lib/model/commerce.js.map +1 -1
  113. package/src/lib/model/index.d.ts +1 -0
  114. package/src/lib/model/index.js +1 -0
  115. package/src/lib/model/index.js.map +1 -1
  116. package/src/lib/model/pos-cellular.d.ts +36 -4
  117. package/src/lib/model/pos-cellular.js +39 -4
  118. package/src/lib/model/pos-cellular.js.map +1 -1
  119. package/src/lib/model/product-card-rules.d.ts +41 -0
  120. package/src/lib/model/product-card-rules.js +90 -0
  121. package/src/lib/model/product-card-rules.js.map +1 -0
  122. package/src/lib/model/product-modifiers.d.ts +11 -0
  123. package/src/lib/model/product-modifiers.js +10 -0
  124. package/src/lib/model/product-modifiers.js.map +1 -1
  125. package/src/lib/model/product-write.d.ts +3 -0
  126. package/src/lib/server/billing-webhook.js +6 -2
  127. package/src/lib/server/billing-webhook.js.map +1 -1
  128. package/src/lib/server/cancel-order.js +15 -0
  129. package/src/lib/server/cancel-order.js.map +1 -1
  130. package/src/lib/server/channel-order-updates.js +15 -1
  131. package/src/lib/server/channel-order-updates.js.map +1 -1
  132. package/src/lib/server/channel-orders.js +20 -0
  133. package/src/lib/server/channel-orders.js.map +1 -1
  134. package/src/lib/server/checkout.js +1 -1
  135. package/src/lib/server/checkout.js.map +1 -1
  136. package/src/lib/server/local-fulfillment.js +1 -1
  137. package/src/lib/server/local-fulfillment.js.map +1 -1
  138. package/src/lib/server/pos-cellular-billing.d.ts +5 -4
  139. package/src/lib/server/pos-cellular-billing.js +24 -12
  140. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  141. package/src/lib/server/pos-cellular.d.ts +3 -1
  142. package/src/lib/server/pos-cellular.js +55 -33
  143. package/src/lib/server/pos-cellular.js.map +1 -1
  144. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  145. package/src/lib/server/pos-offline-sync.js +17 -4
  146. package/src/lib/server/pos-offline-sync.js.map +1 -1
  147. package/src/lib/server/pos-order.js +17 -6
  148. package/src/lib/server/pos-order.js.map +1 -1
  149. package/src/lib/server/pos-payment.js +27 -11
  150. package/src/lib/server/pos-payment.js.map +1 -1
  151. package/src/lib/server/pos-reader-splash.js +10 -5
  152. package/src/lib/server/pos-reader-splash.js.map +1 -1
  153. package/src/lib/server/pos-readers.js +42 -12
  154. package/src/lib/server/pos-readers.js.map +1 -1
  155. package/src/lib/server/pos-return.js +19 -3
  156. package/src/lib/server/pos-return.js.map +1 -1
  157. package/src/lib/server/pos-stripe.d.ts +14 -0
  158. package/src/lib/server/pos-stripe.js +6 -2
  159. package/src/lib/server/pos-stripe.js.map +1 -1
  160. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  161. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  162. package/src/lib/server/pos-terminal.d.ts +80 -14
  163. package/src/lib/server/pos-terminal.js +393 -123
  164. package/src/lib/server/pos-terminal.js.map +1 -1
  165. package/src/lib/server/product-drafts.d.ts +1 -1
  166. package/src/lib/server/product-drafts.js +4 -3
  167. package/src/lib/server/product-drafts.js.map +1 -1
  168. package/src/lib/server/product-writer.js +5 -4
  169. package/src/lib/server/product-writer.js.map +1 -1
  170. package/src/lib/server/product.d.ts +11 -0
  171. package/src/lib/server/product.js +18 -3
  172. package/src/lib/server/product.js.map +1 -1
  173. package/src/lib/server/products-write.js +4 -3
  174. package/src/lib/server/products-write.js.map +1 -1
  175. package/src/lib/server/quote-email.d.ts +26 -0
  176. package/src/lib/server/quote-email.js +73 -7
  177. package/src/lib/server/quote-email.js.map +1 -1
  178. package/src/lib/server/quote-messages.d.ts +72 -0
  179. package/src/lib/server/quote-messages.js +356 -0
  180. package/src/lib/server/quote-messages.js.map +1 -0
  181. package/src/lib/server/quote-pay.d.ts +42 -0
  182. package/src/lib/server/quote-pay.js +81 -4
  183. package/src/lib/server/quote-pay.js.map +1 -1
  184. package/src/lib/server/quote-proofs.d.ts +1 -1
  185. package/src/lib/server/quote-proofs.js +63 -19
  186. package/src/lib/server/quote-proofs.js.map +1 -1
  187. package/src/lib/server/quote.d.ts +12 -0
  188. package/src/lib/server/quote.js +69 -16
  189. package/src/lib/server/quote.js.map +1 -1
  190. package/src/lib/server/refund.js +3 -1
  191. package/src/lib/server/refund.js.map +1 -1
  192. package/src/lib/server/reserve-stock.js +9 -0
  193. package/src/lib/server/reserve-stock.js.map +1 -1
  194. package/src/lib/server/returns.js +15 -1
  195. package/src/lib/server/returns.js.map +1 -1
  196. package/src/lib/server/reviews.js +15 -0
  197. package/src/lib/server/reviews.js.map +1 -1
  198. package/src/lib/server/sold-out-drop.d.ts +58 -0
  199. package/src/lib/server/sold-out-drop.js +81 -0
  200. package/src/lib/server/sold-out-drop.js.map +1 -0
  201. package/src/lib/server/stock-levels.js +9 -0
  202. package/src/lib/server/stock-levels.js.map +1 -1
  203. package/src/lib/server/stripe-refund.d.ts +7 -0
  204. package/src/lib/server/stripe-refund.js +26 -7
  205. package/src/lib/server/stripe-refund.js.map +1 -1
  206. package/src/lib/server.d.ts +15 -0
  207. package/src/lib/server.js +30 -1
  208. package/src/lib/server.js.map +1 -1
  209. package/src/lib/tenant-emails.js +85 -2
  210. package/src/lib/tenant-emails.js.map +1 -1
  211. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  212. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  213. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  214. package/src/lib/transfer/product-transfer.js +6 -5
  215. package/src/lib/transfer/product-transfer.js.map +1 -1
  216. package/src/lib/transfer/products.server.js +4 -3
  217. package/src/lib/transfer/products.server.js.map +1 -1
  218. package/src/lib/utils/quote-email-content.d.ts +6 -0
  219. package/src/lib/utils/quote-email-content.js +6 -3
  220. 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 {\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 /** The store's sales tax choice, which a quote saved before it was made takes. */\n store: CommerceModel.PayLinkStore\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 proofOnly = CommerceModel.quoteIsProofOnly(order)\n const money = CommerceModel.formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n // The tax the customer is charged (AGL-4162). The saved total stands whichever\n // basis that is: a basis taken from the store's choice now adds no tax here.\n const total = CommerceModel.quotePayTax(quote, input.store).basis.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 // A proof only quote has no price to name yet (AGL-4184).\n ...(proofOnly ? [] : [{ 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 ? (proofOnly\n ? `Revision ${revision} is approved. It has no price yet: add items to the quote when you’re ready, and send it.`\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 store: CommerceModel.payLinkStoreOf({ tax: store.get('tax') }),\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","proofOnly","quoteIsProofOnly","money","formatOrderMoney","Number","totals","totalCents","currency","total","quotePayTax","store","basis","kind","filesSent","length","details","label","filter","Boolean","join","comment","payload","type","level","actionLabel","title","requireProofApproval","link","encodeURIComponent","options","emailDetails","test","replyTo","handleQuoteRespond","idempotencyKey","host","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","payLinkStoreOf","tax","console","quoteProofHand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,qBAAqB8L,KAAK;YAAE9J,QAAQ;YAAKjB,MAAM;gBAAEmB,OAAO;YAA6C;QAAE;IAChH;AACF,EAAC;AAED,uCAAuC,GACvC,OAAO,MAAM8J,qBAAuC,OAAOnL,KAAKiL;IAC9D,IAAI;QACF,OAAO9L,qBAAqB8L,KAAK,MAAMrH,kBAAkBjE,yBAAyBK;IACpF,EAAE,OAAOqB,OAAO;QACd0J,QAAQ1J,KAAK,CAAC,uBAAuBA;QACrC,OAAOlC,qBAAqB8L,KAAK;YAAE9J,QAAQ;YAAKjB,MAAM;gBAAEmB,OAAO;YAAyC;QAAE;IAC5G;AACF,EAAC;AAED,wCAAwC,GACxC,OAAO,MAAM+J,sBAAwC,OAAOpL,KAAKiL,MAC/D9L,qBAAqB8L,KAAK,MAAM/C,mBAAmBvI,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 quoteProofAccessFor,\n quoteProofAccessRefusal,\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, confirmed }\n * { hostId, q, t, v, action: 'changes', comment, name, fileIds? }\n * + Idempotency-Key → 200 { view } | 409 { error, reason } | 410 { replaced } | 404 | 400 | 429\n *\n * An approval ticks every statement the store asks for (`confirmed`, the\n * store's words as the page showed them, AGL-4206); one that skips any is\n * 400, and one whose words the store has since changed is 409 `updated`.\n * A quote that asks a customer with a site account to sign in\n * (`requireProofSignIn`) answers all three routes 403 { reason: 'sign-in' |\n * 'other-account' } until the browser is signed in to that account; a guest\n * keeps the link alone.\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 // A customer with a site account signs in to see it, when the quote asks (AGL-4206).\n const access = await quoteProofAccessFor(deps, req, { hostId, host: linked.loaded.host, order: linked.loaded.order })\n if (access !== 'open') return quoteProofAccessRefusal(access, linked.loaded.storeName)\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 const access = await quoteProofAccessFor(deps, req, { hostId, host: linked.loaded.host, order })\n if (access !== 'open') return quoteProofAccessRefusal(access, storeName)\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 * \"Rejected with changes\" 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 /** The store's sales tax choice, which a quote saved before it was made takes. */\n store: CommerceModel.PayLinkStore\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 proofOnly = CommerceModel.quoteIsProofOnly(order)\n const money = CommerceModel.formatOrderMoney(Number(order.totals?.totalCents ?? 0), input.currency)\n // The tax the customer is charged (AGL-4162). The saved total stands whichever\n // basis that is: a basis taken from the store's choice now adds no tax here.\n const total = CommerceModel.quotePayTax(quote, input.store).basis.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 // A proof only quote has no price to name yet (AGL-4184).\n ...(proofOnly ? [] : [{ label: 'Total', value: total }]),\n ...(approving\n ? [\n { label: 'Approved as', value: response.name ?? '' },\n ...(response.confirmed?.length ? [{ label: 'They confirmed', value: response.confirmed.join(' ') }] : []),\n ]\n : [\n ...(response.name ? [{ label: 'Rejected as', value: response.name }] : []),\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' : 'Rejected with changes',\n actionLabel: 'View quote',\n title: approving\n ? `${customer} approved the proof for ${number} on {site}`\n : `${customer} rejected the proof for ${number} with changes on {site}`,\n body: approving\n ? (proofOnly\n ? `Revision ${revision} is approved. It has no price yet: add items to the quote when you’re ready, and send it.`\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, what they confirmed, and the time and address it was given from, is on the quote.'\n : files.length\n ? `They rejected revision ${revision}. What they want changed, and the ${filesSent} they sent, are on the quote. ` +\n `Read them, then start revision ${revision + 1} with new proofs and send it.`\n : `They rejected revision ${revision}. What they want changed 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 rejects it with 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. A customer with a site account answers\n // signed in to it, when the quote asks (AGL-4206).\n const access = await quoteProofAccessFor(deps, req, { hostId, host, order })\n if (access !== 'open') return quoteProofAccessRefusal(access, storeName)\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 // An approval ticks every statement the store asks for now, word for word (AGL-4206).\n const parsed = CommerceModel.parseQuoteResponseInput(body, CommerceModel.quoteApprovalStatements(store.get('quotes')))\n if ('error' in parsed) {\n return parsed.reason === 'statements-changed'\n ? reasonRefusal(409, 'updated', parsed.error)\n : { status: 400, body: { error: parsed.error } }\n }\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 proofAccess: access,\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 store: CommerceModel.payLinkStoreOf({ tax: store.get('tax') }),\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","quoteProofAccessFor","quoteProofAccessRefusal","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","access","host","loaded","order","storeName","quote","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","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","proofOnly","quoteIsProofOnly","money","formatOrderMoney","Number","totals","totalCents","currency","total","quotePayTax","store","basis","kind","filesSent","length","details","label","filter","Boolean","join","confirmed","comment","payload","type","level","actionLabel","title","requireProofApproval","link","encodeURIComponent","options","emailDetails","test","replyTo","handleQuoteRespond","idempotencyKey","seen","version","updatedAtMs","isFinite","parseQuoteResponseInput","quoteApprovalStatements","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","proofAccess","record","notice","payLinkStoreOf","tax","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,SACEC,mBAAmB,EACnBC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,mBAAmB,EACnBC,uBAAuB,EACvBC,oBAAoB,QAGf,iBAAa;AACpB,SAASC,oBAAoB,EAAEC,iBAAiB,EAAEC,wBAAwB,QAAQ,yBAAqB;AACvG,SAASC,gBAAgB,QAA+B,qBAAiB;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAqC2C,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,aACFf;QACHgB,SAAS,UAAYL;QACrBM,QAAQ,CAAC,GAAGC,OAASpB,sBAAsBoB;;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,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AOvL,KAAKqL;IAC9D,IAAI;QACF,OAAOlM,qBAAqBkM,KAAK,MAAMtH,kBAAkBpE,yBAAyBK;IACpF,EAAE,OAAOqB,OAAO;QACd8J,QAAQ9J,KAAK,CAAC,uBAAuBA;QACrC,OAAOlC,qBAAqBkM,KAAK;YAAElK,QAAQ;YAAKjB,MAAM;gBAAEmB,OAAO;YAAyC;QAAE;IAC5G;AACF,EAAC;AAED,wCAAwC,GACxC,OAAO,MAAMmK,sBAAwC,OAAOxL,KAAKqL,MAC/DlM,qBAAqBkM,KAAK,MAAMhD,mBAAmB1I,yBAAyBK,MAAK"}
@@ -58,6 +58,18 @@ export interface QuoteDeps {
58
58
  * through the core's seam; null when no plugin reads them in this process.
59
59
  */
60
60
  requestFacts(request: PluginRecordFactsRequest): Promise<PluginRecordFactsRead | null>;
61
+ /**
62
+ * The customer's account on the site (AGL-4206), for a send that must not
63
+ * draw a proof a signed-out inbox cannot open. Absent, every customer reads
64
+ * as a guest.
65
+ */
66
+ customerAccount?(input: {
67
+ hostId: string;
68
+ host: Record<string, unknown>;
69
+ email: string;
70
+ }): Promise<{
71
+ id: string;
72
+ } | null>;
61
73
  now(): number;
62
74
  }
63
75
  export declare function defaultQuoteDeps(): QuoteDeps;
@@ -55,6 +55,7 @@ export function defaultQuoteDeps() {
55
55
  var _pluginRecordFactsReader;
56
56
  return (_ref = await ((_pluginRecordFactsReader = pluginRecordFactsReader(CommerceModel.QUOTE_REQUEST_FACTS_RESOURCE)) == null ? void 0 : _pluginRecordFactsReader.reader.read(request))) != null ? _ref : null;
57
57
  },
58
+ customerAccount: async (input)=>(await import("./quote-pay.js")).readQuoteCustomerAccount(input),
58
59
  now: ()=>Date.now()
59
60
  };
60
61
  }
@@ -121,10 +122,12 @@ function headerOf(req, name) {
121
122
  return String(Array.isArray(value) ? (_value_ = value[0]) != null ? _value_ : '' : value != null ? value : '').trim();
122
123
  }
123
124
  const DOC_ID = /^(?!__.*__$)[^/]{1,200}$/;
124
- /** The actions under "Send quotes and invoices to customers" (`commerce.quotes.send`). */ const SEND_ACTIONS = new Set([
125
+ /** The actions under "Send quotes and invoices to customers" (`commerce.quotes.send`). */ // A reply from the quote emails the customer, as a send does (AGL-4207).
126
+ const SEND_ACTIONS = new Set([
125
127
  'pay-link',
126
128
  'replace-link',
127
- 'send'
129
+ 'send',
130
+ 'reply'
128
131
  ]);
129
132
  /** The ship-to as a tax service reads it, or `null` to tax at the store's address. */ function serviceAddress(shipTo) {
130
133
  if (!(shipTo == null ? void 0 : shipTo.country)) return null;
@@ -229,7 +232,8 @@ const DOC_ID = /^(?!__.*__$)[^/]{1,200}$/;
229
232
  totals: CommerceModel.quoteOrderTotals(totals),
230
233
  tax,
231
234
  taxMode: CommerceModel.quoteTaxMode(tax, totals.taxCents),
232
- requireProofApprovalDefault: CommerceModel.quoteRequiresProofApprovalByDefault(store.get('quotes'))
235
+ requireProofApprovalDefault: CommerceModel.quoteRequiresProofApprovalByDefault(store.get('quotes')),
236
+ requireProofSignInDefault: CommerceModel.quoteRequiresProofSignInByDefault(store.get('quotes'))
233
237
  };
234
238
  }
235
239
  /** The editable half of the `quote` section, every key written so a save clears what was removed. */ function editedQuoteFields(input) {
@@ -344,6 +348,22 @@ export async function handleQuote(deps, req) {
344
348
  senderEmail: decoded.email ? String(decoded.email) : null
345
349
  });
346
350
  }
351
+ if (action === 'messages' || action === 'reply') {
352
+ var _body_quoteId3, _host_data2;
353
+ const quoteId = String((_body_quoteId3 = body['quoteId']) != null ? _body_quoteId3 : '');
354
+ if (!DOC_ID.test(quoteId)) return refuse(400, 'Missing quoteId');
355
+ return (await import("./quote-messages.js")).handleQuoteMessagesAction(deps, {
356
+ action,
357
+ req,
358
+ body,
359
+ hostId,
360
+ quoteId,
361
+ hostRef,
362
+ host: (_host_data2 = host.data()) != null ? _host_data2 : {},
363
+ actor,
364
+ senderEmail: decoded.email ? String(decoded.email) : null
365
+ });
366
+ }
347
367
  if (action === 'start-from-request') {
348
368
  var _body_submissionId;
349
369
  const read = await readRequest(deps, {
@@ -365,8 +385,8 @@ export async function handleQuote(deps, req) {
365
385
  };
366
386
  }
367
387
  if (PROOF_ACTIONS.has(action)) {
368
- var _body_quoteId3;
369
- const quoteId = String((_body_quoteId3 = body['quoteId']) != null ? _body_quoteId3 : '');
388
+ var _body_quoteId4;
389
+ const quoteId = String((_body_quoteId4 = body['quoteId']) != null ? _body_quoteId4 : '');
370
390
  if (!DOC_ID.test(quoteId)) return refuse(400, 'Missing quoteId');
371
391
  return handleProofAction(deps, {
372
392
  action,
@@ -380,8 +400,8 @@ export async function handleQuote(deps, req) {
380
400
  });
381
401
  }
382
402
  if (action === 'pdf') {
383
- var _body_quoteId4, _host_data2;
384
- const quoteId = String((_body_quoteId4 = body['quoteId']) != null ? _body_quoteId4 : '');
403
+ var _body_quoteId5, _host_data3;
404
+ const quoteId = String((_body_quoteId5 = body['quoteId']) != null ? _body_quoteId5 : '');
385
405
  if (!DOC_ID.test(quoteId)) return refuse(400, 'Missing quoteId');
386
406
  const [snapshot, store] = await Promise.all([
387
407
  hostRef.collection('orders').doc(quoteId).get(),
@@ -389,7 +409,7 @@ export async function handleQuote(deps, req) {
389
409
  ]);
390
410
  const order = snapshot.exists ? snapshot.data() : null;
391
411
  if (!order || !CommerceModel.isQuote(order) || !order.quote) return refuse(404, 'Unknown quote');
392
- const hostData = (_host_data2 = host.data()) != null ? _host_data2 : {};
412
+ const hostData = (_host_data3 = host.data()) != null ? _host_data3 : {};
393
413
  // The pay link is "Send quotes and invoices to customers"; without it the PDF leaves the link off.
394
414
  const payUrl = CommerceModel.isUnpaidQuote(order) && holdsCommerceSiteKey(host, decoded.uid, 'commerce.quotes.send') ? deps.payLinkUrl(hostData, hostId, quoteId, CommerceModel.quoteLinkVersion(order.quote)) : null;
395
415
  try {
@@ -499,8 +519,11 @@ export async function handleQuote(deps, req) {
499
519
  "closeSession"
500
520
  ]);
501
521
  await closeOpenSession(deps, closeSession, 'quote deleted', hostId);
502
- // Its proofs and anything the customer sent go with it.
503
- if (outcome.status === 200) await removeQuoteFiles(deps, hostId, quoteId);
522
+ // Its proofs, anything the customer sent and its conversation go with it.
523
+ if (outcome.status === 200) {
524
+ await removeQuoteFiles(deps, hostId, quoteId);
525
+ await removeQuoteMessages(ref);
526
+ }
504
527
  return outcome;
505
528
  }
506
529
  if (action !== 'create' && action !== 'update') return refuse(400, 'Unknown action');
@@ -583,7 +606,7 @@ export async function handleQuote(deps, req) {
583
606
  keptProofs.push(kept.file);
584
607
  }
585
608
  await firestore.runTransaction(async (transaction)=>{
586
- var _counter_get, _input_requireProofApproval;
609
+ var _counter_get, _input_requireProofApproval, _input_requireProofSignIn;
587
610
  const counter = await transaction.get(counterRef);
588
611
  number = Number((_counter_get = counter.get('next')) != null ? _counter_get : 1);
589
612
  transaction.set(counterRef, {
@@ -596,7 +619,8 @@ export async function handleQuote(deps, req) {
596
619
  revision: 1
597
620
  }, editedQuoteFields(input), {
598
621
  tax: priced.tax,
599
- requireProofApproval: (_input_requireProofApproval = input.requireProofApproval) != null ? _input_requireProofApproval : priced.requireProofApprovalDefault
622
+ requireProofApproval: (_input_requireProofApproval = input.requireProofApproval) != null ? _input_requireProofApproval : priced.requireProofApprovalDefault,
623
+ requireProofSignIn: (_input_requireProofSignIn = input.requireProofSignIn) != null ? _input_requireProofSignIn : priced.requireProofSignInDefault
600
624
  }, started ? _extends({
601
625
  request: started.request
602
626
  }, started.files.length ? {
@@ -652,7 +676,7 @@ export async function handleQuote(deps, req) {
652
676
  const orderRef = hostRef.collection('orders').doc(quoteId);
653
677
  let closeSession;
654
678
  outcome = await firestore.runTransaction(async (transaction)=>{
655
- var _input_requireProofApproval, _existing_number;
679
+ var _input_requireProofApproval, _input_requireProofSignIn, _existing_number;
656
680
  closeSession = undefined;
657
681
  const snapshot = await transaction.get(orderRef);
658
682
  const existing = snapshot.exists ? snapshot.data() : null;
@@ -685,6 +709,7 @@ export async function handleQuote(deps, req) {
685
709
  quote: _extends({}, existing.quote, editedQuoteFields(input), {
686
710
  tax: priced.tax,
687
711
  requireProofApproval: (_input_requireProofApproval = input.requireProofApproval) != null ? _input_requireProofApproval : existing.quote.requireProofApproval === true,
712
+ requireProofSignIn: (_input_requireProofSignIn = input.requireProofSignIn) != null ? _input_requireProofSignIn : existing.quote.requireProofSignIn === true,
688
713
  updatedAtMs: now,
689
714
  updatedBy: actor
690
715
  })
@@ -765,6 +790,26 @@ export async function handleQuote(deps, req) {
765
790
  file: kept.file
766
791
  };
767
792
  }
793
+ /** How many of a deleted quote's messages one read removes. */ const QUOTE_MESSAGES_DELETE_PAGE = 200;
794
+ /**
795
+ * Deletes a quote's conversation (AGL-4207), which lives under the order and
796
+ * so outlives it otherwise: a draft that was never sent can still hold
797
+ * replies, since it has the customer's address. Never throws.
798
+ */ async function removeQuoteMessages(orderRef) {
799
+ try {
800
+ const messages = orderRef.collection('messages');
801
+ for(;;){
802
+ const page = await messages.limit(QUOTE_MESSAGES_DELETE_PAGE).get();
803
+ if (!page.docs.length) return;
804
+ await Promise.all(page.docs.map((message)=>messages.doc(message.id).delete()));
805
+ }
806
+ } catch (error) {
807
+ console.error('quote messages were not removed', {
808
+ orderPath: orderRef.path,
809
+ error
810
+ });
811
+ }
812
+ }
768
813
  /** Deletes a quote's kept files, its proofs and the customer's artwork; never throws. */ async function removeQuoteFiles(deps, hostId, quoteId) {
769
814
  try {
770
815
  const uploads = await deps.uploads();
@@ -1068,7 +1113,7 @@ async function handleProofAction(deps, context) {
1068
1113
  * link already replaced, so it never replaces it twice.
1069
1114
  *=========================================*/ async function handleSendAction(deps, context) {
1070
1115
  var _ref, _ref1;
1071
- var _order_quote;
1116
+ var _order_quote, _order_quote1;
1072
1117
  const { req, body, hostId, quoteId, hostRef, host, firestore, actor } = context;
1073
1118
  const parsed = CommerceModel.parseQuoteSendInput(body);
1074
1119
  if ('error' in parsed) return refuse(400, parsed.error);
@@ -1162,6 +1207,13 @@ async function handleProofAction(deps, context) {
1162
1207
  const { order, linkVersion, linkReplaced } = prepared;
1163
1208
  await closeOpenSession(deps, prepared.closeSession, 'quote link replaced to send a revision', hostId);
1164
1209
  const payUrl = deps.payLinkUrl(host, hostId, quoteId, linkVersion);
1210
+ // A customer who signs in to see the proof gets no picture of it by email: an inbox is not signed in (AGL-4206).
1211
+ const accountEmail = ((_order_quote = order.quote) == null ? void 0 : _order_quote.requireProofSignIn) === true ? CommerceModel.quoteCustomerAccountEmail(order.quote) : '';
1212
+ const signInFirst = Boolean(accountEmail && deps.customerAccount && await deps.customerAccount({
1213
+ hostId,
1214
+ host,
1215
+ email: accountEmail
1216
+ }).catch(()=>null));
1165
1217
  let delivered;
1166
1218
  try {
1167
1219
  var _store_data;
@@ -1179,7 +1231,8 @@ async function handleProofAction(deps, context) {
1179
1231
  subject: parsed.input.subject,
1180
1232
  message: parsed.input.message,
1181
1233
  payUrl,
1182
- proofUrl: (proofId)=>deps.proofLinkUrl(host, hostId, quoteId, linkVersion, proofId),
1234
+ proofUrl: (proofId)=>signInFirst ? null : deps.proofLinkUrl(host, hostId, quoteId, linkVersion, proofId),
1235
+ signInFirst,
1183
1236
  linkReplaced,
1184
1237
  senderEmail: context.senderEmail,
1185
1238
  atMs: now
@@ -1197,7 +1250,7 @@ async function handleProofAction(deps, context) {
1197
1250
  const done = delivered;
1198
1251
  // The email is out: from here a failure is logged, never answered as one,
1199
1252
  // so a retry does not send it twice.
1200
- const revision = Math.max(1, Number((_ref1 = (_order_quote = order.quote) == null ? void 0 : _order_quote.revision) != null ? _ref1 : 1) || 1);
1253
+ const revision = Math.max(1, Number((_ref1 = (_order_quote1 = order.quote) == null ? void 0 : _order_quote1.revision) != null ? _ref1 : 1) || 1);
1201
1254
  const send = {
1202
1255
  revision,
1203
1256
  to,