@aglyn/plugins-commerce 1.30.0 → 1.32.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 (132) hide show
  1. package/README.md +4 -0
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +46 -20
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/commerce-console-page.js +6 -0
  6. package/src/lib/components/commerce-console-page.js.map +1 -1
  7. package/src/lib/components/console/currencies-card.component.d.ts +21 -0
  8. package/src/lib/components/console/currencies-card.component.js +408 -0
  9. package/src/lib/components/console/currencies-card.component.js.map +1 -0
  10. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  11. package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
  12. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  13. package/src/lib/components/console/product-editor-dialog.component.js +47 -1
  14. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  15. package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
  16. package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
  17. package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
  18. package/src/lib/components/console/product-traffic-card.component.d.ts +24 -0
  19. package/src/lib/components/console/product-traffic-card.component.js +172 -0
  20. package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
  21. package/src/lib/components/console/products-hub-card.component.js +181 -59
  22. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  23. package/src/lib/components/console/reservations-card.component.js +32 -15
  24. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  25. package/src/lib/components/console/shipping-settings-card.component.js +131 -10
  26. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  27. package/src/lib/components/console/store-settings-card.component.js +1 -1
  28. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  29. package/src/lib/components/console/use-currency-setup.d.ts +20 -0
  30. package/src/lib/components/console/use-currency-setup.js +61 -0
  31. package/src/lib/components/console/use-currency-setup.js.map +1 -0
  32. package/src/lib/components/currency-selector.d.ts +36 -0
  33. package/src/lib/components/currency-selector.js +157 -0
  34. package/src/lib/components/currency-selector.js.map +1 -0
  35. package/src/lib/components/product-add-ons.d.ts +9 -1
  36. package/src/lib/components/product-add-ons.js +8 -4
  37. package/src/lib/components/product-add-ons.js.map +1 -1
  38. package/src/lib/components/product-choice-cards.d.ts +13 -1
  39. package/src/lib/components/product-choice-cards.js +5 -4
  40. package/src/lib/components/product-choice-cards.js.map +1 -1
  41. package/src/lib/components/product-detail.d.ts +8 -0
  42. package/src/lib/components/product-detail.js +38 -11
  43. package/src/lib/components/product-detail.js.map +1 -1
  44. package/src/lib/components/product-grid.d.ts +2 -0
  45. package/src/lib/components/product-grid.js +22 -9
  46. package/src/lib/components/product-grid.js.map +1 -1
  47. package/src/lib/components/related-products.js +6 -2
  48. package/src/lib/components/related-products.js.map +1 -1
  49. package/src/lib/components/shopper-currency.d.ts +108 -0
  50. package/src/lib/components/shopper-currency.js +262 -0
  51. package/src/lib/components/shopper-currency.js.map +1 -0
  52. package/src/lib/components/wishlist.js +7 -1
  53. package/src/lib/components/wishlist.js.map +1 -1
  54. package/src/lib/declarations.server.js +39 -0
  55. package/src/lib/declarations.server.js.map +1 -1
  56. package/src/lib/model/commerce-currency-setup.d.ts +79 -0
  57. package/src/lib/model/commerce-currency-setup.js +124 -0
  58. package/src/lib/model/commerce-currency-setup.js.map +1 -0
  59. package/src/lib/model/commerce-currency.d.ts +215 -0
  60. package/src/lib/model/commerce-currency.js +511 -0
  61. package/src/lib/model/commerce-currency.js.map +1 -0
  62. package/src/lib/model/commerce-orders.d.ts +17 -0
  63. package/src/lib/model/commerce-orders.js +10 -5
  64. package/src/lib/model/commerce-orders.js.map +1 -1
  65. package/src/lib/model/commerce-record-routes.js +56 -0
  66. package/src/lib/model/commerce-record-routes.js.map +1 -1
  67. package/src/lib/model/commerce-reservations.d.ts +6 -0
  68. package/src/lib/model/commerce-reservations.js.map +1 -1
  69. package/src/lib/model/commerce-shipping.d.ts +61 -17
  70. package/src/lib/model/commerce-shipping.js +346 -32
  71. package/src/lib/model/commerce-shipping.js.map +1 -1
  72. package/src/lib/model/commerce.d.ts +6 -0
  73. package/src/lib/model/commerce.js.map +1 -1
  74. package/src/lib/model/index.d.ts +2 -0
  75. package/src/lib/model/index.js +2 -0
  76. package/src/lib/model/index.js.map +1 -1
  77. package/src/lib/model/order-figures.js +9 -2
  78. package/src/lib/model/order-figures.js.map +1 -1
  79. package/src/lib/model/product-modifiers.d.ts +5 -0
  80. package/src/lib/model/product-modifiers.js.map +1 -1
  81. package/src/lib/model/product-write.d.ts +10 -1
  82. package/src/lib/model/product-write.js +13 -2
  83. package/src/lib/model/product-write.js.map +1 -1
  84. package/src/lib/server/billing-webhook.js +37 -24
  85. package/src/lib/server/billing-webhook.js.map +1 -1
  86. package/src/lib/server/carrier-shipping.js +3 -2
  87. package/src/lib/server/carrier-shipping.js.map +1 -1
  88. package/src/lib/server/cart-checkout.js +77 -15
  89. package/src/lib/server/cart-checkout.js.map +1 -1
  90. package/src/lib/server/cart.d.ts +12 -0
  91. package/src/lib/server/cart.js +52 -6
  92. package/src/lib/server/cart.js.map +1 -1
  93. package/src/lib/server/catalog.d.ts +5 -0
  94. package/src/lib/server/catalog.js +7 -0
  95. package/src/lib/server/catalog.js.map +1 -1
  96. package/src/lib/server/checkout.js +54 -16
  97. package/src/lib/server/checkout.js.map +1 -1
  98. package/src/lib/server/currency.d.ts +93 -0
  99. package/src/lib/server/currency.js +182 -0
  100. package/src/lib/server/currency.js.map +1 -0
  101. package/src/lib/server/draft-order.js +3 -3
  102. package/src/lib/server/draft-order.js.map +1 -1
  103. package/src/lib/server/order-notifications.js +4 -2
  104. package/src/lib/server/order-notifications.js.map +1 -1
  105. package/src/lib/server/product.d.ts +9 -0
  106. package/src/lib/server/product.js +12 -0
  107. package/src/lib/server/product.js.map +1 -1
  108. package/src/lib/server/products-write.js +10 -2
  109. package/src/lib/server/products-write.js.map +1 -1
  110. package/src/lib/server/refund.js +3 -3
  111. package/src/lib/server/refund.js.map +1 -1
  112. package/src/lib/server/site-chat-tools.d.ts +22 -0
  113. package/src/lib/server/site-chat-tools.js +369 -0
  114. package/src/lib/server/site-chat-tools.js.map +1 -0
  115. package/src/lib/server/site-chat-visitor.d.ts +24 -0
  116. package/src/lib/server/site-chat-visitor.js +39 -0
  117. package/src/lib/server/site-chat-visitor.js.map +1 -0
  118. package/src/lib/server/site-offers.d.ts +31 -0
  119. package/src/lib/server/site-offers.js +91 -0
  120. package/src/lib/server/site-offers.js.map +1 -0
  121. package/src/lib/server/stays-site-search.d.ts +20 -0
  122. package/src/lib/server/stays-site-search.js +78 -0
  123. package/src/lib/server/stays-site-search.js.map +1 -0
  124. package/src/lib/server.js +20 -0
  125. package/src/lib/server.js.map +1 -1
  126. package/src/lib/site-chat-tool-definitions.d.ts +26 -0
  127. package/src/lib/site-chat-tool-definitions.js +141 -0
  128. package/src/lib/site-chat-tool-definitions.js.map +1 -0
  129. package/src/lib/site.js +8 -0
  130. package/src/lib/site.js.map +1 -1
  131. package/src/lib/subprocessors.js +7 -0
  132. package/src/lib/subprocessors.js.map +1 -1
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import type { PluginApiHandler } from '@aglyn/aglyn/server';
18
18
  import * as CommerceModel from '../model';
