@aglyn/plugins-commerce 1.15.2 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/README.md +1 -1
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +2 -1
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/console/payments-settings-card.component.js +6 -1
  6. package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
  7. package/src/lib/components/console/pos/pos-api.d.ts +5 -0
  8. package/src/lib/components/console/pos/pos-api.js.map +1 -1
  9. package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
  10. package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
  11. package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
  12. package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
  13. package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
  14. package/src/lib/components/console/pos-cellular-control.component.d.ts +5 -0
  15. package/src/lib/components/console/pos-cellular-control.component.js +29 -15
  16. package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
  17. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  18. package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
  19. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  20. package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
  21. package/src/lib/components/console/product-builder-fields.component.js +195 -0
  22. package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
  23. package/src/lib/components/console/product-editor-dialog.component.js +35 -2
  24. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  25. package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
  26. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  27. package/src/lib/components/console/quote-messages.component.d.ts +21 -0
  28. package/src/lib/components/console/quote-messages.component.js +185 -0
  29. package/src/lib/components/console/quote-messages.component.js.map +1 -0
  30. package/src/lib/components/console/quote-pay-link.component.js +1 -1
  31. package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
  32. package/src/lib/components/console/quote-proofs.component.js +30 -3
  33. package/src/lib/components/console/quote-proofs.component.js.map +1 -1
  34. package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
  35. package/src/lib/components/console/quote-settings-card.component.js +154 -24
  36. package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
  37. package/src/lib/components/product-builder-context.d.ts +22 -0
  38. package/src/lib/components/product-builder-context.js +21 -0
  39. package/src/lib/components/product-builder-context.js.map +1 -0
  40. package/src/lib/components/product-builder-mockup.d.ts +42 -0
  41. package/src/lib/components/product-builder-mockup.js +120 -0
  42. package/src/lib/components/product-builder-mockup.js.map +1 -0
  43. package/src/lib/components/product-builder-sample.d.ts +63 -0
  44. package/src/lib/components/product-builder-sample.js +96 -0
  45. package/src/lib/components/product-builder-sample.js.map +1 -0
  46. package/src/lib/components/product-choice-cards.d.ts +51 -0
  47. package/src/lib/components/product-choice-cards.js +311 -0
  48. package/src/lib/components/product-choice-cards.js.map +1 -0
  49. package/src/lib/components/product-detail-panels.d.ts +42 -0
  50. package/src/lib/components/product-detail-panels.js +185 -0
  51. package/src/lib/components/product-detail-panels.js.map +1 -0
  52. package/src/lib/components/product-detail.d.ts +20 -12
  53. package/src/lib/components/product-detail.js +136 -221
  54. package/src/lib/components/product-detail.js.map +1 -1
  55. package/src/lib/components/product-grid.d.ts +7 -0
  56. package/src/lib/components/product-grid.js +13 -9
  57. package/src/lib/components/product-grid.js.map +1 -1
  58. package/src/lib/components/product-name-lines.d.ts +37 -0
  59. package/src/lib/components/product-name-lines.js +36 -0
  60. package/src/lib/components/product-name-lines.js.map +1 -0
  61. package/src/lib/components/product-options-field-body.d.ts +9 -8
  62. package/src/lib/components/product-options-field-body.js +152 -3
  63. package/src/lib/components/product-options-field-body.js.map +1 -1
  64. package/src/lib/components/product-options-field.js +1 -1
  65. package/src/lib/components/product-options-field.js.map +1 -1
  66. package/src/lib/components/product-photo-fit.d.ts +49 -0
  67. package/src/lib/components/product-photo-fit.js +58 -0
  68. package/src/lib/components/product-photo-fit.js.map +1 -0
  69. package/src/lib/components/product-restock-notify.d.ts +12 -0
  70. package/src/lib/components/product-restock-notify.js +86 -0
  71. package/src/lib/components/product-restock-notify.js.map +1 -0
  72. package/src/lib/components/quote-messages-panel.d.ts +21 -0
  73. package/src/lib/components/quote-messages-panel.js +191 -0
  74. package/src/lib/components/quote-messages-panel.js.map +1 -0
  75. package/src/lib/components/quote-page-body.js +15 -1
  76. package/src/lib/components/quote-page-body.js.map +1 -1
  77. package/src/lib/components/quote-proof-panel.d.ts +6 -3
  78. package/src/lib/components/quote-proof-panel.js +139 -14
  79. package/src/lib/components/quote-proof-panel.js.map +1 -1
  80. package/src/lib/components/related-products.d.ts +7 -0
  81. package/src/lib/components/related-products.js +10 -7
  82. package/src/lib/components/related-products.js.map +1 -1
  83. package/src/lib/constants/quote-page.d.ts +8 -0
  84. package/src/lib/constants/quote-page.js +11 -0
  85. package/src/lib/constants/quote-page.js.map +1 -1
  86. package/src/lib/model/commerce-cart.d.ts +6 -1
  87. package/src/lib/model/commerce-cart.js +5 -1
  88. package/src/lib/model/commerce-cart.js.map +1 -1
  89. package/src/lib/model/commerce-invoices.js +5 -1
  90. package/src/lib/model/commerce-invoices.js.map +1 -1
  91. package/src/lib/model/commerce-pos-ops.d.ts +3 -0
  92. package/src/lib/model/commerce-pos-ops.js +3 -0
  93. package/src/lib/model/commerce-pos-ops.js.map +1 -1
  94. package/src/lib/model/commerce-pos.d.ts +8 -0
  95. package/src/lib/model/commerce-pos.js.map +1 -1
  96. package/src/lib/model/commerce-quote-messages.d.ts +106 -0
  97. package/src/lib/model/commerce-quote-messages.js +146 -0
  98. package/src/lib/model/commerce-quote-messages.js.map +1 -0
  99. package/src/lib/model/commerce-quote-pay.d.ts +31 -2
  100. package/src/lib/model/commerce-quote-pay.js +31 -7
  101. package/src/lib/model/commerce-quote-pay.js.map +1 -1
  102. package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
  103. package/src/lib/model/commerce-quote-proofs.js +73 -18
  104. package/src/lib/model/commerce-quote-proofs.js.map +1 -1
  105. package/src/lib/model/commerce-quote-request.d.ts +14 -4
  106. package/src/lib/model/commerce-quote-request.js +25 -2
  107. package/src/lib/model/commerce-quote-request.js.map +1 -1
  108. package/src/lib/model/commerce-quotes.d.ts +56 -3
  109. package/src/lib/model/commerce-quotes.js +47 -2
  110. package/src/lib/model/commerce-quotes.js.map +1 -1
  111. package/src/lib/model/commerce.d.ts +12 -1
  112. package/src/lib/model/commerce.js.map +1 -1
  113. package/src/lib/model/index.d.ts +1 -0
  114. package/src/lib/model/index.js +1 -0
  115. package/src/lib/model/index.js.map +1 -1
  116. package/src/lib/model/pos-cellular.d.ts +36 -4
  117. package/src/lib/model/pos-cellular.js +39 -4
  118. package/src/lib/model/pos-cellular.js.map +1 -1
  119. package/src/lib/model/product-card-rules.d.ts +41 -0
  120. package/src/lib/model/product-card-rules.js +90 -0
  121. package/src/lib/model/product-card-rules.js.map +1 -0
  122. package/src/lib/model/product-modifiers.d.ts +11 -0
  123. package/src/lib/model/product-modifiers.js +10 -0
  124. package/src/lib/model/product-modifiers.js.map +1 -1
  125. package/src/lib/model/product-write.d.ts +3 -0
  126. package/src/lib/server/billing-webhook.js +6 -2
  127. package/src/lib/server/billing-webhook.js.map +1 -1
  128. package/src/lib/server/cancel-order.js +15 -0
  129. package/src/lib/server/cancel-order.js.map +1 -1
  130. package/src/lib/server/channel-order-updates.js +15 -1
  131. package/src/lib/server/channel-order-updates.js.map +1 -1
  132. package/src/lib/server/channel-orders.js +20 -0
  133. package/src/lib/server/channel-orders.js.map +1 -1
  134. package/src/lib/server/checkout.js +1 -1
  135. package/src/lib/server/checkout.js.map +1 -1
  136. package/src/lib/server/local-fulfillment.js +1 -1
  137. package/src/lib/server/local-fulfillment.js.map +1 -1
  138. package/src/lib/server/pos-cellular-billing.d.ts +5 -4
  139. package/src/lib/server/pos-cellular-billing.js +24 -12
  140. package/src/lib/server/pos-cellular-billing.js.map +1 -1
  141. package/src/lib/server/pos-cellular.d.ts +3 -1
  142. package/src/lib/server/pos-cellular.js +55 -33
  143. package/src/lib/server/pos-cellular.js.map +1 -1
  144. package/src/lib/server/pos-offline-sync.d.ts +3 -3
  145. package/src/lib/server/pos-offline-sync.js +17 -4
  146. package/src/lib/server/pos-offline-sync.js.map +1 -1
  147. package/src/lib/server/pos-order.js +17 -6
  148. package/src/lib/server/pos-order.js.map +1 -1
  149. package/src/lib/server/pos-payment.js +27 -11
  150. package/src/lib/server/pos-payment.js.map +1 -1
  151. package/src/lib/server/pos-reader-splash.js +10 -5
  152. package/src/lib/server/pos-reader-splash.js.map +1 -1
  153. package/src/lib/server/pos-readers.js +42 -12
  154. package/src/lib/server/pos-readers.js.map +1 -1
  155. package/src/lib/server/pos-return.js +19 -3
  156. package/src/lib/server/pos-return.js.map +1 -1
  157. package/src/lib/server/pos-stripe.d.ts +14 -0
  158. package/src/lib/server/pos-stripe.js +6 -2
  159. package/src/lib/server/pos-stripe.js.map +1 -1
  160. package/src/lib/server/pos-terminal-connection-token.js +23 -9
  161. package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
  162. package/src/lib/server/pos-terminal.d.ts +80 -14
  163. package/src/lib/server/pos-terminal.js +393 -123
  164. package/src/lib/server/pos-terminal.js.map +1 -1
  165. package/src/lib/server/product-drafts.d.ts +1 -1
  166. package/src/lib/server/product-drafts.js +4 -3
  167. package/src/lib/server/product-drafts.js.map +1 -1
  168. package/src/lib/server/product-writer.js +5 -4
  169. package/src/lib/server/product-writer.js.map +1 -1
  170. package/src/lib/server/product.d.ts +11 -0
  171. package/src/lib/server/product.js +18 -3
  172. package/src/lib/server/product.js.map +1 -1
  173. package/src/lib/server/products-write.js +4 -3
  174. package/src/lib/server/products-write.js.map +1 -1
  175. package/src/lib/server/quote-email.d.ts +26 -0
  176. package/src/lib/server/quote-email.js +73 -7
  177. package/src/lib/server/quote-email.js.map +1 -1
  178. package/src/lib/server/quote-messages.d.ts +72 -0
  179. package/src/lib/server/quote-messages.js +356 -0
  180. package/src/lib/server/quote-messages.js.map +1 -0
  181. package/src/lib/server/quote-pay.d.ts +42 -0
  182. package/src/lib/server/quote-pay.js +81 -4
  183. package/src/lib/server/quote-pay.js.map +1 -1
  184. package/src/lib/server/quote-proofs.d.ts +1 -1
  185. package/src/lib/server/quote-proofs.js +63 -19
  186. package/src/lib/server/quote-proofs.js.map +1 -1
  187. package/src/lib/server/quote.d.ts +12 -0
  188. package/src/lib/server/quote.js +69 -16
  189. package/src/lib/server/quote.js.map +1 -1
  190. package/src/lib/server/refund.js +3 -1
  191. package/src/lib/server/refund.js.map +1 -1
  192. package/src/lib/server/reserve-stock.js +9 -0
  193. package/src/lib/server/reserve-stock.js.map +1 -1
  194. package/src/lib/server/returns.js +15 -1
  195. package/src/lib/server/returns.js.map +1 -1
  196. package/src/lib/server/reviews.js +15 -0
  197. package/src/lib/server/reviews.js.map +1 -1
  198. package/src/lib/server/sold-out-drop.d.ts +58 -0
  199. package/src/lib/server/sold-out-drop.js +81 -0
  200. package/src/lib/server/sold-out-drop.js.map +1 -0
  201. package/src/lib/server/stock-levels.js +9 -0
  202. package/src/lib/server/stock-levels.js.map +1 -1
  203. package/src/lib/server/stripe-refund.d.ts +7 -0
  204. package/src/lib/server/stripe-refund.js +26 -7
  205. package/src/lib/server/stripe-refund.js.map +1 -1
  206. package/src/lib/server.d.ts +15 -0
  207. package/src/lib/server.js +30 -1
  208. package/src/lib/server.js.map +1 -1
  209. package/src/lib/tenant-emails.js +85 -2
  210. package/src/lib/tenant-emails.js.map +1 -1
  211. package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
  212. package/src/lib/testing/fake-seller-payment-account.js +40 -0
  213. package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
  214. package/src/lib/transfer/product-transfer.js +6 -5
  215. package/src/lib/transfer/product-transfer.js.map +1 -1
  216. package/src/lib/transfer/products.server.js +4 -3
  217. package/src/lib/transfer/products.server.js.map +1 -1
  218. package/src/lib/utils/quote-email-content.d.ts +6 -0
  219. package/src/lib/utils/quote-email-content.js +6 -3
  220. package/src/lib/utils/quote-email-content.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/reviews.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { AggregateField } from 'firebase-admin/firestore'\nimport {\n MEMBER_SUSPENDED_ERROR,\n readActiveMemberSession,\n type MemberSessionCheck,\n} from './membership'\nimport { inspectReviewToken, redeemReviewTokenIn } from './review-tokens'\n\nexport interface PublicProductReview {\n id: string\n rating: number\n body: string\n authorName: string\n verified: boolean\n reply: string | null\n createdAtMs: number\n}\n\nexport interface ProductReviewAggregate {\n count: number\n /** Mean rating, one decimal. */\n average: number\n}\n\n/**\n * Approved reviews for a product, newest first, plus their aggregate.\n *\n * Extracted from the handler (AGL-686) so the site-page resolver can nest\n * `aggregateRating` inside the server-rendered `Product` node. Schema.org\n * wants it as a PROPERTY of the product; the reviews block was emitting a\n * free-standing `AggregateRating` node alongside it, which is orphaned and\n * ignored. One reader means the rating in the structured data and the rating\n * on the page cannot disagree.\n */\nexport async function readProductReviews(\n hostId: string,\n productId: string,\n): Promise<{\n reviews: PublicProductReview[]\n aggregate: ProductReviewAggregate\n}> {\n const hostRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n const reviewsSnapshot = await hostRef\n .collection('reviews')\n .where('productId', '==', productId)\n .where('status', '==', 'approved')\n .limit(100)\n .get()\n const reviews = reviewsSnapshot.docs\n .map((docSnapshot) => ({\n id: docSnapshot.id,\n rating: Number(docSnapshot.get('rating') ?? 0),\n body: String(docSnapshot.get('body') ?? ''),\n authorName: String(docSnapshot.get('authorName') ?? 'Anonymous'),\n verified: Boolean(docSnapshot.get('verified')),\n reply: (docSnapshot.get('reply') as string | undefined) ?? null,\n createdAtMs: Number(docSnapshot.get('createdAtMs') ?? 0),\n }))\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n const count = reviews.length\n const average = count\n ? reviews.reduce((sum, review) => sum + review.rating, 0) / count\n : 0\n return {\n reviews,\n aggregate: { count, average: Math.round(average * 10) / 10 },\n }\n}\n\n/** One approved review as the store-wide list shows it. */\nexport interface PublicStoreReview {\n id: string\n rating: number\n body: string\n /** First name and last initial only (\"Jane D.\"), never the full name. */\n authorName: string\n verified: boolean\n createdAtMs: number\n /** The reviewed product, when it is still on sale. */\n productName?: string\n /** Its page, when it is sold online; a product sold in person only has none. */\n productSlug?: string\n /**\n * The product is sold in person only and the store shows its reviews\n * (AGL-4060): the band marks it \"Sold in store\" and links nowhere.\n */\n soldInStore?: true\n}\n\n/** The most reviews the store-wide list returns. */\nexport const STORE_REVIEWS_MAX = 12\n/** What the store-wide list returns when the caller names no limit. */\nexport const STORE_REVIEWS_DEFAULT = 6\n\n/** \"Jane Doe\" → \"Jane D.\"; one word stays as it is. */\nexport function reviewerShortName(name: string): string {\n const words = String(name ?? '').trim().split(/\\s+/).filter(Boolean)\n if (!words.length) return 'Anonymous'\n const [first, ...others] = words\n const last = others[others.length - 1]\n return last ? `${first} ${last[0].toUpperCase()}.` : first\n}\n\n/** The most products a store may keep its in-store reviews off the site for, read at once. */\nexport const HIDDEN_REVIEW_PRODUCTS_MAX = 500\n/** How many pages of the newest reviews the band reads to fill itself past hidden ones. */\nconst STORE_REVIEWS_PAGES = 4\n/** Firestore's ceiling on the values of one `in` filter. */\nconst IN_FILTER_MAX = 30\n\n/**\n * The products sold in person only whose reviews the store keeps off the site\n * (AGL-4060, `inStoreReviews: 'hide'`). Two equalities, which Firestore\n * serves from its automatic single-field indexes.\n */\nexport async function readHiddenReviewProductIds(\n hostRef: FirebaseFirestore.DocumentReference,\n): Promise<Set<string>> {\n const snapshot = await hostRef\n .collection('products')\n .where('sellOnline', '==', false)\n .where('inStoreReviews', '==', 'hide')\n .limit(HIDDEN_REVIEW_PRODUCTS_MAX)\n .get()\n return new Set(snapshot.docs.map((doc) => doc.id))\n}\n\n/**\n * The store's latest APPROVED reviews across every product, newest first, with\n * the aggregate over all of them — the store-wide reviews band a storefront\n * home carries. Approved only: a pending or rejected review never reaches a\n * page, and nothing here is ever sample text (a published page shows real\n * reviews or none).\n *\n * A product sold in person only (AGL-4060) shows its reviews here by default,\n * named, marked `soldInStore` and never linked, since it has no page; one\n * whose store chose to hide them (`inStoreReviews: 'hide'`) is in neither the\n * list nor the aggregate.\n *\n * The list is `status == approved` ordered by `createdAtMs desc`, served by\n * the COLLECTION composite `reviews (status ASC, createdAtMs DESC)` that the\n * moderation queue already declares, read a page at a time past hidden ones;\n * the aggregate is a count and a sum over the same equality, less the hidden\n * products' (`productId in …`, at most 30 at a time).\n */\nexport async function readStoreReviews(\n hostId: string,\n limit: number = STORE_REVIEWS_DEFAULT,\n): Promise<{ reviews: PublicStoreReview[]; aggregate: ProductReviewAggregate }> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const approved = hostRef.collection('reviews').where('status', '==', 'approved')\n const max = Math.min(STORE_REVIEWS_MAX, Math.max(1, Math.floor(Number(limit)) || STORE_REVIEWS_DEFAULT))\n const hidden = await readHiddenReviewProductIds(hostRef)\n const hiddenIds = [...hidden]\n const tally = { count: AggregateField.count(), sum: AggregateField.sum('rating') }\n const aggregates = Promise.all([\n approved.aggregate(tally).get(),\n ...Array.from({ length: Math.ceil(hiddenIds.length / IN_FILTER_MAX) }, (_, chunk) =>\n approved\n .where('productId', 'in', hiddenIds.slice(chunk * IN_FILTER_MAX, (chunk + 1) * IN_FILTER_MAX))\n .aggregate(tally)\n .get(),\n ),\n ])\n\n // The newest approved reviews, a page at a time, past any the store hides.\n const docs: FirebaseFirestore.QueryDocumentSnapshot[] = []\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (let page = 0; page < STORE_REVIEWS_PAGES && docs.length < max; page += 1) {\n let query = approved.orderBy('createdAtMs', 'desc')\n if (after) query = query.startAfter(after)\n const snapshot = await query.limit(max).get()\n docs.push(...snapshot.docs.filter((doc) => !hidden.has(String(doc.get('productId') ?? ''))))\n if (snapshot.docs.length < max || !hidden.size) break\n after = snapshot.docs[snapshot.docs.length - 1]\n }\n const rows = docs.slice(0, max).map((docSnapshot) => ({\n id: docSnapshot.id,\n productId: String(docSnapshot.get('productId') ?? ''),\n rating: Number(docSnapshot.get('rating') ?? 0),\n body: String(docSnapshot.get('body') ?? ''),\n authorName: reviewerShortName(String(docSnapshot.get('authorName') ?? '')),\n verified: Boolean(docSnapshot.get('verified')),\n createdAtMs: Number(docSnapshot.get('createdAtMs') ?? 0),\n }))\n // The reviewed products, in one batched read of at most `max` docs.\n const productIds = [...new Set(rows.map((row) => row.productId).filter(Boolean))]\n const products = new Map<string, { name: string; slug: string | null; online: CommerceModel.ProductReviewsOnline }>()\n if (productIds.length) {\n const snapshots = await firestore.getAll(\n ...productIds.map((id) => hostRef.collection('products').doc(id)),\n )\n for (const snapshot of snapshots) {\n const data = snapshot.exists ? (snapshot.data() as Record<string, unknown>) : null\n const online = CommerceModel.productReviewsOnline(data)\n // A draft or a deleted product is named nowhere, as before.\n if (!online) continue\n products.set(snapshot.id, {\n name: String(data['name'] ?? ''),\n // Sold in person only: no page to link to.\n slug: online === 'listed' ? String(data['slug'] ?? '') : null,\n online,\n })\n }\n }\n const reviews = rows\n // A product hidden since the list was read is still never shown.\n .filter((row) => products.get(row.productId)?.online !== 'hidden')\n .map(({ productId, ...row }) => {\n const product = products.get(productId)\n return {\n ...row,\n ...(product?.name ? { productName: product.name } : {}),\n ...(product?.slug ? { productSlug: product.slug } : {}),\n ...(product?.online === 'sold-in-store' ? { soldInStore: true as const } : {}),\n }\n })\n const [all, ...hiddenTallies] = await aggregates\n const counted = (snapshot: { data: () => unknown }) => {\n const data = snapshot.data() as { count?: number; sum?: number | null }\n return { count: Number(data.count ?? 0), sum: Number(data.sum ?? 0) }\n }\n const total = counted(all)\n for (const tallied of hiddenTallies.map(counted)) {\n total.count -= tallied.count\n total.sum -= tallied.sum\n }\n const count = Math.max(0, total.count)\n const average = count ? total.sum / count : 0\n return { reviews, aggregate: { count, average: Math.round(average * 10) / 10 } }\n}\n\n/** Reviews one address may submit per site, per hour (AGL-3736). */\nexport const REVIEW_POSTS_PER_IP_PER_HOUR = 10\n/** Reviews one signed-in member may submit per site, per day. */\nexport const REVIEW_POSTS_PER_MEMBER_PER_DAY = 10\nconst HOUR_MS = 60 * 60 * 1000\n\n/**\n * The address a signed-in member has PROVEN they own, or `''`.\n *\n * A site member signs up by typing an email nobody checks, so the address on\n * the member document alone would let anyone register with a buyer's address\n * and collect a \"Verified buyer\" badge on their purchases. Only a member\n * whose inbox has answered — `emailVerifiedAtMs`, stamped when they complete\n * a password reset from the emailed link or redeem a review link while signed\n * in — counts.\n */\nexport function memberProvenEmail(\n member: FirebaseFirestore.DocumentSnapshot | null | undefined,\n): string {\n if (!member?.exists) return ''\n if (!Number(member.get('emailVerifiedAtMs') ?? 0)) return ''\n return String(member.get('email') ?? '').trim().toLowerCase()\n}\n\n/** The first order under `email` that still entitles `productId`, or null. */\nexport async function entitlingOrderId(\n hostRef: FirebaseFirestore.DocumentReference,\n email: string,\n productId: string,\n): Promise<string | null> {\n if (!email) return null\n // By the member's email, as the account page matches order history.\n const orders = await hostRef\n .collection('orders')\n .where('customerEmail', '==', email)\n .limit(25)\n .get()\n for (const docSnapshot of orders.docs) {\n const order = CommerceModel.liftLegacyOrder(docSnapshot.data() as any)\n // The shared entitlement test (AGL-2454): a line refunded by name is\n // goods the buyer no longer has.\n if (CommerceModel.orderEntitlesProduct(order, productId)) return docSnapshot.id\n }\n return null\n}\n\n/** A store's review settings, from `settings/store`. */\nasync function readReviewSettings(\n hostRef: FirebaseFirestore.DocumentReference,\n): Promise<CommerceModel.ReviewSettings> {\n const snapshot = await hostRef\n .collection('settings')\n .doc('store')\n .get()\n .catch(() => null)\n return CommerceModel.reviewSettingsFrom(snapshot?.data?.() ?? null)\n}\n\ntype ReviewsRequest = Parameters<PluginApiHandler>[0]\ntype ReviewsResponse = Parameters<PluginApiHandler>[1]\n\nfunction clientIp(req: ReviewsRequest): string {\n return (\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n 'no-address'\n )\n}\n\n/** What the server established about who is reviewing. */\ninterface ReviewerIdentity {\n signedIn: boolean\n suspended: boolean\n memberId: string | null\n memberEmail: string\n memberName: string\n /** The member's proven email holds an order that entitles the product. */\n memberOrderId: string | null\n}\n\nconst ANONYMOUS_REVIEWER: ReviewerIdentity = {\n signedIn: false,\n suspended: false,\n memberId: null,\n memberEmail: '',\n memberName: '',\n memberOrderId: null,\n}\n\nasync function identifyReviewer(\n req: ReviewsRequest,\n hostRef: FirebaseFirestore.DocumentReference,\n hostId: string,\n productId: string,\n): Promise<ReviewerIdentity> {\n const session: MemberSessionCheck = await readActiveMemberSession(req, hostId).catch(\n () => ({ status: 'anonymous' }) as MemberSessionCheck,\n )\n if (session.status === 'suspended') {\n return { ...ANONYMOUS_REVIEWER, signedIn: true, suspended: true, memberId: session.memberId }\n }\n if (session.status !== 'active') return ANONYMOUS_REVIEWER\n const proven = memberProvenEmail(session.member)\n return {\n signedIn: true,\n suspended: false,\n memberId: session.memberId,\n memberEmail: String(session.member.get('email') ?? '').trim().toLowerCase(),\n memberName: String(session.member.get('displayName') ?? '').trim(),\n memberOrderId: proven ? await entitlingOrderId(hostRef, proven, productId) : null,\n }\n}\n\n/**\n * The storefront form's question (AGL-3736): may this visitor review this\n * product, and would the review be verified? `GET ?mode=eligibility`, never\n * cached — the answer depends on the visitor's cookie and link.\n */\nasync function eligibilityHandler(\n req: ReviewsRequest,\n res: ReviewsResponse,\n hostId: string,\n productId: string,\n) {\n res.setHeader('Cache-Control', 'private, no-store')\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const org = await getOrgForHost(hostId)\n const enabled = Aglyn.checkEntitlement(org?.org as any, 'productReviews')\n const settings = await readReviewSettings(hostRef)\n const reviewer = await identifyReviewer(req, hostRef, hostId, productId)\n const presented = req.query.review\n let tokenVerified = false\n let tokenProblem: CommerceModel.ReviewErrorCode | undefined\n if (presented) {\n const check = await inspectReviewToken(firestore, hostId, presented, productId)\n if (check.ok) tokenVerified = true\n else tokenProblem = check.code ?? CommerceModel.REVIEW_ERROR_CODES.tokenInvalid\n }\n const eligibility = CommerceModel.reviewEligibility({\n policy: settings.policy,\n signedIn: reviewer.signedIn && !reviewer.suspended,\n memberVerified: Boolean(reviewer.memberOrderId),\n tokenVerified,\n tokenProblem,\n })\n return res.status(200).json({\n ...eligibility,\n enabled,\n canReview: enabled && !reviewer.suspended && eligibility.canReview,\n })\n}\n\n/**\n * Product reviews (AGL-324, AGL-3736).\n *\n * GET returns approved reviews + aggregate (`scope=store`: store-wide;\n * `mode=eligibility`: what the form may do). POST submits one review:\n *\n * - VERIFIED when the reviewer presents an unspent, unexpired review link\n * for this product, or is a signed-in member whose proven email has an\n * order that still entitles it. Published at once (`approved`): the FTC's\n * 2024 rule bars suppressing honest negative reviews; the merchant may\n * still hide or reject one for a content reason.\n * - Otherwise, under the store's `verified` policy (the default), 403\n * `verified_purchase_required`; under `anyone`, saved `pending` with the\n * name and email given — the email is never shown and verifies nothing.\n *\n * Rate-limited per address and per member, durably. Plan-gated\n * (`productReviews`).\n */\nexport const reviewsHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n const hostId = String((isPost ? req.body?.hostId : req.query.hostId) ?? '')\n const productId = String(\n (isPost ? req.body?.productId : req.query.productId) ?? '',\n )\n // Store-wide (`scope=store`, no productId): the latest approved reviews\n // across the store, for the storefront's reviews band. Read only, and only\n // where the store's plan has reviews — a store without the feature shows\n // no band rather than reviews it can no longer collect.\n if (!isPost && !productId && req.query.scope === 'store') {\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n try {\n const org = await getOrgForHost(hostId)\n if (!Aglyn.checkEntitlement(org?.org as any, 'productReviews')) {\n return res.status(200).json({ reviews: [], aggregate: { count: 0, average: 0 } })\n }\n const { reviews, aggregate } = await readStoreReviews(hostId, Number(req.query.limit))\n res.setHeader('Cache-Control', 'public, s-maxage=120, stale-while-revalidate=300')\n return res.status(200).json({ reviews, aggregate })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Reviews unavailable' })\n }\n }\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n try {\n if (isPost) return await submitReview(req, res, hostId, productId)\n if (req.query.mode === 'eligibility') {\n return await eligibilityHandler(req, res, hostId, productId)\n }\n // A product sold in person only whose store hides its reviews from the\n // site (AGL-4060) answers none, here as on every other online surface.\n const product = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .doc(productId)\n .get()\n const hiddenOnline =\n CommerceModel.productReviewsOnline(product?.exists ? (product.data() as Record<string, unknown>) : null) ===\n 'hidden'\n const { reviews, aggregate } = hiddenOnline\n ? { reviews: [], aggregate: { count: 0, average: 0 } }\n : await readProductReviews(hostId, productId)\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=120, stale-while-revalidate=300',\n )\n return res.status(200).json({ reviews, aggregate })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Reviews unavailable' })\n }\n}\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nasync function submitReview(\n req: ReviewsRequest,\n res: ReviewsResponse,\n hostId: string,\n productId: string,\n) {\n const codes = CommerceModel.REVIEW_ERROR_CODES\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const org = await getOrgForHost(hostId)\n if (!Aglyn.checkEntitlement(org?.org as any, 'productReviews')) {\n return res.status(403).json({ error: 'Reviews are not enabled', code: codes.notEnabled })\n }\n const refuseRate = (resetMs: number) => {\n res.setHeader(\n 'Retry-After',\n String(Math.max(1, Math.ceil((resetMs - Date.now()) / 1000))),\n )\n return res.status(429).json({\n error: 'Too many reviews from here. Try again later.',\n code: codes.rateLimited,\n })\n }\n // Per address, before anything else is read.\n const perIp = await consumeRateLimit(`commerce-review:ip:${hostId}:${clientIp(req)}`, {\n limit: REVIEW_POSTS_PER_IP_PER_HOUR,\n windowMs: HOUR_MS,\n })\n if (!perIp.allowed) return refuseRate(perIp.resetMs)\n\n const rating = Math.min(5, Math.max(1, Math.round(Number(req.body?.rating ?? 0))))\n const body = String(req.body?.body ?? '').trim().slice(0, 2000)\n const typedName = String(req.body?.authorName ?? '').trim().slice(0, 80)\n if (!rating || !body) {\n return res.status(400).json({ error: 'A rating and a review are required' })\n }\n\n const settings = await readReviewSettings(hostRef)\n const reviewer = await identifyReviewer(req, hostRef, hostId, productId)\n if (reviewer.suspended) {\n return res.status(403).json({ error: MEMBER_SUSPENDED_ERROR, code: codes.memberSuspended })\n }\n if (reviewer.memberId) {\n const perMember = await consumeRateLimit(\n `commerce-review:member:${hostId}:${reviewer.memberId}`,\n { limit: REVIEW_POSTS_PER_MEMBER_PER_DAY, windowMs: 24 * HOUR_MS },\n )\n if (!perMember.allowed) return refuseRate(perMember.resetMs)\n }\n\n // 1. A review link from the email. A link that does not work is an error,\n // never a silent fall back to an unverified review.\n const presented = req.body?.reviewToken\n if (presented) {\n const check = await inspectReviewToken(firestore, hostId, presented, productId)\n if (!check.ok || !check.record || !check.ref) {\n const code = check.code ?? codes.tokenInvalid\n return res.status(403).json({ error: tokenProblemMessage(code), code })\n }\n const reviewRef = hostRef.collection('reviews').doc(createResourceUid())\n const nowMs = Date.now()\n const problem = await firestore.runTransaction(async (transaction) => {\n const spent = await redeemReviewTokenIn(transaction, check.ref, productId, reviewRef.id, nowMs)\n if (spent) return spent\n transaction.create(reviewRef, {\n productId,\n rating,\n body,\n authorName: typedName || reviewer.memberName || 'Anonymous',\n authorEmail: check.record.email,\n ...(reviewer.memberId ? { memberId: reviewer.memberId } : {}),\n verified: true,\n verifiedVia: 'token',\n orderId: check.record.orderId,\n status: CommerceModel.initialReviewStatus(true),\n createdAtMs: nowMs,\n })\n return null\n })\n if (problem) {\n return res.status(403).json({ error: tokenProblemMessage(problem), code: problem })\n }\n // The link came through the inbox, so a member signed in with the same\n // address has now proven it.\n if (reviewer.memberId && reviewer.memberEmail === check.record.email) {\n await hostRef\n .collection('siteMembers')\n .doc(reviewer.memberId)\n .set({ emailVerifiedAtMs: nowMs }, { merge: true })\n .catch(() => undefined)\n }\n return res.status(200).json({ ok: true, pending: false, verified: true })\n }\n\n // 2. A signed-in member whose proven email bought it. One verified review\n // per member per product.\n if (reviewer.memberOrderId) {\n const already = await hostRef\n .collection('reviews')\n .where('productId', '==', productId)\n .where('memberId', '==', reviewer.memberId)\n .limit(1)\n .get()\n if (!already.empty) {\n return res.status(409).json({\n error: 'You have already reviewed this product.',\n code: codes.alreadyReviewed,\n })\n }\n await hostRef.collection('reviews').doc(createResourceUid()).set({\n productId,\n rating,\n body,\n authorName: typedName || reviewer.memberName || 'Anonymous',\n authorEmail: reviewer.memberEmail,\n memberId: reviewer.memberId,\n verified: true,\n verifiedVia: 'member',\n orderId: reviewer.memberOrderId,\n status: CommerceModel.initialReviewStatus(true),\n createdAtMs: Date.now(),\n })\n return res.status(200).json({ ok: true, pending: false, verified: true })\n }\n\n // 3. Nobody the store can verify.\n if (settings.policy !== 'anyone') {\n return res.status(403).json({\n error: 'Only customers who bought this can review it.',\n code: codes.verifiedPurchaseRequired,\n })\n }\n const authorEmail = reviewer.signedIn\n ? reviewer.memberEmail\n : String(req.body?.authorEmail ?? '').trim().toLowerCase().slice(0, 120)\n const authorName = typedName || reviewer.memberName\n if (!authorName || !EMAIL_PATTERN.test(authorEmail)) {\n return res.status(400).json({ error: 'Your name and email are required' })\n }\n await hostRef.collection('reviews').doc(createResourceUid()).set({\n productId,\n rating,\n body,\n authorName,\n // Kept for the merchant; never shown, and it verifies nothing.\n authorEmail,\n ...(reviewer.memberId ? { memberId: reviewer.memberId } : {}),\n verified: false,\n status: CommerceModel.initialReviewStatus(false),\n createdAtMs: Date.now(),\n })\n return res.status(200).json({ ok: true, pending: true, verified: false })\n}\n\n/** The words for a review link that does not work. */\nexport function tokenProblemMessage(code: CommerceModel.ReviewErrorCode): string {\n switch (code) {\n case CommerceModel.REVIEW_ERROR_CODES.tokenUsed:\n return 'This review link has already been used.'\n case CommerceModel.REVIEW_ERROR_CODES.tokenExpired:\n return 'This review link has expired.'\n default:\n return 'This review link is not valid for this product.'\n }\n}\n"],"names":["Aglyn","CommerceModel","consumeRateLimit","firebaseAdmin","getOrgForHost","readClientIp","createResourceUid","AggregateField","MEMBER_SUSPENDED_ERROR","readActiveMemberSession","inspectReviewToken","redeemReviewTokenIn","readProductReviews","hostId","productId","hostRef","app","firestore","collection","doc","reviewsSnapshot","where","limit","get","reviews","docs","map","docSnapshot","id","rating","Number","body","String","authorName","verified","Boolean","reply","createdAtMs","sort","a","b","count","length","average","reduce","sum","review","aggregate","Math","round","STORE_REVIEWS_MAX","STORE_REVIEWS_DEFAULT","reviewerShortName","name","words","trim","split","filter","first","others","last","toUpperCase","HIDDEN_REVIEW_PRODUCTS_MAX","STORE_REVIEWS_PAGES","IN_FILTER_MAX","readHiddenReviewProductIds","snapshot","Set","readStoreReviews","approved","max","min","floor","hidden","hiddenIds","tally","aggregates","Promise","all","Array","from","ceil","_","chunk","slice","after","page","query","orderBy","startAfter","push","has","size","rows","productIds","row","products","Map","snapshots","getAll","data","exists","online","productReviewsOnline","set","slug","product","productName","productSlug","soldInStore","hiddenTallies","counted","total","tallied","REVIEW_POSTS_PER_IP_PER_HOUR","REVIEW_POSTS_PER_MEMBER_PER_DAY","HOUR_MS","memberProvenEmail","member","toLowerCase","entitlingOrderId","email","orders","order","liftLegacyOrder","orderEntitlesProduct","readReviewSettings","catch","reviewSettingsFrom","clientIp","req","headers","remoteAddress","socket","ANONYMOUS_REVIEWER","signedIn","suspended","memberId","memberEmail","memberName","memberOrderId","identifyReviewer","session","status","proven","eligibilityHandler","res","setHeader","org","enabled","checkEntitlement","settings","reviewer","presented","tokenVerified","tokenProblem","check","ok","code","REVIEW_ERROR_CODES","tokenInvalid","eligibility","reviewEligibility","policy","memberVerified","json","canReview","reviewsHandler","isPost","method","scope","error","console","submitReview","mode","hiddenOnline","EMAIL_PATTERN","codes","notEnabled","refuseRate","resetMs","Date","now","rateLimited","perIp","windowMs","allowed","typedName","memberSuspended","perMember","reviewToken","record","ref","tokenProblemMessage","reviewRef","nowMs","problem","runTransaction","transaction","spent","create","authorEmail","verifiedVia","orderId","initialReviewStatus","emailVerifiedAtMs","merge","undefined","pending","already","empty","alreadyReviewed","verifiedPurchaseRequired","test","tokenUsed","tokenExpired"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;AAGD,YAAYA,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,cAAc,QAAQ,2BAA0B;AACzD,SACEC,sBAAsB,EACtBC,u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;AAEA,oDAAoD,GACpD,OAAO,SAAS+J,oBAAoBnC,IAAmC;IACrE,OAAQA;QACN,KAAK7J,cAAc8J,kBAAkB,CAACuD,SAAS;YAC7C,OAAO;QACT,KAAKrN,cAAc8J,kBAAkB,CAACwD,YAAY;YAChD,OAAO;QACT;YACE,OAAO;IACX;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/reviews.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { readClientIp } from '@aglyn/aglyn/app-utils/request-ip'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { AggregateField } from 'firebase-admin/firestore'\nimport {\n MEMBER_SUSPENDED_ERROR,\n readActiveMemberSession,\n type MemberSessionCheck,\n} from './membership'\nimport { inspectReviewToken, redeemReviewTokenIn } from './review-tokens'\nimport { dropStorefrontPages } from './sold-out-drop'\n\n/**\n * A verified review is published the moment it is submitted, and the product\n * page bakes the rating and the list into its cached HTML (AGL-4121). The\n * moderation card drops the site when a merchant approves one; a review that\n * skips moderation has to do the same, or it waits out the week-long backstop.\n * A pending review is not shown, so it drops nothing.\n */\nasync function announcePublishedReview(hostId: string): Promise<void> {\n await dropStorefrontPages({ hostId, reason: 'a verified review was published' })\n}\n\nexport interface PublicProductReview {\n id: string\n rating: number\n body: string\n authorName: string\n verified: boolean\n reply: string | null\n createdAtMs: number\n}\n\nexport interface ProductReviewAggregate {\n count: number\n /** Mean rating, one decimal. */\n average: number\n}\n\n/**\n * Approved reviews for a product, newest first, plus their aggregate.\n *\n * Extracted from the handler (AGL-686) so the site-page resolver can nest\n * `aggregateRating` inside the server-rendered `Product` node. Schema.org\n * wants it as a PROPERTY of the product; the reviews block was emitting a\n * free-standing `AggregateRating` node alongside it, which is orphaned and\n * ignored. One reader means the rating in the structured data and the rating\n * on the page cannot disagree.\n */\nexport async function readProductReviews(\n hostId: string,\n productId: string,\n): Promise<{\n reviews: PublicProductReview[]\n aggregate: ProductReviewAggregate\n}> {\n const hostRef = firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n const reviewsSnapshot = await hostRef\n .collection('reviews')\n .where('productId', '==', productId)\n .where('status', '==', 'approved')\n .limit(100)\n .get()\n const reviews = reviewsSnapshot.docs\n .map((docSnapshot) => ({\n id: docSnapshot.id,\n rating: Number(docSnapshot.get('rating') ?? 0),\n body: String(docSnapshot.get('body') ?? ''),\n authorName: String(docSnapshot.get('authorName') ?? 'Anonymous'),\n verified: Boolean(docSnapshot.get('verified')),\n reply: (docSnapshot.get('reply') as string | undefined) ?? null,\n createdAtMs: Number(docSnapshot.get('createdAtMs') ?? 0),\n }))\n .sort((a, b) => b.createdAtMs - a.createdAtMs)\n const count = reviews.length\n const average = count\n ? reviews.reduce((sum, review) => sum + review.rating, 0) / count\n : 0\n return {\n reviews,\n aggregate: { count, average: Math.round(average * 10) / 10 },\n }\n}\n\n/** One approved review as the store-wide list shows it. */\nexport interface PublicStoreReview {\n id: string\n rating: number\n body: string\n /** First name and last initial only (\"Jane D.\"), never the full name. */\n authorName: string\n verified: boolean\n createdAtMs: number\n /** The reviewed product, when it is still on sale. */\n productName?: string\n /** Its page, when it is sold online; a product sold in person only has none. */\n productSlug?: string\n /**\n * The product is sold in person only and the store shows its reviews\n * (AGL-4060): the band marks it \"Sold in store\" and links nowhere.\n */\n soldInStore?: true\n}\n\n/** The most reviews the store-wide list returns. */\nexport const STORE_REVIEWS_MAX = 12\n/** What the store-wide list returns when the caller names no limit. */\nexport const STORE_REVIEWS_DEFAULT = 6\n\n/** \"Jane Doe\" → \"Jane D.\"; one word stays as it is. */\nexport function reviewerShortName(name: string): string {\n const words = String(name ?? '').trim().split(/\\s+/).filter(Boolean)\n if (!words.length) return 'Anonymous'\n const [first, ...others] = words\n const last = others[others.length - 1]\n return last ? `${first} ${last[0].toUpperCase()}.` : first\n}\n\n/** The most products a store may keep its in-store reviews off the site for, read at once. */\nexport const HIDDEN_REVIEW_PRODUCTS_MAX = 500\n/** How many pages of the newest reviews the band reads to fill itself past hidden ones. */\nconst STORE_REVIEWS_PAGES = 4\n/** Firestore's ceiling on the values of one `in` filter. */\nconst IN_FILTER_MAX = 30\n\n/**\n * The products sold in person only whose reviews the store keeps off the site\n * (AGL-4060, `inStoreReviews: 'hide'`). Two equalities, which Firestore\n * serves from its automatic single-field indexes.\n */\nexport async function readHiddenReviewProductIds(\n hostRef: FirebaseFirestore.DocumentReference,\n): Promise<Set<string>> {\n const snapshot = await hostRef\n .collection('products')\n .where('sellOnline', '==', false)\n .where('inStoreReviews', '==', 'hide')\n .limit(HIDDEN_REVIEW_PRODUCTS_MAX)\n .get()\n return new Set(snapshot.docs.map((doc) => doc.id))\n}\n\n/**\n * The store's latest APPROVED reviews across every product, newest first, with\n * the aggregate over all of them — the store-wide reviews band a storefront\n * home carries. Approved only: a pending or rejected review never reaches a\n * page, and nothing here is ever sample text (a published page shows real\n * reviews or none).\n *\n * A product sold in person only (AGL-4060) shows its reviews here by default,\n * named, marked `soldInStore` and never linked, since it has no page; one\n * whose store chose to hide them (`inStoreReviews: 'hide'`) is in neither the\n * list nor the aggregate.\n *\n * The list is `status == approved` ordered by `createdAtMs desc`, served by\n * the COLLECTION composite `reviews (status ASC, createdAtMs DESC)` that the\n * moderation queue already declares, read a page at a time past hidden ones;\n * the aggregate is a count and a sum over the same equality, less the hidden\n * products' (`productId in …`, at most 30 at a time).\n */\nexport async function readStoreReviews(\n hostId: string,\n limit: number = STORE_REVIEWS_DEFAULT,\n): Promise<{ reviews: PublicStoreReview[]; aggregate: ProductReviewAggregate }> {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const approved = hostRef.collection('reviews').where('status', '==', 'approved')\n const max = Math.min(STORE_REVIEWS_MAX, Math.max(1, Math.floor(Number(limit)) || STORE_REVIEWS_DEFAULT))\n const hidden = await readHiddenReviewProductIds(hostRef)\n const hiddenIds = [...hidden]\n const tally = { count: AggregateField.count(), sum: AggregateField.sum('rating') }\n const aggregates = Promise.all([\n approved.aggregate(tally).get(),\n ...Array.from({ length: Math.ceil(hiddenIds.length / IN_FILTER_MAX) }, (_, chunk) =>\n approved\n .where('productId', 'in', hiddenIds.slice(chunk * IN_FILTER_MAX, (chunk + 1) * IN_FILTER_MAX))\n .aggregate(tally)\n .get(),\n ),\n ])\n\n // The newest approved reviews, a page at a time, past any the store hides.\n const docs: FirebaseFirestore.QueryDocumentSnapshot[] = []\n let after: FirebaseFirestore.QueryDocumentSnapshot | null = null\n for (let page = 0; page < STORE_REVIEWS_PAGES && docs.length < max; page += 1) {\n let query = approved.orderBy('createdAtMs', 'desc')\n if (after) query = query.startAfter(after)\n const snapshot = await query.limit(max).get()\n docs.push(...snapshot.docs.filter((doc) => !hidden.has(String(doc.get('productId') ?? ''))))\n if (snapshot.docs.length < max || !hidden.size) break\n after = snapshot.docs[snapshot.docs.length - 1]\n }\n const rows = docs.slice(0, max).map((docSnapshot) => ({\n id: docSnapshot.id,\n productId: String(docSnapshot.get('productId') ?? ''),\n rating: Number(docSnapshot.get('rating') ?? 0),\n body: String(docSnapshot.get('body') ?? ''),\n authorName: reviewerShortName(String(docSnapshot.get('authorName') ?? '')),\n verified: Boolean(docSnapshot.get('verified')),\n createdAtMs: Number(docSnapshot.get('createdAtMs') ?? 0),\n }))\n // The reviewed products, in one batched read of at most `max` docs.\n const productIds = [...new Set(rows.map((row) => row.productId).filter(Boolean))]\n const products = new Map<string, { name: string; slug: string | null; online: CommerceModel.ProductReviewsOnline }>()\n if (productIds.length) {\n const snapshots = await firestore.getAll(\n ...productIds.map((id) => hostRef.collection('products').doc(id)),\n )\n for (const snapshot of snapshots) {\n const data = snapshot.exists ? (snapshot.data() as Record<string, unknown>) : null\n const online = CommerceModel.productReviewsOnline(data)\n // A draft or a deleted product is named nowhere, as before.\n if (!online) continue\n products.set(snapshot.id, {\n name: String(data['name'] ?? ''),\n // Sold in person only: no page to link to.\n slug: online === 'listed' ? String(data['slug'] ?? '') : null,\n online,\n })\n }\n }\n const reviews = rows\n // A product hidden since the list was read is still never shown.\n .filter((row) => products.get(row.productId)?.online !== 'hidden')\n .map(({ productId, ...row }) => {\n const product = products.get(productId)\n return {\n ...row,\n ...(product?.name ? { productName: product.name } : {}),\n ...(product?.slug ? { productSlug: product.slug } : {}),\n ...(product?.online === 'sold-in-store' ? { soldInStore: true as const } : {}),\n }\n })\n const [all, ...hiddenTallies] = await aggregates\n const counted = (snapshot: { data: () => unknown }) => {\n const data = snapshot.data() as { count?: number; sum?: number | null }\n return { count: Number(data.count ?? 0), sum: Number(data.sum ?? 0) }\n }\n const total = counted(all)\n for (const tallied of hiddenTallies.map(counted)) {\n total.count -= tallied.count\n total.sum -= tallied.sum\n }\n const count = Math.max(0, total.count)\n const average = count ? total.sum / count : 0\n return { reviews, aggregate: { count, average: Math.round(average * 10) / 10 } }\n}\n\n/** Reviews one address may submit per site, per hour (AGL-3736). */\nexport const REVIEW_POSTS_PER_IP_PER_HOUR = 10\n/** Reviews one signed-in member may submit per site, per day. */\nexport const REVIEW_POSTS_PER_MEMBER_PER_DAY = 10\nconst HOUR_MS = 60 * 60 * 1000\n\n/**\n * The address a signed-in member has PROVEN they own, or `''`.\n *\n * A site member signs up by typing an email nobody checks, so the address on\n * the member document alone would let anyone register with a buyer's address\n * and collect a \"Verified buyer\" badge on their purchases. Only a member\n * whose inbox has answered — `emailVerifiedAtMs`, stamped when they complete\n * a password reset from the emailed link or redeem a review link while signed\n * in — counts.\n */\nexport function memberProvenEmail(\n member: FirebaseFirestore.DocumentSnapshot | null | undefined,\n): string {\n if (!member?.exists) return ''\n if (!Number(member.get('emailVerifiedAtMs') ?? 0)) return ''\n return String(member.get('email') ?? '').trim().toLowerCase()\n}\n\n/** The first order under `email` that still entitles `productId`, or null. */\nexport async function entitlingOrderId(\n hostRef: FirebaseFirestore.DocumentReference,\n email: string,\n productId: string,\n): Promise<string | null> {\n if (!email) return null\n // By the member's email, as the account page matches order history.\n const orders = await hostRef\n .collection('orders')\n .where('customerEmail', '==', email)\n .limit(25)\n .get()\n for (const docSnapshot of orders.docs) {\n const order = CommerceModel.liftLegacyOrder(docSnapshot.data() as any)\n // The shared entitlement test (AGL-2454): a line refunded by name is\n // goods the buyer no longer has.\n if (CommerceModel.orderEntitlesProduct(order, productId)) return docSnapshot.id\n }\n return null\n}\n\n/** A store's review settings, from `settings/store`. */\nasync function readReviewSettings(\n hostRef: FirebaseFirestore.DocumentReference,\n): Promise<CommerceModel.ReviewSettings> {\n const snapshot = await hostRef\n .collection('settings')\n .doc('store')\n .get()\n .catch(() => null)\n return CommerceModel.reviewSettingsFrom(snapshot?.data?.() ?? null)\n}\n\ntype ReviewsRequest = Parameters<PluginApiHandler>[0]\ntype ReviewsResponse = Parameters<PluginApiHandler>[1]\n\nfunction clientIp(req: ReviewsRequest): string {\n return (\n readClientIp(req.headers, { remoteAddress: req.socket?.remoteAddress }) ??\n 'no-address'\n )\n}\n\n/** What the server established about who is reviewing. */\ninterface ReviewerIdentity {\n signedIn: boolean\n suspended: boolean\n memberId: string | null\n memberEmail: string\n memberName: string\n /** The member's proven email holds an order that entitles the product. */\n memberOrderId: string | null\n}\n\nconst ANONYMOUS_REVIEWER: ReviewerIdentity = {\n signedIn: false,\n suspended: false,\n memberId: null,\n memberEmail: '',\n memberName: '',\n memberOrderId: null,\n}\n\nasync function identifyReviewer(\n req: ReviewsRequest,\n hostRef: FirebaseFirestore.DocumentReference,\n hostId: string,\n productId: string,\n): Promise<ReviewerIdentity> {\n const session: MemberSessionCheck = await readActiveMemberSession(req, hostId).catch(\n () => ({ status: 'anonymous' }) as MemberSessionCheck,\n )\n if (session.status === 'suspended') {\n return { ...ANONYMOUS_REVIEWER, signedIn: true, suspended: true, memberId: session.memberId }\n }\n if (session.status !== 'active') return ANONYMOUS_REVIEWER\n const proven = memberProvenEmail(session.member)\n return {\n signedIn: true,\n suspended: false,\n memberId: session.memberId,\n memberEmail: String(session.member.get('email') ?? '').trim().toLowerCase(),\n memberName: String(session.member.get('displayName') ?? '').trim(),\n memberOrderId: proven ? await entitlingOrderId(hostRef, proven, productId) : null,\n }\n}\n\n/**\n * The storefront form's question (AGL-3736): may this visitor review this\n * product, and would the review be verified? `GET ?mode=eligibility`, never\n * cached — the answer depends on the visitor's cookie and link.\n */\nasync function eligibilityHandler(\n req: ReviewsRequest,\n res: ReviewsResponse,\n hostId: string,\n productId: string,\n) {\n res.setHeader('Cache-Control', 'private, no-store')\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const org = await getOrgForHost(hostId)\n const enabled = Aglyn.checkEntitlement(org?.org as any, 'productReviews')\n const settings = await readReviewSettings(hostRef)\n const reviewer = await identifyReviewer(req, hostRef, hostId, productId)\n const presented = req.query.review\n let tokenVerified = false\n let tokenProblem: CommerceModel.ReviewErrorCode | undefined\n if (presented) {\n const check = await inspectReviewToken(firestore, hostId, presented, productId)\n if (check.ok) tokenVerified = true\n else tokenProblem = check.code ?? CommerceModel.REVIEW_ERROR_CODES.tokenInvalid\n }\n const eligibility = CommerceModel.reviewEligibility({\n policy: settings.policy,\n signedIn: reviewer.signedIn && !reviewer.suspended,\n memberVerified: Boolean(reviewer.memberOrderId),\n tokenVerified,\n tokenProblem,\n })\n return res.status(200).json({\n ...eligibility,\n enabled,\n canReview: enabled && !reviewer.suspended && eligibility.canReview,\n })\n}\n\n/**\n * Product reviews (AGL-324, AGL-3736).\n *\n * GET returns approved reviews + aggregate (`scope=store`: store-wide;\n * `mode=eligibility`: what the form may do). POST submits one review:\n *\n * - VERIFIED when the reviewer presents an unspent, unexpired review link\n * for this product, or is a signed-in member whose proven email has an\n * order that still entitles it. Published at once (`approved`): the FTC's\n * 2024 rule bars suppressing honest negative reviews; the merchant may\n * still hide or reject one for a content reason.\n * - Otherwise, under the store's `verified` policy (the default), 403\n * `verified_purchase_required`; under `anyone`, saved `pending` with the\n * name and email given — the email is never shown and verifies nothing.\n *\n * Rate-limited per address and per member, durably. Plan-gated\n * (`productReviews`).\n */\nexport const reviewsHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n const hostId = String((isPost ? req.body?.hostId : req.query.hostId) ?? '')\n const productId = String(\n (isPost ? req.body?.productId : req.query.productId) ?? '',\n )\n // Store-wide (`scope=store`, no productId): the latest approved reviews\n // across the store, for the storefront's reviews band. Read only, and only\n // where the store's plan has reviews — a store without the feature shows\n // no band rather than reviews it can no longer collect.\n if (!isPost && !productId && req.query.scope === 'store') {\n if (!hostId) return res.status(400).json({ error: 'Missing hostId' })\n try {\n const org = await getOrgForHost(hostId)\n if (!Aglyn.checkEntitlement(org?.org as any, 'productReviews')) {\n return res.status(200).json({ reviews: [], aggregate: { count: 0, average: 0 } })\n }\n const { reviews, aggregate } = await readStoreReviews(hostId, Number(req.query.limit))\n res.setHeader('Cache-Control', 'public, s-maxage=120, stale-while-revalidate=300')\n return res.status(200).json({ reviews, aggregate })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Reviews unavailable' })\n }\n }\n if (!hostId || !productId) {\n return res.status(400).json({ error: 'Missing hostId or productId' })\n }\n try {\n if (isPost) return await submitReview(req, res, hostId, productId)\n if (req.query.mode === 'eligibility') {\n return await eligibilityHandler(req, res, hostId, productId)\n }\n // A product sold in person only whose store hides its reviews from the\n // site (AGL-4060) answers none, here as on every other online surface.\n const product = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .doc(productId)\n .get()\n const hiddenOnline =\n CommerceModel.productReviewsOnline(product?.exists ? (product.data() as Record<string, unknown>) : null) ===\n 'hidden'\n const { reviews, aggregate } = hiddenOnline\n ? { reviews: [], aggregate: { count: 0, average: 0 } }\n : await readProductReviews(hostId, productId)\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=120, stale-while-revalidate=300',\n )\n return res.status(200).json({ reviews, aggregate })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Reviews unavailable' })\n }\n}\n\nconst EMAIL_PATTERN = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\nasync function submitReview(\n req: ReviewsRequest,\n res: ReviewsResponse,\n hostId: string,\n productId: string,\n) {\n const codes = CommerceModel.REVIEW_ERROR_CODES\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const org = await getOrgForHost(hostId)\n if (!Aglyn.checkEntitlement(org?.org as any, 'productReviews')) {\n return res.status(403).json({ error: 'Reviews are not enabled', code: codes.notEnabled })\n }\n const refuseRate = (resetMs: number) => {\n res.setHeader(\n 'Retry-After',\n String(Math.max(1, Math.ceil((resetMs - Date.now()) / 1000))),\n )\n return res.status(429).json({\n error: 'Too many reviews from here. Try again later.',\n code: codes.rateLimited,\n })\n }\n // Per address, before anything else is read.\n const perIp = await consumeRateLimit(`commerce-review:ip:${hostId}:${clientIp(req)}`, {\n limit: REVIEW_POSTS_PER_IP_PER_HOUR,\n windowMs: HOUR_MS,\n })\n if (!perIp.allowed) return refuseRate(perIp.resetMs)\n\n const rating = Math.min(5, Math.max(1, Math.round(Number(req.body?.rating ?? 0))))\n const body = String(req.body?.body ?? '').trim().slice(0, 2000)\n const typedName = String(req.body?.authorName ?? '').trim().slice(0, 80)\n if (!rating || !body) {\n return res.status(400).json({ error: 'A rating and a review are required' })\n }\n\n const settings = await readReviewSettings(hostRef)\n const reviewer = await identifyReviewer(req, hostRef, hostId, productId)\n if (reviewer.suspended) {\n return res.status(403).json({ error: MEMBER_SUSPENDED_ERROR, code: codes.memberSuspended })\n }\n if (reviewer.memberId) {\n const perMember = await consumeRateLimit(\n `commerce-review:member:${hostId}:${reviewer.memberId}`,\n { limit: REVIEW_POSTS_PER_MEMBER_PER_DAY, windowMs: 24 * HOUR_MS },\n )\n if (!perMember.allowed) return refuseRate(perMember.resetMs)\n }\n\n // 1. A review link from the email. A link that does not work is an error,\n // never a silent fall back to an unverified review.\n const presented = req.body?.reviewToken\n if (presented) {\n const check = await inspectReviewToken(firestore, hostId, presented, productId)\n if (!check.ok || !check.record || !check.ref) {\n const code = check.code ?? codes.tokenInvalid\n return res.status(403).json({ error: tokenProblemMessage(code), code })\n }\n const reviewRef = hostRef.collection('reviews').doc(createResourceUid())\n const nowMs = Date.now()\n const problem = await firestore.runTransaction(async (transaction) => {\n const spent = await redeemReviewTokenIn(transaction, check.ref, productId, reviewRef.id, nowMs)\n if (spent) return spent\n transaction.create(reviewRef, {\n productId,\n rating,\n body,\n authorName: typedName || reviewer.memberName || 'Anonymous',\n authorEmail: check.record.email,\n ...(reviewer.memberId ? { memberId: reviewer.memberId } : {}),\n verified: true,\n verifiedVia: 'token',\n orderId: check.record.orderId,\n status: CommerceModel.initialReviewStatus(true),\n createdAtMs: nowMs,\n })\n return null\n })\n if (problem) {\n return res.status(403).json({ error: tokenProblemMessage(problem), code: problem })\n }\n // The link came through the inbox, so a member signed in with the same\n // address has now proven it.\n if (reviewer.memberId && reviewer.memberEmail === check.record.email) {\n await hostRef\n .collection('siteMembers')\n .doc(reviewer.memberId)\n .set({ emailVerifiedAtMs: nowMs }, { merge: true })\n .catch(() => undefined)\n }\n await announcePublishedReview(hostId)\n return res.status(200).json({ ok: true, pending: false, verified: true })\n }\n\n // 2. A signed-in member whose proven email bought it. One verified review\n // per member per product.\n if (reviewer.memberOrderId) {\n const already = await hostRef\n .collection('reviews')\n .where('productId', '==', productId)\n .where('memberId', '==', reviewer.memberId)\n .limit(1)\n .get()\n if (!already.empty) {\n return res.status(409).json({\n error: 'You have already reviewed this product.',\n code: codes.alreadyReviewed,\n })\n }\n await hostRef.collection('reviews').doc(createResourceUid()).set({\n productId,\n rating,\n body,\n authorName: typedName || reviewer.memberName || 'Anonymous',\n authorEmail: reviewer.memberEmail,\n memberId: reviewer.memberId,\n verified: true,\n verifiedVia: 'member',\n orderId: reviewer.memberOrderId,\n status: CommerceModel.initialReviewStatus(true),\n createdAtMs: Date.now(),\n })\n await announcePublishedReview(hostId)\n return res.status(200).json({ ok: true, pending: false, verified: true })\n }\n\n // 3. Nobody the store can verify.\n if (settings.policy !== 'anyone') {\n return res.status(403).json({\n error: 'Only customers who bought this can review it.',\n code: codes.verifiedPurchaseRequired,\n })\n }\n const authorEmail = reviewer.signedIn\n ? reviewer.memberEmail\n : String(req.body?.authorEmail ?? '').trim().toLowerCase().slice(0, 120)\n const authorName = typedName || reviewer.memberName\n if (!authorName || !EMAIL_PATTERN.test(authorEmail)) {\n return res.status(400).json({ error: 'Your name and email are required' })\n }\n await hostRef.collection('reviews').doc(createResourceUid()).set({\n productId,\n rating,\n body,\n authorName,\n // Kept for the merchant; never shown, and it verifies nothing.\n authorEmail,\n ...(reviewer.memberId ? { memberId: reviewer.memberId } : {}),\n verified: false,\n status: CommerceModel.initialReviewStatus(false),\n createdAtMs: Date.now(),\n })\n return res.status(200).json({ ok: true, pending: true, verified: false })\n}\n\n/** The words for a review link that does not work. */\nexport function tokenProblemMessage(code: CommerceModel.ReviewErrorCode): string {\n switch (code) {\n case CommerceModel.REVIEW_ERROR_CODES.tokenUsed:\n return 'This review link has already been used.'\n case CommerceModel.REVIEW_ERROR_CODES.tokenExpired:\n return 'This review link has expired.'\n default:\n return 'This review link is not valid for this product.'\n }\n}\n"],"names":["Aglyn","CommerceModel","consumeRateLimit","firebaseAdmin","getOrgForHost","readClientIp","createResourceUid","AggregateField","MEMBER_SUSPENDED_ERROR","readActiveMemberSession","inspectReviewToken","redeemReviewTokenIn","dropStorefrontPages","announcePublishedReview","hostId","reason","readProductReviews","productId","hostRef","app","firestore","collection","doc","reviewsSnapshot","where","limit","get","reviews","docs","map","docSnapshot","id","rating","Number","body","String","authorName","verified","Boolean","reply","createdAtMs","sort","a","b","count","length","average","reduce","sum","review","aggregate","Math","round","STORE_REVIEWS_MAX","STORE_REVIEWS_DEFAULT","reviewerShortName","name","words","trim","split","filter","first","others","last","toUpperCase","HIDDEN_REVIEW_PRODUCTS_MAX","STORE_REVIEWS_PAGES","IN_FILTER_MAX","readHiddenReviewProductIds","snapshot","Set","readStoreReviews","approved","max","min","floor","hidden","hiddenIds","tally","aggregates","Promise","all","Array","from","ceil","_","chunk","slice","after","page","query","orderBy","startAfter","push","has","size","rows","productIds","row","products","Map","snapshots","getAll","data","exists","online","productReviewsOnline","set","slug","product","productName","productSlug","soldInStore","hiddenTallies","counted","total","tallied","REVIEW_POSTS_PER_IP_PER_HOUR","REVIEW_POSTS_PER_MEMBER_PER_DAY","HOUR_MS","memberProvenEmail","member","toLowerCase","entitlingOrderId","email","orders","order","liftLegacyOrder","orderEntitlesProduct","readReviewSettings","catch","reviewSettingsFrom","clientIp","req","headers","remoteAddress","socket","ANONYMOUS_REVIEWER","signedIn","suspended","memberId","memberEmail","memberName","memberOrderId","identifyReviewer","session","status","proven","eligibilityHandler","res","setHeader","org","enabled","checkEntitlement","settings","reviewer","presented","tokenVerified","tokenProblem","check","ok","code","REVIEW_ERROR_CODES","tokenInvalid","eligibility","reviewEligibility","policy","memberVerified","json","canReview","reviewsHandler","isPost","method","scope","error","console","submitReview","mode","hiddenOnline","EMAIL_PATTERN","codes","notEnabled","refuseRate","resetMs","Date","now","rateLimited","perIp","windowMs","allowed","typedName","memberSuspended","perMember","reviewToken","record","ref","tokenProblemMessage","reviewRef","nowMs","problem","runTransaction","transaction","spent","create","authorEmail","verifiedVia","orderId","initialReviewStatus","emailVerifiedAtMs","merge","undefined","pending","already","empty","alreadyReviewed","verifiedPurchaseRequired","test","tokenUsed","tokenExpired"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;AAGD,YAAYA,WAAW,sBAAqB;AAC5C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SAASC,YAAY,QAAQ,oCAAmC;AAChE,SAASC,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,cAAc,QAAQ,2BAA0B;AACzD,SACEC,sBAAsB,EACtBC,uBAAuB,QAElB,kBAAc;AACrB,SAASC,kBAAkB,EAAEC,mBAAmB,QAAQ,qBAAiB;AACzE,SAASC,mBAAmB,QAAQ,qBAAiB;AAErD;;;;;;CAMC,GACD,eAAeC,wBAAwBC,MAAc;IACnD,MAAMF,oBAAoB;QAAEE;QAAQC,QAAQ;IAAkC;AAChF;AAkBA;;;;;;;;;CASC,GACD,OAAO,eAAeC,mBACpBF,MAAc,EACdG,SAAiB;IAKjB,MAAMC,UAAUf,cACbgB,GAAG,GACHC,SAAS,GACTC,UAAU,CAAC,SACXC,GAAG,CAACR;IACP,MAAMS,kBAAkB,MAAML,QAC3BG,UAAU,CAAC,WACXG,KAAK,CAAC,aAAa,MAAMP,WACzBO,KAAK,CAAC,UAAU,MAAM,YACtBC,KAAK,CAAC,KACNC,GAAG;IACN,MAAMC,UAAUJ,gBAAgBK,IAAI,CACjCC,GAAG,CAAC,CAACC;YAEWA,kBACFA,mBACMA,mBAEXA,mBACYA;eAPC;YACrBC,IAAID,YAAYC,EAAE;YAClBC,QAAQC,QAAOH,mBAAAA,YAAYJ,GAAG,CAAC,qBAAhBI,mBAA6B;YAC5CI,MAAMC,QAAOL,oBAAAA,YAAYJ,GAAG,CAAC,mBAAhBI,oBAA2B;YACxCM,YAAYD,QAAOL,oBAAAA,YAAYJ,GAAG,CAAC,yBAAhBI,oBAAiC;YACpDO,UAAUC,QAAQR,YAAYJ,GAAG,C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AAanC,SAASb,UAAU;IACnD,IAAI,CAAC1G,cAAc,CAAC+I,cAAcqC,IAAI,CAACZ,cAAc;QACnD,OAAOvD,IAAIH,MAAM,CAAC,KAAKsB,IAAI,CAAC;YAAEM,OAAO;QAAmC;IAC1E;IACA,MAAM5J,QAAQG,UAAU,CAAC,WAAWC,GAAG,CAAChB,qBAAqBqG,GAAG,CAAC;QAC/D1F;QACAe;QACAE;QACAE;QACA,+DAA+D;QAC/DwK;OACIjD,SAASf,QAAQ,GAAG;QAAEA,UAAUe,SAASf,QAAQ;IAAC,IAAI,CAAC;QAC3DvG,UAAU;QACV6G,QAAQjJ,cAAc8M,mBAAmB,CAAC;QAC1CvK,aAAagJ,KAAKC,GAAG;;IAEvB,OAAOpC,IAAIH,MAAM,CAAC,KAAKsB,IAAI,CAAC;QAAER,IAAI;QAAMmD,SAAS;QAAM9K,UAAU;IAAM;AACzE;AAEA,oDAAoD,GACpD,OAAO,SAAS+J,oBAAoBnC,IAAmC;IACrE,OAAQA;QACN,KAAKhK,cAAciK,kBAAkB,CAACuD,SAAS;YAC7C,OAAO;QACT,KAAKxN,cAAciK,kBAAkB,CAACwD,YAAY;YAChD,OAAO;QACT;YACE,OAAO;IACX;AACF"}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache';
