@aglyn/plugins-commerce 1.15.2 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +13 -13
- package/src/lib/components/cart.js +2 -1
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +6 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-api.d.ts +5 -0
- package/src/lib/components/console/pos/pos-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-dialogs.component.d.ts +2 -0
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js +13 -6
- package/src/lib/components/console/pos/pos-tender-dialogs.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-tender-panel.component.js +7 -4
- package/src/lib/components/console/pos/pos-tender-panel.component.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +5 -0
- package/src/lib/components/console/pos-cellular-control.component.js +29 -15
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +96 -3
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-builder-fields.component.d.ts +39 -0
- package/src/lib/components/console/product-builder-fields.component.js +195 -0
- package/src/lib/components/console/product-builder-fields.component.js.map +1 -0
- package/src/lib/components/console/product-editor-dialog.component.js +35 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +43 -6
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/quote-messages.component.d.ts +21 -0
- package/src/lib/components/console/quote-messages.component.js +185 -0
- package/src/lib/components/console/quote-messages.component.js.map +1 -0
- package/src/lib/components/console/quote-pay-link.component.js +1 -1
- package/src/lib/components/console/quote-pay-link.component.js.map +1 -1
- package/src/lib/components/console/quote-proofs.component.js +30 -3
- package/src/lib/components/console/quote-proofs.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.d.ts +7 -3
- package/src/lib/components/console/quote-settings-card.component.js +154 -24
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/product-builder-context.d.ts +22 -0
- package/src/lib/components/product-builder-context.js +21 -0
- package/src/lib/components/product-builder-context.js.map +1 -0
- package/src/lib/components/product-builder-mockup.d.ts +42 -0
- package/src/lib/components/product-builder-mockup.js +120 -0
- package/src/lib/components/product-builder-mockup.js.map +1 -0
- package/src/lib/components/product-builder-sample.d.ts +63 -0
- package/src/lib/components/product-builder-sample.js +96 -0
- package/src/lib/components/product-builder-sample.js.map +1 -0
- package/src/lib/components/product-choice-cards.d.ts +51 -0
- package/src/lib/components/product-choice-cards.js +311 -0
- package/src/lib/components/product-choice-cards.js.map +1 -0
- package/src/lib/components/product-detail-panels.d.ts +42 -0
- package/src/lib/components/product-detail-panels.js +185 -0
- package/src/lib/components/product-detail-panels.js.map +1 -0
- package/src/lib/components/product-detail.d.ts +20 -12
- package/src/lib/components/product-detail.js +136 -221
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/product-grid.d.ts +7 -0
- package/src/lib/components/product-grid.js +13 -9
- package/src/lib/components/product-grid.js.map +1 -1
- package/src/lib/components/product-name-lines.d.ts +37 -0
- package/src/lib/components/product-name-lines.js +36 -0
- package/src/lib/components/product-name-lines.js.map +1 -0
- package/src/lib/components/product-options-field-body.d.ts +9 -8
- package/src/lib/components/product-options-field-body.js +152 -3
- package/src/lib/components/product-options-field-body.js.map +1 -1
- package/src/lib/components/product-options-field.js +1 -1
- package/src/lib/components/product-options-field.js.map +1 -1
- package/src/lib/components/product-photo-fit.d.ts +49 -0
- package/src/lib/components/product-photo-fit.js +58 -0
- package/src/lib/components/product-photo-fit.js.map +1 -0
- package/src/lib/components/product-restock-notify.d.ts +12 -0
- package/src/lib/components/product-restock-notify.js +86 -0
- package/src/lib/components/product-restock-notify.js.map +1 -0
- package/src/lib/components/quote-messages-panel.d.ts +21 -0
- package/src/lib/components/quote-messages-panel.js +191 -0
- package/src/lib/components/quote-messages-panel.js.map +1 -0
- package/src/lib/components/quote-page-body.js +15 -1
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/quote-proof-panel.d.ts +6 -3
- package/src/lib/components/quote-proof-panel.js +139 -14
- package/src/lib/components/quote-proof-panel.js.map +1 -1
- package/src/lib/components/related-products.d.ts +7 -0
- package/src/lib/components/related-products.js +10 -7
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/constants/quote-page.d.ts +8 -0
- package/src/lib/constants/quote-page.js +11 -0
- package/src/lib/constants/quote-page.js.map +1 -1
- package/src/lib/model/commerce-cart.d.ts +6 -1
- package/src/lib/model/commerce-cart.js +5 -1
- package/src/lib/model/commerce-cart.js.map +1 -1
- package/src/lib/model/commerce-invoices.js +5 -1
- package/src/lib/model/commerce-invoices.js.map +1 -1
- package/src/lib/model/commerce-pos-ops.d.ts +3 -0
- package/src/lib/model/commerce-pos-ops.js +3 -0
- package/src/lib/model/commerce-pos-ops.js.map +1 -1
- package/src/lib/model/commerce-pos.d.ts +8 -0
- package/src/lib/model/commerce-pos.js.map +1 -1
- package/src/lib/model/commerce-quote-messages.d.ts +106 -0
- package/src/lib/model/commerce-quote-messages.js +146 -0
- package/src/lib/model/commerce-quote-messages.js.map +1 -0
- package/src/lib/model/commerce-quote-pay.d.ts +31 -2
- package/src/lib/model/commerce-quote-pay.js +31 -7
- package/src/lib/model/commerce-quote-pay.js.map +1 -1
- package/src/lib/model/commerce-quote-proofs.d.ts +47 -8
- package/src/lib/model/commerce-quote-proofs.js +73 -18
- package/src/lib/model/commerce-quote-proofs.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +14 -4
- package/src/lib/model/commerce-quote-request.js +25 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.d.ts +56 -3
- package/src/lib/model/commerce-quotes.js +47 -2
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce.d.ts +12 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/pos-cellular.d.ts +36 -4
- package/src/lib/model/pos-cellular.js +39 -4
- package/src/lib/model/pos-cellular.js.map +1 -1
- package/src/lib/model/product-card-rules.d.ts +41 -0
- package/src/lib/model/product-card-rules.js +90 -0
- package/src/lib/model/product-card-rules.js.map +1 -0
- package/src/lib/model/product-modifiers.d.ts +11 -0
- package/src/lib/model/product-modifiers.js +10 -0
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/server/billing-webhook.js +6 -2
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +15 -0
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/channel-order-updates.js +15 -1
- package/src/lib/server/channel-order-updates.js.map +1 -1
- package/src/lib/server/channel-orders.js +20 -0
- package/src/lib/server/channel-orders.js.map +1 -1
- package/src/lib/server/checkout.js +1 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/local-fulfillment.js +1 -1
- package/src/lib/server/local-fulfillment.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.d.ts +5 -4
- package/src/lib/server/pos-cellular-billing.js +24 -12
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular.d.ts +3 -1
- package/src/lib/server/pos-cellular.js +55 -33
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-offline-sync.d.ts +3 -3
- package/src/lib/server/pos-offline-sync.js +17 -4
- package/src/lib/server/pos-offline-sync.js.map +1 -1
- package/src/lib/server/pos-order.js +17 -6
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-payment.js +27 -11
- package/src/lib/server/pos-payment.js.map +1 -1
- package/src/lib/server/pos-reader-splash.js +10 -5
- package/src/lib/server/pos-reader-splash.js.map +1 -1
- package/src/lib/server/pos-readers.js +42 -12
- package/src/lib/server/pos-readers.js.map +1 -1
- package/src/lib/server/pos-return.js +19 -3
- package/src/lib/server/pos-return.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +14 -0
- package/src/lib/server/pos-stripe.js +6 -2
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal-connection-token.js +23 -9
- package/src/lib/server/pos-terminal-connection-token.js.map +1 -1
- package/src/lib/server/pos-terminal.d.ts +80 -14
- package/src/lib/server/pos-terminal.js +393 -123
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/product-drafts.d.ts +1 -1
- package/src/lib/server/product-drafts.js +4 -3
- package/src/lib/server/product-drafts.js.map +1 -1
- package/src/lib/server/product-writer.js +5 -4
- package/src/lib/server/product-writer.js.map +1 -1
- package/src/lib/server/product.d.ts +11 -0
- package/src/lib/server/product.js +18 -3
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +4 -3
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/server/quote-email.d.ts +26 -0
- package/src/lib/server/quote-email.js +73 -7
- package/src/lib/server/quote-email.js.map +1 -1
- package/src/lib/server/quote-messages.d.ts +72 -0
- package/src/lib/server/quote-messages.js +356 -0
- package/src/lib/server/quote-messages.js.map +1 -0
- package/src/lib/server/quote-pay.d.ts +42 -0
- package/src/lib/server/quote-pay.js +81 -4
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote-proofs.d.ts +1 -1
- package/src/lib/server/quote-proofs.js +63 -19
- package/src/lib/server/quote-proofs.js.map +1 -1
- package/src/lib/server/quote.d.ts +12 -0
- package/src/lib/server/quote.js +69 -16
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +3 -1
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/reserve-stock.js +9 -0
- package/src/lib/server/reserve-stock.js.map +1 -1
- package/src/lib/server/returns.js +15 -1
- package/src/lib/server/returns.js.map +1 -1
- package/src/lib/server/reviews.js +15 -0
- package/src/lib/server/reviews.js.map +1 -1
- package/src/lib/server/sold-out-drop.d.ts +58 -0
- package/src/lib/server/sold-out-drop.js +81 -0
- package/src/lib/server/sold-out-drop.js.map +1 -0
- package/src/lib/server/stock-levels.js +9 -0
- package/src/lib/server/stock-levels.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +7 -0
- package/src/lib/server/stripe-refund.js +26 -7
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server.d.ts +15 -0
- package/src/lib/server.js +30 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/tenant-emails.js +85 -2
- package/src/lib/tenant-emails.js.map +1 -1
- package/src/lib/testing/fake-seller-payment-account.d.ts +29 -0
- package/src/lib/testing/fake-seller-payment-account.js +40 -0
- package/src/lib/testing/fake-seller-payment-account.js.map +1 -0
- package/src/lib/transfer/product-transfer.js +6 -5
- package/src/lib/transfer/product-transfer.js.map +1 -1
- package/src/lib/transfer/products.server.js +4 -3
- package/src/lib/transfer/products.server.js.map +1 -1
- package/src/lib/utils/quote-email-content.d.ts +6 -0
- package/src/lib/utils/quote-email-content.js +6 -3
- package/src/lib/utils/quote-email-content.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular-billing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeOrgLockdown } from '@aglyn/aglyn/app-utils/lockdown'\nimport { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport type { PluginOrgEraser } from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport type { PluginJobHostGate } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, raiseOperatorAlert, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport {\n chargeOrgUsageInvoice,\n USAGE_INVOICE_MIN_CHARGE_CENTS,\n type OrgUsageInvoiceRequest,\n type OrgUsageInvoiceResult,\n} from '@aglyn/tenant-data-admin/server/usage-invoice'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n COMMERCE_POS_CELLULAR_CHARGE_FAILED,\n COMMERCE_POS_CELLULAR_TURN_OFF_FAILED,\n COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID,\n} from '../constants/operator-alerts'\nimport {\n closePosCellularPeriod,\n parsePosCellularConfig,\n posCellularChargeCents,\n posCellularGraceEndsAtMs,\n posCellularMonthBounds,\n posCellularMonthKey,\n posCellularMonthLabel,\n posCellularOverdue,\n posCellularPreviousMonthKey,\n posCellularReadersByWorkspace,\n posCellularWarningDue,\n POS_CELLULAR_CHARGE_KIND,\n POS_CELLULAR_CHARGES_COLLECTION,\n POS_CELLULAR_READERS_COLLECTION,\n POS_CELLULAR_SETTLED_STATES,\n type PosCellularCharge,\n type PosCellularChargeState,\n type PosCellularConfig,\n type PosCellularReaderRecord,\n type PosCellularSuspension,\n} from '../model/pos-cellular'\nimport {\n posCellularInvoiceStatus,\n settleSuspendedPosCellularCharge,\n turnOffPosCellularConfiguration,\n} from './pos-cellular'\n\n/*==========================================\n * THE MONTHLY 4G CHARGE (AGL-4038).\n *\n * Once a day, for the calendar month that has just ended, each workspace\n * whose Stripe Reader S710s had 4G at any time in it is charged once: Stripe's\n * price per reader, plus what collecting it costs (`posCellularChargeCents`),\n * on a one-off invoice to its card through core's usage-invoice charge, the\n * path domains and AI overages take. That is the month Stripe bills the\n * platform for, in arrears, so a reader turned off on the 3rd is charged for\n * that month and not the next.\n *\n * Once per workspace per month: `posCellularCharges/{orgId}_{month}` is\n * claimed in a transaction before Stripe is called, and the invoice's\n * idempotency key is the same pair, so a run that died mid-charge and the\n * next day's run land on the same invoice. A charge that did not collect is\n * left open on the workspace's Billing page (nothing retries it) and staff\n * are alerted; a workspace with no one to bill is recorded and alerted, and\n * never charged later for that month.\n *\n * Daily rather than monthly: a month whose charge failed to START (Stripe\n * unreachable) is retried the next day; one that settled costs a read.\n *\n * A STORE THAT IS GONE stops costing the platform: a reader record whose\n * store no longer exists has its period closed and the store's Configuration\n * told to turn cellular off; a workspace being erased does the same for all\n * of its stores first ({@link posCellularOrgEraser}).\n *\n * WARN, THEN TURN OFF. A charge left open is asked about each day: paid\n * since, it is settled as paid; voided by staff, as voided. The first time\n * Stripe says it is still unpaid (the same run that left it open, unless\n * Stripe could not be asked), the members who manage the workspace's billing\n * are warned, once (`warnedAtMs`), of the amount and of the day 4G turns off\n * unless it is paid; paid before then, nothing else is sent. Still unpaid\n * once the grace period (`POS_CELLULAR_GRACE_DAYS`, 14 by default) has run\n * from the day it was left open, 4G is turned off at Stripe for every store\n * of the workspace, the members who manage its billing are emailed and\n * notified again, and staff are alerted. Stripe that cannot be asked is never\n * read as unpaid.\n * Paying does not turn 4G back on: the merchant does, once it is paid\n * (`pos-cellular.ts` refuses it until then). Each step is idempotent, so a run\n * that dies half-way is finished by the next.\n *\n * A WORKSPACE DELETED MID-MONTH is charged for that final month as it is\n * erased, before its data goes, through the same claim as the monthly run\n * (and last month too, if the run had not charged it yet), so the two never\n * charge one month twice. A failure there alerts staff and never holds the\n * erasure.\n *=========================================*/\n\nconst LABEL = '[pos-cellular] billing'\n\n/** A charge claimed this long ago and not settled was abandoned by its run. */\nconst CLAIM_STALE_MS = 30 * 60 * 1000\n\n/** How many times a charge that never reached Stripe is tried before staff hear of it. */\nconst ALERT_AFTER_ATTEMPTS = 3\n\ntype Charge = (request: OrgUsageInvoiceRequest) => Promise<OrgUsageInvoiceResult>\n\ntype InvoiceStatus = (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null>\n\nexport interface PosCellularBillingDeps {\n now?: () => number\n config?: PosCellularConfig | null\n charge?: Charge\n readBilling?: (orgId: string) => Promise<{ stripeCustomerId?: unknown }>\n turnOff?: (configurationId: string) => Promise<boolean>\n alert?: typeof raiseOperatorAlert\n /** Stripe's word on a charge's invoice now, or null when it cannot be asked. */\n invoiceStatus?: InvoiceStatus\n /** Tells the workspace 4G was turned off; true once told (or there is nobody to tell). */\n notify?: (notice: import('./pos-cellular-notify').PosCellularTurnedOffNotice) => Promise<boolean>\n /** Warns the workspace 4G turns off unless the charge is paid; true once told (or there is nobody to tell). */\n warn?: (notice: import('./pos-cellular-notify').PosCellularPaymentDueNotice) => Promise<boolean>\n}\n\nexport interface PosCellularBillingReport {\n month: string | null\n workspaces: number\n paid: number\n open: number\n failed: number\n unbillable: number\n deferred: number\n storesGone: number\n /** Open charges paid since, found by asking Stripe. */\n paidLate: number\n /** Workspaces warned that 4G turns off unless a charge left open is paid. */\n warned: number\n /** Workspaces whose 4G was turned off for a month unpaid past its grace. */\n turnedOff: number\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction recordsRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nfunction chargesRef() {\n return firestore().collection(POS_CELLULAR_CHARGES_COLLECTION)\n}\n\n/** A workspace's charge for one month, `{orgId}_{month}`: one per pair, so a rerun finds it. */\nfunction posCellularChargeId(orgId: string, month: string): string {\n return `${orgId}_${month}`\n}\n\n/** The reader records that may count for a month: on now, or turned off since it began. */\nasync function recordsForMonth(startMs: number): Promise<Array<{ id: string; record: PosCellularReaderRecord }>> {\n const [on, off] = await Promise.all([\n recordsRef().where('enabled', '==', true).limit(1_000).get(),\n recordsRef().where('disabledAtMs', '>=', startMs).limit(1_000).get(),\n ])\n const byId = new Map<string, PosCellularReaderRecord>()\n for (const doc of [...on.docs, ...off.docs] as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n byId.set(String(doc.id), doc.data())\n }\n return [...byId].map(([id, record]) => ({ id, record }))\n}\n\n/**\n * Closes the records of stores that no longer exist and turns cellular off\n * on their Configuration, alerting staff when Stripe refuses. Returns how\n * many stores it found gone.\n */\nasync function closeGoneStores(\n records: ReadonlyArray<{ id: string; record: PosCellularReaderRecord }>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n now: number,\n): Promise<number> {\n const open = records.filter(({ record }) => record.enabled)\n const hostIds = [...new Set(open.map(({ record }) => record.hostId))]\n let gone = 0\n for (const hostId of hostIds) {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (host.exists) continue\n gone += 1\n const mine = open.filter(({ record }) => record.hostId === hostId)\n await turnOffConfigurations(mine.map(({ record }) => record), deps)\n for (const { id, record } of mine) await recordsRef().doc(id).set(closePosCellularPeriod(record, now))\n }\n return gone\n}\n\n/** Turns cellular off on each distinct Configuration the records name, alerting a refusal. */\nasync function turnOffConfigurations(\n records: ReadonlyArray<PosCellularReaderRecord>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n): Promise<{ off: number; failed: number }> {\n const configurations = new Map<string, PosCellularReaderRecord>()\n for (const record of records) {\n if (record.stripeConfigurationId) configurations.set(record.stripeConfigurationId, record)\n }\n let off = 0\n let failed = 0\n for (const [configurationId, record] of configurations) {\n const done = await deps.turnOff(configurationId).catch(() => false)\n if (done) {\n off += 1\n continue\n }\n failed += 1\n await deps\n .alert(COMMERCE_POS_CELLULAR_TURN_OFF_FAILED, {\n dedupeKey: configurationId,\n orgId: record.orgId,\n hostId: record.hostId,\n context: { configurationId, hostId: record.hostId, orgId: record.orgId },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turn-off alert was not raised`, configurationId, error))\n }\n return { off, failed }\n}\n\n/**\n * Claims a workspace's month for this run, or says it is not this run's:\n * settled already, or claimed by a run still within its window. The claim\n * counts the attempt.\n */\nasync function claimMonth(\n orgId: string,\n month: string,\n readers: number,\n amountCents: number,\n now: number,\n): Promise<{ attempts: number } | null> {\n const ref = chargesRef().doc(posCellularChargeId(orgId, month))\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const existing = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (existing && POS_CELLULAR_SETTLED_STATES.includes(existing.state)) return null\n if (existing?.state === 'charging' && now - existing.updatedAtMs < CLAIM_STALE_MS) return null\n const attempts = (existing?.attempts ?? 0) + 1\n const claim: PosCellularCharge = {\n orgId,\n month,\n // The figures of the FIRST attempt stand: the invoice's key is the\n // month's, and Stripe refuses a key reused with other parameters.\n readers: existing?.readers ?? readers,\n amountCents: existing?.amountCents ?? amountCents,\n state: 'charging',\n invoiceId: existing?.invoiceId ?? null,\n paidCents: 0,\n attempts,\n createdAtMs: existing?.createdAtMs ?? now,\n updatedAtMs: now,\n }\n transaction.set(ref, claim)\n return { attempts }\n })\n}\n\nasync function settleMonth(\n orgId: string,\n month: string,\n patch: {\n state: PosCellularChargeState\n invoiceId?: string | null\n paidCents?: number\n openedAtMs?: number\n final?: boolean\n },\n now: number,\n): Promise<void> {\n await chargesRef()\n .doc(posCellularChargeId(orgId, month))\n .set({ ...patch, updatedAtMs: now }, { merge: true })\n}\n\ntype ChargeOutcome = 'paid' | 'open' | 'failed' | 'unbillable' | 'settled'\n\n/**\n * Charges one workspace's month once: claimed in a transaction first, so the\n * monthly run and a workspace erasure never both charge it, and keyed by the\n * month so a retried run lands on the same invoice. `final` marks the charge\n * an erasure made, which alerts staff at once on a failure, since nothing\n * retries it.\n */\nasync function chargeWorkspaceMonth(\n input: { orgId: string; month: string; readers: number; final?: boolean },\n context: {\n config: PosCellularConfig\n now: number\n charge: Charge\n readBilling: NonNullable<PosCellularBillingDeps['readBilling']>\n alert: typeof raiseOperatorAlert\n },\n): Promise<ChargeOutcome> {\n const { orgId, month, readers } = input\n const { config, now, alert } = context\n const amountCents = posCellularChargeCents(readers, config)\n const claim = await claimMonth(orgId, month, readers, amountCents, now)\n if (!claim) return 'settled'\n const stored = (await chargesRef().doc(posCellularChargeId(orgId, month)).get()).data() as PosCellularCharge\n const final = input.final ? { final: true } : {}\n const raise = (reason: string) =>\n alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(stored.readers),\n amount: formatOperatorAlertAmount(stored.amountCents),\n reason: input.final ? `${reason} (charged as the workspace was deleted)` : reason,\n },\n }).catch((error: unknown) => console.error(`${LABEL}: the alert was not raised`, orgId, error))\n\n const org = await firestore().collection('orgs').doc(orgId).get()\n if (!org.exists) {\n await settleMonth(orgId, month, { state: 'no-workspace', ...final }, now)\n if (input.final) await raise('the workspace was already gone')\n return 'unbillable'\n }\n if (stored.amountCents < USAGE_INVOICE_MIN_CHARGE_CENTS) {\n await settleMonth(orgId, month, { state: 'below-minimum', ...final }, now)\n return 'unbillable'\n }\n const billing = await context.readBilling(orgId).catch(() => ({}) as { stripeCustomerId?: unknown })\n const stripeCustomerId = String(billing.stripeCustomerId ?? '')\n if (!stripeCustomerId) {\n await settleMonth(orgId, month, { state: 'no-customer', ...final }, now)\n await raise('the workspace has no payment method on file')\n return 'unbillable'\n }\n const label = posCellularMonthLabel(month)\n const result = await context\n .charge({\n orgId,\n stripeCustomerId,\n productId: config.productId,\n amountCents: stored.amountCents,\n currency: 'usd',\n description: `4G for ${stored.readers} S710 card reader${stored.readers === 1 ? '' : 's'}, ${label}`,\n metadata: {\n orgId,\n pluginId: BUNDLE_ID,\n kind: POS_CELLULAR_CHARGE_KIND,\n month,\n readers: String(stored.readers),\n },\n idempotencyKey: `pos-cellular-${orgId}-${month}`,\n })\n .catch(\n (error: unknown): OrgUsageInvoiceResult => ({\n ok: false,\n invoiceId: null,\n status: null,\n totalCents: 0,\n amountPaidCents: 0,\n requiresAction: false,\n error: error instanceof Error ? error.message : 'the charge threw',\n }),\n )\n if (result.ok) {\n await settleMonth(orgId, month, { state: 'paid', invoiceId: result.invoiceId, paidCents: result.amountPaidCents, ...final }, now)\n return 'paid'\n }\n if (result.invoiceId) {\n // The invoice stays open on their Billing page, where they can pay it;\n // the grace period runs from today.\n await settleMonth(orgId, month, { state: 'open', invoiceId: result.invoiceId, openedAtMs: now, ...final }, now)\n await raise(result.requiresAction ? 'the card needs the cardholder to authenticate' : result.error || 'the card was declined')\n return 'open'\n }\n await settleMonth(orgId, month, { state: 'failed', ...final }, now)\n console.error(`${LABEL}: the charge did not reach Stripe`, orgId, month, result.error)\n // Nothing retries a charge made at erasure: staff hear of it now.\n if (input.final || claim.attempts >= ALERT_AFTER_ATTEMPTS) await raise(result.error || 'Stripe did not answer')\n return 'failed'\n}\n\n/** The charge of every workspace whose readers had 4G last month, once each. */\nexport async function runPosCellularBilling(\n gate: PluginJobHostGate,\n deps: PosCellularBillingDeps = {},\n): Promise<PosCellularBillingReport> {\n const config = deps.config === undefined ? parsePosCellularConfig(process.env) : deps.config\n const now = (deps.now ?? Date.now)()\n const report: PosCellularBillingReport = {\n month: null,\n workspaces: 0,\n paid: 0,\n open: 0,\n failed: 0,\n unbillable: 0,\n deferred: 0,\n storesGone: 0,\n paidLate: 0,\n warned: 0,\n turnedOff: 0,\n }\n if (!config) return report\n const charge = deps.charge ?? ((request: OrgUsageInvoiceRequest) => chargeOrgUsageInvoice(request))\n const readBilling = deps.readBilling ?? ((orgId: string) => readOrgBilling(orgId) as Promise<{ stripeCustomerId?: unknown }>)\n const alert = deps.alert ?? raiseOperatorAlert\n const turnOff = deps.turnOff ?? turnOffPosCellularConfiguration\n\n const month = posCellularPreviousMonthKey(now)\n report.month = month\n const bounds = posCellularMonthBounds(month) as { startMs: number; endMs: number }\n const records = await recordsForMonth(bounds.startMs)\n report.storesGone = await closeGoneStores(records, { turnOff, alert }, now)\n\n const byOrg = posCellularReadersByWorkspace(\n records.map(({ record }) => record),\n month,\n )\n report.workspaces = byOrg.size\n for (const [orgId, { readers, hostIds }] of byOrg) {\n // A store locked for security or abuse is charged nothing while it is:\n // its card may be the stolen one the lock is about. Tried again daily.\n const locked = await Promise.all(hostIds.map((hostId) => gate.isLocked(hostId).catch(() => true)))\n if (locked.some(Boolean)) {\n report.deferred += 1\n continue\n }\n const outcome = await chargeWorkspaceMonth({ orgId, month, readers }, { config, now, charge, readBilling, alert })\n if (outcome === 'paid') report.paid += 1\n else if (outcome === 'open') report.open += 1\n else if (outcome === 'failed') report.failed += 1\n else if (outcome === 'unbillable') report.unbillable += 1\n }\n\n const grace = await enforcePosCellularGrace({\n config,\n now,\n alert,\n turnOff,\n invoiceStatus: deps.invoiceStatus ?? posCellularInvoiceStatus,\n notify:\n deps.notify ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularTurnedOffNotice(notice)),\n warn:\n deps.warn ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularPaymentDueNotice(notice)),\n })\n report.paidLate = grace.paidLate\n report.warned = grace.warned\n report.turnedOff = grace.turnedOff\n return report\n}\n\n/**\n * WARN, THEN TURN OFF (AGL-4038): every charge left open is asked about at\n * Stripe; paid or voided since, it is settled so; still unpaid within its\n * grace, the workspace is warned once of the day 4G turns off; still unpaid\n * past it, 4G goes off for the workspace. A charge already suspended is\n * finished if a run died half-way (a store still on, nobody told yet) and\n * settled once paid.\n */\nasync function enforcePosCellularGrace(context: {\n config: PosCellularConfig\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string) => Promise<boolean>\n invoiceStatus: InvoiceStatus\n notify: NonNullable<PosCellularBillingDeps['notify']>\n warn: NonNullable<PosCellularBillingDeps['warn']>\n}): Promise<{ paidLate: number; warned: number; turnedOff: number }> {\n const { config, now } = context\n let paidLate = 0\n let warned = 0\n let turnedOff = 0\n for (const state of ['open', 'suspended'] as const) {\n const snapshot = await chargesRef().where('state', '==', state).limit(200).get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const id = String(doc.id)\n const stored = doc.data()\n const invoice = stored.invoiceId ? await context.invoiceStatus(stored.invoiceId).catch(() => null) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n const settled = invoice.status === 'paid' ? 'paid' : 'voided'\n if (state === 'suspended') {\n await settleSuspendedPosCellularCharge(id, stored, settled, invoice.amountPaidCents, now)\n } else {\n await settleMonth(stored.orgId, stored.month, { state: settled, ...(settled === 'paid' ? { paidCents: invoice.amountPaidCents } : {}) }, now)\n }\n if (settled === 'paid') paidLate += 1\n continue\n }\n // Stripe could not be asked: never read as unpaid.\n if (!invoice) continue\n if (state === 'open') {\n if (!posCellularOverdue(stored, config.graceDays, now)) {\n if (posCellularWarningDue(stored) && (await warnPaymentDue(id, context))) warned += 1\n continue\n }\n const claimed = await claimSuspension(id, now)\n if (!claimed) continue\n turnedOff += 1\n await context\n .alert(COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID, {\n dedupeKey: id,\n orgId: stored.orgId,\n context: {\n orgId: stored.orgId,\n month: posCellularMonthLabel(stored.month),\n amount: formatOperatorAlertAmount(stored.amountCents),\n graceDays: String(config.graceDays),\n },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turned-off alert was not raised`, id, error))\n }\n await finishSuspension(id, { ...stored, state: 'suspended', suspendedAtMs: stored.suspendedAtMs ?? now }, context)\n }\n }\n return { paidLate, warned, turnedOff }\n}\n\n/**\n * Claims the warning of an open charge, once: the charge as it stood, or null\n * when a run already warned of it or it is no longer open. The day its grace\n * counts from is pinned with the claim, so the day the warning states is the\n * day the turn-off keeps, even for a charge from before that day was stored.\n */\nasync function claimWarning(id: string, now: number): Promise<PosCellularCharge | null> {\n const ref = chargesRef().doc(id)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const charge = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (!charge || !posCellularWarningDue(charge)) return null\n const openedAtMs = Number(charge.openedAtMs ?? charge.updatedAtMs)\n transaction.set(ref, { warnedAtMs: now, openedAtMs, updatedAtMs: now }, { merge: true })\n return { ...charge, openedAtMs }\n })\n}\n\n/**\n * WARN AT THE START (AGL-4038): the members who manage the workspace's\n * billing are told the charge is due and the day 4G turns off for its stores\n * unless it is paid. Claimed before it is sent, so two runs never both send\n * it; a warning nobody could be sent is released for the next run to try.\n */\nasync function warnPaymentDue(\n id: string,\n context: { config: PosCellularConfig; now: number; warn: NonNullable<PosCellularBillingDeps['warn']> },\n): Promise<boolean> {\n const { config, now } = context\n const charge = await claimWarning(id, now)\n if (!charge) return false\n const told = await (async () => {\n // The stores that have 4G now, which lose it on that day.\n const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get()\n const hostIds = [\n ...new Set(\n (snapshot.docs as unknown as Array<{ data: () => PosCellularReaderRecord }>).map((doc) => doc.data().hostId),\n ),\n ]\n return context.warn({\n orgId: charge.orgId,\n month: charge.month,\n amount: formatOperatorAlertAmount(charge.amountCents),\n readers: charge.readers,\n openedAtMs: Number(charge.openedAtMs),\n turnsOffAtMs: posCellularGraceEndsAtMs(charge, config.graceDays),\n hostIds,\n })\n })().catch((error: unknown) => {\n console.error(`${LABEL}: the payment-due warning was not sent`, id, error)\n return false\n })\n if (!told) await chargesRef().doc(id).set({ warnedAtMs: null, updatedAtMs: now }, { merge: true })\n return told\n}\n\n/** Moves an open charge to `suspended`, once: false when a run already did, or it is no longer open. */\nasync function claimSuspension(id: string, now: number): Promise<boolean> {\n const ref = chargesRef().doc(id)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n if (!snapshot.exists || (snapshot.data() as PosCellularCharge).state !== 'open') return false\n transaction.set(ref, { state: 'suspended', suspendedAtMs: now, updatedAtMs: now }, { merge: true })\n return true\n })\n}\n\n/**\n * 4G off at Stripe for every store of the workspace that still has it, each\n * store's settings saying why, its readers' periods closed, and the workspace\n * told once. Safe to run again: a store already off and a notice already\n * sent are left alone.\n */\nasync function finishSuspension(\n id: string,\n charge: PosCellularCharge,\n context: {\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string) => Promise<boolean>\n notify: NonNullable<PosCellularBillingDeps['notify']>\n },\n): Promise<void> {\n const { now } = context\n const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get()\n const records = (snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>).map(\n (doc) => ({ id: String(doc.id), record: doc.data() }),\n )\n const hostIds = new Set(charge.suspendedHostIds ?? [])\n if (records.length) {\n await turnOffConfigurations(\n records.map(({ record }) => record),\n { turnOff: context.turnOff, alert: context.alert },\n )\n const suspension: PosCellularSuspension = { month: charge.month, invoiceId: charge.invoiceId, atMs: now }\n for (const hostId of new Set(records.map(({ record }) => record.hostId))) {\n hostIds.add(hostId)\n const terminal = firestore().collection('hosts').doc(hostId).collection('terminal').doc('config')\n if (!(await terminal.get()).exists) continue\n await terminal.set(\n { cellularEnabled: false, cellularChangedAtMs: now, cellularChangedBy: 'unpaid', cellularSuspended: suspension },\n { merge: true },\n )\n }\n for (const { id: recordId, record } of records) await recordsRef().doc(recordId).set(closePosCellularPeriod(record, now))\n }\n const patch: Partial<PosCellularCharge> = {}\n if (records.length || hostIds.size !== (charge.suspendedHostIds ?? []).length) patch.suspendedHostIds = [...hostIds]\n if (!charge.noticeSentAtMs) {\n const told = await context.notify({\n orgId: charge.orgId,\n month: charge.month,\n amount: formatOperatorAlertAmount(charge.amountCents),\n readers: charge.readers,\n openedAtMs: Number(charge.openedAtMs ?? charge.updatedAtMs),\n turnedOffAtMs: Number(charge.suspendedAtMs ?? now),\n hostIds: [...hostIds],\n })\n if (told) patch.noticeSentAtMs = now\n }\n // A suspension already finished, and still unpaid, writes nothing.\n if (Object.keys(patch).length) await chargesRef().doc(id).set({ ...patch, updatedAtMs: now }, { merge: true })\n}\n\n/**\n * Commerce's 4G share of a WORKSPACE erasure (AGL-4038), before its data\n * goes:\n *\n * 1. CHARGE IT. The month the workspace is deleted in is charged now, for\n * each S710 that had 4G in it, as the monthly run would have charged it a\n * month later; and last month too, if the run had not charged it yet.\n * Through the run's own claim and key, so the two never charge one month\n * twice. A workspace that is locked is not charged (its card may be the\n * stolen one the lock is about): staff are alerted instead. Any failure\n * alerts staff and goes on.\n * 2. TURN IT OFF. Every store of the workspace with 4G on has cellular turned\n * off at Stripe, so the platform stops paying for readers nobody will be\n * charged for, and their periods are closed.\n *\n * Never fails the erasure: a refusal is a must alert. A dry run only counts.\n */\nexport function createPosCellularOrgEraser(\n deps: Pick<PosCellularBillingDeps, 'turnOff' | 'alert' | 'now' | 'config' | 'charge' | 'readBilling'> = {},\n): PluginOrgEraser {\n return async ({ orgId, dryRun }) => {\n const empty = { cellularStoresTurnedOff: 0, cellularTurnOffFailed: 0, cellularFinalMonthsCharged: 0, cellularFinalChargeFailed: 0 }\n if (!orgId) return empty\n const now = (deps.now ?? Date.now)()\n const alert = deps.alert ?? raiseOperatorAlert\n const snapshot = await recordsRef().where('orgId', '==', orgId).limit(500).get()\n const all = (snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>).map((doc) => ({\n id: String(doc.id),\n record: doc.data(),\n }))\n const records = all.filter(({ record }) => record.enabled)\n const stores = new Set(records.map(({ record }) => record.stripeConfigurationId).filter(Boolean)).size\n\n // 1. The final month (and last month, if it is still owed).\n const config = deps.config === undefined ? parsePosCellularConfig(process.env) : deps.config\n // The months with readers that no run has settled yet.\n const months: Array<{ month: string; readers: number }> = []\n for (const month of config ? [posCellularPreviousMonthKey(now), posCellularMonthKey(now)] : []) {\n const readers = posCellularReadersByWorkspace(all.map(({ record }) => record), month).get(orgId)?.readers ?? 0\n if (!readers) continue\n const existing = await chargesRef().doc(posCellularChargeId(orgId, month)).get()\n const state = existing.exists ? (existing.data() as PosCellularCharge).state : null\n if (!state || !POS_CELLULAR_SETTLED_STATES.includes(state)) months.push({ month, readers })\n }\n let charged = 0\n let chargeFailed = 0\n if (dryRun) return { ...empty, cellularStoresTurnedOff: stores, cellularFinalMonthsCharged: months.length }\n if (config && months.length) {\n const org = await firestore().collection('orgs').doc(orgId).get().catch(() => null)\n const locked = org?.exists ? normalizeOrgLockdown(org.data() as never) !== null : false\n for (const { month, readers } of months) {\n try {\n if (locked) {\n chargeFailed += 1\n await alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(readers),\n amount: formatOperatorAlertAmount(posCellularChargeCents(readers, config)),\n reason: 'the workspace is locked, so it was not charged as it was deleted',\n },\n })\n continue\n }\n const outcome = await chargeWorkspaceMonth(\n { orgId, month, readers, final: true },\n {\n config,\n now,\n charge: deps.charge ?? ((request: OrgUsageInvoiceRequest) => chargeOrgUsageInvoice(request)),\n readBilling:\n deps.readBilling ?? ((id: string) => readOrgBilling(id) as Promise<{ stripeCustomerId?: unknown }>),\n alert,\n },\n )\n if (outcome === 'paid') charged += 1\n else if (outcome !== 'settled') chargeFailed += 1\n } catch (error) {\n chargeFailed += 1\n console.error(`${LABEL}: the final month was not charged`, orgId, month, error)\n await alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(readers),\n amount: formatOperatorAlertAmount(posCellularChargeCents(readers, config)),\n reason: 'the charge failed as the workspace was deleted',\n },\n }).catch(() => undefined)\n }\n }\n }\n\n // 2. Off at Stripe, so the platform stops paying for it.\n if (!records.length) return { ...empty, cellularFinalMonthsCharged: charged, cellularFinalChargeFailed: chargeFailed }\n const { off, failed } = await turnOffConfigurations(\n records.map(({ record }) => record),\n { turnOff: deps.turnOff ?? turnOffPosCellularConfiguration, alert },\n )\n for (const { id, record } of records) await recordsRef().doc(id).set(closePosCellularPeriod(record, now))\n return {\n cellularStoresTurnedOff: off,\n cellularTurnOffFailed: failed,\n cellularFinalMonthsCharged: charged,\n cellularFinalChargeFailed: chargeFailed,\n }\n }\n}\n\n/** The eraser over the platform's own Firestore and Stripe, as the declarations register it. */\nexport const posCellularOrgEraser: PluginOrgEraser = (request) => createPosCellularOrgEraser()(request)\n"],"names":["normalizeOrgLockdown","formatOperatorAlertAmount","firebaseAdmin","raiseOperatorAlert","readOrgBilling","chargeOrgUsageInvoice","USAGE_INVOICE_MIN_CHARGE_CENTS","BUNDLE_ID","COMMERCE_POS_CELLULAR_CHARGE_FAILED","COMMERCE_POS_CELLULAR_TURN_OFF_FAILED","COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID","closePosCellularPeriod","parsePosCellularConfig","posCellularChargeCents","posCellularGraceEndsAtMs","posCellularMonthBounds","posCellularMonthKey","posCellularMonthLabel","posCellularOverdue","posCellularPreviousMonthKey","posCellularReadersByWorkspace","posCellularWarningDue","POS_CELLULAR_CHARGE_KIND","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","POS_CELLULAR_SETTLED_STATES","posCellularInvoiceStatus","settleSuspendedPosCellularCharge","turnOffPosCellularConfiguration","LABEL","CLAIM_STALE_MS","ALERT_AFTER_ATTEMPTS","firestore","app","recordsRef","collection","chargesRef","posCellularChargeId","orgId","month","recordsForMonth","startMs","on","off","Promise","all","where","limit","get","byId","Map","doc","docs","set","String","id","data","map","record","closeGoneStores","records","deps","now","open","filter","enabled","hostIds","Set","hostId","gone","host","exists","mine","turnOffConfigurations","configurations","stripeConfigurationId","failed","configurationId","done","turnOff","catch","alert","dedupeKey","context","error","console","claimMonth","readers","amountCents","ref","runTransaction","transaction","snapshot","existing","includes","state","updatedAtMs","attempts","claim","invoiceId","paidCents","createdAtMs","settleMonth","patch","merge","chargeWorkspaceMonth","input","billing","config","stored","final","raise","reason","amount","org","readBilling","stripeCustomerId","label","result","charge","productId","currency","description","metadata","pluginId","kind","idempotencyKey","ok","status","totalCents","amountPaidCents","requiresAction","Error","message","openedAtMs","runPosCellularBilling","gate","undefined","process","env","Date","report","workspaces","paid","unbillable","deferred","storesGone","paidLate","warned","turnedOff","request","bounds","byOrg","size","locked","isLocked","some","Boolean","outcome","grace","enforcePosCellularGrace","invoiceStatus","notify","notice","sendPosCellularTurnedOffNotice","warn","sendPosCellularPaymentDueNotice","invoice","settled","graceDays","warnPaymentDue","claimed","claimSuspension","finishSuspension","suspendedAtMs","claimWarning","Number","warnedAtMs","told","turnsOffAtMs","suspendedHostIds","length","suspension","atMs","add","terminal","cellularEnabled","cellularChangedAtMs","cellularChangedBy","cellularSuspended","recordId","noticeSentAtMs","turnedOffAtMs","Object","keys","createPosCellularOrgEraser","dryRun","empty","cellularStoresTurnedOff","cellularTurnOffFailed","cellularFinalMonthsCharged","cellularFinalChargeFailed","stores","months","push","charged","chargeFailed","posCellularOrgEraser"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,kCAAiC;AACtE,SAASC,yBAAyB,QAAQ,yCAAwC;AAGlF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,cAAc,QAAQ,2BAA0B;AAC5F,SACEC,qBAAqB,EACrBC,8BAA8B,QAGzB,gDAA+C;AACtD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,mCAAmC,EACnCC,qCAAqC,EACrCC,uCAAuC,QAClC,kCAA8B;AACrC,SACEC,sBAAsB,EACtBC,sBAAsB,EACtBC,sBAAsB,EACtBC,wBAAwB,EACxBC,sBAAsB,EACtBC,mBAAmB,EACnBC,qBAAqB,EACrBC,kBAAkB,EAClBC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,qBAAqB,EACrBC,wBAAwB,EACxBC,+BAA+B,EAC/BC,+BAA+B,EAC/BC,2BAA2B,QAMtB,2BAAuB;AAC9B,SACEC,wBAAwB,EACxBC,gCAAgC,EAChCC,+BAA+B,QAC1B,oBAAgB;AAEvB;;;;;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AAC7E,QAAQyH,MAAM,EAAE,OAAO,aAAKgB;YAAOG,4BAA4BK;YAASJ,2BAA2BK;;QACxG,MAAM,EAAEnK,GAAG,EAAEiC,MAAM,EAAE,GAAG,MAAMH,sBAC5Bb,QAAQH,GAAG,CAAC,CAAC,EAAEC,MAAM,EAAE,GAAKA,SAC5B;YAAEqB,OAAO,GAAElB,gBAAAA,KAAKkB,OAAO,YAAZlB,gBAAgBjC;YAAiCqD;QAAM;QAEpE,KAAK,MAAM,EAAE1B,EAAE,EAAEG,MAAM,EAAE,IAAIE,QAAS,MAAM1B,aAAaiB,GAAG,CAACI,IAAIF,GAAG,CAAC1C,uBAAuB+C,QAAQI;QACpG,OAAO;YACLwI,yBAAyB3J;YACzB4J,uBAAuB3H;YACvB4H,4BAA4BK;YAC5BJ,2BAA2BK;QAC7B;IACF;AACF;AAEA,8FAA8F,GAC9F,OAAO,MAAMC,uBAAwC,CAACzD,UAAY6C,6BAA6B7C,SAAQ"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular-billing.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { normalizeOrgLockdown } from '@aglyn/aglyn/app-utils/lockdown'\nimport { formatOperatorAlertAmount } from '@aglyn/aglyn/app-utils/operator-alerts'\nimport type { PluginOrgEraser } from '@aglyn/aglyn/plugin-manager/plugin-org-erasure'\nimport type { PluginJobHostGate } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, raiseOperatorAlert, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport {\n chargeOrgUsageInvoice,\n USAGE_INVOICE_MIN_CHARGE_CENTS,\n type OrgUsageInvoiceRequest,\n type OrgUsageInvoiceResult,\n} from '@aglyn/tenant-data-admin/server/usage-invoice'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport {\n COMMERCE_POS_CELLULAR_CHARGE_FAILED,\n COMMERCE_POS_CELLULAR_TURN_OFF_FAILED,\n COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID,\n} from '../constants/operator-alerts'\nimport {\n closePosCellularPeriod,\n parsePosCellularConfig,\n posCellularBilledToPlatform,\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 * A STORE ON ITS OWN STRIPE ACCOUNT (a reader record with\n * `stripeConfigurationAccount`) is billed for its 4G by Stripe, on that\n * account, so none of the charging above counts it\n * (`posCellularReadersByWorkspace`), and no charge here can warn about it or\n * turn its 4G off: an unpaid month suspends only the workspace's stores on\n * the platform. A gone store and an erased workspace still turn it off at\n * Stripe, on the account it is on.\n *=========================================*/\n\nconst LABEL = '[pos-cellular] billing'\n\n/** A charge claimed this long ago and not settled was abandoned by its run. */\nconst CLAIM_STALE_MS = 30 * 60 * 1000\n\n/** How many times a charge that never reached Stripe is tried before staff hear of it. */\nconst ALERT_AFTER_ATTEMPTS = 3\n\ntype Charge = (request: OrgUsageInvoiceRequest) => Promise<OrgUsageInvoiceResult>\n\ntype InvoiceStatus = (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null>\n\nexport interface PosCellularBillingDeps {\n now?: () => number\n config?: PosCellularConfig | null\n charge?: Charge\n readBilling?: (orgId: string) => Promise<{ stripeCustomerId?: unknown }>\n turnOff?: (configurationId: string, stripeAccount?: string | null) => Promise<boolean>\n alert?: typeof raiseOperatorAlert\n /** Stripe's word on a charge's invoice now, or null when it cannot be asked. */\n invoiceStatus?: InvoiceStatus\n /** Tells the workspace 4G was turned off; true once told (or there is nobody to tell). */\n notify?: (notice: import('./pos-cellular-notify').PosCellularTurnedOffNotice) => Promise<boolean>\n /** Warns the workspace 4G turns off unless the charge is paid; true once told (or there is nobody to tell). */\n warn?: (notice: import('./pos-cellular-notify').PosCellularPaymentDueNotice) => Promise<boolean>\n}\n\nexport interface PosCellularBillingReport {\n month: string | null\n workspaces: number\n paid: number\n open: number\n failed: number\n unbillable: number\n deferred: number\n storesGone: number\n /** Open charges paid since, found by asking Stripe. */\n paidLate: number\n /** Workspaces warned that 4G turns off unless a charge left open is paid. */\n warned: number\n /** Workspaces whose 4G was turned off for a month unpaid past its grace. */\n turnedOff: number\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction recordsRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nfunction chargesRef() {\n return firestore().collection(POS_CELLULAR_CHARGES_COLLECTION)\n}\n\n/** A workspace's charge for one month, `{orgId}_{month}`: one per pair, so a rerun finds it. */\nfunction posCellularChargeId(orgId: string, month: string): string {\n return `${orgId}_${month}`\n}\n\n/** The reader records that may count for a month: on now, or turned off since it began. */\nasync function recordsForMonth(startMs: number): Promise<Array<{ id: string; record: PosCellularReaderRecord }>> {\n const [on, off] = await Promise.all([\n recordsRef().where('enabled', '==', true).limit(1_000).get(),\n recordsRef().where('disabledAtMs', '>=', startMs).limit(1_000).get(),\n ])\n const byId = new Map<string, PosCellularReaderRecord>()\n for (const doc of [...on.docs, ...off.docs] as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n byId.set(String(doc.id), doc.data())\n }\n return [...byId].map(([id, record]) => ({ id, record }))\n}\n\n/**\n * Closes the records of stores that no longer exist and turns cellular off\n * on their Configuration, alerting staff when Stripe refuses. Returns how\n * many stores it found gone.\n */\nasync function closeGoneStores(\n records: ReadonlyArray<{ id: string; record: PosCellularReaderRecord }>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n now: number,\n): Promise<number> {\n const open = records.filter(({ record }) => record.enabled)\n const hostIds = [...new Set(open.map(({ record }) => record.hostId))]\n let gone = 0\n for (const hostId of hostIds) {\n const host = await firestore().collection('hosts').doc(hostId).get()\n if (host.exists) continue\n gone += 1\n const mine = open.filter(({ record }) => record.hostId === hostId)\n await turnOffConfigurations(mine.map(({ record }) => record), deps)\n for (const { id, record } of mine) await recordsRef().doc(id).set(closePosCellularPeriod(record, now))\n }\n return gone\n}\n\n/** Turns cellular off on each distinct Configuration the records name, alerting a refusal. */\nasync function turnOffConfigurations(\n records: ReadonlyArray<PosCellularReaderRecord>,\n deps: Required<Pick<PosCellularBillingDeps, 'turnOff' | 'alert'>>,\n): Promise<{ off: number; failed: number }> {\n const configurations = new Map<string, PosCellularReaderRecord>()\n for (const record of records) {\n if (record.stripeConfigurationId) configurations.set(record.stripeConfigurationId, record)\n }\n let off = 0\n let failed = 0\n for (const [configurationId, record] of configurations) {\n const done = await deps.turnOff(configurationId, record.stripeConfigurationAccount ?? null).catch(() => false)\n if (done) {\n off += 1\n continue\n }\n failed += 1\n await deps\n .alert(COMMERCE_POS_CELLULAR_TURN_OFF_FAILED, {\n dedupeKey: configurationId,\n orgId: record.orgId,\n hostId: record.hostId,\n context: { configurationId, hostId: record.hostId, orgId: record.orgId },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turn-off alert was not raised`, configurationId, error))\n }\n return { off, failed }\n}\n\n/**\n * Claims a workspace's month for this run, or says it is not this run's:\n * settled already, or claimed by a run still within its window. The claim\n * counts the attempt.\n */\nasync function claimMonth(\n orgId: string,\n month: string,\n readers: number,\n amountCents: number,\n now: number,\n): Promise<{ attempts: number } | null> {\n const ref = chargesRef().doc(posCellularChargeId(orgId, month))\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const existing = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (existing && POS_CELLULAR_SETTLED_STATES.includes(existing.state)) return null\n if (existing?.state === 'charging' && now - existing.updatedAtMs < CLAIM_STALE_MS) return null\n const attempts = (existing?.attempts ?? 0) + 1\n const claim: PosCellularCharge = {\n orgId,\n month,\n // The figures of the FIRST attempt stand: the invoice's key is the\n // month's, and Stripe refuses a key reused with other parameters.\n readers: existing?.readers ?? readers,\n amountCents: existing?.amountCents ?? amountCents,\n state: 'charging',\n invoiceId: existing?.invoiceId ?? null,\n paidCents: 0,\n attempts,\n createdAtMs: existing?.createdAtMs ?? now,\n updatedAtMs: now,\n }\n transaction.set(ref, claim)\n return { attempts }\n })\n}\n\nasync function settleMonth(\n orgId: string,\n month: string,\n patch: {\n state: PosCellularChargeState\n invoiceId?: string | null\n paidCents?: number\n openedAtMs?: number\n final?: boolean\n },\n now: number,\n): Promise<void> {\n await chargesRef()\n .doc(posCellularChargeId(orgId, month))\n .set({ ...patch, updatedAtMs: now }, { merge: true })\n}\n\ntype ChargeOutcome = 'paid' | 'open' | 'failed' | 'unbillable' | 'settled'\n\n/**\n * Charges one workspace's month once: claimed in a transaction first, so the\n * monthly run and a workspace erasure never both charge it, and keyed by the\n * month so a retried run lands on the same invoice. `final` marks the charge\n * an erasure made, which alerts staff at once on a failure, since nothing\n * retries it.\n */\nasync function chargeWorkspaceMonth(\n input: { orgId: string; month: string; readers: number; final?: boolean },\n context: {\n config: PosCellularConfig\n now: number\n charge: Charge\n readBilling: NonNullable<PosCellularBillingDeps['readBilling']>\n alert: typeof raiseOperatorAlert\n },\n): Promise<ChargeOutcome> {\n const { orgId, month, readers } = input\n const { config, now, alert } = context\n const amountCents = posCellularChargeCents(readers, config)\n const claim = await claimMonth(orgId, month, readers, amountCents, now)\n if (!claim) return 'settled'\n const stored = (await chargesRef().doc(posCellularChargeId(orgId, month)).get()).data() as PosCellularCharge\n const final = input.final ? { final: true } : {}\n const raise = (reason: string) =>\n alert(COMMERCE_POS_CELLULAR_CHARGE_FAILED, {\n dedupeKey: posCellularChargeId(orgId, month),\n orgId,\n context: {\n orgId,\n month: posCellularMonthLabel(month),\n readers: String(stored.readers),\n amount: formatOperatorAlertAmount(stored.amountCents),\n reason: input.final ? `${reason} (charged as the workspace was deleted)` : reason,\n },\n }).catch((error: unknown) => console.error(`${LABEL}: the alert was not raised`, orgId, error))\n\n const org = await firestore().collection('orgs').doc(orgId).get()\n if (!org.exists) {\n await settleMonth(orgId, month, { state: 'no-workspace', ...final }, now)\n if (input.final) await raise('the workspace was already gone')\n return 'unbillable'\n }\n if (stored.amountCents < USAGE_INVOICE_MIN_CHARGE_CENTS) {\n await settleMonth(orgId, month, { state: 'below-minimum', ...final }, now)\n return 'unbillable'\n }\n const billing = await context.readBilling(orgId).catch(() => ({}) as { stripeCustomerId?: unknown })\n const stripeCustomerId = String(billing.stripeCustomerId ?? '')\n if (!stripeCustomerId) {\n await settleMonth(orgId, month, { state: 'no-customer', ...final }, now)\n await raise('the workspace has no payment method on file')\n return 'unbillable'\n }\n const label = posCellularMonthLabel(month)\n const result = await context\n .charge({\n orgId,\n stripeCustomerId,\n productId: config.productId,\n amountCents: stored.amountCents,\n currency: 'usd',\n description: `4G for ${stored.readers} S710 card reader${stored.readers === 1 ? '' : 's'}, ${label}`,\n metadata: {\n orgId,\n pluginId: BUNDLE_ID,\n kind: POS_CELLULAR_CHARGE_KIND,\n month,\n readers: String(stored.readers),\n },\n idempotencyKey: `pos-cellular-${orgId}-${month}`,\n })\n .catch(\n (error: unknown): OrgUsageInvoiceResult => ({\n ok: false,\n invoiceId: null,\n status: null,\n totalCents: 0,\n amountPaidCents: 0,\n requiresAction: false,\n error: error instanceof Error ? error.message : 'the charge threw',\n }),\n )\n if (result.ok) {\n await settleMonth(orgId, month, { state: 'paid', invoiceId: result.invoiceId, paidCents: result.amountPaidCents, ...final }, now)\n return 'paid'\n }\n if (result.invoiceId) {\n // The invoice stays open on their Billing page, where they can pay it;\n // the grace period runs from today.\n await settleMonth(orgId, month, { state: 'open', invoiceId: result.invoiceId, openedAtMs: now, ...final }, now)\n await raise(result.requiresAction ? 'the card needs the cardholder to authenticate' : result.error || 'the card was declined')\n return 'open'\n }\n await settleMonth(orgId, month, { state: 'failed', ...final }, now)\n console.error(`${LABEL}: the charge did not reach Stripe`, orgId, month, result.error)\n // Nothing retries a charge made at erasure: staff hear of it now.\n if (input.final || claim.attempts >= ALERT_AFTER_ATTEMPTS) await raise(result.error || 'Stripe did not answer')\n return 'failed'\n}\n\n/** The charge of every workspace whose readers had 4G last month, once each. */\nexport async function runPosCellularBilling(\n gate: PluginJobHostGate,\n deps: PosCellularBillingDeps = {},\n): Promise<PosCellularBillingReport> {\n const config = deps.config === undefined ? parsePosCellularConfig(process.env) : deps.config\n const now = (deps.now ?? Date.now)()\n const report: PosCellularBillingReport = {\n month: null,\n workspaces: 0,\n paid: 0,\n open: 0,\n failed: 0,\n unbillable: 0,\n deferred: 0,\n storesGone: 0,\n paidLate: 0,\n warned: 0,\n turnedOff: 0,\n }\n if (!config) return report\n const charge = deps.charge ?? ((request: OrgUsageInvoiceRequest) => chargeOrgUsageInvoice(request))\n const readBilling = deps.readBilling ?? ((orgId: string) => readOrgBilling(orgId) as Promise<{ stripeCustomerId?: unknown }>)\n const alert = deps.alert ?? raiseOperatorAlert\n const turnOff = deps.turnOff ?? turnOffPosCellularConfiguration\n\n const month = posCellularPreviousMonthKey(now)\n report.month = month\n const bounds = posCellularMonthBounds(month) as { startMs: number; endMs: number }\n const records = await recordsForMonth(bounds.startMs)\n report.storesGone = await closeGoneStores(records, { turnOff, alert }, now)\n\n const byOrg = posCellularReadersByWorkspace(\n records.map(({ record }) => record),\n month,\n )\n report.workspaces = byOrg.size\n for (const [orgId, { readers, hostIds }] of byOrg) {\n // A store locked for security or abuse is charged nothing while it is:\n // its card may be the stolen one the lock is about. Tried again daily.\n const locked = await Promise.all(hostIds.map((hostId) => gate.isLocked(hostId).catch(() => true)))\n if (locked.some(Boolean)) {\n report.deferred += 1\n continue\n }\n const outcome = await chargeWorkspaceMonth({ orgId, month, readers }, { config, now, charge, readBilling, alert })\n if (outcome === 'paid') report.paid += 1\n else if (outcome === 'open') report.open += 1\n else if (outcome === 'failed') report.failed += 1\n else if (outcome === 'unbillable') report.unbillable += 1\n }\n\n const grace = await enforcePosCellularGrace({\n config,\n now,\n alert,\n turnOff,\n invoiceStatus: deps.invoiceStatus ?? posCellularInvoiceStatus,\n notify:\n deps.notify ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularTurnedOffNotice(notice)),\n warn:\n deps.warn ??\n (async (notice) => (await import('./pos-cellular-notify')).sendPosCellularPaymentDueNotice(notice)),\n })\n report.paidLate = grace.paidLate\n report.warned = grace.warned\n report.turnedOff = grace.turnedOff\n return report\n}\n\n/**\n * WARN, THEN TURN OFF (AGL-4038): every charge left open is asked about at\n * Stripe; paid or voided since, it is settled so; still unpaid within its\n * grace, the workspace is warned once of the day 4G turns off; still unpaid\n * past it, 4G goes off for the workspace. A charge already suspended is\n * finished if a run died half-way (a store still on, nobody told yet) and\n * settled once paid.\n */\nasync function enforcePosCellularGrace(context: {\n config: PosCellularConfig\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string, stripeAccount?: string | null) => Promise<boolean>\n invoiceStatus: InvoiceStatus\n notify: NonNullable<PosCellularBillingDeps['notify']>\n warn: NonNullable<PosCellularBillingDeps['warn']>\n}): Promise<{ paidLate: number; warned: number; turnedOff: number }> {\n const { config, now } = context\n let paidLate = 0\n let warned = 0\n let turnedOff = 0\n for (const state of ['open', 'suspended'] as const) {\n const snapshot = await chargesRef().where('state', '==', state).limit(200).get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const id = String(doc.id)\n const stored = doc.data()\n const invoice = stored.invoiceId ? await context.invoiceStatus(stored.invoiceId).catch(() => null) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n const settled = invoice.status === 'paid' ? 'paid' : 'voided'\n if (state === 'suspended') {\n await settleSuspendedPosCellularCharge(id, stored, settled, invoice.amountPaidCents, now)\n } else {\n await settleMonth(stored.orgId, stored.month, { state: settled, ...(settled === 'paid' ? { paidCents: invoice.amountPaidCents } : {}) }, now)\n }\n if (settled === 'paid') paidLate += 1\n continue\n }\n // Stripe could not be asked: never read as unpaid.\n if (!invoice) continue\n if (state === 'open') {\n if (!posCellularOverdue(stored, config.graceDays, now)) {\n if (posCellularWarningDue(stored) && (await warnPaymentDue(id, context))) warned += 1\n continue\n }\n const claimed = await claimSuspension(id, now)\n if (!claimed) continue\n turnedOff += 1\n await context\n .alert(COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID, {\n dedupeKey: id,\n orgId: stored.orgId,\n context: {\n orgId: stored.orgId,\n month: posCellularMonthLabel(stored.month),\n amount: formatOperatorAlertAmount(stored.amountCents),\n graceDays: String(config.graceDays),\n },\n })\n .catch((error: unknown) => console.error(`${LABEL}: the turned-off alert was not raised`, id, error))\n }\n await finishSuspension(id, { ...stored, state: 'suspended', suspendedAtMs: stored.suspendedAtMs ?? now }, context)\n }\n }\n return { paidLate, warned, turnedOff }\n}\n\n/**\n * Claims the warning of an open charge, once: the charge as it stood, or null\n * when a run already warned of it or it is no longer open. The day its grace\n * counts from is pinned with the claim, so the day the warning states is the\n * day the turn-off keeps, even for a charge from before that day was stored.\n */\nasync function claimWarning(id: string, now: number): Promise<PosCellularCharge | null> {\n const ref = chargesRef().doc(id)\n return firestore().runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(ref)\n const charge = snapshot.exists ? (snapshot.data() as PosCellularCharge) : null\n if (!charge || !posCellularWarningDue(charge)) return null\n const openedAtMs = Number(charge.openedAtMs ?? charge.updatedAtMs)\n transaction.set(ref, { warnedAtMs: now, openedAtMs, updatedAtMs: now }, { merge: true })\n return { ...charge, openedAtMs }\n })\n}\n\n/**\n * WARN AT THE START (AGL-4038): the members who manage the workspace's\n * billing are told the charge is due and the day 4G turns off for its stores\n * unless it is paid. Claimed before it is sent, so two runs never both send\n * it; a warning nobody could be sent is released for the next run to try.\n */\nasync function warnPaymentDue(\n id: string,\n context: { config: PosCellularConfig; now: number; warn: NonNullable<PosCellularBillingDeps['warn']> },\n): Promise<boolean> {\n const { config, now } = context\n const charge = await claimWarning(id, now)\n if (!charge) return false\n const told = await (async () => {\n // The stores that have 4G on the platform now, which lose it on that\n // day. A store on its own Stripe account keeps it whatever happens here.\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 }>)\n .map((doc) => doc.data())\n .filter(posCellularBilledToPlatform)\n .map((record) => record.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 on the\n * platform, each store's settings saying why, its readers' periods closed,\n * and the workspace told once. A store on its own Stripe account is never\n * touched: its 4G is not part of the charge. Safe to run again: a store\n * already off and a notice already sent are left alone.\n */\nasync function finishSuspension(\n id: string,\n charge: PosCellularCharge,\n context: {\n now: number\n alert: typeof raiseOperatorAlert\n turnOff: (configurationId: string, stripeAccount?: string | null) => Promise<boolean>\n notify: NonNullable<PosCellularBillingDeps['notify']>\n },\n): Promise<void> {\n const { now } = context\n const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get()\n const records = (snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularReaderRecord }>)\n .map((doc) => ({ id: String(doc.id), record: doc.data() }))\n .filter(({ record }) => posCellularBilledToPlatform(record))\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 on the platform that had 4G in it (one on a store's own\n * Stripe account is Stripe's to bill), 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, on the account it is on, so nobody keeps paying for\n * readers of a workspace that is gone, 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","posCellularBilledToPlatform","posCellularChargeCents","posCellularGraceEndsAtMs","posCellularMonthBounds","posCellularMonthKey","posCellularMonthLabel","posCellularOverdue","posCellularPreviousMonthKey","posCellularReadersByWorkspace","posCellularWarningDue","POS_CELLULAR_CHARGE_KIND","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","POS_CELLULAR_SETTLED_STATES","posCellularInvoiceStatus","settleSuspendedPosCellularCharge","turnOffPosCellularConfiguration","LABEL","CLAIM_STALE_MS","ALERT_AFTER_ATTEMPTS","firestore","app","recordsRef","collection","chargesRef","posCellularChargeId","orgId","month","recordsForMonth","startMs","on","off","Promise","all","where","limit","get","byId","Map","doc","docs","set","String","id","data","map","record","closeGoneStores","records","deps","now","open","filter","enabled","hostIds","Set","hostId","gone","host","exists","mine","turnOffConfigurations","configurations","stripeConfigurationId","failed","configurationId","done","turnOff","stripeConfigurationAccount","catch","alert","dedupeKey","context","error","console","claimMonth","readers","amountCents","ref","runTransaction","transaction","snapshot","existing","includes","state","updatedAtMs","attempts","claim","invoiceId","paidCents","createdAtMs","settleMonth","patch","merge","chargeWorkspaceMonth","input","billing","config","stored","final","raise","reason","amount","org","readBilling","stripeCustomerId","label","result","charge","productId","currency","description","metadata","pluginId","kind","idempotencyKey","ok","status","totalCents","amountPaidCents","requiresAction","Error","message","openedAtMs","runPosCellularBilling","gate","undefined","process","env","Date","report","workspaces","paid","unbillable","deferred","storesGone","paidLate","warned","turnedOff","request","bounds","byOrg","size","locked","isLocked","some","Boolean","outcome","grace","enforcePosCellularGrace","invoiceStatus","notify","notice","sendPosCellularTurnedOffNotice","warn","sendPosCellularPaymentDueNotice","invoice","settled","graceDays","warnPaymentDue","claimed","claimSuspension","finishSuspension","suspendedAtMs","claimWarning","Number","warnedAtMs","told","turnsOffAtMs","suspendedHostIds","length","suspension","atMs","add","terminal","cellularEnabled","cellularChangedAtMs","cellularChangedBy","cellularSuspended","recordId","noticeSentAtMs","turnedOffAtMs","Object","keys","createPosCellularOrgEraser","dryRun","empty","cellularStoresTurnedOff","cellularTurnOffFailed","cellularFinalMonthsCharged","cellularFinalChargeFailed","stores","months","push","charged","chargeFailed","posCellularOrgEraser"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,oBAAoB,QAAQ,kCAAiC;AACtE,SAASC,yBAAyB,QAAQ,yCAAwC;AAGlF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,cAAc,QAAQ,2BAA0B;AAC5F,SACEC,qBAAqB,EACrBC,8BAA8B,QAGzB,gDAA+C;AACtD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SACEC,mCAAmC,EACnCC,qCAAqC,EACrCC,uCAAuC,QAClC,kCAA8B;AACrC,SACEC,sBAAsB,EACtBC,sBAAsB,EACtBC,2BAA2B,EAC3BC,sBAAsB,EACtBC,wBAAwB,EACx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YAAY,QAAQ+C,WAAW;yBAC9B,IAAI/C,YAAY,WAAWgD,gBAAgB;gBAClD,EAAE,OAAO1H,OAAO;oBACd0H,gBAAgB;oBAChBzH,QAAQD,KAAK,CAAC,GAAGxD,MAAM,iCAAiC,CAAC,EAAES,OAAOC,OAAO8C;oBACzE,MAAMH,MAAM3E,qCAAqC;wBAC/C4E,WAAW9C,oBAAoBC,OAAOC;wBACtCD;wBACA8C,SAAS;4BACP9C;4BACAC,OAAOtB,sBAAsBsB;4BAC7BiD,SAASlC,OAAOkC;4BAChB0B,QAAQlH,0BAA0Ba,uBAAuB2E,SAASqB;4BAClEI,QAAQ;wBACV;oBACF,GAAGhC,KAAK,CAAC,IAAMyD;gBACjB;YACF;QACF;QAEA,yDAAyD;QACzD,IAAI,CAAC9E,QAAQ0H,MAAM,EAAE,OAAO,aAAKgB;YAAOG,4BAA4BK;YAASJ,2BAA2BK;;QACxG,MAAM,EAAEpK,GAAG,EAAEiC,MAAM,EAAE,GAAG,MAAMH,sBAC5Bb,QAAQH,GAAG,CAAC,CAAC,EAAEC,MAAM,EAAE,GAAKA,SAC5B;YAAEqB,OAAO,GAAElB,gBAAAA,KAAKkB,OAAO,YAAZlB,gBAAgBjC;YAAiCsD;QAAM;QAEpE,KAAK,MAAM,EAAE3B,EAAE,EAAEG,MAAM,EAAE,IAAIE,QAAS,MAAM1B,aAAaiB,GAAG,CAACI,IAAIF,GAAG,CAAC3C,uBAAuBgD,QAAQI;QACpG,OAAO;YACLyI,yBAAyB5J;YACzB6J,uBAAuB5H;YACvB6H,4BAA4BK;YAC5BJ,2BAA2BK;QAC7B;IACF;AACF;AAEA,8FAA8F,GAC9F,OAAO,MAAMC,uBAAwC,CAACzD,UAAY6C,6BAA6B7C,SAAQ"}
|
|
@@ -85,4 +85,6 @@ export declare function setPosStoreCellular(staff: PosStaff, body: Record<string
|
|
|
85
85
|
* or workspace that is being deleted, whose settings may be gone already.
|
|
86
86
|
* True when Stripe took it, or the Configuration no longer exists.
|
|
87
87
|
*/
|
|
88
|
-
export declare function turnOffPosCellularConfiguration(configurationId: string
|
|
88
|
+
export declare function turnOffPosCellularConfiguration(configurationId: string,
|
|
89
|
+
/** The store's own account the Configuration is on; null for the platform. */
|
|
90
|
+
stripeAccount?: string | null): Promise<boolean>;
|
|
@@ -16,7 +16,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
16
16
|
* limitations under the License.
|
|
17
17
|
*/ import { firebaseAdmin, readOrgBilling } from "@aglyn/tenant-data-admin";
|
|
18
18
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
19
|
-
import { closePosCellularPeriod, isPosCellularDeviceType, openPosCellularPeriod, parsePosCellularConfig, posCellularReaderId, posCellularMonthLabel, posCellularReaderMonthlyCents, POS_CELLULAR_CHARGES_COLLECTION, POS_CELLULAR_READERS_COLLECTION } from "../model/pos-cellular.js";
|
|
19
|
+
import { closePosCellularPeriod, isPosCellularDeviceType, openPosCellularPeriod, parsePosCellularConfig, posCellularOwnAccount, posCellularReaderId, posCellularMonthLabel, posCellularReaderMonthlyCents, POS_CELLULAR_CHARGES_COLLECTION, POS_CELLULAR_READERS_COLLECTION } from "../model/pos-cellular.js";
|
|
20
20
|
import { posStripe, posTerminalAvailable } from "./pos-stripe.js";
|
|
21
21
|
import { savePosReaderConfiguration } from "./pos-terminal.js";
|
|
22
22
|
/*==========================================
|
|
@@ -42,6 +42,15 @@ import { savePosReaderConfiguration } from "./pos-terminal.js";
|
|
|
42
42
|
* devices"; turning it off takes only the card's key. While a month's charge
|
|
43
43
|
* is unpaid past its grace period (`pos-cellular-billing.ts`), it cannot be
|
|
44
44
|
* turned on again: paying it, then turning it on, is the way back.
|
|
45
|
+
*
|
|
46
|
+
* A store whose Location, and so its Configuration, is on its OWN Stripe
|
|
47
|
+
* account (direct charges: `stripeLocationAccount`, the account
|
|
48
|
+
* `savePosReaderConfiguration` writes to) is billed for 4G by Stripe, on
|
|
49
|
+
* that account, under the store's own agreement with Stripe. The workspace
|
|
50
|
+
* is never charged for it, so turning it on there takes only the card's
|
|
51
|
+
* "Registers and devices": no "Manage billing", no card on file, no
|
|
52
|
+
* agreement to the platform's price, and no unpaid month of the workspace's
|
|
53
|
+
* holds it back.
|
|
45
54
|
*=========================================*/ /** The workspace key turning 4G on takes, beside "Registers and devices". */ export const POS_CELLULAR_BILLING_PERMISSION = 'billing.manage';
|
|
46
55
|
/** What a member without it is told, naming the permission. */ export const POS_CELLULAR_BILLING_REFUSAL = 'Your role does not include "Manage billing" — ask an organization admin. 4G is charged to the workspace.';
|
|
47
56
|
/** Whether the member may turn 4G on for a store: the workspace's "Manage billing", resolved for that store. */ export async function mayTurnOnPosCellular(uid, hostId) {
|
|
@@ -140,6 +149,9 @@ function cellularReadersRef() {
|
|
|
140
149
|
]);
|
|
141
150
|
const enabled = terminal.get('cellularEnabled') === true;
|
|
142
151
|
const configurationId = String((_terminal_get = terminal.get('stripeConfigurationId')) != null ? _terminal_get : '') || null;
|
|
152
|
+
// The account that configuration lives on: the store's own for a
|
|
153
|
+
// direct-charge store's Location, absent for the platform's.
|
|
154
|
+
const configurationAccount = posCellularOwnAccount(terminal.get('stripeLocationAccount'));
|
|
143
155
|
const capable = new Map();
|
|
144
156
|
for (const doc of readers.docs){
|
|
145
157
|
if (isPosCellularDeviceType(doc.get('deviceType'))) {
|
|
@@ -159,18 +171,20 @@ function cellularReadersRef() {
|
|
|
159
171
|
let closed = 0;
|
|
160
172
|
if (enabled) {
|
|
161
173
|
for (const [readerId, reader] of capable){
|
|
162
|
-
var _records_get;
|
|
174
|
+
var _records_get, _existing_stripeConfigurationAccount;
|
|
163
175
|
const id = posCellularReaderId(input.hostId, readerId);
|
|
164
176
|
const existing = (_records_get = records.get(id)) != null ? _records_get : null;
|
|
165
|
-
const next = openPosCellularPeriod({
|
|
177
|
+
const next = openPosCellularPeriod(_extends({
|
|
166
178
|
orgId: input.orgId,
|
|
167
179
|
hostId: input.hostId,
|
|
168
180
|
readerId,
|
|
169
181
|
serialNumber: reader.serialNumber,
|
|
170
182
|
stripeConfigurationId: configurationId
|
|
171
|
-
},
|
|
183
|
+
}, configurationAccount ? {
|
|
184
|
+
stripeConfigurationAccount: configurationAccount
|
|
185
|
+
} : {}), existing, now);
|
|
172
186
|
open += 1;
|
|
173
|
-
const unchanged = (existing == null ? void 0 : existing.enabled) === true && existing.periods.some((period)=>period.toMs === null) && existing.orgId === input.orgId && existing.serialNumber === reader.serialNumber && existing.stripeConfigurationId === configurationId;
|
|
187
|
+
const unchanged = (existing == null ? void 0 : existing.enabled) === true && existing.periods.some((period)=>period.toMs === null) && existing.orgId === input.orgId && existing.serialNumber === reader.serialNumber && existing.stripeConfigurationId === configurationId && ((_existing_stripeConfigurationAccount = existing.stripeConfigurationAccount) != null ? _existing_stripeConfigurationAccount : null) === configurationAccount;
|
|
174
188
|
if (unchanged) continue;
|
|
175
189
|
transaction.set(cellularReadersRef().doc(id), next);
|
|
176
190
|
}
|
|
@@ -221,10 +235,13 @@ function cellularReadersRef() {
|
|
|
221
235
|
}
|
|
222
236
|
};
|
|
223
237
|
}
|
|
238
|
+
// On the store's own Stripe account, Stripe bills the 4G to that account:
|
|
239
|
+
// nothing here is charged to the workspace.
|
|
240
|
+
const ownAccount = posCellularOwnAccount(terminal.get('stripeLocationAccount')) !== null;
|
|
224
241
|
if (enable) {
|
|
225
|
-
|
|
226
|
-
//
|
|
227
|
-
if (!await mayTurnOnPosCellular(staff.uid, staff.hostId)) {
|
|
242
|
+
// Charged to the workspace: its billing key, as well as the card's own,
|
|
243
|
+
// and the person's agreement to the price.
|
|
244
|
+
if (!ownAccount && !await mayTurnOnPosCellular(staff.uid, staff.hostId)) {
|
|
228
245
|
return {
|
|
229
246
|
status: 403,
|
|
230
247
|
body: {
|
|
@@ -233,7 +250,7 @@ function cellularReadersRef() {
|
|
|
233
250
|
}
|
|
234
251
|
};
|
|
235
252
|
}
|
|
236
|
-
if (body['consent'] !== true) {
|
|
253
|
+
if (!ownAccount && body['consent'] !== true) {
|
|
237
254
|
return {
|
|
238
255
|
status: 400,
|
|
239
256
|
body: {
|
|
@@ -253,26 +270,29 @@ function cellularReadersRef() {
|
|
|
253
270
|
}
|
|
254
271
|
};
|
|
255
272
|
}
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
273
|
+
if (!ownAccount) {
|
|
274
|
+
var _billing_stripeCustomerId;
|
|
275
|
+
const billing = await readOrgBilling(staff.orgId).catch(()=>({}));
|
|
276
|
+
if (!String((_billing_stripeCustomerId = billing.stripeCustomerId) != null ? _billing_stripeCustomerId : '')) {
|
|
277
|
+
return {
|
|
278
|
+
status: 409,
|
|
279
|
+
body: {
|
|
280
|
+
error: 'Add a payment method in Billing first: 4G is charged to this workspace each month.',
|
|
281
|
+
code: 'no-billing'
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
// Turned off for an unpaid month: paid first, then on again.
|
|
286
|
+
const unpaid = await unpaidPosCellularSuspension(staff.orgId, Date.now());
|
|
287
|
+
if (unpaid) {
|
|
288
|
+
return {
|
|
289
|
+
status: 409,
|
|
290
|
+
body: {
|
|
291
|
+
error: `4G was turned off because the 4G charge for ${posCellularMonthLabel(unpaid.month)} wasn't paid. Pay it on the Billing page, then turn 4G on again.`,
|
|
292
|
+
code: 'cellular-unpaid'
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
276
296
|
}
|
|
277
297
|
}
|
|
278
298
|
const already = terminal.get('cellularEnabled') === true === enable && (!enable || terminal.get('cellularConfigurationId') === terminal.get('stripeConfigurationId'));
|
|
@@ -297,7 +317,7 @@ function cellularReadersRef() {
|
|
|
297
317
|
cellularConfigurationId: saved.configurationId,
|
|
298
318
|
cellularChangedAtMs: now,
|
|
299
319
|
cellularChangedBy: staff.uid
|
|
300
|
-
}, enable ? {
|
|
320
|
+
}, enable && !ownAccount ? {
|
|
301
321
|
cellularConsent: {
|
|
302
322
|
atMs: now,
|
|
303
323
|
uid: staff.uid,
|
|
@@ -326,13 +346,15 @@ function cellularReadersRef() {
|
|
|
326
346
|
* Turns 4G off at Stripe on a store's Configuration, by its id: for a store
|
|
327
347
|
* or workspace that is being deleted, whose settings may be gone already.
|
|
328
348
|
* True when Stripe took it, or the Configuration no longer exists.
|
|
329
|
-
*/ export async function turnOffPosCellularConfiguration(configurationId) {
|
|
349
|
+
*/ export async function turnOffPosCellularConfiguration(configurationId, /** The store's own account the Configuration is on; null for the platform. */ stripeAccount = null) {
|
|
330
350
|
if (!/^tmc_[A-Za-z0-9]+$/.test(configurationId)) return false;
|
|
331
|
-
const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, {
|
|
351
|
+
const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, _extends({
|
|
332
352
|
params: {
|
|
333
353
|
'cellular[enabled]': false
|
|
334
354
|
}
|
|
335
|
-
}
|
|
355
|
+
}, stripeAccount ? {
|
|
356
|
+
stripeAccount
|
|
357
|
+
} : {}));
|
|
336
358
|
return answer.ok || answer.status === 404;
|
|
337
359
|
}
|
|
338
360
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular.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 { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n closePosCellularPeriod,\n isPosCellularDeviceType,\n openPosCellularPeriod,\n parsePosCellularConfig,\n posCellularReaderId,\n posCellularMonthLabel,\n posCellularReaderMonthlyCents,\n POS_CELLULAR_CHARGES_COLLECTION,\n POS_CELLULAR_READERS_COLLECTION,\n type PosCellularCharge,\n type PosCellularReaderRecord,\n} from '../model/pos-cellular'\nimport type { PosStaff } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\nimport { savePosReaderConfiguration } from './pos-terminal'\n\n/*==========================================\n * TURNING 4G ON AND OFF FOR A STORE (AGL-4038).\n *\n * The POS devices card's \"Turn on 4G\" sets `cellular[enabled]` on the\n * store's ONE Terminal Configuration (`savePosReaderConfiguration`, where\n * tipping, offline mode and the start-up screen also live), so every Stripe\n * Reader S710 at the store has 4G from the next time it connects. See\n * `model/pos-cellular.ts` for why it is per store and what it costs.\n *\n * Each S710 at a store with 4G on has an open period on its\n * `posCellularReaders` record, which is what the month's charge counts\n * (`pos-cellular-billing.ts`). The records follow the store: turning 4G on\n * or off, and adding or removing a reader, re-reads the store's readers and\n * opens or closes each one's period ({@link syncPosCellularReaders}).\n *\n * Turning it on needs the workspace to be billable (a Stripe customer, so a\n * card on file) and the person's agreement to the monthly charge, which the\n * store's terminal settings record with the price they agreed to. It is\n * charged to the workspace, so turning it ON also takes the workspace's\n * \"Manage billing\" key (`billing.manage`) beside the card's \"Registers and\n * devices\"; turning it off takes only the card's key. While a month's charge\n * is unpaid past its grace period (`pos-cellular-billing.ts`), it cannot be\n * turned on again: paying it, then turning it on, is the way back.\n *=========================================*/\n\n/** The workspace key turning 4G on takes, beside \"Registers and devices\". */\nexport const POS_CELLULAR_BILLING_PERMISSION = 'billing.manage'\n\n/** What a member without it is told, naming the permission. */\nexport const POS_CELLULAR_BILLING_REFUSAL =\n 'Your role does not include \"Manage billing\" — ask an organization admin. 4G is charged to the workspace.'\n\n/** Whether the member may turn 4G on for a store: the workspace's \"Manage billing\", resolved for that store. */\nexport async function mayTurnOnPosCellular(uid: string, hostId: string): Promise<boolean> {\n const resolved = await resolveOrgPermissions(uid, { hostId }).catch(() => null)\n return resolved?.permissions?.[POS_CELLULAR_BILLING_PERMISSION] === true\n}\n\n/**\n * A charge's invoice as Stripe has it now: its status and what it collected,\n * or null when Stripe could not be asked (which is never read as \"unpaid\n * long enough to act on\" nor as \"paid\").\n */\nexport async function posCellularInvoiceStatus(\n invoiceId: string,\n): Promise<{ status: string; amountPaidCents: number } | null> {\n if (!/^in_[A-Za-z0-9]+$/.test(invoiceId)) return null\n const answer = await posStripe('GET', `invoices/${invoiceId}`).catch(() => null)\n if (!answer?.ok) return null\n const body = answer.body as { status?: unknown; amount_paid?: unknown }\n const status = String(body.status ?? '')\n return status ? { status, amountPaidCents: Math.max(0, Math.round(Number(body.amount_paid) || 0)) } : null\n}\n\n/**\n * The month whose unpaid charge turned 4G off for the workspace and is STILL\n * unpaid, or null. Asks Stripe about each, so one paid since is settled as\n * paid here, and its stores' notices cleared, rather than waiting for the\n * next daily run.\n */\nexport async function unpaidPosCellularSuspension(\n orgId: string,\n now: number,\n invoiceStatus: (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null> = posCellularInvoiceStatus,\n): Promise<{ month: string } | null> {\n const snapshot = await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .where('orgId', '==', orgId)\n .where('state', '==', 'suspended')\n .limit(24)\n .get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const charge = doc.data()\n const invoice = charge.invoiceId ? await invoiceStatus(charge.invoiceId) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n await settleSuspendedPosCellularCharge(String(doc.id), charge, invoice.status === 'paid' ? 'paid' : 'voided', invoice.amountPaidCents, now)\n continue\n }\n return { month: charge.month }\n }\n return null\n}\n\n/**\n * A suspended month that was paid (or voided by staff): settled, and the\n * notice on each store it turned 4G off for taken down. 4G stays off until\n * the merchant turns it on again.\n */\nexport async function settleSuspendedPosCellularCharge(\n chargeId: string,\n charge: PosCellularCharge,\n state: 'paid' | 'voided',\n paidCents: number,\n now: number,\n): Promise<void> {\n await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .doc(chargeId)\n .set({ state, ...(state === 'paid' ? { paidCents } : {}), updatedAtMs: now }, { merge: true })\n for (const hostId of charge.suspendedHostIds ?? []) {\n const ref = terminalConfigRef(hostId)\n const terminal = await ref.get()\n const notice = terminal.exists ? (terminal.get('cellularSuspended') as { month?: unknown } | null) : null\n if (notice?.month === charge.month) await ref.set({ cellularSuspended: null }, { merge: true })\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction terminalConfigRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminal').doc('config')\n}\n\nfunction readersRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminalReaders')\n}\n\nfunction cellularReadersRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nexport interface PosCellularAnswer {\n status: number\n body: { ok: true; enabled: boolean } | { error: string; code?: string }\n}\n\n/**\n * Opens a 4G period for every S710 the store has while 4G is on, and closes\n * every open one that should not be: 4G off, or the reader gone. In one\n * transaction over the store's records, so two calls at once never open a\n * reader twice. Idempotent, and cheap where the store never had 4G: one\n * read of its settings and one of its (empty) records.\n */\nexport async function syncPosCellularReaders(input: {\n hostId: string\n orgId: string\n now?: number\n}): Promise<{ open: number; closed: number }> {\n const now = input.now ?? Date.now()\n const [terminal, readers] = await Promise.all([\n terminalConfigRef(input.hostId).get(),\n readersRef(input.hostId).limit(50).get(),\n ])\n const enabled = terminal.get('cellularEnabled') === true\n const configurationId = String(terminal.get('stripeConfigurationId') ?? '') || null\n const capable = new Map<string, { serialNumber: string | null }>()\n for (const doc of readers.docs as Array<{ id: string; get: (field: string) => unknown }>) {\n if (isPosCellularDeviceType(doc.get('deviceType'))) {\n capable.set(String(doc.id), { serialNumber: String(doc.get('serialNumber') ?? '') || null })\n }\n }\n return firestore().runTransaction(async (transaction: any) => {\n const known = await transaction.get(cellularReadersRef().where('hostId', '==', input.hostId).limit(100))\n const records = new Map<string, PosCellularReaderRecord>()\n for (const doc of known.docs as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n records.set(String(doc.id), doc.data())\n }\n let open = 0\n let closed = 0\n if (enabled) {\n for (const [readerId, reader] of capable) {\n const id = posCellularReaderId(input.hostId, readerId)\n const existing = records.get(id) ?? null\n const next = openPosCellularPeriod(\n {\n orgId: input.orgId,\n hostId: input.hostId,\n readerId,\n serialNumber: reader.serialNumber,\n stripeConfigurationId: configurationId,\n },\n existing,\n now,\n )\n open += 1\n const unchanged =\n existing?.enabled === true &&\n existing.periods.some((period) => period.toMs === null) &&\n existing.orgId === input.orgId &&\n existing.serialNumber === reader.serialNumber &&\n existing.stripeConfigurationId === configurationId\n if (unchanged) continue\n transaction.set(cellularReadersRef().doc(id), next)\n }\n }\n for (const [id, record] of records) {\n const keep = enabled && capable.has(record.readerId)\n if (keep || !record.enabled) continue\n transaction.set(cellularReadersRef().doc(id), closePosCellularPeriod(record, now))\n closed += 1\n }\n return { open, closed }\n })\n}\n\n/**\n * `cellular` on the card readers route: turns 4G on (`enabled: true`, with\n * `consent: true`) or off for the caller's store. The route has already\n * checked the \"Registers and devices\" key on the store.\n */\nexport async function setPosStoreCellular(\n staff: PosStaff,\n body: Record<string, unknown>,\n): Promise<PosCellularAnswer> {\n const config = parsePosCellularConfig(process.env)\n // Not offered: answered as unknown, the way the card never shows it.\n if (!config || !posTerminalAvailable()) {\n return { status: 404, body: { error: '4G is not available.', code: 'cellular-unavailable' } }\n }\n if (typeof body['enabled'] !== 'boolean') return { status: 400, body: { error: 'Say whether 4G is on or off.' } }\n const enable = body['enabled'] === true\n const terminalRef = terminalConfigRef(staff.hostId)\n const terminal = await terminalRef.get()\n if (!terminal.get('stripeLocationId')) {\n return { status: 409, body: { error: 'Add a card reader to this store first.', code: 'no-location' } }\n }\n if (enable) {\n // Charged to the workspace: its billing key, as well as the card's own.\n if (!(await mayTurnOnPosCellular(staff.uid, staff.hostId))) {\n return { status: 403, body: { error: POS_CELLULAR_BILLING_REFUSAL, code: 'billing-permission' } }\n }\n if (body['consent'] !== true) {\n return {\n status: 400,\n body: { error: 'Agree to the monthly charge for each reader to turn 4G on.', code: 'consent-required' },\n }\n }\n const readers = await readersRef(staff.hostId).limit(50).get()\n const capable = (readers.docs as Array<{ get: (field: string) => unknown }>).some((doc) =>\n isPosCellularDeviceType(doc.get('deviceType')),\n )\n if (!capable) {\n return {\n status: 409,\n body: { error: '4G works on the S710 reader. Add one to this store first.', code: 'no-capable-reader' },\n }\n }\n const billing = (await readOrgBilling(staff.orgId).catch(() => ({}))) as { stripeCustomerId?: unknown }\n if (!String(billing.stripeCustomerId ?? '')) {\n return {\n status: 409,\n body: {\n error: 'Add a payment method in Billing first: 4G is charged to this workspace each month.',\n code: 'no-billing',\n },\n }\n }\n // Turned off for an unpaid month: paid first, then on again.\n const unpaid = await unpaidPosCellularSuspension(staff.orgId, Date.now())\n if (unpaid) {\n return {\n status: 409,\n body: {\n error: `4G was turned off because the 4G charge for ${posCellularMonthLabel(unpaid.month)} wasn't paid. Pay it on the Billing page, then turn 4G on again.`,\n code: 'cellular-unpaid',\n },\n }\n }\n }\n const already =\n (terminal.get('cellularEnabled') === true) === enable &&\n (!enable || terminal.get('cellularConfigurationId') === terminal.get('stripeConfigurationId'))\n const now = Date.now()\n if (!already) {\n // Each direction keys its own first create: one key sent with other\n // parameters is refused by Stripe for a day.\n const saved = await savePosReaderConfiguration(\n staff.hostId,\n { 'cellular[enabled]': enable },\n enable ? 'cellular-on' : 'cellular-off',\n )\n if ('error' in saved) {\n console.error('[pos-cellular] Stripe refused the cellular setting', staff.hostId, saved.error)\n return {\n status: 502,\n body: { error: enable ? 'Stripe did not turn 4G on. Try again.' : 'Stripe did not turn 4G off. Try again.' },\n }\n }\n await terminalRef.set(\n {\n cellularEnabled: enable,\n cellularConfigurationId: saved.configurationId,\n cellularChangedAtMs: now,\n cellularChangedBy: staff.uid,\n // What they agreed to, and when: the price per reader at the time.\n ...(enable ? { cellularConsent: { atMs: now, uid: staff.uid, readerMonthlyCents: posCellularReaderMonthlyCents(config) } } : {}),\n // On again: the notice of an unpaid month that turned it off is done.\n ...(enable ? { cellularSuspended: null } : {}),\n },\n { merge: true },\n )\n }\n await syncPosCellularReaders({ hostId: staff.hostId, orgId: staff.orgId, now })\n return { status: 200, body: { ok: true, enabled: enable } }\n}\n\n/**\n * Turns 4G off at Stripe on a store's Configuration, by its id: for a store\n * or workspace that is being deleted, whose settings may be gone already.\n * True when Stripe took it, or the Configuration no longer exists.\n */\nexport async function turnOffPosCellularConfiguration(configurationId: string): Promise<boolean> {\n if (!/^tmc_[A-Za-z0-9]+$/.test(configurationId)) return false\n const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, {\n params: { 'cellular[enabled]': false },\n })\n return answer.ok || answer.status === 404\n}\n"],"names":["firebaseAdmin","readOrgBilling","resolveOrgPermissions","closePosCellularPeriod","isPosCellularDeviceType","openPosCellularPeriod","parsePosCellularConfig","posCellularReaderId","posCellularMonthLabel","posCellularReaderMonthlyCents","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","posStripe","posTerminalAvailable","savePosReaderConfiguration","POS_CELLULAR_BILLING_PERMISSION","POS_CELLULAR_BILLING_REFUSAL","mayTurnOnPosCellular","uid","hostId","resolved","catch","permissions","posCellularInvoiceStatus","invoiceId","body","test","answer","ok","status","String","amountPaidCents","Math","max","round","Number","amount_paid","unpaidPosCellularSuspension","orgId","now","invoiceStatus","snapshot","firestore","collection","where","limit","get","doc","docs","charge","data","invoice","settleSuspendedPosCellularCharge","id","month","chargeId","state","paidCents","set","updatedAtMs","merge","suspendedHostIds","ref","terminalConfigRef","terminal","notice","exists","cellularSuspended","app","readersRef","cellularReadersRef","syncPosCellularReaders","input","Date","readers","Promise","all","enabled","configurationId","capable","Map","serialNumber","runTransaction","transaction","known","records","open","closed","readerId","reader","existing","next","stripeConfigurationId","unchanged","periods","some","period","toMs","record","keep","has","setPosStoreCellular","staff","config","process","env","error","code","enable","terminalRef","billing","stripeCustomerId","unpaid","already","saved","console","cellularEnabled","cellularConfigurationId","cellularChangedAtMs","cellularChangedBy","cellularConsent","atMs","readerMonthlyCents","turnOffPosCellularConfiguration","params"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,sBAAsB,EACtBC,uBAAuB,EACvBC,qBAAqB,EACrBC,sBAAsB,EACtBC,mBAAmB,EACnBC,qBAAqB,EACrBC,6BAA6B,EAC7BC,+BAA+B,EAC/BC,+BAA+B,QAG1B,2BAAuB;AAE9B,SAASC,SAAS,EAAEC,oBAAoB,QAAQ,kBAAc;AAC9D,SAASC,0BAA0B,QAAQ,oBAAgB;AAE3D;;;;;;;;;;;;;;;;;;;;;;;2CAuB2C,GAE3C,2EAA2E,GAC3E,OAAO,MAAMC,kCAAkC,iBAAgB;AAE/D,6DAA6D,GAC7D,OAAO,MAAMC,+BACX,2GAA0G;AAE5G,8GAA8G,GAC9G,OAAO,eAAeC,qBAAqBC,GAAW,EAAEC,MAAc;QAE7DC;IADP,MAAMA,WAAW,MAAMlB,sBAAsBgB,KAAK;QAAEC;IAAO,GAAGE,KAAK,CAAC,IAAM;IAC1E,OAAOD,CAAAA,6BAAAA,wBAAAA,SAAUE,WAAW,qBAArBF,qBAAuB,CAACL,gCAAgC,MAAK;AACtE;AAEA;;;;CAIC,GACD,OAAO,eAAeQ,yBACpBC,SAAiB;QAMKC;IAJtB,IAAI,CAAC,oBAAoBC,IAAI,CAACF,YAAY,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,OAAOE,MAAM,KAAK;AACxC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular.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 { firebaseAdmin, readOrgBilling } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n closePosCellularPeriod,\n isPosCellularDeviceType,\n openPosCellularPeriod,\n parsePosCellularConfig,\n posCellularOwnAccount,\n posCellularReaderId,\n posCellularMonthLabel,\n posCellularReaderMonthlyCents,\n POS_CELLULAR_CHARGES_COLLECTION,\n POS_CELLULAR_READERS_COLLECTION,\n type PosCellularCharge,\n type PosCellularReaderRecord,\n} from '../model/pos-cellular'\nimport type { PosStaff } from './pos-auth'\nimport { posStripe, posTerminalAvailable } from './pos-stripe'\nimport { savePosReaderConfiguration } from './pos-terminal'\n\n/*==========================================\n * TURNING 4G ON AND OFF FOR A STORE (AGL-4038).\n *\n * The POS devices card's \"Turn on 4G\" sets `cellular[enabled]` on the\n * store's ONE Terminal Configuration (`savePosReaderConfiguration`, where\n * tipping, offline mode and the start-up screen also live), so every Stripe\n * Reader S710 at the store has 4G from the next time it connects. See\n * `model/pos-cellular.ts` for why it is per store and what it costs.\n *\n * Each S710 at a store with 4G on has an open period on its\n * `posCellularReaders` record, which is what the month's charge counts\n * (`pos-cellular-billing.ts`). The records follow the store: turning 4G on\n * or off, and adding or removing a reader, re-reads the store's readers and\n * opens or closes each one's period ({@link syncPosCellularReaders}).\n *\n * Turning it on needs the workspace to be billable (a Stripe customer, so a\n * card on file) and the person's agreement to the monthly charge, which the\n * store's terminal settings record with the price they agreed to. It is\n * charged to the workspace, so turning it ON also takes the workspace's\n * \"Manage billing\" key (`billing.manage`) beside the card's \"Registers and\n * devices\"; turning it off takes only the card's key. While a month's charge\n * is unpaid past its grace period (`pos-cellular-billing.ts`), it cannot be\n * turned on again: paying it, then turning it on, is the way back.\n *\n * A store whose Location, and so its Configuration, is on its OWN Stripe\n * account (direct charges: `stripeLocationAccount`, the account\n * `savePosReaderConfiguration` writes to) is billed for 4G by Stripe, on\n * that account, under the store's own agreement with Stripe. The workspace\n * is never charged for it, so turning it on there takes only the card's\n * \"Registers and devices\": no \"Manage billing\", no card on file, no\n * agreement to the platform's price, and no unpaid month of the workspace's\n * holds it back.\n *=========================================*/\n\n/** The workspace key turning 4G on takes, beside \"Registers and devices\". */\nexport const POS_CELLULAR_BILLING_PERMISSION = 'billing.manage'\n\n/** What a member without it is told, naming the permission. */\nexport const POS_CELLULAR_BILLING_REFUSAL =\n 'Your role does not include \"Manage billing\" — ask an organization admin. 4G is charged to the workspace.'\n\n/** Whether the member may turn 4G on for a store: the workspace's \"Manage billing\", resolved for that store. */\nexport async function mayTurnOnPosCellular(uid: string, hostId: string): Promise<boolean> {\n const resolved = await resolveOrgPermissions(uid, { hostId }).catch(() => null)\n return resolved?.permissions?.[POS_CELLULAR_BILLING_PERMISSION] === true\n}\n\n/**\n * A charge's invoice as Stripe has it now: its status and what it collected,\n * or null when Stripe could not be asked (which is never read as \"unpaid\n * long enough to act on\" nor as \"paid\").\n */\nexport async function posCellularInvoiceStatus(\n invoiceId: string,\n): Promise<{ status: string; amountPaidCents: number } | null> {\n if (!/^in_[A-Za-z0-9]+$/.test(invoiceId)) return null\n const answer = await posStripe('GET', `invoices/${invoiceId}`).catch(() => null)\n if (!answer?.ok) return null\n const body = answer.body as { status?: unknown; amount_paid?: unknown }\n const status = String(body.status ?? '')\n return status ? { status, amountPaidCents: Math.max(0, Math.round(Number(body.amount_paid) || 0)) } : null\n}\n\n/**\n * The month whose unpaid charge turned 4G off for the workspace and is STILL\n * unpaid, or null. Asks Stripe about each, so one paid since is settled as\n * paid here, and its stores' notices cleared, rather than waiting for the\n * next daily run.\n */\nexport async function unpaidPosCellularSuspension(\n orgId: string,\n now: number,\n invoiceStatus: (invoiceId: string) => Promise<{ status: string; amountPaidCents: number } | null> = posCellularInvoiceStatus,\n): Promise<{ month: string } | null> {\n const snapshot = await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .where('orgId', '==', orgId)\n .where('state', '==', 'suspended')\n .limit(24)\n .get()\n for (const doc of snapshot.docs as unknown as Array<{ id: string; data: () => PosCellularCharge }>) {\n const charge = doc.data()\n const invoice = charge.invoiceId ? await invoiceStatus(charge.invoiceId) : null\n if (invoice?.status === 'paid' || invoice?.status === 'void') {\n await settleSuspendedPosCellularCharge(String(doc.id), charge, invoice.status === 'paid' ? 'paid' : 'voided', invoice.amountPaidCents, now)\n continue\n }\n return { month: charge.month }\n }\n return null\n}\n\n/**\n * A suspended month that was paid (or voided by staff): settled, and the\n * notice on each store it turned 4G off for taken down. 4G stays off until\n * the merchant turns it on again.\n */\nexport async function settleSuspendedPosCellularCharge(\n chargeId: string,\n charge: PosCellularCharge,\n state: 'paid' | 'voided',\n paidCents: number,\n now: number,\n): Promise<void> {\n await firestore()\n .collection(POS_CELLULAR_CHARGES_COLLECTION)\n .doc(chargeId)\n .set({ state, ...(state === 'paid' ? { paidCents } : {}), updatedAtMs: now }, { merge: true })\n for (const hostId of charge.suspendedHostIds ?? []) {\n const ref = terminalConfigRef(hostId)\n const terminal = await ref.get()\n const notice = terminal.exists ? (terminal.get('cellularSuspended') as { month?: unknown } | null) : null\n if (notice?.month === charge.month) await ref.set({ cellularSuspended: null }, { merge: true })\n }\n}\n\nfunction firestore() {\n return firebaseAdmin.app().firestore()\n}\n\nfunction terminalConfigRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminal').doc('config')\n}\n\nfunction readersRef(hostId: string) {\n return firestore().collection('hosts').doc(hostId).collection('terminalReaders')\n}\n\nfunction cellularReadersRef() {\n return firestore().collection(POS_CELLULAR_READERS_COLLECTION)\n}\n\nexport interface PosCellularAnswer {\n status: number\n body: { ok: true; enabled: boolean } | { error: string; code?: string }\n}\n\n/**\n * Opens a 4G period for every S710 the store has while 4G is on, and closes\n * every open one that should not be: 4G off, or the reader gone. In one\n * transaction over the store's records, so two calls at once never open a\n * reader twice. Idempotent, and cheap where the store never had 4G: one\n * read of its settings and one of its (empty) records.\n */\nexport async function syncPosCellularReaders(input: {\n hostId: string\n orgId: string\n now?: number\n}): Promise<{ open: number; closed: number }> {\n const now = input.now ?? Date.now()\n const [terminal, readers] = await Promise.all([\n terminalConfigRef(input.hostId).get(),\n readersRef(input.hostId).limit(50).get(),\n ])\n const enabled = terminal.get('cellularEnabled') === true\n const configurationId = String(terminal.get('stripeConfigurationId') ?? '') || null\n // The account that configuration lives on: the store's own for a\n // direct-charge store's Location, absent for the platform's.\n const configurationAccount = posCellularOwnAccount(terminal.get('stripeLocationAccount'))\n const capable = new Map<string, { serialNumber: string | null }>()\n for (const doc of readers.docs as Array<{ id: string; get: (field: string) => unknown }>) {\n if (isPosCellularDeviceType(doc.get('deviceType'))) {\n capable.set(String(doc.id), { serialNumber: String(doc.get('serialNumber') ?? '') || null })\n }\n }\n return firestore().runTransaction(async (transaction: any) => {\n const known = await transaction.get(cellularReadersRef().where('hostId', '==', input.hostId).limit(100))\n const records = new Map<string, PosCellularReaderRecord>()\n for (const doc of known.docs as Array<{ id: string; data: () => PosCellularReaderRecord }>) {\n records.set(String(doc.id), doc.data())\n }\n let open = 0\n let closed = 0\n if (enabled) {\n for (const [readerId, reader] of capable) {\n const id = posCellularReaderId(input.hostId, readerId)\n const existing = records.get(id) ?? null\n const next = openPosCellularPeriod(\n {\n orgId: input.orgId,\n hostId: input.hostId,\n readerId,\n serialNumber: reader.serialNumber,\n stripeConfigurationId: configurationId,\n ...(configurationAccount ? { stripeConfigurationAccount: configurationAccount } : {}),\n },\n existing,\n now,\n )\n open += 1\n const unchanged =\n existing?.enabled === true &&\n existing.periods.some((period) => period.toMs === null) &&\n existing.orgId === input.orgId &&\n existing.serialNumber === reader.serialNumber &&\n existing.stripeConfigurationId === configurationId &&\n (existing.stripeConfigurationAccount ?? null) === configurationAccount\n if (unchanged) continue\n transaction.set(cellularReadersRef().doc(id), next)\n }\n }\n for (const [id, record] of records) {\n const keep = enabled && capable.has(record.readerId)\n if (keep || !record.enabled) continue\n transaction.set(cellularReadersRef().doc(id), closePosCellularPeriod(record, now))\n closed += 1\n }\n return { open, closed }\n })\n}\n\n/**\n * `cellular` on the card readers route: turns 4G on (`enabled: true`, with\n * `consent: true`) or off for the caller's store. The route has already\n * checked the \"Registers and devices\" key on the store.\n */\nexport async function setPosStoreCellular(\n staff: PosStaff,\n body: Record<string, unknown>,\n): Promise<PosCellularAnswer> {\n const config = parsePosCellularConfig(process.env)\n // Not offered: answered as unknown, the way the card never shows it.\n if (!config || !posTerminalAvailable()) {\n return { status: 404, body: { error: '4G is not available.', code: 'cellular-unavailable' } }\n }\n if (typeof body['enabled'] !== 'boolean') return { status: 400, body: { error: 'Say whether 4G is on or off.' } }\n const enable = body['enabled'] === true\n const terminalRef = terminalConfigRef(staff.hostId)\n const terminal = await terminalRef.get()\n if (!terminal.get('stripeLocationId')) {\n return { status: 409, body: { error: 'Add a card reader to this store first.', code: 'no-location' } }\n }\n // On the store's own Stripe account, Stripe bills the 4G to that account:\n // nothing here is charged to the workspace.\n const ownAccount = posCellularOwnAccount(terminal.get('stripeLocationAccount')) !== null\n if (enable) {\n // Charged to the workspace: its billing key, as well as the card's own,\n // and the person's agreement to the price.\n if (!ownAccount && !(await mayTurnOnPosCellular(staff.uid, staff.hostId))) {\n return { status: 403, body: { error: POS_CELLULAR_BILLING_REFUSAL, code: 'billing-permission' } }\n }\n if (!ownAccount && body['consent'] !== true) {\n return {\n status: 400,\n body: { error: 'Agree to the monthly charge for each reader to turn 4G on.', code: 'consent-required' },\n }\n }\n const readers = await readersRef(staff.hostId).limit(50).get()\n const capable = (readers.docs as Array<{ get: (field: string) => unknown }>).some((doc) =>\n isPosCellularDeviceType(doc.get('deviceType')),\n )\n if (!capable) {\n return {\n status: 409,\n body: { error: '4G works on the S710 reader. Add one to this store first.', code: 'no-capable-reader' },\n }\n }\n if (!ownAccount) {\n const billing = (await readOrgBilling(staff.orgId).catch(() => ({}))) as { stripeCustomerId?: unknown }\n if (!String(billing.stripeCustomerId ?? '')) {\n return {\n status: 409,\n body: {\n error: 'Add a payment method in Billing first: 4G is charged to this workspace each month.',\n code: 'no-billing',\n },\n }\n }\n // Turned off for an unpaid month: paid first, then on again.\n const unpaid = await unpaidPosCellularSuspension(staff.orgId, Date.now())\n if (unpaid) {\n return {\n status: 409,\n body: {\n error: `4G was turned off because the 4G charge for ${posCellularMonthLabel(unpaid.month)} wasn't paid. Pay it on the Billing page, then turn 4G on again.`,\n code: 'cellular-unpaid',\n },\n }\n }\n }\n }\n const already =\n (terminal.get('cellularEnabled') === true) === enable &&\n (!enable || terminal.get('cellularConfigurationId') === terminal.get('stripeConfigurationId'))\n const now = Date.now()\n if (!already) {\n // Each direction keys its own first create: one key sent with other\n // parameters is refused by Stripe for a day.\n const saved = await savePosReaderConfiguration(\n staff.hostId,\n { 'cellular[enabled]': enable },\n enable ? 'cellular-on' : 'cellular-off',\n )\n if ('error' in saved) {\n console.error('[pos-cellular] Stripe refused the cellular setting', staff.hostId, saved.error)\n return {\n status: 502,\n body: { error: enable ? 'Stripe did not turn 4G on. Try again.' : 'Stripe did not turn 4G off. Try again.' },\n }\n }\n await terminalRef.set(\n {\n cellularEnabled: enable,\n cellularConfigurationId: saved.configurationId,\n cellularChangedAtMs: now,\n cellularChangedBy: staff.uid,\n // What they agreed to, and when: the price per reader at the time.\n // Nothing is agreed here for a store on its own Stripe account, which\n // Stripe bills under the store's own agreement with it.\n ...(enable && !ownAccount\n ? { cellularConsent: { atMs: now, uid: staff.uid, readerMonthlyCents: posCellularReaderMonthlyCents(config) } }\n : {}),\n // On again: the notice of an unpaid month that turned it off is done.\n ...(enable ? { cellularSuspended: null } : {}),\n },\n { merge: true },\n )\n }\n await syncPosCellularReaders({ hostId: staff.hostId, orgId: staff.orgId, now })\n return { status: 200, body: { ok: true, enabled: enable } }\n}\n\n/**\n * Turns 4G off at Stripe on a store's Configuration, by its id: for a store\n * or workspace that is being deleted, whose settings may be gone already.\n * True when Stripe took it, or the Configuration no longer exists.\n */\nexport async function turnOffPosCellularConfiguration(\n configurationId: string,\n /** The store's own account the Configuration is on; null for the platform. */\n stripeAccount: string | null = null,\n): Promise<boolean> {\n if (!/^tmc_[A-Za-z0-9]+$/.test(configurationId)) return false\n const answer = await posStripe('POST', `terminal/configurations/${configurationId}`, {\n params: { 'cellular[enabled]': false },\n ...(stripeAccount ? { stripeAccount } : {}),\n })\n return answer.ok || answer.status === 404\n}\n"],"names":["firebaseAdmin","readOrgBilling","resolveOrgPermissions","closePosCellularPeriod","isPosCellularDeviceType","openPosCellularPeriod","parsePosCellularConfig","posCellularOwnAccount","posCellularReaderId","posCellularMonthLabel","posCellularReaderMonthlyCents","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_READERS_COLLECTION","posStripe","posTerminalAvailable","savePosReaderConfiguration","POS_CELLULAR_BILLING_PERMISSION","POS_CELLULAR_BILLING_REFUSAL","mayTurnOnPosCellular","uid","hostId","resolved","catch","permissions","posCellularInvoiceStatus","invoiceId","body","test","answer","ok","status","String","amountPaidCents","Math","max","round","Number","amount_paid","unpaidPosCellularSuspension","orgId","now","invoiceStatus","snapshot","firestore","collection","where","limit","get","doc","docs","charge","data","invoice","settleSuspendedPosCellularCharge","id","month","chargeId","state","paidCents","set","updatedAtMs","merge","suspendedHostIds","ref","terminalConfigRef","terminal","notice","exists","cellularSuspended","app","readersRef","cellularReadersRef","syncPosCellularReaders","input","Date","readers","Promise","all","enabled","configurationId","configurationAccount","capable","Map","serialNumber","runTransaction","transaction","known","records","open","closed","readerId","reader","existing","next","stripeConfigurationId","stripeConfigurationAccount","unchanged","periods","some","period","toMs","record","keep","has","setPosStoreCellular","staff","config","process","env","error","code","enable","terminalRef","ownAccount","billing","stripeCustomerId","unpaid","already","saved","console","cellularEnabled","cellularConfigurationId","cellularChangedAtMs","cellularChangedBy","cellularConsent","atMs","readerMonthlyCents","turnOffPosCellularConfiguration","stripeAccount","params"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,aAAa,EAAEC,cAAc,QAAQ,2BAA0B;AACxE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,sBAAsB,EACtBC,uBAAuB,EACvBC,qBAAqB,EACrBC,sBAAsB,EACtBC,qBAAqB,EACrBC,mBAAmB,EACnBC,qBAAqB,EACrBC,6BAA6B,EAC7BC,+BAA+B,EAC/BC,+BAA+B,QAG1B,2BAAuB;AAE9B,SAASC,SAAS,EAAEC,oBAAoB,QAAQ,kBAAc;AAC9D,SAASC,0BAA0B,QAAQ,oBAAgB;AAE3D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAgC2C,GAE3C,2EAA2E,GAC3E,OAAO,MAAMC,kCAAkC,iBAAgB;AAE/D,6DAA6D,GAC7D,OAAO,MAAMC,+BACX,2GAA0G;AAE5G,8GAA8G,GAC9G,OAAO,eAAeC,qBAAqBC,GAAW,EAAEC,MAAc;QAE7DC;IADP,MAAMA,WAAW,MAAMnB,sBAAsBiB,KAAK;QAAEC;IAAO,GAAGE,KAAK,CAAC,IAAM;IAC1E,OAAOD,CAAAA,6BAAAA,wBAAAA,SAAUE,WAAW,qBAArBF,qBAAuB,CAACL,gCAAgC,MAAK;AACtE;AAEA;;;;CAIC,GACD,OAAO,eAAeQ,yBACpBC,SAAiB;QAMKC;IAJtB,IAAI,CAAC,oBAAoBC,IAAI,CAACF,YAAY,OAAO;IACjD,MAAMG,SAAS,MAAMf,UAAU,OAAO,CAAC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QAAQ;QAAKJ,MAAM;YAAEG,IAAI;YAAMiD,SAASiC;QAAO;IAAE;AAC5D;AAEA;;;;CAIC,GACD,OAAO,eAAegB,gCACpBhD,eAAuB,EACvB,4EAA4E,GAC5EiD,gBAA+B,IAAI;IAEnC,IAAI,CAAC,qBAAqBrG,IAAI,CAACoD,kBAAkB,OAAO;IACxD,MAAMnD,SAAS,MAAMf,UAAU,QAAQ,CAAC,wBAAwB,EAAEkE,iBAAiB,EAAE;QACnFkD,QAAQ;YAAE,qBAAqB;QAAM;OACjCD,gBAAgB;QAAEA;IAAc,IAAI,CAAC;IAE3C,OAAOpG,OAAOC,EAAE,IAAID,OAAOE,MAAM,KAAK;AACxC"}
|
|
@@ -19,7 +19,7 @@ import type { PluginApiHandler, PluginApiRequest } from '@aglyn/aglyn/server';
|
|
|
19
19
|
import * as CommerceModel from '../model';
|
|
20
20
|
import { type PosOfflineFlag, type PosOfflineKit, type PosOfflineStockConflict } from '../model/commerce-pos-offline';
|
|
21
21
|
import { type PosOpsDeps, type PosOpsStaff } from './pos-ops-gate';
|
|
22
|
-
import { type PosOfflineCardIntent } from './pos-terminal';
|
|
22
|
+
import { type PosMerchant, type PosOfflineCardIntent } from './pos-terminal';
|
|
23
23
|
import { type StockDecrementOutcome } from './reserve-stock';
|
|
24
24
|
/** The register's sync record: no customer data, only what dedupe and resume need. */
|
|
25
25
|
export interface PosOfflineSyncRecord {
|
|
@@ -74,8 +74,8 @@ export interface PosOfflineCardDeps {
|
|
|
74
74
|
available: boolean;
|
|
75
75
|
locationId: string | null;
|
|
76
76
|
}>;
|
|
77
|
-
/** The merchant's connected account, when it can take card payments. */
|
|
78
|
-
merchantAccount(hostId: string, org: Record<string, any> | null): Promise<
|
|
77
|
+
/** The merchant's connected account and how it sells, when it can take card payments. */
|
|
78
|
+
merchantAccount(hostId: string, org: Record<string, any> | null): Promise<PosMerchant | null>;
|
|
79
79
|
/** Turns Stripe's offline mode on for the site's readers; false when Stripe refused. */
|
|
80
80
|
enableOffline(hostId: string): Promise<boolean>;
|
|
81
81
|
retrieve(paymentIntentId: string): Promise<{
|