@aglyn/plugins-commerce 1.20.2 → 1.21.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.
- package/package.json +13 -13
- package/src/lib/components/cart.js +106 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +81 -30
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +28 -3
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/local-delivery-settings-card.component.js +23 -7
- package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +61 -44
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +32 -4
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.js +20 -6
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +28 -2
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/return-settings-card.component.js +28 -15
- package/src/lib/components/console/return-settings-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +23 -8
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +27 -11
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +38 -13
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/console/tax-settings-card.component.js +25 -10
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/server/cart.js +57 -0
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/pos-terminal.js +2 -2
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/transfer/product-transfer.js +15 -1
- package/src/lib/transfer/product-transfer.js.map +1 -1
|
@@ -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'\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 return res.status(200).json({\n lines,\n count: CommerceModel.cartCount(cart),\n subtotalCents,\n ...(hardwareTerms ? { hardwareTerms: true } : {}),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Cart unavailable' })\n }\n}\n"],"names":["isPosHardwareSkuId","parsePosHardwareInPersonConfig","CommerceModel","firebaseAdmin","isDocumentId","cartCookieName","mintCartId","readCartId","readStoreDay","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","cartCount","console"],"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;AAgB1C;;;;;;CAMC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QAAQmD,SAAS,qBAAjBnD,mBAAmB,CAAC,EAAE,YADtB8B,OAEA9B,QAAQkD,QAAQ;YACpB,IACA,CAAC,GACDlH,cAAcoH,WAAW,CAACpD,SAAS8B,QAAQ3B,EAAE,EAAExB,KAAKI,QAAQ,IAC5D,CAAC,IACD;gBAAEmD,aAAa;YAAK;QAE5B;QACA,MAAMmB,gBAAgBvF,MACnBwF,MAAM,CAAC,CAAC3E,OAAS,CAACA,KAAKuD,WAAW,EAClCqB,MAAM,CAAC,CAACC,KAAK7E,OAAS6E,MAAM7E,KAAKsD,eAAe,GAAGtD,KAAKI,QAAQ,EAAE;QACrE,sEAAsE;QACtE,iEAAiE;QACjE,4DAA4D;QAC5D,MAAM0E,gBAAe1H,kCAAAA,+BAA+B2H,QAAQC,GAAG,sBAA1C5H,gCAA6C0H,YAAY;QAC9E,MAAMG,gBACJH,iBAAiBvG,UACjBiB,KAAKL,KAAK,CAAC+B,IAAI,CAAC,CAAClB;gBAA4BgD;mBAAnB7F,oBAAmB6F,oBAAAA,aAAazD,GAAG,CAACS,KAAKC,SAAS,sBAA/B+C,kBAAkCkC,WAAW;;QAC5F,OAAOpH,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BiB;YACAC,OAAO/B,cAAc8H,SAAS,CAAC3F;YAC/BkF;WACIO,gBAAgB;YAAEA,eAAe;QAAK,IAAI,CAAC;IAEnD,EAAE,OAAO9G,OAAO;QACdiH,QAAQjH,KAAK,CAACA;QACd,OAAOL,IAAIG,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAmB;IAC1D;AACF,EAAC"}
|
|
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;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,CAAE;YAKzBkC;QAJL,IAAIrB,KAAKuD,WAAW,EAAE;QACtB,MAAMlC,UAAUqE,MAAM1C,YAAY,CAACzD,GAAG,CAACS,KAAKC,SAAS;QACrD,IAAI,CAACoB,SAAS;QACd,4DAA4D;QAC5D,IAAI,EAACA,gBAAAA,QAAQwE,IAAI,YAAZxE,gBAAgB,gBAAgB,YAAY;QACjDsE,WAAW;QACX,MAAMxC,UAAUnD,KAAKE,SAAS,GAC1BmB,QAAQE,QAAQ,CAACiC,IAAI,CAAC,CAACC,OAASA,KAAKjC,EAAE,KAAKxB,KAAKE,SAAS,IAC1DmB,QAAQE,QAAQ,CAAC,EAAE;QACvBqE,cAAcvF,KAAKG,GAAG,CAAC,GAAGC,eAAO0C,2BAAAA,QAAS2C,WAAW,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"}
|
|
@@ -1493,7 +1493,7 @@ function offlineCardIntent(body) {
|
|
|
1493
1493
|
*/ export async function retrievePosOfflineCardIntent(paymentIntentId, account = null) {
|
|
1494
1494
|
const fetched = await posStripe('GET', `payment_intents/${encodeURIComponent(paymentIntentId)}`, _extends({
|
|
1495
1495
|
params: {
|
|
1496
|
-
|
|
1496
|
+
expand: [
|
|
1497
1497
|
'latest_charge'
|
|
1498
1498
|
]
|
|
1499
1499
|
}
|
|
@@ -1514,7 +1514,7 @@ function offlineCardIntent(body) {
|
|
|
1514
1514
|
params: _extends({}, applicationFeeCents > 0 ? {
|
|
1515
1515
|
application_fee_amount: applicationFeeCents
|
|
1516
1516
|
} : {}, {
|
|
1517
|
-
|
|
1517
|
+
expand: [
|
|
1518
1518
|
'latest_charge'
|
|
1519
1519
|
]
|
|
1520
1520
|
})
|