18
+ import * as CommerceModel from '../model';
19
+ /**
20
+ * A SALE OR A RESTOCK THAT FLIPS "SOLD OUT" (AGL-4121).
21
+ *
22
+ * The storefront bakes stock into the cached page as booleans only: each
23
+ * variant's `soldOut` on the product page (the chip, the disabled add-to-cart,
24
+ * the JSON-LD availability) and each product's `soldOut` in every product grid,
25
+ * which can sit on any page, the home page included. No count reaches the HTML.
26
+ *
27
+ * Product edits and stock adjustments from the console and the app already drop
28
+ * the site. The checkout, the register, returns, cancellations, channel orders
29
+ * and inventory sync did not, so a product that sold out kept offering itself
30
+ * for as long as the page was cached — up to the week-long backstop once that
31
+ * moved. Those writers call this with the product before and after their write.
32
+ *
33
+ * Only a FLIP drops anything: a sale that takes 7 units to 6 changes nothing a
34
+ * visitor can see, and dropping on every unit would regenerate a busy store's
35
+ * pages on every order. A flip is rare, so the drop is the whole site — a grid
36
+ * on an arbitrary page shows the verdict and nothing maps a product to the
37
+ * pages that place a grid.
38
+ */
39
+ type StockShape = Pick<CommerceModel.HostProduct, 'variants' | 'oversellPolicy'>;
40
+ /** Every sold-out verdict the storefront renders for a product, as one key. */
41
+ export declare function soldOutSignature(product: StockShape | null | undefined): string;
42
+ /** Whether a write moved any sold-out verdict a visitor sees. */
43
+ export declare function soldOutMoved(before: StockShape | null | undefined, after: StockShape | null | undefined): boolean;
44
+ export interface SoldOutDropDeps {
45
+ firestore?: () => FirebaseFirestore.Firestore;
46
+ dropCache?: typeof dropPluginSiteCache;
47
+ }
48
+ /**
49
+ * Drops the site's cached pages after a sold-out flip: a publish outbox entry
50
+ * first, so the console's drain retries a refused drop, then the drop, then
51
+ * the entry released once it certainly landed. NEVER THROWS — it runs after a
52
+ * paid order or a restock that must not fail on a cache.
53
+ */
54
+ export declare function dropStorefrontPages(options: {
55
+ hostId: string;
56
+ reason: string;
57
+ }, deps?: SoldOutDropDeps): Promise<void>;
58
+ export {};
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
17
+ import { dropPluginSiteCache } from "@aglyn/aglyn/plugin-manager/plugin-site-cache";
18
+ // By path: the barrel pulls `next/cache` in through the render cache.
19
+ import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
20
+ import { FieldValue } from "firebase-admin/firestore";
21
+ import * as CommerceModel from "../model/index.js";
22
+ /** Every sold-out verdict the storefront renders for a product, as one key. */ export function soldOutSignature(product) {
23
+ var _product_variants;
24
+ if (!product) return '';
25
+ const backorder = product.oversellPolicy === 'backorder';
26
+ const variants = ((_product_variants = product.variants) != null ? _product_variants : []).map((variant)=>variant.inventory != null && Number(variant.inventory) <= 0 && !backorder ? 1 : 0);
27
+ return `${CommerceModel.productStockFields(product).soldOut ? 1 : 0}:${variants.join('')}`;
28
+ }
29
+ /** Whether a write moved any sold-out verdict a visitor sees. */ export function soldOutMoved(before, after) {
30
+ if (!before || !after) return false;
31
+ return soldOutSignature(before) !== soldOutSignature(after);
32
+ }
33
+ /**
34
+ * Drops the site's cached pages after a sold-out flip: a publish outbox entry
35
+ * first, so the console's drain retries a refused drop, then the drop, then
36
+ * the entry released once it certainly landed. NEVER THROWS — it runs after a
37
+ * paid order or a restock that must not fail on a cache.
38
+ */ export async function dropStorefrontPages(options, deps = {}) {
39
+ var _deps_firestore, _deps_dropCache;
40
+ const { hostId, reason } = options;
41
+ if (!hostId) return;
42
+ const firestore = (_deps_firestore = deps.firestore) != null ? _deps_firestore : ()=>firebaseAdmin.app().firestore();
43
+ const dropCache = (_deps_dropCache = deps.dropCache) != null ? _deps_dropCache : dropPluginSiteCache;
44
+ let entry = null;
45
+ try {
46
+ const ref = firestore().collection('publishOutbox').doc(createResourceUid());
47
+ await ref.set({
48
+ hostId,
49
+ paths: [
50
+ '/'
51
+ ],
52
+ createdAt: FieldValue.serverTimestamp(),
53
+ attempts: 0,
54
+ entireHost: true,
55
+ reason: reason.slice(0, 200)
56
+ });
57
+ entry = ref;
58
+ } catch (error) {
59
+ console.error('[commerce] a sold-out flip could not be queued', hostId, error);
60
+ }
61
+ try {
62
+ const dropped = await dropCache({
63
+ hostIds: [
64
+ hostId
65
+ ],
66
+ reason
67
+ });
68
+ if (dropped.complete && entry) await entry.delete().catch(()=>undefined);
69
+ if (!dropped.complete && !entry) {
70
+ console.error(JSON.stringify({
71
+ tag: 'AGL-4121:sold-out-drop-lost',
72
+ hostId,
73
+ reason
74
+ }));
75
+ }
76
+ } catch (error) {
77
+ console.error('[commerce] a sold-out flip did not reach the live site', hostId, error);
78
+ }
79
+ }
80
+
81
+ //# sourceMappingURL=sold-out-drop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/sold-out-drop.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 { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\n// By path: the barrel pulls `next/cache` in through the render cache.\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport * as CommerceModel from '../model'\n\n/**\n * A SALE OR A RESTOCK THAT FLIPS \"SOLD OUT\" (AGL-4121).\n *\n * The storefront bakes stock into the cached page as booleans only: each\n * variant's `soldOut` on the product page (the chip, the disabled add-to-cart,\n * the JSON-LD availability) and each product's `soldOut` in every product grid,\n * which can sit on any page, the home page included. No count reaches the HTML.\n *\n * Product edits and stock adjustments from the console and the app already drop\n * the site. The checkout, the register, returns, cancellations, channel orders\n * and inventory sync did not, so a product that sold out kept offering itself\n * for as long as the page was cached — up to the week-long backstop once that\n * moved. Those writers call this with the product before and after their write.\n *\n * Only a FLIP drops anything: a sale that takes 7 units to 6 changes nothing a\n * visitor can see, and dropping on every unit would regenerate a busy store's\n * pages on every order. A flip is rare, so the drop is the whole site — a grid\n * on an arbitrary page shows the verdict and nothing maps a product to the\n * pages that place a grid.\n */\n\ntype StockShape = Pick<CommerceModel.HostProduct, 'variants' | 'oversellPolicy'>\n\n/** Every sold-out verdict the storefront renders for a product, as one key. */\nexport function soldOutSignature(product: StockShape | null | undefined): string {\n if (!product) return ''\n const backorder = product.oversellPolicy === 'backorder'\n const variants = (product.variants ?? []).map((variant) =>\n variant.inventory != null && Number(variant.inventory) <= 0 && !backorder ? 1 : 0,\n )\n return `${CommerceModel.productStockFields(product).soldOut ? 1 : 0}:${variants.join('')}`\n}\n\n/** Whether a write moved any sold-out verdict a visitor sees. */\nexport function soldOutMoved(\n before: StockShape | null | undefined,\n after: StockShape | null | undefined,\n): boolean {\n if (!before || !after) return false\n return soldOutSignature(before) !== soldOutSignature(after)\n}\n\nexport interface SoldOutDropDeps {\n firestore?: () => FirebaseFirestore.Firestore\n dropCache?: typeof dropPluginSiteCache\n}\n\n/**\n * Drops the site's cached pages after a sold-out flip: a publish outbox entry\n * first, so the console's drain retries a refused drop, then the drop, then\n * the entry released once it certainly landed. NEVER THROWS — it runs after a\n * paid order or a restock that must not fail on a cache.\n */\nexport async function dropStorefrontPages(\n options: { hostId: string; reason: string },\n deps: SoldOutDropDeps = {},\n): Promise<void> {\n const { hostId, reason } = options\n if (!hostId) return\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore())\n const dropCache = deps.dropCache ?? dropPluginSiteCache\n let entry: FirebaseFirestore.DocumentReference | null = null\n try {\n const ref = firestore().collection('publishOutbox').doc(createResourceUid())\n await ref.set({\n hostId,\n paths: ['/'],\n createdAt: FieldValue.serverTimestamp(),\n attempts: 0,\n entireHost: true,\n reason: reason.slice(0, 200),\n })\n entry = ref\n } catch (error) {\n console.error('[commerce] a sold-out flip could not be queued', hostId, error)\n }\n try {\n const dropped = await dropCache({ hostIds: [hostId], reason })\n if (dropped.complete && entry) await entry.delete().catch(() => undefined)\n if (!dropped.complete && !entry) {\n console.error(\n JSON.stringify({ tag: 'AGL-4121:sold-out-drop-lost', hostId, reason }),\n )\n }\n } catch (error) {\n console.error('[commerce] a sold-out flip did not reach the live site', hostId, error)\n }\n}\n"],"names":["createResourceUid","dropPluginSiteCache","firebaseAdmin","FieldValue","CommerceModel","soldOutSignature","product","backorder","oversellPolicy","variants","map","variant","inventory","Number","productStockFields","soldOut","join","soldOutMoved","before","after","dropStorefrontPages","options","deps","hostId","reason","firestore","app","dropCache","entry","ref","collection","doc","set","paths","createdAt","serverTimestamp","attempts","entireHost","slice","error","console","dropped","hostIds","complete","delete","catch","undefined","JSON","stringify","tag"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,sEAAsE;AACtE,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,SAASC,UAAU,QAAQ,2BAA0B;AACrD,YAAYC,mBAAmB,oBAAU;AAyBzC,6EAA6E,GAC7E,OAAO,SAASC,iBAAiBC,OAAsC;QAGnDA;IAFlB,IAAI,CAACA,SAAS,OAAO;IACrB,MAAMC,YAAYD,QAAQE,cAAc,KAAK;IAC7C,MAAMC,WAAW,EAACH,oBAAAA,QA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,GAAGC,KAAK,CAAC,IAAMC;QAChE,IAAI,CAACL,QAAQE,QAAQ,IAAI,CAACf,OAAO;YAC/BY,QAAQD,KAAK,CACXQ,KAAKC,SAAS,CAAC;gBAAEC,KAAK;gBAA+B1B;gBAAQC;YAAO;QAExE;IACF,EAAE,OAAOe,OAAO;QACdC,QAAQD,KAAK,CAAC,0DAA0DhB,QAAQgB;IAClF;AACF"}
@@ -18,6 +18,7 @@ import { createResourceUid } from "@aglyn/aglyn/server";
18
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin/server/firebase-admin";
19
19
  import * as CommerceModel from "../model/index.js";
