@aglyn/plugins-commerce 1.15.2 → 1.16.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 (212) 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/product-add-ons-fields.component.d.ts +13 -0
  15. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  16. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  17. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  18. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  19. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  20. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  21. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  22. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  23. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  24. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  25. package/src/lib/components/console/quote-messages.component.js +185 -0
  26. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  27. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  28. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  29. package/src/lib/components/console/quote-proofs.component.js +30 -3
  30. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  31. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  32. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  33. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  34. package/src/lib/components/product-builder-context.d.ts +22 -0
  35. package/src/lib/components/product-builder-context.js +21 -0
  36. package/src/lib/components/product-builder-context.js.map +1 -0
  37. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  38. package/src/lib/components/product-builder-mockup.js +120 -0
  39. package/src/lib/components/product-builder-mockup.js.map +1 -0
  40. package/src/lib/components/product-builder-sample.d.ts +63 -0
  41. package/src/lib/components/product-builder-sample.js +96 -0
  42. package/src/lib/components/product-builder-sample.js.map +1 -0
  43. package/src/lib/components/product-choice-cards.d.ts +51 -0
  44. package/src/lib/components/product-choice-cards.js +311 -0
  45. package/src/lib/components/product-choice-cards.js.map +1 -0
  46. package/src/lib/components/product-detail-panels.d.ts +42 -0
  47. package/src/lib/components/product-detail-panels.js +185 -0
  48. package/src/lib/components/product-detail-panels.js.map +1 -0
  49. package/src/lib/components/product-detail.d.ts +20 -12
  50. package/src/lib/components/product-detail.js +136 -221
  51. package/src/lib/components/product-detail.js.map +1 -1
  52. package/src/lib/components/product-grid.d.ts +7 -0
  53. package/src/lib/components/product-grid.js +11 -8
  54. package/src/lib/components/product-grid.js.map +1 -1
  55. package/src/lib/components/product-options-field-body.d.ts +9 -8
  56. package/src/lib/components/product-options-field-body.js +152 -3
  57. package/src/lib/components/product-options-field-body.js.map +1 -1
  58. package/src/lib/components/product-options-field.js +1 -1
  59. package/src/lib/components/product-options-field.js.map +1 -1
  60. package/src/lib/components/product-photo-fit.d.ts +49 -0
  61. package/src/lib/components/product-photo-fit.js +58 -0
  62. package/src/lib/components/product-photo-fit.js.map +1 -0
  63. package/src/lib/components/product-restock-notify.d.ts +12 -0
  64. package/src/lib/components/product-restock-notify.js +86 -0
  65. package/src/lib/components/product-restock-notify.js.map +1 -0
  66. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  67. package/src/lib/components/quote-messages-panel.js +191 -0
  68. package/src/lib/components/quote-messages-panel.js.map +1 -0
  69. package/src/lib/components/quote-page-body.js +15 -1
  70. package/src/lib/components/quote-page-body.js.map +1 -1
  71. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  72. package/src/lib/components/quote-proof-panel.js +139 -14
  73. package/src/lib/components/quote-proof-panel.js.map +1 -1
  74. package/src/lib/components/related-products.d.ts +7 -0
  75. package/src/lib/components/related-products.js +8 -6
  76. package/src/lib/components/related-products.js.map +1 -1
  77. package/src/lib/constants/quote-page.d.ts +8 -0
  78. package/src/lib/constants/quote-page.js +11 -0
  79. package/src/lib/constants/quote-page.js.map +1 -1
  80. package/src/lib/model/commerce-cart.d.ts +6 -1
  81. package/src/lib/model/commerce-cart.js +5 -1
  82. package/src/lib/model/commerce-cart.js.map +1 -1
  83. package/src/lib/model/commerce-invoices.js +5 -1
  84. package/src/lib/model/commerce-invoices.js.map +1 -1
  85. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  86. package/src/lib/model/commerce-pos-ops.js +3 -0
  87. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  88. package/src/lib/model/commerce-pos.d.ts +8 -0
  89. package/src/lib/model/commerce-pos.js.map +1 -1
  90. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  91. package/src/lib/model/commerce-quote-messages.js +146 -0
  92. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  93. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  94. package/src/lib/model/commerce-quote-pay.js +31 -7
  95. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  96. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  97. package/src/lib/model/commerce-quote-proofs.js +73 -18
  98. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  99. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  100. package/src/lib/model/commerce-quote-request.js +25 -2
  101. package/src/lib/model/commerce-quote-request.js.map +1 -1
  102. package/src/lib/model/commerce-quotes.d.ts +56 -3
  103. package/src/lib/model/commerce-quotes.js +47 -2
  104. package/src/lib/model/commerce-quotes.js.map +1 -1
  105. package/src/lib/model/commerce.d.ts +12 -1
  106. package/src/lib/model/commerce.js.map +1 -1
  107. package/src/lib/model/index.d.ts +1 -0
  108. package/src/lib/model/index.js +1 -0
  109. package/src/lib/model/index.js.map +1 -1
  110. package/src/lib/model/pos-cellular.d.ts +5 -0
  111. package/src/lib/model/pos-cellular.js.map +1 -1
  112. package/src/lib/model/product-card-rules.d.ts +41 -0
  113. package/src/lib/model/product-card-rules.js +90 -0
  114. package/src/lib/model/product-card-rules.js.map +1 -0
  115. package/src/lib/model/product-modifiers.d.ts +11 -0
  116. package/src/lib/model/product-modifiers.js +10 -0
  117. package/src/lib/model/product-modifiers.js.map +1 -1
  118. package/src/lib/model/product-write.d.ts +3 -0
  119. package/src/lib/server/billing-webhook.js +6 -2
  120. package/src/lib/server/billing-webhook.js.map +1 -1
  121. package/src/lib/server/cancel-order.js +15 -0
  122. package/src/lib/server/cancel-order.js.map +1 -1
  123. package/src/lib/server/channel-order-updates.js +15 -1
  124. package/src/lib/server/channel-order-updates.js.map +1 -1
  125. package/src/lib/server/channel-orders.js +20 -0
  126. package/src/lib/server/channel-orders.js.map +1 -1
  127. package/src/lib/server/checkout.js +1 -1
  128. package/src/lib/server/checkout.js.map +1 -1
  129. package/src/lib/server/local-fulfillment.js +1 -1
  130. package/src/lib/server/local-fulfillment.js.map +1 -1
  131. package/src/lib/server/pos-cellular-billing.d.ts +1 -1
  132. package/src/lib/server/pos-cellular-billing.js +2 -1
  133. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  134. package/src/lib/server/pos-cellular.d.ts +3 -1
  135. package/src/lib/server/pos-cellular.js +15 -8
  136. package/src/lib/server/pos-cellular.js.map +1 -1
  137. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  138. package/src/lib/server/pos-offline-sync.js +17 -4
  139. package/src/lib/server/pos-offline-sync.js.map +1 -1
  140. package/src/lib/server/pos-order.js +17 -6
  141. package/src/lib/server/pos-order.js.map +1 -1
  142. package/src/lib/server/pos-payment.js +27 -11
  143. package/src/lib/server/pos-payment.js.map +1 -1
  144. package/src/lib/server/pos-reader-splash.js +10 -5
  145. package/src/lib/server/pos-reader-splash.js.map +1 -1
  146. package/src/lib/server/pos-readers.js +34 -10
  147. package/src/lib/server/pos-readers.js.map +1 -1
  148. package/src/lib/server/pos-return.js +19 -3
  149. package/src/lib/server/pos-return.js.map +1 -1
  150. package/src/lib/server/pos-stripe.d.ts +14 -0
  151. package/src/lib/server/pos-stripe.js +6 -2
  152. package/src/lib/server/pos-stripe.js.map +1 -1
  153. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  154. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  155. package/src/lib/server/pos-terminal.d.ts +80 -14
  156. package/src/lib/server/pos-terminal.js +393 -123
  157. package/src/lib/server/pos-terminal.js.map +1 -1
  158. package/src/lib/server/product-drafts.d.ts +1 -1
  159. package/src/lib/server/product-drafts.js +4 -3
  160. package/src/lib/server/product-drafts.js.map +1 -1
  161. package/src/lib/server/product-writer.js +5 -4
  162. package/src/lib/server/product-writer.js.map +1 -1
  163. package/src/lib/server/product.d.ts +11 -0
  164. package/src/lib/server/product.js +18 -3
  165. package/src/lib/server/product.js.map +1 -1
  166. package/src/lib/server/products-write.js +4 -3
  167. package/src/lib/server/products-write.js.map +1 -1
  168. package/src/lib/server/quote-email.d.ts +26 -0
  169. package/src/lib/server/quote-email.js +73 -7
  170. package/src/lib/server/quote-email.js.map +1 -1
  171. package/src/lib/server/quote-messages.d.ts +72 -0
  172. package/src/lib/server/quote-messages.js +356 -0
  173. package/src/lib/server/quote-messages.js.map +1 -0
  174. package/src/lib/server/quote-pay.d.ts +42 -0
  175. package/src/lib/server/quote-pay.js +81 -4
  176. package/src/lib/server/quote-pay.js.map +1 -1
  177. package/src/lib/server/quote-proofs.d.ts +1 -1
  178. package/src/lib/server/quote-proofs.js +63 -19
  179. package/src/lib/server/quote-proofs.js.map +1 -1
  180. package/src/lib/server/quote.d.ts +12 -0
  181. package/src/lib/server/quote.js +44 -14
  182. package/src/lib/server/quote.js.map +1 -1
  183. package/src/lib/server/refund.js +3 -1
  184. package/src/lib/server/refund.js.map +1 -1
  185. package/src/lib/server/reserve-stock.js +9 -0
  186. package/src/lib/server/reserve-stock.js.map +1 -1
  187. package/src/lib/server/returns.js +15 -1
  188. package/src/lib/server/returns.js.map +1 -1
  189. package/src/lib/server/reviews.js +15 -0
  190. package/src/lib/server/reviews.js.map +1 -1
  191. package/src/lib/server/sold-out-drop.d.ts +58 -0
  192. package/src/lib/server/sold-out-drop.js +81 -0
  193. package/src/lib/server/sold-out-drop.js.map +1 -0
  194. package/src/lib/server/stock-levels.js +9 -0
  195. package/src/lib/server/stock-levels.js.map +1 -1
  196. package/src/lib/server/stripe-refund.d.ts +7 -0
  197. package/src/lib/server/stripe-refund.js +26 -7
  198. package/src/lib/server/stripe-refund.js.map +1 -1
  199. package/src/lib/server.js +2 -0
  200. package/src/lib/server.js.map +1 -1
  201. package/src/lib/tenant-emails.js +85 -2
  202. package/src/lib/tenant-emails.js.map +1 -1
  203. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  204. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  205. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  206. package/src/lib/transfer/product-transfer.js +6 -5
  207. package/src/lib/transfer/product-transfer.js.map +1 -1
  208. package/src/lib/transfer/products.server.js +4 -3
  209. package/src/lib/transfer/products.server.js.map +1 -1
  210. package/src/lib/utils/quote-email-content.d.ts +6 -0
  211. package/src/lib/utils/quote-email-content.js +6 -3
  212. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -0,0 +1,356 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
