@aglyn/plugins-commerce 1.26.6 → 1.28.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/console/pos-hardware-card.component.js +70 -67
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-waiting-card.component.js +19 -17
- package/src/lib/components/console/pos-hardware-waiting-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +4 -43
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/contracts.d.ts +7 -0
- package/src/lib/contracts.js.map +1 -1
- package/src/lib/model/pos-hardware-shop.d.ts +152 -0
- package/src/lib/model/pos-hardware-shop.js +152 -0
- package/src/lib/model/pos-hardware-shop.js.map +1 -0
- package/src/lib/model/product-write.d.ts +29 -8
- package/src/lib/model/product-write.js +64 -2
- package/src/lib/model/product-write.js.map +1 -1
- package/src/lib/native-nav.js +13 -1
- package/src/lib/native-nav.js.map +1 -1
- package/src/lib/server/api-v1/openapi.d.ts +6 -6
- package/src/lib/server/api-v1/openapi.js +203 -16
- package/src/lib/server/api-v1/openapi.js.map +1 -1
- package/src/lib/server/api-v1/order-view.d.ts +8 -0
- package/src/lib/server/api-v1/order-view.js +21 -4
- package/src/lib/server/api-v1/order-view.js.map +1 -1
- package/src/lib/server/api-v1/orders-and-products.js +46 -59
- package/src/lib/server/api-v1/orders-and-products.js.map +1 -1
- package/src/lib/server/api-v1/product-view.d.ts +76 -0
- package/src/lib/server/api-v1/product-view.js +86 -0
- package/src/lib/server/api-v1/product-view.js.map +1 -0
- package/src/lib/server/api-v1/product-writes.d.ts +149 -0
- package/src/lib/server/api-v1/product-writes.js +673 -0
- package/src/lib/server/api-v1/product-writes.js.map +1 -0
- package/src/lib/server/products-write.d.ts +94 -2
- package/src/lib/server/products-write.js +171 -112
- package/src/lib/server/products-write.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/order-view.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 { serialize } from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { fulfillmentLineQuantities } from '../../model/order-fulfillment'\nimport { fulfillmentTrackingUrl } from '../../model/tracking-url'\nimport { orderTaxEngineView } from '../../model/commerce-tax-engine'\nimport { orderIsTestMode } from '../../model/commerce-orders'\nimport { orderPayments, type OrderPaymentMethod } from '../../model/commerce-pos'\n\n/**\n * The public order shape from an order's data (AGL-3611): the same object the\n * API returns, so an order event and an outbound webhook carry exactly what\n * `GET /v1/sites/{id}/orders/{id}` would.\n */\nexport function orderViewFromData(id: string, data: Record<string, any>) {\n const totals = (data.totals ?? {}) as Record<string, unknown>\n const legacyTotal = Number(data.amountCents ?? NaN)\n const totalCents = Number.isFinite(Number(totals.totalCents))\n ? Number(totals.totalCents)\n : Number.isFinite(legacyTotal)\n ? legacyTotal\n : null\n const legacyFee = Number(data.feeCents ?? NaN)\n return {\n id,\n object: 'order',\n number: typeof data.number === 'number' ? data.number : null,\n status: (data.status as string) ?? null,\n channel: (data.channel as string) ?? 'online',\n currency: 'usd',\n customerEmail: data.customerEmail ?? null,\n customerName: data.customerName ?? null,\n lineItems: serialize(data.lineItems ?? []),\n totals: {\n itemsCents: Number(totals.itemsCents ?? 0),\n shippingCents: Number(totals.shippingCents ?? 0),\n taxCents: Number(totals.taxCents ?? 0),\n discountCents: Number(totals.discountCents ?? 0),\n totalCents,\n // The Connect application fee. NOT subtracted from `totalCents` — it is\n // Aglyn's cut of a total the shopper already paid in full, so a client\n // that nets it out of revenue would understate what it collected.\n feeCents: Number.isFinite(Number(totals.feeCents))\n ? Number(totals.feeCents)\n : Number.isFinite(legacyFee)\n ? legacyFee\n : 0,\n // Optional lines the buyer added at checkout (AGL-3635), inside\n // `totalCents` and outside `itemsCents`.\n extrasCents: Number(totals.extrasCents ?? 0) || 0,\n // A register tip (AGL-3607), on top of `totalCents` and not revenue.\n tipCents: Math.max(0, Math.round(Number(totals.tipCents ?? 0)) || 0),\n },\n // How a register sale was paid (AGL-3614): one entry per tender that\n // succeeded. A ledger needs it because only the card tenders went through\n // Stripe; cash went in the drawer, a gift card spent value the store\n // already held. Empty for every sale that is not the register's.\n payments: orderPaymentsView(data),\n // The part of `discountCents` a gift card paid online (AGL-3614).\n giftCardRedeemedCents: Math.max(0, Math.round(Number(data.giftCardRedeemedCents ?? 0)) || 0),\n // What those lines were and whose offer each was: the fact a plugin that\n // insures a parcel reads off `order.paid` to know it was bought.\n extras: (Array.isArray(data.extras) ? data.extras : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.id === 'string')\n .map((entry: Record<string, unknown>) => ({\n id: String(entry.id),\n pluginId: String(entry.pluginId ?? ''),\n key: String(entry.key ?? ''),\n label: String(entry.label ?? ''),\n amountCents: Number(entry.amountCents ?? 0) || 0,\n quoteRef: typeof entry.quoteRef === 'string' ? entry.quoteRef : null,\n })),\n // Store credit another plugin kept that paid part of the sale (AGL-3640):\n // a rewards redemption online comes off the goods (`discount`), one at\n // the register is one of its payments (`tender`). The provider reads its\n // own `reference` back off `order.paid` and `order.refunded`.\n credits: orderCreditsView(data),\n // Money already handed back, for any reason. A chargeback lands here too,\n // so `refundedCents > 0` does not by itself mean the merchant chose it.\n refundedCents: Number(data.refundedCents ?? 0),\n // Whether real money moved (AGL-3699): `false` for a Stripe test-mode\n // order, so a subscriber that tells an outside service about a sale —\n // a review invitation, a ledger — can leave a store's rehearsal out.\n // The seller's own rule: the recorded fact, else the session id.\n livemode: !orderIsTestMode({\n livemode: data.livemode,\n checkoutSessionId: data.checkoutSessionId,\n $id: id,\n }),\n // Who the tax was charged under (AGL-3614): `stripe-automatic` tax is\n // Aglyn's to remit as marketplace facilitator and never reaches the\n // merchant's account, which a ledger posting the sale has to know. An\n // order from before the regime was recorded says `null`, never a guess.\n taxMode: typeof data.taxMode === 'string' && data.taxMode ? data.taxMode : null,\n // The merchant's own tax service (AGL-3631): which one priced the sale, or\n // that it was asked and the store's own rates were charged instead\n // (`status: 'fallback'`). `null` when no service was asked. The regime is\n // still `taxMode` — a service the merchant connected answers for tax the\n // merchant remits.\n taxEngine: orderTaxEngineView(data.taxEngine),\n disputed: Boolean(data.dispute),\n shippingAddress: serialize(data.shippingAddress) ?? null,\n couponCode: data.couponCode ?? null,\n // Shipment records — the half of fulfilment an integration can use\n // without a write (AGL-2460). `status` says an order is `fulfilled`; it\n // does not say which carrier took it or under what tracking number, so a\n // 3PL or accounting reconcile could see THAT an order shipped and never\n // WHICH shipment it was. The console's order dialog shows both, and an\n // order that has been shipped twice (a split shipment) is indistinguish-\n // able from one shipped once when only the status is published.\n //\n // `atMs` is a number of milliseconds, not a Firestore Timestamp, so\n // `serialize` passes it through untouched. It is republished as `at` in\n // ISO 8601 to match `created` and every other time this API emits: one\n // object publishing two time formats is a bug an integrator finds late,\n // in their own timezone conversion, and blames on their own code.\n fulfillments: (Array.isArray(data.fulfillments) ? data.fulfillments : []).map(\n (entry: Record<string, unknown>) => {\n const atMs = Number((entry ?? {}).atMs)\n return {\n id: (entry ?? {}).id ?? null,\n lineItemIds: Array.isArray((entry ?? {}).lineItemIds)\n ? (entry as { lineItemIds: unknown[] }).lineItemIds\n : [],\n // Units per line (AGL-3611); a fulfillment recorded before\n // quantities shipped every unit of the lines it names.\n lines: fulfillmentLineQuantities(\n { lineItems: Array.isArray(data.lineItems) ? data.lineItems : [] },\n (entry ?? {}) as never,\n ),\n status: (entry ?? {}).status === 'cancelled' ? 'cancelled' : 'active',\n carrier: (entry ?? {}).carrier ?? null,\n trackingNumber: (entry ?? {}).trackingNumber ?? null,\n trackingUrl: fulfillmentTrackingUrl((entry ?? {}) as never),\n labelUrl: (entry ?? {}).labelUrl ?? null,\n at: Number.isFinite(atMs) ? new Date(atMs).toISOString() : null,\n }\n },\n ),\n created: serialize(data.createdAt) ?? null,\n }\n}\n\n/** The plugin credits an order carries, online and at the register (AGL-3640). */\nexport function orderCreditsView(data: Record<string, any>): Array<{\n providerId: string\n pluginId: string\n reference: string\n label: string\n last4: string\n amountCents: number\n appliedAs: 'discount' | 'tender'\n}> {\n const online = (Array.isArray(data.credits) ? data.credits : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.providerId === 'string')\n .map((entry: Record<string, unknown>) => ({\n providerId: String(entry.providerId),\n pluginId: String(entry.pluginId ?? String(entry.providerId).split('.')[0]),\n reference: String(entry.reference ?? ''),\n label: String(entry.label ?? ''),\n last4: String(entry.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(entry.amountCents) || 0)),\n appliedAs: entry.appliedAs === 'tender' ? ('tender' as const) : ('discount' as const),\n }))\n const register = (Array.isArray(data.payments) ? data.payments : [])\n .filter(\n (payment: Record<string, unknown>) =>\n payment &&\n payment.method === 'credit' &&\n payment.status === 'succeeded' &&\n typeof payment.creditProviderId === 'string',\n )\n .map((payment: Record<string, unknown>) => ({\n providerId: String(payment.creditProviderId),\n pluginId: String(payment.creditProviderId).split('.')[0],\n reference: String(payment.creditReference ?? ''),\n label: String(payment.creditLabel ?? ''),\n last4: String(payment.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(payment.amountCents) || 0)),\n appliedAs: 'tender' as const,\n }))\n return [...online, ...register].filter((credit) => credit.reference && credit.amountCents > 0)\n}\n\nconst CARD_METHODS: ReadonlySet<OrderPaymentMethod> = new Set(['card_present', 'card_keyed', 'card_link'])\n\n/**\n * A register sale's settled tenders as the order event names them (AGL-3614).\n * An order from before the split-tender ledger is one payment, inferred the\n * way the register's own reader infers it, with the order's tip and fee.\n */\nexport function orderPaymentsView(data: Record<string, any>): Array<{\n method: OrderPaymentMethod\n amountCents: number\n tipCents: number\n feeCents: number\n}> {\n if (data?.channel !== 'pos') return []\n const whole = (value: unknown) => Math.max(0, Math.round(Number(value ?? 0)) || 0)\n return orderPayments(data)\n .filter((payment) => payment.status === 'succeeded')\n .map((payment) => {\n const legacy = payment.id === 'legacy'\n return {\n method: payment.method,\n amountCents: whole(payment.amountCents),\n tipCents: whole(legacy ? data.totals?.tipCents : payment.tipCents),\n // The application fee Stripe took from this payment; a tender Stripe\n // never saw carried none.\n feeCents: legacy\n ? CARD_METHODS.has(payment.method) ? whole(data.totals?.feeCents ?? data.feeCents) : 0\n : whole(payment.feeCents),\n }\n })\n}\n"],"names":["serialize","fulfillmentLineQuantities","fulfillmentTrackingUrl","orderTaxEngineView","orderIsTestMode","orderPayments","orderViewFromData","id","data","totals","legacyTotal","Number","amountCents","NaN","totalCents","isFinite","legacyFee","feeCents","object","number","status","channel","currency","customerEmail","customerName","lineItems","itemsCents","shippingCents","taxCents","discountCents","extrasCents","tipCents","Math","max","round","payments","orderPaymentsView","giftCardRedeemedCents","extras","Array","isArray","filter","entry","map","String","pluginId","key","label","quoteRef","credits","orderCreditsView","refundedCents","livemode","checkoutSessionId","$id","taxMode","taxEngine","disputed","Boolean","dispute","shippingAddress","couponCode","fulfillments","atMs","lineItemIds","lines","carrier","trackingNumber","trackingUrl","labelUrl","at","Date","toISOString","created","createdAt","online","providerId","split","reference","last4","trunc","appliedAs","register","payment","method","creditProviderId","creditReference","creditLabel","credit","CARD_METHODS","Set","whole","value","legacy","has"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,6CAA4C;AACtE,SAASC,yBAAyB,QAAQ,mCAA+B;AACzE,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SAASC,eA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AQvE,WAAW,KAAK;YACnEqE,WAAW;QACb;;IACF,OAAO;WAAIN;WAAWO;KAAS,CAACzC,MAAM,CAAC,CAAC+C,SAAWA,OAAOV,SAAS,IAAIU,OAAO5E,WAAW,GAAG;AAC9F;AAEA,MAAM6E,eAAgD,IAAIC,IAAI;IAAC;IAAgB;IAAc;CAAY;AAEzG;;;;CAIC,GACD,OAAO,SAAStD,kBAAkB5B,IAAyB;IAMzD,IAAIA,CAAAA,wBAAAA,KAAMa,OAAO,MAAK,OAAO,OAAO,EAAE;IACtC,MAAMsE,QAAQ,CAACC,QAAmB5D,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACvB,OAAOiF,gBAAAA,QAAS,OAAO;IAChF,OAAOvF,cAAcG,MAClBiC,MAAM,CAAC,CAAC0C,UAAYA,QAAQ/D,MAAM,KAAK,aACvCuB,GAAG,CAAC,CAACwC;;YAKuB3E,cAIoBA;QAR/C,MAAMqF,SAASV,QAAQ5E,EAAE,KAAK;QAC9B,OAAO;YACL6E,QAAQD,QAAQC,MAAM;YACtBxE,aAAa+E,MAAMR,QAAQvE,WAAW;YACtCmB,UAAU4D,MAAME,UAASrF,eAAAA,KAAKC,MAAM,qBAAXD,aAAauB,QAAQ,GAAGoD,QAAQpD,QAAQ;YACjE,qEAAqE;YACrE,0BAA0B;YAC1Bd,UAAU4E,SACNJ,aAAaK,GAAG,CAACX,QAAQC,MAAM,IAAIO,eAAMnF,gBAAAA,KAAKC,MAAM,qBAAXD,cAAaS,QAAQ,mBAAIT,KAAKS,QAAQ,IAAI,IACnF0E,MAAMR,QAAQlE,QAAQ;QAC5B;IACF;AACJ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/order-view.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 { serialize } from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { fulfillmentLineQuantities } from '../../model/order-fulfillment'\nimport { fulfillmentTrackingUrl } from '../../model/tracking-url'\nimport { orderTaxEngineView } from '../../model/commerce-tax-engine'\nimport { orderIsTestMode } from '../../model/commerce-orders'\nimport { orderPayments, type OrderPaymentMethod } from '../../model/commerce-pos'\n\n/**\n * The public order shape from an order's data (AGL-3611): the same object the\n * API returns, so an order event and an outbound webhook carry exactly what\n * `GET /v1/sites/{id}/orders/{id}` would.\n */\nexport function orderViewFromData(id: string, data: Record<string, any>) {\n const totals = (data.totals ?? {}) as Record<string, unknown>\n const legacyTotal = Number(data.amountCents ?? NaN)\n const totalCents = Number.isFinite(Number(totals.totalCents))\n ? Number(totals.totalCents)\n : Number.isFinite(legacyTotal)\n ? legacyTotal\n : null\n const legacyFee = Number(data.feeCents ?? NaN)\n return {\n id,\n object: 'order',\n number: typeof data.number === 'number' ? data.number : null,\n status: (data.status as string) ?? null,\n channel: (data.channel as string) ?? 'online',\n currency: 'usd',\n customerEmail: data.customerEmail ?? null,\n customerName: data.customerName ?? null,\n lineItems: serialize(data.lineItems ?? []),\n totals: {\n itemsCents: Number(totals.itemsCents ?? 0),\n shippingCents: Number(totals.shippingCents ?? 0),\n taxCents: Number(totals.taxCents ?? 0),\n discountCents: Number(totals.discountCents ?? 0),\n totalCents,\n // The Connect application fee. NOT subtracted from `totalCents` — it is\n // Aglyn's cut of a total the shopper already paid in full, so a client\n // that nets it out of revenue would understate what it collected.\n feeCents: Number.isFinite(Number(totals.feeCents))\n ? Number(totals.feeCents)\n : Number.isFinite(legacyFee)\n ? legacyFee\n : 0,\n // Optional lines the buyer added at checkout (AGL-3635), inside\n // `totalCents` and outside `itemsCents`.\n extrasCents: Number(totals.extrasCents ?? 0) || 0,\n // A register tip (AGL-3607), on top of `totalCents` and not revenue.\n tipCents: Math.max(0, Math.round(Number(totals.tipCents ?? 0)) || 0),\n },\n // How a register sale was paid (AGL-3614): one entry per tender that\n // succeeded. A ledger needs it because only the card tenders went through\n // Stripe; cash went in the drawer, a gift card spent value the store\n // already held. Empty for every sale that is not the register's.\n payments: orderPaymentsView(data),\n // The part of `discountCents` a gift card paid online (AGL-3614).\n giftCardRedeemedCents: Math.max(0, Math.round(Number(data.giftCardRedeemedCents ?? 0)) || 0),\n // What those lines were and whose offer each was: the fact a plugin that\n // insures a parcel reads off `order.paid` to know it was bought.\n extras: (Array.isArray(data.extras) ? data.extras : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.id === 'string')\n .map((entry: Record<string, unknown>) => ({\n id: String(entry.id),\n pluginId: String(entry.pluginId ?? ''),\n key: String(entry.key ?? ''),\n label: String(entry.label ?? ''),\n amountCents: Number(entry.amountCents ?? 0) || 0,\n quoteRef: typeof entry.quoteRef === 'string' ? entry.quoteRef : null,\n })),\n // Store credit another plugin kept that paid part of the sale (AGL-3640):\n // a rewards redemption online comes off the goods (`discount`), one at\n // the register is one of its payments (`tender`). The provider reads its\n // own `reference` back off `order.paid` and `order.refunded`.\n credits: orderCreditsView(data),\n // Money already handed back, for any reason. A chargeback lands here too,\n // so `refundedCents > 0` does not by itself mean the merchant chose it.\n refundedCents: Number(data.refundedCents ?? 0),\n // Whether real money moved (AGL-3699): `false` for a Stripe test-mode\n // order, so a subscriber that tells an outside service about a sale —\n // a review invitation, a ledger — can leave a store's rehearsal out.\n // The seller's own rule: the recorded fact, else the session id.\n livemode: !orderIsTestMode({\n livemode: data.livemode,\n checkoutSessionId: data.checkoutSessionId,\n $id: id,\n }),\n // Who the tax was charged under (AGL-3614): `stripe-automatic` tax on a\n // sale that is not `direct` is Aglyn's to remit as marketplace facilitator\n // and never reaches the merchant's account; on a `direct` sale Stripe Tax\n // ran on the seller's own account and the tax is the seller's. A ledger\n // posting the sale has to know which. An order from before the regime was\n // recorded says `null`, never a guess.\n taxMode: typeof data.taxMode === 'string' && data.taxMode ? data.taxMode : null,\n // Where the sale was charged (AGL-3614): `direct` on the seller's own\n // Stripe account, so the money, Stripe's fees and any Stripe Tax are the\n // seller's; `null` through the platform's account, or not recorded.\n chargeModel: orderChargeModelView(data),\n // The merchant's own tax service (AGL-3631): which one priced the sale, or\n // that it was asked and the store's own rates were charged instead\n // (`status: 'fallback'`). `null` when no service was asked. The regime is\n // still `taxMode` — a service the merchant connected answers for tax the\n // merchant remits.\n taxEngine: orderTaxEngineView(data.taxEngine),\n disputed: Boolean(data.dispute),\n shippingAddress: serialize(data.shippingAddress) ?? null,\n couponCode: data.couponCode ?? null,\n // Shipment records — the half of fulfilment an integration can use\n // without a write (AGL-2460). `status` says an order is `fulfilled`; it\n // does not say which carrier took it or under what tracking number, so a\n // 3PL or accounting reconcile could see THAT an order shipped and never\n // WHICH shipment it was. The console's order dialog shows both, and an\n // order that has been shipped twice (a split shipment) is indistinguish-\n // able from one shipped once when only the status is published.\n //\n // `atMs` is a number of milliseconds, not a Firestore Timestamp, so\n // `serialize` passes it through untouched. It is republished as `at` in\n // ISO 8601 to match `created` and every other time this API emits: one\n // object publishing two time formats is a bug an integrator finds late,\n // in their own timezone conversion, and blames on their own code.\n fulfillments: (Array.isArray(data.fulfillments) ? data.fulfillments : []).map(\n (entry: Record<string, unknown>) => {\n const atMs = Number((entry ?? {}).atMs)\n return {\n id: (entry ?? {}).id ?? null,\n lineItemIds: Array.isArray((entry ?? {}).lineItemIds)\n ? (entry as { lineItemIds: unknown[] }).lineItemIds\n : [],\n // Units per line (AGL-3611); a fulfillment recorded before\n // quantities shipped every unit of the lines it names.\n lines: fulfillmentLineQuantities(\n { lineItems: Array.isArray(data.lineItems) ? data.lineItems : [] },\n (entry ?? {}) as never,\n ),\n status: (entry ?? {}).status === 'cancelled' ? 'cancelled' : 'active',\n carrier: (entry ?? {}).carrier ?? null,\n trackingNumber: (entry ?? {}).trackingNumber ?? null,\n trackingUrl: fulfillmentTrackingUrl((entry ?? {}) as never),\n labelUrl: (entry ?? {}).labelUrl ?? null,\n at: Number.isFinite(atMs) ? new Date(atMs).toISOString() : null,\n }\n },\n ),\n created: serialize(data.createdAt) ?? null,\n }\n}\n\n/** The plugin credits an order carries, online and at the register (AGL-3640). */\nexport function orderCreditsView(data: Record<string, any>): Array<{\n providerId: string\n pluginId: string\n reference: string\n label: string\n last4: string\n amountCents: number\n appliedAs: 'discount' | 'tender'\n}> {\n const online = (Array.isArray(data.credits) ? data.credits : [])\n .filter((entry: Record<string, unknown>) => entry && typeof entry.providerId === 'string')\n .map((entry: Record<string, unknown>) => ({\n providerId: String(entry.providerId),\n pluginId: String(entry.pluginId ?? String(entry.providerId).split('.')[0]),\n reference: String(entry.reference ?? ''),\n label: String(entry.label ?? ''),\n last4: String(entry.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(entry.amountCents) || 0)),\n appliedAs: entry.appliedAs === 'tender' ? ('tender' as const) : ('discount' as const),\n }))\n const register = (Array.isArray(data.payments) ? data.payments : [])\n .filter(\n (payment: Record<string, unknown>) =>\n payment &&\n payment.method === 'credit' &&\n payment.status === 'succeeded' &&\n typeof payment.creditProviderId === 'string',\n )\n .map((payment: Record<string, unknown>) => ({\n providerId: String(payment.creditProviderId),\n pluginId: String(payment.creditProviderId).split('.')[0],\n reference: String(payment.creditReference ?? ''),\n label: String(payment.creditLabel ?? ''),\n last4: String(payment.last4 ?? ''),\n amountCents: Math.max(0, Math.trunc(Number(payment.amountCents) || 0)),\n appliedAs: 'tender' as const,\n }))\n return [...online, ...register].filter((credit) => credit.reference && credit.amountCents > 0)\n}\n\nconst CARD_METHODS: ReadonlySet<OrderPaymentMethod> = new Set(['card_present', 'card_keyed', 'card_link'])\n\n/**\n * `direct` when the sale was charged on the seller's own Stripe account. An\n * online sale says so on the order; a register card taken on the store's own\n * account says so on its payment, so a succeeded card payment that does\n * counts too.\n */\nexport function orderChargeModelView(data: Record<string, any>): 'direct' | null {\n if (data?.chargeModel === 'direct') return 'direct'\n const payments = Array.isArray(data?.payments) ? (data.payments as Array<Record<string, unknown>>) : []\n const directCard = payments.some(\n (payment) =>\n payment?.status === 'succeeded' &&\n CARD_METHODS.has(payment.method as OrderPaymentMethod) &&\n payment.chargeModel === 'direct',\n )\n return directCard ? 'direct' : null\n}\n\n/**\n * A register sale's settled tenders as the order event names them (AGL-3614).\n * An order from before the split-tender ledger is one payment, inferred the\n * way the register's own reader infers it, with the order's tip and fee.\n */\nexport function orderPaymentsView(data: Record<string, any>): Array<{\n method: OrderPaymentMethod\n amountCents: number\n tipCents: number\n feeCents: number\n}> {\n if (data?.channel !== 'pos') return []\n const whole = (value: unknown) => Math.max(0, Math.round(Number(value ?? 0)) || 0)\n return orderPayments(data)\n .filter((payment) => payment.status === 'succeeded')\n .map((payment) => {\n const legacy = payment.id === 'legacy'\n return {\n method: payment.method,\n amountCents: whole(payment.amountCents),\n tipCents: whole(legacy ? data.totals?.tipCents : payment.tipCents),\n // The application fee Stripe took from this payment; a tender Stripe\n // never saw carried none.\n feeCents: legacy\n ? CARD_METHODS.has(payment.method) ? whole(data.totals?.feeCents ?? data.feeCents) : 0\n : whole(payment.feeCents),\n }\n })\n}\n"],"names":["serialize","fulfillmentLineQuantities","fulfillmentTrackingUrl","orderTaxEngineView","orderIsTestMode","orderPayments","orderViewFromData","id","data","totals","legacyTotal","Number","amountCents","NaN","totalCents","isFinite","legacyFee","feeCents","object","number","status","channel","currency","customerEmail","customerName","lineItems","itemsCents","shippingCents","taxCents","discountCents","extrasCents","tipCents","Math","max","round","payments","orderPaymentsView","giftCardRedeemedCents","extras","Array","isArray","filter","entry","map","String","pluginId","key","label","quoteRef","credits","orderCreditsView","refundedCents","livemode","checkoutSessionId","$id","taxMode","chargeModel","orderChargeModelView","taxEngine","disputed","Boolean","dispute","shippingAddress","couponCode","fulfillments","atMs","lineItemIds","lines","carrier","trackingNumber","trackingUrl","labelUrl","at","Date","toISOString","created","createdAt","online","providerId","split","reference","last4","trunc","appliedAs","register","payment","method","creditProviderId","creditReference","creditLabel","credit","CARD_METHODS","Set","directCard","some","has","whole","value","legacy"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,6CAA4C;AACtE,SAASC,yBAAyB,QAAQ,mCAA+B;AACzE,SAASC,sBAAsB,QAAQ,8BAA0B;AACjE,SAASC,kBAAkB,QAAQ,qCAAiC;AACpE,SAASC,eAAe,QAAQ,iCAA6B;AAC7D,SAASC,aAAa,QAAiC,8BAA0B;AAEjF;;;;CAIC,GACD,OAAO,SAASC,kBAAkBC,EAAU,EAAEC,IAAyB;QACrDA,cACWA,mBAMFA,gBAKdA,cACCA,eAEKA,qBACDA,oBACOA,iBAEAC,oBACGA,uBACLA,kBACKA,uBAYFA,qBAEoBA,kBAQWD,6BAoB/BA,qBA4BLR,YACLQ,kBAqCHR;IAlIX,MAAMS,UAAUD,eAAAA,KAAKC,MAAM,YAAXD,eAAe,CAAC;IAChC,MAAME,cAAcC,QAAOH,oBAAAA,KAAKI,WAAW,YAAhBJ,oBAAoBK;IAC/C,MAAMC,aAAaH,OAAOI,QAAQ,CAACJ,OAAOF,OAAOK,UAAU,KACvDH,OAAOF,OAAOK,UAAU,IACxBH,OAAOI,QAAQ,CAACL,eACdA,cACA;IACN,MAAMM,YAAYL,QAAOH,iBAAAA,KAAKS,QAAQ,YAAbT,iBAAiBK;IAC1C,OAAO;QACLN;QACAW,QAAQ;QACRC,QAAQ,OAAOX,KAAKW,MAAM,KAAK,WAAWX,KAAKW,MAAM,GAAG;QACxDC,MAAM,GAAGZ,eAAAA,KAAKY,MAAM,YAAXZ,eAA0B;QACnCa,OAAO,GAAGb,gBAAAA,KAAKa,OAAO,YAAZb,gBAA2B;QACrCc,UAAU;QACVC,aAAa,GAAEf,sBAAAA,KAAKe,aAAa,YAAlBf,sBAAsB;Q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AACC,QAAmBjE,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACvB,OAAOsF,gBAAAA,QAAS,OAAO;IAChF,OAAO5F,cAAcG,MAClBiC,MAAM,CAAC,CAAC4C,UAAYA,QAAQjE,MAAM,KAAK,aACvCuB,GAAG,CAAC,CAAC0C;;YAKuB7E,cAIoBA;QAR/C,MAAM0F,SAASb,QAAQ9E,EAAE,KAAK;QAC9B,OAAO;YACL+E,QAAQD,QAAQC,MAAM;YACtB1E,aAAaoF,MAAMX,QAAQzE,WAAW;YACtCmB,UAAUiE,MAAME,UAAS1F,eAAAA,KAAKC,MAAM,qBAAXD,aAAauB,QAAQ,GAAGsD,QAAQtD,QAAQ;YACjE,qEAAqE;YACrE,0BAA0B;YAC1Bd,UAAUiF,SACNP,aAAaI,GAAG,CAACV,QAAQC,MAAM,IAAIU,eAAMxF,gBAAAA,KAAKC,MAAM,qBAAXD,cAAaS,QAAQ,mBAAIT,KAAKS,QAAQ,IAAI,IACnF+E,MAAMX,QAAQpE,QAAQ;QAC5B;IACF;AACJ"}
|
|
@@ -16,10 +16,11 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { checkEntitlement, isHostPluginEnabled } from "@aglyn/aglyn/server";
|
|
18
18
|
import { ApiErrors, apiJson, listResponse } from "@aglyn/tenant-data-admin";
|
|
19
|
-
import { paginate, readJsonBody, requireScope,
|
|
19
|
+
import { paginate, readJsonBody, requireScope, requireSitePermission } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
20
20
|
import { BUNDLE_ID } from "../../constants/bundle-common.js";
|
|
21
21
|
import { recordOrderShipment } from "../fulfill-order.js";
|
|
22
22
|
import { orderViewFromData } from "./order-view.js";
|
|
23
|
+
import { productView } from "./product-view.js";
|
|
23
24
|
import { isUnpaidQuote } from "../../model/commerce-quotes.js";
|
|
24
25
|
/**
|
|
25
26
|
* A site's orders and products on the customer REST API,
|
|
@@ -322,71 +323,57 @@ export async function handleOrders(request, ctx, segments, url) {
|
|
|
322
323
|
});
|
|
323
324
|
}
|
|
324
325
|
/**
|
|
325
|
-
*
|
|
326
|
-
* `
|
|
327
|
-
*
|
|
328
|
-
*
|
|
329
|
-
* product
|
|
330
|
-
*
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
options: (_variant_options = variant.options) != null ? _variant_options : {},
|
|
344
|
-
priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,
|
|
345
|
-
compareAtPriceUsd: typeof variant.compareAtPriceUsd === 'number' ? variant.compareAtPriceUsd : null,
|
|
346
|
-
weightGrams: typeof variant.weightGrams === 'number' ? variant.weightGrams : null,
|
|
347
|
-
inventory: typeof inventory === 'number' ? inventory : null,
|
|
348
|
-
inventoryTracked: typeof inventory === 'number'
|
|
349
|
-
};
|
|
350
|
-
}
|
|
351
|
-
function productView(doc) {
|
|
352
|
-
var _doc_data, _data_name, _data_slug, _data_description, _data_type, _data_status, _data_tags, _data_categoryIds, _data_mediaUrls, _data_options, _serialize;
|
|
353
|
-
const data = (_doc_data = doc.data()) != null ? _doc_data : {};
|
|
354
|
-
const variants = Array.isArray(data.variants) ? data.variants : [];
|
|
355
|
-
const tracked = variants.filter((v)=>typeof v.inventory === 'number');
|
|
356
|
-
return {
|
|
357
|
-
id: doc.id,
|
|
358
|
-
object: 'product',
|
|
359
|
-
name: (_data_name = data.name) != null ? _data_name : null,
|
|
360
|
-
slug: (_data_slug = data.slug) != null ? _data_slug : null,
|
|
361
|
-
description: (_data_description = data.description) != null ? _data_description : null,
|
|
362
|
-
type: (_data_type = data.type) != null ? _data_type : null,
|
|
363
|
-
status: (_data_status = data.status) != null ? _data_status : null,
|
|
364
|
-
tags: (_data_tags = data.tags) != null ? _data_tags : [],
|
|
365
|
-
categoryIds: (_data_categoryIds = data.categoryIds) != null ? _data_categoryIds : [],
|
|
366
|
-
mediaUrls: (_data_mediaUrls = data.mediaUrls) != null ? _data_mediaUrls : [],
|
|
367
|
-
options: (_data_options = data.options) != null ? _data_options : [],
|
|
368
|
-
variants: variants.map(variantView),
|
|
369
|
-
// The sum across TRACKED variants only, and `null` when none of them is
|
|
370
|
-
// tracked — so an untracked catalogue reads as "we don't count this"
|
|
371
|
-
// rather than as a store with nothing left to sell.
|
|
372
|
-
inventory: tracked.length ? tracked.reduce((sum, v)=>{
|
|
373
|
-
var _v_inventory;
|
|
374
|
-
return sum + Number((_v_inventory = v.inventory) != null ? _v_inventory : 0);
|
|
375
|
-
}, 0) : null,
|
|
376
|
-
subscription: (_serialize = serialize(data.subscription)) != null ? _serialize : null,
|
|
377
|
-
created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,
|
|
378
|
-
updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null
|
|
379
|
-
};
|
|
326
|
+
* The product writes' gates (AGL-4235), each load-bearing, in `updateOrder`'s
|
|
327
|
+
* order: `products:write` on the credential, the `commerce` PLAN entitlement,
|
|
328
|
+
* this plugin switched on for this site, and — for an app a person connected
|
|
329
|
+
* — that person's "Edit site content" on the site, the permission the
|
|
330
|
+
* console's product editor and the native apps' save route ask. The router
|
|
331
|
+
* has already applied the site's lock and the person's membership.
|
|
332
|
+
*/ function productWriteRefusal(ctx, hostId, hostDoc) {
|
|
333
|
+
const denied = requireScope(ctx, 'products:write');
|
|
334
|
+
if (denied) return denied;
|
|
335
|
+
const unentitled = requireCommerce(ctx);
|
|
336
|
+
if (unentitled) return unentitled;
|
|
337
|
+
if (!isHostPluginEnabled(ctx.org, hostDoc.data(), BUNDLE_ID)) {
|
|
338
|
+
return ApiErrors.notFound({
|
|
339
|
+
message: 'No such site',
|
|
340
|
+
headers: ctx.headers
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
return requireSitePermission(ctx, hostDoc, 'site.edit');
|
|
380
344
|
}
|
|
381
345
|
export async function handleProducts(request, ctx, segments, url) {
|
|
382
|
-
const [, hostId, , productId] = segments;
|
|
346
|
+
const [, hostId, , productId, sub, variantId] = segments;
|
|
347
|
+
if (sub !== undefined && (sub !== 'variants' || !variantId || segments.length > 6)) {
|
|
348
|
+
return ApiErrors.notFound({
|
|
349
|
+
message: 'Unknown endpoint',
|
|
350
|
+
headers: ctx.headers
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
const writing = request.method === 'POST' && !productId || (request.method === 'PATCH' || request.method === 'DELETE') && productId && !variantId || request.method === 'PATCH' && variantId;
|
|
354
|
+
// `products:write` is asked BEFORE `products:read`, as the order writes ask
|
|
355
|
+
// theirs (AGL-900): a key that only writes the catalog holds no read scope.
|
|
356
|
+
if (writing) {
|
|
357
|
+
var _ref;
|
|
358
|
+
var _ctx_site;
|
|
359
|
+
const hostDoc = (_ref = (_ctx_site = ctx.site) == null ? void 0 : _ctx_site.snapshot) != null ? _ref : await hostRef(ctx, hostId).get();
|
|
360
|
+
const refused = productWriteRefusal(ctx, hostId, hostDoc);
|
|
361
|
+
if (refused) return refused;
|
|
362
|
+
const writes = await import("./product-writes.js");
|
|
363
|
+
if (variantId) return writes.updateProductVariant(request, ctx, hostId, productId, variantId);
|
|
364
|
+
if (!productId) return writes.createProduct(request, ctx, hostId);
|
|
365
|
+
if (request.method === 'PATCH') return writes.updateProduct(request, ctx, hostId, productId);
|
|
366
|
+
return writes.deleteProductOverApi(ctx, hostId, productId);
|
|
367
|
+
}
|
|
383
368
|
const denied = requireScope(ctx, 'products:read');
|
|
384
369
|
if (denied) return denied;
|
|
385
370
|
const unentitled = requireCommerce(ctx);
|
|
386
371
|
if (unentitled) return unentitled;
|
|
387
|
-
if (request.method !== 'GET') {
|
|
372
|
+
if (request.method !== 'GET' || variantId) {
|
|
388
373
|
return ApiErrors.methodNotAllowed({
|
|
389
|
-
headers: ctx.headers
|
|
374
|
+
headers: _extends({}, ctx.headers, {
|
|
375
|
+
Allow: variantId ? 'PATCH' : productId ? 'GET, PATCH, DELETE' : 'GET, POST'
|
|
376
|
+
})
|
|
390
377
|
});
|
|
391
378
|
}
|
|
392
379
|
const collection = hostRef(ctx, hostId).collection('products');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/orders-and-products.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 { checkEntitlement, isHostPluginEnabled } from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n paginate,\n readJsonBody,\n requireScope,\n serialize,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { BUNDLE_ID } from '../../constants/bundle-common'\nimport { type OrderFulfilmentTarget, recordOrderShipment } from '../fulfill-order'\nimport { orderViewFromData } from './order-view'\nimport { isUnpaidQuote } from '../../model/commerce-quotes'\n\n/**\n * A site's orders and products on the customer REST API,\n * `/v1/sites/{siteId}/orders/…` and `/v1/sites/{siteId}/products/…`\n * (AGL-1928, AGL-2461, AGL-3080). Registered from this plugin's console\n * server declarations; the console's `/v1` router owns the pipeline in\n * front — the key, the plan's API access, the request quota, the rate limit —\n * and refuses a site the key's organization does not own before it hands a\n * request here.\n */\n\n/**\n * Commerce resources need the `commerce` entitlement as well as the scope\n * (AGL-1928). `apiAccess` alone is the wrong gate here: it says the org may\n * call the API at all, not that it may still use the store. AGL-1873 closed\n * exactly this class on the write side — two money doors that asked the\n * plugin switch (`org.enabledPlugins`) instead of the plan, so a lapsed org\n * kept selling — and the same reasoning applies to a read. `enabledPlugins`\n * is the customer's own on/off switch and survives a downgrade; the plan does\n * not, and the published rule is that paid features stop at the door when the\n * plan no longer includes them.\n *\n * Answered as `plan_required` rather than `not_found`, deliberately. Hiding a\n * store that plainly exists behind a 404 sends an integrator hunting a wrong\n * site id; the honest answer names the plan.\n */\nfunction requireCommerce(ctx: ApiV1Context): Response | null {\n return checkEntitlement(ctx.org, 'commerce')\n ? null\n : ApiErrors.planRequired({\n message: 'Commerce is not included in this organization’s plan',\n code: 'commerce',\n headers: ctx.headers,\n })\n}\n\nfunction hostRef(ctx: ApiV1Context, hostId: string) {\n return ctx.firestore.collection('hosts').doc(hostId)\n}\n\n/**\n * Orders carry a legacy Commerce Starter shape (AGL-90) alongside the modern\n * one: `amountCents`/`feeCents` at the top level rather than a `totals` map.\n * The console lifts them through `CommerceModel.liftLegacyOrder` and reads\n * `lifted.totals?.totalCents ?? order.amountCents`. The API cannot publish two\n * shapes for one object, so the legacy fields are folded into `totals` here\n * and a client only ever sees the modern one. `channel` defaults to `online`\n * for the same reason the console's list does — an absent channel is a\n * pre-channel order, not an unknown one.\n */\nfunction orderView(doc: FirebaseFirestore.DocumentSnapshot) {\n return orderViewFromData(doc.id, doc.data() ?? {})\n}\n\nexport async function handleOrders(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , orderId] = segments\n // `orders:write` is checked BEFORE `orders:read`, matching `handleSites`\n // and `handleScopedMedia` (AGL-900): a fulfilment key that only records\n // shipments must not be told it lacks a read scope it was never meant to\n // hold.\n if (request.method === 'PATCH' && orderId) {\n const deniedWrite = requireScope(ctx, 'orders:write')\n if (deniedWrite) return deniedWrite\n const unentitledWrite = requireCommerce(ctx)\n if (unentitledWrite) return unentitledWrite\n return updateOrder(request, ctx, hostId, orderId)\n }\n const denied = requireScope(ctx, 'orders:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET') {\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: orderId ? 'GET, PATCH' : 'GET' },\n })\n }\n const collection = hostRef(ctx, hostId).collection('orders')\n\n if (orderId) {\n const snap = await collection.doc(orderId).get()\n // An unpaid quote is not an order yet (AGL-4093).\n if (!snap.exists || isUnpaidQuote(snap.data())) {\n return ApiErrors.notFound({ message: 'No such order', headers: ctx.headers })\n }\n return apiJson(orderView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const channel = url.searchParams.get('channel')\n // `online` is the DEFAULT, not a stored value on older orders, so filtering\n // for it in Firestore would silently drop every pre-channel order. Those are\n // exactly the oldest orders an accounting backfill is reaching for, so this\n // one value is filtered after the read instead. The page can therefore come\n // back shorter than `limit` while `has_more` is still true — which the\n // published pagination contract already tells clients to expect (check\n // `has_more`, never a page's length).\n if (channel && channel !== 'online') query = query.where('channel', '==', channel)\n const { docs, nextCursor } = await paginate(query, url)\n // Unpaid quotes share the collection and are not orders yet (AGL-4093);\n // left out after the read, like `online` above, so a page can be short.\n const data = docs\n .filter((doc) => !isUnpaidQuote(doc.data()))\n .map(orderView)\n .filter((order) => (channel === 'online' ? order.channel === 'online' : true))\n return listResponse(data, nextCursor, ctx.headers)\n}\n\n/**\n * Statuses this endpoint will move an order TO, and the two it names as\n * refused. Kept as data so the 400 can list them and the docs can be checked\n * against the same source the handler branches on.\n */\nconst ORDER_WRITE_TARGETS: OrderFulfilmentTarget[] = ['fulfilled', 'delivered']\n\n/** The keys a PATCH may carry (AGL-3611 added the last three). */\nconst ORDER_WRITABLE_KEYS = ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify']\n\n/**\n * Transitions that exist in the commerce model and are DELIBERATELY not\n * reachable here — refused by name with a 400 that says why, never silently\n * ignored. `cancelled` releases held stock under its own transaction and\n * `refunded` moves money under another; admitting either here would hand a\n * caller a door around exactly the specifics those two routes exist to\n * enforce, and an API key is the credential least able to answer the\n * questions they ask.\n */\nconst ORDER_WRITE_REFUSED: Record<string, string> = {\n cancelled:\n 'Canceling an order releases held stock, so it is not part of this endpoint. Cancel it in the console.',\n refunded:\n 'Refunding an order moves money, so it is not part of this endpoint. Refund it in the console.',\n}\n\n/**\n * `PATCH /v1/sites/{siteId}/orders/{orderId}` — record a shipment (AGL-2461).\n *\n * ## The write is the console's, shared\n *\n * The transition rule, the transaction that re-asks it under the write, the\n * fulfillment append and the timeline entry are `recordOrderShipment`'s,\n * the one implementation the console's `commerce/fulfill-order` route calls\n * too. A second copy of `ORDER_TRANSITIONS` here would be the bug rather\n * than the fix: two tables drift, and drift here means the API writing an\n * order status the console forbids — `paid → delivered` skipping\n * fulfilment, or a write onto a `refunded` order. That is the class\n * AGL-1818/AGL-1819 exist to close, and it is money-adjacent.\n *\n * ## What THIS function is responsible for: all of the authorization\n *\n * `recordOrderShipment` is pre-authorized by contract — it takes `hostId`\n * on trust — so every gate is here, and all four are load-bearing:\n *\n * 1. `orders:write` on the key (checked by the caller, above).\n * 2. The `commerce` PLAN entitlement (checked by the caller, above) — the\n * plan, never the plugin switch, which is the AGL-1873 distinction.\n * 3. **Org owns the site** — the console's `handleSites` refuses an unowned\n * `hostId` with a 404 before it hands any site resource to its plugin,\n * which is what keeps this from being a cross-tenant write primitive\n * addressable by anyone who can guess a host id. Deliberately NOT\n * re-checked here: a second copy would be a gate no test can redden\n * (removing either one alone leaves the other answering), and an unproven\n * guard on a cross-tenant write is worse than the one guard a test\n * actually holds. `api-v1-order-fulfilment.spec.ts`'s \"CANNOT move\n * another org's order\" case is that test, and it fails when\n * `handleSites`' `orgOwnsHost` is removed.\n * 4. **This plugin is switched on for this site.** The resource is\n * registered for every organization the console serves, so its being here\n * says nothing about one org's configuration; without this an org that\n * switched commerce off for a site would still accept writes into it,\n * which is the per-site enablement rule (AGL-1014) the plugin API\n * dispatcher applies to every other commerce door.\n *\n * ## No `Idempotency-Key`\n *\n * None is needed and none is accepted: the write returns without writing when\n * the order is already in the target status, so a retry lands the same state\n * AND returns the same `200` with the same order body — the contract\n * `updateRecord`, `updateContact` and `updateFormSubmission` are held to.\n */\nasync function updateOrder(\n request: Request,\n ctx: ApiV1Context,\n hostId: string,\n orderId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const unknown = Object.keys(body).filter((key) => !ORDER_WRITABLE_KEYS.includes(key))\n if (unknown.length > 0) {\n // Named, not dropped — the `updateFormSubmission` / `updateContact` rule.\n // A silently ignored `trackingUrl` here reads as \"we recorded your\n // shipment as you described it\" when half of it went nowhere, and the\n // caller is a warehouse system that will never look again.\n return ApiErrors.badRequest({\n message:\n 'Only `status`, `carrier`, `trackingNumber`, `trackingUrl`, `lineItems` and `notify` can be set on an order',\n code: 'validation_failed',\n fields: Object.fromEntries(\n unknown.map((key) => [key, 'Not writable on an order']),\n ),\n headers: ctx.headers,\n })\n }\n\n const status = String(body.status ?? '')\n const refusal = ORDER_WRITE_REFUSED[status]\n if (refusal) {\n return ApiErrors.badRequest({\n message: refusal,\n code: 'validation_failed',\n fields: { status: refusal },\n headers: ctx.headers,\n })\n }\n if (!(ORDER_WRITE_TARGETS as string[]).includes(status)) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n status: `Must be one of: ${ORDER_WRITE_TARGETS.join(', ')}`,\n },\n headers: ctx.headers,\n })\n }\n // Bounded exactly as the console route bounds them, so one field cannot be\n // used to stuff an order document through a door the console keeps narrow.\n const carrier = String(body.carrier ?? '').slice(0, 40)\n const trackingNumber = String(body.trackingNumber ?? '').slice(0, 60)\n // Partial shipments (AGL-3611): `lineItems: [{ lineItemId, quantity }]`.\n // Absent keeps the old meaning, everything still to ship.\n let lineItems: Array<{ lineItemId: number; quantity: number }> | undefined\n if (body.lineItems !== undefined) {\n if (status !== 'fulfilled' || !Array.isArray(body.lineItems) || body.lineItems.length === 0) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n lineItems:\n status !== 'fulfilled'\n ? 'Only a `fulfilled` update names line items'\n : 'Must be a non-empty array of { lineItemId, quantity }',\n },\n headers: ctx.headers,\n })\n }\n lineItems = (body.lineItems as unknown[]).slice(0, 500).map((entry) => ({\n lineItemId: Number((entry as Record<string, unknown>)?.lineItemId),\n quantity: Number((entry as Record<string, unknown>)?.quantity),\n }))\n }\n const idempotencyKey = request.headers.get('idempotency-key') ?? undefined\n\n // Gate 4: this plugin, on for this site.\n const hostSnap = await hostRef(ctx, hostId).get()\n if (!isHostPluginEnabled(ctx.org, hostSnap.data(), BUNDLE_ID)) {\n return ApiErrors.notFound({\n message: 'No such site',\n headers: ctx.headers,\n })\n }\n\n const outcome = await recordOrderShipment({\n hostId,\n orderId,\n to: status as OrderFulfilmentTarget,\n carrier,\n trackingNumber,\n ...(lineItems ? { lineItems } : {}),\n ...(typeof body.trackingUrl === 'string' ? { trackingUrl: body.trackingUrl } : {}),\n ...(body.notify === false ? { notify: false } : {}),\n ...(idempotencyKey ? { idempotencyKey } : {}),\n })\n if (outcome.outcome === 'invalid_lines') {\n return outcome.problem.problem === 'over_fulfilled'\n ? ApiErrors.conflict({\n message: outcome.message,\n code: 'over_fulfilled',\n headers: ctx.headers,\n })\n : ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: { lineItems: outcome.message },\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'no_such_order') {\n return ApiErrors.notFound({\n message: 'No such order',\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'blocked') {\n // A NEW 409 code (`order_transition`), because an integrator has to be\n // able to tell \"the order moved on without me\" apart from every other\n // conflict this API can raise — it is the one a fulfilment poller will\n // actually hit, and the one it must not retry forever.\n return ApiErrors.conflict({\n message: `Orders in \"${outcome.from}\" cannot be marked ${status}`,\n code: 'order_transition',\n headers: ctx.headers,\n })\n }\n // The order object, on both `recorded` and `already` — a retry lands the\n // same state and reads the same 200. Re-read after the write so the body\n // shows the shipment that was just recorded rather than the one before it.\n return apiJson(orderView(await hostRef(ctx, hostId).collection('orders').doc(orderId).get()), {\n headers: ctx.headers,\n })\n}\n\n/**\n * Price and stock live on VARIANTS, never on the product — a product-level\n * `inventory` exists only as a denormalized sum the console rewrites on every\n * decrement, and a product-level `priceUsd` is the legacy single-variant\n * shape. Publishing either as the product's price would be wrong the moment a\n * product has two variants, so the variant array is the contract and the\n * product carries only the roll-up, clearly named.\n *\n * `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.\n * Collapsing them (the `?? 0` an integrator writes on the first day) turns\n * every untracked product into an out-of-stock one, so the distinction is\n * carried through verbatim rather than defaulted.\n */\nfunction variantView(variant: Record<string, unknown>) {\n const inventory = variant.inventory\n return {\n id: variant.id ?? null,\n sku: variant.sku ?? null,\n barcode: variant.barcode ?? null,\n options: variant.options ?? {},\n priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,\n compareAtPriceUsd:\n typeof variant.compareAtPriceUsd === 'number'\n ? variant.compareAtPriceUsd\n : null,\n weightGrams:\n typeof variant.weightGrams === 'number' ? variant.weightGrams : null,\n inventory: typeof inventory === 'number' ? inventory : null,\n inventoryTracked: typeof inventory === 'number',\n }\n}\n\nfunction productView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n const variants = Array.isArray(data.variants)\n ? (data.variants as Array<Record<string, unknown>>)\n : []\n const tracked = variants.filter((v) => typeof v.inventory === 'number')\n return {\n id: doc.id,\n object: 'product',\n name: data.name ?? null,\n slug: data.slug ?? null,\n description: data.description ?? null,\n type: data.type ?? null,\n status: data.status ?? null,\n tags: data.tags ?? [],\n categoryIds: data.categoryIds ?? [],\n mediaUrls: data.mediaUrls ?? [],\n options: data.options ?? [],\n variants: variants.map(variantView),\n // The sum across TRACKED variants only, and `null` when none of them is\n // tracked — so an untracked catalogue reads as \"we don't count this\"\n // rather than as a store with nothing left to sell.\n inventory: tracked.length\n ? tracked.reduce((sum, v) => sum + Number(v.inventory ?? 0), 0)\n : null,\n subscription: serialize(data.subscription) ?? null,\n created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,\n updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null,\n }\n}\n\nexport async function handleProducts(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , productId] = segments\n const denied = requireScope(ctx, 'products:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET') {\n return ApiErrors.methodNotAllowed({ headers: ctx.headers })\n }\n const collection = hostRef(ctx, hostId).collection('products')\n\n if (productId) {\n const snap = await collection.doc(productId).get()\n // A soft-deleted product is gone as far as a customer is concerned. The\n // console filters `deletedAt` client-side; the API must not hand back a\n // product the merchant deleted just because the document survives.\n if (!snap.exists || snap.get('deletedAt')) {\n return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n }\n return apiJson(productView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const { docs, nextCursor } = await paginate(query, url)\n const data = docs.filter((doc) => !doc.get('deletedAt')).map(productView)\n return listResponse(data, nextCursor, ctx.headers)\n}\n\n"],"names":["checkEntitlement","isHostPluginEnabled","ApiErrors","apiJson","listResponse","paginate","readJsonBody","requireScope","serialize","BUNDLE_ID","recordOrderShipment","orderViewFromData","isUnpaidQuote","requireCommerce","ctx","org","planRequired","message","code","headers","hostRef","hostId","firestore","collection","doc","orderView","id","data","handleOrders","request","segments","url","orderId","method","deniedWrite","unentitledWrite","updateOrder","denied","unentitled","methodNotAllowed","Allow","snap","get","exists","notFound","query","status","searchParams","where","channel","docs","nextCursor","filter","map","order","ORDER_WRITE_TARGETS","ORDER_WRITABLE_KEYS","ORDER_WRITE_REFUSED","cancelled","refunded","body","unknown","Object","keys","key","includes","length","badRequest","fields","fromEntries","String","refusal","join","carrier","slice","trackingNumber","lineItems","undefined","Array","isArray","entry","lineItemId","Number","quantity","idempotencyKey","hostSnap","outcome","to","trackingUrl","notify","problem","conflict","from","variantView","variant","inventory","sku","barcode","options","priceUsd","compareAtPriceUsd","weightGrams","inventoryTracked","productView","variants","tracked","v","object","name","slug","description","type","tags","categoryIds","mediaUrls","reduce","sum","subscription","created","createdAtMs","Date","toISOString","updated","updatedAtMs","handleProducts","productId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,mBAAmB,QAAQ,sBAAqB;AAC3E,SACEC,SAAS,EACTC,OAAO,EACPC,YAAY,QACP,2BAA0B;AACjC,SAEEC,QAAQ,EACRC,YAAY,EACZC,YAAY,EACZC,SAAS,QACJ,6CAA4C;AACnD,SAASC,SAAS,QAAQ,mCAA+B;AACzD,SAAqCC,mBAAmB,QAAQ,sBAAkB;AAClF,SAASC,iBAAiB,QAAQ,kBAAc;AAChD,SAASC,aAAa,QAAQ,iCAA6B;AAE3D;;;;;;;;CAQC,GAED;;;;;;;;;;;;;;CAcC,GACD,SAASC,gBAAgBC,GAAiB;IACxC,OAAOd,iBAAiBc,IAAIC,GAAG,EAAE,cAC7B,OACAb,UAAUc,YAAY,CAAC;QACrBC,SAAS;QACTC,MAAM;QACNC,SAASL,IAAIK,OAAO;IACtB;AACN;AAEA,SAASC,QAAQN,GAAiB,EAAEO,MAAc;IAChD,OAAOP,IAAIQ,SAAS,CAACC,UAAU,CAAC,SAASC,GAAG,CAACH;AAC/C;AAEA;;;;;;;;;CASC,GACD,SAASI,UAAUD,GAAuC;QACvBA;IAAjC,OAAOb,kBAAkBa,IAAIE,EAAE,GAAEF,YAAAA,IAAIG,IAAI,cAARH,YAAc,CAAC;AAClD;AAEA,OAAO,eAAeI,aACpBC,OAAgB,EAChBf,GAAiB,EACjBgB,QAAkB,EAClBC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
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/orders-and-products.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 { checkEntitlement, isHostPluginEnabled } from '@aglyn/aglyn/server'\nimport {\n ApiErrors,\n apiJson,\n listResponse,\n} from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n paginate,\n readJsonBody,\n requireScope,\n requireSitePermission,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport { BUNDLE_ID } from '../../constants/bundle-common'\nimport { type OrderFulfilmentTarget, recordOrderShipment } from '../fulfill-order'\nimport { orderViewFromData } from './order-view'\nimport { productView } from './product-view'\nimport { isUnpaidQuote } from '../../model/commerce-quotes'\n\n/**\n * A site's orders and products on the customer REST API,\n * `/v1/sites/{siteId}/orders/…` and `/v1/sites/{siteId}/products/…`\n * (AGL-1928, AGL-2461, AGL-3080). Registered from this plugin's console\n * server declarations; the console's `/v1` router owns the pipeline in\n * front — the key, the plan's API access, the request quota, the rate limit —\n * and refuses a site the key's organization does not own before it hands a\n * request here.\n */\n\n/**\n * Commerce resources need the `commerce` entitlement as well as the scope\n * (AGL-1928). `apiAccess` alone is the wrong gate here: it says the org may\n * call the API at all, not that it may still use the store. AGL-1873 closed\n * exactly this class on the write side — two money doors that asked the\n * plugin switch (`org.enabledPlugins`) instead of the plan, so a lapsed org\n * kept selling — and the same reasoning applies to a read. `enabledPlugins`\n * is the customer's own on/off switch and survives a downgrade; the plan does\n * not, and the published rule is that paid features stop at the door when the\n * plan no longer includes them.\n *\n * Answered as `plan_required` rather than `not_found`, deliberately. Hiding a\n * store that plainly exists behind a 404 sends an integrator hunting a wrong\n * site id; the honest answer names the plan.\n */\nfunction requireCommerce(ctx: ApiV1Context): Response | null {\n return checkEntitlement(ctx.org, 'commerce')\n ? null\n : ApiErrors.planRequired({\n message: 'Commerce is not included in this organization’s plan',\n code: 'commerce',\n headers: ctx.headers,\n })\n}\n\nfunction hostRef(ctx: ApiV1Context, hostId: string) {\n return ctx.firestore.collection('hosts').doc(hostId)\n}\n\n/**\n * Orders carry a legacy Commerce Starter shape (AGL-90) alongside the modern\n * one: `amountCents`/`feeCents` at the top level rather than a `totals` map.\n * The console lifts them through `CommerceModel.liftLegacyOrder` and reads\n * `lifted.totals?.totalCents ?? order.amountCents`. The API cannot publish two\n * shapes for one object, so the legacy fields are folded into `totals` here\n * and a client only ever sees the modern one. `channel` defaults to `online`\n * for the same reason the console's list does — an absent channel is a\n * pre-channel order, not an unknown one.\n */\nfunction orderView(doc: FirebaseFirestore.DocumentSnapshot) {\n return orderViewFromData(doc.id, doc.data() ?? {})\n}\n\nexport async function handleOrders(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , orderId] = segments\n // `orders:write` is checked BEFORE `orders:read`, matching `handleSites`\n // and `handleScopedMedia` (AGL-900): a fulfilment key that only records\n // shipments must not be told it lacks a read scope it was never meant to\n // hold.\n if (request.method === 'PATCH' && orderId) {\n const deniedWrite = requireScope(ctx, 'orders:write')\n if (deniedWrite) return deniedWrite\n const unentitledWrite = requireCommerce(ctx)\n if (unentitledWrite) return unentitledWrite\n return updateOrder(request, ctx, hostId, orderId)\n }\n const denied = requireScope(ctx, 'orders:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET') {\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: orderId ? 'GET, PATCH' : 'GET' },\n })\n }\n const collection = hostRef(ctx, hostId).collection('orders')\n\n if (orderId) {\n const snap = await collection.doc(orderId).get()\n // An unpaid quote is not an order yet (AGL-4093).\n if (!snap.exists || isUnpaidQuote(snap.data())) {\n return ApiErrors.notFound({ message: 'No such order', headers: ctx.headers })\n }\n return apiJson(orderView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const channel = url.searchParams.get('channel')\n // `online` is the DEFAULT, not a stored value on older orders, so filtering\n // for it in Firestore would silently drop every pre-channel order. Those are\n // exactly the oldest orders an accounting backfill is reaching for, so this\n // one value is filtered after the read instead. The page can therefore come\n // back shorter than `limit` while `has_more` is still true — which the\n // published pagination contract already tells clients to expect (check\n // `has_more`, never a page's length).\n if (channel && channel !== 'online') query = query.where('channel', '==', channel)\n const { docs, nextCursor } = await paginate(query, url)\n // Unpaid quotes share the collection and are not orders yet (AGL-4093);\n // left out after the read, like `online` above, so a page can be short.\n const data = docs\n .filter((doc) => !isUnpaidQuote(doc.data()))\n .map(orderView)\n .filter((order) => (channel === 'online' ? order.channel === 'online' : true))\n return listResponse(data, nextCursor, ctx.headers)\n}\n\n/**\n * Statuses this endpoint will move an order TO, and the two it names as\n * refused. Kept as data so the 400 can list them and the docs can be checked\n * against the same source the handler branches on.\n */\nconst ORDER_WRITE_TARGETS: OrderFulfilmentTarget[] = ['fulfilled', 'delivered']\n\n/** The keys a PATCH may carry (AGL-3611 added the last three). */\nconst ORDER_WRITABLE_KEYS = ['status', 'carrier', 'trackingNumber', 'trackingUrl', 'lineItems', 'notify']\n\n/**\n * Transitions that exist in the commerce model and are DELIBERATELY not\n * reachable here — refused by name with a 400 that says why, never silently\n * ignored. `cancelled` releases held stock under its own transaction and\n * `refunded` moves money under another; admitting either here would hand a\n * caller a door around exactly the specifics those two routes exist to\n * enforce, and an API key is the credential least able to answer the\n * questions they ask.\n */\nconst ORDER_WRITE_REFUSED: Record<string, string> = {\n cancelled:\n 'Canceling an order releases held stock, so it is not part of this endpoint. Cancel it in the console.',\n refunded:\n 'Refunding an order moves money, so it is not part of this endpoint. Refund it in the console.',\n}\n\n/**\n * `PATCH /v1/sites/{siteId}/orders/{orderId}` — record a shipment (AGL-2461).\n *\n * ## The write is the console's, shared\n *\n * The transition rule, the transaction that re-asks it under the write, the\n * fulfillment append and the timeline entry are `recordOrderShipment`'s,\n * the one implementation the console's `commerce/fulfill-order` route calls\n * too. A second copy of `ORDER_TRANSITIONS` here would be the bug rather\n * than the fix: two tables drift, and drift here means the API writing an\n * order status the console forbids — `paid → delivered` skipping\n * fulfilment, or a write onto a `refunded` order. That is the class\n * AGL-1818/AGL-1819 exist to close, and it is money-adjacent.\n *\n * ## What THIS function is responsible for: all of the authorization\n *\n * `recordOrderShipment` is pre-authorized by contract — it takes `hostId`\n * on trust — so every gate is here, and all four are load-bearing:\n *\n * 1. `orders:write` on the key (checked by the caller, above).\n * 2. The `commerce` PLAN entitlement (checked by the caller, above) — the\n * plan, never the plugin switch, which is the AGL-1873 distinction.\n * 3. **Org owns the site** — the console's `handleSites` refuses an unowned\n * `hostId` with a 404 before it hands any site resource to its plugin,\n * which is what keeps this from being a cross-tenant write primitive\n * addressable by anyone who can guess a host id. Deliberately NOT\n * re-checked here: a second copy would be a gate no test can redden\n * (removing either one alone leaves the other answering), and an unproven\n * guard on a cross-tenant write is worse than the one guard a test\n * actually holds. `api-v1-order-fulfilment.spec.ts`'s \"CANNOT move\n * another org's order\" case is that test, and it fails when\n * `handleSites`' `orgOwnsHost` is removed.\n * 4. **This plugin is switched on for this site.** The resource is\n * registered for every organization the console serves, so its being here\n * says nothing about one org's configuration; without this an org that\n * switched commerce off for a site would still accept writes into it,\n * which is the per-site enablement rule (AGL-1014) the plugin API\n * dispatcher applies to every other commerce door.\n *\n * ## No `Idempotency-Key`\n *\n * None is needed and none is accepted: the write returns without writing when\n * the order is already in the target status, so a retry lands the same state\n * AND returns the same `200` with the same order body — the contract\n * `updateRecord`, `updateContact` and `updateFormSubmission` are held to.\n */\nasync function updateOrder(\n request: Request,\n ctx: ApiV1Context,\n hostId: string,\n orderId: string,\n): Promise<Response> {\n const body = await readJsonBody(request)\n const unknown = Object.keys(body).filter((key) => !ORDER_WRITABLE_KEYS.includes(key))\n if (unknown.length > 0) {\n // Named, not dropped — the `updateFormSubmission` / `updateContact` rule.\n // A silently ignored `trackingUrl` here reads as \"we recorded your\n // shipment as you described it\" when half of it went nowhere, and the\n // caller is a warehouse system that will never look again.\n return ApiErrors.badRequest({\n message:\n 'Only `status`, `carrier`, `trackingNumber`, `trackingUrl`, `lineItems` and `notify` can be set on an order',\n code: 'validation_failed',\n fields: Object.fromEntries(\n unknown.map((key) => [key, 'Not writable on an order']),\n ),\n headers: ctx.headers,\n })\n }\n\n const status = String(body.status ?? '')\n const refusal = ORDER_WRITE_REFUSED[status]\n if (refusal) {\n return ApiErrors.badRequest({\n message: refusal,\n code: 'validation_failed',\n fields: { status: refusal },\n headers: ctx.headers,\n })\n }\n if (!(ORDER_WRITE_TARGETS as string[]).includes(status)) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n status: `Must be one of: ${ORDER_WRITE_TARGETS.join(', ')}`,\n },\n headers: ctx.headers,\n })\n }\n // Bounded exactly as the console route bounds them, so one field cannot be\n // used to stuff an order document through a door the console keeps narrow.\n const carrier = String(body.carrier ?? '').slice(0, 40)\n const trackingNumber = String(body.trackingNumber ?? '').slice(0, 60)\n // Partial shipments (AGL-3611): `lineItems: [{ lineItemId, quantity }]`.\n // Absent keeps the old meaning, everything still to ship.\n let lineItems: Array<{ lineItemId: number; quantity: number }> | undefined\n if (body.lineItems !== undefined) {\n if (status !== 'fulfilled' || !Array.isArray(body.lineItems) || body.lineItems.length === 0) {\n return ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: {\n lineItems:\n status !== 'fulfilled'\n ? 'Only a `fulfilled` update names line items'\n : 'Must be a non-empty array of { lineItemId, quantity }',\n },\n headers: ctx.headers,\n })\n }\n lineItems = (body.lineItems as unknown[]).slice(0, 500).map((entry) => ({\n lineItemId: Number((entry as Record<string, unknown>)?.lineItemId),\n quantity: Number((entry as Record<string, unknown>)?.quantity),\n }))\n }\n const idempotencyKey = request.headers.get('idempotency-key') ?? undefined\n\n // Gate 4: this plugin, on for this site.\n const hostSnap = await hostRef(ctx, hostId).get()\n if (!isHostPluginEnabled(ctx.org, hostSnap.data(), BUNDLE_ID)) {\n return ApiErrors.notFound({\n message: 'No such site',\n headers: ctx.headers,\n })\n }\n\n const outcome = await recordOrderShipment({\n hostId,\n orderId,\n to: status as OrderFulfilmentTarget,\n carrier,\n trackingNumber,\n ...(lineItems ? { lineItems } : {}),\n ...(typeof body.trackingUrl === 'string' ? { trackingUrl: body.trackingUrl } : {}),\n ...(body.notify === false ? { notify: false } : {}),\n ...(idempotencyKey ? { idempotencyKey } : {}),\n })\n if (outcome.outcome === 'invalid_lines') {\n return outcome.problem.problem === 'over_fulfilled'\n ? ApiErrors.conflict({\n message: outcome.message,\n code: 'over_fulfilled',\n headers: ctx.headers,\n })\n : ApiErrors.badRequest({\n message: 'Order failed validation',\n code: 'validation_failed',\n fields: { lineItems: outcome.message },\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'no_such_order') {\n return ApiErrors.notFound({\n message: 'No such order',\n headers: ctx.headers,\n })\n }\n if (outcome.outcome === 'blocked') {\n // A NEW 409 code (`order_transition`), because an integrator has to be\n // able to tell \"the order moved on without me\" apart from every other\n // conflict this API can raise — it is the one a fulfilment poller will\n // actually hit, and the one it must not retry forever.\n return ApiErrors.conflict({\n message: `Orders in \"${outcome.from}\" cannot be marked ${status}`,\n code: 'order_transition',\n headers: ctx.headers,\n })\n }\n // The order object, on both `recorded` and `already` — a retry lands the\n // same state and reads the same 200. Re-read after the write so the body\n // shows the shipment that was just recorded rather than the one before it.\n return apiJson(orderView(await hostRef(ctx, hostId).collection('orders').doc(orderId).get()), {\n headers: ctx.headers,\n })\n}\n\n/**\n * The product writes' gates (AGL-4235), each load-bearing, in `updateOrder`'s\n * order: `products:write` on the credential, the `commerce` PLAN entitlement,\n * this plugin switched on for this site, and — for an app a person connected\n * — that person's \"Edit site content\" on the site, the permission the\n * console's product editor and the native apps' save route ask. The router\n * has already applied the site's lock and the person's membership.\n */\nfunction productWriteRefusal(ctx: ApiV1Context, hostId: string, hostDoc: FirebaseFirestore.DocumentSnapshot): Response | null {\n const denied = requireScope(ctx, 'products:write')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (!isHostPluginEnabled(ctx.org, hostDoc.data(), BUNDLE_ID)) {\n return ApiErrors.notFound({ message: 'No such site', headers: ctx.headers })\n }\n return requireSitePermission(ctx, hostDoc, 'site.edit')\n}\n\nexport async function handleProducts(\n request: Request,\n ctx: ApiV1Context,\n segments: string[],\n url: URL,\n): Promise<Response> {\n const [, hostId, , productId, sub, variantId] = segments\n if (sub !== undefined && (sub !== 'variants' || !variantId || segments.length > 6)) {\n return ApiErrors.notFound({ message: 'Unknown endpoint', headers: ctx.headers })\n }\n const writing =\n (request.method === 'POST' && !productId) ||\n ((request.method === 'PATCH' || request.method === 'DELETE') && productId && !variantId) ||\n (request.method === 'PATCH' && variantId)\n // `products:write` is asked BEFORE `products:read`, as the order writes ask\n // theirs (AGL-900): a key that only writes the catalog holds no read scope.\n if (writing) {\n const hostDoc = ctx.site?.snapshot ?? (await hostRef(ctx, hostId).get())\n const refused = productWriteRefusal(ctx, hostId, hostDoc)\n if (refused) return refused\n const writes = await import('./product-writes')\n if (variantId) return writes.updateProductVariant(request, ctx, hostId, productId, variantId)\n if (!productId) return writes.createProduct(request, ctx, hostId)\n if (request.method === 'PATCH') return writes.updateProduct(request, ctx, hostId, productId)\n return writes.deleteProductOverApi(ctx, hostId, productId)\n }\n const denied = requireScope(ctx, 'products:read')\n if (denied) return denied\n const unentitled = requireCommerce(ctx)\n if (unentitled) return unentitled\n if (request.method !== 'GET' || variantId) {\n return ApiErrors.methodNotAllowed({\n headers: { ...ctx.headers, Allow: variantId ? 'PATCH' : productId ? 'GET, PATCH, DELETE' : 'GET, POST' },\n })\n }\n const collection = hostRef(ctx, hostId).collection('products')\n\n if (productId) {\n const snap = await collection.doc(productId).get()\n // A soft-deleted product is gone as far as a customer is concerned. The\n // console filters `deletedAt` client-side; the API must not hand back a\n // product the merchant deleted just because the document survives.\n if (!snap.exists || snap.get('deletedAt')) {\n return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n }\n return apiJson(productView(snap), { headers: ctx.headers })\n }\n\n let query: FirebaseFirestore.Query = collection\n const status = url.searchParams.get('status')\n if (status) query = query.where('status', '==', status)\n const { docs, nextCursor } = await paginate(query, url)\n const data = docs.filter((doc) => !doc.get('deletedAt')).map(productView)\n return listResponse(data, nextCursor, ctx.headers)\n}\n"],"names":["checkEntitlement","isHostPluginEnabled","ApiErrors","apiJson","listResponse","paginate","readJsonBody","requireScope","requireSitePermission","BUNDLE_ID","recordOrderShipment","orderViewFromData","productView","isUnpaidQuote","requireCommerce","ctx","org","planRequired","message","code","headers","hostRef","hostId","firestore","collection","doc","orderView","id","data","handleOrders","request","segments","url","orderId","method","deniedWrite","unentitledWrite","updateOrder","denied","unentitled","methodNotAllowed","Allow","snap","get","exists","notFound","query","status","searchParams","where","channel","docs","nextCursor","filter","map","order","ORDER_WRITE_TARGETS","ORDER_WRITABLE_KEYS","ORDER_WRITE_REFUSED","cancelled","refunded","body","unknown","Object","keys","key","includes","length","badRequest","fields","fromEntries","String","refusal","join","carrier","slice","trackingNumber","lineItems","undefined","Array","isArray","entry","lineItemId","Number","quantity","idempotencyKey","hostSnap","outcome","to","trackingUrl","notify","problem","conflict","from","productWriteRefusal","hostDoc","handleProducts","productId","sub","variantId","writing","site","snapshot","refused","writes","updateProductVariant","createProduct","updateProduct","deleteProductOverApi"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,mBAAmB,QAAQ,sBAAqB;AAC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C,SAASyC,OAAOd;IACnD,MAAMJ,OAAOuB,KAAKE,MAAM,CAAC,CAAC5B,MAAQ,CAACA,IAAIkB,GAAG,CAAC,cAAcW,GAAG,CAAC1C;IAC7D,OAAOR,aAAawB,MAAMwB,YAAYrC,IAAIK,OAAO;AACnD"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* A product as the customer API publishes it (AGL-1928): the reads and, since
|
|
19
|
+
* AGL-4235, the writes answer this one shape.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* Price and stock live on VARIANTS, never on the product — a product-level
|
|
23
|
+
* `inventory` exists only as a denormalized sum the console rewrites on every
|
|
24
|
+
* decrement, and a product-level `priceUsd` is the legacy single-variant
|
|
25
|
+
* shape. Publishing either as the product's price would be wrong the moment a
|
|
26
|
+
* product has two variants, so the variant array is the contract and the
|
|
27
|
+
* product carries only the roll-up, clearly named.
|
|
28
|
+
*
|
|
29
|
+
* `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.
|
|
30
|
+
* Collapsing them (the `?? 0` an integrator writes on the first day) turns
|
|
31
|
+
* every untracked product into an out-of-stock one, so the distinction is
|
|
32
|
+
* carried through verbatim rather than defaulted.
|
|
33
|
+
*/
|
|
34
|
+
export declare function variantView(variant: Record<string, unknown>): {
|
|
35
|
+
id: unknown;
|
|
36
|
+
sku: unknown;
|
|
37
|
+
barcode: unknown;
|
|
38
|
+
options: unknown;
|
|
39
|
+
priceUsd: number;
|
|
40
|
+
compareAtPriceUsd: number;
|
|
41
|
+
weightGrams: number;
|
|
42
|
+
inventory: number;
|
|
43
|
+
inventoryTracked: boolean;
|
|
44
|
+
};
|
|
45
|
+
export declare function productView(doc: FirebaseFirestore.DocumentSnapshot): {
|
|
46
|
+
id: string;
|
|
47
|
+
object: string;
|
|
48
|
+
name: any;
|
|
49
|
+
slug: any;
|
|
50
|
+
description: any;
|
|
51
|
+
type: any;
|
|
52
|
+
status: any;
|
|
53
|
+
tags: any;
|
|
54
|
+
categoryIds: any;
|
|
55
|
+
mediaUrls: any;
|
|
56
|
+
options: any;
|
|
57
|
+
variants: {
|
|
58
|
+
id: unknown;
|
|
59
|
+
sku: unknown;
|
|
60
|
+
barcode: unknown;
|
|
61
|
+
options: unknown;
|
|
62
|
+
priceUsd: number;
|
|
63
|
+
compareAtPriceUsd: number;
|
|
64
|
+
weightGrams: number;
|
|
65
|
+
inventory: number;
|
|
66
|
+
inventoryTracked: boolean;
|
|
67
|
+
}[];
|
|
68
|
+
seo: {
|
|
69
|
+
title: any;
|
|
70
|
+
description: any;
|
|
71
|
+
};
|
|
72
|
+
inventory: number;
|
|
73
|
+
subscription: unknown;
|
|
74
|
+
created: string;
|
|
75
|
+
updated: string;
|
|
76
|
+
};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { serialize } from "@aglyn/tenant-data-admin/server/api-v1-kit";
|
|
17
|
+
/**
|
|
18
|
+
* A product as the customer API publishes it (AGL-1928): the reads and, since
|
|
19
|
+
* AGL-4235, the writes answer this one shape.
|
|
20
|
+
*/ /**
|
|
21
|
+
* Price and stock live on VARIANTS, never on the product — a product-level
|
|
22
|
+
* `inventory` exists only as a denormalized sum the console rewrites on every
|
|
23
|
+
* decrement, and a product-level `priceUsd` is the legacy single-variant
|
|
24
|
+
* shape. Publishing either as the product's price would be wrong the moment a
|
|
25
|
+
* product has two variants, so the variant array is the contract and the
|
|
26
|
+
* product carries only the roll-up, clearly named.
|
|
27
|
+
*
|
|
28
|
+
* `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.
|
|
29
|
+
* Collapsing them (the `?? 0` an integrator writes on the first day) turns
|
|
30
|
+
* every untracked product into an out-of-stock one, so the distinction is
|
|
31
|
+
* carried through verbatim rather than defaulted.
|
|
32
|
+
*/ export function variantView(variant) {
|
|
33
|
+
var _variant_id, _variant_sku, _variant_barcode, _variant_options;
|
|
34
|
+
const inventory = variant.inventory;
|
|
35
|
+
return {
|
|
36
|
+
id: (_variant_id = variant.id) != null ? _variant_id : null,
|
|
37
|
+
sku: (_variant_sku = variant.sku) != null ? _variant_sku : null,
|
|
38
|
+
barcode: (_variant_barcode = variant.barcode) != null ? _variant_barcode : null,
|
|
39
|
+
options: (_variant_options = variant.options) != null ? _variant_options : {},
|
|
40
|
+
priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,
|
|
41
|
+
compareAtPriceUsd: typeof variant.compareAtPriceUsd === 'number' ? variant.compareAtPriceUsd : null,
|
|
42
|
+
weightGrams: typeof variant.weightGrams === 'number' ? variant.weightGrams : null,
|
|
43
|
+
inventory: typeof inventory === 'number' ? inventory : null,
|
|
44
|
+
inventoryTracked: typeof inventory === 'number'
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export function productView(doc) {
|
|
48
|
+
var _doc_data, _data_name, _data_slug, _data_description, _data_type, _data_status, _data_tags, _data_categoryIds, _data_mediaUrls, _data_options, _serialize;
|
|
49
|
+
var _data_seo, _data_seo1;
|
|
50
|
+
const data = (_doc_data = doc.data()) != null ? _doc_data : {};
|
|
51
|
+
const variants = Array.isArray(data.variants) ? data.variants : [];
|
|
52
|
+
const tracked = variants.filter((v)=>typeof v.inventory === 'number');
|
|
53
|
+
return {
|
|
54
|
+
id: doc.id,
|
|
55
|
+
object: 'product',
|
|
56
|
+
name: (_data_name = data.name) != null ? _data_name : null,
|
|
57
|
+
slug: (_data_slug = data.slug) != null ? _data_slug : null,
|
|
58
|
+
description: (_data_description = data.description) != null ? _data_description : null,
|
|
59
|
+
type: (_data_type = data.type) != null ? _data_type : null,
|
|
60
|
+
status: (_data_status = data.status) != null ? _data_status : null,
|
|
61
|
+
tags: (_data_tags = data.tags) != null ? _data_tags : [],
|
|
62
|
+
categoryIds: (_data_categoryIds = data.categoryIds) != null ? _data_categoryIds : [],
|
|
63
|
+
mediaUrls: (_data_mediaUrls = data.mediaUrls) != null ? _data_mediaUrls : [],
|
|
64
|
+
options: (_data_options = data.options) != null ? _data_options : [],
|
|
65
|
+
variants: variants.map(variantView),
|
|
66
|
+
// The product's own search listing (AGL-4235): what its page's title and
|
|
67
|
+
// description say to a search engine, `null` where the page falls back
|
|
68
|
+
// to the product's name and description.
|
|
69
|
+
seo: {
|
|
70
|
+
title: typeof ((_data_seo = data.seo) == null ? void 0 : _data_seo.title) === 'string' && data.seo.title ? data.seo.title : null,
|
|
71
|
+
description: typeof ((_data_seo1 = data.seo) == null ? void 0 : _data_seo1.description) === 'string' && data.seo.description ? data.seo.description : null
|
|
72
|
+
},
|
|
73
|
+
// The sum across TRACKED variants only, and `null` when none of them is
|
|
74
|
+
// tracked — so an untracked catalogue reads as "we don't count this"
|
|
75
|
+
// rather than as a store with nothing left to sell.
|
|
76
|
+
inventory: tracked.length ? tracked.reduce((sum, v)=>{
|
|
77
|
+
var _v_inventory;
|
|
78
|
+
return sum + Number((_v_inventory = v.inventory) != null ? _v_inventory : 0);
|
|
79
|
+
}, 0) : null,
|
|
80
|
+
subscription: (_serialize = serialize(data.subscription)) != null ? _serialize : null,
|
|
81
|
+
created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,
|
|
82
|
+
updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
//# sourceMappingURL=product-view.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/product-view.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 { serialize } from '@aglyn/tenant-data-admin/server/api-v1-kit'\n\n/**\n * A product as the customer API publishes it (AGL-1928): the reads and, since\n * AGL-4235, the writes answer this one shape.\n */\n\n/**\n * Price and stock live on VARIANTS, never on the product — a product-level\n * `inventory` exists only as a denormalized sum the console rewrites on every\n * decrement, and a product-level `priceUsd` is the legacy single-variant\n * shape. Publishing either as the product's price would be wrong the moment a\n * product has two variants, so the variant array is the contract and the\n * product carries only the roll-up, clearly named.\n *\n * `inventory: null` on a variant means UNTRACKED and `0` means SOLD OUT.\n * Collapsing them (the `?? 0` an integrator writes on the first day) turns\n * every untracked product into an out-of-stock one, so the distinction is\n * carried through verbatim rather than defaulted.\n */\nexport function variantView(variant: Record<string, unknown>) {\n const inventory = variant.inventory\n return {\n id: variant.id ?? null,\n sku: variant.sku ?? null,\n barcode: variant.barcode ?? null,\n options: variant.options ?? {},\n priceUsd: typeof variant.priceUsd === 'number' ? variant.priceUsd : null,\n compareAtPriceUsd:\n typeof variant.compareAtPriceUsd === 'number'\n ? variant.compareAtPriceUsd\n : null,\n weightGrams:\n typeof variant.weightGrams === 'number' ? variant.weightGrams : null,\n inventory: typeof inventory === 'number' ? inventory : null,\n inventoryTracked: typeof inventory === 'number',\n }\n}\n\nexport function productView(doc: FirebaseFirestore.DocumentSnapshot) {\n const data = doc.data() ?? {}\n const variants = Array.isArray(data.variants)\n ? (data.variants as Array<Record<string, unknown>>)\n : []\n const tracked = variants.filter((v) => typeof v.inventory === 'number')\n return {\n id: doc.id,\n object: 'product',\n name: data.name ?? null,\n slug: data.slug ?? null,\n description: data.description ?? null,\n type: data.type ?? null,\n status: data.status ?? null,\n tags: data.tags ?? [],\n categoryIds: data.categoryIds ?? [],\n mediaUrls: data.mediaUrls ?? [],\n options: data.options ?? [],\n variants: variants.map(variantView),\n // The product's own search listing (AGL-4235): what its page's title and\n // description say to a search engine, `null` where the page falls back\n // to the product's name and description.\n seo: {\n title: typeof data.seo?.title === 'string' && data.seo.title ? data.seo.title : null,\n description:\n typeof data.seo?.description === 'string' && data.seo.description ? data.seo.description : null,\n },\n // The sum across TRACKED variants only, and `null` when none of them is\n // tracked — so an untracked catalogue reads as \"we don't count this\"\n // rather than as a store with nothing left to sell.\n inventory: tracked.length\n ? tracked.reduce((sum, v) => sum + Number(v.inventory ?? 0), 0)\n : null,\n subscription: serialize(data.subscription) ?? null,\n created: data.createdAtMs ? new Date(Number(data.createdAtMs)).toISOString() : null,\n updated: data.updatedAtMs ? new Date(Number(data.updatedAtMs)).toISOString() : null,\n }\n}\n\n"],"names":["serialize","variantView","variant","inventory","id","sku","barcode","options","priceUsd","compareAtPriceUsd","weightGrams","inventoryTracked","productView","doc","data","variants","Array","isArray","tracked","filter","v","object","name","slug","description","type","status","tags","categoryIds","mediaUrls","map","seo","title","length","reduce","sum","Number","subscription","created","createdAtMs","Date","toISOString","updated","updatedAtMs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,SAAS,QAAQ,6CAA4C;AAEtE;;;CAGC,GAED;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,YAAYC,OAAgC;QAGpDA,aACCA,cACIA,kBACAA;IALX,MAAMC,YAAYD,QAAQC,SAAS;IACnC,OAAO;QACLC,EAAE,GAAEF,cAAAA,QAAQE,EAAE,YAAVF,cAAc;QAClBG,GAAG,GAAEH,eAAAA,QAAQG,GAAG,YAAXH,eAAe;QACpBI,OAAO,GAAEJ,mBAAAA,QAAQI,OAAO,YAAfJ,mBAAmB;QAC5BK,OAAO,GAAEL,mBAAAA,QAAQK,OAAO,YAAfL,mBAAmB,CAAC;QAC7BM,UAAU,OAAON,QAAQM,QAAQ,KAAK,WAAWN,QAAQM,QAAQ,GAAG;QACpEC,mBACE,OAAOP,QAAQO,iBAAiB,KAAK,WACjCP,QAAQO,iBAAiB,GACzB;QACNC,aACE,OAAOR,QAAQQ,WAAW,KAAK,WAAWR,QAAQQ,WAAW,GAAG;QAClEP,WAAW,OAAOA,cAAc,WAAWA,YAAY;QACvDQ,kBAAkB,OAAOR,cAAc;IACzC;AACF;AAEA,OAAO,SAASS,YAAYC,GAAuC;QACpDA,WAQLC,YACAA,YACOA,mBACPA,YACEA,cACFA,YACOA,mBACFA,iBACFA,eAgBKd;QAVEc,WAELA;IAxBb,MAAMA,QAAOD,YAAAA,IAAIC,IAAI,cAARD,YAAc,CAAC;IAC5B,MAAME,WAAWC,MAAMC,OAAO,CAACH,KAAKC,QAAQ,IACvCD,KAAKC,QAAQ,GACd,EAAE;IACN,MAAMG,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