@aglyn/plugins-commerce 1.29.2 → 1.30.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.
Files changed (54) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/pos/pos-item-dialog.component.js +12 -0
  3. package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
  4. package/src/lib/components/console/pos-kiosk-page.component.js +3 -5
  5. package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
  6. package/src/lib/components/console/product-add-ons-fields.component.d.ts +11 -0
  7. package/src/lib/components/console/product-add-ons-fields.component.js +229 -13
  8. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  9. package/src/lib/components/console/products-hub-card.component.js +51 -14
  10. package/src/lib/components/console/products-hub-card.component.js.map +1 -1
  11. package/src/lib/components/console/quote-editor-dialog.component.js +38 -0
  12. package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
  13. package/src/lib/components/product-add-ons.d.ts +21 -0
  14. package/src/lib/components/product-add-ons.js +77 -1
  15. package/src/lib/components/product-add-ons.js.map +1 -1
  16. package/src/lib/components/product-builder-mockup.d.ts +1 -1
  17. package/src/lib/components/product-builder-mockup.js +17 -5
  18. package/src/lib/components/product-builder-mockup.js.map +1 -1
  19. package/src/lib/components/product-choice-cards.js +14 -2
  20. package/src/lib/components/product-choice-cards.js.map +1 -1
  21. package/src/lib/model/commerce-pos-kiosk.js +8 -2
  22. package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
  23. package/src/lib/model/commerce-pos-offline.d.ts +1 -1
  24. package/src/lib/model/commerce-pos-offline.js +8 -2
  25. package/src/lib/model/commerce-pos-offline.js.map +1 -1
  26. package/src/lib/model/commerce-quote-request.d.ts +1 -0
  27. package/src/lib/model/commerce-quote-request.js +6 -2
  28. package/src/lib/model/commerce-quote-request.js.map +1 -1
  29. package/src/lib/model/commerce-quotes.js +10 -5
  30. package/src/lib/model/commerce-quotes.js.map +1 -1
  31. package/src/lib/model/commerce-record-routes.d.ts +13 -1
  32. package/src/lib/model/commerce-record-routes.js +22 -2
  33. package/src/lib/model/commerce-record-routes.js.map +1 -1
  34. package/src/lib/model/commerce.js +1 -1
  35. package/src/lib/model/commerce.js.map +1 -1
  36. package/src/lib/model/product-modifiers.d.ts +53 -2
  37. package/src/lib/model/product-modifiers.js +127 -27
  38. package/src/lib/model/product-modifiers.js.map +1 -1
  39. package/src/lib/plan-entitlements.d.ts +1 -2
  40. package/src/lib/plan-entitlements.js +3 -12
  41. package/src/lib/plan-entitlements.js.map +1 -1
  42. package/src/lib/server/pos-kiosk.js +1 -4
  43. package/src/lib/server/pos-kiosk.js.map +1 -1
  44. package/src/lib/server/product.d.ts +5 -0
  45. package/src/lib/server/product.js +10 -2
  46. package/src/lib/server/product.js.map +1 -1
  47. package/src/lib/server/site-page-resolver.d.ts +12 -1
  48. package/src/lib/server/site-page-resolver.js +100 -9
  49. package/src/lib/server/site-page-resolver.js.map +1 -1
  50. package/src/lib/server.js +4 -2
  51. package/src/lib/server.js.map +1 -1
  52. package/src/lib/transfer/product-register-cells.d.ts +7 -0
  53. package/src/lib/transfer/product-register-cells.js +88 -10
  54. package/src/lib/transfer/product-register-cells.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-kiosk.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHmac, timingSafeEqual } from 'crypto'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler, PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport { resolveMediaSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport { pluginSmsAvailable } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport { planListQuery } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport {\n consumeRateLimit,\n firebaseAdmin,\n getLockdownVerdict,\n getOrgForHost,\n getPluginConfig,\n} from '@aglyn/tenant-data-admin'\nimport { applyListQuery } from '@aglyn/tenant-data-admin/server/list-query'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n STOREFRONT_CATALOG_BASE,\n STOREFRONT_CATALOG_DECLARATION,\n STOREFRONT_CATALOG_SORTS,\n} from '../constants/storefront-catalog-query'\nimport * as CommerceModel from '../model'\nimport { productOfferedOnKiosk } from '../model/commerce-kiosk-offer'\nimport { posKioskNameMatches } from '../model/commerce-kiosk-search'\nimport { posRegisterSettings, type PosRegisterSettings } from '../plugin-config'\nimport { posKioskSettings, type PosKioskSettings } from '../pos-kiosk-config'\nimport { verifyMemberPassword } from './membership'\nimport { authorizePosStaff, posIdempotencyKey, posQueryBody, posRequestBody, type PosStaff } from './pos-auth'\nimport {\n displayBranding,\n displayToken,\n posDisplayCurrency,\n resolveDisplayToken,\n type PosDeviceToken,\n} from './pos-display'\nimport { withPosKioskPrincipal } from './pos-kiosk-principal'\nimport { posOrderHandler } from './pos-order'\nimport { recordReceiptChoice, voidPosSale } from './pos-payment'\nimport { posPaymentId, posSaleSummary, readPosSale, type PosLiftedOrder } from './pos-sale'\nimport { posStripeTestMode, posTerminalAvailable } from './pos-stripe'\nimport {\n cancelPosCardPayment,\n createCardPresentIntent,\n createPosTerminalConnectionToken,\n refreshPosCardPayment,\n simulatePosReaderTap,\n startCardPresentPayment,\n} from './pos-terminal'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623): `/api/commerce/pos-kiosk`.\n *\n * ## Who is asking\n *\n * A kiosk is a register's paired screen with `mode: 'kiosk'` — the same\n * six-digit code and hashed device token as the customer display\n * (`pos-display.ts`), so pairing is one trust path, not two. It holds no\n * staff session. Every device action carries the token, and the gate below\n * re-checks, on every call, that the staff member whose code paired it may\n * still work this register (`admin`/`editor` on the site, `managePos`), that\n * the plan still includes POS, and that no lockdown covers them, the org or\n * the site. Demote them and the kiosk stops on its next tap.\n *\n * ## What it can reach\n *\n * Its own register's catalog, the orders IT opened (`kioskDeviceId`), and\n * nothing else: no staff names, no other customer's order, no register\n * state. A customer's email or phone goes straight onto their own order as\n * the receipt request and is never echoed back.\n *\n * ## Money\n *\n * The cart is priced by the register's own sale route (`pos-order.ts`), in\n * process, as an OPEN sale — the same tax, automatic promotions, platform\n * fee and idempotency as a cashier's sale, and none of a cashier's\n * discretion: no discount, no code, no customer, no stay. The amount a card\n * pays is always the server's balance; the kiosk names only a tip choice,\n * which is recomputed here from the store's own presets. Card payments are\n * the register's Stripe Terminal flow (AGL-3607) unchanged, and they stay\n * behind `STRIPE_TERMINAL_LIVE_ENABLED` exactly as the register's do.\n *\n * ## Staff\n *\n * `queue` and `take` are the register's: signed in and gated like a sale.\n * A queued (\"pay at counter\") order is an open sale like any other, and the\n * register takes payment on it through `commerce/pos-payment`.\n *=========================================*/\n\ntype Outcome = { status: number; body: Record<string, unknown> }\n\nconst DEVICE_READS = new Set(['context', 'catalog', 'sale'])\nconst STAFF_READS = new Set(['queue'])\n\ninterface KioskGate {\n device: PosDeviceToken\n /** The token hash prefix the kiosk's orders carry. */\n deviceId: string\n hostId: string\n registerId: string\n hostRef: FirebaseFirestore.DocumentReference\n /** The staff member who paired the kiosk; what it acts as. */\n uid: string\n orgId: string\n org: Record<string, any> | null\n register: Record<string, any>\n settings: PosRegisterSettings\n kiosk: PosKioskSettings\n}\n\n/** The prefix of a token row's id a kiosk's orders are stamped with. */\nexport function posKioskDeviceId(device: PosDeviceToken): string {\n return String(device.ref?.id ?? '').slice(0, 16)\n}\n\nfunction refuse(status: number, error: string): Outcome {\n return { status, body: { error } }\n}\n\n/** The kiosk's gate, asked again on every call. */\nasync function authorizeKiosk(\n req: PluginApiRequest,\n body: Record<string, any>,\n write: boolean,\n): Promise<KioskGate | Outcome> {\n const device = await resolveDisplayToken(displayToken(req, body))\n if (!device) return refuse(401, 'This kiosk is not paired.')\n if (device.mode !== 'kiosk') return refuse(403, 'This device is a customer display, not a kiosk.')\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(device.hostId)\n const [host, register] = await Promise.all([\n hostRef.get(),\n hostRef.collection('registers').doc(device.registerId).get(),\n ])\n if (!host.exists || !register.exists) return refuse(401, 'This kiosk is not paired.')\n // The member who paired it must still work the register here: the key\n // decides, not the site role (AGL-4047).\n const membership = device.createdBy\n ? await resolveOrgPermissions(device.createdBy, { hostId: device.hostId })\n : null\n if (!membership?.permissions?.managePos) {\n return refuse(403, 'This kiosk needs a staff member to pair it again.')\n }\n const owner = await getOrgForHost(device.hostId)\n if (!Aglyn.checkEntitlement(owner?.org as any, 'pos')) {\n return refuse(403, 'This kiosk is not available. Please order at the counter.')\n }\n const locked = await getLockdownVerdict({\n uid: device.createdBy,\n org: owner?.org as never,\n host: host.data() as never,\n intent: write ? 'write' : 'read',\n })\n if (locked) return { status: 423, body: { error: 'This kiosk is paused. Please order at the counter.', locked: true } }\n const orgId = String(owner?.org?.id ?? owner?.orgId ?? '')\n const config = await getPluginConfig(orgId || undefined, 'commerce', { hostId: device.hostId }).catch(\n () => ({}),\n )\n return {\n device,\n deviceId: posKioskDeviceId(device),\n hostId: device.hostId,\n registerId: device.registerId,\n hostRef,\n uid: device.createdBy,\n orgId,\n org: (owner?.org as Record<string, any>) ?? null,\n register: (register.data() ?? {}) as Record<string, any>,\n settings: posRegisterSettings(config),\n kiosk: posKioskSettings(config),\n }\n}\n\n/** One durable budget per kiosk and action; refused requests do nothing. */\nasync function withinBudget(gate: KioskGate, action: string, limit: number): Promise<boolean> {\n const rate = await consumeRateLimit(`pos-kiosk:${action}:${gate.deviceId}`, {\n limit,\n windowMs: 10 * 60 * 1000,\n })\n return rate.allowed\n}\n\n/** The register's card readers, when Terminal is switched on. */\nasync function registerReaders(gate: KioskGate): Promise<Array<{ id: string; label: string; status: string }>> {\n if (!posTerminalAvailable()) return []\n const snapshot = await gate.hostRef\n .collection('terminalReaders')\n .where('registerId', '==', gate.registerId)\n .limit(10)\n .get()\n return snapshot.docs.map((doc: any) => ({\n id: String(doc.id),\n label: String(doc.get('label') ?? 'Card reader'),\n status: String(doc.get('status') ?? 'offline'),\n }))\n}\n\n/** The reader this kiosk sends cards to: the one chosen in its settings, else the register's only one. */\nasync function kioskReaderId(gate: KioskGate): Promise<string | null> {\n const readers = await registerReaders(gate)\n const chosen = String(gate.device.data['kioskReaderId'] ?? '')\n if (chosen && readers.some((reader) => reader.id === chosen)) return chosen\n return readers.length === 1 ? readers[0]!.id : null\n}\n\n/** The receipt choices this kiosk can honor. */\nasync function receiptChannels(gate: KioskGate): Promise<CommerceModel.PosReceiptChannel[]> {\n const channels: CommerceModel.PosReceiptChannel[] = ['email']\n if (pluginSmsAvailable()) channels.push('sms')\n // Printed on the register's own receipt printer, so offered only when it has one.\n const printers = await gate.hostRef\n .collection('printers')\n .where('registerId', '==', gate.registerId)\n .limit(1)\n .get()\n .catch(() => null)\n if (printers && !printers.empty) channels.push('print')\n channels.push('none')\n return channels\n}\n\nasync function context(gate: KioskGate): Promise<Outcome> {\n const [branding, currency, reader, receipts] = await Promise.all([\n displayBranding(gate.hostId),\n posDisplayCurrency(gate.hostId),\n kioskReaderId(gate),\n receiptChannels(gate),\n ])\n const value: CommerceModel.PosKioskContext = {\n branding: { ...branding, message: gate.kiosk.welcome || 'Order here' },\n currency,\n tipping: { enabled: gate.settings.tippingEnabled, percentages: gate.settings.tipPercentages },\n payments: {\n reader: Boolean(reader),\n cardPresent: posTerminalAvailable(),\n payAtCounter: gate.kiosk.payAtCounter,\n },\n receipts,\n offerMarketing: gate.settings.displayMarketingOptIn,\n idleSeconds: gate.kiosk.idleSeconds,\n testMode: posStripeTestMode(),\n }\n return { status: 200, body: value as unknown as Record<string, unknown> }\n}\n\n/**\n * Whether a product may be sold at a kiosk at all: what the register sells,\n * less what a customer cannot be handed at a counter — a subscription-only\n * product, a gift card whose code needs issuing, and a digital download.\n */\nexport function posKioskSellable(product: CommerceModel.HostProduct): boolean {\n if (product.status !== 'active') return false\n // The merchant's own choice of what the kiosk offers (AGL-4038), for any\n // product: \"Offer on the kiosk\" in the product editor.\n if (!productOfferedOnKiosk(product)) return false\n if (product.subscription && !product.subscriptionOptional) return false\n if (product.giftCard) return false\n if (product.type === 'digital') return false\n return (product.variants ?? []).some((variant) => posKioskVariantOffered(product, variant))\n}\n\n/** A variant the kiosk may sell: priced, and offered by the merchant's choice (AGL-4038). */\nexport function posKioskVariantOffered(\n product: CommerceModel.HostProduct,\n variant: CommerceModel.ProductVariant,\n): boolean {\n return CommerceModel.variantHasPrice(variant) && productOfferedOnKiosk(product, variant.id)\n}\n\n/** A product as the kiosk may show it: names, prices and choices, nothing else. */\nexport function posKioskProduct(\n id: string,\n product: CommerceModel.HostProduct,\n hostId: string,\n): CommerceModel.PosKioskProduct {\n const image = resolveMediaSrc(product.mediaUrls?.[0], { hostId })\n const description = String(product.description ?? '').trim().slice(0, 280)\n return {\n id,\n name: String(product.name ?? '').slice(0, 120),\n ...(description ? { description } : {}),\n ...(image ? { imageUrl: image } : {}),\n categoryIds: (product.categoryIds ?? []).slice(0, 20),\n options: (product.options ?? []).map((option) => ({ name: option.name, values: [...option.values] })),\n variants: (product.variants ?? [])\n .filter((variant) => posKioskVariantOffered(product, variant))\n .map((variant) => ({\n id: variant.id,\n options: { ...(variant.options ?? {}) },\n priceCents: Math.round(Number(variant.priceUsd) * 100),\n soldOut: Boolean(CommerceModel.stockShortfall(product, variant.id, 1)),\n })),\n modifierGroups: CommerceModel.productModifierGroups(product),\n }\n}\n\n/**\n * How many pages of the query one answer may read looking for products the\n * kiosk can sell. What a kiosk can't sell isn't on any product as a field a\n * query can ask, so it is answered row by row, and a page of those must not\n * cost the store the products named after them. The ceiling is the read cost\n * of a catalog that is nearly all held back; past it the answer says\n * `truncated`, and a search still reaches any name.\n */\nconst POS_KIOSK_CATALOG_PAGES = 5\n\n/** The first page of sellable products in name order, however many rows that takes to find. */\nasync function sellableProducts(\n query: FirebaseFirestore.Query,\n hostId: string,\n typed: string,\n): Promise<{ products: CommerceModel.PosKioskProduct[]; truncated: boolean }> {\n const limit = CommerceModel.POS_KIOSK_CATALOG_LIMIT\n const products: CommerceModel.PosKioskProduct[] = []\n let after: FirebaseFirestore.QueryDocumentSnapshot | undefined\n for (let page = 0; page < POS_KIOSK_CATALOG_PAGES; page += 1) {\n const snapshot = await (after ? query.startAfter(after) : query).limit(limit).get()\n for (const doc of snapshot.docs) {\n const product = CommerceModel.liftLegacyProduct(doc.data())\n if (!posKioskSellable(product)) continue\n if (!posKioskNameMatches(String(product.name ?? ''), typed)) continue\n products.push(posKioskProduct(String(doc.id), product, hostId))\n }\n // A short page is the end of the query: all of it has been read.\n const ended = snapshot.docs.length < limit\n if (ended || products.length >= limit) {\n return { products: products.slice(0, limit), truncated: products.length > limit || !ended }\n }\n after = snapshot.docs[snapshot.docs.length - 1]\n }\n return { products, truncated: true }\n}\n\nasync function catalog(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n const categoryId = String(body['categoryId'] ?? '')\n if (categoryId && !/^[A-Za-z0-9_-]{1,128}$/.test(categoryId)) return refuse(400, 'Unknown category')\n const typed = String(body['search'] ?? '').trim().slice(0, 120)\n if (typed && !(await withinBudget(gate, 'search', 600))) return refuse(429, 'Too many tries. Wait a moment.')\n // The storefront catalog's own query (AGL-3321), and its composites: live,\n // active, by name. A category or the first word typed is a clause on it,\n // never a filter over what was read, and a search takes the one array\n // clause when both are asked.\n const plan = planListQuery(\n STOREFRONT_CATALOG_DECLARATION,\n {\n base: STOREFRONT_CATALOG_BASE,\n clauses: categoryId ? [{ field: 'category', op: 'contains', value: categoryId }] : [],\n search: typed.split(/\\s+/).filter(Boolean),\n sort: STOREFRONT_CATALOG_SORTS.name,\n },\n nameSearchNormalizers,\n )\n const [sellable, categories, currency] = await Promise.all([\n sellableProducts(applyListQuery(gate.hostRef.collection('products'), plan), gate.hostId, typed),\n // A search answers products alone: the menu already has its chips.\n typed ? null : gate.hostRef.collection('productCategories').limit(30).get(),\n posDisplayCurrency(gate.hostId),\n ])\n const value: CommerceModel.PosKioskCatalog = {\n products: sellable.products,\n categories: (categories?.docs ?? []).map((doc: any) => ({\n id: String(doc.id),\n name: String(doc.get('name') ?? 'Category').slice(0, 60),\n })),\n currency,\n ...(sellable.truncated ? { truncated: true } : {}),\n }\n return { status: 200, body: value as unknown as Record<string, unknown> }\n}\n\n/** An order as its kiosk reads it back; null for any order this kiosk did not open. */\nexport function posKioskSaleView(\n order: PosLiftedOrder | null,\n deviceId: string,\n): CommerceModel.PosKioskSale | null {\n if (!order || order.posSource !== 'kiosk' || order.kioskDeviceId !== deviceId) return null\n const summary = posSaleSummary(order)\n const status: CommerceModel.PosKioskSaleStatus =\n order.status === 'paid'\n ? 'paid'\n : order.status === 'pending'\n ? order.kioskQueueRegisterId\n ? 'queued'\n : 'open'\n : 'voided'\n const card = [...summary.payments]\n .reverse()\n .find((payment) => CommerceModel.isCardPaymentMethod(payment.method))\n return {\n orderId: order.$id,\n number: Number(order.number ?? 0),\n status,\n lines: (order.lineItems ?? []).map((line) => ({\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n quantity: line.quantity,\n amountCents: line.unitAmountCents * line.quantity,\n })),\n itemsCents: Number(order.totals?.itemsCents ?? 0),\n discountCents: Number(order.totals?.discountCents ?? 0),\n taxCents: Number(order.totals?.taxCents ?? 0),\n totalCents: summary.totalCents,\n tipCents: summary.tipCents,\n paidCents: summary.paidCents,\n dueCents: summary.dueCents,\n payment: card\n ? {\n id: card.id,\n status: card.status,\n ...(card.failureMessage ? { failureMessage: card.failureMessage } : {}),\n }\n : null,\n }\n}\n\n/** This kiosk's order, or a refusal that says nothing about anyone else's. */\nasync function readOwnSale(\n gate: KioskGate,\n rawOrderId: unknown,\n): Promise<{ order: PosLiftedOrder; view: CommerceModel.PosKioskSale } | Outcome> {\n const orderId = String(rawOrderId ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(orderId)) return refuse(404, 'Unknown order')\n const order = await readPosSale(gate.hostId, orderId)\n const view = posKioskSaleView(order, gate.deviceId)\n if (!order || !view) return refuse(404, 'Unknown order')\n return { order, view }\n}\n\n/** The response the in-process sale route wrote. */\nfunction recorder() {\n const result = { status: 500, body: {} as Record<string, any> }\n const res = {\n status(code: number) {\n result.status = code\n return res\n },\n json(value: unknown) {\n result.body = (value ?? {}) as Record<string, any>\n },\n send() {},\n setHeader() {},\n redirect() {},\n end() {},\n } as unknown as PluginApiResponse\n return { res, result }\n}\n\nasync function checkout(\n gate: KioskGate,\n req: PluginApiRequest,\n body: Record<string, any>,\n): Promise<Outcome> {\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return refuse(400, 'Missing Idempotency-Key')\n const cart = CommerceModel.sanitizePosKioskLines(body['lines'])\n if ('error' in cart) return refuse(400, cart.error)\n if (!(await withinBudget(gate, 'checkout', 40))) {\n return refuse(429, 'Too many orders from this kiosk. Please order at the counter.')\n }\n // What a customer may buy here, read from the product documents before\n // anything is priced: the sale route warns a cashier about stock and sells\n // anyway (the goods are in their hand); a kiosk refuses what is sold out.\n const ids = [...new Set(cart.lines.map((line) => line.productId))]\n const snapshots = await Promise.all(ids.map((id) => gate.hostRef.collection('products').doc(id).get()))\n const products = new Map(\n snapshots.map((snapshot: any) => [\n String(snapshot.id),\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data()) : null,\n ]),\n )\n for (const line of cart.lines) {\n const product = products.get(line.productId)\n if (!product || (product as { deletedAt?: unknown }).deletedAt || !posKioskSellable(product)) {\n return refuse(409, 'An item in your cart is no longer available. Remove it and try again.')\n }\n const variant = line.variantId\n ? product.variants.find((candidate) => candidate.id === line.variantId)\n : product.variants[0]\n if (!variant || !posKioskVariantOffered(product, variant)) {\n return refuse(409, `${product.name} is no longer available. Remove it and try again.`)\n }\n const wanted = cart.lines\n .filter((other) => other.productId === line.productId && (other.variantId ?? '') === (line.variantId ?? ''))\n .reduce((sum, other) => sum + other.quantity, 0)\n if (CommerceModel.stockShortfall(product, variant.id, wanted)) {\n return refuse(409, `${product.name} is sold out. Remove it and try again.`)\n }\n }\n const { res, result } = recorder()\n const priced = withPosKioskPrincipal(\n {\n method: 'POST',\n headers: { 'idempotency-key': `kiosk:${gate.deviceId}:${attemptKey}` },\n query: {},\n cookies: {},\n socket: req.socket,\n body: {\n hostId: gate.hostId,\n registerId: gate.registerId,\n payment: 'open',\n lines: cart.lines,\n ...(typeof gate.register['locationId'] === 'string' && gate.register['locationId']\n ? { locationId: gate.register['locationId'] }\n : {}),\n },\n } as PluginApiRequest,\n { uid: gate.uid, registerId: gate.registerId, deviceId: gate.deviceId },\n )\n await posOrderHandler(priced, res)\n if (result.status !== 200 || !result.body['orderId']) {\n // A refusal about a product names it, and the customer can fix it. One\n // about the store — a shift, the tax setup, the plan — is the staff's to\n // fix, and the customer is sent to the counter.\n console.warn('[pos-kiosk] sale refused', gate.hostId, result.status, result.body['error'])\n if (result.status === 400 && result.body['error']) return refuse(400, String(result.body['error']))\n return refuse(\n result.status === 429 ? 429 : 409,\n 'This kiosk cannot take orders right now. Please order at the counter.',\n )\n }\n const own = await readOwnSale(gate, result.body['orderId'])\n if ('status' in own) return own\n if (own.view.totalCents <= 0) {\n // Nothing to take a card for, and nothing a kiosk should hand out free.\n await voidPosSale(kioskStaff(gate), own.order.$id).catch(() => undefined)\n return refuse(409, 'Please ask at the counter for this order.')\n }\n return { status: 200, body: { sale: own.view } }\n}\n\n/** The kiosk, as the register's payment helpers expect the person at the till. */\nfunction kioskStaff(gate: KioskGate): PosStaff {\n return { uid: gate.uid, hostId: gate.hostId, orgId: gate.orgId, org: gate.org }\n}\n\nasync function pay(gate: KioskGate, req: PluginApiRequest, body: Record<string, any>): Promise<Outcome> {\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return refuse(400, 'Missing Idempotency-Key')\n const method = String(body['method'] ?? '')\n if (method !== 'reader' && method !== 'tap') return refuse(400, 'Choose how to pay.')\n if (!posTerminalAvailable()) return refuse(409, 'Card payments are not available on this kiosk.')\n if (!(await withinBudget(gate, 'pay', 60))) return refuse(429, 'Too many tries. Please pay at the counter.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status !== 'open') return refuse(409, 'This order is no longer waiting for payment.')\n const paymentId = posPaymentId(own.order.$id, `kiosk:${attemptKey}`)\n // A retried press finds the payment its first press reserved, for the\n // amount and tip that press chose: the reservation is already out of the\n // balance, so the balance alone would read as nothing left to pay.\n const pressed = CommerceModel.orderPayments(own.order).find((payment) => payment.id === paymentId)\n const amountCents = pressed ? pressed.amountCents : posSaleSummary(own.order).tenderableCents\n if (!(amountCents > 0)) return refuse(409, 'Nothing is left to pay on this order.')\n const tipCents = pressed ? Number(pressed.tipCents ?? 0) : CommerceModel.posKioskTipCents(body['tipChoice'], {\n baseCents: amountCents,\n enabled: gate.settings.tippingEnabled,\n percentages: gate.settings.tipPercentages,\n percent: body['tipPercent'],\n cents: body['tipCents'],\n })\n if (tipCents === null) return refuse(400, 'Choose one of the tips shown, or no tip.')\n const start = {\n hostId: gate.hostId,\n orderId: own.order.$id,\n paymentId,\n amountCents,\n tipCents,\n cashierId: gate.uid,\n org: gate.org,\n }\n let outcome: Awaited<ReturnType<typeof createCardPresentIntent>>\n if (method === 'reader') {\n const readerId = await kioskReaderId(gate)\n if (!readerId) return refuse(409, 'No card reader is set up for this kiosk. Please pay at the counter.')\n // The kiosk asked for the tip on its own screen: the reader must not ask again.\n outcome = await startCardPresentPayment({\n ...start,\n readerId,\n settings: { ...gate.settings, tippingEnabled: false },\n })\n } else {\n // Tap to Pay: collected by the native POS app's Stripe Terminal SDK\n // against this server-made intent (AGL-3618), settled like any reader.\n outcome = await createCardPresentIntent(start)\n }\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n const view = posKioskSaleView(outcome.order, gate.deviceId)\n return {\n status: 200,\n body: {\n sale: view,\n ...(outcome.payment ? { paymentId: outcome.payment.id } : {}),\n ...(outcome.clientSecret ? { clientSecret: outcome.clientSecret } : {}),\n ...(outcome.paymentIntentId ? { paymentIntentId: outcome.paymentIntentId } : {}),\n },\n }\n}\n\n/** A card payment on this kiosk's own order: refreshed, canceled or (test mode) tapped. */\nasync function cardStep(\n gate: KioskGate,\n body: Record<string, any>,\n step: 'payment-status' | 'cancel-payment' | 'simulate',\n): Promise<Outcome> {\n if (!(await withinBudget(gate, 'card', 900))) return refuse(429, 'Too many tries. Wait a moment.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n const paymentId = String(body['paymentId'] ?? '')\n if (!own.order.payments?.some((payment) => payment.id === paymentId)) return refuse(404, 'Unknown payment')\n const ref = { hostId: gate.hostId, orderId: own.order.$id, paymentId }\n let outcome\n if (step === 'payment-status') outcome = await refreshPosCardPayment(ref)\n else if (step === 'cancel-payment') outcome = await cancelPosCardPayment(ref)\n else {\n if (!posStripeTestMode()) return refuse(404, 'Unknown action')\n outcome = await simulatePosReaderTap({ ...ref, cardNumber: String(body['cardNumber'] ?? '') })\n }\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n return { status: 200, body: { sale: posKioskSaleView(outcome.order, gate.deviceId) } }\n}\n\n/** \"Pay at counter\": the order joins the register's queue with its number. */\nasync function sendToCounter(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n if (!gate.kiosk.payAtCounter) return refuse(409, 'Please pay here with a card.')\n if (!(await withinBudget(gate, 'counter', 40))) return refuse(429, 'Too many orders from this kiosk.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status === 'queued') return { status: 200, body: { sale: own.view } }\n const ref = gate.hostRef.collection('orders').doc(own.order.$id)\n const firestore = firebaseAdmin.app().firestore()\n // In a transaction: a card that settled between the customer's two taps\n // leaves a paid order, which never joins a queue.\n const queued = await firestore.runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n if (!fresh.exists || fresh.get('status') !== 'pending') return false\n const payments = CommerceModel.orderPayments(fresh.data() as any)\n if (payments.some((payment) => payment.status === 'pending' || payment.status === 'succeeded')) {\n return false\n }\n transaction.set(\n ref,\n {\n kioskQueueRegisterId: gate.registerId,\n kioskQueuedAtMs: Date.now(),\n timeline: CommerceModel.appendOrderEvent(\n { ...(fresh.data() as any) },\n 'pos-kiosk-pay-at-counter',\n 'Sent to the counter from the self-service kiosk',\n ),\n },\n { merge: true },\n )\n return true\n })\n if (!queued) return refuse(409, 'This order is already being paid. Check the screen.')\n const after = await readOwnSale(gate, own.order.$id)\n if ('status' in after) return after\n return { status: 200, body: { sale: after.view } }\n}\n\nasync function receipt(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n if (!(await withinBudget(gate, 'receipt', 40))) return refuse(429, 'Too many tries.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status !== 'paid') return refuse(409, 'Your receipt is ready once your order is paid.')\n const channel = String(body['channel'] ?? '') as CommerceModel.PosReceiptChannel\n if (!(await receiptChannels(gate)).includes(channel)) return refuse(400, 'Choose a receipt shown on the screen.')\n const outcome = await recordReceiptChoice(kioskStaff(gate), own.order.$id, {\n channel,\n to: body['to'],\n marketingOptIn: gate.settings.displayMarketingOptIn && body['marketingOptIn'] === true,\n })\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n // The address is on the order now; nothing of it comes back to the screen.\n return { status: 200, body: { ok: true } }\n}\n\n/**\n * The idle reset and \"Start over\": an order this kiosk opened and nobody\n * paid is voided, so it holds no promotion slot and no stock. A queued or\n * paid order is left exactly as it is.\n */\nasync function abandon(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status !== 'open') return { status: 200, body: { sale: own.view } }\n // Money that already moved is the counter's to settle, never a screen's\n // to refund on its own.\n if (CommerceModel.orderPayments(own.order).some((payment) => payment.status === 'succeeded')) {\n return { status: 200, body: { sale: own.view } }\n }\n const outcome = await voidPosSale(kioskStaff(gate), own.order.$id)\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n return { status: 200, body: { sale: posKioskSaleView(outcome.order, gate.deviceId) } }\n}\n\n/*==========================================\n * STAFF UNLOCK.\n *\n * The register's staff PINs (AGL-3609), checked on the server: a PIN at a\n * kiosk unlocks its settings — choosing the card reader, leaving kiosk mode\n * — for a few minutes. A kiosk faces the public, so it shows no roster of\n * names; the PIN alone is checked against every member of the site who may\n * work the register. The attempt is claimed on the device's own token row\n * BEFORE any PIN is checked, so a burst of guesses gets\n * POS_KIOSK_UNLOCK_MAX_ATTEMPTS in the lockout window and no more, and a\n * member whose own PIN is locked at the register cannot unlock a kiosk\n * either.\n *=========================================*/\n\nfunction unlockSecret(): string {\n const secret = process.env['TOKEN_SIGNING_SECRET']\n if (!secret) throw new Error('TOKEN_SIGNING_SECRET is not configured')\n return secret\n}\n\nfunction signUnlock(payload: string): string {\n return createHmac('sha256', unlockSecret()).update(`pos-kiosk-unlock:${payload}`).digest('hex')\n}\n\n/** A short-lived, signed \"staff unlocked THIS kiosk\". */\nexport function mintPosKioskUnlock(deviceId: string, memberUid: string, nowMs: number): {\n unlock: string\n expiresAtMs: number\n} {\n const expiresAtMs = nowMs + CommerceModel.POS_KIOSK_UNLOCK_TTL_MS\n const payload = Buffer.from(JSON.stringify({ v: 1, d: deviceId, u: memberUid, e: expiresAtMs })).toString(\n 'base64url',\n )\n return { unlock: `${payload}.${signUnlock(payload)}`, expiresAtMs }\n}\n\n/** The member a valid unlock names for this kiosk, or null. */\nexport function readPosKioskUnlock(token: unknown, deviceId: string, nowMs: number): string | null {\n const value = typeof token === 'string' ? token.trim() : ''\n const dot = value.lastIndexOf('.')\n if (dot <= 0 || value.length > 1000) return null\n const payload = value.slice(0, dot)\n let expected: string\n try {\n expected = signUnlock(payload)\n } catch {\n return null\n }\n const a = Buffer.from(value.slice(dot + 1))\n const b = Buffer.from(expected)\n if (a.length !== b.length || !timingSafeEqual(new Uint8Array(a), new Uint8Array(b))) return null\n try {\n const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))\n if (claims?.v !== 1 || claims.d !== deviceId || typeof claims.u !== 'string' || !(Number(claims.e) > nowMs)) {\n return null\n }\n return claims.u\n } catch {\n return null\n }\n}\n\n/** Whether a member may still unlock: `managePos` here today, whatever their site role (AGL-4047). */\nasync function mayUnlock(gate: KioskGate, memberUid: string): Promise<boolean> {\n const membership = await resolveOrgPermissions(memberUid, { hostId: gate.hostId })\n return membership?.permissions?.managePos === true\n}\n\nasync function unlock(gate: KioskGate, req: PluginApiRequest, body: Record<string, any>): Promise<Outcome> {\n const pin = String(body['pin'] ?? '')\n if (!/^\\d{4,6}$/.test(pin)) return refuse(400, 'Enter your staff PIN.')\n const address = String(req.socket?.remoteAddress ?? '') || 'no-address'\n const rate = await consumeRateLimit(`pos-kiosk-unlock:${address}`, { limit: 20, windowMs: 15 * 60 * 1000 })\n if (!rate.allowed) return refuse(429, 'Too many tries. Wait a few minutes and try again.')\n try {\n unlockSecret()\n } catch {\n return refuse(501, 'Staff PINs are not configured on this server.')\n }\n const firestore = firebaseAdmin.app().firestore()\n const now = Date.now()\n const claim = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(gate.device.ref)\n if (!snapshot.exists) return { kind: 'gone' as const }\n const lockedUntilMs = Number(snapshot.get('kioskUnlockLockedUntilMs') ?? 0)\n if (lockedUntilMs > now) return { kind: 'locked' as const, lockedUntilMs }\n const failed = lockedUntilMs ? 0 : Number(snapshot.get('kioskUnlockFailures') ?? 0)\n if (failed >= CommerceModel.POS_KIOSK_UNLOCK_MAX_ATTEMPTS) {\n const until = now + CommerceModel.POS_KIOSK_UNLOCK_LOCKOUT_MS\n transaction.update(gate.device.ref, { kioskUnlockLockedUntilMs: until, kioskUnlockFailures: 0 })\n return { kind: 'locked' as const, lockedUntilMs: until }\n }\n transaction.update(gate.device.ref, { kioskUnlockFailures: failed + 1, kioskUnlockLockedUntilMs: null })\n return { kind: 'claimed' as const, attempt: failed + 1 }\n })\n if (claim.kind === 'gone') return refuse(401, 'This kiosk is not paired.')\n if (claim.kind === 'locked') {\n return { status: 423, body: { error: 'Too many wrong PINs. Try again later.', lockedUntilMs: claim.lockedUntilMs } }\n }\n // Members of this site only, any role: `mayUnlock` below asks the key.\n const host = await gate.hostRef.get()\n const roles = (host.get('memberRoles') ?? {}) as Record<string, string>\n const pins = await gate.hostRef.collection('posStaffPins').limit(50).get()\n let matched = ''\n for (const doc of pins.docs) {\n const uid = String(doc.id)\n if (!roles[uid]) continue\n if (Number(doc.get('lockedUntilMs') ?? 0) > now) continue\n const hash = String(doc.get('pinScrypt') ?? '')\n if (hash && verifyMemberPassword(pin, hash)) {\n matched = uid\n break\n }\n }\n if (!matched || !(await mayUnlock(gate, matched))) {\n const left = CommerceModel.POS_KIOSK_UNLOCK_MAX_ATTEMPTS - claim.attempt\n if (left <= 0) {\n await gate.device.ref.update({\n kioskUnlockLockedUntilMs: now + CommerceModel.POS_KIOSK_UNLOCK_LOCKOUT_MS,\n kioskUnlockFailures: 0,\n })\n return { status: 423, body: { error: 'Too many wrong PINs. Try again later.' } }\n }\n return { status: 401, body: { error: `That PIN is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.` } }\n }\n await gate.device.ref.update({ kioskUnlockFailures: 0, kioskUnlockLockedUntilMs: null })\n const minted = mintPosKioskUnlock(gate.deviceId, matched, now)\n return { status: 200, body: minted }\n}\n\nasync function staffSettings(\n gate: KioskGate,\n body: Record<string, any>,\n action: 'settings' | 'set-reader' | 'exit',\n): Promise<Outcome> {\n const memberUid = readPosKioskUnlock(body['unlock'], gate.deviceId, Date.now())\n if (!memberUid || !(await mayUnlock(gate, memberUid))) return refuse(401, 'Enter your staff PIN again.')\n if (action === 'exit') {\n // Leaving kiosk mode unpairs the device: a new code from the register\n // is the only way back.\n await gate.device.ref.delete()\n return { status: 200, body: { ok: true } }\n }\n const readers = await registerReaders(gate)\n let data = gate.device.data\n if (action === 'set-reader') {\n const readerId = String(body['readerId'] ?? '')\n if (readerId && !readers.some((reader) => reader.id === readerId)) {\n return refuse(404, 'That card reader is not on this register.')\n }\n await gate.device.ref.set({ kioskReaderId: readerId || null }, { merge: true })\n data = { ...data, kioskReaderId: readerId || null }\n }\n const chosen = await kioskReaderId({ ...gate, device: { ...gate.device, data } })\n return {\n status: 200,\n body: {\n readers,\n readerId: chosen,\n label: String(gate.device.data['label'] ?? 'Self-service kiosk'),\n },\n }\n}\n\n/** A Terminal SDK connection token for the native app's Tap to Pay, scoped to the site's Location. */\nasync function connectionToken(gate: KioskGate): Promise<Outcome> {\n if (!posTerminalAvailable()) return refuse(409, 'Card payments are not available on this kiosk.')\n if (!(await withinBudget(gate, 'connection-token', 60))) return refuse(429, 'Too many tries.')\n const token = await createPosTerminalConnectionToken(gate.hostId)\n if (!token) return refuse(409, 'Set up a card reader location for this site first.')\n return { status: 200, body: token }\n}\n\n/*==========================================\n * THE REGISTER'S SIDE: the queue of \"pay at counter\" orders.\n *=========================================*/\n\nexport interface PosKioskQueueEntry {\n orderId: string\n number: number\n queuedAtMs: number\n totalCents: number\n itemCount: number\n}\n\nasync function staffAction(req: PluginApiRequest, body: Record<string, any>, action: string): Promise<Outcome> {\n const hostId = String(body['hostId'] ?? '')\n const gate = await authorizePosStaff(req, hostId)\n if ('error' in gate) return refuse(gate.status, gate.error)\n const registerId = String(body['registerId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(registerId)) return refuse(400, 'Missing registerId')\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n if (!(await hostRef.collection('registers').doc(registerId).get()).exists) {\n return refuse(404, 'Unknown register')\n }\n if (action === 'queue') {\n // `kioskQueueRegisterId ==, status ==, kioskQueuedAtMs ASC`, declared in\n // the index file: the oldest order first, as a counter serves them.\n const snapshot = await hostRef\n .collection('orders')\n .where('kioskQueueRegisterId', '==', registerId)\n .where('status', '==', 'pending')\n .orderBy('kioskQueuedAtMs', 'asc')\n .limit(25)\n .get()\n const entries: PosKioskQueueEntry[] = snapshot.docs.map((doc: any) => {\n const order = CommerceModel.liftLegacyOrder(doc.data()) as CommerceModel.HostOrder\n return {\n orderId: String(doc.id),\n number: Number(order.number ?? 0),\n queuedAtMs: Number(order.kioskQueuedAtMs ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n itemCount: (order.lineItems ?? []).reduce((sum, line) => sum + line.quantity, 0),\n }\n })\n return { status: 200, body: { entries, currency: await posDisplayCurrency(hostId) } }\n }\n // `take`: the queued order, as the register loads it into its tender panel.\n const orderId = String(body['orderId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(orderId)) return refuse(400, 'Missing orderId')\n const order = await readPosSale(hostId, orderId)\n if (!order || order.kioskQueueRegisterId !== registerId) return refuse(404, 'Unknown order')\n if (order.status !== 'pending') return refuse(409, 'This order is no longer waiting for payment.')\n return {\n status: 200,\n body: {\n sale: posSaleSummary(order),\n number: Number(order.number ?? 0),\n lines: (order.lineItems ?? []).map((line) => ({\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n unitAmountCents: line.unitAmountCents,\n quantity: line.quantity,\n ...(line.modifiers?.length\n ? { modifiers: line.modifiers.map((modifier) => ({ groupId: modifier.groupId, optionId: modifier.optionId })) }\n : {}),\n })),\n },\n }\n}\n\nexport async function handlePosKiosk(req: PluginApiRequest): Promise<Outcome> {\n const body = req.method === 'GET' ? posQueryBody(req) : posRequestBody(req)\n const action = String(body['action'] ?? '')\n const read = DEVICE_READS.has(action) || STAFF_READS.has(action)\n if (!(req.method === 'POST' || (req.method === 'GET' && read))) {\n return refuse(405, 'Method not allowed')\n }\n if (action === 'queue' || action === 'take') return await staffAction(req, body, action)\n const gate = await authorizeKiosk(req, body, !read)\n if ('status' in gate) return gate\n switch (action) {\n case 'context':\n return await context(gate)\n case 'catalog':\n return await catalog(gate, body)\n case 'sale': {\n const own = await readOwnSale(gate, body['orderId'])\n return 'status' in own ? own : { status: 200, body: { sale: own.view } }\n }\n case 'checkout':\n return await checkout(gate, req, body)\n case 'pay':\n return await pay(gate, req, body)\n case 'payment-status':\n case 'cancel-payment':\n case 'simulate':\n return await cardStep(gate, body, action)\n case 'counter':\n return await sendToCounter(gate, body)\n case 'receipt':\n return await receipt(gate, body)\n case 'abandon':\n return await abandon(gate, body)\n case 'connection-token':\n return await connectionToken(gate)\n case 'unlock':\n return await unlock(gate, req, body)\n case 'settings':\n case 'set-reader':\n case 'exit':\n return await staffSettings(gate, body, action)\n default:\n return refuse(400, 'Unknown action')\n }\n}\n\n/** `GET|POST /api/commerce/pos-kiosk`. */\nexport const posKioskHandler: PluginApiHandler = async (req, res) => {\n res.setHeader('Cache-Control', 'no-store')\n try {\n const outcome = await handlePosKiosk(req)\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n console.error('[pos-kiosk]', error)\n return res.status(500).json({ error: 'Something went wrong. Please order at the counter.' })\n }\n}\n"],"names":["createHmac","timingSafeEqual","Aglyn","resolveMediaSrc","nameSearchNormalizers","pluginSmsAvailable","planListQuery","consumeRateLimit","firebaseAdmin","getLockdownVerdict","getOrgForHost","getPluginConfig","applyListQuery","resolveOrgPermissions","STOREFRONT_CATALOG_BASE","STOREFRONT_CATALOG_DECLARATION","STOREFRONT_CATALOG_SORTS","CommerceModel","productOfferedOnKiosk","posKioskNameMatches","posRegisterSettings","posKioskSettings","verifyMemberPassword","authorizePosStaff","posIdempotencyKey","posQueryBody","posRequestBody","displayBranding","displayToken","posDisplayCurrency","resolveDisplayToken","withPosKioskPrincipal","posOrderHandler","recordReceiptChoice","voidPosSale","posPaymentId","posSaleSummary","readPosSale","posStripeTestMode","posTerminalAvailable","cancelPosCardPayment","createCardPresentIntent","createPosTerminalConnectionToken","refreshPosCardPayment","simulatePosReaderTap","startCardPresentPayment","DEVICE_READS","Set","STAFF_READS","posKioskDeviceId","device","String","ref","id","slice","refuse","status","error","body","authorizeKiosk","req","write","owner","register","membership","mode","firestore","app","hostRef","collection","doc","hostId","host","Promise","all","get","registerId","exists","createdBy","permissions","managePos","checkEntitlement","org","locked","uid","data","intent","orgId","config","undefined","catch","deviceId","settings","kiosk","withinBudget","gate","action","limit","rate","windowMs","allowed","registerReaders","snapshot","where","docs","map","label","kioskReaderId","readers","chosen","some","reader","length","receiptChannels","channels","push","printers","empty","context","branding","currency","receipts","value","message","welcome","tipping","enabled","tippingEnabled","percentages","tipPercentages","payments","Boolean","cardPresent","payAtCounter","offerMarketing","displayMarketingOptIn","idleSeconds","testMode","posKioskSellable","product","subscription","subscriptionOptional","giftCard","type","variants","variant","posKioskVariantOffered","variantHasPrice","posKioskProduct","image","mediaUrls","description","trim","name","imageUrl","categoryIds","options","option","values","filter","priceCents","Math","round","Number","priceUsd","soldOut","stockShortfall","modifierGroups","productModifierGroups","POS_KIOSK_CATALOG_PAGES","sellableProducts","query","typed","POS_KIOSK_CATALOG_LIMIT","products","after","page","startAfter","liftLegacyProduct","ended","truncated","catalog","categoryId","test","plan","base","clauses","field","op","search","split","sort","sellable","categories","posKioskSaleView","order","posSource","kioskDeviceId","summary","kioskQueueRegisterId","card","reverse","find","payment","isCardPaymentMethod","method","orderId","$id","number","lines","lineItems","line","variantLabel","quantity","amountCents","unitAmountCents","itemsCents","totals","discountCents","taxCents","totalCents","tipCents","paidCents","dueCents","failureMessage","readOwnSale","rawOrderId","view","recorder","result","res","code","json","send","setHeader","redirect","end","checkout","attemptKey","cart","sanitizePosKioskLines","ids","productId","snapshots","Map","deletedAt","variantId","candidate","wanted","other","reduce","sum","priced","headers","cookies","socket","locationId","console","warn","own","kioskStaff","sale","pay","pressed","paymentId","orderPayments","tenderableCents","posKioskTipCents","baseCents","percent","cents","start","cashierId","outcome","readerId","clientSecret","paymentIntentId","cardStep","step","cardNumber","sendToCounter","queued","runTransaction","transaction","fresh","set","kioskQueuedAtMs","Date","now","timeline","appendOrderEvent","merge","receipt","channel","includes","to","marketingOptIn","ok","abandon","unlockSecret","secret","process","env","Error","signUnlock","payload","update","digest","mintPosKioskUnlock","memberUid","nowMs","expiresAtMs","POS_KIOSK_UNLOCK_TTL_MS","Buffer","from","JSON","stringify","v","d","u","e","toString","unlock","readPosKioskUnlock","token","dot","lastIndexOf","expected","a","b","Uint8Array","claims","parse","mayUnlock","pin","address","remoteAddress","claim","kind","lockedUntilMs","failed","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","until","POS_KIOSK_UNLOCK_LOCKOUT_MS","kioskUnlockLockedUntilMs","kioskUnlockFailures","attempt","roles","pins","matched","hash","left","minted","staffSettings","delete","connectionToken","staffAction","orderBy","entries","liftLegacyOrder","queuedAtMs","itemCount","modifiers","modifier","groupId","optionId","handlePosKiosk","read","has","posKioskHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,eAAe,QAAQ,SAAQ;AACpD,YAAYC,WAAW,sBAAqB;AAE5C,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,qBAAqB,QAAQ,qCAAoC;AAC1E,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SAASC,aAAa,QAAQ,6CAA4C;AAC1E,SACEC,gBAAgB,EAChBC,aAAa,EACbC,kBAAkB,EAClBC,aAAa,EACbC,eAAe,QACV,2BAA0B;AACjC,SAASC,cAAc,QAAQ,6CAA4C;AAC3E,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,uBAAuB,EACvBC,8BAA8B,EAC9BC,wBAAwB,QACnB,2CAAuC;AAC9C,YAAYC,mBAAmB,oBAAU;AACzC,SA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MgP,QAAQ3M,MAAMrC;QAC7B,KAAK;YACH,OAAO,MAAMyS,gBAAgBpQ;QAC/B,KAAK;YACH,OAAO,MAAMmO,OAAOnO,MAAMnC,KAAKF;QACjC,KAAK;QACL,KAAK;QACL,KAAK;YACH,OAAO,MAAMuS,cAAclQ,MAAMrC,MAAMsC;QACzC;YACE,OAAOzC,OAAO,KAAK;IACvB;AACF;AAEA,wCAAwC,GACxC,OAAO,MAAM0T,kBAAoC,OAAOrT,KAAK0K;IAC3DA,IAAII,SAAS,CAAC,iBAAiB;IAC/B,IAAI;QACF,MAAMuC,UAAU,MAAM6F,eAAelT;QACrC,OAAO0K,IAAI9K,MAAM,CAACyN,QAAQzN,MAAM,EAAEgL,IAAI,CAACyC,QAAQvN,IAAI;IACrD,EAAE,OAAOD,OAAO;QACdwM,QAAQxM,KAAK,CAAC,eAAeA;QAC7B,OAAO6K,IAAI9K,MAAM,CAAC,KAAKgL,IAAI,CAAC;YAAE/K,OAAO;QAAqD;IAC5F;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/pos-kiosk.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHmac, timingSafeEqual } from 'crypto'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport type { PluginApiHandler, PluginApiRequest, PluginApiResponse } from '@aglyn/aglyn/server'\nimport { resolveMediaSrc } from '@aglyn/aglyn/app-utils/media-ref'\nimport { nameSearchNormalizers } from '@aglyn/aglyn/app-utils/name-search'\nimport { pluginSmsAvailable } from '@aglyn/aglyn/plugin-manager/plugin-sms-messaging'\nimport { planListQuery } from '@aglyn/shared-ui-jsx/const/list-query-plan'\nimport {\n consumeRateLimit,\n firebaseAdmin,\n getLockdownVerdict,\n getOrgForHost,\n getPluginConfig,\n} from '@aglyn/tenant-data-admin'\nimport { applyListQuery } from '@aglyn/tenant-data-admin/server/list-query'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n STOREFRONT_CATALOG_BASE,\n STOREFRONT_CATALOG_DECLARATION,\n STOREFRONT_CATALOG_SORTS,\n} from '../constants/storefront-catalog-query'\nimport * as CommerceModel from '../model'\nimport { productOfferedOnKiosk } from '../model/commerce-kiosk-offer'\nimport { posKioskNameMatches } from '../model/commerce-kiosk-search'\nimport { posRegisterSettings, type PosRegisterSettings } from '../plugin-config'\nimport { posKioskSettings, type PosKioskSettings } from '../pos-kiosk-config'\nimport { verifyMemberPassword } from './membership'\nimport { authorizePosStaff, posIdempotencyKey, posQueryBody, posRequestBody, type PosStaff } from './pos-auth'\nimport {\n displayBranding,\n displayToken,\n posDisplayCurrency,\n resolveDisplayToken,\n type PosDeviceToken,\n} from './pos-display'\nimport { withPosKioskPrincipal } from './pos-kiosk-principal'\nimport { posOrderHandler } from './pos-order'\nimport { recordReceiptChoice, voidPosSale } from './pos-payment'\nimport { posPaymentId, posSaleSummary, readPosSale, type PosLiftedOrder } from './pos-sale'\nimport { posStripeTestMode, posTerminalAvailable } from './pos-stripe'\nimport {\n cancelPosCardPayment,\n createCardPresentIntent,\n createPosTerminalConnectionToken,\n refreshPosCardPayment,\n simulatePosReaderTap,\n startCardPresentPayment,\n} from './pos-terminal'\n\n/*==========================================\n * THE SELF-SERVICE KIOSK (AGL-3623): `/api/commerce/pos-kiosk`.\n *\n * ## Who is asking\n *\n * A kiosk is a register's paired screen with `mode: 'kiosk'` — the same\n * six-digit code and hashed device token as the customer display\n * (`pos-display.ts`), so pairing is one trust path, not two. It holds no\n * staff session. Every device action carries the token, and the gate below\n * re-checks, on every call, that the staff member whose code paired it may\n * still work this register (`admin`/`editor` on the site, `managePos`), that\n * the plan still includes POS, and that no lockdown covers them, the org or\n * the site. Demote them and the kiosk stops on its next tap.\n *\n * ## What it can reach\n *\n * Its own register's catalog, the orders IT opened (`kioskDeviceId`), and\n * nothing else: no staff names, no other customer's order, no register\n * state. A customer's email or phone goes straight onto their own order as\n * the receipt request and is never echoed back.\n *\n * ## Money\n *\n * The cart is priced by the register's own sale route (`pos-order.ts`), in\n * process, as an OPEN sale — the same tax, automatic promotions, platform\n * fee and idempotency as a cashier's sale, and none of a cashier's\n * discretion: no discount, no code, no customer, no stay. The amount a card\n * pays is always the server's balance; the kiosk names only a tip choice,\n * which is recomputed here from the store's own presets. Card payments are\n * the register's Stripe Terminal flow (AGL-3607) unchanged, and they stay\n * behind `STRIPE_TERMINAL_LIVE_ENABLED` exactly as the register's do.\n *\n * ## Staff\n *\n * `queue` and `take` are the register's: signed in and gated like a sale.\n * A queued (\"pay at counter\") order is an open sale like any other, and the\n * register takes payment on it through `commerce/pos-payment`.\n *=========================================*/\n\ntype Outcome = { status: number; body: Record<string, unknown> }\n\nconst DEVICE_READS = new Set(['context', 'catalog', 'sale'])\nconst STAFF_READS = new Set(['queue'])\n\ninterface KioskGate {\n device: PosDeviceToken\n /** The token hash prefix the kiosk's orders carry. */\n deviceId: string\n hostId: string\n registerId: string\n hostRef: FirebaseFirestore.DocumentReference\n /** The staff member who paired the kiosk; what it acts as. */\n uid: string\n orgId: string\n org: Record<string, any> | null\n register: Record<string, any>\n settings: PosRegisterSettings\n kiosk: PosKioskSettings\n}\n\n/** The prefix of a token row's id a kiosk's orders are stamped with. */\nexport function posKioskDeviceId(device: PosDeviceToken): string {\n return String(device.ref?.id ?? '').slice(0, 16)\n}\n\nfunction refuse(status: number, error: string): Outcome {\n return { status, body: { error } }\n}\n\n/** The kiosk's gate, asked again on every call. */\nasync function authorizeKiosk(\n req: PluginApiRequest,\n body: Record<string, any>,\n write: boolean,\n): Promise<KioskGate | Outcome> {\n const device = await resolveDisplayToken(displayToken(req, body))\n if (!device) return refuse(401, 'This kiosk is not paired.')\n if (device.mode !== 'kiosk') return refuse(403, 'This device is a customer display, not a kiosk.')\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(device.hostId)\n const [host, register] = await Promise.all([\n hostRef.get(),\n hostRef.collection('registers').doc(device.registerId).get(),\n ])\n if (!host.exists || !register.exists) return refuse(401, 'This kiosk is not paired.')\n // The member who paired it must still work the register here: the key\n // decides, not the site role (AGL-4047).\n const membership = device.createdBy\n ? await resolveOrgPermissions(device.createdBy, { hostId: device.hostId })\n : null\n if (!membership?.permissions?.managePos) {\n return refuse(403, 'This kiosk needs a staff member to pair it again.')\n }\n const owner = await getOrgForHost(device.hostId)\n if (!Aglyn.checkEntitlement(owner?.org as any, 'pos')) {\n return refuse(403, 'This kiosk is not available. Please order at the counter.')\n }\n const locked = await getLockdownVerdict({\n uid: device.createdBy,\n org: owner?.org as never,\n host: host.data() as never,\n intent: write ? 'write' : 'read',\n })\n if (locked) return { status: 423, body: { error: 'This kiosk is paused. Please order at the counter.', locked: true } }\n const orgId = String(owner?.org?.id ?? owner?.orgId ?? '')\n const config = await getPluginConfig(orgId || undefined, 'commerce', { hostId: device.hostId }).catch(\n () => ({}),\n )\n return {\n device,\n deviceId: posKioskDeviceId(device),\n hostId: device.hostId,\n registerId: device.registerId,\n hostRef,\n uid: device.createdBy,\n orgId,\n org: (owner?.org as Record<string, any>) ?? null,\n register: (register.data() ?? {}) as Record<string, any>,\n settings: posRegisterSettings(config),\n kiosk: posKioskSettings(config),\n }\n}\n\n/** One durable budget per kiosk and action; refused requests do nothing. */\nasync function withinBudget(gate: KioskGate, action: string, limit: number): Promise<boolean> {\n const rate = await consumeRateLimit(`pos-kiosk:${action}:${gate.deviceId}`, {\n limit,\n windowMs: 10 * 60 * 1000,\n })\n return rate.allowed\n}\n\n/** The register's card readers, when Terminal is switched on. */\nasync function registerReaders(gate: KioskGate): Promise<Array<{ id: string; label: string; status: string }>> {\n if (!posTerminalAvailable()) return []\n const snapshot = await gate.hostRef\n .collection('terminalReaders')\n .where('registerId', '==', gate.registerId)\n .limit(10)\n .get()\n return snapshot.docs.map((doc: any) => ({\n id: String(doc.id),\n label: String(doc.get('label') ?? 'Card reader'),\n status: String(doc.get('status') ?? 'offline'),\n }))\n}\n\n/** The reader this kiosk sends cards to: the one chosen in its settings, else the register's only one. */\nasync function kioskReaderId(gate: KioskGate): Promise<string | null> {\n const readers = await registerReaders(gate)\n const chosen = String(gate.device.data['kioskReaderId'] ?? '')\n if (chosen && readers.some((reader) => reader.id === chosen)) return chosen\n return readers.length === 1 ? readers[0]!.id : null\n}\n\n/** The receipt choices this kiosk can honor. */\nasync function receiptChannels(gate: KioskGate): Promise<CommerceModel.PosReceiptChannel[]> {\n const channels: CommerceModel.PosReceiptChannel[] = ['email']\n if (pluginSmsAvailable()) channels.push('sms')\n // Printed on the register's own receipt printer, so offered only when it has one.\n const printers = await gate.hostRef\n .collection('printers')\n .where('registerId', '==', gate.registerId)\n .limit(1)\n .get()\n .catch(() => null)\n if (printers && !printers.empty) channels.push('print')\n channels.push('none')\n return channels\n}\n\nasync function context(gate: KioskGate): Promise<Outcome> {\n const [branding, currency, reader, receipts] = await Promise.all([\n displayBranding(gate.hostId),\n posDisplayCurrency(gate.hostId),\n kioskReaderId(gate),\n receiptChannels(gate),\n ])\n const value: CommerceModel.PosKioskContext = {\n branding: { ...branding, message: gate.kiosk.welcome || 'Order here' },\n currency,\n tipping: { enabled: gate.settings.tippingEnabled, percentages: gate.settings.tipPercentages },\n payments: {\n reader: Boolean(reader),\n cardPresent: posTerminalAvailable(),\n payAtCounter: gate.kiosk.payAtCounter,\n },\n receipts,\n offerMarketing: gate.settings.displayMarketingOptIn,\n idleSeconds: gate.kiosk.idleSeconds,\n testMode: posStripeTestMode(),\n }\n return { status: 200, body: value as unknown as Record<string, unknown> }\n}\n\n/**\n * Whether a product may be sold at a kiosk at all: what the register sells,\n * less what a customer cannot be handed at a counter — a subscription-only\n * product, a gift card whose code needs issuing, and a digital download.\n */\nexport function posKioskSellable(product: CommerceModel.HostProduct): boolean {\n if (product.status !== 'active') return false\n // The merchant's own choice of what the kiosk offers (AGL-4038), for any\n // product: \"Offer on the kiosk\" in the product editor.\n if (!productOfferedOnKiosk(product)) return false\n if (product.subscription && !product.subscriptionOptional) return false\n if (product.giftCard) return false\n if (product.type === 'digital') return false\n return (product.variants ?? []).some((variant) => posKioskVariantOffered(product, variant))\n}\n\n/** A variant the kiosk may sell: priced, and offered by the merchant's choice (AGL-4038). */\nexport function posKioskVariantOffered(\n product: CommerceModel.HostProduct,\n variant: CommerceModel.ProductVariant,\n): boolean {\n return CommerceModel.variantHasPrice(variant) && productOfferedOnKiosk(product, variant.id)\n}\n\n/** A product as the kiosk may show it: names, prices and choices, nothing else. */\nexport function posKioskProduct(\n id: string,\n product: CommerceModel.HostProduct,\n hostId: string,\n): CommerceModel.PosKioskProduct {\n const image = resolveMediaSrc(product.mediaUrls?.[0], { hostId })\n const description = String(product.description ?? '').trim().slice(0, 280)\n return {\n id,\n name: String(product.name ?? '').slice(0, 120),\n ...(description ? { description } : {}),\n ...(image ? { imageUrl: image } : {}),\n categoryIds: (product.categoryIds ?? []).slice(0, 20),\n options: (product.options ?? []).map((option) => ({ name: option.name, values: [...option.values] })),\n variants: (product.variants ?? [])\n .filter((variant) => posKioskVariantOffered(product, variant))\n .map((variant) => ({\n id: variant.id,\n options: { ...(variant.options ?? {}) },\n priceCents: Math.round(Number(variant.priceUsd) * 100),\n soldOut: Boolean(CommerceModel.stockShortfall(product, variant.id, 1)),\n })),\n modifierGroups: CommerceModel.productModifierGroups(product),\n }\n}\n\n/**\n * How many pages of the query one answer may read looking for products the\n * kiosk can sell. What a kiosk can't sell isn't on any product as a field a\n * query can ask, so it is answered row by row, and a page of those must not\n * cost the store the products named after them. The ceiling is the read cost\n * of a catalog that is nearly all held back; past it the answer says\n * `truncated`, and a search still reaches any name.\n */\nconst POS_KIOSK_CATALOG_PAGES = 5\n\n/** The first page of sellable products in name order, however many rows that takes to find. */\nasync function sellableProducts(\n query: FirebaseFirestore.Query,\n hostId: string,\n typed: string,\n): Promise<{ products: CommerceModel.PosKioskProduct[]; truncated: boolean }> {\n const limit = CommerceModel.POS_KIOSK_CATALOG_LIMIT\n const products: CommerceModel.PosKioskProduct[] = []\n let after: FirebaseFirestore.QueryDocumentSnapshot | undefined\n for (let page = 0; page < POS_KIOSK_CATALOG_PAGES; page += 1) {\n const snapshot = await (after ? query.startAfter(after) : query).limit(limit).get()\n for (const doc of snapshot.docs) {\n const product = CommerceModel.liftLegacyProduct(doc.data())\n if (!posKioskSellable(product)) continue\n if (!posKioskNameMatches(String(product.name ?? ''), typed)) continue\n products.push(posKioskProduct(String(doc.id), product, hostId))\n }\n // A short page is the end of the query: all of it has been read.\n const ended = snapshot.docs.length < limit\n if (ended || products.length >= limit) {\n return { products: products.slice(0, limit), truncated: products.length > limit || !ended }\n }\n after = snapshot.docs[snapshot.docs.length - 1]\n }\n return { products, truncated: true }\n}\n\nasync function catalog(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n const categoryId = String(body['categoryId'] ?? '')\n if (categoryId && !/^[A-Za-z0-9_-]{1,128}$/.test(categoryId)) return refuse(400, 'Unknown category')\n const typed = String(body['search'] ?? '').trim().slice(0, 120)\n if (typed && !(await withinBudget(gate, 'search', 600))) return refuse(429, 'Too many tries. Wait a moment.')\n // The storefront catalog's own query (AGL-3321), and its composites: live,\n // active, by name. A category or the first word typed is a clause on it,\n // never a filter over what was read, and a search takes the one array\n // clause when both are asked.\n const plan = planListQuery(\n STOREFRONT_CATALOG_DECLARATION,\n {\n base: STOREFRONT_CATALOG_BASE,\n clauses: categoryId ? [{ field: 'category', op: 'contains', value: categoryId }] : [],\n search: typed.split(/\\s+/).filter(Boolean),\n sort: STOREFRONT_CATALOG_SORTS.name,\n },\n nameSearchNormalizers,\n )\n const [sellable, categories, currency] = await Promise.all([\n sellableProducts(applyListQuery(gate.hostRef.collection('products'), plan), gate.hostId, typed),\n // A search answers products alone: the menu already has its chips.\n typed ? null : gate.hostRef.collection('productCategories').limit(30).get(),\n posDisplayCurrency(gate.hostId),\n ])\n const value: CommerceModel.PosKioskCatalog = {\n products: sellable.products,\n categories: (categories?.docs ?? []).map((doc: any) => ({\n id: String(doc.id),\n name: String(doc.get('name') ?? 'Category').slice(0, 60),\n })),\n currency,\n ...(sellable.truncated ? { truncated: true } : {}),\n }\n return { status: 200, body: value as unknown as Record<string, unknown> }\n}\n\n/** An order as its kiosk reads it back; null for any order this kiosk did not open. */\nexport function posKioskSaleView(\n order: PosLiftedOrder | null,\n deviceId: string,\n): CommerceModel.PosKioskSale | null {\n if (!order || order.posSource !== 'kiosk' || order.kioskDeviceId !== deviceId) return null\n const summary = posSaleSummary(order)\n const status: CommerceModel.PosKioskSaleStatus =\n order.status === 'paid'\n ? 'paid'\n : order.status === 'pending'\n ? order.kioskQueueRegisterId\n ? 'queued'\n : 'open'\n : 'voided'\n const card = [...summary.payments]\n .reverse()\n .find((payment) => CommerceModel.isCardPaymentMethod(payment.method))\n return {\n orderId: order.$id,\n number: Number(order.number ?? 0),\n status,\n lines: (order.lineItems ?? []).map((line) => ({\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n quantity: line.quantity,\n amountCents: line.unitAmountCents * line.quantity,\n })),\n itemsCents: Number(order.totals?.itemsCents ?? 0),\n discountCents: Number(order.totals?.discountCents ?? 0),\n taxCents: Number(order.totals?.taxCents ?? 0),\n totalCents: summary.totalCents,\n tipCents: summary.tipCents,\n paidCents: summary.paidCents,\n dueCents: summary.dueCents,\n payment: card\n ? {\n id: card.id,\n status: card.status,\n ...(card.failureMessage ? { failureMessage: card.failureMessage } : {}),\n }\n : null,\n }\n}\n\n/** This kiosk's order, or a refusal that says nothing about anyone else's. */\nasync function readOwnSale(\n gate: KioskGate,\n rawOrderId: unknown,\n): Promise<{ order: PosLiftedOrder; view: CommerceModel.PosKioskSale } | Outcome> {\n const orderId = String(rawOrderId ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(orderId)) return refuse(404, 'Unknown order')\n const order = await readPosSale(gate.hostId, orderId)\n const view = posKioskSaleView(order, gate.deviceId)\n if (!order || !view) return refuse(404, 'Unknown order')\n return { order, view }\n}\n\n/** The response the in-process sale route wrote. */\nfunction recorder() {\n const result = { status: 500, body: {} as Record<string, any> }\n const res = {\n status(code: number) {\n result.status = code\n return res\n },\n json(value: unknown) {\n result.body = (value ?? {}) as Record<string, any>\n },\n send() {},\n setHeader() {},\n redirect() {},\n end() {},\n } as unknown as PluginApiResponse\n return { res, result }\n}\n\nasync function checkout(\n gate: KioskGate,\n req: PluginApiRequest,\n body: Record<string, any>,\n): Promise<Outcome> {\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return refuse(400, 'Missing Idempotency-Key')\n const cart = CommerceModel.sanitizePosKioskLines(body['lines'])\n if ('error' in cart) return refuse(400, cart.error)\n if (!(await withinBudget(gate, 'checkout', 40))) {\n return refuse(429, 'Too many orders from this kiosk. Please order at the counter.')\n }\n // What a customer may buy here, read from the product documents before\n // anything is priced: the sale route warns a cashier about stock and sells\n // anyway (the goods are in their hand); a kiosk refuses what is sold out.\n const ids = [...new Set(cart.lines.map((line) => line.productId))]\n const snapshots = await Promise.all(ids.map((id) => gate.hostRef.collection('products').doc(id).get()))\n const products = new Map(\n snapshots.map((snapshot: any) => [\n String(snapshot.id),\n snapshot.exists ? CommerceModel.liftLegacyProduct(snapshot.data()) : null,\n ]),\n )\n for (const line of cart.lines) {\n const product = products.get(line.productId)\n if (!product || (product as { deletedAt?: unknown }).deletedAt || !posKioskSellable(product)) {\n return refuse(409, 'An item in your cart is no longer available. Remove it and try again.')\n }\n const variant = line.variantId\n ? product.variants.find((candidate) => candidate.id === line.variantId)\n : product.variants[0]\n if (!variant || !posKioskVariantOffered(product, variant)) {\n return refuse(409, `${product.name} is no longer available. Remove it and try again.`)\n }\n const wanted = cart.lines\n .filter((other) => other.productId === line.productId && (other.variantId ?? '') === (line.variantId ?? ''))\n .reduce((sum, other) => sum + other.quantity, 0)\n if (CommerceModel.stockShortfall(product, variant.id, wanted)) {\n return refuse(409, `${product.name} is sold out. Remove it and try again.`)\n }\n }\n const { res, result } = recorder()\n const priced = withPosKioskPrincipal(\n {\n method: 'POST',\n headers: { 'idempotency-key': `kiosk:${gate.deviceId}:${attemptKey}` },\n query: {},\n cookies: {},\n socket: req.socket,\n body: {\n hostId: gate.hostId,\n registerId: gate.registerId,\n payment: 'open',\n lines: cart.lines,\n ...(typeof gate.register['locationId'] === 'string' && gate.register['locationId']\n ? { locationId: gate.register['locationId'] }\n : {}),\n },\n } as PluginApiRequest,\n { uid: gate.uid, registerId: gate.registerId, deviceId: gate.deviceId },\n )\n await posOrderHandler(priced, res)\n if (result.status !== 200 || !result.body['orderId']) {\n // A refusal about a product names it, and the customer can fix it. One\n // about the store — a shift, the tax setup, the plan — is the staff's to\n // fix, and the customer is sent to the counter.\n console.warn('[pos-kiosk] sale refused', gate.hostId, result.status, result.body['error'])\n if (result.status === 400 && result.body['error']) return refuse(400, String(result.body['error']))\n return refuse(\n result.status === 429 ? 429 : 409,\n 'This kiosk cannot take orders right now. Please order at the counter.',\n )\n }\n const own = await readOwnSale(gate, result.body['orderId'])\n if ('status' in own) return own\n if (own.view.totalCents <= 0) {\n // Nothing to take a card for, and nothing a kiosk should hand out free.\n await voidPosSale(kioskStaff(gate), own.order.$id).catch(() => undefined)\n return refuse(409, 'Please ask at the counter for this order.')\n }\n return { status: 200, body: { sale: own.view } }\n}\n\n/** The kiosk, as the register's payment helpers expect the person at the till. */\nfunction kioskStaff(gate: KioskGate): PosStaff {\n return { uid: gate.uid, hostId: gate.hostId, orgId: gate.orgId, org: gate.org }\n}\n\nasync function pay(gate: KioskGate, req: PluginApiRequest, body: Record<string, any>): Promise<Outcome> {\n const attemptKey = posIdempotencyKey(req)\n if (!attemptKey) return refuse(400, 'Missing Idempotency-Key')\n const method = String(body['method'] ?? '')\n if (method !== 'reader' && method !== 'tap') return refuse(400, 'Choose how to pay.')\n if (!posTerminalAvailable()) return refuse(409, 'Card payments are not available on this kiosk.')\n if (!(await withinBudget(gate, 'pay', 60))) return refuse(429, 'Too many tries. Please pay at the counter.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status !== 'open') return refuse(409, 'This order is no longer waiting for payment.')\n const paymentId = posPaymentId(own.order.$id, `kiosk:${attemptKey}`)\n // A retried press finds the payment its first press reserved, for the\n // amount and tip that press chose: the reservation is already out of the\n // balance, so the balance alone would read as nothing left to pay.\n const pressed = CommerceModel.orderPayments(own.order).find((payment) => payment.id === paymentId)\n const amountCents = pressed ? pressed.amountCents : posSaleSummary(own.order).tenderableCents\n if (!(amountCents > 0)) return refuse(409, 'Nothing is left to pay on this order.')\n const tipCents = pressed ? Number(pressed.tipCents ?? 0) : CommerceModel.posKioskTipCents(body['tipChoice'], {\n baseCents: amountCents,\n enabled: gate.settings.tippingEnabled,\n percentages: gate.settings.tipPercentages,\n percent: body['tipPercent'],\n cents: body['tipCents'],\n })\n if (tipCents === null) return refuse(400, 'Choose one of the tips shown, or no tip.')\n const start = {\n hostId: gate.hostId,\n orderId: own.order.$id,\n paymentId,\n amountCents,\n tipCents,\n cashierId: gate.uid,\n org: gate.org,\n }\n let outcome: Awaited<ReturnType<typeof createCardPresentIntent>>\n if (method === 'reader') {\n const readerId = await kioskReaderId(gate)\n if (!readerId) return refuse(409, 'No card reader is set up for this kiosk. Please pay at the counter.')\n // The kiosk asked for the tip on its own screen: the reader must not ask again.\n outcome = await startCardPresentPayment({\n ...start,\n readerId,\n settings: { ...gate.settings, tippingEnabled: false },\n })\n } else {\n // Tap to Pay: collected by the native POS app's Stripe Terminal SDK\n // against this server-made intent (AGL-3618), settled like any reader.\n outcome = await createCardPresentIntent(start)\n }\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n const view = posKioskSaleView(outcome.order, gate.deviceId)\n return {\n status: 200,\n body: {\n sale: view,\n ...(outcome.payment ? { paymentId: outcome.payment.id } : {}),\n ...(outcome.clientSecret ? { clientSecret: outcome.clientSecret } : {}),\n ...(outcome.paymentIntentId ? { paymentIntentId: outcome.paymentIntentId } : {}),\n },\n }\n}\n\n/** A card payment on this kiosk's own order: refreshed, canceled or (test mode) tapped. */\nasync function cardStep(\n gate: KioskGate,\n body: Record<string, any>,\n step: 'payment-status' | 'cancel-payment' | 'simulate',\n): Promise<Outcome> {\n if (!(await withinBudget(gate, 'card', 900))) return refuse(429, 'Too many tries. Wait a moment.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n const paymentId = String(body['paymentId'] ?? '')\n if (!own.order.payments?.some((payment) => payment.id === paymentId)) return refuse(404, 'Unknown payment')\n const ref = { hostId: gate.hostId, orderId: own.order.$id, paymentId }\n let outcome\n if (step === 'payment-status') outcome = await refreshPosCardPayment(ref)\n else if (step === 'cancel-payment') outcome = await cancelPosCardPayment(ref)\n else {\n if (!posStripeTestMode()) return refuse(404, 'Unknown action')\n outcome = await simulatePosReaderTap({ ...ref, cardNumber: String(body['cardNumber'] ?? '') })\n }\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n return { status: 200, body: { sale: posKioskSaleView(outcome.order, gate.deviceId) } }\n}\n\n/** \"Pay at counter\": the order joins the register's queue with its number. */\nasync function sendToCounter(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n if (!gate.kiosk.payAtCounter) return refuse(409, 'Please pay here with a card.')\n if (!(await withinBudget(gate, 'counter', 40))) return refuse(429, 'Too many orders from this kiosk.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status === 'queued') return { status: 200, body: { sale: own.view } }\n const ref = gate.hostRef.collection('orders').doc(own.order.$id)\n const firestore = firebaseAdmin.app().firestore()\n // In a transaction: a card that settled between the customer's two taps\n // leaves a paid order, which never joins a queue.\n const queued = await firestore.runTransaction(async (transaction: any) => {\n const fresh = await transaction.get(ref)\n if (!fresh.exists || fresh.get('status') !== 'pending') return false\n const payments = CommerceModel.orderPayments(fresh.data() as any)\n if (payments.some((payment) => payment.status === 'pending' || payment.status === 'succeeded')) {\n return false\n }\n transaction.set(\n ref,\n {\n kioskQueueRegisterId: gate.registerId,\n kioskQueuedAtMs: Date.now(),\n timeline: CommerceModel.appendOrderEvent(\n { ...(fresh.data() as any) },\n 'pos-kiosk-pay-at-counter',\n 'Sent to the counter from the self-service kiosk',\n ),\n },\n { merge: true },\n )\n return true\n })\n if (!queued) return refuse(409, 'This order is already being paid. Check the screen.')\n const after = await readOwnSale(gate, own.order.$id)\n if ('status' in after) return after\n return { status: 200, body: { sale: after.view } }\n}\n\nasync function receipt(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n if (!(await withinBudget(gate, 'receipt', 40))) return refuse(429, 'Too many tries.')\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status !== 'paid') return refuse(409, 'Your receipt is ready once your order is paid.')\n const channel = String(body['channel'] ?? '') as CommerceModel.PosReceiptChannel\n if (!(await receiptChannels(gate)).includes(channel)) return refuse(400, 'Choose a receipt shown on the screen.')\n const outcome = await recordReceiptChoice(kioskStaff(gate), own.order.$id, {\n channel,\n to: body['to'],\n marketingOptIn: gate.settings.displayMarketingOptIn && body['marketingOptIn'] === true,\n })\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n // The address is on the order now; nothing of it comes back to the screen.\n return { status: 200, body: { ok: true } }\n}\n\n/**\n * The idle reset and \"Start over\": an order this kiosk opened and nobody\n * paid is voided, so it holds no promotion slot and no stock. A queued or\n * paid order is left exactly as it is.\n */\nasync function abandon(gate: KioskGate, body: Record<string, any>): Promise<Outcome> {\n const own = await readOwnSale(gate, body['orderId'])\n if ('status' in own) return own\n if (own.view.status !== 'open') return { status: 200, body: { sale: own.view } }\n // Money that already moved is the counter's to settle, never a screen's\n // to refund on its own.\n if (CommerceModel.orderPayments(own.order).some((payment) => payment.status === 'succeeded')) {\n return { status: 200, body: { sale: own.view } }\n }\n const outcome = await voidPosSale(kioskStaff(gate), own.order.$id)\n if ('error' in outcome) return refuse(outcome.status, outcome.error)\n return { status: 200, body: { sale: posKioskSaleView(outcome.order, gate.deviceId) } }\n}\n\n/*==========================================\n * STAFF UNLOCK.\n *\n * The register's staff PINs (AGL-3609), checked on the server: a PIN at a\n * kiosk unlocks its settings — choosing the card reader, leaving kiosk mode\n * — for a few minutes. A kiosk faces the public, so it shows no roster of\n * names; the PIN alone is checked against every member of the site who may\n * work the register. The attempt is claimed on the device's own token row\n * BEFORE any PIN is checked, so a burst of guesses gets\n * POS_KIOSK_UNLOCK_MAX_ATTEMPTS in the lockout window and no more, and a\n * member whose own PIN is locked at the register cannot unlock a kiosk\n * either.\n *=========================================*/\n\nfunction unlockSecret(): string {\n const secret = process.env['TOKEN_SIGNING_SECRET']\n if (!secret) throw new Error('TOKEN_SIGNING_SECRET is not configured')\n return secret\n}\n\nfunction signUnlock(payload: string): string {\n return createHmac('sha256', unlockSecret()).update(`pos-kiosk-unlock:${payload}`).digest('hex')\n}\n\n/** A short-lived, signed \"staff unlocked THIS kiosk\". */\nexport function mintPosKioskUnlock(deviceId: string, memberUid: string, nowMs: number): {\n unlock: string\n expiresAtMs: number\n} {\n const expiresAtMs = nowMs + CommerceModel.POS_KIOSK_UNLOCK_TTL_MS\n const payload = Buffer.from(JSON.stringify({ v: 1, d: deviceId, u: memberUid, e: expiresAtMs })).toString(\n 'base64url',\n )\n return { unlock: `${payload}.${signUnlock(payload)}`, expiresAtMs }\n}\n\n/** The member a valid unlock names for this kiosk, or null. */\nexport function readPosKioskUnlock(token: unknown, deviceId: string, nowMs: number): string | null {\n const value = typeof token === 'string' ? token.trim() : ''\n const dot = value.lastIndexOf('.')\n if (dot <= 0 || value.length > 1000) return null\n const payload = value.slice(0, dot)\n let expected: string\n try {\n expected = signUnlock(payload)\n } catch {\n return null\n }\n const a = Buffer.from(value.slice(dot + 1))\n const b = Buffer.from(expected)\n if (a.length !== b.length || !timingSafeEqual(new Uint8Array(a), new Uint8Array(b))) return null\n try {\n const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))\n if (claims?.v !== 1 || claims.d !== deviceId || typeof claims.u !== 'string' || !(Number(claims.e) > nowMs)) {\n return null\n }\n return claims.u\n } catch {\n return null\n }\n}\n\n/** Whether a member may still unlock: `managePos` here today, whatever their site role (AGL-4047). */\nasync function mayUnlock(gate: KioskGate, memberUid: string): Promise<boolean> {\n const membership = await resolveOrgPermissions(memberUid, { hostId: gate.hostId })\n return membership?.permissions?.managePos === true\n}\n\nasync function unlock(gate: KioskGate, req: PluginApiRequest, body: Record<string, any>): Promise<Outcome> {\n const pin = String(body['pin'] ?? '')\n if (!/^\\d{4,6}$/.test(pin)) return refuse(400, 'Enter your staff PIN.')\n const address = String(req.socket?.remoteAddress ?? '') || 'no-address'\n const rate = await consumeRateLimit(`pos-kiosk-unlock:${address}`, { limit: 20, windowMs: 15 * 60 * 1000 })\n if (!rate.allowed) return refuse(429, 'Too many tries. Wait a few minutes and try again.')\n try {\n unlockSecret()\n } catch {\n return refuse(501, 'Staff PINs are not configured on this server.')\n }\n const firestore = firebaseAdmin.app().firestore()\n const now = Date.now()\n const claim = await firestore.runTransaction(async (transaction: any) => {\n const snapshot = await transaction.get(gate.device.ref)\n if (!snapshot.exists) return { kind: 'gone' as const }\n const lockedUntilMs = Number(snapshot.get('kioskUnlockLockedUntilMs') ?? 0)\n if (lockedUntilMs > now) return { kind: 'locked' as const, lockedUntilMs }\n const failed = lockedUntilMs ? 0 : Number(snapshot.get('kioskUnlockFailures') ?? 0)\n if (failed >= CommerceModel.POS_KIOSK_UNLOCK_MAX_ATTEMPTS) {\n const until = now + CommerceModel.POS_KIOSK_UNLOCK_LOCKOUT_MS\n transaction.update(gate.device.ref, { kioskUnlockLockedUntilMs: until, kioskUnlockFailures: 0 })\n return { kind: 'locked' as const, lockedUntilMs: until }\n }\n transaction.update(gate.device.ref, { kioskUnlockFailures: failed + 1, kioskUnlockLockedUntilMs: null })\n return { kind: 'claimed' as const, attempt: failed + 1 }\n })\n if (claim.kind === 'gone') return refuse(401, 'This kiosk is not paired.')\n if (claim.kind === 'locked') {\n return { status: 423, body: { error: 'Too many wrong PINs. Try again later.', lockedUntilMs: claim.lockedUntilMs } }\n }\n // Members of this site only, any role: `mayUnlock` below asks the key.\n const host = await gate.hostRef.get()\n const roles = (host.get('memberRoles') ?? {}) as Record<string, string>\n const pins = await gate.hostRef.collection('posStaffPins').limit(50).get()\n let matched = ''\n for (const doc of pins.docs) {\n const uid = String(doc.id)\n if (!roles[uid]) continue\n if (Number(doc.get('lockedUntilMs') ?? 0) > now) continue\n const hash = String(doc.get('pinScrypt') ?? '')\n if (hash && verifyMemberPassword(pin, hash)) {\n matched = uid\n break\n }\n }\n if (!matched || !(await mayUnlock(gate, matched))) {\n const left = CommerceModel.POS_KIOSK_UNLOCK_MAX_ATTEMPTS - claim.attempt\n if (left <= 0) {\n await gate.device.ref.update({\n kioskUnlockLockedUntilMs: now + CommerceModel.POS_KIOSK_UNLOCK_LOCKOUT_MS,\n kioskUnlockFailures: 0,\n })\n return { status: 423, body: { error: 'Too many wrong PINs. Try again later.' } }\n }\n return { status: 401, body: { error: `That PIN is not right. ${left} ${left === 1 ? 'try' : 'tries'} left.` } }\n }\n await gate.device.ref.update({ kioskUnlockFailures: 0, kioskUnlockLockedUntilMs: null })\n const minted = mintPosKioskUnlock(gate.deviceId, matched, now)\n return { status: 200, body: minted }\n}\n\nasync function staffSettings(\n gate: KioskGate,\n body: Record<string, any>,\n action: 'settings' | 'set-reader' | 'exit',\n): Promise<Outcome> {\n const memberUid = readPosKioskUnlock(body['unlock'], gate.deviceId, Date.now())\n if (!memberUid || !(await mayUnlock(gate, memberUid))) return refuse(401, 'Enter your staff PIN again.')\n if (action === 'exit') {\n // Leaving kiosk mode unpairs the device: a new code from the register\n // is the only way back.\n await gate.device.ref.delete()\n return { status: 200, body: { ok: true } }\n }\n const readers = await registerReaders(gate)\n let data = gate.device.data\n if (action === 'set-reader') {\n const readerId = String(body['readerId'] ?? '')\n if (readerId && !readers.some((reader) => reader.id === readerId)) {\n return refuse(404, 'That card reader is not on this register.')\n }\n await gate.device.ref.set({ kioskReaderId: readerId || null }, { merge: true })\n data = { ...data, kioskReaderId: readerId || null }\n }\n const chosen = await kioskReaderId({ ...gate, device: { ...gate.device, data } })\n return {\n status: 200,\n body: {\n readers,\n readerId: chosen,\n label: String(gate.device.data['label'] ?? 'Self-service kiosk'),\n },\n }\n}\n\n/** A Terminal SDK connection token for the native app's Tap to Pay, scoped to the site's Location. */\nasync function connectionToken(gate: KioskGate): Promise<Outcome> {\n if (!posTerminalAvailable()) return refuse(409, 'Card payments are not available on this kiosk.')\n if (!(await withinBudget(gate, 'connection-token', 60))) return refuse(429, 'Too many tries.')\n const token = await createPosTerminalConnectionToken(gate.hostId)\n if (!token) return refuse(409, 'Set up a card reader location for this site first.')\n return { status: 200, body: token }\n}\n\n/*==========================================\n * THE REGISTER'S SIDE: the queue of \"pay at counter\" orders.\n *=========================================*/\n\nexport interface PosKioskQueueEntry {\n orderId: string\n number: number\n queuedAtMs: number\n totalCents: number\n itemCount: number\n}\n\nasync function staffAction(req: PluginApiRequest, body: Record<string, any>, action: string): Promise<Outcome> {\n const hostId = String(body['hostId'] ?? '')\n const gate = await authorizePosStaff(req, hostId)\n if ('error' in gate) return refuse(gate.status, gate.error)\n const registerId = String(body['registerId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(registerId)) return refuse(400, 'Missing registerId')\n const hostRef = firebaseAdmin.app().firestore().collection('hosts').doc(hostId)\n if (!(await hostRef.collection('registers').doc(registerId).get()).exists) {\n return refuse(404, 'Unknown register')\n }\n if (action === 'queue') {\n // `kioskQueueRegisterId ==, status ==, kioskQueuedAtMs ASC`, declared in\n // the index file: the oldest order first, as a counter serves them.\n const snapshot = await hostRef\n .collection('orders')\n .where('kioskQueueRegisterId', '==', registerId)\n .where('status', '==', 'pending')\n .orderBy('kioskQueuedAtMs', 'asc')\n .limit(25)\n .get()\n const entries: PosKioskQueueEntry[] = snapshot.docs.map((doc: any) => {\n const order = CommerceModel.liftLegacyOrder(doc.data()) as CommerceModel.HostOrder\n return {\n orderId: String(doc.id),\n number: Number(order.number ?? 0),\n queuedAtMs: Number(order.kioskQueuedAtMs ?? 0),\n totalCents: Number(order.totals?.totalCents ?? 0),\n itemCount: (order.lineItems ?? []).reduce((sum, line) => sum + line.quantity, 0),\n }\n })\n return { status: 200, body: { entries, currency: await posDisplayCurrency(hostId) } }\n }\n // `take`: the queued order, as the register loads it into its tender panel.\n const orderId = String(body['orderId'] ?? '')\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(orderId)) return refuse(400, 'Missing orderId')\n const order = await readPosSale(hostId, orderId)\n if (!order || order.kioskQueueRegisterId !== registerId) return refuse(404, 'Unknown order')\n if (order.status !== 'pending') return refuse(409, 'This order is no longer waiting for payment.')\n return {\n status: 200,\n body: {\n sale: posSaleSummary(order),\n number: Number(order.number ?? 0),\n lines: (order.lineItems ?? []).map((line) => ({\n productId: line.productId,\n ...(line.variantId ? { variantId: line.variantId } : {}),\n name: line.name,\n ...(line.variantLabel ? { variantLabel: line.variantLabel } : {}),\n unitAmountCents: line.unitAmountCents,\n quantity: line.quantity,\n ...(line.modifiers?.length\n ? { modifiers: CommerceModel.modifierSelectionOf(line.modifiers) }\n : {}),\n })),\n },\n }\n}\n\nexport async function handlePosKiosk(req: PluginApiRequest): Promise<Outcome> {\n const body = req.method === 'GET' ? posQueryBody(req) : posRequestBody(req)\n const action = String(body['action'] ?? '')\n const read = DEVICE_READS.has(action) || STAFF_READS.has(action)\n if (!(req.method === 'POST' || (req.method === 'GET' && read))) {\n return refuse(405, 'Method not allowed')\n }\n if (action === 'queue' || action === 'take') return await staffAction(req, body, action)\n const gate = await authorizeKiosk(req, body, !read)\n if ('status' in gate) return gate\n switch (action) {\n case 'context':\n return await context(gate)\n case 'catalog':\n return await catalog(gate, body)\n case 'sale': {\n const own = await readOwnSale(gate, body['orderId'])\n return 'status' in own ? own : { status: 200, body: { sale: own.view } }\n }\n case 'checkout':\n return await checkout(gate, req, body)\n case 'pay':\n return await pay(gate, req, body)\n case 'payment-status':\n case 'cancel-payment':\n case 'simulate':\n return await cardStep(gate, body, action)\n case 'counter':\n return await sendToCounter(gate, body)\n case 'receipt':\n return await receipt(gate, body)\n case 'abandon':\n return await abandon(gate, body)\n case 'connection-token':\n return await connectionToken(gate)\n case 'unlock':\n return await unlock(gate, req, body)\n case 'settings':\n case 'set-reader':\n case 'exit':\n return await staffSettings(gate, body, action)\n default:\n return refuse(400, 'Unknown action')\n }\n}\n\n/** `GET|POST /api/commerce/pos-kiosk`. */\nexport const posKioskHandler: PluginApiHandler = async (req, res) => {\n res.setHeader('Cache-Control', 'no-store')\n try {\n const outcome = await handlePosKiosk(req)\n return res.status(outcome.status).json(outcome.body)\n } catch (error) {\n console.error('[pos-kiosk]', error)\n return res.status(500).json({ error: 'Something went wrong. Please order at the counter.' })\n }\n}\n"],"names":["createHmac","timingSafeEqual","Aglyn","resolveMediaSrc","nameSearchNormalizers","pluginSmsAvailable","planListQuery","consumeRateLimit","firebaseAdmin","getLockdownVerdict","getOrgForHost","getPluginConfig","applyListQuery","resolveOrgPermissions","STOREFRONT_CATALOG_BASE","STOREFRONT_CATALOG_DECLARATION","STOREFRONT_CATALOG_SORTS","CommerceModel","productOfferedOnKiosk","posKioskNameMatches","posRegisterSettings","posKioskSettings","verifyMemberPassword","authorizePosStaff","posIdempotencyKey","posQueryBody","posRequestBody","displayBranding","displayToken","posDisplayCurrency","resolveDisplayToken","withPosKioskPrincipal","posOrderHandler","recordReceiptChoice","voidPosSale","posPaymentId","posSaleSummary","readPosSale","posStripeTestMode","posTerminalAvailable","cancelPosCardPayment","createCardPresentIntent","createPosTerminalConnectionToken","refreshPosCardPayment","simulatePosReaderTap","startCardPresentPayment","DEVICE_READS","Set","STAFF_READS","posKioskDeviceId","device","String","ref","id","slice","refuse","status","error","body","authorizeKiosk","req","write","owner","register","membership","mode","firestore","app","hostRef","collection","doc","hostId","host","Promise","all","get","registerId","exists","createdBy","permissions","managePos","checkEntitlement","org","locked","uid","data","intent","orgId","config","undefined","catch","deviceId","settings","kiosk","withinBudget","gate","action","limit","rate","windowMs","allowed","registerReaders","snapshot","where","docs","map","label","kioskReaderId","readers","chosen","some","reader","length","receiptChannels","channels","push","printers","empty","context","branding","currency","receipts","value","message","welcome","tipping","enabled","tippingEnabled","percentages","tipPercentages","payments","Boolean","cardPresent","payAtCounter","offerMarketing","displayMarketingOptIn","idleSeconds","testMode","posKioskSellable","product","subscription","subscriptionOptional","giftCard","type","variants","variant","posKioskVariantOffered","variantHasPrice","posKioskProduct","image","mediaUrls","description","trim","name","imageUrl","categoryIds","options","option","values","filter","priceCents","Math","round","Number","priceUsd","soldOut","stockShortfall","modifierGroups","productModifierGroups","POS_KIOSK_CATALOG_PAGES","sellableProducts","query","typed","POS_KIOSK_CATALOG_LIMIT","products","after","page","startAfter","liftLegacyProduct","ended","truncated","catalog","categoryId","test","plan","base","clauses","field","op","search","split","sort","sellable","categories","posKioskSaleView","order","posSource","kioskDeviceId","summary","kioskQueueRegisterId","card","reverse","find","payment","isCardPaymentMethod","method","orderId","$id","number","lines","lineItems","line","variantLabel","quantity","amountCents","unitAmountCents","itemsCents","totals","discountCents","taxCents","totalCents","tipCents","paidCents","dueCents","failureMessage","readOwnSale","rawOrderId","view","recorder","result","res","code","json","send","setHeader","redirect","end","checkout","attemptKey","cart","sanitizePosKioskLines","ids","productId","snapshots","Map","deletedAt","variantId","candidate","wanted","other","reduce","sum","priced","headers","cookies","socket","locationId","console","warn","own","kioskStaff","sale","pay","pressed","paymentId","orderPayments","tenderableCents","posKioskTipCents","baseCents","percent","cents","start","cashierId","outcome","readerId","clientSecret","paymentIntentId","cardStep","step","cardNumber","sendToCounter","queued","runTransaction","transaction","fresh","set","kioskQueuedAtMs","Date","now","timeline","appendOrderEvent","merge","receipt","channel","includes","to","marketingOptIn","ok","abandon","unlockSecret","secret","process","env","Error","signUnlock","payload","update","digest","mintPosKioskUnlock","memberUid","nowMs","expiresAtMs","POS_KIOSK_UNLOCK_TTL_MS","Buffer","from","JSON","stringify","v","d","u","e","toString","unlock","readPosKioskUnlock","token","dot","lastIndexOf","expected","a","b","Uint8Array","claims","parse","mayUnlock","pin","address","remoteAddress","claim","kind","lockedUntilMs","failed","POS_KIOSK_UNLOCK_MAX_ATTEMPTS","until","POS_KIOSK_UNLOCK_LOCKOUT_MS","kioskUnlockLockedUntilMs","kioskUnlockFailures","attempt","roles","pins","matched","hash","left","minted","staffSettings","delete","connectionToken","staffAction","orderBy","entries","liftLegacyOrder","queuedAtMs","itemCount","modifiers","modifierSelectionOf","handlePosKiosk","read","has","posKioskHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,UAAU,EAAEC,eAAe,QAAQ,SAAQ;AACpD,YAAYC,WAAW,sBAAqB;AAE5C,SAASC,eAAe,QAAQ,mCAAkC;AAClE,SAASC,qBAAqB,QAAQ,qCAAoC;AAC1E,SAASC,kBAAkB,QAAQ,mDAAkD;AACrF,SAASC,aAAa,QAAQ,6CAA4C;AAC1E,SACEC,gBAAgB,EAChBC,aAAa,EACbC,kBAAkB,EAClBC,aAAa,EACbC,eAAe,QACV,2BAA0B;AACjC,SAASC,cAAc,QAAQ,6CAA4C;AAC3E,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,uBAAuB,EACvBC,8BAA8B,EAC9BC,wBAAwB,QACnB,2CAAuC;AAC9C,YAAYC,mBAAmB,oBAAU;AACzC,SAASC,qBAAqB,QAAQ,mCAA+B;AACrE,SAASC,mBAAmB,QAAQ,oCAAgC;AACpE,SAASC,mBAAmB,QAAkC,sBAAkB;AAChF,SAASC,gBAAgB,QAA+B,yBAAqB;AAC7E,SAASC,oBAAoB,QAAQ,kBAAc;AAC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AwC,GACxC,OAAO,MAAMwT,kBAAoC,OAAOnT,KAAK0K;IAC3DA,IAAII,SAAS,CAAC,iBAAiB;IAC/B,IAAI;QACF,MAAMuC,UAAU,MAAM2F,eAAehT;QACrC,OAAO0K,IAAI9K,MAAM,CAACyN,QAAQzN,MAAM,EAAEgL,IAAI,CAACyC,QAAQvN,IAAI;IACrD,EAAE,OAAOD,OAAO;QACdwM,QAAQxM,KAAK,CAAC,eAAeA;QAC7B,OAAO6K,IAAI9K,MAAM,CAAC,KAAKgL,IAAI,CAAC;YAAE/K,OAAO;QAAqD;IAC5F;AACF,EAAC"}
