@aglyn/plugins-commerce 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +38 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +282 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +32 -8
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +27 -16
- package/src/lib/model/commerce-payment-methods.js +11 -83
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +27 -6
- package/src/lib/server/billing-webhook.js +271 -81
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +105 -23
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +98 -26
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +36 -7
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +111 -27
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-methods.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { checkEntitlement, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport type { SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n isStorefrontPaymentMethodOn,\n normalizeStorefrontPaymentMethodSettings,\n STOREFRONT_PAYMENT_METHODS,\n type StorefrontPaymentMethodId,\n type StorefrontPaymentMethodSettings,\n} from '../model/commerce-payment-methods'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport {\n type PaymentMethodDomainRecord,\n readSiteDomainRecords,\n} from './payment-method-domains'\n\n/**\n * The merchant's payment methods card (AGL-3629):\n * `GET|POST /api/commerce/payment-methods?hostId=…`, served by the console.\n *\n * GET answers, per method, three facts the card needs and no client can read:\n *\n * - whether the PLATFORM offers it (its default payment method configuration\n * — storefront charges are destination charges with the platform as\n * merchant of record, so that configuration is the ceiling). A method the\n * platform has not turned on, or that Stripe has not made available to it,\n * is reported `unavailable` and the card does not show it at all;\n * - the connected account's capability for it, which Stripe asks platforms to\n * request before an account accepts BNPL, Cash App, Amazon Pay or crypto;\n * - the site's domain registrations, which Apple Pay depends on.\n *\n * POST saves the toggles to `hosts/{hostId}/settings/store.paymentMethods` and\n * requests the capability of each method turned on, in one account update with\n * an idempotency key. Server-side, because the toggle and the capability are\n * one decision: a toggle saved by the browser with no capability behind it\n * would read as on and never appear.\n */\n\nexport type PlatformAvailability = 'on' | 'unavailable' | null\n\nexport type CapabilityStatus = 'active' | 'pending' | 'inactive' | 'unrequested' | null\n\nexport interface PaymentMethodRow {\n id: StorefrontPaymentMethodId\n on: boolean\n platform: PlatformAvailability\n capability: CapabilityStatus\n}\n\nexport interface PaymentMethodsAnswer {\n methods: PaymentMethodRow[]\n domains: PaymentMethodDomainRecord[]\n accountConnected: boolean\n /** The caller may save toggles: a site admin. */\n canEdit: boolean\n /** The caller may open Stripe to finish a method: the organization owner. */\n canFinish: boolean\n warnings: string[]\n}\n\n/** How long the platform's configuration is trusted in memory. */\nconst PLATFORM_CONFIGURATION_TTL_MS = 10 * 60 * 1000\n\nlet platformCache: { at: number; value: Record<string, PlatformAvailability> } | null = null\n\n/** Test seam: forget the cached platform configuration. */\nexport function resetPlatformPaymentMethodCacheForTests(): void {\n platformCache = null\n}\n\nasync function stripe<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: URLSearchParams,\n idempotencyKey?: string,\n): Promise<T> {\n const query = method === 'GET' && params ? `?${params}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && { 'Content-Type': 'application/x-www-form-urlencoded' }),\n ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: params.toString() }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\ninterface StripeConfiguration {\n is_default?: boolean\n application?: string | null\n active?: boolean\n [key: string]: unknown\n}\n\n/**\n * Which methods the platform's own default configuration offers. The list\n * also returns configurations OTHER Connect applications made for this\n * account (`application` set); those do not govern our sessions and are\n * skipped. `null` per method when Stripe could not be asked — the card then\n * shows the toggle without a verdict rather than hiding a method that may work.\n */\nexport async function platformPaymentMethodAvailability(): Promise<\n Record<string, PlatformAvailability>\n> {\n if (platformCache && Date.now() - platformCache.at < PLATFORM_CONFIGURATION_TTL_MS) {\n return platformCache.value\n }\n const value: Record<string, PlatformAvailability> = {}\n try {\n const list = await stripe<{ data?: StripeConfiguration[] }>(\n 'GET',\n 'payment_method_configurations',\n new URLSearchParams({ limit: '20' }),\n )\n const own =\n list.data?.find((entry) => entry.is_default && !entry.application) ??\n list.data?.find((entry) => !entry.application) ??\n null\n for (const method of STOREFRONT_PAYMENT_METHODS) {\n if (!own) {\n value[method.id] = null\n continue\n }\n const entry = own[method.configurationKey] as\n | { available?: boolean; display_preference?: { value?: string } }\n | undefined\n value[method.id] =\n entry?.available === true && entry?.display_preference?.value === 'on'\n ? 'on'\n : 'unavailable'\n }\n platformCache = { at: Date.now(), value }\n } catch (error) {\n console.warn('[commerce] payment method configuration unreadable', error)\n for (const method of STOREFRONT_PAYMENT_METHODS) value[method.id] = null\n }\n return value\n}\n\nfunction capabilityStatus(\n capabilities: Record<string, string> | undefined,\n key: string | undefined,\n): CapabilityStatus {\n if (!key) return null\n const status = capabilities?.[key]\n if (status === 'active' || status === 'pending' || status === 'inactive') return status\n return 'unrequested'\n}\n\nasync function readAccountCapabilities(\n accountId: string | null,\n): Promise<Record<string, string> | undefined> {\n if (!accountId) return undefined\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'GET',\n `accounts/${encodeURIComponent(accountId)}`,\n )\n return account.capabilities ?? {}\n } catch (error) {\n console.warn('[commerce] connected account unreadable', error)\n return undefined\n }\n}\n\n/** The capabilities a save asks Stripe for: on, offered, not yet requested. */\nexport function capabilitiesToRequest(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): string[] {\n return STOREFRONT_PAYMENT_METHODS.filter(\n (method) =>\n method.capability &&\n isStorefrontPaymentMethodOn(settings, method.id) &&\n platform[method.id] !== 'unavailable' &&\n capabilityStatus(capabilities, method.capability) === 'unrequested',\n ).map((method) => method.capability as string)\n}\n\nexport function buildPaymentMethodRows(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): PaymentMethodRow[] {\n return STOREFRONT_PAYMENT_METHODS.map((method) => ({\n id: method.id,\n on: isStorefrontPaymentMethodOn(settings, method.id),\n platform: platform[method.id] ?? null,\n capability: capabilities ? capabilityStatus(capabilities, method.capability) : null,\n }))\n}\n\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\n\n/**\n * Where Stripe sends the owner back: the console page they pressed the button\n * on, judged against the request's own origin so a forged `Referer` cannot\n * turn the link into a redirect to somewhere else.\n */\nexport function consoleReturnUrl(headers: Partial<Record<string, string>>): string {\n const origin = headers.origin || (headers.host ? `https://${headers.host}` : '')\n const referer = headers.referer ?? ''\n try {\n if (origin && referer && new URL(referer).origin === new URL(origin).origin) {\n return referer\n }\n } catch {\n // Unparseable: fall through to the origin.\n }\n return origin || 'https://localhost/'\n}\n\nexport async function paymentMethodsHandler(request: Request): Promise<Response> {\n const { method, headers: rawHeaders, query, body } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET' && method !== 'POST') {\n return json({ error: 'Method not allowed' }, 405)\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' }, 501)\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const parsed =\n typeof body === 'string' ? (JSON.parse(body || '{}') as Record<string, unknown>) : (body ?? {})\n const hostId = String(\n (method === 'GET' ? query?.['hostId'] : (parsed as Record<string, unknown>)['hostId']) ?? '',\n )\n if (!hostId) return json({ error: 'Missing hostId' }, 400)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return json({ error: 'Not found' }, 404)\n\n // An allowlist. Reading the card is for whoever works the store's orders\n // or changes its methods; a change asks Stripe for capabilities on the\n // owner's payout account, so it is \"Manage payment methods\" (AGL-4047),\n // whose preset is the site Admin who alone made it before, as the\n // reader's is the Admin and Editor.\n const mayEdit = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.paymentMethods')\n const mayRead = mayEdit || holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')\n if (!mayRead) return json({ error: 'Not found' }, 404)\n if (method === 'POST' && !mayEdit) {\n return json({ error: commerceSitePermissionRefusal('commerce.paymentMethods') }, 403)\n }\n\n const owner = await getOrgForHost(hostId)\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org: owner?.org,\n host: hostSnapshot.data(),\n })\n if (locked) return locked\n if (!checkEntitlement((owner?.org ?? {}) as never, 'commerce')) {\n return json({ error: 'Selling is not included on this plan' }, 402)\n }\n\n const ownerUid = String(owner?.org?.ownerUid ?? '')\n const accountId = ownerUid\n ? (((await firestore.collection('profiles').doc(ownerUid).get()).get(\n 'stripeAccountId',\n ) as string | undefined) ?? null)\n : null\n\n const storeRef = hostRef.collection('settings').doc('store')\n let settings = normalizeStorefrontPaymentMethodSettings(\n (await storeRef.get()).get('paymentMethods'),\n )\n const platform = await platformPaymentMethodAvailability()\n let capabilities = await readAccountCapabilities(accountId)\n const warnings: string[] = []\n\n // FINISH IN STRIPE: a capability Stripe holds `inactive` needs details\n // only the account holder can give, and an Express account has no login of\n // its own, so a link minted here is the only way in. The owner's alone,\n // as connecting the account is (`connect.ts`): the link opens the owner's\n // identity and bank details.\n if (method === 'POST' && (parsed as Record<string, unknown>)['action'] === 'finish') {\n if (!accountId || decoded.uid !== ownerUid) {\n return json({ error: 'Only the organization owner can finish this in Stripe' }, 403)\n }\n const back = consoleReturnUrl(headers)\n const link = await stripe<{ url?: string }>(\n 'POST',\n 'account_links',\n new URLSearchParams({\n account: accountId,\n type: 'account_onboarding',\n 'collection_options[fields]': 'currently_due',\n refresh_url: back,\n return_url: back,\n }),\n )\n return json({ url: link.url ?? null })\n }\n\n if (method === 'POST') {\n const requested = normalizeStorefrontPaymentMethodSettings(\n (parsed as Record<string, unknown>)['methods'],\n )\n if (!Object.keys(requested).length) {\n return json({ error: 'Nothing to save' }, 400)\n }\n settings = { ...settings, ...requested }\n await storeRef.set(\n { paymentMethods: settings, paymentMethodsUpdatedAtMs: Date.now(), paymentMethodsUpdatedBy: decoded.uid },\n { merge: true },\n )\n const wanted = accountId ? capabilitiesToRequest(settings, platform, capabilities) : []\n if (accountId && wanted.length) {\n const params = new URLSearchParams()\n for (const capability of wanted) {\n params.set(`capabilities[${capability}][requested]`, 'true')\n }\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'POST',\n `accounts/${encodeURIComponent(accountId)}`,\n params,\n `aglyn-pm-capabilities:${accountId}:${[...wanted].sort().join(',')}`,\n )\n capabilities = account.capabilities ?? capabilities\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n warnings.push(\n `Stripe did not accept the request to enable ${wanted.join(', ')} on your payout account: ${message}`,\n )\n }\n }\n }\n\n const answer: PaymentMethodsAnswer = {\n methods: buildPaymentMethodRows(settings, platform, capabilities),\n domains: await readSiteDomainRecords(hostSnapshot.data() as SiteReturnHost | undefined),\n accountConnected: Boolean(accountId),\n canEdit: mayEdit,\n canFinish: Boolean(accountId) && decoded.uid === ownerUid,\n warnings,\n }\n return json(answer)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error(error)\n return json({ error: 'Payment methods could not be loaded' }, 500)\n }\n}\n"],"names":["checkEntitlement","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","lockdownRefusal","invalidIdTokenResponse","isStorefrontPaymentMethodOn","normalizeStorefrontPaymentMethodSettings","STOREFRONT_PAYMENT_METHODS","commerceSitePermissionRefusal","holdsCommerceSiteKey","readSiteDomainRecords","PLATFORM_CONFIGURATION_TTL_MS","platformCache","resetPlatformPaymentMethodCacheForTests","stripe","method","path","params","idempotencyKey","query","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","catch","ok","Error","error","message","status","platformPaymentMethodAvailability","Date","now","at","value","list","URLSearchParams","limit","own","data","find","entry","is_default","application","id","configurationKey","available","display_preference","console","warn","capabilityStatus","capabilities","key","readAccountCapabilities","accountId","undefined","account","encodeURIComponent","capabilitiesToRequest","settings","platform","filter","capability","map","buildPaymentMethodRows","on","Response","consoleReturnUrl","origin","host","referer","URL","paymentMethodsHandler","request","rawHeaders","authorization","idToken","startsWith","slice","length","parsed","JSON","parse","hostId","String","owner","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","hostSnapshot","get","exists","mayEdit","uid","mayRead","locked","staff","org","ownerUid","storeRef","warnings","link","back","type","refresh_url","return_url","url","requested","Object","keys","set","paymentMethods","paymentMethodsUpdatedAtMs","paymentMethodsUpdatedBy","merge","wanted","sort","join","push","answer","methods","domains","accountConnected","Boolean","canEdit","canFinish","unauthenticated"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,gBAAgB,EAAEC,oBAAoB,QAAQ,sBAAqB;AAE5E,SACEC,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,QACV,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,2BAA2B,EAC3BC,wCAAwC,EACxCC,0BAA0B,QAGrB,uCAAmC;AAC1C,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAEEC,qBAAqB,QAChB,8BAA0B;AA8CjC,gEAAgE,GAChE,MAAMC,gCAAgC,KAAK,KAAK;AAEhD,IAAIC,gBAAoF;AAExF,yDAAyD,GACzD,OAAO,SAASC;IACdD,gBAAgB;AAClB;AAEA,eAAeE,OACbC,MAAsB,EACtBC,IAAY,EACZC,MAAwB,EACxBC,cAAuB;IAEvB,MAAMC,QAAQJ,WAAW,SAASE,SAAS,CAAC,CAAC,EAAEA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oBAEtExE,gBAAeK,wBAAAA,QAAQL,YAAY,YAApBK,wBAAwBL;gBACzC,EAAE,OAAOxB,OAAO;oBACd,MAAMC,UAAUD,iBAAiBD,QAAQC,MAAMC,OAAO,GAAGwD,OAAOzD;oBAChE+E,SAASkB,IAAI,CACX,CAAC,4CAA4C,EAAEH,OAAOE,IAAI,CAAC,MAAM,yBAAyB,EAAE/F,SAAS;gBAEzG;YACF;QACF;QAEA,MAAMiG,SAA+B;YACnCC,SAAS9D,uBAAuBL,UAAUC,UAAUT;YACpD4E,SAAS,MAAM5H,sBAAsB4F,aAAaxD,IAAI;YACtDyF,kBAAkBC,QAAQ3E;YAC1B4E,SAAShC;YACTiC,WAAWF,QAAQ3E,cAAcgC,QAAQa,GAAG,KAAKK;YACjDE;QACF;QACA,OAAOnF,KAAKsG;IACd,EAAE,OAAOlG,OAAO;QACd,MAAMyG,kBAAkBvI,uBAAuB8B;QAC/C,IAAIyG,iBAAiB,OAAOA;QAC5BpF,QAAQrB,KAAK,CAACA;QACd,OAAOJ,KAAK;YAAEI,OAAO;QAAsC,GAAG;IAChE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/payment-methods.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 { directSellerAccountForHost } from './seller-stripe-account'\nimport { checkEntitlement, pluginRequestFromWeb } from '@aglyn/aglyn/server'\nimport type { SiteReturnHost } from '@aglyn/aglyn/app-utils/site-return-url'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n lockdownRefusal,\n} from '@aglyn/tenant-data-admin'\nimport { invalidIdTokenResponse } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n isStorefrontPaymentMethodOn,\n normalizeStorefrontPaymentMethodSettings,\n STOREFRONT_PAYMENT_METHODS,\n type StorefrontPaymentMethodId,\n type StorefrontPaymentMethodSettings,\n} from '../model/commerce-payment-methods'\nimport { commerceSitePermissionRefusal } from '../model/plugin-permissions'\nimport { holdsCommerceSiteKey } from './commerce-site-keys'\nimport {\n type PaymentMethodDomainRecord,\n readSiteDomainRecords,\n} from './payment-method-domains'\n\n/**\n * The merchant's payment methods card (AGL-3629):\n * `GET|POST /api/commerce/payment-methods?hostId=…`, served by the console.\n *\n * GET answers, per method, three facts the card needs and no client can read:\n *\n * - whether the PLATFORM offers it (its default payment method configuration\n * — storefront charges are destination charges with the platform as\n * merchant of record, so that configuration is the ceiling). A method the\n * platform has not turned on, or that Stripe has not made available to it,\n * is reported `unavailable` and the card does not show it at all;\n * - the connected account's capability for it, which Stripe asks platforms to\n * request before an account accepts BNPL, Cash App, Amazon Pay or crypto;\n * - the site's domain registrations, which Apple Pay depends on.\n *\n * POST saves the toggles to `hosts/{hostId}/settings/store.paymentMethods` and\n * requests the capability of each method turned on, in one account update with\n * an idempotency key. Server-side, because the toggle and the capability are\n * one decision: a toggle saved by the browser with no capability behind it\n * would read as on and never appear.\n */\n\nexport type PlatformAvailability = 'on' | 'unavailable' | null\n\nexport type CapabilityStatus = 'active' | 'pending' | 'inactive' | 'unrequested' | null\n\nexport interface PaymentMethodRow {\n id: StorefrontPaymentMethodId\n on: boolean\n platform: PlatformAvailability\n capability: CapabilityStatus\n}\n\nexport interface PaymentMethodsAnswer {\n methods: PaymentMethodRow[]\n domains: PaymentMethodDomainRecord[]\n accountConnected: boolean\n /** The caller may save toggles: a site admin. */\n canEdit: boolean\n /** The caller may open Stripe to finish a method: the organization owner. */\n canFinish: boolean\n warnings: string[]\n}\n\n/** How long the platform's configuration is trusted in memory. */\nconst PLATFORM_CONFIGURATION_TTL_MS = 10 * 60 * 1000\n\nlet platformCache: { at: number; value: Record<string, PlatformAvailability> } | null = null\n\n/** Test seam: forget the cached platform configuration. */\nexport function resetPlatformPaymentMethodCacheForTests(): void {\n platformCache = null\n}\n\nasync function stripe<T>(\n method: 'GET' | 'POST',\n path: string,\n params?: URLSearchParams,\n idempotencyKey?: string,\n): Promise<T> {\n const query = method === 'GET' && params ? `?${params}` : ''\n const response = await fetch(`https://api.stripe.com/v1/${path}${query}`, {\n method,\n headers: {\n Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,\n ...(method === 'POST' && { 'Content-Type': 'application/x-www-form-urlencoded' }),\n ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),\n },\n ...(method === 'POST' && params && { body: params.toString() }),\n })\n const payload = (await response.json().catch(() => ({}))) as T & {\n error?: { message?: string }\n }\n if (!response.ok) {\n throw new Error(payload?.error?.message ?? `Stripe ${path} failed (${response.status})`)\n }\n return payload\n}\n\ninterface StripeConfiguration {\n is_default?: boolean\n application?: string | null\n active?: boolean\n [key: string]: unknown\n}\n\n/**\n * Which methods the platform's own default configuration offers. The list\n * also returns configurations OTHER Connect applications made for this\n * account (`application` set); those do not govern our sessions and are\n * skipped. `null` per method when Stripe could not be asked — the card then\n * shows the toggle without a verdict rather than hiding a method that may work.\n */\nexport async function platformPaymentMethodAvailability(): Promise<\n Record<string, PlatformAvailability>\n> {\n if (platformCache && Date.now() - platformCache.at < PLATFORM_CONFIGURATION_TTL_MS) {\n return platformCache.value\n }\n const value: Record<string, PlatformAvailability> = {}\n try {\n const list = await stripe<{ data?: StripeConfiguration[] }>(\n 'GET',\n 'payment_method_configurations',\n new URLSearchParams({ limit: '20' }),\n )\n const own =\n list.data?.find((entry) => entry.is_default && !entry.application) ??\n list.data?.find((entry) => !entry.application) ??\n null\n for (const method of STOREFRONT_PAYMENT_METHODS) {\n if (!own) {\n value[method.id] = null\n continue\n }\n const entry = own[method.configurationKey] as\n | { available?: boolean; display_preference?: { value?: string } }\n | undefined\n value[method.id] =\n entry?.available === true && entry?.display_preference?.value === 'on'\n ? 'on'\n : 'unavailable'\n }\n platformCache = { at: Date.now(), value }\n } catch (error) {\n console.warn('[commerce] payment method configuration unreadable', error)\n for (const method of STOREFRONT_PAYMENT_METHODS) value[method.id] = null\n }\n return value\n}\n\nfunction capabilityStatus(\n capabilities: Record<string, string> | undefined,\n key: string | undefined,\n): CapabilityStatus {\n if (!key) return null\n const status = capabilities?.[key]\n if (status === 'active' || status === 'pending' || status === 'inactive') return status\n return 'unrequested'\n}\n\nasync function readAccountCapabilities(\n accountId: string | null,\n): Promise<Record<string, string> | undefined> {\n if (!accountId) return undefined\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'GET',\n `accounts/${encodeURIComponent(accountId)}`,\n )\n return account.capabilities ?? {}\n } catch (error) {\n console.warn('[commerce] connected account unreadable', error)\n return undefined\n }\n}\n\n/** The capabilities a save asks Stripe for: on, offered, not yet requested. */\nexport function capabilitiesToRequest(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): string[] {\n return STOREFRONT_PAYMENT_METHODS.filter(\n (method) =>\n method.capability &&\n isStorefrontPaymentMethodOn(settings, method.id) &&\n platform[method.id] !== 'unavailable' &&\n capabilityStatus(capabilities, method.capability) === 'unrequested',\n ).map((method) => method.capability as string)\n}\n\nexport function buildPaymentMethodRows(\n settings: StorefrontPaymentMethodSettings,\n platform: Record<string, PlatformAvailability>,\n capabilities: Record<string, string> | undefined,\n): PaymentMethodRow[] {\n return STOREFRONT_PAYMENT_METHODS.map((method) => ({\n id: method.id,\n on: isStorefrontPaymentMethodOn(settings, method.id),\n platform: platform[method.id] ?? null,\n capability: capabilities ? capabilityStatus(capabilities, method.capability) : null,\n }))\n}\n\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\n\n/**\n * Where Stripe sends the owner back: the console page they pressed the button\n * on, judged against the request's own origin so a forged `Referer` cannot\n * turn the link into a redirect to somewhere else.\n */\nexport function consoleReturnUrl(headers: Partial<Record<string, string>>): string {\n const origin = headers.origin || (headers.host ? `https://${headers.host}` : '')\n const referer = headers.referer ?? ''\n try {\n if (origin && referer && new URL(referer).origin === new URL(origin).origin) {\n return referer\n }\n } catch {\n // Unparseable: fall through to the origin.\n }\n return origin || 'https://localhost/'\n}\n\nexport async function paymentMethodsHandler(request: Request): Promise<Response> {\n const { method, headers: rawHeaders, query, body } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'GET' && method !== 'POST') {\n return json({ error: 'Method not allowed' }, 405)\n }\n if (!process.env.STRIPE_SECRET_KEY) {\n return json({ error: 'Payments are not configured (STRIPE_SECRET_KEY).' }, 501)\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return json({ error: 'Unauthenticated' }, 401)\n\n const parsed =\n typeof body === 'string' ? (JSON.parse(body || '{}') as Record<string, unknown>) : (body ?? {})\n const hostId = String(\n (method === 'GET' ? query?.['hostId'] : (parsed as Record<string, unknown>)['hostId']) ?? '',\n )\n if (!hostId) return json({ error: 'Missing hostId' }, 400)\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) return json({ error: 'Not found' }, 404)\n\n // An allowlist. Reading the card is for whoever works the store's orders\n // or changes its methods; a change asks Stripe for capabilities on the\n // owner's payout account, so it is \"Manage payment methods\" (AGL-4047),\n // whose preset is the site Admin who alone made it before, as the\n // reader's is the Admin and Editor.\n const mayEdit = holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.paymentMethods')\n const mayRead = mayEdit || holdsCommerceSiteKey(hostSnapshot, decoded.uid, 'commerce.orders')\n if (!mayRead) return json({ error: 'Not found' }, 404)\n if (method === 'POST' && !mayEdit) {\n return json({ error: commerceSitePermissionRefusal('commerce.paymentMethods') }, 403)\n }\n\n const owner = await getOrgForHost(hostId)\n const locked = await lockdownRefusal({\n request,\n staff: decoded['staff'] === true,\n uid: decoded.uid,\n org: owner?.org,\n host: hostSnapshot.data(),\n })\n if (locked) return locked\n if (!checkEntitlement((owner?.org ?? {}) as never, 'commerce')) {\n return json({ error: 'Selling is not included on this plan' }, 402)\n }\n\n const ownerUid = String(owner?.org?.ownerUid ?? '')\n const accountId = ownerUid\n ? (((await firestore.collection('profiles').doc(ownerUid).get()).get(\n 'stripeAccountId',\n ) as string | undefined) ?? null)\n : null\n\n const storeRef = hostRef.collection('settings').doc('store')\n let settings = normalizeStorefrontPaymentMethodSettings(\n (await storeRef.get()).get('paymentMethods'),\n )\n const platform = await platformPaymentMethodAvailability()\n let capabilities = await readAccountCapabilities(accountId)\n const warnings: string[] = []\n\n // FINISH IN STRIPE: a capability Stripe holds `inactive` needs details\n // only the account holder can give, and an Express account has no login of\n // its own, so a link minted here is the only way in. The owner's alone,\n // as connecting the account is (`connect.ts`): the link opens the owner's\n // identity and bank details.\n if (method === 'POST' && (parsed as Record<string, unknown>)['action'] === 'finish') {\n if (!accountId || decoded.uid !== ownerUid) {\n return json({ error: 'Only the organization owner can finish this in Stripe' }, 403)\n }\n const back = consoleReturnUrl(headers)\n const link = await stripe<{ url?: string }>(\n 'POST',\n 'account_links',\n new URLSearchParams({\n account: accountId,\n type: 'account_onboarding',\n 'collection_options[fields]': 'currently_due',\n refresh_url: back,\n return_url: back,\n }),\n )\n return json({ url: link.url ?? null })\n }\n\n if (method === 'POST') {\n const requested = normalizeStorefrontPaymentMethodSettings(\n (parsed as Record<string, unknown>)['methods'],\n )\n if (!Object.keys(requested).length) {\n return json({ error: 'Nothing to save' }, 400)\n }\n settings = { ...settings, ...requested }\n await storeRef.set(\n { paymentMethods: settings, paymentMethodsUpdatedAtMs: Date.now(), paymentMethodsUpdatedBy: decoded.uid },\n { merge: true },\n )\n const wanted = accountId ? capabilitiesToRequest(settings, platform, capabilities) : []\n if (accountId && wanted.length) {\n const params = new URLSearchParams()\n for (const capability of wanted) {\n params.set(`capabilities[${capability}][requested]`, 'true')\n }\n try {\n const account = await stripe<{ capabilities?: Record<string, string> }>(\n 'POST',\n `accounts/${encodeURIComponent(accountId)}`,\n params,\n `aglyn-pm-capabilities:${accountId}:${[...wanted].sort().join(',')}`,\n )\n capabilities = account.capabilities ?? capabilities\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n warnings.push(\n `Stripe did not accept the request to enable ${wanted.join(', ')} on your payout account: ${message}`,\n )\n }\n }\n }\n\n const answer: PaymentMethodsAnswer = {\n methods: buildPaymentMethodRows(settings, platform, capabilities),\n domains: await readSiteDomainRecords(\n hostSnapshot.data() as SiteReturnHost | undefined,\n await directSellerAccountForHost(hostId),\n ),\n accountConnected: Boolean(accountId),\n canEdit: mayEdit,\n canFinish: Boolean(accountId) && decoded.uid === ownerUid,\n warnings,\n }\n return json(answer)\n } catch (error) {\n const unauthenticated = invalidIdTokenResponse(error)\n if (unauthenticated) return unauthenticated\n console.error(error)\n return json({ error: 'Payment methods could not be loaded' }, 500)\n }\n}\n"],"names":["directSellerAccountForHost","checkEntitlement","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","lockdownRefusal","invalidIdTokenResponse","isStorefrontPaymentMethodOn","normalizeStorefrontPaymentMethodSettings","STOREFRONT_PAYMENT_METHODS","commerceSitePermissionRefusal","holdsCommerceSiteKey","readSiteDomainRecords","PLATFORM_CONFIGURATION_TTL_MS","platformCache","resetPlatformPaymentMethodCacheForTests","stripe","method","path","params","idempotencyKey","query","response","fetch","headers","Authorization","process","env","STRIPE_SECRET_KEY","body","toString","payload","json","catch","ok","Error","error","message","status","platformPaymentMethodAvailability","Date","now","at","value","list","URLSearchParams","limit","own","data","find","entry","is_default","application","id","configurationKey","available","display_preference","console","warn","capabilityStatus","capabilities","key","readAccountCapabilities","accountId","undefined","account","encodeURIComponent","capabilitiesToRequest","settings","platform","filter","capability","map","buildPaymentMethodRows","on","Response","consoleReturnUrl","origin","host","referer","URL","paymentMethodsHandler","request","rawHeaders","authorization","idToken","startsWith","slice","length","parsed","JSON","parse","hostId","String","owner","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","hostSnapshot","get","exists","mayEdit","uid","mayRead","locked","staff","org","ownerUid","storeRef","warnings","link","back","type","refresh_url","return_url","url","requested","Object","keys","set","paymentMethods","paymentMethodsUpdatedAtMs","paymentMethodsUpdatedBy","merge","wanted","sort","join","push","answer","methods","domains","accountConnected","Boolean","canEdit","canFinish","unauthenticated"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,sBAAqB;AAE5E,SACEC,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,QACV,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,mDAAkD;AACzF,SACEC,2BAA2B,EAC3BC,wCAAwC,EACxCC,0BAA0B,QAGrB,uCAAmC;AAC1C,SAASC,6BAA6B,QAAQ,iCAA6B;AAC3E,SAASC,oBAAoB,QAAQ,0BAAsB;AAC3D,SAEEC,qBAAqB,QAChB,8BAA0B;AA8CjC,gEAAgE,GAChE,MAAMC,gCAAgC,KAAK,KAAK;AAEhD,IAAIC,gBAAoF;AAExF,yDAAyD,GACzD,OAAO,SAASC;IACdD,gBAAgB;AAClB;AAEA,eAAeE,OACbC,MAAsB,EACtBC,IAAY,EACZC,MAAwB,EACxBC,cAAuB;IAEvB,MAAMC,QAAQJ,WAAW,SAASE,SAAS,CAAC,CAAC,EAAEA,QAAQ,GAAG;IAC1D,M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AA,QAAQL,YAAY,YAApBK,wBAAwBL;gBACzC,EAAE,OAAOxB,OAAO;oBACd,MAAMC,UAAUD,iBAAiBD,QAAQC,MAAMC,OAAO,GAAGwD,OAAOzD;oBAChE+E,SAASkB,IAAI,CACX,CAAC,4CAA4C,EAAEH,OAAOE,IAAI,CAAC,MAAM,yBAAyB,EAAE/F,SAAS;gBAEzG;YACF;QACF;QAEA,MAAMiG,SAA+B;YACnCC,SAAS9D,uBAAuBL,UAAUC,UAAUT;YACpD4E,SAAS,MAAM5H,sBACb4F,aAAaxD,IAAI,IACjB,MAAMlD,2BAA2B8F;YAEnC6C,kBAAkBC,QAAQ3E;YAC1B4E,SAAShC;YACTiC,WAAWF,QAAQ3E,cAAcgC,QAAQa,GAAG,KAAKK;YACjDE;QACF;QACA,OAAOnF,KAAKsG;IACd,EAAE,OAAOlG,OAAO;QACd,MAAMyG,kBAAkBvI,uBAAuB8B;QAC/C,IAAIyG,iBAAiB,OAAOA;QAC5BpF,QAAQrB,KAAK,CAACA;QACd,OAAOJ,KAAK;YAAEI,OAAO;QAAsC,GAAG;IAChE;AACF"}
|
|
@@ -66,9 +66,9 @@ export declare function authorizePosStaff(req: PluginApiRequest, hostId: string,
|
|
|
66
66
|
admits?: (permissions: Readonly<Record<string, boolean | undefined>>) => boolean,
|
|
67
67
|
/**
|
|
68
68
|
* `planRequired: false` admits a workspace whose plan does not include the
|
|
69
|
-
* point of sale
|
|
70
|
-
*
|
|
71
|
-
*
|
|
69
|
+
* point of sale: the hardware shop (AGL-4038), where anyone may buy readers
|
|
70
|
+
* and the card prompts to add the plan that takes payments with them.
|
|
71
|
+
* Everything at the register still asks the plan.
|
|
72
72
|
*/
|
|
73
73
|
options?: {
|
|
74
74
|
planRequired?: boolean;
|
|
@@ -50,9 +50,9 @@ import { holdsPosPermission, posPermissionRefusal } from "../model/plugin-permis
|
|
|
50
50
|
* who may buy hardware without the register.
|
|
51
51
|
*/ admits = worksPosRegister, /**
|
|
52
52
|
* `planRequired: false` admits a workspace whose plan does not include the
|
|
53
|
-
* point of sale
|
|
54
|
-
*
|
|
55
|
-
*
|
|
53
|
+
* point of sale: the hardware shop (AGL-4038), where anyone may buy readers
|
|
54
|
+
* and the card prompts to add the plan that takes payments with them.
|
|
55
|
+
* Everything at the register still asks the plan.
|
|
56
56
|
*/ options = {}) {
|
|
57
57
|
var _req_headers_authorization, _membership_permissions, _ref, _ref1, _ref2;
|
|
58
58
|
var _ownerOrg_org;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-auth.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiRequest } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n holdsPosPermission,\n posPermissionRefusal,\n type PosPermission,\n} from '../model/plugin-permissions'\n\n/** Who is working the register, once the gate has admitted them. */\nexport interface PosStaff {\n uid: string\n hostId: string\n orgId: string\n org: Record<string, any> | null\n}\n\nexport type PosStaffGate =\n | { ok: true; staff: PosStaff }\n | { ok: false; status: number; error: string }\n\n/** Who works the register: `managePos`, as resolved for the site (AGL-4047). */\nexport function worksPosRegister(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n): boolean {\n return permissions?.['managePos'] === true\n}\n\n/**\n * The register's gate, shared by every POS route (AGL-3607): the same\n * questions `pos-order.ts` asks, in the same order, so a payment, a reader or\n * a display pairing is refused to exactly the people a sale is refused to.\n *\n * 1. A Firebase ID token.\n * 2. `managePos` on the member's permissions as resolved FOR THIS SITE\n * (AGL-2474) — or what `admits` asks instead — and the `pos` plan\n * entitlement on the org that owns the site.\n * 3. When the route names one, the finer register key its action needs\n * (AGL-4047): `posSell`, `posDevices`, `posBuyHardware` and the rest,\n * each following `managePos` unless a role or the member sets it.\n *\n * THE KEYS DECIDE, NOT THE SITE ROLE (AGL-4047). This asked for `admin` or\n * `editor` in the site's `memberRoles` as well, which is exactly the set the\n * key is on for by default, so nobody who had the register loses it. The\n * resolver answers for this site: an org-wide member from their org role,\n * custom role and overrides; a site collaborator from the role they hold\n * here and their overrides; and anyone without access to the site with\n * nothing. So a site viewer the workspace grants the register works it, and\n * an admin a role narrows is refused. A site no workspace owns resolves\n * against the caller's own workspace, and is refused by the plan step, which\n * reads the plan of the workspace that owns the site.\n */\nexport async function authorizePosStaff(\n req: PluginApiRequest,\n hostId: string,\n permission?: PosPermission,\n /**\n * Who the route admits before the finer key: whoever works the register,\n * unless the route says otherwise — the hardware shop also admits a member\n * who may buy hardware without the register.\n */\n admits: (permissions: Readonly<Record<string, boolean | undefined>>) => boolean = worksPosRegister,\n /**\n * `planRequired: false` admits a workspace whose plan does not include the\n * point of sale
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-auth.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiRequest } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport {\n holdsPosPermission,\n posPermissionRefusal,\n type PosPermission,\n} from '../model/plugin-permissions'\n\n/** Who is working the register, once the gate has admitted them. */\nexport interface PosStaff {\n uid: string\n hostId: string\n orgId: string\n org: Record<string, any> | null\n}\n\nexport type PosStaffGate =\n | { ok: true; staff: PosStaff }\n | { ok: false; status: number; error: string }\n\n/** Who works the register: `managePos`, as resolved for the site (AGL-4047). */\nexport function worksPosRegister(\n permissions: Readonly<Record<string, boolean | undefined>> | null | undefined,\n): boolean {\n return permissions?.['managePos'] === true\n}\n\n/**\n * The register's gate, shared by every POS route (AGL-3607): the same\n * questions `pos-order.ts` asks, in the same order, so a payment, a reader or\n * a display pairing is refused to exactly the people a sale is refused to.\n *\n * 1. A Firebase ID token.\n * 2. `managePos` on the member's permissions as resolved FOR THIS SITE\n * (AGL-2474) — or what `admits` asks instead — and the `pos` plan\n * entitlement on the org that owns the site.\n * 3. When the route names one, the finer register key its action needs\n * (AGL-4047): `posSell`, `posDevices`, `posBuyHardware` and the rest,\n * each following `managePos` unless a role or the member sets it.\n *\n * THE KEYS DECIDE, NOT THE SITE ROLE (AGL-4047). This asked for `admin` or\n * `editor` in the site's `memberRoles` as well, which is exactly the set the\n * key is on for by default, so nobody who had the register loses it. The\n * resolver answers for this site: an org-wide member from their org role,\n * custom role and overrides; a site collaborator from the role they hold\n * here and their overrides; and anyone without access to the site with\n * nothing. So a site viewer the workspace grants the register works it, and\n * an admin a role narrows is refused. A site no workspace owns resolves\n * against the caller's own workspace, and is refused by the plan step, which\n * reads the plan of the workspace that owns the site.\n */\nexport async function authorizePosStaff(\n req: PluginApiRequest,\n hostId: string,\n permission?: PosPermission,\n /**\n * Who the route admits before the finer key: whoever works the register,\n * unless the route says otherwise — the hardware shop also admits a member\n * who may buy hardware without the register.\n */\n admits: (permissions: Readonly<Record<string, boolean | undefined>>) => boolean = worksPosRegister,\n /**\n * `planRequired: false` admits a workspace whose plan does not include the\n * point of sale: the hardware shop (AGL-4038), where anyone may buy readers\n * and the card prompts to add the plan that takes payments with them.\n * Everything at the register still asks the plan.\n */\n options: { planRequired?: boolean } = {},\n): Promise<PosStaffGate> {\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : ''\n if (!idToken) return { ok: false, status: 401, error: 'Unauthenticated' }\n if (!hostId) return { ok: false, status: 400, error: 'Missing hostId' }\n let uid: string\n try {\n uid = (await firebaseAdmin.app().auth().verifyIdToken(idToken)).uid\n } catch (error) {\n if (!isRefusedIdToken(error)) throw error\n return { ok: false, status: 401, error: 'Unauthenticated' }\n }\n const hostSnapshot = await firebaseAdmin\n .app()\n .firestore()\n .collection('hosts')\n .doc(hostId)\n .get()\n if (!hostSnapshot.exists) return { ok: false, status: 404, error: 'Unknown site' }\n const membership = await resolveOrgPermissions(uid, { hostId })\n if (!admits(membership.permissions ?? {})) {\n return { ok: false, status: 403, error: 'Not permitted' }\n }\n if (permission && !holdsPosPermission(membership.permissions, permission)) {\n return { ok: false, status: 403, error: posPermissionRefusal(permission) }\n }\n const ownerOrg = await getOrgForHost(hostId)\n if (options.planRequired !== false && !Aglyn.checkEntitlement(ownerOrg?.org as any, 'pos')) {\n return { ok: false, status: 403, error: 'POS requires the Pro plan or above' }\n }\n return {\n ok: true,\n staff: {\n uid,\n hostId,\n orgId: String(ownerOrg?.org?.id ?? ownerOrg?.orgId ?? ''),\n org: (ownerOrg?.org as Record<string, any>) ?? null,\n },\n }\n}\n\n/** A JSON body, whether the dispatcher parsed it or not. */\nexport function posRequestBody(req: PluginApiRequest): Record<string, any> {\n if (typeof req.body === 'string') {\n try {\n const parsed = JSON.parse(req.body)\n return parsed && typeof parsed === 'object' ? parsed : {}\n } catch {\n return {}\n }\n }\n return req.body && typeof req.body === 'object' ? req.body : {}\n}\n\n/** A GET request's query as a flat body, first value of each key. */\nexport function posQueryBody(req: PluginApiRequest): Record<string, any> {\n return Object.fromEntries(\n Object.entries(req.query ?? {}).map(([key, value]) => [\n key,\n Array.isArray(value) ? value[0] : value,\n ]),\n )\n}\n\n/** The request's Idempotency-Key header, trimmed and bounded. */\nexport function posIdempotencyKey(req: PluginApiRequest): string {\n return String(\n req.headers['idempotency-key'] ?? req.headers['Idempotency-Key'] ?? '',\n )\n .trim()\n .slice(0, 200)\n}\n"],"names":["Aglyn","firebaseAdmin","getOrgForHost","resolveOrgPermissions","isRefusedIdToken","holdsPosPermission","posPermissionRefusal","worksPosRegister","permissions","authorizePosStaff","req","hostId","permission","admits","options","membership","ownerOrg","authorization","String","headers","idToken","startsWith","slice","length","ok","status","error","uid","app","auth","verifyIdToken","hostSnapshot","firestore","collection","doc","get","exists","planRequired","checkEntitlement","org","staff","orgId","id","posRequestBody","body","parsed","JSON","parse","posQueryBody","Object","fromEntries","entries","query","map","key","value","Array","isArray","posIdempotencyKey","trim"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,YAAYA,WAAW,sBAAqB;AAE5C,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SACEC,kBAAkB,EAClBC,oBAAoB,QAEf,iCAA6B;AAcpC,8EAA8E,GAC9E,OAAO,SAASC,iBACdC,WAA6E;IAE7E,OAAOA,CAAAA,+BAAAA,WAAa,CAAC,YAAY,MAAK;AACxC;AAEA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,eAAeC,kBACpBC,GAAqB,EACrBC,MAAc,EACdC,UAA0B,EAC1B;;;;GAIC,GACDC,SAAkFN,gBAAgB,EAClG;;;;;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YAAhET,OAAoE,IAEnEiD,IAAI,GACJrC,KAAK,CAAC,GAAG;AACd"}
|
|
@@ -251,7 +251,7 @@ async function settleMonth(orgId, month, patch, now) {
|
|
|
251
251
|
productId: config.productId,
|
|
252
252
|
amountCents: stored.amountCents,
|
|
253
253
|
currency: 'usd',
|
|
254
|
-
description: `4G for ${stored.readers}
|
|
254
|
+
description: `4G for ${stored.readers} S710 card reader${stored.readers === 1 ? '' : 's'}, ${label}`,
|
|
255
255
|
metadata: {
|
|
256
256
|
orgId,
|
|
257
257
|
pluginId: BUNDLE_ID,
|
|
@@ -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} Stripe Reader 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,EAC/BC,2BAA2B,QAMtB,2BAAuB;AAC9B,SACEC,wBAAwB,EACxBC,gCAAgC,EAChCC,+BAA+B,QAC1B,oBAAgB;AAEvB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA+C2C,GAE3C,MAAMC,QAAQ;AAEd,6EAA6E,GAC7E,MAAMC,iBAAiB,KAAK,KAAK;AAEjC,wFAAwF,GACxF,MAAMC,uBAAuB;AAsC7B,SAASC;IACP,OAAO9B,cAAc+B,GAAG,GAAGD,SAAS;AACtC;AAEA,SAASE;IACP,OAAOF,YAAYG,UAAU,CAACX;AAChC;AAEA,SAASY;IACP,OAAOJ,YAAYG,UAAU,CAACZ;AAChC;AAEA,8FAA8F,GAC9F,SAASc,oBAAoBC,KAAa,EAAEC,KAAa;IACvD,OAAO,GAAGD,MAAM,CAAC,EAAEC,OAAO;AAC5B;AAEA,yFAAyF,GACzF,eAAeC,gBAAgBC,OAAe;IA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BK;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) => 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,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Y,QAAQ+C,WAAW;yBAC9B,IAAI/C,YAAY,WAAWgD,gBAAgB;gBAClD,EAAE,OAAO1H,OAAO;oBACd0H,gBAAgB;oBAChBzH,QAAQD,KAAK,CAAC,GAAGvD,MAAM,iCAAiC,CAAC,EAAES,OAAOC,OAAO6C;oBACzE,MAAMH,MAAMzE,qCAAqC;wBAC/C0E,WAAW7C,oBAAoBC,OAAOC;wBACtCD;wBACA6C,SAAS;4BACP7C;4BACAC,OAAOtB,sBAAsBsB;4BAC7BgD,SAASjC,OAAOiC;4BAChB0B,QAAQhH,0BAA0BY,uBAAuB0E,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"}
|
|
@@ -86,7 +86,7 @@ import { posCellularDayLabel, posCellularMonthLabel } from "../model/pos-cellula
|
|
|
86
86
|
});
|
|
87
87
|
return told || recipients.length === 0;
|
|
88
88
|
}
|
|
89
|
-
const readersText = (readers)=>`${readers}
|
|
89
|
+
const readersText = (readers)=>`${readers} S710 reader${readers === 1 ? '' : 's'}`;
|
|
90
90
|
/**
|
|
91
91
|
* The day a month's charge is left open: it is due, and 4G turns off for the
|
|
92
92
|
* workspace's stores on the day its grace runs out unless it is paid.
|