18
+ import { claimAttempt } from "@aglyn/aglyn/server";
19
+ import { checkEntitlement } from "@aglyn/aglyn/server";
20
+ import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
21
+ import { VISITOR_UPLOAD_HONEYPOT_FIELD } from "@aglyn/aglyn/app-utils/visitor-upload";
22
+ import * as CommerceModel from "../model/index.js";
23
+ import { limitedQuoteLink, loadLinkedQuote, quoteLinkParams, quoteProofAccessFor, quoteProofAccessRefusal, sendQuoteLinkOutcome } from "./quote-pay.js";
24
+ import { defaultQuoteProofDeps } from "./quote-proofs.js";
25
+ const refuse = (status, error)=>({
26
+ status,
27
+ body: {
28
+ error
29
+ }
30
+ });
31
+ /** Messages the customer may send per address per site, per ten minutes. */ export const QUOTE_MESSAGES_PER_WINDOW = 20;
32
+ function headerOf(req, name) {
33
+ var _req_headers, _headers_name_toLowerCase, _value_;
34
+ const headers = (_req_headers = req.headers) != null ? _req_headers : {};
35
+ const value = (_headers_name_toLowerCase = headers[name.toLowerCase()]) != null ? _headers_name_toLowerCase : headers[name];
36
+ return String(Array.isArray(value) ? (_value_ = value[0]) != null ? _value_ : '' : value != null ? value : '').trim();
37
+ }
38
+ function bodyOf(req) {
39
+ const raw = req.body;
40
+ if (typeof raw === 'string') {
41
+ try {
42
+ const parsed = JSON.parse(raw);
43
+ return parsed && typeof parsed === 'object' ? parsed : {};
44
+ } catch (unused) {
45
+ return {};
46
+ }
47
+ }
48
+ return raw && typeof raw === 'object' ? raw : {};
49
+ }
50
+ /** The quote's messages, newest {@link CommerceModel.QUOTE_MESSAGES_SHOWN}, as stored (the page's view reads the same, in `payLinkPageView`). */ export async function readQuoteMessages(orderRef) {
51
+ const listed = await orderRef.collection('messages').orderBy('atMs', 'desc').limit(CommerceModel.QUOTE_MESSAGES_SHOWN).get();
52
+ return listed.docs.map((entry)=>({
53
+ id: entry.id,
54
+ data: entry.data()
55
+ }));
56
+ }
57
+ /*------------------------------------------
58
+ * The console: read the conversation, and reply
59
+ *-----------------------------------------*/ export async function handleQuoteMessagesAction(deps, context) {
60
+ var _ref, _ref1;
61
+ var _stored_quote;
62
+ const { action, req, body, hostId, quoteId, hostRef, host, actor } = context;
63
+ const firestore = deps.firestore();
64
+ const ref = hostRef.collection('orders').doc(quoteId);
65
+ if (action === 'messages') {
66
+ const snapshot = await ref.get();
67
+ const order = snapshot.exists ? snapshot.data() : null;
68
+ if (!order || !CommerceModel.isQuote(order) || !order.quote) return refuse(404, 'Unknown quote');
69
+ const messages = CommerceModel.quoteConsoleMessages(await readQuoteMessages(ref));
70
+ return {
71
+ status: 200,
72
+ body: {
73
+ messages,
74
+ to: CommerceModel.quoteReplyRecipient(order)
75
+ }
76
+ };
77
+ }
78
+ const parsed = CommerceModel.parseQuoteMessageBody(body['message']);
79
+ if ('error' in parsed) return refuse(400, parsed.error);
80
+ const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200);
81
+ if (!idempotencyKey) return refuse(400, 'Sending a reply needs an Idempotency-Key header.');
82
+ const snapshot = await ref.get();
83
+ const stored = snapshot.exists ? snapshot.data() : null;
84
+ const refused = CommerceModel.quoteReplyRefusal(stored);
85
+ if (refused || !stored) {
86
+ const reason = refused != null ? refused : 'not-a-quote';
87
+ return refuse(reason === 'not-a-quote' ? 404 : 409, CommerceModel.quoteReplyRefusalMessage(reason));
88
+ }
89
+ const to = CommerceModel.quoteReplyRecipient(stored);
90
+ const url = deps.payLinkUrl(host, hostId, quoteId, CommerceModel.quoteLinkVersion(stored.quote));
91
+ if (!url) return refuse(409, 'This site has no web address yet, so its quotes have no link to reply with. Publish the site first.');
92
+ const owner = await deps.orgForHost(hostId);
93
+ if (!checkEntitlement(owner == null ? void 0 : owner.org, 'commerce')) return refuse(403, 'Selling is not enabled');
94
+ const mailer = await deps.mailer();
95
+ if (!mailer.configured()) return refuse(503, 'Email isn’t set up here, so replies can’t be emailed.');
96
+ // The bounce and complaint list only: the customer is in a conversation they started.
97
+ if (await mailer.suppression(to)) {
98
+ return refuse(409, `${to} bounced or reported an email as spam, so it can’t be emailed.`);
99
+ }
100
+ const claimed = await claimAttempt(firestore, {
101
+ kind: 'commerce-quote-reply',
102
+ scopeId: `${hostId}:${quoteId}`,
103
+ orgId: (_ref = owner == null ? void 0 : owner.id) != null ? _ref : '',
104
+ key: idempotencyKey,
105
+ busyMessage: 'This reply is already being sent'
106
+ });
107
+ if ('replay' in claimed) return {
108
+ status: claimed.replay.status,
109
+ body: claimed.replay.body
110
+ };
111
+ const claim = claimed.claim;
112
+ const now = deps.now();
113
+ let delivered;
114
+ try {
115
+ delivered = await mailer.deliverMessage({
116
+ hostId,
117
+ quoteId,
118
+ order: stored,
119
+ host,
120
+ owner: owner ? {
121
+ id: owner.id,
122
+ org: owner.org
123
+ } : null,
124
+ to,
125
+ body: parsed.body,
126
+ url,
127
+ senderEmail: context.senderEmail,
128
+ atMs: now
129
+ });
130
+ } catch (error) {
131
+ console.error('commerce quote reply failed', error);
132
+ await claim.release();
133
+ return refuse(502, 'The reply could not be sent. Try again.');
134
+ }
135
+ // `strictNullChecks` is off, so the result does not narrow on `sent`.
136
+ if ('error' in delivered) {
137
+ await claim.release();
138
+ return refuse(delivered.status, delivered.error);
139
+ }
140
+ const done = delivered;
141
+ // The email is out: from here a failure is logged, never answered as one, so a retry does not send it twice.
142
+ const message = {
143
+ direction: 'out',
144
+ body: parsed.body,
145
+ atMs: now,
146
+ revision: Math.max(1, Number((_ref1 = (_stored_quote = stored.quote) == null ? void 0 : _stored_quote.revision) != null ? _ref1 : 1) || 1),
147
+ by: actor,
148
+ to,
149
+ messageId: done.messageId,
150
+ providerId: done.providerId
151
+ };
152
+ try {
153
+ await firestore.runTransaction(async (transaction)=>{
154
+ const current = await transaction.get(ref);
155
+ const latest = current.exists ? current.data() : null;
156
+ transaction.set(ref.collection('messages').doc(createResourceUid()), message);
157
+ if (!(latest == null ? void 0 : latest.quote)) return;
158
+ transaction.set(ref, CommerceModel.quoteAfterReply(latest, {
159
+ to,
160
+ by: actor,
161
+ atMs: now
162
+ }, done.thread));
163
+ });
164
+ } catch (error) {
165
+ console.error('commerce quote reply sent but not recorded', {
166
+ hostId,
167
+ quoteId,
168
+ messageId: done.messageId,
169
+ error
170
+ });
171
+ }
172
+ const outcome = {
173
+ status: 200,
174
+ body: {
175
+ sent: true,
176
+ to,
177
+ atMs: now
178
+ }
179
+ };
180
+ await claim.record(outcome.status, outcome.body);
181
+ return outcome;
182
+ }
183
+ /*------------------------------------------
184
+ * The site: the customer writes on the quote page
185
+ *-----------------------------------------*/ /** The managers' notice of a customer's message: who, which quote, what they said, and how to answer. */ export function quoteMessageNotice(input) {
186
+ var _ref;
187
+ var _quote_customer, _quote_customer1, _quote_customer2, _quote_customer3, _quote_customer4, _quote_customer5;
188
+ const { hostId, quoteId, order, body } = input;
189
+ const quote = order.quote;
190
+ const number = CommerceModel.formatQuoteNumber(order, quoteId);
191
+ const customer = ((_quote_customer = quote.customer) == null ? void 0 : _quote_customer.name) || ((_quote_customer1 = quote.customer) == null ? void 0 : _quote_customer1.company) || ((_quote_customer2 = quote.customer) == null ? void 0 : _quote_customer2.email) || 'The customer';
192
+ const email = String((_ref = (_quote_customer3 = quote.customer) == null ? void 0 : _quote_customer3.email) != null ? _ref : '').trim();
193
+ const excerpt = body.length > 1000 ? `${body.slice(0, 1000)}…` : body;
194
+ return {
195
+ payload: {
196
+ type: 'content.order',
197
+ level: 'info',
198
+ label: 'Customer message',
199
+ actionLabel: 'View quote',
200
+ title: `${customer} wrote about ${number} on {site}`,
201
+ body: `${excerpt}\n\nReply from the quote, or reply to this email to reach them.`,
202
+ link: `/${hostId}/products/orders?quote=${encodeURIComponent(quoteId)}`
203
+ },
204
+ options: _extends({
205
+ emailDetails: [
206
+ {
207
+ label: 'Quote',
208
+ value: number
209
+ },
210
+ {
211
+ label: 'Customer',
212
+ value: [
213
+ (_quote_customer4 = quote.customer) == null ? void 0 : _quote_customer4.name,
214
+ (_quote_customer5 = quote.customer) == null ? void 0 : _quote_customer5.company,
215
+ email
216
+ ].filter(Boolean).join(', ')
217
+ },
218
+ {
219
+ label: 'Message',
220
+ value: excerpt
221
+ }
222
+ ]
223
+ }, /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? {
224
+ replyTo: email
225
+ } : {})
226
+ };
227
+ }
228
+ /** `POST /api/commerce/quote-message`: the customer writes to the business on the quote page. */ export async function handleQuoteMessage(deps, req) {
229
+ var _order_quote_revision, _ref, _ref1;
230
+ var _req_socket, _order_quote_customer, _order_quote_customer1;
231
+ if (req.method !== 'POST') return {
232
+ status: 405,
233
+ body: {
234
+ error: 'Method not allowed'
235
+ }
236
+ };
237
+ const body = bodyOf(req);
238
+ const { hostId, quoteId, token, complete } = quoteLinkParams(body);
239
+ if (!complete) return {
240
+ status: 400,
241
+ body: {
242
+ error: 'This link is incomplete.'
243
+ }
244
+ };
245
+ // A form a person fills never fills this; a bot that did learns nothing.
246
+ const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD];
247
+ if (typeof honeypot === 'string' && honeypot.trim()) return {
248
+ status: 200,
249
+ body: {
250
+ received: true
251
+ }
252
+ };
253
+ const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200);
254
+ if (!idempotencyKey) return {
255
+ status: 400,
256
+ body: {
257
+ error: 'A message needs an Idempotency-Key header.'
258
+ }
259
+ };
260
+ const limited = await limitedQuoteLink(deps, req, `commerce-quote-message:${hostId}`, QUOTE_MESSAGES_PER_WINDOW);
261
+ if (limited) return limited;
262
+ const linked = await loadLinkedQuote(deps, hostId, quoteId, token);
263
+ if ('outcome' in linked) return linked.outcome;
264
+ const { hostRef, order } = linked.loaded;
265
+ if (linked.loaded.kind !== 'quote' || !order.quote) return {
266
+ status: 404,
267
+ body: {
268
+ error: 'We could not find that quote. Check the link you were sent.'
269
+ }
270
+ };
271
+ // The conversation is about the proof, so it waits on the same sign-in as the proof (AGL-4206).
272
+ if (CommerceModel.currentQuoteProofs(order.quote).length) {
273
+ const access = await quoteProofAccessFor(deps, req, {
274
+ hostId,
275
+ host: linked.loaded.host,
276
+ order
277
+ });
278
+ if (access !== 'open') return quoteProofAccessRefusal(access, linked.loaded.storeName);
279
+ }
280
+ const parsed = CommerceModel.parseQuoteMessageBody(body['message']);
281
+ if ('error' in parsed) return {
282
+ status: 400,
283
+ body: {
284
+ error: parsed.error
285
+ }
286
+ };
287
+ const claimed = await claimAttempt(deps.firestore(), {
288
+ kind: 'commerce-quote-message',
289
+ scopeId: `${hostId}:${quoteId}`,
290
+ orgId: '',
291
+ key: idempotencyKey,
292
+ busyMessage: 'Your message is already being sent'
293
+ });
294
+ if ('replay' in claimed) return {
295
+ status: claimed.replay.status,
296
+ body: claimed.replay.body
297
+ };
298
+ const claim = claimed.claim;
299
+ const now = deps.now();
300
+ const ref = hostRef.collection('orders').doc(quoteId);
301
+ const ip = readClientIp(req.headers, {
302
+ remoteAddress: (_req_socket = req.socket) == null ? void 0 : _req_socket.remoteAddress
303
+ });
304
+ const message = {
305
+ direction: 'in',
306
+ body: parsed.body,
307
+ atMs: now,
308
+ revision: Math.max(1, Number((_order_quote_revision = order.quote.revision) != null ? _order_quote_revision : 1) || 1),
309
+ name: String((_ref = (_order_quote_customer = order.quote.customer) == null ? void 0 : _order_quote_customer.name) != null ? _ref : '').trim() || String((_ref1 = (_order_quote_customer1 = order.quote.customer) == null ? void 0 : _order_quote_customer1.company) != null ? _ref1 : '').trim(),
310
+ ip: ip ? ip.slice(0, 64) : null,
311
+ userAgent: headerOf(req, 'user-agent').slice(0, 400) || null
312
+ };
313
+ try {
314
+ await ref.collection('messages').doc(createResourceUid()).set(message);
315
+ } catch (error) {
316
+ console.error('quote message failed', error);
317
+ await claim.release();
318
+ return {
319
+ status: 500,
320
+ body: {
321
+ error: 'Your message could not be sent. Try again.'
322
+ }
323
+ };
324
+ }
325
+ const messages = CommerceModel.quotePageMessages(await readQuoteMessages(ref));
326
+ const outcome = {
327
+ status: 200,
328
+ body: {
329
+ messages
330
+ }
331
+ };
332
+ await claim.record(200, outcome.body);
333
+ const notice = quoteMessageNotice({
334
+ hostId,
335
+ quoteId,
336
+ order,
337
+ body: parsed.body
338
+ });
339
+ void deps.notify(hostId, notice.payload, notice.options);
340
+ return outcome;
341
+ }
342
+ /** `POST /api/commerce/quote-message`. */ export const quoteMessageHandler = async (req, res)=>{
343
+ try {
344
+ return sendQuoteLinkOutcome(res, await handleQuoteMessage(defaultQuoteProofDeps(), req));
345
+ } catch (error) {
346
+ console.error('quote message failed', error);
347
+ return sendQuoteLinkOutcome(res, {
348
+ status: 500,
349
+ body: {
350
+ error: 'Your message could not be sent. Try again.'
351
+ }
352
+ });
353
+ }
354
+ };
355
+
356
+ //# sourceMappingURL=quote-messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/quote-messages.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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { claimAttempt, type PluginApiHandler, type PluginApiRequest } from '@aglyn/aglyn/server'\nimport { checkEntitlement } from '@aglyn/aglyn/server'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { VISITOR_UPLOAD_HONEYPOT_FIELD } from '@aglyn/aglyn/app-utils/visitor-upload'\nimport * as CommerceModel from '../model'\nimport type { QuoteDeps } from './quote'\nimport type { QuoteMailer } from './quote-email'\nimport {\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n quoteProofAccessFor,\n quoteProofAccessRefusal,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n} from './quote-pay'\nimport { defaultQuoteProofDeps, type QuoteProofDeps } from './quote-proofs'\n\n/*==========================================\n * A QUOTE'S CONVERSATION (AGL-4207), both halves:\n *\n * console POST /api/commerce/quote { action: 'messages', quoteId }\n * → { messages } (\"Create and edit quotes\")\n * POST /api/commerce/quote { action: 'reply', quoteId, message } + Idempotency-Key\n * → { sent, to, atMs } (\"Send quotes and invoices to customers\")\n * site POST /api/commerce/quote-message { hostId, q, t, message } + Idempotency-Key\n * → 200 { messages } | 400 | 403 (the proof waits on a sign-in) | 404 | 410 | 429\n *\n * A reply goes by email in the quote's own conversation (`quote.emailThread`)\n * and is kept under the quote; what the customer writes on the quote page is\n * kept there too, and the business is told in Aglyn and by email. Nothing\n * receives mail: an answer to the email reaches the business's own mailbox\n * (its Reply-To), as an Inbox reply's does.\n *=========================================*/\n\ntype Outcome = { status: number; body: Record<string, unknown> }\n\nconst refuse = (status: number, error: string): Outcome => ({ status, body: { error } })\n\n/** Messages the customer may send per address per site, per ten minutes. */\nexport const QUOTE_MESSAGES_PER_WINDOW = 20\n\nfunction headerOf(req: PluginApiRequest, name: string): string {\n const headers = (req.headers ?? {}) as Record<string, unknown>\n const value = headers[name.toLowerCase()] ?? headers[name]\n return String(Array.isArray(value) ? (value[0] ?? '') : (value ?? '')).trim()\n}\n\nfunction bodyOf(req: PluginApiRequest): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n try {\n const parsed = JSON.parse(raw)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {}\n}\n\n/** The quote's messages, newest {@link CommerceModel.QUOTE_MESSAGES_SHOWN}, as stored (the page's view reads the same, in `payLinkPageView`). */\nexport async function readQuoteMessages(\n orderRef: FirebaseFirestore.DocumentReference,\n): Promise<Array<{ id: string; data: Partial<CommerceModel.QuoteMessage> }>> {\n const listed = await orderRef.collection('messages').orderBy('atMs', 'desc').limit(CommerceModel.QUOTE_MESSAGES_SHOWN).get()\n return listed.docs.map((entry) => ({ id: entry.id, data: entry.data() as Partial<CommerceModel.QuoteMessage> }))\n}\n\n/*------------------------------------------\n * The console: read the conversation, and reply\n *-----------------------------------------*/\n\nexport async function handleQuoteMessagesAction(\n deps: QuoteDeps,\n context: {\n action: 'messages' | 'reply'\n req: PluginApiRequest\n body: Record<string, unknown>\n hostId: string\n quoteId: string\n hostRef: FirebaseFirestore.DocumentReference\n host: Record<string, unknown>\n actor: string\n senderEmail: string | null\n },\n): Promise<Outcome> {\n const { action, req, body, hostId, quoteId, hostRef, host, actor } = context\n const firestore = deps.firestore()\n const ref = hostRef.collection('orders').doc(quoteId)\n\n if (action === 'messages') {\n const snapshot = await ref.get()\n const order = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n if (!order || !CommerceModel.isQuote(order) || !order.quote) return refuse(404, 'Unknown quote')\n const messages = CommerceModel.quoteConsoleMessages(await readQuoteMessages(ref))\n return { status: 200, body: { messages, to: CommerceModel.quoteReplyRecipient(order) } }\n }\n\n const parsed = CommerceModel.parseQuoteMessageBody(body['message'])\n if ('error' in parsed) return refuse(400, parsed.error)\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return refuse(400, 'Sending a reply needs an Idempotency-Key header.')\n const snapshot = await ref.get()\n const stored = snapshot.exists ? (snapshot.data() as CommerceModel.HostOrder) : null\n const refused = CommerceModel.quoteReplyRefusal(stored)\n if (refused || !stored) {\n const reason = refused ?? 'not-a-quote'\n return refuse(reason === 'not-a-quote' ? 404 : 409, CommerceModel.quoteReplyRefusalMessage(reason))\n }\n const to = CommerceModel.quoteReplyRecipient(stored)\n const url = deps.payLinkUrl(host, hostId, quoteId, CommerceModel.quoteLinkVersion(stored.quote))\n if (!url) return refuse(409, 'This site has no web address yet, so its quotes have no link to reply with. Publish the site first.')\n const owner = await deps.orgForHost(hostId)\n if (!checkEntitlement(owner?.org as never, 'commerce')) return refuse(403, 'Selling is not enabled')\n const mailer = await deps.mailer()\n if (!mailer.configured()) return refuse(503, 'Email isn’t set up here, so replies can’t be emailed.')\n // The bounce and complaint list only: the customer is in a conversation they started.\n if (await mailer.suppression(to)) {\n return refuse(409, `${to} bounced or reported an email as spam, so it can’t be emailed.`)\n }\n\n const claimed = await claimAttempt(firestore, {\n kind: 'commerce-quote-reply',\n scopeId: `${hostId}:${quoteId}`,\n orgId: owner?.id ?? '',\n key: idempotencyKey,\n busyMessage: 'This reply is already being sent',\n })\n if ('replay' in claimed) return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n const claim = claimed.claim\n const now = deps.now()\n let delivered: Awaited<ReturnType<QuoteMailer['deliverMessage']>>\n try {\n delivered = await mailer.deliverMessage({\n hostId,\n quoteId,\n order: stored,\n host,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n to,\n body: parsed.body,\n url,\n senderEmail: context.senderEmail,\n atMs: now,\n })\n } catch (error) {\n console.error('commerce quote reply failed', error)\n await claim.release()\n return refuse(502, 'The reply could not be sent. Try again.')\n }\n // `strictNullChecks` is off, so the result does not narrow on `sent`.\n if ('error' in delivered) {\n await claim.release()\n return refuse(delivered.status, delivered.error)\n }\n const done = delivered as Extract<typeof delivered, { sent: true }>\n\n // The email is out: from here a failure is logged, never answered as one, so a retry does not send it twice.\n const message: CommerceModel.QuoteMessage = {\n direction: 'out',\n body: parsed.body,\n atMs: now,\n revision: Math.max(1, Number(stored.quote?.revision ?? 1) || 1),\n by: actor,\n to,\n messageId: done.messageId,\n providerId: done.providerId,\n }\n try {\n await firestore.runTransaction(async (transaction) => {\n const current = await transaction.get(ref)\n const latest = current.exists ? (current.data() as CommerceModel.HostOrder) : null\n transaction.set(ref.collection('messages').doc(createResourceUid()), message)\n if (!latest?.quote) return\n transaction.set(ref, CommerceModel.quoteAfterReply(latest, { to, by: actor, atMs: now }, done.thread))\n })\n } catch (error) {\n console.error('commerce quote reply sent but not recorded', { hostId, quoteId, messageId: done.messageId, error })\n }\n const outcome: Outcome = { status: 200, body: { sent: true, to, atMs: now } }\n await claim.record(outcome.status, outcome.body)\n return outcome\n}\n\n/*------------------------------------------\n * The site: the customer writes on the quote page\n *-----------------------------------------*/\n\n/** The managers' notice of a customer's message: who, which quote, what they said, and how to answer. */\nexport function quoteMessageNotice(input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n body: string\n}) {\n const { hostId, quoteId, order, body } = input\n const quote = order.quote as CommerceModel.OrderQuote\n const number = CommerceModel.formatQuoteNumber(order, quoteId)\n const customer = quote.customer?.name || quote.customer?.company || quote.customer?.email || 'The customer'\n const email = String(quote.customer?.email ?? '').trim()\n const excerpt = body.length > 1_000 ? `${body.slice(0, 1_000)}…` : body\n return {\n payload: {\n type: 'content.order' as const,\n level: 'info' as const,\n label: 'Customer message',\n actionLabel: 'View quote',\n title: `${customer} wrote about ${number} on {site}`,\n body: `${excerpt}\\n\\nReply from the quote, or reply to this email to reach them.`,\n link: `/${hostId}/products/orders?quote=${encodeURIComponent(quoteId)}`,\n },\n options: {\n emailDetails: [\n { label: 'Quote', value: number },\n { label: 'Customer', value: [quote.customer?.name, quote.customer?.company, email].filter(Boolean).join(', ') },\n { label: 'Message', value: excerpt },\n ],\n ...(/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email) ? { replyTo: email } : {}),\n },\n }\n}\n\n/** `POST /api/commerce/quote-message`: the customer writes to the business on the quote page. */\nexport async function handleQuoteMessage(deps: QuoteProofDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome> {\n if (req.method !== 'POST') return { status: 405, body: { error: 'Method not allowed' } }\n const body = bodyOf(req)\n const { hostId, quoteId, token, complete } = quoteLinkParams(body)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n // A form a person fills never fills this; a bot that did learns nothing.\n const honeypot = body[VISITOR_UPLOAD_HONEYPOT_FIELD]\n if (typeof honeypot === 'string' && honeypot.trim()) return { status: 200, body: { received: true } }\n const idempotencyKey = headerOf(req, 'idempotency-key').slice(0, 200)\n if (!idempotencyKey) return { status: 400, body: { error: 'A message needs an Idempotency-Key header.' } }\n const limited = await limitedQuoteLink(deps, req, `commerce-quote-message:${hostId}`, QUOTE_MESSAGES_PER_WINDOW)\n if (limited) return limited\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token)\n if ('outcome' in linked) return linked.outcome\n const { hostRef, order } = linked.loaded\n if (linked.loaded.kind !== 'quote' || !order.quote) return { status: 404, body: { error: 'We could not find that quote. Check the link you were sent.' } }\n // The conversation is about the proof, so it waits on the same sign-in as the proof (AGL-4206).\n if (CommerceModel.currentQuoteProofs(order.quote).length) {\n const access = await quoteProofAccessFor(deps, req, { hostId, host: linked.loaded.host, order })\n if (access !== 'open') return quoteProofAccessRefusal(access, linked.loaded.storeName)\n }\n const parsed = CommerceModel.parseQuoteMessageBody(body['message'])\n if ('error' in parsed) return { status: 400, body: { error: parsed.error } }\n\n const claimed = await claimAttempt(deps.firestore(), {\n kind: 'commerce-quote-message',\n scopeId: `${hostId}:${quoteId}`,\n orgId: '',\n key: idempotencyKey,\n busyMessage: 'Your message is already being sent',\n })\n if ('replay' in claimed) return { status: claimed.replay.status, body: claimed.replay.body as Record<string, unknown> }\n const claim = claimed.claim\n const now = deps.now()\n const ref = hostRef.collection('orders').doc(quoteId)\n const ip = readClientIp(req.headers as never, { remoteAddress: req.socket?.remoteAddress })\n const message: CommerceModel.QuoteMessage = {\n direction: 'in',\n body: parsed.body,\n atMs: now,\n revision: Math.max(1, Number(order.quote.revision ?? 1) || 1),\n name: String(order.quote.customer?.name ?? '').trim() || String(order.quote.customer?.company ?? '').trim(),\n ip: ip ? ip.slice(0, 64) : null,\n userAgent: headerOf(req, 'user-agent').slice(0, 400) || null,\n }\n try {\n await ref.collection('messages').doc(createResourceUid()).set(message)\n } catch (error) {\n console.error('quote message failed', error)\n await claim.release()\n return { status: 500, body: { error: 'Your message could not be sent. Try again.' } }\n }\n const messages = CommerceModel.quotePageMessages(await readQuoteMessages(ref))\n const outcome = { status: 200, body: { messages } as Record<string, unknown> }\n await claim.record(200, outcome.body)\n const notice = quoteMessageNotice({ hostId, quoteId, order, body: parsed.body })\n void deps.notify(hostId, notice.payload, notice.options)\n return outcome\n}\n\n/** `POST /api/commerce/quote-message`. */\nexport const quoteMessageHandler: PluginApiHandler = async (req, res) => {\n try {\n return sendQuoteLinkOutcome(res, await handleQuoteMessage(defaultQuoteProofDeps(), req))\n } catch (error) {\n console.error('quote message failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'Your message could not be sent. Try again.' } })\n }\n}\n"],"names":["createResourceUid","claimAttempt","checkEntitlement","readClientIp","VISITOR_UPLOAD_HONEYPOT_FIELD","CommerceModel","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","quoteProofAccessFor","quoteProofAccessRefusal","sendQuoteLinkOutcome","defaultQuoteProofDeps","refuse","status","error","body","QUOTE_MESSAGES_PER_WINDOW","headerOf","req","name","headers","value","toLowerCase","String","Array","isArray","trim","bodyOf","raw","parsed","JSON","parse","readQuoteMessages","orderRef","listed","collection","orderBy","limit","QUOTE_MESSAGES_SHOWN","get","docs","map","entry","id","data","handleQuoteMessagesAction","deps","context","stored","action","hostId","quoteId","hostRef","host","actor","firestore","ref","doc","snapshot","order","exists","isQuote","quote","messages","quoteConsoleMessages","to","quoteReplyRecipient","parseQuoteMessageBody","idempotencyKey","slice","refused","quoteReplyRefusal","reason","quoteReplyRefusalMessage","url","payLinkUrl","quoteLinkVersion","owner","orgForHost","org","mailer","configured","suppression","claimed","kind","scopeId","orgId","key","busyMessage","replay","claim","now","delivered","deliverMessage","senderEmail","atMs","console","release","done","message","direction","revision","Math","max","Number","by","messageId","providerId","runTransaction","transaction","current","latest","set","quoteAfterReply","thread","outcome","sent","record","quoteMessageNotice","input","number","formatQuoteNumber","customer","company","email","excerpt","length","payload","type","level","label","actionLabel","title","link","encodeURIComponent","options","emailDetails","filter","Boolean","join","test","replyTo","handleQuoteMessage","method","token","complete","honeypot","received","limited","linked","loaded","currentQuoteProofs","access","storeName","ip","remoteAddress","socket","userAgent","quotePageMessages","notice","notify","quoteMessageHandler","res"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,YAAY,QAAsD,sBAAqB;AAChG,SAASC,gBAAgB,QAAQ,sBAAqB;AACtD,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,6BAA6B,QAAQ,wCAAuC;AACrF,YAAYC,mBAAmB,oBAAU;AAGzC,SACEC,gBAAgB,EAChBC,eAAe,EACfC,eAAe,EACfC,mBAAmB,EACnBC,uBAAuB,EACvBC,oBAAoB,QAEf,iBAAa;AACpB,SAASC,qBAAqB,QAA6B,oBAAgB;AAqB3E,MAAMC,SAAS,CAACC,QAAgBC,QAA4B,CAAA;QAAED;QAAQE,MAAM;YAAED;QAAM;IAAE,CAAA;AAEtF,0EAA0E,GAC1E,OAAO,MAAME,4BAA4B,GAAE;AAE3C,SAASC,SAASC,GAAqB,EAAEC,IAAY;QAClCD,cACHE,2BACwBC;IAFtC,MAAMD,WAAWF,eAAAA,IAAIE,OAAO,YAAXF,eAAe,CAAC;IACjC,MAAMG,SAAQD,4BAAAA,OAAO,CAACD,KAAKG,WAAW,GAAG,YAA3BF,4BAA+BA,OAAO,CAACD,KAAK;IAC1D,OAAOI,OAAOC,MAAMC,OAAO,CAACJ,UAAUA,UAAAA,KAAK,CAAC,EAAE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UAAU,CAAC,YAAYsB,GAAG,CAAC1D,qBAAqBiH,GAAG,CAACb;IAChE,EAAE,OAAOrF,OAAO;QACdkF,QAAQlF,KAAK,CAAC,wBAAwBA;QACtC,MAAM4E,MAAMO,OAAO;QACnB,OAAO;YAAEpF,QAAQ;YAAKE,MAAM;gBAAED,OAAO;YAA6C;QAAE;IACtF;IACA,MAAMiD,WAAW3D,cAAc0J,iBAAiB,CAAC,MAAM9H,kBAAkBwB;IACzE,MAAM2D,UAAU;QAAEtG,QAAQ;QAAKE,MAAM;YAAEgD;QAAS;IAA6B;IAC7E,MAAM2B,MAAM2B,MAAM,CAAC,KAAKF,QAAQpG,IAAI;IACpC,MAAMgJ,SAASzC,mBAAmB;QAAEpE;QAAQC;QAASQ;QAAO5C,MAAMc,OAAOd,IAAI;IAAC;IAC9E,KAAK+B,KAAKkH,MAAM,CAAC9G,QAAQ6G,OAAOhC,OAAO,EAAEgC,OAAOxB,OAAO;IACvD,OAAOpB;AACT;AAEA,wCAAwC,GACxC,OAAO,MAAM8C,sBAAwC,OAAO/I,KAAKgJ;IAC/D,IAAI;QACF,OAAOxJ,qBAAqBwJ,KAAK,MAAMpB,mBAAmBnI,yBAAyBO;IACrF,EAAE,OAAOJ,OAAO;QACdkF,QAAQlF,KAAK,CAAC,wBAAwBA;QACtC,OAAOJ,qBAAqBwJ,KAAK;YAAErJ,QAAQ;YAAKE,MAAM;gBAAED,OAAO;YAA6C;QAAE;IAChH;AACF,EAAC"}
@@ -63,8 +63,48 @@ export interface QuotePayDeps {
63
63
  sellerTaxActive?(accountId: string): Promise<boolean>;
64
64
  /** Registers the page's domain for Apple Pay; never throws. */
65
65
  ensureDomain(input: Parameters<typeof ensureCheckoutDomain>[0]): Promise<unknown>;
66
+ /**
67
+ * The site account a quote's customer signs in to (AGL-4206): the member
68
+ * under that address, on a site that serves accounts; null for a guest.
69
+ * Absent, every customer reads as a guest.
70
+ */
71
+ customerAccount?(input: {
72
+ hostId: string;
73
+ host: Record<string, unknown>;
74
+ email: string;
75
+ }): Promise<QuoteCustomerAccount | null>;
66
76
  now(): number;
67
77
  }
