@aglyn/plugins-commerce 1.11.0 → 1.13.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/catalog-organization-card.component.js +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/host-quotes-card.component.js +23 -13
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -1
- package/src/lib/components/console/order-detail-dialog.component.js +1 -1
- package/src/lib/components/console/order-detail-dialog.component.js.map +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.d.ts +1 -1
- package/src/lib/components/console/pay-link-readiness-notice.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-kiosk/kiosk-menu.d.ts +10 -3
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js +29 -8
- package/src/lib/components/console/pos-kiosk/kiosk-menu.js.map +1 -1
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js +7 -0
- package/src/lib/components/console/pos-kiosk/pos-kiosk-api.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.d.ts +2 -0
- package/src/lib/components/console/pos-kiosk-page.component.js +54 -3
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +1 -1
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
- package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js +1 -1
- package/src/lib/components/console/pos-ops/pos-day-totals-card.component.js.map +1 -1
- package/src/lib/components/console/pos-reader-splash-setting.component.js +1 -1
- package/src/lib/components/console/pos-reader-splash-setting.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +0 -2
- package/src/lib/components/console/product-add-ons-fields.component.js +1 -6
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +7 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +129 -32
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-pay-link.component.d.ts +4 -1
- package/src/lib/components/console/quote-pay-link.component.js +23 -12
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.d.ts +3 -2
- package/src/lib/components/console/quote-proofs.component.js +73 -5
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-send.component.js +9 -6
- package/src/lib/components/console/quote-send.component.js.map +1 -1
- package/src/lib/components/console/site-member-purchases.component.js +1 -1
- package/src/lib/components/console/site-member-purchases.component.js.map +1 -1
- package/src/lib/components/product-detail.js +1 -1
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.js +5 -3
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-reviews.js +17 -12
- package/src/lib/components/product-reviews.js.map +1 -1
- package/src/lib/components/quote-page-body.js +14 -8
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +2 -1
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/model/commerce-invoices.d.ts +1 -1
- package/src/lib/model/commerce-invoices.js +4 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-kiosk-search.d.ts +22 -0
- package/src/lib/model/commerce-kiosk-search.js +32 -0
- package/src/lib/model/commerce-kiosk-search.js.map +1 -0
- package/src/lib/model/commerce-pos-kiosk.d.ts +7 -1
- package/src/lib/model/commerce-pos-kiosk.js +1 -1
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/commerce-quote-email.d.ts +7 -6
- package/src/lib/model/commerce-quote-email.js +11 -6
- package/src/lib/model/commerce-quote-email.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +6 -1
- package/src/lib/model/commerce-quote-pay.js +18 -8
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +28 -1
- package/src/lib/model/commerce-quote-proofs.js +58 -2
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +22 -1
- package/src/lib/model/commerce-quotes.js +25 -5
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/plugin-permissions.d.ts +1 -1
- package/src/lib/model/plugin-permissions.js +10 -0
- package/src/lib/model/plugin-permissions.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +4 -0
- package/src/lib/model/product-modifiers.js +5 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/server/commerce-pdf.d.ts +1 -1
- package/src/lib/server/commerce-pdf.js +1 -1
- package/src/lib/server/commerce-pdf.js.map +1 -1
- package/src/lib/server/paid-media-delivery.js +1 -1
- package/src/lib/server/paid-media-delivery.js.map +1 -1
- package/src/lib/server/pos-kiosk.js +70 -15
- package/src/lib/server/pos-kiosk.js.map +1 -1
- package/src/lib/server/quote-email.js +29 -25
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-pay.js +6 -2
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proof-media.d.ts +63 -0
- package/src/lib/server/quote-proof-media.js +96 -0
- package/src/lib/server/quote-proof-media.js.map +1 -0
- package/src/lib/server/quote-proofs.js +17 -8
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote-uploads.d.ts +3 -1
- package/src/lib/server/quote-uploads.js +2 -1
- package/src/lib/server/quote-uploads.js.map +1 -1
- package/src/lib/server/quote.d.ts +3 -0
- package/src/lib/server/quote.js +127 -20
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/site-page-enricher.js +5 -1
- package/src/lib/server/site-page-enricher.js.map +1 -1
- package/src/lib/tenant-emails.js +16 -9
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/testing/fake-firestore.js +34 -5
- package/src/lib/testing/fake-firestore.js.map +1 -1
- package/src/lib/transfer/gift-cards.server.js +9 -11
- package/src/lib/transfer/gift-cards.server.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +75 -0
- package/src/lib/transfer/product-register-cells.js +487 -0
- package/src/lib/transfer/product-register-cells.js.map +1 -0
- package/src/lib/transfer/product-transfer.d.ts +12 -0
- package/src/lib/transfer/product-transfer.js +174 -10
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +24 -9
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/commerce-document-pdf.js +12 -9
- package/src/lib/utils/commerce-document-pdf.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +2 -0
- package/src/lib/utils/quote-email-content.js +20 -10
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/plugin-permissions.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\n\n/**\n * The register's finer permissions (AGL-4047), each a part of `managePos`\n * (Use the point of sale). Each REFINES it: never held without it, and,\n * where no custom role or override sets one, it follows `managePos` — so a\n * member keeps exactly the register they had until somebody narrows it.\n */\nexport type PosRegisterPermission =\n | 'posSell'\n | 'posRefund'\n | 'posDiscount'\n | 'posCashDrawer'\n | 'posDevices'\n\n/**\n * The register's keys and `posBuyHardware`, which stands on its own\n * (AGL-4047): it FOLLOWS `managePos` where no custom role or override sets\n * it, so every member keeps the hardware shop they had, but it may be\n * granted without the register — a bookkeeper who orders the store's readers\n * and never rings a sale.\n */\nexport type PosPermission = PosRegisterPermission | 'posBuyHardware'\n\n/** The tier defaults `managePos` has, which every finer key mirrors. */\nconst POS_TIER_DEFAULTS = { admin: true, editor: true, viewer: false } as const\n\n/*\n * The register is a site's own (AGL-4047): `managePos` and its five finer\n * keys are `narrowsPerSite`, so an editor of the whole workspace given Viewer\n * or Author access to one site does not work that site's register unless the\n * site grants it to them. `posBuyHardware` is not: the hardware shop spends\n * the workspace's money, and its verdict is the workspace's on every site.\n */\n\n/**\n * Commerce's plugin-declared permissions (AGL-435) — the reference\n * adopter. Pure data: the client barrel and /server entry both register\n * it, so console gating and API-side resolution agree.\n */\nexport const COMMERCE_PERMISSIONS: readonly PluginPermission[] = [\n {\n key: 'managePos',\n pluginId: 'commerce',\n label: 'Use the point of sale',\n description:\n 'Open the point of sale. Each point of sale permission below follows this one unless a role or member sets it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n },\n {\n key: 'posSell',\n pluginId: 'commerce',\n label: 'Sell at the register',\n description: 'Ring up sales and take payment at the register, the kiosk and the point of sale apps.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posRefund',\n pluginId: 'commerce',\n label: 'Refunds and returns',\n description: 'Refund point of sale orders at the register, up to its refund limit, and take returns and exchanges.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDiscount',\n pluginId: 'commerce',\n label: 'Give discounts at the register',\n description:\n 'Take a discount off a sale at the register. A shopper’s discount code and the store’s own promotions apply without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posCashDrawer',\n pluginId: 'commerce',\n label: 'Cash drawer and shifts',\n description: 'Open and close shifts, record cash in and out, print shift reports and open the drawer without a sale.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDevices',\n pluginId: 'commerce',\n label: 'Registers and devices',\n description: 'Add, change and remove card readers, receipt printers and customer displays, and set the reader screen.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posBuyHardware',\n pluginId: 'commerce',\n label: 'Buy point of sale hardware',\n description:\n 'Order card readers and other hardware from the hardware shop. Follows \"Use the point of sale\" unless a role or member sets it, and may be allowed without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n follows: 'managePos',\n },\n]\n\n/** One finer register key's label, for a refusal or a disabled control's reason. */\nexport function posPermissionLabel(permission: PosPermission): string {\n return COMMERCE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/**\n * Whether a resolved permission map allows one of the register's finer\n * actions (AGL-4047): `managePos`, and the finer key not refused. A map\n * that does not carry the finer key at all follows `managePos` — the\n * resolvers always carry it once commerce has registered, so an absent key\n * is a map built before that, which keeps the register it had.\n *\n * `posBuyHardware` stands on its own: its own verdict when the map carries\n * one, granted with or without `managePos`, and `managePos`'s when it does\n * not.\n */\nexport function holdsPosPermission(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n permission: PosPermission,\n): boolean {\n if (permission === 'posBuyHardware') {\n const own = permissions?.[permission]\n return typeof own === 'boolean' ? own : permissions?.['managePos'] === true\n }\n return permissions?.['managePos'] === true && permissions?.[permission] !== false\n}\n\n/**\n * Whether a member may open the hardware shop at all (AGL-4047): see what\n * it offers and what the store ordered. Whoever works the register, and\n * whoever may buy hardware without working it.\n */\nexport function mayVisitPosHardwareShop(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n): boolean {\n return permissions?.['managePos'] === true || holdsPosPermission(permissions, 'posBuyHardware')\n}\n\n/** The refusal a register route answers when a finer key is not held. */\nexport function posPermissionRefusal(permission: PosPermission): string {\n return `Your role does not include \"${posPermissionLabel(permission)}\" — ask an organization admin`\n}\n\n/*\n * RESERVATIONS (AGL-4047).\n *\n * A site's stays and what they book were decided by the member's role ON THE\n * SITE: Admin, Editor and Author could book a walk-in, change a stay's guests\n * and edit or cancel stays, and a Viewer could not (`canWriteHostContent` in\n * the rules, the same three roles at the routes). Those are now keys whose\n * preset is that site role (`presetFromSiteRole`), so every member keeps\n * exactly the access they had, and a custom role, a member's own permissions\n * or a site's toggle can grant or refuse either one: the window's staff can\n * be allowed walk-ins without editing anyone's booking.\n */\n\n/** The reservation keys. */\nexport type ReservationPermission = 'commerce.reservations' | 'commerce.walkIns'\n\n/** Commerce's keys whose preset is the site role (AGL-4047). */\nexport type CommerceSitePermission =\n | ReservationPermission\n | 'commerce.orders'\n | 'commerce.quotes'\n | 'commerce.quotes.send'\n | 'commerce.giftCards'\n | 'commerce.paymentMethods'\n | 'commerce.shippingConnections'\n\n/** Who held reservations on a site before they were keys: Admin, Editor and Author. */\nexport const RESERVATION_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: true,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nconst RESERVATION_ORG_ROLE_PRESET = { owner: true, admin: true, editor: true, viewer: false } as const\n\n/**\n * Who worked a site's orders and gift cards before they were keys: the site's\n * Admin and Editor (an Author edits the catalog and never touched an order).\n */\nexport const ORDERS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/**\n * Who changed a site's payment methods and its shipping app connections\n * before they were keys: the site's Admin alone (an Editor could see them, as\n * whoever works the orders still can).\n */\nexport const STORE_SETTINGS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: false,\n author: false,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nexport const STORE_SETTINGS_ORG_ROLE_PRESET = { owner: true, admin: true, editor: false, viewer: false } as const\n\n/**\n * The reservation keys as commerce declares them into the org permission\n * catalog (AGL-4047), registered beside `COMMERCE_PERMISSIONS`.\n */\nexport const COMMERCE_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'commerce.reservations',\n label: 'Manage reservations',\n description:\n 'Edit, cancel and check out stays, and add, change and remove what can be booked. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.walkIns',\n label: 'Book walk-ins and change guests',\n description:\n 'Book a walk-in stay and change how many guests a stay is for. Follows \"Manage reservations\" unless a role or member sets it, and may be allowed without it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n follows: 'commerce.reservations',\n },\n {\n key: 'commerce.orders',\n label: 'Manage orders',\n description:\n 'Fulfill, cancel and print orders, resend receipts, build draft orders, take returns and record shipments. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes',\n label: 'Create and edit quotes',\n description:\n 'Create, edit and delete quotes for customers. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes.send',\n label: 'Send quotes and invoices to customers',\n description:\n 'Copy a quote’s pay link to send to the customer, and replace it so the old link stops working. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.giftCards',\n label: 'Issue gift cards',\n description: 'Issue, adjust and void the store’s gift cards. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.paymentMethods',\n label: 'Manage payment methods',\n description:\n 'Turn the store’s payment methods on and off. Anyone with \"Manage orders\" sees them. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.shippingConnections',\n label: 'Connect shipping apps',\n description:\n 'Connect, sync and disconnect ShipStation and ShippingEasy, and show or replace their credentials. Anyone with \"Manage orders\" sees whether they are connected. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a door answers when a commerce site key is not held: names the permission. */\nexport function commerceSitePermissionRefusal(key: CommerceSitePermission): string {\n const label = COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === key)?.label ?? key\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/** One reservation key's label, for a refusal. */\nexport function reservationPermissionLabel(permission: ReservationPermission): string {\n return COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/** The refusal a reservation route answers when its key is not held; names the permission, never a role. */\nexport function reservationPermissionRefusal(permission: ReservationPermission): string {\n return commerceSitePermissionRefusal(permission)\n}\n"],"names":["POS_TIER_DEFAULTS","admin","editor","viewer","COMMERCE_PERMISSIONS","key","pluginId","label","description","defaults","groupLabel","narrowsPerSite","refines","follows","posPermissionLabel","permission","find","entry","holdsPosPermission","permissions","own","mayVisitPosHardwareShop","posPermissionRefusal","RESERVATION_SITE_ROLE_PRESET","author","RESERVATION_ORG_ROLE_PRESET","owner","ORDERS_SITE_ROLE_PRESET","STORE_SETTINGS_SITE_ROLE_PRESET","STORE_SETTINGS_ORG_ROLE_PRESET","COMMERCE_SITE_PERMISSIONS","roleDefaults","hostRoleDefaults","group","presetFromSiteRole","commerceSitePermissionRefusal","reservationPermissionLabel","reservationPermissionRefusal"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AA4BD,sEAAsE,GACtE,MAAMA,oBAAoB;IAAEC,OAAO;IAAMC,QAAQ;IAAMC,QAAQ;AAAM;AAErE;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,uBAAoD;IAC/D;QACEC,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;IAClB;IACA;QACEN,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAA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,aAAKL;QACvBM,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;IACA;QACE7B,KAAK;QACLE,OAAO;QACPC,aAAa;QACbuB,cAAc,aAAKN;QACnBO,kBAAkB,aAAKL;QACvBM,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;IACA;QACE7B,KAAK;QACLE,OAAO;QACPC,aACE;QACFuB,cAAc,aAAKF;QACnBG,kBAAkB,aAAKJ;QACvBK,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;IACA;QACE7B,KAAK;QACLE,OAAO;QACPC,aACE;QACFuB,cAAc,aAAKF;QACnBG,kBAAkB,aAAKJ;QACvBK,OAAO;QACPvB,YAAY;QACZwB,oBAAoB;IACtB;CACD,CAAA;AAED,2FAA2F,GAC3F,OAAO,SAASC,8BAA8B9B,GAA2B;;QACzDyB;IAAd,MAAMvB,iBAAQuB,kCAAAA,0BAA0Bd,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKA,yBAAxDyB,gCAA8DvB,KAAK,mBAAIF;IACrF,OAAO,CAAC,4BAA4B,EAAEE,MAAM,6BAA6B,CAAC;AAC5E;AAEA,gDAAgD,GAChD,OAAO,SAAS6B,2BAA2BrB,UAAiC;;QACnEe;IAAP,gBAAOA,kCAAAA,0BAA0Bd,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKU,gCAAxDe,gCAAqEvB,KAAK,mBAAIQ;AACvF;AAEA,0GAA0G,GAC1G,OAAO,SAASsB,6BAA6BtB,UAAiC;IAC5E,OAAOoB,8BAA8BpB;AACvC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/plugin-permissions.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\n\n/**\n * The register's finer permissions (AGL-4047), each a part of `managePos`\n * (Use the point of sale). Each REFINES it: never held without it, and,\n * where no custom role or override sets one, it follows `managePos` — so a\n * member keeps exactly the register they had until somebody narrows it.\n */\nexport type PosRegisterPermission =\n | 'posSell'\n | 'posRefund'\n | 'posDiscount'\n | 'posCashDrawer'\n | 'posDevices'\n\n/**\n * The register's keys and `posBuyHardware`, which stands on its own\n * (AGL-4047): it FOLLOWS `managePos` where no custom role or override sets\n * it, so every member keeps the hardware shop they had, but it may be\n * granted without the register — a bookkeeper who orders the store's readers\n * and never rings a sale.\n */\nexport type PosPermission = PosRegisterPermission | 'posBuyHardware'\n\n/** The tier defaults `managePos` has, which every finer key mirrors. */\nconst POS_TIER_DEFAULTS = { admin: true, editor: true, viewer: false } as const\n\n/*\n * The register is a site's own (AGL-4047): `managePos` and its five finer\n * keys are `narrowsPerSite`, so an editor of the whole workspace given Viewer\n * or Author access to one site does not work that site's register unless the\n * site grants it to them. `posBuyHardware` is not: the hardware shop spends\n * the workspace's money, and its verdict is the workspace's on every site.\n */\n\n/**\n * Commerce's plugin-declared permissions (AGL-435) — the reference\n * adopter. Pure data: the client barrel and /server entry both register\n * it, so console gating and API-side resolution agree.\n */\nexport const COMMERCE_PERMISSIONS: readonly PluginPermission[] = [\n {\n key: 'managePos',\n pluginId: 'commerce',\n label: 'Use the point of sale',\n description:\n 'Open the point of sale. Each point of sale permission below follows this one unless a role or member sets it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n },\n {\n key: 'posSell',\n pluginId: 'commerce',\n label: 'Sell at the register',\n description: 'Ring up sales and take payment at the register, the kiosk and the point of sale apps.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posRefund',\n pluginId: 'commerce',\n label: 'Refunds and returns',\n description: 'Refund point of sale orders at the register, up to its refund limit, and take returns and exchanges.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDiscount',\n pluginId: 'commerce',\n label: 'Give discounts at the register',\n description:\n 'Take a discount off a sale at the register. A shopper’s discount code and the store’s own promotions apply without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posCashDrawer',\n pluginId: 'commerce',\n label: 'Cash drawer and shifts',\n description: 'Open and close shifts, record cash in and out, print shift reports and open the drawer without a sale.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posDevices',\n pluginId: 'commerce',\n label: 'Registers and devices',\n description: 'Add, change and remove card readers, receipt printers and customer displays, and set the reader screen.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n narrowsPerSite: true,\n refines: 'managePos',\n },\n {\n key: 'posBuyHardware',\n pluginId: 'commerce',\n label: 'Buy point of sale hardware',\n description:\n 'Order card readers and other hardware from the hardware shop. Follows \"Use the point of sale\" unless a role or member sets it, and may be allowed without it.',\n defaults: { ...POS_TIER_DEFAULTS },\n groupLabel: 'Commerce',\n follows: 'managePos',\n },\n]\n\n/** One finer register key's label, for a refusal or a disabled control's reason. */\nexport function posPermissionLabel(permission: PosPermission): string {\n return COMMERCE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/**\n * Whether a resolved permission map allows one of the register's finer\n * actions (AGL-4047): `managePos`, and the finer key not refused. A map\n * that does not carry the finer key at all follows `managePos` — the\n * resolvers always carry it once commerce has registered, so an absent key\n * is a map built before that, which keeps the register it had.\n *\n * `posBuyHardware` stands on its own: its own verdict when the map carries\n * one, granted with or without `managePos`, and `managePos`'s when it does\n * not.\n */\nexport function holdsPosPermission(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n permission: PosPermission,\n): boolean {\n if (permission === 'posBuyHardware') {\n const own = permissions?.[permission]\n return typeof own === 'boolean' ? own : permissions?.['managePos'] === true\n }\n return permissions?.['managePos'] === true && permissions?.[permission] !== false\n}\n\n/**\n * Whether a member may open the hardware shop at all (AGL-4047): see what\n * it offers and what the store ordered. Whoever works the register, and\n * whoever may buy hardware without working it.\n */\nexport function mayVisitPosHardwareShop(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n): boolean {\n return permissions?.['managePos'] === true || holdsPosPermission(permissions, 'posBuyHardware')\n}\n\n/** The refusal a register route answers when a finer key is not held. */\nexport function posPermissionRefusal(permission: PosPermission): string {\n return `Your role does not include \"${posPermissionLabel(permission)}\" — ask an organization admin`\n}\n\n/*\n * RESERVATIONS (AGL-4047).\n *\n * A site's stays and what they book were decided by the member's role ON THE\n * SITE: Admin, Editor and Author could book a walk-in, change a stay's guests\n * and edit or cancel stays, and a Viewer could not (`canWriteHostContent` in\n * the rules, the same three roles at the routes). Those are now keys whose\n * preset is that site role (`presetFromSiteRole`), so every member keeps\n * exactly the access they had, and a custom role, a member's own permissions\n * or a site's toggle can grant or refuse either one: the window's staff can\n * be allowed walk-ins without editing anyone's booking.\n */\n\n/** The reservation keys. */\nexport type ReservationPermission = 'commerce.reservations' | 'commerce.walkIns'\n\n/** Commerce's keys whose preset is the site role (AGL-4047). */\nexport type CommerceSitePermission =\n | ReservationPermission\n | 'commerce.orders'\n | 'commerce.quotes'\n | 'commerce.quotes.send'\n | 'commerce.giftCards'\n | 'commerce.giftCards.import'\n | 'commerce.paymentMethods'\n | 'commerce.shippingConnections'\n\n/** Who held reservations on a site before they were keys: Admin, Editor and Author. */\nexport const RESERVATION_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: true,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nconst RESERVATION_ORG_ROLE_PRESET = { owner: true, admin: true, editor: true, viewer: false } as const\n\n/**\n * Who worked a site's orders and gift cards before they were keys: the site's\n * Admin and Editor (an Author edits the catalog and never touched an order).\n */\nexport const ORDERS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: true,\n author: false,\n viewer: false,\n}\n\n/**\n * Who changed a site's payment methods and its shipping app connections\n * before they were keys: the site's Admin alone (an Editor could see them, as\n * whoever works the orders still can).\n */\nexport const STORE_SETTINGS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> = {\n admin: true,\n editor: false,\n author: false,\n viewer: false,\n}\n\n/** The same, per workspace role: the answer with no site named. */\nexport const STORE_SETTINGS_ORG_ROLE_PRESET = { owner: true, admin: true, editor: false, viewer: false } as const\n\n/**\n * The reservation keys as commerce declares them into the org permission\n * catalog (AGL-4047), registered beside `COMMERCE_PERMISSIONS`.\n */\nexport const COMMERCE_SITE_PERMISSIONS: readonly PluginOrgPermissionDeclaration[] = [\n {\n key: 'commerce.reservations',\n label: 'Manage reservations',\n description:\n 'Edit, cancel and check out stays, and add, change and remove what can be booked. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.walkIns',\n label: 'Book walk-ins and change guests',\n description:\n 'Book a walk-in stay and change how many guests a stay is for. Follows \"Manage reservations\" unless a role or member sets it, and may be allowed without it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...RESERVATION_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n follows: 'commerce.reservations',\n },\n {\n key: 'commerce.orders',\n label: 'Manage orders',\n description:\n 'Fulfill, cancel and print orders, resend receipts, build draft orders, take returns and record shipments. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes',\n label: 'Create and edit quotes',\n description:\n 'Create, edit and delete quotes for customers. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.quotes.send',\n label: 'Send quotes and invoices to customers',\n description:\n 'Copy a quote’s pay link to send to the customer, and replace it so the old link stops working. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.giftCards',\n label: 'Issue gift cards',\n description: 'Issue, adjust and void the store’s gift cards. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...RESERVATION_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...ORDERS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.giftCards.import',\n label: 'Import gift cards',\n description:\n 'Import gift cards from a file, which issues each one as spendable money. Also takes \"Manage data\". Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.paymentMethods',\n label: 'Manage payment methods',\n description:\n 'Turn the store’s payment methods on and off. Anyone with \"Manage orders\" sees them. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n {\n key: 'commerce.shippingConnections',\n label: 'Connect shipping apps',\n description:\n 'Connect, sync and disconnect ShipStation and ShippingEasy, and show or replace their credentials. Anyone with \"Manage orders\" sees whether they are connected. Follows the site role unless a role or member sets it.',\n roleDefaults: { ...STORE_SETTINGS_ORG_ROLE_PRESET },\n hostRoleDefaults: { ...STORE_SETTINGS_SITE_ROLE_PRESET },\n group: 'commerce',\n groupLabel: 'Commerce',\n presetFromSiteRole: true,\n },\n]\n\n/** The refusal a door answers when a commerce site key is not held: names the permission. */\nexport function commerceSitePermissionRefusal(key: CommerceSitePermission): string {\n const label = COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === key)?.label ?? key\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/** One reservation key's label, for a refusal. */\nexport function reservationPermissionLabel(permission: ReservationPermission): string {\n return COMMERCE_SITE_PERMISSIONS.find((entry) => entry.key === permission)?.label ?? permission\n}\n\n/** The refusal a reservation route answers when its key is not held; names the permission, never a role. */\nexport function reservationPermissionRefusal(permission: ReservationPermission): string {\n return commerceSitePermissionRefusal(permission)\n}\n"],"names":["POS_TIER_DEFAULTS","admin","editor","viewer","COMMERCE_PERMISSIONS","key","pluginId","label","description","defaults","groupLabel","narrowsPerSite","refines","follows","posPermissionLabel","permission","find","entry","holdsPosPermission","permissions","own","mayVisitPosHardwareShop","posPermissionRefusal","RESERVATION_SITE_ROLE_PRESET","author","RESERVATION_ORG_ROLE_PRESET","owner","ORDERS_SITE_ROLE_PRESET","STORE_SETTINGS_SITE_ROLE_PRESET","STORE_SETTINGS_ORG_ROLE_PRESET","COMMERCE_SITE_PERMISSIONS","roleDefaults","hostRoleDefaults","group","presetFromSiteRole","commerceSitePermissionRefusal","reservationPermissionLabel","reservationPermissionRefusal"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AA4BD,sEAAsE,GACtE,MAAMA,oBAAoB;IAAEC,OAAO;IAAMC,QAAQ;IAAMC,QAAQ;AAAM;AAErE;;;;;;CAMC,GAED;;;;CAIC,GACD,OAAO,MAAMC,uBAAoD;IAC/D;QACEC,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;IAClB;IACA;QACEN,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aAAa;QACbC,UAAU,aAAKT;QACfU,YAAY;QACZC,gBAAgB;QAChBC,SAAS;IACX;IACA;QACEP,KAAK;QACLC,UAAU;QACVC,OAAO;QACPC,aACE;QACFC,UAAU,aAAKT;QACfU,YAAY;QACZG,SAAS;IACX;CACD,CAAA;AAED,kFAAkF,GAClF,OAAO,SAASC,mBAAmBC,UAAyB;;QACnDX;IAAP,gBAAOA,6BAAAA,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B,oBAAoB;IACtB;CACD,CAAA;AAED,2FAA2F,GAC3F,OAAO,SAASC,8BAA8B9B,GAA2B;;QACzDyB;IAAd,MAAMvB,iBAAQuB,kCAAAA,0BAA0Bd,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKA,yBAAxDyB,gCAA8DvB,KAAK,mBAAIF;IACrF,OAAO,CAAC,4BAA4B,EAAEE,MAAM,6BAA6B,CAAC;AAC5E;AAEA,gDAAgD,GAChD,OAAO,SAAS6B,2BAA2BrB,UAAiC;;QACnEe;IAAP,gBAAOA,kCAAAA,0BAA0Bd,IAAI,CAAC,CAACC,QAAUA,MAAMZ,GAAG,KAAKU,gCAAxDe,gCAAqEvB,KAAK,mBAAIQ;AACvF;AAEA,0GAA0G,GAC1G,OAAO,SAASsB,6BAA6BtB,UAAiC;IAC5E,OAAOoB,8BAA8BpB;AACvC"}
|
|
@@ -63,6 +63,10 @@ export declare const POS_MAX_MODIFIER_OPTIONS = 20;
|
|
|
63
63
|
export declare const POS_MAX_MODIFIER_PRICE_CENTS = 100000;
|
|
64
64
|
/** Why a product's modifier groups cannot be saved, or null when they can. */
|
|
65
65
|
export declare function modifierGroupsProblem(groups: unknown): string | null;
|
|
66
|
+
/** How a variant is named in a choice's price list, in the editor and in an import file. */
|
|
67
|
+
export declare function variantPriceLabel(variant: {
|
|
68
|
+
options?: Record<string, string>;
|
|
69
|
+
}): string;
|
|
66
70
|
/** The product's groups, or none when they are missing or malformed. */
|
|
67
71
|
export declare function productModifierGroups(product: {
|
|
68
72
|
modifierGroups?: unknown;
|
|
@@ -88,6 +88,11 @@ function modifierPriceIsValid(price) {
|
|
|
88
88
|
}
|
|
89
89
|
return null;
|
|
90
90
|
}
|
|
91
|
+
/** How a variant is named in a choice's price list, in the editor and in an import file. */ export function variantPriceLabel(variant) {
|
|
92
|
+
var _variant_options;
|
|
93
|
+
const values = Object.values((_variant_options = variant.options) != null ? _variant_options : {}).filter(Boolean);
|
|
94
|
+
return values.length ? values.join(' / ') : 'Default';
|
|
95
|
+
}
|
|
91
96
|
/** The product's groups, or none when they are missing or malformed. */ export function productModifierGroups(product) {
|
|
92
97
|
const groups = product == null ? void 0 : product.modifierGroups;
|
|
93
98
|
if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return [];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-modifiers.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 * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any) => ({\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }))\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n for (const option of group.options) {\n if (picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id)) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly Pick<OrderLineModifier, 'groupId' | 'optionId'>[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({ groupId: modifier.groupId, optionId: modifier.optionId }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n return JSON.stringify(selection.map((pick) => [pick.groupId, pick.optionId]))\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId]) => ({ groupId, optionId }))\n } catch {\n return []\n }\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(\n variantLabel: string | undefined,\n modifiers: readonly Pick<OrderLineModifier, 'name'>[],\n): string {\n const added = modifiers.map((modifier) => modifier.name).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => `${pick.groupId}:${pick.optionId}`)\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","modifierPriceIsValid","price","Number","isInteger","modifierGroupsProblem","groups","Array","isArray","length","groupIds","Set","group","id","has","add","String","name","trim","options","optionIds","option","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","min","max","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","filter","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","raw","slice","map","entry","groupId","optionId","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","pick","key","find","chosen","toLowerCase","push","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","cartLineModifierProblem","reason","test","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","lineLabelWithModifiers","variantLabel","added","join","Boolean","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,mFAAmF,GA+CnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,yEAAyE,GACzE,OAAO,MAAMC,+BAA+B,OAAO;AAEnD,SAASC,qBAAqBC,KAAc;IAC1C,OACE,OAAOA,UAAU,YACjBC,OAAOC,SAAS,CAACF,UACjBA,SAAS,KACTA,SAASF;AAEb;AAEA,4EAA4E,GAC5E,OAAO,SAASK,sBAAsBC,MAAe;IACnD,IAAIA,UAAU,MAAM,OAAO;IAC3B,IAAI,CAACC,MAAMC,OAAO,CAACF,SAAS,OAAO;IACnC,IAAIA,OAAOG,MAAM,GAAGX,yBAAyB;QAC3C,OAAO,CAAC,QAAQ,EAAEA,wBAAwB,4BAA4B,CAAC;IACzE;IACA,MAAMY,WAAW,IAAIC;IACrB,KAAK,MAAMC,SAASN,OAAkC;YAGxCM;QAFZ,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AE,OAAO;IAC/B,OAAOkE,KAAKC,SAAS,CAACF,UAAU5B,GAAG,CAAC,CAACY,OAAS;YAACA,KAAKV,OAAO;YAAEU,KAAKT,QAAQ;SAAC;AAC7E;AAEA,qFAAqF,GACrF,OAAO,SAAS4B,wBAAwBC,KAAc;IACpD,IAAI,OAAOA,UAAU,YAAY,CAACA,OAAO,OAAO,EAAE;IAClD,IAAI;QACF,MAAMC,SAAkBJ,KAAKK,KAAK,CAACF;QACnC,IAAI,CAACvE,MAAMC,OAAO,CAACuE,SAAS,OAAO,EAAE;QACrC,OAAOA,OACJ1C,MAAM,CACL,CAAC4C,OACC1E,MAAMC,OAAO,CAACyE,SAAS,OAAOA,IAAI,CAAC,EAAE,KAAK,YAAY,OAAOA,IAAI,CAAC,EAAE,KAAK,UAE5EpC,KAAK,CAAC,GAAG/C,0BAA0BC,0BACnC+C,GAAG,CAAC,CAAC,CAACE,SAASC,SAAS,GAAM,CAAA;gBAAED;gBAASC;YAAS,CAAA;IACvD,EAAE,eAAM;QACN,OAAO,EAAE;IACX;AACF;AAEA,+FAA+F,GAC/F,OAAO,SAASiC,uBACdC,YAAgC,EAChC7B,SAAqD;IAErD,MAAM8B,QAAQ9B,UAAUR,GAAG,CAAC,CAACoB,WAAaA,SAASjD,IAAI,EAAEoE,IAAI,CAAC;IAC9D,OAAO;QAACF;QAAcC;KAAM,CAAC/C,MAAM,CAACiD,SAASD,IAAI,CAAC;AACpD;AAEA,4EAA4E,GAC5E,OAAO,SAASE,qBAAqBb,SAAmD;IACtF,OAAO;WAAKA,oBAAAA,YAAa,EAAE;KAAE,CAC1B5B,GAAG,CAAC,CAACY,OAAS,GAAGA,KAAKV,OAAO,CAAC,CAAC,EAAEU,KAAKT,QAAQ,EAAE,EAChDuC,IAAI,GACJH,IAAI,CAAC;AACV"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/product-modifiers.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 * REGISTER MODIFIERS AND QUICK KEYS (AGL-3607).\n *\n * A modifier is a choice added to an item as it is rung up — \"Oat milk\",\n * \"Extra shot +$0.75\", \"No onions\" — that is not a stocked variant. Groups\n * live on the product (`modifierGroups`); the register sends the chosen\n * option ids with each line and the SERVER prices them from the product\n * document, so a register never names what a modifier costs.\n *\n * A chosen modifier is folded into the line's `variantLabel` as well as kept\n * structured in `modifiers`: every receipt, email, order view and export\n * already prints the label, so the choice reaches all of them without each\n * learning a new field.\n *\n * ADD-ONS ON THE WEBSITE (AGL-4100). A group switched to \"Show on the\n * website\" (`online`) is offered on the product's page too, and a cart line,\n * Buy now and the order carry its picks the same way: ids from the shopper,\n * prices from the product. A choice may cost more on one variant than\n * another (`priceCentsByVariant`), which is how one page sells a canopy whose\n * walls cost more at a larger size without a variant for every combination.\n *=========================================*/\n\n/** One choice in a modifier group. `priceCents` is added to the item, 0 for free. */\nexport interface ProductModifierOption {\n id: string\n name: string\n priceCents: number\n /**\n * What the choice adds on one variant, keyed by variant id (AGL-4100):\n * walls cost more on a larger canopy. A variant not listed pays\n * `priceCents`. Read through {@link modifierOptionPriceCents}.\n */\n priceCentsByVariant?: Record<string, number>\n}\n\n/**\n * A set of choices offered together (\"Milk\", \"Add-ons\"). `min` of 1 or more\n * makes it required; `max` caps how many can be picked (1 = pick one).\n */\nexport interface ProductModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: ProductModifierOption[]\n /**\n * Offered on the product's page on the website as well as at the register\n * (AGL-4100), \"Show on the website\". Absent reads as register only, so a\n * group made before the switch changes nothing on a live store; the\n * console makes new groups with it on.\n */\n online?: boolean\n}\n\n/** A modifier as the order line keeps it: names and price as sold. */\nexport interface OrderLineModifier {\n groupId: string\n optionId: string\n group: string\n name: string\n priceCents: number\n}\n\n/** What the register sends for a line: the option ids it picked, nothing priced. */\nexport interface ModifierSelection {\n groupId: string\n optionId: string\n}\n\nexport const POS_MAX_MODIFIER_GROUPS = 10\nexport const POS_MAX_MODIFIER_OPTIONS = 20\n/** $1,000 on one modifier: anything larger is a product, not an add-on. */\nexport const POS_MAX_MODIFIER_PRICE_CENTS = 100_000\n\nfunction modifierPriceIsValid(price: unknown): boolean {\n return (\n typeof price === 'number' &&\n Number.isInteger(price) &&\n price >= 0 &&\n price <= POS_MAX_MODIFIER_PRICE_CENTS\n )\n}\n\n/** Why a product's modifier groups cannot be saved, or null when they can. */\nexport function modifierGroupsProblem(groups: unknown): string | null {\n if (groups == null) return null\n if (!Array.isArray(groups)) return 'Modifiers must be a list'\n if (groups.length > POS_MAX_MODIFIER_GROUPS) {\n return `At most ${POS_MAX_MODIFIER_GROUPS} modifier groups per product`\n }\n const groupIds = new Set<string>()\n for (const group of groups as ProductModifierGroup[]) {\n if (!group?.id || groupIds.has(group.id)) return 'Modifier groups need unique ids'\n groupIds.add(group.id)\n if (!String(group.name ?? '').trim()) return 'Name every modifier group'\n const options = Array.isArray(group.options) ? group.options : []\n if (options.length === 0) return `Add a choice to “${group.name}”`\n if (options.length > POS_MAX_MODIFIER_OPTIONS) {\n return `“${group.name}” has more than ${POS_MAX_MODIFIER_OPTIONS} choices`\n }\n const optionIds = new Set<string>()\n for (const option of options) {\n if (!option?.id || optionIds.has(option.id)) return 'Modifier choices need unique ids'\n optionIds.add(option.id)\n if (!String(option.name ?? '').trim()) return `Name every choice in “${group.name}”`\n const price = option.priceCents\n if (!modifierPriceIsValid(price)) {\n return `“${option.name}” needs a price of $0 to $1,000`\n }\n const byVariant = option.priceCentsByVariant\n if (byVariant != null) {\n if (typeof byVariant !== 'object' || Array.isArray(byVariant)) {\n return `“${option.name}” has prices that are not a list by option`\n }\n if (Object.values(byVariant).some((cents) => !modifierPriceIsValid(cents))) {\n return `“${option.name}” needs a price of $0 to $1,000 for each option it is priced by`\n }\n }\n }\n if (group.online != null && typeof group.online !== 'boolean') {\n return `“${group.name}” is shown on the website or not`\n }\n const { min, max } = group\n if (!Number.isInteger(min) || min < 0) return `“${group.name}” needs a minimum of 0 or more`\n if (!Number.isInteger(max) || max < 1 || max > options.length) {\n return `“${group.name}” allows 1 to ${options.length} choices`\n }\n if (min > max) return `“${group.name}” requires more choices than it allows`\n }\n return null\n}\n\n/** How a variant is named in a choice's price list, in the editor and in an import file. */\nexport function variantPriceLabel(variant: { options?: Record<string, string> }): string {\n const values = Object.values(variant.options ?? {}).filter(Boolean)\n return values.length ? values.join(' / ') : 'Default'\n}\n\n/** The product's groups, or none when they are missing or malformed. */\nexport function productModifierGroups(product: {\n modifierGroups?: unknown\n}): ProductModifierGroup[] {\n const groups = product?.modifierGroups\n if (!Array.isArray(groups) || modifierGroupsProblem(groups)) return []\n return groups as ProductModifierGroup[]\n}\n\n/** Whether a group must be answered before the item can be added. */\nexport function modifierGroupRequired(group: ProductModifierGroup): boolean {\n return group.min > 0\n}\n\n/**\n * The groups the product's page on the website offers (AGL-4100): those\n * switched to \"Show on the website\". A register-only group is never sent to\n * a shopper, never asked of one and never priced on an online order.\n */\nexport function websiteModifierGroups(product: { modifierGroups?: unknown }): ProductModifierGroup[] {\n return productModifierGroups(product).filter((group) => group.online === true)\n}\n\n/** Whether the website must ask a shopper a choice before the item goes in a cart. */\nexport function websiteModifiersRequired(product: { modifierGroups?: unknown }): boolean {\n return websiteModifierGroups(product).some(modifierGroupRequired)\n}\n\n/**\n * What one choice adds to one unit of the picked variant (AGL-4100): its\n * price on that variant where it has one, else its own price.\n */\nexport function modifierOptionPriceCents(\n option: Pick<ProductModifierOption, 'priceCents' | 'priceCentsByVariant'>,\n variantId?: string | null,\n): number {\n const byVariant = variantId ? option.priceCentsByVariant?.[variantId] : undefined\n return typeof byVariant === 'number' && Number.isFinite(byVariant) ? byVariant : option.priceCents\n}\n\n/** A line's chosen modifiers, priced. */\nexport interface ResolvedLineModifiers {\n ok: boolean\n /** The chosen modifiers, in group order; empty when not `ok`. */\n modifiers: OrderLineModifier[]\n /** What they add to one unit, in cents. */\n extraCents: number\n /** What to fix, when not `ok`. */\n error?: string\n}\n\n/** The picks a request names, as ids only, bounded; nothing for a value that is not a list. */\nexport function modifierSelectionFrom(raw: unknown): ModifierSelection[] {\n return (Array.isArray(raw) ? raw : [])\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map((entry: any) => ({\n groupId: String(entry?.groupId ?? ''),\n optionId: String(entry?.optionId ?? ''),\n }))\n}\n\n/**\n * Prices a line's chosen modifiers from the PRODUCT, in group order, and\n * checks every group's minimum and maximum. Unknown ids, a repeated choice\n * and a group answered past its maximum are refused with what to fix.\n *\n * `variantId` is the variant the line sells (AGL-4100): a choice priced by\n * variant adds its price on that one. Without it every choice adds its own\n * `priceCents`, as it always did.\n */\nexport function resolveLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n const refuse = (error: string): ResolvedLineModifiers => ({\n ok: false,\n modifiers: [],\n extraCents: 0,\n error,\n })\n const groups = productModifierGroups(product)\n const picks = modifierSelectionFrom(raw)\n const seen = new Set<string>()\n for (const pick of picks) {\n const key = `${pick.groupId}:${pick.optionId}`\n if (seen.has(key)) return refuse(`A choice on ${product.name} was picked twice.`)\n seen.add(key)\n const group = groups.find((entry) => entry.id === pick.groupId)\n if (!group || !group.options.some((option) => option.id === pick.optionId)) {\n return refuse(`A choice on ${product.name} is no longer offered. Remove it and add it again.`)\n }\n }\n const modifiers: OrderLineModifier[] = []\n for (const group of groups) {\n const chosen = group.options.filter((option) =>\n picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id),\n )\n if (chosen.length < group.min) {\n return refuse(`Choose ${group.name.toLowerCase()} for ${product.name}.`)\n }\n if (chosen.length > group.max) {\n return refuse(`Choose at most ${group.max} for ${group.name.toLowerCase()} on ${product.name}.`)\n }\n for (const option of chosen) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n return {\n ok: true,\n modifiers,\n extraCents: modifiers.reduce((sum, modifier) => sum + modifier.priceCents, 0),\n }\n}\n\n/**\n * {@link resolveLineModifiers} for a sale made online (AGL-4100): only the\n * groups shown on the website are offered, asked or priced. A register-only\n * group, required or not, is not the shopper's to answer.\n */\nexport function resolveWebsiteLineModifiers(\n product: { name?: string; modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): ResolvedLineModifiers {\n return resolveLineModifiers(\n { name: product.name, modifierGroups: websiteModifierGroups(product) },\n raw,\n variantId,\n )\n}\n\n/**\n * The modifiers a PAID line names, for its order record (AGL-4100): every\n * pick the product still offers, in group order, priced as it is now, with no\n * minimum or maximum asked. The money was taken when the sale was priced;\n * a choice the merchant removed since is left off the record, never a reason\n * to lose the order.\n */\nexport function soldLineModifiers(\n product: { modifierGroups?: unknown },\n raw: unknown,\n variantId?: string | null,\n): OrderLineModifier[] {\n const picks = modifierSelectionFrom(raw)\n const modifiers: OrderLineModifier[] = []\n for (const group of productModifierGroups(product)) {\n for (const option of group.options) {\n if (picks.some((pick) => pick.groupId === group.id && pick.optionId === option.id)) {\n modifiers.push({\n groupId: group.id,\n optionId: option.id,\n group: group.name,\n name: option.name,\n priceCents: modifierOptionPriceCents(option, variantId),\n })\n }\n }\n }\n return modifiers\n}\n\n/**\n * What a shopper is told about a cart line whose add-ons no longer answer\n * the product (AGL-4100): the resolver's reason, and how to put it right.\n */\nexport function cartLineModifierProblem(error: string | undefined): string {\n const reason = String(error ?? '').trim() || 'The choices on this item have changed.'\n return /Remove it and add it again/.test(reason)\n ? reason\n : `${reason} Remove it and add it again from its page.`\n}\n\n/** The picks a priced line keeps: ids only, in the product's group order. */\nexport function modifierSelectionOf(\n modifiers: readonly Pick<OrderLineModifier, 'groupId' | 'optionId'>[],\n): ModifierSelection[] {\n return modifiers.map((modifier) => ({ groupId: modifier.groupId, optionId: modifier.optionId }))\n}\n\n/**\n * The picks as one metadata value (AGL-4100), for a payment processor that\n * holds strings only: `[[\"group\",\"option\"],…]`. Empty for no picks.\n */\nexport function encodeModifierSelection(selection: readonly ModifierSelection[] | undefined): string {\n if (!selection?.length) return ''\n return JSON.stringify(selection.map((pick) => [pick.groupId, pick.optionId]))\n}\n\n/** {@link encodeModifierSelection} read back; nothing for a value it did not write. */\nexport function decodeModifierSelection(value: unknown): ModifierSelection[] {\n if (typeof value !== 'string' || !value) return []\n try {\n const parsed: unknown = JSON.parse(value)\n if (!Array.isArray(parsed)) return []\n return parsed\n .filter(\n (pair): pair is [string, string] =>\n Array.isArray(pair) && typeof pair[0] === 'string' && typeof pair[1] === 'string',\n )\n .slice(0, POS_MAX_MODIFIER_GROUPS * POS_MAX_MODIFIER_OPTIONS)\n .map(([groupId, optionId]) => ({ groupId, optionId }))\n } catch {\n return []\n }\n}\n\n/** The label a line prints: the variant, then each modifier (`Large / Oat milk, Extra shot`). */\nexport function lineLabelWithModifiers(\n variantLabel: string | undefined,\n modifiers: readonly Pick<OrderLineModifier, 'name'>[],\n): string {\n const added = modifiers.map((modifier) => modifier.name).join(', ')\n return [variantLabel, added].filter(Boolean).join(' / ')\n}\n\n/** Two lines merge only when they are the same item with the same choices. */\nexport function modifierSelectionKey(selection: readonly ModifierSelection[] | undefined): string {\n return [...(selection ?? [])]\n .map((pick) => `${pick.groupId}:${pick.optionId}`)\n .sort()\n .join('|')\n}\n"],"names":["POS_MAX_MODIFIER_GROUPS","POS_MAX_MODIFIER_OPTIONS","POS_MAX_MODIFIER_PRICE_CENTS","modifierPriceIsValid","price","Number","isInteger","modifierGroupsProblem","groups","Array","isArray","length","groupIds","Set","group","id","has","add","String","name","trim","options","optionIds","option","priceCents","byVariant","priceCentsByVariant","Object","values","some","cents","online","min","max","variantPriceLabel","variant","filter","Boolean","join","productModifierGroups","product","modifierGroups","modifierGroupRequired","websiteModifierGroups","websiteModifiersRequired","modifierOptionPriceCents","variantId","undefined","isFinite","modifierSelectionFrom","raw","slice","map","entry","groupId","optionId","resolveLineModifiers","refuse","error","ok","modifiers","extraCents","picks","seen","pick","key","find","chosen","toLowerCase","push","reduce","sum","modifier","resolveWebsiteLineModifiers","soldLineModifiers","cartLineModifierProblem","reason","test","modifierSelectionOf","encodeModifierSelection","selection","JSON","stringify","decodeModifierSelection","value","parsed","parse","pair","lineLabelWithModifiers","variantLabel","added","modifierSelectionKey","sort"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;2CAoB2C,GAE3C,mFAAmF,GA+CnF,OAAO,MAAMA,0BAA0B,GAAE;AACzC,OAAO,MAAMC,2BAA2B,GAAE;AAC1C,yEAAyE,GACzE,OAAO,MAAMC,+BAA+B,OAAO;AAEnD,SAASC,qBAAqBC,KAAc;IAC1C,OACE,OAAOA,UAAU,YACjBC,OAAOC,SAAS,CAACF,UACjBA,SAAS,KACTA,SAASF;AAEb;AAEA,4EAA4E,GAC5E,OAAO,SAASK,sBAAsBC,MAAe;IACnD,IAAIA,UAAU,MAAM,OAAO;IAC3B,IAAI,CAACC,MAAMC,OAAO,CAACF,SAAS,OAAO;IACnC,IAAIA,OAAOG,MAAM,GAAGX,yBAAyB;QAC3C,OAAO,CAAC,QAAQ,EAAEA,wBAAwB,4BAA4B,CAAC;IACzE;IACA,MAAMY,WAAW,IAAIC;IACrB,KAAK,MAAMC,SAASN,OAAkC;YAGxCM;QAFZ,IAAI,EAACA,yBAAAA,MAAOC,EAAE,KAAIH,SAASI,GAAG,CAACF,MAAMC,EAAE,GAAG,OAAO;QACjDH,SAASK,GAAG,CAACH,MAAMC,EAAE;QACrB,IAAI,CAACG,QAAOJ,cAAA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input: {
|
|
|
61
61
|
} | null;
|
|
62
62
|
}, deps?: CommercePdfBrandDeps): Promise<CommercePdfBrand>;
|
|
63
63
|
/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */
|
|
64
|
-
export declare function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string;
|
|
64
|
+
export declare function commercePdfFilename(businessName: string, document: 'quote' | 'proof' | 'invoice', number: unknown, docId: string): string;
|
|
65
65
|
/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */
|
|
66
66
|
export declare function quotePdfFile(input: {
|
|
67
67
|
hostId: string;
|
|
@@ -202,7 +202,7 @@ export function defaultCommercePdfBrandDeps() {
|
|
|
202
202
|
revision: Number((_input_order_quote = input.order.quote) == null ? void 0 : _input_order_quote.revision) || 1,
|
|
203
203
|
payUrl: input.payUrl
|
|
204
204
|
}),
|
|
205
|
-
filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId)
|
|
205
|
+
filename: commercePdfFilename(brand.businessName, view.proofOnly ? 'proof' : 'quote', input.order.number, input.quoteId)
|
|
206
206
|
};
|
|
207
207
|
}
|
|
208
208
|
/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */ export async function orderInvoicePdfFile(input, deps) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (the\n * one line Setup → Business profile saves, or an older one-block address a line per\n * line), the email visitors write to, its phone, and its web address without\n * the scheme. The address and email are the host tokens' (AGL-4136), so the\n * document says what the site's pages and emails say.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","payLinkStoreOf","revision","Number","quote","payUrl","filename","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,gBA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;gBAAEL,IAAIK,MAAML,EAAE;gBAAEC,KAAKI,MAAMJ,GAAG;YAAC,IAAI;YAClDsC;QACF;QACA,OAAO;YAAEO,QAAQ;YAAKY;QAAI;IAC5B;IACA,MAAMA,MAAM,MAAMtD,KAAKyD,QAAQ,CAAC;QAC9BtE;QACAsC;QACAF;QACAtF;QACA2F,KAAK,GAAGA,cAAAA,MAAM4B,IAAI,cAAV5B,cAAgB;QACxB3B,OAAOA,QAAQ;YAAEL,IAAIK,MAAML,EAAE;YAAEC,KAAKI,MAAMJ,GAAG;QAAC,IAAI;QAClDsC;IACF;IACA,OAAO;QAAEO,QAAQ;QAAKY;IAAI;AAC5B;AAEA,mCAAmC,GACnC,OAAO,MAAMI,kBAAoC,OAAOlB,KAAKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK3H;YAAuB6I,UAAUtC;YAAgBqB;QAC3F,IAAI,SAASU,SAAS,OAAOxI,QAAQiJ,KAAKT,QAAQI,GAAG;QACrD,OAAOtI,qBAAqB2I,KAAKT;IACnC,EAAE,OAAO3D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB2I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAEpD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/commerce-pdf.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server'\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { siteContactEmail, resolveHostToken, type HostTokenSource } from '@aglyn/aglyn/app-utils/host-tokens'\nimport { resolveSiteTheme, type ThemeHostDocument } from '@aglyn/aglyn/app-utils/site-theme'\nimport { buildEmailPalette, emailPaletteBaseForHost } from '@aglyn/shared-util-email'\nimport { readJpeg, type PdfJpegImage } from '@aglyn/shared-util-tools/pdf/pdf-file'\nimport { getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { loadSharp } from '@aglyn/tenant-data-admin/server/media-variants'\nimport * as CommerceModel from '../model'\nimport {\n COMMERCE_PDF_NEUTRAL_COLORS,\n commercePdfColorsFromPalette,\n renderOrderInvoicePdf,\n renderQuotePdf,\n type CommercePdfBrand,\n type CommercePdfColors,\n} from '../utils/commerce-document-pdf'\nimport { invoiceStoreFrom } from '../utils/order-invoice'\nimport { orderStatusUrl } from './order-status-token'\nimport { sendPdf, type CommercePdfFile } from './pdf-response'\nimport { quotePayLinkUrl } from './quote-link-token'\nimport {\n defaultQuotePayDeps,\n limitedQuoteLink,\n loadLinkedQuote,\n quoteLinkParams,\n sendQuoteLinkOutcome,\n type QuoteLinkOutcome,\n type QuotePayDeps,\n} from './quote-pay'\nimport { locateImageSource, readImageSourceBytes } from './site-image-source'\n\n/*==========================================\n * A QUOTE'S AND AN ORDER'S PDF ON THE SERVER (AGL-4095).\n *\n * What the renderers in `utils/commerce-document-pdf.ts` are given comes from\n * here: the site's business name and contact, its theme's colors, its logo\n * (read from storage or its public address, converted to a JPEG on white by\n * sharp, and left out when there is none or it cannot be read), its time\n * zone, and the quote or order itself.\n *\n * Three doors use it, each loading this module only when it is asked for a\n * PDF, so sharp and the PDF writer stay out of every other request:\n *\n * POST commerce/quote { action: 'pdf' } the console's quote (\"Create and edit quotes\")\n * GET commerce/order-print?kind=invoice-pdf the console's and the apps' invoice (\"Manage orders\")\n * GET commerce/quote-pdf?hostId=&q=&t= the customer's quote, by its signed link,\n * or an order's invoice by the same kind (AGL-4099)\n *\n * And the invoice email (AGL-4099, `invoice-email.ts`) attaches the invoice.\n *=========================================*/\n\n/** A logo source larger than this is not read. */\nconst LOGO_SOURCE_MAX_BYTES = 10_000_000\n\n/** The logo's pixels: about four times the box it is drawn in, never enlarged. */\nconst LOGO_PIXELS = { width: 720, height: 200 } as const\n\n/** A converted logo larger than this is left out rather than bloat every copy of the document. */\nconst LOGO_MAX_JPEG_BYTES = 350_000\n\n/** A source whose decoded pixels exceed this is refused rather than decoded. */\nconst LOGO_MAX_INPUT_PIXELS = 50_000_000\n\n/** The ground a logo's transparent pixels are flattened onto: the page's white. */\nconst LOGO_GROUND = { r: 255, g: 255, b: 255 } as const\n\ntype HostDocument = Record<string, unknown>\n\nconst trimmed = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')\n\n/**\n * The business's contact as the document prints it: its postal address (the\n * one line Setup → Business profile saves, or an older one-block address a line per\n * line), the email visitors write to, its phone, and its web address without\n * the scheme. The address and email are the host tokens' (AGL-4136), so the\n * document says what the site's pages and emails say.\n */\nexport function commercePdfContactLines(host: HostDocument | null | undefined): string[] {\n const source = (host ?? {}) as HostTokenSource & {\n seo?: { entity?: { email?: unknown; telephone?: unknown } }\n business?: { supportEmail?: unknown }\n }\n const address = trimmed(resolveHostToken('address', source))\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter(Boolean)\n const email = siteContactEmail(source) ?? ''\n const phone = trimmed(source.seo?.entity?.telephone)\n const site = trimmed(resolveHostToken('url', source)).replace(/^https?:\\/\\//, '').replace(/\\/$/, '')\n return [...address, email, phone, site].filter(Boolean)\n}\n\n/** The site theme's colors for a document, or the neutral ones when the theme cannot be read. */\nexport function commercePdfSiteColors(host: HostDocument | null | undefined): CommercePdfColors {\n try {\n const theme = resolveSiteTheme((host ?? null) as ThemeHostDocument | null)\n return commercePdfColorsFromPalette(\n buildEmailPalette({\n base: emailPaletteBaseForHost(host as { cname?: string; subdomain?: string } | null),\n colors: (theme?.colorSchemes?.light ?? null) as Record<string, unknown> | null,\n }),\n )\n } catch {\n return { ...COMMERCE_PDF_NEUTRAL_COLORS }\n }\n}\n\n/** sharp's decoding options; an SVG is rasterized dense enough for the logo's pixels. */\nasync function decodeOptions(sharp: Awaited<ReturnType<typeof loadSharp>>, source: Buffer) {\n const base = { limitInputPixels: LOGO_MAX_INPUT_PIXELS, failOn: 'error' as const }\n const meta = await sharp(source, base).metadata()\n if (meta.format !== 'svg') return base\n const longest = Math.max(meta.width ?? 0, meta.height ?? 0)\n if (!longest) return base\n return { ...base, density: Math.min(2400, Math.max(1, Math.ceil((72 * LOGO_PIXELS.width) / longest))) }\n}\n\n/**\n * A logo's bytes as a JPEG the PDF can carry: turned upright, fitted inside\n * {@link LOGO_PIXELS}, transparency flattened onto white, and small enough to\n * attach. Null when the bytes are not an image sharp reads.\n */\nexport async function logoJpeg(source: Buffer, sharpFactory?: Awaited<ReturnType<typeof loadSharp>>): Promise<PdfJpegImage | null> {\n const sharp = sharpFactory ?? (await loadSharp())\n const options = await decodeOptions(sharp, source)\n for (const quality of [86, 72]) {\n const jpeg = await sharp(source, options)\n .rotate()\n .resize(LOGO_PIXELS.width, LOGO_PIXELS.height, { fit: 'inside', withoutEnlargement: true })\n .flatten({ background: LOGO_GROUND })\n .jpeg({ quality })\n .toBuffer()\n if (jpeg.length <= LOGO_MAX_JPEG_BYTES) return readJpeg(new Uint8Array(jpeg))\n }\n return null\n}\n\nexport interface CommercePdfBrandDeps {\n /** The site's logo as a JPEG, or null; never throws. */\n logo(input: { hostId: string; orgId: string; value: string }): Promise<PdfJpegImage | null>\n orgForHost(hostId: string): Promise<{ id?: string; org?: unknown } | null>\n}\n\nexport function defaultCommercePdfBrandDeps(): CommercePdfBrandDeps {\n return {\n logo: async ({ hostId, orgId, value }) => {\n try {\n const located = await locateImageSource(value, hostId, orgId, LOGO_SOURCE_MAX_BYTES)\n const bytes = located ? await readImageSourceBytes(located, LOGO_SOURCE_MAX_BYTES) : null\n return bytes ? await logoJpeg(bytes) : null\n } catch (error) {\n console.warn('[commerce/pdf] the site logo was left out', error)\n return null\n }\n },\n orgForHost: async (hostId) => {\n const found = await getOrgForHost(hostId)\n return found ? { id: found.orgId, org: found.org } : null\n },\n }\n}\n\n/** Who a site's documents are from: its name, contact, colors, logo and time zone. */\nexport async function loadCommercePdfBrand(\n input: { hostId: string; host: HostDocument; owner?: { id?: string; org?: unknown } | null },\n deps: CommercePdfBrandDeps = defaultCommercePdfBrandDeps(),\n): Promise<CommercePdfBrand> {\n const host = input.host\n const owner = input.owner === undefined ? await deps.orgForHost(input.hostId).catch(() => null) : input.owner\n const logoValue = trimmed(resolveHostToken('logo', host as HostTokenSource))\n const logo = logoValue ? await deps.logo({ hostId: input.hostId, orgId: String(owner?.id ?? ''), value: logoValue }) : null\n return {\n businessName: trimmed(resolveHostToken('businessName', host as HostTokenSource)) || trimmed(host['name']),\n contactLines: commercePdfContactLines(host),\n logo,\n colors: commercePdfSiteColors(host),\n timeZone: resolveSiteTimeZone(\n (owner?.org ?? null) as { timeZone?: string } | null,\n host as { timeZone?: string },\n ),\n }\n}\n\n/** `acme-signs-quote-1042.pdf`: the business, the document and its number, in ASCII. */\nexport function commercePdfFilename(businessName: string, document: 'quote' | 'proof' | 'invoice', number: unknown, docId: string): string {\n const slug = (value: string) =>\n value\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 40)\n const numbered = number != null && String(number).trim() ? String(number) : docId.slice(-6)\n return `${[slug(businessName), document, slug(numbered)].filter(Boolean).join('-')}.pdf`\n}\n\n/** A quote's PDF: what its customer's page shows, from the business, with its pay link when given one. */\nexport async function quotePdfFile(\n input: {\n hostId: string\n quoteId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on a quote still to be paid; null leaves it off. */\n payUrl: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n const view = CommerceModel.buildQuotePageView({\n order: input.order,\n orderId: input.quoteId,\n storeName: brand.businessName,\n currency: String(input.store?.['currency'] ?? 'USD'),\n receiptUrl: CommerceModel.isUnpaidQuote(input.order) ? null : orderStatusUrl(input.host, input.hostId, input.quoteId),\n store: CommerceModel.payLinkStoreOf(input.store),\n })\n return {\n bytes: renderQuotePdf({ brand, view, revision: Number(input.order.quote?.revision) || 1, payUrl: input.payUrl }),\n filename: commercePdfFilename(brand.businessName, view.proofOnly ? 'proof' : 'quote', input.order.number, input.quoteId),\n }\n}\n\n/** An order's invoice PDF, a paid quote's included; an unpaid one carries its pay link when given (AGL-4099). */\nexport async function orderInvoicePdfFile(\n input: {\n hostId: string\n orderId: string\n order: CommerceModel.HostOrder\n host: HostDocument\n store: HostDocument | null | undefined\n owner?: { id?: string; org?: unknown } | null\n /** Printed on an invoice still to be paid; absent or null leaves it off. */\n payUrl?: string | null\n },\n deps?: CommercePdfBrandDeps,\n): Promise<CommercePdfFile> {\n const brand = await loadCommercePdfBrand({ hostId: input.hostId, host: input.host, owner: input.owner }, deps)\n return {\n bytes: renderOrderInvoicePdf({\n brand,\n order: input.order,\n orderId: input.orderId,\n store: invoiceStoreFrom(input.host, input.store),\n payUrl: input.payUrl ?? null,\n }),\n filename: commercePdfFilename(brand.businessName, 'invoice', input.order.number, input.orderId),\n }\n}\n\n/*==========================================\n * THE CUSTOMER'S DOWNLOAD: GET commerce/quote-pdf?hostId=&q=&t=\n *\n * The same signed link and the same rules as the quote page's data\n * (`commerce/quote-view`): a wrong token answers exactly as a missing quote,\n * a link to an older version of the quote is refused, and every address is\n * rate-limited per site before the token is checked. The PDF is the page's\n * own view, so it shows nothing the page does not.\n *=========================================*/\n\n/** Downloads one address may make per site, per ten minutes. */\nexport const QUOTE_PDF_DOWNLOADS_PER_WINDOW = 20\n\nexport interface QuotePdfRouteDeps extends QuotePayDeps {\n quotePdf: typeof quotePdfFile\n /** An invoice's PDF, for the link of an order that is not a quote (AGL-4099). */\n invoicePdf?: typeof orderInvoicePdfFile\n}\n\nexport async function handleQuotePdf(\n deps: QuotePdfRouteDeps,\n req: PluginApiRequest,\n): Promise<QuoteLinkOutcome | { status: 200; pdf: CommercePdfFile }> {\n if (req.method !== 'GET') return { status: 405, body: { error: 'Method not allowed' } }\n const { hostId, quoteId, token, complete } = quoteLinkParams((req.query ?? {}) as Record<string, unknown>)\n if (!complete) return { status: 400, body: { error: 'This link is incomplete.' } }\n const refused = await limitedQuoteLink(deps, req, `commerce-quote-pdf:${hostId}`, QUOTE_PDF_DOWNLOADS_PER_WINDOW)\n if (refused) return refused\n const linked = await loadLinkedQuote(deps, hostId, quoteId, token, { invoices: true })\n if ('outcome' in linked) return linked.outcome\n const { host, order, store, kind } = linked.loaded\n const payUrl =\n order.status === 'pending' ? quotePayLinkUrl(host, hostId, quoteId, CommerceModel.orderPayLinkVersion(order)) : null\n const owner = await deps.orgForHost(hostId).catch(() => null)\n if (kind === 'invoice') {\n const pdf = await (deps.invoicePdf ?? orderInvoicePdfFile)({\n hostId,\n orderId: quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n }\n const pdf = await deps.quotePdf({\n hostId,\n quoteId,\n order,\n host,\n store: (store.data() ?? null) as HostDocument | null,\n owner: owner ? { id: owner.id, org: owner.org } : null,\n payUrl,\n })\n return { status: 200, pdf }\n}\n\n/** `GET /api/commerce/quote-pdf`. */\nexport const quotePdfHandler: PluginApiHandler = async (req, res) => {\n try {\n const outcome = await handleQuotePdf({ ...defaultQuotePayDeps(), quotePdf: quotePdfFile }, req)\n if ('pdf' in outcome) return sendPdf(res, outcome.pdf)\n return sendQuoteLinkOutcome(res, outcome)\n } catch (error) {\n console.error('quote pdf failed', error)\n return sendQuoteLinkOutcome(res, { status: 500, body: { error: 'This quote could not be made into a PDF. Try again.' } })\n }\n}\n"],"names":["resolveSiteTimeZone","siteContactEmail","resolveHostToken","resolveSiteTheme","buildEmailPalette","emailPaletteBaseForHost","readJpeg","getOrgForHost","loadSharp","CommerceModel","COMMERCE_PDF_NEUTRAL_COLORS","commercePdfColorsFromPalette","renderOrderInvoicePdf","renderQuotePdf","invoiceStoreFrom","orderStatusUrl","sendPdf","quotePayLinkUrl","defaultQuotePayDeps","limitedQuoteLink","loadLinkedQuote","quoteLinkParams","sendQuoteLinkOutcome","locateImageSource","readImageSourceBytes","LOGO_SOURCE_MAX_BYTES","LOGO_PIXELS","width","height","LOGO_MAX_JPEG_BYTES","LOGO_MAX_INPUT_PIXELS","LOGO_GROUND","r","g","b","trimmed","value","trim","commercePdfContactLines","host","source","address","split","map","line","filter","Boolean","email","phone","seo","entity","telephone","site","replace","commercePdfSiteColors","theme","base","colors","colorSchemes","light","decodeOptions","sharp","meta","limitInputPixels","failOn","metadata","format","longest","Math","max","density","min","ceil","logoJpeg","sharpFactory","options","quality","jpeg","rotate","resize","fit","withoutEnlargement","flatten","background","toBuffer","length","Uint8Array","defaultCommercePdfBrandDeps","logo","hostId","orgId","located","bytes","error","console","warn","orgForHost","found","id","org","loadCommercePdfBrand","input","deps","owner","undefined","catch","logoValue","String","businessName","contactLines","timeZone","commercePdfFilename","document","number","docId","slug","normalize","toLowerCase","slice","numbered","join","quotePdfFile","brand","view","buildQuotePageView","order","orderId","quoteId","storeName","currency","store","receiptUrl","isUnpaidQuote","payLinkStoreOf","revision","Number","quote","payUrl","filename","proofOnly","orderInvoicePdfFile","QUOTE_PDF_DOWNLOADS_PER_WINDOW","handleQuotePdf","req","method","status","body","token","complete","query","refused","linked","invoices","outcome","kind","loaded","orderPayLinkVersion","pdf","invoicePdf","data","quotePdf","quotePdfHandler","res"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,mBAAmB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AAAA,MAAM6B,IAAI,cAAV7B,eAAgB;YACxB3B,OAAOA,QAAQ;gBAAEL,IAAIK,MAAML,EAAE;gBAAEC,KAAKI,MAAMJ,GAAG;YAAC,IAAI;YAClDsC;QACF;QACA,OAAO;YAAEQ,QAAQ;YAAKY;QAAI;IAC5B;IACA,MAAMA,MAAM,MAAMvD,KAAK0D,QAAQ,CAAC;QAC9BvE;QACAsC;QACAF;QACAtF;QACA2F,KAAK,GAAGA,cAAAA,MAAM6B,IAAI,cAAV7B,cAAgB;QACxB3B,OAAOA,QAAQ;YAAEL,IAAIK,MAAML,EAAE;YAAEC,KAAKI,MAAMJ,GAAG;QAAC,IAAI;QAClDsC;IACF;IACA,OAAO;QAAEQ,QAAQ;QAAKY;IAAI;AAC5B;AAEA,mCAAmC,GACnC,OAAO,MAAMI,kBAAoC,OAAOlB,KAAKmB;IAC3D,IAAI;QACF,MAAMT,UAAU,MAAMX,eAAe,aAAK5H;YAAuB8I,UAAUvC;YAAgBsB;QAC3F,IAAI,SAASU,SAAS,OAAOzI,QAAQkJ,KAAKT,QAAQI,GAAG;QACrD,OAAOvI,qBAAqB4I,KAAKT;IACnC,EAAE,OAAO5D,OAAO;QACdC,QAAQD,KAAK,CAAC,oBAAoBA;QAClC,OAAOvE,qBAAqB4I,KAAK;YAAEjB,QAAQ;YAAKC,MAAM;gBAAErD,OAAO;YAAsD;QAAE;IACzH;AACF,EAAC"}
|
|
@@ -119,7 +119,7 @@ import { mediaCdnScopeRefusal, parseMediaCdnScope, selectAutoRendition } from "@
|
|
|
119
119
|
}
|
|
120
120
|
// The CDN would 404 an org asset this site is not allowed to use, so a
|
|
121
121
|
// link to one is a link that cannot play.
|
|
122
|
-
if (mediaCdnScopeRefusal(deliveryParsed, document.get('visibleTo'))) {
|
|
122
|
+
if (mediaCdnScopeRefusal(deliveryParsed, document.get('visibleTo'), document.get('scopeMode'))) {
|
|
123
123
|
return refuse('not-found');
|
|
124
124
|
}
|
|
125
125
|
if (document.get('private') !== true) return refuse('not-private');
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/paid-media-delivery.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 {\n hostQualifiedScope,\n MEDIA_CDN_RENDITION_AUTO,\n MEDIA_CDN_RENDITION_PARAM,\n MEDIA_CDN_ROUTE,\n paidMediaAssetOfObject,\n parseMediaRenditions,\n parsePaidMediaSource,\n} from '@aglyn/aglyn/server'\nimport {\n type MediaDeliveryProvider,\n mediaDeliveryProvider,\n} from '@aglyn/aglyn/plugin-manager/media-delivery-provider'\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { mediaDeliveryRedirect } from '@aglyn/tenant-data-admin/server/media-delivery'\nimport {\n assertMediaSignatureTtl,\n mediaSignatureQuery,\n mintMediaSignature,\n} from '@aglyn/tenant-data-admin/server/media-signing'\nimport { isMediaStoragePathInScope } from '@aglyn/tenant-data-admin/server/media-storage-path'\nimport {\n mediaCdnScopeRefusal,\n parseMediaCdnScope,\n selectAutoRendition,\n} from '@aglyn/tenant-data-admin/server/serve-media-cdn'\n\n/**\n * Turning a URL stored on a product into a link a buyer may follow (AGL-2814).\n *\n * A product's paid media — its members videos — is stored as whatever the\n * author's picker wrote: a media reference, a CDN path, a raw Storage download\n * URL, or a hotlink somebody typed. `parsePaidMediaSource` says which of those\n * a value is. The commerce routes verify who is entitled and then redirect;\n * this module decides WHERE they may redirect, and its whole job is that the\n * answer is never a URL that outlives the purchase.\n *\n * ## The rules, in the order they are applied\n *\n * 1. **A library asset is delivered only when it is PRIVATE**, as a CDN URL\n * signed with {@link mintMediaSignature}. The CDN refuses a private asset on\n * every path without an unexpired signature, which is what makes the link\n * die. A public asset is refused here instead of redirected to: its URL\n * works for anyone forever, so handing it to a buyer is the leak itself.\n * 2. **A Storage download URL is never redirected to.** Its token lives as\n * long as the object. When the object belongs to a library asset, rule 1\n * applies to that asset. When no asset owns it (a legacy object, a derived\n * rendition file), it gets a V4 signed read URL with the same bounded\n * lifetime. When it is not in this platform's bucket, or not inside the\n * site's own library or its org's, it is refused.\n * 3. **Only the requesting site's own libraries are signed.** A product is\n * author data. Signing whatever scope it names would let one site's author\n * mint working links to another org's private files, so a host scope must\n * be this site and an org scope must be this site's org, and the signed\n * scope is always qualified with this site so the CDN's `visibleTo` check\n * runs against the site actually selling it.\n * 4. **A hotlink to somebody else's server passes through unchanged.** No code\n * of ours runs there and nothing here can make its URL expire. That is the\n * author's hosting decision, and the docs say so. EXCEPT a hotlink whose\n * host wears a brand it is not (`lookalikeBrandForHost`, the phishing\n * screen's rule): the redirect leaves from the merchant's own domain, so a\n * lure behind it is one no screen of the page or the receipt ever saw. It\n * is refused for every workspace, like a lookalike link in an email\n * (AGL-3363), and the caller files it.\n * 5. **A signed Storage read is a download when it is one.** A download, or\n * an object whose type a browser would run (HTML, SVG, XML), is signed\n * with `response-content-disposition: attachment`, so the file is saved\n * rather than rendered (AGL-3363). The CDN already does this for its own\n * deliveries; a V4 URL carried nothing.\n *\n * ## A video with a copy at the delivery provider (AGL-2824)\n *\n * A caller that asks for it with `delivery` gets, for a video that passes\n * rule 1, the delivery provider's own short-lived URL instead of the signed CDN\n * URL, whenever `mediaDeliveryRedirect` finds a current copy and the release\n * flag is on for the owning org. It is the URL the CDN would redirect the\n * signed request to anyway, minted one hop earlier and bounded by the same\n * lifetime. Anything else takes the signed CDN URL exactly as before.\n */\n\n/** Why a stored URL was not turned into a link. */\nexport type PaidMediaRefusal =\n /** A library asset the public can still fetch without a signature. */\n | 'not-private'\n /** No such asset, a deleted one, or one not shared with this site. */\n | 'not-found'\n /** Another site's library, another org's, or outside the media prefixes. */\n | 'out-of-scope'\n /** A Storage URL for a bucket this platform does not serve from. */\n | 'foreign-storage'\n /** Not a value any delivery can be built from. */\n | 'malformed'\n /** A hotlink to a host that wears another brand's name (AGL-3363). */\n | 'lookalike'\n\nexport type PaidMediaDelivery =\n | {\n ok: true\n via: 'signed-cdn'\n location: string\n expiresAtMs: number\n /** The scope segment the signature covers. */\n scope: string\n mediaId: string\n }\n | {\n ok: true\n via: 'signed-storage'\n location: string\n expiresAtMs: number\n objectPath: string\n /** Whose library the object is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The object's size, 0 when Storage did not say. */\n sizeBytes: number\n }\n | { ok: true; via: 'external'; location: string }\n | {\n ok: true\n via: 'delivery'\n location: string\n expiresAtMs: number\n /** The scope segment the delivery was minted for. */\n scope: string\n mediaId: string\n /** Whose library the asset is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The size of the copy the provider serves. */\n sizeBytes: number\n }\n | {\n ok: false\n refusal: PaidMediaRefusal\n /** For a `lookalike`: the host it wears a brand in, for the caller to file. */\n host?: string\n }\n\n/** A document read, reduced to what this module asks of one. */\nexport interface PaidMediaDocument {\n exists: boolean\n get(field: string): unknown\n}\n\n/** Every read and signature this module needs, injectable for tests. */\nexport interface PaidMediaDeliveryIo {\n /** The platform's media bucket; empty when unconfigured. */\n bucketName: string\n readMedia(\n collection: 'hosts' | 'orgs',\n scopeId: string,\n mediaId: string,\n ): Promise<PaidMediaDocument>\n /** The org a site belongs to, or null for an unindexed site. */\n orgIdForHost(hostId: string): Promise<string | null>\n /**\n * A V4 signed read URL for one object in {@link bucketName}. `attachment`\n * signs `response-content-disposition: attachment` into it (AGL-3363).\n */\n signStorageRead(\n objectPath: string,\n expiresAtMs: number,\n options?: { attachment?: boolean },\n ): Promise<string>\n /**\n * The object's size in bytes, for the bandwidth a signed read can send;\n * 0 when it cannot be read. Optional, so a double that never signs a\n * Storage read need not answer it.\n */\n storageObjectSize?(objectPath: string): Promise<number>\n}\n\n/** Object types a browser runs rather than shows: always saved, never rendered. */\nconst ACTIVE_OBJECT_EXTENSION = /\\.(html?|xhtml|xht|svgz?|xml|xsl|xslt|mht|mhtml|js|mjs)$/i\n\n/** Is this signed read a download, by the caller's ask or by what the object is? */\nexport function storageReadIsAttachment(\n objectPath: string,\n cdnParams: ReadonlyArray<readonly [string, string]> | undefined,\n): boolean {\n if ((cdnParams ?? []).some(([key, value]) => key === 'download' && value === '1')) {\n return true\n }\n return ACTIVE_OBJECT_EXTENSION.test(objectPath)\n}\n\n/**\n * Resolves a stored product media URL to a redirect target that expires, or\n * says why there is none. See the module comment for the rules.\n *\n * `cdnParams` ride on a signed CDN URL ahead of the signature, which covers\n * `(scope, mediaId, exp)` and never the parameters, so they select a\n * representation of the one asset the signature names and nothing else.\n */\nexport async function resolvePaidMediaDelivery(options: {\n stored: unknown\n /** The site selling the media; the only libraries it may sign from. */\n hostId: string\n /** The lifetime of the link; bounded by `assertMediaSignatureTtl`. */\n ttlMs: number\n cdnParams?: ReadonlyArray<readonly [string, string]>\n /**\n * Hand a video with a current copy at the delivery provider its URL there\n * (AGL-2824). `accept` is the request's `Accept`, which chooses the\n * rendition when `cdnParams` asks for `?r=auto`. The provider and the flag\n * verdict default to the registered provider and the release flag.\n */\n delivery?: {\n accept?: unknown\n provider?: MediaDeliveryProvider | null\n enabled?: (orgId: string | null) => Promise<boolean>\n }\n nowMs?: number\n io: PaidMediaDeliveryIo\n}): Promise<PaidMediaDelivery> {\n const { hostId, ttlMs, io } = options\n const nowMs = options.nowMs ?? Date.now()\n const refuse = (refusal: PaidMediaRefusal): PaidMediaDelivery => ({\n ok: false,\n refusal,\n })\n if (!hostId) return refuse('out-of-scope')\n\n // One lookup per call, and only for the forms that need to know the org.\n let orgId: Promise<string | null> | undefined\n const siteOrgId = () => (orgId ??= io.orgIdForHost(hostId))\n\n /**\n * The delivery provider's URL for a private library video, or null for\n * the signed CDN URL. The representation is the one the CDN would pick for\n * the same `?r=` and `Accept`, so the buyer gets the copy the signed URL\n * would have been redirected to.\n */\n const deliverFromProvider = async (\n delivery: NonNullable<typeof options.delivery>,\n asset: {\n collection: 'hosts' | 'orgs'\n scopeId: string\n orgScope: boolean\n deliveryScope: string\n mediaId: string\n document: PaidMediaDocument\n },\n ): Promise<PaidMediaDelivery | null> => {\n const provider =\n delivery.provider === undefined ? mediaDeliveryProvider('deliver') : delivery.provider\n if (!provider) return null\n const requested = (options.cdnParams ?? []).find(\n ([key]) => key === MEDIA_CDN_RENDITION_PARAM,\n )?.[1]\n const renditions = parseMediaRenditions(asset.document.get('videoRenditions'))\n const rendition = !requested\n ? undefined\n : requested === MEDIA_CDN_RENDITION_AUTO\n ? selectAutoRendition(renditions, delivery.accept)\n : renditions.find((entry) => entry.key === requested)\n const redirect = await mediaDeliveryRedirect({\n provider,\n asset: {\n collection: asset.collection,\n scopeId: asset.scopeId,\n mediaId: asset.mediaId,\n },\n document: asset.document,\n rendition,\n servedType: rendition ? rendition.contentType : asset.document.get('contentType'),\n claims: { scope: asset.deliveryScope, mediaId: asset.mediaId, hostId },\n orgId: async () => (asset.orgScope ? asset.scopeId : await siteOrgId()),\n ...(delivery.enabled ? { deliveryEnabled: delivery.enabled } : {}),\n ttlMs,\n nowMs,\n }).catch(() => null)\n if (!redirect) return null\n return {\n ok: true,\n via: 'delivery',\n location: redirect.location,\n expiresAtMs: redirect.expiresAtMs,\n scope: asset.deliveryScope,\n mediaId: asset.mediaId,\n collection: asset.collection,\n scopeId: asset.scopeId,\n sizeBytes: redirect.sizeBytes,\n }\n }\n\n const deliverAsset = async (\n scope: string,\n mediaId: string,\n ): Promise<PaidMediaDelivery> => {\n const parsed = parseMediaCdnScope(scope)\n if (!parsed) return refuse('malformed')\n let collection: 'hosts' | 'orgs'\n let deliveryScope: string\n if (parsed.isOrg) {\n const owner = await siteOrgId()\n if (!owner || parsed.scopeId !== owner) return refuse('out-of-scope')\n collection = 'orgs'\n deliveryScope = hostQualifiedScope(scope, hostId)\n } else {\n if (parsed.scopeId !== hostId) return refuse('out-of-scope')\n collection = 'hosts'\n deliveryScope = hostId\n }\n const deliveryParsed = parseMediaCdnScope(deliveryScope)\n if (!deliveryParsed) return refuse('malformed')\n const document = await io.readMedia(collection, parsed.scopeId, mediaId)\n if (!document?.exists || document.get('deletedAt')) {\n return refuse('not-found')\n }\n // The CDN would 404 an org asset this site is not allowed to use, so a\n // link to one is a link that cannot play.\n if (mediaCdnScopeRefusal(deliveryParsed, document.get('visibleTo'))) {\n return refuse('not-found')\n }\n if (document.get('private') !== true) return refuse('not-private')\n assertMediaSignatureTtl(ttlMs)\n const delivered = options.delivery\n ? await deliverFromProvider(options.delivery, {\n collection,\n scopeId: parsed.scopeId,\n orgScope: parsed.isOrg,\n deliveryScope,\n mediaId,\n document,\n })\n : null\n if (delivered) return delivered\n const signature = mintMediaSignature(deliveryScope, mediaId, nowMs, ttlMs)\n const params = new URLSearchParams()\n for (const [key, value] of options.cdnParams ?? []) {\n if (key !== 'exp' && key !== 'sig') params.set(key, value)\n }\n const prefix = params.toString()\n return {\n ok: true,\n via: 'signed-cdn',\n location:\n `${MEDIA_CDN_ROUTE}/${deliveryScope}/${mediaId}?` +\n `${prefix ? `${prefix}&` : ''}${mediaSignatureQuery(signature)}`,\n expiresAtMs: signature.exp,\n scope: deliveryScope,\n mediaId,\n }\n }\n\n const source = parsePaidMediaSource(options.stored)\n switch (source.kind) {\n case 'malformed':\n return refuse('malformed')\n case 'external': {\n let externalHost: string\n try {\n externalHost = new URL(source.url).hostname\n } catch {\n return refuse('malformed')\n }\n if (lookalikeBrandForHost(externalHost)) {\n return { ok: false, refusal: 'lookalike', host: externalHost }\n }\n return { ok: true, via: 'external', location: source.url }\n }\n case 'asset':\n return deliverAsset(source.scope, source.mediaId)\n case 'storage-object': {\n if (!io.bucketName || source.bucket !== io.bucketName) {\n return refuse('foreign-storage')\n }\n const { objectPath } = source\n const segments = objectPath.split('/')\n let base: string | null = null\n if (segments[0] === 'hosts' && segments[1] === hostId) {\n base = `hosts/${hostId}`\n } else if (segments[0] === 'orgs' && segments[1]) {\n const owner = await siteOrgId()\n if (owner && segments[1] === owner) base = `orgs/${owner}`\n }\n // The same prefix test the CDN applies to a document's `storagePath`,\n // which also refuses traversal and empty segments.\n if (!base || !isMediaStoragePathInScope(objectPath, base)) {\n return refuse('out-of-scope')\n }\n // An object keyed like an asset IS that asset, and the asset's own rules\n // decide — including refusing it when the asset is still public.\n const asset = paidMediaAssetOfObject(objectPath)\n if (asset) return deliverAsset(asset.scope, asset.mediaId)\n assertMediaSignatureTtl(ttlMs)\n const expiresAtMs = nowMs + ttlMs\n const [location, sizeBytes] = await Promise.all([\n io.signStorageRead(objectPath, expiresAtMs, {\n attachment: storageReadIsAttachment(objectPath, options.cdnParams),\n }),\n io.storageObjectSize?.(objectPath).catch(() => 0) ?? Promise.resolve(0),\n ])\n return {\n ok: true,\n via: 'signed-storage',\n location,\n expiresAtMs,\n objectPath,\n collection: segments[0] === 'orgs' ? 'orgs' : 'hosts',\n scopeId: segments[1],\n sizeBytes,\n }\n }\n }\n}\n\n/**\n * The production reads behind {@link resolvePaidMediaDelivery}, built on the\n * caller's Firestore and bucket handles so a route's own mocks reach them.\n */\nexport function createPaidMediaDeliveryIo(options: {\n firestore: {\n collection(name: string): {\n doc(id: string): {\n get(): Promise<PaidMediaDocument>\n collection(name: string): {\n doc(id: string): { get(): Promise<PaidMediaDocument> }\n }\n }\n }\n }\n bucket: {\n name?: string\n file(path: string): {\n getSignedUrl(config: {\n version: 'v4'\n action: 'read'\n expires: number\n responseDisposition?: string\n }): Promise<[string] | string[]>\n getMetadata?(): Promise<[{ size?: unknown }, ...unknown[]] | Array<{ size?: unknown }>>\n }\n }\n}): PaidMediaDeliveryIo {\n const { firestore, bucket } = options\n return {\n bucketName: String(bucket?.name ?? ''),\n readMedia: (collection, scopeId, mediaId) =>\n firestore\n .collection(collection)\n .doc(scopeId)\n .collection('media')\n .doc(mediaId)\n .get(),\n orgIdForHost: async (hostId) => {\n const index = await firestore.collection('hostIndex').doc(hostId).get()\n const orgId = index.exists ? index.get('orgId') : undefined\n return typeof orgId === 'string' && orgId ? orgId : null\n },\n signStorageRead: async (objectPath, expiresAtMs, signOptions) => {\n const [url] = await bucket.file(objectPath).getSignedUrl({\n version: 'v4',\n action: 'read',\n expires: expiresAtMs,\n ...(signOptions?.attachment ? { responseDisposition: 'attachment' } : {}),\n })\n return String(url)\n },\n storageObjectSize: async (objectPath) => {\n const file = bucket.file(objectPath)\n if (!file.getMetadata) return 0\n const [metadata] = await file.getMetadata()\n const size = Number(metadata?.size)\n return Number.isSafeInteger(size) && size > 0 ? size : 0\n },\n }\n}\n"],"names":["hostQualifiedScope","MEDIA_CDN_RENDITION_AUTO","MEDIA_CDN_RENDITION_PARAM","MEDIA_CDN_ROUTE","paidMediaAssetOfObject","parseMediaRenditions","parsePaidMediaSource","mediaDeliveryProvider","lookalikeBrandForHost","mediaDeliveryRedirect","assertMediaSignatureTtl","mediaSignatureQuery","mintMediaSignature","isMediaStoragePathInScope","mediaCdnScopeRefusal","parseMediaCdnScope","selectAutoRendition","ACTIVE_OBJECT_EXTENSION","storageReadIsAttachment","objectPath","cdnParams","some","key","value","test","resolvePaidMediaDelivery","options","hostId","ttlMs","io","nowMs","Date","now","refuse","refusal","ok","orgId","siteOrgId","orgIdForHost","deliverFromProvider","delivery","asset","provider","undefined","requested","find","renditions","document","get","rendition","accept","entry","redirect","collection","scopeId","mediaId","servedType","contentType","claims","scope","deliveryScope","orgScope","enabled","deliveryEnabled","catch","via","location","expiresAtMs","sizeBytes","deliverAsset","parsed","isOrg","owner","deliveryParsed","readMedia","exists","delivered","signature","params","URLSearchParams","set","prefix","toString","exp","source","stored","kind","externalHost","URL","url","hostname","host","bucketName","bucket","segments","split","base","Promise","all","signStorageRead","attachment","storageObjectSize","resolve","createPaidMediaDeliveryIo","firestore","String","name","doc","index","signOptions","file","getSignedUrl","version","action","expires","responseDisposition","getMetadata","metadata","size","Number","isSafeInteger"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,wBAAwB,EACxBC,yBAAyB,EACzBC,eAAe,EACfC,sBAAsB,EACtBC,oBAAoB,EACpBC,oBAAoB,QACf,sBAAqB;AAC5B,SAEEC,qBAAqB,QAChB,sDAAqD;AAC5D,SAASC,qBAAqB,QAAQ,oDAAmD;AACzF,SAASC,qBAAqB,QAAQ,iDAAgD;AACtF,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,kBAAkB,QACb,gDAA+C;AACtD,SAASC,yBAAyB,QAAQ,qDAAoD;AAC9F,SACEC,oBAAoB,EACpBC,kBAAkB,EAClBC,mBAAmB,QACd,kDAAiD;AAoJxD,iFAAiF,GACjF,MAAMC,0BAA0B;AAEhC,kFAAkF,GAClF,OAAO,SAASC,wBACdC,UAAkB,EAClBC,SAA+D;IAE/D,IAAI,CAACA,oBAAAA,YAAa,EAAE,EAAEC,IAAI,CAAC,CAAC,CAACC,KAAKC,MAAM,GAAKD,QAAQ,cAAcC,UAAU,MAAM;QACjF,OAAO;IACT;IACA,OAAON,wBAAwBO,IAAI,CAACL;AACtC;AAEA;;;;;;;CAOC,GACD,OAAO,eAAeM,yBAAyBC,OAoB9C;QAEeA;IADd,MAAM,EAAEC,MAAM,EAAEC,KAAK,EAAEC,EAAE,EAAE,GAAGH;IAC9B,MAAMI,SAAQJ,iBAAAA,QAAQI,KAAK,YAAbJ,iBAAiBK,KAAKC,GAAG;IACvC,MAAMC,SAAS,CAACC,UAAkD,CAAA;YAChEC,IAAI;YACJD;QACF,CAAA;IACA,IAAI,CAACP,QAAQ,OAAOM,OAAO;IAE3B,yEAAyE;IACzE,IAAIG;IACJ,MAAMC,YAAY,IAAOD,gBAAAA,QAAAA,QAAUP,GAAGS,YAAY,CAACX;IAEnD;;;;;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MAAM,EAAE8E,SAAS,EAAEX,MAAM,EAAE,GAAGnE;IAC9B,OAAO;QACLkE,YAAYa,eAAOZ,0BAAAA,OAAQa,IAAI,mBAAI;QACnChC,WAAW,CAACrB,YAAYC,SAASC,UAC/BiD,UACGnD,UAAU,CAACA,YACXsD,GAAG,CAACrD,SACJD,UAAU,CAAC,SACXsD,GAAG,CAACpD,SACJP,GAAG;QACRV,cAAc,OAAOX;YACnB,MAAMiF,QAAQ,MAAMJ,UAAUnD,UAAU,CAAC,aAAasD,GAAG,CAAChF,QAAQqB,GAAG;YACrE,MAAMZ,QAAQwE,MAAMjC,MAAM,GAAGiC,MAAM5D,GAAG,CAAC,WAAWL;YAClD,OAAO,OAAOP,UAAU,YAAYA,QAAQA,QAAQ;QACtD;QACA+D,iBAAiB,OAAOhF,YAAYgD,aAAa0C;YAC/C,MAAM,CAACpB,IAAI,GAAG,MAAMI,OAAOiB,IAAI,CAAC3F,YAAY4F,YAAY,CAAC;gBACvDC,SAAS;gBACTC,QAAQ;gBACRC,SAAS/C;eACL0C,CAAAA,+BAAAA,YAAaT,UAAU,IAAG;gBAAEe,qBAAqB;YAAa,IAAI,CAAC;YAEzE,OAAOV,OAAOhB;QAChB;QACAY,mBAAmB,OAAOlF;YACxB,MAAM2F,OAAOjB,OAAOiB,IAAI,CAAC3F;YACzB,IAAI,CAAC2F,KAAKM,WAAW,EAAE,OAAO;YAC9B,MAAM,CAACC,SAAS,GAAG,MAAMP,KAAKM,WAAW;YACzC,MAAME,OAAOC,OAAOF,4BAAAA,SAAUC,IAAI;YAClC,OAAOC,OAAOC,aAAa,CAACF,SAASA,OAAO,IAAIA,OAAO;QACzD;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/paid-media-delivery.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 {\n hostQualifiedScope,\n MEDIA_CDN_RENDITION_AUTO,\n MEDIA_CDN_RENDITION_PARAM,\n MEDIA_CDN_ROUTE,\n paidMediaAssetOfObject,\n parseMediaRenditions,\n parsePaidMediaSource,\n} from '@aglyn/aglyn/server'\nimport {\n type MediaDeliveryProvider,\n mediaDeliveryProvider,\n} from '@aglyn/aglyn/plugin-manager/media-delivery-provider'\nimport { lookalikeBrandForHost } from '@aglyn/shared-util-email/outbound-phishing-screen'\nimport { mediaDeliveryRedirect } from '@aglyn/tenant-data-admin/server/media-delivery'\nimport {\n assertMediaSignatureTtl,\n mediaSignatureQuery,\n mintMediaSignature,\n} from '@aglyn/tenant-data-admin/server/media-signing'\nimport { isMediaStoragePathInScope } from '@aglyn/tenant-data-admin/server/media-storage-path'\nimport {\n mediaCdnScopeRefusal,\n parseMediaCdnScope,\n selectAutoRendition,\n} from '@aglyn/tenant-data-admin/server/serve-media-cdn'\n\n/**\n * Turning a URL stored on a product into a link a buyer may follow (AGL-2814).\n *\n * A product's paid media — its members videos — is stored as whatever the\n * author's picker wrote: a media reference, a CDN path, a raw Storage download\n * URL, or a hotlink somebody typed. `parsePaidMediaSource` says which of those\n * a value is. The commerce routes verify who is entitled and then redirect;\n * this module decides WHERE they may redirect, and its whole job is that the\n * answer is never a URL that outlives the purchase.\n *\n * ## The rules, in the order they are applied\n *\n * 1. **A library asset is delivered only when it is PRIVATE**, as a CDN URL\n * signed with {@link mintMediaSignature}. The CDN refuses a private asset on\n * every path without an unexpired signature, which is what makes the link\n * die. A public asset is refused here instead of redirected to: its URL\n * works for anyone forever, so handing it to a buyer is the leak itself.\n * 2. **A Storage download URL is never redirected to.** Its token lives as\n * long as the object. When the object belongs to a library asset, rule 1\n * applies to that asset. When no asset owns it (a legacy object, a derived\n * rendition file), it gets a V4 signed read URL with the same bounded\n * lifetime. When it is not in this platform's bucket, or not inside the\n * site's own library or its org's, it is refused.\n * 3. **Only the requesting site's own libraries are signed.** A product is\n * author data. Signing whatever scope it names would let one site's author\n * mint working links to another org's private files, so a host scope must\n * be this site and an org scope must be this site's org, and the signed\n * scope is always qualified with this site so the CDN's `visibleTo` check\n * runs against the site actually selling it.\n * 4. **A hotlink to somebody else's server passes through unchanged.** No code\n * of ours runs there and nothing here can make its URL expire. That is the\n * author's hosting decision, and the docs say so. EXCEPT a hotlink whose\n * host wears a brand it is not (`lookalikeBrandForHost`, the phishing\n * screen's rule): the redirect leaves from the merchant's own domain, so a\n * lure behind it is one no screen of the page or the receipt ever saw. It\n * is refused for every workspace, like a lookalike link in an email\n * (AGL-3363), and the caller files it.\n * 5. **A signed Storage read is a download when it is one.** A download, or\n * an object whose type a browser would run (HTML, SVG, XML), is signed\n * with `response-content-disposition: attachment`, so the file is saved\n * rather than rendered (AGL-3363). The CDN already does this for its own\n * deliveries; a V4 URL carried nothing.\n *\n * ## A video with a copy at the delivery provider (AGL-2824)\n *\n * A caller that asks for it with `delivery` gets, for a video that passes\n * rule 1, the delivery provider's own short-lived URL instead of the signed CDN\n * URL, whenever `mediaDeliveryRedirect` finds a current copy and the release\n * flag is on for the owning org. It is the URL the CDN would redirect the\n * signed request to anyway, minted one hop earlier and bounded by the same\n * lifetime. Anything else takes the signed CDN URL exactly as before.\n */\n\n/** Why a stored URL was not turned into a link. */\nexport type PaidMediaRefusal =\n /** A library asset the public can still fetch without a signature. */\n | 'not-private'\n /** No such asset, a deleted one, or one not shared with this site. */\n | 'not-found'\n /** Another site's library, another org's, or outside the media prefixes. */\n | 'out-of-scope'\n /** A Storage URL for a bucket this platform does not serve from. */\n | 'foreign-storage'\n /** Not a value any delivery can be built from. */\n | 'malformed'\n /** A hotlink to a host that wears another brand's name (AGL-3363). */\n | 'lookalike'\n\nexport type PaidMediaDelivery =\n | {\n ok: true\n via: 'signed-cdn'\n location: string\n expiresAtMs: number\n /** The scope segment the signature covers. */\n scope: string\n mediaId: string\n }\n | {\n ok: true\n via: 'signed-storage'\n location: string\n expiresAtMs: number\n objectPath: string\n /** Whose library the object is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The object's size, 0 when Storage did not say. */\n sizeBytes: number\n }\n | { ok: true; via: 'external'; location: string }\n | {\n ok: true\n via: 'delivery'\n location: string\n expiresAtMs: number\n /** The scope segment the delivery was minted for. */\n scope: string\n mediaId: string\n /** Whose library the asset is in, for the bandwidth count. */\n collection: 'hosts' | 'orgs'\n scopeId: string\n /** The size of the copy the provider serves. */\n sizeBytes: number\n }\n | {\n ok: false\n refusal: PaidMediaRefusal\n /** For a `lookalike`: the host it wears a brand in, for the caller to file. */\n host?: string\n }\n\n/** A document read, reduced to what this module asks of one. */\nexport interface PaidMediaDocument {\n exists: boolean\n get(field: string): unknown\n}\n\n/** Every read and signature this module needs, injectable for tests. */\nexport interface PaidMediaDeliveryIo {\n /** The platform's media bucket; empty when unconfigured. */\n bucketName: string\n readMedia(\n collection: 'hosts' | 'orgs',\n scopeId: string,\n mediaId: string,\n ): Promise<PaidMediaDocument>\n /** The org a site belongs to, or null for an unindexed site. */\n orgIdForHost(hostId: string): Promise<string | null>\n /**\n * A V4 signed read URL for one object in {@link bucketName}. `attachment`\n * signs `response-content-disposition: attachment` into it (AGL-3363).\n */\n signStorageRead(\n objectPath: string,\n expiresAtMs: number,\n options?: { attachment?: boolean },\n ): Promise<string>\n /**\n * The object's size in bytes, for the bandwidth a signed read can send;\n * 0 when it cannot be read. Optional, so a double that never signs a\n * Storage read need not answer it.\n */\n storageObjectSize?(objectPath: string): Promise<number>\n}\n\n/** Object types a browser runs rather than shows: always saved, never rendered. */\nconst ACTIVE_OBJECT_EXTENSION = /\\.(html?|xhtml|xht|svgz?|xml|xsl|xslt|mht|mhtml|js|mjs)$/i\n\n/** Is this signed read a download, by the caller's ask or by what the object is? */\nexport function storageReadIsAttachment(\n objectPath: string,\n cdnParams: ReadonlyArray<readonly [string, string]> | undefined,\n): boolean {\n if ((cdnParams ?? []).some(([key, value]) => key === 'download' && value === '1')) {\n return true\n }\n return ACTIVE_OBJECT_EXTENSION.test(objectPath)\n}\n\n/**\n * Resolves a stored product media URL to a redirect target that expires, or\n * says why there is none. See the module comment for the rules.\n *\n * `cdnParams` ride on a signed CDN URL ahead of the signature, which covers\n * `(scope, mediaId, exp)` and never the parameters, so they select a\n * representation of the one asset the signature names and nothing else.\n */\nexport async function resolvePaidMediaDelivery(options: {\n stored: unknown\n /** The site selling the media; the only libraries it may sign from. */\n hostId: string\n /** The lifetime of the link; bounded by `assertMediaSignatureTtl`. */\n ttlMs: number\n cdnParams?: ReadonlyArray<readonly [string, string]>\n /**\n * Hand a video with a current copy at the delivery provider its URL there\n * (AGL-2824). `accept` is the request's `Accept`, which chooses the\n * rendition when `cdnParams` asks for `?r=auto`. The provider and the flag\n * verdict default to the registered provider and the release flag.\n */\n delivery?: {\n accept?: unknown\n provider?: MediaDeliveryProvider | null\n enabled?: (orgId: string | null) => Promise<boolean>\n }\n nowMs?: number\n io: PaidMediaDeliveryIo\n}): Promise<PaidMediaDelivery> {\n const { hostId, ttlMs, io } = options\n const nowMs = options.nowMs ?? Date.now()\n const refuse = (refusal: PaidMediaRefusal): PaidMediaDelivery => ({\n ok: false,\n refusal,\n })\n if (!hostId) return refuse('out-of-scope')\n\n // One lookup per call, and only for the forms that need to know the org.\n let orgId: Promise<string | null> | undefined\n const siteOrgId = () => (orgId ??= io.orgIdForHost(hostId))\n\n /**\n * The delivery provider's URL for a private library video, or null for\n * the signed CDN URL. The representation is the one the CDN would pick for\n * the same `?r=` and `Accept`, so the buyer gets the copy the signed URL\n * would have been redirected to.\n */\n const deliverFromProvider = async (\n delivery: NonNullable<typeof options.delivery>,\n asset: {\n collection: 'hosts' | 'orgs'\n scopeId: string\n orgScope: boolean\n deliveryScope: string\n mediaId: string\n document: PaidMediaDocument\n },\n ): Promise<PaidMediaDelivery | null> => {\n const provider =\n delivery.provider === undefined ? mediaDeliveryProvider('deliver') : delivery.provider\n if (!provider) return null\n const requested = (options.cdnParams ?? []).find(\n ([key]) => key === MEDIA_CDN_RENDITION_PARAM,\n )?.[1]\n const renditions = parseMediaRenditions(asset.document.get('videoRenditions'))\n const rendition = !requested\n ? undefined\n : requested === MEDIA_CDN_RENDITION_AUTO\n ? selectAutoRendition(renditions, delivery.accept)\n : renditions.find((entry) => entry.key === requested)\n const redirect = await mediaDeliveryRedirect({\n provider,\n asset: {\n collection: asset.collection,\n scopeId: asset.scopeId,\n mediaId: asset.mediaId,\n },\n document: asset.document,\n rendition,\n servedType: rendition ? rendition.contentType : asset.document.get('contentType'),\n claims: { scope: asset.deliveryScope, mediaId: asset.mediaId, hostId },\n orgId: async () => (asset.orgScope ? asset.scopeId : await siteOrgId()),\n ...(delivery.enabled ? { deliveryEnabled: delivery.enabled } : {}),\n ttlMs,\n nowMs,\n }).catch(() => null)\n if (!redirect) return null\n return {\n ok: true,\n via: 'delivery',\n location: redirect.location,\n expiresAtMs: redirect.expiresAtMs,\n scope: asset.deliveryScope,\n mediaId: asset.mediaId,\n collection: asset.collection,\n scopeId: asset.scopeId,\n sizeBytes: redirect.sizeBytes,\n }\n }\n\n const deliverAsset = async (\n scope: string,\n mediaId: string,\n ): Promise<PaidMediaDelivery> => {\n const parsed = parseMediaCdnScope(scope)\n if (!parsed) return refuse('malformed')\n let collection: 'hosts' | 'orgs'\n let deliveryScope: string\n if (parsed.isOrg) {\n const owner = await siteOrgId()\n if (!owner || parsed.scopeId !== owner) return refuse('out-of-scope')\n collection = 'orgs'\n deliveryScope = hostQualifiedScope(scope, hostId)\n } else {\n if (parsed.scopeId !== hostId) return refuse('out-of-scope')\n collection = 'hosts'\n deliveryScope = hostId\n }\n const deliveryParsed = parseMediaCdnScope(deliveryScope)\n if (!deliveryParsed) return refuse('malformed')\n const document = await io.readMedia(collection, parsed.scopeId, mediaId)\n if (!document?.exists || document.get('deletedAt')) {\n return refuse('not-found')\n }\n // The CDN would 404 an org asset this site is not allowed to use, so a\n // link to one is a link that cannot play.\n if (\n mediaCdnScopeRefusal(\n deliveryParsed,\n document.get('visibleTo'),\n document.get('scopeMode'),\n )\n ) {\n return refuse('not-found')\n }\n if (document.get('private') !== true) return refuse('not-private')\n assertMediaSignatureTtl(ttlMs)\n const delivered = options.delivery\n ? await deliverFromProvider(options.delivery, {\n collection,\n scopeId: parsed.scopeId,\n orgScope: parsed.isOrg,\n deliveryScope,\n mediaId,\n document,\n })\n : null\n if (delivered) return delivered\n const signature = mintMediaSignature(deliveryScope, mediaId, nowMs, ttlMs)\n const params = new URLSearchParams()\n for (const [key, value] of options.cdnParams ?? []) {\n if (key !== 'exp' && key !== 'sig') params.set(key, value)\n }\n const prefix = params.toString()\n return {\n ok: true,\n via: 'signed-cdn',\n location:\n `${MEDIA_CDN_ROUTE}/${deliveryScope}/${mediaId}?` +\n `${prefix ? `${prefix}&` : ''}${mediaSignatureQuery(signature)}`,\n expiresAtMs: signature.exp,\n scope: deliveryScope,\n mediaId,\n }\n }\n\n const source = parsePaidMediaSource(options.stored)\n switch (source.kind) {\n case 'malformed':\n return refuse('malformed')\n case 'external': {\n let externalHost: string\n try {\n externalHost = new URL(source.url).hostname\n } catch {\n return refuse('malformed')\n }\n if (lookalikeBrandForHost(externalHost)) {\n return { ok: false, refusal: 'lookalike', host: externalHost }\n }\n return { ok: true, via: 'external', location: source.url }\n }\n case 'asset':\n return deliverAsset(source.scope, source.mediaId)\n case 'storage-object': {\n if (!io.bucketName || source.bucket !== io.bucketName) {\n return refuse('foreign-storage')\n }\n const { objectPath } = source\n const segments = objectPath.split('/')\n let base: string | null = null\n if (segments[0] === 'hosts' && segments[1] === hostId) {\n base = `hosts/${hostId}`\n } else if (segments[0] === 'orgs' && segments[1]) {\n const owner = await siteOrgId()\n if (owner && segments[1] === owner) base = `orgs/${owner}`\n }\n // The same prefix test the CDN applies to a document's `storagePath`,\n // which also refuses traversal and empty segments.\n if (!base || !isMediaStoragePathInScope(objectPath, base)) {\n return refuse('out-of-scope')\n }\n // An object keyed like an asset IS that asset, and the asset's own rules\n // decide — including refusing it when the asset is still public.\n const asset = paidMediaAssetOfObject(objectPath)\n if (asset) return deliverAsset(asset.scope, asset.mediaId)\n assertMediaSignatureTtl(ttlMs)\n const expiresAtMs = nowMs + ttlMs\n const [location, sizeBytes] = await Promise.all([\n io.signStorageRead(objectPath, expiresAtMs, {\n attachment: storageReadIsAttachment(objectPath, options.cdnParams),\n }),\n io.storageObjectSize?.(objectPath).catch(() => 0) ?? Promise.resolve(0),\n ])\n return {\n ok: true,\n via: 'signed-storage',\n location,\n expiresAtMs,\n objectPath,\n collection: segments[0] === 'orgs' ? 'orgs' : 'hosts',\n scopeId: segments[1],\n sizeBytes,\n }\n }\n }\n}\n\n/**\n * The production reads behind {@link resolvePaidMediaDelivery}, built on the\n * caller's Firestore and bucket handles so a route's own mocks reach them.\n */\nexport function createPaidMediaDeliveryIo(options: {\n firestore: {\n collection(name: string): {\n doc(id: string): {\n get(): Promise<PaidMediaDocument>\n collection(name: string): {\n doc(id: string): { get(): Promise<PaidMediaDocument> }\n }\n }\n }\n }\n bucket: {\n name?: string\n file(path: string): {\n getSignedUrl(config: {\n version: 'v4'\n action: 'read'\n expires: number\n responseDisposition?: string\n }): Promise<[string] | string[]>\n getMetadata?(): Promise<[{ size?: unknown }, ...unknown[]] | Array<{ size?: unknown }>>\n }\n }\n}): PaidMediaDeliveryIo {\n const { firestore, bucket } = options\n return {\n bucketName: String(bucket?.name ?? ''),\n readMedia: (collection, scopeId, mediaId) =>\n firestore\n .collection(collection)\n .doc(scopeId)\n .collection('media')\n .doc(mediaId)\n .get(),\n orgIdForHost: async (hostId) => {\n const index = await firestore.collection('hostIndex').doc(hostId).get()\n const orgId = index.exists ? index.get('orgId') : undefined\n return typeof orgId === 'string' && orgId ? orgId : null\n },\n signStorageRead: async (objectPath, expiresAtMs, signOptions) => {\n const [url] = await bucket.file(objectPath).getSignedUrl({\n version: 'v4',\n action: 'read',\n expires: expiresAtMs,\n ...(signOptions?.attachment ? { responseDisposition: 'attachment' } : {}),\n })\n return String(url)\n },\n storageObjectSize: async (objectPath) => {\n const file = bucket.file(objectPath)\n if (!file.getMetadata) return 0\n const [metadata] = await file.getMetadata()\n const size = Number(metadata?.size)\n return Number.isSafeInteger(size) && size > 0 ? size : 0\n },\n }\n}\n"],"names":["hostQualifiedScope","MEDIA_CDN_RENDITION_AUTO","MEDIA_CDN_RENDITION_PARAM","MEDIA_CDN_ROUTE","paidMediaAssetOfObject","parseMediaRenditions","parsePaidMediaSource","mediaDeliveryProvider","lookalikeBrandForHost","mediaDeliveryRedirect","assertMediaSignatureTtl","mediaSignatureQuery","mintMediaSignature","isMediaStoragePathInScope","mediaCdnScopeRefusal","parseMediaCdnScope","selectAutoRendition","ACTIVE_OBJECT_EXTENSION","storageReadIsAttachment","objectPath","cdnParams","some","key","value","test","resolvePaidMediaDelivery","options","hostId","ttlMs","io","nowMs","Date","now","refuse","refusal","ok","orgId","siteOrgId","orgIdForHost","deliverFromProvider","delivery","asset","provider","undefined","requested","find","renditions","document","get","rendition","accept","entry","redirect","collection","scopeId","mediaId","servedType","contentType","claims","scope","deliveryScope","orgScope","enabled","deliveryEnabled","catch","via","location","expiresAtMs","sizeBytes","deliverAsset","parsed","isOrg","owner","deliveryParsed","readMedia","exists","delivered","signature","params","URLSearchParams","set","prefix","toString","exp","source","stored","kind","externalHost","URL","url","hostname","host","bucketName","bucket","segments","split","base","Promise","all","signStorageRead","attachment","storageObjectSize","resolve","createPaidMediaDeliveryIo","firestore","String","name","doc","index","signOptions","file","getSignedUrl","version","action","expires","responseDisposition","getMetadata","metadata","size","Number","isSafeInteger"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,kBAAkB,EAClBC,wBAAwB,EACxBC,yBAAyB,EACzBC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