@aglyn/plugins-commerce 1.14.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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 +30 -6
- 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 +280 -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 +25 -5
- package/src/lib/components/product-detail.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 +24 -0
- package/src/lib/model/commerce-payment-methods.js +35 -0
- 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 +4 -6
- package/src/lib/server/billing-webhook.js +109 -51
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/cart-checkout.js +45 -10
- 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/checkout.js +58 -16
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/draft-order.js +7 -3
- package/src/lib/server/draft-order.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/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/quote-pay.js +8 -4
- package/src/lib/server/quote-pay.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/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/model/pos-hardware.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\n/*==========================================\n * THE POS HARDWARE SHOP (AGL-4038), PHASE 1: THE MODEL.\n *\n * A merchant buys Stripe Terminal readers from the platform, the platform\n * places the order in Stripe's Terminal hardware shop and Stripe ships it\n * straight to the merchant. The platform is the seller of record, because the\n * register's card payments are destination charges on the PLATFORM account\n * and a reader must be registered there to take them.\n *\n * THE CATALOG IS CODE, THE PRICES ARE CONFIG. Which readers the register\n * works with is a fact about this codebase; what Stripe charges for them, the\n * markup on top and what shipping costs are business decisions that change\n * without a release. Every figure comes from the console's environment, read\n * by {@link parsePosHardwareConfig}, and a missing or malformed figure keeps\n * the shop HIDDEN: it is a gate only the platform can lift, so no workspace is\n * shown a control it cannot use.\n *\n * Everything here is pure, so the price math, the metadata a Checkout Session\n * carries and the status rules are specced without Firestore or Stripe.\n *=========================================*/\n\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport type { PosHardwareTermsAcceptance } from './pos-hardware-terms'\n\n/** The register's currency, and so the shop's: US dollars. */\nexport const POS_HARDWARE_CURRENCY = 'usd'\n\n/**\n * Where the shop ships. Stripe's Terminal hardware shop ships to many\n * countries, but the register sells in US dollars only and the readers a\n * merchant buys here are registered to a US Location, so the shop is US-only\n * (Stripe itself excludes the US Virgin Islands, military addresses and\n * P.O. boxes).\n */\nexport const POS_HARDWARE_SHIP_COUNTRIES: readonly string[] = ['US']\n\n/** The most of one item, and the most units, a single order may hold. */\nexport const POS_HARDWARE_MAX_PER_LINE = 10\nexport const POS_HARDWARE_MAX_UNITS = 20\n\n/** The env names the shop reads, named once for the reader and the docs. */\nexport const POS_HARDWARE_ENV = {\n /** `true` releases the shop. Absent or anything else keeps it hidden. */\n enabled: 'POS_HARDWARE_SHOP_ENABLED',\n /** JSON `{ \"<sku>\": <Stripe's price in cents> }`. */\n prices: 'POS_HARDWARE_PRICES',\n /**\n * The markup on Stripe's price, an integer in basis points (100 = 1%).\n * Absent, {@link POS_HARDWARE_DEFAULT_MARKUP_BPS} applies.\n */\n markupBps: 'POS_HARDWARE_MARKUP_BPS',\n /** JSON `{ \"standard\" | \"express\" | \"priority\": <cents> }`. */\n shipping: 'POS_HARDWARE_SHIPPING',\n /** `true` turns Stripe automatic tax on for hardware checkouts. */\n automaticTax: 'POS_HARDWARE_AUTOMATIC_TAX',\n /**\n * `true` lets the platform's own store sell hardware IN PERSON at its\n * register (AGL-4038): a reader handed over at an event, attached to the\n * buyer's workspace. Absent or anything else keeps it off.\n */\n inPersonEnabled: 'POS_HARDWARE_IN_PERSON_ENABLED',\n /** The site id of the platform's own store whose register sells hardware in person. */\n sellerHostId: 'POS_HARDWARE_SELLER_HOST_ID',\n /** The workspace that owns that store. */\n sellerOrgId: 'POS_HARDWARE_SELLER_ORG_ID',\n} as const\n\n/**\n * The markup when the deployment sets none: 3000 basis points on Stripe's\n * price. The business sets it; this is the one place the default lives, and\n * `POS_HARDWARE_MARKUP_BPS` overrides it.\n */\nexport const POS_HARDWARE_DEFAULT_MARKUP_BPS = 3000\n\nexport type PosHardwareSkuId =\n | 'stripe-reader-s710'\n | 'stripe-reader-s700'\n | 'stripe-reader-t600'\n | 'stripe-reader-m2'\n | 'bbpos-wisepos-e'\n | 'stripe-reader-s700-dock'\n | 'stripe-reader-hub'\n | 'stripe-reader-s700-case'\n | 'stripe-reader-s700-cable'\n | 'stripe-reader-charger'\n | 'stripe-reader-m2-dock'\n | 'stripe-reader-m2-mount'\n | 'bbpos-wisepos-e-dock'\n | 'bbpos-wisepos-e-power-cable'\n\nexport interface PosHardwareSku {\n id: PosHardwareSkuId\n kind: 'reader' | 'accessory'\n /** What Stripe's hardware shop calls it, for the staff member ordering it. */\n stripeProductName: string\n /** What the merchant sees. */\n displayName: string\n /** One line on what it is for. */\n use: string\n}\n\n/**\n * Every item the shop can sell. An item is offered only once its Stripe\n * price is configured, so one Stripe stops selling disappears by deleting its\n * price, not by a release.\n */\nexport const POS_HARDWARE_SKUS: readonly PosHardwareSku[] = [\n {\n id: 'stripe-reader-s710',\n kind: 'reader',\n stripeProductName: 'Stripe Reader S710',\n displayName: 'Stripe Reader S710',\n // 4G needs Stripe's cellular service, billed monthly per reader, which a\n // store turns on for its S710s where it is offered (AGL-4038): the reader\n // alone does not bring a connection.\n use: 'Handheld for events and parking lots; 4G needs Stripe’s cellular service, billed monthly',\n },\n {\n id: 'stripe-reader-s700',\n kind: 'reader',\n stripeProductName: 'Stripe Reader S700',\n displayName: 'Stripe Reader S700',\n use: 'Handheld or countertop reader on Wi-Fi',\n },\n {\n id: 'stripe-reader-t600',\n kind: 'reader',\n stripeProductName: 'Stripe Reader T600',\n displayName: 'Stripe Reader T600',\n use: 'Countertop reader on Wi-Fi, or on Ethernet with the hub',\n },\n {\n id: 'bbpos-wisepos-e',\n kind: 'reader',\n stripeProductName: 'BBPOS WisePOS E',\n displayName: 'BBPOS WisePOS E',\n use: 'Countertop reader on Wi-Fi',\n },\n {\n id: 'stripe-reader-m2',\n kind: 'reader',\n stripeProductName: 'Stripe Reader M2',\n displayName: 'Stripe Reader M2',\n use: `Pairs with the ${PLATFORM_BRAND_NAME} POS app on your phone or tablet by Bluetooth`,\n },\n {\n id: 'stripe-reader-s700-dock',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader S700/S710 Dock',\n displayName: 'Charging dock for the S700 and S710',\n use: 'Keeps the reader charged at the counter and adds an Ethernet port',\n },\n {\n id: 'stripe-reader-hub',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader Hub',\n displayName: 'Hub for the S700, S710 and T600',\n use: 'Connects the reader to Ethernet and power',\n },\n {\n id: 'stripe-reader-s700-case',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader S700/S710 Case',\n displayName: 'Case for the S700 and S710',\n use: 'Protects a handheld reader on the move',\n },\n {\n id: 'stripe-reader-s700-cable',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader S700/S710 Cable',\n displayName: 'Cable for the S700 and S710',\n use: 'A spare cable for the reader',\n },\n {\n id: 'stripe-reader-charger',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader Charger',\n displayName: 'Charger for Stripe readers',\n use: 'A spare wall charger',\n },\n {\n id: 'stripe-reader-m2-dock',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader M2 Dock',\n displayName: 'Charging dock for the M2',\n use: 'Keeps the M2 charged at the counter',\n },\n {\n id: 'stripe-reader-m2-mount',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader M2 Mount',\n displayName: 'Mount for the M2',\n use: 'Holds the M2 in place at the counter',\n },\n {\n id: 'bbpos-wisepos-e-dock',\n kind: 'accessory',\n stripeProductName: 'BBPOS WisePOS E Dock',\n displayName: 'Charging dock for the WisePOS E',\n use: 'Keeps the reader charged at the counter and adds an Ethernet port',\n },\n {\n id: 'bbpos-wisepos-e-power-cable',\n kind: 'accessory',\n stripeProductName: 'BBPOS WisePOS E 5ft Power Cable',\n displayName: '5 ft power cable for the WisePOS E',\n use: 'A spare power cable for the reader',\n },\n]\n\nexport function posHardwareSku(id: string): PosHardwareSku | null {\n return POS_HARDWARE_SKUS.find((sku) => sku.id === id) ?? null\n}\n\nexport type PosHardwareShippingMethod = 'standard' | 'express' | 'priority'\n\nexport const POS_HARDWARE_SHIPPING_LABELS: Record<PosHardwareShippingMethod, string> = {\n standard: 'Standard shipping',\n express: 'Express shipping',\n priority: 'Priority shipping',\n}\n\nconst SHIPPING_METHODS = Object.keys(POS_HARDWARE_SHIPPING_LABELS) as PosHardwareShippingMethod[]\n\nexport function isPosHardwareShippingMethod(value: unknown): value is PosHardwareShippingMethod {\n return typeof value === 'string' && (SHIPPING_METHODS as string[]).includes(value)\n}\n\n/**\n * How an order reached the buyer: one of the shop's shipping speeds, or\n * `in_person` — handed over at the platform's own register (AGL-4038), with\n * no parcel, address or carrier. Never offered at checkout.\n */\nexport type PosHardwareOrderShippingMethod = PosHardwareShippingMethod | 'in_person'\n\nexport const POS_HARDWARE_IN_PERSON_SHIPPING_LABEL = 'Handed over in person'\n\n/** The label of any order's method, the in-person one included. */\nexport function posHardwareShippingLabel(method: PosHardwareOrderShippingMethod | null | undefined): string {\n if (method === 'in_person') return POS_HARDWARE_IN_PERSON_SHIPPING_LABEL\n return POS_HARDWARE_SHIPPING_LABELS[isPosHardwareShippingMethod(method) ? method : 'standard']\n}\n\n/** The shop's configuration, once every figure it needs is present and sane. */\nexport interface PosHardwareConfig {\n /** Stripe's price for each configured item, in cents. */\n costs: Partial<Record<PosHardwareSkuId, number>>\n markupBps: number\n shipping: Array<{ method: PosHardwareShippingMethod; cents: number }>\n automaticTax: boolean\n}\n\n/** The highest single figure the parser accepts, in cents: $10,000. */\nconst MAX_FIGURE_CENTS = 1_000_000\n/** The highest markup the parser accepts: 1000%. */\nconst MAX_MARKUP_BPS = 100_000\n\nconst isCents = (value: unknown, min: number): value is number =>\n typeof value === 'number' &&\n Number.isSafeInteger(value) &&\n value >= min &&\n value <= MAX_FIGURE_CENTS\n\nfunction parseJsonObject(raw: string | undefined): Record<string, unknown> | null {\n const text = String(raw ?? '').trim()\n if (!text) return null\n try {\n const parsed = JSON.parse(text) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n}\n\n/**\n * The shop's configuration from the environment, or `null` while the shop is\n * hidden: not released, no reader priced, a malformed markup, or no shipping\n * figure. An ABSENT markup is the default\n * ({@link POS_HARDWARE_DEFAULT_MARKUP_BPS}), so a deployment can never sell\n * at cost by forgetting a variable; `0` is a valid, explicit choice to sell\n * at Stripe's price. A markup that is set but unreadable hides the shop\n * rather than guessing.\n *\n * Unknown item ids and malformed figures are dropped one by one rather than\n * failing the whole shop, so a typo in one price hides that one item.\n */\nexport function parsePosHardwareConfig(\n env: Record<string, string | undefined>,\n): PosHardwareConfig | null {\n if (String(env[POS_HARDWARE_ENV.enabled] ?? '').trim().toLowerCase() !== 'true') return null\n\n const markupText = String(env[POS_HARDWARE_ENV.markupBps] ?? '').trim()\n if (markupText && !/^\\d+$/.test(markupText)) return null\n const markupBps = markupText ? Number(markupText) : POS_HARDWARE_DEFAULT_MARKUP_BPS\n if (!Number.isSafeInteger(markupBps) || markupBps > MAX_MARKUP_BPS) return null\n\n const prices = parseJsonObject(env[POS_HARDWARE_ENV.prices])\n if (!prices) return null\n const costs: Partial<Record<PosHardwareSkuId, number>> = {}\n for (const sku of POS_HARDWARE_SKUS) {\n const cost = prices[sku.id]\n if (isCents(cost, 1)) costs[sku.id] = cost\n }\n const anyReader = POS_HARDWARE_SKUS.some((sku) => sku.kind === 'reader' && costs[sku.id] !== undefined)\n if (!anyReader) return null\n\n const shippingRaw = parseJsonObject(env[POS_HARDWARE_ENV.shipping])\n if (!shippingRaw) return null\n const shipping = SHIPPING_METHODS.flatMap((method) => {\n const cents = shippingRaw[method]\n return isCents(cents, 0) ? [{ method, cents }] : []\n })\n if (!shipping.length) return null\n\n return {\n costs,\n markupBps,\n shipping,\n automaticTax:\n String(env[POS_HARDWARE_ENV.automaticTax] ?? '').trim().toLowerCase() === 'true',\n }\n}\n\n/*==========================================\n * SELLING HARDWARE IN PERSON (AGL-4038).\n *\n * The platform also sells readers face to face, at an event, from its OWN\n * store's register: the same products a store sells, rung up like any other\n * sale, priced and taxed by that store, paid into that store's account. The\n * one difference is what follows the sale — a hardware order for the buyer's\n * workspace, so the reader shows up there and can be set up, returned or\n * refunded like one bought online.\n *\n * Which store that is, is configuration: the site and its workspace, named in\n * the environment beside the shop's other figures. A product on that store\n * names the hardware item it is ({@link isPosHardwareSkuId} on the product's\n * `hardwareSku`), and no other store's product ever does, whatever it says.\n *=========================================*/\n\n/** The platform's own store, once the in-person sale is turned on and named. */\nexport interface PosHardwareInPersonConfig {\n sellerHostId: string\n sellerOrgId: string\n}\n\nconst CONFIG_ID = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The in-person sale's configuration from the environment, or `null` while\n * it is off: not turned on, or the store or its workspace not named, or\n * named with something that cannot be an id. It needs nothing of the online\n * shop's: the store's own products carry the prices.\n */\nexport function parsePosHardwareInPersonConfig(\n env: Record<string, string | undefined>,\n): PosHardwareInPersonConfig | null {\n if (String(env[POS_HARDWARE_ENV.inPersonEnabled] ?? '').trim().toLowerCase() !== 'true') return null\n const sellerHostId = String(env[POS_HARDWARE_ENV.sellerHostId] ?? '').trim()\n const sellerOrgId = String(env[POS_HARDWARE_ENV.sellerOrgId] ?? '').trim()\n if (!CONFIG_ID.test(sellerHostId) || !CONFIG_ID.test(sellerOrgId)) return null\n return { sellerHostId, sellerOrgId }\n}\n\nexport function isPosHardwareSkuId(value: unknown): value is PosHardwareSkuId {\n return typeof value === 'string' && posHardwareSku(value) !== null\n}\n\n/**\n * A reader's serial number as staff scanned or typed it, in the one form\n * every comparison uses: upper case, letters, digits and dashes only, at\n * most 64 characters. Empty when nothing usable was given.\n */\nexport function normalizePosHardwareSerial(value: unknown): string {\n return String(value ?? '')\n .toUpperCase()\n .replace(/[^A-Z0-9-]/g, '')\n .slice(0, 64)\n}\n\n/**\n * What the merchant pays for one item: Stripe's price plus the markup,\n * rounded half up to the cent, in integer math throughout.\n *\n * `cost + round(cost × bps / 10 000)`. The markup is basis points ON COST, so\n * a 50% markup is `5000` and a price at which half of it is profit (a 50%\n * margin) is `10000`. Whichever the business means, it is this one number.\n */\nexport function posHardwareUnitCents(costCents: number, markupBps: number): number {\n if (!Number.isSafeInteger(costCents) || costCents <= 0) return 0\n if (!Number.isSafeInteger(markupBps) || markupBps < 0) return costCents\n return costCents + Math.floor((costCents * markupBps + 5_000) / 10_000)\n}\n\n/** An item as the shop offers it: the merchant's price, never Stripe's. */\nexport interface PosHardwareOffer {\n sku: PosHardwareSkuId\n kind: PosHardwareSku['kind']\n name: string\n use: string\n unitCents: number\n}\n\n/** The items on offer, readers first, in catalog order. */\nexport function posHardwareOffers(config: PosHardwareConfig): PosHardwareOffer[] {\n return POS_HARDWARE_SKUS.flatMap((sku) => {\n const cost = config.costs[sku.id]\n if (cost === undefined) return []\n return [\n {\n sku: sku.id,\n kind: sku.kind,\n name: sku.displayName,\n use: sku.use,\n unitCents: posHardwareUnitCents(cost, config.markupBps),\n },\n ]\n })\n}\n\nexport interface PosHardwareLine {\n sku: PosHardwareSkuId\n name: string\n quantity: number\n unitCents: number\n lineCents: number\n}\n\nexport type PosHardwareCartResult =\n | { ok: true; lines: PosHardwareLine[]; subtotalCents: number }\n | { ok: false; error: string }\n\n/**\n * A merchant's basket priced on the SERVER: every item must be on offer, each\n * quantity a whole number from 1 to {@link POS_HARDWARE_MAX_PER_LINE}, and\n * the order at most {@link POS_HARDWARE_MAX_UNITS} units. A repeated item is\n * folded into one line. Prices come from the config, never the request.\n */\nexport function pricePosHardwareCart(\n config: PosHardwareConfig,\n requested: unknown,\n): PosHardwareCartResult {\n if (!Array.isArray(requested) || requested.length === 0) {\n return { ok: false, error: 'Choose at least one item.' }\n }\n const offers = new Map(posHardwareOffers(config).map((offer) => [offer.sku as string, offer]))\n const quantities = new Map<string, number>()\n for (const entry of requested) {\n const sku = String((entry as { sku?: unknown })?.sku ?? '')\n const quantity = Number((entry as { quantity?: unknown })?.quantity)\n if (!offers.has(sku)) return { ok: false, error: 'That item is not available.' }\n if (!Number.isInteger(quantity) || quantity < 1) {\n return { ok: false, error: 'Each quantity must be a whole number of at least 1.' }\n }\n quantities.set(sku, (quantities.get(sku) ?? 0) + quantity)\n }\n let units = 0\n const lines: PosHardwareLine[] = []\n for (const [sku, quantity] of quantities) {\n if (quantity > POS_HARDWARE_MAX_PER_LINE) {\n return { ok: false, error: `Order at most ${POS_HARDWARE_MAX_PER_LINE} of each item.` }\n }\n units += quantity\n const offer = offers.get(sku) as PosHardwareOffer\n lines.push({\n sku: offer.sku,\n name: offer.name,\n quantity,\n unitCents: offer.unitCents,\n lineCents: offer.unitCents * quantity,\n })\n }\n if (units > POS_HARDWARE_MAX_UNITS) {\n return { ok: false, error: `One order holds at most ${POS_HARDWARE_MAX_UNITS} items.` }\n }\n // Accessories alone are allowed: a merchant may want a second dock.\n return { ok: true, lines, subtotalCents: lines.reduce((sum, line) => sum + line.lineCents, 0) }\n}\n\n/*==========================================\n * THE CHECKOUT SESSION'S METADATA.\n *\n * The webhook builds the order from the session Stripe hands back, so the\n * lines ride in its metadata in a compact form (`sku*qty*unit;…`, inside\n * Stripe's 500-character value limit even with every item in the catalog in\n * one basket at the highest price the config accepts, which a spec holds),\n * and the webhook re-reads every one against the catalog rather than trusting\n * a name from the wire.\n *=========================================*/\n\nexport const POS_HARDWARE_METADATA_TYPE = 'pos-hardware-order'\n\nexport function encodePosHardwareLines(lines: readonly PosHardwareLine[]): string {\n return lines.map((line) => `${line.sku}*${line.quantity}*${line.unitCents}`).join(';')\n}\n\nexport function decodePosHardwareLines(encoded: unknown): PosHardwareLine[] | null {\n const text = String(encoded ?? '').trim()\n if (!text) return null\n const lines: PosHardwareLine[] = []\n for (const part of text.split(';')) {\n const [skuId, quantityText, unitText] = part.split('*')\n const sku = posHardwareSku(String(skuId ?? ''))\n const quantity = Number(quantityText)\n const unitCents = Number(unitText)\n if (!sku) return null\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_HARDWARE_MAX_PER_LINE) return null\n if (!Number.isSafeInteger(unitCents) || unitCents < 1) return null\n lines.push({ sku: sku.id, name: sku.displayName, quantity, unitCents, lineCents: quantity * unitCents })\n }\n return lines\n}\n\n/*==========================================\n * THE ORDER AND ITS STATUSES.\n *=========================================*/\n\nexport type PosHardwareOrderStatus =\n | 'paid'\n | 'ordered'\n | 'shipped'\n | 'delivered'\n | 'registered'\n | 'canceled'\n | 'refunded'\n\nexport const POS_HARDWARE_ORDER_STATUSES: readonly PosHardwareOrderStatus[] = [\n 'paid',\n 'ordered',\n 'shipped',\n 'delivered',\n 'registered',\n 'canceled',\n 'refunded',\n]\n\nexport function isPosHardwareOrderStatus(value: unknown): value is PosHardwareOrderStatus {\n return typeof value === 'string' && (POS_HARDWARE_ORDER_STATUSES as readonly string[]).includes(value)\n}\n\n/** What the merchant reads on the Hardware card. */\nexport const POS_HARDWARE_STATUS_LABELS: Record<PosHardwareOrderStatus, string> = {\n paid: 'Order received',\n ordered: 'Being prepared',\n shipped: 'Shipped',\n delivered: 'Delivered',\n registered: 'Set up',\n canceled: 'Canceled',\n refunded: 'Refunded',\n}\n\n/** What staff read on the orders page: where the order is in fulfillment. */\nexport const POS_HARDWARE_STAFF_STATUS_LABELS: Record<PosHardwareOrderStatus, string> = {\n paid: 'Paid',\n ordered: 'Ordered from Stripe',\n shipped: 'Shipped',\n delivered: 'Delivered',\n registered: 'Registered',\n canceled: 'Canceled',\n refunded: 'Refunded',\n}\n\n/**\n * The forward steps staff may move an order through. Canceling and refunding\n * are separate acts with their own rule ({@link posHardwareRefundable}),\n * because each returns money.\n */\nconst NEXT_STATUS: Partial<Record<PosHardwareOrderStatus, PosHardwareOrderStatus>> = {\n paid: 'ordered',\n ordered: 'shipped',\n shipped: 'delivered',\n delivered: 'registered',\n}\n\nexport function nextPosHardwareStatus(\n status: PosHardwareOrderStatus,\n): PosHardwareOrderStatus | null {\n return NEXT_STATUS[status] ?? null\n}\n\n/**\n * Whether the order may still be canceled or refunded in full: only before it\n * ships. Once a parcel is on its way the money comes back through a return of\n * the hardware, which is a separate process this phase does not automate.\n */\nexport function posHardwareRefundable(status: PosHardwareOrderStatus): boolean {\n return status === 'paid' || status === 'ordered'\n}\n\nexport interface PosHardwareAddress {\n line1: string\n line2?: string\n city: string\n state?: string\n postalCode: string\n country: string\n}\n\n/**\n * What sales tax is sourced by: where the order shipped, without the street\n * or the person. An erasure keeps this much of the address (see\n * {@link posHardwareBuyerErasedPatch}) and the retained sale record holds\n * nothing finer ({@link PosHardwareSaleRecord}).\n */\nexport interface PosHardwareTaxRegion {\n country: string\n state: string | null\n postalCode: string | null\n}\n\nexport interface PosHardwareTracking {\n carrier: string\n number: string\n url: string | null\n}\n\n/**\n * Why an order was canceled and refunded: by staff on the Hardware orders\n * page, or because the workspace that bought it was deleted or the account\n * that placed it was closed before it shipped (AGL-4038 closure).\n */\nexport type PosHardwareCancelReason = 'staff' | 'workspace-closed' | 'account-closed'\n\n/**\n * One entry of the tax Stripe computed on a hardware checkout, as the\n * storefront's tax rows store it (`StorefrontTaxLine`): the amount, the base\n * it was applied to (`taxable_amount`, null when Stripe did not state one)\n * and the rate, for the working papers of the platform's own return.\n */\nexport interface PosHardwareTaxLine {\n amountCents: number\n taxabilityReason: string | null\n taxRateId: string | null\n taxableAmountCents: number | null\n jurisdiction: string | null\n rateState: string | null\n percentage: number | null\n}\n\n/**\n * Where an order was sold (AGL-4038): the Hardware card's checkout, or the\n * platform's own register, in person. Absent on every order sold before the\n * in-person sale existed, which were all online; read it through\n * {@link posHardwareOrderSource}.\n */\nexport type PosHardwareOrderSource = 'online' | 'in_person'\n\nexport function posHardwareOrderSource(\n order: { source?: unknown } | null | undefined,\n): PosHardwareOrderSource {\n return order?.source === 'in_person' ? 'in_person' : 'online'\n}\n\n/**\n * The register sale an in-person order came from: the platform's own store,\n * the register order and its number, and how it was rung.\n */\nexport interface PosHardwareRegisterSale {\n hostId: string\n orgId: string\n orderId: string\n /** The register order's number, as its receipt shows it. */\n number: number | null\n registerId: string | null\n /** A customer built it at the self-service kiosk. */\n kiosk: boolean\n /** It was rung while the register was offline, and synced later. */\n offline: boolean\n /**\n * The Checkout Session of the register's payment link, when the sale was\n * paid by one: the storefront's tax record of the sale is filed under it.\n */\n paymentLinkSessionId: string | null\n}\n\n/**\n * Where an in-person sale's money went, for the books to reconcile it\n * against: the selling store's own takings — cash in its drawer, cards into\n * its connected Stripe account, exactly as every sale on its register. The\n * hardware order records it because the platform's online sales land in the\n * platform's own account instead, and the two must never be summed as one.\n */\nexport interface PosHardwarePaidTo {\n account: 'seller_store'\n hostId: string\n orgId: string\n /** The register sale's tenders, as its payments name them (`cash`, `card_present`, …). */\n tenders: string[]\n /** The store's connected Stripe account, when its owner has one. */\n stripeAccountId: string | null\n}\n\n/**\n * Who an in-person order belongs to (AGL-4038). `attached` once it is in the\n * buyer's workspace; `pending` while staff have still to say whose it is —\n * a kiosk or offline sale, a buyer with no account yet (`email`, invited to\n * sign up), or one with an account and no workspace yet (`uid`). A pending\n * order is kept in the selling workspace's own `hardwareOrders`, on its \"To\n * attach\" list, and moves to the buyer's workspace when it is attached.\n */\nexport interface PosHardwareAttachment {\n state: 'attached' | 'pending'\n /** The buyer's address: the account's, or the one typed for a buyer with no account. */\n email: string | null\n uid: string | null\n /** The buyer's workspace, once there is one. */\n orgId: string | null\n /** The store the buyer chose for the reader, when they chose one at the sale. */\n hostId: string | null\n /** The register user who attached it; null for the buyer's own sign-up. */\n attachedBy: string | null\n attachedAtMs: number | null\n /** When the sign-up invitation went to `email`, for a buyer with no account. */\n invitedAtMs?: number | null\n /**\n * The buyer's name, for the platform's reseller records (AGL-4038): the\n * account's name, or the one typed at the sale. An online order keeps it\n * in `shipping.name` instead. Taken off with the buyer's account.\n */\n name?: string | null\n /**\n * The buyer's business address, for the same records: typed at the sale,\n * or the address of the store the readers are set up on. Never the tax\n * region, which stays the selling store's. Taken off with the account.\n */\n address?: PosHardwareAddress | null\n}\n\n/**\n * One reader of an in-person order, by its serial number when staff scanned\n * it at the sale (AGL-4038). The order moves to Set up when every reader on\n * it is registered to the buyer's store.\n */\nexport interface PosHardwareUnit {\n sku: PosHardwareSkuId\n /** Normalized ({@link normalizePosHardwareSerial}); null when none was taken. */\n serialNumber: string | null\n /** The Stripe Terminal reader it was registered as, and on which store. */\n readerId: string | null\n hostId: string | null\n registeredAtMs: number | null\n}\n\n/**\n * One refund of an in-person order (AGL-4038), once by its key: a return at\n * the selling store's register (`register:{returnId}`), or a refund from the\n * staff Hardware orders page (`staff:{n}`), both paid back from the selling\n * store's own takings the way the sale was paid.\n */\nexport interface PosHardwareRefund {\n key: string\n via: 'register' | 'staff'\n cents: number\n /** Hardware items it took back; 0 when the refund named none. */\n quantity: number\n atMs: number\n stripeRefundId: string | null\n}\n\n/**\n * The buyer's request to return an in-person order, from their own\n * purchase history (AGL-4038). Staff refund it (`refunded`) or decline it.\n * Returns follow Stripe's hardware terms.\n */\nexport interface PosHardwareReturnRequest {\n state: 'requested' | 'declined' | 'refunded'\n /** The buyer's words; taken off with the buyer when their account is erased. */\n reason: string | null\n requestedBy: string | null\n requestedAtMs: number\n decidedBy: string | null\n decidedAtMs: number | null\n /** What staff told the buyer when declining. */\n note: string | null\n}\n\nexport const POS_HARDWARE_RETURN_REASON_MAX = 500\n\n/** `orgs/{orgId}/hardwareOrders/{orderId}`, written only by the server. */\nexport interface PosHardwareOrder {\n orgId: string\n /**\n * The site whose POS settings the order was placed from; for an in-person\n * order, the buyer's store once known, else the selling store.\n */\n hostId: string\n /** The member who started the checkout; `null` once their account is erased. */\n createdBy: string | null\n /** Where the order emails go: the address entered at checkout. */\n contactEmail: string | null\n lines: PosHardwareLine[]\n subtotalCents: number\n shipping: {\n method: PosHardwareOrderShippingMethod\n label: string\n cents: number\n name: string | null\n phone: string | null\n address: PosHardwareAddress | null\n /**\n * Set when the buyer's account is erased, in place of `address`: the part\n * of it sales tax is sourced by.\n */\n taxRegion?: PosHardwareTaxRegion | null\n }\n taxCents: number\n /**\n * The register sale's discounts that fell on this order's lines, for an\n * in-person order (AGL-4038): `totalCents` is the lines less this, plus\n * the tax. Absent, and so nothing, on every online order.\n */\n discountCents?: number\n totalCents: number\n currency: string\n /** Whether Stripe Tax computed the tax on the checkout. Absent on orders before it was recorded. */\n automaticTax?: boolean\n /** Stripe's tax breakdown for the checkout, when Stripe Tax computed it. */\n taxLines?: PosHardwareTaxLine[]\n /** The Hardware card's checkout; null for an in-person sale, which had none. */\n stripeCheckoutSessionId: string | null\n stripePaymentIntentId: string | null\n /** Stripe's hardware order id, recorded by staff (phase 2 sets it itself). */\n stripeHardwareOrderId: string | null\n tracking: PosHardwareTracking | null\n status: PosHardwareOrderStatus\n livemode: boolean\n createdAtMs: number\n updatedAtMs: number\n paidAtMs: number\n orderedAtMs?: number\n shippedAtMs?: number\n deliveredAtMs?: number\n registeredAtMs?: number\n canceledAtMs?: number\n refundedAtMs?: number\n refundId?: string | null\n /** The cents Stripe reported refunding. */\n refundedCents?: number\n /** Why it was canceled, when it was. */\n cancelReason?: PosHardwareCancelReason\n /** When the buyer's account was erased and their details taken off the order. */\n buyerErasedAtMs?: number\n /** Where it was sold; absent reads as online ({@link posHardwareOrderSource}). */\n source?: PosHardwareOrderSource\n /** The register sale an in-person order came from. */\n posSale?: PosHardwareRegisterSale\n /** Where an in-person sale's money went. */\n paidTo?: PosHardwarePaidTo\n /** Whose an in-person order is, or that staff have still to say. */\n attachment?: PosHardwareAttachment\n /**\n * How the buyer of an in-person order agreed to the terms of sale\n * (AGL-4038): copied from the register sale, or the receipt-and-sign\n * notice when they did not accept electronically.\n */\n termsAcceptance?: PosHardwareTermsAcceptance\n /** Each reader of an in-person order, with its serial when one was taken. */\n units?: PosHardwareUnit[]\n /** The units' serial numbers, for finding the order when a reader is registered. */\n serialNumbers?: string[]\n /** An in-person order's refunds, each once by its key. */\n refunds?: PosHardwareRefund[]\n /** The buyer's request to return it, and what staff decided. */\n returnRequest?: PosHardwareReturnRequest\n /**\n * The emails that are sent once (AGL-4038), by key: `canceled`, or\n * `refunded:{refund key}`. Claimed before the send, so the staff page and a\n * closure never both send one.\n */\n buyerEmails?: Record<string, { state: 'sending' | 'sent' | 'skipped' | 'failed'; atMs: number }>\n}\n\n/** The timestamp field each status stamps when it is reached. */\nexport const POS_HARDWARE_STATUS_STAMP: Record<PosHardwareOrderStatus, keyof PosHardwareOrder> = {\n paid: 'paidAtMs',\n ordered: 'orderedAtMs',\n shipped: 'shippedAtMs',\n delivered: 'deliveredAtMs',\n registered: 'registeredAtMs',\n canceled: 'canceledAtMs',\n refunded: 'refundedAtMs',\n}\n\n/** The Hardware card's anchor: Checkout returns to it and the emails link at it. */\nexport const POS_HARDWARE_ANCHOR = 'pos-hardware'\n\n/** The collection under `orgs/{orgId}`, named once. */\nexport const POS_HARDWARE_ORDERS_COLLECTION = 'hardwareOrders'\n\n/*==========================================\n * THE SALE RECORD THE PLATFORM KEEPS (AGL-4038).\n *\n * A hardware order is the PLATFORM's own sale: the platform is the seller of\n * record and owes the sales tax on it. So beside every order the server keeps\n * `posHardwareSales/{orderId}`, a TOP-LEVEL record of what tax and accounting\n * need — the lines, the amounts, the tax, Stripe's ids, the status dates and\n * the region it shipped to — and, of the person who bought it, only their\n * NAME and ADDRESS ({@link PosHardwareSaleBuyer}).\n *\n * The name and address are the reseller's records Stripe's Terminal Reseller\n * Terms §10 ask for: the identity and address of each buyer, open to Stripe's\n * inspection. §10 states no period, so they are kept for the record's own\n * seven years. They SURVIVE the buyer's account erasure, which still takes\n * the email, phone, tracking and the name and street off the ORDER: every\n * write sets the record through {@link posHardwareSaleSetOptions}, which\n * leaves the stored name and address alone when the order no longer has\n * them because its buyer was erased.\n *\n * It is the `platformRevenue` / `storefrontTaxCollected` shape on purpose\n * (AGL-1811, AGL-1904): keyed to the workspace by FIELD, outside\n * `orgs/{orgId}`, so the workspace erasure's `recursiveDelete(orgs/{orgId})`\n * cannot see it, and never in any org-keyed sweep. GDPR Art. 17(3)(b) exempts\n * records kept to comply with a legal obligation. The order under the\n * workspace, with the buyer's name, street, phone, email and tracking, is\n * erased with the workspace as before.\n *\n * Written in the same transaction as every write to the order, from the\n * order as it stands after that write, so the two never disagree and a\n * missing record heals on the next write.\n *\n * KEPT SEVEN YEARS FROM THE SALE, THEN DELETED. Every write stamps\n * `expiresAt` ({@link posHardwareSaleExpiry}) and the Firestore TTL policy on\n * `posHardwareSales.expiresAt` deletes the record once it passes.\n *=========================================*/\n\n/** The top-level collection of retained hardware sale records. */\nexport const POS_HARDWARE_SALES_COLLECTION = 'posHardwareSales'\n\n/**\n * A street address as the sale record keeps it: every key present, so a\n * later write of a different address replaces each one.\n */\nexport interface PosHardwareSaleAddress {\n line1: string\n line2: string | null\n city: string\n state: string | null\n postalCode: string | null\n country: string\n}\n\n/**\n * Who bought it, for the reseller's records (AGL-4038): the buyer's name and\n * address and nothing else of theirs. An online order's are the shipping\n * name and address; an in-person order's are on its attachment.\n */\nexport interface PosHardwareSaleBuyer {\n name: string | null\n address: PosHardwareSaleAddress | null\n}\n\n/**\n * `posHardwareSales/{orderId}`: an order with every personal detail left out\n * but the buyer's name and address.\n */\nexport interface PosHardwareSaleRecord {\n orderId: string\n /** The workspace that bought it, by id; the record outlives the workspace. */\n orgId: string\n lines: Array<Pick<PosHardwareLine, 'sku' | 'name' | 'quantity' | 'unitCents' | 'lineCents'>>\n subtotalCents: number\n shippingMethod: PosHardwareOrderShippingMethod\n shippingCents: number\n taxCents: number\n /** The register discount on an in-person order's lines; 0 for every online one. */\n discountCents: number\n totalCents: number\n currency: string\n /** The sales tax sourcing input: country, state and postal code, never the street. */\n shipTo: PosHardwareTaxRegion | null\n /** Whether Stripe Tax computed the tax; null on orders before it was recorded. */\n automaticTax: boolean | null\n /** Stripe's tax breakdown: the base each rate was applied to, for the return. */\n taxLines: PosHardwareTaxLine[]\n stripeCheckoutSessionId: string | null\n stripePaymentIntentId: string | null\n stripeHardwareOrderId: string | null\n refundId: string | null\n refundedCents: number | null\n status: PosHardwareOrderStatus\n livemode: boolean\n createdAtMs: number\n updatedAtMs: number\n paidAtMs: number | null\n orderedAtMs: number | null\n shippedAtMs: number | null\n deliveredAtMs: number | null\n registeredAtMs: number | null\n canceledAtMs: number | null\n refundedAtMs: number | null\n /** Where it was sold; `online` for every order before the in-person sale. */\n source: PosHardwareOrderSource\n /** The register sale an in-person order came from: the selling store and its order. */\n posHostId: string | null\n posOrderId: string | null\n /**\n * Where the money went: `platform` for the Hardware card's checkout, on\n * the platform's own Stripe account; `seller_store` for an in-person sale,\n * the selling store's own takings ({@link PosHardwarePaidTo}).\n */\n paidTo: { account: 'platform' } | PosHardwarePaidTo\n /**\n * The `storefrontTaxCollected` row the register sale ALSO filed, when it\n * was paid by a payment link. That row is the whole register sale; the\n * storefront section leaves this order's part of it out, so the sale is on\n * the return once, in the hardware section.\n */\n storefrontTaxRowId: string | null\n /**\n * The buyer's name and address, for the reseller's records; null when the\n * order names none (a sale not attached to anyone yet). Absent from a write\n * whose order no longer has them because the buyer's account was erased,\n * so the stored ones stay ({@link posHardwareSaleSetOptions}).\n */\n buyer?: PosHardwareSaleBuyer | null\n /**\n * When the record is deleted: {@link POS_HARDWARE_SALE_RETENTION_YEARS}\n * after the sale, by the Firestore TTL policy on `posHardwareSales.expiresAt`.\n * Null when the record states no sale date, which keeps it rather than\n * guessing a date to delete it by.\n */\n expiresAt: Date | null\n}\n\n/**\n * How long the platform keeps a hardware sale record (AGL-4038): seven years\n * from the sale, then the record is deleted. Longer than the four years Texas\n * requires for sales tax records, a margin for an audit of an older period.\n */\nexport const POS_HARDWARE_SALE_RETENTION_YEARS = 7\n\n/**\n * When a sale record expires: the same calendar instant, seven years after\n * the sale was paid (the order's creation where no payment time is stated).\n * A sale on 29 February expires on 1 March, a day late rather than early.\n * Null when there is no sale time, so the record is kept, never reaped at\n * the epoch.\n */\nexport function posHardwareSaleExpiry(\n order: Pick<PosHardwareOrder, 'paidAtMs' | 'createdAtMs'>,\n): Date | null {\n const saleAtMs = [order.paidAtMs, order.createdAtMs].find(\n (value) => typeof value === 'number' && Number.isFinite(value) && value > 0,\n )\n if (saleAtMs === undefined) return null\n const expires = new Date(saleAtMs)\n expires.setUTCFullYear(expires.getUTCFullYear() + POS_HARDWARE_SALE_RETENTION_YEARS)\n return expires\n}\n\n/** A tax line as the record keeps it: every field picked, every figure an integer. */\nfunction saleTaxLine(line: Partial<PosHardwareTaxLine> | null | undefined): PosHardwareTaxLine {\n const integerOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? Math.round(value) : null\n const numberOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n const textOf = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null\n return {\n amountCents: integerOrNull(line?.amountCents) ?? 0,\n taxabilityReason: textOf(line?.taxabilityReason),\n taxRateId: textOf(line?.taxRateId),\n taxableAmountCents: integerOrNull(line?.taxableAmountCents),\n jurisdiction: textOf(line?.jurisdiction),\n rateState: textOf(line?.rateState),\n percentage: numberOrNull(line?.percentage),\n }\n}\n\nconst stampOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\n/** The tax region of an order: its address cut down, or what an erasure left. */\nexport function posHardwareTaxRegion(order: Pick<PosHardwareOrder, 'shipping'>): PosHardwareTaxRegion | null {\n const address = order.shipping?.address\n if (address?.country) {\n return {\n country: address.country,\n state: textOrNull(address.state),\n postalCode: textOrNull(address.postalCode),\n }\n }\n const kept = order.shipping?.taxRegion\n return kept?.country\n ? { country: kept.country, state: textOrNull(kept.state), postalCode: textOrNull(kept.postalCode) }\n : null\n}\n\n/** An address with every key present, or null when it names no place. */\nfunction saleAddress(address: Partial<PosHardwareAddress> | null | undefined): PosHardwareSaleAddress | null {\n const line1 = textOrNull(address?.line1)\n const city = textOrNull(address?.city)\n const country = textOrNull(address?.country)\n if (!line1 || !city || !country) return null\n return {\n line1: line1.slice(0, 200),\n line2: textOrNull(address?.line2)?.slice(0, 200) ?? null,\n city: city.slice(0, 100),\n state: textOrNull(address?.state)?.slice(0, 100) ?? null,\n postalCode: textOrNull(address?.postalCode)?.slice(0, 20) ?? null,\n country: country.toUpperCase().slice(0, 2),\n }\n}\n\n/**\n * A buyer's business address as an in-person order keeps it (AGL-4038):\n * trimmed and cut to length, or null when it lacks a street, city, postal\n * code or two-letter country.\n */\nexport function posHardwareBuyerAddress(value: unknown): PosHardwareAddress | null {\n const address = (value && typeof value === 'object' ? value : {}) as Partial<Record<keyof PosHardwareAddress, unknown>>\n const line1 = textOrNull(address.line1)?.slice(0, 200)\n const city = textOrNull(address.city)?.slice(0, 100)\n const postalCode = textOrNull(address.postalCode)?.slice(0, 20)\n const country = textOrNull(address.country)?.toUpperCase()\n if (!line1 || !city || !postalCode || !country || !/^[A-Z]{2}$/.test(country)) return null\n const line2 = textOrNull(address.line2)?.slice(0, 200)\n const state = textOrNull(address.state)?.slice(0, 100)\n return { line1, ...(line2 ? { line2 } : {}), city, ...(state ? { state } : {}), postalCode, country }\n}\n\n/**\n * The buyer's name and address as the order holds them now (AGL-4038): the\n * shipping name and address of an online order, the attachment's of an\n * in-person one. `undefined` when the order has none BECAUSE its buyer's\n * account was erased, which tells the write to keep what the record has;\n * null when it simply names no one yet.\n */\nexport function posHardwareSaleBuyer(\n order: Pick<PosHardwareOrder, 'shipping' | 'attachment' | 'source' | 'buyerErasedAtMs'>,\n): PosHardwareSaleBuyer | null | undefined {\n const inPerson = posHardwareOrderSource(order) === 'in_person'\n const name = textOrNull(inPerson ? order.attachment?.name : order.shipping?.name)?.slice(0, 200) ?? null\n const address = saleAddress(inPerson ? order.attachment?.address : order.shipping?.address)\n if (name || address) return { name, address }\n return typeof order.buyerErasedAtMs === 'number' ? undefined : null\n}\n\n/**\n * The retained sale record of an order, as it stands. Every field is picked\n * by name, so a field added to the order later reaches the record only when\n * someone decides it should.\n */\nexport function posHardwareSaleRecord(orderId: string, order: PosHardwareOrder): PosHardwareSaleRecord {\n const buyer = posHardwareSaleBuyer(order)\n return {\n orderId,\n orgId: order.orgId,\n lines: (order.lines ?? []).map((line) => ({\n sku: line.sku,\n name: line.name,\n quantity: line.quantity,\n unitCents: line.unitCents,\n lineCents: line.lineCents,\n })),\n subtotalCents: order.subtotalCents ?? 0,\n shippingMethod: order.shipping?.method ?? 'standard',\n shippingCents: order.shipping?.cents ?? 0,\n taxCents: order.taxCents ?? 0,\n discountCents: stampOrNull(order.discountCents) ?? 0,\n totalCents: order.totalCents ?? 0,\n currency: order.currency ?? POS_HARDWARE_CURRENCY,\n shipTo: posHardwareTaxRegion(order),\n automaticTax: typeof order.automaticTax === 'boolean' ? order.automaticTax : null,\n taxLines: (Array.isArray(order.taxLines) ? order.taxLines : []).map(saleTaxLine),\n stripeCheckoutSessionId: textOrNull(order.stripeCheckoutSessionId),\n stripePaymentIntentId: textOrNull(order.stripePaymentIntentId),\n stripeHardwareOrderId: textOrNull(order.stripeHardwareOrderId),\n refundId: textOrNull(order.refundId),\n refundedCents: stampOrNull(order.refundedCents),\n status: order.status,\n livemode: order.livemode === true,\n createdAtMs: order.createdAtMs ?? 0,\n updatedAtMs: order.updatedAtMs ?? order.createdAtMs ?? 0,\n paidAtMs: stampOrNull(order.paidAtMs),\n orderedAtMs: stampOrNull(order.orderedAtMs),\n shippedAtMs: stampOrNull(order.shippedAtMs),\n deliveredAtMs: stampOrNull(order.deliveredAtMs),\n registeredAtMs: stampOrNull(order.registeredAtMs),\n canceledAtMs: stampOrNull(order.canceledAtMs),\n refundedAtMs: stampOrNull(order.refundedAtMs),\n source: posHardwareOrderSource(order),\n posHostId: textOrNull(order.posSale?.hostId),\n posOrderId: textOrNull(order.posSale?.orderId),\n paidTo: salePaidTo(order),\n storefrontTaxRowId: textOrNull(order.posSale?.paymentLinkSessionId),\n // Left out, never written as null, once the buyer was erased: the\n // stored name and address are the reseller's records and stay.\n ...(buyer === undefined ? {} : { buyer }),\n // The TTL policy's field: the record outlives the workspace, not the law.\n expiresAt: posHardwareSaleExpiry(order),\n }\n}\n\n/**\n * How every write of a sale record is made (AGL-4038): `set` with exactly\n * the record's own fields as `mergeFields`, so each one is replaced whole —\n * a map included, never merged key by key — and a field the record leaves\n * out is left as stored. The record leaves out only `buyer`, and only once\n * the buyer's account was erased ({@link posHardwareSaleBuyer}), so the\n * buyer's name and address outlive the erasure and every write after it.\n */\nexport function posHardwareSaleSetOptions(order: PosHardwareOrder): { mergeFields: string[] } {\n return { mergeFields: Object.keys(posHardwareSaleRecord('', order)) }\n}\n\n/** Where a sale's money went, picked by name: never a buyer detail. */\nfunction salePaidTo(order: Pick<PosHardwareOrder, 'source' | 'paidTo'>): PosHardwareSaleRecord['paidTo'] {\n const paidTo = order.paidTo\n if (posHardwareOrderSource(order) !== 'in_person' || paidTo?.account !== 'seller_store') {\n return { account: 'platform' }\n }\n return {\n account: 'seller_store',\n hostId: String(paidTo.hostId ?? ''),\n orgId: String(paidTo.orgId ?? ''),\n tenders: (Array.isArray(paidTo.tenders) ? paidTo.tenders : []).map(String).slice(0, 10),\n stripeAccountId: textOrNull(paidTo.stripeAccountId),\n }\n}\n\n/**\n * What an account erasure does to an order the person placed (AGL-4038): the\n * workspace keeps the order and every amount on it; the buyer comes off it —\n * who started it, the email, the name, the phone, the street and the\n * tracking, which names the parcel to a carrier who would say where it went.\n * The country, state and postal code stay, because sales tax is sourced by\n * them. Deterministic but for the stamp, and an order already erased no\n * longer answers to the person's uid, so a second run finds nothing.\n *\n * The buyer's NAME and ADDRESS stay on the platform's sale record, not on\n * the order: `buyerErasedAtMs` is what tells the record's next write to keep\n * them ({@link posHardwareSaleBuyer}, {@link posHardwareSaleSetOptions}).\n */\nexport function posHardwareBuyerErasedPatch(\n order: Pick<PosHardwareOrder, 'shipping' | 'attachment' | 'returnRequest'>,\n now: number,\n): Record<string, unknown> {\n // The whole map, read in the same transaction: a dotted-path update would\n // leave a field added to `shipping` later standing with the person in it.\n const shipping = order.shipping\n const attachment = order.attachment\n return {\n createdBy: null,\n contactEmail: null,\n shipping: {\n method: shipping?.method ?? 'standard',\n label: shipping?.label ?? posHardwareShippingLabel(shipping?.method),\n cents: shipping?.cents ?? 0,\n name: null,\n phone: null,\n address: null,\n taxRegion: posHardwareTaxRegion(order),\n },\n tracking: null,\n // An in-person order's attachment names the buyer too (AGL-4038): their\n // email, account, name and address come off it (the map is rebuilt with\n // none of them); the workspace and store it is in stay.\n ...(attachment\n ? {\n attachment: {\n state: attachment.state === 'attached' ? 'attached' : 'pending',\n email: null,\n uid: null,\n orgId: attachment.orgId ?? null,\n hostId: attachment.hostId ?? null,\n attachedBy: attachment.attachedBy ?? null,\n attachedAtMs: attachment.attachedAtMs ?? null,\n },\n }\n : {}),\n // Their return request keeps its outcome; their words and account go.\n ...(order.returnRequest\n ? { returnRequest: { ...order.returnRequest, reason: null, requestedBy: null } }\n : {}),\n buyerErasedAtMs: now,\n updatedAtMs: now,\n }\n}\n\n/** An order id: `hw_` and twenty hex characters. */\nexport const POS_HARDWARE_ORDER_ID = /^hw_[a-f0-9]{20}$/\n\n/** Dollars and cents for the card and the emails. */\nexport function formatPosHardwareCents(cents: number): string {\n const value = Number.isFinite(cents) ? cents : 0\n return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value / 100)\n}\n"],"names":["PLATFORM_BRAND_NAME","POS_HARDWARE_CURRENCY","POS_HARDWARE_SHIP_COUNTRIES","POS_HARDWARE_MAX_PER_LINE","POS_HARDWARE_MAX_UNITS","POS_HARDWARE_ENV","enabled","prices","markupBps","shipping","automaticTax","inPersonEnabled","sellerHostId","sellerOrgId","POS_HARDWARE_DEFAULT_MARKUP_BPS","POS_HARDWARE_SKUS","id","kind","stripeProductName","displayName","use","posHardwareSku","find","sku","POS_HARDWARE_SHIPPING_LABELS","standard","express","priority","SHIPPING_METHODS","Object","keys","isPosHardwareShippingMethod","value","includes","POS_HARDWARE_IN_PERSON_SHIPPING_LABEL","posHardwareShippingLabel","method","MAX_FIGURE_CENTS","MAX_MARKUP_BPS","isCents","min","Number","isSafeInteger","parseJsonObject","raw","text","String","trim","parsed","JSON","parse","Array","isArray","parsePosHardwareConfig","env","toLowerCase","markupText","test","costs","cost","anyReader","some","undefined","shippingRaw","flatMap","cents","length","CONFIG_ID","parsePosHardwareInPersonConfig","isPosHardwareSkuId","normalizePosHardwareSerial","toUpperCase","replace","slice","posHardwareUnitCents","costCents","Math","floor","posHardwareOffers","config","name","unitCents","pricePosHardwareCart","requested","ok","error","offers","Map","map","offer","quantities","entry","quantity","has","isInteger","set","get","units","lines","push","lineCents","subtotalCents","reduce","sum","line","POS_HARDWARE_METADATA_TYPE","encodePosHardwareLines","join","decodePosHardwareLines","encoded","part","split","skuId","quantityText","unitText","POS_HARDWARE_ORDER_STATUSES","isPosHardwareOrderStatus","POS_HARDWARE_STATUS_LABELS","paid","ordered","shipped","delivered","registered","canceled","refunded","POS_HARDWARE_STAFF_STATUS_LABELS","NEXT_STATUS","nextPosHardwareStatus","status","posHardwareRefundable","posHardwareOrderSource","order","source","POS_HARDWARE_RETURN_REASON_MAX","POS_HARDWARE_STATUS_STAMP","POS_HARDWARE_ANCHOR","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_SALES_COLLECTION","POS_HARDWARE_SALE_RETENTION_YEARS","posHardwareSaleExpiry","saleAtMs","paidAtMs","createdAtMs","isFinite","expires","Date","setUTCFullYear","getUTCFullYear","saleTaxLine","integerOrNull","round","numberOrNull","textOf","amountCents","taxabilityReason","taxRateId","taxableAmountCents","jurisdiction","rateState","percentage","stampOrNull","textOrNull","posHardwareTaxRegion","address","country","state","postalCode","kept","taxRegion","saleAddress","line1","city","line2","posHardwareBuyerAddress","posHardwareSaleBuyer","inPerson","attachment","buyerErasedAtMs","posHardwareSaleRecord","orderId","buyer","orgId","shippingMethod","shippingCents","taxCents","discountCents","totalCents","currency","shipTo","taxLines","stripeCheckoutSessionId","stripePaymentIntentId","stripeHardwareOrderId","refundId","refundedCents","livemode","updatedAtMs","orderedAtMs","shippedAtMs","deliveredAtMs","registeredAtMs","canceledAtMs","refundedAtMs","posHostId","posSale","hostId","posOrderId","paidTo","salePaidTo","storefrontTaxRowId","paymentLinkSessionId","expiresAt","posHardwareSaleSetOptions","mergeFields","account","tenders","stripeAccountId","posHardwareBuyerErasedPatch","now","createdBy","contactEmail","label","phone","tracking","email","uid","attachedBy","attachedAtMs","returnRequest","reason","requestedBy","POS_HARDWARE_ORDER_ID","formatPosHardwareCents","Intl","NumberFormat","style","format"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,SAASA,mBAAmB,QAAQ,wCAAuC;AAG3E,4DAA4D,GAC5D,OAAO,MAAMC,wBAAwB,MAAK;AAE1C;;;;;;CAMC,GACD,OAAO,MAAMC,8BAAiD;IAAC;CAAK,CAAA;AAEpE,uEAAuE,GACvE,OAAO,MAAMC,4BAA4B,GAAE;AAC3C,OAAO,MAAMC,yBAAyB,GAAE;AAExC,0EAA0E,GAC1E,OAAO,MAAMC,mBAAmB;IAC9B,uEAAuE,GACvEC,SAAS;IACT,mDAAmD,GACnDC,QAAQ;IACR;;;GAGC,GACDC,WAAW;IACX,6DAA6D,GAC7DC,UAAU;IACV,iEAAiE,GACjEC,cAAc;IACd;;;;GAIC,GACDC,iBAAiB;IACjB,qFAAqF,GACrFC,cAAc;IACd,wCAAwC,GACxCC,aAAa;AACf,EAAU;AAEV;;;;CAIC,GACD,OAAO,MAAMC,kCAAkC,KAAI;AA6BnD;;;;CAIC,GACD,OAAO,MAAMC,oBAA+C;IAC1D;QACEC,IAAI;QACJC,MAAM;QACNC,mBAAmB;QACnBC,aAAa;QACb,yEAAyE;QACzE,0EAA0E;QAC1E,qCAAqC;QACrCC,KAAK;IACP;IACA;QACEJ,IAAI;QACJC,MAAM;QACNC,mBAAmB;QACnBC,aAAa;QACbC,KAAK;IACP;IACA;QACEJ,IAAI;QACJC,MAAM;Q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AAA,SAAU2B,MAAM,mBAAI;YAC5ByL,KAAK,WAAEpN,4BAAAA,SAAUoN,KAAK,oBAAI1L,yBAAyB1B,4BAAAA,SAAU2B,MAAM;YACnE6B,KAAK,WAAExD,4BAAAA,SAAUwD,KAAK,oBAAI;YAC1Be,MAAM;YACN8I,OAAO;YACP3D,SAAS;YACTK,WAAWN,qBAAqB/B;QAClC;QACA4F,UAAU;OAIN/C,aACA;QACEA,YAAY;YACVX,OAAOW,WAAWX,KAAK,KAAK,aAAa,aAAa;YACtD2D,OAAO;YACPC,KAAK;YACL5C,KAAK,GAAEL,oBAAAA,WAAWK,KAAK,YAAhBL,oBAAoB;YAC3B6B,MAAM,GAAE7B,qBAAAA,WAAW6B,MAAM,YAAjB7B,qBAAqB;YAC7BkD,UAAU,GAAElD,yBAAAA,WAAWkD,UAAU,YAArBlD,yBAAyB;YACrCmD,YAAY,GAAEnD,2BAAAA,WAAWmD,YAAY,YAAvBnD,2BAA2B;QAC3C;IACF,IACA,CAAC,GAED7C,MAAMiG,aAAa,GACnB;QAAEA,eAAe,aAAKjG,MAAMiG,aAAa;YAAEC,QAAQ;YAAMC,aAAa;;IAAO,IAC7E,CAAC;QACLrD,iBAAiByC;QACjBtB,aAAasB;;AAEjB;AAEA,kDAAkD,GAClD,OAAO,MAAMa,wBAAwB,oBAAmB;AAExD,mDAAmD,GACnD,OAAO,SAASC,uBAAuBvK,KAAa;IAClD,MAAMjC,QAAQS,OAAOsG,QAAQ,CAAC9E,SAASA,QAAQ;IAC/C,OAAO,IAAIwK,KAAKC,YAAY,CAAC,SAAS;QAAEC,OAAO;QAAYhD,UAAU;IAAM,GAAGiD,MAAM,CAAC5M,QAAQ;AAC/F"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/pos-hardware.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\n/*==========================================\n * THE POS HARDWARE SHOP (AGL-4038), PHASE 1: THE MODEL.\n *\n * A merchant buys Stripe Terminal readers from the platform, the platform\n * places the order in Stripe's Terminal hardware shop and Stripe ships it\n * straight to the merchant. The platform is the seller of record, because the\n * register's card payments are destination charges on the PLATFORM account\n * and a reader must be registered there to take them.\n *\n * THE CATALOG IS CODE, THE PRICES ARE CONFIG. Which readers the register\n * works with is a fact about this codebase; what Stripe charges for them, the\n * markup on top and what shipping costs are business decisions that change\n * without a release. Every figure comes from the console's environment, read\n * by {@link parsePosHardwareConfig}, and a missing or malformed figure keeps\n * the shop HIDDEN: it is a gate only the platform can lift, so no workspace is\n * shown a control it cannot use.\n *\n * Everything here is pure, so the price math, the metadata a Checkout Session\n * carries and the status rules are specced without Firestore or Stripe.\n *=========================================*/\n\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport type { PosHardwareTermsAcceptance } from './pos-hardware-terms'\n\n/** The register's currency, and so the shop's: US dollars. */\nexport const POS_HARDWARE_CURRENCY = 'usd'\n\n/**\n * Where the shop ships. Stripe's Terminal hardware shop ships to many\n * countries, but the register sells in US dollars only and the readers a\n * merchant buys here are registered to a US Location, so the shop is US-only\n * (Stripe itself excludes the US Virgin Islands, military addresses and\n * P.O. boxes).\n */\nexport const POS_HARDWARE_SHIP_COUNTRIES: readonly string[] = ['US']\n\n/** The most of one item, and the most units, a single order may hold. */\nexport const POS_HARDWARE_MAX_PER_LINE = 10\nexport const POS_HARDWARE_MAX_UNITS = 20\n\n/**\n * The Stripe Tax code every hardware line carries (AGL-4038): \"General -\n * Tangible Goods\" (https://docs.stripe.com/tax/tax-codes), the physical good\n * a reader or an accessory is. Without it a line takes the account's default\n * code, which is software as a service, and would be taxed as software.\n * Stripe's list has no narrower code for a card reader.\n */\nexport const POS_HARDWARE_TAX_CODE = 'txcd_99999999'\n\n/** The env names the shop reads, named once for the reader and the docs. */\nexport const POS_HARDWARE_ENV = {\n /** `true` releases the shop. Absent or anything else keeps it hidden. */\n enabled: 'POS_HARDWARE_SHOP_ENABLED',\n /** JSON `{ \"<sku>\": <Stripe's price in cents> }`. */\n prices: 'POS_HARDWARE_PRICES',\n /**\n * The markup on Stripe's price, an integer in basis points (100 = 1%).\n * Absent, {@link POS_HARDWARE_DEFAULT_MARKUP_BPS} applies.\n */\n markupBps: 'POS_HARDWARE_MARKUP_BPS',\n /** JSON `{ \"standard\" | \"express\" | \"priority\": <cents> }`. */\n shipping: 'POS_HARDWARE_SHIPPING',\n /** `true` turns Stripe automatic tax on for hardware checkouts. */\n automaticTax: 'POS_HARDWARE_AUTOMATIC_TAX',\n /**\n * `true` lets the platform's own store sell hardware IN PERSON at its\n * register (AGL-4038): a reader handed over at an event, attached to the\n * buyer's workspace. Absent or anything else keeps it off.\n */\n inPersonEnabled: 'POS_HARDWARE_IN_PERSON_ENABLED',\n /** The site id of the platform's own store whose register sells hardware in person. */\n sellerHostId: 'POS_HARDWARE_SELLER_HOST_ID',\n /** The workspace that owns that store. */\n sellerOrgId: 'POS_HARDWARE_SELLER_ORG_ID',\n} as const\n\n/**\n * The markup when the deployment sets none: 3000 basis points on Stripe's\n * price. The business sets it; this is the one place the default lives, and\n * `POS_HARDWARE_MARKUP_BPS` overrides it.\n */\nexport const POS_HARDWARE_DEFAULT_MARKUP_BPS = 3000\n\nexport type PosHardwareSkuId =\n | 'stripe-reader-s710'\n | 'stripe-reader-s700'\n | 'stripe-reader-t600'\n | 'stripe-reader-m2'\n | 'bbpos-wisepos-e'\n | 'stripe-reader-s700-dock'\n | 'stripe-reader-hub'\n | 'stripe-reader-s700-case'\n | 'stripe-reader-s700-cable'\n | 'stripe-reader-charger'\n | 'stripe-reader-m2-dock'\n | 'stripe-reader-m2-mount'\n | 'bbpos-wisepos-e-dock'\n | 'bbpos-wisepos-e-power-cable'\n\nexport interface PosHardwareSku {\n id: PosHardwareSkuId\n kind: 'reader' | 'accessory'\n /**\n * What the supplier's hardware shop calls it, for the staff member ordering\n * it. Staff-only: the merchant never sees it.\n */\n stripeProductName: string\n /**\n * What the merchant sees, everywhere: shop, Hardware card, booth register,\n * emails and receipts. A plain name with the model in brackets, never the\n * maker's name; the record keeps the exact model in `sku` for support.\n */\n displayName: string\n /** One line on what it is for. */\n use: string\n}\n\n/**\n * Every item the shop can sell. An item is offered only once its Stripe\n * price is configured, so one Stripe stops selling disappears by deleting its\n * price, not by a release.\n */\nexport const POS_HARDWARE_SKUS: readonly PosHardwareSku[] = [\n {\n id: 'stripe-reader-s710',\n kind: 'reader',\n stripeProductName: 'Stripe Reader S710',\n // Plain names with the model in brackets, no maker's name (AGL-4038).\n // \"4G-capable\", never \"with 4G\": 4G is a separate per-store monthly\n // service, turned on where it is offered, and the reader alone does not\n // bring a connection.\n displayName: 'Touchscreen reader, 4G-capable (S710)',\n use: 'Handheld for events and parking lots, on Wi-Fi. 4G is a separate monthly service, where offered',\n },\n {\n id: 'stripe-reader-s700',\n kind: 'reader',\n stripeProductName: 'Stripe Reader S700',\n displayName: 'Touchscreen reader (S700)',\n use: 'Handheld or countertop reader on Wi-Fi',\n },\n {\n id: 'stripe-reader-t600',\n kind: 'reader',\n stripeProductName: 'Stripe Reader T600',\n displayName: 'Countertop reader (T600)',\n use: 'Countertop reader on Wi-Fi, or on Ethernet with the hub',\n },\n {\n id: 'bbpos-wisepos-e',\n kind: 'reader',\n stripeProductName: 'BBPOS WisePOS E',\n displayName: 'Countertop reader (WisePOS E)',\n use: 'Countertop reader on Wi-Fi',\n },\n {\n id: 'stripe-reader-m2',\n kind: 'reader',\n stripeProductName: 'Stripe Reader M2',\n displayName: 'Pocket reader (M2)',\n use: `Pairs with the ${PLATFORM_BRAND_NAME} POS app on your phone or tablet by Bluetooth`,\n },\n {\n id: 'stripe-reader-s700-dock',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader S700/S710 Dock',\n displayName: 'Charging dock for the S700 and S710',\n use: 'Keeps the reader charged at the counter and adds an Ethernet port',\n },\n {\n id: 'stripe-reader-hub',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader Hub',\n displayName: 'Hub for the S700, S710 and T600',\n use: 'Connects the reader to Ethernet and power',\n },\n {\n id: 'stripe-reader-s700-case',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader S700/S710 Case',\n displayName: 'Case for the S700 and S710',\n use: 'Protects a handheld reader on the move',\n },\n {\n id: 'stripe-reader-s700-cable',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader S700/S710 Cable',\n displayName: 'Cable for the S700 and S710',\n use: 'A spare cable for the reader',\n },\n {\n id: 'stripe-reader-charger',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader Charger',\n displayName: 'Charger for card readers',\n use: 'A spare wall charger',\n },\n {\n id: 'stripe-reader-m2-dock',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader M2 Dock',\n displayName: 'Charging dock for the M2',\n use: 'Keeps the M2 charged at the counter',\n },\n {\n id: 'stripe-reader-m2-mount',\n kind: 'accessory',\n stripeProductName: 'Stripe Reader M2 Mount',\n displayName: 'Mount for the M2',\n use: 'Holds the M2 in place at the counter',\n },\n {\n id: 'bbpos-wisepos-e-dock',\n kind: 'accessory',\n stripeProductName: 'BBPOS WisePOS E Dock',\n displayName: 'Charging dock for the WisePOS E',\n use: 'Keeps the reader charged at the counter and adds an Ethernet port',\n },\n {\n id: 'bbpos-wisepos-e-power-cable',\n kind: 'accessory',\n stripeProductName: 'BBPOS WisePOS E 5ft Power Cable',\n displayName: '5 ft power cable for the WisePOS E',\n use: 'A spare power cable for the reader',\n },\n]\n\nexport function posHardwareSku(id: string): PosHardwareSku | null {\n return POS_HARDWARE_SKUS.find((sku) => sku.id === id) ?? null\n}\n\nexport type PosHardwareShippingMethod = 'standard' | 'express' | 'priority'\n\nexport const POS_HARDWARE_SHIPPING_LABELS: Record<PosHardwareShippingMethod, string> = {\n standard: 'Standard shipping',\n express: 'Express shipping',\n priority: 'Priority shipping',\n}\n\nconst SHIPPING_METHODS = Object.keys(POS_HARDWARE_SHIPPING_LABELS) as PosHardwareShippingMethod[]\n\nexport function isPosHardwareShippingMethod(value: unknown): value is PosHardwareShippingMethod {\n return typeof value === 'string' && (SHIPPING_METHODS as string[]).includes(value)\n}\n\n/**\n * How an order reached the buyer: one of the shop's shipping speeds, or\n * `in_person` — handed over at the platform's own register (AGL-4038), with\n * no parcel, address or carrier. Never offered at checkout.\n */\nexport type PosHardwareOrderShippingMethod = PosHardwareShippingMethod | 'in_person'\n\nexport const POS_HARDWARE_IN_PERSON_SHIPPING_LABEL = 'Handed over in person'\n\n/** The label of any order's method, the in-person one included. */\nexport function posHardwareShippingLabel(method: PosHardwareOrderShippingMethod | null | undefined): string {\n if (method === 'in_person') return POS_HARDWARE_IN_PERSON_SHIPPING_LABEL\n return POS_HARDWARE_SHIPPING_LABELS[isPosHardwareShippingMethod(method) ? method : 'standard']\n}\n\n/** The shop's configuration, once every figure it needs is present and sane. */\nexport interface PosHardwareConfig {\n /** Stripe's price for each configured item, in cents. */\n costs: Partial<Record<PosHardwareSkuId, number>>\n markupBps: number\n shipping: Array<{ method: PosHardwareShippingMethod; cents: number }>\n automaticTax: boolean\n /**\n * The price each item is listed at in the platform's own store, in cents\n * (AGL-4038), where the server read one: the shop then charges that, so\n * the Hardware card and the store's product page quote one price\n * ({@link posHardwareOfferUnitCents}). Never read from the environment.\n */\n listedCents?: Partial<Record<PosHardwareSkuId, number>>\n}\n\n/** The highest single figure the parser accepts, in cents: $10,000. */\nconst MAX_FIGURE_CENTS = 1_000_000\n/** The highest markup the parser accepts: 1000%. */\nconst MAX_MARKUP_BPS = 100_000\n\nconst isCents = (value: unknown, min: number): value is number =>\n typeof value === 'number' &&\n Number.isSafeInteger(value) &&\n value >= min &&\n value <= MAX_FIGURE_CENTS\n\nfunction parseJsonObject(raw: string | undefined): Record<string, unknown> | null {\n const text = String(raw ?? '').trim()\n if (!text) return null\n try {\n const parsed = JSON.parse(text) as unknown\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null\n } catch {\n return null\n }\n}\n\n/**\n * The shop's configuration from the environment, or `null` while the shop is\n * hidden: not released, no reader priced, a malformed markup, or no shipping\n * figure. An ABSENT markup is the default\n * ({@link POS_HARDWARE_DEFAULT_MARKUP_BPS}), so a deployment can never sell\n * at cost by forgetting a variable; `0` is a valid, explicit choice to sell\n * at Stripe's price. A markup that is set but unreadable hides the shop\n * rather than guessing.\n *\n * Unknown item ids and malformed figures are dropped one by one rather than\n * failing the whole shop, so a typo in one price hides that one item.\n */\nexport function parsePosHardwareConfig(\n env: Record<string, string | undefined>,\n): PosHardwareConfig | null {\n if (String(env[POS_HARDWARE_ENV.enabled] ?? '').trim().toLowerCase() !== 'true') return null\n\n const markupText = String(env[POS_HARDWARE_ENV.markupBps] ?? '').trim()\n if (markupText && !/^\\d+$/.test(markupText)) return null\n const markupBps = markupText ? Number(markupText) : POS_HARDWARE_DEFAULT_MARKUP_BPS\n if (!Number.isSafeInteger(markupBps) || markupBps > MAX_MARKUP_BPS) return null\n\n const prices = parseJsonObject(env[POS_HARDWARE_ENV.prices])\n if (!prices) return null\n const costs: Partial<Record<PosHardwareSkuId, number>> = {}\n for (const sku of POS_HARDWARE_SKUS) {\n const cost = prices[sku.id]\n if (isCents(cost, 1)) costs[sku.id] = cost\n }\n const anyReader = POS_HARDWARE_SKUS.some((sku) => sku.kind === 'reader' && costs[sku.id] !== undefined)\n if (!anyReader) return null\n\n const shippingRaw = parseJsonObject(env[POS_HARDWARE_ENV.shipping])\n if (!shippingRaw) return null\n const shipping = SHIPPING_METHODS.flatMap((method) => {\n const cents = shippingRaw[method]\n return isCents(cents, 0) ? [{ method, cents }] : []\n })\n if (!shipping.length) return null\n\n return {\n costs,\n markupBps,\n shipping,\n automaticTax:\n String(env[POS_HARDWARE_ENV.automaticTax] ?? '').trim().toLowerCase() === 'true',\n }\n}\n\n/*==========================================\n * SELLING HARDWARE IN PERSON (AGL-4038).\n *\n * The platform also sells readers face to face, at an event, from its OWN\n * store's register: the same products a store sells, rung up like any other\n * sale, priced and taxed by that store, paid into that store's account. The\n * one difference is what follows the sale — a hardware order for the buyer's\n * workspace, so the reader shows up there and can be set up, returned or\n * refunded like one bought online.\n *\n * Which store that is, is configuration: the site and its workspace, named in\n * the environment beside the shop's other figures. A product on that store\n * names the hardware item it is ({@link isPosHardwareSkuId} on the product's\n * `hardwareSku`), and no other store's product ever does, whatever it says.\n *=========================================*/\n\n/** The platform's own store, once the in-person sale is turned on and named. */\nexport interface PosHardwareInPersonConfig {\n sellerHostId: string\n sellerOrgId: string\n}\n\nconst CONFIG_ID = /^[A-Za-z0-9_-]{1,128}$/\n\n/**\n * The in-person sale's configuration from the environment, or `null` while\n * it is off: not turned on, or the store or its workspace not named, or\n * named with something that cannot be an id. It needs nothing of the online\n * shop's: the store's own products carry the prices.\n */\nexport function parsePosHardwareInPersonConfig(\n env: Record<string, string | undefined>,\n): PosHardwareInPersonConfig | null {\n if (String(env[POS_HARDWARE_ENV.inPersonEnabled] ?? '').trim().toLowerCase() !== 'true') return null\n const sellerHostId = String(env[POS_HARDWARE_ENV.sellerHostId] ?? '').trim()\n const sellerOrgId = String(env[POS_HARDWARE_ENV.sellerOrgId] ?? '').trim()\n if (!CONFIG_ID.test(sellerHostId) || !CONFIG_ID.test(sellerOrgId)) return null\n return { sellerHostId, sellerOrgId }\n}\n\nexport function isPosHardwareSkuId(value: unknown): value is PosHardwareSkuId {\n return typeof value === 'string' && posHardwareSku(value) !== null\n}\n\n/**\n * A reader's serial number as staff scanned or typed it, in the one form\n * every comparison uses: upper case, letters, digits and dashes only, at\n * most 64 characters. Empty when nothing usable was given.\n */\nexport function normalizePosHardwareSerial(value: unknown): string {\n return String(value ?? '')\n .toUpperCase()\n .replace(/[^A-Z0-9-]/g, '')\n .slice(0, 64)\n}\n\n/**\n * What the merchant pays for one item: Stripe's price plus the markup,\n * rounded half up to the cent, in integer math throughout.\n *\n * `cost + round(cost × bps / 10 000)`. The markup is basis points ON COST, so\n * a 50% markup is `5000` and a price at which half of it is profit (a 50%\n * margin) is `10000`. Whichever the business means, it is this one number.\n */\nexport function posHardwareUnitCents(costCents: number, markupBps: number): number {\n if (!Number.isSafeInteger(costCents) || costCents <= 0) return 0\n if (!Number.isSafeInteger(markupBps) || markupBps < 0) return costCents\n return costCents + Math.floor((costCents * markupBps + 5_000) / 10_000)\n}\n\n/**\n * ONE PRICE FOR ONE ITEM (AGL-4038). The platform's own store lists the same\n * readers on its product pages, at prices set on the products, and the\n * Hardware card prices them from the environment, Stripe's cost plus the\n * markup. Two sources would quote two prices for one reader. So the item's\n * listed price is the price wherever it is listed, and the Hardware card\n * charges exactly what the product page shows. It never sells below cost: a\n * listed price under Stripe's cost is a mistake on the product, and the card\n * keeps the marked-up price for it instead. An item the store does not list\n * is priced from the environment as before.\n */\nexport function posHardwareOfferUnitCents(\n config: Pick<PosHardwareConfig, 'costs' | 'markupBps' | 'listedCents'>,\n sku: PosHardwareSkuId,\n): number {\n const cost = config.costs[sku]\n if (cost === undefined) return 0\n const listed = config.listedCents?.[sku]\n if (typeof listed === 'number' && Number.isSafeInteger(listed) && listed >= cost) return listed\n return posHardwareUnitCents(cost, config.markupBps)\n}\n\n/** An item as the shop offers it: the merchant's price, never Stripe's. */\nexport interface PosHardwareOffer {\n sku: PosHardwareSkuId\n kind: PosHardwareSku['kind']\n name: string\n use: string\n unitCents: number\n}\n\n/** The items on offer, readers first, in catalog order. */\nexport function posHardwareOffers(config: PosHardwareConfig): PosHardwareOffer[] {\n return POS_HARDWARE_SKUS.flatMap((sku) => {\n const cost = config.costs[sku.id]\n if (cost === undefined) return []\n return [\n {\n sku: sku.id,\n kind: sku.kind,\n name: sku.displayName,\n use: sku.use,\n unitCents: posHardwareOfferUnitCents(config, sku.id),\n },\n ]\n })\n}\n\nexport interface PosHardwareLine {\n sku: PosHardwareSkuId\n name: string\n quantity: number\n unitCents: number\n lineCents: number\n}\n\nexport type PosHardwareCartResult =\n | { ok: true; lines: PosHardwareLine[]; subtotalCents: number }\n | { ok: false; error: string }\n\n/**\n * A merchant's basket priced on the SERVER: every item must be on offer, each\n * quantity a whole number from 1 to {@link POS_HARDWARE_MAX_PER_LINE}, and\n * the order at most {@link POS_HARDWARE_MAX_UNITS} units. A repeated item is\n * folded into one line. Prices come from the config, never the request.\n */\nexport function pricePosHardwareCart(\n config: PosHardwareConfig,\n requested: unknown,\n): PosHardwareCartResult {\n if (!Array.isArray(requested) || requested.length === 0) {\n return { ok: false, error: 'Choose at least one item.' }\n }\n const offers = new Map(posHardwareOffers(config).map((offer) => [offer.sku as string, offer]))\n const quantities = new Map<string, number>()\n for (const entry of requested) {\n const sku = String((entry as { sku?: unknown })?.sku ?? '')\n const quantity = Number((entry as { quantity?: unknown })?.quantity)\n if (!offers.has(sku)) return { ok: false, error: 'That item is not available.' }\n if (!Number.isInteger(quantity) || quantity < 1) {\n return { ok: false, error: 'Each quantity must be a whole number of at least 1.' }\n }\n quantities.set(sku, (quantities.get(sku) ?? 0) + quantity)\n }\n let units = 0\n const lines: PosHardwareLine[] = []\n for (const [sku, quantity] of quantities) {\n if (quantity > POS_HARDWARE_MAX_PER_LINE) {\n return { ok: false, error: `Order at most ${POS_HARDWARE_MAX_PER_LINE} of each item.` }\n }\n units += quantity\n const offer = offers.get(sku) as PosHardwareOffer\n lines.push({\n sku: offer.sku,\n name: offer.name,\n quantity,\n unitCents: offer.unitCents,\n lineCents: offer.unitCents * quantity,\n })\n }\n if (units > POS_HARDWARE_MAX_UNITS) {\n return { ok: false, error: `One order holds at most ${POS_HARDWARE_MAX_UNITS} items.` }\n }\n // Accessories alone are allowed: a merchant may want a second dock.\n return { ok: true, lines, subtotalCents: lines.reduce((sum, line) => sum + line.lineCents, 0) }\n}\n\n/*==========================================\n * THE CHECKOUT SESSION'S METADATA.\n *\n * The webhook builds the order from the session Stripe hands back, so the\n * lines ride in its metadata in a compact form (`sku*qty*unit;…`, inside\n * Stripe's 500-character value limit even with every item in the catalog in\n * one basket at the highest price the config accepts, which a spec holds),\n * and the webhook re-reads every one against the catalog rather than trusting\n * a name from the wire.\n *=========================================*/\n\nexport const POS_HARDWARE_METADATA_TYPE = 'pos-hardware-order'\n\nexport function encodePosHardwareLines(lines: readonly PosHardwareLine[]): string {\n return lines.map((line) => `${line.sku}*${line.quantity}*${line.unitCents}`).join(';')\n}\n\nexport function decodePosHardwareLines(encoded: unknown): PosHardwareLine[] | null {\n const text = String(encoded ?? '').trim()\n if (!text) return null\n const lines: PosHardwareLine[] = []\n for (const part of text.split(';')) {\n const [skuId, quantityText, unitText] = part.split('*')\n const sku = posHardwareSku(String(skuId ?? ''))\n const quantity = Number(quantityText)\n const unitCents = Number(unitText)\n if (!sku) return null\n if (!Number.isInteger(quantity) || quantity < 1 || quantity > POS_HARDWARE_MAX_PER_LINE) return null\n if (!Number.isSafeInteger(unitCents) || unitCents < 1) return null\n lines.push({ sku: sku.id, name: sku.displayName, quantity, unitCents, lineCents: quantity * unitCents })\n }\n return lines\n}\n\n/*==========================================\n * THE ORDER AND ITS STATUSES.\n *=========================================*/\n\nexport type PosHardwareOrderStatus =\n | 'paid'\n | 'ordered'\n | 'received'\n | 'shipped'\n | 'delivered'\n | 'registered'\n | 'canceled'\n | 'refunded'\n\nexport const POS_HARDWARE_ORDER_STATUSES: readonly PosHardwareOrderStatus[] = [\n 'paid',\n 'ordered',\n 'received',\n 'shipped',\n 'delivered',\n 'registered',\n 'canceled',\n 'refunded',\n]\n\nexport function isPosHardwareOrderStatus(value: unknown): value is PosHardwareOrderStatus {\n return typeof value === 'string' && (POS_HARDWARE_ORDER_STATUSES as readonly string[]).includes(value)\n}\n\n/** What the merchant reads on the Hardware card. */\nexport const POS_HARDWARE_STATUS_LABELS: Record<PosHardwareOrderStatus, string> = {\n paid: 'Order received',\n ordered: 'Being prepared',\n received: 'Being prepared',\n shipped: 'Shipped',\n delivered: 'Delivered',\n registered: 'Set up',\n canceled: 'Canceled',\n refunded: 'Refunded',\n}\n\n/** What staff read on the orders page: where the order is in fulfillment. */\nexport const POS_HARDWARE_STAFF_STATUS_LABELS: Record<PosHardwareOrderStatus, string> = {\n paid: 'Paid',\n ordered: 'Ordered from Stripe',\n received: 'Received',\n shipped: 'Shipped',\n delivered: 'Delivered',\n registered: 'Registered',\n canceled: 'Canceled',\n refunded: 'Refunded',\n}\n\n/**\n * The forward steps staff may move an order through (AGL-4038): ordered from\n * the supplier, received at the platform, set up, shipped with tracking,\n * delivered, and set up on the buyer's store. Setting it up is not a status\n * of its own: it is each reader's serial number recorded and, where the\n * buyer's store can take it, the reader registered to that store\n * ({@link posHardwareReadyToShip}), which shipping waits for. Canceling and\n * refunding are separate acts with their own rule\n * ({@link posHardwareRefundable}), because each returns money.\n */\nconst NEXT_STATUS: Partial<Record<PosHardwareOrderStatus, PosHardwareOrderStatus>> = {\n paid: 'ordered',\n ordered: 'received',\n received: 'shipped',\n shipped: 'delivered',\n delivered: 'registered',\n}\n\nexport function nextPosHardwareStatus(\n status: PosHardwareOrderStatus,\n): PosHardwareOrderStatus | null {\n return NEXT_STATUS[status] ?? null\n}\n\n/**\n * Whether the order may still be canceled or refunded in full: only before it\n * ships. Once a parcel is on its way the money comes back through a return of\n * the hardware, which is a separate process this phase does not automate.\n */\nexport function posHardwareRefundable(status: PosHardwareOrderStatus): boolean {\n return status === 'paid' || status === 'ordered' || status === 'received'\n}\n\n/** The statuses of an order that has not shipped yet, which a closure cancels and refunds. */\nexport const POS_HARDWARE_UNSHIPPED_STATUSES: readonly PosHardwareOrderStatus[] = ['paid', 'ordered', 'received']\n\nexport interface PosHardwareAddress {\n line1: string\n line2?: string\n city: string\n state?: string\n postalCode: string\n country: string\n}\n\n/**\n * What sales tax is sourced by: where the order shipped, without the street\n * or the person. An erasure keeps this much of the address (see\n * {@link posHardwareBuyerErasedPatch}) and the retained sale record holds\n * nothing finer ({@link PosHardwareSaleRecord}).\n */\nexport interface PosHardwareTaxRegion {\n country: string\n state: string | null\n postalCode: string | null\n}\n\nexport interface PosHardwareTracking {\n carrier: string\n number: string\n url: string | null\n}\n\n/**\n * Why an order was canceled and refunded: by staff on the Hardware orders\n * page, or because the workspace that bought it was deleted or the account\n * that placed it was closed before it shipped (AGL-4038 closure).\n */\nexport type PosHardwareCancelReason = 'staff' | 'workspace-closed' | 'account-closed'\n\n/**\n * One entry of the tax Stripe computed on a hardware checkout, as the\n * storefront's tax rows store it (`StorefrontTaxLine`): the amount, the base\n * it was applied to (`taxable_amount`, null when Stripe did not state one)\n * and the rate, for the working papers of the platform's own return.\n */\nexport interface PosHardwareTaxLine {\n amountCents: number\n taxabilityReason: string | null\n taxRateId: string | null\n taxableAmountCents: number | null\n jurisdiction: string | null\n rateState: string | null\n percentage: number | null\n}\n\n/**\n * Where an order was sold (AGL-4038): the Hardware card's checkout\n * (`online`), the platform's own register, in person (`in_person`), or the\n * platform's own online store, its product pages and cart (`storefront`).\n * Absent on every order sold before the in-person sale existed, which were\n * all from the Hardware card; read it through {@link posHardwareOrderSource}.\n */\nexport type PosHardwareOrderSource = 'online' | 'in_person' | 'storefront'\n\nexport function posHardwareOrderSource(\n order: { source?: unknown } | null | undefined,\n): PosHardwareOrderSource {\n return order?.source === 'in_person' ? 'in_person' : order?.source === 'storefront' ? 'storefront' : 'online'\n}\n\n/**\n * Whether an order was sold by the platform's own store (AGL-4038), at its\n * register or online: paid into that store's own account, with the store's\n * order behind it (`posSale`), and whose buyer may still be to attach. It is\n * attached, refunded and counted on the tax return the same way either way.\n */\nexport function isPosHardwareSellerStoreSale(order: { source?: unknown } | null | undefined): boolean {\n const source = posHardwareOrderSource(order)\n return source === 'in_person' || source === 'storefront'\n}\n\n/** Whether an order is shipped to its buyer, rather than handed over at a register. */\nexport function posHardwareShips(order: { source?: unknown } | null | undefined): boolean {\n return posHardwareOrderSource(order) !== 'in_person'\n}\n\n/**\n * The store order an order sold by the platform's own store came from: the\n * store, the order and its number, and how it was rung. For a `storefront`\n * order it is the store's online order, with no register, and\n * `paymentLinkSessionId` is the Checkout Session it was paid through.\n */\nexport interface PosHardwareRegisterSale {\n hostId: string\n orgId: string\n orderId: string\n /** The register order's number, as its receipt shows it. */\n number: number | null\n registerId: string | null\n /** A customer built it at the self-service kiosk. */\n kiosk: boolean\n /** It was rung while the register was offline, and synced later. */\n offline: boolean\n /**\n * The Checkout Session of the register's payment link, when the sale was\n * paid by one: the storefront's tax record of the sale is filed under it.\n */\n paymentLinkSessionId: string | null\n}\n\n/**\n * Where an in-person sale's money went, for the books to reconcile it\n * against: the selling store's own takings — cash in its drawer, cards into\n * its connected Stripe account, exactly as every sale on its register. The\n * hardware order records it because the platform's online sales land in the\n * platform's own account instead, and the two must never be summed as one.\n */\nexport interface PosHardwarePaidTo {\n account: 'seller_store'\n hostId: string\n orgId: string\n /** The register sale's tenders, as its payments name them (`cash`, `card_present`, …). */\n tenders: string[]\n /** The store's connected Stripe account, when its owner has one. */\n stripeAccountId: string | null\n}\n\n/**\n * Who an in-person order belongs to (AGL-4038). `attached` once it is in the\n * buyer's workspace; `pending` while staff have still to say whose it is —\n * a kiosk or offline sale, a buyer with no account yet (`email`, invited to\n * sign up), or one with an account and no workspace yet (`uid`). A pending\n * order is kept in the selling workspace's own `hardwareOrders`, on its \"To\n * attach\" list, and moves to the buyer's workspace when it is attached.\n */\nexport interface PosHardwareAttachment {\n state: 'attached' | 'pending'\n /** The buyer's address: the account's, or the one typed for a buyer with no account. */\n email: string | null\n uid: string | null\n /** The buyer's workspace, once there is one. */\n orgId: string | null\n /** The store the buyer chose for the reader, when they chose one at the sale. */\n hostId: string | null\n /** The register user who attached it; null for the buyer's own sign-up. */\n attachedBy: string | null\n attachedAtMs: number | null\n /** When the sign-up invitation went to `email`, for a buyer with no account. */\n invitedAtMs?: number | null\n /**\n * The buyer's name, for the platform's reseller records (AGL-4038): the\n * account's name, or the one typed at the sale. An online order keeps it\n * in `shipping.name` instead. Taken off with the buyer's account.\n */\n name?: string | null\n /**\n * The buyer's business address, for the same records: typed at the sale,\n * or the address of the store the readers are set up on. Never the tax\n * region, which stays the selling store's. Taken off with the account.\n */\n address?: PosHardwareAddress | null\n}\n\n/**\n * One reader of an in-person order, by its serial number when staff scanned\n * it at the sale (AGL-4038). The order moves to Set up when every reader on\n * it is registered to the buyer's store.\n */\nexport interface PosHardwareUnit {\n sku: PosHardwareSkuId\n /** Normalized ({@link normalizePosHardwareSerial}); null when none was taken. */\n serialNumber: string | null\n /** The Stripe Terminal reader it was registered as, and on which store. */\n readerId: string | null\n hostId: string | null\n registeredAtMs: number | null\n}\n\n/**\n * One refund of an in-person order (AGL-4038), once by its key: a return at\n * the selling store's register (`register:{returnId}`), or a refund from the\n * staff Hardware orders page (`staff:{n}`), both paid back from the selling\n * store's own takings the way the sale was paid.\n */\nexport interface PosHardwareRefund {\n key: string\n via: 'register' | 'staff'\n cents: number\n /** Hardware items it took back; 0 when the refund named none. */\n quantity: number\n atMs: number\n stripeRefundId: string | null\n}\n\n/**\n * The buyer's request to return an in-person order, from their own\n * purchase history (AGL-4038). Staff refund it (`refunded`) or decline it.\n * Returns follow Stripe's hardware terms.\n */\nexport interface PosHardwareReturnRequest {\n state: 'requested' | 'declined' | 'refunded'\n /** The buyer's words; taken off with the buyer when their account is erased. */\n reason: string | null\n requestedBy: string | null\n requestedAtMs: number\n decidedBy: string | null\n decidedAtMs: number | null\n /** What staff told the buyer when declining. */\n note: string | null\n}\n\nexport const POS_HARDWARE_RETURN_REASON_MAX = 500\n\n/** `orgs/{orgId}/hardwareOrders/{orderId}`, written only by the server. */\nexport interface PosHardwareOrder {\n orgId: string\n /**\n * The site whose POS settings the order was placed from; for an in-person\n * order, the buyer's store once known, else the selling store.\n */\n hostId: string\n /** The member who started the checkout; `null` once their account is erased. */\n createdBy: string | null\n /** Where the order emails go: the address entered at checkout. */\n contactEmail: string | null\n lines: PosHardwareLine[]\n subtotalCents: number\n shipping: {\n method: PosHardwareOrderShippingMethod\n label: string\n cents: number\n name: string | null\n phone: string | null\n address: PosHardwareAddress | null\n /**\n * Set when the buyer's account is erased, in place of `address`: the part\n * of it sales tax is sourced by.\n */\n taxRegion?: PosHardwareTaxRegion | null\n }\n taxCents: number\n /**\n * The register sale's discounts that fell on this order's lines, for an\n * in-person order (AGL-4038): `totalCents` is the lines less this, plus\n * the tax. Absent, and so nothing, on every online order.\n */\n discountCents?: number\n totalCents: number\n currency: string\n /** Whether Stripe Tax computed the tax on the checkout. Absent on orders before it was recorded. */\n automaticTax?: boolean\n /** Stripe's tax breakdown for the checkout, when Stripe Tax computed it. */\n taxLines?: PosHardwareTaxLine[]\n /** The Hardware card's checkout; null for an in-person sale, which had none. */\n stripeCheckoutSessionId: string | null\n stripePaymentIntentId: string | null\n /** Stripe's hardware order id, recorded by staff (phase 2 sets it itself). */\n stripeHardwareOrderId: string | null\n tracking: PosHardwareTracking | null\n status: PosHardwareOrderStatus\n livemode: boolean\n createdAtMs: number\n updatedAtMs: number\n paidAtMs: number\n orderedAtMs?: number\n /** When the platform received it from the supplier (AGL-4038). */\n receivedAtMs?: number\n shippedAtMs?: number\n deliveredAtMs?: number\n registeredAtMs?: number\n canceledAtMs?: number\n refundedAtMs?: number\n refundId?: string | null\n /** The cents Stripe reported refunding. */\n refundedCents?: number\n /** Why it was canceled, when it was. */\n cancelReason?: PosHardwareCancelReason\n /** When the buyer's account was erased and their details taken off the order. */\n buyerErasedAtMs?: number\n /** Where it was sold; absent reads as online ({@link posHardwareOrderSource}). */\n source?: PosHardwareOrderSource\n /** The register sale an in-person order came from. */\n posSale?: PosHardwareRegisterSale\n /** Where an in-person sale's money went. */\n paidTo?: PosHardwarePaidTo\n /** Whose an in-person order is, or that staff have still to say. */\n attachment?: PosHardwareAttachment\n /**\n * How the buyer agreed to the terms of sale (AGL-4038): for an in-person\n * order, copied from the register sale, or the receipt-and-sign notice\n * when they did not accept electronically; for an order paid online,\n * ticked at checkout with business use confirmed (`online`).\n */\n termsAcceptance?: PosHardwareTermsAcceptance\n /** Each reader of an in-person order, with its serial when one was taken. */\n units?: PosHardwareUnit[]\n /** The units' serial numbers, for finding the order when a reader is registered. */\n serialNumbers?: string[]\n /** An in-person order's refunds, each once by its key. */\n refunds?: PosHardwareRefund[]\n /** The buyer's request to return it, and what staff decided. */\n returnRequest?: PosHardwareReturnRequest\n /**\n * The emails that are sent once (AGL-4038), by key: `canceled`, or\n * `refunded:{refund key}`. Claimed before the send, so the staff page and a\n * closure never both send one.\n */\n buyerEmails?: Record<string, { state: 'sending' | 'sent' | 'skipped' | 'failed'; atMs: number }>\n}\n\n/** The timestamp field each status stamps when it is reached. */\nexport const POS_HARDWARE_STATUS_STAMP: Record<PosHardwareOrderStatus, keyof PosHardwareOrder> = {\n paid: 'paidAtMs',\n ordered: 'orderedAtMs',\n received: 'receivedAtMs',\n shipped: 'shippedAtMs',\n delivered: 'deliveredAtMs',\n registered: 'registeredAtMs',\n canceled: 'canceledAtMs',\n refunded: 'refundedAtMs',\n}\n\n/** The Hardware card's anchor: Checkout returns to it and the emails link at it. */\nexport const POS_HARDWARE_ANCHOR = 'pos-hardware'\n\n/**\n * What the point of sale adds to a reader (AGL-4038), for the prompt a\n * workspace without it sees: anyone may buy readers, and a reader takes\n * payments at the register, which comes with the point of sale.\n */\nexport const POS_PLAN_ADDS =\n 'registers that ring up sales, card payments on your readers, cash with change due, receipts and shift reports'\n\n/**\n * The prompt to add the point of sale (AGL-4038), never a refusal: on the\n * Hardware card before anything has arrived, naming the orders that have\n * arrived once one has, and at the register.\n */\nexport function posPlanPrompt(where: { arrived?: readonly string[]; atRegister?: boolean } = {}): string {\n const arrived = where.arrived ?? []\n if (where.atRegister) {\n return `A card reader takes payments at the register, which comes with the point of sale: ${POS_PLAN_ADDS}. Add it to start selling.`\n }\n if (arrived.length) {\n const one = arrived.length === 1\n return `${arrived.join(', ')} ${one ? 'has' : 'have'} arrived. To take payments with ${one ? 'it' : 'them'}, add the point of sale: ${POS_PLAN_ADDS}.`\n }\n return `You can buy readers on any plan. To take payments with them, add the point of sale: ${POS_PLAN_ADDS}.`\n}\n\n/** The collection under `orgs/{orgId}`, named once. */\nexport const POS_HARDWARE_ORDERS_COLLECTION = 'hardwareOrders'\n\n/*==========================================\n * THE SALE RECORD THE PLATFORM KEEPS (AGL-4038).\n *\n * A hardware order is the PLATFORM's own sale: the platform is the seller of\n * record and owes the sales tax on it. So beside every order the server keeps\n * `posHardwareSales/{orderId}`, a TOP-LEVEL record of what tax and accounting\n * need — the lines, the amounts, the tax, Stripe's ids, the status dates and\n * the region it shipped to — and, of the person who bought it, only their\n * NAME and ADDRESS ({@link PosHardwareSaleBuyer}).\n *\n * The name and address are the reseller's records Stripe's Terminal Reseller\n * Terms §10 ask for: the identity and address of each buyer, open to Stripe's\n * inspection. §10 states no period, so they are kept for the record's own\n * seven years. They SURVIVE the buyer's account erasure, which still takes\n * the email, phone, tracking and the name and street off the ORDER: every\n * write sets the record through {@link posHardwareSaleSetOptions}, which\n * leaves the stored name and address alone when the order no longer has\n * them because its buyer was erased.\n *\n * It is the `platformRevenue` / `storefrontTaxCollected` shape on purpose\n * (AGL-1811, AGL-1904): keyed to the workspace by FIELD, outside\n * `orgs/{orgId}`, so the workspace erasure's `recursiveDelete(orgs/{orgId})`\n * cannot see it, and never in any org-keyed sweep. GDPR Art. 17(3)(b) exempts\n * records kept to comply with a legal obligation. The order under the\n * workspace, with the buyer's name, street, phone, email and tracking, is\n * erased with the workspace as before.\n *\n * Written in the same transaction as every write to the order, from the\n * order as it stands after that write, so the two never disagree and a\n * missing record heals on the next write.\n *\n * KEPT SEVEN YEARS FROM THE SALE, THEN DELETED. Every write stamps\n * `expiresAt` ({@link posHardwareSaleExpiry}) and the Firestore TTL policy on\n * `posHardwareSales.expiresAt` deletes the record once it passes.\n *=========================================*/\n\n/** The top-level collection of retained hardware sale records. */\nexport const POS_HARDWARE_SALES_COLLECTION = 'posHardwareSales'\n\n/**\n * A street address as the sale record keeps it: every key present, so a\n * later write of a different address replaces each one.\n */\nexport interface PosHardwareSaleAddress {\n line1: string\n line2: string | null\n city: string\n state: string | null\n postalCode: string | null\n country: string\n}\n\n/**\n * Who bought it, for the reseller's records (AGL-4038): the buyer's name and\n * address and nothing else of theirs. An online order's are the shipping\n * name and address; an in-person order's are on its attachment.\n */\nexport interface PosHardwareSaleBuyer {\n name: string | null\n address: PosHardwareSaleAddress | null\n}\n\n/**\n * `posHardwareSales/{orderId}`: an order with every personal detail left out\n * but the buyer's name and address.\n */\nexport interface PosHardwareSaleRecord {\n orderId: string\n /** The workspace that bought it, by id; the record outlives the workspace. */\n orgId: string\n lines: Array<Pick<PosHardwareLine, 'sku' | 'name' | 'quantity' | 'unitCents' | 'lineCents'>>\n subtotalCents: number\n shippingMethod: PosHardwareOrderShippingMethod\n shippingCents: number\n taxCents: number\n /** The register discount on an in-person order's lines; 0 for every online one. */\n discountCents: number\n totalCents: number\n currency: string\n /** The sales tax sourcing input: country, state and postal code, never the street. */\n shipTo: PosHardwareTaxRegion | null\n /** Whether Stripe Tax computed the tax; null on orders before it was recorded. */\n automaticTax: boolean | null\n /** Stripe's tax breakdown: the base each rate was applied to, for the return. */\n taxLines: PosHardwareTaxLine[]\n stripeCheckoutSessionId: string | null\n stripePaymentIntentId: string | null\n stripeHardwareOrderId: string | null\n refundId: string | null\n refundedCents: number | null\n status: PosHardwareOrderStatus\n livemode: boolean\n createdAtMs: number\n updatedAtMs: number\n paidAtMs: number | null\n orderedAtMs: number | null\n receivedAtMs: number | null\n shippedAtMs: number | null\n deliveredAtMs: number | null\n registeredAtMs: number | null\n canceledAtMs: number | null\n refundedAtMs: number | null\n /** Where it was sold; `online` for every order before the in-person sale. */\n source: PosHardwareOrderSource\n /** The register sale an in-person order came from: the selling store and its order. */\n posHostId: string | null\n posOrderId: string | null\n /**\n * Where the money went: `platform` for the Hardware card's checkout, on\n * the platform's own Stripe account; `seller_store` for a sale by the\n * platform's own store, in person or online, the selling store's own\n * takings ({@link PosHardwarePaidTo}).\n */\n paidTo: { account: 'platform' } | PosHardwarePaidTo\n /**\n * The `storefrontTaxCollected` row the register sale ALSO filed, when it\n * was paid by a payment link. That row is the whole register sale; the\n * storefront section leaves this order's part of it out, so the sale is on\n * the return once, in the hardware section.\n */\n storefrontTaxRowId: string | null\n /**\n * The buyer's name and address, for the reseller's records; null when the\n * order names none (a sale not attached to anyone yet). Absent from a write\n * whose order no longer has them because the buyer's account was erased,\n * so the stored ones stay ({@link posHardwareSaleSetOptions}).\n */\n buyer?: PosHardwareSaleBuyer | null\n /**\n * When the record is deleted: {@link POS_HARDWARE_SALE_RETENTION_YEARS}\n * after the sale, by the Firestore TTL policy on `posHardwareSales.expiresAt`.\n * Null when the record states no sale date, which keeps it rather than\n * guessing a date to delete it by.\n */\n expiresAt: Date | null\n}\n\n/**\n * How long the platform keeps a hardware sale record (AGL-4038): seven years\n * from the sale, then the record is deleted. Longer than the four years Texas\n * requires for sales tax records, a margin for an audit of an older period.\n */\nexport const POS_HARDWARE_SALE_RETENTION_YEARS = 7\n\n/**\n * When a sale record expires: the same calendar instant, seven years after\n * the sale was paid (the order's creation where no payment time is stated).\n * A sale on 29 February expires on 1 March, a day late rather than early.\n * Null when there is no sale time, so the record is kept, never reaped at\n * the epoch.\n */\nexport function posHardwareSaleExpiry(\n order: Pick<PosHardwareOrder, 'paidAtMs' | 'createdAtMs'>,\n): Date | null {\n const saleAtMs = [order.paidAtMs, order.createdAtMs].find(\n (value) => typeof value === 'number' && Number.isFinite(value) && value > 0,\n )\n if (saleAtMs === undefined) return null\n const expires = new Date(saleAtMs)\n expires.setUTCFullYear(expires.getUTCFullYear() + POS_HARDWARE_SALE_RETENTION_YEARS)\n return expires\n}\n\n/** A tax line as the record keeps it: every field picked, every figure an integer. */\nfunction saleTaxLine(line: Partial<PosHardwareTaxLine> | null | undefined): PosHardwareTaxLine {\n const integerOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? Math.round(value) : null\n const numberOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n const textOf = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null\n return {\n amountCents: integerOrNull(line?.amountCents) ?? 0,\n taxabilityReason: textOf(line?.taxabilityReason),\n taxRateId: textOf(line?.taxRateId),\n taxableAmountCents: integerOrNull(line?.taxableAmountCents),\n jurisdiction: textOf(line?.jurisdiction),\n rateState: textOf(line?.rateState),\n percentage: numberOrNull(line?.percentage),\n }\n}\n\nconst stampOrNull = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\nconst textOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\n/** The tax region of an order: its address cut down, or what an erasure left. */\nexport function posHardwareTaxRegion(order: Pick<PosHardwareOrder, 'shipping'>): PosHardwareTaxRegion | null {\n const address = order.shipping?.address\n if (address?.country) {\n return {\n country: address.country,\n state: textOrNull(address.state),\n postalCode: textOrNull(address.postalCode),\n }\n }\n const kept = order.shipping?.taxRegion\n return kept?.country\n ? { country: kept.country, state: textOrNull(kept.state), postalCode: textOrNull(kept.postalCode) }\n : null\n}\n\n/** An address with every key present, or null when it names no place. */\nfunction saleAddress(address: Partial<PosHardwareAddress> | null | undefined): PosHardwareSaleAddress | null {\n const line1 = textOrNull(address?.line1)\n const city = textOrNull(address?.city)\n const country = textOrNull(address?.country)\n if (!line1 || !city || !country) return null\n return {\n line1: line1.slice(0, 200),\n line2: textOrNull(address?.line2)?.slice(0, 200) ?? null,\n city: city.slice(0, 100),\n state: textOrNull(address?.state)?.slice(0, 100) ?? null,\n postalCode: textOrNull(address?.postalCode)?.slice(0, 20) ?? null,\n country: country.toUpperCase().slice(0, 2),\n }\n}\n\n/**\n * A buyer's business address as an in-person order keeps it (AGL-4038):\n * trimmed and cut to length, or null when it lacks a street, city, postal\n * code or two-letter country.\n */\nexport function posHardwareBuyerAddress(value: unknown): PosHardwareAddress | null {\n const address = (value && typeof value === 'object' ? value : {}) as Partial<Record<keyof PosHardwareAddress, unknown>>\n const line1 = textOrNull(address.line1)?.slice(0, 200)\n const city = textOrNull(address.city)?.slice(0, 100)\n const postalCode = textOrNull(address.postalCode)?.slice(0, 20)\n const country = textOrNull(address.country)?.toUpperCase()\n if (!line1 || !city || !postalCode || !country || !/^[A-Z]{2}$/.test(country)) return null\n const line2 = textOrNull(address.line2)?.slice(0, 200)\n const state = textOrNull(address.state)?.slice(0, 100)\n return { line1, ...(line2 ? { line2 } : {}), city, ...(state ? { state } : {}), postalCode, country }\n}\n\n/**\n * The buyer's name and address as the order holds them now (AGL-4038): the\n * shipping name and address of an online order, the attachment's of an\n * in-person one. `undefined` when the order has none BECAUSE its buyer's\n * account was erased, which tells the write to keep what the record has;\n * null when it simply names no one yet.\n */\nexport function posHardwareSaleBuyer(\n order: Pick<PosHardwareOrder, 'shipping' | 'attachment' | 'source' | 'buyerErasedAtMs'>,\n): PosHardwareSaleBuyer | null | undefined {\n const inPerson = posHardwareOrderSource(order) === 'in_person'\n const name = textOrNull(inPerson ? order.attachment?.name : order.shipping?.name)?.slice(0, 200) ?? null\n const address = saleAddress(inPerson ? order.attachment?.address : order.shipping?.address)\n if (name || address) return { name, address }\n return typeof order.buyerErasedAtMs === 'number' ? undefined : null\n}\n\n/**\n * The retained sale record of an order, as it stands. Every field is picked\n * by name, so a field added to the order later reaches the record only when\n * someone decides it should.\n */\nexport function posHardwareSaleRecord(orderId: string, order: PosHardwareOrder): PosHardwareSaleRecord {\n const buyer = posHardwareSaleBuyer(order)\n return {\n orderId,\n orgId: order.orgId,\n lines: (order.lines ?? []).map((line) => ({\n sku: line.sku,\n name: line.name,\n quantity: line.quantity,\n unitCents: line.unitCents,\n lineCents: line.lineCents,\n })),\n subtotalCents: order.subtotalCents ?? 0,\n shippingMethod: order.shipping?.method ?? 'standard',\n shippingCents: order.shipping?.cents ?? 0,\n taxCents: order.taxCents ?? 0,\n discountCents: stampOrNull(order.discountCents) ?? 0,\n totalCents: order.totalCents ?? 0,\n currency: order.currency ?? POS_HARDWARE_CURRENCY,\n shipTo: posHardwareTaxRegion(order),\n automaticTax: typeof order.automaticTax === 'boolean' ? order.automaticTax : null,\n taxLines: (Array.isArray(order.taxLines) ? order.taxLines : []).map(saleTaxLine),\n stripeCheckoutSessionId: textOrNull(order.stripeCheckoutSessionId),\n stripePaymentIntentId: textOrNull(order.stripePaymentIntentId),\n stripeHardwareOrderId: textOrNull(order.stripeHardwareOrderId),\n refundId: textOrNull(order.refundId),\n refundedCents: stampOrNull(order.refundedCents),\n status: order.status,\n livemode: order.livemode === true,\n createdAtMs: order.createdAtMs ?? 0,\n updatedAtMs: order.updatedAtMs ?? order.createdAtMs ?? 0,\n paidAtMs: stampOrNull(order.paidAtMs),\n orderedAtMs: stampOrNull(order.orderedAtMs),\n receivedAtMs: stampOrNull(order.receivedAtMs),\n shippedAtMs: stampOrNull(order.shippedAtMs),\n deliveredAtMs: stampOrNull(order.deliveredAtMs),\n registeredAtMs: stampOrNull(order.registeredAtMs),\n canceledAtMs: stampOrNull(order.canceledAtMs),\n refundedAtMs: stampOrNull(order.refundedAtMs),\n source: posHardwareOrderSource(order),\n posHostId: textOrNull(order.posSale?.hostId),\n posOrderId: textOrNull(order.posSale?.orderId),\n paidTo: salePaidTo(order),\n storefrontTaxRowId: textOrNull(order.posSale?.paymentLinkSessionId),\n // Left out, never written as null, once the buyer was erased: the\n // stored name and address are the reseller's records and stay.\n ...(buyer === undefined ? {} : { buyer }),\n // The TTL policy's field: the record outlives the workspace, not the law.\n expiresAt: posHardwareSaleExpiry(order),\n }\n}\n\n/**\n * How every write of a sale record is made (AGL-4038): `set` with exactly\n * the record's own fields as `mergeFields`, so each one is replaced whole —\n * a map included, never merged key by key — and a field the record leaves\n * out is left as stored. The record leaves out only `buyer`, and only once\n * the buyer's account was erased ({@link posHardwareSaleBuyer}), so the\n * buyer's name and address outlive the erasure and every write after it.\n */\nexport function posHardwareSaleSetOptions(order: PosHardwareOrder): { mergeFields: string[] } {\n return { mergeFields: Object.keys(posHardwareSaleRecord('', order)) }\n}\n\n/** Where a sale's money went, picked by name: never a buyer detail. */\nfunction salePaidTo(order: Pick<PosHardwareOrder, 'source' | 'paidTo'>): PosHardwareSaleRecord['paidTo'] {\n const paidTo = order.paidTo\n if (!isPosHardwareSellerStoreSale(order) || paidTo?.account !== 'seller_store') {\n return { account: 'platform' }\n }\n return {\n account: 'seller_store',\n hostId: String(paidTo.hostId ?? ''),\n orgId: String(paidTo.orgId ?? ''),\n tenders: (Array.isArray(paidTo.tenders) ? paidTo.tenders : []).map(String).slice(0, 10),\n stripeAccountId: textOrNull(paidTo.stripeAccountId),\n }\n}\n\n/**\n * What an account erasure does to an order the person placed (AGL-4038): the\n * workspace keeps the order and every amount on it; the buyer comes off it —\n * who started it, the email, the name, the phone, the street and the\n * tracking, which names the parcel to a carrier who would say where it went.\n * The country, state and postal code stay, because sales tax is sourced by\n * them. Deterministic but for the stamp, and an order already erased no\n * longer answers to the person's uid, so a second run finds nothing.\n *\n * The buyer's NAME and ADDRESS stay on the platform's sale record, not on\n * the order: `buyerErasedAtMs` is what tells the record's next write to keep\n * them ({@link posHardwareSaleBuyer}, {@link posHardwareSaleSetOptions}).\n */\nexport function posHardwareBuyerErasedPatch(\n order: Pick<PosHardwareOrder, 'shipping' | 'attachment' | 'returnRequest'>,\n now: number,\n): Record<string, unknown> {\n // The whole map, read in the same transaction: a dotted-path update would\n // leave a field added to `shipping` later standing with the person in it.\n const shipping = order.shipping\n const attachment = order.attachment\n return {\n createdBy: null,\n contactEmail: null,\n shipping: {\n method: shipping?.method ?? 'standard',\n label: shipping?.label ?? posHardwareShippingLabel(shipping?.method),\n cents: shipping?.cents ?? 0,\n name: null,\n phone: null,\n address: null,\n taxRegion: posHardwareTaxRegion(order),\n },\n tracking: null,\n // An in-person order's attachment names the buyer too (AGL-4038): their\n // email, account, name and address come off it (the map is rebuilt with\n // none of them); the workspace and store it is in stay.\n ...(attachment\n ? {\n attachment: {\n state: attachment.state === 'attached' ? 'attached' : 'pending',\n email: null,\n uid: null,\n orgId: attachment.orgId ?? null,\n hostId: attachment.hostId ?? null,\n attachedBy: attachment.attachedBy ?? null,\n attachedAtMs: attachment.attachedAtMs ?? null,\n },\n }\n : {}),\n // Their return request keeps its outcome; their words and account go.\n ...(order.returnRequest\n ? { returnRequest: { ...order.returnRequest, reason: null, requestedBy: null } }\n : {}),\n buyerErasedAtMs: now,\n updatedAtMs: now,\n }\n}\n\n/** An order id: `hw_` and twenty hex characters. */\nexport const POS_HARDWARE_ORDER_ID = /^hw_[a-f0-9]{20}$/\n\n/** Dollars and cents for the card and the emails. */\nexport function formatPosHardwareCents(cents: number): string {\n const value = Number.isFinite(cents) ? cents : 0\n return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(value / 100)\n}\n\n/**\n * Every reader an order ships, one unit each (AGL-4038): the units it holds,\n * or, for an order recorded before units were kept for shipped orders, one\n * per reader on its lines with nothing recorded yet. Accessories have none.\n */\nexport function posHardwareOrderUnits(order: Pick<PosHardwareOrder, 'units' | 'lines'>): PosHardwareUnit[] {\n if (Array.isArray(order.units) && order.units.length) return order.units\n const units: PosHardwareUnit[] = []\n for (const line of order.lines ?? []) {\n if (posHardwareSku(line.sku)?.kind !== 'reader') continue\n for (let index = 0; index < line.quantity; index += 1) {\n units.push({ sku: line.sku, serialNumber: null, readerId: null, hostId: null, registeredAtMs: null })\n }\n }\n return units\n}\n\n/**\n * Why an order may not ship yet, or null when it may (AGL-4038): every\n * reader on it is set up first, its serial number recorded, so the buyer's\n * reader is matched to its order the moment they pair it, if it was not\n * registered to their store already. An order of accessories alone ships as\n * it is.\n */\nexport function posHardwareReadyToShip(order: Pick<PosHardwareOrder, 'units' | 'lines'>): string | null {\n const units = posHardwareOrderUnits(order)\n const missing = units.filter((unit) => !unit.serialNumber).length\n if (!missing) return null\n return missing === units.length && units.length === 1\n ? 'Set the reader up first: record its serial number.'\n : `Set every reader up first: ${missing} of ${units.length} still need a serial number.`\n}\n"],"names":["PLATFORM_BRAND_NAME","POS_HARDWARE_CURRENCY","POS_HARDWARE_SHIP_COUNTRIES","POS_HARDWARE_MAX_PER_LINE","POS_HARDWARE_MAX_UNITS","POS_HARDWARE_TAX_CODE","POS_HARDWARE_ENV","enabled","prices","markupBps","shipping","automaticTax","inPersonEnabled","sellerHostId","sellerOrgId","POS_HARDWARE_DEFAULT_MARKUP_BPS","POS_HARDWARE_SKUS","id","kind","stripeProductName","displayName","use","posHardwareSku","find","sku","POS_HARDWARE_SHIPPING_LABELS","standard","express","priority","SHIPPING_METHODS","Object","keys","isPosHardwareShippingMethod","value","includes","POS_HARDWARE_IN_PERSON_SHIPPING_LABEL","posHardwareShippingLabel","method","MAX_FIGURE_CENTS","MAX_MARKUP_BPS","isCents","min","Number","isSafeInteger","parseJsonObject","raw","text","String","trim","parsed","JSON","parse","Array","isArray","parsePosHardwareConfig","env","toLowerCase","markupText","test","costs","cost","anyReader","some","undefined","shippingRaw","flatMap","cents","length","CONFIG_ID","parsePosHardwareInPersonConfig","isPosHardwareSkuId","normalizePosHardwareSerial","toUpperCase","replace","slice","posHardwareUnitCents","costCents","Math","floor","posHardwareOfferUnitCents","config","listed","listedCents","posHardwareOffers","name","unitCents","pricePosHardwareCart","requested","ok","error","offers","Map","map","offer","quantities","entry","quantity","has","isInteger","set","get","units","lines","push","lineCents","subtotalCents","reduce","sum","line","POS_HARDWARE_METADATA_TYPE","encodePosHardwareLines","join","decodePosHardwareLines","encoded","part","split","skuId","quantityText","unitText","POS_HARDWARE_ORDER_STATUSES","isPosHardwareOrderStatus","POS_HARDWARE_STATUS_LABELS","paid","ordered","received","shipped","delivered","registered","canceled","refunded","POS_HARDWARE_STAFF_STATUS_LABELS","NEXT_STATUS","nextPosHardwareStatus","status","posHardwareRefundable","POS_HARDWARE_UNSHIPPED_STATUSES","posHardwareOrderSource","order","source","isPosHardwareSellerStoreSale","posHardwareShips","POS_HARDWARE_RETURN_REASON_MAX","POS_HARDWARE_STATUS_STAMP","POS_HARDWARE_ANCHOR","POS_PLAN_ADDS","posPlanPrompt","where","arrived","atRegister","one","POS_HARDWARE_ORDERS_COLLECTION","POS_HARDWARE_SALES_COLLECTION","POS_HARDWARE_SALE_RETENTION_YEARS","posHardwareSaleExpiry","saleAtMs","paidAtMs","createdAtMs","isFinite","expires","Date","setUTCFullYear","getUTCFullYear","saleTaxLine","integerOrNull","round","numberOrNull","textOf","amountCents","taxabilityReason","taxRateId","taxableAmountCents","jurisdiction","rateState","percentage","stampOrNull","textOrNull","posHardwareTaxRegion","address","country","state","postalCode","kept","taxRegion","saleAddress","line1","city","line2","posHardwareBuyerAddress","posHardwareSaleBuyer","inPerson","attachment","buyerErasedAtMs","posHardwareSaleRecord","orderId","buyer","orgId","shippingMethod","shippingCents","taxCents","discountCents","totalCents","currency","shipTo","taxLines","stripeCheckoutSessionId","stripePaymentIntentId","stripeHardwareOrderId","refundId","refundedCents","livemode","updatedAtMs","orderedAtMs","receivedAtMs","shippedAtMs","deliveredAtMs","registeredAtMs","canceledAtMs","refundedAtMs","posHostId","posSale","hostId","posOrderId","paidTo","salePaidTo","storefrontTaxRowId","paymentLinkSessionId","expiresAt","posHardwareSaleSetOptions","mergeFields","account","tenders","stripeAccountId","posHardwareBuyerErasedPatch","now","createdBy","contactEmail","label","phone","tracking","email","uid","attachedBy","attachedAtMs","returnRequest","reason","requestedBy","POS_HARDWARE_ORDER_ID","formatPosHardwareCents","Intl","NumberFormat","style","format","posHardwareOrderUnits","index","serialNumber","readerId","posHardwareReadyToShip","missing","filter","unit"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;2CAmB2C,GAE3C,SAASA,mBAAmB,QAAQ,wCAAuC;AAG3E,4DAA4D,GAC5D,OAAO,MAAMC,wBAAwB,MAAK;AAE1C;;;;;;CA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AME,IAAI,CAAC;gBAAE/E,KAAKoF,KAAKpF,GAAG;gBAAEsO,cAAc;gBAAMC,UAAU;gBAAMnC,QAAQ;gBAAML,gBAAgB;YAAK;QACrG;IACF;IACA,OAAOlH;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAAS2J,uBAAuBvH,KAAgD;IACrF,MAAMpC,QAAQuJ,sBAAsBnH;IACpC,MAAMwH,UAAU5J,MAAM6J,MAAM,CAAC,CAACC,OAAS,CAACA,KAAKL,YAAY,EAAE3L,MAAM;IACjE,IAAI,CAAC8L,SAAS,OAAO;IACrB,OAAOA,YAAY5J,MAAMlC,MAAM,IAAIkC,MAAMlC,MAAM,KAAK,IAChD,uDACA,CAAC,2BAA2B,EAAE8L,QAAQ,IAAI,EAAE5J,MAAMlC,MAAM,CAAC,4BAA4B,CAAC;AAC5F"}
|
|
@@ -50,7 +50,7 @@ export function isPosReaderSplashChoice(value) {
|
|
|
50
50
|
export const POS_READER_SPLASH_FAMILIES = [
|
|
51
51
|
{
|
|
52
52
|
id: 'portrait-large',
|
|
53
|
-
label: '
|
|
53
|
+
label: 'Touchscreen readers (S700 and S710)',
|
|
54
54
|
width: 1080,
|
|
55
55
|
height: 1920,
|
|
56
56
|
deviceTypes: [
|
|
@@ -60,7 +60,7 @@ export const POS_READER_SPLASH_FAMILIES = [
|
|
|
60
60
|
},
|
|
61
61
|
{
|
|
62
62
|
id: 'portrait-small',
|
|
63
|
-
label: '
|
|
63
|
+
label: 'Countertop reader (WisePOS E)',
|
|
64
64
|
width: 720,
|
|
65
65
|
height: 1280,
|
|
66
66
|
deviceTypes: [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/pos-reader-splash.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\n/*==========================================\n * A CARD READER'S START-UP SCREEN (AGL-4048).\n *\n * Stripe's smart readers show a \"splash screen\" while they wait for a\n * payment. Stripe sets it per device type on a Terminal Configuration, from a\n * File uploaded with purpose `terminal_reader_splashscreen`, and a\n * Configuration is assigned per Location, so each store's readers can carry\n * their own. The rules Stripe states for the image, and the only ones this\n * module enforces:\n *\n * - JPEG or PNG under 2 MB (a GIF may be 4 MB, but it is re-encoded here,\n * so it is not offered);\n * - cropped to the reader's own screen: 1080 × 1920 on the Stripe Reader\n * S700 and S710, 720 × 1280 on the BBPOS WisePOS E.\n *\n * What a store shows is one of three CHOICES:\n *\n * - `platform` the platform's default screen, which staff upload;\n * - `logo` the workspace's own logo, centered on a white screen;\n * - `image` a full-screen portrait image the merchant picked from\n * their media library.\n *\n * A white-label workspace defaults to `logo` and can never be given\n * `platform`: its readers never show the platform's brand.\n *\n * Shared by the console and the server, so this module imports nothing.\n *=========================================*/\n\nexport type PosReaderSplashChoice = 'platform' | 'logo' | 'image'\n\nexport const POS_READER_SPLASH_CHOICES: readonly PosReaderSplashChoice[] = ['platform', 'logo', 'image']\n\nexport function isPosReaderSplashChoice(value: unknown): value is PosReaderSplashChoice {\n return typeof value === 'string' && (POS_READER_SPLASH_CHOICES as readonly string[]).includes(value)\n}\n\n/** A group of readers that share one screen size, so one image. */\nexport type PosReaderSplashFamilyId = 'portrait-large' | 'portrait-small'\n\nexport interface PosReaderSplashFamily {\n id: PosReaderSplashFamilyId\n /** The readers in it, for a person. */\n label: string\n width: number\n height: number\n /** The Terminal Configuration keys that take this family's image. */\n deviceTypes: readonly string[]\n}\n\nexport const POS_READER_SPLASH_FAMILIES: readonly PosReaderSplashFamily[] = [\n {\n id: 'portrait-large',\n label: 'Stripe Reader S700 and S710',\n width: 1080,\n height: 1920,\n deviceTypes: ['stripe_s700', 'stripe_s710'],\n },\n {\n id: 'portrait-small',\n label: 'BBPOS WisePOS E',\n width: 720,\n height: 1280,\n deviceTypes: ['bbpos_wisepos_e'],\n },\n]\n\nexport function posReaderSplashFamily(id: unknown): PosReaderSplashFamily | null {\n return POS_READER_SPLASH_FAMILIES.find((family) => family.id === id) ?? null\n}\n\n/** Every Terminal Configuration device key a start-up screen is set on. */\nexport const POS_READER_SPLASH_DEVICE_TYPES: readonly string[] = POS_READER_SPLASH_FAMILIES.flatMap(\n (family) => family.deviceTypes,\n)\n\n/** Stripe's limit is \"less than 2 MB\"; read as decimal megabytes, the smaller. */\nexport const POS_READER_SPLASH_MAX_BYTES = 2_000_000\n\n/** What Stripe takes for a still start-up screen. */\nexport const POS_READER_SPLASH_CONTENT_TYPES: readonly string[] = ['image/png', 'image/jpeg']\n\n/** What a merchant's own full-screen image may be picked as; it is re-encoded. */\nexport const POS_READER_SPLASH_SOURCE_TYPES: readonly string[] = ['image/png', 'image/jpeg', 'image/webp']\n\n/** The largest source read to draw a screen from: a logo or a photo, never a video. */\nexport const POS_READER_SPLASH_SOURCE_MAX_BYTES = 15_000_000\n\n/** The choice a store gets before anyone picks one. */\nexport function posReaderSplashDefaultChoice(whiteLabel: boolean): PosReaderSplashChoice {\n return whiteLabel ? 'logo' : 'platform'\n}\n\n/**\n * The choice that is applied: the stored one when it is valid, the default\n * otherwise, and never `platform` for a white-label workspace (one that\n * stored it before it was white-labeled gets its logo instead).\n */\nexport function posReaderSplashEffectiveChoice(stored: unknown, whiteLabel: boolean): PosReaderSplashChoice {\n const choice = isPosReaderSplashChoice(stored) ? stored : posReaderSplashDefaultChoice(whiteLabel)\n return whiteLabel && choice === 'platform' ? 'logo' : choice\n}\n\nexport interface PosReaderSplashImageFacts {\n contentType: string\n bytes: number\n width: number\n height: number\n}\n\n/**\n * Why an image cannot be sent to Stripe as `family`'s start-up screen, or\n * null when it can: the exact screen size, JPEG or PNG, under 2 MB. Staff's\n * default screens are checked with this as they are uploaded, and every\n * rendered screen again before it leaves.\n */\nexport function posReaderSplashImageProblem(\n facts: PosReaderSplashImageFacts,\n family: PosReaderSplashFamily,\n): string | null {\n if (!POS_READER_SPLASH_CONTENT_TYPES.includes(facts.contentType)) {\n return 'Use a PNG or JPEG image.'\n }\n if (facts.width !== family.width || facts.height !== family.height) {\n return `The ${family.label} screen is ${family.width} × ${family.height} pixels; this image is ${facts.width} × ${facts.height}.`\n }\n if (!(facts.bytes > 0) || facts.bytes >= POS_READER_SPLASH_MAX_BYTES) {\n return 'Use an image under 2 MB.'\n }\n return null\n}\n\n/** The largest screen, which a merchant's full-screen image must cover. */\nexport const POS_READER_SPLASH_LARGEST = POS_READER_SPLASH_FAMILIES[0]\n\n/**\n * Why a merchant's own image cannot be a full-screen start-up screen, or null\n * when it can: a PNG, JPEG or WebP, portrait 9:16 (a 1% slack, since a\n * designer's export is often a pixel off), at least as large as the largest\n * screen so no reader shows it enlarged.\n */\nexport function posReaderSplashArtworkProblem(facts: {\n contentType?: string | null\n bytes?: number | null\n width: number\n height: number\n}): string | null {\n const largest = POS_READER_SPLASH_LARGEST\n if (facts.contentType && !POS_READER_SPLASH_SOURCE_TYPES.includes(facts.contentType)) {\n return 'Choose a PNG, JPEG or WebP image.'\n }\n if (typeof facts.bytes === 'number' && facts.bytes > POS_READER_SPLASH_SOURCE_MAX_BYTES) {\n return 'Choose an image under 15 MB.'\n }\n if (!(facts.width > 0) || !(facts.height > 0)) return 'That image could not be read.'\n const ratio = facts.width / facts.height\n const wanted = largest.width / largest.height\n if (Math.abs(ratio - wanted) / wanted > 0.01) {\n return `Choose a portrait image shaped 9:16, such as ${largest.width} × ${largest.height} pixels.`\n }\n if (facts.width < largest.width || facts.height < largest.height) {\n return `Choose an image at least ${largest.width} × ${largest.height} pixels.`\n }\n return null\n}\n\n/** `hosts/{hostId}/terminal/config.splash`: the store's choice. */\nexport interface PosReaderSplashSetting {\n choice: PosReaderSplashChoice\n /** For `image`: the picked asset, as the media library names it. */\n mediaScope?: string\n mediaId?: string\n updatedAtMs: number\n updatedBy?: string\n}\n\n/** What the POS devices card shows about the store's start-up screen. */\nexport interface PosReaderSplashStatus {\n /** Whether card readers are offered at all; the setting is hidden otherwise. */\n available: boolean\n /** The stored choice, or null when none was made. */\n choice: PosReaderSplashChoice | null\n /** What is applied, after the default and the white-label rule. */\n effectiveChoice: PosReaderSplashChoice\n whiteLabel: boolean\n /** The brand a white-label workspace or the platform goes by, for copy. */\n productName: string\n /** Whether staff have uploaded the platform's default screen. */\n platformReady: boolean\n /** The workspace logo that `logo` would use, or null when there is none. */\n logoUrl: string | null\n /** The asset `image` uses, when one was picked, with an address to preview it. */\n image: { mediaScope: string; mediaId: string; url: string | null } | null\n /** Whether the store has a Terminal Location yet (its first reader makes it). */\n locationReady: boolean\n /** When the current choice last reached Stripe. */\n appliedAtMs: number | null\n /** Why the current choice could not be applied, when it could not. */\n problem: string | null\n}\n"],"names":["POS_READER_SPLASH_CHOICES","isPosReaderSplashChoice","value","includes","POS_READER_SPLASH_FAMILIES","id","label","width","height","deviceTypes","posReaderSplashFamily","find","family","POS_READER_SPLASH_DEVICE_TYPES","flatMap","POS_READER_SPLASH_MAX_BYTES","POS_READER_SPLASH_CONTENT_TYPES","POS_READER_SPLASH_SOURCE_TYPES","POS_READER_SPLASH_SOURCE_MAX_BYTES","posReaderSplashDefaultChoice","whiteLabel","posReaderSplashEffectiveChoice","stored","choice","posReaderSplashImageProblem","facts","contentType","bytes","POS_READER_SPLASH_LARGEST","posReaderSplashArtworkProblem","largest","ratio","wanted","Math","abs"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;2CA0B2C,GAI3C,OAAO,MAAMA,4BAA8D;IAAC;IAAY;IAAQ;CAAQ,CAAA;AAExG,OAAO,SAASC,wBAAwBC,KAAc;IACpD,OAAO,OAAOA,UAAU,YAAY,AAAC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CAAC;IAChF;IACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/model/pos-reader-splash.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\n/*==========================================\n * A CARD READER'S START-UP SCREEN (AGL-4048).\n *\n * Stripe's smart readers show a \"splash screen\" while they wait for a\n * payment. Stripe sets it per device type on a Terminal Configuration, from a\n * File uploaded with purpose `terminal_reader_splashscreen`, and a\n * Configuration is assigned per Location, so each store's readers can carry\n * their own. The rules Stripe states for the image, and the only ones this\n * module enforces:\n *\n * - JPEG or PNG under 2 MB (a GIF may be 4 MB, but it is re-encoded here,\n * so it is not offered);\n * - cropped to the reader's own screen: 1080 × 1920 on the Stripe Reader\n * S700 and S710, 720 × 1280 on the BBPOS WisePOS E.\n *\n * What a store shows is one of three CHOICES:\n *\n * - `platform` the platform's default screen, which staff upload;\n * - `logo` the workspace's own logo, centered on a white screen;\n * - `image` a full-screen portrait image the merchant picked from\n * their media library.\n *\n * A white-label workspace defaults to `logo` and can never be given\n * `platform`: its readers never show the platform's brand.\n *\n * Shared by the console and the server, so this module imports nothing.\n *=========================================*/\n\nexport type PosReaderSplashChoice = 'platform' | 'logo' | 'image'\n\nexport const POS_READER_SPLASH_CHOICES: readonly PosReaderSplashChoice[] = ['platform', 'logo', 'image']\n\nexport function isPosReaderSplashChoice(value: unknown): value is PosReaderSplashChoice {\n return typeof value === 'string' && (POS_READER_SPLASH_CHOICES as readonly string[]).includes(value)\n}\n\n/** A group of readers that share one screen size, so one image. */\nexport type PosReaderSplashFamilyId = 'portrait-large' | 'portrait-small'\n\nexport interface PosReaderSplashFamily {\n id: PosReaderSplashFamilyId\n /** The readers in it, for a person. */\n label: string\n width: number\n height: number\n /** The Terminal Configuration keys that take this family's image. */\n deviceTypes: readonly string[]\n}\n\nexport const POS_READER_SPLASH_FAMILIES: readonly PosReaderSplashFamily[] = [\n {\n id: 'portrait-large',\n label: 'Touchscreen readers (S700 and S710)',\n width: 1080,\n height: 1920,\n deviceTypes: ['stripe_s700', 'stripe_s710'],\n },\n {\n id: 'portrait-small',\n label: 'Countertop reader (WisePOS E)',\n width: 720,\n height: 1280,\n deviceTypes: ['bbpos_wisepos_e'],\n },\n]\n\nexport function posReaderSplashFamily(id: unknown): PosReaderSplashFamily | null {\n return POS_READER_SPLASH_FAMILIES.find((family) => family.id === id) ?? null\n}\n\n/** Every Terminal Configuration device key a start-up screen is set on. */\nexport const POS_READER_SPLASH_DEVICE_TYPES: readonly string[] = POS_READER_SPLASH_FAMILIES.flatMap(\n (family) => family.deviceTypes,\n)\n\n/** Stripe's limit is \"less than 2 MB\"; read as decimal megabytes, the smaller. */\nexport const POS_READER_SPLASH_MAX_BYTES = 2_000_000\n\n/** What Stripe takes for a still start-up screen. */\nexport const POS_READER_SPLASH_CONTENT_TYPES: readonly string[] = ['image/png', 'image/jpeg']\n\n/** What a merchant's own full-screen image may be picked as; it is re-encoded. */\nexport const POS_READER_SPLASH_SOURCE_TYPES: readonly string[] = ['image/png', 'image/jpeg', 'image/webp']\n\n/** The largest source read to draw a screen from: a logo or a photo, never a video. */\nexport const POS_READER_SPLASH_SOURCE_MAX_BYTES = 15_000_000\n\n/** The choice a store gets before anyone picks one. */\nexport function posReaderSplashDefaultChoice(whiteLabel: boolean): PosReaderSplashChoice {\n return whiteLabel ? 'logo' : 'platform'\n}\n\n/**\n * The choice that is applied: the stored one when it is valid, the default\n * otherwise, and never `platform` for a white-label workspace (one that\n * stored it before it was white-labeled gets its logo instead).\n */\nexport function posReaderSplashEffectiveChoice(stored: unknown, whiteLabel: boolean): PosReaderSplashChoice {\n const choice = isPosReaderSplashChoice(stored) ? stored : posReaderSplashDefaultChoice(whiteLabel)\n return whiteLabel && choice === 'platform' ? 'logo' : choice\n}\n\nexport interface PosReaderSplashImageFacts {\n contentType: string\n bytes: number\n width: number\n height: number\n}\n\n/**\n * Why an image cannot be sent to Stripe as `family`'s start-up screen, or\n * null when it can: the exact screen size, JPEG or PNG, under 2 MB. Staff's\n * default screens are checked with this as they are uploaded, and every\n * rendered screen again before it leaves.\n */\nexport function posReaderSplashImageProblem(\n facts: PosReaderSplashImageFacts,\n family: PosReaderSplashFamily,\n): string | null {\n if (!POS_READER_SPLASH_CONTENT_TYPES.includes(facts.contentType)) {\n return 'Use a PNG or JPEG image.'\n }\n if (facts.width !== family.width || facts.height !== family.height) {\n return `The ${family.label} screen is ${family.width} × ${family.height} pixels; this image is ${facts.width} × ${facts.height}.`\n }\n if (!(facts.bytes > 0) || facts.bytes >= POS_READER_SPLASH_MAX_BYTES) {\n return 'Use an image under 2 MB.'\n }\n return null\n}\n\n/** The largest screen, which a merchant's full-screen image must cover. */\nexport const POS_READER_SPLASH_LARGEST = POS_READER_SPLASH_FAMILIES[0]\n\n/**\n * Why a merchant's own image cannot be a full-screen start-up screen, or null\n * when it can: a PNG, JPEG or WebP, portrait 9:16 (a 1% slack, since a\n * designer's export is often a pixel off), at least as large as the largest\n * screen so no reader shows it enlarged.\n */\nexport function posReaderSplashArtworkProblem(facts: {\n contentType?: string | null\n bytes?: number | null\n width: number\n height: number\n}): string | null {\n const largest = POS_READER_SPLASH_LARGEST\n if (facts.contentType && !POS_READER_SPLASH_SOURCE_TYPES.includes(facts.contentType)) {\n return 'Choose a PNG, JPEG or WebP image.'\n }\n if (typeof facts.bytes === 'number' && facts.bytes > POS_READER_SPLASH_SOURCE_MAX_BYTES) {\n return 'Choose an image under 15 MB.'\n }\n if (!(facts.width > 0) || !(facts.height > 0)) return 'That image could not be read.'\n const ratio = facts.width / facts.height\n const wanted = largest.width / largest.height\n if (Math.abs(ratio - wanted) / wanted > 0.01) {\n return `Choose a portrait image shaped 9:16, such as ${largest.width} × ${largest.height} pixels.`\n }\n if (facts.width < largest.width || facts.height < largest.height) {\n return `Choose an image at least ${largest.width} × ${largest.height} pixels.`\n }\n return null\n}\n\n/** `hosts/{hostId}/terminal/config.splash`: the store's choice. */\nexport interface PosReaderSplashSetting {\n choice: PosReaderSplashChoice\n /** For `image`: the picked asset, as the media library names it. */\n mediaScope?: string\n mediaId?: string\n updatedAtMs: number\n updatedBy?: string\n}\n\n/** What the POS devices card shows about the store's start-up screen. */\nexport interface PosReaderSplashStatus {\n /** Whether card readers are offered at all; the setting is hidden otherwise. */\n available: boolean\n /** The stored choice, or null when none was made. */\n choice: PosReaderSplashChoice | null\n /** What is applied, after the default and the white-label rule. */\n effectiveChoice: PosReaderSplashChoice\n whiteLabel: boolean\n /** The brand a white-label workspace or the platform goes by, for copy. */\n productName: string\n /** Whether staff have uploaded the platform's default screen. */\n platformReady: boolean\n /** The workspace logo that `logo` would use, or null when there is none. */\n logoUrl: string | null\n /** The asset `image` uses, when one was picked, with an address to preview it. */\n image: { mediaScope: string; mediaId: string; url: string | null } | null\n /** Whether the store has a Terminal Location yet (its first reader makes it). */\n locationReady: boolean\n /** When the current choice last reached Stripe. */\n appliedAtMs: number | null\n /** Why the current choice could not be applied, when it could not. */\n problem: string | null\n}\n"],"names":["POS_READER_SPLASH_CHOICES","isPosReaderSplashChoice","value","includes","POS_READER_SPLASH_FAMILIES","id","label","width","height","deviceTypes","posReaderSplashFamily","find","family","POS_READER_SPLASH_DEVICE_TYPES","flatMap","POS_READER_SPLASH_MAX_BYTES","POS_READER_SPLASH_CONTENT_TYPES","POS_READER_SPLASH_SOURCE_TYPES","POS_READER_SPLASH_SOURCE_MAX_BYTES","posReaderSplashDefaultChoice","whiteLabel","posReaderSplashEffectiveChoice","stored","choice","posReaderSplashImageProblem","facts","contentType","bytes","POS_READER_SPLASH_LARGE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AAG,EAAEuB,QAAQtB,MAAM,CAAC,QAAQ,CAAC;IACpG;IACA,IAAIiB,MAAMlB,KAAK,GAAGuB,QAAQvB,KAAK,IAAIkB,MAAMjB,MAAM,GAAGsB,QAAQtB,MAAM,EAAE;QAChE,OAAO,CAAC,yBAAyB,EAAEsB,QAAQvB,KAAK,CAAC,GAAG,EAAEuB,QAAQtB,MAAM,CAAC,QAAQ,CAAC;IAChF;IACA,OAAO;AACT"}
|
|
@@ -82,6 +82,7 @@ export declare function productSaveFields(current: EditedProduct, nowMs: number)
|
|
|
82
82
|
url: string;
|
|
83
83
|
title?: string;
|
|
84
84
|
}>;
|
|
85
|
+
videoAccessProductIds?: string[];
|
|
85
86
|
relatedProductIds?: string[];
|
|
86
87
|
shipping?: import("./commerce").ProductShippingFacts;
|
|
87
88
|
giftCard?: boolean;
|
|
@@ -162,6 +163,7 @@ export declare function productEditWrite(fields: ReturnType<typeof productSaveFi
|
|
|
162
163
|
url: string;
|
|
163
164
|
title?: string;
|
|
164
165
|
}>;
|
|
166
|
+
videoAccessProductIds?: string[];
|
|
165
167
|
relatedProductIds?: string[];
|
|
166
168
|
shipping?: import("./commerce").ProductShippingFacts;
|
|
167
169
|
giftCard?: boolean;
|
|
@@ -237,6 +239,7 @@ export declare function productDuplicateFields(product: HostProduct & {
|
|
|
237
239
|
url: string;
|
|
238
240
|
title?: string;
|
|
239
241
|
}>;
|
|
242
|
+
videoAccessProductIds?: string[];
|
|
240
243
|
relatedProductIds?: string[];
|
|
241
244
|
shipping?: import("./commerce").ProductShippingFacts;
|
|
242
245
|
giftCard?: boolean;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* How a storefront subscription (`hosts/{hostId}/subscriptions`) reads to a
|
|
19
|
+
* person (AGL-4191): its status in words, the one date that matters next, and
|
|
20
|
+
* what it is worth a month. One copy for the console's Subscriptions list and
|
|
21
|
+
* the buyer's account page, so the merchant and the subscriber never read two
|
|
22
|
+
* different answers about the same subscription.
|
|
23
|
+
*/
|
|
24
|
+
export type SubscriptionBillingInterval = 'month' | 'year';
|
|
25
|
+
/** Stripe's subscription statuses, in the merchant's words. */
|
|
26
|
+
export declare const SUBSCRIPTION_STATUS_LABELS: Readonly<Record<string, string>>;
|
|
27
|
+
export declare const SUBSCRIPTION_STATUS_COLOR: Readonly<Record<string, 'success' | 'info' | 'warning' | 'error' | 'default'>>;
|
|
28
|
+
/** The statuses the console's filter offers, in the order a merchant scans them. */
|
|
29
|
+
export declare const SUBSCRIPTION_FILTER_STATUSES: readonly ["active", "trialing", "past_due", "unpaid", "incomplete", "canceled"];
|
|
30
|
+
/**
|
|
31
|
+
* The statuses that bring money in every cycle: what monthly recurring revenue
|
|
32
|
+
* counts. A trial has not paid yet, and `unpaid` has stopped paying; `past_due`
|
|
33
|
+
* stays in because Stripe is still collecting and the subscriber has not left,
|
|
34
|
+
* the same reason it stays live for access (`commerce-subscription-status.ts`).
|
|
35
|
+
*/
|
|
36
|
+
export declare const SUBSCRIPTION_PAYING_STATUSES: readonly ["active", "past_due"];
|
|
37
|
+
export declare function subscriptionStatusLabel(status: unknown): string;
|
|
38
|
+
export declare function subscriptionStatusColor(status: unknown): 'success' | 'info' | 'warning' | 'error' | 'default';
|
|
39
|
+
/** `month` or `year` from a stored value, or null for anything else. */
|
|
40
|
+
export declare function subscriptionInterval(value: unknown): SubscriptionBillingInterval | null;
|
|
41
|
+
/**
|
|
42
|
+
* A recurring charge as a monthly figure: a yearly price counts a twelfth.
|
|
43
|
+
* Tax is the government's, not the merchant's revenue, so it is left out.
|
|
44
|
+
* Rounded to whole cents.
|
|
45
|
+
*/
|
|
46
|
+
export declare function monthlyRecurringCents(totalCents: unknown, taxCents: unknown, interval: unknown): number;
|
|
47
|
+
/** The fields of a stored subscription the date line reads. */
|
|
48
|
+
export interface SubscriptionDateFields {
|
|
49
|
+
status?: unknown;
|
|
50
|
+
cancelAtPeriodEnd?: unknown;
|
|
51
|
+
currentPeriodEndMs?: unknown;
|
|
52
|
+
/** Set by each paid invoice; the fallback when Stripe sent no period end. */
|
|
53
|
+
paidThroughMs?: unknown;
|
|
54
|
+
}
|
|
55
|
+
export type SubscriptionDateKind = 'renews' | 'trialEnds' | 'ends' | 'ended' | 'paymentFailed' | 'awaitingPayment';
|
|
56
|
+
export interface SubscriptionDateLine {
|
|
57
|
+
kind: SubscriptionDateKind;
|
|
58
|
+
/** Absent where the line names no date ("Payment failed"). */
|
|
59
|
+
atMs?: number;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The one date that matters next for a subscription, or null when there is
|
|
63
|
+
* nothing honest to say.
|
|
64
|
+
*
|
|
65
|
+
* `cancelAtPeriodEnd` wins over a renewal: a subscriber who cancelled in the
|
|
66
|
+
* billing portal keeps access to the end of the period they paid for and is
|
|
67
|
+
* not charged again, so "Renews" would be a promise of a charge that will not
|
|
68
|
+
* happen. A failed payment names no date, because Stripe moves the period end
|
|
69
|
+
* forward while the unpaid invoice is retried, so that date is neither a
|
|
70
|
+
* renewal nor an end.
|
|
71
|
+
*/
|
|
72
|
+
export declare function subscriptionDateLine(subscription: SubscriptionDateFields): SubscriptionDateLine | null;
|
|
73
|
+
/** A short date in the reader's own locale: "Dec 4, 2026". */
|
|
74
|
+
export declare function formatSubscriptionDate(ms: number): string;
|
|
75
|
+
/** The date line in words: "Renews Dec 4, 2026", "Payment failed". */
|
|
76
|
+
export declare function subscriptionDateText(line: SubscriptionDateLine | null, formatDate?: (ms: number) => string): string;
|
|
77
|
+
/** "/month" or "/year", or "" for a stored value that is neither. */
|
|
78
|
+
export declare function subscriptionIntervalSuffix(interval: unknown): string;
|
|
79
|
+
/**
|
|
80
|
+
* What a subscription's plan is called: the line the subscriber bought, with
|
|
81
|
+
* its quantity when more than one, or the product id for a subscription sold
|
|
82
|
+
* before lines were stored (AGL-1732).
|
|
83
|
+
*/
|
|
84
|
+
export declare function subscriptionPlanName(subscription: {
|
|
85
|
+
lineItems?: Array<{
|
|
86
|
+
name?: string;
|
|
87
|
+
quantity?: number;
|
|
88
|
+
}>;
|
|
89
|
+
productId?: string;
|
|
90
|
+
}): string;
|