@aglyn/plugins-commerce 1.31.0 → 1.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/package.json +13 -13
- package/src/lib/components/cart.js +35 -15
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/console/currencies-card.component.d.ts +21 -0
- package/src/lib/components/console/currencies-card.component.js +408 -0
- package/src/lib/components/console/currencies-card.component.js.map +1 -0
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +42 -1
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
- package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
- package/src/lib/components/console/reservations-card.component.js +32 -15
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +100 -1
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +1 -1
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/use-currency-setup.d.ts +20 -0
- package/src/lib/components/console/use-currency-setup.js +61 -0
- package/src/lib/components/console/use-currency-setup.js.map +1 -0
- package/src/lib/components/currency-selector.d.ts +36 -0
- package/src/lib/components/currency-selector.js +157 -0
- package/src/lib/components/currency-selector.js.map +1 -0
- package/src/lib/components/product-add-ons.d.ts +9 -1
- package/src/lib/components/product-add-ons.js +8 -4
- package/src/lib/components/product-add-ons.js.map +1 -1
- package/src/lib/components/product-choice-cards.d.ts +13 -1
- package/src/lib/components/product-choice-cards.js +5 -4
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/components/product-detail.d.ts +8 -0
- package/src/lib/components/product-detail.js +38 -11
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +2 -0
- package/src/lib/components/product-grid.js +22 -9
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/related-products.js +6 -2
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/shopper-currency.d.ts +108 -0
- package/src/lib/components/shopper-currency.js +262 -0
- package/src/lib/components/shopper-currency.js.map +1 -0
- package/src/lib/components/wishlist.js +7 -1
- package/src/lib/components/wishlist.js.map +1 -1
- package/src/lib/declarations.server.js +39 -0
- package/src/lib/declarations.server.js.map +1 -1
- package/src/lib/model/commerce-currency-setup.d.ts +79 -0
- package/src/lib/model/commerce-currency-setup.js +124 -0
- package/src/lib/model/commerce-currency-setup.js.map +1 -0
- package/src/lib/model/commerce-currency.d.ts +215 -0
- package/src/lib/model/commerce-currency.js +511 -0
- package/src/lib/model/commerce-currency.js.map +1 -0
- package/src/lib/model/commerce-orders.d.ts +17 -0
- package/src/lib/model/commerce-orders.js +10 -5
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-record-routes.js +26 -1
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce-reservations.d.ts +6 -0
- package/src/lib/model/commerce-reservations.js.map +1 -1
- package/src/lib/model/commerce-shipping.d.ts +22 -1
- package/src/lib/model/commerce-shipping.js +31 -2
- package/src/lib/model/commerce-shipping.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +2 -0
- package/src/lib/model/index.js +2 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/order-figures.js +9 -2
- package/src/lib/model/order-figures.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/server/billing-webhook.js +37 -24
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cart-checkout.js +67 -11
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.d.ts +12 -0
- package/src/lib/server/cart.js +50 -4
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.d.ts +5 -0
- package/src/lib/server/catalog.js +7 -0
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout.js +48 -12
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/currency.d.ts +93 -0
- package/src/lib/server/currency.js +182 -0
- package/src/lib/server/currency.js.map +1 -0
- package/src/lib/server/order-notifications.js +4 -2
- package/src/lib/server/order-notifications.js.map +1 -1
- package/src/lib/server/product.d.ts +9 -0
- package/src/lib/server/product.js +12 -0
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/refund.js +3 -3
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/site-chat-tools.d.ts +22 -0
- package/src/lib/server/site-chat-tools.js +369 -0
- package/src/lib/server/site-chat-tools.js.map +1 -0
- package/src/lib/server/site-chat-visitor.d.ts +24 -0
- package/src/lib/server/site-chat-visitor.js +39 -0
- package/src/lib/server/site-chat-visitor.js.map +1 -0
- package/src/lib/server/site-offers.d.ts +31 -0
- package/src/lib/server/site-offers.js +91 -0
- package/src/lib/server/site-offers.js.map +1 -0
- package/src/lib/server/stays-site-search.d.ts +20 -0
- package/src/lib/server/stays-site-search.js +78 -0
- package/src/lib/server/stays-site-search.js.map +1 -0
- package/src/lib/server.js +20 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site-chat-tool-definitions.d.ts +26 -0
- package/src/lib/site-chat-tool-definitions.js +141 -0
- package/src/lib/site-chat-tool-definitions.js.map +1 -0
- package/src/lib/site.js +8 -0
- package/src/lib/site.js.map +1 -1
- package/src/lib/subprocessors.js +7 -0
- package/src/lib/subprocessors.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-record-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\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 * http://www.apache.org/licenses/LICENSE-2.0\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\n\nimport { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport {\n registerPluginRecordRoute,\n type PluginRecordRouteContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport { registerSitePathKind } from '@aglyn/aglyn/plugin-manager/site-path-kinds'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { COMMERCE_SETTINGS_PAGE_ZONES } from '../components/commerce-console-sections'\n\n/**\n * Where a product and an order are read, published for every other surface\n * (AGL-3080).\n *\n * A surface elsewhere — the AI plugin's job drawer opening a product it\n * drafted, a contact's timeline opening the order it names, a person's page\n * listing their orders — asks the record-route registry for `product` or\n * `order` rather than spelling this plugin's console path, and gets `null`\n * (text instead of a link) where this plugin is not loaded.\n *\n * Both are a site's, so only a site has an address. The catalog has no page\n * per product — a product opens in the hub's editor — so the record answers\n * the Catalog with {@link PRODUCTS_PRODUCT_PARAM}, which opens that product's\n * editor on arrival. An order opens as a dialog over the\n * Orders list, which reads {@link ORDERS_ORDER_PARAM} on arrival; the list\n * narrowed to one buyer reads {@link ORDERS_CUSTOMER_PARAM}.\n */\n\n/** The nav slug the shell resolves the catalog by. */\nexport const PRODUCTS_SLUG = 'products'\n\n/** The Catalog section of the products hub, where the product editor opens. */\nexport const PRODUCTS_CATALOG_SECTION = 'catalog'\n\n/** The query key the Catalog opens one product's editor by. */\nexport const PRODUCTS_PRODUCT_PARAM = 'product'\n\n/**\n * One product's editor, as a path under the site's console dashboard: the\n * form the admin edit bar takes a record's address in (it prefixes the\n * console origin and org path itself), so the tenant server can link a\n * product page to its product without building console routes.\n */\nexport function productEditPath(productId: string): string {\n return `/${PRODUCTS_SLUG}/${PRODUCTS_CATALOG_SECTION}?${new URLSearchParams({\n [PRODUCTS_PRODUCT_PARAM]: productId,\n }).toString()}`\n}\n\n/** The query key the Orders list opens one order's dialog by. */\nexport const ORDERS_ORDER_PARAM = 'order'\n\n/**\n * The query key the Orders list narrows to one buyer by — the same word the\n * CRM's contacts list opens a person by, so a reader who edits one URL into\n * the other is not surprised.\n */\nexport const ORDERS_CUSTOMER_PARAM = 'email'\n\nfunction catalog(context: PluginRecordRouteContext): string | null {\n return context.host\n ? buildRoute(Route.HOST_PLUGIN, {\n orgSlug: context.orgSlug,\n host: context.host,\n pluginSlug: PRODUCTS_SLUG,\n })\n : null\n}\n\nfunction orders(context: PluginRecordRouteContext, key?: string, value?: string): string | null {\n const list = catalog(context)\n if (!list) return null\n return key && value\n ? `${list}/orders?${new URLSearchParams({ [key]: value }).toString()}`\n : `${list}/orders`\n}\n\n/** One product's address: the Catalog, opening that product's editor. */\nfunction product(context: PluginRecordRouteContext, id: string): string | null {\n const list = catalog(context)\n if (!list || !id) return list\n return `${list}/${PRODUCTS_CATALOG_SECTION}?${new URLSearchParams({\n [PRODUCTS_PRODUCT_PARAM]: id,\n }).toString()}`\n}\n\n/**\n * One order's address: the Orders list, opening that order's dialog. The\n * same answer the `order` record route gives, for a caller that holds the\n * id but not the registry (the one-box search, AGL-3943).\n */\nexport function orderRecordHref(context: PluginRecordRouteContext, id: string): string | null {\n return id ? orders(context, ORDERS_ORDER_PARAM, id) : null\n}\n\n/**\n * The store's settings — payments (Stripe), shipping, tax and returns — under\n * `store-settings` (AGL-3676): where an AI-built store's \"Finish your store\"\n * list sends its owner, without spelling this plugin's console path.\n *\n * A page each since AGL-3713: the list is Payments, the first of them, and a\n * record is the settings page of that id (`shipping`, `taxes` …). An id that\n * is not a settings page opens the list rather than a 404.\n */\nfunction settings(context: PluginRecordRouteContext, page?: string): string | null {\n const list = catalog(context)\n if (!list) return null\n const id = page && Object.hasOwn(COMMERCE_SETTINGS_PAGE_ZONES, page) ? page : 'payments'\n return `${list}/${id}`\n}\n\n/**\n * Called from the console registrar. The owner is named rather than read off\n * the loader's marker, so the route registers the same way under a spec that\n * calls the registrar directly.\n */\nexport function registerCommerceRecordRoutes(): void {\n registerPluginRecordRoute(\n 'product',\n { list: catalog, record: product },\n { pluginId: BUNDLE_ID },\n )\n registerPluginRecordRoute(\n 'store-settings',\n { list: (context) => settings(context), record: settings },\n { pluginId: BUNDLE_ID },\n )\n registerPluginRecordRoute(\n 'order',\n {\n list: (context) => orders(context),\n record: (context, id) => orders(context, ORDERS_ORDER_PARAM, id),\n byEmail: (context, email) => orders(context, ORDERS_CUSTOMER_PARAM, email),\n },\n { pluginId: BUNDLE_ID },\n )\n /*\n * The addresses this plugin composes, for the site's Analytics page\n * (AGL-4253): `/products/{slug}` and `/collections/{slug}` each render\n * through ONE template screen, so without these every product counted as\n * one `cr-product` row. Declared, so the page names each visited product\n * and store collection itself without naming this plugin.\n */\n registerSitePathKind(\n {\n segment: 'products',\n groupLabel: 'Products',\n noun: 'product',\n collection: 'products',\n editHref: product,\n },\n { pluginId: BUNDLE_ID },\n )\n registerSitePathKind(\n {\n segment: 'collections',\n groupLabel: 'Collections',\n noun: 'collection',\n collection: 'collections',\n // Content collections share the collection and a slug is unique only\n // within a kind (AGL-954), as the storefront resolver reads it.\n accepts: (data) => hostCollectionKind(data) === 'catalog',\n // Store collections are organized on the catalog page; there is no\n // page of one collection's own to open.\n editHref: (context) => catalog(context),\n },\n { pluginId: BUNDLE_ID },\n )\n}\n"],"names":["buildRoute","Route","registerPluginRecordRoute","hostCollectionKind","registerSitePathKind","BUNDLE_ID","COMMERCE_SETTINGS_PAGE_ZONES","PRODUCTS_SLUG","PRODUCTS_CATALOG_SECTION","PRODUCTS_PRODUCT_PARAM","productEditPath","productId","URLSearchParams","toString","ORDERS_ORDER_PARAM","ORDERS_CUSTOMER_PARAM","catalog","context","host","HOST_PLUGIN","orgSlug","pluginSlug","orders","key","value","list","product","id","orderRecordHref","settings","page","Object","hasOwn","registerCommerceRecordRoutes","record","pluginId","byEmail","email","segment","groupLabel","noun","collection","editHref","accepts","data"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAGD,SAASA,UAAU,EAAEC,KAAK,QAAQ,wCAAuC;AACzE,SACEC,yBAAyB,QAEpB,mDAAkD;AACzD,SAASC,kBAAkB,QAAQ,yCAAwC;AAC3E,SAASC,oBAAoB,QAAQ,8CAA6C;AAClF,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,4BAA4B,QAAQ,6CAAyC;AAEtF;;;;;;;;;;;;;;;;CAgBC,GAED,oDAAoD,GACpD,OAAO,MAAMC,gBAAgB,WAAU;AAEvC,6EAA6E,GAC7E,OAAO,MAAMC,2BAA2B,UAAS;AAEjD,6DAA6D,GAC7D,OAAO,MAAMC,yBAAyB,UAAS;AAE/C;;;;;CAKC,GACD,OAAO,SAASC,gBAAgBC,SAAiB;IAC/C,OAAO,CAAC,CAAC,EAAEJ,cAAc,CAAC,EAAEC,yBAAyB,CAAC,EAAE,IAAII,gBAAgB;QAC1E,CAACH,uBAAuB,EAAEE;IAC5B,GAAGE,QAAQ,IAAI;AACjB;AAEA,+DAA+D,GAC/D,OAAO,MAAMC,qBAAqB,QAAO;AAEzC;;;;CAIC,GACD,OAAO,MAAMC,wBAAwB,QAAO;AAE5C,SAASC,QAAQC,OAAiC;IAChD,OAAOA,QAAQC,IAAI,GACflB,WAAWC,MAAMkB,WAAW,EAAE;QAC5BC,SAASH,QAAQG,OAAO;QACxBF,MAAMD,QAAQC,IAAI;QAClBG,YAAYd;IACd,KACA;AACN;AAEA,SAASe,OAAOL,OAAiC,EAAEM,GAAY,EAAEC,KA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sB;IACtE,GACA;QAAEF,UAAU9B;IAAU;IAExB;;;;;;GAMC,GACDD,qBACE;QACEkC,SAAS;QACTC,YAAY;QACZC,MAAM;QACNC,YAAY;QACZC,UAAUhB;IACZ,GACA;QAAES,UAAU9B;IAAU;IAExBD,qBACE;QACEkC,SAAS;QACTC,YAAY;QACZC,MAAM;QACNC,YAAY;QACZ,qEAAqE;QACrE,gEAAgE;QAChEE,SAAS,CAACC,OAASzC,mBAAmByC,UAAU;QAChD,mEAAmE;QACnE,wCAAwC;QACxCF,UAAU,CAACzB,UAAYD,QAAQC;IACjC,GACA;QAAEkB,UAAU9B;IAAU;AAE1B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-record-routes.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\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 * http://www.apache.org/licenses/LICENSE-2.0\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\n\nimport { buildRoute, Route } from '@aglyn/aglyn/app-utils/console-routes'\nimport {\n registerPluginRecordRoute,\n type PluginRecordRouteContext,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-routes'\nimport { hostCollectionKind } from '@aglyn/aglyn/app-utils/collection-kind'\nimport {\n registerSiteBuiltInPage,\n registerSitePathKind,\n} from '@aglyn/aglyn/plugin-manager/site-path-kinds'\nimport { QUOTE_PAGE_PATH } from '../constants/quote-page'\nimport { RETURN_REQUEST_PATH } from '../constants/return-request'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { COMMERCE_SETTINGS_PAGE_ZONES } from '../components/commerce-console-sections'\n\n/**\n * Where a product and an order are read, published for every other surface\n * (AGL-3080).\n *\n * A surface elsewhere — the AI plugin's job drawer opening a product it\n * drafted, a contact's timeline opening the order it names, a person's page\n * listing their orders — asks the record-route registry for `product` or\n * `order` rather than spelling this plugin's console path, and gets `null`\n * (text instead of a link) where this plugin is not loaded.\n *\n * Both are a site's, so only a site has an address. The catalog has no page\n * per product — a product opens in the hub's editor — so the record answers\n * the Catalog with {@link PRODUCTS_PRODUCT_PARAM}, which opens that product's\n * editor on arrival. An order opens as a dialog over the\n * Orders list, which reads {@link ORDERS_ORDER_PARAM} on arrival; the list\n * narrowed to one buyer reads {@link ORDERS_CUSTOMER_PARAM}.\n */\n\n/** The nav slug the shell resolves the catalog by. */\nexport const PRODUCTS_SLUG = 'products'\n\n/** The Catalog section of the products hub, where the product editor opens. */\nexport const PRODUCTS_CATALOG_SECTION = 'catalog'\n\n/** The query key the Catalog opens one product's editor by. */\nexport const PRODUCTS_PRODUCT_PARAM = 'product'\n\n/**\n * One product's editor, as a path under the site's console dashboard: the\n * form the admin edit bar takes a record's address in (it prefixes the\n * console origin and org path itself), so the tenant server can link a\n * product page to its product without building console routes.\n */\nexport function productEditPath(productId: string): string {\n return `/${PRODUCTS_SLUG}/${PRODUCTS_CATALOG_SECTION}?${new URLSearchParams({\n [PRODUCTS_PRODUCT_PARAM]: productId,\n }).toString()}`\n}\n\n/** The query key the Orders list opens one order's dialog by. */\nexport const ORDERS_ORDER_PARAM = 'order'\n\n/**\n * The query key the Orders list narrows to one buyer by — the same word the\n * CRM's contacts list opens a person by, so a reader who edits one URL into\n * the other is not surprised.\n */\nexport const ORDERS_CUSTOMER_PARAM = 'email'\n\nfunction catalog(context: PluginRecordRouteContext): string | null {\n return context.host\n ? buildRoute(Route.HOST_PLUGIN, {\n orgSlug: context.orgSlug,\n host: context.host,\n pluginSlug: PRODUCTS_SLUG,\n })\n : null\n}\n\nfunction orders(context: PluginRecordRouteContext, key?: string, value?: string): string | null {\n const list = catalog(context)\n if (!list) return null\n return key && value\n ? `${list}/orders?${new URLSearchParams({ [key]: value }).toString()}`\n : `${list}/orders`\n}\n\n/** One product's address: the Catalog, opening that product's editor. */\nfunction product(context: PluginRecordRouteContext, id: string): string | null {\n const list = catalog(context)\n if (!list || !id) return list\n return `${list}/${PRODUCTS_CATALOG_SECTION}?${new URLSearchParams({\n [PRODUCTS_PRODUCT_PARAM]: id,\n }).toString()}`\n}\n\n/**\n * One order's address: the Orders list, opening that order's dialog. The\n * same answer the `order` record route gives, for a caller that holds the\n * id but not the registry (the one-box search, AGL-3943).\n */\nexport function orderRecordHref(context: PluginRecordRouteContext, id: string): string | null {\n return id ? orders(context, ORDERS_ORDER_PARAM, id) : null\n}\n\n/**\n * The store's settings — payments (Stripe), shipping, tax and returns — under\n * `store-settings` (AGL-3676): where an AI-built store's \"Finish your store\"\n * list sends its owner, without spelling this plugin's console path.\n *\n * A page each since AGL-3713: the list is Payments, the first of them, and a\n * record is the settings page of that id (`shipping`, `taxes` …). An id that\n * is not a settings page opens the list rather than a 404.\n */\nfunction settings(context: PluginRecordRouteContext, page?: string): string | null {\n const list = catalog(context)\n if (!list) return null\n const id = page && Object.hasOwn(COMMERCE_SETTINGS_PAGE_ZONES, page) ? page : 'payments'\n return `${list}/${id}`\n}\n\n/**\n * Called from the console registrar. The owner is named rather than read off\n * the loader's marker, so the route registers the same way under a spec that\n * calls the registrar directly.\n */\nexport function registerCommerceRecordRoutes(): void {\n registerPluginRecordRoute(\n 'product',\n { list: catalog, record: product },\n { pluginId: BUNDLE_ID },\n )\n registerPluginRecordRoute(\n 'store-settings',\n { list: (context) => settings(context), record: settings },\n { pluginId: BUNDLE_ID },\n )\n registerPluginRecordRoute(\n 'order',\n {\n list: (context) => orders(context),\n record: (context, id) => orders(context, ORDERS_ORDER_PARAM, id),\n byEmail: (context, email) => orders(context, ORDERS_CUSTOMER_PARAM, email),\n },\n { pluginId: BUNDLE_ID },\n )\n /*\n * The addresses this plugin composes, for the site's Analytics page\n * (AGL-4253): `/products/{slug}` and `/collections/{slug}` each render\n * through ONE template screen, so without these every product counted as\n * one `cr-product` row. Declared, so the page names each visited product\n * and store collection itself without naming this plugin.\n */\n registerSitePathKind(\n {\n segment: 'products',\n groupLabel: 'Products',\n noun: 'product',\n collection: 'products',\n editHref: product,\n },\n { pluginId: BUNDLE_ID },\n )\n registerSitePathKind(\n {\n segment: 'collections',\n groupLabel: 'Collections',\n noun: 'collection',\n collection: 'collections',\n // Content collections share the collection and a slug is unique only\n // within a kind (AGL-954), as the storefront resolver reads it.\n accepts: (data) => hostCollectionKind(data) === 'catalog',\n // Store collections are organized on the catalog page; there is no\n // page of one collection's own to open.\n editHref: (context) => catalog(context),\n },\n { pluginId: BUNDLE_ID },\n )\n /*\n * The fixed pages the storefront resolver serves (AGL-4253), so Analytics\n * names a visit there instead of filing it under \"Other addresses\". The\n * order status address is `ORDER_STATUS_PATH`, which lives with its server\n * token code; spelled here so the console bundle does not pull that in.\n */\n registerSiteBuiltInPage({ path: 'order-status', title: 'Order status' }, { pluginId: BUNDLE_ID })\n registerSiteBuiltInPage({ path: RETURN_REQUEST_PATH, title: 'Start a return' }, { pluginId: BUNDLE_ID })\n registerSiteBuiltInPage({ path: QUOTE_PAGE_PATH, title: 'Pay a quote' }, { pluginId: BUNDLE_ID })\n}\n"],"names":["buildRoute","Route","registerPluginRecordRoute","hostCollectionKind","registerSiteBuiltInPage","registerSitePathKind","QUOTE_PAGE_PATH","RETURN_REQUEST_PATH","BUNDLE_ID","COMMERCE_SETTINGS_PAGE_ZONES","PRODUCTS_SLUG","PRODUCTS_CATALOG_SECTION","PRODUCTS_PRODUCT_PARAM","productEditPath","productId","URLSearchParams","toString","ORDERS_ORDER_PARAM","ORDERS_CUSTOMER_PARAM","catalog","context","host","HOST_PLUGIN","orgSlug","pluginSlug","orders","key","value","list","product","id","orderRecordHref","settings","page","Object","hasOwn","registerCommerceRecordRoutes","record","pluginId","byEmail","email","segment","groupLabel","noun","collection","editHref","accepts","data","path","title"],"mappings":"AAAA;;;;;;;;;;;;CAYC,GAGD,SAASA,UAAU,EAAEC,K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EAAgE;QAChEE,SAAS,CAACC,OAAS5C,mBAAmB4C,UAAU;QAChD,mEAAmE;QACnE,wCAAwC;QACxCF,UAAU,CAACzB,UAAYD,QAAQC;IACjC,GACA;QAAEkB,UAAU9B;IAAU;IAExB;;;;;GAKC,GACDJ,wBAAwB;QAAE4C,MAAM;QAAgBC,OAAO;IAAe,GAAG;QAAEX,UAAU9B;IAAU;IAC/FJ,wBAAwB;QAAE4C,MAAMzC;QAAqB0C,OAAO;IAAiB,GAAG;QAAEX,UAAU9B;IAAU;IACtGJ,wBAAwB;QAAE4C,MAAM1C;QAAiB2C,OAAO;IAAc,GAAG;QAAEX,UAAU9B;IAAU;AACjG"}
|
|
@@ -72,6 +72,12 @@ export interface HostResource {
|
|
|
72
72
|
checkInPerGuest?: boolean;
|
|
73
73
|
photoUrls?: string[];
|
|
74
74
|
amenities?: string[];
|
|
75
|
+
/**
|
|
76
|
+
* The page on the site that holds this resource's booking widget
|
|
77
|
+
* (AGL-4252), site-relative (`/cabins/lakeside`): where a site search
|
|
78
|
+
* result for the stay opens. Absent, the stay is not a search result.
|
|
79
|
+
*/
|
|
80
|
+
pagePath?: string;
|
|
75
81
|
nightlyRateUsd: number;
|
|
76
82
|
/** Friday/Saturday nights multiply by this (default 1). */
|
|
77
83
|
weekendMultiplier?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-reservations.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\n/**\n * Reservations v1 (AGL-304): bookable units (cabins) with date-range\n * stays, seasonal pricing, deposits, and cancellation windows —\n * extending the appointment-slot bookings (AGL-159) rather than\n * replacing them. Dates are day-precision epoch-ms at UTC midnight\n * (`dayMs`); nights = checkout day − checkin day. Pure — the\n * reservation APIs and console own I/O.\n */\n\nimport type { StorefrontTaxMode } from './commerce-tax-decision'\n\nexport const DAY_MS = 24 * 60 * 60 * 1000\n\n/** Seasonal pricing window by month-day (year-agnostic, inclusive). */\nexport interface ResourceSeason {\n /** 'MM-DD' inclusive start, e.g. '06-01'. */\n from: string\n /** 'MM-DD' inclusive end; may wrap the year (e.g. '12-15'..'01-05'). */\n to: string\n /** Multiplier on the nightly rate, e.g. 1.5 for peak. */\n multiplier: number\n label?: string\n}\n\n/** `hosts/{hostId}/resources/{id}` doc. */\nexport interface HostResource {\n name: string\n description?: string\n /**\n * Sleeps N; display only. Never availability: how many guests one unit\n * takes says nothing about how many units there are (see `units`).\n */\n capacity?: number\n /**\n * How many identical units this one resource holds (AGL-4044): 12 RV\n * hookups, 30 tent sites, 4 matching cabins. Each night can take this many\n * stays at once. Absent means 1, which is every resource written before the\n * field existed, and one unit behaves exactly as a resource always has.\n * An integer from 1 to {@link MAX_RESOURCE_UNITS}; read it through\n * {@link resourceUnits}, never raw.\n */\n units?: number\n /**\n * When the booking widget's scarcity line (\"Only 2 left\") starts, for a\n * resource with several units (AGL-4044): it shows once this many units or\n * fewer are free on a night of the stay. Absent is\n * {@link FEW_UNITS_LEFT}, the line every several-unit resource has always\n * had; 0 never shows it. A whole number from 0 to\n * {@link MAX_RESOURCE_UNITS}; read it through {@link resourceFewLeftAt},\n * never raw.\n */\n fewLeftAt?: number\n /**\n * How a stay on this resource is checked in at the window (AGL-4043):\n * `false` or absent, one check-in (and wristband) per stay per day; `true`,\n * one per guest per day, from the stay's {@link HostReservation.guests}.\n * The store's quick control on the check-in screen can set every resource\n * at once (`settings/checkIn.stays`).\n */\n checkInPerGuest?: boolean\n photoUrls?: string[]\n amenities?: string[]\n nightlyRateUsd: number\n /** Friday/Saturday nights multiply by this (default 1). */\n weekendMultiplier?: number\n seasons?: ResourceSeason[]\n minNights?: number\n /** Deposit due at reservation: percent of total (1-100). */\n depositPct?: number\n /** Free cancellation until this many hours before check-in. */\n cancellationHours?: number\n /** Manually blocked day ranges (maintenance etc.), dayMs pairs. */\n blocks?: Array<{ fromDayMs: number; toDayMs: number }>\n}\n\nexport type ReservationStatus =\n | 'pending'\n | 'confirmed'\n | 'checked_in'\n | 'checked_out'\n | 'cancelled'\n | 'no_show'\n\n/** `hosts/{hostId}/reservations/{id}` doc. */\nexport interface HostReservation {\n resourceId: string\n status: ReservationStatus\n /** UTC-midnight day of arrival. */\n checkInDayMs: number\n /** UTC-midnight day of departure (exclusive). */\n checkOutDayMs: number\n guestName?: string | null\n guestEmail?: string | null\n /**\n * How many guests the stay is for (AGL-4043), 1 up to what the resource\n * sleeps ({@link resourceGuestCeiling}); absent on a stay booked before the\n * field existed, or without an answer, which reads as 1. Checking in one\n * guest at a time asks it.\n */\n guests?: number\n /** When staff last changed {@link guests} after booking, and who (AGL-4043). */\n guestsChangedAtMs?: number\n guestsChangedBy?: string\n nights?: number\n totalCents?: number\n depositCents?: number\n /** Payments applied so far (deposit, folio settlements). */\n paidCents?: number\n /** POS folio lines charged to the stay (AGL-317). */\n folio?: Array<{\n orderId: string\n amountCents: number\n note?: string\n atMs: number\n }>\n checkoutSessionId?: string\n createdAtMs?: number\n /**\n * WHICH tax regime the paid deposit carried (AGL-1969), stamped at\n * confirmation from the same `storefrontTaxModeOf` derivation every order\n * door uses (AGL-2451).\n *\n * `manual` on a stay whose merchant had set a lodging rate\n * (`TaxSettings.lodging`), `none` where they had not — which is the default\n * and every store that has not opted in. Never `stripe-automatic` from this\n * path: Stripe Tax cannot compute occupancy tax without a lodging tax code\n * `reserve.ts` does not send, so the rate is always the merchant's own and\n * is never computed against Aglyn's registrations (AGL-1904).\n *\n * ABSENT is a fourth state and is not `none` — it means the reservation was\n * confirmed before this field existed. See `StorefrontTaxMode`.\n */\n taxMode?: StorefrontTaxMode\n /**\n * The lodging tax charged on top of `paidCents` (AGL-1969), from the\n * merchant's own rate. Absent, never zero, where none was charged.\n *\n * SEPARATE FROM `paidCents` on purpose: that field is the money applied to\n * the STAY and the console divides it by `totalCents` to show what is still\n * owed. Tax is not part of the stay's price and is not the merchant's\n * revenue.\n *\n * LIMITATION, stated rather than decided: this is the rate applied to what\n * was CHARGED, which on a deposit-taking resource is the deposit rather than\n * the stay. Whether a jurisdiction wants occupancy tax on the full stay at\n * booking, on the deposit, or on redemption is not a question this codebase\n * answers — see `reserve.ts` and the merchant copy on the Taxes card.\n */\n taxCents?: number\n}\n\n/** UTC midnight for an instant. */\nexport function toDayMs(atMs: number): number {\n return Math.floor(atMs / DAY_MS) * DAY_MS\n}\n\nfunction monthDay(dayMs: number): string {\n const date = new Date(dayMs)\n const month = String(date.getUTCMonth() + 1).padStart(2, '0')\n const day = String(date.getUTCDate()).padStart(2, '0')\n return `${month}-${day}`\n}\n\nfunction inSeason(dayKey: string, season: ResourceSeason): boolean {\n if (season.from <= season.to) {\n return dayKey >= season.from && dayKey <= season.to\n }\n // Wrapping season (e.g. 12-15 .. 01-05).\n return dayKey >= season.from || dayKey <= season.to\n}\n\n/** Per-night rate in cents for one specific night. */\nexport function nightlyRateCents(\n resource: Pick<\n HostResource,\n 'nightlyRateUsd' | 'weekendMultiplier' | 'seasons'\n >,\n dayMs: number,\n): number {\n let rate = resource.nightlyRateUsd * 100\n const weekday = new Date(dayMs).getUTCDay()\n if ((weekday === 5 || weekday === 6) && resource.weekendMultiplier) {\n rate *= resource.weekendMultiplier\n }\n const dayKey = monthDay(dayMs)\n for (const season of resource.seasons ?? []) {\n if (inSeason(dayKey, season)) {\n rate *= season.multiplier\n break\n }\n }\n return Math.round(rate)\n}\n\nexport interface ReservationQuote {\n nights: number\n subtotalCents: number\n depositCents: number\n totalCents: number\n /** Per-night breakdown for the quote UI. */\n nightlyCents: number[]\n problem?: string\n}\n\n/** Prices a stay; `problem` set (and zeros) when the range is invalid. */\nexport function computeReservationQuote(\n resource: HostResource,\n checkInDayMs: number,\n checkOutDayMs: number,\n): ReservationQuote {\n const empty: ReservationQuote = {\n nights: 0,\n subtotalCents: 0,\n depositCents: 0,\n totalCents: 0,\n nightlyCents: [],\n }\n const nights = Math.round((checkOutDayMs - checkInDayMs) / DAY_MS)\n if (!(nights > 0)) return { ...empty, problem: 'Choose at least one night' }\n if (resource.minNights && nights < resource.minNights) {\n return { ...empty, problem: `Minimum stay is ${resource.minNights} nights` }\n }\n const nightlyCents: number[] = []\n for (let day = checkInDayMs; day < checkOutDayMs; day += DAY_MS) {\n nightlyCents.push(nightlyRateCents(resource, day))\n }\n const subtotalCents = nightlyCents.reduce((sum, cents) => sum + cents, 0)\n const depositPct = Math.min(100, Math.max(0, resource.depositPct ?? 100))\n const depositCents = Math.round((subtotalCents * depositPct) / 100)\n return {\n nights,\n subtotalCents,\n depositCents,\n totalCents: subtotalCents,\n nightlyCents,\n }\n}\n\n/**\n * How long an unpaid `pending` reservation stands between the next guest and\n * the dates it named.\n *\n * A `pending` row is written before the Stripe session opens, and nothing ever\n * clears one: `process-abandoned.ts` sweeps `checkouts`, not `reservations`.\n * So the hold has to lapse by the clock rather than by a job, or one guest who\n * closed the tab at the payment screen takes those dates off the market\n * permanently.\n */\nexport const PENDING_RESERVATION_HOLD_MS = 30 * 60 * 1000\n\n/**\n * Does this reservation still stand between a guest and its dates?\n *\n * THE one answer, because four surfaces ask it — the booking door, the booking\n * transaction's re-read, the storefront availability endpoint behind the\n * date-picker, and the console's walk-in check — and they were not asking it\n * the same way. Only the booking door aged out a stale `pending`, so the\n * storefront painted dates unavailable that the booking door would have sold,\n * and the front desk was told a room was taken while it stood empty.\n *\n * A `pending` row carrying no `createdAtMs` releases rather than holds: an\n * unbounded hold on a row that cannot prove its own age is the failure this\n * lapse exists to prevent, and the booking door re-checks inside its\n * transaction before any money moves.\n */\nexport function reservationHoldsDates(\n reservation: Pick<HostReservation, 'status'> & { createdAtMs?: number },\n nowMs: number = Date.now(),\n): boolean {\n if (reservation.status === 'cancelled' || reservation.status === 'no_show') {\n return false\n }\n if (reservation.status !== 'pending') return true\n const createdAtMs = Number(reservation.createdAtMs ?? 0)\n return createdAtMs > 0 && nowMs - createdAtMs < PENDING_RESERVATION_HOLD_MS\n}\n\n/** The most identical units one resource can hold (AGL-4044). */\nexport const MAX_RESOURCE_UNITS = 500\n\n/**\n * How many units a resource holds: the stored `units` as a whole number from 1\n * to {@link MAX_RESOURCE_UNITS}, and 1 for anything else (absent, zero,\n * negative, not a number). Closing a resource is what `blocks` are for, so no\n * stored value can make a resource hold no units at all.\n */\nexport function resourceUnits(\n resource: Pick<HostResource, 'units'> | null | undefined,\n): number {\n const units = Math.floor(Number(resource?.units))\n if (!Number.isFinite(units) || units < 1) return 1\n return Math.min(MAX_RESOURCE_UNITS, units)\n}\n\n/** A reservation as an availability check reads it. */\nexport type HeldStay = Pick<\n HostReservation,\n 'checkInDayMs' | 'checkOutDayMs' | 'status'\n> & {\n createdAtMs?: number\n}\n\n/**\n * How many units are taken on each night from `fromDayMs` up to (not\n * including) `toDayMs`, one entry per night, counting only the stays that\n * still hold their dates ({@link reservationHoldsDates}). A stay takes a night\n * when it overlaps it, with the same `[checkIn, checkOut)` semantics as\n * {@link isRangeAvailable}: a stay that leaves the morning another arrives\n * does not take that night.\n */\nexport function unitsTakenByNight(\n reservations: HeldStay[],\n fromDayMs: number,\n toDayMs: number,\n nowMs: number = Date.now(),\n): number[] {\n const live = reservations.filter((reservation) =>\n reservationHoldsDates(reservation, nowMs),\n )\n const taken: number[] = []\n for (let night = fromDayMs; night < toDayMs; night += DAY_MS) {\n const nightEnd = Math.min(night + DAY_MS, toDayMs)\n let count = 0\n for (const reservation of live) {\n if (\n reservation.checkInDayMs < nightEnd &&\n reservation.checkOutDayMs > night\n ) {\n count++\n }\n }\n taken.push(count)\n }\n return taken\n}\n\n/** One night of a resource: how many of its units are still free. */\nexport interface ResourceNightUnits {\n dayMs: number\n unitsLeft: number\n units: number\n}\n\n/**\n * Units left on each of `nights` nights from `fromDayMs`: the resource's\n * units less the stays holding that night, and none on a blocked night,\n * because a block closes the whole resource.\n */\nexport function unitsLeftByNight(\n resource: Pick<HostResource, 'units' | 'blocks'>,\n reservations: HeldStay[],\n fromDayMs: number,\n nights: number,\n nowMs: number = Date.now(),\n): ResourceNightUnits[] {\n const units = resourceUnits(resource)\n const toDayMs = fromDayMs + Math.max(0, Math.floor(nights)) * DAY_MS\n return unitsTakenByNight(reservations, fromDayMs, toDayMs, nowMs).map(\n (taken, index) => {\n const dayMs = fromDayMs + index * DAY_MS\n const blocked = (resource.blocks ?? []).some(\n (block) => dayMs < block.toDayMs && dayMs + DAY_MS > block.fromDayMs,\n )\n return {\n dayMs,\n units,\n unitsLeft: blocked ? 0 : Math.max(0, units - taken),\n }\n },\n )\n}\n\n/**\n * Availability: a candidate range is free when, on EVERY night in it, fewer\n * live reservations overlap that night than the resource has units\n * (AGL-4044), and no manual block touches it. `[checkIn, checkOut)`\n * semantics, so back-to-back stays touch without conflict. A block closes the\n * whole resource, every unit at once.\n *\n * One unit (the default, and every resource written before `units`) takes\n * the original path unchanged: the range conflicts when it overlaps any live\n * reservation at all.\n *\n * `nowMs` is a parameter so the pending lapse is testable without freezing the\n * clock. A caller passing reservations without `createdAtMs` gets the same\n * answer as before for every status but `pending`.\n */\nexport function isRangeAvailable(\n resource: Pick<HostResource, 'blocks' | 'units'>,\n reservations: HeldStay[],\n checkInDayMs: number,\n checkOutDayMs: number,\n nowMs: number = Date.now(),\n): boolean {\n if (!(checkOutDayMs > checkInDayMs)) return false\n for (const block of resource.blocks ?? []) {\n if (checkInDayMs < block.toDayMs && checkOutDayMs > block.fromDayMs) {\n return false\n }\n }\n const units = resourceUnits(resource)\n if (units === 1) {\n for (const reservation of reservations) {\n if (!reservationHoldsDates(reservation, nowMs)) continue\n if (\n checkInDayMs < reservation.checkOutDayMs &&\n checkOutDayMs > reservation.checkInDayMs\n ) {\n return false\n }\n }\n return true\n }\n return unitsTakenByNight(\n reservations,\n checkInDayMs,\n checkOutDayMs,\n nowMs,\n ).every((taken) => taken < units)\n}\n\n/**\n * The widget's scarcity line starts at this many units left (AGL-4044):\n * \"Only 2 left\". Never on a one-unit resource, where every free night would\n * read \"Only 1 left\", and never on a night nothing is booked on.\n * A resource may set its own threshold, {@link HostResource.fewLeftAt}.\n */\nexport const FEW_UNITS_LEFT = 3\n\n/**\n * When a resource's scarcity line starts: its own `fewLeftAt` as a whole\n * number from 0 (never) to {@link MAX_RESOURCE_UNITS}, and\n * {@link FEW_UNITS_LEFT} for anything else (absent, negative, not a number),\n * so a resource saved before the setting existed reads exactly as it did.\n */\nexport function resourceFewLeftAt(\n resource: Pick<HostResource, 'fewLeftAt'> | null | undefined,\n): number {\n const raw = resource?.fewLeftAt\n if (raw === undefined || raw === null || (raw as unknown) === '') return FEW_UNITS_LEFT\n const at = Math.floor(Number(raw))\n if (!Number.isFinite(at) || at < 0) return FEW_UNITS_LEFT\n return Math.min(MAX_RESOURCE_UNITS, at)\n}\n\n/**\n * The fewest units left across `[checkInDayMs, checkOutDayMs)` when that is\n * `fewLeftAt` or fewer and at least one, else null. `fewLeft` lists only the\n * scarce nights, as the availability endpoint sends them; a night it leaves\n * out has more than the resource's threshold free. `fewLeftAt` is the\n * resource's threshold ({@link resourceFewLeftAt}); 0 never shows the line.\n */\nexport function fewestUnitsLeft(\n fewLeft: Array<{ dayMs: number; unitsLeft: number }> | null | undefined,\n checkInDayMs: number,\n checkOutDayMs: number,\n fewLeftAt: number = FEW_UNITS_LEFT,\n): number | null {\n let fewest: number | null = null\n for (const night of fewLeft ?? []) {\n if (night.dayMs < checkInDayMs || night.dayMs >= checkOutDayMs) continue\n if (!(night.unitsLeft >= 1) || night.unitsLeft > fewLeftAt) continue\n fewest = fewest === null ? night.unitsLeft : Math.min(fewest, night.unitsLeft)\n }\n return fewest\n}\n\n/** The most guests one stay may name when its resource says nothing of how many it sleeps. */\nexport const MAX_RESERVATION_GUESTS = 50\n\n/** Where staff change a stay's guest count after it is booked (AGL-4043): `{ hostId, reservationId, guests }`. */\nexport const RESERVATION_GUESTS_ROUTE = '/api/commerce/reservations/guests'\n\n/**\n * The most guests a stay on this resource may name: what one unit sleeps\n * (`capacity`), else {@link MAX_RESERVATION_GUESTS}.\n */\nexport function resourceGuestCeiling(resource: Pick<HostResource, 'capacity'> | null | undefined): number {\n const sleeps = Math.floor(Number(resource?.capacity))\n return Number.isFinite(sleeps) && sleeps >= 1 ? Math.min(sleeps, MAX_RESERVATION_GUESTS) : MAX_RESERVATION_GUESTS\n}\n\n/** How many guests a stay is for: its `guests` as a whole number of at least 1, else 1. */\nexport function reservationGuests(reservation: Pick<HostReservation, 'guests'> | null | undefined): number {\n const guests = Math.floor(Number(reservation?.guests))\n return Number.isFinite(guests) && guests >= 1 ? Math.min(guests, MAX_RESERVATION_GUESTS) : 1\n}\n\n/**\n * Why a guest count cannot be booked on a resource, or null. Absent (or\n * empty) is fine: the stay is for one guest as far as check-in is concerned.\n */\nexport function reservationGuestsProblem(\n guests: unknown,\n resource: Pick<HostResource, 'capacity'> | null | undefined,\n): string | null {\n if (guests === undefined || guests === null || guests === '') return null\n const count = Number(guests)\n const ceiling = resourceGuestCeiling(resource)\n if (!Number.isInteger(count) || count < 1 || count > ceiling) {\n return ceiling === 1 ? 'This stay sleeps 1 guest' : `Guests must be a whole number from 1 to ${ceiling}`\n }\n return null\n}\n\n/**\n * How the store checks stays in (AGL-4043), the quick control on the\n * check-in screen: `resource` follows each resource's own setting\n * ({@link HostResource.checkInPerGuest}); `stay` and `guest` set every\n * resource at once. Stored at `hosts/{hostId}/settings/checkIn.stays`.\n */\nexport type StayCheckInMode = 'resource' | 'stay' | 'guest'\n\nexport const STAY_CHECK_IN_MODES: readonly StayCheckInMode[] = ['resource', 'stay', 'guest']\n\n/** A stored mode made safe: anything unknown follows each resource. */\nexport function readStayCheckInMode(value: unknown): StayCheckInMode {\n return value === 'stay' || value === 'guest' ? value : 'resource'\n}\n\n/** Whether a stay on this resource is checked in one guest at a time, under the store's mode. */\nexport function stayChecksInPerGuest(\n resource: Pick<HostResource, 'checkInPerGuest'> | null | undefined,\n mode: StayCheckInMode,\n): boolean {\n if (mode === 'guest') return true\n if (mode === 'stay') return false\n return resource?.checkInPerGuest === true\n}\n\n/** Free-cancellation check against the policy window. */\nexport function canCancelReservation(\n resource: Pick<HostResource, 'cancellationHours'>,\n reservation: Pick<HostReservation, 'checkInDayMs' | 'status'>,\n nowMs = Date.now(),\n): boolean {\n if (!['pending', 'confirmed'].includes(reservation.status)) return false\n const windowMs = (resource.cancellationHours ?? 0) * 60 * 60 * 1000\n return nowMs <= reservation.checkInDayMs - windowMs\n}\n"],"names":["DAY_MS","toDayMs","atMs","Math","floor","monthDay","dayMs","date","Date","month","String","getUTCMonth","padStart","day","getUTCDate","inSeason","dayKey","season","from","to","nightlyRateCents","resource","rate","nightlyRateUsd","weekday","getUTCDay","weekendMultiplier","seasons","multiplier","round","computeReservationQuote","checkInDayMs","checkOutDayMs","empty","nights","subtotalCents","depositCents","totalCents","nightlyCents","problem","minNights","push","reduce","sum","cents","depositPct","min","max","PENDING_RESERVATION_HOLD_MS","reservationHoldsDates","reservation","nowMs","now","status","createdAtMs","Number","MAX_RESOURCE_UNITS","resourceUnits","units","isFinite","unitsTakenByNight","reservations","fromDayMs","live","filter","taken","night","nightEnd","count","unitsLeftByNight","map","index","blocked","blocks","some","block","unitsLeft","isRangeAvailable","every","FEW_UNITS_LEFT","resourceFewLeftAt","raw","fewLeftAt","undefined","at","fewestUnitsLeft","fewLeft","fewest","MAX_RESERVATION_GUESTS","RESERVATION_GUESTS_ROUTE","resourceGuestCeiling","sleeps","capacity","reservationGuests","guests","reservationGuestsProblem","ceiling","isInteger","STAY_CHECK_IN_MODES","readStayCheckInMode","value","stayChecksInPerGuest","mode","checkInPerGuest","canCancelReservation","includes","windowMs","cancellationHours"],"mappings":"AAAA;;;;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OAAO,SAASO,yBACdD,MAAe,EACfzE,QAA2D;IAE3D,IAAIyE,WAAWX,aAAaW,WAAW,QAAQA,WAAW,IAAI,OAAO;IACrE,MAAM1B,QAAQb,OAAOuC;IACrB,MAAME,UAAUN,qBAAqBrE;IACrC,IAAI,CAACkC,OAAO0C,SAAS,CAAC7B,UAAUA,QAAQ,KAAKA,QAAQ4B,SAAS;QAC5D,OAAOA,YAAY,IAAI,6BAA6B,CAAC,wCAAwC,EAAEA,SAAS;IAC1G;IACA,OAAO;AACT;AAUA,OAAO,MAAME,sBAAkD;IAAC;IAAY;IAAQ;CAAQ,CAAA;AAE5F,qEAAqE,GACrE,OAAO,SAASC,oBAAoBC,KAAc;IAChD,OAAOA,UAAU,UAAUA,UAAU,UAAUA,QAAQ;AACzD;AAEA,+FAA+F,GAC/F,OAAO,SAASC,qBACdhF,QAAkE,EAClEiF,IAAqB;IAErB,IAAIA,SAAS,SAAS,OAAO;IAC7B,IAAIA,SAAS,QAAQ,OAAO;IAC5B,OAAOjF,CAAAA,4BAAAA,SAAUkF,eAAe,MAAK;AACvC;AAEA,uDAAuD,GACvD,OAAO,SAASC,qBACdnF,QAAiD,EACjD6B,WAA6D,EAC7DC,QAAQ3C,KAAK4C,GAAG,EAAE;QAGA/B;IADlB,IAAI,CAAC;QAAC;QAAW;KAAY,CAACoF,QAAQ,CAACvD,YAAYG,MAAM,GAAG,OAAO;IACnE,MAAMqD,WAAW,EAACrF,8BAAAA,SAASsF,iBAAiB,YAA1BtF,8BAA8B,KAAK,KAAK,KAAK;IAC/D,OAAO8B,SAASD,YAAYnB,YAAY,GAAG2E;AAC7C"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/commerce-reservations.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\n/**\n * Reservations v1 (AGL-304): bookable units (cabins) with date-range\n * stays, seasonal pricing, deposits, and cancellation windows —\n * extending the appointment-slot bookings (AGL-159) rather than\n * replacing them. Dates are day-precision epoch-ms at UTC midnight\n * (`dayMs`); nights = checkout day − checkin day. Pure — the\n * reservation APIs and console own I/O.\n */\n\nimport type { StorefrontTaxMode } from './commerce-tax-decision'\n\nexport const DAY_MS = 24 * 60 * 60 * 1000\n\n/** Seasonal pricing window by month-day (year-agnostic, inclusive). */\nexport interface ResourceSeason {\n /** 'MM-DD' inclusive start, e.g. '06-01'. */\n from: string\n /** 'MM-DD' inclusive end; may wrap the year (e.g. '12-15'..'01-05'). */\n to: string\n /** Multiplier on the nightly rate, e.g. 1.5 for peak. */\n multiplier: number\n label?: string\n}\n\n/** `hosts/{hostId}/resources/{id}` doc. */\nexport interface HostResource {\n name: string\n description?: string\n /**\n * Sleeps N; display only. Never availability: how many guests one unit\n * takes says nothing about how many units there are (see `units`).\n */\n capacity?: number\n /**\n * How many identical units this one resource holds (AGL-4044): 12 RV\n * hookups, 30 tent sites, 4 matching cabins. Each night can take this many\n * stays at once. Absent means 1, which is every resource written before the\n * field existed, and one unit behaves exactly as a resource always has.\n * An integer from 1 to {@link MAX_RESOURCE_UNITS}; read it through\n * {@link resourceUnits}, never raw.\n */\n units?: number\n /**\n * When the booking widget's scarcity line (\"Only 2 left\") starts, for a\n * resource with several units (AGL-4044): it shows once this many units or\n * fewer are free on a night of the stay. Absent is\n * {@link FEW_UNITS_LEFT}, the line every several-unit resource has always\n * had; 0 never shows it. A whole number from 0 to\n * {@link MAX_RESOURCE_UNITS}; read it through {@link resourceFewLeftAt},\n * never raw.\n */\n fewLeftAt?: number\n /**\n * How a stay on this resource is checked in at the window (AGL-4043):\n * `false` or absent, one check-in (and wristband) per stay per day; `true`,\n * one per guest per day, from the stay's {@link HostReservation.guests}.\n * The store's quick control on the check-in screen can set every resource\n * at once (`settings/checkIn.stays`).\n */\n checkInPerGuest?: boolean\n photoUrls?: string[]\n amenities?: string[]\n /**\n * The page on the site that holds this resource's booking widget\n * (AGL-4252), site-relative (`/cabins/lakeside`): where a site search\n * result for the stay opens. Absent, the stay is not a search result.\n */\n pagePath?: string\n nightlyRateUsd: number\n /** Friday/Saturday nights multiply by this (default 1). */\n weekendMultiplier?: number\n seasons?: ResourceSeason[]\n minNights?: number\n /** Deposit due at reservation: percent of total (1-100). */\n depositPct?: number\n /** Free cancellation until this many hours before check-in. */\n cancellationHours?: number\n /** Manually blocked day ranges (maintenance etc.), dayMs pairs. */\n blocks?: Array<{ fromDayMs: number; toDayMs: number }>\n}\n\nexport type ReservationStatus =\n | 'pending'\n | 'confirmed'\n | 'checked_in'\n | 'checked_out'\n | 'cancelled'\n | 'no_show'\n\n/** `hosts/{hostId}/reservations/{id}` doc. */\nexport interface HostReservation {\n resourceId: string\n status: ReservationStatus\n /** UTC-midnight day of arrival. */\n checkInDayMs: number\n /** UTC-midnight day of departure (exclusive). */\n checkOutDayMs: number\n guestName?: string | null\n guestEmail?: string | null\n /**\n * How many guests the stay is for (AGL-4043), 1 up to what the resource\n * sleeps ({@link resourceGuestCeiling}); absent on a stay booked before the\n * field existed, or without an answer, which reads as 1. Checking in one\n * guest at a time asks it.\n */\n guests?: number\n /** When staff last changed {@link guests} after booking, and who (AGL-4043). */\n guestsChangedAtMs?: number\n guestsChangedBy?: string\n nights?: number\n totalCents?: number\n depositCents?: number\n /** Payments applied so far (deposit, folio settlements). */\n paidCents?: number\n /** POS folio lines charged to the stay (AGL-317). */\n folio?: Array<{\n orderId: string\n amountCents: number\n note?: string\n atMs: number\n }>\n checkoutSessionId?: string\n createdAtMs?: number\n /**\n * WHICH tax regime the paid deposit carried (AGL-1969), stamped at\n * confirmation from the same `storefrontTaxModeOf` derivation every order\n * door uses (AGL-2451).\n *\n * `manual` on a stay whose merchant had set a lodging rate\n * (`TaxSettings.lodging`), `none` where they had not — which is the default\n * and every store that has not opted in. Never `stripe-automatic` from this\n * path: Stripe Tax cannot compute occupancy tax without a lodging tax code\n * `reserve.ts` does not send, so the rate is always the merchant's own and\n * is never computed against Aglyn's registrations (AGL-1904).\n *\n * ABSENT is a fourth state and is not `none` — it means the reservation was\n * confirmed before this field existed. See `StorefrontTaxMode`.\n */\n taxMode?: StorefrontTaxMode\n /**\n * The lodging tax charged on top of `paidCents` (AGL-1969), from the\n * merchant's own rate. Absent, never zero, where none was charged.\n *\n * SEPARATE FROM `paidCents` on purpose: that field is the money applied to\n * the STAY and the console divides it by `totalCents` to show what is still\n * owed. Tax is not part of the stay's price and is not the merchant's\n * revenue.\n *\n * LIMITATION, stated rather than decided: this is the rate applied to what\n * was CHARGED, which on a deposit-taking resource is the deposit rather than\n * the stay. Whether a jurisdiction wants occupancy tax on the full stay at\n * booking, on the deposit, or on redemption is not a question this codebase\n * answers — see `reserve.ts` and the merchant copy on the Taxes card.\n */\n taxCents?: number\n}\n\n/** UTC midnight for an instant. */\nexport function toDayMs(atMs: number): number {\n return Math.floor(atMs / DAY_MS) * DAY_MS\n}\n\nfunction monthDay(dayMs: number): string {\n const date = new Date(dayMs)\n const month = String(date.getUTCMonth() + 1).padStart(2, '0')\n const day = String(date.getUTCDate()).padStart(2, '0')\n return `${month}-${day}`\n}\n\nfunction inSeason(dayKey: string, season: ResourceSeason): boolean {\n if (season.from <= season.to) {\n return dayKey >= season.from && dayKey <= season.to\n }\n // Wrapping season (e.g. 12-15 .. 01-05).\n return dayKey >= season.from || dayKey <= season.to\n}\n\n/** Per-night rate in cents for one specific night. */\nexport function nightlyRateCents(\n resource: Pick<\n HostResource,\n 'nightlyRateUsd' | 'weekendMultiplier' | 'seasons'\n >,\n dayMs: number,\n): number {\n let rate = resource.nightlyRateUsd * 100\n const weekday = new Date(dayMs).getUTCDay()\n if ((weekday === 5 || weekday === 6) && resource.weekendMultiplier) {\n rate *= resource.weekendMultiplier\n }\n const dayKey = monthDay(dayMs)\n for (const season of resource.seasons ?? []) {\n if (inSeason(dayKey, season)) {\n rate *= season.multiplier\n break\n }\n }\n return Math.round(rate)\n}\n\nexport interface ReservationQuote {\n nights: number\n subtotalCents: number\n depositCents: number\n totalCents: number\n /** Per-night breakdown for the quote UI. */\n nightlyCents: number[]\n problem?: string\n}\n\n/** Prices a stay; `problem` set (and zeros) when the range is invalid. */\nexport function computeReservationQuote(\n resource: HostResource,\n checkInDayMs: number,\n checkOutDayMs: number,\n): ReservationQuote {\n const empty: ReservationQuote = {\n nights: 0,\n subtotalCents: 0,\n depositCents: 0,\n totalCents: 0,\n nightlyCents: [],\n }\n const nights = Math.round((checkOutDayMs - checkInDayMs) / DAY_MS)\n if (!(nights > 0)) return { ...empty, problem: 'Choose at least one night' }\n if (resource.minNights && nights < resource.minNights) {\n return { ...empty, problem: `Minimum stay is ${resource.minNights} nights` }\n }\n const nightlyCents: number[] = []\n for (let day = checkInDayMs; day < checkOutDayMs; day += DAY_MS) {\n nightlyCents.push(nightlyRateCents(resource, day))\n }\n const subtotalCents = nightlyCents.reduce((sum, cents) => sum + cents, 0)\n const depositPct = Math.min(100, Math.max(0, resource.depositPct ?? 100))\n const depositCents = Math.round((subtotalCents * depositPct) / 100)\n return {\n nights,\n subtotalCents,\n depositCents,\n totalCents: subtotalCents,\n nightlyCents,\n }\n}\n\n/**\n * How long an unpaid `pending` reservation stands between the next guest and\n * the dates it named.\n *\n * A `pending` row is written before the Stripe session opens, and nothing ever\n * clears one: `process-abandoned.ts` sweeps `checkouts`, not `reservations`.\n * So the hold has to lapse by the clock rather than by a job, or one guest who\n * closed the tab at the payment screen takes those dates off the market\n * permanently.\n */\nexport const PENDING_RESERVATION_HOLD_MS = 30 * 60 * 1000\n\n/**\n * Does this reservation still stand between a guest and its dates?\n *\n * THE one answer, because four surfaces ask it — the booking door, the booking\n * transaction's re-read, the storefront availability endpoint behind the\n * date-picker, and the console's walk-in check — and they were not asking it\n * the same way. Only the booking door aged out a stale `pending`, so the\n * storefront painted dates unavailable that the booking door would have sold,\n * and the front desk was told a room was taken while it stood empty.\n *\n * A `pending` row carrying no `createdAtMs` releases rather than holds: an\n * unbounded hold on a row that cannot prove its own age is the failure this\n * lapse exists to prevent, and the booking door re-checks inside its\n * transaction before any money moves.\n */\nexport function reservationHoldsDates(\n reservation: Pick<HostReservation, 'status'> & { createdAtMs?: number },\n nowMs: number = Date.now(),\n): boolean {\n if (reservation.status === 'cancelled' || reservation.status === 'no_show') {\n return false\n }\n if (reservation.status !== 'pending') return true\n const createdAtMs = Number(reservation.createdAtMs ?? 0)\n return createdAtMs > 0 && nowMs - createdAtMs < PENDING_RESERVATION_HOLD_MS\n}\n\n/** The most identical units one resource can hold (AGL-4044). */\nexport const MAX_RESOURCE_UNITS = 500\n\n/**\n * How many units a resource holds: the stored `units` as a whole number from 1\n * to {@link MAX_RESOURCE_UNITS}, and 1 for anything else (absent, zero,\n * negative, not a number). Closing a resource is what `blocks` are for, so no\n * stored value can make a resource hold no units at all.\n */\nexport function resourceUnits(\n resource: Pick<HostResource, 'units'> | null | undefined,\n): number {\n const units = Math.floor(Number(resource?.units))\n if (!Number.isFinite(units) || units < 1) return 1\n return Math.min(MAX_RESOURCE_UNITS, units)\n}\n\n/** A reservation as an availability check reads it. */\nexport type HeldStay = Pick<\n HostReservation,\n 'checkInDayMs' | 'checkOutDayMs' | 'status'\n> & {\n createdAtMs?: number\n}\n\n/**\n * How many units are taken on each night from `fromDayMs` up to (not\n * including) `toDayMs`, one entry per night, counting only the stays that\n * still hold their dates ({@link reservationHoldsDates}). A stay takes a night\n * when it overlaps it, with the same `[checkIn, checkOut)` semantics as\n * {@link isRangeAvailable}: a stay that leaves the morning another arrives\n * does not take that night.\n */\nexport function unitsTakenByNight(\n reservations: HeldStay[],\n fromDayMs: number,\n toDayMs: number,\n nowMs: number = Date.now(),\n): number[] {\n const live = reservations.filter((reservation) =>\n reservationHoldsDates(reservation, nowMs),\n )\n const taken: number[] = []\n for (let night = fromDayMs; night < toDayMs; night += DAY_MS) {\n const nightEnd = Math.min(night + DAY_MS, toDayMs)\n let count = 0\n for (const reservation of live) {\n if (\n reservation.checkInDayMs < nightEnd &&\n reservation.checkOutDayMs > night\n ) {\n count++\n }\n }\n taken.push(count)\n }\n return taken\n}\n\n/** One night of a resource: how many of its units are still free. */\nexport interface ResourceNightUnits {\n dayMs: number\n unitsLeft: number\n units: number\n}\n\n/**\n * Units left on each of `nights` nights from `fromDayMs`: the resource's\n * units less the stays holding that night, and none on a blocked night,\n * because a block closes the whole resource.\n */\nexport function unitsLeftByNight(\n resource: Pick<HostResource, 'units' | 'blocks'>,\n reservations: HeldStay[],\n fromDayMs: number,\n nights: number,\n nowMs: number = Date.now(),\n): ResourceNightUnits[] {\n const units = resourceUnits(resource)\n const toDayMs = fromDayMs + Math.max(0, Math.floor(nights)) * DAY_MS\n return unitsTakenByNight(reservations, fromDayMs, toDayMs, nowMs).map(\n (taken, index) => {\n const dayMs = fromDayMs + index * DAY_MS\n const blocked = (resource.blocks ?? []).some(\n (block) => dayMs < block.toDayMs && dayMs + DAY_MS > block.fromDayMs,\n )\n return {\n dayMs,\n units,\n unitsLeft: blocked ? 0 : Math.max(0, units - taken),\n }\n },\n )\n}\n\n/**\n * Availability: a candidate range is free when, on EVERY night in it, fewer\n * live reservations overlap that night than the resource has units\n * (AGL-4044), and no manual block touches it. `[checkIn, checkOut)`\n * semantics, so back-to-back stays touch without conflict. A block closes the\n * whole resource, every unit at once.\n *\n * One unit (the default, and every resource written before `units`) takes\n * the original path unchanged: the range conflicts when it overlaps any live\n * reservation at all.\n *\n * `nowMs` is a parameter so the pending lapse is testable without freezing the\n * clock. A caller passing reservations without `createdAtMs` gets the same\n * answer as before for every status but `pending`.\n */\nexport function isRangeAvailable(\n resource: Pick<HostResource, 'blocks' | 'units'>,\n reservations: HeldStay[],\n checkInDayMs: number,\n checkOutDayMs: number,\n nowMs: number = Date.now(),\n): boolean {\n if (!(checkOutDayMs > checkInDayMs)) return false\n for (const block of resource.blocks ?? []) {\n if (checkInDayMs < block.toDayMs && checkOutDayMs > block.fromDayMs) {\n return false\n }\n }\n const units = resourceUnits(resource)\n if (units === 1) {\n for (const reservation of reservations) {\n if (!reservationHoldsDates(reservation, nowMs)) continue\n if (\n checkInDayMs < reservation.checkOutDayMs &&\n checkOutDayMs > reservation.checkInDayMs\n ) {\n return false\n }\n }\n return true\n }\n return unitsTakenByNight(\n reservations,\n checkInDayMs,\n checkOutDayMs,\n nowMs,\n ).every((taken) => taken < units)\n}\n\n/**\n * The widget's scarcity line starts at this many units left (AGL-4044):\n * \"Only 2 left\". Never on a one-unit resource, where every free night would\n * read \"Only 1 left\", and never on a night nothing is booked on.\n * A resource may set its own threshold, {@link HostResource.fewLeftAt}.\n */\nexport const FEW_UNITS_LEFT = 3\n\n/**\n * When a resource's scarcity line starts: its own `fewLeftAt` as a whole\n * number from 0 (never) to {@link MAX_RESOURCE_UNITS}, and\n * {@link FEW_UNITS_LEFT} for anything else (absent, negative, not a number),\n * so a resource saved before the setting existed reads exactly as it did.\n */\nexport function resourceFewLeftAt(\n resource: Pick<HostResource, 'fewLeftAt'> | null | undefined,\n): number {\n const raw = resource?.fewLeftAt\n if (raw === undefined || raw === null || (raw as unknown) === '') return FEW_UNITS_LEFT\n const at = Math.floor(Number(raw))\n if (!Number.isFinite(at) || at < 0) return FEW_UNITS_LEFT\n return Math.min(MAX_RESOURCE_UNITS, at)\n}\n\n/**\n * The fewest units left across `[checkInDayMs, checkOutDayMs)` when that is\n * `fewLeftAt` or fewer and at least one, else null. `fewLeft` lists only the\n * scarce nights, as the availability endpoint sends them; a night it leaves\n * out has more than the resource's threshold free. `fewLeftAt` is the\n * resource's threshold ({@link resourceFewLeftAt}); 0 never shows the line.\n */\nexport function fewestUnitsLeft(\n fewLeft: Array<{ dayMs: number; unitsLeft: number }> | null | undefined,\n checkInDayMs: number,\n checkOutDayMs: number,\n fewLeftAt: number = FEW_UNITS_LEFT,\n): number | null {\n let fewest: number | null = null\n for (const night of fewLeft ?? []) {\n if (night.dayMs < checkInDayMs || night.dayMs >= checkOutDayMs) continue\n if (!(night.unitsLeft >= 1) || night.unitsLeft > fewLeftAt) continue\n fewest = fewest === null ? night.unitsLeft : Math.min(fewest, night.unitsLeft)\n }\n return fewest\n}\n\n/** The most guests one stay may name when its resource says nothing of how many it sleeps. */\nexport const MAX_RESERVATION_GUESTS = 50\n\n/** Where staff change a stay's guest count after it is booked (AGL-4043): `{ hostId, reservationId, guests }`. */\nexport const RESERVATION_GUESTS_ROUTE = '/api/commerce/reservations/guests'\n\n/**\n * The most guests a stay on this resource may name: what one unit sleeps\n * (`capacity`), else {@link MAX_RESERVATION_GUESTS}.\n */\nexport function resourceGuestCeiling(resource: Pick<HostResource, 'capacity'> | null | undefined): number {\n const sleeps = Math.floor(Number(resource?.capacity))\n return Number.isFinite(sleeps) && sleeps >= 1 ? Math.min(sleeps, MAX_RESERVATION_GUESTS) : MAX_RESERVATION_GUESTS\n}\n\n/** How many guests a stay is for: its `guests` as a whole number of at least 1, else 1. */\nexport function reservationGuests(reservation: Pick<HostReservation, 'guests'> | null | undefined): number {\n const guests = Math.floor(Number(reservation?.guests))\n return Number.isFinite(guests) && guests >= 1 ? Math.min(guests, MAX_RESERVATION_GUESTS) : 1\n}\n\n/**\n * Why a guest count cannot be booked on a resource, or null. Absent (or\n * empty) is fine: the stay is for one guest as far as check-in is concerned.\n */\nexport function reservationGuestsProblem(\n guests: unknown,\n resource: Pick<HostResource, 'capacity'> | null | undefined,\n): string | null {\n if (guests === undefined || guests === null || guests === '') return null\n const count = Number(guests)\n const ceiling = resourceGuestCeiling(resource)\n if (!Number.isInteger(count) || count < 1 || count > ceiling) {\n return ceiling === 1 ? 'This stay sleeps 1 guest' : `Guests must be a whole number from 1 to ${ceiling}`\n }\n return null\n}\n\n/**\n * How the store checks stays in (AGL-4043), the quick control on the\n * check-in screen: `resource` follows each resource's own setting\n * ({@link HostResource.checkInPerGuest}); `stay` and `guest` set every\n * resource at once. Stored at `hosts/{hostId}/settings/checkIn.stays`.\n */\nexport type StayCheckInMode = 'resource' | 'stay' | 'guest'\n\nexport const STAY_CHECK_IN_MODES: readonly StayCheckInMode[] = ['resource', 'stay', 'guest']\n\n/** A stored mode made safe: anything unknown follows each resource. */\nexport function readStayCheckInMode(value: unknown): StayCheckInMode {\n return value === 'stay' || value === 'guest' ? value : 'resource'\n}\n\n/** Whether a stay on this resource is checked in one guest at a time, under the store's mode. */\nexport function stayChecksInPerGuest(\n resource: Pick<HostResource, 'checkInPerGuest'> | null | undefined,\n mode: StayCheckInMode,\n): boolean {\n if (mode === 'guest') return true\n if (mode === 'stay') return false\n return resource?.checkInPerGuest === true\n}\n\n/** Free-cancellation check against the policy window. */\nexport function canCancelReservation(\n resource: Pick<HostResource, 'cancellationHours'>,\n reservation: Pick<HostReservation, 'checkInDayMs' | 'status'>,\n nowMs = Date.now(),\n): boolean {\n if (!['pending', 'confirmed'].includes(reservation.status)) return false\n const windowMs = (resource.cancellationHours ?? 0) * 60 * 60 * 1000\n return nowMs <= reservation.checkInDayMs - windowMs\n}\n"],"names":["DAY_MS","toDayMs","atMs","Math","floor","monthDay","dayMs","date","Date","month","String","getUTCMonth","padStart","day","getUTCDate","inSeason","dayKey","season","from","to","nightlyRateCents","resource","rate","nightlyRateUsd","weekday","getUTCDay","weekendMultiplier","seasons","multiplier","round","computeReservationQuote","checkInDayMs","checkOutDayMs","empty","nights","subtotalCents","depositCents","totalCents","nightlyCents","problem","minNights","push","reduce","sum","cents","depositPct","min","max","PENDING_RESERVATION_HOLD_MS","reservationHoldsDates","reservation","nowMs","now","status","createdAtMs","Number","MAX_RESOURCE_UNITS","resourceUnits","units","isFinite","unitsTakenByNight","reservations","fromDayMs","live","filter","taken","night","nightEnd","count","unitsLeftByNight","map","index","blocked","blocks","some","block","unitsLeft","isRangeAvailable","every","FEW_UNITS_LEFT","resourceFewLeftAt","raw","fewLeftAt","undefined","at","fewestUnitsLeft","fewLeft","fewest","MAX_RESERVATION_GUESTS","RESERVATION_GUESTS_ROUTE","resourceGuestCeiling","sleeps","capacity","reservationGuests","guests","reservationGuestsProblem","ceiling","isInteger","STAY_CHECK_IN_MODES","readStayCheckInMode","value","stayChecksInPerGuest","mode","checkInPerGuest","canCancelReservation","includes","windowMs","cancellationHours"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;CAOC;AAID,OAAO,MAAMA,SAAS,KAAK,KAAK,KAAK,KAAI;AAkJzC,iCAAiC,GACjC,OAAO,SAASC,QAAQC,IAAY;IAClC,OAAOC,KAAKC,KAAK,CAACF,OAAOF,UAAUA;AACrC;AAEA,SAASK,SAASC,KAAa;IAC7B,MAAMC,OAAO,IAAIC,KAAKF;IACtB,MAAMG,QAAQC,OAAOH,KAAKI,WAAW,KAAK,GAAGC,QAAQ,CAAC,GAAG;IACzD,MAAMC,MAAMH,OAAOH,KAAKO,UAAU,IAAIF,QAAQ,CAAC,GAAG;IAClD,OAAO,GAAGH,MAAM,CAAC,EAAEI,KAAK;AAC1B;AAEA,SAASE,SAASC,MAAc,EAAEC,MAAsB;IACtD,IAAIA,OAAOC,IAAI,IAAID,OAAOE,EAAE,EAAE;QAC5B,OAAOH,UAAUC,OAAOC,IAAI,IAAIF,UAAUC,OAAOE,EAAE;IACrD;IACA,yCAAyC;IACzC,OAAOH,UAAUC,OAAOC,IAAI,IAAIF,UAAUC,OAAOE,EAAE;AACrD;AAEA,oDAAoD,GACpD,OAAO,SAASC,iBACdC,QAGC,EACDf,KAAa;QAQQe;IANrB,IAAIC,OAAOD,SAASE,cAAc,GAAG;IACrC,MAAMC,UAAU,IAAIhB,KAAKF,OAAOmB,SAAS;IACzC,IAAI,AAACD,CAAAA,YAAY,KAAKA,YAAY,CAAA,KAAMH,SAASK,iBAAiB,EAAE;QAClEJ,QAAQD,SAASK,iBAAiB;IACpC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,KAAK,KAAK;IAC/D,OAAO8B,SAASD,YAAYnB,YAAY,GAAG2E;AAC7C"}
|
|
@@ -89,6 +89,13 @@ export interface ShippingRate {
|
|
|
89
89
|
tiers?: ShippingTier[];
|
|
90
90
|
/** carrier: the live rate's options (AGL-3612). */
|
|
91
91
|
carrier?: CarrierRateSettings;
|
|
92
|
+
/**
|
|
93
|
+
* flat + free_over: the price in another currency the store sells in
|
|
94
|
+
* (AGL-4248), minor units keyed by ISO code. A currency not listed converts.
|
|
95
|
+
*/
|
|
96
|
+
amountsByCurrency?: Record<string, number>;
|
|
97
|
+
/** free_over: the threshold in another currency (AGL-4248), minor units by ISO code. */
|
|
98
|
+
freeOverByCurrency?: Record<string, number>;
|
|
92
99
|
}
|
|
93
100
|
export interface ShippingSettings {
|
|
94
101
|
zones?: ShippingZone[];
|
|
@@ -397,4 +404,18 @@ export declare function appendShippingAddressCollectionParams(params: URLSearchP
|
|
|
397
404
|
* before shipping was wired at all. That guarantee lives here rather than in
|
|
398
405
|
* each caller, so neither checkout path can lose it independently (AGL-1720).
|
|
399
406
|
*/
|
|
400
|
-
export declare function appendCheckoutShippingParams(params: URLSearchParams, options: readonly ResolvedShippingRate[]
|
|
407
|
+
export declare function appendCheckoutShippingParams(params: URLSearchParams, options: readonly ResolvedShippingRate[], currency?: string, extra?: {
|
|
408
|
+
taxBehavior?: 'inclusive' | 'exclusive';
|
|
409
|
+
}): void;
|
|
410
|
+
/**
|
|
411
|
+
* Resolved options re-priced in a shopper currency (AGL-4248): a rate's own
|
|
412
|
+
* amount in that currency when the merchant set one, else the store amount
|
|
413
|
+
* converted; and a free-over rate with its own threshold there is free, or
|
|
414
|
+
* not, against the goods in that currency rather than the store-currency
|
|
415
|
+
* subtotal it was planned on. Pickup stays free. Order is kept.
|
|
416
|
+
*/
|
|
417
|
+
export declare function shippingOptionsInCurrency(options: readonly ResolvedShippingRate[], settings: ShippingSettings | undefined, currency: {
|
|
418
|
+
code: string;
|
|
419
|
+
subtotalMinor: number;
|
|
420
|
+
convert: (baseCents: number, fixedMinor?: Record<string, number>) => number;
|
|
421
|
+
}): ResolvedShippingRate[];
|
|
@@ -822,13 +822,42 @@ export function describeShippingCoverage(coverage) {
|
|
|
822
822
|
* configured no shipping keeps a session byte-identical to the one built
|
|
823
823
|
* before shipping was wired at all. That guarantee lives here rather than in
|
|
824
824
|
* each caller, so neither checkout path can lose it independently (AGL-1720).
|
|
825
|
-
*/ export function appendCheckoutShippingParams(params, options) {
|
|
825
|
+
*/ export function appendCheckoutShippingParams(params, options, currency = 'usd', extra = {}) {
|
|
826
826
|
options.forEach((option, index)=>{
|
|
827
827
|
const field = `shipping_options[${index}][shipping_rate_data]`;
|
|
828
828
|
params.set(`${field}[type]`, 'fixed_amount');
|
|
829
829
|
params.set(`${field}[display_name]`, option.name.slice(0, 100));
|
|
830
830
|
params.set(`${field}[fixed_amount][amount]`, String(option.amountCents));
|
|
831
|
-
params.set(`${field}[fixed_amount][currency]`,
|
|
831
|
+
params.set(`${field}[fixed_amount][currency]`, currency.toLowerCase());
|
|
832
|
+
if (extra.taxBehavior) params.set(`${field}[tax_behavior]`, extra.taxBehavior);
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Resolved options re-priced in a shopper currency (AGL-4248): a rate's own
|
|
837
|
+
* amount in that currency when the merchant set one, else the store amount
|
|
838
|
+
* converted; and a free-over rate with its own threshold there is free, or
|
|
839
|
+
* not, against the goods in that currency rather than the store-currency
|
|
840
|
+
* subtotal it was planned on. Pickup stays free. Order is kept.
|
|
841
|
+
*/ export function shippingOptionsInCurrency(options, settings, currency) {
|
|
842
|
+
const code = currency.code.toUpperCase();
|
|
843
|
+
return options.map((option)=>{
|
|
844
|
+
var _settings_rates, _rate_freeOverByCurrency;
|
|
845
|
+
if (option.rateId === LOCAL_PICKUP_RATE_ID) return option;
|
|
846
|
+
const rate = settings == null ? void 0 : (_settings_rates = settings.rates) == null ? void 0 : _settings_rates.find((entry)=>entry.id === option.rateId);
|
|
847
|
+
const threshold = (rate == null ? void 0 : rate.kind) === 'free_over' ? (_rate_freeOverByCurrency = rate.freeOverByCurrency) == null ? void 0 : _rate_freeOverByCurrency[code] : undefined;
|
|
848
|
+
if (rate && typeof threshold === 'number') {
|
|
849
|
+
var _rate_amountCents;
|
|
850
|
+
const free = currency.subtotalMinor >= threshold;
|
|
851
|
+
const amount = free ? 0 : currency.convert(Math.max(0, Math.round((_rate_amountCents = rate.amountCents) != null ? _rate_amountCents : 0)), rate.amountsByCurrency);
|
|
852
|
+
return _extends({}, option, {
|
|
853
|
+
amountCents: amount
|
|
854
|
+
});
|
|
855
|
+
}
|
|
856
|
+
if (option.amountCents === 0) return option;
|
|
857
|
+
const fixed = rate && (rate.kind === 'flat' || rate.kind === 'free_over') ? rate.amountsByCurrency : undefined;
|
|
858
|
+
return _extends({}, option, {
|
|
859
|
+
amountCents: currency.convert(option.amountCents, fixed)
|
|
860
|
+
});
|
|
832
861
|
});
|
|
833
862
|
}
|
|
834
863
|
|