@aglyn/plugins-commerce 1.16.0 → 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.
@@ -111,6 +111,21 @@ export interface PosCellularReaderRecord {
111
111
  disabledAtMs: number | null;
112
112
  updatedAtMs: number;
113
113
  }
114
+ /**
115
+ * The store's own Stripe account its 4G Configuration is on, from the
116
+ * account its terminal settings record for its Location
117
+ * (`stripeLocationAccount`), or null when it is on the platform. The
118
+ * Configuration always lives where the Location does
119
+ * (`savePosReaderConfiguration`), so this is the account Stripe bills.
120
+ */
121
+ export declare function posCellularOwnAccount(stripeLocationAccount: unknown): string | null;
122
+ /**
123
+ * Whether the platform pays Stripe for this reader's 4G, and so charges the
124
+ * workspace for it: its Configuration is on the platform. A reader whose
125
+ * Configuration is on the store's own Stripe account is billed by Stripe to
126
+ * that account, so the workspace is never charged for it here (Terms §4.32).
127
+ */
128
+ export declare function posCellularBilledToPlatform(record: Pick<PosCellularReaderRecord, 'stripeConfigurationAccount'>): boolean;
114
129
  /** The record's document id. */
115
130
  export declare function posCellularReaderId(hostId: string, readerId: string): string;
116
131
  /** The record with a period open from `now`, unless one already is. */
@@ -122,7 +137,11 @@ export declare function posCellularBilledInMonth(record: Pick<PosCellularReaderR
122
137
  startMs: number;
123
138
  endMs: number;
124
139
  }): boolean;