78
+ /** A quote customer's account on the site, as the sign-in check needs it. */
79
+ export interface QuoteCustomerAccount {
80
+ id: string;
81
+ /** Sessions minted before this were revoked in bulk (AGL-914). */
82
+ validFromMs: number;
83
+ suspended: boolean;
84
+ }
85
+ /**
86
+ * The member under `email` on a site that serves accounts, or null. A site
87
+ * with User Accounts switched off has no sign-in page to send anyone to, so
88
+ * every customer of it is a guest.
89
+ */
90
+ export declare function readQuoteCustomerAccount(input: {
91
+ hostId: string;
92
+ host: Record<string, unknown>;
93
+ email: string;
94
+ }): Promise<QuoteCustomerAccount | null>;
95
+ /**
96
+ * Whether this request may see the quote's proof and answer it (AGL-4206):
97
+ * `open` unless the quote asks a customer with a site account to sign in and
98
+ * this browser is not signed in to that account. Reads nothing for a quote
99
+ * that does not ask, or a customer with no address.
100
+ */
101
+ export declare function quoteProofAccessFor(deps: QuotePayDeps, req: PluginApiRequest, input: {
102
+ hostId: string;
103
+ host: Record<string, unknown>;
104
+ order: CommerceModel.HostOrder;
105
+ }): Promise<CommerceModel.QuoteProofAccess>;
106
+ /** A proof route's answer while the proof waits on a sign-in. */
107
+ export declare function quoteProofAccessRefusal(access: Exclude<CommerceModel.QuoteProofAccess, 'open'>, storeName: string): QuoteLinkOutcome;
68
108
  export declare function defaultQuotePayDeps(): QuotePayDeps;