19
+ import { type CheckoutCurrency } from './currency';
19
20
  export interface ResolvedCartLine extends CommerceModel.CartLine {
20
21
  name: string;
21
22
  variantLabel?: string;
@@ -37,3 +38,14 @@ export interface ResolvedCartLine extends CommerceModel.CartLine {
37
38
  * lines surface instead of silently charging.
38
39
  */
39
40
  export declare const cartHandler: PluginApiHandler;
41
+ /**
42
+ * One unit of a line in the checkout currency, as checkout charges it: the
43
+ * variant's price there (its fixed price wins), plus each add-on converted
44
+ * on its own (an add-on's fixed amount wins).
45
+ */
46
+ export declare function cartUnitMinor(currency: CheckoutCurrency, product: {
47
+ modifierGroups?: unknown;
48
+ }, variant: {
49
+ priceUsd?: number;
50
+ fixedPrices?: Record<string, number>;
51
+ }, modifiers: readonly CommerceModel.OrderLineModifier[]): number;
@@ -21,6 +21,7 @@ import { isDocumentId } from "@aglyn/tenant-data-admin/server/document-id";
21
21
  import { cartCookieName, mintCartId, readCartId } from "./cart-cookie.js";
22
22
  import { readStoreDay } from "./store-day.js";
23
23
  import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
24
+ import { checkoutAmountMinor, checkoutVariantMinor, loadFxRates, resolveCheckoutCurrency, storeCurrencyContextFrom } from "./currency.js";
24
25
  /**
25
26
  * Server-backed cart (AGL-293): cookie-keyed doc under
26
27
  * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates
@@ -28,7 +29,7 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
28
29
  * docs on every read so prices/names never go stale, and unavailable
29
30
  * lines surface instead of silently charging.
30
31
  */ export const cartHandler = async (req, res)=>{
31
- var _req_body, _ref;
32
+ var _req_body, _ref, _ref1;
32
33
  const isPost = req.method === 'POST';
33
34
  if (!isPost && req.method !== 'GET') {
34
35
  return res.status(405).json({
@@ -63,6 +64,9 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
63
64
  let cartId = readCartId(req.cookies, hostId);
64
65
  const firestore = firebaseAdmin.app().firestore();
65
66
  const hostRef = firestore.collection('hosts').doc(hostId);
67
+ // The shopper's currency (AGL-4248), asked by a storefront showing another
68
+ // than the store's: the cart prices in it exactly as checkout will charge.
69
+ const requestedCurrency = String((_ref1 = isPost ? body.currency : req.query.currency) != null ? _ref1 : '').trim();
66
70
  try {
67
71
  var _cartSnapshot_data;
68
72
  var _parsePosHardwareInPersonConfig;
@@ -193,6 +197,10 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
193
197
  snapshot.id,
194
198
  snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data()) : null
195
199
  ]));
200
+ const currency = requestedCurrency ? await cartCurrency(hostRef, requestedCurrency) : undefined;
201
+ // Each line in the store currency as well, for what the store's own
202
+ // rules (free shipping over, zones) are written in.
203
+ const baseUnitCents = new Map();
196
204
  const lines = cart.lines.map((line)=>{
197
205
  var _variant_options, _variant_options1, _ref, _variant_imageUrl;
198
206
  var _product_mediaUrls, _product_mediaUrls1;
@@ -232,12 +240,14 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
232
240
  });
233
241
  }
234
242
  const label = CommerceModel.lineLabelWithModifiers(variantLabel, chosen.modifiers);
243
+ const baseCents = Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents;
244
+ baseUnitCents.set(line, baseCents);
235
245
  return _extends({}, line, {
236
246
  name: product.name
237
247
  }, label ? {
238
248
  variantLabel: label
239
249
  } : {}, {
240
- unitAmountCents: Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents
250
+ unitAmountCents: (currency == null ? void 0 : currency.foreign) ? cartUnitMinor(currency, product, variant, chosen.modifiers) : baseCents
241
251
  }, variant.imageUrl || ((_product_mediaUrls = product.mediaUrls) == null ? void 0 : _product_mediaUrls[0]) || product.imageUrl ? {
242
252
  imageUrl: (_ref = (_variant_imageUrl = variant.imageUrl) != null ? _variant_imageUrl : (_product_mediaUrls1 = product.mediaUrls) == null ? void 0 : _product_mediaUrls1[0]) != null ? _ref : product.imageUrl
243
253
  } : {}, CommerceModel.canPurchase(product, variant.id, line.quantity) ? {} : {
@@ -245,6 +255,11 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
245
255
  });
246
256
  });
247
257
  const subtotalCents = lines.filter((line)=>!line.unavailable).reduce((sum, line)=>sum + line.unitAmountCents * line.quantity, 0);
258
+ const baseSubtotalCents = (currency == null ? void 0 : currency.foreign) ? cart.lines.reduce((sum, line, index)=>{
259
+ var _baseUnitCents_get;
260
+ var _lines_index;
261
+ return ((_lines_index = lines[index]) == null ? void 0 : _lines_index.unavailable) ? sum : sum + ((_baseUnitCents_get = baseUnitCents.get(line)) != null ? _baseUnitCents_get : 0) * line.quantity;
262
+ }, 0) : subtotalCents;
248
263
  // Card reader hardware the platform's own store sells (AGL-4038): the
249
264
  // cart asks for the terms of sale before checkout. Read from the
250
265
  // environment first, so no other store reads anything more.
@@ -259,18 +274,20 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
259
274
  hostRef,
260
275
  lines,
261
276
  productsById,
262
- subtotalCents
277
+ subtotalCents: baseSubtotalCents
263
278
  });
