@aglyn/plugins-commerce 1.0.0-beta.288 → 1.0.0-beta.289
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +13 -13
- package/src/lib/components/commerce-console-page.js +29 -2
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/console/commerce-analytics-card.component.js +4 -2
- package/src/lib/components/console/commerce-analytics-card.component.js.map +1 -1
- package/src/lib/components/console/host-orders-card.component.js +5 -1
- package/src/lib/components/console/host-orders-card.component.js.map +1 -1
- package/src/lib/components/console/host-quotes-card.component.d.ts +34 -0
- package/src/lib/components/console/host-quotes-card.component.js +247 -0
- package/src/lib/components/console/host-quotes-card.component.js.map +1 -0
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js +33 -28
- package/src/lib/components/console/pos-ops/pos-check-ins-card.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.d.ts +45 -0
- package/src/lib/components/console/quote-editor-dialog.component.js +1266 -0
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -0
- package/src/lib/components/console/quote-pay-link.component.d.ts +38 -0
- package/src/lib/components/console/quote-pay-link.component.js +213 -0
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -0
- package/src/lib/components/console/quote-settings-card.component.d.ts +29 -0
- package/src/lib/components/console/quote-settings-card.component.js +121 -0
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -0
- package/src/lib/components/console/tax-settings-card.component.js +4 -1
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/components/quote-page-body.d.ts +33 -0
- package/src/lib/components/quote-page-body.js +696 -0
- package/src/lib/components/quote-page-body.js.map +1 -0
- package/src/lib/components/quote-page.d.ts +29 -0
- package/src/lib/components/quote-page.js +96 -0
- package/src/lib/components/quote-page.js.map +1 -0
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +8 -3
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/constants/orders-list-query.js +6 -1
- package/src/lib/constants/orders-list-query.js.map +1 -1
- package/src/lib/constants/quote-page.d.ts +30 -0
- package/src/lib/constants/quote-page.js +35 -0
- package/src/lib/constants/quote-page.js.map +1 -0
- package/src/lib/model/commerce-orders.d.ts +25 -2
- package/src/lib/model/commerce-orders.js +10 -1
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-quote-pay.d.ts +229 -0
- package/src/lib/model/commerce-quote-pay.js +393 -0
- package/src/lib/model/commerce-quote-pay.js.map +1 -0
- package/src/lib/model/commerce-quotes.d.ts +279 -0
- package/src/lib/model/commerce-quotes.js +522 -0
- package/src/lib/model/commerce-quotes.js.map +1 -0
- package/src/lib/model/index.d.ts +2 -0
- package/src/lib/model/index.js +2 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/plugin-permissions.d.ts +1 -1
- package/src/lib/model/plugin-permissions.js +20 -0
- package/src/lib/model/plugin-permissions.js.map +1 -1
- package/src/lib/server/api-v1/orders-and-products.js +6 -2
- package/src/lib/server/api-v1/orders-and-products.js.map +1 -1
- package/src/lib/server/billing-webhook.js +127 -52
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +36 -0
- package/src/lib/server/checkout-session-expiry.js +63 -0
- package/src/lib/server/checkout-session-expiry.js.map +1 -0
- package/src/lib/server/draft-order.js +16 -8
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/person-eraser.d.ts +7 -0
- package/src/lib/server/person-eraser.js +24 -2
- package/src/lib/server/person-eraser.js.map +1 -1
- package/src/lib/server/pos-return.js +3 -1
- package/src/lib/server/pos-return.js.map +1 -1
- package/src/lib/server/quote-link-token.d.ts +39 -0
- package/src/lib/server/quote-link-token.js +97 -0
- package/src/lib/server/quote-link-token.js.map +1 -0
- package/src/lib/server/quote-pay.d.ts +83 -0
- package/src/lib/server/quote-pay.js +606 -0
- package/src/lib/server/quote-pay.js.map +1 -0
- package/src/lib/server/quote.d.ts +49 -0
- package/src/lib/server/quote.js +513 -0
- package/src/lib/server/quote.js.map +1 -0
- package/src/lib/server/related.js +2 -0
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/site-page-resolver.d.ts +2 -0
- package/src/lib/server/site-page-resolver.js +75 -0
- package/src/lib/server/site-page-resolver.js.map +1 -1
- package/src/lib/server.js +14 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/site.js +6 -0
- package/src/lib/site.js.map +1 -1
- package/src/lib/transfer/tracking.server.js +6 -0
- package/src/lib/transfer/tracking.server.js.map +1 -1
package/src/lib/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.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/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerStoreSetupAiCapabilities } from './server/store-setup-ai-capability'\nimport { registerStoreSetupAiWriter } from './server/store-setup-ai-writer.console'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The review-request email (AGL-3736). HOURLY: a request is owed days after\n * fulfilment, so an hour's lateness is invisible, and the scan is one\n * collection-group range query over `reviewRequestDueAtMs` — a field only\n * orders still owed a request carry, so an empty beat costs one read.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'review-request-emails',\n intervalMinutes: 60,\n description:\n 'Email each buyer one review request, with a single-use link per product, ' +\n 'days after their order is fulfilled (AGL-3736).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { scanReviewRequests } = await import('./server/review-requests')\n const { sent } = await scanReviewRequests(gate)\n if (sent) console.info(`commerce: sent ${sent} review requests`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * The monthly 4G charge for Stripe Reader S710s (AGL-4038): each workspace\n * whose readers had 4G in the month just ended is charged once, through\n * core's usage-invoice charge. Every six hours, so the charge goes out early\n * on the 1st and one that could not reach Stripe is tried again the same\n * day; a month already settled costs a read per workspace. Nothing runs\n * where 4G is not offered (`POS_CELLULAR_MONTHLY_COST_CENTS` unset).\n * Per-host: a store locked for security or abuse is not charged while it is.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-cellular-billing',\n intervalMinutes: 6 * 60,\n description:\n 'Charge each workspace for 4G on its Stripe Reader S710s for the month just ended, once (AGL-4038).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY || !process.env.POS_CELLULAR_MONTHLY_COST_CENTS) return\n const { runPosCellularBilling } = await import('./server/pos-cellular-billing')\n const report = await runPosCellularBilling(gate)\n if (report.workspaces || report.storesGone || report.warned || report.turnedOff || report.paidLate) {\n console.info(\n `commerce: 4G for ${report.month} — ${report.paid} paid, ${report.open} left open, ` +\n `${report.failed} not reached, ${report.unbillable} not billable, ${report.deferred} deferred, ` +\n `${report.storesGone} deleted stores turned off; unpaid charges: ${report.warned} warned, ` +\n `${report.paidLate} paid since, ${report.turnedOff} turned off`,\n )\n }\n },\n})\n\n/**\n * Card reader start-up screens (AGL-4048) that went stale with nobody opening\n * the POS devices card: a logo changed on the organization profile or the\n * white-label brand, or the logo's file replaced in the media library. Every\n * 15 minutes, like the recovery pair: a store whose screen did not move costs\n * a few reads and no Stripe call, and nothing a merchant saves waits on it.\n * A screen Stripe refused is retried after six hours here, and at once when\n * the card is opened.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-reader-splash-refresh',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Bring card reader start-up screens up to date after a logo change (AGL-4048).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { refreshPosReaderSplashes } = await import('./server/pos-reader-splash')\n const result = await refreshPosReaderSplashes(gate)\n if (result.applied || result.failed || result.more) {\n console.info(\n `commerce: reader start-up screens — ${result.applied} updated, ` +\n `${result.failed} failed${result.more ? ', more stores than one pass reaches' : ''}`,\n )\n }\n },\n})\n\n/**\n * Cards taken offline whose sale never synced (AGL-4039).\n *\n * HOURLY. The alert falls due six hours after the intent was first seen, and\n * Stripe's authorization lasts about two days, so an hour's delay costs\n * nothing and leaves the beat one collection-group range read that is empty in\n * the ordinary case. It never captures: without the sale there is no fee to\n * capture with, so it tells the operator and the site's managers instead.\n *\n * Not gated on `isEmailConfigured()`: the console notification and the\n * operator alert both work without mail.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'offline-card-unsynced',\n intervalMinutes: 60,\n description:\n 'Tell the operator and the site when a card taken offline reached Stripe but its sale never synced (AGL-4039).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const { scanUnsyncedOfflineCards } = await import('./server/pos-offline-card-reconcile')\n const scan = await scanUnsyncedOfflineCards(gate)\n if (scan.alerted) {\n console.warn(`commerce: ${scan.alerted} cards taken offline have no synced sale`)\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and the store's shipping, pickup, local delivery and tax settings an AI\n // build sets up (AGL-3749), written live as the console's cards write them,\n // with the four operations that writer executes.\n registerStoreSetupAiWriter()\n registerStoreSetupAiCapabilities()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // A paid card-reader order from the POS hardware shop (AGL-4038), on the\n // same platform webhook: its own handler, self-selecting on the session's\n // `metadata.type`, so the storefront sections above never see it.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-hardware-webhook')).posHardwareBillingWebhookHandler(event),\n )\n // A card the Aglyn POS app took offline (AGL-4039): its PaymentIntent can\n // reach Stripe before the sale reaches the server, so every event on one is\n // kept by the sale's key. Self-selecting on `metadata.kind`.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-offline-card-reconcile')).posOfflineCardBillingWebhookHandler(event),\n )\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // A staff walk-in from the Reservations card and the native apps\n // (AGL-4046): availability re-asked inside the transaction that writes, so\n // two staff cannot hand out the last unit at once. Loaded on first call.\n registerPluginApiRoute('commerce/reservations/walk-in', async (req, res) =>\n (await import('./server/reservation-walk-in')).reservationWalkInHandler(req, res),\n )\n // A stay's guest count after it is booked (AGL-4043), from the Reservations\n // card and the check-in screen: the walk-in's gate, and the stay's\n // check-ins for today on brought in line in the same transaction. Loaded\n // on first call.\n registerPluginApiRoute('commerce/reservations/guests', async (req, res) =>\n (await import('./server/reservation-guests')).reservationGuestsHandler(req, res),\n )\n // The products list's Duplicate and Delete for the native apps (AGL-3841):\n // the console's own copy and soft delete, with the site-wide cache drop.\n registerPluginApiRoute('commerce/products/duplicate', async (req, res) =>\n (await import('./server/products-write')).productDuplicateHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/delete', async (req, res) =>\n (await import('./server/products-write')).productDeleteHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // The order dialog's Packing slip and Invoice for the native apps\n // (AGL-3841): the console's own two pages over the stored order, which the\n // apps print on the device's print sheet. Loaded on first call.\n registerPluginApiRoute('commerce/order-print', async (req, res) =>\n (await import('./server/order-print')).orderPrintHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The POS hardware shop (AGL-4038): the Hardware card's catalog, Checkout\n // and order list, gated like a sale and hidden until the deployment prices\n // it; and the staff page's orders, which name no site. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware', async (req, res) =>\n (await import('./server/pos-hardware')).posHardwareHandler(req, res),\n )\n // Selling a card reader in person at the platform's own store's register\n // (AGL-4038): whether this store is that seller. Gated like a sale, and\n // silent about the configuration on every other store. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware-sale', async (req, res) =>\n (await import('./server/pos-hardware-sale')).posHardwareSaleHandler(req, res),\n )\n // A store's card reader start-up screen (AGL-4048): the POS devices card's\n // setting, gated like a sale, and the staff page's platform default. Each\n // loads with its first call; the drawing they ask for is the images\n // route's, below.\n registerPluginApiRoute('commerce/pos-reader-splash', async (req, res) =>\n (await import('./server/pos-reader-splash')).posReaderSplashHandler(req, res),\n )\n registerPluginApiRoute('commerce/admin/reader-splash', {\n web: async (request) =>\n (await import('./server/pos-reader-splash-admin')).posReaderSplashAdmin(request),\n })\n // The image work behind both (AGL-4048): drawing a screen and reading an\n // uploaded one take `sharp`, whose native library only the console's\n // plugins' image function ships (`/api/plugin-images/…`), so the plugin\n // API's function does not carry it. Called by our own servers, signed; a\n // machine's door.\n registerPluginApiRoute(\n 'commerce/pos-reader-splash-images',\n {\n web: async (request) =>\n (await import('./server/pos-reader-splash-images-route')).posReaderSplashImagesRoute(request),\n },\n { machine: true, images: true },\n )\n registerPluginApiRoute('commerce/admin/hardware-orders', {\n web: async (request) =>\n (await import('./server/pos-hardware-admin')).posHardwareAdminOrders(request),\n })\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerStoreSetupAiCapabilities","registerStoreSetupAiWriter","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scanReviewRequests","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","POS_CELLULAR_MONTHLY_COST_CENTS","runPosCellularBilling","report","workspaces","storesGone","warned","turnedOff","paidLate","month","paid","open","unbillable","deferred","refreshPosReaderSplashes","applied","more","scanUnsyncedOfflineCards","alerted","CARD_PAYMENT_DOOR","cardPayment","registerCommerceApi","req","res","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","registerCommerceConsoleApi","event","posHardwareBillingWebhookHandler","posOfflineCardBillingWebhookHandler","localFulfillmentHandler","productSaveHandler","productStockHandler","reservationWalkInHandler","reservationGuestsHandler","productDuplicateHandler","productDeleteHandler","orderNoteHandler","orderRestockAnswerHandler","orderPrintHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posHardwareHandler","posHardwareSaleHandler","posReaderSplashHandler","posReaderSplashAdmin","posReaderSplashImagesRoute","images","posHardwareAdminOrders","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAGD;;;;;;;CAOC,GAED,SACEA,6BAA6B,EAC7BC,sBAAsB,EACtBC,iBAAiB,EACjBC,wBAAwB,EACxBC,wBAAwB,EACxBC,yBAAyB,EACzBC,0BAA0B,QACrB,sBAAqB;AAC5B,SAASC,iBAAiB,QAAQ,2BAA0B;AAC5D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,iCAAiC,QAAQ,kCAA8B;AAChF,SAASC,gCAAgC,QAAQ,gCAA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AAqE;IACrE,yEAAyE;IACzE,uDAAuD;IACvDlH,2BAA2B,IAAMhB,cAAcuK,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/server.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/**\n * Server half of the commerce plugin (AGL-396): the site-facing storefront\n * API handlers, registered with the plugin API registry and served by the\n * tenant dispatcher at their unchanged `/api/commerce/*` URLs. This module\n * pulls in firebase-admin + Stripe, so it is NOT re-exported from the client\n * barrel — apps import `@aglyn/plugins-commerce/server` only from their\n * (server-only) API dispatcher registration.\n */\n\nimport {\n registerBillingWebhookHandler,\n registerPluginApiRoute,\n registerPluginJob,\n registerSitePageEnricher,\n registerSitePageResolver,\n registerPluginPermissions,\n registerPluginConfigSchema,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { isEmailConfigured } from '@aglyn/shared-util-email'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { registerCommerceMediaPublishGuard } from './server/media-publish-guard'\nimport { registerCommerceRecurringCharges } from './server/recurring-charges'\nimport { registerProductCardReader } from './server/product-card'\nimport { registerProductAiCapability } from './server/product-ai-capability'\nimport { registerStoreSetupAiCapabilities } from './server/store-setup-ai-capability'\nimport { registerStoreSetupAiWriter } from './server/store-setup-ai-writer.console'\nimport { registerProductDraftWriter } from './server/product-drafts'\nimport { registerCommerceTaxProfile } from './server/tax-profile'\nimport { registerTaxReturnSource } from '@aglyn/aglyn/plugin-manager/plugin-tax-return-sources'\nimport { commerceTaxReturnSource } from './server/tax-return-source'\nimport { taxSummaryHandler } from './server/tax-summary'\nimport { registerRevenueSource } from '@aglyn/aglyn/plugin-manager/plugin-revenue-sources'\nimport { commerceRevenueSource } from './server/revenue-source'\nimport { commerceBillingWebhookHandler } from './server/billing-webhook'\nimport { registerOrderFigureReaders } from './server/order-figures'\nimport { COMMERCE_PERMISSIONS } from './model/plugin-permissions'\nimport { COMMERCE_CONFIG_SCHEMA } from './plugin-config'\nimport { commerceSitePageEnricher } from './server/site-page-enricher'\nimport { commerceSitePageResolver } from './server/site-page-resolver'\nimport { cartCheckoutHandler } from './server/cart-checkout'\nimport { cartHandler } from './server/cart'\nimport { cartExtrasHandler } from './server/checkout-extras'\nimport { catalogHandler } from './server/catalog'\nimport { checkoutHandler } from './server/checkout'\nimport { downloadHandler } from './server/download'\nimport { newsletterHandler } from './server/newsletter'\nimport { notifyRestockHandler } from './server/notify-restock'\nimport { productHandler } from './server/product'\nimport { relatedHandler } from './server/related'\nimport { reservationAvailabilityHandler } from './server/reservation-availability'\nimport { gateHandler } from './server/gate'\nimport { memberFeedHandler } from './server/member-feed'\nimport { membershipAccountHandler } from './server/membership-account'\nimport { membershipAdminPasswordHandler } from './server/membership-admin-password'\nimport { membershipAdminRemoveHandler } from './server/membership-admin-remove'\nimport { membershipContentHandler } from './server/membership-content'\nimport { membershipLoginHandler } from './server/membership-login'\nimport { membershipLogoutHandler } from './server/membership-logout'\nimport { membershipRecoverHandler } from './server/membership-recover'\nimport { membershipRegisterHandler } from './server/membership-register'\nimport { membershipResetHandler } from './server/membership-reset'\nimport { membershipWishlistHandler } from './server/membership-wishlist'\nimport { reserveHandler } from './server/reserve'\nimport { streamHandler } from './server/stream'\nimport { subscriptionPortalHandler } from './server/subscription-portal'\nimport { reviewsHandler } from './server/reviews'\nimport { connectHandler } from './server/connect'\nimport { cancelOrderHandler } from './server/cancel-order'\nimport { carrierRatesAvailabilityHandler } from './server/carrier-rates-availability'\nimport { collectionMembershipHandler } from './server/collection-membership'\nimport { draftOrderHandler } from './server/draft-order'\nimport { fulfillOrderHandler } from './server/fulfill-order'\nimport { orderReceiptSendHandler } from './server/order-receipt-send'\nimport { orderStatusHandler, registerOrderStatusActions } from './server/order-status'\nimport { returnRequestStatusAction } from './server/return-status-action'\nimport { giftCardsHandler } from './server/gift-cards'\nimport { memberPostHandler } from './server/member-post'\nimport { orderAnalyticsHandler } from './server/order-analytics'\nimport { checkoutStatusHandler } from './server/checkout-status'\nimport { posOrderHandler } from './server/pos-order'\nimport { printersHandler } from './server/printers'\nimport { posPaymentHandler } from './server/pos-payment'\nimport { posReadersHandler } from './server/pos-readers'\nimport { posTerminalConnectionTokenHandler } from './server/pos-terminal-connection-token'\nimport { posDisplayHandler } from './server/pos-display'\nimport { posKioskHandler } from './server/pos-kiosk'\nimport { registerPosOpsRoutes } from './server/pos-ops-routes'\nimport {\n processAbandonedHandler,\n scanAbandonedCheckouts,\n} from './server/process-abandoned'\nimport { processRestockHandler, scanRestockAlerts } from './server/process-restock'\nimport { scanStockDecrements } from './server/reconcile-stock'\nimport { refundHandler } from './server/refund'\nimport { orderWebhooksHandler } from './server/order-webhooks'\nimport { returnRequestHandler, returnsHandler } from './server/returns'\nimport { scanSupplierDeliveries } from './server/supplier-outbox'\nimport { supplierUpdateHandler } from './server/supplier-update'\n\n/**\n * The two commerce beats (AGL-2227).\n *\n * `commerce/process-abandoned` and `commerce/process-restock` have existed\n * since AGL-323/326 as `x-cron-secret` HTTP doors, and `registerCommerceConsoleApi`\n * below has called them \"the scheduler-driven jobs\" in a comment that whole\n * time. **Nothing scheduled them.** Not `scheduled-crons.yml` (its table names\n * 11 paths; neither of these), not `vercel.json` (no `crons` key at all), not\n * `registerPluginJob` — the only two registrations in the repo were scheduled\n * publishing and the bookings hold-expiry.\n *\n * The cost was a Pro-tier entitlement (`abandonedCart`) that had never sent an\n * email, and a storefront \"notify me when it's back\" form writing into a queue\n * with no drain. AGL-1793 had already added the collection-group indexes these\n * two scans need, which is the clearest evidence they were always meant to run.\n *\n * Module scope, like the bookings job beside it: the runner route reaches jobs\n * through `ensureAll(['tenantApi'])`, and a registration inside a `register*`\n * function would depend on which entry point happened to be loaded.\n *\n * 15 minutes, not 1: `process-abandoned` will not remind a checkout younger\n * than an hour and `process-restock` only mails alerts whose product already\n * has stock, so a tighter beat buys nothing and costs two collection-group\n * scans a minute. Both are bounded (200 docs) and idempotent — each pass\n * stamps what it sent — so an overlapping or repeated beat cannot double-send.\n */\nconst RECOVERY_JOB_INTERVAL_MINUTES = 15\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'abandoned-checkout-recovery',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Email one recovery reminder per stalled checkout (abandonedCart plans).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n // Quietly, not as an error: email is optional per deployment, and a beat\n // that logs every minute on a self-host without Resend buries everything\n // else in the log.\n if (!isEmailConfigured()) return\n const { sent } = await scanAbandonedCheckouts(gate)\n if (sent) console.info(`commerce: sent ${sent} abandoned-cart reminders`)\n },\n})\n\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'back-in-stock-alerts',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description: 'Email shoppers whose requested product is in stock again.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { sent } = await scanRestockAlerts(gate)\n if (sent) console.info(`commerce: sent ${sent} back-in-stock alerts`)\n },\n})\n\n/**\n * The review-request email (AGL-3736). HOURLY: a request is owed days after\n * fulfilment, so an hour's lateness is invisible, and the scan is one\n * collection-group range query over `reviewRequestDueAtMs` — a field only\n * orders still owed a request carry, so an empty beat costs one read.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'review-request-emails',\n intervalMinutes: 60,\n description:\n 'Email each buyer one review request, with a single-use link per product, ' +\n 'days after their order is fulfilled (AGL-3736).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!isEmailConfigured()) return\n const { scanReviewRequests } = await import('./server/review-requests')\n const { sent } = await scanReviewRequests(gate)\n if (sent) console.info(`commerce: sent ${sent} review requests`)\n },\n})\n\n/**\n * The missing-decrement detector (AGL-2358).\n *\n * HOURLY, not on the 15-minute recovery beat: it is a detector for a rare\n * process death, not a queue drain, and nothing it finds gets less true for\n * waiting an hour. The cost of the beat is what sets the interval — one\n * collection-group read of the platform's most recent orders, plus two\n * queries per host that has any — and an hour keeps that off the same tick as\n * the two scans above.\n *\n * NOT gated on `isEmailConfigured()`, unlike its two neighbours. Those send\n * mail; this writes a console notification and a log line, both of which work\n * on a self-host with no mail provider at all — and a stock count that is\n * silently wrong is exactly what a self-hoster least wants suppressed by a\n * setting about email.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'stock-decrement-reconciliation',\n intervalMinutes: 60,\n description:\n 'Report paid orders whose stock decrement never landed (AGL-2358).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanStockDecrements(gate)\n if (scan.missingLines || scan.truncatedHosts) {\n console.warn(\n `commerce: ${scan.missingLines} order lines across ${scan.hosts} ` +\n `sites have no sale ledger row (${scan.reportedOrders} newly ` +\n `reported, ${scan.truncatedHosts} sites' ledger window truncated)`,\n )\n }\n },\n})\n\n/**\n * The dropship supplier outbox drain (AGL-2473).\n *\n * EVERY MINUTE, unlike the three above, and the interval is the point rather\n * than an oversight. This is the only one of the four that a BUYER is waiting\n * on: the row it drains is a paid order that has not been routed to whoever\n * ships it, and every minute it sits is a minute the parcel is not moving. The\n * first backoff step is also 60s, so a supplier that blipped is retried on the\n * next tick.\n *\n * The cost that set fifteen minutes for the recovery pair does not apply. Those\n * are collection-GROUP scans across every site on the platform; this is one\n * ordinary equality query against a top-level collection that is EMPTY in the\n * ordinary case — an empty result bills a single read, so the whole beat is\n * ~1,440 reads a day whether or not anyone is dropshipping.\n *\n * Not gated on `isEmailConfigured()`. The supplier notification is an HTTP POST\n * to the merchant's own supplier, and a self-host with no mail provider still\n * has dropship orders to route.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'supplier-webhook-delivery',\n intervalMinutes: 1,\n description:\n 'Deliver queued dropship supplier notifications, with backoff and a ' +\n 'dead letter that tells the merchant (AGL-2473).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const scan = await scanSupplierDeliveries(gate)\n if (scan.deadLettered) {\n console.warn(\n `commerce: ${scan.deadLettered} dropship orders could not be routed ` +\n `to their supplier and have been reported on the order`,\n )\n }\n },\n})\n\n/**\n * Stripe payment method domains for every connected custom domain (AGL-3629).\n *\n * The backfill for domains connected before registration existed, and the\n * repair for a connect whose event was lost, in one daily pass. A domain\n * already registered costs a document read and no Stripe call, so the beat is\n * cheap; a day's delay costs only the Apple Pay button on a domain connected\n * while Stripe was unreachable, and the first in-page checkout there registers\n * it anyway.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'payment-method-domains',\n intervalMinutes: 24 * 60,\n description:\n 'Register connected custom domains with Stripe so Apple Pay, Google Pay ' +\n 'and Link show on them (AGL-3629).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { reconcileCustomDomains } = await import('./server/payment-method-domains')\n const result = await reconcileCustomDomains(gate)\n if (result.registered || result.failed) {\n console.info(\n `commerce: payment method domains — ${result.registered} registered, ` +\n `${result.failed} failed across ${result.hosts} sites`,\n )\n }\n },\n})\n\n/**\n * The monthly 4G charge for Stripe Reader S710s (AGL-4038): each workspace\n * whose readers had 4G in the month just ended is charged once, through\n * core's usage-invoice charge. Every six hours, so the charge goes out early\n * on the 1st and one that could not reach Stripe is tried again the same\n * day; a month already settled costs a read per workspace. Nothing runs\n * where 4G is not offered (`POS_CELLULAR_MONTHLY_COST_CENTS` unset).\n * Per-host: a store locked for security or abuse is not charged while it is.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-cellular-billing',\n intervalMinutes: 6 * 60,\n description:\n 'Charge each workspace for 4G on its Stripe Reader S710s for the month just ended, once (AGL-4038).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY || !process.env.POS_CELLULAR_MONTHLY_COST_CENTS) return\n const { runPosCellularBilling } = await import('./server/pos-cellular-billing')\n const report = await runPosCellularBilling(gate)\n if (report.workspaces || report.storesGone || report.warned || report.turnedOff || report.paidLate) {\n console.info(\n `commerce: 4G for ${report.month} — ${report.paid} paid, ${report.open} left open, ` +\n `${report.failed} not reached, ${report.unbillable} not billable, ${report.deferred} deferred, ` +\n `${report.storesGone} deleted stores turned off; unpaid charges: ${report.warned} warned, ` +\n `${report.paidLate} paid since, ${report.turnedOff} turned off`,\n )\n }\n },\n})\n\n/**\n * Card reader start-up screens (AGL-4048) that went stale with nobody opening\n * the POS devices card: a logo changed on the organization profile or the\n * white-label brand, or the logo's file replaced in the media library. Every\n * 15 minutes, like the recovery pair: a store whose screen did not move costs\n * a few reads and no Stripe call, and nothing a merchant saves waits on it.\n * A screen Stripe refused is retried after six hours here, and at once when\n * the card is opened.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'pos-reader-splash-refresh',\n intervalMinutes: RECOVERY_JOB_INTERVAL_MINUTES,\n description:\n 'Bring card reader start-up screens up to date after a logo change (AGL-4048).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n if (!process.env.STRIPE_SECRET_KEY) return\n const { refreshPosReaderSplashes } = await import('./server/pos-reader-splash')\n const result = await refreshPosReaderSplashes(gate)\n if (result.applied || result.failed || result.more) {\n console.info(\n `commerce: reader start-up screens — ${result.applied} updated, ` +\n `${result.failed} failed${result.more ? ', more stores than one pass reaches' : ''}`,\n )\n }\n },\n})\n\n/**\n * Cards taken offline whose sale never synced (AGL-4039).\n *\n * HOURLY. The alert falls due six hours after the intent was first seen, and\n * Stripe's authorization lasts about two days, so an hour's delay costs\n * nothing and leaves the beat one collection-group range read that is empty in\n * the ordinary case. It never captures: without the sale there is no fee to\n * capture with, so it tells the operator and the site's managers instead.\n *\n * Not gated on `isEmailConfigured()`: the console notification and the\n * operator alert both work without mail.\n */\nregisterPluginJob({\n pluginId: BUNDLE_ID,\n name: 'offline-card-unsynced',\n intervalMinutes: 60,\n description:\n 'Tell the operator and the site when a card taken offline reached Stripe but its sale never synced (AGL-4039).',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n const { scanUnsyncedOfflineCards } = await import('./server/pos-offline-card-reconcile')\n const scan = await scanUnsyncedOfflineCards(gate)\n if (scan.alerted) {\n console.warn(`commerce: ${scan.alerted} cards taken offline have no synced sale`)\n }\n },\n})\n\n/**\n * A visitor's payment door: it opens a Stripe Checkout Session for whoever\n * calls it, so the dispatcher holds it to the card-testing counters\n * (AGL-3363). Declared here, beside the registration, so the door cannot\n * exist without it.\n */\nconst CARD_PAYMENT_DOOR = { cardPayment: true } as const\n\n/**\n * The quote page's Pay button (AGL-4094): a fresh Checkout Session for a\n * quote, for whoever holds its signed pay link. Loaded on first call.\n */\nconst quotePayDoor: PluginApiHandler = async (req, res) =>\n (await import('./server/quote-pay')).quotePayHandler(req, res)\n\n/** Registers the commerce plugin's storefront API routes. */\nexport function registerCommerceApi(): void {\n registerProductCardReader()\n // The merchant's tax rule, for every plugin that prices a charge here.\n registerCommerceTaxProfile()\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // Merchant-settable register discount ceiling (AGL-2161). Registered on\n // BOTH surfaces, like the permissions above: the POS route reads it\n // server-side, and the settings card renders it from the same schema.\n registerPluginConfigSchema(COMMERCE_CONFIG_SCHEMA)\n // PDP/PLP template pages (AGL-418): /products/* + /collections/*.\n registerSitePageResolver(commerceSitePageResolver)\n // Seeds product grids on ordinary screens (AGL-659) — the resolver above\n // only covers /products/* and /collections/*, so /products itself, and any\n // designed page with a grid on it, needed this to render server-side.\n registerSitePageEnricher(commerceSitePageEnricher)\n registerPluginApiRoute('commerce/cart-checkout', cartCheckoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/cart', cartHandler)\n // What the cart offers besides shipping (AGL-3624): pickup locations, and\n // local delivery's fee, minimum and windows for a postal code.\n registerPluginApiRoute('commerce/local-fulfillment-options', async (req, res) =>\n (await import('./server/local-fulfillment')).localFulfillmentOptionsHandler(req, res),\n )\n // Optional lines another plugin offers at the cart (AGL-3635).\n registerPluginApiRoute('commerce/cart-extras', cartExtrasHandler)\n registerPluginApiRoute('commerce/catalog', catalogHandler)\n registerPluginApiRoute('commerce/checkout', checkoutHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/download', downloadHandler)\n // The pre-channels Google feed address (AGL-299), now written by the\n // catalog's feed publisher (AGL-3637); the module loads with a fetch.\n registerPluginApiRoute('commerce/feed', {\n web: async (request) => (await import('./server/legacy-feed')).legacyFeedRoute(request),\n })\n registerPluginApiRoute('commerce/newsletter', newsletterHandler)\n registerPluginApiRoute('commerce/notify-restock', notifyRestockHandler)\n // GA-safe order projection for the storefront `purchase` (AGL-1641).\n registerPluginApiRoute('commerce/order-analytics', orderAnalyticsHandler)\n // The guest order-status page's data (AGL-3610), behind the signed link in\n // every buyer email — a recipient link, so it outlives the site's gates.\n registerPluginApiRoute('commerce/order-status', orderStatusHandler, { recipientLink: true })\n // …and its \"Request a return\" button (AGL-3611), on an order that can\n // still send something back.\n registerOrderStatusActions(returnRequestStatusAction)\n // The customer's quote page (AGL-4094), behind the signed pay link a\n // business sends: the quote, and its Pay button. The page's data is a\n // recipient link, so it outlives the site's gates like the order status.\n registerPluginApiRoute(\n 'commerce/quote-view',\n async (req, res) => (await import('./server/quote-pay')).quoteViewHandler(req, res),\n { recipientLink: true },\n )\n registerPluginApiRoute('commerce/quote-pay', quotePayDoor, CARD_PAYMENT_DOOR)\n // What became of a session the shopper was returned from (AGL-3606).\n registerPluginApiRoute('commerce/checkout-status', checkoutStatusHandler)\n registerPluginApiRoute('commerce/product', productHandler)\n registerPluginApiRoute('commerce/related', relatedHandler)\n registerPluginApiRoute('commerce/reservation-availability', reservationAvailabilityHandler)\n registerPluginApiRoute('commerce/reserve', reserveHandler, CARD_PAYMENT_DOOR)\n registerPluginApiRoute('commerce/gate', gateHandler)\n registerPluginApiRoute('commerce/member-feed', memberFeedHandler)\n registerPluginApiRoute('commerce/stream', streamHandler)\n registerPluginApiRoute('commerce/subscription-portal', subscriptionPortalHandler)\n registerPluginApiRoute('commerce/reviews', reviewsHandler)\n // A buyer's return request (AGL-3611), from their account or the signed\n // order-status link.\n registerPluginApiRoute('commerce/return-request', returnRequestHandler)\n registerPluginApiRoute('membership/account', membershipAccountHandler)\n registerPluginApiRoute('membership/content', membershipContentHandler)\n registerPluginApiRoute('membership/login', membershipLoginHandler)\n registerPluginApiRoute('membership/logout', membershipLogoutHandler)\n // Password recovery pair (AGL-552): request + complete.\n registerPluginApiRoute('membership/recover', membershipRecoverHandler)\n registerPluginApiRoute('membership/register', membershipRegisterHandler)\n registerPluginApiRoute('membership/reset', membershipResetHandler)\n registerPluginApiRoute('membership/wishlist', membershipWishlistHandler)\n}\n\n/**\n * Registers the commerce plugin's console-side API routes (AGL-396):\n * merchant/staff operations (Connect onboarding, refunds, draft & POS\n * orders, member posts), the supplier tracking callback, and the HTTP doors\n * for the abandoned-cart / restock passes.\n *\n * Those last two are NOT what schedules them — the `registerPluginJob` calls\n * above are (AGL-2227). This comment used to call them \"the scheduler-driven\n * jobs\", which is how they stayed dark for months: it asserted the wiring\n * instead of having it.\n */\nexport function registerCommerceConsoleApi(): void {\n // The register's gate (`managePos`) is resolved on THIS surface: every POS\n // route below runs in the console, and a key no surface registered here is\n // absent from the resolved map, which reads as refused — the site's own\n // owner was answered 403 at the register.\n registerPluginPermissions(COMMERCE_PERMISSIONS)\n // What a product looks like to a surface that is not this plugin's — a\n // campaign email that features one asks here rather than importing the model.\n registerProductCardReader()\n // …and a draft product another plugin asks for by name (AGL-3616): an AI\n // build setting a store up from a brief, unpriced unless the brief priced it.\n // The console runs AI jobs (AGL-3026).\n registerProductDraftWriter()\n // …and the operation an AI build plans for it, which that writer executes.\n registerProductAiCapability()\n // …and the store's shipping, pickup, local delivery and tax settings an AI\n // build sets up (AGL-3749), written live as the console's cards write them,\n // with the four operations that writer executes.\n registerStoreSetupAiWriter()\n registerStoreSetupAiCapabilities()\n // …and why a file somebody is SELLING may not be made public (AGL-3080).\n // The media library asks before it hands an asset its permanent CDN URL\n // back; what a product is, and which of its fields hold paid media, is\n // this plugin's to know.\n registerCommerceMediaPublishGuard()\n // …and which memberships a site sells, for a security lockdown to pause\n // (AGL-3364). The lockdown route runs on this surface.\n registerCommerceRecurringCharges()\n // …and the tax rule, for the webhook that confirms what they charged.\n registerCommerceTaxProfile()\n // …and its sales on the operator's own sales tax return (AGL-3080): the\n // tax a storefront checkout collected under the platform's registrations.\n // The staff return awaits this surface before it asks, and refuses to be\n // filed without this source — commerce declares `taxReturnSource`.\n registerTaxReturnSource(commerceTaxReturnSource, { pluginId: BUNDLE_ID })\n // …and the take its orders earn the operator, on the staff revenue report\n // (AGL-3080) — commerce declares `revenueSource`, so the report names this\n // source as unread rather than counting it as zero if it is missing.\n registerRevenueSource(commerceRevenueSource, { pluginId: BUNDLE_ID })\n // Stripe webhook sections (AGL-418): orders/carts/drafts/reservations/\n // subscriptions ride the platform webhook via the hook registry.\n registerBillingWebhookHandler(commerceBillingWebhookHandler)\n // A paid card-reader order from the POS hardware shop (AGL-4038), on the\n // same platform webhook: its own handler, self-selecting on the session's\n // `metadata.type`, so the storefront sections above never see it.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-hardware-webhook')).posHardwareBillingWebhookHandler(event),\n )\n // A card the Aglyn POS app took offline (AGL-4039): its PaymentIntent can\n // reach Stripe before the sale reaches the server, so every event on one is\n // kept by the sale's key. Self-selecting on `metadata.kind`.\n registerBillingWebhookHandler(async (event) =>\n (await import('./server/pos-offline-card-reconcile')).posOfflineCardBillingWebhookHandler(event),\n )\n // Cancel + stock release in one transaction (AGL-1808). Server-side because\n // the release depends on the transition rule, and a client write could not\n // re-ask it under the same lock that flips the status.\n registerPluginApiRoute('commerce/cancel-order', cancelOrderHandler)\n // Whether live carrier rates can be offered on this site (AGL-3612).\n registerPluginApiRoute('commerce/shipping/carrier-rates', carrierRatesAvailabilityHandler)\n registerPluginApiRoute('commerce/connect', connectHandler)\n registerPluginApiRoute('commerce/draft-order', draftOrderHandler)\n // Quotes (AGL-4093): create, edit and delete a quote, and find the customer\n // it is for, under \"Create and edit quotes\". Loaded on first call.\n registerPluginApiRoute('commerce/quote', async (req, res) =>\n (await import('./server/quote')).quoteHandler(req, res),\n )\n // Fulfil + mark-delivered with the transition re-asked under the write\n // (AGL-1819) — the same stale-dialog hole cancel-order closes, minus the\n // stock release those two transitions never had. The customer REST API's\n // `PATCH /v1/sites/{id}/orders/{id}` records a shipment through the same\n // transaction (`server/api-v1/orders-and-products.ts`).\n registerPluginApiRoute('commerce/fulfill-order', fulfillOrderHandler)\n // Pickup and local delivery steps (AGL-3624) — ready, picked up, out for\n // delivery, delivered — from the console queue, the order dialog and the\n // native Aglyn app. Loaded on first call.\n registerPluginApiRoute('commerce/local-fulfillment', async (req, res) =>\n (await import('./server/local-fulfillment-status')).localFulfillmentHandler(req, res),\n )\n // \"Resend receipt\" from the order dialog (AGL-3610): by email, or by text\n // when the platform's SMS provider is configured. Rate-limited per member\n // and per order.\n registerPluginApiRoute('commerce/order-receipt-send', orderReceiptSendHandler)\n // The product editor's save and Adjust stock for the native apps (AGL-3652):\n // the console's own product-write computation under the rules' gate. Loaded\n // on first call.\n registerPluginApiRoute('commerce/products/save', async (req, res) =>\n (await import('./server/products-write')).productSaveHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/stock', async (req, res) =>\n (await import('./server/products-write')).productStockHandler(req, res),\n )\n // A staff walk-in from the Reservations card and the native apps\n // (AGL-4046): availability re-asked inside the transaction that writes, so\n // two staff cannot hand out the last unit at once. Loaded on first call.\n registerPluginApiRoute('commerce/reservations/walk-in', async (req, res) =>\n (await import('./server/reservation-walk-in')).reservationWalkInHandler(req, res),\n )\n // A stay's guest count after it is booked (AGL-4043), from the Reservations\n // card and the check-in screen: the walk-in's gate, and the stay's\n // check-ins for today on brought in line in the same transaction. Loaded\n // on first call.\n registerPluginApiRoute('commerce/reservations/guests', async (req, res) =>\n (await import('./server/reservation-guests')).reservationGuestsHandler(req, res),\n )\n // The products list's Duplicate and Delete for the native apps (AGL-3841):\n // the console's own copy and soft delete, with the site-wide cache drop.\n registerPluginApiRoute('commerce/products/duplicate', async (req, res) =>\n (await import('./server/products-write')).productDuplicateHandler(req, res),\n )\n registerPluginApiRoute('commerce/products/delete', async (req, res) =>\n (await import('./server/products-write')).productDeleteHandler(req, res),\n )\n // The order dialog's note and restock answer for the native apps\n // (AGL-3651, AGL-3652): the console's own timeline computation, in one\n // transaction on the stored order. Loaded on first call.\n registerPluginApiRoute('commerce/order-note', async (req, res) =>\n (await import('./server/order-annotations')).orderNoteHandler(req, res),\n )\n registerPluginApiRoute('commerce/order-restock-answer', async (req, res) =>\n (await import('./server/order-annotations')).orderRestockAnswerHandler(req, res),\n )\n // The order dialog's Packing slip and Invoice for the native apps\n // (AGL-3841): the console's own two pages over the stored order, which the\n // apps print on the device's print sheet. Loaded on first call.\n registerPluginApiRoute('commerce/order-print', async (req, res) =>\n (await import('./server/order-print')).orderPrintHandler(req, res),\n )\n // Issue / void store credit (AGL-2226). Server-side because the host\n // catch-all in the Firestore rules would otherwise let a client write\n // its own `balanceCents`, which checkout applies as amount-off.\n registerPluginApiRoute('commerce/gift-cards', giftCardsHandler)\n // The merchant's own storefront sales tax, by who owes it (AGL-2440): the\n // same rows and classifier the operator's return reads, fenced to one site.\n registerPluginApiRoute('commerce/tax-summary', { web: taxSummaryHandler })\n // The payment methods card (AGL-3629): toggles, the platform's offer, the\n // payout account's capabilities and the site's wallet domains. Loaded with\n // the first request, so a console that never opens Settings never imports it.\n registerPluginApiRoute('commerce/payment-methods', {\n web: async (request) =>\n (await import('./server/payment-methods')).paymentMethodsHandler(request),\n })\n // A smart collection's rules changed or it was deleted: re-stamp which\n // products it holds (AGL-3321), the membership the storefront queries.\n registerPluginApiRoute('commerce/collection-membership', collectionMembershipHandler)\n // A site member's password help (AGL-914) and removal (AGL-3308), from the\n // Users page drawer and the Inbox. Console-auth, not the visitor cookie the\n // storefront's `membership/*` routes take, so they are served where the\n // console posts: the console's own dispatcher loads this surface only.\n registerPluginApiRoute(\n 'membership/admin-password',\n membershipAdminPasswordHandler,\n )\n registerPluginApiRoute('membership/admin-remove', membershipAdminRemoveHandler)\n registerPluginApiRoute('commerce/member-post', memberPostHandler)\n registerPluginApiRoute('commerce/pos-order', posOrderHandler)\n // A register's cloud receipt printers and the jobs a manager sends them\n // (AGL-3619), and the two doors the printers themselves poll. The doors are\n // MACHINE routes: a printer is no member and names no site cookie, so it\n // authenticates with the per-printer secret in its URL and its own device id,\n // and the route asks the plan before it hands over a job. Loaded with the\n // first poll, so a console that has no printers never imports them.\n registerPluginApiRoute('commerce/printers', printersHandler)\n registerPluginApiRoute(\n 'commerce/cloudprnt/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).cloudPrntRoute(request, context),\n },\n { machine: true },\n )\n registerPluginApiRoute(\n 'commerce/epson-sdp/:hostId/:printerId/:secret',\n {\n web: async (request, context) =>\n (await import('./server/printer-poll')).epsonServerDirectPrintRoute(request, context),\n },\n { machine: true },\n )\n // The register's tenders against an open sale, its Stripe Terminal card\n // readers, and the paired customer display (AGL-3607, AGL-3608). The\n // display's `pair`/`poll`/`respond` take a display token and no console\n // session; every other action is gated like a sale.\n registerPluginApiRoute('commerce/pos-payment', posPaymentHandler)\n registerPluginApiRoute('commerce/pos-readers', posReadersHandler)\n registerPluginApiRoute('commerce/pos-display', posDisplayHandler)\n // The POS hardware shop (AGL-4038): the Hardware card's catalog, Checkout\n // and order list, gated like a sale and hidden until the deployment prices\n // it; and the staff page's orders, which name no site. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware', async (req, res) =>\n (await import('./server/pos-hardware')).posHardwareHandler(req, res),\n )\n // Selling a card reader in person at the platform's own store's register\n // (AGL-4038): whether this store is that seller. Gated like a sale, and\n // silent about the configuration on every other store. Loaded on first call.\n registerPluginApiRoute('commerce/pos-hardware-sale', async (req, res) =>\n (await import('./server/pos-hardware-sale')).posHardwareSaleHandler(req, res),\n )\n // A store's card reader start-up screen (AGL-4048): the POS devices card's\n // setting, gated like a sale, and the staff page's platform default. Each\n // loads with its first call; the drawing they ask for is the images\n // route's, below.\n registerPluginApiRoute('commerce/pos-reader-splash', async (req, res) =>\n (await import('./server/pos-reader-splash')).posReaderSplashHandler(req, res),\n )\n registerPluginApiRoute('commerce/admin/reader-splash', {\n web: async (request) =>\n (await import('./server/pos-reader-splash-admin')).posReaderSplashAdmin(request),\n })\n // The image work behind both (AGL-4048): drawing a screen and reading an\n // uploaded one take `sharp`, whose native library only the console's\n // plugins' image function ships (`/api/plugin-images/…`), so the plugin\n // API's function does not carry it. Called by our own servers, signed; a\n // machine's door.\n registerPluginApiRoute(\n 'commerce/pos-reader-splash-images',\n {\n web: async (request) =>\n (await import('./server/pos-reader-splash-images-route')).posReaderSplashImagesRoute(request),\n },\n { machine: true, images: true },\n )\n registerPluginApiRoute('commerce/admin/hardware-orders', {\n web: async (request) =>\n (await import('./server/pos-hardware-admin')).posHardwareAdminOrders(request),\n })\n // The self-service kiosk (AGL-3623): a register's paired screen where the\n // customer orders and pays. Its device token, never a staff session; the\n // register's queue of \"pay at counter\" orders is gated like a sale.\n registerPluginApiRoute('commerce/pos-kiosk', posKioskHandler)\n // Shifts, staff PINs, the customer lookup and returns (AGL-3609).\n registerPosOpsRoutes()\n // The offline register (AGL-3625): the kit a register caches to sell cash\n // while the connection is down, and the sync that records those sales once.\n // Gated like a sale; loaded with its first call.\n registerPluginApiRoute('commerce/pos-offline-sync', async (req, res) =>\n (await import('./server/pos-offline-sync')).posOfflineSyncHandler(req, res),\n )\n // The native Aglyn POS app's Stripe Terminal SDK: a connection token scoped\n // to the site's Location, and the Location itself (AGL-3618). Gated like a\n // sale.\n registerPluginApiRoute('commerce/pos-terminal-connection-token', posTerminalConnectionTokenHandler)\n registerPluginApiRoute('commerce/process-abandoned', processAbandonedHandler)\n registerPluginApiRoute('commerce/process-restock', processRestockHandler)\n registerPluginApiRoute('commerce/refund', refundHandler)\n // Returns (AGL-3611): approve, decline, receive with restock, refund\n // through the route above, a label from a shipping plugin.\n registerPluginApiRoute('commerce/returns', returnsHandler)\n // The merchant's outbound order webhooks (AGL-3611): endpoints, secrets,\n // a test ping and a resend from the delivery log.\n registerPluginApiRoute('commerce/order-webhooks', orderWebhooksHandler)\n registerPluginApiRoute('commerce/supplier-update', supplierUpdateHandler)\n // Stamps the open orders that predate the shipping fields, before an\n // export for shipping (AGL-3613).\n registerPluginApiRoute('commerce/orders-shipping-prepare', async (req, res) =>\n (await import('./server/orders-shipping-prepare')).ordersShippingPrepareHandler(req, res),\n )\n // ShipStation's Custom Store endpoint (AGL-3613): ShipStation's servers\n // pull the order feed and post shipments back with the site's own Basic\n // credentials, so it is a MACHINE's route and asks the site's commerce,\n // plan, release and lockdown gates itself once the credentials prove the\n // site. Loaded on its first call, never with the console API surface.\n registerPluginApiRoute(\n 'commerce/shipstation/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shipstation')).shipStationRoute(request, context),\n },\n { machine: true },\n )\n // ShippingEasy's shipment callback (AGL-3633): ShippingEasy's servers post\n // each label bought for an order this store sent them, signed with the\n // merchant's own API secret, so it is a MACHINE's route like ShipStation's\n // above and asks the same gates once the signature proves the site.\n registerPluginApiRoute(\n 'commerce/shippingeasy/:hostId',\n {\n web: async (request, context) =>\n (await import('./server/shippingeasy')).shippingEasyRoute(request, context),\n },\n { machine: true },\n )\n // The ShipStation and ShippingEasy cards' connect, show, new password,\n // send open orders and disconnect.\n registerPluginApiRoute('commerce/shipping-connectors', async (req, res) =>\n (await import('./server/shipping-connectors')).shippingConnectorsHandler(req, res),\n )\n // The store's sales as figure tables (AGL-2915), for the AI plugin's\n // insights to read by id rather than by reading orders. The console runs\n // insight jobs, so the console surface registers them.\n registerOrderFigureReaders(() => firebaseAdmin.app().firestore())\n}\n\n// Shared with the (still app-side) membership/account route.\nexport { mintDownloadToken } from './server/download'\n\n// Site-member session primitives, shared with the (still app-side)\n// membership/* routes until those migrate too (AGL-396).\nexport * from './server/membership'\n\n// Type-only (AGL-3080): the plugin's entitlement keys, declared by module\n// augmentation, for every program that loads this entry point.\nexport type { commercePlanEntitlements } from './plan-entitlements'\n"],"names":["registerBillingWebhookHandler","registerPluginApiRoute","registerPluginJob","registerSitePageEnricher","registerSitePageResolver","registerPluginPermissions","registerPluginConfigSchema","isEmailConfigured","firebaseAdmin","BUNDLE_ID","registerCommerceMediaPublishGuard","registerCommerceRecurringCharges","registerProductCardReader","registerProductAiCapability","registerStoreSetupAiCapabilities","registerStoreSetupAiWriter","registerProductDraftWriter","registerCommerceTaxProfile","registerTaxReturnSource","commerceTaxReturnSource","taxSummaryHandler","registerRevenueSource","commerceRevenueSource","commerceBillingWebhookHandler","registerOrderFigureReaders","COMMERCE_PERMISSIONS","COMMERCE_CONFIG_SCHEMA","commerceSitePageEnricher","commerceSitePageResolver","cartCheckoutHandler","cartHandler","cartExtrasHandler","catalogHandler","checkoutHandler","downloadHandler","newsletterHandler","notifyRestockHandler","productHandler","relatedHandler","reservationAvailabilityHandler","gateHandler","memberFeedHandler","membershipAccountHandler","membershipAdminPasswordHandler","membershipAdminRemoveHandler","membershipContentHandler","membershipLoginHandler","membershipLogoutHandler","membershipRecoverHandler","membershipRegisterHandler","membershipResetHandler","membershipWishlistHandler","reserveHandler","streamHandler","subscriptionPortalHandler","reviewsHandler","connectHandler","cancelOrderHandler","carrierRatesAvailabilityHandler","collectionMembershipHandler","draftOrderHandler","fulfillOrderHandler","orderReceiptSendHandler","orderStatusHandler","registerOrderStatusActions","returnRequestStatusAction","giftCardsHandler","memberPostHandler","orderAnalyticsHandler","checkoutStatusHandler","posOrderHandler","printersHandler","posPaymentHandler","posReadersHandler","posTerminalConnectionTokenHandler","posDisplayHandler","posKioskHandler","registerPosOpsRoutes","processAbandonedHandler","scanAbandonedCheckouts","processRestockHandler","scanRestockAlerts","scanStockDecrements","refundHandler","orderWebhooksHandler","returnRequestHandler","returnsHandler","scanSupplierDeliveries","supplierUpdateHandler","RECOVERY_JOB_INTERVAL_MINUTES","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","sent","console","info","scanReviewRequests","scan","missingLines","truncatedHosts","warn","hosts","reportedOrders","deadLettered","process","env","STRIPE_SECRET_KEY","reconcileCustomDomains","result","registered","failed","POS_CELLULAR_MONTHLY_COST_CENTS","runPosCellularBilling","report","workspaces","storesGone","warned","turnedOff","paidLate","month","paid","open","unbillable","deferred","refreshPosReaderSplashes","applied","more","scanUnsyncedOfflineCards","alerted","CARD_PAYMENT_DOOR","cardPayment","quotePayDoor","req","res","quotePayHandler","registerCommerceApi","localFulfillmentOptionsHandler","web","request","legacyFeedRoute","recipientLink","quoteViewHandler","registerCommerceConsoleApi","event","posHardwareBillingWebhookHandler","posOfflineCardBillingWebhookHandler","quoteHandler","localFulfillmentHandler","productSaveHandler","productStockHandler","reservationWalkInHandler","reservationGuestsHandler","productDuplicateHandler","productDeleteHandler","orderNoteHandler","orderRestockAnswerHandler","orderPrintHandler","paymentMethodsHandler","context","cloudPrntRoute","machine","epsonServerDirectPrintRoute","posHardwareHandler","posHardwareSaleHandler","posReaderSplashHandler","posReaderSplashAdmin","posReaderSplashImagesRoute","images","posHardwareAdminOrders","posOfflineSyncHandler","ordersShippingPrepareHandler","shipStationRoute","shippingEasyRoute","shippingConnectorsHandler","app","firestore","mintDownloadToken"],"mappings":"AAAA;;;;;;;;;;;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3C,yEAAyE;IACzE,kDAAkD;IAClDrF,uBAAuB,2BAA2BmF;IAClDnF,uBAAuB,4BAA4BuF;IACnD,qEAAqE;IACrE,kCAAkC;IAClCvF,uBAAuB,oCAAoC,OAAOwI,KAAKC,MACrE,AAAC,CAAA,MAAM,MAAM,CAAC,sCAAkC,EAAGqC,4BAA4B,CAACtC,KAAKC;IAEvF,wEAAwE;IACxE,wEAAwE;IACxE,wEAAwE;IACxE,yEAAyE;IACzE,sEAAsE;IACtEzI,uBACE,gCACA;QACE6I,KAAK,OAAOC,SAASoB,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,0BAAsB,EAAGa,gBAAgB,CAACjC,SAASoB;IACrE,GACA;QAAEE,SAAS;IAAK;IAElB,2EAA2E;IAC3E,uEAAuE;IACvE,2EAA2E;IAC3E,oEAAoE;IACpEpK,uBACE,iCACA;QACE6I,KAAK,OAAOC,SAASoB,UACnB,AAAC,CAAA,MAAM,MAAM,CAAC,2BAAuB,EAAGc,iBAAiB,CAAClC,SAASoB;IACvE,GACA;QAAEE,SAAS;IAAK;IAElB,uEAAuE;IACvE,mCAAmC;IACnCpK,uBAAuB,gCAAgC,OAAOwI,KAAKC,MACjE,AAAC,CAAA,MAAM,MAAM,CAAC,kCAA8B,EAAGwC,yBAAyB,CAACzC,KAAKC;IAEhF,qEAAqE;IACrE,yEAAyE;IACzE,uDAAuD;IACvDlH,2BAA2B,IAAMhB,cAAc2K,GAAG,GAAGC,SAAS;AAChE;AAEA,6DAA6D;AAC7D,SAASC,iBAAiB,QAAQ,uBAAmB;AAErD,mEAAmE;AACnE,yDAAyD;AACzD,cAAc,yBAAqB"}
|
package/src/lib/site.js
CHANGED
|
@@ -29,6 +29,7 @@ import * as ProductDetail from "./components/product-detail.js";
|
|
|
29
29
|
import * as ReservationWidget from "./components/reservation-widget.js";
|
|
30
30
|
import * as ProductGrid from "./components/product-grid.js";
|
|
31
31
|
import * as ProductReviews from "./components/product-reviews.js";
|
|
32
|
+
import * as QuotePage from "./components/quote-page.js";
|
|
32
33
|
import * as RelatedProducts from "./components/related-products.js";
|
|
33
34
|
import * as ReturnRequest from "./components/return-request.js";
|
|
34
35
|
import * as Wishlist from "./components/wishlist.js";
|
|
@@ -125,6 +126,11 @@ import { BUNDLE_ID } from "./constants/bundle-common.js";
|
|
|
125
126
|
component: ReturnRequest.default,
|
|
126
127
|
schema: ReturnRequest.schema,
|
|
127
128
|
presets: ReturnRequest.presets
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
component: QuotePage.default,
|
|
132
|
+
schema: QuotePage.schema,
|
|
133
|
+
presets: QuotePage.presets
|
|
128
134
|
}
|
|
129
135
|
];
|
|
130
136
|
export function registerCommercePlugin() {
|
package/src/lib/site.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/site.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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiStorefrontOutline } from '@aglyn/shared-data-mdi'\nimport * as Account from './components/account'\nimport * as Cart from './components/cart'\nimport * as Gate from './components/gate'\nimport * as GatedVideo from './components/gated-video'\nimport * as MemberFeed from './components/member-feed'\nimport * as MemberRecovery from './components/member-recovery'\nimport * as MemberSignin from './components/member-signin'\nimport * as MemberSignup from './components/member-signup'\nimport * as NewsletterSignup from './components/newsletter-signup'\nimport * as OrderStatus from './components/order-status'\nimport * as ProductDetail from './components/product-detail'\nimport * as ReservationWidget from './components/reservation-widget'\nimport * as ProductGrid from './components/product-grid'\nimport * as ProductReviews from './components/product-reviews'\nimport * as RelatedProducts from './components/related-products'\nimport * as ReturnRequest from './components/return-request'\nimport * as Wishlist from './components/wishlist'\nimport { BUNDLE_ID } from './constants/bundle-common'\n\n/**\n * Commerce UI feature plugin (AGL-290): the storefront component set,\n * built on the feature-plugin pattern (AGL-277) — depends on the mui\n * bundle for primitives/theming and registers alongside it in the\n * besigner and the tenant renderer. Components join `COMMERCE_BUNDLE`\n * as they land (PLP AGL-291, PDP AGL-292, cart AGL-293, …); ids are\n * persisted in screen docs and never renamed.\n */\nexport const COMMERCE_BUNDLE: Aglyn.FeatureBundleEntry[] = [\n {\n component: ProductGrid.default,\n schema: ProductGrid.schema,\n presets: ProductGrid.presets,\n },\n {\n component: ProductDetail.default,\n schema: ProductDetail.schema,\n presets: ProductDetail.presets,\n },\n {\n component: Cart.default,\n schema: Cart.schema,\n presets: Cart.presets,\n },\n {\n component: Account.default,\n schema: Account.schema,\n presets: Account.presets,\n },\n {\n component: Wishlist.default,\n schema: Wishlist.schema,\n presets: Wishlist.presets,\n },\n {\n component: NewsletterSignup.default,\n schema: NewsletterSignup.schema,\n presets: NewsletterSignup.presets,\n },\n {\n component: Gate.default,\n schema: Gate.schema,\n presets: Gate.presets,\n },\n {\n component: GatedVideo.default,\n schema: GatedVideo.schema,\n presets: GatedVideo.presets,\n },\n {\n component: MemberFeed.default,\n schema: MemberFeed.schema,\n presets: MemberFeed.presets,\n },\n {\n component: MemberRecovery.default,\n schema: MemberRecovery.schema,\n presets: MemberRecovery.presets,\n },\n {\n component: MemberSignin.default,\n schema: MemberSignin.schema,\n presets: MemberSignin.presets,\n },\n {\n component: MemberSignup.default,\n schema: MemberSignup.schema,\n presets: MemberSignup.presets,\n },\n {\n component: ReservationWidget.default,\n schema: ReservationWidget.schema,\n presets: ReservationWidget.presets,\n },\n {\n component: ProductReviews.default,\n schema: ProductReviews.schema,\n presets: ProductReviews.presets,\n },\n {\n component: RelatedProducts.default,\n schema: RelatedProducts.schema,\n presets: RelatedProducts.presets,\n },\n {\n component: OrderStatus.default,\n schema: OrderStatus.schema,\n presets: OrderStatus.presets,\n },\n {\n component: ReturnRequest.default,\n schema: ReturnRequest.schema,\n presets: ReturnRequest.presets,\n },\n]\n\nexport function registerCommercePlugin(): void {\n // The canvas half only. The console registers the console half through its\n // own `console` surface, and a published page must never load console code\n // (AGL-3116): this runs on every page that places one of these elements.\n if (Aglyn.plugins.getDependency(BUNDLE_ID)) return\n Aglyn.plugins.addDependency(\n Aglyn.defineUiFeatureBundle(\n {\n bundleId: BUNDLE_ID,\n displayName: 'Commerce',\n description: 'Storefront blocks: product grids, detail, cart',\n icon: { path: mdiStorefrontOutline.path },\n components: COMMERCE_BUNDLE,\n },\n Aglyn.components,\n ),\n )\n}\n"],"names":["Aglyn","mdiStorefrontOutline","Account","Cart","Gate","GatedVideo","MemberFeed","MemberRecovery","MemberSignin","MemberSignup","NewsletterSignup","OrderStatus","ProductDetail","ReservationWidget","ProductGrid","ProductReviews","RelatedProducts","ReturnRequest","Wishlist","BUNDLE_ID","COMMERCE_BUNDLE","component","default","schema","presets","registerCommercePlugin","plugins","getDependency","addDependency","defineUiFeatureBundle","bundleId","displayName","description","icon","path","components"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,YAAYC,aAAa,0BAAsB;AAC/C,YAAYC,UAAU,uBAAmB;AACzC,YAAYC,UAAU,uBAAmB;AACzC,YAAYC,gBAAgB,8BAA0B;AACtD,YAAYC,gBAAgB,8BAA0B;AACtD,YAAYC,oBAAoB,kCAA8B;AAC9D,YAAYC,kBAAkB,gCAA4B;AAC1D,YAAYC,kBAAkB,gCAA4B;AAC1D,YAAYC,sBAAsB,oCAAgC;AAClE,YAAYC,iBAAiB,+BAA2B;AACxD,YAAYC,mBAAmB,iCAA6B;AAC5D,YAAYC,uBAAuB,qCAAiC;AACpE,YAAYC,iBAAiB,+BAA2B;AACxD,YAAYC,oBAAoB,kCAA8B;AAC9D,YAAYC,qBAAqB,mCAA+B;AAChE,YAAYC,mBAAmB,iCAA6B;AAC5D,YAAYC,cAAc,2BAAuB;AACjD,SAASC,SAAS,QAAQ,+BAA2B;AAErD;;;;;;;CAOC,GACD,OAAO,MAAMC,kBAA8C;IACzD;QACEC,
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/commerce/src/lib/site.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 * as Aglyn from '@aglyn/aglyn'\nimport { mdiStorefrontOutline } from '@aglyn/shared-data-mdi'\nimport * as Account from './components/account'\nimport * as Cart from './components/cart'\nimport * as Gate from './components/gate'\nimport * as GatedVideo from './components/gated-video'\nimport * as MemberFeed from './components/member-feed'\nimport * as MemberRecovery from './components/member-recovery'\nimport * as MemberSignin from './components/member-signin'\nimport * as MemberSignup from './components/member-signup'\nimport * as NewsletterSignup from './components/newsletter-signup'\nimport * as OrderStatus from './components/order-status'\nimport * as ProductDetail from './components/product-detail'\nimport * as ReservationWidget from './components/reservation-widget'\nimport * as ProductGrid from './components/product-grid'\nimport * as ProductReviews from './components/product-reviews'\nimport * as QuotePage from './components/quote-page'\nimport * as RelatedProducts from './components/related-products'\nimport * as ReturnRequest from './components/return-request'\nimport * as Wishlist from './components/wishlist'\nimport { BUNDLE_ID } from './constants/bundle-common'\n\n/**\n * Commerce UI feature plugin (AGL-290): the storefront component set,\n * built on the feature-plugin pattern (AGL-277) — depends on the mui\n * bundle for primitives/theming and registers alongside it in the\n * besigner and the tenant renderer. Components join `COMMERCE_BUNDLE`\n * as they land (PLP AGL-291, PDP AGL-292, cart AGL-293, …); ids are\n * persisted in screen docs and never renamed.\n */\nexport const COMMERCE_BUNDLE: Aglyn.FeatureBundleEntry[] = [\n {\n component: ProductGrid.default,\n schema: ProductGrid.schema,\n presets: ProductGrid.presets,\n },\n {\n component: ProductDetail.default,\n schema: ProductDetail.schema,\n presets: ProductDetail.presets,\n },\n {\n component: Cart.default,\n schema: Cart.schema,\n presets: Cart.presets,\n },\n {\n component: Account.default,\n schema: Account.schema,\n presets: Account.presets,\n },\n {\n component: Wishlist.default,\n schema: Wishlist.schema,\n presets: Wishlist.presets,\n },\n {\n component: NewsletterSignup.default,\n schema: NewsletterSignup.schema,\n presets: NewsletterSignup.presets,\n },\n {\n component: Gate.default,\n schema: Gate.schema,\n presets: Gate.presets,\n },\n {\n component: GatedVideo.default,\n schema: GatedVideo.schema,\n presets: GatedVideo.presets,\n },\n {\n component: MemberFeed.default,\n schema: MemberFeed.schema,\n presets: MemberFeed.presets,\n },\n {\n component: MemberRecovery.default,\n schema: MemberRecovery.schema,\n presets: MemberRecovery.presets,\n },\n {\n component: MemberSignin.default,\n schema: MemberSignin.schema,\n presets: MemberSignin.presets,\n },\n {\n component: MemberSignup.default,\n schema: MemberSignup.schema,\n presets: MemberSignup.presets,\n },\n {\n component: ReservationWidget.default,\n schema: ReservationWidget.schema,\n presets: ReservationWidget.presets,\n },\n {\n component: ProductReviews.default,\n schema: ProductReviews.schema,\n presets: ProductReviews.presets,\n },\n {\n component: RelatedProducts.default,\n schema: RelatedProducts.schema,\n presets: RelatedProducts.presets,\n },\n {\n component: OrderStatus.default,\n schema: OrderStatus.schema,\n presets: OrderStatus.presets,\n },\n {\n component: ReturnRequest.default,\n schema: ReturnRequest.schema,\n presets: ReturnRequest.presets,\n },\n {\n component: QuotePage.default,\n schema: QuotePage.schema,\n presets: QuotePage.presets,\n },\n]\n\nexport function registerCommercePlugin(): void {\n // The canvas half only. The console registers the console half through its\n // own `console` surface, and a published page must never load console code\n // (AGL-3116): this runs on every page that places one of these elements.\n if (Aglyn.plugins.getDependency(BUNDLE_ID)) return\n Aglyn.plugins.addDependency(\n Aglyn.defineUiFeatureBundle(\n {\n bundleId: BUNDLE_ID,\n displayName: 'Commerce',\n description: 'Storefront blocks: product grids, detail, cart',\n icon: { path: mdiStorefrontOutline.path },\n components: COMMERCE_BUNDLE,\n },\n Aglyn.components,\n ),\n )\n}\n"],"names":["Aglyn","mdiStorefrontOutline","Account","Cart","Gate","GatedVideo","MemberFeed","MemberRecovery","MemberSignin","MemberSignup","NewsletterSignup","OrderStatus","ProductDetail","ReservationWidget","ProductGrid","ProductReviews","QuotePage","RelatedProducts","ReturnRequest","Wishlist","BUNDLE_ID","COMMERCE_BUNDLE","component","default","schema","presets","registerCommercePlugin","plugins","getDependency","addDependency","defineUiFeatureBundle","bundleId","displayName","description","icon","path","components"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,eAAc;AACrC,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,YAAYC,aAAa,0BAAsB;AAC/C,YAAYC,UAAU,uBAAmB;AACzC,YAAYC,UAAU,uBAAmB;AACzC,YAAYC,gBAAgB,8BAA0B;AACtD,YAAYC,gBAAgB,8BAA0B;AACtD,YAAYC,oBAAoB,kCAA8B;AAC9D,YAAYC,kBAAkB,gCAA4B;AAC1D,YAAYC,kBAAkB,gCAA4B;AAC1D,YAAYC,sBAAsB,oCAAgC;AAClE,YAAYC,iBAAiB,+BAA2B;AACxD,YAAYC,mBAAmB,iCAA6B;AAC5D,YAAYC,uBAAuB,qCAAiC;AACpE,YAAYC,iBAAiB,+BAA2B;AACxD,YAAYC,oBAAoB,kCAA8B;AAC9D,YAAYC,eAAe,6BAAyB;AACpD,YAAYC,qBAAqB,mCAA+B;AAChE,YAAYC,mBAAmB,iCAA6B;AAC5D,YAAYC,cAAc,2BAAuB;AACjD,SAASC,SAAS,Q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;QACEH,WAAWT,kBAAkBU,OAAO;QACpCC,QAAQX,kBAAkBW,MAAM;QAChCC,SAASZ,kBAAkBY,OAAO;IACpC;IACA;QACEH,WAAWP,eAAeQ,OAAO;QACjCC,QAAQT,eAAeS,MAAM;QAC7BC,SAASV,eAAeU,OAAO;IACjC;IACA;QACEH,WAAWL,gBAAgBM,OAAO;QAClCC,QAAQP,gBAAgBO,MAAM;QAC9BC,SAASR,gBAAgBQ,OAAO;IAClC;IACA;QACEH,WAAWX,YAAYY,OAAO;QAC9BC,QAAQb,YAAYa,MAAM;QAC1BC,SAASd,YAAYc,OAAO;IAC9B;IACA;QACEH,WAAWJ,cAAcK,OAAO;QAChCC,QAAQN,cAAcM,MAAM;QAC5BC,SAASP,cAAcO,OAAO;IAChC;IACA;QACEH,WAAWN,UAAUO,OAAO;QAC5BC,QAAQR,UAAUQ,MAAM;QACxBC,SAAST,UAAUS,OAAO;IAC5B;CACD,CAAA;AAED,OAAO,SAASC;IACd,2EAA2E;IAC3E,2EAA2E;IAC3E,yEAAyE;IACzE,IAAI1B,MAAM2B,OAAO,CAACC,aAAa,CAACR,YAAY;IAC5CpB,MAAM2B,OAAO,CAACE,aAAa,CACzB7B,MAAM8B,qBAAqB,CACzB;QACEC,UAAUX;QACVY,aAAa;QACbC,aAAa;QACbC,MAAM;YAAEC,MAAMlC,qBAAqBkC,IAAI;QAAC;QACxCC,YAAYf;IACd,GACArB,MAAMoC,UAAU;AAGtB"}
|
|
@@ -19,6 +19,7 @@ import * as Aglyn from "@aglyn/aglyn/server";
|
|
|
19
19
|
import { firebaseAdmin, getOrgForHost, memberHasPermissionOnHost, resolveOrgMembership } from "@aglyn/tenant-data-admin";
|
|
20
20
|
import { TransferEngineError } from "@aglyn/tenant-data-admin/server/transfer-jobs";
|
|
21
21
|
import { normalizeTrackingNumber, parseShippingOrderRef } from "../model/order-shipping-export.js";
|
|
22
|
+
import { isUnpaidQuote } from "../model/commerce-quotes.js";
|
|
22
23
|
import { commerceSitePermissionRefusal } from "../model/plugin-permissions.js";
|
|
23
24
|
import { cancelOrderFulfillment, recordOrderShipment, updateFulfillmentTracking } from "../server/fulfill-order.js";
|
|
24
25
|
import { NOTHING, ROW_BUDGET_MS, firestoreOf, hostRefOf, readerSeesHost } from "./server-common.js";
|
|
@@ -96,6 +97,11 @@ const ordersOf = (firestore, ctx)=>hostRefOf(firestore, ctx).collection('orders'
|
|
|
96
97
|
if (doc.exists) found.set(doc.id, doc);
|
|
97
98
|
}
|
|
98
99
|
}
|
|
100
|
+
// An unpaid quote holds an order number but is not an order yet (AGL-4093):
|
|
101
|
+
// a file naming that number matches nothing to ship.
|
|
102
|
+
for (const [id, doc] of found){
|
|
103
|
+
if (isUnpaidQuote(doc.data())) found.delete(id);
|
|
104
|
+
}
|
|
99
105
|
return found;
|
|
100
106
|
}
|
|
101
107
|
export async function lookupTrackingOrders(ctx, requests) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/tracking.server.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 buildMatchLookup,\n type BuildTransferPlanInput,\n type MatchKeySpec,\n type MatchLookupRequest,\n type PlannedTransferRow,\n type TransferChunk,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n type TransferUndoStep,\n} from '@aglyn/aglyn/data-transfer'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type {\n PluginTransferResource,\n TransferApplyResult,\n TransferApplyWriter,\n TransferLookupResult,\n TransferReadOptions,\n TransferReadPage,\n TransferResourceContext,\n TransferRevertDecisions,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, memberHasPermissionOnHost, resolveOrgMembership } from '@aglyn/tenant-data-admin'\nimport { TransferEngineError } from '@aglyn/tenant-data-admin/server/transfer-jobs'\nimport { normalizeTrackingNumber, parseShippingOrderRef } from '../model/order-shipping-export'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport {\n cancelOrderFulfillment,\n recordOrderShipment,\n updateFulfillmentTracking,\n} from '../server/fulfill-order'\nimport { NOTHING, ROW_BUDGET_MS, firestoreOf, hostRefOf, readerSeesHost, type Firestore } from './server-common'\nimport {\n TRACKING_DEFAULT_POLICY,\n TRACKING_MATCH_KEYS,\n matchTrackingRows,\n planTrackingRows,\n trackingExportRows,\n trackingMatchValues,\n trackingRecord,\n type StoredTrackingOrder,\n type TrackingPlannedRow,\n} from './tracking-transfer'\n\n/*\n * THE TRACKING IMPORT'S SERVER HALF (AGL-3613). The plan is\n * `planTrackingRows`; this module reads the orders it plans against, writes\n * each parcel through the order's own shipment paths and undoes them.\n *\n * - WHO: the site's admins and editors — the roles the console's Fulfill\n * button has — on a plan that sells. Asked by the plan, the apply and the\n * undo, each server-side.\n * - HOW: a new parcel through `recordOrderShipment`, keyed by its tracking\n * number, so a retried chunk or a second import of the same file is one\n * parcel; the buyer is emailed as for any shipment. A replaced tracking\n * number through `updateFulfillmentTracking`.\n * - UNDO: a parcel this import recorded is cancelled (its units go back to\n * unfulfilled), and a replaced tracking number is put back — each only\n * while the shipment still holds what the import wrote; otherwise it is a\n * conflict the person decides.\n */\n\nconst IN_MAX = 30\n\n/** Orders a page of the shipments export reads: those that have shipped something. */\nconst SHIPPED_STATUSES = ['partially_fulfilled', 'fulfilled', 'delivered']\n\n/** The member importing, checked for the role and the plan, or the refusal. */\nasync function shipperOf(ctx: TransferResourceContext): Promise<{ hostId: string }> {\n const hostId = ctx.hostId\n if (!hostId) throw new TransferEngineError('invalid', 400, 'Tracking numbers belong to a site; name the site.')\n const uid = ctx.actorUid\n const membership = uid ? await resolveOrgMembership(uid, ctx.orgId) : null\n // \"Manage orders\" (`commerce.orders`, AGL-4047) on this site, resolved fresh\n // from the membership: its preset is the site's Admin and Editor this\n // asked for, then the member's custom role, own permissions and site toggle.\n const allowed =\n !!uid && !!membership?.member &&\n (await memberHasPermissionOnHost(ctx.orgId, hostId, membership.member, 'commerce.orders'))\n if (!allowed) {\n throw new TransferEngineError('forbidden', 403, commerceSitePermissionRefusal('commerce.orders'))\n }\n const owner = await getOrgForHost(hostId).catch(() => null)\n if (!Aglyn.checkEntitlement(owner?.org as never, 'commerce')) {\n throw new TransferEngineError('forbidden', 403, 'This site’s plan does not include selling.')\n }\n return { hostId }\n}\n\nconst ordersOf = (firestore: Firestore, ctx: TransferResourceContext) => hostRefOf(firestore, ctx).collection('orders')\n\n/** Orders by the values a file names them by: numbers through one query per 30, ids directly. */\nasync function findOrders(\n firestore: Firestore,\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n): Promise<Map<string, FirebaseFirestore.DocumentSnapshot>> {\n const collection = ordersOf(firestore, ctx)\n const found = new Map<string, FirebaseFirestore.DocumentSnapshot>()\n const numbers = new Set<number>()\n const ids = new Set<string>()\n for (const request of requests) {\n for (const value of request.values) {\n const ref = request.fieldId === 'id' ? { id: value } : parseShippingOrderRef(value)\n if (!ref) continue\n if (ref.number !== undefined) numbers.add(ref.number)\n if (ref.id && !ref.id.includes('/') && !/^__.*__$/.test(ref.id)) ids.add(ref.id)\n }\n }\n const numberList = [...numbers]\n for (let at = 0; at < numberList.length; at += IN_MAX) {\n const snapshot = await collection.where('number', 'in', numberList.slice(at, at + IN_MAX)).get()\n for (const doc of snapshot.docs) found.set(doc.id, doc)\n }\n const idList = [...ids].filter((id) => !found.has(id))\n for (let at = 0; at < idList.length; at += 100) {\n for (const doc of await firestore.getAll(...idList.slice(at, at + 100).map((id) => collection.doc(id)))) {\n if (doc.exists) found.set(doc.id, doc)\n }\n }\n return found\n}\n\nexport async function lookupTrackingOrders(\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n): Promise<TransferLookupResult> {\n const found = await findOrders(firestoreOf(), ctx, requests)\n const keys: MatchKeySpec[] = requests.map((request) => ({ fieldId: request.fieldId, normalizer: request.normalizer }))\n const records = new Map<string, Readonly<Record<string, unknown>>>()\n const entries: Array<{ id: string; values: Record<string, unknown> }> = []\n for (const doc of found.values()) {\n const data = (doc.data() ?? {}) as StoredTrackingOrder\n records.set(doc.id, trackingRecord(doc.id, data))\n entries.push({ id: doc.id, values: trackingMatchValues(doc.id, data) })\n }\n return { lookup: buildMatchLookup(entries, keys), records }\n}\n\n/**\n * The shipments export: every order that has shipped something, newest\n * first, one row per shipment with a tracking number. The cursor is the last\n * order's `createdAtMs` and id, as the orders export pages.\n */\nexport async function readTrackingPage(\n ctx: TransferResourceContext,\n cursor: string | null,\n fieldIds: readonly string[],\n options?: TransferReadOptions,\n): Promise<TransferReadPage> {\n if (!readerSeesHost(ctx, options)) return NOTHING\n if (options?.filter) throw new Error('Shipments export every shipment, or those of the orders you select.')\n const firestore = firestoreOf()\n const collection = ordersOf(firestore, ctx)\n const pageSize = Math.max(1, Math.min(500, options?.pageSize ?? 200))\n let docs: FirebaseFirestore.DocumentSnapshot[]\n let next: string | null\n if (options?.ids) {\n const offset = cursor ? Number(cursor) : 0\n const ids = options.ids.slice(offset, offset + pageSize)\n docs = ids.length ? (await firestore.getAll(...ids.map((id) => collection.doc(id)))).filter((doc) => doc.exists) : []\n next = offset + ids.length < options.ids.length ? String(offset + ids.length) : null\n } else {\n const query = collection\n .where('status', 'in', SHIPPED_STATUSES)\n .orderBy('createdAtMs', 'desc')\n .orderBy(firebaseAdmin.firestore.FieldPath.documentId(), 'desc')\n const after = cursor ? (JSON.parse(cursor) as unknown[]) : null\n const snapshot = await (after ? query.startAfter(...after) : query).limit(pageSize).get()\n docs = snapshot.docs\n const last = snapshot.docs[snapshot.docs.length - 1]\n next = last && snapshot.docs.length === pageSize ? JSON.stringify([last.get('createdAtMs') ?? null, last.id]) : null\n }\n const rows = docs.flatMap((doc) =>\n trackingExportRows(doc.id, (doc.data() ?? {}) as StoredTrackingOrder).map((record) =>\n Object.fromEntries(fieldIds.map((fieldId) => [fieldId, record[fieldId] ?? null])),\n ),\n )\n return { rows, next }\n}\n\n/** The dry run, against every matched order read once. */\nexport async function planTracking(ctx: TransferResourceContext, input: BuildTransferPlanInput): Promise<TransferPlan> {\n await shipperOf(ctx)\n const firestore = firestoreOf()\n const ids = [\n ...new Set(\n input.matches\n .map((match) => (match.kind === 'matched' ? match.recordId : null))\n .filter((id): id is string => Boolean(id)),\n ),\n ]\n const collection = ordersOf(firestore, ctx)\n const orders = new Map<string, StoredTrackingOrder>()\n for (let at = 0; at < ids.length; at += 100) {\n for (const doc of await firestore.getAll(...ids.slice(at, at + 100).map((id) => collection.doc(id)))) {\n if (doc.exists) orders.set(doc.id, (doc.data() ?? {}) as StoredTrackingOrder)\n }\n }\n return planTrackingRows(input, orders)\n}\n\n/** Records one chunk's parcels, each through the order's own shipment paths. */\nexport async function applyTracking(\n ctx: TransferResourceContext,\n chunk: TransferChunk<PlannedTransferRow>,\n writer: TransferApplyWriter,\n): Promise<TransferApplyResult> {\n const { hostId } = await shipperOf(ctx)\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const fail = async (row: number, message: string) => {\n const result: TransferRowResult = { row, outcome: 'failed', reason: 'refusedValue', message }\n results.push(result)\n await writer.markApplied(result)\n }\n for (const row of chunk.rows as TrackingPlannedRow[]) {\n const earlier = await writer.alreadyApplied(row.index)\n if (earlier) {\n results.push(earlier)\n continue\n }\n if (writer.timeLeftMs() < ROW_BUDGET_MS) break\n const decision = row.tracking\n if (row.verdict !== 'update' || !decision) {\n await fail(row.index, 'A tracking file only records parcels for orders it names.')\n continue\n }\n if (decision.action === 'ship') {\n const outcome = await recordOrderShipment({\n hostId,\n orderId: decision.orderId,\n to: 'fulfilled',\n carrier: decision.carrier,\n trackingNumber: decision.trackingNumber,\n ...(decision.trackingUrl ? { trackingUrl: decision.trackingUrl } : {}),\n ...(decision.lineItems ? { lineItems: decision.lineItems } : {}),\n idempotencyKey: `tracking-import:${normalizeTrackingNumber(decision.trackingNumber)}`,\n onceByTracking: true,\n })\n if (outcome.outcome === 'recorded' || (outcome.outcome === 'already' && outcome.fulfillment)) {\n const fulfillment = outcome.fulfillment\n const result: TransferRowResult = {\n row: row.index,\n outcome: outcome.outcome === 'recorded' ? 'updated' : 'unchanged',\n recordId: decision.orderId,\n }\n // Only a parcel THIS import recorded is undone; one found already\n // there was somebody else's.\n const entry: TransferUndoEntry | undefined =\n outcome.outcome === 'recorded' && fulfillment\n ? {\n row: row.index,\n recordId: decision.orderId,\n action: 'updated',\n previous: { fulfillmentId: null },\n written: {\n fulfillmentId: fulfillment.id,\n trackingNumber: fulfillment.trackingNumber ?? null,\n carrier: fulfillment.carrier ?? null,\n },\n }\n : undefined\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n continue\n }\n await fail(\n row.index,\n outcome.outcome === 'blocked'\n ? `The order is ${outcome.from.replace(/_/g, ' ')} and cannot be shipped.`\n : outcome.outcome === 'invalid_lines'\n ? outcome.message\n : outcome.outcome === 'no_such_order'\n ? 'The order no longer exists.'\n : 'The order has nothing left to ship.',\n )\n continue\n }\n const outcome = await updateFulfillmentTracking({\n hostId,\n orderId: decision.orderId,\n fulfillmentId: decision.fulfillmentId,\n carrier: decision.carrier,\n trackingNumber: decision.trackingNumber,\n ...(decision.trackingUrl ? { trackingUrl: decision.trackingUrl } : {}),\n })\n if (outcome.outcome === 'updated' || outcome.outcome === 'already') {\n const result: TransferRowResult = {\n row: row.index,\n outcome: outcome.outcome === 'updated' ? 'updated' : 'unchanged',\n recordId: decision.orderId,\n }\n const entry: TransferUndoEntry | undefined =\n outcome.outcome === 'updated'\n ? {\n row: row.index,\n recordId: decision.orderId,\n action: 'updated',\n previous: { fulfillmentId: decision.fulfillmentId, ...decision.previous },\n written: {\n fulfillmentId: decision.fulfillmentId,\n trackingNumber: outcome.fulfillment.trackingNumber ?? null,\n carrier: outcome.fulfillment.carrier ?? null,\n },\n }\n : undefined\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n continue\n }\n await fail(\n row.index,\n outcome.outcome === 'locked'\n ? `The order is ${outcome.from.replace(/_/g, ' ')}; its shipments can no longer change.`\n : 'The shipment no longer exists.',\n )\n }\n return { results, undo }\n}\n\n/**\n * Undoes one chunk, newest first: a parcel the import recorded is cancelled\n * and a tracking number it replaced is put back — while the shipment still\n * holds what the import wrote. A shipment edited since is a conflict, done\n * only when the person's decision says `revert`.\n */\nexport async function revertTracking(\n ctx: TransferResourceContext,\n snapshot: TransferUndoSnapshot,\n decisions?: TransferRevertDecisions,\n): Promise<TransferRevertResult> {\n const { hostId } = await shipperOf(ctx)\n const firestore = firestoreOf()\n const collection = ordersOf(firestore, ctx)\n const done: TransferUndoStep[] = []\n const conflicts: TransferUndoStep[] = []\n for (const entry of [...snapshot.entries].reverse()) {\n const fulfillmentId = String(entry.written['fulfillmentId'] ?? '')\n const doc = await collection.doc(entry.recordId).get()\n const order = doc.exists ? ((doc.data() ?? {}) as Record<string, unknown>) : null\n const current = ((order?.['fulfillments'] as Array<Record<string, unknown>> | undefined) ?? []).find(\n (fulfillment) => fulfillment['id'] === fulfillmentId,\n )\n if (!doc.exists || !current || current['status'] === 'cancelled') {\n done.push({ action: 'nothing', recordId: entry.recordId, why: doc.exists ? 'alreadyReverted' : 'gone' })\n continue\n }\n const edited =\n normalizeTrackingNumber(current['trackingNumber']) !== normalizeTrackingNumber(entry.written['trackingNumber'])\n if (edited && decisions?.[entry.recordId] !== 'revert') {\n conflicts.push({\n action: 'conflict',\n recordId: entry.recordId,\n fields: ['trackingNumber'],\n values: { trackingNumber: current['trackingNumber'] ?? null },\n })\n continue\n }\n const recorded = entry.previous?.['fulfillmentId'] === null\n const outcome = recorded\n ? await cancelOrderFulfillment({ hostId, orderId: entry.recordId, fulfillmentId })\n : await updateFulfillmentTracking({\n hostId,\n orderId: entry.recordId,\n fulfillmentId,\n carrier: String(entry.previous?.['carrier'] ?? ''),\n trackingNumber: String(entry.previous?.['trackingNumber'] ?? ''),\n ...(entry.previous?.['trackingUrl'] ? { trackingUrl: String(entry.previous['trackingUrl']) } : {}),\n })\n if (outcome.outcome === 'locked') {\n conflicts.push({\n action: 'conflict',\n recordId: entry.recordId,\n fields: ['status'],\n values: { status: outcome.from },\n })\n continue\n }\n done.push(\n recorded\n ? { action: 'delete', recordId: entry.recordId }\n : {\n action: 'restore',\n recordId: entry.recordId,\n values: { trackingNumber: entry.previous?.['trackingNumber'] ?? null },\n },\n )\n }\n return { done, conflicts }\n}\n\nexport const trackingTransfer: PluginTransferResource = {\n matchKeys: TRACKING_MATCH_KEYS,\n defaultPolicy: TRACKING_DEFAULT_POLICY,\n readPage: (ctx, cursor, fieldIds, options) => readTrackingPage(ctx, cursor, fieldIds, options),\n lookup: (ctx, requests) => lookupTrackingOrders(ctx, requests),\n match: (_ctx, input) => ({ outcomes: matchTrackingRows(input.rows, input.lookup) }),\n plan: (ctx, input) => planTracking(ctx, input),\n apply: (ctx, chunk, writer) => applyTracking(ctx, chunk, writer),\n revert: (ctx, snapshot, decisions) => revertTracking(ctx, snapshot, decisions),\n}\n"],"names":["buildMatchLookup","Aglyn","firebaseAdmin","getOrgForHost","memberHasPermissionOnHost","resolveOrgMembership","TransferEngineError","normalizeTrackingNumber","parseShippingOrderRef","commerceSitePermissionRefusal","cancelOrderFulfillment","recordOrderShipment","updateFulfillmentTracking","NOTHING","ROW_BUDGET_MS","firestoreOf","hostRefOf","readerSeesHost","TRACKING_DEFAULT_POLICY","TRACKING_MATCH_KEYS","matchTrackingRows","planTrackingRows","trackingExportRows","trackingMatchValues","trackingRecord","IN_MAX","SHIPPED_STATUSES","shipperOf","ctx","hostId","uid","actorUid","membership","orgId","allowed","member","owner","catch","checkEntitlement","org","ordersOf","firestore","collection","findOrders","requests","found","Map","numbers","Set","ids","request","value","values","ref","fieldId","id","number","undefined","add","includes","test","numberList","at","length","snapshot","where","slice","get","doc","docs","set","idList","filter","has","getAll","map","exists","lookupTrackingOrders","keys","normalizer","records","entries","data","push","lookup","readTrackingPage","cursor","fieldIds","options","Error","pageSize","Math","max","min","next","offset","Number","String","last","query","orderBy","FieldPath","documentId","after","JSON","parse","startAfter","limit","stringify","rows","flatMap","record","Object","fromEntries","planTracking","input","matches","match","kind","recordId","Boolean","orders","applyTracking","chunk","writer","results","undo","fail","row","message","result","outcome","reason","markApplied","earlier","alreadyApplied","index","timeLeftMs","decision","tracking","verdict","action","orderId","to","carrier","trackingNumber","trackingUrl","lineItems","idempotencyKey","onceByTracking","fulfillment","entry","previous","fulfillmentId","written","from","replace","revertTracking","decisions","done","conflicts","reverse","order","current","find","why","edited","fields","recorded","status","trackingTransfer","matchKeys","defaultPolicy","readPage","_ctx","outcomes","plan","apply","revert"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAWX,6BAA4B;AACnC,YAAYC,WAAW,sBAAqB;AAY5C,SAASC,aAAa,EAAEC,aAAa,EAAEC,yBAAyB,EAAEC,oBAAoB,QAAQ,2BAA0B;AACxH,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,uBAAuB,EAAEC,qBAAqB,QAAQ,oCAAgC;AAC/F,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,SACEC,sBAAsB,EACtBC,mBAAmB,EACnBC,yBAAyB,QACpB,6BAAyB;AAChC,SAASC,OAAO,EAAEC,aAAa,EAAEC,WAAW,EAAEC,SAAS,EAAEC,cAAc,QAAwB,qBAAiB;AAChH,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,iBAAiB,EACjBC,gBAAgB,EAChBC,kBAAkB,EAClBC,mBAAmB,EACnBC,c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AQwB,IAAI;gBAAC;YACjC;YACA;QACF;QACAI,KAAK5E,IAAI,CACPqF,WACI;YAAE3B,QAAQ;YAAUtB,UAAUgC,MAAMhC,QAAQ;QAAC,IAC7C;YACEsB,QAAQ;YACRtB,UAAUgC,MAAMhC,QAAQ;YACxBnE,QAAQ;gBAAE6F,cAAc,YAAEM,mBAAAA,MAAMC,QAAQ,qBAAdD,gBAAgB,CAAC,iBAAiB,oBAAI;YAAK;QACvE;IAER;IACA,OAAO;QAAEQ;QAAMC;IAAU;AAC3B;AAEA,OAAO,MAAMU,mBAA2C;IACtDC,WAAWxJ;IACXyJ,eAAe1J;IACf2J,UAAU,CAACjJ,KAAK0D,QAAQC,UAAUC,UAAYH,iBAAiBzD,KAAK0D,QAAQC,UAAUC;IACtFJ,QAAQ,CAACxD,KAAKgB,WAAaiC,qBAAqBjD,KAAKgB;IACrDyE,OAAO,CAACyD,MAAM3D,QAAW,CAAA;YAAE4D,UAAU3J,kBAAkB+F,MAAMN,IAAI,EAAEM,MAAM/B,MAAM;QAAE,CAAA;IACjF4F,MAAM,CAACpJ,KAAKuF,QAAUD,aAAatF,KAAKuF;IACxC8D,OAAO,CAACrJ,KAAK+F,OAAOC,SAAWF,cAAc9F,KAAK+F,OAAOC;IACzDsD,QAAQ,CAACtJ,KAAKoC,UAAU8F,YAAcD,eAAejI,KAAKoC,UAAU8F;AACtE,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/transfer/tracking.server.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 buildMatchLookup,\n type BuildTransferPlanInput,\n type MatchKeySpec,\n type MatchLookupRequest,\n type PlannedTransferRow,\n type TransferChunk,\n type TransferPlan,\n type TransferRowResult,\n type TransferUndoEntry,\n type TransferUndoSnapshot,\n type TransferUndoStep,\n} from '@aglyn/aglyn/data-transfer'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type {\n PluginTransferResource,\n TransferApplyResult,\n TransferApplyWriter,\n TransferLookupResult,\n TransferReadOptions,\n TransferReadPage,\n TransferResourceContext,\n TransferRevertDecisions,\n TransferRevertResult,\n} from '@aglyn/aglyn/plugin-manager/plugin-transfer-resources'\nimport { firebaseAdmin, getOrgForHost, memberHasPermissionOnHost, resolveOrgMembership } from '@aglyn/tenant-data-admin'\nimport { TransferEngineError } from '@aglyn/tenant-data-admin/server/transfer-jobs'\nimport { normalizeTrackingNumber, parseShippingOrderRef } from '../model/order-shipping-export'\nimport { isUnpaidQuote } from '../model/commerce-quotes'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport {\n cancelOrderFulfillment,\n recordOrderShipment,\n updateFulfillmentTracking,\n} from '../server/fulfill-order'\nimport { NOTHING, ROW_BUDGET_MS, firestoreOf, hostRefOf, readerSeesHost, type Firestore } from './server-common'\nimport {\n TRACKING_DEFAULT_POLICY,\n TRACKING_MATCH_KEYS,\n matchTrackingRows,\n planTrackingRows,\n trackingExportRows,\n trackingMatchValues,\n trackingRecord,\n type StoredTrackingOrder,\n type TrackingPlannedRow,\n} from './tracking-transfer'\n\n/*\n * THE TRACKING IMPORT'S SERVER HALF (AGL-3613). The plan is\n * `planTrackingRows`; this module reads the orders it plans against, writes\n * each parcel through the order's own shipment paths and undoes them.\n *\n * - WHO: the site's admins and editors — the roles the console's Fulfill\n * button has — on a plan that sells. Asked by the plan, the apply and the\n * undo, each server-side.\n * - HOW: a new parcel through `recordOrderShipment`, keyed by its tracking\n * number, so a retried chunk or a second import of the same file is one\n * parcel; the buyer is emailed as for any shipment. A replaced tracking\n * number through `updateFulfillmentTracking`.\n * - UNDO: a parcel this import recorded is cancelled (its units go back to\n * unfulfilled), and a replaced tracking number is put back — each only\n * while the shipment still holds what the import wrote; otherwise it is a\n * conflict the person decides.\n */\n\nconst IN_MAX = 30\n\n/** Orders a page of the shipments export reads: those that have shipped something. */\nconst SHIPPED_STATUSES = ['partially_fulfilled', 'fulfilled', 'delivered']\n\n/** The member importing, checked for the role and the plan, or the refusal. */\nasync function shipperOf(ctx: TransferResourceContext): Promise<{ hostId: string }> {\n const hostId = ctx.hostId\n if (!hostId) throw new TransferEngineError('invalid', 400, 'Tracking numbers belong to a site; name the site.')\n const uid = ctx.actorUid\n const membership = uid ? await resolveOrgMembership(uid, ctx.orgId) : null\n // \"Manage orders\" (`commerce.orders`, AGL-4047) on this site, resolved fresh\n // from the membership: its preset is the site's Admin and Editor this\n // asked for, then the member's custom role, own permissions and site toggle.\n const allowed =\n !!uid && !!membership?.member &&\n (await memberHasPermissionOnHost(ctx.orgId, hostId, membership.member, 'commerce.orders'))\n if (!allowed) {\n throw new TransferEngineError('forbidden', 403, commerceSitePermissionRefusal('commerce.orders'))\n }\n const owner = await getOrgForHost(hostId).catch(() => null)\n if (!Aglyn.checkEntitlement(owner?.org as never, 'commerce')) {\n throw new TransferEngineError('forbidden', 403, 'This site’s plan does not include selling.')\n }\n return { hostId }\n}\n\nconst ordersOf = (firestore: Firestore, ctx: TransferResourceContext) => hostRefOf(firestore, ctx).collection('orders')\n\n/** Orders by the values a file names them by: numbers through one query per 30, ids directly. */\nasync function findOrders(\n firestore: Firestore,\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n): Promise<Map<string, FirebaseFirestore.DocumentSnapshot>> {\n const collection = ordersOf(firestore, ctx)\n const found = new Map<string, FirebaseFirestore.DocumentSnapshot>()\n const numbers = new Set<number>()\n const ids = new Set<string>()\n for (const request of requests) {\n for (const value of request.values) {\n const ref = request.fieldId === 'id' ? { id: value } : parseShippingOrderRef(value)\n if (!ref) continue\n if (ref.number !== undefined) numbers.add(ref.number)\n if (ref.id && !ref.id.includes('/') && !/^__.*__$/.test(ref.id)) ids.add(ref.id)\n }\n }\n const numberList = [...numbers]\n for (let at = 0; at < numberList.length; at += IN_MAX) {\n const snapshot = await collection.where('number', 'in', numberList.slice(at, at + IN_MAX)).get()\n for (const doc of snapshot.docs) found.set(doc.id, doc)\n }\n const idList = [...ids].filter((id) => !found.has(id))\n for (let at = 0; at < idList.length; at += 100) {\n for (const doc of await firestore.getAll(...idList.slice(at, at + 100).map((id) => collection.doc(id)))) {\n if (doc.exists) found.set(doc.id, doc)\n }\n }\n // An unpaid quote holds an order number but is not an order yet (AGL-4093):\n // a file naming that number matches nothing to ship.\n for (const [id, doc] of found) {\n if (isUnpaidQuote(doc.data())) found.delete(id)\n }\n return found\n}\n\nexport async function lookupTrackingOrders(\n ctx: TransferResourceContext,\n requests: readonly MatchLookupRequest[],\n): Promise<TransferLookupResult> {\n const found = await findOrders(firestoreOf(), ctx, requests)\n const keys: MatchKeySpec[] = requests.map((request) => ({ fieldId: request.fieldId, normalizer: request.normalizer }))\n const records = new Map<string, Readonly<Record<string, unknown>>>()\n const entries: Array<{ id: string; values: Record<string, unknown> }> = []\n for (const doc of found.values()) {\n const data = (doc.data() ?? {}) as StoredTrackingOrder\n records.set(doc.id, trackingRecord(doc.id, data))\n entries.push({ id: doc.id, values: trackingMatchValues(doc.id, data) })\n }\n return { lookup: buildMatchLookup(entries, keys), records }\n}\n\n/**\n * The shipments export: every order that has shipped something, newest\n * first, one row per shipment with a tracking number. The cursor is the last\n * order's `createdAtMs` and id, as the orders export pages.\n */\nexport async function readTrackingPage(\n ctx: TransferResourceContext,\n cursor: string | null,\n fieldIds: readonly string[],\n options?: TransferReadOptions,\n): Promise<TransferReadPage> {\n if (!readerSeesHost(ctx, options)) return NOTHING\n if (options?.filter) throw new Error('Shipments export every shipment, or those of the orders you select.')\n const firestore = firestoreOf()\n const collection = ordersOf(firestore, ctx)\n const pageSize = Math.max(1, Math.min(500, options?.pageSize ?? 200))\n let docs: FirebaseFirestore.DocumentSnapshot[]\n let next: string | null\n if (options?.ids) {\n const offset = cursor ? Number(cursor) : 0\n const ids = options.ids.slice(offset, offset + pageSize)\n docs = ids.length ? (await firestore.getAll(...ids.map((id) => collection.doc(id)))).filter((doc) => doc.exists) : []\n next = offset + ids.length < options.ids.length ? String(offset + ids.length) : null\n } else {\n const query = collection\n .where('status', 'in', SHIPPED_STATUSES)\n .orderBy('createdAtMs', 'desc')\n .orderBy(firebaseAdmin.firestore.FieldPath.documentId(), 'desc')\n const after = cursor ? (JSON.parse(cursor) as unknown[]) : null\n const snapshot = await (after ? query.startAfter(...after) : query).limit(pageSize).get()\n docs = snapshot.docs\n const last = snapshot.docs[snapshot.docs.length - 1]\n next = last && snapshot.docs.length === pageSize ? JSON.stringify([last.get('createdAtMs') ?? null, last.id]) : null\n }\n const rows = docs.flatMap((doc) =>\n trackingExportRows(doc.id, (doc.data() ?? {}) as StoredTrackingOrder).map((record) =>\n Object.fromEntries(fieldIds.map((fieldId) => [fieldId, record[fieldId] ?? null])),\n ),\n )\n return { rows, next }\n}\n\n/** The dry run, against every matched order read once. */\nexport async function planTracking(ctx: TransferResourceContext, input: BuildTransferPlanInput): Promise<TransferPlan> {\n await shipperOf(ctx)\n const firestore = firestoreOf()\n const ids = [\n ...new Set(\n input.matches\n .map((match) => (match.kind === 'matched' ? match.recordId : null))\n .filter((id): id is string => Boolean(id)),\n ),\n ]\n const collection = ordersOf(firestore, ctx)\n const orders = new Map<string, StoredTrackingOrder>()\n for (let at = 0; at < ids.length; at += 100) {\n for (const doc of await firestore.getAll(...ids.slice(at, at + 100).map((id) => collection.doc(id)))) {\n if (doc.exists) orders.set(doc.id, (doc.data() ?? {}) as StoredTrackingOrder)\n }\n }\n return planTrackingRows(input, orders)\n}\n\n/** Records one chunk's parcels, each through the order's own shipment paths. */\nexport async function applyTracking(\n ctx: TransferResourceContext,\n chunk: TransferChunk<PlannedTransferRow>,\n writer: TransferApplyWriter,\n): Promise<TransferApplyResult> {\n const { hostId } = await shipperOf(ctx)\n const results: TransferRowResult[] = []\n const undo: TransferUndoEntry[] = []\n const fail = async (row: number, message: string) => {\n const result: TransferRowResult = { row, outcome: 'failed', reason: 'refusedValue', message }\n results.push(result)\n await writer.markApplied(result)\n }\n for (const row of chunk.rows as TrackingPlannedRow[]) {\n const earlier = await writer.alreadyApplied(row.index)\n if (earlier) {\n results.push(earlier)\n continue\n }\n if (writer.timeLeftMs() < ROW_BUDGET_MS) break\n const decision = row.tracking\n if (row.verdict !== 'update' || !decision) {\n await fail(row.index, 'A tracking file only records parcels for orders it names.')\n continue\n }\n if (decision.action === 'ship') {\n const outcome = await recordOrderShipment({\n hostId,\n orderId: decision.orderId,\n to: 'fulfilled',\n carrier: decision.carrier,\n trackingNumber: decision.trackingNumber,\n ...(decision.trackingUrl ? { trackingUrl: decision.trackingUrl } : {}),\n ...(decision.lineItems ? { lineItems: decision.lineItems } : {}),\n idempotencyKey: `tracking-import:${normalizeTrackingNumber(decision.trackingNumber)}`,\n onceByTracking: true,\n })\n if (outcome.outcome === 'recorded' || (outcome.outcome === 'already' && outcome.fulfillment)) {\n const fulfillment = outcome.fulfillment\n const result: TransferRowResult = {\n row: row.index,\n outcome: outcome.outcome === 'recorded' ? 'updated' : 'unchanged',\n recordId: decision.orderId,\n }\n // Only a parcel THIS import recorded is undone; one found already\n // there was somebody else's.\n const entry: TransferUndoEntry | undefined =\n outcome.outcome === 'recorded' && fulfillment\n ? {\n row: row.index,\n recordId: decision.orderId,\n action: 'updated',\n previous: { fulfillmentId: null },\n written: {\n fulfillmentId: fulfillment.id,\n trackingNumber: fulfillment.trackingNumber ?? null,\n carrier: fulfillment.carrier ?? null,\n },\n }\n : undefined\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n continue\n }\n await fail(\n row.index,\n outcome.outcome === 'blocked'\n ? `The order is ${outcome.from.replace(/_/g, ' ')} and cannot be shipped.`\n : outcome.outcome === 'invalid_lines'\n ? outcome.message\n : outcome.outcome === 'no_such_order'\n ? 'The order no longer exists.'\n : 'The order has nothing left to ship.',\n )\n continue\n }\n const outcome = await updateFulfillmentTracking({\n hostId,\n orderId: decision.orderId,\n fulfillmentId: decision.fulfillmentId,\n carrier: decision.carrier,\n trackingNumber: decision.trackingNumber,\n ...(decision.trackingUrl ? { trackingUrl: decision.trackingUrl } : {}),\n })\n if (outcome.outcome === 'updated' || outcome.outcome === 'already') {\n const result: TransferRowResult = {\n row: row.index,\n outcome: outcome.outcome === 'updated' ? 'updated' : 'unchanged',\n recordId: decision.orderId,\n }\n const entry: TransferUndoEntry | undefined =\n outcome.outcome === 'updated'\n ? {\n row: row.index,\n recordId: decision.orderId,\n action: 'updated',\n previous: { fulfillmentId: decision.fulfillmentId, ...decision.previous },\n written: {\n fulfillmentId: decision.fulfillmentId,\n trackingNumber: outcome.fulfillment.trackingNumber ?? null,\n carrier: outcome.fulfillment.carrier ?? null,\n },\n }\n : undefined\n results.push(result)\n if (entry) undo.push(entry)\n await writer.markApplied(result, entry)\n continue\n }\n await fail(\n row.index,\n outcome.outcome === 'locked'\n ? `The order is ${outcome.from.replace(/_/g, ' ')}; its shipments can no longer change.`\n : 'The shipment no longer exists.',\n )\n }\n return { results, undo }\n}\n\n/**\n * Undoes one chunk, newest first: a parcel the import recorded is cancelled\n * and a tracking number it replaced is put back — while the shipment still\n * holds what the import wrote. A shipment edited since is a conflict, done\n * only when the person's decision says `revert`.\n */\nexport async function revertTracking(\n ctx: TransferResourceContext,\n snapshot: TransferUndoSnapshot,\n decisions?: TransferRevertDecisions,\n): Promise<TransferRevertResult> {\n const { hostId } = await shipperOf(ctx)\n const firestore = firestoreOf()\n const collection = ordersOf(firestore, ctx)\n const done: TransferUndoStep[] = []\n const conflicts: TransferUndoStep[] = []\n for (const entry of [...snapshot.entries].reverse()) {\n const fulfillmentId = String(entry.written['fulfillmentId'] ?? '')\n const doc = await collection.doc(entry.recordId).get()\n const order = doc.exists ? ((doc.data() ?? {}) as Record<string, unknown>) : null\n const current = ((order?.['fulfillments'] as Array<Record<string, unknown>> | undefined) ?? []).find(\n (fulfillment) => fulfillment['id'] === fulfillmentId,\n )\n if (!doc.exists || !current || current['status'] === 'cancelled') {\n done.push({ action: 'nothing', recordId: entry.recordId, why: doc.exists ? 'alreadyReverted' : 'gone' })\n continue\n }\n const edited =\n normalizeTrackingNumber(current['trackingNumber']) !== normalizeTrackingNumber(entry.written['trackingNumber'])\n if (edited && decisions?.[entry.recordId] !== 'revert') {\n conflicts.push({\n action: 'conflict',\n recordId: entry.recordId,\n fields: ['trackingNumber'],\n values: { trackingNumber: current['trackingNumber'] ?? null },\n })\n continue\n }\n const recorded = entry.previous?.['fulfillmentId'] === null\n const outcome = recorded\n ? await cancelOrderFulfillment({ hostId, orderId: entry.recordId, fulfillmentId })\n : await updateFulfillmentTracking({\n hostId,\n orderId: entry.recordId,\n fulfillmentId,\n carrier: String(entry.previous?.['carrier'] ?? ''),\n trackingNumber: String(entry.previous?.['trackingNumber'] ?? ''),\n ...(entry.previous?.['trackingUrl'] ? { trackingUrl: String(entry.previous['trackingUrl']) } : {}),\n })\n if (outcome.outcome === 'locked') {\n conflicts.push({\n action: 'conflict',\n recordId: entry.recordId,\n fields: ['status'],\n values: { status: outcome.from },\n })\n continue\n }\n done.push(\n recorded\n ? { action: 'delete', recordId: entry.recordId }\n : {\n action: 'restore',\n recordId: entry.recordId,\n values: { trackingNumber: entry.previous?.['trackingNumber'] ?? null },\n },\n )\n }\n return { done, conflicts }\n}\n\nexport const trackingTransfer: PluginTransferResource = {\n matchKeys: TRACKING_MATCH_KEYS,\n defaultPolicy: TRACKING_DEFAULT_POLICY,\n readPage: (ctx, cursor, fieldIds, options) => readTrackingPage(ctx, cursor, fieldIds, options),\n lookup: (ctx, requests) => lookupTrackingOrders(ctx, requests),\n match: (_ctx, input) => ({ outcomes: matchTrackingRows(input.rows, input.lookup) }),\n plan: (ctx, input) => planTracking(ctx, input),\n apply: (ctx, chunk, writer) => applyTracking(ctx, chunk, writer),\n revert: (ctx, snapshot, decisions) => revertTracking(ctx, snapshot, decisions),\n}\n"],"names":["buildMatchLookup","Aglyn","firebaseAdmin","getOrgForHost","memberHasPermissionOnHost","resolveOrgMembership","TransferEngineError","normalizeTrackingNumber","parseShippingOrderRef","isUnpaidQuote","commerceSitePermissionRefusal","cancelOrderFulfillment","recordOrderShipment","updateFulfillmentTracking","NOTHING","ROW_BUDGET_MS","firestoreOf","hostRefOf","readerSeesHost","TRACKING_DEFAULT_POLICY","TRACKING_MATCH_KEYS","matchTrackingRows","planTrackingRows","trackingExportRows","trackingMatchValues","trackingRecord","IN_MAX","SHIPPED_STATUSES","shipperOf","ctx","hostId","uid","actorUid","membership","orgId","allowed","member","owner","catch","checkEntitlement","org","ordersOf","firestore","collection","findOrders","requests","found","Map","numbers","Set","ids","request","value","values","ref","fieldId","id","number","undefined","add","includes","test","numberList","at","length","snapshot","where","slice","get","doc","docs","set","idList","filter","has","getAll","map","exists","data","delete","lookupTrackingOrders","keys","normalizer","records","entries","push","lookup","readTrackingPage","cursor","fieldIds","options","Error","pageSize","Math","max","min","next","offset","Number","String","last","query","orderBy","FieldPath","documentId","after","JSON","parse","startAfter","limit","stringify","rows","flatMap","record","Object","fromEntries","planTracking","input","matches","match","kind","recordId","Boolean","orders","applyTracking","chunk","writer","results","undo","fail","row","message","result","outcome","reason","markApplied","earlier","alreadyApplied","index","timeLeftMs","decision","tracking","verdict","action","orderId","to","carrier","trackingNumber","trackingUrl","lineItems","idempotencyKey","onceByTracking","fulfillment","entry","previous","fulfillmentId","written","from","replace","revertTracking","decisions","done","conflicts","reverse","order","current","find","why","edited","fields","recorded","status","trackingTransfer","matchKeys","defaultPolicy","readPage","_ctx","outcomes","plan","apply","revert"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAWX,6BAA4B;AACnC,YAAYC,WAAW,sBAAqB;AAY5C,SAASC,a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