69
109
  /** A link route's answer: a status, a JSON body and any extra headers. */
70
110
  export type QuoteLinkOutcome = {
@@ -143,6 +183,8 @@ export declare function payLinkPageView(deps: QuotePayDeps, input: {
143
183
  hostId: string;
144
184
  orderId: string;
145
185
  loaded: Pick<LoadedQuote, 'host' | 'order' | 'storeName' | 'store' | 'kind'>;
186
+ /** Whether this browser may see the proof (AGL-4206); absent reads as `open`. */
187
+ proofAccess?: CommerceModel.QuoteProofAccess;
146
188
  }): Promise<CommerceModel.QuotePageView>;
147
189
  /** `GET /api/commerce/quote-view`: the quote page's data. */
148
190
  export declare function handleQuoteView(deps: QuotePayDeps, req: PluginApiRequest): Promise<QuoteLinkOutcome>;
@@ -14,7 +14,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
14
14
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
- */ import { checkEntitlement, claimAttempt, deriveStripeObjectKey, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
17
+ */ import { ACCOUNTS_PLUGIN_ID, checkEntitlement, claimAttempt, deriveStripeObjectKey, resolveHostEnabledPlugins, resolveTransactionFeeCents } from "@aglyn/aglyn/server";
18
18
  import { resolveHostToken } from "@aglyn/aglyn/app-utils/host-tokens";
19
19
  import { readClientIp } from "@aglyn/aglyn/app-utils/request-ip";
20
20
  import { siteReturnOrigin } from "@aglyn/aglyn/app-utils/site-return-url";
@@ -27,6 +27,7 @@ import { expireCheckoutSession } from "./checkout-session-expiry.js";
27
27
  import { resolveManualTaxRateId } from "./manual-tax-rate.js";
28
28
  import { applyNativeCheckoutParams, nativeCheckoutStripeHeaders, readCheckoutSessionPayload, resolveNativeCheckoutMode } from "./native-checkout.js";
29
29
  import { orderStatusUrl } from "./order-status-token.js";
30
+ import { MEMBER_SESSIONS_VALID_FROM_FIELD, memberCookieName, parseMemberSession } from "./membership.js";
30
31
  import { ensureCheckoutDomain } from "./payment-method-domains.js";
31
32
  import { verifyQuoteLinkToken } from "./quote-link-token.js";
32
33
  import { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from "./seller-stripe-account.js";
@@ -75,6 +76,58 @@ import { SELLER_STRIPE_TAX_NOT_SET_UP_MESSAGE, sellerStripeTaxActive } from "./s
75
76
  *=========================================*/ /** Lookups and presses one address may make per site, per ten minutes. */ export const QUOTE_VIEW_LOOKUPS_PER_WINDOW = 60;
76
77
  export const QUOTE_PAY_PRESSES_PER_WINDOW = 20;
77
78
  export const QUOTE_WINDOW_MS = 10 * 60000;
79
+ /**
80
+ * The member under `email` on a site that serves accounts, or null. A site
81
+ * with User Accounts switched off has no sign-in page to send anyone to, so
82
+ * every customer of it is a guest.
83
+ */ export async function readQuoteCustomerAccount(input) {
84
+ var _member_get;
85
+ const owner = await getOrgForHost(input.hostId);
86
+ if (!owner || !resolveHostEnabledPlugins(owner.org, input.host).includes(ACCOUNTS_PLUGIN_ID)) return null;
87
+ const found = await firebaseAdmin.app().firestore().collection('hosts').doc(input.hostId).collection('siteMembers').where('email', '==', input.email).limit(1).get();
88
+ const member = found.docs[0];
89
+ if (!member) return null;
90
+ return {
91
+ id: member.id,
92
+ validFromMs: Number((_member_get = member.get(MEMBER_SESSIONS_VALID_FROM_FIELD)) != null ? _member_get : 0) || 0,
93
+ suspended: member.get('suspended') === true
94
+ };
95
+ }
96
+ /**
97
+ * Whether this request may see the quote's proof and answer it (AGL-4206):
98
+ * `open` unless the quote asks a customer with a site account to sign in and
99
+ * this browser is not signed in to that account. Reads nothing for a quote
100
+ * that does not ask, or a customer with no address.
101
+ */ export async function quoteProofAccessFor(deps, req, input) {
102
+ var _req_cookies, _ref, _ref1;
103
+ const quote = input.order.quote;
104
+ if ((quote == null ? void 0 : quote.requireProofSignIn) !== true) return 'open';
105
+ const email = CommerceModel.quoteCustomerAccountEmail(quote);
106
+ if (!email) return 'open';
107
+ const account = deps.customerAccount ? await deps.customerAccount({
108
+ hostId: input.hostId,
109
+ host: input.host,
110
+ email
111
+ }) : null;
112
+ const cookies = (_req_cookies = req.cookies) != null ? _req_cookies : {};
113
+ const session = parseMemberSession(input.hostId, cookies[memberCookieName(input.hostId)]);
114
+ // A session for the customer's account counts only while the account stands and the session was not revoked.
115
+ const signedIn = session && account && session.memberId === account.id && (account.suspended || session.issuedAtMs < account.validFromMs) ? null : (_ref = session == null ? void 0 : session.memberId) != null ? _ref : null;
116
+ return CommerceModel.quoteProofAccess({
117
+ quote,
118
+ accountId: (_ref1 = account == null ? void 0 : account.id) != null ? _ref1 : null,
119
+ signedInAccountId: signedIn
120
+ });
121
+ }
122
+ /** A proof route's answer while the proof waits on a sign-in. */ export function quoteProofAccessRefusal(access, storeName) {
123
+ return {
124
+ status: 403,
125
+ body: {
126
+ error: CommerceModel.quoteProofAccessMessage(access, storeName),
127
+ reason: access
128
+ }
129
+ };
130
+ }
78
131
  export function defaultQuotePayDeps() {
79
132
  return {
80
133
  firestore: ()=>firebaseAdmin.app().firestore(),
@@ -104,6 +157,7 @@ export function defaultQuotePayDeps() {
104
157
  },
105
158
  expireSession: (sessionId, stripeAccount)=>stripeAccount ? expireConnectedCheckoutSession(sessionId, stripeAccount) : expireCheckoutSession(sessionId),
106
159
  ensureDomain: (input)=>ensureCheckoutDomain(input).catch(()=>null),
160
+ customerAccount: (input)=>readQuoteCustomerAccount(input),
107
161
  now: ()=>Date.now()
108
162
  };
109
163
  }
@@ -307,7 +361,7 @@ function headerOf(req, name) {
307
361
  * priced under the store's tax choice and with Pay only where the business
308
362
  * can take it. A paid one asks nothing about payments.
309
363
  */ export async function payLinkPageView(deps, input) {
310
- var _store_get;
364
+ var _store_get, _input_proofAccess;
311
365
  const { hostId, orderId } = input;
312
366
  const { host, order, storeName, store, kind } = input.loaded;
313
367
  const currency = String((_store_get = store.get('currency')) != null ? _store_get : 'USD');
@@ -329,7 +383,24 @@ function headerOf(req, name) {
329
383
  }),
330
384
  paymentsReady
331
385
  };
332
- return kind === 'quote' ? CommerceModel.buildQuotePageView(view) : CommerceModel.buildInvoicePageView(view);
386
+ if (kind !== 'quote') return CommerceModel.buildInvoicePageView(view);
387
+ const proofAccess = (_input_proofAccess = input.proofAccess) != null ? _input_proofAccess : 'open';
388
+ // The quote's conversation rides its page (AGL-4207), an answer's view too; it waits on
389
+ // the same sign-in as the proof, so it is not read for a page that will not show it.
390
+ let messages = [];
391
+ if (proofAccess === 'open' || CommerceModel.currentQuoteProofs(order.quote).length === 0) {
392
+ const orderRef = deps.firestore().collection('hosts').doc(hostId).collection('orders').doc(orderId);
393
+ const listed = await orderRef.collection('messages').orderBy('atMs', 'desc').limit(CommerceModel.QUOTE_MESSAGES_SHOWN).get();
394
+ messages = CommerceModel.quotePageMessages(listed.docs.map((entry)=>({
395
+ id: entry.id,
396
+ data: entry.data()
397
+ })));
398
+ }
399
+ return CommerceModel.buildQuotePageView(_extends({}, view, {
400
+ messages,
401
+ approvalStatements: CommerceModel.quoteApprovalStatements(store.get('quotes')),
402
+ proofAccess
403
+ }));
333
404
  }
334
405
  /** `GET /api/commerce/quote-view`: the quote page's data. */ export async function handleQuoteView(deps, req) {
335
406
  var _req_query;
@@ -367,10 +438,16 @@ function headerOf(req, name) {
367
438
  }
368
439
  return linked.outcome;
369
440
  }
441
+ const proofAccess = linked.loaded.kind === 'quote' ? await quoteProofAccessFor(deps, req, {
442
+ hostId,
443
+ host: linked.loaded.host,
444
+ order: linked.loaded.order
445
+ }) : 'open';
370
446
  const view = await payLinkPageView(deps, {
371
447
  hostId,
372
448
  orderId: quoteId,
373
- loaded: linked.loaded
449
+ loaded: linked.loaded,
450
+ proofAccess
374
451
  });
375
452
  return {
376
453
  status: 200,