@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/model/commerce-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 { visitorUploadTypeOf } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport { appendOrderEvent, type HostOrder, type OrderAddress, type OrderLineItem, type OrderTotals } from './commerce-orders'\nimport {\n formatQuoteNumber,\n isQuote,\n isUnpaidQuote,\n quoteIsProofOnly,\n type OrderQuote,\n type QuoteApproval,\n type QuoteCustomer,\n type QuoteCustomerResponse,\n type QuoteDiscount,\n type QuoteProof,\n type QuoteResponseFile,\n type QuoteShipping,\n type QuoteStage,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { StorefrontTaxMode } from './commerce-tax-decision'\n\n/*==========================================\n * PROOFS, REVISIONS AND THE CUSTOMER'S ANSWER (AGL-4096).\n *\n * A quote's REVISION is the version the customer is looking at. The business\n * attaches proofs to the current revision; the customer approves them under\n * a typed name or asks for changes; the business then starts the next\n * revision, which keeps the one before exactly as it stood in\n * `hosts/{hostId}/orders/{id}/revisions/{n}` and starts the new one with no\n * proofs and no answer. Every revision is kept.\n *\n * Whether paying waits on an approval is the business's control\n * (`requireProofApproval`, AGL-4093) and `quotePaymentBlockedByApproval`\n * answers it; nothing here makes paying wait when it is off.\n *\n * Pure: the console route, the customer's route and (slice 5) the send that\n * starts a revision all call these, and write what they answer.\n *=========================================*/\n\n/** The most proofs one revision holds. */\nexport const QUOTE_MAX_PROOFS = 10\n\n/** The most answers the customer gives one revision; plenty for a change of mind. */\nexport const QUOTE_MAX_RESPONSES = 20\n\n/** The longest comment a customer may leave. */\nexport const QUOTE_MAX_COMMENT = 5_000\n\n/** The longest name an approval is signed with. */\nexport const QUOTE_MAX_APPROVER_NAME = 120\n\n/** What the visitor uploads are called for a quote: its proofs, and the customer's artwork. */\nexport const QUOTE_PROOF_PURPOSE = 'quote-proof'\nexport const QUOTE_ARTWORK_PURPOSE = 'quote-artwork'\n\n/** A revision as it stood when the next one started. */\nexport interface QuoteRevisionSnapshot {\n revision: number\n /** Where it stood with the business when it closed. */\n stage: QuoteStage\n lineItems: OrderLineItem[]\n totals: OrderTotals | null\n taxMode: StorefrontTaxMode | null\n tax: QuoteTaxBasis | null\n discount: QuoteDiscount | null\n shipping: QuoteShipping | null\n notes: string\n terms: string\n customer: QuoteCustomer | null\n billTo: OrderAddress | null\n shipTo: OrderAddress | null\n proofs: QuoteProof[]\n responses: QuoteCustomerResponse[]\n approval: QuoteApproval | null\n /** When the revision was last written by the business. */\n updatedAtMs: number\n /** When the next revision started, and who started it. */\n closedAtMs: number\n closedBy: string\n}\n\n/** The current revision's proofs. */\nexport function currentQuoteProofs(quote: Pick<OrderQuote, 'proofs' | 'revision'> | null | undefined): QuoteProof[] {\n const revision = Number(quote?.revision ?? 1)\n return (quote?.proofs ?? []).filter((proof) => Number(proof?.revision) === revision)\n}\n\n/**\n * One of the proofs the quote has shown its customer, by id (AGL-4097): the\n * current revision's, else an earlier revision's as its snapshot keeps it\n * (`orders/{id}/revisions/{n}`). A proof the business took off a revision\n * before the next one started is in neither, so it is not found.\n */\nexport function quoteProofInHistory(\n quote: Pick<OrderQuote, 'proofs' | 'revision'> | null | undefined,\n snapshots: ReadonlyArray<Partial<Pick<QuoteRevisionSnapshot, 'proofs'>> | null | undefined>,\n proofId: string,\n): QuoteProof | null {\n if (!proofId) return null\n const current = currentQuoteProofs(quote).find((proof) => proof?.id === proofId)\n if (current) return current\n for (const snapshot of snapshots) {\n const kept = (Array.isArray(snapshot?.proofs) ? snapshot.proofs : []).find((proof) => proof?.id === proofId)\n if (kept) return kept\n }\n return null\n}\n\n/** The customer's latest answer to the current revision, if they gave one. */\nexport function latestQuoteResponse(\n quote: Pick<OrderQuote, 'responses' | 'revision'> | null | undefined,\n): QuoteCustomerResponse | null {\n const revision = Number(quote?.revision ?? 1)\n const answers = (quote?.responses ?? []).filter((response) => Number(response?.revision) === revision)\n return answers.length ? answers[answers.length - 1] : null\n}\n\n/** Whether the customer has answered the current revision. */\nexport function quoteRevisionAnswered(quote: Pick<OrderQuote, 'responses' | 'revision'> | null | undefined): boolean {\n return latestQuoteResponse(quote) !== null\n}\n\n/*------------------------------------------\n * The business's proofs\n *-----------------------------------------*/\n\nexport type QuoteProofRefusal = 'not-a-quote' | 'paid' | 'answered' | 'full' | 'unknown-proof' | 'needs-proof'\n\n/** Why the current revision's proofs cannot be changed now, if they cannot. */\nexport function quoteProofChangeRefusal(\n order: Pick<HostOrder, 'channel' | 'status' | 'quote'> | null | undefined,\n change: 'add' | 'remove',\n): QuoteProofRefusal | null {\n if (!order || !isQuote(order) || !order.quote) return 'not-a-quote'\n if (!isUnpaidQuote(order)) return 'paid'\n if (quoteRevisionAnswered(order.quote)) return 'answered'\n if (change === 'add' && currentQuoteProofs(order.quote).length >= QUOTE_MAX_PROOFS) return 'full'\n return null\n}\n\nexport function quoteProofRefusalMessage(reason: QuoteProofRefusal): string {\n switch (reason) {\n case 'not-a-quote':\n return 'Unknown quote'\n case 'paid':\n return 'This quote has been paid, so its proofs can no longer be changed.'\n case 'answered':\n return 'The customer has answered this revision. Start a new revision to send different proofs.'\n case 'full':\n return `A revision holds up to ${QUOTE_MAX_PROOFS} proofs. Remove one first.`\n case 'unknown-proof':\n return 'That proof is no longer on this quote.'\n case 'needs-proof':\n return 'This quote has no items yet, so it needs its proof. Add another proof or an item first.'\n }\n}\n\n/** A media library file chosen for a proof, as the console names it: the library and the file's id. */\nexport interface QuoteLibraryProof {\n mediaScope: string\n mediaId: string\n}\n\n/**\n * What is wrong with a file just chosen in the media picker, before it is sent:\n * no way to name it, or a kind of file a proof can't be. The server decides for\n * itself; this only says so sooner.\n */\nexport function quoteLibraryProofProblem(picked: { fileName?: string; contentType?: string; mediaId?: string; mediaScope?: string }): string | null {\n if (!picked.mediaId || !picked.mediaScope) return 'That file can’t be used as a proof. Choose another.'\n if (picked.contentType && !visitorUploadTypeOf(picked.contentType)) {\n return `${picked.fileName || 'That file'} can’t be used as a proof. Choose an image or a PDF.`\n }\n return null\n}\n\n/**\n * The media library files a new quote is saved with (AGL-4184), or what to fix.\n * Only the names of the files: the server reads each one for the member saving.\n */\nexport function parseQuoteLibraryProofs(raw: unknown): { ok: true; proofs: QuoteLibraryProof[] } | { ok: false; error: string } {\n if (raw === undefined || raw === null) return { ok: true, proofs: [] }\n if (!Array.isArray(raw)) return { ok: false, error: 'Choose the proofs from your media library again.' }\n const proofs: QuoteLibraryProof[] = []\n for (const entry of raw) {\n const source = (entry && typeof entry === 'object' ? entry : {}) as Record<string, unknown>\n const mediaScope = typeof source['mediaScope'] === 'string' ? source['mediaScope'] : ''\n const mediaId = typeof source['mediaId'] === 'string' ? source['mediaId'] : ''\n if (!mediaScope || !mediaId) return { ok: false, error: 'Choose the proofs from your media library again.' }\n if (!proofs.some((proof) => proof.mediaScope === mediaScope && proof.mediaId === mediaId)) {\n proofs.push({ mediaScope, mediaId })\n }\n }\n if (proofs.length > QUOTE_MAX_PROOFS) return { ok: false, error: quoteProofRefusalMessage('full') }\n return { ok: true, proofs }\n}\n\n/** The quote with a proof added to its current revision, edited by `by` at `atMs`. */\nexport function withQuoteProofAdded(\n order: HostOrder,\n proof: Omit<QuoteProof, 'revision' | 'addedAtMs' | 'addedBy'>,\n options: { atMs: number; by: string },\n): { ok: true; order: HostOrder; proof: QuoteProof } | { ok: false; reason: QuoteProofRefusal } {\n const refused = quoteProofChangeRefusal(order, 'add')\n if (refused) return { ok: false, reason: refused }\n const quote = order.quote as OrderQuote\n const added: QuoteProof = {\n id: proof.id,\n revision: Number(quote.revision ?? 1),\n name: proof.name,\n contentType: proof.contentType,\n size: proof.size,\n path: proof.path,\n addedAtMs: options.atMs,\n addedBy: options.by,\n }\n return {\n ok: true,\n proof: added,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-proof-added',\n `Proof ${added.name} added to revision ${added.revision} by ${options.by}`,\n options.atMs,\n ),\n quote: {\n ...quote,\n proofs: [...currentQuoteProofs(quote).filter((entry) => entry.id !== added.id), added],\n updatedAtMs: options.atMs,\n updatedBy: options.by,\n },\n },\n }\n}\n\n/** The quote with one of the current revision's proofs taken off. */\nexport function withQuoteProofRemoved(\n order: HostOrder,\n proofId: string,\n options: { atMs: number; by: string },\n): { ok: true; order: HostOrder; proof: QuoteProof } | { ok: false; reason: QuoteProofRefusal } {\n const refused = quoteProofChangeRefusal(order, 'remove')\n if (refused) return { ok: false, reason: refused }\n const quote = order.quote as OrderQuote\n const proofs = currentQuoteProofs(quote)\n const proof = proofs.find((entry) => entry.id === proofId)\n if (!proof) return { ok: false, reason: 'unknown-proof' }\n // A quote with no lines shows nothing but its proof (AGL-4184).\n if (quoteIsProofOnly(order) && proofs.length === 1) return { ok: false, reason: 'needs-proof' }\n return {\n ok: true,\n proof,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-proof-removed',\n `Proof ${proof.name} removed from revision ${proof.revision} by ${options.by}`,\n options.atMs,\n ),\n quote: {\n ...quote,\n proofs: proofs.filter((entry) => entry.id !== proofId),\n updatedAtMs: options.atMs,\n updatedBy: options.by,\n },\n },\n }\n}\n\n/*------------------------------------------\n * Revisions\n *-----------------------------------------*/\n\nexport type QuoteRevisionRefusal = 'not-a-quote' | 'paid'\n\n/**\n * Starts the quote's next revision. The current one is SNAPSHOTTED as it\n * stands (its lines, totals, notes, terms, proofs and the customer's\n * answers); the quote moves to revision N+1 with no proofs and no answer,\n * back at Draft, edited by `by` at `atMs`. A paid quote starts none.\n *\n * The caller writes `snapshot` to `hosts/{hostId}/orders/{id}/revisions/{revision}`\n * (`String(snapshot.revision)`, created, never overwritten) and `order` over\n * the quote, in one transaction. The pay link's version is not touched: the\n * send that hands the customer the new revision decides that.\n */\nexport function startQuoteRevision(\n order: HostOrder,\n options: { atMs: number; by: string },\n):\n | { ok: true; snapshot: QuoteRevisionSnapshot; order: HostOrder; revision: number }\n | { ok: false; reason: QuoteRevisionRefusal; error: string } {\n if (!isQuote(order) || !order.quote) return { ok: false, reason: 'not-a-quote', error: 'Unknown quote' }\n if (!isUnpaidQuote(order)) {\n return { ok: false, reason: 'paid', error: 'This quote has been paid, so it takes no new revision.' }\n }\n const quote = order.quote\n const current = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const responses = (quote.responses ?? []).filter((response) => Number(response?.revision) === current)\n const approval = quote.approval && Number(quote.approval.revision) === current ? quote.approval : null\n const snapshot: QuoteRevisionSnapshot = {\n revision: current,\n stage: quote.stage ?? 'draft',\n lineItems: order.lineItems ?? [],\n totals: order.totals ?? null,\n taxMode: order.taxMode ?? null,\n tax: quote.tax ?? null,\n discount: quote.discount ?? null,\n shipping: quote.shipping ?? null,\n notes: quote.notes ?? '',\n terms: quote.terms ?? '',\n customer: quote.customer ?? null,\n billTo: quote.billTo ?? null,\n shipTo: quote.shipTo ?? null,\n proofs: currentQuoteProofs(quote),\n responses,\n approval,\n updatedAtMs: Number(quote.updatedAtMs) || 0,\n closedAtMs: options.atMs,\n closedBy: options.by,\n }\n const next = current + 1\n return {\n ok: true,\n revision: current,\n snapshot,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-revision-started',\n `Revision ${next} started by ${options.by}; revision ${current} is kept with its proofs and answers`,\n options.atMs,\n ),\n quote: {\n ...quote,\n revision: next,\n stage: 'draft',\n proofs: [],\n responses: [],\n approval: null,\n updatedAtMs: options.atMs,\n updatedBy: options.by,\n },\n },\n }\n}\n\n/*------------------------------------------\n * The customer's answer\n *-----------------------------------------*/\n\nexport type QuoteRespondRefusal = 'not-a-quote' | 'paid' | 'no-proof' | 'too-many'\n\n/** Why the customer cannot answer the current revision now, if they cannot. */\nexport function quoteRespondRefusal(\n order: Pick<HostOrder, 'channel' | 'status' | 'quote'> | null | undefined,\n): QuoteRespondRefusal | null {\n if (!order || !isQuote(order) || !order.quote) return 'not-a-quote'\n if (!isUnpaidQuote(order)) return 'paid'\n if (currentQuoteProofs(order.quote).length === 0) return 'no-proof'\n const revision = Number(order.quote.revision ?? 1)\n const given = (order.quote.responses ?? []).filter((response) => Number(response?.revision) === revision)\n if (given.length >= QUOTE_MAX_RESPONSES) return 'too-many'\n return null\n}\n\nexport function quoteRespondRefusalMessage(reason: QuoteRespondRefusal, storeName: string): string {\n const business = storeName || 'the business'\n switch (reason) {\n case 'not-a-quote':\n return 'We could not find that quote. Check the link you were sent.'\n case 'paid':\n return 'This quote has been paid, so it takes no more answers.'\n case 'no-proof':\n return `There is no proof on this quote to answer yet. ${storeName || 'The business'} will send one.`\n case 'too-many':\n return `This proof has had a lot of answers already. Contact ${business} directly.`\n }\n}\n\n/** What the customer sends: approve under a name, or changes with a comment and any files. */\nexport type QuoteResponseInput =\n | { action: 'approve'; name: string }\n | { action: 'changes'; comment: string; fileIds: string[] }\n\n/** The customer's answer as the route received it, checked and trimmed, or what to fix. */\nexport function parseQuoteResponseInput(raw: unknown): { ok: true; input: QuoteResponseInput } | { ok: false; error: string } {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n if (source['action'] === 'approve') {\n const name = typeof source['name'] === 'string' ? source['name'].replace(/\\s+/g, ' ').trim() : ''\n if (name.length < 2) return { ok: false, error: 'Type your name to approve the proof.' }\n return { ok: true, input: { action: 'approve', name: name.slice(0, QUOTE_MAX_APPROVER_NAME) } }\n }\n if (source['action'] === 'changes') {\n const comment = typeof source['comment'] === 'string' ? source['comment'].trim() : ''\n if (!comment) return { ok: false, error: 'Tell us what to change.' }\n const raws = Array.isArray(source['fileIds']) ? (source['fileIds'] as unknown[]) : []\n const named = raws.map((value) => String(value ?? '')).filter((value) => /^[A-Za-z0-9_-]{1,128}$/.test(value))\n if (named.length !== raws.length) return { ok: false, error: 'One of the files could not be attached. Send it again.' }\n const fileIds = [...new Set(named)]\n if (fileIds.length > QUOTE_MAX_PROOFS) return { ok: false, error: `Send up to ${QUOTE_MAX_PROOFS} files at a time.` }\n return { ok: true, input: { action: 'changes', comment: comment.slice(0, QUOTE_MAX_COMMENT), fileIds } }\n }\n return { ok: false, error: 'Approve the proof or ask for changes.' }\n}\n\n/**\n * The quote with the customer's answer recorded on its current revision.\n * Approving names the revision approved and moves the quote to Approved;\n * asking for changes moves it to Changes requested and withdraws an approval\n * of the same revision. The latest answer is the one that counts. The\n * business's edit stamp (`updatedAtMs`) is not touched: the quote's content\n * did not change, and the page that sent the answer can still pay it.\n */\nexport function applyQuoteResponse(\n order: HostOrder,\n input: QuoteResponseInput & { files?: QuoteResponseFile[] },\n context: { atMs: number; ip: string | null; userAgent: string | null },\n): { ok: true; order: HostOrder; response: QuoteCustomerResponse } | { ok: false; reason: QuoteRespondRefusal } {\n const refused = quoteRespondRefusal(order)\n if (refused) return { ok: false, reason: refused }\n const quote = order.quote as OrderQuote\n const revision = Number(quote.revision ?? 1)\n const ip = context.ip ? context.ip.slice(0, 64) : null\n const userAgent = context.userAgent ? context.userAgent.slice(0, 400) : null\n const response: QuoteCustomerResponse =\n input.action === 'approve'\n ? { action: 'approve', revision, atMs: context.atMs, name: input.name, ip, userAgent }\n : {\n action: 'changes',\n revision,\n atMs: context.atMs,\n comment: input.comment,\n ...(input.files?.length ? { files: input.files } : {}),\n ip,\n userAgent,\n }\n const responses = [...(quote.responses ?? []).filter((entry) => Number(entry?.revision) === revision), response]\n const number = formatQuoteNumber(order)\n const next: OrderQuote =\n response.action === 'approve'\n ? {\n ...quote,\n responses,\n stage: 'approved',\n approvedRevision: revision,\n approval: { revision, name: response.name ?? '', atMs: context.atMs, ip, userAgent },\n }\n : {\n ...quote,\n responses,\n stage: 'changes_requested',\n approvedRevision: Number(quote.approvedRevision) === revision ? null : (quote.approvedRevision ?? null),\n approval: null,\n }\n return {\n ok: true,\n response,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n response.action === 'approve' ? 'quote-approved' : 'quote-changes-requested',\n response.action === 'approve'\n ? `${number} revision ${revision} approved by the customer as ${response.name}`\n : `The customer asked for changes to ${number} revision ${revision}` +\n (response.files?.length ? ` and sent ${response.files.length} file${response.files.length === 1 ? '' : 's'}` : ''),\n context.atMs,\n ),\n quote: next,\n },\n }\n}\n\n/** One line on what the customer last said: `Approved by Jordan Lee`, `Changes requested`. */\nexport function describeQuoteResponse(response: Pick<QuoteCustomerResponse, 'action' | 'name'>): string {\n return response.action === 'approve' ? `Approved by ${response.name || 'the customer'}` : 'Changes requested'\n}\n"],"names":["visitorUploadTypeOf","appendOrderEvent","formatQuoteNumber","isQuote","isUnpaidQuote","quoteIsProofOnly","QUOTE_MAX_PROOFS","QUOTE_MAX_RESPONSES","QUOTE_MAX_COMMENT","QUOTE_MAX_APPROVER_NAME","QUOTE_PROOF_PURPOSE","QUOTE_ARTWORK_PURPOSE","currentQuoteProofs","quote","revision","Number","proofs","filter","proof","quoteProofInHistory","snapshots","proofId","current","find","id","snapshot","kept","Array","isArray","latestQuoteResponse","answers","responses","response","length","quoteRevisionAnswered","quoteProofChangeRefusal","order","change","quoteProofRefusalMessage","reason","quoteLibraryProofProblem","picked","mediaId","mediaScope","contentType","fileName","parseQuoteLibraryProofs","raw","undefined","ok","error","entry","source","some","push","withQuoteProofAdded","options","refused","added","name","size","path","addedAtMs","atMs","addedBy","by","timeline","updatedAtMs","updatedBy","withQuoteProofRemoved","startQuoteRevision","Math","max","floor","approval","stage","lineItems","totals","taxMode","tax","discount","shipping","notes","terms","customer","billTo","shipTo","closedAtMs","closedBy","next","quoteRespondRefusal","given","quoteRespondRefusalMessage","storeName","business","parseQuoteResponseInput","replace","trim","input","action","slice","comment","raws","named","map","value","String","test","fileIds","Set","applyQuoteResponse","context","ip","userAgent","files","number","approvedRevision","describeQuoteResponse"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,gBAAgB,QAAiF,uBAAmB;AAC7H,SACEC,iBAAiB,EACjBC,OAAO,EACPC,aAAa,EACbC,gBAAgB,QAWX,uBAAmB;AAG1B;;;;;;;;;;;;;;;;2CAgB2C,GAE3C,wCAAwC,GACxC,OAAO,MAAMC,mBAAmB,GAAE;AAElC,mFAAmF,GACnF,OAAO,MAAMC,sBAAsB,GAAE;AAErC,8CAA8C,GAC9C,OAAO,MAAMC,oBAAoB,KAAK;AAEtC,iDAAiD,GACjD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,6FAA6F,GAC7F,OAAO,MAAMC,sBAAsB,cAAa;AAChD,OAAO,MAAMC,wBAAwB,gBAAe;AA4BpD,mCAAmC,GACnC,OAAO,SAASC,mBAAmBC,KAAiE;;IAClG,MAAMC,WAAWC,eAAOF,yBAAAA,MAAOC,QAAQ,mBAAI;IAC3C,OAAO,UAACD,yBAAAA,MAAOG,MAAM,oBAAI,EAAE,EAAEC,MAAM,CAAC,CAACC,QAAUH,OAAOG,yBAAAA,MAAOJ,QAAQ,MAAMA;AAC7E;AAEA;;;;;CAKC,GACD,OAAO,SAASK,oBACdN,KAAiE,EACjEO,SAA2F,EAC3FC,OAAe;IAEf,IAAI,CAACA,SAAS,OAAO;IACrB,MAAMC,UAAUV,mBAAmBC,OAAOU,IAAI,CAAC,CAACL,QAAUA,CAAAA,yBAAAA,MAAOM,EAAE,MAAKH;IACxE,IAAIC,SAAS,OAAOA;IACpB,KAAK,MAAMG,YAAYL,UAAW;QAChC,MAAMM,OAAO,AAACC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b3B,iBAAiB;YAAI+B,MAAMgD,QAAQhD,IAAI;YAAEiD;YAAIC;QAAU;SAErF,aACKpG;QACHkB;QACA4C,OAAO;QACPyC,kBAAkBrG,OAAOF,MAAMuG,gBAAgB,MAAMtG,WAAW,QAAQD,0BAAAA,MAAMuG,gBAAgB,YAAtBvG,0BAA0B;QAClG6D,UAAU;;IAElB,OAAO;QACLzB,IAAI;QACJjB;QACAI,OAAO,aACFA;YACH8B,UAAUjE,iBACRmC,OACAJ,SAASmE,MAAM,KAAK,YAAY,mBAAmB,2BACnDnE,SAASmE,MAAM,KAAK,YAChB,GAAGgB,OAAO,UAAU,EAAErG,SAAS,6BAA6B,EAAEkB,SAAS2B,IAAI,EAAE,GAC7E,CAAC,kCAAkC,EAAEwD,OAAO,UAAU,EAAErG,UAAU,GAC/DkB,CAAAA,EAAAA,kBAAAA,SAASkF,KAAK,qBAAdlF,gBAAgBC,MAAM,IAAG,CAAC,UAAU,EAAED,SAASkF,KAAK,CAACjF,MAAM,CAAC,KAAK,EAAED,SAASkF,KAAK,CAACjF,MAAM,KAAK,IAAI,KAAK,KAAK,GAAG,EAAC,GACtH8E,QAAQhD,IAAI;YAEdlD,OAAO4E;;IAEX;AACF;AAEA,4FAA4F,GAC5F,OAAO,SAAS4B,sBAAsBrF,QAAwD;IAC5F,OAAOA,SAASmE,MAAM,KAAK,YAAY,CAAC,YAAY,EAAEnE,SAAS2B,IAAI,IAAI,gBAAgB,GAAG;AAC5F"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-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 { visitorUploadTypeOf } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport { appendOrderEvent, type HostOrder, type OrderAddress, type OrderLineItem, type OrderTotals } from './commerce-orders'\nimport {\n cleanQuoteApprovalStatements,\n formatQuoteNumber,\n isQuote,\n isUnpaidQuote,\n quoteIsProofOnly,\n type OrderQuote,\n type QuoteApproval,\n type QuoteCustomer,\n type QuoteCustomerResponse,\n type QuoteDiscount,\n type QuoteProof,\n type QuoteResponseFile,\n type QuoteShipping,\n type QuoteStage,\n type QuoteTaxBasis,\n} from './commerce-quotes'\nimport type { StorefrontTaxMode } from './commerce-tax-decision'\n\n/*==========================================\n * PROOFS, REVISIONS AND THE CUSTOMER'S ANSWER (AGL-4096).\n *\n * A quote's REVISION is the version the customer is looking at. The business\n * attaches proofs to the current revision; the customer approves them under\n * a typed name or rejects them with changes; the business then starts the next\n * revision, which keeps the one before exactly as it stood in\n * `hosts/{hostId}/orders/{id}/revisions/{n}` and starts the new one with no\n * proofs and no answer. Every revision is kept.\n *\n * Whether paying waits on an approval is the business's control\n * (`requireProofApproval`, AGL-4093) and `quotePaymentBlockedByApproval`\n * answers it; nothing here makes paying wait when it is off.\n *\n * Pure: the console route, the customer's route and (slice 5) the send that\n * starts a revision all call these, and write what they answer.\n *=========================================*/\n\n/** The most proofs one revision holds. */\nexport const QUOTE_MAX_PROOFS = 10\n\n/** The most answers the customer gives one revision; plenty for a change of mind. */\nexport const QUOTE_MAX_RESPONSES = 20\n\n/** The longest comment a customer may leave. */\nexport const QUOTE_MAX_COMMENT = 5_000\n\n/** The longest name an approval is signed with. */\nexport const QUOTE_MAX_APPROVER_NAME = 120\n\n/** What the visitor uploads are called for a quote: its proofs, and the customer's artwork. */\nexport const QUOTE_PROOF_PURPOSE = 'quote-proof'\nexport const QUOTE_ARTWORK_PURPOSE = 'quote-artwork'\n\n/** A revision as it stood when the next one started. */\nexport interface QuoteRevisionSnapshot {\n revision: number\n /** Where it stood with the business when it closed. */\n stage: QuoteStage\n lineItems: OrderLineItem[]\n totals: OrderTotals | null\n taxMode: StorefrontTaxMode | null\n tax: QuoteTaxBasis | null\n discount: QuoteDiscount | null\n shipping: QuoteShipping | null\n notes: string\n terms: string\n customer: QuoteCustomer | null\n billTo: OrderAddress | null\n shipTo: OrderAddress | null\n proofs: QuoteProof[]\n responses: QuoteCustomerResponse[]\n approval: QuoteApproval | null\n /** When the revision was last written by the business. */\n updatedAtMs: number\n /** When the next revision started, and who started it. */\n closedAtMs: number\n closedBy: string\n}\n\n/** The current revision's proofs. */\nexport function currentQuoteProofs(quote: Pick<OrderQuote, 'proofs' | 'revision'> | null | undefined): QuoteProof[] {\n const revision = Number(quote?.revision ?? 1)\n return (quote?.proofs ?? []).filter((proof) => Number(proof?.revision) === revision)\n}\n\n/**\n * One of the proofs the quote has shown its customer, by id (AGL-4097): the\n * current revision's, else an earlier revision's as its snapshot keeps it\n * (`orders/{id}/revisions/{n}`). A proof the business took off a revision\n * before the next one started is in neither, so it is not found.\n */\nexport function quoteProofInHistory(\n quote: Pick<OrderQuote, 'proofs' | 'revision'> | null | undefined,\n snapshots: ReadonlyArray<Partial<Pick<QuoteRevisionSnapshot, 'proofs'>> | null | undefined>,\n proofId: string,\n): QuoteProof | null {\n if (!proofId) return null\n const current = currentQuoteProofs(quote).find((proof) => proof?.id === proofId)\n if (current) return current\n for (const snapshot of snapshots) {\n const kept = (Array.isArray(snapshot?.proofs) ? snapshot.proofs : []).find((proof) => proof?.id === proofId)\n if (kept) return kept\n }\n return null\n}\n\n/** The customer's latest answer to the current revision, if they gave one. */\nexport function latestQuoteResponse(\n quote: Pick<OrderQuote, 'responses' | 'revision'> | null | undefined,\n): QuoteCustomerResponse | null {\n const revision = Number(quote?.revision ?? 1)\n const answers = (quote?.responses ?? []).filter((response) => Number(response?.revision) === revision)\n return answers.length ? answers[answers.length - 1] : null\n}\n\n/** Whether the customer has answered the current revision. */\nexport function quoteRevisionAnswered(quote: Pick<OrderQuote, 'responses' | 'revision'> | null | undefined): boolean {\n return latestQuoteResponse(quote) !== null\n}\n\n/*------------------------------------------\n * The business's proofs\n *-----------------------------------------*/\n\nexport type QuoteProofRefusal = 'not-a-quote' | 'paid' | 'answered' | 'full' | 'unknown-proof' | 'needs-proof'\n\n/** Why the current revision's proofs cannot be changed now, if they cannot. */\nexport function quoteProofChangeRefusal(\n order: Pick<HostOrder, 'channel' | 'status' | 'quote'> | null | undefined,\n change: 'add' | 'remove',\n): QuoteProofRefusal | null {\n if (!order || !isQuote(order) || !order.quote) return 'not-a-quote'\n if (!isUnpaidQuote(order)) return 'paid'\n if (quoteRevisionAnswered(order.quote)) return 'answered'\n if (change === 'add' && currentQuoteProofs(order.quote).length >= QUOTE_MAX_PROOFS) return 'full'\n return null\n}\n\nexport function quoteProofRefusalMessage(reason: QuoteProofRefusal): string {\n switch (reason) {\n case 'not-a-quote':\n return 'Unknown quote'\n case 'paid':\n return 'This quote has been paid, so its proofs can no longer be changed.'\n case 'answered':\n return 'The customer has answered this revision. Start a new revision to send different proofs.'\n case 'full':\n return `A revision holds up to ${QUOTE_MAX_PROOFS} proofs. Remove one first.`\n case 'unknown-proof':\n return 'That proof is no longer on this quote.'\n case 'needs-proof':\n return 'This quote has no items yet, so it needs its proof. Add another proof or an item first.'\n }\n}\n\n/** A media library file chosen for a proof, as the console names it: the library and the file's id. */\nexport interface QuoteLibraryProof {\n mediaScope: string\n mediaId: string\n}\n\n/**\n * What is wrong with a file just chosen in the media picker, before it is sent:\n * no way to name it, or a kind of file a proof can't be. The server decides for\n * itself; this only says so sooner.\n */\nexport function quoteLibraryProofProblem(picked: { fileName?: string; contentType?: string; mediaId?: string; mediaScope?: string }): string | null {\n if (!picked.mediaId || !picked.mediaScope) return 'That file can’t be used as a proof. Choose another.'\n if (picked.contentType && !visitorUploadTypeOf(picked.contentType)) {\n return `${picked.fileName || 'That file'} can’t be used as a proof. Choose an image or a PDF.`\n }\n return null\n}\n\n/**\n * The media library files a new quote is saved with (AGL-4184), or what to fix.\n * Only the names of the files: the server reads each one for the member saving.\n */\nexport function parseQuoteLibraryProofs(raw: unknown): { ok: true; proofs: QuoteLibraryProof[] } | { ok: false; error: string } {\n if (raw === undefined || raw === null) return { ok: true, proofs: [] }\n if (!Array.isArray(raw)) return { ok: false, error: 'Choose the proofs from your media library again.' }\n const proofs: QuoteLibraryProof[] = []\n for (const entry of raw) {\n const source = (entry && typeof entry === 'object' ? entry : {}) as Record<string, unknown>\n const mediaScope = typeof source['mediaScope'] === 'string' ? source['mediaScope'] : ''\n const mediaId = typeof source['mediaId'] === 'string' ? source['mediaId'] : ''\n if (!mediaScope || !mediaId) return { ok: false, error: 'Choose the proofs from your media library again.' }\n if (!proofs.some((proof) => proof.mediaScope === mediaScope && proof.mediaId === mediaId)) {\n proofs.push({ mediaScope, mediaId })\n }\n }\n if (proofs.length > QUOTE_MAX_PROOFS) return { ok: false, error: quoteProofRefusalMessage('full') }\n return { ok: true, proofs }\n}\n\n/** The quote with a proof added to its current revision, edited by `by` at `atMs`. */\nexport function withQuoteProofAdded(\n order: HostOrder,\n proof: Omit<QuoteProof, 'revision' | 'addedAtMs' | 'addedBy'>,\n options: { atMs: number; by: string },\n): { ok: true; order: HostOrder; proof: QuoteProof } | { ok: false; reason: QuoteProofRefusal } {\n const refused = quoteProofChangeRefusal(order, 'add')\n if (refused) return { ok: false, reason: refused }\n const quote = order.quote as OrderQuote\n const added: QuoteProof = {\n id: proof.id,\n revision: Number(quote.revision ?? 1),\n name: proof.name,\n contentType: proof.contentType,\n size: proof.size,\n path: proof.path,\n addedAtMs: options.atMs,\n addedBy: options.by,\n }\n return {\n ok: true,\n proof: added,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-proof-added',\n `Proof ${added.name} added to revision ${added.revision} by ${options.by}`,\n options.atMs,\n ),\n quote: {\n ...quote,\n proofs: [...currentQuoteProofs(quote).filter((entry) => entry.id !== added.id), added],\n updatedAtMs: options.atMs,\n updatedBy: options.by,\n },\n },\n }\n}\n\n/** The quote with one of the current revision's proofs taken off. */\nexport function withQuoteProofRemoved(\n order: HostOrder,\n proofId: string,\n options: { atMs: number; by: string },\n): { ok: true; order: HostOrder; proof: QuoteProof } | { ok: false; reason: QuoteProofRefusal } {\n const refused = quoteProofChangeRefusal(order, 'remove')\n if (refused) return { ok: false, reason: refused }\n const quote = order.quote as OrderQuote\n const proofs = currentQuoteProofs(quote)\n const proof = proofs.find((entry) => entry.id === proofId)\n if (!proof) return { ok: false, reason: 'unknown-proof' }\n // A quote with no lines shows nothing but its proof (AGL-4184).\n if (quoteIsProofOnly(order) && proofs.length === 1) return { ok: false, reason: 'needs-proof' }\n return {\n ok: true,\n proof,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-proof-removed',\n `Proof ${proof.name} removed from revision ${proof.revision} by ${options.by}`,\n options.atMs,\n ),\n quote: {\n ...quote,\n proofs: proofs.filter((entry) => entry.id !== proofId),\n updatedAtMs: options.atMs,\n updatedBy: options.by,\n },\n },\n }\n}\n\n/*------------------------------------------\n * Revisions\n *-----------------------------------------*/\n\nexport type QuoteRevisionRefusal = 'not-a-quote' | 'paid'\n\n/**\n * Starts the quote's next revision. The current one is SNAPSHOTTED as it\n * stands (its lines, totals, notes, terms, proofs and the customer's\n * answers); the quote moves to revision N+1 with no proofs and no answer,\n * back at Draft, edited by `by` at `atMs`. A paid quote starts none.\n *\n * The caller writes `snapshot` to `hosts/{hostId}/orders/{id}/revisions/{revision}`\n * (`String(snapshot.revision)`, created, never overwritten) and `order` over\n * the quote, in one transaction. The pay link's version is not touched: the\n * send that hands the customer the new revision decides that.\n */\nexport function startQuoteRevision(\n order: HostOrder,\n options: { atMs: number; by: string },\n):\n | { ok: true; snapshot: QuoteRevisionSnapshot; order: HostOrder; revision: number }\n | { ok: false; reason: QuoteRevisionRefusal; error: string } {\n if (!isQuote(order) || !order.quote) return { ok: false, reason: 'not-a-quote', error: 'Unknown quote' }\n if (!isUnpaidQuote(order)) {\n return { ok: false, reason: 'paid', error: 'This quote has been paid, so it takes no new revision.' }\n }\n const quote = order.quote\n const current = Math.max(1, Math.floor(Number(quote.revision ?? 1)) || 1)\n const responses = (quote.responses ?? []).filter((response) => Number(response?.revision) === current)\n const approval = quote.approval && Number(quote.approval.revision) === current ? quote.approval : null\n const snapshot: QuoteRevisionSnapshot = {\n revision: current,\n stage: quote.stage ?? 'draft',\n lineItems: order.lineItems ?? [],\n totals: order.totals ?? null,\n taxMode: order.taxMode ?? null,\n tax: quote.tax ?? null,\n discount: quote.discount ?? null,\n shipping: quote.shipping ?? null,\n notes: quote.notes ?? '',\n terms: quote.terms ?? '',\n customer: quote.customer ?? null,\n billTo: quote.billTo ?? null,\n shipTo: quote.shipTo ?? null,\n proofs: currentQuoteProofs(quote),\n responses,\n approval,\n updatedAtMs: Number(quote.updatedAtMs) || 0,\n closedAtMs: options.atMs,\n closedBy: options.by,\n }\n const next = current + 1\n return {\n ok: true,\n revision: current,\n snapshot,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n 'quote-revision-started',\n `Revision ${next} started by ${options.by}; revision ${current} is kept with its proofs and answers`,\n options.atMs,\n ),\n quote: {\n ...quote,\n revision: next,\n stage: 'draft',\n proofs: [],\n responses: [],\n approval: null,\n updatedAtMs: options.atMs,\n updatedBy: options.by,\n },\n },\n }\n}\n\n/*------------------------------------------\n * The customer's answer\n *-----------------------------------------*/\n\nexport type QuoteRespondRefusal = 'not-a-quote' | 'paid' | 'no-proof' | 'too-many'\n\n/** Why the customer cannot answer the current revision now, if they cannot. */\nexport function quoteRespondRefusal(\n order: Pick<HostOrder, 'channel' | 'status' | 'quote'> | null | undefined,\n): QuoteRespondRefusal | null {\n if (!order || !isQuote(order) || !order.quote) return 'not-a-quote'\n if (!isUnpaidQuote(order)) return 'paid'\n if (currentQuoteProofs(order.quote).length === 0) return 'no-proof'\n const revision = Number(order.quote.revision ?? 1)\n const given = (order.quote.responses ?? []).filter((response) => Number(response?.revision) === revision)\n if (given.length >= QUOTE_MAX_RESPONSES) return 'too-many'\n return null\n}\n\nexport function quoteRespondRefusalMessage(reason: QuoteRespondRefusal, storeName: string): string {\n const business = storeName || 'the business'\n switch (reason) {\n case 'not-a-quote':\n return 'We could not find that quote. Check the link you were sent.'\n case 'paid':\n return 'This quote has been paid, so it takes no more answers.'\n case 'no-proof':\n return `There is no proof on this quote to answer yet. ${storeName || 'The business'} will send one.`\n case 'too-many':\n return `This proof has had a lot of answers already. Contact ${business} directly.`\n }\n}\n\n/**\n * What the customer sends: approve under a name with every statement ticked,\n * or reject with changes (AGL-4206): what to change, under a name, with any\n * files.\n */\nexport type QuoteResponseInput =\n | { action: 'approve'; name: string; confirmed: string[] }\n | { action: 'changes'; comment: string; name: string; fileIds: string[] }\n\n/** Why an answer was refused before it reached the quote: what to fix, and (for stale statements) that the page is out of date. */\nexport type QuoteResponseInputProblem = { ok: false; error: string; reason?: 'statements-changed' }\n\n/**\n * The customer's answer as the route received it, checked and trimmed, or what\n * to fix. An approval must tick every one of `statements` (AGL-4206), the\n * statements the store asks for now, word for word: a statement the page\n * showed that the store has since reworded is `statements-changed`, and the\n * page shows them again.\n */\nexport function parseQuoteResponseInput(\n raw: unknown,\n statements: readonly string[] = [],\n): { ok: true; input: QuoteResponseInput } | QuoteResponseInputProblem {\n const source = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>\n const name = typeof source['name'] === 'string' ? source['name'].replace(/\\s+/g, ' ').trim() : ''\n if (source['action'] === 'approve') {\n const ticked = cleanQuoteApprovalStatements(source['confirmed'])\n if (ticked.some((statement) => !statements.includes(statement))) {\n return {\n ok: false,\n reason: 'statements-changed',\n error: 'What you confirm before approving has changed. Read it again and tick each one.',\n }\n }\n if (statements.some((statement) => !ticked.includes(statement))) {\n return { ok: false, error: 'Tick each box to confirm you checked the proof.' }\n }\n if (name.length < 2) return { ok: false, error: 'Type your name to approve the proof.' }\n return {\n ok: true,\n input: { action: 'approve', name: name.slice(0, QUOTE_MAX_APPROVER_NAME), confirmed: [...statements] },\n }\n }\n if (source['action'] === 'changes') {\n const comment = typeof source['comment'] === 'string' ? source['comment'].trim() : ''\n if (!comment) return { ok: false, error: 'Tell us what to change.' }\n if (name.length < 2) return { ok: false, error: 'Type your name to reject the proof.' }\n const raws = Array.isArray(source['fileIds']) ? (source['fileIds'] as unknown[]) : []\n const named = raws.map((value) => String(value ?? '')).filter((value) => /^[A-Za-z0-9_-]{1,128}$/.test(value))\n if (named.length !== raws.length) return { ok: false, error: 'One of the files could not be attached. Send it again.' }\n const fileIds = [...new Set(named)]\n if (fileIds.length > QUOTE_MAX_PROOFS) return { ok: false, error: `Send up to ${QUOTE_MAX_PROOFS} files at a time.` }\n return {\n ok: true,\n input: { action: 'changes', comment: comment.slice(0, QUOTE_MAX_COMMENT), name: name.slice(0, QUOTE_MAX_APPROVER_NAME), fileIds },\n }\n }\n return { ok: false, error: 'Approve the proof or reject it with changes.' }\n}\n\n/**\n * The quote with the customer's answer recorded on its current revision.\n * Approving names the revision approved and moves the quote to Approved;\n * rejecting with changes moves it to Rejected with changes and withdraws an approval\n * of the same revision. The latest answer is the one that counts. The\n * business's edit stamp (`updatedAtMs`) is not touched: the quote's content\n * did not change, and the page that sent the answer can still pay it.\n */\nexport function applyQuoteResponse(\n order: HostOrder,\n input: QuoteResponseInput & { files?: QuoteResponseFile[] },\n context: { atMs: number; ip: string | null; userAgent: string | null },\n): { ok: true; order: HostOrder; response: QuoteCustomerResponse } | { ok: false; reason: QuoteRespondRefusal } {\n const refused = quoteRespondRefusal(order)\n if (refused) return { ok: false, reason: refused }\n const quote = order.quote as OrderQuote\n const revision = Number(quote.revision ?? 1)\n const ip = context.ip ? context.ip.slice(0, 64) : null\n const userAgent = context.userAgent ? context.userAgent.slice(0, 400) : null\n const response: QuoteCustomerResponse =\n input.action === 'approve'\n ? {\n action: 'approve',\n revision,\n atMs: context.atMs,\n name: input.name,\n ...(input.confirmed?.length ? { confirmed: [...input.confirmed] } : {}),\n ip,\n userAgent,\n }\n : {\n action: 'changes',\n revision,\n atMs: context.atMs,\n comment: input.comment,\n ...(input.name ? { name: input.name } : {}),\n ...(input.files?.length ? { files: input.files } : {}),\n ip,\n userAgent,\n }\n const responses = [...(quote.responses ?? []).filter((entry) => Number(entry?.revision) === revision), response]\n const number = formatQuoteNumber(order)\n const next: OrderQuote =\n response.action === 'approve'\n ? {\n ...quote,\n responses,\n stage: 'approved',\n approvedRevision: revision,\n approval: {\n revision,\n name: response.name ?? '',\n atMs: context.atMs,\n ...(response.confirmed?.length ? { confirmed: [...response.confirmed] } : {}),\n ip,\n userAgent,\n },\n }\n : {\n ...quote,\n responses,\n stage: 'changes_requested',\n approvedRevision: Number(quote.approvedRevision) === revision ? null : (quote.approvedRevision ?? null),\n approval: null,\n }\n return {\n ok: true,\n response,\n order: {\n ...order,\n timeline: appendOrderEvent(\n order,\n response.action === 'approve' ? 'quote-approved' : 'quote-changes-requested',\n response.action === 'approve'\n ? `${number} revision ${revision} approved by the customer as ${response.name}`\n : `${number} revision ${revision} rejected with changes by the customer` +\n (response.name ? ` as ${response.name}` : '') +\n (response.files?.length ? ` and sent ${response.files.length} file${response.files.length === 1 ? '' : 's'}` : ''),\n context.atMs,\n ),\n quote: next,\n },\n }\n}\n\n/** One line on what the customer last said: `Approved by Jordan Lee`, `Rejected with changes by Jordan Lee`. */\nexport function describeQuoteResponse(response: Pick<QuoteCustomerResponse, 'action' | 'name'>): string {\n return response.action === 'approve'\n ? `Approved by ${response.name || 'the customer'}`\n : `Rejected with changes${response.name ? ` by ${response.name}` : ''}`\n}\n\n/*------------------------------------------\n * Who may open the proof (AGL-4206)\n *-----------------------------------------*/\n\n/**\n * Whether the person holding the link may see the proof and answer it:\n * `open` (the link is enough, or they are signed in to the customer's\n * account), `sign-in` (the customer has an account on the site and this\n * browser is not signed in to it), or `other-account` (signed in, but to\n * someone else's account).\n *\n * Only a quote that asks for it (`requireProofSignIn`) and whose customer has\n * an account on the site (`accountId`) needs a sign-in. A guest, with no\n * account to sign in to, keeps the private link, and Replace link still\n * shuts that off. Nothing here opens, closes or expires.\n */\nexport type QuoteProofAccess = 'open' | 'sign-in' | 'other-account'\n\nexport function quoteProofAccess(input: {\n quote: Pick<OrderQuote, 'requireProofSignIn'> | null | undefined\n /** The customer's own account on the site, when they have one. */\n accountId: string | null\n /** The account this browser is signed in to on the site, if any. */\n signedInAccountId: string | null\n}): QuoteProofAccess {\n if (input.quote?.requireProofSignIn !== true || !input.accountId) return 'open'\n if (input.signedInAccountId === input.accountId) return 'open'\n return input.signedInAccountId ? 'other-account' : 'sign-in'\n}\n\n/** The address a quote's customer signs in with, lower-cased, or '' for a customer with none. */\nexport function quoteCustomerAccountEmail(quote: Pick<OrderQuote, 'customer'> | null | undefined): string {\n const email = String(quote?.customer?.emailLower || quote?.customer?.email || '').trim().toLowerCase()\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? email : ''\n}\n\n/** What the page and the routes say when the proof waits on a sign-in. */\nexport function quoteProofAccessMessage(access: Exclude<QuoteProofAccess, 'open'>, storeName: string): string {\n const business = storeName || 'the business'\n return access === 'other-account'\n ? `You’re signed in to a different account. Sign in with the account ${business} sent this quote to, to see the proof and approve it.`\n : `Sign in to your account with ${business} to see the proof and approve it.`\n}\n"],"names":["visitorUploadTypeOf","appendOrderEvent","cleanQuoteApprovalStatements","formatQuoteNumber","isQuote","isUnpaidQuote","quoteIsProofOnly","QUOTE_MAX_PROOFS","QUOTE_MAX_RESPONSES","QUOTE_MAX_COMMENT","QUOTE_MAX_APPROVER_NAME","QUOTE_PROOF_PURPOSE","QUOTE_ARTWORK_PURPOSE","currentQuoteProofs","quote","revision","Number","proofs","filter","proof","quoteProofInHistory","snapshots","proofId","current","find","id","snapshot","kept","Array","isArray","latestQuoteResponse","answers","responses","response","length","quoteRevisionAnswered","quoteProofChangeRefusal","order","change","quoteProofRefusalMessage","reason","quoteLibraryProofProblem","picked","mediaId","mediaScope","contentType","fileName","parseQuoteLibraryProofs","raw","undefined","ok","error","entry","source","some","push","withQuoteProofAdded","options","refused","added","name","size","path","addedAtMs","atMs","addedBy","by","timeline","updatedAtMs","updatedBy","withQuoteProofRemoved","startQuoteRevision","Math","max","floor","approval","stage","lineItems","totals","taxMode","tax","discount","shipping","notes","terms","customer","billTo","shipTo","closedAtMs","closedBy","next","quoteRespondRefusal","given","quoteRespondRefusalMessage","storeName","business","parseQuoteResponseInput","statements","replace","trim","ticked","statement","includes","input","action","slice","confirmed","comment","raws","named","map","value","String","test","fileIds","Set","applyQuoteResponse","context","ip","userAgent","files","number","approvedRevision","describeQuoteResponse","quoteProofAccess","requireProofSignIn","accountId","signedInAccountId","quoteCustomerAccountEmail","email","emailLower","toLowerCase","quoteProofAccessMessage","access"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,gBAAgB,QAAiF,uBAAmB;AAC7H,SACEC,4BAA4B,EAC5BC,iBAAiB,EACjBC,OAAO,EACPC,aAAa,EACbC,gBAAgB,QAWX,uBAAmB;AAG1B;;;;;;;;;;;;;;;;2CAgB2C,GAE3C,wCAAwC,GACxC,OAAO,MAAMC,mBAAmB,GAAE;AAElC,mFAAmF,GACnF,OAAO,MAAMC,sBAAsB,GAAE;AAErC,8CAA8C,GAC9C,OAAO,MAAMC,oBAAoB,KAAK;AAEtC,iDAAiD,GACjD,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,6FAA6F,GAC7F,OAAO,MAAMC,sBAAsB,cAAa;AAChD,OAAO,MAAMC,wBAAwB,gBAAe;AA4BpD,mCAAmC,GACnC,OAAO,SAASC,mBAAmBC,KAAiE;;IAClG,MAAMC,WAAWC,eAAOF,yBAAAA,MAAOC,QAAQ,mBAAI;IAC3C,OAAO,UAACD,yBAAAA,MAAOG,MAAM,oBAAI,EAAE,EAAEC,MAAM,CAAC,CAACC,QAAUH,OAAOG,yBAAAA,MAAOJ,QAAQ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AAS,EAAE,OAAO;IACxD,OAAOvB,MAAMwB,iBAAiB,GAAG,kBAAkB;AACrD;AAEA,+FAA+F,GAC/F,OAAO,SAASC,0BAA0BlH,KAAsD;QACzEA,iBAA+BA;IAApD,MAAMmH,QAAQjB,OAAOlG,CAAAA,0BAAAA,kBAAAA,MAAOuE,QAAQ,qBAAfvE,gBAAiBoH,UAAU,MAAIpH,0BAAAA,mBAAAA,MAAOuE,QAAQ,qBAAfvE,iBAAiBmH,KAAK,KAAI,IAAI9B,IAAI,GAAGgC,WAAW;IACpG,OAAO,6BAA6BlB,IAAI,CAACgB,SAASA,QAAQ;AAC5D;AAEA,wEAAwE,GACxE,OAAO,SAASG,wBAAwBC,MAAyC,EAAEvC,SAAiB;IAClG,MAAMC,WAAWD,aAAa;IAC9B,OAAOuC,WAAW,kBACd,CAAC,kEAAkE,EAAEtC,SAAS,qDAAqD,CAAC,GACpI,CAAC,6BAA6B,EAAEA,SAAS,iCAAiC,CAAC;AACjF"}
@@ -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 { QuoteCatalogLineRequest, QuoteCustomer, QuoteEmailThread, QuoteResponseFile } from './commerce-quotes';
17
+ import { type QuoteCatalogLineRequest, type QuoteCustomer, type QuoteEmailThread, type QuoteResponseFile } from './commerce-quotes';
18
18
  /** The resource the forms plugin reads a submission's facts under, on the core's seam. */
19
19
  export declare const QUOTE_REQUEST_FACTS_RESOURCE = "forms.submission";
20
20
  /** The request a quote was started from. */
@@ -27,9 +27,9 @@ export interface QuoteRequestRef {
27
27
  /**
28
28
  * What the Product and options field posts beside its readable line, under
29
29
  * `{name}__data`: the product, the variant the options make, and the options
30
- * as picked. Add-ons are not taken from the storefront yet; when they are,
31
- * they ride here as `modifiers` and the quote line prices them as the editor
32
- * does.
30
+ * as picked. On a product page's builder (AGL-4205) it also carries the
31
+ * add-ons picked (`modifiers`) and how many (`quantity`); the quote line
32
+ * prices them as the editor does.
33
33
  */
34
34
  export interface ProductFieldValue {
35
35
  productId: string;
@@ -39,7 +39,11 @@ export interface ProductFieldValue {
39
39
  groupId: string;
40
40
  optionId: string;
41
41
  }>;
42
+ /** How many the shopper asked about, 1 to {@link PRODUCT_FIELD_MAX_QUANTITY}. Absent: one. */
43
+ quantity?: number;
42
44
  }
45
+ /** The most a request can ask about in one line: a quote line's own limit, 9,999. */
46
+ export declare const PRODUCT_FIELD_MAX_QUANTITY = 9999;
43
47
  /** The compact value the field posts. */
44
48
  export declare function encodeProductFieldValue(value: ProductFieldValue): string;
45
49
  /**
@@ -50,6 +54,12 @@ export declare function encodeProductFieldValue(value: ProductFieldValue): strin
50
54
  export declare function parseProductFieldValue(raw: unknown): ProductFieldValue | null;
51
55
  /** The readable line the field posts under its name: the product, then its options. */
52
56
  export declare function productFieldLabel(productName: string, options: Record<string, string> | undefined): string;
57
+ /**
58
+ * The readable line a request carries for a product page's picks (AGL-4205):
59
+ * the product and its options, then the add-ons, then how many —
60
+ * `Custom canopy — 10 × 10 ft + Full wall, Printed roof × 2`.
61
+ */
62
+ export declare function builderPicksLabel(productName: string, options: Record<string, string> | undefined, addOnNames: readonly string[], quantity?: number): string;
53
63
  /** What this plugin reads of a request's facts (the forms plugin's reader documents them). */
54
64
  export interface QuoteRequestFacts {
55
65
  hostId: string;
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -13,7 +14,7 @@
13
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
15
  * See the License for the specific language governing permissions and
15
16
  * limitations under the License.
16
- */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
+ */ import { QUOTE_MAX_QUANTITY } from "./commerce-quotes.js";
17
18
  /*==========================================
18
19
  * A QUOTE STARTED FROM A REQUEST (AGL-4098).
19
20
  *
@@ -39,6 +40,12 @@
39
40
  const ID = /^(?!__.*__$)[^/]{1,200}$/;
40
41
  const MAX_OPTIONS = 20;
41
42
  const MAX_MODIFIERS = 50;
43
+ /** The most a request can ask about in one line: a quote line's own limit, 9,999. */ export const PRODUCT_FIELD_MAX_QUANTITY = QUOTE_MAX_QUANTITY;
44
+ /** A posted quantity as a whole number from 1 to the cap; anything else is none. */ function fieldQuantity(raw) {
45
+ const number = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN;
46
+ if (!Number.isInteger(number) || number < 1) return null;
47
+ return Math.min(number, PRODUCT_FIELD_MAX_QUANTITY);
48
+ }
42
49
  const text = (value, max = 200)=>typeof value === 'string' ? value.trim().slice(0, max) : '';
43
50
  /** The compact value the field posts. */ export function encodeProductFieldValue(value) {
44
51
  var _value_modifiers;
@@ -50,6 +57,8 @@ const text = (value, max = 200)=>typeof value === 'string' ? value.trim().slice(
50
57
  options: value.options
51
58
  } : {}, ((_value_modifiers = value.modifiers) == null ? void 0 : _value_modifiers.length) ? {
52
59
  modifiers: value.modifiers
60
+ } : {}, value.quantity && value.quantity > 1 ? {
61
+ quantity: value.quantity
53
62
  } : {}));
54
63
  }
55
64
  /**
@@ -85,6 +94,7 @@ const text = (value, max = 200)=>typeof value === 'string' ? value.trim().slice(
85
94
  optionId: text(pick['optionId'])
86
95
  };
87
96
  }).filter((pick)=>pick.groupId && pick.optionId) : [];
97
+ const quantity = fieldQuantity(source['quantity']);
88
98
  return _extends({
89
99
  productId
90
100
  }, variantId && ID.test(variantId) ? {
@@ -93,12 +103,24 @@ const text = (value, max = 200)=>typeof value === 'string' ? value.trim().slice(
93
103
  options
94
104
  } : {}, modifiers.length ? {
95
105
  modifiers
106
+ } : {}, quantity && quantity > 1 ? {
107
+ quantity
96
108
  } : {});
97
109
  }
98
110
  /** The readable line the field posts under its name: the product, then its options. */ export function productFieldLabel(productName, options) {
99
111
  const picked = Object.values(options != null ? options : {}).filter(Boolean);
100
112
  return picked.length ? `${productName} — ${picked.join(' / ')}` : productName;
101
113
  }
114
+ /**
115
+ * The readable line a request carries for a product page's picks (AGL-4205):
116
+ * the product and its options, then the add-ons, then how many —
117
+ * `Custom canopy — 10 × 10 ft + Full wall, Printed roof × 2`.
118
+ */ export function builderPicksLabel(productName, options, addOnNames, quantity = 1) {
119
+ const names = addOnNames.map((name)=>name.trim()).filter(Boolean);
120
+ const base = productFieldLabel(productName, options);
121
+ const withAddOns = names.length ? `${base} + ${names.join(', ')}` : base;
122
+ return quantity > 1 ? `${withAddOns} × ${quantity}` : withAddOns;
123
+ }
102
124
  /** A request's facts as the seam answered them, read defensively. */ export function readQuoteRequestFacts(raw) {
103
125
  var _raw_person, _raw_request, _raw_emailThread, _raw_capturedRecord, _raw_fieldData;
104
126
  if (!raw || raw['record'] !== 'formSubmission') return null;
@@ -153,6 +175,7 @@ const text = (value, max = 200)=>typeof value === 'string' ? value.trim().slice(
153
175
  /** The product lines a request's Product and options fields ask for, one per field. */ export function quoteLinesFromFieldData(fieldData) {
154
176
  const lines = [];
155
177
  for (const raw of Object.values(fieldData)){
178
+ var _value_quantity;
156
179
  var _value_modifiers;
157
180
  const value = parseProductFieldValue(raw);
158
181
  if (!value) continue;
@@ -162,7 +185,7 @@ const text = (value, max = 200)=>typeof value === 'string' ? value.trim().slice(
162
185
  }, value.variantId ? {
163
186
  variantId: value.variantId
164
187
  } : {}, {
165
- quantity: 1
188
+ quantity: (_value_quantity = value.quantity) != null ? _value_quantity : 1
166
189
  }, ((_value_modifiers = value.modifiers) == null ? void 0 : _value_modifiers.length) ? {
167
190
  modifiers: value.modifiers
168
191
  } : {}));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quote-request.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QuoteCatalogLineRequest, QuoteCustomer, QuoteEmailThread, QuoteResponseFile } from './commerce-quotes'\n\n/*==========================================\n * A QUOTE STARTED FROM A REQUEST (AGL-4098).\n *\n * A \"Request a quote\" form sends a submission the forms plugin keeps; the\n * Inbox shows it, and this plugin answers it with a quote. Neither plugin\n * imports the other: the request is read through the core's record-facts\n * seam ({@link QUOTE_REQUEST_FACTS_RESOURCE}, the forms plugin's reader), and\n * the product a customer picked rides the submission as plain strings the\n * Product and options field posted ({@link parseProductFieldValue}).\n *\n * What a quote takes from a request, all of it server-read:\n *\n * - the CUSTOMER: name, email, phone and company, as the form gave them;\n * - a LINE for the product and its options, when the form had the field;\n * - the NOTES: the request's own words;\n * - its FILES, kept where the request keeps them and listed on the quote as\n * the customer's files (`quote.requestFiles`), downloaded through the\n * quote's own gated route;\n * - the REQUEST itself (`quote.request`): which submission, which form, when;\n * - the CONVERSATION (`quote.emailThread`): the thread the request's\n * confirmation email started, so the quote's first email replies into it.\n *=========================================*/\n\n/** The resource the forms plugin reads a submission's facts under, on the core's seam. */\nexport const QUOTE_REQUEST_FACTS_RESOURCE = 'forms.submission'\n\n/** The request a quote was started from. */\nexport interface QuoteRequestRef {\n submissionId: string\n formName: string\n /** When the request arrived, epoch ms; null when the submission did not say. */\n receivedAtMs: number | null\n}\n\n/**\n * What the Product and options field posts beside its readable line, under\n * `{name}__data`: the product, the variant the options make, and the options\n * as picked. Add-ons are not taken from the storefront yet; when they are,\n * they ride here as `modifiers` and the quote line prices them as the editor\n * does.\n */\nexport interface ProductFieldValue {\n productId: string\n variantId?: string\n options?: Record<string, string>\n modifiers?: Array<{ groupId: string; optionId: string }>\n}\n\nconst ID = /^(?!__.*__$)[^/]{1,200}$/\nconst MAX_OPTIONS = 20\nconst MAX_MODIFIERS = 50\n\nconst text = (value: unknown, max = 200): string => (typeof value === 'string' ? value.trim().slice(0, max) : '')\n\n/** The compact value the field posts. */\nexport function encodeProductFieldValue(value: ProductFieldValue): string {\n return JSON.stringify({\n productId: value.productId,\n ...(value.variantId ? { variantId: value.variantId } : {}),\n ...(value.options && Object.keys(value.options).length ? { options: value.options } : {}),\n ...(value.modifiers?.length ? { modifiers: value.modifiers } : {}),\n })\n}\n\n/**\n * The field's posted value, read back, or null for anything that is not one:\n * malformed JSON, no product id, ids that cannot be document ids. The options\n * keep at most twenty names and values of up to 200 characters.\n */\nexport function parseProductFieldValue(raw: unknown): ProductFieldValue | null {\n if (typeof raw !== 'string' || !raw.trim() || raw.length > 4000) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return null\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null\n const source = parsed as Record<string, unknown>\n const productId = text(source['productId'])\n if (!ID.test(productId)) return null\n const variantId = text(source['variantId'])\n const options: Record<string, string> = {}\n const rawOptions = source['options']\n if (rawOptions && typeof rawOptions === 'object' && !Array.isArray(rawOptions)) {\n for (const [name, value] of Object.entries(rawOptions as Record<string, unknown>).slice(0, MAX_OPTIONS)) {\n const key = text(name)\n const picked = text(value)\n if (key && picked) options[key] = picked\n }\n }\n const modifiers = Array.isArray(source['modifiers'])\n ? (source['modifiers'] as unknown[])\n .slice(0, MAX_MODIFIERS)\n .map((entry) => {\n const pick = (entry ?? {}) as Record<string, unknown>\n return { groupId: text(pick['groupId']), optionId: text(pick['optionId']) }\n })\n .filter((pick) => pick.groupId && pick.optionId)\n : []\n return {\n productId,\n ...(variantId && ID.test(variantId) ? { variantId } : {}),\n ...(Object.keys(options).length ? { options } : {}),\n ...(modifiers.length ? { modifiers } : {}),\n }\n}\n\n/** The readable line the field posts under its name: the product, then its options. */\nexport function productFieldLabel(productName: string, options: Record<string, string> | undefined): string {\n const picked = Object.values(options ?? {}).filter(Boolean)\n return picked.length ? `${productName} — ${picked.join(' / ')}` : productName\n}\n\n/** What this plugin reads of a request's facts (the forms plugin's reader documents them). */\nexport interface QuoteRequestFacts {\n hostId: string\n formName: string\n createdAtMs: number | null\n requestKind: string | null\n person: { name: string; email: string; phone: string; company: string }\n /** The lead or contact the request was filed as, which the quote's customer links to. */\n capturedRecord: { kind: string; id: string } | null\n message: string\n fieldData: Record<string, string>\n files: Array<QuoteResponseFile>\n emailThread: QuoteEmailThread | null\n}\n\n/** A request's facts as the seam answered them, read defensively. */\nexport function readQuoteRequestFacts(raw: Readonly<Record<string, unknown>> | null | undefined): QuoteRequestFacts | null {\n if (!raw || raw['record'] !== 'formSubmission') return null\n const person = (raw['person'] ?? {}) as Record<string, unknown>\n const request = (raw['request'] ?? null) as { kind?: unknown } | null\n const files = Array.isArray(raw['files']) ? (raw['files'] as unknown[]) : []\n const thread = (raw['emailThread'] ?? null) as Record<string, unknown> | null\n const captured = (raw['capturedRecord'] ?? null) as { kind?: unknown; id?: unknown } | null\n const references = Array.isArray(thread?.['references']) ? (thread?.['references'] as unknown[]).map(String) : []\n return {\n hostId: text(raw['hostId']),\n formName: text(raw['formName']) || 'Form',\n createdAtMs: typeof raw['createdAtMs'] === 'number' ? raw['createdAtMs'] : null,\n requestKind: typeof request?.kind === 'string' ? request.kind : null,\n person: {\n name: text(person['name']),\n email: text(person['email']),\n phone: text(person['phone'], 40),\n company: text(person['company']),\n },\n capturedRecord:\n (captured?.kind === 'lead' || captured?.kind === 'contact') && ID.test(text(captured.id))\n ? { kind: captured.kind, id: text(captured.id) }\n : null,\n message: text(raw['message'], 5000),\n fieldData: Object.fromEntries(\n Object.entries((raw['fieldData'] ?? {}) as Record<string, unknown>)\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n .map(([key, value]) => [key, value.slice(0, 4000)]),\n ),\n files: files.slice(0, 10).flatMap((entry) => {\n const file = (entry ?? {}) as Record<string, unknown>\n const id = text(file['id'], 128)\n const path = text(file['path'], 500)\n if (!id || !path.startsWith('hosts/') || !text(file['name'])) return []\n return [\n {\n id,\n name: text(file['name']),\n contentType: text(file['contentType'], 100),\n size: Number(file['size']) || 0,\n path,\n },\n ]\n }),\n emailThread:\n thread && typeof thread['messageId'] === 'string' && typeof thread['subject'] === 'string'\n ? { messageId: thread['messageId'], references, subject: thread['subject'] }\n : null,\n }\n}\n\n/** What the quote editor opens with when a quote is started from a request. */\nexport interface QuoteStartPrefill {\n customer: Pick<QuoteCustomer, 'record' | 'name' | 'email' | 'phone' | 'company'>\n lines: QuoteCatalogLineRequest[]\n notes: string\n}\n\n/** The product lines a request's Product and options fields ask for, one per field. */\nexport function quoteLinesFromFieldData(fieldData: Readonly<Record<string, string>>): QuoteCatalogLineRequest[] {\n const lines: QuoteCatalogLineRequest[] = []\n for (const raw of Object.values(fieldData)) {\n const value = parseProductFieldValue(raw)\n if (!value) continue\n lines.push({\n kind: 'catalog',\n productId: value.productId,\n ...(value.variantId ? { variantId: value.variantId } : {}),\n quantity: 1,\n ...(value.modifiers?.length ? { modifiers: value.modifiers } : {}),\n })\n }\n return lines\n}\n\n/** A quote's start from a request: the editor's prefill, and what the server stamps on the quote. */\nexport function quoteStartFromRequest(\n submissionId: string,\n facts: QuoteRequestFacts,\n): {\n prefill: QuoteStartPrefill\n request: QuoteRequestRef\n files: QuoteResponseFile[]\n emailThread: QuoteEmailThread | null\n} {\n return {\n prefill: {\n customer: {\n ...(facts.capturedRecord ? { record: facts.capturedRecord } : {}),\n ...(facts.person.name ? { name: facts.person.name } : {}),\n ...(facts.person.email ? { email: facts.person.email } : {}),\n ...(facts.person.phone ? { phone: facts.person.phone } : {}),\n ...(facts.person.company ? { company: facts.person.company } : {}),\n },\n lines: quoteLinesFromFieldData(facts.fieldData),\n notes: facts.message,\n },\n request: { submissionId, formName: facts.formName, receivedAtMs: facts.createdAtMs },\n files: facts.files,\n emailThread: facts.emailThread,\n }\n}\n\n/** A request's files as the console may see them: no storage path. */\nexport function quoteRequestFileViews(files: readonly QuoteResponseFile[] | null | undefined): Array<Omit<QuoteResponseFile, 'path'>> {\n return (files ?? []).map(({ id, name, contentType, size }) => ({ id, name, contentType, size }))\n}\n"],"names":["QUOTE_REQUEST_FACTS_RESOURCE","ID","MAX_OPTIONS","MAX_MODIFIERS","text","value","max","trim","slice","encodeProductFieldValue","JSON","stringify","productId","variantId","options","Object","keys","length","modifiers","parseProductFieldValue","raw","parsed","parse","Array","isArray","source","test","rawOptions","name","entries","key","picked","map","entry","pick","groupId","optionId","filter","productFieldLabel","productName","values","Boolean","join","readQuoteRequestFacts","person","request","files","thread","captured","references","String","hostId","formName","createdAtMs","requestKind","kind","email","phone","company","capturedRecord","id","message","fieldData","fromEntries","flatMap","file","path","startsWith","contentType","size","Number","emailThread","messageId","subject","quoteLinesFromFieldData","lines","push","quantity","quoteStartFromRequest","submissionId","facts","prefill","customer","record","notes","receivedAtMs","quoteRequestFileViews"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID;;;;;;;;;;;;;;;;;;;;;2CAqB2C,GAE3C,wFAAwF,GACxF,OAAO,MAAMA,+BAA+B,mBAAkB;AAwB9D,MAAMC,KAAK;AACX,MAAMC,cAAc;AACpB,MAAMC,gBAAgB;AAEtB,MAAMC,OAAO,CAACC,OAAgBC,MAAM,GAAG,GAAc,OAAOD,UAAU,WAAWA,MAAME,IAAI,GAAGC,KAAK,CAAC,GAAGF,OAAO;AAE9G,uCAAuC,GACvC,OAAO,SAASG,wBAAwBJ,KAAwB;QAKxDA;IAJN,OAAOK,KAAKC,SAAS,CAAC;QACpBC,WAAWP,MAAMO,SAAS;OACtBP,MAAMQ,SAAS,GAAG;QAAEA,WAAWR,MAAMQ,SAAS;IAAC,IAAI,CAAC,GACpDR,MAAMS,OAAO,IAAIC,OAAOC,IAAI,CAACX,MAAMS,OAAO,EAAEG,MAAM,GAAG;QAAEH,SAAST,MAAMS,OAAO;IAAC,IAAI,CAAC,GACnFT,EAAAA,mBAAAA,MAAMa,SAAS,qBAAfb,iBAAiBY,MAAM,IAAG;QAAEC,WAAWb,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BAAEA,OAAOwB,MAAMpC,MAAM,CAACY,KAAK;YAAC,IAAI,CAAC,GACtDwB,MAAMpC,MAAM,CAACa,KAAK,GAAG;gBAAEA,OAAOuB,MAAMpC,MAAM,CAACa,KAAK;YAAC,IAAI,CAAC,GACtDuB,MAAMpC,MAAM,CAACc,OAAO,GAAG;gBAAEA,SAASsB,MAAMpC,MAAM,CAACc,OAAO;YAAC,IAAI,CAAC;YAElEiB,OAAOD,wBAAwBM,MAAMlB,SAAS;YAC9CsB,OAAOJ,MAAMnB,OAAO;QACtB;QACAhB,SAAS;YAAEkC;YAAc3B,UAAU4B,MAAM5B,QAAQ;YAAEiC,cAAcL,MAAM3B,WAAW;QAAC;QACnFP,OAAOkC,MAAMlC,KAAK;QAClByB,aAAaS,MAAMT,WAAW;IAChC;AACF;AAEA,oEAAoE,GACpE,OAAO,SAASe,sBAAsBxC,KAAsD;IAC1F,OAAO,CAACA,gBAAAA,QAAS,EAAE,EAAEd,GAAG,CAAC,CAAC,EAAE4B,EAAE,EAAEhC,IAAI,EAAEwC,WAAW,EAAEC,IAAI,EAAE,GAAM,CAAA;YAAET;YAAIhC;YAAMwC;YAAaC;QAAK,CAAA;AAC/F"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-quote-request.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 QUOTE_MAX_QUANTITY,\n type QuoteCatalogLineRequest,\n type QuoteCustomer,\n type QuoteEmailThread,\n type QuoteResponseFile,\n} from './commerce-quotes'\n\n/*==========================================\n * A QUOTE STARTED FROM A REQUEST (AGL-4098).\n *\n * A \"Request a quote\" form sends a submission the forms plugin keeps; the\n * Inbox shows it, and this plugin answers it with a quote. Neither plugin\n * imports the other: the request is read through the core's record-facts\n * seam ({@link QUOTE_REQUEST_FACTS_RESOURCE}, the forms plugin's reader), and\n * the product a customer picked rides the submission as plain strings the\n * Product and options field posted ({@link parseProductFieldValue}).\n *\n * What a quote takes from a request, all of it server-read:\n *\n * - the CUSTOMER: name, email, phone and company, as the form gave them;\n * - a LINE for the product and its options, when the form had the field;\n * - the NOTES: the request's own words;\n * - its FILES, kept where the request keeps them and listed on the quote as\n * the customer's files (`quote.requestFiles`), downloaded through the\n * quote's own gated route;\n * - the REQUEST itself (`quote.request`): which submission, which form, when;\n * - the CONVERSATION (`quote.emailThread`): the thread the request's\n * confirmation email started, so the quote's first email replies into it.\n *=========================================*/\n\n/** The resource the forms plugin reads a submission's facts under, on the core's seam. */\nexport const QUOTE_REQUEST_FACTS_RESOURCE = 'forms.submission'\n\n/** The request a quote was started from. */\nexport interface QuoteRequestRef {\n submissionId: string\n formName: string\n /** When the request arrived, epoch ms; null when the submission did not say. */\n receivedAtMs: number | null\n}\n\n/**\n * What the Product and options field posts beside its readable line, under\n * `{name}__data`: the product, the variant the options make, and the options\n * as picked. On a product page's builder (AGL-4205) it also carries the\n * add-ons picked (`modifiers`) and how many (`quantity`); the quote line\n * prices them as the editor does.\n */\nexport interface ProductFieldValue {\n productId: string\n variantId?: string\n options?: Record<string, string>\n modifiers?: Array<{ groupId: string; optionId: string }>\n /** How many the shopper asked about, 1 to {@link PRODUCT_FIELD_MAX_QUANTITY}. Absent: one. */\n quantity?: number\n}\n\nconst ID = /^(?!__.*__$)[^/]{1,200}$/\nconst MAX_OPTIONS = 20\nconst MAX_MODIFIERS = 50\n/** The most a request can ask about in one line: a quote line's own limit, 9,999. */\nexport const PRODUCT_FIELD_MAX_QUANTITY = QUOTE_MAX_QUANTITY\n\n/** A posted quantity as a whole number from 1 to the cap; anything else is none. */\nfunction fieldQuantity(raw: unknown): number | null {\n const number = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN\n if (!Number.isInteger(number) || number < 1) return null\n return Math.min(number, PRODUCT_FIELD_MAX_QUANTITY)\n}\n\nconst text = (value: unknown, max = 200): string => (typeof value === 'string' ? value.trim().slice(0, max) : '')\n\n/** The compact value the field posts. */\nexport function encodeProductFieldValue(value: ProductFieldValue): string {\n return JSON.stringify({\n productId: value.productId,\n ...(value.variantId ? { variantId: value.variantId } : {}),\n ...(value.options && Object.keys(value.options).length ? { options: value.options } : {}),\n ...(value.modifiers?.length ? { modifiers: value.modifiers } : {}),\n ...(value.quantity && value.quantity > 1 ? { quantity: value.quantity } : {}),\n })\n}\n\n/**\n * The field's posted value, read back, or null for anything that is not one:\n * malformed JSON, no product id, ids that cannot be document ids. The options\n * keep at most twenty names and values of up to 200 characters.\n */\nexport function parseProductFieldValue(raw: unknown): ProductFieldValue | null {\n if (typeof raw !== 'string' || !raw.trim() || raw.length > 4000) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return null\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null\n const source = parsed as Record<string, unknown>\n const productId = text(source['productId'])\n if (!ID.test(productId)) return null\n const variantId = text(source['variantId'])\n const options: Record<string, string> = {}\n const rawOptions = source['options']\n if (rawOptions && typeof rawOptions === 'object' && !Array.isArray(rawOptions)) {\n for (const [name, value] of Object.entries(rawOptions as Record<string, unknown>).slice(0, MAX_OPTIONS)) {\n const key = text(name)\n const picked = text(value)\n if (key && picked) options[key] = picked\n }\n }\n const modifiers = Array.isArray(source['modifiers'])\n ? (source['modifiers'] as unknown[])\n .slice(0, MAX_MODIFIERS)\n .map((entry) => {\n const pick = (entry ?? {}) as Record<string, unknown>\n return { groupId: text(pick['groupId']), optionId: text(pick['optionId']) }\n })\n .filter((pick) => pick.groupId && pick.optionId)\n : []\n const quantity = fieldQuantity(source['quantity'])\n return {\n productId,\n ...(variantId && ID.test(variantId) ? { variantId } : {}),\n ...(Object.keys(options).length ? { options } : {}),\n ...(modifiers.length ? { modifiers } : {}),\n ...(quantity && quantity > 1 ? { quantity } : {}),\n }\n}\n\n/** The readable line the field posts under its name: the product, then its options. */\nexport function productFieldLabel(productName: string, options: Record<string, string> | undefined): string {\n const picked = Object.values(options ?? {}).filter(Boolean)\n return picked.length ? `${productName} — ${picked.join(' / ')}` : productName\n}\n\n/**\n * The readable line a request carries for a product page's picks (AGL-4205):\n * the product and its options, then the add-ons, then how many —\n * `Custom canopy — 10 × 10 ft + Full wall, Printed roof × 2`.\n */\nexport function builderPicksLabel(\n productName: string,\n options: Record<string, string> | undefined,\n addOnNames: readonly string[],\n quantity = 1,\n): string {\n const names = addOnNames.map((name) => name.trim()).filter(Boolean)\n const base = productFieldLabel(productName, options)\n const withAddOns = names.length ? `${base} + ${names.join(', ')}` : base\n return quantity > 1 ? `${withAddOns} × ${quantity}` : withAddOns\n}\n\n/** What this plugin reads of a request's facts (the forms plugin's reader documents them). */\nexport interface QuoteRequestFacts {\n hostId: string\n formName: string\n createdAtMs: number | null\n requestKind: string | null\n person: { name: string; email: string; phone: string; company: string }\n /** The lead or contact the request was filed as, which the quote's customer links to. */\n capturedRecord: { kind: string; id: string } | null\n message: string\n fieldData: Record<string, string>\n files: Array<QuoteResponseFile>\n emailThread: QuoteEmailThread | null\n}\n\n/** A request's facts as the seam answered them, read defensively. */\nexport function readQuoteRequestFacts(raw: Readonly<Record<string, unknown>> | null | undefined): QuoteRequestFacts | null {\n if (!raw || raw['record'] !== 'formSubmission') return null\n const person = (raw['person'] ?? {}) as Record<string, unknown>\n const request = (raw['request'] ?? null) as { kind?: unknown } | null\n const files = Array.isArray(raw['files']) ? (raw['files'] as unknown[]) : []\n const thread = (raw['emailThread'] ?? null) as Record<string, unknown> | null\n const captured = (raw['capturedRecord'] ?? null) as { kind?: unknown; id?: unknown } | null\n const references = Array.isArray(thread?.['references']) ? (thread?.['references'] as unknown[]).map(String) : []\n return {\n hostId: text(raw['hostId']),\n formName: text(raw['formName']) || 'Form',\n createdAtMs: typeof raw['createdAtMs'] === 'number' ? raw['createdAtMs'] : null,\n requestKind: typeof request?.kind === 'string' ? request.kind : null,\n person: {\n name: text(person['name']),\n email: text(person['email']),\n phone: text(person['phone'], 40),\n company: text(person['company']),\n },\n capturedRecord:\n (captured?.kind === 'lead' || captured?.kind === 'contact') && ID.test(text(captured.id))\n ? { kind: captured.kind, id: text(captured.id) }\n : null,\n message: text(raw['message'], 5000),\n fieldData: Object.fromEntries(\n Object.entries((raw['fieldData'] ?? {}) as Record<string, unknown>)\n .filter((entry): entry is [string, string] => typeof entry[1] === 'string')\n .map(([key, value]) => [key, value.slice(0, 4000)]),\n ),\n files: files.slice(0, 10).flatMap((entry) => {\n const file = (entry ?? {}) as Record<string, unknown>\n const id = text(file['id'], 128)\n const path = text(file['path'], 500)\n if (!id || !path.startsWith('hosts/') || !text(file['name'])) return []\n return [\n {\n id,\n name: text(file['name']),\n contentType: text(file['contentType'], 100),\n size: Number(file['size']) || 0,\n path,\n },\n ]\n }),\n emailThread:\n thread && typeof thread['messageId'] === 'string' && typeof thread['subject'] === 'string'\n ? { messageId: thread['messageId'], references, subject: thread['subject'] }\n : null,\n }\n}\n\n/** What the quote editor opens with when a quote is started from a request. */\nexport interface QuoteStartPrefill {\n customer: Pick<QuoteCustomer, 'record' | 'name' | 'email' | 'phone' | 'company'>\n lines: QuoteCatalogLineRequest[]\n notes: string\n}\n\n/** The product lines a request's Product and options fields ask for, one per field. */\nexport function quoteLinesFromFieldData(fieldData: Readonly<Record<string, string>>): QuoteCatalogLineRequest[] {\n const lines: QuoteCatalogLineRequest[] = []\n for (const raw of Object.values(fieldData)) {\n const value = parseProductFieldValue(raw)\n if (!value) continue\n lines.push({\n kind: 'catalog',\n productId: value.productId,\n ...(value.variantId ? { variantId: value.variantId } : {}),\n quantity: value.quantity ?? 1,\n ...(value.modifiers?.length ? { modifiers: value.modifiers } : {}),\n })\n }\n return lines\n}\n\n/** A quote's start from a request: the editor's prefill, and what the server stamps on the quote. */\nexport function quoteStartFromRequest(\n submissionId: string,\n facts: QuoteRequestFacts,\n): {\n prefill: QuoteStartPrefill\n request: QuoteRequestRef\n files: QuoteResponseFile[]\n emailThread: QuoteEmailThread | null\n} {\n return {\n prefill: {\n customer: {\n ...(facts.capturedRecord ? { record: facts.capturedRecord } : {}),\n ...(facts.person.name ? { name: facts.person.name } : {}),\n ...(facts.person.email ? { email: facts.person.email } : {}),\n ...(facts.person.phone ? { phone: facts.person.phone } : {}),\n ...(facts.person.company ? { company: facts.person.company } : {}),\n },\n lines: quoteLinesFromFieldData(facts.fieldData),\n notes: facts.message,\n },\n request: { submissionId, formName: facts.formName, receivedAtMs: facts.createdAtMs },\n files: facts.files,\n emailThread: facts.emailThread,\n }\n}\n\n/** A request's files as the console may see them: no storage path. */\nexport function quoteRequestFileViews(files: readonly QuoteResponseFile[] | null | undefined): Array<Omit<QuoteResponseFile, 'path'>> {\n return (files ?? []).map(({ id, name, contentType, size }) => ({ id, name, contentType, size }))\n}\n"],"names":["QUOTE_MAX_QUANTITY","QUOTE_REQUEST_FACTS_RESOURCE","ID","MAX_OPTIONS","MAX_MODIFIERS","PRODUCT_FIELD_MAX_QUANTITY","fieldQuantity","raw","number","Number","NaN","isInteger","Math","min","text","value","max","trim","slice","encodeProductFieldValue","JSON","stringify","productId","variantId","options","Object","keys","length","modifiers","quantity","parseProductFieldValue","parsed","parse","Array","isArray","source","test","rawOptions","name","entries","key","picked","map","entry","pick","groupId","optionId","filter","productFieldLabel","productName","values","Boolean","join","builderPicksLabel","addOnNames","names","base","withAddOns","readQuoteRequestFacts","person","request","files","thread","captured","references","String","hostId","formName","createdAtMs","requestKind","kind","email","phone","company","capturedRecord","id","message","fieldData","fromEntries","flatMap","file","path","startsWith","contentType","size","emailThread","messageId","subject","quoteLinesFromFieldData","lines","push","quoteStartFromRequest","submissionId","facts","prefill","customer","record","notes","received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
@@ -19,7 +19,7 @@ import type { QuoteRequestRef } from './commerce-quote-request';
19
19
  import type { HostOrder, OrderAddress, OrderLineItem, OrderStatus, OrderTotals } from './commerce-orders';
20
20
  import { type TaxSettings } from './commerce-tax';
21
21
  import { type StorefrontTaxMode } from './commerce-tax-decision';
22
- import { type ModifierSelection } from './product-modifiers';
22
+ import { type ModifierSelection, type ProductModifierOption } from './product-modifiers';
23
23
  /** Where a quote stands with the business. The customer side has no states. */
24
24
  export type QuoteStage = 'draft' | 'sent' | 'changes_requested' | 'approved';
25
25
  export declare const QUOTE_STAGE_LABELS: Record<QuoteStage, string>;
@@ -105,12 +105,21 @@ export interface QuoteCustomerResponse {
105
105
  action: 'approve' | 'changes';
106
106
  revision: number;
107
107
  atMs: number;
108
- /** With `approve`: the name they typed. */
108
+ /**
109
+ * The name they typed: with `approve`, the approval's; with `changes`, the
110
+ * rejection's (AGL-4206; absent on rejections given before it was asked for).
111
+ */
109
112
  name?: string;
110
- /** With `changes`: what to change. */
113
+ /** With `changes`: what to change. `changes` is a rejection of the revision, with this note. */
111
114
  comment?: string;
112
115
  /** With `changes`: files they sent. */
113
116
  files?: QuoteResponseFile[];
117
+ /**
118
+ * With `approve`: the statements they ticked before approving, word for
119
+ * word as the page showed them (AGL-4206). Absent on approvals given before
120
+ * the page asked for them.
121
+ */
122
+ confirmed?: string[];
114
123
  ip: string | null;
115
124
  userAgent: string | null;
116
125
  }
@@ -119,6 +128,8 @@ export interface QuoteApproval {
119
128
  revision: number;
120
129
  name: string;
121
130
  atMs: number;
131
+ /** The statements the customer ticked, word for word (AGL-4206). Absent on older approvals. */
132
+ confirmed?: string[];
122
133
  ip: string | null;
123
134
  userAgent: string | null;
124
135
  }
@@ -218,6 +229,12 @@ export interface OrderQuote {
218
229
  tax: QuoteTaxBasis;
219
230
  /** The customer approves the current revision's proof before they can pay. Absent reads as off. */
220
231
  requireProofApproval?: boolean;
232
+ /**
233
+ * A customer with an account on the site signs in to that account to see
234
+ * the proof and answer it (AGL-4206). A customer with no account (a guest)
235
+ * keeps using the private link. Absent reads as off: the link is enough.
236
+ */
237
+ requireProofSignIn?: boolean;
221
238
  /** The current revision's proofs; earlier revisions keep theirs in `revisions/{n}`. */
222
239
  proofs?: QuoteProof[];
223
240
  /** The customer's answers to the current revision, oldest first; the last one counts. */
@@ -259,9 +276,43 @@ export interface OrderQuote {
259
276
  export interface QuoteStoreSettings {
260
277
  /** What `requireProofApproval` a new quote starts with. Absent reads as off. */
261
278
  requireProofApproval?: boolean;
279
+ /** What `requireProofSignIn` a new quote starts with (AGL-4206). Absent reads as off. */
280
+ requireProofSignIn?: boolean;
281
+ /**
282
+ * What the customer ticks before Approve works (AGL-4206), in the
283
+ * business's own words. Absent or empty reads as
284
+ * {@link QUOTE_DEFAULT_APPROVAL_STATEMENTS}.
285
+ */
286
+ approvalStatements?: string[];
262
287
  }
288
+ /**
289
+ * An add-on as the quote editor's menu names it: `Back wall (+$150.00)`,
290
+ * priced for the size or option picked on the line (`variantId`), as the
291
+ * server prices the line; a free one is its name alone.
292
+ */
293
+ export declare function quoteModifierOptionLabel(option: Pick<ProductModifierOption, 'name' | 'priceCents' | 'priceCentsByVariant'>, variantId: string | null | undefined, money: (cents: number) => string): string;
263
294
  /** Whether new quotes start out asking the customer to approve the proof first. */
264
295
  export declare function quoteRequiresProofApprovalByDefault(settings: QuoteStoreSettings | null | undefined): boolean;
296
+ /** Whether new quotes start out asking a customer with a site account to sign in for the proof (AGL-4206). */
297
+ export declare function quoteRequiresProofSignInByDefault(settings: QuoteStoreSettings | null | undefined): boolean;
298
+ /** The most statements a customer ticks before approving. */
299
+ export declare const QUOTE_MAX_APPROVAL_STATEMENTS = 5;
300
+ /** The longest one statement may be. */
301
+ export declare const QUOTE_MAX_APPROVAL_STATEMENT = 200;
302
+ /**
303
+ * What a customer confirms before approving a proof when the business has not
304
+ * written its own (AGL-4206): they read the words, they checked the look, and
305
+ * they know approving starts the work.
306
+ */
307
+ export declare const QUOTE_DEFAULT_APPROVAL_STATEMENTS: readonly string[];
308
+ /**
309
+ * Statements as typed: each trimmed to one line and its length, blanks and
310
+ * repeats dropped, at most {@link QUOTE_MAX_APPROVAL_STATEMENTS}. What the
311
+ * Quotes card saves, and what every reader trusts nothing beyond.
312
+ */
313
+ export declare function cleanQuoteApprovalStatements(raw: unknown): string[];
314
+ /** What the customer ticks before Approve works: the store's own statements, else the defaults. */
315
+ export declare function quoteApprovalStatements(settings: QuoteStoreSettings | null | undefined): string[];
265
316
  /**
266
317
  * Whether paying waits on the customer approving the proof: the quote asks for
267
318
  * approval, its current revision has a proof, and that revision is not the
@@ -394,6 +445,8 @@ export interface QuoteInput {
394
445
  shipping: QuoteShipping | null;
395
446
  /** Absent: the store's default (on create) or unchanged (on update). */
396
447
  requireProofApproval?: boolean;
448
+ /** Absent: the store's default (on create) or unchanged (on update). AGL-4206. */
449
+ requireProofSignIn?: boolean;
397
450
  }
398
451
  /** What a save with no lines and no proof is told: a quote needs one or the other. */
399
452
  export declare const QUOTE_NEEDS_LINE_OR_PROOF = "Add at least one line, or a proof, to the quote.";
@@ -18,16 +18,59 @@ import { liftLegacyProduct, variantHasPrice } from "./commerce.js";
18
18
  import { computeTaxCents, resolveTaxRate } from "./commerce-tax.js";
19
19
  import { storefrontTaxDecision } from "./commerce-tax-decision.js";
20
20
  import { allocateCentsByWeight } from "./commerce-tax-engine.js";
21
- import { lineLabelWithModifiers, resolveLineModifiers } from "./product-modifiers.js";
21
+ import { lineLabelWithModifiers, modifierOptionPriceCents, resolveLineModifiers } from "./product-modifiers.js";
22
22
  export const QUOTE_STAGE_LABELS = {
23
23
  draft: 'Draft',
24
24
  sent: 'Sent',
25
- changes_requested: 'Changes requested',
25
+ // Stored as `changes_requested`; the customer rejected the proof and said what to change (AGL-4206).
26
+ changes_requested: 'Rejected with changes',
26
27
  approved: 'Approved'
27
28
  };
29
+ /**
30
+ * An add-on as the quote editor's menu names it: `Back wall (+$150.00)`,
31
+ * priced for the size or option picked on the line (`variantId`), as the
32
+ * server prices the line; a free one is its name alone.
33
+ */ export function quoteModifierOptionLabel(option, variantId, money) {
34
+ const cents = modifierOptionPriceCents(option, variantId);
35
+ return cents ? `${option.name} (+${money(cents)})` : option.name;
36
+ }
28
37
  /** Whether new quotes start out asking the customer to approve the proof first. */ export function quoteRequiresProofApprovalByDefault(settings) {
29
38
  return (settings == null ? void 0 : settings.requireProofApproval) === true;
30
39
  }
40
+ /** Whether new quotes start out asking a customer with a site account to sign in for the proof (AGL-4206). */ export function quoteRequiresProofSignInByDefault(settings) {
41
+ return (settings == null ? void 0 : settings.requireProofSignIn) === true;
42
+ }
43
+ /** The most statements a customer ticks before approving. */ export const QUOTE_MAX_APPROVAL_STATEMENTS = 5;
44
+ /** The longest one statement may be. */ export const QUOTE_MAX_APPROVAL_STATEMENT = 200;
45
+ /**
46
+ * What a customer confirms before approving a proof when the business has not
47
+ * written its own (AGL-4206): they read the words, they checked the look, and
48
+ * they know approving starts the work.
49
+ */ export const QUOTE_DEFAULT_APPROVAL_STATEMENTS = [
50
+ 'I checked the spelling, names and numbers.',
51
+ 'I checked the colors, sizes and placement.',
52
+ 'I understand production starts when I approve, and changes after that may cost extra.'
53
+ ];
54
+ /**
55
+ * Statements as typed: each trimmed to one line and its length, blanks and
56
+ * repeats dropped, at most {@link QUOTE_MAX_APPROVAL_STATEMENTS}. What the
57
+ * Quotes card saves, and what every reader trusts nothing beyond.
58
+ */ export function cleanQuoteApprovalStatements(raw) {
59
+ if (!Array.isArray(raw)) return [];
60
+ const kept = [];
61
+ for (const entry of raw){
62
+ const statement = typeof entry === 'string' ? entry.replace(/\s+/g, ' ').trim().slice(0, QUOTE_MAX_APPROVAL_STATEMENT) : '';
63
+ if (statement && !kept.includes(statement)) kept.push(statement);
64
+ if (kept.length >= QUOTE_MAX_APPROVAL_STATEMENTS) break;
65
+ }
66
+ return kept;
67
+ }
68
+ /** What the customer ticks before Approve works: the store's own statements, else the defaults. */ export function quoteApprovalStatements(settings) {
69
+ const own = cleanQuoteApprovalStatements(settings == null ? void 0 : settings.approvalStatements);
70
+ return own.length ? own : [
71
+ ...QUOTE_DEFAULT_APPROVAL_STATEMENTS
72
+ ];
73
+ }
31
74
  /**
32
75
  * Whether paying waits on the customer approving the proof: the quote asks for
33
76
  * approval, its current revision has a proof, and that revision is not the
@@ -422,6 +465,8 @@ function parseLine(raw, index) {
422
465
  shipping
423
466
  }, typeof source['requireProofApproval'] === 'boolean' ? {
424
467
  requireProofApproval: source['requireProofApproval']
468
+ } : {}, typeof source['requireProofSignIn'] === 'boolean' ? {
469
+ requireProofSignIn: source['requireProofSignIn']
425
470
  } : {})
426
471
  };
427
472
  }