@aglyn/plugins-commerce 1.15.2 → 1.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +13 -13
- package/src/lib/components/cart.js +2 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +6 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +5 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
- package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
- package/src/lib/components/console/product-builder-fields.component.js +195 -0
- package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
- package/src/lib/components/console/product-editor-dialog.component.js +35 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-messages.component.d.ts +21 -0
- package/src/lib/components/console/quote-messages.component.js +185 -0
- package/src/lib/components/console/quote-messages.component.js.map +1 -0
- package/src/lib/components/console/quote-pay-link.component.js +1 -1
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.js +30 -3
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
- package/src/lib/components/console/quote-settings-card.component.js +154 -24
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/product-builder-context.d.ts +22 -0
- package/src/lib/components/product-builder-context.js +21 -0
- package/src/lib/components/product-builder-context.js.map +1 -0
- package/src/lib/components/product-builder-mockup.d.ts +42 -0
- package/src/lib/components/product-builder-mockup.js +120 -0
- package/src/lib/components/product-builder-mockup.js.map +1 -0
- package/src/lib/components/product-builder-sample.d.ts +63 -0
- package/src/lib/components/product-builder-sample.js +96 -0
- package/src/lib/components/product-builder-sample.js.map +1 -0
- package/src/lib/components/product-choice-cards.d.ts +51 -0
- package/src/lib/components/product-choice-cards.js +311 -0
- package/src/lib/components/product-choice-cards.js.map +1 -0
- package/src/lib/components/product-detail-panels.d.ts +42 -0
- package/src/lib/components/product-detail-panels.js +185 -0
- package/src/lib/components/product-detail-panels.js.map +1 -0
- package/src/lib/components/product-detail.d.ts +20 -12
- package/src/lib/components/product-detail.js +136 -221
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +7 -0
- package/src/lib/components/product-grid.js +11 -8
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-options-field-body.d.ts +9 -8
- package/src/lib/components/product-options-field-body.js +152 -3
- package/src/lib/components/product-options-field-body.js.map +1 -1
- package/src/lib/components/product-options-field.js +1 -1
- package/src/lib/components/product-options-field.js.map +1 -1
- package/src/lib/components/product-photo-fit.d.ts +49 -0
- package/src/lib/components/product-photo-fit.js +58 -0
- package/src/lib/components/product-photo-fit.js.map +1 -0
- package/src/lib/components/product-restock-notify.d.ts +12 -0
- package/src/lib/components/product-restock-notify.js +86 -0
- package/src/lib/components/product-restock-notify.js.map +1 -0
- package/src/lib/components/quote-messages-panel.d.ts +21 -0
- package/src/lib/components/quote-messages-panel.js +191 -0
- package/src/lib/components/quote-messages-panel.js.map +1 -0
- package/src/lib/components/quote-page-body.js +15 -1
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/quote-proof-panel.d.ts +6 -3
- package/src/lib/components/quote-proof-panel.js +139 -14
- package/src/lib/components/quote-proof-panel.js.map +1 -1
- package/src/lib/components/related-products.d.ts +7 -0
- package/src/lib/components/related-products.js +8 -6
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/constants/quote-page.d.ts +8 -0
- package/src/lib/constants/quote-page.js +11 -0
- package/src/lib/constants/quote-page.js.map +1 -1
- package/src/lib/model/commerce-cart.d.ts +6 -1
- package/src/lib/model/commerce-cart.js +5 -1
- package/src/lib/model/commerce-cart.js.map +1 -1
- package/src/lib/model/commerce-invoices.js +5 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-pos-ops.d.ts +3 -0
- package/src/lib/model/commerce-pos-ops.js +3 -0
- package/src/lib/model/commerce-pos-ops.js.map +1 -1
- package/src/lib/model/commerce-pos.d.ts +8 -0
- package/src/lib/model/commerce-pos.js.map +1 -1
- package/src/lib/model/commerce-quote-messages.d.ts +106 -0
- package/src/lib/model/commerce-quote-messages.js +146 -0
- package/src/lib/model/commerce-quote-messages.js.map +1 -0
- package/src/lib/model/commerce-quote-pay.d.ts +31 -2
- package/src/lib/model/commerce-quote-pay.js +31 -7
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
- package/src/lib/model/commerce-quote-proofs.js +73 -18
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +14 -4
- package/src/lib/model/commerce-quote-request.js +25 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +56 -3
- package/src/lib/model/commerce-quotes.js +47 -2
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce.d.ts +12 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/pos-cellular.d.ts +5 -0
- package/src/lib/model/pos-cellular.js.map +1 -1
- package/src/lib/model/product-card-rules.d.ts +41 -0
- package/src/lib/model/product-card-rules.js +90 -0
- package/src/lib/model/product-card-rules.js.map +1 -0
- package/src/lib/model/product-modifiers.d.ts +11 -0
- package/src/lib/model/product-modifiers.js +10 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/server/billing-webhook.js +6 -2
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +15 -0
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/channel-order-updates.js +15 -1
- package/src/lib/server/channel-order-updates.js.map +1 -1
- package/src/lib/server/channel-orders.js +20 -0
- package/src/lib/server/channel-orders.js.map +1 -1
- package/src/lib/server/checkout.js +1 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/local-fulfillment.js +1 -1
- package/src/lib/server/local-fulfillment.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.d.ts +1 -1
- package/src/lib/server/pos-cellular-billing.js +2 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular.d.ts +3 -1
- package/src/lib/server/pos-cellular.js +15 -8
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +3 -3
- package/src/lib/server/pos-offline-sync.js +17 -4
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-order.js +17 -6
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-payment.js +27 -11
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-reader-splash.js +10 -5
- package/src/lib/server/pos-reader-splash.js.map +1 -1
- package/src/lib/server/pos-readers.js +34 -10
- package/src/lib/server/pos-readers.js.map +1 -1
- package/src/lib/server/pos-return.js +19 -3
- package/src/lib/server/pos-return.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +14 -0
- package/src/lib/server/pos-stripe.js +6 -2
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal-connection-token.js +23 -9
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +80 -14
- package/src/lib/server/pos-terminal.js +393 -123
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/product-drafts.d.ts +1 -1
- package/src/lib/server/product-drafts.js +4 -3
- package/src/lib/server/product-drafts.js.map +1 -1
- package/src/lib/server/product-writer.js +5 -4
- package/src/lib/server/product-writer.js.map +1 -1
- package/src/lib/server/product.d.ts +11 -0
- package/src/lib/server/product.js +18 -3
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +4 -3
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server/quote-email.d.ts +26 -0
- package/src/lib/server/quote-email.js +73 -7
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-messages.d.ts +72 -0
- package/src/lib/server/quote-messages.js +356 -0
- package/src/lib/server/quote-messages.js.map +1 -0
- package/src/lib/server/quote-pay.d.ts +42 -0
- package/src/lib/server/quote-pay.js +81 -4
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.d.ts +1 -1
- package/src/lib/server/quote-proofs.js +63 -19
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote.d.ts +12 -0
- package/src/lib/server/quote.js +44 -14
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +3 -1
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/reserve-stock.js +9 -0
- package/src/lib/server/reserve-stock.js.map +1 -1
- package/src/lib/server/returns.js +15 -1
- package/src/lib/server/returns.js.map +1 -1
- package/src/lib/server/reviews.js +15 -0
- package/src/lib/server/reviews.js.map +1 -1
- package/src/lib/server/sold-out-drop.d.ts +58 -0
- package/src/lib/server/sold-out-drop.js +81 -0
- package/src/lib/server/sold-out-drop.js.map +1 -0
- package/src/lib/server/stock-levels.js +9 -0
- package/src/lib/server/stock-levels.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +7 -0
- package/src/lib/server/stripe-refund.js +26 -7
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server.js +2 -0
- package/src/lib/server.js.map +1 -1
- package/src/lib/tenant-emails.js +85 -2
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
- package/src/lib/testing/fake-seller-payment-account.js +40 -0
- package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
- package/src/lib/transfer/product-transfer.js +6 -5
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +4 -3
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +6 -0
- package/src/lib/utils/quote-email-content.js +6 -3
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/local-fulfillment.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 { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { normalizePhone } from '@aglyn/aglyn/foundation/definitions/contact.types'\nimport { pluginSmsMessaging } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport { pluginShippingRateQuoter } from '@aglyn/aglyn/plugin-manager/plugin-shipping-rates'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport * as CommerceModel from '../model'\nimport { readCartId } from './cart-cookie'\n\n/**\n * Buy online, pick up in store, and local delivery at checkout (AGL-3624).\n *\n * The buyer chooses at the CART, before payment — the only place the store\n * still controls what is offered: a Stripe Checkout Session prices shipping\n * from the options it is created with and asks nothing back. So the cart\n * declares one of three ways, and this module turns the declaration into the\n * session it needs, or refuses it in words the cart can show:\n *\n * - `pickup` at one location: no shipping charged, no address collected,\n * the stock reserved at that location, and the order routed there.\n * - `local_delivery`: the store's OWN driver (not a marketplace courier —\n * that is the delivery-apps plugin, which never reads this). The postal\n * code — or, for a distance zone, the address — picks a zone, the zone\n * prices the fee and enforces its minimum, and the buyer books a window.\n * The session carries the fee as its one shipping option and collects an\n * address only in the store's country.\n * - `shipping`: everything as it was.\n *\n * A DECLARATION IS A REQUEST, NEVER A PRICE. The cart sends a location id, a\n * postal code and a window; the fee, the minimum and whether the window is\n * still open are all decided here from the store's own settings, on every\n * attempt.\n *\n * DISTANCE ZONES need both ends on a map, and the repository has no geocoder\n * of its own: the destination is placed by the shipping plugin's address\n * check (core's `core.shipping-rate-quoter` seam) when its provider returns a\n * position. Where none does, a distance zone matches nothing and the buyer is\n * told the store does not deliver there; postal-code zones need nothing.\n */\n\n/** What the cart declares. */\nexport interface LocalFulfillmentRequest {\n method: CommerceModel.OrderFulfillmentMethod\n locationId?: string\n postalCode?: string\n windowStartMs?: number\n /** The street address, asked only when the store has distance zones. */\n address?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string }\n /**\n * The mobile number the buyer gave AT THE CART for texts about this pickup\n * or delivery (AGL-3624), in E.164. The only phone an online order's texts\n * go to: asked for that purpose, never taken from an address.\n */\n textPhone?: string\n}\n\n/** Reads the cart's declaration; `null` when it made none (a shipped order). */\nexport function readLocalFulfillmentRequest(value: unknown): LocalFulfillmentRequest | null {\n if (!value || typeof value !== 'object') return null\n const raw = value as Record<string, unknown>\n const method = raw['method']\n if (method !== 'pickup' && method !== 'local_delivery') return null\n const text = (input: unknown, max: number) => String(input ?? '').trim().slice(0, max)\n const request: LocalFulfillmentRequest = { method }\n const phone = normalizePhone(text(raw['textPhone'], 32))\n if (phone) request.textPhone = phone\n if (method === 'pickup') {\n request.locationId = text(raw['locationId'], 120)\n return request\n }\n const postalCode = text(raw['postalCode'], 16)\n if (postalCode) request.postalCode = postalCode\n const start = Math.round(Number(raw['windowStartMs']))\n if (Number.isFinite(start) && start > 0) request.windowStartMs = start\n const address = raw['address']\n if (address && typeof address === 'object') {\n const parts = address as Record<string, unknown>\n request.address = {\n line1: text(parts['line1'], 120),\n line2: text(parts['line2'], 120),\n city: text(parts['city'], 80),\n state: text(parts['state'], 40),\n postalCode: text(parts['postalCode'], 16) || postalCode,\n }\n }\n return request\n}\n\n/** The store's pickup locations and delivery settings, read once per attempt. */\nexport interface LocalFulfillmentStore {\n pickupLocations: CommerceModel.PickupLocationOption[]\n delivery: CommerceModel.LocalDeliverySettings\n timeZone: string\n}\n\n/** Reads what checkout and the cart need. Never throws: a failed read offers nothing. */\nexport async function readLocalFulfillmentStore(input: {\n hostRef: any\n /** `settings/store` as already read, to save a read. */\n storeSettings?: Record<string, unknown> | null\n org?: { timeZone?: string } | null\n host?: { timeZone?: string } | null\n}): Promise<LocalFulfillmentStore> {\n const { hostRef } = input\n const [locationsSnapshot, settings, host] = await Promise.all([\n hostRef\n .collection('locations')\n .limit(CommerceModel.PICKUP_LOCATIONS_MAX)\n .get()\n .catch(() => null),\n input.storeSettings !== undefined\n ? Promise.resolve(input.storeSettings)\n : hostRef\n .collection('settings')\n .doc('store')\n .get()\n .then((snapshot: any) => (snapshot?.data?.() ?? null) as Record<string, unknown> | null)\n .catch(() => null),\n input.host !== undefined\n ? Promise.resolve(input.host)\n : hostRef\n .get()\n .then((snapshot: any) => (snapshot?.data?.() ?? null) as { timeZone?: string } | null)\n .catch(() => null),\n ])\n const locations = (locationsSnapshot?.docs ?? []).map((snapshot: any) => ({\n ...(snapshot.data() as CommerceModel.InventoryLocation),\n id: String(snapshot.id),\n }))\n return {\n pickupLocations: CommerceModel.pickupLocationOptions(locations),\n delivery: CommerceModel.normalizeLocalDeliverySettings(settings?.['localDelivery']),\n timeZone: resolveSiteTimeZone(input.org ?? null, host ?? null),\n }\n}\n\n/** How long checkout waits for an address to be placed on a map. */\nexport const LOCAL_DELIVERY_GEOCODE_TIMEOUT_MS = 3_000\n\n/**\n * Places an address on the map through the shipping plugin's address check,\n * or answers `null`: no plugin, not available on this site, no position in\n * the answer, or slower than the timeout. Never throws.\n */\nexport async function placeDeliveryAddress(\n hostId: string,\n address: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country: string },\n): Promise<CommerceModel.LocalDeliveryCoordinates | null> {\n if (!address.line1 || !address.postalCode) return null\n const quoter = pluginShippingRateQuoter()\n if (!quoter?.validateAddress) return null\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const placed = await Promise.race([\n (async () => {\n if (!(await quoter.available(hostId))) return null\n const check = await quoter.validateAddress?.(hostId, {\n line1: address.line1,\n ...(address.line2 ? { line2: address.line2 } : {}),\n ...(address.city ? { city: address.city } : {}),\n ...(address.state ? { state: address.state } : {}),\n postalCode: address.postalCode,\n country: address.country,\n } as never)\n return check?.verdict === 'invalid' ? null : (check?.coordinates ?? null)\n })().catch(() => null),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), LOCAL_DELIVERY_GEOCODE_TIMEOUT_MS)\n }),\n ])\n return placed ?? null\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\n/** The shipping option id a local delivery fee is declared under. */\nexport const LOCAL_DELIVERY_RATE_ID = 'local-delivery'\n\nexport type LocalFulfillmentPlan =\n | { kind: 'shipping' }\n | {\n kind: 'refusal'\n status: 400 | 409\n error: string\n /** What the cart should re-ask: the options changed under the buyer. */\n changed?: 'pickup' | 'delivery'\n }\n | {\n kind: 'pickup'\n location: CommerceModel.PickupLocationOption\n metadata: Record<string, string>\n }\n | {\n kind: 'local_delivery'\n zone: CommerceModel.LocalDeliveryZone\n window: CommerceModel.LocalDeliveryWindow\n feeCents: number\n country: string\n locationId?: string\n option: CommerceModel.ResolvedShippingRate\n metadata: Record<string, string>\n }\n\nconst money = (cents: number) => CommerceModel.formatOrderMoney(cents, 'USD')\n\n/**\n * Turns the cart's declaration into what the session needs, or a refusal.\n * Taken BEFORE any reservation or Stripe call, so a refusal costs nothing\n * and the buyer's same button works once they choose again.\n */\nexport async function planLocalFulfillment(input: {\n hostId: string\n request: LocalFulfillmentRequest | null\n /** The goods, pre-discount — what a minimum and a free-over threshold read. */\n itemsCents: number\n hasPhysicalLine: boolean\n store: LocalFulfillmentStore\n nowMs?: number\n}): Promise<LocalFulfillmentPlan> {\n const { request, store } = input\n // A cart of downloads is not collected or driven anywhere.\n if (!request || request.method === 'shipping' || !input.hasPhysicalLine) return { kind: 'shipping' }\n const nowMs = input.nowMs ?? Date.now()\n\n if (request.method === 'pickup') {\n const location = store.pickupLocations.find((entry) => entry.id === request.locationId)\n if (!location) {\n return {\n kind: 'refusal',\n status: 409,\n error: 'That pickup location is no longer available. Choose another.',\n changed: 'pickup',\n }\n }\n return {\n kind: 'pickup',\n location,\n metadata: {\n fulfillment: 'pickup',\n pickupLocationId: location.id,\n ...(request.textPhone ? { orderTextPhone: request.textPhone } : {}),\n },\n }\n }\n\n const delivery = store.delivery\n if (!CommerceModel.localDeliveryOffered(delivery)) {\n return {\n kind: 'refusal',\n status: 409,\n error: 'Local delivery is not available right now. Choose shipping or pickup.',\n changed: 'delivery',\n }\n }\n const country = String(delivery.country)\n const postalCode = CommerceModel.normalizePostcode(\n request.postalCode ?? request.address?.postalCode,\n country,\n )\n if (!postalCode) {\n return { kind: 'refusal', status: 400, error: 'Enter your postal code for delivery.' }\n }\n let zone = CommerceModel.matchLocalDeliveryZone(delivery, { country, postalCode })\n if (!zone && CommerceModel.localDeliveryHasRadiusZones(delivery)) {\n if (!request.address?.line1) {\n return { kind: 'refusal', status: 400, error: 'Enter your street address for delivery.' }\n }\n const coordinates = await placeDeliveryAddress(input.hostId, {\n ...request.address,\n postalCode,\n country,\n })\n zone = CommerceModel.matchLocalDeliveryZone(delivery, { country, postalCode, coordinates })\n }\n if (!zone) {\n return {\n kind: 'refusal',\n status: 409,\n error: `We don’t deliver to ${postalCode}. Choose shipping or pickup instead.`,\n }\n }\n const shortfall = CommerceModel.localDeliveryMinimumShortfall(zone, input.itemsCents)\n if (shortfall > 0) {\n return {\n kind: 'refusal',\n status: 409,\n error:\n `Delivery to ${postalCode} needs an order of at least ${money(zone.minimumCents ?? 0)}. ` +\n `Add ${money(shortfall)} more, or choose shipping or pickup.`,\n }\n }\n const window = CommerceModel.findLocalDeliveryWindow(delivery, request.windowStartMs, {\n nowMs,\n timeZone: store.timeZone,\n })\n if (!window) {\n return {\n kind: 'refusal',\n status: 409,\n error: 'That delivery time is no longer available. Choose another.',\n changed: 'delivery',\n }\n }\n const feeCents = CommerceModel.localDeliveryFeeCents(zone, input.itemsCents)\n const label = CommerceModel.formatLocalDeliveryWindow(window, store.timeZone)\n return {\n kind: 'local_delivery',\n zone,\n window,\n feeCents,\n country,\n ...(delivery.locationId ? { locationId: delivery.locationId } : {}),\n option: {\n rateId: LOCAL_DELIVERY_RATE_ID,\n name: `Local delivery — ${label}`.slice(0, 100),\n amountCents: feeCents,\n },\n metadata: {\n fulfillment: 'local_delivery',\n deliveryZoneId: zone.id,\n deliveryWindowStartMs: String(window.startMs),\n deliveryWindowEndMs: String(window.endMs),\n deliveryPostalCode: postalCode,\n deliveryFeeCents: String(feeCents),\n ...(delivery.locationId ? { deliveryLocationId: delivery.locationId } : {}),\n ...(request.textPhone ? { orderTextPhone: request.textPhone } : {}),\n },\n }\n}\n\n/** Sets a plan's metadata on a session's form body. */\nexport function appendLocalFulfillmentMetadata(params: URLSearchParams, metadata: Record<string, string>): void {\n for (const [key, value] of Object.entries(metadata)) {\n params.set(`metadata[${key}]`, String(value).slice(0, 480))\n }\n}\n\n/** The location a plan takes its stock from, if any. */\nexport function localFulfillmentLocationId(plan: LocalFulfillmentPlan): string | undefined {\n if (plan.kind === 'pickup') return plan.location.id\n if (plan.kind === 'local_delivery') return plan.locationId\n return undefined\n}\n\n/** A stock refusal for a plan that reserves at one location (AGL-3624). */\nexport function localStockRefusalMessage(plan: LocalFulfillmentPlan, productName: string): string {\n const what = productName ? `\"${productName}\"` : 'An item in your cart'\n if (plan.kind === 'pickup') {\n return `${what} is not in stock at ${plan.location.name}. Choose another location, or have it shipped.`\n }\n return `${what} is not in stock for local delivery. Choose pickup at another location, or have it shipped.`\n}\n\n// ---------------------------------------------------------------------------\n// The order, as the webhook records it\n// ---------------------------------------------------------------------------\n\n/** What a paid session's declaration becomes on its order. */\nexport interface OrderLocalFulfillment {\n fields: {\n fulfillmentMethod: CommerceModel.OrderFulfillmentMethod\n pickup?: CommerceModel.OrderPickup\n localDelivery?: CommerceModel.OrderLocalDelivery\n locationId?: string\n /** The number the buyer asked to be texted at, at the cart. */\n customerPhone?: string\n } & CommerceModel.OrderLocalFulfillmentListFields\n /** The line the receipt adds, so the buyer knows where and when. */\n summary: string\n /** The address entered at payment is outside the zone the fee was charged for. */\n outsideZone: boolean\n}\n\n/**\n * Reads a paid session's `fulfillment` metadata into order fields, or `null`\n * for a shipped order. The location and zone are re-read so the order keeps\n * their names as they were when the buyer paid.\n */\nexport async function orderLocalFulfillmentFromSession(input: {\n hostId: string\n hostRef: any\n metadata: Record<string, unknown> | null | undefined\n /** The address the buyer entered at payment, when the session collected one. */\n shippingAddress?: { postalCode?: string | null; country?: string | null } | null\n createdAtMs: number\n}): Promise<OrderLocalFulfillment | null> {\n const metadata = input.metadata ?? {}\n const method = metadata['fulfillment']\n if (method !== 'pickup' && method !== 'local_delivery') return null\n const textPhone = normalizePhone(String(metadata['orderTextPhone'] ?? ''))\n const phone = textPhone ? { customerPhone: textPhone } : {}\n const org = await getOrgForHost(input.hostId).catch(() => null)\n const store = await readLocalFulfillmentStore({\n hostRef: input.hostRef,\n org: (org?.org ?? null) as { timeZone?: string } | null,\n })\n\n if (method === 'pickup') {\n const locationId = String(metadata['pickupLocationId'] ?? '')\n let location = store.pickupLocations.find((entry) => entry.id === locationId)\n // A location renamed or switched off after the buyer paid: the order\n // still goes there, under the name the location doc now has.\n if (!location && locationId) {\n const snapshot = await input.hostRef\n .collection('locations')\n .doc(locationId)\n .get()\n .catch(() => null)\n const data = (snapshot?.exists ? snapshot.data() : null) as CommerceModel.InventoryLocation | null\n location = {\n id: locationId,\n name: String(data?.name || 'the store'),\n ...(data\n ? { address: CommerceModel.formatPostalAddressLine(data.postalAddress, data.address) || undefined }\n : {}),\n }\n }\n if (!location) return null\n const pickup: CommerceModel.OrderPickup = {\n locationId: location.id,\n locationName: location.name,\n ...(location.address ? { address: location.address } : {}),\n ...(location.instructions ? { instructions: location.instructions } : {}),\n ...(location.hours ? { hours: location.hours } : {}),\n status: 'preparing',\n updatedAtMs: input.createdAtMs,\n }\n const order = { fulfillmentMethod: 'pickup' as const, pickup, createdAtMs: input.createdAtMs }\n const list = CommerceModel.orderLocalFulfillmentListFields(order) as CommerceModel.OrderLocalFulfillmentListFields\n const ready = CommerceModel.pickupReadyWithinLabel(location.readyWithinMinutes)\n return {\n fields: { fulfillmentMethod: 'pickup', pickup, locationId: location.id, ...phone, ...list },\n summary: [\n `Pickup at ${location.name}${location.address ? `, ${location.address}` : ''}.`,\n `We’ll let you know when it’s ready${ready ? ` (${ready.toLowerCase()})` : ''}.`,\n location.instructions ?? '',\n ]\n .filter(Boolean)\n .join(' '),\n outsideZone: false,\n }\n }\n\n const zoneId = String(metadata['deliveryZoneId'] ?? '')\n const zone = (store.delivery.zones ?? []).find((entry) => entry.id === zoneId)\n const windowStartMs = Number(metadata['deliveryWindowStartMs']) || 0\n const windowEndMs = Number(metadata['deliveryWindowEndMs']) || windowStartMs\n const declared = String(metadata['deliveryPostalCode'] ?? '')\n const country = store.delivery.country ?? String(input.shippingAddress?.country ?? '')\n const entered = CommerceModel.normalizePostcode(input.shippingAddress?.postalCode, country)\n // The fee was charged for the code the buyer declared. The address they\n // then typed at payment must be in a zone too — a zone of ANY fee, since\n // the store delivers there — or the store is told.\n const outsideZone = Boolean(\n entered &&\n entered !== declared &&\n !CommerceModel.matchLocalDeliveryZone(store.delivery, { country, postalCode: entered }),\n )\n const windowLabel = windowStartMs\n ? CommerceModel.formatLocalDeliveryWindow({ startMs: windowStartMs, endMs: windowEndMs }, store.timeZone)\n : ''\n const locationId = String(metadata['deliveryLocationId'] ?? '') || undefined\n const localDelivery: CommerceModel.OrderLocalDelivery = {\n zoneId,\n zoneName: zone?.name ?? 'Local delivery',\n feeCents: Math.max(0, Math.round(Number(metadata['deliveryFeeCents']) || 0)),\n windowStartMs,\n windowEndMs,\n ...(windowLabel ? { windowLabel } : {}),\n ...(declared ? { postalCode: declared } : {}),\n ...(locationId ? { locationId } : {}),\n status: 'scheduled',\n ...(outsideZone ? { addressOutsideZone: true } : {}),\n updatedAtMs: input.createdAtMs,\n }\n const order = { fulfillmentMethod: 'local_delivery' as const, localDelivery, createdAtMs: input.createdAtMs }\n const list = CommerceModel.orderLocalFulfillmentListFields(order) as CommerceModel.OrderLocalFulfillmentListFields\n return {\n fields: {\n fulfillmentMethod: 'local_delivery',\n localDelivery,\n ...(locationId ? { locationId } : {}),\n ...phone,\n ...list,\n },\n summary: [\n `Local delivery${windowLabel ? `: ${windowLabel}` : ''}.`,\n store.delivery.instructions ?? '',\n ]\n .filter(Boolean)\n .join(' '),\n outsideZone,\n }\n}\n\n// ---------------------------------------------------------------------------\n// The cart's question: what can this basket be?\n// ---------------------------------------------------------------------------\n\n/** Distance zones place an address through a provider: a visitor may ask this often. */\nconst PLACE_LIMIT = { limit: 20, windowMs: 60 * 60 * 1000 }\n\n/**\n * `POST commerce/local-fulfillment-options` (AGL-3624): what the cart offers\n * besides shipping — the pickup locations and, with a postal code, the\n * delivery zone's fee, minimum and the windows open to book.\n *\n * Public, because a shopper asks it; it returns only what a storefront would\n * print anyway (location names, addresses, hours, fees). It reads the\n * visitor's own cart through the cart cookie and offers nothing for a\n * basket with nothing physical in it.\n */\nexport const localFulfillmentOptionsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST' && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n let body: Record<string, any>\n try {\n body =\n req.method === 'POST'\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : ((req.query ?? {}) as Record<string, any>)\n } catch {\n return res.status(400).json({ error: 'Invalid request' })\n }\n const hostId = String(body.hostId ?? '')\n if (!isDocumentId(hostId)) return res.status(400).json({ error: 'Missing or invalid hostId' })\n const nothing = { pickup: [], delivery: null }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const ownerOrg = await getOrgForHost(hostId).catch(() => null)\n if (!ownerOrg?.org || !Aglyn.checkEntitlement(ownerOrg.org as any, 'commerce')) {\n return res.status(200).json(nothing)\n }\n // The visitor's own basket decides whether there is anything to collect\n // — or, from a product's Buy button, that one product (AGL-3624).\n const buyNowProductId = typeof body.productId === 'string' ? body.productId : ''\n let cart: Pick<CommerceModel.HostCart, 'lines'>\n if (buyNowProductId) {\n if (!isDocumentId(buyNowProductId)) return res.status(400).json({ error: 'Invalid productId' })\n cart = {\n lines: [\n {\n productId: buyNowProductId,\n ...(typeof body.variantId === 'string' && body.variantId ? { variantId: body.variantId } : {}),\n // The add-ons chosen on the page (AGL-4100), priced below.\n ...(Array.isArray(body.modifiers)\n ? { modifiers: CommerceModel.modifierSelectionFrom(body.modifiers) }\n : {}),\n quantity: Math.min(99, Math.max(1, Math.round(Number(body.quantity) || 1))),\n },\n ],\n }\n } else {\n const cartId = readCartId(req.cookies, hostId)\n const cartSnapshot = cartId ? await hostRef.collection('carts').doc(cartId).get().catch(() => null) : null\n cart = (cartSnapshot?.data?.() as CommerceModel.HostCart | undefined) ?? { lines: [] }\n }\n const productIds = [...new Set((cart.lines ?? []).map((line) => line.productId))].slice(0, 50)\n const products = await Promise.all(\n productIds.map((id) =>\n hostRef\n .collection('products')\n .doc(id)\n .get()\n .catch(() => null),\n ),\n )\n let itemsCents = 0\n let hasPhysicalLine = false\n for (const line of cart.lines ?? []) {\n const snapshot = products[productIds.indexOf(line.productId)]\n if (!snapshot?.exists) continue\n const product = CommerceModel.liftLegacyProduct(snapshot.data() as any)\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // With its add-ons (AGL-4100), as checkout prices the line.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant?.id)\n itemsCents +=\n (Math.round(Number(variant?.priceUsd ?? 0) * 100) + (chosen.ok ? chosen.extraCents : 0)) *\n (Number(line.quantity) || 0)\n if ((product.type ?? 'physical') === 'physical') hasPhysicalLine = true\n }\n if (!hasPhysicalLine) return res.status(200).json(nothing)\n\n const store = await readLocalFulfillmentStore({\n hostRef,\n org: ownerOrg.org as { timeZone?: string },\n })\n const nowMs = Date.now()\n let delivery: Record<string, unknown> | null = null\n if (CommerceModel.localDeliveryOffered(store.delivery)) {\n const settings = store.delivery\n const country = String(settings.country)\n const windows = CommerceModel.upcomingLocalDeliveryWindows(settings, { nowMs, timeZone: store.timeZone }).map(\n (window) => ({\n ...window,\n label: CommerceModel.formatLocalDeliveryWindow(window, store.timeZone),\n }),\n )\n const radius = CommerceModel.localDeliveryHasRadiusZones(settings)\n delivery = {\n country,\n ...(settings.instructions ? { instructions: settings.instructions } : {}),\n needsAddress: radius,\n windows,\n }\n const request = readLocalFulfillmentRequest({\n method: 'local_delivery',\n postalCode: body.postalCode,\n address: body.address,\n })\n const postalCode = CommerceModel.normalizePostcode(request?.postalCode ?? request?.address?.postalCode, country)\n if (postalCode) {\n let zone = CommerceModel.matchLocalDeliveryZone(settings, { country, postalCode })\n if (!zone && radius && request?.address?.line1) {\n const visitor = String(req.socket?.remoteAddress ?? '') || 'no-address'\n const allowed = await consumeRateLimit(`local-delivery:place:${hostId}:${visitor}`, PLACE_LIMIT)\n .then((result) => result.allowed)\n .catch(() => false)\n const coordinates = allowed\n ? await placeDeliveryAddress(hostId, { ...request.address, postalCode, country })\n : null\n zone = CommerceModel.matchLocalDeliveryZone(settings, { country, postalCode, coordinates })\n }\n delivery['quote'] = zone\n ? {\n zoneId: zone.id,\n zoneName: zone.name,\n feeCents: CommerceModel.localDeliveryFeeCents(zone, itemsCents),\n ...(zone.minimumCents ? { minimumCents: zone.minimumCents } : {}),\n ...(zone.freeOverCents ? { freeOverCents: zone.freeOverCents } : {}),\n shortfallCents: CommerceModel.localDeliveryMinimumShortfall(zone, itemsCents),\n }\n : { unavailable: `We don’t deliver to ${postalCode}.` }\n }\n }\n // Whether the cart may offer texts about the pickup or delivery: the\n // platform can send them and the store has not turned them off.\n const toggles = (await hostRef\n .collection('settings')\n .doc('store')\n .get()\n .then((snapshot: any) => snapshot?.get?.('buyerNotifications'))\n .catch(() => null)) as unknown\n const texts = Boolean(\n pluginSmsMessaging()?.isConfigured() && CommerceModel.buyerNotificationEnabled(toggles, 'texts'),\n )\n return res.status(200).json({ pickup: store.pickupLocations, delivery, texts })\n } catch (error) {\n console.error('[local-fulfillment] options failed', hostId, error)\n return res.status(200).json(nothing)\n }\n}\n"],"names":["resolveSiteTimeZone","normalizePhone","pluginSmsMessaging","pluginShippingRateQuoter","Aglyn","consumeRateLimit","firebaseAdmin","getOrgForHost","isDocumentId","CommerceModel","readCartId","readLocalFulfillmentRequest","value","raw","method","text","input","max","String","trim","slice","request","phone","textPhone","locationId","postalCode","start","Math","round","Number","isFinite","windowStartMs","address","parts","line1","line2","city","state","readLocalFulfillmentStore","hostRef","locationsSnapshot","settings","host","Promise","all","collection","limit","PICKUP_LOCATIONS_MAX","get","catch","storeSettings","undefined","resolve","doc","then","snapshot","data","locations","docs","map","id","pickupLocations","pickupLocationOptions","delivery","normalizeLocalDeliverySettings","timeZone","org","LOCAL_DELIVERY_GEOCODE_TIMEOUT_MS","placeDeliveryAddress","hostId","quoter","validateAddress","timer","placed","race","available","check","country","verdict","coordinates","setTimeout","clearTimeout","LOCAL_DELIVERY_RATE_ID","money","cents","formatOrderMoney","planLocalFulfillment","store","hasPhysicalLine","kind","nowMs","Date","now","location","find","entry","status","error","changed","metadata","fulfillment","pickupLocationId","orderTextPhone","localDeliveryOffered","normalizePostcode","zone","matchLocalDeliveryZone","localDeliveryHasRadiusZones","shortfall","localDeliveryMinimumShortfall","itemsCents","minimumCents","window","findLocalDeliveryWindow","feeCents","localDeliveryFeeCents","label","formatLocalDeliveryWindow","option","rateId","name","amountCents","deliveryZoneId","deliveryWindowStartMs","startMs","deliveryWindowEndMs","endMs","deliveryPostalCode","deliveryFeeCents","deliveryLocationId","appendLocalFulfillmentMetadata","params","key","Object","entries","set","localFulfillmentLocationId","plan","localStockRefusalMessage","productName","what","orderLocalFulfillmentFromSession","customerPhone","exists","formatPostalAddressLine","postalAddress","pickup","locationName","instructions","hours","updatedAtMs","createdAtMs","order","fulfillmentMethod","list","orderLocalFulfillmentListFields","ready","pickupReadyWithinLabel","readyWithinMinutes","fields","summary","toLowerCase","filter","Boolean","join","outsideZone","zoneId","zones","windowEndMs","declared","shippingAddress","entered","windowLabel","localDelivery","zoneName","addressOutsideZone","PLACE_LIMIT","windowMs","localFulfillmentOptionsHandler","req","res","body","json","JSON","parse","query","nothing","cart","firestore","app","ownerOrg","checkEntitlement","buyNowProductId","productId","lines","variantId","Array","isArray","modifiers","modifierSelectionFrom","quantity","min","cartSnapshot","cartId","cookies","productIds","Set","line","products","product","indexOf","liftLegacyProduct","variant","variants","item","chosen","resolveWebsiteLineModifiers","priceUsd","ok","extraCents","type","windows","upcomingLocalDeliveryWindows","radius","needsAddress","visitor","socket","remoteAddress","allowed","result","freeOverCents","shortfallCents","unavailable","toggles","texts","isConfigured","buyerNot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C3F;gBACAhB,QAAQ,CAAC,QAAQ,GAAG0C,OAChB;oBACE6D,QAAQ7D,KAAK7C,EAAE;oBACfkH,UAAUrE,KAAKe,IAAI;oBACnBN,UAAUzG,cAAc0G,qBAAqB,CAACV,MAAMK;mBAChDL,KAAKM,YAAY,GAAG;oBAAEA,cAAcN,KAAKM,YAAY;gBAAC,IAAI,CAAC,GAC3DN,KAAK6H,aAAa,GAAG;oBAAEA,eAAe7H,KAAK6H,aAAa;gBAAC,IAAI,CAAC;oBAClEC,gBAAgB9N,cAAcoG,6BAA6B,CAACJ,MAAMK;qBAEpE;oBAAE0H,aAAa,CAAC,oBAAoB,EAAE/M,WAAW,CAAC,CAAC;gBAAC;YAC1D;QACF;QACA,qEAAqE;QACrE,gEAAgE;QAChE,MAAMgN,UAAW,MAAMlM,QACpBM,UAAU,CAAC,YACXQ,GAAG,CAAC,SACJL,GAAG,GACHM,IAAI,CAAC,CAACC;gBAAkBA;mBAAAA,6BAAAA,gBAAAA,SAAUP,GAAG,qBAAbO,mBAAAA,UAAgB;WACxCN,KAAK,CAAC,IAAM;QACf,MAAMyL,QAAQvE,QACZjK,EAAAA,sBAAAA,yCAAAA,oBAAsByO,YAAY,OAAMlO,cAAcmO,wBAAwB,CAACH,SAAS;QAE1F,OAAOrD,IAAIpF,MAAM,CAAC,KAAKsF,IAAI,CAAC;YAAEpC,QAAQ3D,MAAM1B,eAAe;YAAEE;YAAU2K;QAAM;IAC/E,EAAE,OAAOzI,OAAO;QACd4I,QAAQ5I,KAAK,CAAC,sCAAsC5B,QAAQ4B;QAC5D,OAAOmF,IAAIpF,MAAM,CAAC,KAAKsF,IAAI,CAACI;IAC9B;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/local-fulfillment.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 { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { normalizePhone } from '@aglyn/aglyn/foundation/definitions/contact.types'\nimport { pluginSmsMessaging } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport { pluginShippingRateQuoter } from '@aglyn/aglyn/plugin-manager/plugin-shipping-rates'\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport { consumeRateLimit, firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { isDocumentId } from '@aglyn/tenant-data-admin/server/document-id'\nimport * as CommerceModel from '../model'\nimport { readCartId } from './cart-cookie'\n\n/**\n * Buy online, pick up in store, and local delivery at checkout (AGL-3624).\n *\n * The buyer chooses at the CART, before payment — the only place the store\n * still controls what is offered: a Stripe Checkout Session prices shipping\n * from the options it is created with and asks nothing back. So the cart\n * declares one of three ways, and this module turns the declaration into the\n * session it needs, or refuses it in words the cart can show:\n *\n * - `pickup` at one location: no shipping charged, no address collected,\n * the stock reserved at that location, and the order routed there.\n * - `local_delivery`: the store's OWN driver (not a marketplace courier —\n * that is the delivery-apps plugin, which never reads this). The postal\n * code — or, for a distance zone, the address — picks a zone, the zone\n * prices the fee and enforces its minimum, and the buyer books a window.\n * The session carries the fee as its one shipping option and collects an\n * address only in the store's country.\n * - `shipping`: everything as it was.\n *\n * A DECLARATION IS A REQUEST, NEVER A PRICE. The cart sends a location id, a\n * postal code and a window; the fee, the minimum and whether the window is\n * still open are all decided here from the store's own settings, on every\n * attempt.\n *\n * DISTANCE ZONES need both ends on a map, and the repository has no geocoder\n * of its own: the destination is placed by the shipping plugin's address\n * check (core's `core.shipping-rate-quoter` seam) when its provider returns a\n * position. Where none does, a distance zone matches nothing and the buyer is\n * told the store does not deliver there; postal-code zones need nothing.\n */\n\n/** What the cart declares. */\nexport interface LocalFulfillmentRequest {\n method: CommerceModel.OrderFulfillmentMethod\n locationId?: string\n postalCode?: string\n windowStartMs?: number\n /** The street address, asked only when the store has distance zones. */\n address?: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string }\n /**\n * The mobile number the buyer gave AT THE CART for texts about this pickup\n * or delivery (AGL-3624), in E.164. The only phone an online order's texts\n * go to: asked for that purpose, never taken from an address.\n */\n textPhone?: string\n}\n\n/** Reads the cart's declaration; `null` when it made none (a shipped order). */\nexport function readLocalFulfillmentRequest(value: unknown): LocalFulfillmentRequest | null {\n if (!value || typeof value !== 'object') return null\n const raw = value as Record<string, unknown>\n const method = raw['method']\n if (method !== 'pickup' && method !== 'local_delivery') return null\n const text = (input: unknown, max: number) => String(input ?? '').trim().slice(0, max)\n const request: LocalFulfillmentRequest = { method }\n const phone = normalizePhone(text(raw['textPhone'], 32))\n if (phone) request.textPhone = phone\n if (method === 'pickup') {\n request.locationId = text(raw['locationId'], 120)\n return request\n }\n const postalCode = text(raw['postalCode'], 16)\n if (postalCode) request.postalCode = postalCode\n const start = Math.round(Number(raw['windowStartMs']))\n if (Number.isFinite(start) && start > 0) request.windowStartMs = start\n const address = raw['address']\n if (address && typeof address === 'object') {\n const parts = address as Record<string, unknown>\n request.address = {\n line1: text(parts['line1'], 120),\n line2: text(parts['line2'], 120),\n city: text(parts['city'], 80),\n state: text(parts['state'], 40),\n postalCode: text(parts['postalCode'], 16) || postalCode,\n }\n }\n return request\n}\n\n/** The store's pickup locations and delivery settings, read once per attempt. */\nexport interface LocalFulfillmentStore {\n pickupLocations: CommerceModel.PickupLocationOption[]\n delivery: CommerceModel.LocalDeliverySettings\n timeZone: string\n}\n\n/** Reads what checkout and the cart need. Never throws: a failed read offers nothing. */\nexport async function readLocalFulfillmentStore(input: {\n hostRef: any\n /** `settings/store` as already read, to save a read. */\n storeSettings?: Record<string, unknown> | null\n org?: { timeZone?: string } | null\n host?: { timeZone?: string } | null\n}): Promise<LocalFulfillmentStore> {\n const { hostRef } = input\n const [locationsSnapshot, settings, host] = await Promise.all([\n hostRef\n .collection('locations')\n .limit(CommerceModel.PICKUP_LOCATIONS_MAX)\n .get()\n .catch(() => null),\n input.storeSettings !== undefined\n ? Promise.resolve(input.storeSettings)\n : hostRef\n .collection('settings')\n .doc('store')\n .get()\n .then((snapshot: any) => (snapshot?.data?.() ?? null) as Record<string, unknown> | null)\n .catch(() => null),\n input.host !== undefined\n ? Promise.resolve(input.host)\n : hostRef\n .get()\n .then((snapshot: any) => (snapshot?.data?.() ?? null) as { timeZone?: string } | null)\n .catch(() => null),\n ])\n const locations = (locationsSnapshot?.docs ?? []).map((snapshot: any) => ({\n ...(snapshot.data() as CommerceModel.InventoryLocation),\n id: String(snapshot.id),\n }))\n return {\n pickupLocations: CommerceModel.pickupLocationOptions(locations),\n delivery: CommerceModel.normalizeLocalDeliverySettings(settings?.['localDelivery']),\n timeZone: resolveSiteTimeZone(input.org ?? null, host ?? null),\n }\n}\n\n/** How long checkout waits for an address to be placed on a map. */\nexport const LOCAL_DELIVERY_GEOCODE_TIMEOUT_MS = 3_000\n\n/**\n * Places an address on the map through the shipping plugin's address check,\n * or answers `null`: no plugin, not available on this site, no position in\n * the answer, or slower than the timeout. Never throws.\n */\nexport async function placeDeliveryAddress(\n hostId: string,\n address: { line1?: string; line2?: string; city?: string; state?: string; postalCode?: string; country: string },\n): Promise<CommerceModel.LocalDeliveryCoordinates | null> {\n if (!address.line1 || !address.postalCode) return null\n const quoter = pluginShippingRateQuoter()\n if (!quoter?.validateAddress) return null\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const placed = await Promise.race([\n (async () => {\n if (!(await quoter.available(hostId))) return null\n const check = await quoter.validateAddress?.(hostId, {\n line1: address.line1,\n ...(address.line2 ? { line2: address.line2 } : {}),\n ...(address.city ? { city: address.city } : {}),\n ...(address.state ? { state: address.state } : {}),\n postalCode: address.postalCode,\n country: address.country,\n } as never)\n return check?.verdict === 'invalid' ? null : (check?.coordinates ?? null)\n })().catch(() => null),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), LOCAL_DELIVERY_GEOCODE_TIMEOUT_MS)\n }),\n ])\n return placed ?? null\n } finally {\n if (timer) clearTimeout(timer)\n }\n}\n\n/** The shipping option id a local delivery fee is declared under. */\nexport const LOCAL_DELIVERY_RATE_ID = 'local-delivery'\n\nexport type LocalFulfillmentPlan =\n | { kind: 'shipping' }\n | {\n kind: 'refusal'\n status: 400 | 409\n error: string\n /** What the cart should re-ask: the options changed under the buyer. */\n changed?: 'pickup' | 'delivery'\n }\n | {\n kind: 'pickup'\n location: CommerceModel.PickupLocationOption\n metadata: Record<string, string>\n }\n | {\n kind: 'local_delivery'\n zone: CommerceModel.LocalDeliveryZone\n window: CommerceModel.LocalDeliveryWindow\n feeCents: number\n country: string\n locationId?: string\n option: CommerceModel.ResolvedShippingRate\n metadata: Record<string, string>\n }\n\nconst money = (cents: number) => CommerceModel.formatOrderMoney(cents, 'USD')\n\n/**\n * Turns the cart's declaration into what the session needs, or a refusal.\n * Taken BEFORE any reservation or Stripe call, so a refusal costs nothing\n * and the buyer's same button works once they choose again.\n */\nexport async function planLocalFulfillment(input: {\n hostId: string\n request: LocalFulfillmentRequest | null\n /** The goods, pre-discount — what a minimum and a free-over threshold read. */\n itemsCents: number\n hasPhysicalLine: boolean\n store: LocalFulfillmentStore\n nowMs?: number\n}): Promise<LocalFulfillmentPlan> {\n const { request, store } = input\n // A cart of downloads is not collected or driven anywhere.\n if (!request || request.method === 'shipping' || !input.hasPhysicalLine) return { kind: 'shipping' }\n const nowMs = input.nowMs ?? Date.now()\n\n if (request.method === 'pickup') {\n const location = store.pickupLocations.find((entry) => entry.id === request.locationId)\n if (!location) {\n return {\n kind: 'refusal',\n status: 409,\n error: 'That pickup location is no longer available. Choose another.',\n changed: 'pickup',\n }\n }\n return {\n kind: 'pickup',\n location,\n metadata: {\n fulfillment: 'pickup',\n pickupLocationId: location.id,\n ...(request.textPhone ? { orderTextPhone: request.textPhone } : {}),\n },\n }\n }\n\n const delivery = store.delivery\n if (!CommerceModel.localDeliveryOffered(delivery)) {\n return {\n kind: 'refusal',\n status: 409,\n error: 'Local delivery is not available right now. Choose shipping or pickup.',\n changed: 'delivery',\n }\n }\n const country = String(delivery.country)\n const postalCode = CommerceModel.normalizePostcode(\n request.postalCode ?? request.address?.postalCode,\n country,\n )\n if (!postalCode) {\n return { kind: 'refusal', status: 400, error: 'Enter your postal code for delivery.' }\n }\n let zone = CommerceModel.matchLocalDeliveryZone(delivery, { country, postalCode })\n if (!zone && CommerceModel.localDeliveryHasRadiusZones(delivery)) {\n if (!request.address?.line1) {\n return { kind: 'refusal', status: 400, error: 'Enter your street address for delivery.' }\n }\n const coordinates = await placeDeliveryAddress(input.hostId, {\n ...request.address,\n postalCode,\n country,\n })\n zone = CommerceModel.matchLocalDeliveryZone(delivery, { country, postalCode, coordinates })\n }\n if (!zone) {\n return {\n kind: 'refusal',\n status: 409,\n error: `We don’t deliver to ${postalCode}. Choose shipping or pickup instead.`,\n }\n }\n const shortfall = CommerceModel.localDeliveryMinimumShortfall(zone, input.itemsCents)\n if (shortfall > 0) {\n return {\n kind: 'refusal',\n status: 409,\n error:\n `Delivery to ${postalCode} needs an order of at least ${money(zone.minimumCents ?? 0)}. ` +\n `Add ${money(shortfall)} more, or choose shipping or pickup.`,\n }\n }\n const window = CommerceModel.findLocalDeliveryWindow(delivery, request.windowStartMs, {\n nowMs,\n timeZone: store.timeZone,\n })\n if (!window) {\n return {\n kind: 'refusal',\n status: 409,\n error: 'That delivery time is no longer available. Choose another.',\n changed: 'delivery',\n }\n }\n const feeCents = CommerceModel.localDeliveryFeeCents(zone, input.itemsCents)\n const label = CommerceModel.formatLocalDeliveryWindow(window, store.timeZone)\n return {\n kind: 'local_delivery',\n zone,\n window,\n feeCents,\n country,\n ...(delivery.locationId ? { locationId: delivery.locationId } : {}),\n option: {\n rateId: LOCAL_DELIVERY_RATE_ID,\n name: `Local delivery — ${label}`.slice(0, 100),\n amountCents: feeCents,\n },\n metadata: {\n fulfillment: 'local_delivery',\n deliveryZoneId: zone.id,\n deliveryWindowStartMs: String(window.startMs),\n deliveryWindowEndMs: String(window.endMs),\n deliveryPostalCode: postalCode,\n deliveryFeeCents: String(feeCents),\n ...(delivery.locationId ? { deliveryLocationId: delivery.locationId } : {}),\n ...(request.textPhone ? { orderTextPhone: request.textPhone } : {}),\n },\n }\n}\n\n/** Sets a plan's metadata on a session's form body. */\nexport function appendLocalFulfillmentMetadata(params: URLSearchParams, metadata: Record<string, string>): void {\n for (const [key, value] of Object.entries(metadata)) {\n params.set(`metadata[${key}]`, String(value).slice(0, 480))\n }\n}\n\n/** The location a plan takes its stock from, if any. */\nexport function localFulfillmentLocationId(plan: LocalFulfillmentPlan): string | undefined {\n if (plan.kind === 'pickup') return plan.location.id\n if (plan.kind === 'local_delivery') return plan.locationId\n return undefined\n}\n\n/** A stock refusal for a plan that reserves at one location (AGL-3624). */\nexport function localStockRefusalMessage(plan: LocalFulfillmentPlan, productName: string): string {\n const what = productName ? `\"${productName}\"` : 'An item in your cart'\n if (plan.kind === 'pickup') {\n return `${what} is not in stock at ${plan.location.name}. Choose another location, or have it shipped.`\n }\n return `${what} is not in stock for local delivery. Choose pickup at another location, or have it shipped.`\n}\n\n// ---------------------------------------------------------------------------\n// The order, as the webhook records it\n// ---------------------------------------------------------------------------\n\n/** What a paid session's declaration becomes on its order. */\nexport interface OrderLocalFulfillment {\n fields: {\n fulfillmentMethod: CommerceModel.OrderFulfillmentMethod\n pickup?: CommerceModel.OrderPickup\n localDelivery?: CommerceModel.OrderLocalDelivery\n locationId?: string\n /** The number the buyer asked to be texted at, at the cart. */\n customerPhone?: string\n } & CommerceModel.OrderLocalFulfillmentListFields\n /** The line the receipt adds, so the buyer knows where and when. */\n summary: string\n /** The address entered at payment is outside the zone the fee was charged for. */\n outsideZone: boolean\n}\n\n/**\n * Reads a paid session's `fulfillment` metadata into order fields, or `null`\n * for a shipped order. The location and zone are re-read so the order keeps\n * their names as they were when the buyer paid.\n */\nexport async function orderLocalFulfillmentFromSession(input: {\n hostId: string\n hostRef: any\n metadata: Record<string, unknown> | null | undefined\n /** The address the buyer entered at payment, when the session collected one. */\n shippingAddress?: { postalCode?: string | null; country?: string | null } | null\n createdAtMs: number\n}): Promise<OrderLocalFulfillment | null> {\n const metadata = input.metadata ?? {}\n const method = metadata['fulfillment']\n if (method !== 'pickup' && method !== 'local_delivery') return null\n const textPhone = normalizePhone(String(metadata['orderTextPhone'] ?? ''))\n const phone = textPhone ? { customerPhone: textPhone } : {}\n const org = await getOrgForHost(input.hostId).catch(() => null)\n const store = await readLocalFulfillmentStore({\n hostRef: input.hostRef,\n org: (org?.org ?? null) as { timeZone?: string } | null,\n })\n\n if (method === 'pickup') {\n const locationId = String(metadata['pickupLocationId'] ?? '')\n let location = store.pickupLocations.find((entry) => entry.id === locationId)\n // A location renamed or switched off after the buyer paid: the order\n // still goes there, under the name the location doc now has.\n if (!location && locationId) {\n const snapshot = await input.hostRef\n .collection('locations')\n .doc(locationId)\n .get()\n .catch(() => null)\n const data = (snapshot?.exists ? snapshot.data() : null) as CommerceModel.InventoryLocation | null\n location = {\n id: locationId,\n name: String(data?.name || 'the store'),\n ...(data\n ? { address: CommerceModel.formatPostalAddressLine(data.postalAddress, data.address) || undefined }\n : {}),\n }\n }\n if (!location) return null\n const pickup: CommerceModel.OrderPickup = {\n locationId: location.id,\n locationName: location.name,\n ...(location.address ? { address: location.address } : {}),\n ...(location.instructions ? { instructions: location.instructions } : {}),\n ...(location.hours ? { hours: location.hours } : {}),\n status: 'preparing',\n updatedAtMs: input.createdAtMs,\n }\n const order = { fulfillmentMethod: 'pickup' as const, pickup, createdAtMs: input.createdAtMs }\n const list = CommerceModel.orderLocalFulfillmentListFields(order) as CommerceModel.OrderLocalFulfillmentListFields\n const ready = CommerceModel.pickupReadyWithinLabel(location.readyWithinMinutes)\n return {\n fields: { fulfillmentMethod: 'pickup', pickup, locationId: location.id, ...phone, ...list },\n summary: [\n `Pickup at ${location.name}${location.address ? `, ${location.address}` : ''}.`,\n `We’ll let you know when it’s ready${ready ? ` (${ready.toLowerCase()})` : ''}.`,\n location.instructions ?? '',\n ]\n .filter(Boolean)\n .join(' '),\n outsideZone: false,\n }\n }\n\n const zoneId = String(metadata['deliveryZoneId'] ?? '')\n const zone = (store.delivery.zones ?? []).find((entry) => entry.id === zoneId)\n const windowStartMs = Number(metadata['deliveryWindowStartMs']) || 0\n const windowEndMs = Number(metadata['deliveryWindowEndMs']) || windowStartMs\n const declared = String(metadata['deliveryPostalCode'] ?? '')\n const country = store.delivery.country ?? String(input.shippingAddress?.country ?? '')\n const entered = CommerceModel.normalizePostcode(input.shippingAddress?.postalCode, country)\n // The fee was charged for the code the buyer declared. The address they\n // then typed at payment must be in a zone too — a zone of ANY fee, since\n // the store delivers there — or the store is told.\n const outsideZone = Boolean(\n entered &&\n entered !== declared &&\n !CommerceModel.matchLocalDeliveryZone(store.delivery, { country, postalCode: entered }),\n )\n const windowLabel = windowStartMs\n ? CommerceModel.formatLocalDeliveryWindow({ startMs: windowStartMs, endMs: windowEndMs }, store.timeZone)\n : ''\n const locationId = String(metadata['deliveryLocationId'] ?? '') || undefined\n const localDelivery: CommerceModel.OrderLocalDelivery = {\n zoneId,\n zoneName: zone?.name ?? 'Local delivery',\n feeCents: Math.max(0, Math.round(Number(metadata['deliveryFeeCents']) || 0)),\n windowStartMs,\n windowEndMs,\n ...(windowLabel ? { windowLabel } : {}),\n ...(declared ? { postalCode: declared } : {}),\n ...(locationId ? { locationId } : {}),\n status: 'scheduled',\n ...(outsideZone ? { addressOutsideZone: true } : {}),\n updatedAtMs: input.createdAtMs,\n }\n const order = { fulfillmentMethod: 'local_delivery' as const, localDelivery, createdAtMs: input.createdAtMs }\n const list = CommerceModel.orderLocalFulfillmentListFields(order) as CommerceModel.OrderLocalFulfillmentListFields\n return {\n fields: {\n fulfillmentMethod: 'local_delivery',\n localDelivery,\n ...(locationId ? { locationId } : {}),\n ...phone,\n ...list,\n },\n summary: [\n `Local delivery${windowLabel ? `: ${windowLabel}` : ''}.`,\n store.delivery.instructions ?? '',\n ]\n .filter(Boolean)\n .join(' '),\n outsideZone,\n }\n}\n\n// ---------------------------------------------------------------------------\n// The cart's question: what can this basket be?\n// ---------------------------------------------------------------------------\n\n/** Distance zones place an address through a provider: a visitor may ask this often. */\nconst PLACE_LIMIT = { limit: 20, windowMs: 60 * 60 * 1000 }\n\n/**\n * `POST commerce/local-fulfillment-options` (AGL-3624): what the cart offers\n * besides shipping — the pickup locations and, with a postal code, the\n * delivery zone's fee, minimum and the windows open to book.\n *\n * Public, because a shopper asks it; it returns only what a storefront would\n * print anyway (location names, addresses, hours, fees). It reads the\n * visitor's own cart through the cart cookie and offers nothing for a\n * basket with nothing physical in it.\n */\nexport const localFulfillmentOptionsHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST' && req.method !== 'GET') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n let body: Record<string, any>\n try {\n body =\n req.method === 'POST'\n ? typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n : ((req.query ?? {}) as Record<string, any>)\n } catch {\n return res.status(400).json({ error: 'Invalid request' })\n }\n const hostId = String(body.hostId ?? '')\n if (!isDocumentId(hostId)) return res.status(400).json({ error: 'Missing or invalid hostId' })\n const nothing = { pickup: [], delivery: null }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const ownerOrg = await getOrgForHost(hostId).catch(() => null)\n if (!ownerOrg?.org || !Aglyn.checkEntitlement(ownerOrg.org as any, 'commerce')) {\n return res.status(200).json(nothing)\n }\n // The visitor's own basket decides whether there is anything to collect\n // — or, from a product's Buy button, that one product (AGL-3624).\n const buyNowProductId = typeof body.productId === 'string' ? body.productId : ''\n let cart: Pick<CommerceModel.HostCart, 'lines'>\n if (buyNowProductId) {\n if (!isDocumentId(buyNowProductId)) return res.status(400).json({ error: 'Invalid productId' })\n cart = {\n lines: [\n {\n productId: buyNowProductId,\n ...(typeof body.variantId === 'string' && body.variantId ? { variantId: body.variantId } : {}),\n // The add-ons chosen on the page (AGL-4100), priced below.\n ...(Array.isArray(body.modifiers)\n ? { modifiers: CommerceModel.modifierSelectionFrom(body.modifiers) }\n : {}),\n quantity: Math.min(CommerceModel.CART_MAX_QUANTITY, Math.max(1, Math.round(Number(body.quantity) || 1))),\n },\n ],\n }\n } else {\n const cartId = readCartId(req.cookies, hostId)\n const cartSnapshot = cartId ? await hostRef.collection('carts').doc(cartId).get().catch(() => null) : null\n cart = (cartSnapshot?.data?.() as CommerceModel.HostCart | undefined) ?? { lines: [] }\n }\n const productIds = [...new Set((cart.lines ?? []).map((line) => line.productId))].slice(0, 50)\n const products = await Promise.all(\n productIds.map((id) =>\n hostRef\n .collection('products')\n .doc(id)\n .get()\n .catch(() => null),\n ),\n )\n let itemsCents = 0\n let hasPhysicalLine = false\n for (const line of cart.lines ?? []) {\n const snapshot = products[productIds.indexOf(line.productId)]\n if (!snapshot?.exists) continue\n const product = CommerceModel.liftLegacyProduct(snapshot.data() as any)\n const variant = line.variantId\n ? product.variants.find((item) => item.id === line.variantId)\n : product.variants[0]\n // With its add-ons (AGL-4100), as checkout prices the line.\n const chosen = CommerceModel.resolveWebsiteLineModifiers(product, line.modifiers, variant?.id)\n itemsCents +=\n (Math.round(Number(variant?.priceUsd ?? 0) * 100) + (chosen.ok ? chosen.extraCents : 0)) *\n (Number(line.quantity) || 0)\n if ((product.type ?? 'physical') === 'physical') hasPhysicalLine = true\n }\n if (!hasPhysicalLine) return res.status(200).json(nothing)\n\n const store = await readLocalFulfillmentStore({\n hostRef,\n org: ownerOrg.org as { timeZone?: string },\n })\n const nowMs = Date.now()\n let delivery: Record<string, unknown> | null = null\n if (CommerceModel.localDeliveryOffered(store.delivery)) {\n const settings = store.delivery\n const country = String(settings.country)\n const windows = CommerceModel.upcomingLocalDeliveryWindows(settings, { nowMs, timeZone: store.timeZone }).map(\n (window) => ({\n ...window,\n label: CommerceModel.formatLocalDeliveryWindow(window, store.timeZone),\n }),\n )\n const radius = CommerceModel.localDeliveryHasRadiusZones(settings)\n delivery = {\n country,\n ...(settings.instructions ? { instructions: settings.instructions } : {}),\n needsAddress: radius,\n windows,\n }\n const request = readLocalFulfillmentRequest({\n method: 'local_delivery',\n postalCode: body.postalCode,\n address: body.address,\n })\n const postalCode = CommerceModel.normalizePostcode(request?.postalCode ?? request?.address?.postalCode, country)\n if (postalCode) {\n let zone = CommerceModel.matchLocalDeliveryZone(settings, { country, postalCode })\n if (!zone && radius && request?.address?.line1) {\n const visitor = String(req.socket?.remoteAddress ?? '') || 'no-address'\n const allowed = await consumeRateLimit(`local-delivery:place:${hostId}:${visitor}`, PLACE_LIMIT)\n .then((result) => result.allowed)\n .catch(() => false)\n const coordinates = allowed\n ? await placeDeliveryAddress(hostId, { ...request.address, postalCode, country })\n : null\n zone = CommerceModel.matchLocalDeliveryZone(settings, { country, postalCode, coordinates })\n }\n delivery['quote'] = zone\n ? {\n zoneId: zone.id,\n zoneName: zone.name,\n feeCents: CommerceModel.localDeliveryFeeCents(zone, itemsCents),\n ...(zone.minimumCents ? { minimumCents: zone.minimumCents } : {}),\n ...(zone.freeOverCents ? { freeOverCents: zone.freeOverCents } : {}),\n shortfallCents: CommerceModel.localDeliveryMinimumShortfall(zone, itemsCents),\n }\n : { unavailable: `We don’t deliver to ${postalCode}.` }\n }\n }\n // Whether the cart may offer texts about the pickup or delivery: the\n // platform can send them and the store has not turned them off.\n const toggles = (await hostRef\n .collection('settings')\n .doc('store')\n .get()\n .then((snapshot: any) => snapshot?.get?.('buyerNotifications'))\n .catch(() => null)) as unknown\n const texts = Boolean(\n pluginSmsMessaging()?.isConfigured() && CommerceModel.buyerNotificationEnabled(toggles, 'texts'),\n )\n return res.status(200).json({ pickup: store.pickupLocations, delivery, texts })\n } catch (error) {\n console.error('[local-fulfillment] options failed', hostId, error)\n return res.status(200).json(nothing)\n }\n}\n"],"names":["resolveSiteTimeZone","normalizePhone","pluginSmsMessaging","pluginShippingRateQuoter","Aglyn","consumeRateLimit","firebaseAdmin","getOrgForHost","isDocumentId","CommerceModel","readCartId","readLocalFulfillmentRequest","value","raw","method","text","input","max","String","trim","slice","request","phone","textPhone","locationId","postalCode","start","Math","round","Number","isFinite","windowStartMs","address","parts","line1","line2","city","state","readLocalFulfillmentStore","hostRef","locationsSnapshot","settings","host","Promise","all","collection","limit","PICKUP_LOCATIONS_MAX","get","catch","storeSettings","undefined","resolve","doc","then","snapshot","data","locations","docs","map","id","pickupLocations","pickupLocationOptions","delivery","normalizeLocalDeliverySettings","timeZone","org","LOCAL_DELIVERY_GEOCODE_TIMEOUT_MS","placeDeliveryAddress","hostId","quoter","validateAddress","timer","placed","race","available","check","country","verdict","coordinates","setTimeout","clearTimeout","LOCAL_DELIVERY_RATE_ID","money","cents","formatOrderMoney","planLocalFulfillment","store","hasPhysicalLine","kind","nowMs","Date","now","location","find","entry","status","error","changed","metadata","fulfillment","pickupLocationId","orderTextPhone","localDeliveryOffered","normalizePostcode","zone","matchLocalDeliveryZone","localDeliveryHasRadiusZones","shortfall","localDeliveryMinimumShortfall","itemsCents","minimumCents","window","findLocalDeliveryWindow","feeCents","localDeliveryFeeCents","label","formatLocalDeliveryWindow","option","rateId","name","amountCents","deliveryZoneId","deliveryWindowStartMs","startMs","deliveryWindowEndMs","endMs","deliveryPostalCode","deliveryFeeCents","deliveryLocationId","appendLocalFulfillmentMetadata","params","key","Object","entries","set","localFulfillmentLocationId","plan","localStockRefusalMessage","productName","what","orderLocalFulfillmentFromSession","customerPhone","exists","formatPostalAddressLine","postalAddress","pickup","locationName","instructions","hours","updatedAtMs","createdAtMs","order","fulfillmentMethod","list","orderLocalFulfillmentListFields","ready","pickupReadyWithinLabel","readyWithinMinutes","fields","summary","toLowerCase","filter","Boolean","join","outsideZone","zoneId","zones","windowEndMs","declared","shippingAddress","entered","windowLabel","localDelivery","zoneName","addressOutsideZone","PLACE_LIMIT","windowMs","localFulfillmentOptionsHandler","req","res","body","json","JSON","parse","query","nothing","cart","firestore","app","ownerOrg","checkEntitlement","buyNowProductId","productId","lines","variantId","Array","isArray","modifiers","modifierSelectionFrom","quantity","min","CART_MAX_QUANTITY","cartSnapshot","cartId","cookies","productIds","Set","line","products","product","indexOf","liftLegacyProduct","variant","variants","item","chosen","resolveWebsiteLineModifiers","priceUsd","ok","extraCents","type","windows","upcomingLocalDeliveryWindows","radius","needsAddress","visitor","socket","remoteAddress","allowed","result","freeOverCents","shortfallCents","unavailable","toggles","texts","isConfigured","buyerNotificationEnabled","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,cAAc,QAAQ,oDAAmD;AAClF,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SAASC,wBAAwB,QAAQ,oDAAmD;AAE5F,YAAYC,WAAW,sBAAqB;AAC5C,SAASC,gBAAgB,EAAEC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACzF,SAASC,YAAY,QAAQ,8CAA6C;AAC1E,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,UAAU,QAAQ,mBAAe;AAiD1C,8EAA8E,GAC9E,OAAO,SAASC,4BAA4BC,KAAc;IACxD,IAAI,CAACA,SAAS,OAAOA,UAAU,UAAU,OAAO;IAChD,MAAMC,MAAMD;IACZ,MAAME,SAASD,GAAG,CAAC,SAAS;IAC5B,IAAIC,WAAW,YAAYA,WAAW,kBAAkB,OAAO;IAC/D,MAAMC,OAAO,CAACC,OAAgBC,MAAgBC,OAAOF,gBAAAA,QAAS,IAAIG,IAAI,GAAGC,KAAK,CAAC,GAAGH;IAClF,MAAMI,UAAmC;QAAEP;IAAO;IAClD,MAAMQ,QAAQrB,eAAec,KAAKF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AMnO,cAAcoO,wBAAwB,CAACH,SAAS;QAE1F,OAAOtD,IAAIpF,MAAM,CAAC,KAAKsF,IAAI,CAAC;YAAEpC,QAAQ3D,MAAM1B,eAAe;YAAEE;YAAU4K;QAAM;IAC/E,EAAE,OAAO1I,OAAO;QACd6I,QAAQ7I,KAAK,CAAC,sCAAsC5B,QAAQ4B;QAC5D,OAAOmF,IAAIpF,MAAM,CAAC,KAAKsF,IAAI,CAACI;IAC9B;AACF,EAAC"}
|
|
@@ -31,7 +31,7 @@ export interface PosCellularBillingDeps {
|
|
|
31
31
|
readBilling?: (orgId: string) => Promise<{
|
|
32
32
|
stripeCustomerId?: unknown;
|
|
33
33
|
}>;
|
|
34
|
-
turnOff?: (configurationId: string) => Promise<boolean>;
|
|
34
|
+
turnOff?: (configurationId: string, stripeAccount?: string | null) => Promise<boolean>;
|
|
35
35
|
alert?: typeof raiseOperatorAlert;
|
|
36
36
|
/** Stripe's word on a charge's invoice now, or null when it cannot be asked. */
|
|
37
37
|
invoiceStatus?: InvoiceStatus;
|
|
@@ -131,7 +131,8 @@ function chargesRef() {
|
|
|
131
131
|
let off = 0;
|
|
132
132
|
let failed = 0;
|
|
133
133
|
for (const [configurationId, record] of configurations){
|
|
134
|
-
|
|
134
|
+
var _record_stripeConfigurationAccount;
|
|
135
|
+
const done = await deps.turnOff(configurationId, (_record_stripeConfigurationAccount = record.stripeConfigurationAccount) != null ? _record_stripeConfigurationAccount : null).catch(()=>false);
|
|
135
136
|
if (done) {
|
|
136
137
|
off += 1;
|
|
137
138
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular-billing.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 { normalizeOrgLockdown } from '@aglyn/aglyn/app-utils/lockdown'\nimport { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport type { PluginOrgEraser } from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport type { PluginJobHostGate } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, raiseOperatorAlert, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport {\n chargeOrgUsageInvoice,\n USAGE_INVOICE_MIN_CHARGE_CENTS,\n type OrgUsageInvoiceRequest,\n type OrgUsageInvoiceResult,\n} from '@aglyn/tenant-data-admin/server/usage-invoice'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n COMMERCE_POS_CELLULAR_CHARGE_FAILED,\n COMMERCE_POS_CELLULAR_TURN_OFF_FAILED,\n COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID,\n} from '../constants/operator-alerts'\nimport {\n closePosCellularPeriod,\n parsePosCellularConfig,\n posCellularChargeCents,\n posCellularGraceEndsAtMs,\n posCellularMonthBounds,\n posCellularMonthKey,\n posCellularMonthLabel,\n posCellularOverdue,\n posCellularPreviousMonthKey,\n posCellularReadersByWorkspace,\n posCellularWarningDue,\n POS_CELLULAR_CHARGE_KIND,\n POS_CELLULAR_CHARGES_COLLECTION,\n POS_CELLULAR_READERS_COLLECTION,\n POS_CELLULAR_SETTLED_STATES,\n type PosCellularCharge,\n type PosCellularChargeState,\n type PosCellularConfig,\n type PosCellularReaderRecord,\n type PosCellularSuspension,\n} from '../model/pos-cellular'\nimport {\n posCellularInvoiceStatus,\n settleSuspendedPosCellularCharge,\n turnOffPosCellularConfiguration,\n} from './pos-cellular'\n\n/*==========================================\n * THE MONTHLY 4G CHARGE (AGL-4038).\n *\n * Once a day, for the calendar month that has just ended, each workspace\n * whose Stripe Reader S710s had 4G at any time in it is charged once: Stripe's\n * price per reader, plus what collecting it costs (`posCellularChargeCents`),\n * on a one-off invoice to its card through core's usage-invoice charge, the\n * path domains and AI overages take. That is the month Stripe bills the\n * platform for, in arrears, so a reader turned off on the 3rd is charged for\n * that month and not the next.\n *\n * Once per workspace per month: `posCellularCharges/{orgId}_{month}` is\n * claimed in a transaction before Stripe is called, and the invoice's\n * idempotency key is the same pair, so a run that died mid-charge and the\n * next day's run land on the same invoice. A charge that did not collect is\n * left open on the workspace's Billing page (nothing retries it) and staff\n * are alerted; a workspace with no one to bill is recorded and alerted, and\n * never charged later for that month.\n *\n * Daily rather than monthly: a month whose charge failed to START (Stripe\n * unreachable) is retried the next day; one that settled costs a read.\n *\n * A STORE THAT IS GONE stops costing the platform: a reader record whose\n * store no longer exists has its period closed and the store's Configuration\n * told to turn cellular off; a workspace being erased does the same for all\n * of its stores first ({@link posCellularOrgEraser}).\n *\n * WARN, THEN TURN OFF. A charge left open is asked about each day: paid\n * since, it is settled as paid; voided by staff, as voided. The first time\n * Stripe says it is still unpaid (the same run that left it open, unless\n * Stripe could not be asked), the members who manage the workspace's billing\n * are warned, once (`warnedAtMs`), of the amount and of the day 4G turns off\n * unless it is paid; paid before then, nothing else is sent. Still unpaid\n * once the grace period (`POS_CELLULAR_GRACE_DAYS`, 14 by default) has run\n * from the day it was left open, 4G is turned off at Stripe for every store\n * of the workspace, the members who manage its billing are emailed and\n * notified again, and staff are alerted. Stripe that cannot be asked is never\n * read as unpaid.\n * Paying does not turn 4G back on: the merchant does, once it is paid\n * (`pos-cellular.ts` refuses it until then). Each step is idempotent, so a run\n * that dies half-way is finished by the next.\n *\n * A WORKSPACE DELETED MID-MONTH is charged for that final month as it is\n * erased, before its data goes, through the same claim as the monthly run\n * (and last month too, if the run had not charged it yet), so the two never\n * charge one month twice. A failure there alerts staff and never holds the\n * erasure.\n *=========================================*/\n\nconst LABEL = '[pos-cellular] billing'\n\n/** A charge claimed this long ago and not settled was abandoned by its run. */\nconst CLAIM_STALE_MS = 30 * 60 * 1000\n\n/** How many times a charge that never reached Stripe is tried before staff hear of it. */\nconst ALERT_AFTER_ATTEMPTS = 3\n\ntype Charge = (request: OrgUsageInvoiceRequest) => Promise<OrgUsageInvoiceResult>\n\ntype InvoiceStatus = (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null>\n\nexport interface PosCellularBillingDeps {\n now?: () => number\n config?: PosCellularConfig | null\n charge?: Charge\n readBilling?: (orgId: string) => Promise<{ stripeCustomerId?: unknown }>\n turnOff?: (configurationId: string) => Promise<boolean>\n alert?: typeof raiseOperatorAlert\n /** Stripe's word on a charge's invoice now, or null when it cannot be asked. */\n invoiceStatus?: InvoiceStatus\n /** Tells the workspace 4G was turned off; true once told (or there is nobody to tell). */\n notify?: (notice: import('./pos-cellular-notify').PosCellularTurnedOffNotice) => Promise<boolean>\n /** Warns the workspace 4G turns off unless the charge is paid; true once told (or there is nobody to tell). */\n warn?: (notice: import('./pos-cellular-notify').PosCellularPaymentDueNotice) => Promise<boolean>\n}\n\nexport interface PosCellularBillingReport {\n month: string | null\n workspaces: number\n paid: number\n open: number\n failed: number\n unbillable: number\n deferred: number\n storesGone: number\n /** Open charges paid since, found by asking Stripe. */\n paidLate: number\n /** Workspaces warned that 4G turns off unless a charge left open is paid. */\n warned: number\n /** Workspaces whose 4G was turned off for a month unpaid past its grace. */\n turnedOff: number\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction recordsRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nfunction chargesRef() {\n return firestore().collection(POS_CELLULAR_CHARGES_COLLECTION)\n}\n\n/** A workspace's charge for one month, `{orgId}_{month}`: one per pair, so a rerun finds it. */\nfunction posCellularChargeId(orgId: string, month: string): string {\n return `${orgId}_${month}`\n}\n\n/** The reader records that may count for a month: on now, or turned off since it began. */\nasync function recordsForMonth(startMs: number): Promise<Array<{ id: string; record: PosCellularReaderRecord }>> {\n const [on, off] = await Promise.all([\n recordsRef().where('enabled', '==', true).limit(1_000).get(),\n recordsRef().where('disabledAtMs', '>=', startMs).limit(1_000).get(),\n ])\n const byId = new Map<string, PosCellularReaderRecord>()\n for (const doc of [...on.docs, ...off.docs] as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n byId.set(String(doc.id), doc.data())\n }\n return [...byId].map(([id, record]) => ({ id, record }))\n}\n\n/**\n * Closes the records of stores that no longer exist and turns cellular off\n * on their Configuration, alerting staff when Stripe refuses. Returns how\n * many stores it found gone.\n */\nasync function closeGoneStores(\n records: ReadonlyArray<{ id: string; record: PosCellularReaderRecord }>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n now: number,\n): Promise<number> {\n const open = records.filter(({ record }) => record.enabled)\n const hostIds = [...new Set(open.map(({ record }) => record.hostId))]\n let gone = 0\n for (const hostId of hostIds) {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (host.exists) continue\n gone += 1\n const mine = open.filter(({ record }) => record.hostId === hostId)\n await turnOffConfigurations(mine.map(({ record }) => record), deps)\n for (const { id, record } of mine) await recordsRef().doc(id).set(closePosCellularPeriod(record, now))\n }\n return gone\n}\n\n/** Turns cellular off on each distinct Configuration the records name, alerting a refusal. */\nasync function turnOffConfigurations(\n records: ReadonlyArray<PosCellularReaderRecord>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n): Promise<{ off: number; failed: number }> {\n const configurations = new Map<string, PosCellularReaderRecord>()\n for (const record of records) {\n if (record.stripeConfigurationId) configurations.set(record.stripeConfigurationId, record)\n }\n let off = 0\n let failed = 0\n for (const [configurationId, record] of configurations) {\n const done = await deps.turnOff(configurationId).catch(() => false)\n if (done) {\n off += 1\n continue\n }\n failed += 1\n await deps\n .alert(COMMERCE_POS_CELLULAR_TURN_OFF_FAILED, {\n dedupeKey: configurationId,\n orgId: record.orgId,\n hostId: record.hostId,\n context: { configurationId, hostId: record.hostId, orgId: record.orgId },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turn-off alert was not raised`, configurationId, error))\n }\n return { off, failed }\n}\n\n/**\n * Claims a workspace's month for this run, or says it is not this run's:\n * settled already, or claimed by a run still within its window. The claim\n * counts the attempt.\n */\nasync function claimMonth(\n orgId: string,\n month: string,\n readers: number,\n amountCents: number,\n now: number,\n): Promise<{ attempts: number } | null> {\n const ref = chargesRef().doc(posCellularChargeId(orgId, month))\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const existing = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (existing && POS_CELLULAR_SETTLED_STATES.includes(existing.state)) return null\n if (existing?.state === 'charging' && now - existing.updatedAtMs < CLAIM_STALE_MS) return null\n const attempts = (existing?.attempts ?? 0) + 1\n const claim: PosCellularCharge = {\n orgId,\n month,\n // The figures of the FIRST attempt stand: the invoice's key is the\n // month's, and Stripe refuses a key reused with other parameters.\n readers: existing?.readers ?? readers,\n amountCents: existing?.amountCents ?? amountCents,\n state: 'charging',\n invoiceId: existing?.invoiceId ?? null,\n paidCents: 0,\n attempts,\n createdAtMs: existing?.createdAtMs ?? now,\n updatedAtMs: now,\n }\n transaction.set(ref, claim)\n return { attempts }\n })\n}\n\nasync function settleMonth(\n orgId: string,\n month: string,\n patch: {\n state: PosCellularChargeState\n invoiceId?: string | null\n paidCents?: number\n openedAtMs?: number\n final?: boolean\n },\n now: number,\n): Promise<void> {\n await chargesRef()\n .doc(posCellularChargeId(orgId, month))\n .set({ ...patch, updatedAtMs: now }, { merge: true })\n}\n\ntype ChargeOutcome = 'paid' | 'open' | 'failed' | 'unbillable' | 'settled'\n\n/**\n * Charges one workspace's month once: claimed in a transaction first, so the\n * monthly run and a workspace erasure never both charge it, and keyed by the\n * month so a retried run lands on the same invoice. `final` marks the charge\n * an erasure made, which alerts staff at once on a failure, since nothing\n * retries it.\n */\nasync function chargeWorkspaceMonth(\n input: { orgId: string; month: string; readers: number; final?: boolean },\n context: {\n config: PosCellularConfig\n now: number\n charge: Charge\n readBilling: NonNullable<PosCellularBillingDeps['readBilling']>\n alert: typeof raiseOperatorAlert\n },\n): Promise<ChargeOutcome> {\n const { orgId, month, readers } = input\n const { config, now, alert } = context\n const amountCents = posCellularChargeCents(readers, config)\n const claim = await claimMonth(orgId, month, readers, amountCents, now)\n if (!claim) return 'settled'\n const stored = (await chargesRef().doc(posCellularChargeId(orgId, month)).get()).data() as PosCellularCharge\n const final = input.final ? { final: true } : {}\n const raise = (reason: string) =>\n alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(stored.readers),\n amount: formatOperatorAlertAmount(stored.amountCents),\n reason: input.final ? `${reason} (charged as the workspace was deleted)` : reason,\n },\n }).catch((error: unknown) => console.error(`${LABEL}: the alert was not raised`, orgId, error))\n\n const org = await firestore().collection('orgs').doc(orgId).get()\n if (!org.exists) {\n await settleMonth(orgId, month, { state: 'no-workspace', ...final }, now)\n if (input.final) await raise('the workspace was already gone')\n return 'unbillable'\n }\n if (stored.amountCents < USAGE_INVOICE_MIN_CHARGE_CENTS) {\n await settleMonth(orgId, month, { state: 'below-minimum', ...final }, now)\n return 'unbillable'\n }\n const billing = await context.readBilling(orgId).catch(() => ({}) as { stripeCustomerId?: unknown })\n const stripeCustomerId = String(billing.stripeCustomerId ?? '')\n if (!stripeCustomerId) {\n await settleMonth(orgId, month, { state: 'no-customer', ...final }, now)\n await raise('the workspace has no payment method on file')\n return 'unbillable'\n }\n const label = posCellularMonthLabel(month)\n const result = await context\n .charge({\n orgId,\n stripeCustomerId,\n productId: config.productId,\n amountCents: stored.amountCents,\n currency: 'usd',\n description: `4G for ${stored.readers} S710 card reader${stored.readers === 1 ? '' : 's'}, ${label}`,\n metadata: {\n orgId,\n pluginId: BUNDLE_ID,\n kind: POS_CELLULAR_CHARGE_KIND,\n month,\n readers: String(stored.readers),\n },\n idempotencyKey: `pos-cellular-${orgId}-${month}`,\n })\n .catch(\n (error: unknown): OrgUsageInvoiceResult => ({\n ok: false,\n invoiceId: null,\n status: null,\n totalCents: 0,\n amountPaidCents: 0,\n requiresAction: false,\n error: error instanceof Error ? error.message : 'the charge threw',\n }),\n )\n if (result.ok) {\n await settleMonth(orgId, month, { state: 'paid', invoiceId: result.invoiceId, paidCents: result.amountPaidCents, ...final }, now)\n return 'paid'\n }\n if (result.invoiceId) {\n // The invoice stays open on their Billing page, where they can pay it;\n // the grace period runs from today.\n await settleMonth(orgId, month, { state: 'open', invoiceId: result.invoiceId, openedAtMs: now, ...final }, now)\n await raise(result.requiresAction ? 'the card needs the cardholder to authenticate' : result.error || 'the card was declined')\n return 'open'\n }\n await settleMonth(orgId, month, { state: 'failed', ...final }, now)\n console.error(`${LABEL}: the charge did not reach Stripe`, orgId, month, result.error)\n // Nothing retries a charge made at erasure: staff hear of it now.\n if (input.final || claim.attempts >= ALERT_AFTER_ATTEMPTS) await raise(result.error || 'Stripe did not answer')\n return 'failed'\n}\n\n/** The charge of every workspace whose readers had 4G last month, once each. */\nexport async function runPosCellularBilling(\n gate: PluginJobHostGate,\n deps: PosCellularBillingDeps = {},\n): Promise<PosCellularBillingReport> {\n const config = deps.config === undefined ? parsePosCellularConfig(process.env) : deps.config\n const now = (deps.now ?? Date.now)()\n const report: PosCellularBillingReport = {\n month: null,\n workspaces: 0,\n paid: 0,\n open: 0,\n failed: 0,\n unbillable: 0,\n deferred: 0,\n storesGone: 0,\n paidLate: 0,\n warned: 0,\n turnedOff: 0,\n }\n if (!config) return report\n const charge = deps.charge ?? ((request: OrgUsageInvoiceRequest) => chargeOrgUsageInvoice(request))\n const readBilling = deps.readBilling ?? ((orgId: string) => readOrgBilling(orgId) as Promise<{ stripeCustomerId?: unknown }>)\n const alert = deps.alert ?? raiseOperatorAlert\n const turnOff = deps.turnOff ?? turnOffPosCellularConfiguration\n\n const month = posCellularPreviousMonthKey(now)\n report.month = month\n const bounds = posCellularMonthBounds(month) as { startMs: number; endMs: number }\n const records = await recordsForMonth(bounds.startMs)\n report.storesGone = await closeGoneStores(records, { turnOff, alert }, now)\n\n const byOrg = posCellularReadersByWorkspace(\n records.map(({ record }) => record),\n month,\n )\n report.workspaces = byOrg.size\n for (const [orgId, { readers, hostIds }] of byOrg) {\n // A store locked for security or abuse is charged nothing while it is:\n // its card may be the stolen one the lock is about. Tried again daily.\n const locked = await Promise.all(hostIds.map((hostId) => gate.isLocked(hostId).catch(() => true)))\n if (locked.some(Boolean)) {\n report.deferred += 1\n continue\n }\n const outcome = await chargeWorkspaceMonth({ orgId, month, readers }, { config, now, charge, readBilling, alert })\n if (outcome === 'paid') report.paid += 1\n else if (outcome === 'open') report.open += 1\n else if (outcome === 'failed') report.failed += 1\n else if (outcome === 'unbillable') report.unbillable += 1\n }\n\n const grace = await enforcePosCellularGrace({\n config,\n now,\n alert,\n turnOff,\n invoiceStatus: deps.invoiceStatus ?? posCellularInvoiceStatus,\n notify:\n deps.notify ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularTurnedOffNotice(notice)),\n warn:\n deps.warn ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularPaymentDueNotice(notice)),\n })\n report.paidLate = grace.paidLate\n report.warned = grace.warned\n report.turnedOff = grace.turnedOff\n return report\n}\n\n/**\n * WARN, THEN TURN OFF (AGL-4038): every charge left open is asked about at\n * Stripe; paid or voided since, it is settled so; still unpaid within its\n * grace, the workspace is warned once of the day 4G turns off; still unpaid\n * past it, 4G goes off for the workspace. A charge already suspended is\n * finished if a run died half-way (a store still on, nobody told yet) and\n * settled once paid.\n */\nasync function enforcePosCellularGrace(context: {\n config: PosCellularConfig\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string) => Promise<boolean>\n invoiceStatus: InvoiceStatus\n notify: NonNullable<PosCellularBillingDeps['notify']>\n warn: NonNullable<PosCellularBillingDeps['warn']>\n}): Promise<{ paidLate: number; warned: number; turnedOff: number }> {\n const { config, now } = context\n let paidLate = 0\n let warned = 0\n let turnedOff = 0\n for (const state of ['open', 'suspended'] as const) {\n const snapshot = await chargesRef().where('state', '==', state).limit(200).get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const id = String(doc.id)\n const stored = doc.data()\n const invoice = stored.invoiceId ? await context.invoiceStatus(stored.invoiceId).catch(() => null) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n const settled = invoice.status === 'paid' ? 'paid' : 'voided'\n if (state === 'suspended') {\n await settleSuspendedPosCellularCharge(id, stored, settled, invoice.amountPaidCents, now)\n } else {\n await settleMonth(stored.orgId, stored.month, { state: settled, ...(settled === 'paid' ? { paidCents: invoice.amountPaidCents } : {}) }, now)\n }\n if (settled === 'paid') paidLate += 1\n continue\n }\n // Stripe could not be asked: never read as unpaid.\n if (!invoice) continue\n if (state === 'open') {\n if (!posCellularOverdue(stored, config.graceDays, now)) {\n if (posCellularWarningDue(stored) && (await warnPaymentDue(id, context))) warned += 1\n continue\n }\n const claimed = await claimSuspension(id, now)\n if (!claimed) continue\n turnedOff += 1\n await context\n .alert(COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID, {\n dedupeKey: id,\n orgId: stored.orgId,\n context: {\n orgId: stored.orgId,\n month: posCellularMonthLabel(stored.month),\n amount: formatOperatorAlertAmount(stored.amountCents),\n graceDays: String(config.graceDays),\n },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turned-off alert was not raised`, id, error))\n }\n await finishSuspension(id, { ...stored, state: 'suspended', suspendedAtMs: stored.suspendedAtMs ?? now }, context)\n }\n }\n return { paidLate, warned, turnedOff }\n}\n\n/**\n * Claims the warning of an open charge, once: the charge as it stood, or null\n * when a run already warned of it or it is no longer open. The day its grace\n * counts from is pinned with the claim, so the day the warning states is the\n * day the turn-off keeps, even for a charge from before that day was stored.\n */\nasync function claimWarning(id: string, now: number): Promise<PosCellularCharge | null> {\n const ref = chargesRef().doc(id)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const charge = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (!charge || !posCellularWarningDue(charge)) return null\n const openedAtMs = Number(charge.openedAtMs ?? charge.updatedAtMs)\n transaction.set(ref, { warnedAtMs: now, openedAtMs, updatedAtMs: now }, { merge: true })\n return { ...charge, openedAtMs }\n })\n}\n\n/**\n * WARN AT THE START (AGL-4038): the members who manage the workspace's\n * billing are told the charge is due and the day 4G turns off for its stores\n * unless it is paid. Claimed before it is sent, so two runs never both send\n * it; a warning nobody could be sent is released for the next run to try.\n */\nasync function warnPaymentDue(\n id: string,\n context: { config: PosCellularConfig; now: number; warn: NonNullable<PosCellularBillingDeps['warn']> },\n): Promise<boolean> {\n const { config, now } = context\n const charge = await claimWarning(id, now)\n if (!charge) return false\n const told = await (async () => {\n // The stores that have 4G now, which lose it on that day.\n const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get()\n const hostIds = [\n ...new Set(\n (snapshot.docs as unknown as Array<{ data: () => PosCellularReaderRecord }>).map((doc) => doc.data().hostId),\n ),\n ]\n return context.warn({\n orgId: charge.orgId,\n month: charge.month,\n amount: formatOperatorAlertAmount(charge.amountCents),\n readers: charge.readers,\n openedAtMs: Number(charge.openedAtMs),\n turnsOffAtMs: posCellularGraceEndsAtMs(charge, config.graceDays),\n hostIds,\n })\n })().catch((error: unknown) => {\n console.error(`${LABEL}: the payment-due warning was not sent`, id, error)\n return false\n })\n if (!told) await chargesRef().doc(id).set({ warnedAtMs: null, updatedAtMs: now }, { merge: true })\n return told\n}\n\n/** Moves an open charge to `suspended`, once: false when a run already did, or it is no longer open. */\nasync function claimSuspension(id: string, now: number): Promise<boolean> {\n const ref = chargesRef().doc(id)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists || (snapshot.data() as PosCellularCharge).state !== 'open') return false\n transaction.set(ref, { state: 'suspended', suspendedAtMs: now, updatedAtMs: now }, { merge: true })\n return true\n })\n}\n\n/**\n * 4G off at Stripe for every store of the workspace that still has it, each\n * store's settings saying why, its readers' periods closed, and the workspace\n * told once. Safe to run again: a store already off and a notice already\n * sent are left alone.\n */\nasync function finishSuspension(\n id: string,\n charge: PosCellularCharge,\n context: {\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string) => Promise<boolean>\n notify: NonNullable<PosCellularBillingDeps['notify']>\n },\n): Promise<void> {\n const { now } = context\n const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get()\n const records = (snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>).map(\n (doc) => ({ id: String(doc.id), record: doc.data() }),\n )\n const hostIds = new Set(charge.suspendedHostIds ?? [])\n if (records.length) {\n await turnOffConfigurations(\n records.map(({ record }) => record),\n { turnOff: context.turnOff, alert: context.alert },\n )\n const suspension: PosCellularSuspension = { month: charge.month, invoiceId: charge.invoiceId, atMs: now }\n for (const hostId of new Set(records.map(({ record }) => record.hostId))) {\n hostIds.add(hostId)\n const terminal = firestore().collection('hosts').doc(hostId).collection('terminal').doc('config')\n if (!(await terminal.get()).exists) continue\n await terminal.set(\n { cellularEnabled: false, cellularChangedAtMs: now, cellularChangedBy: 'unpaid', cellularSuspended: suspension },\n { merge: true },\n )\n }\n for (const { id: recordId, record } of records) await recordsRef().doc(recordId).set(closePosCellularPeriod(record, now))\n }\n const patch: Partial<PosCellularCharge> = {}\n if (records.length || hostIds.size !== (charge.suspendedHostIds ?? []).length) patch.suspendedHostIds = [...hostIds]\n if (!charge.noticeSentAtMs) {\n const told = await context.notify({\n orgId: charge.orgId,\n month: charge.month,\n amount: formatOperatorAlertAmount(charge.amountCents),\n readers: charge.readers,\n openedAtMs: Number(charge.openedAtMs ?? charge.updatedAtMs),\n turnedOffAtMs: Number(charge.suspendedAtMs ?? now),\n hostIds: [...hostIds],\n })\n if (told) patch.noticeSentAtMs = now\n }\n // A suspension already finished, and still unpaid, writes nothing.\n if (Object.keys(patch).length) await chargesRef().doc(id).set({ ...patch, updatedAtMs: now }, { merge: true })\n}\n\n/**\n * Commerce's 4G share of a WORKSPACE erasure (AGL-4038), before its data\n * goes:\n *\n * 1. CHARGE IT. The month the workspace is deleted in is charged now, for\n * each S710 that had 4G in it, as the monthly run would have charged it a\n * month later; and last month too, if the run had not charged it yet.\n * Through the run's own claim and key, so the two never charge one month\n * twice. A workspace that is locked is not charged (its card may be the\n * stolen one the lock is about): staff are alerted instead. Any failure\n * alerts staff and goes on.\n * 2. TURN IT OFF. Every store of the workspace with 4G on has cellular turned\n * off at Stripe, so the platform stops paying for readers nobody will be\n * charged for, and their periods are closed.\n *\n * Never fails the erasure: a refusal is a must alert. A dry run only counts.\n */\nexport function createPosCellularOrgEraser(\n deps: Pick<PosCellularBillingDeps, 'turnOff' | 'alert' | 'now' | 'config' | 'charge' | 'readBilling'> = {},\n): PluginOrgEraser {\n return async ({ orgId, dryRun }) => {\n const empty = { cellularStoresTurnedOff: 0, cellularTurnOffFailed: 0, cellularFinalMonthsCharged: 0, cellularFinalChargeFailed: 0 }\n if (!orgId) return empty\n const now = (deps.now ?? Date.now)()\n const alert = deps.alert ?? raiseOperatorAlert\n const snapshot = await recordsRef().where('orgId', '==', orgId).limit(500).get()\n const all = (snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>).map((doc) => ({\n id: String(doc.id),\n record: doc.data(),\n }))\n const records = all.filter(({ record }) => record.enabled)\n const stores = new Set(records.map(({ record }) => record.stripeConfigurationId).filter(Boolean)).size\n\n // 1. The final month (and last month, if it is still owed).\n const config = deps.config === undefined ? parsePosCellularConfig(process.env) : deps.config\n // The months with readers that no run has settled yet.\n const months: Array<{ month: string; readers: number }> = []\n for (const month of config ? [posCellularPreviousMonthKey(now), posCellularMonthKey(now)] : []) {\n const readers = posCellularReadersByWorkspace(all.map(({ record }) => record), month).get(orgId)?.readers ?? 0\n if (!readers) continue\n const existing = await chargesRef().doc(posCellularChargeId(orgId, month)).get()\n const state = existing.exists ? (existing.data() as PosCellularCharge).state : null\n if (!state || !POS_CELLULAR_SETTLED_STATES.includes(state)) months.push({ month, readers })\n }\n let charged = 0\n let chargeFailed = 0\n if (dryRun) return { ...empty, cellularStoresTurnedOff: stores, cellularFinalMonthsCharged: months.length }\n if (config && months.length) {\n const org = await firestore().collection('orgs').doc(orgId).get().catch(() => null)\n const locked = org?.exists ? normalizeOrgLockdown(org.data() as never) !== null : false\n for (const { month, readers } of months) {\n try {\n if (locked) {\n chargeFailed += 1\n await alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(readers),\n amount: formatOperatorAlertAmount(posCellularChargeCents(readers, config)),\n reason: 'the workspace is locked, so it was not charged as it was deleted',\n },\n })\n continue\n }\n const outcome = await chargeWorkspaceMonth(\n { orgId, month, readers, final: true },\n {\n config,\n now,\n charge: deps.charge ?? ((request: OrgUsageInvoiceRequest) => chargeOrgUsageInvoice(request)),\n readBilling:\n deps.readBilling ?? ((id: string) => readOrgBilling(id) as Promise<{ stripeCustomerId?: unknown }>),\n alert,\n },\n )\n if (outcome === 'paid') charged += 1\n else if (outcome !== 'settled') chargeFailed += 1\n } catch (error) {\n chargeFailed += 1\n console.error(`${LABEL}: the final month was not charged`, orgId, month, error)\n await alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(readers),\n amount: formatOperatorAlertAmount(posCellularChargeCents(readers, config)),\n reason: 'the charge failed as the workspace was deleted',\n },\n }).catch(() => undefined)\n }\n }\n }\n\n // 2. Off at Stripe, so the platform stops paying for it.\n if (!records.length) return { ...empty, cellularFinalMonthsCharged: charged, cellularFinalChargeFailed: chargeFailed }\n const { off, failed } = await turnOffConfigurations(\n records.map(({ record }) => record),\n { turnOff: deps.turnOff ?? turnOffPosCellularConfiguration, alert },\n )\n for (const { id, record } of records) await recordsRef().doc(id).set(closePosCellularPeriod(record, now))\n return {\n cellularStoresTurnedOff: off,\n cellularTurnOffFailed: failed,\n cellularFinalMonthsCharged: charged,\n cellularFinalChargeFailed: chargeFailed,\n }\n }\n}\n\n/** The eraser over the platform's own Firestore and Stripe, as the declarations register it. */\nexport const posCellularOrgEraser: PluginOrgEraser = (request) => createPosCellularOrgEraser()(request)\n"],"names":["normalizeOrgLockdown","formatOperatorAlertAmount","firebaseAdmin","raiseOperatorAlert","readOrgBilling","chargeOrgUsageInvoice","USAGE_INVOICE_MIN_CHARGE_CENTS","BUNDLE_ID","COMMERCE_POS_CELLULAR_CHARGE_FAILED","COMMERCE_POS_CELLULAR_TURN_OFF_FAILED","COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID","closePosCellularPeriod","parsePosCellularConfig","posCellularChargeCents","posCellularGraceEndsAtMs","posCellularMonthBounds","posCellularMonthKey","posCellularMonthLabel","posCellularOverdue","posCellularPreviousMonthKey","posCellularReadersByWorkspace","posCellularWarningDue","POS_CELLULAR_CHARGE_KIND","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","POS_CELLULAR_SETTLED_STATES","posCellularInvoiceStatus","settleSuspendedPosCellularCharge","turnOffPosCellularConfiguration","LABEL","CLAIM_STALE_MS","ALERT_AFTER_ATTEMPTS","firestore","app","recordsRef","collection","chargesRef","posCellularChargeId","orgId","month","recordsForMonth","startMs","on","off","Promise","all","where","limit","get","byId","Map","doc","docs","set","String","id","data","map","record","closeGoneStores","records","deps","now","open","filter","enabled","hostIds","Set","hostId","gone","host","exists","mine","turnOffConfigurations","configurations","stripeConfigurationId","failed","configurationId","done","turnOff","catch","alert","dedupeKey","context","error","console","claimMonth","readers","amountCents","ref","runTransaction","transaction","snapshot","existing","includes","state","updatedAtMs","attempts","claim","invoiceId","paidCents","createdAtMs","settleMonth","patch","merge","chargeWorkspaceMonth","input","billing","config","stored","final","raise","reason","amount","org","readBilling","stripeCustomerId","label","result","charge","productId","currency","description","metadata","pluginId","kind","idempotencyKey","ok","status","totalCents","amountPaidCents","requiresAction","Error","message","openedAtMs","runPosCellularBilling","gate","undefined","process","env","Date","report","workspaces","paid","unbillable","deferred","storesGone","paidLate","warned","turnedOff","request","bounds","byOrg","size","locked","isLocked","some","Boolean","outcome","grace","enforcePosCellularGrace","invoiceStatus","notify","notice","sendPosCellularTurnedOffNotice","warn","sendPosCellularPaymentDueNotice","invoice","settled","graceDays","warnPaymentDue","claimed","claimSuspension","finishSuspension","suspendedAtMs","claimWarning","Number","warnedAtMs","told","turnsOffAtMs","suspendedHostIds","length","suspension","atMs","add","terminal","cellularEnabled","cellularChangedAtMs","cellularChangedBy","cellularSuspended","recordId","noticeSentAtMs","turnedOffAtMs","Object","keys","createPosCellularOrgEraser","dryRun","empty","cellularStoresTurnedOff","cellularTurnOffFailed","cellularFinalMonthsCharged","cellularFinalChargeFailed","stores","months","push","charged","chargeFailed","posCellularOrgEraser"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,kCAAiC;AACtE,SAASC,yBAAyB,QAAQ,yCAAwC;AAGlF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,cAAc,QAAQ,2BAA0B;AAC5F,SACEC,qBAAqB,EACrBC,8BAA8B,QAGzB,gDAA+C;AACtD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,mCAAmC,EACnCC,qCAAqC,EACrCC,uCAAuC,QAClC,kCAA8B;AACrC,SACEC,sBAAsB,EACtBC,sBAAsB,EACtBC,sBAAsB,EACtBC,wBAAwB,EACxBC,sBAAsB,EACtBC,mBAAmB,EACnBC,qBAAqB,EACrBC,kBAAkB,EAClBC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,qBAAqB,EACrBC,wBAAwB,EACxBC,+BAA+B,EAC/BC,+BAA+B,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B0E,SAASqB;4BAClEI,QAAQ;wBACV;oBACF,GAAGhC,KAAK,CAAC,IAAMyD;gBACjB;YACF;QACF;QAEA,yDAAyD;QACzD,IAAI,CAAC7E,QAAQyH,MAAM,EAAE,OAAO,aAAKgB;YAAOG,4BAA4BK;YAASJ,2BAA2BK;;QACxG,MAAM,EAAEnK,GAAG,EAAEiC,MAAM,EAAE,GAAG,MAAMH,sBAC5Bb,QAAQH,GAAG,CAAC,CAAC,EAAEC,MAAM,EAAE,GAAKA,SAC5B;YAAEqB,OAAO,GAAElB,gBAAAA,KAAKkB,OAAO,YAAZlB,gBAAgBjC;YAAiCqD;QAAM;QAEpE,KAAK,MAAM,EAAE1B,EAAE,EAAEG,MAAM,EAAE,IAAIE,QAAS,MAAM1B,aAAaiB,GAAG,CAACI,IAAIF,GAAG,CAAC1C,uBAAuB+C,QAAQI;QACpG,OAAO;YACLwI,yBAAyB3J;YACzB4J,uBAAuB3H;YACvB4H,4BAA4BK;YAC5BJ,2BAA2BK;QAC7B;IACF;AACF;AAEA,8FAA8F,GAC9F,OAAO,MAAMC,uBAAwC,CAACzD,UAAY6C,6BAA6B7C,SAAQ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular-billing.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 { normalizeOrgLockdown } from '@aglyn/aglyn/app-utils/lockdown'\nimport { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport type { PluginOrgEraser } from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport type { PluginJobHostGate } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, raiseOperatorAlert, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport {\n chargeOrgUsageInvoice,\n USAGE_INVOICE_MIN_CHARGE_CENTS,\n type OrgUsageInvoiceRequest,\n type OrgUsageInvoiceResult,\n} from '@aglyn/tenant-data-admin/server/usage-invoice'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n COMMERCE_POS_CELLULAR_CHARGE_FAILED,\n COMMERCE_POS_CELLULAR_TURN_OFF_FAILED,\n COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID,\n} from '../constants/operator-alerts'\nimport {\n closePosCellularPeriod,\n parsePosCellularConfig,\n posCellularChargeCents,\n posCellularGraceEndsAtMs,\n posCellularMonthBounds,\n posCellularMonthKey,\n posCellularMonthLabel,\n posCellularOverdue,\n posCellularPreviousMonthKey,\n posCellularReadersByWorkspace,\n posCellularWarningDue,\n POS_CELLULAR_CHARGE_KIND,\n POS_CELLULAR_CHARGES_COLLECTION,\n POS_CELLULAR_READERS_COLLECTION,\n POS_CELLULAR_SETTLED_STATES,\n type PosCellularCharge,\n type PosCellularChargeState,\n type PosCellularConfig,\n type PosCellularReaderRecord,\n type PosCellularSuspension,\n} from '../model/pos-cellular'\nimport {\n posCellularInvoiceStatus,\n settleSuspendedPosCellularCharge,\n turnOffPosCellularConfiguration,\n} from './pos-cellular'\n\n/*==========================================\n * THE MONTHLY 4G CHARGE (AGL-4038).\n *\n * Once a day, for the calendar month that has just ended, each workspace\n * whose Stripe Reader S710s had 4G at any time in it is charged once: Stripe's\n * price per reader, plus what collecting it costs (`posCellularChargeCents`),\n * on a one-off invoice to its card through core's usage-invoice charge, the\n * path domains and AI overages take. That is the month Stripe bills the\n * platform for, in arrears, so a reader turned off on the 3rd is charged for\n * that month and not the next.\n *\n * Once per workspace per month: `posCellularCharges/{orgId}_{month}` is\n * claimed in a transaction before Stripe is called, and the invoice's\n * idempotency key is the same pair, so a run that died mid-charge and the\n * next day's run land on the same invoice. A charge that did not collect is\n * left open on the workspace's Billing page (nothing retries it) and staff\n * are alerted; a workspace with no one to bill is recorded and alerted, and\n * never charged later for that month.\n *\n * Daily rather than monthly: a month whose charge failed to START (Stripe\n * unreachable) is retried the next day; one that settled costs a read.\n *\n * A STORE THAT IS GONE stops costing the platform: a reader record whose\n * store no longer exists has its period closed and the store's Configuration\n * told to turn cellular off; a workspace being erased does the same for all\n * of its stores first ({@link posCellularOrgEraser}).\n *\n * WARN, THEN TURN OFF. A charge left open is asked about each day: paid\n * since, it is settled as paid; voided by staff, as voided. The first time\n * Stripe says it is still unpaid (the same run that left it open, unless\n * Stripe could not be asked), the members who manage the workspace's billing\n * are warned, once (`warnedAtMs`), of the amount and of the day 4G turns off\n * unless it is paid; paid before then, nothing else is sent. Still unpaid\n * once the grace period (`POS_CELLULAR_GRACE_DAYS`, 14 by default) has run\n * from the day it was left open, 4G is turned off at Stripe for every store\n * of the workspace, the members who manage its billing are emailed and\n * notified again, and staff are alerted. Stripe that cannot be asked is never\n * read as unpaid.\n * Paying does not turn 4G back on: the merchant does, once it is paid\n * (`pos-cellular.ts` refuses it until then). Each step is idempotent, so a run\n * that dies half-way is finished by the next.\n *\n * A WORKSPACE DELETED MID-MONTH is charged for that final month as it is\n * erased, before its data goes, through the same claim as the monthly run\n * (and last month too, if the run had not charged it yet), so the two never\n * charge one month twice. A failure there alerts staff and never holds the\n * erasure.\n *=========================================*/\n\nconst LABEL = '[pos-cellular] billing'\n\n/** A charge claimed this long ago and not settled was abandoned by its run. */\nconst CLAIM_STALE_MS = 30 * 60 * 1000\n\n/** How many times a charge that never reached Stripe is tried before staff hear of it. */\nconst ALERT_AFTER_ATTEMPTS = 3\n\ntype Charge = (request: OrgUsageInvoiceRequest) => Promise<OrgUsageInvoiceResult>\n\ntype InvoiceStatus = (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null>\n\nexport interface PosCellularBillingDeps {\n now?: () => number\n config?: PosCellularConfig | null\n charge?: Charge\n readBilling?: (orgId: string) => Promise<{ stripeCustomerId?: unknown }>\n turnOff?: (configurationId: string, stripeAccount?: string | null) => Promise<boolean>\n alert?: typeof raiseOperatorAlert\n /** Stripe's word on a charge's invoice now, or null when it cannot be asked. */\n invoiceStatus?: InvoiceStatus\n /** Tells the workspace 4G was turned off; true once told (or there is nobody to tell). */\n notify?: (notice: import('./pos-cellular-notify').PosCellularTurnedOffNotice) => Promise<boolean>\n /** Warns the workspace 4G turns off unless the charge is paid; true once told (or there is nobody to tell). */\n warn?: (notice: import('./pos-cellular-notify').PosCellularPaymentDueNotice) => Promise<boolean>\n}\n\nexport interface PosCellularBillingReport {\n month: string | null\n workspaces: number\n paid: number\n open: number\n failed: number\n unbillable: number\n deferred: number\n storesGone: number\n /** Open charges paid since, found by asking Stripe. */\n paidLate: number\n /** Workspaces warned that 4G turns off unless a charge left open is paid. */\n warned: number\n /** Workspaces whose 4G was turned off for a month unpaid past its grace. */\n turnedOff: number\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction recordsRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nfunction chargesRef() {\n return firestore().collection(POS_CELLULAR_CHARGES_COLLECTION)\n}\n\n/** A workspace's charge for one month, `{orgId}_{month}`: one per pair, so a rerun finds it. */\nfunction posCellularChargeId(orgId: string, month: string): string {\n return `${orgId}_${month}`\n}\n\n/** The reader records that may count for a month: on now, or turned off since it began. */\nasync function recordsForMonth(startMs: number): Promise<Array<{ id: string; record: PosCellularReaderRecord }>> {\n const [on, off] = await Promise.all([\n recordsRef().where('enabled', '==', true).limit(1_000).get(),\n recordsRef().where('disabledAtMs', '>=', startMs).limit(1_000).get(),\n ])\n const byId = new Map<string, PosCellularReaderRecord>()\n for (const doc of [...on.docs, ...off.docs] as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n byId.set(String(doc.id), doc.data())\n }\n return [...byId].map(([id, record]) => ({ id, record }))\n}\n\n/**\n * Closes the records of stores that no longer exist and turns cellular off\n * on their Configuration, alerting staff when Stripe refuses. Returns how\n * many stores it found gone.\n */\nasync function closeGoneStores(\n records: ReadonlyArray<{ id: string; record: PosCellularReaderRecord }>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n now: number,\n): Promise<number> {\n const open = records.filter(({ record }) => record.enabled)\n const hostIds = [...new Set(open.map(({ record }) => record.hostId))]\n let gone = 0\n for (const hostId of hostIds) {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (host.exists) continue\n gone += 1\n const mine = open.filter(({ record }) => record.hostId === hostId)\n await turnOffConfigurations(mine.map(({ record }) => record), deps)\n for (const { id, record } of mine) await recordsRef().doc(id).set(closePosCellularPeriod(record, now))\n }\n return gone\n}\n\n/** Turns cellular off on each distinct Configuration the records name, alerting a refusal. */\nasync function turnOffConfigurations(\n records: ReadonlyArray<PosCellularReaderRecord>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n): Promise<{ off: number; failed: number }> {\n const configurations = new Map<string, PosCellularReaderRecord>()\n for (const record of records) {\n if (record.stripeConfigurationId) configurations.set(record.stripeConfigurationId, record)\n }\n let off = 0\n let failed = 0\n for (const [configurationId, record] of configurations) {\n const done = await deps.turnOff(configurationId, record.stripeConfigurationAccount ?? null).catch(() => false)\n if (done) {\n off += 1\n continue\n }\n failed += 1\n await deps\n .alert(COMMERCE_POS_CELLULAR_TURN_OFF_FAILED, {\n dedupeKey: configurationId,\n orgId: record.orgId,\n hostId: record.hostId,\n context: { configurationId, hostId: record.hostId, orgId: record.orgId },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turn-off alert was not raised`, configurationId, error))\n }\n return { off, failed }\n}\n\n/**\n * Claims a workspace's month for this run, or says it is not this run's:\n * settled already, or claimed by a run still within its window. The claim\n * counts the attempt.\n */\nasync function claimMonth(\n orgId: string,\n month: string,\n readers: number,\n amountCents: number,\n now: number,\n): Promise<{ attempts: number } | null> {\n const ref = chargesRef().doc(posCellularChargeId(orgId, month))\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const existing = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (existing && POS_CELLULAR_SETTLED_STATES.includes(existing.state)) return null\n if (existing?.state === 'charging' && now - existing.updatedAtMs < CLAIM_STALE_MS) return null\n const attempts = (existing?.attempts ?? 0) + 1\n const claim: PosCellularCharge = {\n orgId,\n month,\n // The figures of the FIRST attempt stand: the invoice's key is the\n // month's, and Stripe refuses a key reused with other parameters.\n readers: existing?.readers ?? readers,\n amountCents: existing?.amountCents ?? amountCents,\n state: 'charging',\n invoiceId: existing?.invoiceId ?? null,\n paidCents: 0,\n attempts,\n createdAtMs: existing?.createdAtMs ?? now,\n updatedAtMs: now,\n }\n transaction.set(ref, claim)\n return { attempts }\n })\n}\n\nasync function settleMonth(\n orgId: string,\n month: string,\n patch: {\n state: PosCellularChargeState\n invoiceId?: string | null\n paidCents?: number\n openedAtMs?: number\n final?: boolean\n },\n now: number,\n): Promise<void> {\n await chargesRef()\n .doc(posCellularChargeId(orgId, month))\n .set({ ...patch, updatedAtMs: now }, { merge: true })\n}\n\ntype ChargeOutcome = 'paid' | 'open' | 'failed' | 'unbillable' | 'settled'\n\n/**\n * Charges one workspace's month once: claimed in a transaction first, so the\n * monthly run and a workspace erasure never both charge it, and keyed by the\n * month so a retried run lands on the same invoice. `final` marks the charge\n * an erasure made, which alerts staff at once on a failure, since nothing\n * retries it.\n */\nasync function chargeWorkspaceMonth(\n input: { orgId: string; month: string; readers: number; final?: boolean },\n context: {\n config: PosCellularConfig\n now: number\n charge: Charge\n readBilling: NonNullable<PosCellularBillingDeps['readBilling']>\n alert: typeof raiseOperatorAlert\n },\n): Promise<ChargeOutcome> {\n const { orgId, month, readers } = input\n const { config, now, alert } = context\n const amountCents = posCellularChargeCents(readers, config)\n const claim = await claimMonth(orgId, month, readers, amountCents, now)\n if (!claim) return 'settled'\n const stored = (await chargesRef().doc(posCellularChargeId(orgId, month)).get()).data() as PosCellularCharge\n const final = input.final ? { final: true } : {}\n const raise = (reason: string) =>\n alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(stored.readers),\n amount: formatOperatorAlertAmount(stored.amountCents),\n reason: input.final ? `${reason} (charged as the workspace was deleted)` : reason,\n },\n }).catch((error: unknown) => console.error(`${LABEL}: the alert was not raised`, orgId, error))\n\n const org = await firestore().collection('orgs').doc(orgId).get()\n if (!org.exists) {\n await settleMonth(orgId, month, { state: 'no-workspace', ...final }, now)\n if (input.final) await raise('the workspace was already gone')\n return 'unbillable'\n }\n if (stored.amountCents < USAGE_INVOICE_MIN_CHARGE_CENTS) {\n await settleMonth(orgId, month, { state: 'below-minimum', ...final }, now)\n return 'unbillable'\n }\n const billing = await context.readBilling(orgId).catch(() => ({}) as { stripeCustomerId?: unknown })\n const stripeCustomerId = String(billing.stripeCustomerId ?? '')\n if (!stripeCustomerId) {\n await settleMonth(orgId, month, { state: 'no-customer', ...final }, now)\n await raise('the workspace has no payment method on file')\n return 'unbillable'\n }\n const label = posCellularMonthLabel(month)\n const result = await context\n .charge({\n orgId,\n stripeCustomerId,\n productId: config.productId,\n amountCents: stored.amountCents,\n currency: 'usd',\n description: `4G for ${stored.readers} S710 card reader${stored.readers === 1 ? '' : 's'}, ${label}`,\n metadata: {\n orgId,\n pluginId: BUNDLE_ID,\n kind: POS_CELLULAR_CHARGE_KIND,\n month,\n readers: String(stored.readers),\n },\n idempotencyKey: `pos-cellular-${orgId}-${month}`,\n })\n .catch(\n (error: unknown): OrgUsageInvoiceResult => ({\n ok: false,\n invoiceId: null,\n status: null,\n totalCents: 0,\n amountPaidCents: 0,\n requiresAction: false,\n error: error instanceof Error ? error.message : 'the charge threw',\n }),\n )\n if (result.ok) {\n await settleMonth(orgId, month, { state: 'paid', invoiceId: result.invoiceId, paidCents: result.amountPaidCents, ...final }, now)\n return 'paid'\n }\n if (result.invoiceId) {\n // The invoice stays open on their Billing page, where they can pay it;\n // the grace period runs from today.\n await settleMonth(orgId, month, { state: 'open', invoiceId: result.invoiceId, openedAtMs: now, ...final }, now)\n await raise(result.requiresAction ? 'the card needs the cardholder to authenticate' : result.error || 'the card was declined')\n return 'open'\n }\n await settleMonth(orgId, month, { state: 'failed', ...final }, now)\n console.error(`${LABEL}: the charge did not reach Stripe`, orgId, month, result.error)\n // Nothing retries a charge made at erasure: staff hear of it now.\n if (input.final || claim.attempts >= ALERT_AFTER_ATTEMPTS) await raise(result.error || 'Stripe did not answer')\n return 'failed'\n}\n\n/** The charge of every workspace whose readers had 4G last month, once each. */\nexport async function runPosCellularBilling(\n gate: PluginJobHostGate,\n deps: PosCellularBillingDeps = {},\n): Promise<PosCellularBillingReport> {\n const config = deps.config === undefined ? parsePosCellularConfig(process.env) : deps.config\n const now = (deps.now ?? Date.now)()\n const report: PosCellularBillingReport = {\n month: null,\n workspaces: 0,\n paid: 0,\n open: 0,\n failed: 0,\n unbillable: 0,\n deferred: 0,\n storesGone: 0,\n paidLate: 0,\n warned: 0,\n turnedOff: 0,\n }\n if (!config) return report\n const charge = deps.charge ?? ((request: OrgUsageInvoiceRequest) => chargeOrgUsageInvoice(request))\n const readBilling = deps.readBilling ?? ((orgId: string) => readOrgBilling(orgId) as Promise<{ stripeCustomerId?: unknown }>)\n const alert = deps.alert ?? raiseOperatorAlert\n const turnOff = deps.turnOff ?? turnOffPosCellularConfiguration\n\n const month = posCellularPreviousMonthKey(now)\n report.month = month\n const bounds = posCellularMonthBounds(month) as { startMs: number; endMs: number }\n const records = await recordsForMonth(bounds.startMs)\n report.storesGone = await closeGoneStores(records, { turnOff, alert }, now)\n\n const byOrg = posCellularReadersByWorkspace(\n records.map(({ record }) => record),\n month,\n )\n report.workspaces = byOrg.size\n for (const [orgId, { readers, hostIds }] of byOrg) {\n // A store locked for security or abuse is charged nothing while it is:\n // its card may be the stolen one the lock is about. Tried again daily.\n const locked = await Promise.all(hostIds.map((hostId) => gate.isLocked(hostId).catch(() => true)))\n if (locked.some(Boolean)) {\n report.deferred += 1\n continue\n }\n const outcome = await chargeWorkspaceMonth({ orgId, month, readers }, { config, now, charge, readBilling, alert })\n if (outcome === 'paid') report.paid += 1\n else if (outcome === 'open') report.open += 1\n else if (outcome === 'failed') report.failed += 1\n else if (outcome === 'unbillable') report.unbillable += 1\n }\n\n const grace = await enforcePosCellularGrace({\n config,\n now,\n alert,\n turnOff,\n invoiceStatus: deps.invoiceStatus ?? posCellularInvoiceStatus,\n notify:\n deps.notify ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularTurnedOffNotice(notice)),\n warn:\n deps.warn ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularPaymentDueNotice(notice)),\n })\n report.paidLate = grace.paidLate\n report.warned = grace.warned\n report.turnedOff = grace.turnedOff\n return report\n}\n\n/**\n * WARN, THEN TURN OFF (AGL-4038): every charge left open is asked about at\n * Stripe; paid or voided since, it is settled so; still unpaid within its\n * grace, the workspace is warned once of the day 4G turns off; still unpaid\n * past it, 4G goes off for the workspace. A charge already suspended is\n * finished if a run died half-way (a store still on, nobody told yet) and\n * settled once paid.\n */\nasync function enforcePosCellularGrace(context: {\n config: PosCellularConfig\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string, stripeAccount?: string | null) => Promise<boolean>\n invoiceStatus: InvoiceStatus\n notify: NonNullable<PosCellularBillingDeps['notify']>\n warn: NonNullable<PosCellularBillingDeps['warn']>\n}): Promise<{ paidLate: number; warned: number; turnedOff: number }> {\n const { config, now } = context\n let paidLate = 0\n let warned = 0\n let turnedOff = 0\n for (const state of ['open', 'suspended'] as const) {\n const snapshot = await chargesRef().where('state', '==', state).limit(200).get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const id = String(doc.id)\n const stored = doc.data()\n const invoice = stored.invoiceId ? await context.invoiceStatus(stored.invoiceId).catch(() => null) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n const settled = invoice.status === 'paid' ? 'paid' : 'voided'\n if (state === 'suspended') {\n await settleSuspendedPosCellularCharge(id, stored, settled, invoice.amountPaidCents, now)\n } else {\n await settleMonth(stored.orgId, stored.month, { state: settled, ...(settled === 'paid' ? { paidCents: invoice.amountPaidCents } : {}) }, now)\n }\n if (settled === 'paid') paidLate += 1\n continue\n }\n // Stripe could not be asked: never read as unpaid.\n if (!invoice) continue\n if (state === 'open') {\n if (!posCellularOverdue(stored, config.graceDays, now)) {\n if (posCellularWarningDue(stored) && (await warnPaymentDue(id, context))) warned += 1\n continue\n }\n const claimed = await claimSuspension(id, now)\n if (!claimed) continue\n turnedOff += 1\n await context\n .alert(COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID, {\n dedupeKey: id,\n orgId: stored.orgId,\n context: {\n orgId: stored.orgId,\n month: posCellularMonthLabel(stored.month),\n amount: formatOperatorAlertAmount(stored.amountCents),\n graceDays: String(config.graceDays),\n },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turned-off alert was not raised`, id, error))\n }\n await finishSuspension(id, { ...stored, state: 'suspended', suspendedAtMs: stored.suspendedAtMs ?? now }, context)\n }\n }\n return { paidLate, warned, turnedOff }\n}\n\n/**\n * Claims the warning of an open charge, once: the charge as it stood, or null\n * when a run already warned of it or it is no longer open. The day its grace\n * counts from is pinned with the claim, so the day the warning states is the\n * day the turn-off keeps, even for a charge from before that day was stored.\n */\nasync function claimWarning(id: string, now: number): Promise<PosCellularCharge | null> {\n const ref = chargesRef().doc(id)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const charge = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (!charge || !posCellularWarningDue(charge)) return null\n const openedAtMs = Number(charge.openedAtMs ?? charge.updatedAtMs)\n transaction.set(ref, { warnedAtMs: now, openedAtMs, updatedAtMs: now }, { merge: true })\n return { ...charge, openedAtMs }\n })\n}\n\n/**\n * WARN AT THE START (AGL-4038): the members who manage the workspace's\n * billing are told the charge is due and the day 4G turns off for its stores\n * unless it is paid. Claimed before it is sent, so two runs never both send\n * it; a warning nobody could be sent is released for the next run to try.\n */\nasync function warnPaymentDue(\n id: string,\n context: { config: PosCellularConfig; now: number; warn: NonNullable<PosCellularBillingDeps['warn']> },\n): Promise<boolean> {\n const { config, now } = context\n const charge = await claimWarning(id, now)\n if (!charge) return false\n const told = await (async () => {\n // The stores that have 4G now, which lose it on that day.\n const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get()\n const hostIds = [\n ...new Set(\n (snapshot.docs as unknown as Array<{ data: () => PosCellularReaderRecord }>).map((doc) => doc.data().hostId),\n ),\n ]\n return context.warn({\n orgId: charge.orgId,\n month: charge.month,\n amount: formatOperatorAlertAmount(charge.amountCents),\n readers: charge.readers,\n openedAtMs: Number(charge.openedAtMs),\n turnsOffAtMs: posCellularGraceEndsAtMs(charge, config.graceDays),\n hostIds,\n })\n })().catch((error: unknown) => {\n console.error(`${LABEL}: the payment-due warning was not sent`, id, error)\n return false\n })\n if (!told) await chargesRef().doc(id).set({ warnedAtMs: null, updatedAtMs: now }, { merge: true })\n return told\n}\n\n/** Moves an open charge to `suspended`, once: false when a run already did, or it is no longer open. */\nasync function claimSuspension(id: string, now: number): Promise<boolean> {\n const ref = chargesRef().doc(id)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists || (snapshot.data() as PosCellularCharge).state !== 'open') return false\n transaction.set(ref, { state: 'suspended', suspendedAtMs: now, updatedAtMs: now }, { merge: true })\n return true\n })\n}\n\n/**\n * 4G off at Stripe for every store of the workspace that still has it, each\n * store's settings saying why, its readers' periods closed, and the workspace\n * told once. Safe to run again: a store already off and a notice already\n * sent are left alone.\n */\nasync function finishSuspension(\n id: string,\n charge: PosCellularCharge,\n context: {\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string, stripeAccount?: string | null) => Promise<boolean>\n notify: NonNullable<PosCellularBillingDeps['notify']>\n },\n): Promise<void> {\n const { now } = context\n const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get()\n const records = (snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>).map(\n (doc) => ({ id: String(doc.id), record: doc.data() }),\n )\n const hostIds = new Set(charge.suspendedHostIds ?? [])\n if (records.length) {\n await turnOffConfigurations(\n records.map(({ record }) => record),\n { turnOff: context.turnOff, alert: context.alert },\n )\n const suspension: PosCellularSuspension = { month: charge.month, invoiceId: charge.invoiceId, atMs: now }\n for (const hostId of new Set(records.map(({ record }) => record.hostId))) {\n hostIds.add(hostId)\n const terminal = firestore().collection('hosts').doc(hostId).collection('terminal').doc('config')\n if (!(await terminal.get()).exists) continue\n await terminal.set(\n { cellularEnabled: false, cellularChangedAtMs: now, cellularChangedBy: 'unpaid', cellularSuspended: suspension },\n { merge: true },\n )\n }\n for (const { id: recordId, record } of records) await recordsRef().doc(recordId).set(closePosCellularPeriod(record, now))\n }\n const patch: Partial<PosCellularCharge> = {}\n if (records.length || hostIds.size !== (charge.suspendedHostIds ?? []).length) patch.suspendedHostIds = [...hostIds]\n if (!charge.noticeSentAtMs) {\n const told = await context.notify({\n orgId: charge.orgId,\n month: charge.month,\n amount: formatOperatorAlertAmount(charge.amountCents),\n readers: charge.readers,\n openedAtMs: Number(charge.openedAtMs ?? charge.updatedAtMs),\n turnedOffAtMs: Number(charge.suspendedAtMs ?? now),\n hostIds: [...hostIds],\n })\n if (told) patch.noticeSentAtMs = now\n }\n // A suspension already finished, and still unpaid, writes nothing.\n if (Object.keys(patch).length) await chargesRef().doc(id).set({ ...patch, updatedAtMs: now }, { merge: true })\n}\n\n/**\n * Commerce's 4G share of a WORKSPACE erasure (AGL-4038), before its data\n * goes:\n *\n * 1. CHARGE IT. The month the workspace is deleted in is charged now, for\n * each S710 that had 4G in it, as the monthly run would have charged it a\n * month later; and last month too, if the run had not charged it yet.\n * Through the run's own claim and key, so the two never charge one month\n * twice. A workspace that is locked is not charged (its card may be the\n * stolen one the lock is about): staff are alerted instead. Any failure\n * alerts staff and goes on.\n * 2. TURN IT OFF. Every store of the workspace with 4G on has cellular turned\n * off at Stripe, so the platform stops paying for readers nobody will be\n * charged for, and their periods are closed.\n *\n * Never fails the erasure: a refusal is a must alert. A dry run only counts.\n */\nexport function createPosCellularOrgEraser(\n deps: Pick<PosCellularBillingDeps, 'turnOff' | 'alert' | 'now' | 'config' | 'charge' | 'readBilling'> = {},\n): PluginOrgEraser {\n return async ({ orgId, dryRun }) => {\n const empty = { cellularStoresTurnedOff: 0, cellularTurnOffFailed: 0, cellularFinalMonthsCharged: 0, cellularFinalChargeFailed: 0 }\n if (!orgId) return empty\n const now = (deps.now ?? Date.now)()\n const alert = deps.alert ?? raiseOperatorAlert\n const snapshot = await recordsRef().where('orgId', '==', orgId).limit(500).get()\n const all = (snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>).map((doc) => ({\n id: String(doc.id),\n record: doc.data(),\n }))\n const records = all.filter(({ record }) => record.enabled)\n const stores = new Set(records.map(({ record }) => record.stripeConfigurationId).filter(Boolean)).size\n\n // 1. The final month (and last month, if it is still owed).\n const config = deps.config === undefined ? parsePosCellularConfig(process.env) : deps.config\n // The months with readers that no run has settled yet.\n const months: Array<{ month: string; readers: number }> = []\n for (const month of config ? [posCellularPreviousMonthKey(now), posCellularMonthKey(now)] : []) {\n const readers = posCellularReadersByWorkspace(all.map(({ record }) => record), month).get(orgId)?.readers ?? 0\n if (!readers) continue\n const existing = await chargesRef().doc(posCellularChargeId(orgId, month)).get()\n const state = existing.exists ? (existing.data() as PosCellularCharge).state : null\n if (!state || !POS_CELLULAR_SETTLED_STATES.includes(state)) months.push({ month, readers })\n }\n let charged = 0\n let chargeFailed = 0\n if (dryRun) return { ...empty, cellularStoresTurnedOff: stores, cellularFinalMonthsCharged: months.length }\n if (config && months.length) {\n const org = await firestore().collection('orgs').doc(orgId).get().catch(() => null)\n const locked = org?.exists ? normalizeOrgLockdown(org.data() as never) !== null : false\n for (const { month, readers } of months) {\n try {\n if (locked) {\n chargeFailed += 1\n await alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(readers),\n amount: formatOperatorAlertAmount(posCellularChargeCents(readers, config)),\n reason: 'the workspace is locked, so it was not charged as it was deleted',\n },\n })\n continue\n }\n const outcome = await chargeWorkspaceMonth(\n { orgId, month, readers, final: true },\n {\n config,\n now,\n charge: deps.charge ?? ((request: OrgUsageInvoiceRequest) => chargeOrgUsageInvoice(request)),\n readBilling:\n deps.readBilling ?? ((id: string) => readOrgBilling(id) as Promise<{ stripeCustomerId?: unknown }>),\n alert,\n },\n )\n if (outcome === 'paid') charged += 1\n else if (outcome !== 'settled') chargeFailed += 1\n } catch (error) {\n chargeFailed += 1\n console.error(`${LABEL}: the final month was not charged`, orgId, month, error)\n await alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(readers),\n amount: formatOperatorAlertAmount(posCellularChargeCents(readers, config)),\n reason: 'the charge failed as the workspace was deleted',\n },\n }).catch(() => undefined)\n }\n }\n }\n\n // 2. Off at Stripe, so the platform stops paying for it.\n if (!records.length) return { ...empty, cellularFinalMonthsCharged: charged, cellularFinalChargeFailed: chargeFailed }\n const { off, failed } = await turnOffConfigurations(\n records.map(({ record }) => record),\n { turnOff: deps.turnOff ?? turnOffPosCellularConfiguration, alert },\n )\n for (const { id, record } of records) await recordsRef().doc(id).set(closePosCellularPeriod(record, now))\n return {\n cellularStoresTurnedOff: off,\n cellularTurnOffFailed: failed,\n cellularFinalMonthsCharged: charged,\n cellularFinalChargeFailed: chargeFailed,\n }\n }\n}\n\n/** The eraser over the platform's own Firestore and Stripe, as the declarations register it. */\nexport const posCellularOrgEraser: PluginOrgEraser = (request) => createPosCellularOrgEraser()(request)\n"],"names":["normalizeOrgLockdown","formatOperatorAlertAmount","firebaseAdmin","raiseOperatorAlert","readOrgBilling","chargeOrgUsageInvoice","USAGE_INVOICE_MIN_CHARGE_CENTS","BUNDLE_ID","COMMERCE_POS_CELLULAR_CHARGE_FAILED","COMMERCE_POS_CELLULAR_TURN_OFF_FAILED","COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID","closePosCellularPeriod","parsePosCellularConfig","posCellularChargeCents","posCellularGraceEndsAtMs","posCellularMonthBounds","posCellularMonthKey","posCellularMonthLabel","posCellularOverdue","posCellularPreviousMonthKey","posCellularReadersByWorkspace","posCellularWarningDue","POS_CELLULAR_CHARGE_KIND","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","POS_CELLULAR_SETTLED_STATES","posCellularInvoiceStatus","settleSuspendedPosCellularCharge","turnOffPosCellularConfiguration","LABEL","CLAIM_STALE_MS","ALERT_AFTER_ATTEMPTS","firestore","app","recordsRef","collection","chargesRef","posCellularChargeId","orgId","month","recordsForMonth","startMs","on","off","Promise","all","where","limit","get","byId","Map","doc","docs","set","String","id","data","map","record","closeGoneStores","records","deps","now","open","filter","enabled","hostIds","Set","hostId","gone","host","exists","mine","turnOffConfigurations","configurations","stripeConfigurationId","failed","configurationId","done","turnOff","stripeConfigurationAccount","catch","alert","dedupeKey","context","error","console","claimMonth","readers","amountCents","ref","runTransaction","transaction","snapshot","existing","includes","state","updatedAtMs","attempts","claim","invoiceId","paidCents","createdAtMs","settleMonth","patch","merge","chargeWorkspaceMonth","input","billing","config","stored","final","raise","reason","amount","org","readBilling","stripeCustomerId","label","result","charge","productId","currency","description","metadata","pluginId","kind","idempotencyKey","ok","status","totalCents","amountPaidCents","requiresAction","Error","message","openedAtMs","runPosCellularBilling","gate","undefined","process","env","Date","report","workspaces","paid","unbillable","deferred","storesGone","paidLate","warned","turnedOff","request","bounds","byOrg","size","locked","isLocked","some","Boolean","outcome","grace","enforcePosCellularGrace","invoiceStatus","notify","notice","sendPosCellularTurnedOffNotice","warn","sendPosCellularPaymentDueNotice","invoice","settled","graceDays","warnPaymentDue","claimed","claimSuspension","finishSuspension","suspendedAtMs","claimWarning","Number","warnedAtMs","told","turnsOffAtMs","suspendedHostIds","length","suspension","atMs","add","terminal","cellularEnabled","cellularChangedAtMs","cellularChangedBy","cellularSuspended","recordId","noticeSentAtMs","turnedOffAtMs","Object","keys","createPosCellularOrgEraser","dryRun","empty","cellularStoresTurnedOff","cellularTurnOffFailed","cellularFinalMonthsCharged","cellularFinalChargeFailed","stores","months","push","charged","chargeFailed","posCellularOrgEraser"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,kCAAiC;AACtE,SAASC,yBAAyB,QAAQ,yCAAwC;AAGlF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,cAAc,QAAQ,2BAA0B;AAC5F,SACEC,qBAAqB,EACrBC,8BAA8B,QAGzB,gDAA+C;AACtD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,mCAAmC,EACnCC,qCAAqC,EACrCC,uCAAuC,QAClC,kCAA8B;AACrC,SACEC,sBAAsB,EACtBC,sBAAsB,EACtBC,sBAAsB,EACtBC,wBAAwB,EACxBC,sBAAsB,EACtBC,mBAAmB,EACnBC,qBAAqB,EACrBC,kBAAkB,EAClBC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,qBAAqB,EACrBC,wBAAwB,EACxBC,+BAA+B,EAC/BC,+BAA+B,EAC/BC,2BAA2B,QAMtB,2BAAuB;AAC9B,SACEC,wBAAwB,EACxBC,gCAAgC,EAChCC,+BAA+B,QAC1B,oBAAgB;AAEvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA+C2C,GAE3C,MAAMC,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AQ0H,MAAM,EAAE,OAAO,aAAKgB;YAAOG,4BAA4BK;YAASJ,2BAA2BK;;QACxG,MAAM,EAAEpK,GAAG,EAAEiC,MAAM,EAAE,GAAG,MAAMH,sBAC5Bb,QAAQH,GAAG,CAAC,CAAC,EAAEC,MAAM,EAAE,GAAKA,SAC5B;YAAEqB,OAAO,GAAElB,gBAAAA,KAAKkB,OAAO,YAAZlB,gBAAgBjC;YAAiCsD;QAAM;QAEpE,KAAK,MAAM,EAAE3B,EAAE,EAAEG,MAAM,EAAE,IAAIE,QAAS,MAAM1B,aAAaiB,GAAG,CAACI,IAAIF,GAAG,CAAC1C,uBAAuB+C,QAAQI;QACpG,OAAO;YACLyI,yBAAyB5J;YACzB6J,uBAAuB5H;YACvB6H,4BAA4BK;YAC5BJ,2BAA2BK;QAC7B;IACF;AACF;AAEA,8FAA8F,GAC9F,OAAO,MAAMC,uBAAwC,CAACzD,UAAY6C,6BAA6B7C,SAAQ"}
|
|
@@ -85,4 +85,6 @@ export declare function setPosStoreCellular(staff: PosStaff, body: Record<string
|
|
|
85
85
|
* or workspace that is being deleted, whose settings may be gone already.
|
|
86
86
|
* True when Stripe took it, or the Configuration no longer exists.
|
|
87
87
|
*/
|
|
88
|
-
export declare function turnOffPosCellularConfiguration(configurationId: string
|
|
88
|
+
export declare function turnOffPosCellularConfiguration(configurationId: string,
|
|
89
|
+
/** The store's own account the Configuration is on; null for the platform. */
|
|
90
|
+
stripeAccount?: string | null): Promise<boolean>;
|