@@ -85,6 +85,11 @@ export interface PublicModifierGroup {
85
85
  name: string;
86
86
  min: number;
87
87
  max: number;
88
+ /** A write-in the shopper types (write-ins), with its length and whether it takes numbers only. */
89
+ kind?: CommerceModel.ProductModifierGroupKind;
90
+ maxLength?: number;
91
+ digitsOnly?: boolean;
92
+ nameOnOrder?: boolean;
88
93
  options: Array<{
89
94
  id: string;
90
95
  name: string;
@@ -18,11 +18,19 @@ import * as CommerceModel from "../model/index.js";
18
18
  import { firebaseAdmin } from "@aglyn/tenant-data-admin";
19
19
  import { readStoreDay } from "./store-day.js";
20
20
  /** The website add-on groups of a product, in the page's shape (AGL-4100). */ export function publicModifierGroups(product) {
21
- return CommerceModel.websiteModifierGroups(product).map((group)=>({
21
+ return CommerceModel.websiteModifierGroups(product).map((group)=>_extends({
22
22
  id: group.id,
23
23
  name: group.name,
24
24
  min: group.min,
25
- max: group.max,
25
+ max: group.max
26
+ }, CommerceModel.modifierGroupIsWriteIn(group) ? _extends({
27
+ kind: 'text',
28
+ maxLength: CommerceModel.writeInMaxLength(group)
29
+ }, group.digitsOnly === true ? {
30
+ digitsOnly: true
31
+ } : {}) : {}, group.nameOnOrder === true ? {
32
+ nameOnOrder: true
33
+ } : {}, {
26
34
  options: group.options.map((option)=>{
27
35
  var _option_includes;
28
36
  return _extends({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { readStoreDay } from './store-day'\n\nexport interface PublicProductDetail {\n id: string\n name: string\n slug: string\n description?: string\n type: CommerceModel.ProductType\n mediaUrls: string[]\n options: CommerceModel.ProductOption[]\n variants: Array<{\n id: string\n options?: Record<string, string>\n /**\n * `null` for a variant listed before it has a price (AGL-3676): the page\n * says \"Price coming soon\" and offers nothing to buy, as no sale door\n * would sell it.\n */\n priceUsd: number | null\n compareAtPriceUsd?: number\n soldOut: boolean\n imageUrl?: string\n /**\n * Merchant's stock-keeping unit (AGL-686). Carried into the public DTO\n * so the server can put `sku` on the Product structured data — Google\n * Merchant treats it as required for a product offer, and without it a\n * listing is simply ineligible for rich results rather than warned about.\n * It is already public information: it prints on receipts and invoices.\n */\n sku?: string\n /**\n * The buyer may choose the day they will use it (a pass bought ahead,\n * AGL-4043): the page offers an optional date. Absent when it does not.\n */\n asksUseDate?: true\n /** A short line on the variant's picture card (AGL-4205). */\n note?: string\n }>\n /**\n * The page offers \"Get a free mockup\" (AGL-4205): the request form the site\n * placed in the product block opens with the shopper's picks.\n */\n mockupRequests?: true\n /**\n * The store's time zone, sent only when a variant asks for a use day, so\n * the page offers no day that has passed on the store's calendar.\n */\n useDayTimeZone?: string\n tags?: string[]\n /** Recurring billing (AGL-303) so the PDP frames the price. */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /** Buyer may choose one-time OR subscribe (AGL-545). */\n subscriptionOptional?: boolean\n /**\n * The add-ons the page offers (AGL-4100): ONLY the groups switched to\n * \"Show on the website\". A register-only group never leaves the server, so\n * a shop's in-person choices and prices are not published. Absent: none.\n * Display-only like the prices above; every sale door prices them again\n * from the product.\n */\n modifierGroups?: PublicModifierGroup[]\n}\n\n/** An add-on group as the product page shows it (AGL-4100). */\nexport interface PublicModifierGroup {\n id: string\n name: string\n min: number\n max: number\n options: Array<{\n id: string\n name: string\n priceCents: number\n /** What the choice adds on a variant priced differently, by variant id. */\n priceCentsByVariant?: Record<string, number>\n /** The choice's card (AGL-4205): its picture, its note, and what a combo includes. */\n imageUrl?: string\n note?: string\n includes?: string[]\n }>\n}\n\n/** The website add-on groups of a product, in the page's shape (AGL-4100). */\nexport function publicModifierGroups(\n product: { modifierGroups?: unknown },\n): PublicModifierGroup[] {\n return CommerceModel.websiteModifierGroups(product).map((group) => ({\n id: group.id,\n name: group.name,\n min: group.min,\n max: group.max,\n options: group.options.map((option) => ({\n id: option.id,\n name: option.name,\n priceCents: option.priceCents,\n ...(option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length\n ? { priceCentsByVariant: { ...option.priceCentsByVariant } }\n : {}),\n // Card fields are checked at save (`modifierCardsProblem`), not on this\n // read, so only well-formed values reach the page (AGL-4205).\n ...(typeof option.imageUrl === 'string' && option.imageUrl ? { imageUrl: option.imageUrl } : {}),\n ...(typeof option.note === 'string' && option.note.trim() ? { note: option.note.trim() } : {}),\n ...(CommerceModel.modifierOptionIsCombo(option) ? { includes: [...(option.includes ?? [])] } : {}),\n })),\n }))\n}\n\n/**\n * Map a lifted product onto the public PDP DTO.\n *\n * Extracted (AGL-659) so the site-page resolver can put the SAME payload\n * into page props as the API returns — the PDP block used to fetch this in\n * an effect, which meant the server rendered a skeleton and crawlers saw a\n * product page with no product in it. One definition keeps the server-\n * rendered and client-fetched shapes from drifting.\n *\n * Display-only by design: stock is a `soldOut` boolean rather than a raw\n * count, and the charge still prices server-side.\n */\nexport function toPublicProductDetail(\n id: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n options: { timeZone?: string | null } = {},\n): PublicProductDetail {\n const asksUseDate = productAsksUseDateAnywhere(product)\n const modifierGroups = publicModifierGroups(product)\n return {\n id,\n name: product.name,\n slug: product.slug,\n ...(product.description ? { description: product.description } : {}),\n type: product.type,\n mediaUrls:\n product.mediaUrls ?? (product.imageUrl ? [product.imageUrl] : []),\n options: product.options ?? [],\n variants: product.variants.map((variant) => ({\n id: variant.id,\n ...(variant.options ? { options: variant.options } : {}),\n priceUsd: CommerceModel.variantHasPrice(variant) ? variant.priceUsd : null,\n ...(variant.compareAtPriceUsd\n ? { compareAtPriceUsd: variant.compareAtPriceUsd }\n : {}),\n soldOut:\n variant.inventory != null &&\n Number(variant.inventory) <= 0 &&\n product.oversellPolicy !== 'backorder',\n ...(variant.imageUrl ? { imageUrl: variant.imageUrl } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n ...(CommerceModel.productAsksUseDate(product, variant.id) ? { asksUseDate: true as const } : {}),\n ...(typeof variant.note === 'string' && variant.note.trim() ? { note: variant.note.trim() } : {}),\n })),\n ...(product.mockupRequests === true ? { mockupRequests: true as const } : {}),\n ...(asksUseDate ? { useDayTimeZone: options.timeZone || 'UTC' } : {}),\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.subscription ? { subscription: product.subscription } : {}),\n ...(product.subscription && product.subscriptionOptional\n ? { subscriptionOptional: true }\n : {}),\n ...(modifierGroups.length ? { modifierGroups } : {}),\n }\n}\n\n/** Whether any variant of a product asks the buyer for a use day (AGL-4043). */\nexport function productAsksUseDateAnywhere(\n product: Pick<ReturnType<typeof CommerceModel.liftLegacyProduct>, 'variants' | 'checkIn'>,\n): boolean {\n return product.variants.some((variant) => CommerceModel.productAsksUseDate(product, variant.id))\n}\n\n/**\n * Public product detail by slug (AGL-292): everything the PDP block\n * needs — variants with per-option prices and stock booleans, never raw\n * counts. Display-only; the charge still prices server-side.\n */\nexport const productHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n const slug = String(req.query.slug ?? '')\n if (!hostId || !slug) {\n return res.status(400).json({ error: 'Missing hostId or slug' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .where('slug', '==', slug)\n .limit(1)\n .get()\n const docSnapshot = snapshot.docs[0]\n const raw = docSnapshot?.data() as any\n // A product sold in person only (AGL-4060) has no page online: the same\n // 404 as a draft, so its address says nothing about it.\n if (!CommerceModel.productListedOnline(raw)) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n // The store's calendar, only for a product that asks for a use day.\n const timeZone = productAsksUseDateAnywhere(product)\n ? (await readStoreDay(firestore.collection('hosts').doc(hostId))).timeZone\n : null\n const detail = toPublicProductDetail(docSnapshot.id, product, { timeZone })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json({ product: detail })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Product unavailable' })\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","readStoreDay","publicModifierGroups","product","websiteModifierGroups","map","group","id","name","min","max","options","option","priceCents","priceCentsByVariant","Object","keys","length","imageUrl","note","trim","modifierOptionIsCombo","includes","toPublicProductDetail","asksUseDate","productAsksUseDateAnywhere","modifierGroups","slug","description","type","mediaUrls","variants","variant","priceUsd","variantHasPrice","compareAtPriceUsd","soldOut","inventory","Number","oversellPolicy","sku","productAsksUseDate","mockupRequests","useDayTimeZone","timeZone","tags","subscription","subscriptionOptional","some","productHandler","req","res","hostId","String","query","status","json","error","firestore","app","snapshot","collection","doc","where","limit","get","docSnapshot","docs","raw","data","productListedOnline","liftLegacyProduct","detail","setHeader","console"],"mappings":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,IAAI;QAC7B,wEAAwE;QACxE,wDAAwD;QACxD,IAAI,CAACtE,cAAcuE,mBAAmB,CAACF,MAAM;YAC3C,OAAOjB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAkB;QACzD;QACA,MAAMtD,UAAUJ,cAAcwE,iBAAiB,CAACH;QAChD,oEAAoE;QACpE,MAAMxB,WAAWnB,2BAA2BtB,WACxC,AAAC,CAAA,MAAMF,aAAayD,UAAUG,UAAU,CAAC,SAASC,GAAG,CAACV,QAAO,EAAGR,QAAQ,GACxE;QACJ,MAAM4B,SAASjD,sBAAsB2C,YAAY3D,EAAE,EAAEJ,SAAS;YAAEyC;QAAS;QACzEO,IAAIsB,SAAS,CACX,iBACA;QAEF,OAAOtB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAErD,SAASqE;QAAO;IAChD,EAAE,OAAOf,OAAO;QACdiB,QAAQjB,KAAK,CAACA;QACd,OAAON,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/product.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { PluginApiHandler } from '@aglyn/aglyn/server'\nimport * as Aglyn from '@aglyn/aglyn/server'\nimport * as CommerceModel from '../model'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { readStoreDay } from './store-day'\n\nexport interface PublicProductDetail {\n id: string\n name: string\n slug: string\n description?: string\n type: CommerceModel.ProductType\n mediaUrls: string[]\n options: CommerceModel.ProductOption[]\n variants: Array<{\n id: string\n options?: Record<string, string>\n /**\n * `null` for a variant listed before it has a price (AGL-3676): the page\n * says \"Price coming soon\" and offers nothing to buy, as no sale door\n * would sell it.\n */\n priceUsd: number | null\n compareAtPriceUsd?: number\n soldOut: boolean\n imageUrl?: string\n /**\n * Merchant's stock-keeping unit (AGL-686). Carried into the public DTO\n * so the server can put `sku` on the Product structured data — Google\n * Merchant treats it as required for a product offer, and without it a\n * listing is simply ineligible for rich results rather than warned about.\n * It is already public information: it prints on receipts and invoices.\n */\n sku?: string\n /**\n * The buyer may choose the day they will use it (a pass bought ahead,\n * AGL-4043): the page offers an optional date. Absent when it does not.\n */\n asksUseDate?: true\n /** A short line on the variant's picture card (AGL-4205). */\n note?: string\n }>\n /**\n * The page offers \"Get a free mockup\" (AGL-4205): the request form the site\n * placed in the product block opens with the shopper's picks.\n */\n mockupRequests?: true\n /**\n * The store's time zone, sent only when a variant asks for a use day, so\n * the page offers no day that has passed on the store's calendar.\n */\n useDayTimeZone?: string\n tags?: string[]\n /** Recurring billing (AGL-303) so the PDP frames the price. */\n subscription?: { interval: 'month' | 'year'; trialDays?: number }\n /** Buyer may choose one-time OR subscribe (AGL-545). */\n subscriptionOptional?: boolean\n /**\n * The add-ons the page offers (AGL-4100): ONLY the groups switched to\n * \"Show on the website\". A register-only group never leaves the server, so\n * a shop's in-person choices and prices are not published. Absent: none.\n * Display-only like the prices above; every sale door prices them again\n * from the product.\n */\n modifierGroups?: PublicModifierGroup[]\n}\n\n/** An add-on group as the product page shows it (AGL-4100). */\nexport interface PublicModifierGroup {\n id: string\n name: string\n min: number\n max: number\n /** A write-in the shopper types (write-ins), with its length and whether it takes numbers only. */\n kind?: CommerceModel.ProductModifierGroupKind\n maxLength?: number\n digitsOnly?: boolean\n nameOnOrder?: boolean\n options: Array<{\n id: string\n name: string\n priceCents: number\n /** What the choice adds on a variant priced differently, by variant id. */\n priceCentsByVariant?: Record<string, number>\n /** The choice's card (AGL-4205): its picture, its note, and what a combo includes. */\n imageUrl?: string\n note?: string\n includes?: string[]\n }>\n}\n\n/** The website add-on groups of a product, in the page's shape (AGL-4100). */\nexport function publicModifierGroups(\n product: { modifierGroups?: unknown },\n): PublicModifierGroup[] {\n return CommerceModel.websiteModifierGroups(product).map((group) => ({\n id: group.id,\n name: group.name,\n min: group.min,\n max: group.max,\n ...(CommerceModel.modifierGroupIsWriteIn(group)\n ? {\n kind: 'text' as const,\n maxLength: CommerceModel.writeInMaxLength(group),\n ...(group.digitsOnly === true ? { digitsOnly: true } : {}),\n }\n : {}),\n ...(group.nameOnOrder === true ? { nameOnOrder: true } : {}),\n options: group.options.map((option) => ({\n id: option.id,\n name: option.name,\n priceCents: option.priceCents,\n ...(option.priceCentsByVariant && Object.keys(option.priceCentsByVariant).length\n ? { priceCentsByVariant: { ...option.priceCentsByVariant } }\n : {}),\n // Card fields are checked at save (`modifierCardsProblem`), not on this\n // read, so only well-formed values reach the page (AGL-4205).\n ...(typeof option.imageUrl === 'string' && option.imageUrl ? { imageUrl: option.imageUrl } : {}),\n ...(typeof option.note === 'string' && option.note.trim() ? { note: option.note.trim() } : {}),\n ...(CommerceModel.modifierOptionIsCombo(option) ? { includes: [...(option.includes ?? [])] } : {}),\n })),\n }))\n}\n\n/**\n * Map a lifted product onto the public PDP DTO.\n *\n * Extracted (AGL-659) so the site-page resolver can put the SAME payload\n * into page props as the API returns — the PDP block used to fetch this in\n * an effect, which meant the server rendered a skeleton and crawlers saw a\n * product page with no product in it. One definition keeps the server-\n * rendered and client-fetched shapes from drifting.\n *\n * Display-only by design: stock is a `soldOut` boolean rather than a raw\n * count, and the charge still prices server-side.\n */\nexport function toPublicProductDetail(\n id: string,\n product: ReturnType<typeof CommerceModel.liftLegacyProduct>,\n options: { timeZone?: string | null } = {},\n): PublicProductDetail {\n const asksUseDate = productAsksUseDateAnywhere(product)\n const modifierGroups = publicModifierGroups(product)\n return {\n id,\n name: product.name,\n slug: product.slug,\n ...(product.description ? { description: product.description } : {}),\n type: product.type,\n mediaUrls:\n product.mediaUrls ?? (product.imageUrl ? [product.imageUrl] : []),\n options: product.options ?? [],\n variants: product.variants.map((variant) => ({\n id: variant.id,\n ...(variant.options ? { options: variant.options } : {}),\n priceUsd: CommerceModel.variantHasPrice(variant) ? variant.priceUsd : null,\n ...(variant.compareAtPriceUsd\n ? { compareAtPriceUsd: variant.compareAtPriceUsd }\n : {}),\n soldOut:\n variant.inventory != null &&\n Number(variant.inventory) <= 0 &&\n product.oversellPolicy !== 'backorder',\n ...(variant.imageUrl ? { imageUrl: variant.imageUrl } : {}),\n ...(variant.sku ? { sku: variant.sku } : {}),\n ...(CommerceModel.productAsksUseDate(product, variant.id) ? { asksUseDate: true as const } : {}),\n ...(typeof variant.note === 'string' && variant.note.trim() ? { note: variant.note.trim() } : {}),\n })),\n ...(product.mockupRequests === true ? { mockupRequests: true as const } : {}),\n ...(asksUseDate ? { useDayTimeZone: options.timeZone || 'UTC' } : {}),\n ...(product.tags?.length ? { tags: product.tags } : {}),\n ...(product.subscription ? { subscription: product.subscription } : {}),\n ...(product.subscription && product.subscriptionOptional\n ? { subscriptionOptional: true }\n : {}),\n ...(modifierGroups.length ? { modifierGroups } : {}),\n }\n}\n\n/** Whether any variant of a product asks the buyer for a use day (AGL-4043). */\nexport function productAsksUseDateAnywhere(\n product: Pick<ReturnType<typeof CommerceModel.liftLegacyProduct>, 'variants' | 'checkIn'>,\n): boolean {\n return product.variants.some((variant) => CommerceModel.productAsksUseDate(product, variant.id))\n}\n\n/**\n * Public product detail by slug (AGL-292): everything the PDP block\n * needs — variants with per-option prices and stock booleans, never raw\n * counts. Display-only; the charge still prices server-side.\n */\nexport const productHandler: PluginApiHandler = async (req, res) => {\n const hostId = String(req.query.hostId ?? '')\n const slug = String(req.query.slug ?? '')\n if (!hostId || !slug) {\n return res.status(400).json({ error: 'Missing hostId or slug' })\n }\n try {\n const firestore = firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection('hosts')\n .doc(hostId)\n .collection('products')\n .where('slug', '==', slug)\n .limit(1)\n .get()\n const docSnapshot = snapshot.docs[0]\n const raw = docSnapshot?.data() as any\n // A product sold in person only (AGL-4060) has no page online: the same\n // 404 as a draft, so its address says nothing about it.\n if (!CommerceModel.productListedOnline(raw)) {\n return res.status(404).json({ error: 'Unknown product' })\n }\n const product = CommerceModel.liftLegacyProduct(raw)\n // The store's calendar, only for a product that asks for a use day.\n const timeZone = productAsksUseDateAnywhere(product)\n ? (await readStoreDay(firestore.collection('hosts').doc(hostId))).timeZone\n : null\n const detail = toPublicProductDetail(docSnapshot.id, product, { timeZone })\n res.setHeader(\n 'Cache-Control',\n 'public, s-maxage=60, stale-while-revalidate=300',\n )\n return res.status(200).json({ product: detail })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Product unavailable' })\n }\n}\n"],"names":["CommerceModel","firebaseAdmin","readStoreDay","publicModifierGroups","product","websiteModifierGroups","map","group","id","name","min","max","modifierGroupIsWriteIn","kind","maxLength","writeInMaxLength","digitsOnly","nameOnOrder","options","option","priceCents","priceCentsByVariant","Object","keys","length","imageUrl","note","trim","modifierOptionIsCombo","includes","toPublicProductDetail","asksUseDate","productAsksUseDateAnywhere","modifierGroups","slug","description","type","mediaUrls","variants","variant","priceUsd","variantHasPrice","compareAtPriceUsd","soldOut","inventory","Number","oversellPolicy","sku","productAsksUseDate","mockupRequests","useDayTimeZone","timeZone","tags","subscription","subscriptionOptional","some","productHandler","req","res","hostId","String","query","status","json","error","firestore","app","snapshot","collection","doc","where","limit","get","docSnapshot","docs","raw","data","productListedOnline","liftLegacyProduct","detail","setHeader","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID,YAAYA,mBAAmB,oBAAU;AACzC,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,YAAY,QAAQ,iBAAa;AAuF1C,4EAA4E,GAC5E,OAAO,SAASC,qBACdC,OAAqC;IAErC,OAAO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MF,+BAAAA,YAAaG,IAAI;QAC7B,wEAAwE;QACxE,wDAAwD;QACxD,IAAI,CAAC5E,cAAc6E,mBAAmB,CAACF,MAAM;YAC3C,OAAOjB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAAkB;QACzD;QACA,MAAM5D,UAAUJ,cAAc8E,iBAAiB,CAACH;QAChD,oEAAoE;QACpE,MAAMxB,WAAWnB,2BAA2B5B,WACxC,AAAC,CAAA,MAAMF,aAAa+D,UAAUG,UAAU,CAAC,SAASC,GAAG,CAACV,QAAO,EAAGR,QAAQ,GACxE;QACJ,MAAM4B,SAASjD,sBAAsB2C,YAAYjE,EAAE,EAAEJ,SAAS;YAAE+C;QAAS;QACzEO,IAAIsB,SAAS,CACX,iBACA;QAEF,OAAOtB,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAE3D,SAAS2E;QAAO;IAChD,EAAE,OAAOf,OAAO;QACdiB,QAAQjB,KAAK,CAACA;QACd,OAAON,IAAII,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAsB;IAC7D;AACF,EAAC"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import type { SitePageResolver } from '@aglyn/aglyn/server';
17
+ import type { SiteEditContextResolver, SitePageResolver } from '@aglyn/aglyn/server';
18
18
  import * as Aglyn from '@aglyn/aglyn/server';
19
19
  import * as CommerceModel from '../model';
20
20
  /**
@@ -26,6 +26,17 @@ import * as CommerceModel from '../model';
26
26
  * undefined for everything else so the loader falls through.
27
27
  */
28
28
  export declare const commerceSitePageResolver: SitePageResolver;
29
+ /**
30
+ * What the admin edit bar says on the pages the resolver above composes. They
31
+ * are in no routing map, so the bar called a product page "Unrouted page" with
32
+ * no edit link. It answers from the same reads the page is built from: the
33
+ * store's designated template (`pdpScreenId`, `collectionScreenId`), and for
34
+ * a product page the product itself, whose editor the bar links beside the
35
+ * template's Besigner, as it does for a blog post. A product the page would
36
+ * not render (not live, or not sold online) gets no answer, as it gets no
37
+ * page.
38
+ */
39
+ export declare const commerceEditContextResolver: SiteEditContextResolver;
29
40
  export { productPriceText } from '../model';
30
41
  /**
31
42
  * The store's built-in product page (AGL-3676), root first, for the layout's