20
20
  import { alertLowStockCrossing } from "./low-stock.js";
21
+ import { dropStorefrontPages, soldOutMoved } from "./sold-out-drop.js";
21
22
  /**
22
23
  * COUNTS FROM SOMEWHERE ELSE, APPLIED AS THIS PLUGIN APPLIES ANY COUNT
23
24
  * (AGL-3634): commerce's implementation of core's `core.stock-levels`.
@@ -173,6 +174,14 @@ const normalizeSku = (value)=>String(value != null ? value : '').trim().slice(0,
173
174
  };
174
175
  });
175
176
  if (outcome.before && outcome.after) alertLowStockCrossing(hostId, outcome.before, outcome.after);
177
+ // A synced count that sold a product out, or brought it back, reaches the
178
+ // storefront (AGL-4121).
179
+ if (soldOutMoved(outcome.before, outcome.after)) {
180
+ await dropStorefrontPages({
181
+ hostId,
182
+ reason: 'an inventory sync moved a sold-out verdict'
183
+ });
184
+ }
176
185
  return outcome.results;
177
186
  }
178
187
  /** The strongest outcome across the variants one SKU names: a change beats no change. */ const RANK = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stock-levels.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 {\n PluginStockLevelOutcome,\n PluginStockLevelResult,\n PluginStockLevels,\n} from '@aglyn/aglyn/plugin-manager/plugin-stock-levels'\nimport { createResourceUid } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport * as CommerceModel from '../model'\nimport { alertLowStockCrossing } from './low-stock'\n\n/**\n * COUNTS FROM SOMEWHERE ELSE, APPLIED AS THIS PLUGIN APPLIES ANY COUNT\n * (AGL-3634): commerce's implementation of core's `core.stock-levels`.\n *\n * A fulfillment network's warehouse holds the goods, so its count is the\n * true one. Each count is applied the way a merchant's own stock-take is:\n *\n * - inside a transaction on the product, so a sale landing at the same\n * moment is decremented from the count this write set, never lost under\n * it (the AGL-2320 reasoning);\n * - with an `inventoryAdjustments` row in the same transaction, reason\n * `sync` and the counter named as `source`, so the stock history says who\n * moved the number and by how much;\n * - with the product's roll-up and sold-out flag rewritten, its\n * `updatedAtMs` moved so shopping-channel feeds pick the change up, and\n * the low-stock alert raised on a crossing. Back-in-stock email needs\n * nothing here: its cron reads the count.\n *\n * Matched by SKU across the store's products that are not deleted. A\n * variant that does not track stock is left alone (`untracked`), and so is\n * one that counts stock per location (`per_location`): one number written\n * over its buckets would erase the counts the merchant keeps by hand.\n */\n\nconst PRODUCTS_PER_PAGE = 300\n/** The most products one call walks to find its SKUs. */\nconst MAX_PRODUCTS_SCANNED = 20_000\nconst SKU_MAX = 120\n\ntype Firestore = FirebaseFirestore.Firestore\n\ninterface Located {\n productId: string\n variantId: string\n}\n\nconst normalizeSku = (value: unknown): string => String(value ?? '').trim().slice(0, SKU_MAX)\n\n/** Every live variant of the store whose SKU is one of `wanted`, by SKU. */\nasync function locateSkus(firestore: Firestore, hostId: string, wanted: ReadonlySet<string>) {\n const found = new Map<string, Located[]>()\n const products = firestore.collection('hosts').doc(hostId).collection('products')\n let cursor: string | null = null\n let scanned = 0\n while (scanned < MAX_PRODUCTS_SCANNED) {\n let query = products.orderBy(firebaseAdmin.firestore.FieldPath.documentId()).limit(PRODUCTS_PER_PAGE)\n if (cursor) query = query.startAfter(cursor)\n const page = await query.get()\n for (const doc of page.docs) {\n const data = doc.data() ?? {}\n if (data['deletedAt']) continue\n const variants = Array.isArray(data['variants']) ? (data['variants'] as Array<Record<string, unknown>>) : []\n for (const variant of variants) {\n const sku = normalizeSku(variant['sku'])\n if (!sku || !wanted.has(sku) || !variant['id']) continue\n const list = found.get(sku) ?? []\n list.push({ productId: doc.id, variantId: String(variant['id']) })\n found.set(sku, list)\n }\n }\n scanned += page.size\n if (page.size < PRODUCTS_PER_PAGE) break\n cursor = page.docs[page.docs.length - 1]?.id ?? null\n }\n return found\n}\n\n/** Applies one product's counts in one transaction; answers each variant's outcome. */\nasync function applyToProduct(input: {\n firestore: Firestore\n hostId: string\n productId: string\n counts: ReadonlyMap<string, { sku: string; quantity: number }>\n source: string\n nowMs: number\n}): Promise<Map<string, PluginStockLevelResult>> {\n const { firestore, hostId, productId, counts, source, nowMs } = input\n const productRef = firestore.collection('hosts').doc(hostId).collection('products').doc(productId)\n const host = firestore.collection('hosts').doc(hostId)\n const outcome = await firestore.runTransaction(async (transaction) => {\n const results = new Map<string, PluginStockLevelResult>()\n const snapshot = await transaction.get(productRef)\n if (!snapshot.exists || snapshot.get('deletedAt')) {\n for (const [variantId, count] of counts) results.set(variantId, { sku: count.sku, outcome: 'unknown_sku' })\n return { results, before: null, after: null }\n }\n const before = CommerceModel.liftLegacyProduct(snapshot.data() as never)\n const rows: CommerceModel.InventoryAdjustment[] = []\n const variants = before.variants.map((variant) => {\n const count = counts.get(variant.id)\n if (!count) return variant\n if (variant.inventory == null) {\n results.set(variant.id, { sku: count.sku, outcome: 'untracked' })\n return variant\n }\n const current = Number(variant.inventory)\n if (variant.inventoryByLocation && Object.keys(variant.inventoryByLocation).length > 0) {\n results.set(variant.id, { sku: count.sku, outcome: 'per_location', before: current })\n return variant\n }\n if (current === count.quantity) {\n results.set(variant.id, { sku: count.sku, outcome: 'unchanged', before: current, after: current })\n return variant\n }\n rows.push({\n productId,\n variantId: variant.id,\n delta: count.quantity - current,\n reason: 'sync',\n source,\n atMs: nowMs,\n })\n results.set(variant.id, { sku: count.sku, outcome: 'updated', before: current, after: count.quantity })\n return { ...variant, inventory: count.quantity }\n })\n for (const [variantId, count] of counts) {\n if (!results.has(variantId)) results.set(variantId, { sku: count.sku, outcome: 'unknown_sku' })\n }\n if (!rows.length) return { results, before: null, after: null }\n const after = { ...before, variants }\n transaction.set(\n productRef,\n { variants, ...CommerceModel.productStockFields(after), updatedAtMs: nowMs },\n { merge: true },\n )\n for (const row of rows) transaction.set(host.collection('inventoryAdjustments').doc(createResourceUid()), row)\n return { results, before, after }\n })\n if (outcome.before && outcome.after) alertLowStockCrossing(hostId, outcome.before, outcome.after)\n return outcome.results\n}\n\n/** The strongest outcome across the variants one SKU names: a change beats no change. */\nconst RANK: Record<PluginStockLevelOutcome, number> = {\n updated: 7,\n unchanged: 6,\n per_location: 5,\n untracked: 4,\n failed: 3,\n invalid: 2,\n unknown_sku: 1,\n}\n\nexport async function setAvailableStock(\n request: Parameters<PluginStockLevels['setAvailable']>[0],\n firestore: Firestore = firebaseAdmin.app().firestore(),\n): Promise<PluginStockLevelResult[]> {\n const source = String(request.source ?? '').trim().slice(0, 60) || 'Sync'\n const asked = request.levels.map((level) => {\n const sku = normalizeSku(level?.sku)\n const quantity = Number(level?.quantity)\n const valid = Boolean(sku) && Number.isInteger(quantity) && quantity >= 0 && quantity <= 10_000_000\n return { sku, quantity, valid }\n })\n const latest = new Map<string, number>()\n for (const entry of asked) if (entry.valid) latest.set(entry.sku, entry.quantity)\n const bySku = new Map<string, PluginStockLevelResult>()\n if (latest.size) {\n const located = await locateSkus(firestore, request.hostId, new Set(latest.keys()))\n const byProduct = new Map<string, Map<string, { sku: string; quantity: number }>>()\n for (const [sku, places] of located) {\n for (const place of places) {\n const counts = byProduct.get(place.productId) ?? new Map()\n counts.set(place.variantId, { sku, quantity: latest.get(sku) ?? 0 })\n byProduct.set(place.productId, counts)\n }\n }\n const nowMs = Date.now()\n for (const [productId, counts] of byProduct) {\n let results: Map<string, PluginStockLevelResult>\n try {\n results = await applyToProduct({ firestore, hostId: request.hostId, productId, counts, source, nowMs })\n } catch (error) {\n console.error('[stock-levels] count not applied', request.hostId, productId, error)\n results = new Map([...counts].map(([variantId, count]) => [variantId, { sku: count.sku, outcome: 'failed' }]))\n }\n for (const result of results.values()) {\n const held = bySku.get(result.sku)\n if (!held || RANK[result.outcome] > RANK[held.outcome]) bySku.set(result.sku, result)\n }\n }\n }\n return asked.map((entry) => {\n if (!entry.valid) return { sku: entry.sku, outcome: 'invalid' as const }\n return bySku.get(entry.sku) ?? { sku: entry.sku, outcome: 'unknown_sku' as const }\n })\n}\n\nexport const commerceStockLevels: PluginStockLevels = {\n setAvailable: (request) => setAvailableStock(request),\n}\n"],"names":["createResourceUid","firebaseAdmin","CommerceModel","alertLowStockCrossing","PRODUCTS_PER_PAGE","MAX_PRODUCTS_SCANNED","SKU_MAX","normalizeSku","value","String","trim","slice","locateSkus","firestore","hostId","wanted","found","Map","products","collection","doc","cursor","scanned","page","query","orderBy","FieldPath","documentId","limit","startAfter","get","docs","data","variants","Array","isArray","variant","sku","has","list","push","productId","id","variantId","set","size","length","applyToProduct","input","counts","source","nowMs","productRef","host","outcome","runTransaction","transaction","results","snapshot","exists","count","before","after","liftLegacyProduct","rows","map","inventory","current","Number","inventoryByLocation","Object","keys","quantity","delta","reason","atMs","productStockFields","updatedAtMs","merge","row","RANK","updated","unchanged","per_location","untracked","failed","invalid","unknown_sku","setAvailableStock","request","app","asked","levels","level","valid","Boolean","isInteger","latest","entry","bySku","located","Set","byProduct","places","place","Date","now","error","console","result","values","held","commerceStockLevels","setAvailable"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAOD,SAASA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AKuB,MAAMvB,GAAG;4BAAEiB,SAAS;wBAAS;qBAAE;YAC9G;YACA,KAAK,MAAMuD,UAAUpD,QAAQqD,MAAM,GAAI;gBACrC,MAAMC,OAAOZ,MAAMrE,GAAG,CAAC+E,OAAOxE,GAAG;gBACjC,IAAI,CAAC0E,QAAQ/B,IAAI,CAAC6B,OAAOvD,OAAO,CAAC,GAAG0B,IAAI,CAAC+B,KAAKzD,OAAO,CAAC,EAAE6C,MAAMvD,GAAG,CAACiE,OAAOxE,GAAG,EAAEwE;YAChF;QACF;IACF;IACA,OAAOlB,MAAM1B,GAAG,CAAC,CAACiC;YAETC;QADP,IAAI,CAACD,MAAMJ,KAAK,EAAE,OAAO;YAAEzD,KAAK6D,MAAM7D,GAAG;YAAEiB,SAAS;QAAmB;QACvE,QAAO6C,aAAAA,MAAMrE,GAAG,CAACoE,MAAM7D,GAAG,aAAnB8D,aAAwB;YAAE9D,KAAK6D,MAAM7D,GAAG;YAAEiB,SAAS;QAAuB;IACnF;AACF;AAEA,OAAO,MAAM0D,sBAAyC;IACpDC,cAAc,CAACxB,UAAYD,kBAAkBC;AAC/C,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/stock-levels.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 {\n PluginStockLevelOutcome,\n PluginStockLevelResult,\n PluginStockLevels,\n} from '@aglyn/aglyn/plugin-manager/plugin-stock-levels'\nimport { createResourceUid } from '@aglyn/aglyn/server'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin/server/firebase-admin'\nimport * as CommerceModel from '../model'\nimport { alertLowStockCrossing } from './low-stock'\nimport { dropStorefrontPages, soldOutMoved } from './sold-out-drop'\n\n/**\n * COUNTS FROM SOMEWHERE ELSE, APPLIED AS THIS PLUGIN APPLIES ANY COUNT\n * (AGL-3634): commerce's implementation of core's `core.stock-levels`.\n *\n * A fulfillment network's warehouse holds the goods, so its count is the\n * true one. Each count is applied the way a merchant's own stock-take is:\n *\n * - inside a transaction on the product, so a sale landing at the same\n * moment is decremented from the count this write set, never lost under\n * it (the AGL-2320 reasoning);\n * - with an `inventoryAdjustments` row in the same transaction, reason\n * `sync` and the counter named as `source`, so the stock history says who\n * moved the number and by how much;\n * - with the product's roll-up and sold-out flag rewritten, its\n * `updatedAtMs` moved so shopping-channel feeds pick the change up, and\n * the low-stock alert raised on a crossing. Back-in-stock email needs\n * nothing here: its cron reads the count.\n *\n * Matched by SKU across the store's products that are not deleted. A\n * variant that does not track stock is left alone (`untracked`), and so is\n * one that counts stock per location (`per_location`): one number written\n * over its buckets would erase the counts the merchant keeps by hand.\n */\n\nconst PRODUCTS_PER_PAGE = 300\n/** The most products one call walks to find its SKUs. */\nconst MAX_PRODUCTS_SCANNED = 20_000\nconst SKU_MAX = 120\n\ntype Firestore = FirebaseFirestore.Firestore\n\ninterface Located {\n productId: string\n variantId: string\n}\n\nconst normalizeSku = (value: unknown): string => String(value ?? '').trim().slice(0, SKU_MAX)\n\n/** Every live variant of the store whose SKU is one of `wanted`, by SKU. */\nasync function locateSkus(firestore: Firestore, hostId: string, wanted: ReadonlySet<string>) {\n const found = new Map<string, Located[]>()\n const products = firestore.collection('hosts').doc(hostId).collection('products')\n let cursor: string | null = null\n let scanned = 0\n while (scanned < MAX_PRODUCTS_SCANNED) {\n let query = products.orderBy(firebaseAdmin.firestore.FieldPath.documentId()).limit(PRODUCTS_PER_PAGE)\n if (cursor) query = query.startAfter(cursor)\n const page = await query.get()\n for (const doc of page.docs) {\n const data = doc.data() ?? {}\n if (data['deletedAt']) continue\n const variants = Array.isArray(data['variants']) ? (data['variants'] as Array<Record<string, unknown>>) : []\n for (const variant of variants) {\n const sku = normalizeSku(variant['sku'])\n if (!sku || !wanted.has(sku) || !variant['id']) continue\n const list = found.get(sku) ?? []\n list.push({ productId: doc.id, variantId: String(variant['id']) })\n found.set(sku, list)\n }\n }\n scanned += page.size\n if (page.size < PRODUCTS_PER_PAGE) break\n cursor = page.docs[page.docs.length - 1]?.id ?? null\n }\n return found\n}\n\n/** Applies one product's counts in one transaction; answers each variant's outcome. */\nasync function applyToProduct(input: {\n firestore: Firestore\n hostId: string\n productId: string\n counts: ReadonlyMap<string, { sku: string; quantity: number }>\n source: string\n nowMs: number\n}): Promise<Map<string, PluginStockLevelResult>> {\n const { firestore, hostId, productId, counts, source, nowMs } = input\n const productRef = firestore.collection('hosts').doc(hostId).collection('products').doc(productId)\n const host = firestore.collection('hosts').doc(hostId)\n const outcome = await firestore.runTransaction(async (transaction) => {\n const results = new Map<string, PluginStockLevelResult>()\n const snapshot = await transaction.get(productRef)\n if (!snapshot.exists || snapshot.get('deletedAt')) {\n for (const [variantId, count] of counts) results.set(variantId, { sku: count.sku, outcome: 'unknown_sku' })\n return { results, before: null, after: null }\n }\n const before = CommerceModel.liftLegacyProduct(snapshot.data() as never)\n const rows: CommerceModel.InventoryAdjustment[] = []\n const variants = before.variants.map((variant) => {\n const count = counts.get(variant.id)\n if (!count) return variant\n if (variant.inventory == null) {\n results.set(variant.id, { sku: count.sku, outcome: 'untracked' })\n return variant\n }\n const current = Number(variant.inventory)\n if (variant.inventoryByLocation && Object.keys(variant.inventoryByLocation).length > 0) {\n results.set(variant.id, { sku: count.sku, outcome: 'per_location', before: current })\n return variant\n }\n if (current === count.quantity) {\n results.set(variant.id, { sku: count.sku, outcome: 'unchanged', before: current, after: current })\n return variant\n }\n rows.push({\n productId,\n variantId: variant.id,\n delta: count.quantity - current,\n reason: 'sync',\n source,\n atMs: nowMs,\n })\n results.set(variant.id, { sku: count.sku, outcome: 'updated', before: current, after: count.quantity })\n return { ...variant, inventory: count.quantity }\n })\n for (const [variantId, count] of counts) {\n if (!results.has(variantId)) results.set(variantId, { sku: count.sku, outcome: 'unknown_sku' })\n }\n if (!rows.length) return { results, before: null, after: null }\n const after = { ...before, variants }\n transaction.set(\n productRef,\n { variants, ...CommerceModel.productStockFields(after), updatedAtMs: nowMs },\n { merge: true },\n )\n for (const row of rows) transaction.set(host.collection('inventoryAdjustments').doc(createResourceUid()), row)\n return { results, before, after }\n })\n if (outcome.before && outcome.after) alertLowStockCrossing(hostId, outcome.before, outcome.after)\n // A synced count that sold a product out, or brought it back, reaches the\n // storefront (AGL-4121).\n if (soldOutMoved(outcome.before, outcome.after)) {\n await dropStorefrontPages({ hostId, reason: 'an inventory sync moved a sold-out verdict' })\n }\n return outcome.results\n}\n\n/** The strongest outcome across the variants one SKU names: a change beats no change. */\nconst RANK: Record<PluginStockLevelOutcome, number> = {\n updated: 7,\n unchanged: 6,\n per_location: 5,\n untracked: 4,\n failed: 3,\n invalid: 2,\n unknown_sku: 1,\n}\n\nexport async function setAvailableStock(\n request: Parameters<PluginStockLevels['setAvailable']>[0],\n firestore: Firestore = firebaseAdmin.app().firestore(),\n): Promise<PluginStockLevelResult[]> {\n const source = String(request.source ?? '').trim().slice(0, 60) || 'Sync'\n const asked = request.levels.map((level) => {\n const sku = normalizeSku(level?.sku)\n const quantity = Number(level?.quantity)\n const valid = Boolean(sku) && Number.isInteger(quantity) && quantity >= 0 && quantity <= 10_000_000\n return { sku, quantity, valid }\n })\n const latest = new Map<string, number>()\n for (const entry of asked) if (entry.valid) latest.set(entry.sku, entry.quantity)\n const bySku = new Map<string, PluginStockLevelResult>()\n if (latest.size) {\n const located = await locateSkus(firestore, request.hostId, new Set(latest.keys()))\n const byProduct = new Map<string, Map<string, { sku: string; quantity: number }>>()\n for (const [sku, places] of located) {\n for (const place of places) {\n const counts = byProduct.get(place.productId) ?? new Map()\n counts.set(place.variantId, { sku, quantity: latest.get(sku) ?? 0 })\n byProduct.set(place.productId, counts)\n }\n }\n const nowMs = Date.now()\n for (const [productId, counts] of byProduct) {\n let results: Map<string, PluginStockLevelResult>\n try {\n results = await applyToProduct({ firestore, hostId: request.hostId, productId, counts, source, nowMs })\n } catch (error) {\n console.error('[stock-levels] count not applied', request.hostId, productId, error)\n results = new Map([...counts].map(([variantId, count]) => [variantId, { sku: count.sku, outcome: 'failed' }]))\n }\n for (const result of results.values()) {\n const held = bySku.get(result.sku)\n if (!held || RANK[result.outcome] > RANK[held.outcome]) bySku.set(result.sku, result)\n }\n }\n }\n return asked.map((entry) => {\n if (!entry.valid) return { sku: entry.sku, outcome: 'invalid' as const }\n return bySku.get(entry.sku) ?? { sku: entry.sku, outcome: 'unknown_sku' as const }\n })\n}\n\nexport const commerceStockLevels: PluginStockLevels = {\n setAvailable: (request) => setAvailableStock(request),\n}\n"],"names":["createResourceUid","firebaseAdmin","CommerceModel","alertLowStockCrossing","dropStorefrontPages","soldOutMoved","PRODUCTS_PER_PAGE","MAX_PRODUCTS_SCANNED","SKU_MAX","normalizeSku","value","String","trim","slice","locateSkus","firestore","hostId","wanted","found","Map","products","collection","doc","cursor","scanned","page","query","orderBy","FieldPath","documentId","limit","startAfter","get","docs","data","variants","Array","isArray","variant","sku","has","list","push","productId","id","variantId","set","size","length","applyToProduct","input","counts","source","nowMs","productRef","host","outcome","runTransaction","transaction","results","snapshot","exists","count","before","after","liftLegacyProduct","rows","map","inventory","current","Number","inventoryByLocation","Object","keys","quantity","delta","reason","atMs","productStockFields","updatedAtMs","merge","row","RANK","updated","unchanged","per_location","untracked","failed","invalid","unknown_sku","setAvailableStock","request","app","asked","levels","level","valid","Boolean","isInteger","latest","entry","bySku","located","Set","byProduct","places","place","Date","now","error","console","result","values","held","commerceStockLevels","setAvailable"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAOD,SAASA,iBAAiB,QAAQ,sBAAqB;AACvD,SAASC,aAAa,QAAQ,iDAAgD;AAC9E,Y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WAAWkE;gBAC7ElD,UAAU,IAAIxC,IAAI;uBAAIgC;iBAAO,CAACgB,GAAG,CAAC,CAAC,CAACtB,WAAWiB,MAAM,GAAK;wBAACjB;wBAAW;4BAAEN,KAAKuB,MAAMvB,GAAG;4BAAEiB,SAAS;wBAAS;qBAAE;YAC9G;YACA,KAAK,MAAMuD,UAAUpD,QAAQqD,MAAM,GAAI;gBACrC,MAAMC,OAAOZ,MAAMrE,GAAG,CAAC+E,OAAOxE,GAAG;gBACjC,IAAI,CAAC0E,QAAQ/B,IAAI,CAAC6B,OAAOvD,OAAO,CAAC,GAAG0B,IAAI,CAAC+B,KAAKzD,OAAO,CAAC,EAAE6C,MAAMvD,GAAG,CAACiE,OAAOxE,GAAG,EAAEwE;YAChF;QACF;IACF;IACA,OAAOlB,MAAM1B,GAAG,CAAC,CAACiC;YAETC;QADP,IAAI,CAACD,MAAMJ,KAAK,EAAE,OAAO;YAAEzD,KAAK6D,MAAM7D,GAAG;YAAEiB,SAAS;QAAmB;QACvE,QAAO6C,aAAAA,MAAMrE,GAAG,CAACoE,MAAM7D,GAAG,aAAnB8D,aAAwB;YAAE9D,KAAK6D,MAAM7D,GAAG;YAAEiB,SAAS;QAAuB;IACnF;AACF;AAEA,OAAO,MAAM0D,sBAAyC;IACpDC,cAAc,CAACxB,UAAYD,kBAAkBC;AAC/C,EAAC"}
@@ -38,6 +38,13 @@
38
38
  * refunded on the platform as a destination charge, so a caller may pass the
39
39
  * site's direct-charge account without first asking which kind the sale was.
40
40
  */
41
+ /**
42
+ * Stripe's answer when `refund_application_fee` is sent on a charge that
43
+ * carried no application fee: a direct sale on a plan whose take is 0%
44
+ * sends no fee at all. The refund is then sent again without the flag
45
+ * (there is nothing of the platform's to hand back), never failed.
46
+ */
47
+ export declare function isNoApplicationFeeToRefund(body: unknown): boolean;
41
48
  export type StripeRefundResult = {
42
49
  ok: true;
43
50
  refundId: string;
@@ -1,3 +1,4 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
1
2
  /**
2
3
  * @license
3
4
  * Copyright 2026 Aglyn LLC
@@ -36,7 +37,17 @@
36
37
  * know (a sale from before the seller switched, or Aglyn's own hardware) is
37
38
  * refunded on the platform as a destination charge, so a caller may pass the
38
39
  * site's direct-charge account without first asking which kind the sale was.
39
- */ import { _ as _extends } from "@swc/helpers/_/_extends";
40
+ */ /**
41
+ * Stripe's answer when `refund_application_fee` is sent on a charge that
42
+ * carried no application fee: a direct sale on a plan whose take is 0%
43
+ * sends no fee at all. The refund is then sent again without the flag
44
+ * (there is nothing of the platform's to hand back), never failed.
45
+ */ export function isNoApplicationFeeToRefund(body) {
46
+ var _error_message;
47
+ const error = body == null ? void 0 : body.error;
48
+ if (!error) return false;
49
+ return error.param === 'refund_application_fee' || /no application fee to refund/i.test(String((_error_message = error.message) != null ? _error_message : ''));
50
+ }
40
51
  export async function createStripeRefund(input) {
41
52
  var _input_secretKey, _input_fetch, _ref, _ref1;
42
53
  var _refund_error, _refund_error1;
@@ -50,16 +61,16 @@ export async function createStripeRefund(input) {
50
61
  };
51
62
  }
52
63
  const send = (_input_fetch = input.fetch) != null ? _input_fetch : fetch;
53
- const post = (stripeAccount)=>{
64
+ const post = (stripeAccount, withFee = true)=>{
54
65
  var _input_metadata;
55
66
  const params = new URLSearchParams(_extends({
56
67
  payment_intent: input.paymentIntentId,
57
68
  amount: String(Math.round(input.amountCents))
58
69
  }, stripeAccount ? {} : {
59
70
  reverse_transfer: 'true'
60
- }, {
71
+ }, withFee ? {
61
72
  refund_application_fee: 'true'
62
- }));
73
+ } : {}));
63
74
  for (const [key, value] of Object.entries((_input_metadata = input.metadata) != null ? _input_metadata : {})){
64
75
  params.set(`metadata[${key}]`, value);
65
76
  }
@@ -69,7 +80,7 @@ export async function createStripeRefund(input) {
69
80
  Authorization: `Bearer ${secretKey}`,
70
81
  'Content-Type': 'application/x-www-form-urlencoded'
71
82
  }, input.idempotencyKey ? {
72
- 'Idempotency-Key': input.idempotencyKey
83
+ 'Idempotency-Key': withFee ? input.idempotencyKey : `${input.idempotencyKey}:no-fee`
73
84
  } : {}, stripeAccount ? {
74
85
  'Stripe-Account': stripeAccount
75
86
  } : {}),