264
279
  return res.status(200).json(_extends({
265
280
  lines,
266
281
  count: CommerceModel.cartCount(cart),
267
282
  subtotalCents
268
- }, hardwareTerms ? {
283
+ }, currency ? {
284
+ currency: currency.code
285
+ } : {}, hardwareTerms ? {
269
286
  hardwareTerms: true
270
287
  } : {}, askShippingCountry ? {
271
288
  needsShippingCountry: true,
272
289
  shippingCountries: [
273
- ...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES
290
+ ...askShippingCountry
274
291
  ]
275
292
  } : {}));
276
293
  } catch (error) {
@@ -280,6 +297,35 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
280
297
  });
281
298
  }
282
299
  };
300
+ /**
301
+ * The currency a cart prices in (AGL-4248): the one the storefront asked for
302
+ * when the store sells in it and fresh rates cover it, else the store's,
303
+ * resolved exactly as checkout resolves it.
304
+ */ async function cartCurrency(hostRef, requested) {
305
+ try {
306
+ const [storeSnap, rates] = await Promise.all([
307
+ hostRef.collection('settings').doc('store').get(),
308
+ loadFxRates()
309
+ ]);
310
+ return resolveCheckoutCurrency(storeCurrencyContextFrom(storeSnap.data(), rates), requested);
311
+ } catch (error) {
312
+ // The cart still shows, in the store currency, and says so by omission.
313
+ console.error('commerce: cart currency unavailable', error);
314
+ return undefined;
315
+ }
316
+ }
317
+ /**
318
+ * One unit of a line in the checkout currency, as checkout charges it: the
319
+ * variant's price there (its fixed price wins), plus each add-on converted
320
+ * on its own (an add-on's fixed amount wins).
321
+ */ export function cartUnitMinor(currency, product, variant, modifiers) {
322
+ const groups = CommerceModel.productModifierGroups(product);
323
+ return modifiers.reduce((sum, modifier)=>{
324
+ var _groups_find;
325
+ const option = (_groups_find = groups.find((group)=>group.id === modifier.groupId)) == null ? void 0 : _groups_find.options.find((entry)=>entry.id === modifier.optionId);
326
+ return sum + checkoutAmountMinor(currency, modifier.priceCents, option == null ? void 0 : option.fixedPriceCents);
327
+ }, checkoutVariantMinor(currency, variant));
328
+ }
283
329
  /**
284
330
  * Whether checkout will ask this cart where it is shipping to, answered while
285
331
  * the cart is shown so the cart can ask up front. A shopper who pressed
@@ -317,7 +363,7 @@ import { planCheckoutShippingWithCarriers } from "./carrier-shipping.js";
317
363
  },
318
364
  destination: {}
319
365
  });
320
- return plan.refusal === 'destination-required';
366
+ return plan.refusal === 'destination-required' ? plan.countries : false;
321
367
  } catch (unused) {
322
368
  // The cart still shows; checkout asks, as it always has.
323
369
  return false;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cart.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 { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { cartCookieName, mintCartId, readCartId } from './cart-cookie'\nimport { readStoreDay } from './store-day'\nimport { planCheckoutShippingWithCarriers } from './carrier-shipping'\n\nexport interface ResolvedCartLine extends CommerceModel.CartLine {\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n /** Line no longer purchasable (deleted/draft/sold out). */\n unavailable?: boolean\n /**\n * What the shopper must do about an unavailable line, when the cart can say\n * (AGL-4100): its add-ons no longer answer the product's choices.\n */\n problem?: string\n}\n\n/**\n * Server-backed cart (AGL-293): cookie-keyed doc under\n * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates\n * with {action: add|set|remove|clear}. Lines resolve against product\n * docs on every read so prices/names never go stale, and unavailable\n * lines surface instead of silently charging.\n */\nexport const cartHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n if (!isPost && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const body = isPost\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : {}\n // AGL-1769: BOTH components of the path this handler writes come from the\n // caller — `hostId` off the body, `cartId` off a cookie whose name embeds\n // `hostId` — and `.doc()` appends a slash-separated PATH rather than taking\n // one opaque id. So an unvalidated pair named the nesting as well as the\n // document: a `hostId` of `a/b/c` wrote under `hosts/a/b/c`, invisible to\n // every console list because they resolve the host doc first.\n //\n // This handler is the one visitor-facing write in the AGL-1763 sweep that\n // needs NO credentials — no session, no member gate, no signature — so it is\n // the one place the id rule has to hold on its own.\n const hostId = String((isPost ? body.hostId : req.query.hostId) ?? '')\n // The message names BOTH causes it now covers (`762621581`): the guard reads\n // as \"absent\" but also refuses a hostId that is a path rather than an id, and\n // a caller told only \"missing\" would go looking for the wrong mistake.\n // AGL-1771: `isDocumentId`, not the cart module's old `isCartId` alias — this\n // value is a HOST id, and the rule it has to satisfy was never about carts.\n if (!isDocumentId(hostId))\n return res.status(400).json({ error: 'Missing or invalid hostId' })\n\n const cookieName = cartCookieName(hostId)\n // A cookie that is not a single document id reads as NO cart: a GET returns\n // an empty one and a POST mints a fresh id below, exactly as for a first-time\n // visitor. Nothing is stranded — a path that was never a cart id was never a\n // basket anyone filled.\n let cartId = readCartId(req.cookies, hostId)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n try {\n if (!cartId) {\n if (!isPost) return res.status(200).json({ lines: [], count: 0 })\n cartId = mintCartId()\n res.setHeader(\n 'Set-Cookie',\n `${cookieName}=${cartId}; Path=/; Max-Age=${60 * 60 * 24 * 90}; ` +\n 'HttpOnly; SameSite=Lax; Secure',\n )\n }\n const cartRef = hostRef.collection('carts').doc(cartId)\n const cartSnapshot = await cartRef.get()\n const cart: CommerceModel.HostCart = (cartSnapshot.data() as any) ?? { lines: [] }\n\n if (isPost) {\n const action = String(body.action ?? 'add')\n // The day the shopper chose to use a check-in item (AGL-4043): part of\n // the line's identity, so two days of one pass are two lines.\n const useDayKey = typeof body.useDayKey === 'string' ? body.useDayKey.trim() : ''\n // The add-ons chosen on the product's page (AGL-4100), ids only: part\n // of the line's identity, priced from the product, never from here.\n const requestedModifiers = CommerceModel.modifierSelectionFrom(body.modifiers)\n const line: CommerceModel.CartLine = {\n productId: String(body.productId ?? ''),\n ...(body.variantId ? { variantId: String(body.variantId) } : {}),\n ...(useDayKey ? { useDayKey } : {}),\n ...(requestedModifiers.length ? { modifiers: requestedModifiers } : {}),\n // Clamped at the door as well as in the model (AGL-2285): the route\n // used `Math.round(Number(...))` alone, which yields `NaN` for\n // `{\"quantity\":\"x\"}` and slipped past `upsertCartLine`'s `<= 0` guard.\n quantity: Math.min(\n CommerceModel.CART_MAX_QUANTITY,\n Math.max(\n -CommerceModel.CART_MAX_QUANTITY,\n Number.isFinite(Number(body.quantity ?? 1))\n ? Math.round(Number(body.quantity ?? 1))\n : 0,\n ),\n ),\n }\n if (useDayKey && !CommerceModel.isCheckInDayKey(useDayKey)) {\n return res.status(400).json({ error: 'Choose the day as a date.' })\n }\n if (action === 'clear') {\n cart.lines = []\n } else if (!line.productId) {\n return res.status(400).json({ error: 'Missing productId' })\n } else if (action === 'remove') {\n cart.lines = CommerceModel.removeCartLine(cart, line)\n } else {\n // A product sold in person only (AGL-4060) never enters a basket: it\n // answers as no product at all, as its page does. A line already in\n // the cart stays removable and resolves as unavailable below.\n if (line.quantity > 0 && isDocumentId(line.productId)) {\n const productSnapshot = await hostRef.collection('products').doc(line.productId).get()\n if (productSnapshot.exists && !CommerceModel.productSellsOnline(productSnapshot.data())) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n // A use day is asked only by an item that asks for one, and is a\n // day that has not passed on the store's calendar (AGL-4043).\n const isNewLine = !cart.lines.some(\n (held) => CommerceModel.cartLineKey(held) === CommerceModel.cartLineKey(line),\n )\n const product = productSnapshot.exists ? CommerceModel.liftLegacyProduct(productSnapshot.data() as any) : null\n if (useDayKey && (action === 'add' || isNewLine)) {\n const variantId = line.variantId ?? product?.variants[0]?.id\n if (!product || !CommerceModel.productAsksUseDate(product, variantId)) {\n return res.status(400).json({ error: 'This item has no day to choose.' })\n }\n const problem = CommerceModel.checkInUseDayProblem(useDayKey, (await readStoreDay(hostRef)).todayKey)\n if (problem) return res.status(400).json({ error: problem })\n }\n // Add-ons (AGL-4100): asked of the groups the website shows, every\n // required one answered, and kept as ids in the product's order. A\n // required group left unanswered is refused here, so no line goes\n // in a basket that checkout would have to turn away.\n if (product && (action === 'add' || isNewLine)) {\n const chosen = CommerceModel.resolveWebsiteLineModifiers(\n product,\n line.modifiers,\n line.variantId ?? product.variants[0]?.id,\n )\n if (!chosen.ok) return res.status(400).json({ error: chosen.error })\n const selection = CommerceModel.modifierSelectionOf(chosen.modifiers)\n if (selection.length) line.modifiers = selection\n else delete line.modifiers\n }\n }\n cart.lines = CommerceModel.upsertCartLine(\n cart,\n line,\n action === 'set' ? 'set' : 'add',\n )\n }\n // AGL-1769: never mint an EMPTY cart. `clear` returns above before the\n // `!line.productId` check, so `{ hostId, action: 'clear' }` — no\n // product, valid or otherwise, and no credentials — used to create a\n // document per request holding `lines: []` and two timestamps. A `remove`\n // or a `set 0` that empties an absent basket is the same request wearing\n // a productId. A cart that would store no lines is not a cart.\n //\n // AGL-1760's test — does refusing discard money or work that already\n // occurred — is passed trivially here: there is no basket to strand. The\n // caller still gets its cookie and its empty-cart response, so the next\n // add lands on this id and creates the document properly.\n if (cartSnapshot.exists || cart.lines.length > 0) {\n await cartRef.set(\n {\n lines: cart.lines,\n updatedAtMs: Date.now(),\n ...(cartSnapshot.exists ? {} : { createdAtMs: Date.now() }),\n },\n { merge: true },\n )\n }\n }\n\n // Resolve display lines from product docs — never trust stored data.\n const uniqueProductIds = [...new Set(cart.lines.map((l) => l.productId))]\n const productSnapshots = await Promise.all(\n uniqueProductIds.map((id) =>\n hostRef.collection('products').doc(id).get(),\n ),\n )\n const productsById = new Map(\n productSnapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const lines: ResolvedCartLine[] = cart.lines.map((line) => {\n const product = productsById.get(line.productId)\n if (!product || !CommerceModel.productListedOnline(product)) {\n return {\n ...line,\n name: product?.name ?? 'Unavailable product',\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // A variant with no price yet (AGL-2916) is not for sale, and never a\n // line worth nothing.\n if (!variant || !CommerceModel.variantHasPrice(variant)) {\n return {\n ...line,\n name: product.name,\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variantLabel = Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined\n // Add-ons priced from the product on every read (AGL-4100), on this\n // variant. Choices the product no longer offers, or a required one\n // now unanswered, make the line unavailable with what to do.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant.id)\n if (!chosen.ok) {\n return {\n ...line,\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n unitAmountCents: 0,\n unavailable: true,\n problem: CommerceModel.cartLineModifierProblem(chosen.error),\n }\n }\n const label = CommerceModel.lineLabelWithModifiers(variantLabel, chosen.modifiers)\n return {\n ...line,\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents: Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents,\n ...(variant.imageUrl || product.mediaUrls?.[0] || product.imageUrl\n ? {\n imageUrl:\n variant.imageUrl ??\n product.mediaUrls?.[0] ??\n product.imageUrl,\n }\n : {}),\n ...(CommerceModel.canPurchase(product, variant.id, line.quantity)\n ? {}\n : { unavailable: true }),\n }\n })\n const subtotalCents = lines\n .filter((line) => !line.unavailable)\n .reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n // Card reader hardware the platform's own store sells (AGL-4038): the\n // cart asks for the terms of sale before checkout. Read from the\n // environment first, so no other store reads anything more.\n const sellerHostId = parsePosHardwareInPersonConfig(process.env)?.sellerHostId\n const hardwareTerms =\n sellerHostId === hostId &&\n cart.lines.some((line) => isPosHardwareSkuId(productsById.get(line.productId)?.hardwareSku))\n // Where it is going, asked WITH the cart rather than after the first\n // Checkout press: the same plan checkout makes, with no destination yet.\n const askShippingCountry = await shippingCountryNeeded({\n hostRef,\n lines,\n productsById,\n subtotalCents,\n })\n return res.status(200).json({\n lines,\n count: CommerceModel.cartCount(cart),\n subtotalCents,\n ...(hardwareTerms ? { hardwareTerms: true } : {}),\n ...(askShippingCountry\n ? {\n needsShippingCountry: true,\n shippingCountries: [...CommerceModel.CHECKOUT_SHIPPING_COUNTRIES],\n }\n : {}),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Cart unavailable' })\n }\n}\n\n/**\n * Whether checkout will ask this cart where it is shipping to, answered while\n * the cart is shown so the cart can ask up front. A shopper who pressed\n * Checkout used to be refused with \"Choose where you’re shipping to.\" and only\n * then shown the field.\n *\n * The same plan `cart-checkout.ts` makes, with no destination, so the two\n * cannot disagree: rates that differ by zone, or carrier rates, need one. A\n * cart with nothing posted reads nothing more, and a store with one zone, a\n * rest-of-world zone or no shipping at all is never asked. Checkout still asks\n * and enforces the answer on its own; this only moves the question earlier.\n */\nasync function shippingCountryNeeded(input: {\n hostRef: FirebaseFirestore.DocumentReference\n lines: ResolvedCartLine[]\n productsById: Map<string, CommerceModel.HostProduct | null>\n subtotalCents: number\n}): Promise<boolean> {\n let physical = false\n let totalGrams = 0\n for (const line of input.lines) {\n if (line.unavailable) continue\n const product = input.productsById.get(line.productId)\n if (!product) continue\n // A missing `type` reads as physical, as checkout reads it.\n if ((product.type ?? 'physical') !== 'physical') continue\n physical = true\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n totalGrams += Math.max(0, Number(variant?.weightGrams ?? 0)) * line.quantity\n }\n if (!physical) return false\n try {\n const storeSettings = await input.hostRef.collection('settings').doc('store').get()\n const plan = await planCheckoutShippingWithCarriers({\n hostId: input.hostRef.id,\n settings: storeSettings.get('shipping') as CommerceModel.ShippingSettings | undefined,\n cart: { subtotalCents: input.subtotalCents, totalGrams },\n destination: {},\n })\n return plan.refusal === 'destination-required'\n } catch {\n // The cart still shows; checkout asks, as it always has.\n return false\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","CommerceModel","firebaseAdmin","isDocumentId","cartCookieName","mintCartId","readCartId","readStoreDay","planCheckoutShippingWithCarriers","cartHandler","req","res","isPost","method","status","json","error","body","JSON","parse","hostId","String","query","cookieName","cartId","cookies","firestore","app","hostRef","collection","doc","cartSnapshot","lines","count","setHeader","cartRef","get","cart","data","action","useDayKey","trim","requestedModifiers","modifierSelectionFrom","modifiers","line","productId","variantId","length","quantity","Math","min","CART_MAX_QUANTITY","max","Number","isFinite","round","isCheckInDayKey","removeCartLine","productSnapshot","exists","productSellsOnline","isNewLine","some","held","cartLineKey","product","liftLegacyProduct","variants","id","productAsksUseDate","problem","checkInUseDayProblem","todayKey","chosen","resolveWebsiteLineModifiers","ok","selection","modifierSelectionOf","upsertCartLine","set","updatedAtMs","Date","now","createdAtMs","merge","uniqueProductIds","Set","map","l","productSnapshots","Promise","all","productsById","Map","snapshot","variant","productListedOnline","name","unitAmountCents","unavailable","find","item","variantHasPrice","variantLabel","Object","keys","options","values","join","undefined","cartLineModifierProblem","label","lineLabelWithModifiers","priceUsd","extraCents","imageUrl","mediaUrls","canPurchase","subtotalCents","filter","reduce","sum","sellerHostId","process","env","hardwareTerms","hardwareSku","askShippingCountry","shippingCountryNeeded","cartCount","needsShippingCountry","shippingCountries","CHECKOUT_SHIPPING_COUNTRIES","console","input","physical","totalGrams","type","weightGrams","storeSettings","plan","settings","destination","refusal"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,2BAAuB;AAG1F,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,EAAEC,UAAU,EAAEC,UAAU,QAAQ,mBAAe;AACtE,SAASC,YAAY,QAAQ,iBAAa;AAC1C,SAASC,gCAAgC,QAAQ,wBAAoB;AAgBrE;;;;;;CAMC,GACD,OAAO,MAAMC,cAAgC,OAAOC,KAAKC;QAQhDD,WAYgBE;IAnBvB,MAAMA,SAASF,IAAIG,MAAM,KAAK;IAC9B,IAAI,CAACD,UAAUF,IAAIG,MAAM,KAAK,OAAO;QACnC,OAAOF,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,OAAOL,SACT,OAAOF,IAAIO,IAAI,KAAK,WAClBC,KAAKC,KAAK,CAACT,IAAIO,IAAI,IAAI,SACtBP,YAAAA,IAAIO,IAAI,YAARP,YAAY,CAAC,IAChB,CAAC;IACL,0EAA0E;IAC1E,0EAA0E;IAC1E,4EAA4E;IAC5E,yEAAyE;IACzE,0EAA0E;IAC1E,8DAA8D;IAC9D,EAAE;IACF,0EAA0E;IAC1E,6EAA6E;IAC7E,oDAAoD;IACpD,MAAMU,SAASC,QAAQT,OAAAA,SAASK,KAAKG,MAAM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mBAAI,MAAM9F,KAAKI,QAAQ;IAC9E;IACA,IAAI,CAACuF,UAAU,OAAO;IACtB,IAAI;QACF,MAAMI,gBAAgB,MAAML,MAAM3G,OAAO,CAACC,UAAU,CAAC,YAAYC,GAAG,CAAC,SAASM,GAAG;QACjF,MAAMyG,OAAO,MAAMrI,iCAAiC;YAClDY,QAAQmH,MAAM3G,OAAO,CAACyC,EAAE;YACxByE,UAAUF,cAAcxG,GAAG,CAAC;YAC5BC,MAAM;gBAAEkF,eAAegB,MAAMhB,aAAa;gBAAEkB;YAAW;YACvDM,aAAa,CAAC;QAChB;QACA,OAAOF,KAAKG,OAAO,KAAK;IAC1B,EAAE,eAAM;QACN,yDAAyD;QACzD,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/cart.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 { isPosHardwareSkuId, parsePosHardwareInPersonConfig } from '../model/pos-hardware'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport { cartCookieName, mintCartId, readCartId } from './cart-cookie'\nimport { readStoreDay } from './store-day'\nimport { planCheckoutShippingWithCarriers } from './carrier-shipping'\nimport {\n checkoutAmountMinor,\n checkoutVariantMinor,\n loadFxRates,\n resolveCheckoutCurrency,\n storeCurrencyContextFrom,\n type CheckoutCurrency,\n} from './currency'\n\nexport interface ResolvedCartLine extends CommerceModel.CartLine {\n name: string\n variantLabel?: string\n unitAmountCents: number\n imageUrl?: string\n /** Line no longer purchasable (deleted/draft/sold out). */\n unavailable?: boolean\n /**\n * What the shopper must do about an unavailable line, when the cart can say\n * (AGL-4100): its add-ons no longer answer the product's choices.\n */\n problem?: string\n}\n\n/**\n * Server-backed cart (AGL-293): cookie-keyed doc under\n * `hosts/{hostId}/carts`. GET returns the resolved cart; POST mutates\n * with {action: add|set|remove|clear}. Lines resolve against product\n * docs on every read so prices/names never go stale, and unavailable\n * lines surface instead of silently charging.\n */\nexport const cartHandler: PluginApiHandler = async (req, res) => {\n const isPost = req.method === 'POST'\n if (!isPost && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const body = isPost\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : {}\n // AGL-1769: BOTH components of the path this handler writes come from the\n // caller — `hostId` off the body, `cartId` off a cookie whose name embeds\n // `hostId` — and `.doc()` appends a slash-separated PATH rather than taking\n // one opaque id. So an unvalidated pair named the nesting as well as the\n // document: a `hostId` of `a/b/c` wrote under `hosts/a/b/c`, invisible to\n // every console list because they resolve the host doc first.\n //\n // This handler is the one visitor-facing write in the AGL-1763 sweep that\n // needs NO credentials — no session, no member gate, no signature — so it is\n // the one place the id rule has to hold on its own.\n const hostId = String((isPost ? body.hostId : req.query.hostId) ?? '')\n // The message names BOTH causes it now covers (`762621581`): the guard reads\n // as \"absent\" but also refuses a hostId that is a path rather than an id, and\n // a caller told only \"missing\" would go looking for the wrong mistake.\n // AGL-1771: `isDocumentId`, not the cart module's old `isCartId` alias — this\n // value is a HOST id, and the rule it has to satisfy was never about carts.\n if (!isDocumentId(hostId))\n return res.status(400).json({ error: 'Missing or invalid hostId' })\n\n const cookieName = cartCookieName(hostId)\n // A cookie that is not a single document id reads as NO cart: a GET returns\n // an empty one and a POST mints a fresh id below, exactly as for a first-time\n // visitor. Nothing is stranded — a path that was never a cart id was never a\n // basket anyone filled.\n let cartId = readCartId(req.cookies, hostId)\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n\n // The shopper's currency (AGL-4248), asked by a storefront showing another\n // than the store's: the cart prices in it exactly as checkout will charge.\n const requestedCurrency = String((isPost ? body.currency : req.query.currency) ?? '').trim()\n\n try {\n if (!cartId) {\n if (!isPost) return res.status(200).json({ lines: [], count: 0 })\n cartId = mintCartId()\n res.setHeader(\n 'Set-Cookie',\n `${cookieName}=${cartId}; Path=/; Max-Age=${60 * 60 * 24 * 90}; ` +\n 'HttpOnly; SameSite=Lax; Secure',\n )\n }\n const cartRef = hostRef.collection('carts').doc(cartId)\n const cartSnapshot = await cartRef.get()\n const cart: CommerceModel.HostCart = (cartSnapshot.data() as any) ?? { lines: [] }\n\n if (isPost) {\n const action = String(body.action ?? 'add')\n // The day the shopper chose to use a check-in item (AGL-4043): part of\n // the line's identity, so two days of one pass are two lines.\n const useDayKey = typeof body.useDayKey === 'string' ? body.useDayKey.trim() : ''\n // The add-ons chosen on the product's page (AGL-4100), ids only: part\n // of the line's identity, priced from the product, never from here.\n const requestedModifiers = CommerceModel.modifierSelectionFrom(body.modifiers)\n const line: CommerceModel.CartLine = {\n productId: String(body.productId ?? ''),\n ...(body.variantId ? { variantId: String(body.variantId) } : {}),\n ...(useDayKey ? { useDayKey } : {}),\n ...(requestedModifiers.length ? { modifiers: requestedModifiers } : {}),\n // Clamped at the door as well as in the model (AGL-2285): the route\n // used `Math.round(Number(...))` alone, which yields `NaN` for\n // `{\"quantity\":\"x\"}` and slipped past `upsertCartLine`'s `<= 0` guard.\n quantity: Math.min(\n CommerceModel.CART_MAX_QUANTITY,\n Math.max(\n -CommerceModel.CART_MAX_QUANTITY,\n Number.isFinite(Number(body.quantity ?? 1))\n ? Math.round(Number(body.quantity ?? 1))\n : 0,\n ),\n ),\n }\n if (useDayKey && !CommerceModel.isCheckInDayKey(useDayKey)) {\n return res.status(400).json({ error: 'Choose the day as a date.' })\n }\n if (action === 'clear') {\n cart.lines = []\n } else if (!line.productId) {\n return res.status(400).json({ error: 'Missing productId' })\n } else if (action === 'remove') {\n cart.lines = CommerceModel.removeCartLine(cart, line)\n } else {\n // A product sold in person only (AGL-4060) never enters a basket: it\n // answers as no product at all, as its page does. A line already in\n // the cart stays removable and resolves as unavailable below.\n if (line.quantity > 0 && isDocumentId(line.productId)) {\n const productSnapshot = await hostRef.collection('products').doc(line.productId).get()\n if (productSnapshot.exists && !CommerceModel.productSellsOnline(productSnapshot.data())) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n // A use day is asked only by an item that asks for one, and is a\n // day that has not passed on the store's calendar (AGL-4043).\n const isNewLine = !cart.lines.some(\n (held) => CommerceModel.cartLineKey(held) === CommerceModel.cartLineKey(line),\n )\n const product = productSnapshot.exists ? CommerceModel.liftLegacyProduct(productSnapshot.data() as any) : null\n if (useDayKey && (action === 'add' || isNewLine)) {\n const variantId = line.variantId ?? product?.variants[0]?.id\n if (!product || !CommerceModel.productAsksUseDate(product, variantId)) {\n return res.status(400).json({ error: 'This item has no day to choose.' })\n }\n const problem = CommerceModel.checkInUseDayProblem(useDayKey, (await readStoreDay(hostRef)).todayKey)\n if (problem) return res.status(400).json({ error: problem })\n }\n // Add-ons (AGL-4100): asked of the groups the website shows, every\n // required one answered, and kept as ids in the product's order. A\n // required group left unanswered is refused here, so no line goes\n // in a basket that checkout would have to turn away.\n if (product && (action === 'add' || isNewLine)) {\n const chosen = CommerceModel.resolveWebsiteLineModifiers(\n product,\n line.modifiers,\n line.variantId ?? product.variants[0]?.id,\n )\n if (!chosen.ok) return res.status(400).json({ error: chosen.error })\n const selection = CommerceModel.modifierSelectionOf(chosen.modifiers)\n if (selection.length) line.modifiers = selection\n else delete line.modifiers\n }\n }\n cart.lines = CommerceModel.upsertCartLine(\n cart,\n line,\n action === 'set' ? 'set' : 'add',\n )\n }\n // AGL-1769: never mint an EMPTY cart. `clear` returns above before the\n // `!line.productId` check, so `{ hostId, action: 'clear' }` — no\n // product, valid or otherwise, and no credentials — used to create a\n // document per request holding `lines: []` and two timestamps. A `remove`\n // or a `set 0` that empties an absent basket is the same request wearing\n // a productId. A cart that would store no lines is not a cart.\n //\n // AGL-1760's test — does refusing discard money or work that already\n // occurred — is passed trivially here: there is no basket to strand. The\n // caller still gets its cookie and its empty-cart response, so the next\n // add lands on this id and creates the document properly.\n if (cartSnapshot.exists || cart.lines.length > 0) {\n await cartRef.set(\n {\n lines: cart.lines,\n updatedAtMs: Date.now(),\n ...(cartSnapshot.exists ? {} : { createdAtMs: Date.now() }),\n },\n { merge: true },\n )\n }\n }\n\n // Resolve display lines from product docs — never trust stored data.\n const uniqueProductIds = [...new Set(cart.lines.map((l) => l.productId))]\n const productSnapshots = await Promise.all(\n uniqueProductIds.map((id) =>\n hostRef.collection('products').doc(id).get(),\n ),\n )\n const productsById = new Map(\n productSnapshots.map((snapshot) => [\n snapshot.id,\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data() as any) : null,\n ]),\n )\n const currency = requestedCurrency ? await cartCurrency(hostRef, requestedCurrency) : undefined\n // Each line in the store currency as well, for what the store's own\n // rules (free shipping over, zones) are written in.\n const baseUnitCents = new Map<CommerceModel.CartLine, number>()\n const lines: ResolvedCartLine[] = cart.lines.map((line) => {\n const product = productsById.get(line.productId)\n if (!product || !CommerceModel.productListedOnline(product)) {\n return {\n ...line,\n name: product?.name ?? 'Unavailable product',\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // A variant with no price yet (AGL-2916) is not for sale, and never a\n // line worth nothing.\n if (!variant || !CommerceModel.variantHasPrice(variant)) {\n return {\n ...line,\n name: product.name,\n unitAmountCents: 0,\n unavailable: true,\n }\n }\n const variantLabel = Object.keys(variant.options ?? {}).length\n ? Object.values(variant.options ?? {}).join(' / ')\n : undefined\n // Add-ons priced from the product on every read (AGL-4100), on this\n // variant. Choices the product no longer offers, or a required one\n // now unanswered, make the line unavailable with what to do.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant.id)\n if (!chosen.ok) {\n return {\n ...line,\n name: product.name,\n ...(variantLabel ? { variantLabel } : {}),\n unitAmountCents: 0,\n unavailable: true,\n problem: CommerceModel.cartLineModifierProblem(chosen.error),\n }\n }\n const label = CommerceModel.lineLabelWithModifiers(variantLabel, chosen.modifiers)\n const baseCents = Math.round(Number(variant.priceUsd) * 100) + chosen.extraCents\n baseUnitCents.set(line, baseCents)\n return {\n ...line,\n name: product.name,\n ...(label ? { variantLabel: label } : {}),\n unitAmountCents: currency?.foreign\n ? cartUnitMinor(currency, product, variant, chosen.modifiers)\n : baseCents,\n ...(variant.imageUrl || product.mediaUrls?.[0] || product.imageUrl\n ? {\n imageUrl:\n variant.imageUrl ??\n product.mediaUrls?.[0] ??\n product.imageUrl,\n }\n : {}),\n ...(CommerceModel.canPurchase(product, variant.id, line.quantity)\n ? {}\n : { unavailable: true }),\n }\n })\n const subtotalCents = lines\n .filter((line) => !line.unavailable)\n .reduce((sum, line) => sum + line.unitAmountCents * line.quantity, 0)\n const baseSubtotalCents = currency?.foreign\n ? cart.lines.reduce(\n (sum, line, index) =>\n lines[index]?.unavailable ? sum : sum + (baseUnitCents.get(line) ?? 0) * line.quantity,\n 0,\n )\n : subtotalCents\n // Card reader hardware the platform's own store sells (AGL-4038): the\n // cart asks for the terms of sale before checkout. Read from the\n // environment first, so no other store reads anything more.\n const sellerHostId = parsePosHardwareInPersonConfig(process.env)?.sellerHostId\n const hardwareTerms =\n sellerHostId === hostId &&\n cart.lines.some((line) => isPosHardwareSkuId(productsById.get(line.productId)?.hardwareSku))\n // Where it is going, asked WITH the cart rather than after the first\n // Checkout press: the same plan checkout makes, with no destination yet.\n const askShippingCountry = await shippingCountryNeeded({\n hostRef,\n lines,\n productsById,\n subtotalCents: baseSubtotalCents,\n })\n return res.status(200).json({\n lines,\n count: CommerceModel.cartCount(cart),\n subtotalCents,\n // The currency every amount above is in, when the storefront asked.\n ...(currency ? { currency: currency.code } : {}),\n ...(hardwareTerms ? { hardwareTerms: true } : {}),\n ...(askShippingCountry\n ? {\n needsShippingCountry: true,\n shippingCountries: [...askShippingCountry],\n }\n : {}),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Cart unavailable' })\n }\n}\n\n/**\n * The currency a cart prices in (AGL-4248): the one the storefront asked for\n * when the store sells in it and fresh rates cover it, else the store's,\n * resolved exactly as checkout resolves it.\n */\nasync function cartCurrency(\n hostRef: FirebaseFirestore.DocumentReference,\n requested: string,\n): Promise<CheckoutCurrency | undefined> {\n try {\n const [storeSnap, rates] = await Promise.all([\n hostRef.collection('settings').doc('store').get(),\n loadFxRates(),\n ])\n return resolveCheckoutCurrency(\n storeCurrencyContextFrom(storeSnap.data() as Record<string, unknown> | undefined, rates),\n requested,\n )\n } catch (error) {\n // The cart still shows, in the store currency, and says so by omission.\n console.error('commerce: cart currency unavailable', error)\n return undefined\n }\n}\n\n/**\n * One unit of a line in the checkout currency, as checkout charges it: the\n * variant's price there (its fixed price wins), plus each add-on converted\n * on its own (an add-on's fixed amount wins).\n */\nexport function cartUnitMinor(\n currency: CheckoutCurrency,\n product: { modifierGroups?: unknown },\n variant: { priceUsd?: number; fixedPrices?: Record<string, number> },\n modifiers: readonly CommerceModel.OrderLineModifier[],\n): number {\n const groups = CommerceModel.productModifierGroups(product)\n return modifiers.reduce((sum, modifier) => {\n const option = groups\n .find((group) => group.id === modifier.groupId)\n ?.options.find((entry) => entry.id === modifier.optionId)\n return sum + checkoutAmountMinor(currency, modifier.priceCents, option?.fixedPriceCents)\n }, checkoutVariantMinor(currency, variant))\n}\n\n/**\n * Whether checkout will ask this cart where it is shipping to, answered while\n * the cart is shown so the cart can ask up front. A shopper who pressed\n * Checkout used to be refused with \"Choose where you’re shipping to.\" and only\n * then shown the field.\n *\n * The same plan `cart-checkout.ts` makes, with no destination, so the two\n * cannot disagree: rates that differ by zone, or carrier rates, need one. A\n * cart with nothing posted reads nothing more, and a store with one zone, a\n * rest-of-world zone or no shipping at all is never asked. Checkout still asks\n * and enforces the answer on its own; this only moves the question earlier.\n */\nasync function shippingCountryNeeded(input: {\n hostRef: FirebaseFirestore.DocumentReference\n lines: ResolvedCartLine[]\n productsById: Map<string, CommerceModel.HostProduct | null>\n subtotalCents: number\n}): Promise<readonly string[] | false> {\n let physical = false\n let totalGrams = 0\n for (const line of input.lines) {\n if (line.unavailable) continue\n const product = input.productsById.get(line.productId)\n if (!product) continue\n // A missing `type` reads as physical, as checkout reads it.\n if ((product.type ?? 'physical') !== 'physical') continue\n physical = true\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n totalGrams += Math.max(0, Number(variant?.weightGrams ?? 0)) * line.quantity\n }\n if (!physical) return false\n try {\n const storeSettings = await input.hostRef.collection('settings').doc('store').get()\n const plan = await planCheckoutShippingWithCarriers({\n hostId: input.hostRef.id,\n settings: storeSettings.get('shipping') as CommerceModel.ShippingSettings | undefined,\n cart: { subtotalCents: input.subtotalCents, totalGrams },\n destination: {},\n })\n return plan.refusal === 'destination-required' ? plan.countries : false\n } catch {\n // The cart still shows; checkout asks, as it always has.\n return false\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","CommerceModel","firebaseAdmin","isDocumentId","cartCookieName","mintCartId","readCartId","readStoreDay","planCheckoutShippingWithCarriers","checkoutAmountMinor","checkoutVariantMinor","loadFxRates","resolveCheckoutCurrency","storeCurrencyContextFrom","cartHandler","req","res","isPost","method","status","json","error","body","JSON","parse","hostId","String","query","cookieName","cartId","cookies","firestore","app","hostRef","collection","doc","requestedCurrency","currency","trim","cartSnapshot","lines","count","setHeader","cartRef","get","cart","data","action","useDayKey","requestedModifiers","modifierSelectionFrom","modifiers","line","productId","variantId","length","quantity","Math","min","CART_MAX_QUANTITY","max","Number","isFinite","round","isCheckInDayKey","removeCartLine","productSnapshot","exists","productSellsOnline","isNewLine","some","held","cartLineKey","product","liftLegacyProduct","variants","id","productAsksUseDate","problem","checkInUseDayProblem","todayKey","chosen","resolveWebsiteLineModifiers","ok","selection","modifierSelectionOf","upsertCartLine","set","updatedAtMs","Date","now","createdAtMs","merge","uniqueProductIds","Set","map","l","productSnapshots","Promise","all","productsById","Map","snapshot","cartCurrency","undefined","baseUnitCents","variant","productListedOnline","name","unitAmountCents","unavailable","find","item","variantHasPrice","variantLabel","Object","keys","options","values","join","cartLineModifierProblem","label","lineLabelWithModifiers","baseCents","priceUsd","extraCents","foreign","cartUnitMinor","imageUrl","mediaUrls","canPurchase","subtotalCents","filter","reduce","sum","baseSubtotalCents","index","sellerHostId","process","env","hardwareTerms","hardwareSku","askShippingCountry","shippingCountryNeeded","cartCount","code","needsShippingCountry","shippingCountries","console","requested","storeSnap","rates","groups","productModifierGroups","modifier","option","group","groupId","entry","optionId","priceCents","fixedPriceCents","input","physical","totalGrams","type","weightGrams","storeSettings","plan","settings","destination","refusal","countries"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,kBAAkB,EAAEC,8BAA8B,QAAQ,2BAAuB;AAG1F,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,SAASC,cAAc,EAAEC,UAAU,EAAEC,UAAU,QAAQ,mBAAe;AACtE,SAASC,YAAY,QAAQ,iBAAa;AAC1C,SAASC,gCAAgC,QAAQ,wBAAoB;AACrE,SACEC,mBAAmB,EACnBC,oBAAoB,EACpBC,WAAW,EACXC,uBAAuB,EACvBC,wBAAwB,QAEnB,gBAAY;AAgBnB;;;;;;CAMC,GACD,OAAO,MAAMC,cAAgC,OAAOC,KAAKC;QAQhDD,WAYgBE,MAoBWA;IAvClC,MAAMA,SAASF,IAAIG,MAAM,KAAK;IAC9B,IAAI,CAACD,UAAUF,IAAIG,MAAM,KAAK,OAAO;QAC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Aa;gBAAEiC;YAAW;YACvDM,aAAa,CAAC;QAChB;QACA,OAAOF,KAAKG,OAAO,KAAK,yBAAyBH,KAAKI,SAAS,GAAG;IACpE,EAAE,eAAM;QACN,yDAAyD;QACzD,OAAO;IACT;AACF"}
@@ -25,6 +25,11 @@ export interface PublicCatalogItem {
25
25
  priceUsd: number;
26
26
  maxPriceUsd: number;
27
27
  compareAtPriceUsd?: number;
28
+ /**
29
+ * The cheapest priced variant's own prices per currency (AGL-4248), major
30
+ * units, so a card's "from" price matches its product page.
31
+ */
32
+ fixedPrices?: Record<string, number>;
28
33
  imageUrl?: string;
29
34
  soldOut: boolean;
30
35
  tags?: string[];
@@ -22,6 +22,7 @@ import { firebaseAdmin } from "@aglyn/tenant-data-admin";
22
22
  import { applyListQuery } from "@aglyn/tenant-data-admin/server/list-query";
23
23
  import { smartCollectionScope, STOREFRONT_CATALOG_BASE, STOREFRONT_CATALOG_DECLARATION, STOREFRONT_CATALOG_SORTS, STOREFRONT_PRODUCT_TYPES, storefrontCatalogSort } from "../constants/storefront-catalog-query.js";
24
24
  import * as CommerceModel from "../model/index.js";
25
+ import { publicFixedPrices } from "./product.js";
25
26
  /**
26
27
  * The photo a product's card shows: the first non-blank of its media, its
27
28
  * legacy single image, then the first variant photo. Reading only the first
@@ -201,6 +202,10 @@ const compareValues = (a, b)=>{
201
202
  }
202
203
  return rows;
203
204
  }
205
+ /** The fixed prices of the variant a card's price is, when it has any. */ function cheapestFixedPrices(variants, minPrice) {
206
+ const cheapest = variants.find((variant)=>CommerceModel.variantHasPrice(variant) && Number(variant.priceUsd) === minPrice);
207
+ return publicFixedPrices(cheapest == null ? void 0 : cheapest.fixedPrices);
208
+ }
204
209
  /** The card a grid renders for one product. */ function toItem(row) {
205
210
  var _product_tags;
206
211
  const { product } = row;
@@ -215,6 +220,8 @@ const compareValues = (a, b)=>{
215
220
  maxPriceUsd: maxPrice
216
221
  }, (primary == null ? void 0 : primary.compareAtPriceUsd) ? {
217
222
  compareAtPriceUsd: primary.compareAtPriceUsd
223
+ } : {}, cheapestFixedPrices(product.variants, minPrice) ? {
224
+ fixedPrices: cheapestFixedPrices(product.variants, minPrice)
218
225
  } : {}, productCardImage(product) ? {
219
226
  imageUrl: productCardImage(product)
220
227
  } : {}, {