@aglyn/plugins-commerce 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/account-subscriptions.d.ts +51 -0
- package/src/lib/components/account-subscriptions.js +168 -0
- package/src/lib/components/account-subscriptions.js.map +1 -0
- package/src/lib/components/account.js +12 -48
- package/src/lib/components/account.js.map +1 -1
- package/src/lib/components/cart.js +38 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/commerce-console-page.js +6 -0
- package/src/lib/components/commerce-console-page.js.map +1 -1
- package/src/lib/components/commerce-console-sections.d.ts +1 -1
- package/src/lib/components/commerce-console-sections.js +5 -0
- package/src/lib/components/commerce-console-sections.js.map +1 -1
- package/src/lib/components/console/paid-media.d.ts +1 -0
- package/src/lib/components/console/paid-media.js +15 -4
- package/src/lib/components/console/paid-media.js.map +1 -1
- package/src/lib/components/console/payments-settings-card.component.js +1 -1
- package/src/lib/components/console/payments-settings-card.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-api.d.ts +10 -1
- package/src/lib/components/console/pos/pos-hardware-api.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js +2 -2
- package/src/lib/components/console/pos/pos-hardware-buyer.component.js.map +1 -1
- package/src/lib/components/console/pos/pos-hardware-sale-api.d.ts +2 -0
- package/src/lib/components/console/pos/pos-hardware-sale-api.js.map +1 -1
- package/src/lib/components/console/pos-cellular-control.component.d.ts +1 -1
- package/src/lib/components/console/pos-cellular-control.component.js +5 -5
- package/src/lib/components/console/pos-cellular-control.component.js.map +1 -1
- package/src/lib/components/console/pos-devices-card.component.js +2 -2
- package/src/lib/components/console/pos-devices-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-card.component.d.ts +5 -0
- package/src/lib/components/console/pos-hardware-card.component.js +77 -8
- package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js +137 -19
- package/src/lib/components/console/pos-hardware-orders-staff-page.component.js.map +1 -1
- package/src/lib/components/console/pos-page.component.js +19 -2
- package/src/lib/components/console/pos-page.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +21 -2
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/subscription-detail-dialog.component.d.ts +58 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js +201 -0
- package/src/lib/components/console/subscription-detail-dialog.component.js.map +1 -0
- package/src/lib/components/console/subscriptions-card.component.d.ts +60 -0
- package/src/lib/components/console/subscriptions-card.component.js +282 -0
- package/src/lib/components/console/subscriptions-card.component.js.map +1 -0
- package/src/lib/components/hardware-terms-consent.d.ts +22 -0
- package/src/lib/components/hardware-terms-consent.js +85 -0
- package/src/lib/components/hardware-terms-consent.js.map +1 -0
- package/src/lib/components/product-detail.js +32 -8
- package/src/lib/components/product-detail.js.map +1 -1
- package/src/lib/components/quote-page-body.js +7 -3
- package/src/lib/components/quote-page-body.js.map +1 -1
- package/src/lib/components/related-products.js +6 -3
- package/src/lib/components/related-products.js.map +1 -1
- package/src/lib/components/storefront-payment-element.d.ts +7 -1
- package/src/lib/components/storefront-payment-element.js +11 -7
- package/src/lib/components/storefront-payment-element.js.map +1 -1
- package/src/lib/constants/operator-alerts.d.ts +1 -1
- package/src/lib/constants/operator-alerts.js +4 -4
- package/src/lib/constants/operator-alerts.js.map +1 -1
- package/src/lib/model/commerce-orders.d.ts +6 -2
- package/src/lib/model/commerce-orders.js.map +1 -1
- package/src/lib/model/commerce-payment-methods.d.ts +27 -16
- package/src/lib/model/commerce-payment-methods.js +11 -83
- package/src/lib/model/commerce-payment-methods.js.map +1 -1
- package/src/lib/model/commerce.d.ts +6 -0
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/index.d.ts +1 -0
- package/src/lib/model/index.js +1 -0
- package/src/lib/model/index.js.map +1 -1
- package/src/lib/model/paid-media.d.ts +8 -0
- package/src/lib/model/paid-media.js +13 -0
- package/src/lib/model/paid-media.js.map +1 -1
- package/src/lib/model/pos-hardware-in-person.d.ts +23 -2
- package/src/lib/model/pos-hardware-in-person.js +52 -20
- package/src/lib/model/pos-hardware-in-person.js.map +1 -1
- package/src/lib/model/pos-hardware-tax-summary.d.ts +5 -1
- package/src/lib/model/pos-hardware-tax-summary.js +2 -1
- package/src/lib/model/pos-hardware-tax-summary.js.map +1 -1
- package/src/lib/model/pos-hardware-terms.d.ts +37 -2
- package/src/lib/model/pos-hardware-terms.js +68 -3
- package/src/lib/model/pos-hardware-terms.js.map +1 -1
- package/src/lib/model/pos-hardware.d.ts +101 -15
- package/src/lib/model/pos-hardware.js +128 -18
- package/src/lib/model/pos-hardware.js.map +1 -1
- package/src/lib/model/pos-reader-splash.js +2 -2
- package/src/lib/model/pos-reader-splash.js.map +1 -1
- package/src/lib/model/product-write.d.ts +3 -0
- package/src/lib/model/subscription-view.d.ts +90 -0
- package/src/lib/model/subscription-view.js +176 -0
- package/src/lib/model/subscription-view.js.map +1 -0
- package/src/lib/server/billing-webhook.d.ts +27 -6
- package/src/lib/server/billing-webhook.js +271 -81
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cancel-order.js +4 -3
- package/src/lib/server/cancel-order.js.map +1 -1
- package/src/lib/server/cart-checkout.js +105 -23
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +15 -3
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/catalog.js +58 -22
- package/src/lib/server/catalog.js.map +1 -1
- package/src/lib/server/checkout-session-expiry.d.ts +1 -1
- package/src/lib/server/checkout-session-expiry.js +19 -5
- package/src/lib/server/checkout-session-expiry.js.map +1 -1
- package/src/lib/server/checkout-status.js +4 -3
- package/src/lib/server/checkout-status.js.map +1 -1
- package/src/lib/server/checkout.js +98 -26
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/connect.js +42 -11
- package/src/lib/server/connect.js.map +1 -1
- package/src/lib/server/draft-order.js +36 -7
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/manual-tax-rate.d.ts +11 -3
- package/src/lib/server/manual-tax-rate.js +10 -6
- package/src/lib/server/manual-tax-rate.js.map +1 -1
- package/src/lib/server/membership-account.d.ts +22 -0
- package/src/lib/server/membership-account.js +52 -8
- package/src/lib/server/membership-account.js.map +1 -1
- package/src/lib/server/native-checkout.d.ts +10 -3
- package/src/lib/server/native-checkout.js +8 -3
- package/src/lib/server/native-checkout.js.map +1 -1
- package/src/lib/server/payment-method-domains.d.ts +50 -9
- package/src/lib/server/payment-method-domains.js +150 -51
- package/src/lib/server/payment-method-domains.js.map +1 -1
- package/src/lib/server/payment-methods.js +3 -2
- package/src/lib/server/payment-methods.js.map +1 -1
- package/src/lib/server/pos-auth.d.ts +3 -3
- package/src/lib/server/pos-auth.js +3 -3
- package/src/lib/server/pos-auth.js.map +1 -1
- package/src/lib/server/pos-cellular-billing.js +1 -1
- package/src/lib/server/pos-cellular-billing.js.map +1 -1
- package/src/lib/server/pos-cellular-notify.js +1 -1
- package/src/lib/server/pos-cellular-notify.js.map +1 -1
- package/src/lib/server/pos-cellular.js +1 -1
- package/src/lib/server/pos-cellular.js.map +1 -1
- package/src/lib/server/pos-hardware-admin.js +86 -13
- package/src/lib/server/pos-hardware-admin.js.map +1 -1
- package/src/lib/server/pos-hardware-attach.js +5 -5
- package/src/lib/server/pos-hardware-attach.js.map +1 -1
- package/src/lib/server/pos-hardware-cancel.js +65 -0
- package/src/lib/server/pos-hardware-cancel.js.map +1 -1
- package/src/lib/server/pos-hardware-closure-notices.js +2 -5
- package/src/lib/server/pos-hardware-closure-notices.js.map +1 -1
- package/src/lib/server/pos-hardware-closure.js +5 -8
- package/src/lib/server/pos-hardware-closure.js.map +1 -1
- package/src/lib/server/pos-hardware-in-person.d.ts +2 -1
- package/src/lib/server/pos-hardware-in-person.js +72 -17
- package/src/lib/server/pos-hardware-in-person.js.map +1 -1
- package/src/lib/server/pos-hardware-notify.d.ts +2 -0
- package/src/lib/server/pos-hardware-notify.js +30 -5
- package/src/lib/server/pos-hardware-notify.js.map +1 -1
- package/src/lib/server/pos-hardware-readers.d.ts +25 -0
- package/src/lib/server/pos-hardware-readers.js +206 -85
- package/src/lib/server/pos-hardware-readers.js.map +1 -1
- package/src/lib/server/pos-hardware-returns.d.ts +8 -3
- package/src/lib/server/pos-hardware-returns.js +39 -7
- package/src/lib/server/pos-hardware-returns.js.map +1 -1
- package/src/lib/server/pos-hardware-sale-fields.d.ts +76 -0
- package/src/lib/server/pos-hardware-sale-fields.js +114 -1
- package/src/lib/server/pos-hardware-sale-fields.js.map +1 -1
- package/src/lib/server/pos-hardware-sale.d.ts +2 -0
- package/src/lib/server/pos-hardware-sale.js +1 -0
- package/src/lib/server/pos-hardware-sale.js.map +1 -1
- package/src/lib/server/pos-hardware-tax-return-source.js +7 -4
- package/src/lib/server/pos-hardware-tax-return-source.js.map +1 -1
- package/src/lib/server/pos-hardware-webhook.js +16 -3
- package/src/lib/server/pos-hardware-webhook.js.map +1 -1
- package/src/lib/server/pos-hardware.d.ts +14 -3
- package/src/lib/server/pos-hardware.js +83 -18
- package/src/lib/server/pos-hardware.js.map +1 -1
- package/src/lib/server/pos-ops-routes.js +2 -10
- package/src/lib/server/pos-ops-routes.js.map +1 -1
- package/src/lib/server/pos-order.js +5 -1
- package/src/lib/server/pos-order.js.map +1 -1
- package/src/lib/server/pos-stripe.d.ts +7 -7
- package/src/lib/server/pos-stripe.js +15 -13
- package/src/lib/server/pos-stripe.js.map +1 -1
- package/src/lib/server/pos-terminal.js +11 -3
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/server/quote-pay.d.ts +23 -1
- package/src/lib/server/quote-pay.js +111 -27
- package/src/lib/server/quote-pay.js.map +1 -1
- package/src/lib/server/quote.d.ts +2 -1
- package/src/lib/server/quote.js +12 -11
- package/src/lib/server/quote.js.map +1 -1
- package/src/lib/server/refund.js +13 -6
- package/src/lib/server/refund.js.map +1 -1
- package/src/lib/server/related.js +10 -3
- package/src/lib/server/related.js.map +1 -1
- package/src/lib/server/reserve.js +19 -6
- package/src/lib/server/reserve.js.map +1 -1
- package/src/lib/server/revenue-source.d.ts +6 -0
- package/src/lib/server/revenue-source.js +25 -9
- package/src/lib/server/revenue-source.js.map +1 -1
- package/src/lib/server/seller-stripe-account.d.ts +45 -0
- package/src/lib/server/seller-stripe-account.js +99 -0
- package/src/lib/server/seller-stripe-account.js.map +1 -0
- package/src/lib/server/storefront-tax-record.js +6 -1
- package/src/lib/server/storefront-tax-record.js.map +1 -1
- package/src/lib/server/storefront-tax.d.ts +33 -2
- package/src/lib/server/storefront-tax.js +39 -3
- package/src/lib/server/storefront-tax.js.map +1 -1
- package/src/lib/server/stream.d.ts +2 -0
- package/src/lib/server/stream.js +22 -2
- package/src/lib/server/stream.js.map +1 -1
- package/src/lib/server/stripe-refund.d.ts +15 -0
- package/src/lib/server/stripe-refund.js +54 -26
- package/src/lib/server/stripe-refund.js.map +1 -1
- package/src/lib/server/subscription-portal.js +8 -3
- package/src/lib/server/subscription-portal.js.map +1 -1
- package/src/lib/server/tax-return-source.js +5 -1
- package/src/lib/server/tax-return-source.js.map +1 -1
- package/src/lib/server.js +2 -2
- package/src/lib/server.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular-notify.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { isAccountBanLockdownReason, normalizeOrgLockdown } from '@aglyn/aglyn/app-utils/lockdown'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { POS_CELLULAR_EMAIL_KEYS, sendEmail } from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostDisplayName,\n listOrgMembers,\n memberHasOrgPermission,\n meterPlatformEmail,\n notifyUsers,\n} from '@aglyn/tenant-data-admin'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n orgSystemEmailBrand,\n renderSystemEmailContent,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport { posCellularDayLabel, posCellularMonthLabel } from '../model/pos-cellular'\n\n/*==========================================\n * TELLING THE WORKSPACE ABOUT AN UNPAID 4G CHARGE (AGL-4038).\n *\n * Twice, from the daily run (`pos-cellular-billing.ts`), to the members who\n * hold \"Manage billing\" (the key, never a role): the designed system email\n * (`pos-cellular-emails.ts` in the email library), and the same words in\n * their console notification feed, without mailing them twice.\n *\n * 1. PAYMENT DUE, the day a month's charge doesn't go through: the amount,\n * the month, and the day 4G turns off for the workspace's stores unless\n * the open invoice is paid, in the workspace's time zone.\n * 2. TURNED OFF, when that day comes and it is still unpaid: the month, the\n * amount, the stores, and the way back.\n *\n * Each returns whether anyone was told (or there was nobody to tell), so the\n * caller records it once. Neither throws: a lost email must not undo the\n * step it reports on or stop the daily run.\n *=========================================*/\n\n/** What the warning, the day a charge is left open, says. */\nexport interface PosCellularPaymentDueNotice {\n orgId: string\n month: string\n /** Formatted, e.g. `$21.65`. */\n amount: string\n readers: number\n openedAtMs: number\n /** When the grace runs out: 4G turns off for the workspace's stores then, unless it is paid. */\n turnsOffAtMs: number\n /** The stores with 4G on now, which lose it then. */\n hostIds: string[]\n}\n\n/** What the notice that 4G was turned off says. */\nexport interface PosCellularTurnedOffNotice {\n orgId: string\n month: string\n /** Formatted, e.g. `$21.65`. */\n amount: string\n readers: number\n openedAtMs: number\n turnedOffAtMs: number\n hostIds: string[]\n}\n\ntype Firestore = ReturnType<ReturnType<typeof firebaseAdmin.app>['firestore']>\n\ninterface Workspace {\n name: string\n billingPath: string\n timeZone: string\n}\n\n/** The workspace as the notices name it; null for a banned account, which is sent nothing (AGL-3420). */\nasync function readWorkspace(firestore: Firestore, orgId: string): Promise<Workspace | null> {\n const org = await firestore.collection('orgs').doc(orgId).get().catch(() => null)\n const data = (org?.data() ?? null) as Record<string, unknown> | null\n const lock = normalizeOrgLockdown(data as never)\n if (lock && isAccountBanLockdownReason(lock.reason)) return null\n const slug = String(data?.['slug'] ?? '').trim()\n return {\n name: String(data?.['name'] ?? '').trim() || 'your workspace',\n billingPath: slug ? `/${slug}/billing` : '/billing',\n timeZone: resolveSiteTimeZone(data as { timeZone?: string } | null, null),\n }\n}\n\n/** The stores' names, one per line, or `fallback` when none is left. */\nasync function storeNames(firestore: Firestore, hostIds: readonly string[], fallback: string): Promise<string> {\n const hosts = await Promise.all(\n hostIds.map((hostId) => firestore.collection('hosts').doc(hostId).get().catch(() => null)),\n )\n const names = hosts\n .map((host, index) =>\n host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, hostIds[index]) : null,\n )\n .filter((name): name is string => Boolean(name))\n return names.join('\\n') || fallback\n}\n\n/**\n * Emails the members who hold \"Manage billing\" and puts the same words in\n * their console feed. True once someone was emailed, or nobody can be.\n */\nasync function tellBillingManagers(\n orgId: string,\n workspace: Workspace,\n message: {\n key: string\n merge: Record<string, string>\n title: string\n body: string\n },\n): Promise<boolean> {\n // Whoever may pay it: the workspace's \"Manage billing\" key, not a role.\n const members = await listOrgMembers(orgId)\n const managers = (\n await Promise.all(\n members.map(async (member) =>\n (await memberHasOrgPermission(orgId, member, 'billing.manage').catch(() => false)) ? member : null,\n ),\n )\n ).filter((member): member is (typeof members)[number] => member !== null)\n const addresses = managers.map((member) => String((member as { email?: unknown }).email ?? '').trim()).filter(Boolean)\n const recipients = await filterSuppressedEmails(addresses)\n let told = false\n if (recipients.length) {\n const brand = await orgSystemEmailBrand(orgId)\n const content = await renderSystemEmailContent(message.key, message.merge, brand, {\n subject: message.title,\n text: `${message.title}\\n\\n${message.body}\\n\\n${message.merge['cellular.billingUrl']}`,\n })\n const results = await Promise.all(\n recipients.map((to) =>\n sendEmail({\n to,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: message.key,\n }),\n ),\n )\n const sent = results.filter((result) => result.sent).length\n await meterPlatformEmail(sent)\n told = sent > 0\n }\n await notifyUsers(\n managers.map((member) => String((member as { $id?: unknown }).$id ?? '')).filter(Boolean),\n {\n type: 'billing.paymentFailed',\n title: message.title,\n body: message.body,\n level: 'warning',\n link: workspace.billingPath,\n orgId,\n },\n // The designed email above is the email; the notification is the feed.\n { skipEmail: true },\n )\n return told || recipients.length === 0\n}\n\nconst readersText = (readers: number) => `${readers} Stripe Reader S710${readers === 1 ? '' : 's'}`\n\n/**\n * The day a month's charge is left open: it is due, and 4G turns off for the\n * workspace's stores on the day its grace runs out unless it is paid.\n */\nexport async function sendPosCellularPaymentDueNotice(notice: PosCellularPaymentDueNotice): Promise<boolean> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const workspace = await readWorkspace(firestore, notice.orgId)\n if (!workspace) return false\n const month = posCellularMonthLabel(notice.month)\n const turnsOffOn = posCellularDayLabel(notice.turnsOffAtMs, workspace.timeZone)\n const merge: Record<string, string> = {\n 'org.name': workspace.name,\n 'cellular.month': month,\n 'cellular.amount': notice.amount,\n 'cellular.readers': readersText(notice.readers),\n 'cellular.openedOn': posCellularDayLabel(notice.openedAtMs, workspace.timeZone),\n 'cellular.turnsOffOn': turnsOffOn,\n // Blank when no store has 4G now: the email then leaves the row out.\n 'cellular.stores': await storeNames(firestore, notice.hostIds, ''),\n 'cellular.billingUrl': `${platformConsoleOrigin()}${workspace.billingPath}`,\n }\n return await tellBillingManagers(notice.orgId, workspace, {\n key: POS_CELLULAR_EMAIL_KEYS.paymentDue,\n merge,\n title: `4G turns off on ${turnsOffOn} unless the ${month} charge is paid`,\n body:\n `The 4G charge of ${notice.amount} for ${month} didn’t go through. ` +\n `Pay it on the Billing page before ${turnsOffOn} to keep 4G on for your stores.`,\n })\n } catch (error) {\n console.error('[pos-cellular] the payment-due notice failed', notice.orgId, notice.month, error)\n return false\n }\n}\n\n/** The day 4G was turned off for the workspace's stores because a month's charge stayed unpaid. */\nexport async function sendPosCellularTurnedOffNotice(notice: PosCellularTurnedOffNotice): Promise<boolean> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const workspace = await readWorkspace(firestore, notice.orgId)\n if (!workspace) return false\n const month = posCellularMonthLabel(notice.month)\n const merge: Record<string, string> = {\n 'org.name': workspace.name,\n 'cellular.month': month,\n 'cellular.amount': notice.amount,\n 'cellular.readers': readersText(notice.readers),\n 'cellular.openedOn': posCellularDayLabel(notice.openedAtMs, workspace.timeZone),\n 'cellular.turnedOffOn': posCellularDayLabel(notice.turnedOffAtMs, workspace.timeZone),\n 'cellular.stores': await storeNames(firestore, notice.hostIds, 'Your stores'),\n 'cellular.billingUrl': `${platformConsoleOrigin()}${workspace.billingPath}`,\n }\n return await tellBillingManagers(notice.orgId, workspace, {\n key: POS_CELLULAR_EMAIL_KEYS.turnedOffUnpaid,\n merge,\n title: `4G is off for your card readers: the ${month} charge is unpaid`,\n body:\n `The 4G charge of ${notice.amount} for ${month} is still unpaid, so 4G was turned off for your stores. ` +\n 'Pay it on the Billing page, then turn 4G on again from each store’s POS devices card.',\n })\n } catch (error) {\n console.error('[pos-cellular] the turned-off notice failed', notice.orgId, notice.month, error)\n return false\n }\n}\n"],"names":["resolveSiteTimeZone","isAccountBanLockdownReason","normalizeOrgLockdown","platformConsoleOrigin","POS_CELLULAR_EMAIL_KEYS","sendEmail","firebaseAdmin","hostDisplayName","listOrgMembers","memberHasOrgPermission","meterPlatformEmail","notifyUsers","filterSuppressedEmails","orgSystemEmailBrand","renderSystemEmailContent","posCellularDayLabel","posCellularMonthLabel","readWorkspace","firestore","orgId","org","collection","doc","get","catch","data","lock","reason","slug","String","trim","name","billingPath","timeZone","storeNames","hostIds","fallback","hosts","Promise","all","map","hostId","names","host","index","exists","filter","Boolean","join","tellBillingManagers","workspace","message","members","managers","member","addresses","email","recipients","told","length","brand","content","key","merge","subject","title","text","body","results","to","fromName","context","sent","result","$id","type","level","link","skipEmail","readersText","readers","sendPosCellularPaymentDueNotice","notice","app","month","turnsOffOn","turnsOffAtMs","amount","openedAtMs","paymentDue","error","console","sendPosCellularTurnedOffNotice","turnedOffAtMs","turnedOffUnpaid"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,0BAA0B,EAAEC,oBAAoB,QAAQ,kCAAiC;AAClG,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,uBAAuB,EAAEC,SAAS,QAAQ,2BAA0B;AAC7E,SACEC,aAAa,EACbC,eAAe,EACfC,cAAc,EACdC,sBAAsB,EACtBC,kBAAkB,EAClBC,WAAW,QACN,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SACEC,mBAAmB,EACnBC,wBAAwB,QACnB,sDAAqD;AAC5D,SAASC,mBAAmB,EAAEC,qBAAqB,QAAQ,2BAAuB;AAuDlF,uGAAuG,GACvG,eAAeC,cAAcC,SAAoB,EAAEC,KAAa;;IAC9D,MAAMC,MAAM,MAAMF,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOI,GAAG,GAAGC,KAAK,CAAC,IAAM;IAC5E,MAAMC,eAAQL,uBAAAA,IAAKK,IAAI,qBAAM;IAC7B,MAAMC,OAAOxB,qBAAqBuB;IAClC,IAAIC,QAAQzB,2BAA2ByB,KAAKC,MAAM,GAAG,OAAO;IAC5D,MAAMC,OAAOC,gBAAOJ,wBAAAA,IAAM,CAAC,OAAO,oBAAI,IAAIK,IAAI;IAC9C,OAAO;QACLC,MAAMF,gBAAOJ,wBA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I;YAC1B,kBAAkBqD;YAClB,mBAAmBF,OAAOK,MAAM;YAChC,oBAAoBR,YAAYG,OAAOF,OAAO;YAC9C,qBAAqBjE,oBAAoBmE,OAAOM,UAAU,EAAEtC,UAAUjB,QAAQ;YAC9E,wBAAwBlB,oBAAoBmE,OAAOW,aAAa,EAAE3C,UAAUjB,QAAQ;YACpF,mBAAmB,MAAMC,WAAWhB,WAAWgE,OAAO/C,OAAO,EAAE;YAC/D,uBAAuB,GAAGhC,0BAA0B+C,UAAUlB,WAAW,EAAE;QAC7E;QACA,OAAO,MAAMiB,oBAAoBiC,OAAO/D,KAAK,EAAE+B,WAAW;YACxDY,KAAK1D,wBAAwB0F,eAAe;YAC5C/B;YACAE,OAAO,CAAC,qCAAqC,EAAEmB,MAAM,iBAAiB,CAAC;YACvEjB,MACE,CAAC,iBAAiB,EAAEe,OAAOK,MAAM,CAAC,KAAK,EAAEH,MAAM,wDAAwD,CAAC,GACxG;QACJ;IACF,EAAE,OAAOM,OAAO;QACdC,QAAQD,KAAK,CAAC,+CAA+CR,OAAO/D,KAAK,EAAE+D,OAAOE,KAAK,EAAEM;QACzF,OAAO;IACT;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-cellular-notify.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { resolveSiteTimeZone } from '@aglyn/aglyn/app-utils/collection-entry-date'\nimport { isAccountBanLockdownReason, normalizeOrgLockdown } from '@aglyn/aglyn/app-utils/lockdown'\nimport { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { POS_CELLULAR_EMAIL_KEYS, sendEmail } from '@aglyn/shared-util-email'\nimport {\n firebaseAdmin,\n hostDisplayName,\n listOrgMembers,\n memberHasOrgPermission,\n meterPlatformEmail,\n notifyUsers,\n} from '@aglyn/tenant-data-admin'\nimport { filterSuppressedEmails } from '@aglyn/tenant-data-admin/server/email-suppression'\nimport {\n orgSystemEmailBrand,\n renderSystemEmailContent,\n} from '@aglyn/tenant-data-admin/server/render-system-email'\nimport { posCellularDayLabel, posCellularMonthLabel } from '../model/pos-cellular'\n\n/*==========================================\n * TELLING THE WORKSPACE ABOUT AN UNPAID 4G CHARGE (AGL-4038).\n *\n * Twice, from the daily run (`pos-cellular-billing.ts`), to the members who\n * hold \"Manage billing\" (the key, never a role): the designed system email\n * (`pos-cellular-emails.ts` in the email library), and the same words in\n * their console notification feed, without mailing them twice.\n *\n * 1. PAYMENT DUE, the day a month's charge doesn't go through: the amount,\n * the month, and the day 4G turns off for the workspace's stores unless\n * the open invoice is paid, in the workspace's time zone.\n * 2. TURNED OFF, when that day comes and it is still unpaid: the month, the\n * amount, the stores, and the way back.\n *\n * Each returns whether anyone was told (or there was nobody to tell), so the\n * caller records it once. Neither throws: a lost email must not undo the\n * step it reports on or stop the daily run.\n *=========================================*/\n\n/** What the warning, the day a charge is left open, says. */\nexport interface PosCellularPaymentDueNotice {\n orgId: string\n month: string\n /** Formatted, e.g. `$21.65`. */\n amount: string\n readers: number\n openedAtMs: number\n /** When the grace runs out: 4G turns off for the workspace's stores then, unless it is paid. */\n turnsOffAtMs: number\n /** The stores with 4G on now, which lose it then. */\n hostIds: string[]\n}\n\n/** What the notice that 4G was turned off says. */\nexport interface PosCellularTurnedOffNotice {\n orgId: string\n month: string\n /** Formatted, e.g. `$21.65`. */\n amount: string\n readers: number\n openedAtMs: number\n turnedOffAtMs: number\n hostIds: string[]\n}\n\ntype Firestore = ReturnType<ReturnType<typeof firebaseAdmin.app>['firestore']>\n\ninterface Workspace {\n name: string\n billingPath: string\n timeZone: string\n}\n\n/** The workspace as the notices name it; null for a banned account, which is sent nothing (AGL-3420). */\nasync function readWorkspace(firestore: Firestore, orgId: string): Promise<Workspace | null> {\n const org = await firestore.collection('orgs').doc(orgId).get().catch(() => null)\n const data = (org?.data() ?? null) as Record<string, unknown> | null\n const lock = normalizeOrgLockdown(data as never)\n if (lock && isAccountBanLockdownReason(lock.reason)) return null\n const slug = String(data?.['slug'] ?? '').trim()\n return {\n name: String(data?.['name'] ?? '').trim() || 'your workspace',\n billingPath: slug ? `/${slug}/billing` : '/billing',\n timeZone: resolveSiteTimeZone(data as { timeZone?: string } | null, null),\n }\n}\n\n/** The stores' names, one per line, or `fallback` when none is left. */\nasync function storeNames(firestore: Firestore, hostIds: readonly string[], fallback: string): Promise<string> {\n const hosts = await Promise.all(\n hostIds.map((hostId) => firestore.collection('hosts').doc(hostId).get().catch(() => null)),\n )\n const names = hosts\n .map((host, index) =>\n host?.exists ? hostDisplayName(host.data() as Record<string, unknown>, hostIds[index]) : null,\n )\n .filter((name): name is string => Boolean(name))\n return names.join('\\n') || fallback\n}\n\n/**\n * Emails the members who hold \"Manage billing\" and puts the same words in\n * their console feed. True once someone was emailed, or nobody can be.\n */\nasync function tellBillingManagers(\n orgId: string,\n workspace: Workspace,\n message: {\n key: string\n merge: Record<string, string>\n title: string\n body: string\n },\n): Promise<boolean> {\n // Whoever may pay it: the workspace's \"Manage billing\" key, not a role.\n const members = await listOrgMembers(orgId)\n const managers = (\n await Promise.all(\n members.map(async (member) =>\n (await memberHasOrgPermission(orgId, member, 'billing.manage').catch(() => false)) ? member : null,\n ),\n )\n ).filter((member): member is (typeof members)[number] => member !== null)\n const addresses = managers.map((member) => String((member as { email?: unknown }).email ?? '').trim()).filter(Boolean)\n const recipients = await filterSuppressedEmails(addresses)\n let told = false\n if (recipients.length) {\n const brand = await orgSystemEmailBrand(orgId)\n const content = await renderSystemEmailContent(message.key, message.merge, brand, {\n subject: message.title,\n text: `${message.title}\\n\\n${message.body}\\n\\n${message.merge['cellular.billingUrl']}`,\n })\n const results = await Promise.all(\n recipients.map((to) =>\n sendEmail({\n to,\n ...content,\n ...(brand.fromName ? { fromName: brand.fromName } : {}),\n context: message.key,\n }),\n ),\n )\n const sent = results.filter((result) => result.sent).length\n await meterPlatformEmail(sent)\n told = sent > 0\n }\n await notifyUsers(\n managers.map((member) => String((member as { $id?: unknown }).$id ?? '')).filter(Boolean),\n {\n type: 'billing.paymentFailed',\n title: message.title,\n body: message.body,\n level: 'warning',\n link: workspace.billingPath,\n orgId,\n },\n // The designed email above is the email; the notification is the feed.\n { skipEmail: true },\n )\n return told || recipients.length === 0\n}\n\nconst readersText = (readers: number) => `${readers} S710 reader${readers === 1 ? '' : 's'}`\n\n/**\n * The day a month's charge is left open: it is due, and 4G turns off for the\n * workspace's stores on the day its grace runs out unless it is paid.\n */\nexport async function sendPosCellularPaymentDueNotice(notice: PosCellularPaymentDueNotice): Promise<boolean> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const workspace = await readWorkspace(firestore, notice.orgId)\n if (!workspace) return false\n const month = posCellularMonthLabel(notice.month)\n const turnsOffOn = posCellularDayLabel(notice.turnsOffAtMs, workspace.timeZone)\n const merge: Record<string, string> = {\n 'org.name': workspace.name,\n 'cellular.month': month,\n 'cellular.amount': notice.amount,\n 'cellular.readers': readersText(notice.readers),\n 'cellular.openedOn': posCellularDayLabel(notice.openedAtMs, workspace.timeZone),\n 'cellular.turnsOffOn': turnsOffOn,\n // Blank when no store has 4G now: the email then leaves the row out.\n 'cellular.stores': await storeNames(firestore, notice.hostIds, ''),\n 'cellular.billingUrl': `${platformConsoleOrigin()}${workspace.billingPath}`,\n }\n return await tellBillingManagers(notice.orgId, workspace, {\n key: POS_CELLULAR_EMAIL_KEYS.paymentDue,\n merge,\n title: `4G turns off on ${turnsOffOn} unless the ${month} charge is paid`,\n body:\n `The 4G charge of ${notice.amount} for ${month} didn’t go through. ` +\n `Pay it on the Billing page before ${turnsOffOn} to keep 4G on for your stores.`,\n })\n } catch (error) {\n console.error('[pos-cellular] the payment-due notice failed', notice.orgId, notice.month, error)\n return false\n }\n}\n\n/** The day 4G was turned off for the workspace's stores because a month's charge stayed unpaid. */\nexport async function sendPosCellularTurnedOffNotice(notice: PosCellularTurnedOffNotice): Promise<boolean> {\n try {\n const firestore = firebaseAdmin.app().firestore()\n const workspace = await readWorkspace(firestore, notice.orgId)\n if (!workspace) return false\n const month = posCellularMonthLabel(notice.month)\n const merge: Record<string, string> = {\n 'org.name': workspace.name,\n 'cellular.month': month,\n 'cellular.amount': notice.amount,\n 'cellular.readers': readersText(notice.readers),\n 'cellular.openedOn': posCellularDayLabel(notice.openedAtMs, workspace.timeZone),\n 'cellular.turnedOffOn': posCellularDayLabel(notice.turnedOffAtMs, workspace.timeZone),\n 'cellular.stores': await storeNames(firestore, notice.hostIds, 'Your stores'),\n 'cellular.billingUrl': `${platformConsoleOrigin()}${workspace.billingPath}`,\n }\n return await tellBillingManagers(notice.orgId, workspace, {\n key: POS_CELLULAR_EMAIL_KEYS.turnedOffUnpaid,\n merge,\n title: `4G is off for your card readers: the ${month} charge is unpaid`,\n body:\n `The 4G charge of ${notice.amount} for ${month} is still unpaid, so 4G was turned off for your stores. ` +\n 'Pay it on the Billing page, then turn 4G on again from each store’s POS devices card.',\n })\n } catch (error) {\n console.error('[pos-cellular] the turned-off notice failed', notice.orgId, notice.month, error)\n return false\n }\n}\n"],"names":["resolveSiteTimeZone","isAccountBanLockdownReason","normalizeOrgLockdown","platformConsoleOrigin","POS_CELLULAR_EMAIL_KEYS","sendEmail","firebaseAdmin","hostDisplayName","listOrgMembers","memberHasOrgPermission","meterPlatformEmail","notifyUsers","filterSuppressedEmails","orgSystemEmailBrand","renderSystemEmailContent","posCellularDayLabel","posCellularMonthLabel","readWorkspace","firestore","orgId","org","collection","doc","get","catch","data","lock","reason","slug","String","trim","name","billingPath","timeZone","storeNames","hostIds","fallback","hosts","Promise","all","map","hostId","names","host","index","exists","filter","Boolean","join","tellBillingManagers","workspace","message","members","managers","member","addresses","email","recipients","told","length","brand","content","key","merge","subject","title","text","body","results","to","fromName","context","sent","result","$id","type","level","link","skipEmail","readersText","readers","sendPosCellularPaymentDueNotice","notice","app","month","turnsOffOn","turnsOffAtMs","amount","openedAtMs","paymentDue","error","console","sendPosCellularTurnedOffNotice","turnedOffAtMs","turnedOffUnpaid"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,+CAA8C;AAClF,SAASC,0BAA0B,EAAEC,oBAAoB,QAAQ,kCAAiC;AAClG,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SAASC,uBAAuB,EAAEC,SAAS,QAAQ,2BAA0B;AAC7E,SACEC,aAAa,EACbC,eAAe,EACfC,cAAc,EACdC,sBAAsB,EACtBC,kBAAkB,EAClBC,WAAW,QACN,2BAA0B;AACjC,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SACEC,mBAAmB,EACnBC,wBAAwB,QACnB,sDAAqD;AAC5D,SAASC,mBAAmB,EAAEC,qBAAqB,QAAQ,2BAAuB;AAuDlF,uGAAuG,GACvG,eAAeC,cAAcC,SAAoB,EAAEC,KAAa;;IAC9D,MAAMC,MAAM,MAAMF,UAAUG,UAAU,CAAC,QAAQC,GAAG,CAACH,OAAOI,GAAG,GAAGC,KAAK,CAAC,IAAM;IAC5E,MAAMC,eAAQL,uBAAAA,IAAKK,IAAI,qBAAM;IAC7B,MAAMC,OAAOxB,qBAAqBuB;IAClC,IAAIC,QAAQzB,2BAA2ByB,KAAKC,MAAM,GAAG,OAAO;IAC5D,MAAMC,OAAOC,gBAAOJ,wBAAAA,IAAM,CAAC,OAAO,oBAAI,IAAIK,IAAI;IAC9C,OAAO;QACLC,MAAMF,gBAAOJ,wBAAAA,IAAM,CAAC,OAAO,oBAAI,IAAIK,IAAI,MAAM;QAC7CE,aAAaJ,OAAO,CAAC,CAAC,EAAEA,KAAK,QAAQ,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AoBmE,OAAOM,UAAU,EAAEtC,UAAUjB,QAAQ;YAC9E,wBAAwBlB,oBAAoBmE,OAAOW,aAAa,EAAE3C,UAAUjB,QAAQ;YACpF,mBAAmB,MAAMC,WAAWhB,WAAWgE,OAAO/C,OAAO,EAAE;YAC/D,uBAAuB,GAAGhC,0BAA0B+C,UAAUlB,WAAW,EAAE;QAC7E;QACA,OAAO,MAAMiB,oBAAoBiC,OAAO/D,KAAK,EAAE+B,WAAW;YACxDY,KAAK1D,wBAAwB0F,eAAe;YAC5C/B;YACAE,OAAO,CAAC,qCAAqC,EAAEmB,MAAM,iBAAiB,CAAC;YACvEjB,MACE,CAAC,iBAAiB,EAAEe,OAAOK,MAAM,CAAC,KAAK,EAAEH,MAAM,wDAAwD,CAAC,GACxG;QACJ;IACF,EAAE,OAAOM,OAAO;QACdC,QAAQD,KAAK,CAAC,+CAA+CR,OAAO/D,KAAK,EAAE+D,OAAOE,KAAK,EAAEM;QACzF,OAAO;IACT;AACF"}
|
|
@@ -248,7 +248,7 @@ function cellularReadersRef() {
|
|
|
248
248
|
return {
|
|
249
249
|
status: 409,
|
|
250
250
|
body: {
|
|
251
|
-
error: '4G works on the
|
|
251
|
+
error: '4G works on the S710 reader. Add one to this store first.',
|
|
252
252
|
code: 'no-capable-reader'
|
|
253
253
|
}
|
|
254
254
|
};
|
|
@@ -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 Stripe Reader S710. 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,OAAO;IACjD,MAAMG,SAAS,MAAMf,UA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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,G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QAAEV,QAAQ;QAAKJ,MAAM;YAAEG,IAAI;YAAMiD,SAAS+B;QAAO;IAAE;AAC5D;AAEA;;;;CAIC,GACD,OAAO,eAAee,gCAAgC7C,eAAuB;IAC3E,IAAI,CAAC,qBAAqBpD,IAAI,CAACoD,kBAAkB,OAAO;IACxD,MAAMnD,SAAS,MAAMf,UAAU,QAAQ,CAAC,wBAAwB,EAAEkE,iBAAiB,EAAE;QACnF8C,QAAQ;YAAE,qBAAqB;QAAM;IACvC;IACA,OAAOjG,OAAOC,EAAE,IAAID,OAAOE,MAAM,KAAK;AACxC"}
|
|
@@ -18,7 +18,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
18
18
|
import { emailUnverifiedResponse, firebaseAdmin, isImpersonationSession } from "@aglyn/tenant-data-admin";
|
|
19
19
|
import { addAdminAudit } from "@aglyn/tenant-data-admin/server/admin-audit-write";
|
|
20
20
|
import { invalidIdTokenResponse } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
21
|
-
import { isPosHardwareOrderStatus, nextPosHardwareStatus, POS_HARDWARE_ORDER_ID, POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_STATUS_STAMP, posHardwareBuyerErasedPatch, posHardwareOrderSource, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
|
|
21
|
+
import { isPosHardwareSellerStoreSale, isPosHardwareOrderStatus, nextPosHardwareStatus, POS_HARDWARE_ORDER_ID, POS_HARDWARE_ORDERS_COLLECTION, POS_HARDWARE_STATUS_STAMP, posHardwareBuyerErasedPatch, posHardwareOrderUnits, posHardwareReadyToShip, posHardwareOrderSource, posHardwareSaleRecord, posHardwareSaleSetOptions } from "../model/pos-hardware.js";
|
|
22
22
|
import { fulfillmentTrackingUrl } from "../model/tracking-url.js";
|
|
23
23
|
import { hardwareOrdersRef, posHardwareInPersonConfig, posHardwareOrderNumber, posHardwareSaleRef } from "./pos-hardware.js";
|
|
24
24
|
import { cancelAndRefundPosHardwareOrder } from "./pos-hardware-cancel.js";
|
|
@@ -28,12 +28,15 @@ import { sendPosHardwareEmail, sendPosHardwareEmailOnce } from "./pos-hardware-n
|
|
|
28
28
|
* hardware shop, for the Hardware orders staff page.
|
|
29
29
|
*
|
|
30
30
|
* GET every workspace's orders, newest first, optionally one status,
|
|
31
|
-
* or `?attach=pending`: the
|
|
32
|
-
* they are yet (AGL-4038)
|
|
33
|
-
* seller store still waiting to be recorded
|
|
31
|
+
* or `?attach=pending`: the sales of the platform's own store nobody
|
|
32
|
+
* has said whose they are yet (AGL-4038). Any paid sale on the
|
|
33
|
+
* seller store still waiting to be recorded is recorded first.
|
|
34
34
|
* POST update record Stripe's order id and the tracking, or move the
|
|
35
|
-
* order one step on (Ordered →
|
|
36
|
-
* Registered); Shipped needs a tracking number
|
|
35
|
+
* order one step on (Ordered → Received → Shipped →
|
|
36
|
+
* Delivered → Registered); Shipped needs a tracking number
|
|
37
|
+
* and every reader's serial (set up, AGL-4038), and an
|
|
38
|
+
* order whose readers were all registered before it shipped
|
|
39
|
+
* reads Registered once delivered
|
|
37
40
|
* cancel cancel and refund in full, before it ships
|
|
38
41
|
* refund refund in full, before it ships
|
|
39
42
|
* refund an order sold in person (AGL-4038): what is left of it,
|
|
@@ -45,6 +48,10 @@ import { sendPosHardwareEmail, sendPosHardwareEmailOnce } from "./pos-hardware-n
|
|
|
45
48
|
* same claim a closure sends it under; false sends nothing. Absent
|
|
46
49
|
* reads as the dialog's default, true. It is in the audit row.
|
|
47
50
|
* decline-return decline a buyer's open return request, with a note
|
|
51
|
+
* serials record the serial numbers of an order's readers before it
|
|
52
|
+
* ships (AGL-4038): setting it up
|
|
53
|
+
* register-reader register one of its readers to the buyer's store
|
|
54
|
+
* by the code it shows, before it ships (AGL-4038)
|
|
48
55
|
* forget-buyer take the buyer's address and account off an order
|
|
49
56
|
* sold in person (AGL-4038), for a privacy request from
|
|
50
57
|
* someone who never made an account
|
|
@@ -67,7 +74,7 @@ const json = (body, status = 200)=>Response.json(body, {
|
|
|
67
74
|
}
|
|
68
75
|
});
|
|
69
76
|
/** An order as the staff page lists it. */ function staffView(id, order) {
|
|
70
|
-
var _order_contactEmail, _order_lines, _order_subtotalCents, _order_shipping, _order_taxCents, _order_totalCents, _order_stripeCheckoutSessionId, _order_stripePaymentIntentId, _order_stripeHardwareOrderId, _order_tracking, _order_createdAtMs, _order_updatedAtMs, _order_discountCents, _order_posSale, _order_paidTo, _order_attachment,
|
|
77
|
+
var _order_contactEmail, _order_lines, _order_subtotalCents, _order_shipping, _order_taxCents, _order_totalCents, _order_stripeCheckoutSessionId, _order_stripePaymentIntentId, _order_stripeHardwareOrderId, _order_tracking, _order_createdAtMs, _order_updatedAtMs, _order_discountCents, _order_posSale, _order_paidTo, _order_attachment, _order_refundedCents, _order_refunds, _order_returnRequest;
|
|
71
78
|
return {
|
|
72
79
|
id,
|
|
73
80
|
number: posHardwareOrderNumber(id),
|
|
@@ -95,7 +102,8 @@ const json = (body, status = 200)=>Response.json(body, {
|
|
|
95
102
|
posSale: (_order_posSale = order.posSale) != null ? _order_posSale : null,
|
|
96
103
|
paidTo: (_order_paidTo = order.paidTo) != null ? _order_paidTo : null,
|
|
97
104
|
attachment: (_order_attachment = order.attachment) != null ? _order_attachment : null,
|
|
98
|
-
|
|
105
|
+
// Every reader the order ships, for its serial and its store (AGL-4038).
|
|
106
|
+
units: posHardwareOrderUnits(order),
|
|
99
107
|
refundedCents: (_order_refundedCents = order.refundedCents) != null ? _order_refundedCents : 0,
|
|
100
108
|
refunds: (_order_refunds = order.refunds) != null ? _order_refunds : [],
|
|
101
109
|
returnRequest: (_order_returnRequest = order.returnRequest) != null ? _order_returnRequest : null
|
|
@@ -157,15 +165,17 @@ async function handler(request) {
|
|
|
157
165
|
if (returns && returns !== 'requested') return json({
|
|
158
166
|
error: 'Unknown filter'
|
|
159
167
|
}, 400);
|
|
168
|
+
// A sale on the platform's own store whose recording was missed — at
|
|
169
|
+
// its register or online (AGL-4038) — is recorded before any list is
|
|
170
|
+
// read, so it is on the Paid list and To attach both.
|
|
171
|
+
const config = posHardwareInPersonConfig();
|
|
172
|
+
if (config) await (await import("./pos-hardware-in-person.js")).sweepInPersonPosHardwareSales(config);
|
|
160
173
|
let ordersQuery = firestore.collectionGroup(POS_HARDWARE_ORDERS_COLLECTION);
|
|
161
174
|
if (returns === 'requested') {
|
|
162
175
|
// Buyers' open return requests (AGL-4038), oldest waiting first in the
|
|
163
176
|
// newest-first list like every other filter.
|
|
164
177
|
ordersQuery = ordersQuery.where('returnRequest.state', '==', 'requested');
|
|
165
178
|
} else if (attach === 'pending') {
|
|
166
|
-
// A sale whose recording was missed is recorded before the list is read.
|
|
167
|
-
const config = posHardwareInPersonConfig();
|
|
168
|
-
if (config) await (await import("./pos-hardware-in-person.js")).sweepInPersonPosHardwareSales(config);
|
|
169
179
|
ordersQuery = ordersQuery.where('attachment.state', '==', 'pending');
|
|
170
180
|
} else if (requested) {
|
|
171
181
|
if (!isPosHardwareOrderStatus(requested)) return json({
|
|
@@ -225,6 +235,7 @@ async function handler(request) {
|
|
|
225
235
|
}
|
|
226
236
|
const notifyBuyer = notifyRaw !== false;
|
|
227
237
|
if (action === 'update') return await updateOrder(firestore, ref, orgId, orderId, input, actor);
|
|
238
|
+
if (action === 'serials' || action === 'register-reader') return await setUpOrder(firestore, orgId, orderId, action, input, actor);
|
|
228
239
|
if (action === 'forget-buyer') return await forgetBuyer(firestore, ref, orgId, orderId, actor);
|
|
229
240
|
if (action === 'decline-return') return await inPersonReturn(firestore, orgId, orderId, action, input, actor);
|
|
230
241
|
if (action === 'refund-return') return await onlineReturnRefund(firestore, orgId, orderId, input, actor, notifyBuyer);
|
|
@@ -285,9 +296,19 @@ async function updateOrder(firestore, ref, orgId, orderId, input, actor) {
|
|
|
285
296
|
if (advanceTo === 'shipped' && !(trackingAfter == null ? void 0 : trackingAfter.number)) {
|
|
286
297
|
throw new Refusal('Add the tracking number before marking the order shipped.', 400);
|
|
287
298
|
}
|
|
299
|
+
// Set up before it ships (AGL-4038): every reader's serial recorded.
|
|
300
|
+
const notReady = advanceTo === 'shipped' ? posHardwareReadyToShip(before) : null;
|
|
301
|
+
if (notReady) throw new Refusal(notReady, 409);
|
|
288
302
|
patch['status'] = advanceTo;
|
|
289
303
|
patch[POS_HARDWARE_STATUS_STAMP[advanceTo]] = now;
|
|
290
304
|
reached = advanceTo;
|
|
305
|
+
// Every reader was registered to the buyer's store before it shipped:
|
|
306
|
+
// delivered is set up, so it reads Set up at once.
|
|
307
|
+
const units = posHardwareOrderUnits(before);
|
|
308
|
+
if (advanceTo === 'delivered' && units.length && units.every((unit)=>unit.readerId)) {
|
|
309
|
+
patch['status'] = 'registered';
|
|
310
|
+
patch[POS_HARDWARE_STATUS_STAMP.registered] = now;
|
|
311
|
+
}
|
|
291
312
|
}
|
|
292
313
|
const after = _extends({}, before, patch);
|
|
293
314
|
transaction.update(ref, patch);
|
|
@@ -324,6 +345,58 @@ async function updateOrder(firestore, ref, orgId, orderId, input, actor) {
|
|
|
324
345
|
order: staffView(orderId, outcome.after)
|
|
325
346
|
});
|
|
326
347
|
}
|
|
348
|
+
/**
|
|
349
|
+
* Sets an order up before it ships (AGL-4038): its readers' serial numbers,
|
|
350
|
+
* or one reader registered to the buyer's store by the code it shows
|
|
351
|
+
* (`pos-hardware-readers.ts`). Audited.
|
|
352
|
+
*/ async function setUpOrder(firestore, orgId, orderId, action, input, actor) {
|
|
353
|
+
const readers = await import("./pos-hardware-readers.js");
|
|
354
|
+
try {
|
|
355
|
+
var _outcome_order_serialNumbers;
|
|
356
|
+
const outcome = action === 'serials' ? {
|
|
357
|
+
order: await readers.recordPosHardwareOrderSerials({
|
|
358
|
+
orgId,
|
|
359
|
+
orderId,
|
|
360
|
+
serials: input['serials']
|
|
361
|
+
}),
|
|
362
|
+
readerId: null
|
|
363
|
+
} : await readers.registerPosHardwareOrderReader({
|
|
364
|
+
orgId,
|
|
365
|
+
orderId,
|
|
366
|
+
registrationCode: input['registrationCode'],
|
|
367
|
+
label: input['label'],
|
|
368
|
+
uid: actor.actorUid
|
|
369
|
+
});
|
|
370
|
+
await addAdminAudit(firestore, _extends({
|
|
371
|
+
action: action === 'serials' ? 'pos-hardware-order-serials' : 'pos-hardware-order-register-reader'
|
|
372
|
+
}, actor, {
|
|
373
|
+
scope: 'posHardwareOrder',
|
|
374
|
+
target: `orgs/${orgId}/${POS_HARDWARE_ORDERS_COLLECTION}/${orderId}`,
|
|
375
|
+
orgId,
|
|
376
|
+
before: null,
|
|
377
|
+
after: action === 'serials' ? {
|
|
378
|
+
serials: (_outcome_order_serialNumbers = outcome.order.serialNumbers) != null ? _outcome_order_serialNumbers : []
|
|
379
|
+
} : {
|
|
380
|
+
readerId: outcome.readerId,
|
|
381
|
+
hostId: outcome.order.hostId
|
|
382
|
+
},
|
|
383
|
+
at: firebaseAdmin.firestore.FieldValue.serverTimestamp()
|
|
384
|
+
}));
|
|
385
|
+
return json({
|
|
386
|
+
ok: true,
|
|
387
|
+
order: staffView(orderId, outcome.order)
|
|
388
|
+
});
|
|
389
|
+
} catch (error) {
|
|
390
|
+
if (error instanceof readers.PosHardwareReaderRefusal) {
|
|
391
|
+
return json(_extends({
|
|
392
|
+
error: error.message
|
|
393
|
+
}, error.reason ? {
|
|
394
|
+
reason: error.reason
|
|
395
|
+
} : {}), error.status);
|
|
396
|
+
}
|
|
397
|
+
throw error;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
327
400
|
/** Whether an order was sold in person (AGL-4038), which refunds its own way. */ async function soldInPerson(ref) {
|
|
328
401
|
const snapshot = await ref.get();
|
|
329
402
|
return snapshot.exists && posHardwareOrderSource(snapshot.data()) === 'in_person';
|
|
@@ -440,8 +513,8 @@ async function updateOrder(firestore, ref, orgId, orderId, input, actor) {
|
|
|
440
513
|
const snapshot = await transaction.get(ref);
|
|
441
514
|
if (!snapshot.exists) throw new Refusal('No such order', 404);
|
|
442
515
|
const before = snapshot.data();
|
|
443
|
-
if (
|
|
444
|
-
throw new Refusal('Only an order sold
|
|
516
|
+
if (!isPosHardwareSellerStoreSale(before)) {
|
|
517
|
+
throw new Refusal('Only an order sold by our own store has a buyer to remove here.', 409);
|
|
445
518
|
}
|
|
446
519
|
const patch = posHardwareBuyerErasedPatch(before, Date.now());
|
|
447
520
|
const next = _extends({}, before, patch);
|