@@ -78,13 +89,21 @@ export async function createStripeRefund(input) {
78
89
  };
79
90
  const stripeAccount = typeof input.stripeAccount === 'string' && input.stripeAccount.trim() ? input.stripeAccount.trim() : null;
80
91
  const read = async (sent)=>await Promise.resolve().then(()=>sent.json()).catch(()=>({}));
81
- let response = await post(stripeAccount);
92
+ let target = stripeAccount;
93
+ let response = await post(target);
82
94
  let refund = await read(response);
83
95
  // Not the seller's payment: a destination sale on the platform. Stripe
84
96
  // answers a payment intent another account owns as `resource_missing`, and
85
97
  // scopes idempotency keys per account, so the same key is safe there.
86
98
  if (stripeAccount && !response.ok && (response.status === 404 || (refund == null ? void 0 : (_refund_error = refund.error) == null ? void 0 : _refund_error.code) === 'resource_missing' && ((_ref = refund == null ? void 0 : (_refund_error1 = refund.error) == null ? void 0 : _refund_error1.param) != null ? _ref : 'payment_intent') === 'payment_intent')) {
87
- response = await post(null);
99
+ target = null;
100
+ response = await post(target);
101
+ refund = await read(response);
102
+ }
103
+ // No platform fee on the charge (a 0% plan): refund without the flag, on
104
+ // the account the last attempt reached.
105
+ if (!response.ok && isNoApplicationFeeToRefund(refund)) {
106
+ response = await post(target, false);
88
107
  refund = await read(response);
89
108
  }
90
109
  if (!response.ok) {