125
- /** Each workspace's readers that had 4G in the month, by workspace. */
140
+ /**
141
+ * Each workspace's readers that had 4G in the month and that the platform
142
+ * pays for, by workspace: what a month's charge counts. A reader on a store's
143
+ * own Stripe account is left out ({@link posCellularBilledToPlatform}).
144
+ */
126
145
  export declare function posCellularReadersByWorkspace(records: ReadonlyArray<PosCellularReaderRecord>, month: string): Map<string, {
127
146
  readers: number;
128
147
  hostIds: string[];
@@ -197,8 +216,14 @@ export interface PosCellularSuspension {
197
216
  }
198
217
  /** What the POS devices card is told about 4G for a store; null hides it. */
199
218
  export interface PosCellularView {
200
- /** What one reader costs a month, in cents, before any sales tax. */
201
- readerMonthlyCents: number;
219
+ /**
220
+ * What one reader costs the workspace a month, in cents, before any sales
221
+ * tax; null for a store on its own Stripe account, which Stripe bills at
222
+ * its own price and the workspace is never charged for.
223
+ */
224
+ readerMonthlyCents: number | null;
225
+ /** The store's 4G is on its own Stripe account, which Stripe bills directly. */
226
+ ownAccount: boolean;
202
227
  enabled: boolean;
203
228
  /** The store's readers that take 4G. */
204
229
  readers: number;
@@ -210,7 +235,8 @@ export interface PosCellularView {
210
235
  /**
211
236
  * Why the viewer may not turn 4G ON (it is charged to the workspace, so it
212
237
  * also takes "Manage billing"), or null. Turning it off needs only the
213
- * card's own key.
238
+ * card's own key, and so does turning it on for a store on its own Stripe
239
+ * account.
214
240
  */
215
241
  turnOnBlocked?: string | null;
216
242
  }
@@ -221,6 +247,7 @@ export interface PosCellularView {
221
247
  export declare function posCellularView(config: PosCellularConfig | null, terminal: {
222
248
  cellularEnabled?: unknown;
223
249
  cellularSuspended?: unknown;
250
+ stripeLocationAccount?: unknown;
224
251
  } | null | undefined, readers: ReadonlyArray<{
225
252
  deviceType?: unknown;
226
253
  }>, options?: {
@@ -66,6 +66,17 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
66
66
  * workspace, and they are told again; paying does not turn it back on, and
67
67
  * it cannot be turned on again until the charge is paid. A workspace deleted
68
68
  * mid-month is charged for that final month as it is erased.
69
+ *
70
+ * A STORE ON ITS OWN STRIPE ACCOUNT (direct charges, Terms §4.32) is the
71
+ * exception to all of that. Its Location, and so the Configuration that
72
+ * carries `cellular[enabled]`, is on the store's own full Stripe account
73
+ * (`stripeLocationAccount` on its terminal settings, which every reader
74
+ * record copies as `stripeConfigurationAccount`), and Stripe bills its 4G to
75
+ * that account under the store's own agreement with Stripe. The platform
76
+ * pays nothing for it, so the workspace is never charged for it here, never
77
+ * warned about it, and never has it turned off over a charge here
78
+ * ({@link posCellularBilledToPlatform}); and turning it on takes neither
79
+ * "Manage billing" nor an agreement to a price that is not the platform's.
69
80
  *=========================================*/ export const POS_CELLULAR_ENV = {
70
81
  monthlyCostCents: 'POS_CELLULAR_MONTHLY_COST_CENTS',
71
82
  billingCostBps: 'POS_CELLULAR_BILLING_COST_BPS',
@@ -168,6 +179,24 @@ function wholeNumber(text, fallback, max) {
168
179
  timeZone: 'UTC'
169
180
  });
170
181
  }
182
+ /**
183
+ * The store's own Stripe account its 4G Configuration is on, from the
184
+ * account its terminal settings record for its Location
185
+ * (`stripeLocationAccount`), or null when it is on the platform. The
186
+ * Configuration always lives where the Location does
187
+ * (`savePosReaderConfiguration`), so this is the account Stripe bills.
188
+ */ export function posCellularOwnAccount(stripeLocationAccount) {
189
+ const id = typeof stripeLocationAccount === 'string' ? stripeLocationAccount.trim() : '';
190
+ return id || null;
191
+ }
192
+ /**
193
+ * Whether the platform pays Stripe for this reader's 4G, and so charges the
194
+ * workspace for it: its Configuration is on the platform. A reader whose
195
+ * Configuration is on the store's own Stripe account is billed by Stripe to
196
+ * that account, so the workspace is never charged for it here (Terms §4.32).
197
+ */ export function posCellularBilledToPlatform(record) {
198
+ return posCellularOwnAccount(record.stripeConfigurationAccount) === null;
199
+ }
171
200
  /** The record's document id. */ export function posCellularReaderId(hostId, readerId) {
172
201
  return `${hostId}_${readerId}`;
173
202
  }
@@ -203,13 +232,17 @@ function wholeNumber(text, fallback, max) {
203
232
  var _record_periods;
204
233
  return ((_record_periods = record.periods) != null ? _record_periods : []).some((period)=>period.fromMs < bounds.endMs && (period.toMs === null || period.toMs > bounds.startMs));
205
234
  }
206
- /** Each workspace's readers that had 4G in the month, by workspace. */ export function posCellularReadersByWorkspace(records, month) {
235
+ /**
236
+ * Each workspace's readers that had 4G in the month and that the platform
237
+ * pays for, by workspace: what a month's charge counts. A reader on a store's
238
+ * own Stripe account is left out ({@link posCellularBilledToPlatform}).
239
+ */ export function posCellularReadersByWorkspace(records, month) {
207
240
  const bounds = posCellularMonthBounds(month);
208
241
  const byOrg = new Map();
209
242
  if (!bounds) return byOrg;
210
243
  for (const record of records){
211
244
  var _byOrg_get;
212
- if (!record.orgId || !posCellularBilledInMonth(record, bounds)) continue;
245
+ if (!record.orgId || !posCellularBilledToPlatform(record) || !posCellularBilledInMonth(record, bounds)) continue;
213
246
  const entry = (_byOrg_get = byOrg.get(record.orgId)) != null ? _byOrg_get : {
214
247
  readers: 0,
215
248
  hostIds: []
@@ -281,12 +314,14 @@ function wholeNumber(text, fallback, max) {
281
314
  month: posCellularMonthLabel(suspension.month),
282
315
  atMs: Number((_suspension_atMs = suspension.atMs) != null ? _suspension_atMs : 0)
283
316
  } : null;
317
+ const ownAccount = posCellularOwnAccount(terminal == null ? void 0 : terminal.stripeLocationAccount) !== null;
284
318
  return {
285
- readerMonthlyCents: posCellularReaderMonthlyCents(config),
319
+ readerMonthlyCents: ownAccount ? null : posCellularReaderMonthlyCents(config),
320
+ ownAccount,
286
321
  enabled,
287
322
  readers: capable,
288
323
  suspended,
289
- turnOnBlocked: (_options_turnOnBlocked = options.turnOnBlocked) != null ? _options_turnOnBlocked : null
324
+ turnOnBlocked: ownAccount ? null : (_options_turnOnBlocked = options.turnOnBlocked) != null ? _options_turnOnBlocked : null
290
325
  };
291
326
  }
292
327
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/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 {\n STRIPE_PROCESSOR_FEE_FIXED_USD,\n STRIPE_PROCESSOR_FEE_PCT,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\n\n/*==========================================\n * 4G FOR STRIPE READER S710s (AGL-4038).\n *\n * Stripe sells cellular service for the Stripe Reader S710 as a monthly\n * subscription per reader, billed to the Stripe account the reader is\n * registered to — which, for every reader a store sets up here, is the\n * PLATFORM's. A reader has it when the Terminal Location it is registered\n * to has a Configuration with `cellular[enabled]`; Stripe bills a reader for\n * every calendar month it had it at any time.\n *\n * So 4G is turned on for a STORE: the platform keeps one Location and one\n * Configuration per store (`pos-terminal.ts`), and the native apps' connection\n * tokens are scoped to that one Location, so a second, cellular Location for\n * some of a store's readers would be one those apps could never reach, and\n * moving a reader there takes a fresh pairing code. Every S710 at a store\n * with 4G on has it, and each one is charged.\n *\n * The store's workspace pays what the platform pays, passed through: per\n * S710 per calendar month, Stripe's cellular price, plus what collecting it\n * costs the platform (the card processing on the charge), with no markup.\n * Both are configuration, never literals here:\n *\n * POS_CELLULAR_MONTHLY_COST_CENTS Stripe's price per reader per\n * month, in cents. Unset: 4G is not\n * offered anywhere (hidden, not\n * disabled).\n * POS_CELLULAR_BILLING_COST_BPS the processing percentage on the\n * charge, in basis points (default:\n * the platform's card rate)\n * POS_CELLULAR_BILLING_COST_FIXED_CENTS the processing fixed fee per\n * charge (default: the platform's)\n * STRIPE_PRODUCT_POS_CELLULAR the product the invoice line is\n * billed against (its tax code);\n * `setup-stripe.mjs` makes it\n * POS_CELLULAR_GRACE_DAYS how long a month's charge may stay\n * unpaid before 4G is turned off for\n * the workspace's stores (default 14)\n *\n * Billed in ARREARS, once per workspace per calendar month, on a one-off\n * invoice through core's usage-invoice charge — the same path a domain or\n * an AI overage takes — for the readers that had 4G at any time that month,\n * which is what Stripe bills the platform for. Turning 4G off stops the\n * charge from the next calendar month.\n *\n * A charge that does not collect stays open on the workspace's Billing page\n * and staff are alerted; the people who manage its billing are warned the\n * same day, once, of the day 4G turns off unless it is paid. Still unpaid\n * after the grace period, 4G is turned off at Stripe for every store of the\n * workspace, and they are told again; paying does not turn it back on, and\n * it cannot be turned on again until the charge is paid. A workspace deleted\n * mid-month is charged for that final month as it is erased.\n *=========================================*/\n\nexport const POS_CELLULAR_ENV = {\n monthlyCostCents: 'POS_CELLULAR_MONTHLY_COST_CENTS',\n billingCostBps: 'POS_CELLULAR_BILLING_COST_BPS',\n billingCostFixedCents: 'POS_CELLULAR_BILLING_COST_FIXED_CENTS',\n productId: 'STRIPE_PRODUCT_POS_CELLULAR',\n graceDays: 'POS_CELLULAR_GRACE_DAYS',\n} as const\n\n/** How long a month's charge may stay unpaid before 4G is turned off, unless configured. */\nexport const POS_CELLULAR_DEFAULT_GRACE_DAYS = 14\n\n/** A day, in milliseconds. */\nexport const POS_CELLULAR_DAY_MS = 24 * 60 * 60 * 1000\n\n/** The platform's card processing rate, in basis points: the default billing cost. */\nexport const POS_CELLULAR_DEFAULT_BILLING_COST_BPS = Math.round(STRIPE_PROCESSOR_FEE_PCT * 10_000)\n\n/** The platform's card processing fixed fee, in cents: the default billing cost. */\nexport const POS_CELLULAR_DEFAULT_BILLING_COST_FIXED_CENTS = Math.round(STRIPE_PROCESSOR_FEE_FIXED_USD * 100)\n\n/** The Stripe device types that take cellular service: the S710, and its simulator. */\nexport const POS_CELLULAR_DEVICE_TYPES: readonly string[] = ['stripe_s710', 'simulated_stripe_s710']\n\n/** The top-level, server-only record of each reader's 4G months. */\nexport const POS_CELLULAR_READERS_COLLECTION = 'posCellularReaders'\n\n/** The top-level, server-only record of each workspace's monthly 4G charge. */\nexport const POS_CELLULAR_CHARGES_COLLECTION = 'posCellularCharges'\n\n/** The metadata `kind` the charge's invoice carries. */\nexport const POS_CELLULAR_CHARGE_KIND = 'pos-cellular'\n\n/** How many 4G periods a reader's record keeps: two years of on and off. */\nexport const POS_CELLULAR_MAX_PERIODS = 24\n\nexport interface PosCellularConfig {\n monthlyCostCents: number\n billingCostBps: number\n billingCostFixedCents: number\n productId: string\n /** Days a charge may stay unpaid before 4G is turned off for the workspace. */\n graceDays: number\n}\n\nfunction wholeNumber(text: string | undefined, fallback: number, max: number): number | null {\n const trimmed = String(text ?? '').trim()\n if (!trimmed) return fallback\n if (!/^\\d+$/.test(trimmed)) return null\n const value = Number(trimmed)\n return Number.isSafeInteger(value) && value <= max ? value : null\n}\n\n/**\n * The deployment's 4G pricing, or null when 4G is not offered: no monthly\n * cost, no product, or a value that is not a whole number in range. A bad\n * value hides the feature rather than billing a guess.\n */\nexport function parsePosCellularConfig(\n env: Record<string, string | undefined> = process.env,\n): PosCellularConfig | null {\n const costText = String(env[POS_CELLULAR_ENV.monthlyCostCents] ?? '').trim()\n if (!/^\\d+$/.test(costText)) return null\n const monthlyCostCents = Number(costText)\n if (!Number.isSafeInteger(monthlyCostCents) || monthlyCostCents <= 0 || monthlyCostCents > 100_000) return null\n const productId = String(env[POS_CELLULAR_ENV.productId] ?? '').trim()\n if (!/^prod_[A-Za-z0-9]+$/.test(productId)) return null\n const billingCostBps = wholeNumber(env[POS_CELLULAR_ENV.billingCostBps], POS_CELLULAR_DEFAULT_BILLING_COST_BPS, 5_000)\n const billingCostFixedCents = wholeNumber(\n env[POS_CELLULAR_ENV.billingCostFixedCents],\n POS_CELLULAR_DEFAULT_BILLING_COST_FIXED_CENTS,\n 1_000,\n )\n const graceDays = wholeNumber(env[POS_CELLULAR_ENV.graceDays], POS_CELLULAR_DEFAULT_GRACE_DAYS, 90)\n if (billingCostBps === null || billingCostFixedCents === null || graceDays === null || graceDays < 1) return null\n return { monthlyCostCents, billingCostBps, billingCostFixedCents, productId, graceDays }\n}\n\n/**\n * One workspace's 4G charge for a month, in whole cents: Stripe's price for\n * each reader, grossed up so that what the charge's own processing takes\n * leaves the platform exactly that:\n *\n * ceil((readers × cost + fixed) / (1 − rate))\n *\n * Rounded up, the one direction that never bills below cost.\n * Zero readers is no charge.\n */\nexport function posCellularChargeCents(readers: number, config: PosCellularConfig): number {\n if (!Number.isSafeInteger(readers) || readers <= 0) return 0\n const passThrough = readers * config.monthlyCostCents + config.billingCostFixedCents\n return Math.ceil((passThrough * 10_000) / (10_000 - config.billingCostBps))\n}\n\n/**\n * What one reader costs a month, as the console shows it: a store's charge\n * for a single reader. More readers on one charge share its fixed fee, so\n * this is never less than any reader's share of a larger charge.\n */\nexport function posCellularReaderMonthlyCents(config: PosCellularConfig): number {\n return posCellularChargeCents(1, config)\n}\n\n/** Whether a reader of this Stripe device type can have 4G. */\nexport function isPosCellularDeviceType(deviceType: unknown): boolean {\n return typeof deviceType === 'string' && POS_CELLULAR_DEVICE_TYPES.includes(deviceType)\n}\n\n/** `2026-10` for a time in October 2026, in UTC. */\nexport function posCellularMonthKey(ms: number): string {\n const date = new Date(ms)\n return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`\n}\n\n/** The calendar month before the one `ms` falls in. */\nexport function posCellularPreviousMonthKey(ms: number): string {\n const date = new Date(ms)\n return posCellularMonthKey(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() - 1, 1))\n}\n\n/** A month's first instant, and the next month's, in UTC; null for a key that is not one. */\nexport function posCellularMonthBounds(month: string): { startMs: number; endMs: number } | null {\n const match = /^(\\d{4})-(\\d{2})$/.exec(month)\n if (!match) return null\n const year = Number(match[1])\n const index = Number(match[2]) - 1\n if (index < 0 || index > 11) return null\n return { startMs: Date.UTC(year, index, 1), endMs: Date.UTC(year, index + 1, 1) }\n}\n\n/** `October 2026`, for the invoice line. */\nexport function posCellularMonthLabel(month: string): string {\n const bounds = posCellularMonthBounds(month)\n if (!bounds) return month\n return new Date(bounds.startMs).toLocaleString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' })\n}\n\n/** One stretch of time a reader had 4G: from when it was turned on, to when it was turned off (open while it is on). */\nexport interface PosCellularPeriod {\n fromMs: number\n toMs: number | null\n}\n\n/**\n * `posCellularReaders/{hostId}_{readerId}`: one S710's 4G months, written\n * only by the server. No person is named on it: a workspace, a store, a\n * Stripe reader and its serial, and when it had 4G.\n */\nexport interface PosCellularReaderRecord {\n orgId: string\n hostId: string\n readerId: string\n serialNumber: string | null\n /** The store's Terminal Configuration that carries `cellular[enabled]`. */\n stripeConfigurationId: string | null\n /**\n * The store's own Stripe account that Configuration is on, for a\n * direct-charge store; absent when it is on the platform.\n */\n stripeConfigurationAccount?: string\n enabled: boolean\n periods: PosCellularPeriod[]\n /** The last time a period was closed, which the month's charge queries by. */\n disabledAtMs: number | null\n updatedAtMs: number\n}\n\n/** The record's document id. */\nexport function posCellularReaderId(hostId: string, readerId: string): string {\n return `${hostId}_${readerId}`\n}\n\n/** The record with a period open from `now`, unless one already is. */\nexport function openPosCellularPeriod(\n base: Omit<PosCellularReaderRecord, 'enabled' | 'periods' | 'disabledAtMs' | 'updatedAtMs'>,\n existing: PosCellularReaderRecord | null,\n now: number,\n): PosCellularReaderRecord {\n const periods = existing?.periods ?? []\n const open = periods.some((period) => period.toMs === null)\n return {\n ...base,\n enabled: true,\n periods: open ? periods : [...periods, { fromMs: now, toMs: null }].slice(-POS_CELLULAR_MAX_PERIODS),\n disabledAtMs: existing?.disabledAtMs ?? null,\n updatedAtMs: now,\n }\n}\n\n/** The record with its open period closed at `now`; unchanged when none is open. */\nexport function closePosCellularPeriod(existing: PosCellularReaderRecord, now: number): PosCellularReaderRecord {\n if (!existing.periods.some((period) => period.toMs === null) && !existing.enabled) return existing\n return {\n ...existing,\n enabled: false,\n periods: existing.periods.map((period) => (period.toMs === null ? { ...period, toMs: now } : period)),\n disabledAtMs: now,\n updatedAtMs: now,\n }\n}\n\n/** Whether a reader had 4G at any time in the month. */\nexport function posCellularBilledInMonth(\n record: Pick<PosCellularReaderRecord, 'periods'>,\n bounds: { startMs: number; endMs: number },\n): boolean {\n return (record.periods ?? []).some(\n (period) => period.fromMs < bounds.endMs && (period.toMs === null || period.toMs > bounds.startMs),\n )\n}\n\n/** Each workspace's readers that had 4G in the month, by workspace. */\nexport function posCellularReadersByWorkspace(\n records: ReadonlyArray<PosCellularReaderRecord>,\n month: string,\n): Map<string, { readers: number; hostIds: string[] }> {\n const bounds = posCellularMonthBounds(month)\n const byOrg = new Map<string, { readers: number; hostIds: string[] }>()\n if (!bounds) return byOrg\n for (const record of records) {\n if (!record.orgId || !posCellularBilledInMonth(record, bounds)) continue\n const entry = byOrg.get(record.orgId) ?? { readers: 0, hostIds: [] }\n entry.readers += 1\n if (!entry.hostIds.includes(record.hostId)) entry.hostIds.push(record.hostId)\n byOrg.set(record.orgId, entry)\n }\n return byOrg\n}\n\n/**\n * The outcome of a workspace's month: charged and paid; charged and left\n * open on their Billing page because the card failed; still unpaid after the\n * grace period, so 4G was turned off for the workspace (`suspended`); its\n * invoice voided by staff (`voided`); not charged because there is no one to\n * bill (no workspace, no customer) or nothing to bill (under Stripe's\n * minimum); or `charging`, claimed by a run in progress.\n */\nexport type PosCellularChargeState =\n | 'charging'\n | 'paid'\n | 'open'\n | 'suspended'\n | 'voided'\n | 'failed'\n | 'no-workspace'\n | 'no-customer'\n | 'below-minimum'\n\n/** States a later run never charges again. */\nexport const POS_CELLULAR_SETTLED_STATES: readonly PosCellularChargeState[] = [\n 'paid',\n 'open',\n 'suspended',\n 'voided',\n 'no-workspace',\n 'no-customer',\n 'below-minimum',\n]\n\n/** `posCellularCharges/{orgId}_{month}`: one workspace's 4G charge for one month. */\nexport interface PosCellularCharge {\n orgId: string\n month: string\n readers: number\n amountCents: number\n state: PosCellularChargeState\n invoiceId: string | null\n paidCents: number\n attempts: number\n createdAtMs: number\n updatedAtMs: number\n /** When the charge was left open, which the grace period counts from. */\n openedAtMs?: number | null\n /** When 4G was turned off for the workspace because it stayed unpaid. */\n suspendedAtMs?: number | null\n /** The stores 4G was turned off for, whose notice clears once it is paid. */\n suspendedHostIds?: string[]\n /**\n * When the people who manage the workspace's billing were warned, as the\n * charge was left open, of the day 4G turns off unless it is paid.\n */\n warnedAtMs?: number | null\n /** When the people who manage the workspace's billing were told 4G was turned off. */\n noticeSentAtMs?: number | null\n /** Charged as the workspace was erased, for the month it was deleted in (or the one before). */\n final?: boolean\n}\n\n/**\n * When a charge left open runs out of grace: the grace period after it was\n * left open (or, for a charge from before that was recorded, after it last\n * changed).\n */\nexport function posCellularGraceEndsAtMs(\n charge: Pick<PosCellularCharge, 'openedAtMs' | 'updatedAtMs'>,\n graceDays: number,\n): number {\n return Number(charge.openedAtMs ?? charge.updatedAtMs) + graceDays * POS_CELLULAR_DAY_MS\n}\n\n/** Whether an open charge is past its grace period. */\nexport function posCellularOverdue(\n charge: Pick<PosCellularCharge, 'state' | 'openedAtMs' | 'updatedAtMs'>,\n graceDays: number,\n now: number,\n): boolean {\n return charge.state === 'open' && now >= posCellularGraceEndsAtMs(charge, graceDays)\n}\n\n/**\n * Whether the people who manage a workspace's billing are still owed the\n * warning that 4G turns off unless the charge is paid: an open charge not yet\n * warned of. Never a charge made as the workspace was erased, whose 4G is\n * already off and whose members are gone.\n */\nexport function posCellularWarningDue(\n charge: Pick<PosCellularCharge, 'state' | 'warnedAtMs' | 'final'>,\n): boolean {\n return charge.state === 'open' && !charge.warnedAtMs && !charge.final\n}\n\n/**\n * A day as the workspace reads it, `November 16, 2026`, in its time zone\n * (UTC for a zone the runtime cannot format in).\n */\nexport function posCellularDayLabel(ms: number, timeZone = 'UTC'): string {\n const options = { month: 'long', day: 'numeric', year: 'numeric' } as const\n try {\n return new Date(ms).toLocaleDateString('en-US', { ...options, timeZone })\n } catch {\n return new Date(ms).toLocaleDateString('en-US', { ...options, timeZone: 'UTC' })\n }\n}\n\n/**\n * On a store's terminal settings (`cellularSuspended`) while 4G is off because\n * a month's charge was not paid: which month, its invoice, and when.\n */\nexport interface PosCellularSuspension {\n month: string\n invoiceId: string | null\n atMs: number\n}\n\n/** What the POS devices card is told about 4G for a store; null hides it. */\nexport interface PosCellularView {\n /** What one reader costs a month, in cents, before any sales tax. */\n readerMonthlyCents: number\n enabled: boolean\n /** The store's readers that take 4G. */\n readers: number\n /** Turned off because a month's charge was not paid: that month, as `October 2026`, and when. */\n suspended?: { month: string; atMs: number } | null\n /**\n * Why the viewer may not turn 4G ON (it is charged to the workspace, so it\n * also takes \"Manage billing\"), or null. Turning it off needs only the\n * card's own key.\n */\n turnOnBlocked?: string | null\n}\n\n/**\n * The 4G row of a store's POS devices card: shown only where 4G is offered\n * and the store has an S710, or already has 4G on (so it can be turned off).\n */\nexport function posCellularView(\n config: PosCellularConfig | null,\n terminal: { cellularEnabled?: unknown; cellularSuspended?: unknown } | null | undefined,\n readers: ReadonlyArray<{ deviceType?: unknown }>,\n options: { turnOnBlocked?: string | null } = {},\n): PosCellularView | null {\n if (!config) return null\n const enabled = terminal?.cellularEnabled === true\n const capable = readers.filter((reader) => isPosCellularDeviceType(reader.deviceType)).length\n if (!enabled && capable === 0) return null\n const suspension = terminal?.cellularSuspended as Partial<PosCellularSuspension> | null | undefined\n const suspended =\n !enabled && suspension && typeof suspension.month === 'string'\n ? { month: posCellularMonthLabel(suspension.month), atMs: Number(suspension.atMs ?? 0) }\n : null\n return {\n readerMonthlyCents: posCellularReaderMonthlyCents(config),\n enabled,\n readers: capable,\n suspended,\n turnOnBlocked: options.turnOnBlocked ?? null,\n }\n}\n"],"names":["STRIPE_PROCESSOR_FEE_FIXED_USD","STRIPE_PROCESSOR_FEE_PCT","POS_CELLULAR_ENV","monthlyCostCents","billingCostBps","billingCostFixedCents","productId","graceDays","POS_CELLULAR_DEFAULT_GRACE_DAYS","POS_CELLULAR_DAY_MS","POS_CELLULAR_DEFAULT_BILLING_COST_BPS","Math","round","POS_CELLULAR_DEFAULT_BILLING_COST_FIXED_CENTS","POS_CELLULAR_DEVICE_TYPES","POS_CELLULAR_READERS_COLLECTION","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_CHARGE_KIND","POS_CELLULAR_MAX_PERIODS","wholeNumber","text","fallback","max","trimmed","String","trim","test","value","Number","isSafeInteger","parsePosCellularConfig","env","process","costText","posCellularChargeCents","readers","config","passThrough","ceil","posCellularReaderMonthlyCents","isPosCellularDeviceType","deviceType","includes","posCellularMonthKey","ms","date","Date","getUTCFullYear","getUTCMonth","padStart","posCellularPreviousMonthKey","UTC","posCellularMonthBounds","month","match","exec","year","index","startMs","endMs","posCellularMonthLabel","bounds","toLocaleString","timeZone","posCellularReaderId","hostId","readerId","openPosCellularPeriod","base","existing","now","periods","open","some","period","toMs","enabled","fromMs","slice","disabledAtMs","updatedAtMs","closePosCellularPeriod","map","posCellularBilledInMonth","record","posCellularReadersByWorkspace","records","byOrg","Map","orgId","entry","get","hostIds","push","set","POS_CELLULAR_SETTLED_STATES","posCellularGraceEndsAtMs","charge","openedAtMs","posCellularOverdue","state","posCellularWarningDue","warnedAtMs","final","posCellularDayLabel","options","day","toLocaleDateString","posCellularView","terminal","suspension","cellularEnabled","capable","filter","reader","length","cellularSuspended","suspended","atMs","readerMonthlyCents","turnOnBlocked"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,EAC9BC,wBAAwB,QACnB,2CAA0C;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CAmD2C,GAE3C,OAAO,MAAMC,mBAAmB;IAC9BC,kBAAkB;IAClBC,gBAAgB;IAChBC,uBAAuB;IACvBC,WAAW;IACXC,WAAW;AACb,EAAU;AAEV,0FAA0F,GAC1F,OAAO,MAAMC,kCAAkC,GAAE;AAEjD,4BAA4B,GAC5B,OAAO,MAAMC,sBAAsB,KAAK,KAAK,KAAK,KAAI;AAEtD,oFAAoF,GACpF,OAAO,MAAMC,wCAAwCC,KAAKC,KAAK,CAACX,2BAA2B,OAAO;AAElG,kFAAkF,GAClF,OAAO,MAAMY,gDAAgDF,KAAKC,KAAK,CAACZ,iCAAiC,KAAI;AAE7G,qFAAqF,GACrF,OAAO,MAAMc,4BAA+C;IAAC;IAAe;CAAwB,CAAA;AAEpG,kEAAkE,GAClE,OAAO,MAAMC,kCAAkC,qBAAoB;AAEnE,6EAA6E,GAC7E,OAAO,MAAMC,kCAAkC,qBAAoB;AAEnE,sDAAsD,GACtD,OAAO,MAAMC,2BAA2B,eAAc;AAEtD,0EAA0E,GAC1E,OAAO,MAAM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ce/src/lib/model/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 {\n STRIPE_PROCESSOR_FEE_FIXED_USD,\n STRIPE_PROCESSOR_FEE_PCT,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\n\n/*==========================================\n * 4G FOR STRIPE READER S710s (AGL-4038).\n *\n * Stripe sells cellular service for the Stripe Reader S710 as a monthly\n * subscription per reader, billed to the Stripe account the reader is\n * registered to — which, for every reader a store sets up here, is the\n * PLATFORM's. A reader has it when the Terminal Location it is registered\n * to has a Configuration with `cellular[enabled]`; Stripe bills a reader for\n * every calendar month it had it at any time.\n *\n * So 4G is turned on for a STORE: the platform keeps one Location and one\n * Configuration per store (`pos-terminal.ts`), and the native apps' connection\n * tokens are scoped to that one Location, so a second, cellular Location for\n * some of a store's readers would be one those apps could never reach, and\n * moving a reader there takes a fresh pairing code. Every S710 at a store\n * with 4G on has it, and each one is charged.\n *\n * The store's workspace pays what the platform pays, passed through: per\n * S710 per calendar month, Stripe's cellular price, plus what collecting it\n * costs the platform (the card processing on the charge), with no markup.\n * Both are configuration, never literals here:\n *\n * POS_CELLULAR_MONTHLY_COST_CENTS Stripe's price per reader per\n * month, in cents. Unset: 4G is not\n * offered anywhere (hidden, not\n * disabled).\n * POS_CELLULAR_BILLING_COST_BPS the processing percentage on the\n * charge, in basis points (default:\n * the platform's card rate)\n * POS_CELLULAR_BILLING_COST_FIXED_CENTS the processing fixed fee per\n * charge (default: the platform's)\n * STRIPE_PRODUCT_POS_CELLULAR the product the invoice line is\n * billed against (its tax code);\n * `setup-stripe.mjs` makes it\n * POS_CELLULAR_GRACE_DAYS how long a month's charge may stay\n * unpaid before 4G is turned off for\n * the workspace's stores (default 14)\n *\n * Billed in ARREARS, once per workspace per calendar month, on a one-off\n * invoice through core's usage-invoice charge — the same path a domain or\n * an AI overage takes — for the readers that had 4G at any time that month,\n * which is what Stripe bills the platform for. Turning 4G off stops the\n * charge from the next calendar month.\n *\n * A charge that does not collect stays open on the workspace's Billing page\n * and staff are alerted; the people who manage its billing are warned the\n * same day, once, of the day 4G turns off unless it is paid. Still unpaid\n * after the grace period, 4G is turned off at Stripe for every store of the\n * workspace, and they are told again; paying does not turn it back on, and\n * it cannot be turned on again until the charge is paid. A workspace deleted\n * mid-month is charged for that final month as it is erased.\n *\n * A STORE ON ITS OWN STRIPE ACCOUNT (direct charges, Terms §4.32) is the\n * exception to all of that. Its Location, and so the Configuration that\n * carries `cellular[enabled]`, is on the store's own full Stripe account\n * (`stripeLocationAccount` on its terminal settings, which every reader\n * record copies as `stripeConfigurationAccount`), and Stripe bills its 4G to\n * that account under the store's own agreement with Stripe. The platform\n * pays nothing for it, so the workspace is never charged for it here, never\n * warned about it, and never has it turned off over a charge here\n * ({@link posCellularBilledToPlatform}); and turning it on takes neither\n * \"Manage billing\" nor an agreement to a price that is not the platform's.\n *=========================================*/\n\nexport const POS_CELLULAR_ENV = {\n monthlyCostCents: 'POS_CELLULAR_MONTHLY_COST_CENTS',\n billingCostBps: 'POS_CELLULAR_BILLING_COST_BPS',\n billingCostFixedCents: 'POS_CELLULAR_BILLING_COST_FIXED_CENTS',\n productId: 'STRIPE_PRODUCT_POS_CELLULAR',\n graceDays: 'POS_CELLULAR_GRACE_DAYS',\n} as const\n\n/** How long a month's charge may stay unpaid before 4G is turned off, unless configured. */\nexport const POS_CELLULAR_DEFAULT_GRACE_DAYS = 14\n\n/** A day, in milliseconds. */\nexport const POS_CELLULAR_DAY_MS = 24 * 60 * 60 * 1000\n\n/** The platform's card processing rate, in basis points: the default billing cost. */\nexport const POS_CELLULAR_DEFAULT_BILLING_COST_BPS = Math.round(STRIPE_PROCESSOR_FEE_PCT * 10_000)\n\n/** The platform's card processing fixed fee, in cents: the default billing cost. */\nexport const POS_CELLULAR_DEFAULT_BILLING_COST_FIXED_CENTS = Math.round(STRIPE_PROCESSOR_FEE_FIXED_USD * 100)\n\n/** The Stripe device types that take cellular service: the S710, and its simulator. */\nexport const POS_CELLULAR_DEVICE_TYPES: readonly string[] = ['stripe_s710', 'simulated_stripe_s710']\n\n/** The top-level, server-only record of each reader's 4G months. */\nexport const POS_CELLULAR_READERS_COLLECTION = 'posCellularReaders'\n\n/** The top-level, server-only record of each workspace's monthly 4G charge. */\nexport const POS_CELLULAR_CHARGES_COLLECTION = 'posCellularCharges'\n\n/** The metadata `kind` the charge's invoice carries. */\nexport const POS_CELLULAR_CHARGE_KIND = 'pos-cellular'\n\n/** How many 4G periods a reader's record keeps: two years of on and off. */\nexport const POS_CELLULAR_MAX_PERIODS = 24\n\nexport interface PosCellularConfig {\n monthlyCostCents: number\n billingCostBps: number\n billingCostFixedCents: number\n productId: string\n /** Days a charge may stay unpaid before 4G is turned off for the workspace. */\n graceDays: number\n}\n\nfunction wholeNumber(text: string | undefined, fallback: number, max: number): number | null {\n const trimmed = String(text ?? '').trim()\n if (!trimmed) return fallback\n if (!/^\\d+$/.test(trimmed)) return null\n const value = Number(trimmed)\n return Number.isSafeInteger(value) && value <= max ? value : null\n}\n\n/**\n * The deployment's 4G pricing, or null when 4G is not offered: no monthly\n * cost, no product, or a value that is not a whole number in range. A bad\n * value hides the feature rather than billing a guess.\n */\nexport function parsePosCellularConfig(\n env: Record<string, string | undefined> = process.env,\n): PosCellularConfig | null {\n const costText = String(env[POS_CELLULAR_ENV.monthlyCostCents] ?? '').trim()\n if (!/^\\d+$/.test(costText)) return null\n const monthlyCostCents = Number(costText)\n if (!Number.isSafeInteger(monthlyCostCents) || monthlyCostCents <= 0 || monthlyCostCents > 100_000) return null\n const productId = String(env[POS_CELLULAR_ENV.productId] ?? '').trim()\n if (!/^prod_[A-Za-z0-9]+$/.test(productId)) return null\n const billingCostBps = wholeNumber(env[POS_CELLULAR_ENV.billingCostBps], POS_CELLULAR_DEFAULT_BILLING_COST_BPS, 5_000)\n const billingCostFixedCents = wholeNumber(\n env[POS_CELLULAR_ENV.billingCostFixedCents],\n POS_CELLULAR_DEFAULT_BILLING_COST_FIXED_CENTS,\n 1_000,\n )\n const graceDays = wholeNumber(env[POS_CELLULAR_ENV.graceDays], POS_CELLULAR_DEFAULT_GRACE_DAYS, 90)\n if (billingCostBps === null || billingCostFixedCents === null || graceDays === null || graceDays < 1) return null\n return { monthlyCostCents, billingCostBps, billingCostFixedCents, productId, graceDays }\n}\n\n/**\n * One workspace's 4G charge for a month, in whole cents: Stripe's price for\n * each reader, grossed up so that what the charge's own processing takes\n * leaves the platform exactly that:\n *\n * ceil((readers × cost + fixed) / (1 − rate))\n *\n * Rounded up, the one direction that never bills below cost.\n * Zero readers is no charge.\n */\nexport function posCellularChargeCents(readers: number, config: PosCellularConfig): number {\n if (!Number.isSafeInteger(readers) || readers <= 0) return 0\n const passThrough = readers * config.monthlyCostCents + config.billingCostFixedCents\n return Math.ceil((passThrough * 10_000) / (10_000 - config.billingCostBps))\n}\n\n/**\n * What one reader costs a month, as the console shows it: a store's charge\n * for a single reader. More readers on one charge share its fixed fee, so\n * this is never less than any reader's share of a larger charge.\n */\nexport function posCellularReaderMonthlyCents(config: PosCellularConfig): number {\n return posCellularChargeCents(1, config)\n}\n\n/** Whether a reader of this Stripe device type can have 4G. */\nexport function isPosCellularDeviceType(deviceType: unknown): boolean {\n return typeof deviceType === 'string' && POS_CELLULAR_DEVICE_TYPES.includes(deviceType)\n}\n\n/** `2026-10` for a time in October 2026, in UTC. */\nexport function posCellularMonthKey(ms: number): string {\n const date = new Date(ms)\n return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}`\n}\n\n/** The calendar month before the one `ms` falls in. */\nexport function posCellularPreviousMonthKey(ms: number): string {\n const date = new Date(ms)\n return posCellularMonthKey(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() - 1, 1))\n}\n\n/** A month's first instant, and the next month's, in UTC; null for a key that is not one. */\nexport function posCellularMonthBounds(month: string): { startMs: number; endMs: number } | null {\n const match = /^(\\d{4})-(\\d{2})$/.exec(month)\n if (!match) return null\n const year = Number(match[1])\n const index = Number(match[2]) - 1\n if (index < 0 || index > 11) return null\n return { startMs: Date.UTC(year, index, 1), endMs: Date.UTC(year, index + 1, 1) }\n}\n\n/** `October 2026`, for the invoice line. */\nexport function posCellularMonthLabel(month: string): string {\n const bounds = posCellularMonthBounds(month)\n if (!bounds) return month\n return new Date(bounds.startMs).toLocaleString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' })\n}\n\n/** One stretch of time a reader had 4G: from when it was turned on, to when it was turned off (open while it is on). */\nexport interface PosCellularPeriod {\n fromMs: number\n toMs: number | null\n}\n\n/**\n * `posCellularReaders/{hostId}_{readerId}`: one S710's 4G months, written\n * only by the server. No person is named on it: a workspace, a store, a\n * Stripe reader and its serial, and when it had 4G.\n */\nexport interface PosCellularReaderRecord {\n orgId: string\n hostId: string\n readerId: string\n serialNumber: string | null\n /** The store's Terminal Configuration that carries `cellular[enabled]`. */\n stripeConfigurationId: string | null\n /**\n * The store's own Stripe account that Configuration is on, for a\n * direct-charge store; absent when it is on the platform.\n */\n stripeConfigurationAccount?: string\n enabled: boolean\n periods: PosCellularPeriod[]\n /** The last time a period was closed, which the month's charge queries by. */\n disabledAtMs: number | null\n updatedAtMs: number\n}\n\n/**\n * The store's own Stripe account its 4G Configuration is on, from the\n * account its terminal settings record for its Location\n * (`stripeLocationAccount`), or null when it is on the platform. The\n * Configuration always lives where the Location does\n * (`savePosReaderConfiguration`), so this is the account Stripe bills.\n */\nexport function posCellularOwnAccount(stripeLocationAccount: unknown): string | null {\n const id = typeof stripeLocationAccount === 'string' ? stripeLocationAccount.trim() : ''\n return id || null\n}\n\n/**\n * Whether the platform pays Stripe for this reader's 4G, and so charges the\n * workspace for it: its Configuration is on the platform. A reader whose\n * Configuration is on the store's own Stripe account is billed by Stripe to\n * that account, so the workspace is never charged for it here (Terms §4.32).\n */\nexport function posCellularBilledToPlatform(\n record: Pick<PosCellularReaderRecord, 'stripeConfigurationAccount'>,\n): boolean {\n return posCellularOwnAccount(record.stripeConfigurationAccount) === null\n}\n\n/** The record's document id. */\nexport function posCellularReaderId(hostId: string, readerId: string): string {\n return `${hostId}_${readerId}`\n}\n\n/** The record with a period open from `now`, unless one already is. */\nexport function openPosCellularPeriod(\n base: Omit<PosCellularReaderRecord, 'enabled' | 'periods' | 'disabledAtMs' | 'updatedAtMs'>,\n existing: PosCellularReaderRecord | null,\n now: number,\n): PosCellularReaderRecord {\n const periods = existing?.periods ?? []\n const open = periods.some((period) => period.toMs === null)\n return {\n ...base,\n enabled: true,\n periods: open ? periods : [...periods, { fromMs: now, toMs: null }].slice(-POS_CELLULAR_MAX_PERIODS),\n disabledAtMs: existing?.disabledAtMs ?? null,\n updatedAtMs: now,\n }\n}\n\n/** The record with its open period closed at `now`; unchanged when none is open. */\nexport function closePosCellularPeriod(existing: PosCellularReaderRecord, now: number): PosCellularReaderRecord {\n if (!existing.periods.some((period) => period.toMs === null) && !existing.enabled) return existing\n return {\n ...existing,\n enabled: false,\n periods: existing.periods.map((period) => (period.toMs === null ? { ...period, toMs: now } : period)),\n disabledAtMs: now,\n updatedAtMs: now,\n }\n}\n\n/** Whether a reader had 4G at any time in the month. */\nexport function posCellularBilledInMonth(\n record: Pick<PosCellularReaderRecord, 'periods'>,\n bounds: { startMs: number; endMs: number },\n): boolean {\n return (record.periods ?? []).some(\n (period) => period.fromMs < bounds.endMs && (period.toMs === null || period.toMs > bounds.startMs),\n )\n}\n\n/**\n * Each workspace's readers that had 4G in the month and that the platform\n * pays for, by workspace: what a month's charge counts. A reader on a store's\n * own Stripe account is left out ({@link posCellularBilledToPlatform}).\n */\nexport function posCellularReadersByWorkspace(\n records: ReadonlyArray<PosCellularReaderRecord>,\n month: string,\n): Map<string, { readers: number; hostIds: string[] }> {\n const bounds = posCellularMonthBounds(month)\n const byOrg = new Map<string, { readers: number; hostIds: string[] }>()\n if (!bounds) return byOrg\n for (const record of records) {\n if (!record.orgId || !posCellularBilledToPlatform(record) || !posCellularBilledInMonth(record, bounds)) continue\n const entry = byOrg.get(record.orgId) ?? { readers: 0, hostIds: [] }\n entry.readers += 1\n if (!entry.hostIds.includes(record.hostId)) entry.hostIds.push(record.hostId)\n byOrg.set(record.orgId, entry)\n }\n return byOrg\n}\n\n/**\n * The outcome of a workspace's month: charged and paid; charged and left\n * open on their Billing page because the card failed; still unpaid after the\n * grace period, so 4G was turned off for the workspace (`suspended`); its\n * invoice voided by staff (`voided`); not charged because there is no one to\n * bill (no workspace, no customer) or nothing to bill (under Stripe's\n * minimum); or `charging`, claimed by a run in progress.\n */\nexport type PosCellularChargeState =\n | 'charging'\n | 'paid'\n | 'open'\n | 'suspended'\n | 'voided'\n | 'failed'\n | 'no-workspace'\n | 'no-customer'\n | 'below-minimum'\n\n/** States a later run never charges again. */\nexport const POS_CELLULAR_SETTLED_STATES: readonly PosCellularChargeState[] = [\n 'paid',\n 'open',\n 'suspended',\n 'voided',\n 'no-workspace',\n 'no-customer',\n 'below-minimum',\n]\n\n/** `posCellularCharges/{orgId}_{month}`: one workspace's 4G charge for one month. */\nexport interface PosCellularCharge {\n orgId: string\n month: string\n readers: number\n amountCents: number\n state: PosCellularChargeState\n invoiceId: string | null\n paidCents: number\n attempts: number\n createdAtMs: number\n updatedAtMs: number\n /** When the charge was left open, which the grace period counts from. */\n openedAtMs?: number | null\n /** When 4G was turned off for the workspace because it stayed unpaid. */\n suspendedAtMs?: number | null\n /** The stores 4G was turned off for, whose notice clears once it is paid. */\n suspendedHostIds?: string[]\n /**\n * When the people who manage the workspace's billing were warned, as the\n * charge was left open, of the day 4G turns off unless it is paid.\n */\n warnedAtMs?: number | null\n /** When the people who manage the workspace's billing were told 4G was turned off. */\n noticeSentAtMs?: number | null\n /** Charged as the workspace was erased, for the month it was deleted in (or the one before). */\n final?: boolean\n}\n\n/**\n * When a charge left open runs out of grace: the grace period after it was\n * left open (or, for a charge from before that was recorded, after it last\n * changed).\n */\nexport function posCellularGraceEndsAtMs(\n charge: Pick<PosCellularCharge, 'openedAtMs' | 'updatedAtMs'>,\n graceDays: number,\n): number {\n return Number(charge.openedAtMs ?? charge.updatedAtMs) + graceDays * POS_CELLULAR_DAY_MS\n}\n\n/** Whether an open charge is past its grace period. */\nexport function posCellularOverdue(\n charge: Pick<PosCellularCharge, 'state' | 'openedAtMs' | 'updatedAtMs'>,\n graceDays: number,\n now: number,\n): boolean {\n return charge.state === 'open' && now >= posCellularGraceEndsAtMs(charge, graceDays)\n}\n\n/**\n * Whether the people who manage a workspace's billing are still owed the\n * warning that 4G turns off unless the charge is paid: an open charge not yet\n * warned of. Never a charge made as the workspace was erased, whose 4G is\n * already off and whose members are gone.\n */\nexport function posCellularWarningDue(\n charge: Pick<PosCellularCharge, 'state' | 'warnedAtMs' | 'final'>,\n): boolean {\n return charge.state === 'open' && !charge.warnedAtMs && !charge.final\n}\n\n/**\n * A day as the workspace reads it, `November 16, 2026`, in its time zone\n * (UTC for a zone the runtime cannot format in).\n */\nexport function posCellularDayLabel(ms: number, timeZone = 'UTC'): string {\n const options = { month: 'long', day: 'numeric', year: 'numeric' } as const\n try {\n return new Date(ms).toLocaleDateString('en-US', { ...options, timeZone })\n } catch {\n return new Date(ms).toLocaleDateString('en-US', { ...options, timeZone: 'UTC' })\n }\n}\n\n/**\n * On a store's terminal settings (`cellularSuspended`) while 4G is off because\n * a month's charge was not paid: which month, its invoice, and when.\n */\nexport interface PosCellularSuspension {\n month: string\n invoiceId: string | null\n atMs: number\n}\n\n/** What the POS devices card is told about 4G for a store; null hides it. */\nexport interface PosCellularView {\n /**\n * What one reader costs the workspace a month, in cents, before any sales\n * tax; null for a store on its own Stripe account, which Stripe bills at\n * its own price and the workspace is never charged for.\n */\n readerMonthlyCents: number | null\n /** The store's 4G is on its own Stripe account, which Stripe bills directly. */\n ownAccount: boolean\n enabled: boolean\n /** The store's readers that take 4G. */\n readers: number\n /** Turned off because a month's charge was not paid: that month, as `October 2026`, and when. */\n suspended?: { month: string; atMs: number } | null\n /**\n * Why the viewer may not turn 4G ON (it is charged to the workspace, so it\n * also takes \"Manage billing\"), or null. Turning it off needs only the\n * card's own key, and so does turning it on for a store on its own Stripe\n * account.\n */\n turnOnBlocked?: string | null\n}\n\n/**\n * The 4G row of a store's POS devices card: shown only where 4G is offered\n * and the store has an S710, or already has 4G on (so it can be turned off).\n */\nexport function posCellularView(\n config: PosCellularConfig | null,\n terminal:\n | { cellularEnabled?: unknown; cellularSuspended?: unknown; stripeLocationAccount?: unknown }\n | null\n | undefined,\n readers: ReadonlyArray<{ deviceType?: unknown }>,\n options: { turnOnBlocked?: string | null } = {},\n): PosCellularView | null {\n if (!config) return null\n const enabled = terminal?.cellularEnabled === true\n const capable = readers.filter((reader) => isPosCellularDeviceType(reader.deviceType)).length\n if (!enabled && capable === 0) return null\n const suspension = terminal?.cellularSuspended as Partial<PosCellularSuspension> | null | undefined\n const suspended =\n !enabled && suspension && typeof suspension.month === 'string'\n ? { month: posCellularMonthLabel(suspension.month), atMs: Number(suspension.atMs ?? 0) }\n : null\n const ownAccount = posCellularOwnAccount(terminal?.stripeLocationAccount) !== null\n return {\n readerMonthlyCents: ownAccount ? null : posCellularReaderMonthlyCents(config),\n ownAccount,\n enabled,\n readers: capable,\n suspended,\n turnOnBlocked: ownAccount ? null : (options.turnOnBlocked ?? null),\n }\n}\n"],"names":["STRIPE_PROCESSOR_FEE_FIXED_USD","STRIPE_PROCESSOR_FEE_PCT","POS_CELLULAR_ENV","monthlyCostCents","billingCostBps","billingCostFixedCents","productId","graceDays","POS_CELLULAR_DEFAULT_GRACE_DAYS","POS_CELLULAR_DAY_MS","POS_CELLULAR_DEFAULT_BILLING_COST_BPS","Math","round","POS_CELLULAR_DEFAULT_BILLING_COST_FIXED_CENTS","POS_CELLULAR_DEVICE_TYPES","POS_CELLULAR_READERS_COLLECTION","POS_CELLULAR_CHARGES_COLLECTION","POS_CELLULAR_CHARGE_KIND","POS_CELLULAR_MAX_PERIODS","wholeNumber","text","fallback","max","trimmed","String","trim","test","value","Number","isSafeInteger","parsePosCellularConfig","env","process","costText","posCellularChargeCents","readers","config","passThrough","ceil","posCellularReaderMonthlyCents","isPosCellularDeviceType","deviceType","includes","posCellularMonthKey","ms","date","Date","getUTCFullYear","getUTCMonth","padStart","posCellularPreviousMonthKey","UTC","posCellularMonthBounds","month","match","exec","year","index","startMs","endMs","posCellularMonthLabel","bounds","toLocaleString","timeZone","posCellularOwnAccount","stripeLocationAccount","id","posCellularBilledToPlatform","record","stripeConfigurationAccount","posCellularReaderId","hostId","readerId","openPosCellularPeriod","base","existing","now","periods","open","some","period","toMs","enabled","fromMs","slice","disabledAtMs","updatedAtMs","closePosCellularPeriod","map","posCellularBilledInMonth","posCellularReadersByWorkspace","records","byOrg","Map","orgId","entry","get","hostIds","push","set","POS_CELLULAR_SETTLED_STATES","posCellularGraceEndsAtMs","charge","openedAtMs","posCellularOverdue","state","posCellularWarningDue","warnedAtMs","final","posCellularDayLabel","options","day","toLocaleDateString","posCellularView","terminal","suspension","cellularEnabled","capable","filter","reader","length","cellularSuspended","suspended","atMs","ownAccount","readerMonthlyCents","turnOnBlocked"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,8BAA8B,EAC9BC,wBAAwB,QACnB,2CAA0C;AAEjD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA8D2C,GAE3C,OAAO,MAAMC,mBAAmB;IAC9BC,kBAAkB;IAClBC,gBAAgB;IAChBC,uBAAuB;IACvBC,WAAW;IACXC,WAAW;AACb,EAAU;AAEV,0FAA0F,GAC1F,OAAO,MAAMC,kCAAkC,GAAE;AA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,GACD,OAAO,SAASkD,gBACd7E,MAAgC,EAChC8E,QAGa,EACb/E,OAAgD,EAChD2E,UAA6C,CAAC,CAAC;QASsBK,kBAS/BL;IAhBtC,IAAI,CAAC1E,QAAQ,OAAO;IACpB,MAAM8C,UAAUgC,CAAAA,4BAAAA,SAAUE,eAAe,MAAK;IAC9C,MAAMC,UAAUlF,QAAQmF,MAAM,CAAC,CAACC,SAAW/E,wBAAwB+E,OAAO9E,UAAU,GAAG+E,MAAM;IAC7F,IAAI,CAACtC,WAAWmC,YAAY,GAAG,OAAO;IACtC,MAAMF,aAAaD,4BAAAA,SAAUO,iBAAiB;IAC9C,MAAMC,YACJ,CAACxC,WAAWiC,cAAc,OAAOA,WAAW9D,KAAK,KAAK,WAClD;QAAEA,OAAOO,sBAAsBuD,WAAW9D,KAAK;QAAGsE,MAAM/F,QAAOuF,mBAAAA,WAAWQ,IAAI,YAAfR,mBAAmB;IAAG,IACrF;IACN,MAAMS,aAAa5D,sBAAsBkD,4BAAAA,SAAUjD,qBAAqB,MAAM;IAC9E,OAAO;QACL4D,oBAAoBD,aAAa,OAAOrF,8BAA8BH;QACtEwF;QACA1C;QACA/C,SAASkF;QACTK;QACAI,eAAeF,aAAa,QAAQd,yBAAAA,QAAQgB,aAAa,YAArBhB,yBAAyB;IAC/D;AACF"}
@@ -63,15 +63,16 @@ export declare function runPosCellularBilling(gate: PluginJobHostGate, deps?: Po
63
63
  * goes:
64
64
  *
65
65
  * 1. CHARGE IT. The month the workspace is deleted in is charged now, for
66
- * each S710 that had 4G in it, as the monthly run would have charged it a
66
+ * each S710 on the platform that had 4G in it (one on a store's own
67
+ * Stripe account is Stripe's to bill), as the monthly run would have charged it a
67
68
  * month later; and last month too, if the run had not charged it yet.
68
69
  * Through the run's own claim and key, so the two never charge one month
69
70
  * twice. A workspace that is locked is not charged (its card may be the
70
71
  * stolen one the lock is about): staff are alerted instead. Any failure
71
72
  * alerts staff and goes on.
72
73
  * 2. TURN IT OFF. Every store of the workspace with 4G on has cellular turned
73
- * off at Stripe, so the platform stops paying for readers nobody will be
74
- * charged for, and their periods are closed.
74
+ * off at Stripe, on the account it is on, so nobody keeps paying for
75
+ * readers of a workspace that is gone, and their periods are closed.
75
76
  *
76
77
  * Never fails the erasure: a refusal is a must alert. A dry run only counts.
77
78
  */
@@ -20,7 +20,7 @@ import { firebaseAdmin, raiseOperatorAlert, readOrgBilling } from "@aglyn/tenant
20
20
  import { chargeOrgUsageInvoice, USAGE_INVOICE_MIN_CHARGE_CENTS } from "@aglyn/tenant-data-admin/server/usage-invoice";
21
21
  import { BUNDLE_ID } from "../constants/bundle-common.js";
22
22
  import { COMMERCE_POS_CELLULAR_CHARGE_FAILED, COMMERCE_POS_CELLULAR_TURN_OFF_FAILED, COMMERCE_POS_CELLULAR_TURNED_OFF_UNPAID } from "../constants/operator-alerts.js";
23
- import { 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 } from "../model/pos-cellular.js";
23
+ import { 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 } from "../model/pos-cellular.js";
24
24
  import { posCellularInvoiceStatus, settleSuspendedPosCellularCharge, turnOffPosCellularConfiguration } from "./pos-cellular.js";
25
25
  /*==========================================
26
26
  * THE MONTHLY 4G CHARGE (AGL-4038).
@@ -69,6 +69,14 @@ import { posCellularInvoiceStatus, settleSuspendedPosCellularCharge, turnOffPosC
69
69
  * (and last month too, if the run had not charged it yet), so the two never
70
70
  * charge one month twice. A failure there alerts staff and never holds the
71
71
  * erasure.
72
+ *
73
+ * A STORE ON ITS OWN STRIPE ACCOUNT (a reader record with
74
+ * `stripeConfigurationAccount`) is billed for its 4G by Stripe, on that
75
+ * account, so none of the charging above counts it
76
+ * (`posCellularReadersByWorkspace`), and no charge here can warn about it or
77
+ * turn its 4G off: an unpaid month suspends only the workspace's stores on
78
+ * the platform. A gone store and an erased workspace still turn it off at
79
+ * Stripe, on the account it is on.
72
80
  *=========================================*/ const LABEL = '[pos-cellular] billing';
73
81
  /** A charge claimed this long ago and not settled was abandoned by its run. */ const CLAIM_STALE_MS = 30 * 60 * 1000;
74
82
  /** How many times a charge that never reached Stripe is tried before staff hear of it. */ const ALERT_AFTER_ATTEMPTS = 3;
@@ -471,10 +479,11 @@ async function settleMonth(orgId, month, patch, now) {
471
479
  const charge = await claimWarning(id, now);
472
480
  if (!charge) return false;
473
481
  const told = await (async ()=>{
474
- // The stores that have 4G now, which lose it on that day.
482
+ // The stores that have 4G on the platform now, which lose it on that
483
+ // day. A store on its own Stripe account keeps it whatever happens here.
475
484
  const snapshot = await recordsRef().where('orgId', '==', charge.orgId).where('enabled', '==', true).limit(500).get();
476
485
  const hostIds = [
477
- ...new Set(snapshot.docs.map((doc)=>doc.data().hostId))
486
+ ...new Set(snapshot.docs.map((doc)=>doc.data()).filter(posCellularBilledToPlatform).map((record)=>record.hostId))
478
487
  ];
479
488
  return context.warn({
480
489
  orgId: charge.orgId,
@@ -513,10 +522,11 @@ async function settleMonth(orgId, month, patch, now) {
513
522
  });
514
523
  }
515
524
  /**
516
- * 4G off at Stripe for every store of the workspace that still has it, each
517
- * store's settings saying why, its readers' periods closed, and the workspace
518
- * told once. Safe to run again: a store already off and a notice already
519
- * sent are left alone.
525
+ * 4G off at Stripe for every store of the workspace that still has it on the
526
+ * platform, each store's settings saying why, its readers' periods closed,
527
+ * and the workspace told once. A store on its own Stripe account is never
528
+ * touched: its 4G is not part of the charge. Safe to run again: a store
529
+ * already off and a notice already sent are left alone.
520
530
  */ async function finishSuspension(id, charge, context) {
521
531
  var _charge_suspendedHostIds, _charge_suspendedHostIds1;
522
532
  const { now } = context;
@@ -524,7 +534,7 @@ async function settleMonth(orgId, month, patch, now) {
524
534
  const records = snapshot.docs.map((doc)=>({
525
535
  id: String(doc.id),
526
536
  record: doc.data()
527
- }));
537
+ })).filter(({ record })=>posCellularBilledToPlatform(record));
528
538
  const hostIds = new Set((_charge_suspendedHostIds = charge.suspendedHostIds) != null ? _charge_suspendedHostIds : []);
529
539
  if (records.length) {
530
540
  await turnOffConfigurations(records.map(({ record })=>record), {
@@ -582,15 +592,16 @@ async function settleMonth(orgId, month, patch, now) {
582
592
  * goes:
583
593
  *
584
594
  * 1. CHARGE IT. The month the workspace is deleted in is charged now, for
585
- * each S710 that had 4G in it, as the monthly run would have charged it a
595
+ * each S710 on the platform that had 4G in it (one on a store's own
596
+ * Stripe account is Stripe's to bill), as the monthly run would have charged it a
586
597
  * month later; and last month too, if the run had not charged it yet.
587
598
  * Through the run's own claim and key, so the two never charge one month
588
599
  * twice. A workspace that is locked is not charged (its card may be the
589
600
  * stolen one the lock is about): staff are alerted instead. Any failure
590
601
  * alerts staff and goes on.
591
602
  * 2. TURN IT OFF. Every store of the workspace with 4G on has cellular turned
592
- * off at Stripe, so the platform stops paying for readers nobody will be
593
- * charged for, and their periods are closed.
603
+ * off at Stripe, on the account it is on, so nobody keeps paying for
604
+ * readers of a workspace that is gone, and their periods are closed.
594
605
  *
595
606
  * Never fails the erasure: a refusal is a must alert. A dry run only counts.
596
607
  */ export function createPosCellularOrgEraser(deps = {}) {