@aglyn/plugins-commerce 1.29.3 → 1.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -13
- package/src/lib/components/cart.js +11 -5
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/pos/pos-item-dialog.component.js +12 -0
- package/src/lib/components/console/pos/pos-item-dialog.component.js.map +1 -1
- package/src/lib/components/console/pos-kiosk-page.component.js +3 -5
- package/src/lib/components/console/pos-kiosk-page.component.js.map +1 -1
- package/src/lib/components/console/product-add-ons-fields.component.d.ts +11 -0
- package/src/lib/components/console/product-add-ons-fields.component.js +229 -13
- package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +5 -0
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/product-traffic-card.component.d.ts +24 -0
- package/src/lib/components/console/product-traffic-card.component.js +172 -0
- package/src/lib/components/console/product-traffic-card.component.js.map +1 -0
- package/src/lib/components/console/products-hub-card.component.js +181 -59
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-editor-dialog.component.js +38 -0
- package/src/lib/components/console/quote-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +31 -9
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/product-add-ons.d.ts +21 -0
- package/src/lib/components/product-add-ons.js +77 -1
- package/src/lib/components/product-add-ons.js.map +1 -1
- package/src/lib/components/product-builder-mockup.d.ts +1 -1
- package/src/lib/components/product-builder-mockup.js +17 -5
- package/src/lib/components/product-builder-mockup.js.map +1 -1
- package/src/lib/components/product-choice-cards.js +14 -2
- package/src/lib/components/product-choice-cards.js.map +1 -1
- package/src/lib/model/commerce-pos-kiosk.js +8 -2
- package/src/lib/model/commerce-pos-kiosk.js.map +1 -1
- package/src/lib/model/commerce-pos-offline.d.ts +1 -1
- package/src/lib/model/commerce-pos-offline.js +8 -2
- package/src/lib/model/commerce-pos-offline.js.map +1 -1
- package/src/lib/model/commerce-quote-request.d.ts +1 -0
- package/src/lib/model/commerce-quote-request.js +6 -2
- package/src/lib/model/commerce-quote-request.js.map +1 -1
- package/src/lib/model/commerce-quotes.js +10 -5
- package/src/lib/model/commerce-quotes.js.map +1 -1
- package/src/lib/model/commerce-record-routes.js +31 -0
- package/src/lib/model/commerce-record-routes.js.map +1 -1
- package/src/lib/model/commerce-shipping.d.ts +39 -16
- package/src/lib/model/commerce-shipping.js +315 -30
- package/src/lib/model/commerce-shipping.js.map +1 -1
- package/src/lib/model/commerce.js +1 -1
- package/src/lib/model/commerce.js.map +1 -1
- package/src/lib/model/product-modifiers.d.ts +53 -2
- package/src/lib/model/product-modifiers.js +127 -27
- package/src/lib/model/product-modifiers.js.map +1 -1
- package/src/lib/model/product-write.d.ts +10 -1
- package/src/lib/model/product-write.js +13 -2
- package/src/lib/model/product-write.js.map +1 -1
- package/src/lib/server/carrier-shipping.js +3 -2
- package/src/lib/server/carrier-shipping.js.map +1 -1
- package/src/lib/server/cart-checkout.js +10 -4
- package/src/lib/server/cart-checkout.js.map +1 -1
- package/src/lib/server/cart.js +2 -2
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/checkout.js +6 -4
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/draft-order.js +3 -3
- package/src/lib/server/draft-order.js.map +1 -1
- package/src/lib/server/pos-kiosk.js +1 -4
- package/src/lib/server/pos-kiosk.js.map +1 -1
- package/src/lib/server/product.d.ts +5 -0
- package/src/lib/server/product.js +10 -2
- package/src/lib/server/product.js.map +1 -1
- package/src/lib/server/products-write.js +10 -2
- package/src/lib/server/products-write.js.map +1 -1
- package/src/lib/transfer/product-register-cells.d.ts +7 -0
- package/src/lib/transfer/product-register-cells.js +88 -10
- package/src/lib/transfer/product-register-cells.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/products-write.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 { validateProductForSave } from '../model/product-card-rules'\nimport { createHash } from 'node:crypto'\nimport { holdsSiteKey, hostStampedSitePermission, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getLockdownVerdict, getOrgForHost, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n type EditedProduct,\n liftLegacyProduct,\n productCollectionIds,\n productDuplicateFields,\n productDuplicateName,\n productDuplicateSlugBase,\n productEditWrite,\n productMembershipInput,\n productSaveFields,\n smartCollectionRulesOf,\n stockAdjustmentWrite,\n variantMatrixProblem,\n type InventoryAdjustmentReason,\n} from '../model'\nimport { planRefusal, roomRefusal } from './product-drafts'\n\n/*\n * `POST /api/commerce/products/save` and `POST /api/commerce/products/stock`\n * (AGL-3652): the console product editor's save and its Adjust stock dialog,\n * for the native apps.\n *\n * The console makes both writes from the browser, computing derived fields\n * first (search keys, stock verdict, price, image, smart-collection\n * membership). These routes run THAT computation (`model/product-write.ts`,\n * which the console imports too) and make the same writes, under the gate\n * the Firestore rules put on them: a verified member with a write role on the\n * site (`canWriteHostContent`), or staff, while the site, its org and the\n * platform are not frozen (`hostWritesFrozen`). A new product also meets the\n * create path's own door: the plan's `commerce` entitlement and its\n * `productsPerHost` quota, counted in the same transaction as the create.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const ROLE_REFUSAL = siteKeyRefusal('site.edit')\nconst MAX_BODY_BYTES = 256_000\n\n/** The reasons the Adjust stock dialog offers. */\nexport const STOCK_ADJUST_REASONS: readonly InventoryAdjustmentReason[] = ['restock', 'correction', 'damage', 'refund']\n\nexport interface ProductsWriteDeps {\n firestore?: () => Firestore\n verifyIdToken?: (token: string) => Promise<Record<string, unknown> & { uid: string }>\n orgForHost?: (hostId: string) => Promise<{ org: Record<string, unknown> } | null>\n lockdown?: (options: Parameters<typeof getLockdownVerdict>[0]) => Promise<unknown>\n dropCache?: typeof dropPluginSiteCache\n now?: () => number\n}\n\ntype Reply = Parameters<PluginApiHandler>[1]\n\nexport function bodyOf(req: Parameters<PluginApiHandler>[0]): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n if (raw.length > MAX_BODY_BYTES) return {}\n try {\n return JSON.parse(raw || '{}')\n } catch {\n return {}\n }\n }\n return (raw ?? {}) as Record<string, unknown>\n}\n\nexport const validId = (value: unknown): value is string =>\n typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value)\n\nexport interface Gate {\n uid: string\n /** The caller's address, for an activity line; null when the token has none. */\n email: string | null\n staff: boolean\n host: FirebaseFirestore.DocumentSnapshot\n org: Record<string, unknown>\n}\n\n/**\n * The permission a route built on {@link gate} checks instead of the site\n * role (AGL-4047): a key whose preset is the site role, that preset (the\n * declaring plugin's own table, so the answer does not depend on which\n * plugins this process loaded), and the refusal naming it.\n */\nexport interface GatePermission {\n key: string\n presetFor: Readonly<Record<HostAccessRole, boolean>>\n refusal: string\n}\n\n/**\n * Who may write this site's products, as the rules decide it. Answers the\n * caller's reply on a refusal and returns null.\n *\n * A route that is not about products names the key it checks instead\n * (`permission`, AGL-4047): the walk-in and the guests change ask their\n * reservation key, read as the rules read it, from the site's\n * `memberPermissions` stamp, else the preset of the member's `memberRoles`\n * entry, so the route and the rules give one answer. Without it, the\n * product routes ask \"Edit site content\" (`site.edit`) the same way.\n */\nexport async function gate(\n req: Parameters<PluginApiHandler>[0],\n res: Reply,\n hostId: string,\n deps: Required<ProductsWriteDeps>,\n options: { permission?: GatePermission } = {},\n): Promise<Gate | null> {\n const authorization = String(req.headers.authorization ?? '')\n const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!token) return void res.status(401).json({ error: 'Unauthenticated' }), null\n let decoded: Record<string, unknown> & { uid: string }\n try {\n decoded = await deps.verifyIdToken(token)\n } catch (error) {\n // Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return void res.status(401).json({ error: 'Sign in again to continue' }), null\n }\n const staff = decoded['staff'] === true\n if (!staff && decoded['email_verified'] !== true && !isImpersonationSession(decoded as never)) {\n return void res.status(403).json({ error: 'Verify your email address to make changes' }), null\n }\n const host = await deps.firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return void res.status(404).json({ error: 'Unknown site' }), null\n if (!staff) {\n const { permission } = options\n const allowed = permission\n ? hostStampedSitePermission(host.data(), decoded.uid, permission.key, permission.presetFor)\n : holdsSiteKey(host, decoded.uid, 'site.edit')\n if (!allowed) return void res.status(403).json({ error: permission?.refusal ?? ROLE_REFUSAL }), null\n }\n const org = ((await deps.orgForHost(hostId))?.org ?? {}) as Record<string, unknown>\n const locked = await deps.lockdown({ staff, uid: decoded.uid, org: org as never, host: host.data() as never, request: { method: 'POST' } as never })\n if (locked) return void res.status(423).json({ error: 'This site is not accepting changes right now' }), null\n const email = typeof decoded['email'] === 'string' ? decoded['email'] : null\n return { uid: decoded.uid, email, staff, host, org }\n}\n\n/** The site-wide cache drop a product change is owed (AGL-3386): an outbox entry in the write, then the drop. */\nexport function outboxEntry(firestore: Firestore, hostId: string) {\n return {\n ref: firestore.collection('publishOutbox').doc(createResourceUid()),\n data: { hostId, paths: ['/'], createdAt: FieldValue.serverTimestamp(), attempts: 0, entireHost: true },\n }\n}\n\nexport async function settleCache(deps: Pick<Required<ProductsWriteDeps>, 'dropCache'>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string) {\n const dropped = await deps.dropCache({ hostIds: [hostId], reason }).catch(() => ({ complete: false }))\n if (dropped.complete) await entry.delete().catch(() => undefined)\n}\n\nexport function resolved(deps: ProductsWriteDeps): Required<ProductsWriteDeps> {\n return {\n firestore: deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore),\n verifyIdToken: deps.verifyIdToken ?? ((token) => firebaseAdmin.app().auth().verifyIdToken(token) as never),\n orgForHost: deps.orgForHost ?? ((hostId) => getOrgForHost(hostId) as never),\n lockdown: deps.lockdown ?? ((options) => getLockdownVerdict(options)),\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n now: deps.now ?? (() => Date.now()),\n }\n}\n\n/** Why a product save or delete was refused, for its caller to answer in its own words. */\nexport type ProductWriteRefusalCode =\n /** The product fails the editor's rules (`variantMatrixProblem`, `validateProductForSave`). */\n | 'invalid'\n /** The plan does not include commerce. */\n | 'plan'\n /** The plan's product allowance is used up. */\n | 'quota'\n /** The product does not exist, or was deleted. */\n | 'missing'\n /** Another product holds the slug (only asked with `uniqueSlug`). */\n | 'slug_taken'\n /** A refusal the caller's own `product` builder made. */\n | 'refused'\n\nexport interface ProductWriteRefusal {\n ok: false\n status: number\n code: ProductWriteRefusalCode\n error: string\n /** What a builder's refusal names, for its caller. */\n detail?: unknown\n}\n\nexport type ProductSaveResult = { ok: true; id: string; replayed: boolean } | ProductWriteRefusal\n\n/** A refusal a {@link ProductSaveInput.product} builder answers instead of a product. */\nexport interface ProductBuildRefusal {\n refusal: { status: number; error: string; detail?: unknown }\n}\n\n/**\n * One product save, already authorized (AGL-4235): the console editor's\n * write, whoever asks for it. The native apps' save route and the public\n * API's product writes both call this, so the derived fields, the checks, the\n * smart-collection membership, the plan and allowance count, the publish\n * outbox and the cache drop are made once.\n *\n * The caller has decided who may write this site. Nothing here asks.\n */\nexport interface ProductSaveInput {\n firestore: Firestore\n hostId: string\n productId: string\n /** A new product under `productId` (a retry finds its own and answers `replayed`), or an edit of the live one. */\n create: boolean\n /**\n * The product to save, or how to make it from the stored document read in\n * the save's own transaction, so an edit merged onto it cannot lose a\n * change made between a read and the write.\n */\n product: EditedProduct | ((stored: FirebaseFirestore.DocumentSnapshot) => EditedProduct | ProductBuildRefusal)\n /** The organization the plan and the allowance are read from. */\n org: Record<string, unknown>\n /** Who a create is `createdBy`: a person's uid, or null when no person made it. */\n createdBy: string | null\n /** Further fields a create stamps, such as the API credential that made it. */\n createStamps?: Record<string, unknown>\n /** Refuse a slug another product of the site holds, live or deleted. */\n uniqueSlug?: boolean\n nowMs: number\n dropCache: Required<ProductsWriteDeps>['dropCache']\n /** What the cache drop says caused it. */\n cacheReason: string\n}\n\nconst isBuildRefusal = (value: unknown): value is ProductBuildRefusal =>\n Boolean(value && typeof value === 'object' && 'refusal' in (value as object))\n\n/**\n * Saves a product as the console editor does: `create` makes a new product\n * under `productId`; otherwise it replaces the live product, keeping its live\n * stock holds and the stored timestamps the product does not name.\n */\nexport async function saveProduct(input: ProductSaveInput): Promise<ProductSaveResult> {\n const { firestore: db, hostId, productId, create, nowMs } = input\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(productId)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductSaveResult> => {\n const [existing, smart] = await Promise.all([tx.get(productRef), tx.get(smartQuery)])\n const built = typeof input.product === 'function' ? input.product(existing) : input.product\n if (isBuildRefusal(built)) {\n return { ok: false, code: 'refused', ...built.refusal }\n }\n const product = built\n const fields = productSaveFields(product, nowMs)\n // More combinations than a product holds is refused with the count\n // (AGL-4100), never saved short of the options it names.\n const problem = variantMatrixProblem(fields.options) ?? validateProductForSave(fields as never)\n if (problem) return { ok: false, status: 400, code: 'invalid', error: problem }\n if (input.uniqueSlug) {\n const holders = await tx.get(products.where('slug', '==', fields.slug).limit(2))\n if (holders.docs.some((doc) => doc.id !== productId)) {\n return { ok: false, status: 409, code: 'slug_taken', error: `Another product already uses the slug “${fields.slug}”` }\n }\n }\n const membership = {\n collectionIds: productCollectionIds(\n productMembershipInput(fields, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n ),\n }\n if (create) {\n if (existing.exists) return { ok: true, id: productId, replayed: true }\n const early = planRefusal(input.org as never)\n if (early) return { ok: false, status: early.status, code: 'plan', error: early.error }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(input.org as never, Number(used) || 0)\n if (room) return { ok: false, status: room.status, code: 'quota', error: room.error }\n tx.create(productRef, {\n ...fields,\n ...membership,\n createdAtMs: nowMs,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: input.createdBy,\n ...(input.createStamps ?? {}),\n })\n } else {\n if (!existing.exists || existing.get('deletedAt')) {\n return { ok: false, status: 404, code: 'missing', error: 'This product was deleted' }\n }\n tx.set(productRef, {\n ...storedTimestamps(existing.data() ?? {}, product as unknown as Record<string, unknown>),\n ...productEditWrite(fields, existing.get('stockHolds')),\n ...membership,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n tx.set(outbox.ref, outbox.data)\n return { ok: true, id: productId, replayed: false }\n })\n if (answer.ok && !answer.replayed) {\n await settleCache({ dropCache: input.dropCache }, hostId, outbox.ref, input.cacheReason)\n }\n return answer\n}\n\n/**\n * Saves a product as the console editor does. `create: true` makes a new\n * product under the client-minted `productId` (a retry finds its own product\n * and answers `replayed`); otherwise it replaces the live product, keeping\n * its live stock holds.\n */\nexport function createProductSaveHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const product = body['product'] as EditedProduct | undefined\n if (!validId(hostId) || !validId(productId) || !product || typeof product !== 'object' || !Array.isArray(product.variants)) {\n return res.status(400).json({ error: 'Missing site, product or its variants' })\n }\n if (typeof product.name !== 'string' || !product.name.trim()) return res.status(400).json({ error: 'Product name is required' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const saved = await saveProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n create: body['create'] === true,\n product,\n org: door.org,\n createdBy: door.uid,\n nowMs: deps.now(),\n dropCache: deps.dropCache,\n cacheReason: 'product saved from the app',\n })\n if (saved.ok === false) return res.status(saved.status).json({ error: saved.error })\n return res.status(200).json({ ok: true, id: saved.id, replayed: saved.replayed })\n } catch (error) {\n console.error('[commerce/products/save]', error)\n return res.status(500).json({ error: 'The product could not be saved' })\n }\n }\n}\n\n/**\n * The stored timestamps an edit keeps. The console's replace writes back the\n * Timestamps its seed carried (`createdAt`, a publish time); a client's JSON\n * cannot carry one, so each stored Timestamp field the request does not name\n * is kept as stored.\n */\nexport function storedTimestamps(stored: Record<string, unknown>, asked: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(stored).filter(\n ([key, value]) => !(key in asked) && typeof (value as { toDate?: unknown } | null)?.toDate === 'function',\n ),\n )\n}\n\n/** The ledger row id one attempt owns: the same key from the same member is the same row. */\nexport function stockAttemptId(uid: string, key: string): string {\n return 'app-' + createHash('sha256').update(`${uid}:${key}`).digest('hex').slice(0, 40)\n}\n\n/**\n * Adjusts one variant's stock as the Adjust stock dialog does: the variants\n * and stock fields on the product, and one `inventoryAdjustments` row, in one\n * transaction. The Idempotency-Key names that row, so a retried attempt finds\n * it and moves nothing twice.\n */\nexport function createProductStockHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const variantId = body['variantId']\n const key = String(req.headers['idempotency-key'] ?? '').trim().slice(0, 200)\n const reason = body['reason'] as InventoryAdjustmentReason\n const delta = Math.round(Number(body['delta']))\n const locationId = typeof body['locationId'] === 'string' && body['locationId'] ? body['locationId'] : undefined\n if (!validId(hostId) || !validId(productId) || typeof variantId !== 'string' || !variantId) {\n return res.status(400).json({ error: 'Missing site, product or variant' })\n }\n if (!key) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!STOCK_ADJUST_REASONS.includes(reason)) return res.status(400).json({ error: 'Unknown reason' })\n if (!Number.isFinite(delta) || delta === 0) return res.status(400).json({ error: 'Enter a number of units' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const productRef = hostRef.collection('products').doc(productId)\n const ledgerRef = hostRef.collection('inventoryAdjustments').doc(stockAttemptId(door.uid, key))\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [ledger, stored] = await Promise.all([tx.get(ledgerRef), tx.get(productRef)])\n if (ledger.exists) {\n return { status: 200, body: { ok: true, replayed: true, inventory: stored.get('inventory') ?? null } }\n }\n if (!stored.exists || stored.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n const product = stored.data() as never as Parameters<typeof stockAdjustmentWrite>[0]\n if (!(product.variants ?? []).some((variant) => variant.id === variantId)) {\n return { status: 404, body: { error: 'That variant is no longer on this product' } }\n }\n const write = stockAdjustmentWrite(product, productId, { variantId, delta, reason, locationId }, deps.now())\n if (!write) return { status: 400, body: { error: 'Enter a number of units' } }\n tx.update(productRef, write.update)\n tx.create(ledgerRef, write.ledger)\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, replayed: false, inventory: (write.update as { inventory?: unknown }).inventory ?? null } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'stock adjusted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/stock]', error)\n return res.status(500).json({ error: 'Stock could not be adjusted' })\n }\n }\n}\n\n/**\n * The first slug in `base`, `base-2`, `base-3`… no product of the site holds,\n * as the console's slug ledger claims one (`product-slugs.ts`): a second\n * Duplicate of the same product does not mint a second `-copy` (AGL-3321).\n */\nexport async function claimProductSlug(products: FirebaseFirestore.CollectionReference, base: string): Promise<string> {\n for (let suffix = 1; suffix < 1000; suffix += 1) {\n const candidate = suffix < 2 ? base : `${base}-${suffix}`\n const held = await products.where('slug', '==', candidate).limit(1).get()\n if (held.empty) return candidate\n }\n return `${base}-${Date.now()}`\n}\n\n/**\n * `POST /api/commerce/products/duplicate` (AGL-3841): the products list's\n * Duplicate for the native apps. The console builds the copy in the browser\n * (`productDuplicateFields`, its slug ledger, the copy's smart collections)\n * and creates it through the quota-enforcing resources route; this runs the\n * same model over the stored product and creates it under the save route's\n * create door (the plan's commerce entitlement and its product quota, counted\n * in the same transaction). `newProductId` is the client's, so a retry finds\n * its own copy and answers `replayed`.\n */\nexport function createProductDuplicateHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId, newProductId } = body\n if (!validId(hostId) || !validId(productId) || !validId(newProductId) || productId === newProductId) {\n return res.status(400).json({ error: 'Missing site or product' })\n }\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const copyRef = products.doc(newProductId)\n const already = await copyRef.get()\n if (already.exists) return res.status(200).json({ ok: true, id: newProductId, replayed: true })\n const source = await products.doc(productId).get()\n if (!source.exists || source.get('deletedAt')) return res.status(404).json({ error: 'This product was deleted' })\n const product = liftLegacyProduct((source.data() ?? {}) as never)\n const slug = await claimProductSlug(products, productDuplicateSlugBase(product.slug, product.name))\n const nowMs = deps.now()\n const fields = productDuplicateFields(product, slug, nowMs)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart] = await Promise.all([tx.get(copyRef), tx.get(smartQuery)])\n if (existing.exists) return { status: 200, body: { ok: true, id: newProductId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n // The COPY's smart collections: its name differs from the source's.\n const collectionIds = productCollectionIds(\n productMembershipInput({ name: productDuplicateName(product.name) }, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n )\n tx.create(copyRef, {\n ...fields,\n collectionIds,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: newProductId, replayed: false, slug } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product duplicated from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/duplicate]', error)\n return res.status(500).json({ error: 'Could not duplicate product' })\n }\n }\n}\n\nexport type ProductDeleteResult = { ok: true; already: boolean } | ProductWriteRefusal\n\n/**\n * The products list's Delete, already authorized (AGL-4235): `deletedAt` on\n * the product, which stops it being purchasable, with the publish outbox\n * entry and the site-wide cache drop. A deleted product answers `already`.\n * The native apps' delete route and the public API both call this.\n */\nexport async function deleteProduct(input: {\n firestore: Firestore\n hostId: string\n productId: string\n dropCache: Required<ProductsWriteDeps>['dropCache']\n cacheReason: string\n}): Promise<ProductDeleteResult> {\n const { firestore: db, hostId, productId } = input\n const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductDeleteResult> => {\n const stored = await tx.get(productRef)\n if (!stored.exists) return { ok: false, status: 404, code: 'missing', error: 'This product no longer exists' }\n if (stored.get('deletedAt')) return { ok: true, already: true }\n tx.update(productRef, { deletedAt: FieldValue.serverTimestamp() })\n tx.set(outbox.ref, outbox.data)\n return { ok: true, already: false }\n })\n if (answer.ok && !answer.already) await settleCache(input, hostId, outbox.ref, input.cacheReason)\n return answer\n}\n\n/**\n * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete\n * for the native apps, the console's write (`deletedAt` on the product, which\n * stops it being purchasable) with the site-wide cache drop, under the save\n * route's gate. Deleting a deleted product answers `already`.\n */\nexport function createProductDeleteHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId } = body\n if (!validId(hostId) || !validId(productId)) return res.status(400).json({ error: 'Missing site or product' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const removed = await deleteProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n dropCache: deps.dropCache,\n cacheReason: 'product deleted from the app',\n })\n if (removed.ok === false) return res.status(removed.status).json({ error: removed.error })\n return res.status(200).json({ ok: true, already: removed.already })\n } catch (error) {\n console.error('[commerce/products/delete]', error)\n return res.status(500).json({ error: 'Could not delete product' })\n }\n }\n}\n\nexport const productSaveHandler = createProductSaveHandler()\nexport const productStockHandler = createProductStockHandler()\nexport const productDuplicateHandler = createProductDuplicateHandler()\nexport const productDeleteHandler = createProductDeleteHandler()\n"],"names":["validateProductForSave","createHash","holdsSiteKey","hostStampedSitePermission","siteKeyRefusal","isRefusedIdToken","createResourceUid","countLiveDocuments","dropPluginSiteCache","firebaseAdmin","getLockdownVerdict","getOrgForHost","isImpersonationSession","FieldValue","liftLegacyProduct","productCollectionIds","productDuplicateFields","productDuplicateName","productDuplicateSlugBase","productEditWrite","productMembershipInput","productSaveFields","smartCollectionRulesOf","stockAdjustmentWrite","variantMatrixProblem","planRefusal","roomRefusal","ROLE_REFUSAL","MAX_BODY_BYTES","STOCK_ADJUST_REASONS","bodyOf","req","raw","body","length","JSON","parse","validId","value","test","gate","res","hostId","deps","options","authorization","String","headers","token","startsWith","slice","status","json","error","decoded","verifyIdToken","staff","host","firestore","collection","doc","get","exists","permission","allowed","data","uid","key","presetFor","refusal","org","orgForHost","locked","lockdown","request","method","email","outboxEntry","ref","paths","createdAt","serverTimestamp","attempts","entireHost","settleCache","entry","reason","dropped","dropCache","hostIds","catch","complete","delete","undefined","resolved","app","auth","now","Date","isBuildRefusal","Boolean","saveProduct","input","db","productId","create","nowMs","hostRef","products","productRef","smartQuery","where","outbox","answer","runTransaction","tx","existing","smart","Promise","all","built","product","ok","code","fields","problem","uniqueSlug","holders","slug","limit","docs","some","id","membership","collectionIds","map","replayed","early","used","aggregate","room","Number","createdAtMs","deletedAt","updatedAt","createdBy","createStamps","set","storedTimestamps","cacheReason","createProductSaveHandler","Array","isArray","variants","name","trim","door","saved","console","stored","asked","Object","fromEntries","entries","filter","toDate","stockAttemptId","update","digest","createProductStockHandler","variantId","delta","Math","round","locationId","includes","isFinite","ledgerRef","ledger","inventory","variant","write","claimProductSlug","base","suffix","candidate","held","empty","createProductDuplicateHandler","newProductId","source","copyRef","already","deleteProduct","createProductDeleteHandler","removed","productSaveHandler","productStockHandler","productDuplicateHandler","productDeleteHandler"],"mappings":";AAA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C;gBAAEC,OAAO8I,QAAQ9I,KAAK;YAAC;YACxF,OAAOZ,IAAIU,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEsE,IAAI;gBAAMsE,SAASG,QAAQH,OAAO;YAAC;QACnE,EAAE,OAAO3I,OAAO;YACdyG,QAAQzG,KAAK,CAAC,8BAA8BA;YAC5C,OAAOZ,IAAIU,MAAM,CAAC,KAAKC,IAAI,CAAC;gBAAEC,OAAO;YAA2B;QAClE;IACF;AACF;AAEA,OAAO,MAAM+I,qBAAqB9C,2BAA0B;AAC5D,OAAO,MAAM+C,sBAAsB5B,4BAA2B;AAC9D,OAAO,MAAM6B,0BAA0BV,gCAA+B;AACtE,OAAO,MAAMW,uBAAuBL,6BAA4B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/commerce/src/lib/server/products-write.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 { validateProductForSave } from '../model/product-card-rules'\nimport { createHash } from 'node:crypto'\nimport { holdsSiteKey, hostStampedSitePermission, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport { countLiveDocuments } from '@aglyn/aglyn/app-utils/live-document-count'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getLockdownVerdict, getOrgForHost, isImpersonationSession } from '@aglyn/tenant-data-admin'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport {\n type EditedProduct,\n liftLegacyProduct,\n productCollectionIds,\n productDuplicateFields,\n productDuplicateName,\n productDuplicateSlugBase,\n productEditWrite,\n productMembershipInput,\n productSaveFields,\n smartCollectionRulesOf,\n stockAdjustmentWrite,\n variantMatrixProblem,\n type InventoryAdjustmentReason,\n} from '../model'\nimport { planRefusal, roomRefusal } from './product-drafts'\n\n/*\n * `POST /api/commerce/products/save` and `POST /api/commerce/products/stock`\n * (AGL-3652): the console product editor's save and its Adjust stock dialog,\n * for the native apps.\n *\n * The console makes both writes from the browser, computing derived fields\n * first (search keys, stock verdict, price, image, smart-collection\n * membership). These routes run THAT computation (`model/product-write.ts`,\n * which the console imports too) and make the same writes, under the gate\n * the Firestore rules put on them: a verified member with a write role on the\n * site (`canWriteHostContent`), or staff, while the site, its org and the\n * platform are not frozen (`hostWritesFrozen`). A new product also meets the\n * create path's own door: the plan's `commerce` entitlement and its\n * `productsPerHost` quota, counted in the same transaction as the create.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** Names \"Edit site content\" (`site.edit`, AGL-4047), never a role. */\nexport const ROLE_REFUSAL = siteKeyRefusal('site.edit')\nconst MAX_BODY_BYTES = 256_000\n\n/** The reasons the Adjust stock dialog offers. */\nexport const STOCK_ADJUST_REASONS: readonly InventoryAdjustmentReason[] = ['restock', 'correction', 'damage', 'refund']\n\nexport interface ProductsWriteDeps {\n firestore?: () => Firestore\n verifyIdToken?: (token: string) => Promise<Record<string, unknown> & { uid: string }>\n orgForHost?: (hostId: string) => Promise<{ org: Record<string, unknown> } | null>\n lockdown?: (options: Parameters<typeof getLockdownVerdict>[0]) => Promise<unknown>\n dropCache?: typeof dropPluginSiteCache\n now?: () => number\n}\n\ntype Reply = Parameters<PluginApiHandler>[1]\n\nexport function bodyOf(req: Parameters<PluginApiHandler>[0]): Record<string, unknown> {\n const raw = req.body\n if (typeof raw === 'string') {\n if (raw.length > MAX_BODY_BYTES) return {}\n try {\n return JSON.parse(raw || '{}')\n } catch {\n return {}\n }\n }\n return (raw ?? {}) as Record<string, unknown>\n}\n\nexport const validId = (value: unknown): value is string =>\n typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value)\n\nexport interface Gate {\n uid: string\n /** The caller's address, for an activity line; null when the token has none. */\n email: string | null\n staff: boolean\n host: FirebaseFirestore.DocumentSnapshot\n org: Record<string, unknown>\n}\n\n/**\n * The permission a route built on {@link gate} checks instead of the site\n * role (AGL-4047): a key whose preset is the site role, that preset (the\n * declaring plugin's own table, so the answer does not depend on which\n * plugins this process loaded), and the refusal naming it.\n */\nexport interface GatePermission {\n key: string\n presetFor: Readonly<Record<HostAccessRole, boolean>>\n refusal: string\n}\n\n/**\n * Who may write this site's products, as the rules decide it. Answers the\n * caller's reply on a refusal and returns null.\n *\n * A route that is not about products names the key it checks instead\n * (`permission`, AGL-4047): the walk-in and the guests change ask their\n * reservation key, read as the rules read it, from the site's\n * `memberPermissions` stamp, else the preset of the member's `memberRoles`\n * entry, so the route and the rules give one answer. Without it, the\n * product routes ask \"Edit site content\" (`site.edit`) the same way.\n */\nexport async function gate(\n req: Parameters<PluginApiHandler>[0],\n res: Reply,\n hostId: string,\n deps: Required<ProductsWriteDeps>,\n options: { permission?: GatePermission } = {},\n): Promise<Gate | null> {\n const authorization = String(req.headers.authorization ?? '')\n const token = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : ''\n if (!token) return void res.status(401).json({ error: 'Unauthenticated' }), null\n let decoded: Record<string, unknown> & { uid: string }\n try {\n decoded = await deps.verifyIdToken(token)\n } catch (error) {\n // Only a refused token is the caller's; an Auth outage is a 500 (AGL-2852).\n if (!isRefusedIdToken(error)) throw error\n return void res.status(401).json({ error: 'Sign in again to continue' }), null\n }\n const staff = decoded['staff'] === true\n if (!staff && decoded['email_verified'] !== true && !isImpersonationSession(decoded as never)) {\n return void res.status(403).json({ error: 'Verify your email address to make changes' }), null\n }\n const host = await deps.firestore().collection('hosts').doc(hostId).get()\n if (!host.exists) return void res.status(404).json({ error: 'Unknown site' }), null\n if (!staff) {\n const { permission } = options\n const allowed = permission\n ? hostStampedSitePermission(host.data(), decoded.uid, permission.key, permission.presetFor)\n : holdsSiteKey(host, decoded.uid, 'site.edit')\n if (!allowed) return void res.status(403).json({ error: permission?.refusal ?? ROLE_REFUSAL }), null\n }\n const org = ((await deps.orgForHost(hostId))?.org ?? {}) as Record<string, unknown>\n const locked = await deps.lockdown({ staff, uid: decoded.uid, org: org as never, host: host.data() as never, request: { method: 'POST' } as never })\n if (locked) return void res.status(423).json({ error: 'This site is not accepting changes right now' }), null\n const email = typeof decoded['email'] === 'string' ? decoded['email'] : null\n return { uid: decoded.uid, email, staff, host, org }\n}\n\n/** The site-wide cache drop a product change is owed (AGL-3386): an outbox entry in the write, then the drop. */\nexport function outboxEntry(firestore: Firestore, hostId: string) {\n return {\n ref: firestore.collection('publishOutbox').doc(createResourceUid()),\n data: { hostId, paths: ['/'], createdAt: FieldValue.serverTimestamp(), attempts: 0, entireHost: true },\n }\n}\n\nexport async function settleCache(deps: Pick<Required<ProductsWriteDeps>, 'dropCache'>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string) {\n const dropped = await deps.dropCache({ hostIds: [hostId], reason }).catch(() => ({ complete: false }))\n if (dropped.complete) await entry.delete().catch(() => undefined)\n}\n\nexport function resolved(deps: ProductsWriteDeps): Required<ProductsWriteDeps> {\n return {\n firestore: deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore),\n verifyIdToken: deps.verifyIdToken ?? ((token) => firebaseAdmin.app().auth().verifyIdToken(token) as never),\n orgForHost: deps.orgForHost ?? ((hostId) => getOrgForHost(hostId) as never),\n lockdown: deps.lockdown ?? ((options) => getLockdownVerdict(options)),\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n now: deps.now ?? (() => Date.now()),\n }\n}\n\n/** Why a product save or delete was refused, for its caller to answer in its own words. */\nexport type ProductWriteRefusalCode =\n /** The product fails the editor's rules (`variantMatrixProblem`, `validateProductForSave`). */\n | 'invalid'\n /** The plan does not include commerce. */\n | 'plan'\n /** The plan's product allowance is used up. */\n | 'quota'\n /** The product does not exist, or was deleted. */\n | 'missing'\n /** Another product holds the slug (only asked with `uniqueSlug`). */\n | 'slug_taken'\n /** A refusal the caller's own `product` builder made. */\n | 'refused'\n\nexport interface ProductWriteRefusal {\n ok: false\n status: number\n code: ProductWriteRefusalCode\n error: string\n /** What a builder's refusal names, for its caller. */\n detail?: unknown\n}\n\nexport type ProductSaveResult = { ok: true; id: string; replayed: boolean } | ProductWriteRefusal\n\n/** A refusal a {@link ProductSaveInput.product} builder answers instead of a product. */\nexport interface ProductBuildRefusal {\n refusal: { status: number; error: string; detail?: unknown }\n}\n\n/**\n * One product save, already authorized (AGL-4235): the console editor's\n * write, whoever asks for it. The native apps' save route and the public\n * API's product writes both call this, so the derived fields, the checks, the\n * smart-collection membership, the plan and allowance count, the publish\n * outbox and the cache drop are made once.\n *\n * The caller has decided who may write this site. Nothing here asks.\n */\nexport interface ProductSaveInput {\n firestore: Firestore\n hostId: string\n productId: string\n /** A new product under `productId` (a retry finds its own and answers `replayed`), or an edit of the live one. */\n create: boolean\n /**\n * The product to save, or how to make it from the stored document read in\n * the save's own transaction, so an edit merged onto it cannot lose a\n * change made between a read and the write.\n */\n product: EditedProduct | ((stored: FirebaseFirestore.DocumentSnapshot) => EditedProduct | ProductBuildRefusal)\n /** The organization the plan and the allowance are read from. */\n org: Record<string, unknown>\n /** Who a create is `createdBy`: a person's uid, or null when no person made it. */\n createdBy: string | null\n /** Further fields a create stamps, such as the API credential that made it. */\n createStamps?: Record<string, unknown>\n /** Refuse a slug another product of the site holds, live or deleted. */\n uniqueSlug?: boolean\n nowMs: number\n dropCache: Required<ProductsWriteDeps>['dropCache']\n /** What the cache drop says caused it. */\n cacheReason: string\n}\n\nconst isBuildRefusal = (value: unknown): value is ProductBuildRefusal =>\n Boolean(value && typeof value === 'object' && 'refusal' in (value as object))\n\n/**\n * Saves a product as the console editor does: `create` makes a new product\n * under `productId`; otherwise it replaces the live product, keeping its live\n * stock holds and the stored timestamps the product does not name.\n */\nexport async function saveProduct(input: ProductSaveInput): Promise<ProductSaveResult> {\n const { firestore: db, hostId, productId, create, nowMs } = input\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const productRef = products.doc(productId)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductSaveResult> => {\n const [existing, smart] = await Promise.all([tx.get(productRef), tx.get(smartQuery)])\n const built = typeof input.product === 'function' ? input.product(existing) : input.product\n if (isBuildRefusal(built)) {\n return { ok: false, code: 'refused', ...built.refusal }\n }\n const product = built\n const fields = productSaveFields(product, nowMs)\n // More combinations than a product holds is refused with the count\n // (AGL-4100), never saved short of the options it names.\n const problem = variantMatrixProblem(fields.options) ?? validateProductForSave(fields as never)\n if (problem) return { ok: false, status: 400, code: 'invalid', error: problem }\n if (input.uniqueSlug) {\n const holders = await tx.get(products.where('slug', '==', fields.slug).limit(2))\n if (holders.docs.some((doc) => doc.id !== productId)) {\n return { ok: false, status: 409, code: 'slug_taken', error: `Another product already uses the slug “${fields.slug}”` }\n }\n }\n const membership = {\n collectionIds: productCollectionIds(\n productMembershipInput(fields, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n ),\n }\n if (create) {\n if (existing.exists) return { ok: true, id: productId, replayed: true }\n const early = planRefusal(input.org as never)\n if (early) return { ok: false, status: early.status, code: 'plan', error: early.error }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(input.org as never, Number(used) || 0)\n if (room) return { ok: false, status: room.status, code: 'quota', error: room.error }\n tx.create(productRef, {\n ...fields,\n ...membership,\n createdAtMs: nowMs,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: input.createdBy,\n ...(input.createStamps ?? {}),\n })\n } else {\n if (!existing.exists || existing.get('deletedAt')) {\n return { ok: false, status: 404, code: 'missing', error: 'This product was deleted' }\n }\n tx.set(productRef, {\n ...storedTimestamps(existing.data() ?? {}, product as unknown as Record<string, unknown>),\n ...productEditWrite(fields, existing.get('stockHolds')),\n ...membership,\n updatedAt: FieldValue.serverTimestamp(),\n })\n }\n tx.set(outbox.ref, outbox.data)\n return { ok: true, id: productId, replayed: false }\n })\n if (answer.ok && !answer.replayed) {\n await settleCache({ dropCache: input.dropCache }, hostId, outbox.ref, input.cacheReason)\n }\n return answer\n}\n\n/**\n * Saves a product as the console editor does. `create: true` makes a new\n * product under the client-minted `productId` (a retry finds its own product\n * and answers `replayed`); otherwise it replaces the live product, keeping\n * its live stock holds.\n */\nexport function createProductSaveHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const product = body['product'] as EditedProduct | undefined\n if (!validId(hostId) || !validId(productId) || !product || typeof product !== 'object' || !Array.isArray(product.variants)) {\n return res.status(400).json({ error: 'Missing site, product or its variants' })\n }\n if (typeof product.name !== 'string' || !product.name.trim()) return res.status(400).json({ error: 'Product name is required' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const saved = await saveProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n create: body['create'] === true,\n product,\n org: door.org,\n createdBy: door.uid,\n nowMs: deps.now(),\n dropCache: deps.dropCache,\n cacheReason: 'product saved from the app',\n })\n if (saved.ok === false) return res.status(saved.status).json({ error: saved.error })\n return res.status(200).json({ ok: true, id: saved.id, replayed: saved.replayed })\n } catch (error) {\n console.error('[commerce/products/save]', error)\n return res.status(500).json({ error: 'The product could not be saved' })\n }\n }\n}\n\n/**\n * The stored timestamps an edit keeps. The console's replace writes back the\n * Timestamps its seed carried (`createdAt`, a publish time); a client's JSON\n * cannot carry one, so each stored Timestamp field the request does not name\n * is kept as stored.\n */\nexport function storedTimestamps(stored: Record<string, unknown>, asked: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(stored).filter(\n ([key, value]) => !(key in asked) && typeof (value as { toDate?: unknown } | null)?.toDate === 'function',\n ),\n )\n}\n\n/** The ledger row id one attempt owns: the same key from the same member is the same row. */\nexport function stockAttemptId(uid: string, key: string): string {\n return 'app-' + createHash('sha256').update(`${uid}:${key}`).digest('hex').slice(0, 40)\n}\n\n/**\n * Adjusts one variant's stock as the Adjust stock dialog does: the variants\n * and stock fields on the product, and one `inventoryAdjustments` row, in one\n * transaction. The Idempotency-Key names that row, so a retried attempt finds\n * it and moves nothing twice.\n */\nexport function createProductStockHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const hostId = body['hostId']\n const productId = body['productId']\n const variantId = body['variantId']\n const key = String(req.headers['idempotency-key'] ?? '').trim().slice(0, 200)\n const reason = body['reason'] as InventoryAdjustmentReason\n const delta = Math.round(Number(body['delta']))\n const locationId = typeof body['locationId'] === 'string' && body['locationId'] ? body['locationId'] : undefined\n if (!validId(hostId) || !validId(productId) || typeof variantId !== 'string' || !variantId) {\n return res.status(400).json({ error: 'Missing site, product or variant' })\n }\n if (!key) return res.status(400).json({ error: 'Missing Idempotency-Key' })\n if (!STOCK_ADJUST_REASONS.includes(reason)) return res.status(400).json({ error: 'Unknown reason' })\n if (!Number.isFinite(delta) || delta === 0) return res.status(400).json({ error: 'Enter a number of units' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const productRef = hostRef.collection('products').doc(productId)\n const ledgerRef = hostRef.collection('inventoryAdjustments').doc(stockAttemptId(door.uid, key))\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [ledger, stored] = await Promise.all([tx.get(ledgerRef), tx.get(productRef)])\n if (ledger.exists) {\n return { status: 200, body: { ok: true, replayed: true, inventory: stored.get('inventory') ?? null } }\n }\n if (!stored.exists || stored.get('deletedAt')) return { status: 404, body: { error: 'This product was deleted' } }\n const product = stored.data() as never as Parameters<typeof stockAdjustmentWrite>[0]\n if (!(product.variants ?? []).some((variant) => variant.id === variantId)) {\n return { status: 404, body: { error: 'That variant is no longer on this product' } }\n }\n const write = stockAdjustmentWrite(product, productId, { variantId, delta, reason, locationId }, deps.now())\n if (!write) return { status: 400, body: { error: 'Enter a number of units' } }\n tx.update(productRef, write.update)\n tx.create(ledgerRef, write.ledger)\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, replayed: false, inventory: (write.update as { inventory?: unknown }).inventory ?? null } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'stock adjusted from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/stock]', error)\n return res.status(500).json({ error: 'Stock could not be adjusted' })\n }\n }\n}\n\n/**\n * The first slug in `base`, `base-2`, `base-3`… no product of the site holds,\n * as the console's slug ledger claims one (`product-slugs.ts`): a second\n * Duplicate of the same product does not mint a second `-copy` (AGL-3321).\n */\nexport async function claimProductSlug(products: FirebaseFirestore.CollectionReference, base: string): Promise<string> {\n for (let suffix = 1; suffix < 1000; suffix += 1) {\n const candidate = suffix < 2 ? base : `${base}-${suffix}`\n const held = await products.where('slug', '==', candidate).limit(1).get()\n if (held.empty) return candidate\n }\n return `${base}-${Date.now()}`\n}\n\n/**\n * `POST /api/commerce/products/duplicate` (AGL-3841): the products list's\n * Duplicate for the native apps. The console builds the copy in the browser\n * (`productDuplicateFields`, its slug ledger, the copy's smart collections)\n * and creates it through the quota-enforcing resources route; this runs the\n * same model over the stored product and creates it under the save route's\n * create door (the plan's commerce entitlement and its product quota, counted\n * in the same transaction). `newProductId` is the client's, so a retry finds\n * its own copy and answers `replayed`.\n */\nexport function createProductDuplicateHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId, newProductId } = body\n if (!validId(hostId) || !validId(productId) || !validId(newProductId) || productId === newProductId) {\n return res.status(400).json({ error: 'Missing site or product' })\n }\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const db = deps.firestore()\n const hostRef = db.collection('hosts').doc(hostId)\n const products = hostRef.collection('products')\n const copyRef = products.doc(newProductId)\n const already = await copyRef.get()\n if (already.exists) return res.status(200).json({ ok: true, id: newProductId, replayed: true })\n const source = await products.doc(productId).get()\n if (!source.exists || source.get('deletedAt')) return res.status(404).json({ error: 'This product was deleted' })\n const product = liftLegacyProduct((source.data() ?? {}) as never)\n const slug = await claimProductSlug(products, productDuplicateSlugBase(product.slug, product.name))\n const nowMs = deps.now()\n const fields = productDuplicateFields(product, slug, nowMs)\n const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart')\n // The MANUAL collections holding the source by id, which the copy joins.\n const manualQuery = hostRef.collection('collections').where('productIds', 'array-contains', productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx) => {\n const [existing, smart, manual] = await Promise.all([tx.get(copyRef), tx.get(smartQuery), tx.get(manualQuery)])\n if (existing.exists) return { status: 200, body: { ok: true, id: newProductId, replayed: true } }\n const early = planRefusal(door.org as never)\n if (early) return { status: early.status, body: { error: early.error } }\n const used = await countLiveDocuments(products, (aggregate) => tx.get(aggregate))\n const room = roomRefusal(door.org as never, Number(used) || 0)\n if (room) return { status: room.status, body: { error: room.error } }\n // The COPY's smart collections: its name differs from the source's.\n const collectionIds = productCollectionIds(\n productMembershipInput({ name: productDuplicateName(product.name) }, product) as never,\n smart.docs.map((doc) => smartCollectionRulesOf(doc.id, doc.data())),\n )\n tx.create(copyRef, {\n ...fields,\n collectionIds,\n deletedAt: null,\n createdAt: FieldValue.serverTimestamp(),\n updatedAt: FieldValue.serverTimestamp(),\n createdBy: door.uid,\n })\n for (const held of manual.docs) {\n tx.update(held.ref, { productIds: FieldValue.arrayUnion(newProductId) })\n }\n tx.set(outbox.ref, outbox.data)\n return { status: 200, body: { ok: true, id: newProductId, replayed: false, slug } }\n })\n if (answer.status === 200 && !(answer.body as { replayed?: boolean }).replayed) {\n await settleCache(deps, hostId, outbox.ref, 'product duplicated from the app')\n }\n return res.status(answer.status).json(answer.body)\n } catch (error) {\n console.error('[commerce/products/duplicate]', error)\n return res.status(500).json({ error: 'Could not duplicate product' })\n }\n }\n}\n\nexport type ProductDeleteResult = { ok: true; already: boolean } | ProductWriteRefusal\n\n/**\n * The products list's Delete, already authorized (AGL-4235): `deletedAt` on\n * the product, which stops it being purchasable, with the publish outbox\n * entry and the site-wide cache drop. A deleted product answers `already`.\n * The native apps' delete route and the public API both call this.\n */\nexport async function deleteProduct(input: {\n firestore: Firestore\n hostId: string\n productId: string\n dropCache: Required<ProductsWriteDeps>['dropCache']\n cacheReason: string\n}): Promise<ProductDeleteResult> {\n const { firestore: db, hostId, productId } = input\n const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId)\n const outbox = outboxEntry(db, hostId)\n const answer = await db.runTransaction(async (tx): Promise<ProductDeleteResult> => {\n const stored = await tx.get(productRef)\n if (!stored.exists) return { ok: false, status: 404, code: 'missing', error: 'This product no longer exists' }\n if (stored.get('deletedAt')) return { ok: true, already: true }\n tx.update(productRef, { deletedAt: FieldValue.serverTimestamp() })\n tx.set(outbox.ref, outbox.data)\n return { ok: true, already: false }\n })\n if (answer.ok && !answer.already) await settleCache(input, hostId, outbox.ref, input.cacheReason)\n return answer\n}\n\n/**\n * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete\n * for the native apps, the console's write (`deletedAt` on the product, which\n * stops it being purchasable) with the site-wide cache drop, under the save\n * route's gate. Deleting a deleted product answers `already`.\n */\nexport function createProductDeleteHandler(options: ProductsWriteDeps = {}): PluginApiHandler {\n return async (req, res) => {\n if (req.method !== 'POST') return res.status(405).json({ error: 'Method not allowed' })\n const deps = resolved(options)\n const body = bodyOf(req)\n const { hostId, productId } = body\n if (!validId(hostId) || !validId(productId)) return res.status(400).json({ error: 'Missing site or product' })\n try {\n const door = await gate(req, res, hostId, deps)\n if (!door) return\n const removed = await deleteProduct({\n firestore: deps.firestore(),\n hostId,\n productId,\n dropCache: deps.dropCache,\n cacheReason: 'product deleted from the app',\n })\n if (removed.ok === false) return res.status(removed.status).json({ error: removed.error })\n return res.status(200).json({ ok: true, already: removed.already })\n } catch (error) {\n console.error('[commerce/products/delete]', error)\n return res.status(500).json({ error: 'Could not delete product' })\n }\n }\n}\n\nexport const productSaveHandler = createProductSaveHandler()\nexport const productStockHandler = createProductStockHandler()\nexport const productDuplicateHandler = createProductDuplicateHandler()\nexport const productDeleteHandler = createProductDeleteHandler()\n"],"names":["validateProductForSave","createHash","holdsSiteKey","hostStampedSitePermission","siteKeyRefusal","isRefusedIdToken","createResourceUid","countLiveDocuments","dropPluginSiteCache","firebaseAdmin","getLockdownVerdict","getOrgForHost","isImpersonationSession","FieldValue","liftLegacyProduct","productCollectionIds","productDuplicateFields","productDuplicateName","productDuplicateSlugBase","productEditWrite","productMembershipInput","productSaveFields","smartCollectionRulesOf","stockAdjustmentWrite","variantMatrixProblem","planRefusal","roomRefusal","ROLE_REFUSAL","MAX_BODY_BYTES","STOCK_ADJUST_REASONS","bodyOf","req","raw","body","length","JSON","parse","validId","value","test","gate","res","hostId","deps","options","authorization","String","headers","token","startsWith","slice","status","json","error","decoded","verifyIdToken","staff","host","firestore","collection","doc","get","exists","permission","allowed","data","uid","key","presetFor","refusal","org","orgForHost","locked","lockdown","request","method","email","outboxEntry","ref","paths","createdAt","serverTimestamp","attempts","entireHost","settleCache","entry","reason","dropped","dropCache","hostIds","catch","complete","delete","undefined","resolved","app","auth","now","Date","isBuildRefusal","Boolean","saveProduct","input","db","productId","create","nowMs","hostRef","products","productRef","smartQuery","where","outbox","answer","runTransaction","tx","existing","smart","Promise","all","built","product","ok","code","fields","problem","uniqueSlug","holders","slug","limit","docs","some","id","membership","collectionIds","map","replayed","early","used","aggregate","room","Number","createdAtMs","deletedAt","updatedAt","createdBy","createStamps","set","storedTimestamps","cacheReason","createProductSaveHandler","Array","isArray","variants","name","trim","door","saved","console","stored","asked","Object","fromEntries","entries","filter","toDate","stockAttemptId","update","digest","createProductStockHandler","variantId","delta","Math","round","locationId","includes","isFinite","ledgerRef","ledger","inventory","variant","write","claimProductSlug","base","suffix","candidate","held","empty","createProductDuplicateHandler","newProductId","source","copyRef","already","manualQuery","manual","productIds","arrayUnion","deleteProduct","createProductDeleteHandler","removed","productSaveHandler","productStockHandler","productDuplicateHandler","productDeleteHandler"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,sBAAsB,QAAQ,iCAA6B;AACpE,SAASC,UAAU,QAAQ,cAAa;AACxC,SAASC,YAAY,EAAEC,yBAAyB,EAAEC,cAAc,QAAQ,0CAAyC;AACjH,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,iBAAiB,QAAQ,6CAA4C;AAE9E,SAASC,kBAAkB,QAAQ,6CAA4C;AAC/E,SAASC,mBAAmB,QAAQ,gDAA+C;AAEnF,SAASC,aAAa,EAAEC,kBAAkB,EAAEC,aAAa,EAAEC,sBAAsB,QAAQ,2BAA0B;AACnH,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAEEC,iBAAiB,EACjBC,oBAAoB,EACpBC,sBAAsB,EACtBC,oBAAoB,EACpBC,wBAAwB,EACxBC,gBAAgB,EAChBC,sBAAsB,EACtBC,iBAAiB,EACjBC,sBAAsB,EACtBC,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;YAA2B;QAClE;IACF;AACF;AAEA,OAAO,MAAMmJ,qBAAqBlD,2BAA0B;AAC5D,OAAO,MAAMmD,sBAAsBhC,4BAA2B;AAC9D,OAAO,MAAMiC,0BAA0Bd,gCAA+B;AACtE,OAAO,MAAMe,uBAAuBL,6BAA4B"}
|
|
@@ -38,6 +38,13 @@ export interface AddOnCellGroup {
|
|
|
38
38
|
min: number;
|
|
39
39
|
max: number;
|
|
40
40
|
online: boolean;
|
|
41
|
+
/** A write-in (write-ins): `write-in`, `up to 14`, `numbers only`. */
|
|
42
|
+
writeIn?: {
|
|
43
|
+
maxLength: number | null;
|
|
44
|
+
digitsOnly: boolean;
|
|
45
|
+
};
|
|
46
|
+
/** `name on order`: the group's name prints before the choice. */
|
|
47
|
+
nameOnOrder?: boolean;
|
|
41
48
|
choices: AddOnCellChoice[];
|
|
42
49
|
}
|
|
43
50
|
/** An add-ons cell as its groups, or what is wrong with it for the person to fix. */
|
|
@@ -161,24 +161,43 @@ function readSettings(inner) {
|
|
|
161
161
|
let min = 0;
|
|
162
162
|
let max = null;
|
|
163
163
|
let online = true;
|
|
164
|
+
let writeIn = false;
|
|
165
|
+
let maxLength = null;
|
|
166
|
+
let digitsOnly = false;
|
|
167
|
+
let nameOnOrder = false;
|
|
164
168
|
for (const raw of (inner != null ? inner : '').split(',')){
|
|
165
169
|
const setting = raw.trim();
|
|
166
170
|
if (!setting) continue;
|
|
167
171
|
const least = /^at least (\d+)$/i.exec(setting);
|
|
168
172
|
const most = /^at most (\d+)$/i.exec(setting);
|
|
173
|
+
const upTo = /^up to (\d+)$/i.exec(setting);
|
|
169
174
|
if (least) min = Number(least[1]);
|
|
170
175
|
else if (most) max = Number(most[1]);
|
|
171
176
|
else if (/^register only$/i.test(setting)) online = false;
|
|
177
|
+
else if (/^write-?in$/i.test(setting)) writeIn = true;
|
|
178
|
+
else if (upTo) maxLength = Number(upTo[1]);
|
|
179
|
+
else if (/^numbers only$/i.test(setting)) digitsOnly = true;
|
|
180
|
+
else if (/^name on order$/i.test(setting)) nameOnOrder = true;
|
|
172
181
|
else {
|
|
173
|
-
return fail(`"${setting}" is not a group setting. Use at least 1, at most 2 or
|
|
182
|
+
return fail(`"${setting}" is not a group setting. Use at least 1, at most 2, register only, name on order, ` + `or for a write-in: write-in, up to 14, numbers only. ${QUOTE_THE_NAME}`);
|
|
174
183
|
}
|
|
175
184
|
}
|
|
185
|
+
if (!writeIn && (maxLength !== null || digitsOnly)) {
|
|
186
|
+
return fail('"up to" and "numbers only" are for a write-in. Add write-in to the group\'s settings.');
|
|
187
|
+
}
|
|
176
188
|
return {
|
|
177
|
-
value: {
|
|
189
|
+
value: _extends({
|
|
178
190
|
min,
|
|
179
|
-
max: max != null ? max : defaultMax(min),
|
|
191
|
+
max: writeIn ? 1 : max != null ? max : defaultMax(min),
|
|
180
192
|
online
|
|
181
|
-
}
|
|
193
|
+
}, writeIn ? {
|
|
194
|
+
writeIn: {
|
|
195
|
+
maxLength,
|
|
196
|
+
digitsOnly
|
|
197
|
+
}
|
|
198
|
+
} : {}, nameOnOrder ? {
|
|
199
|
+
nameOnOrder: true
|
|
200
|
+
} : {})
|
|
182
201
|
};
|
|
183
202
|
}
|
|
184
203
|
function readByVariant(inner, choice) {
|
|
@@ -238,6 +257,19 @@ function readChoices(source, group) {
|
|
|
238
257
|
value: choices
|
|
239
258
|
};
|
|
240
259
|
}
|
|
260
|
+
/** A write-in's side of the colon: blank or `+$5.00`, priced by variant like any choice. */ function readWriteInChoice(source, group) {
|
|
261
|
+
const trimmed = source.trim();
|
|
262
|
+
const read = readChoices(trimmed && !/^[+$]/.test(trimmed) ? trimmed : `${writeName(group)} ${trimmed}`, group);
|
|
263
|
+
if ('message' in read) return read;
|
|
264
|
+
if (read.value.length !== 1) return fail(`"${group}" is a write-in: after the colon, write only what it adds.`);
|
|
265
|
+
return {
|
|
266
|
+
value: [
|
|
267
|
+
_extends({}, read.value[0], {
|
|
268
|
+
name: group
|
|
269
|
+
})
|
|
270
|
+
]
|
|
271
|
+
};
|
|
272
|
+
}
|
|
241
273
|
/** An add-ons cell as its groups, or what is wrong with it for the person to fix. */ export function readAddOnCell(cell) {
|
|
242
274
|
const groups = [];
|
|
243
275
|
const parts = splitTop(String(cell != null ? cell : ''), ';');
|
|
@@ -262,7 +294,8 @@ function readChoices(source, group) {
|
|
|
262
294
|
if (!name) return fail('Name every add-on group.');
|
|
263
295
|
const settings = readSettings(head.value.inner);
|
|
264
296
|
if ('message' in settings) return settings;
|
|
265
|
-
|
|
297
|
+
// A write-in's one field is named after the group; after the colon is only what it adds, if anything.
|
|
298
|
+
const choices = settings.value.writeIn ? readWriteInChoice(sides[1], name) : readChoices(sides[1], name);
|
|
266
299
|
if ('message' in choices) return choices;
|
|
267
300
|
groups.push(_extends({
|
|
268
301
|
name
|
|
@@ -286,18 +319,43 @@ function writeChoice(choice) {
|
|
|
286
319
|
}
|
|
287
320
|
/** Groups as the one way a cell writes them, so two cells saying the same thing are the same text. */ export function writeAddOnCell(groups) {
|
|
288
321
|
return groups.map((group)=>{
|
|
322
|
+
const writeIn = group.writeIn;
|
|
289
323
|
const settings = [
|
|
324
|
+
...writeIn ? [
|
|
325
|
+
'write-in'
|
|
326
|
+
] : [],
|
|
290
327
|
...group.min > 0 ? [
|
|
291
328
|
`at least ${group.min}`
|
|
292
329
|
] : [],
|
|
293
|
-
|
|
330
|
+
...!writeIn && group.max !== defaultMax(group.min) ? [
|
|
294
331
|
`at most ${group.max}`
|
|
295
332
|
] : [],
|
|
333
|
+
...(writeIn == null ? void 0 : writeIn.maxLength) ? [
|
|
334
|
+
`up to ${writeIn.maxLength}`
|
|
335
|
+
] : [],
|
|
336
|
+
...(writeIn == null ? void 0 : writeIn.digitsOnly) ? [
|
|
337
|
+
'numbers only'
|
|
338
|
+
] : [],
|
|
339
|
+
...group.nameOnOrder ? [
|
|
340
|
+
'name on order'
|
|
341
|
+
] : [],
|
|
296
342
|
...group.online ? [] : [
|
|
297
343
|
'register only'
|
|
298
344
|
]
|
|
299
345
|
];
|
|
300
346
|
const head = settings.length ? `${writeName(group.name)} (${settings.join(', ')})` : writeName(group.name);
|
|
347
|
+
if (writeIn) {
|
|
348
|
+
var _group_choices_;
|
|
349
|
+
// The one field is named after the group, with what a filled answer adds.
|
|
350
|
+
const choice = (_group_choices_ = group.choices[0]) != null ? _group_choices_ : {
|
|
351
|
+
name: group.name,
|
|
352
|
+
priceCents: 0,
|
|
353
|
+
byVariant: []
|
|
354
|
+
};
|
|
355
|
+
return `${head}: ${writeChoice(_extends({}, choice, {
|
|
356
|
+
name: group.name
|
|
357
|
+
}))}`;
|
|
358
|
+
}
|
|
301
359
|
return `${head}: ${group.choices.map(writeChoice).join(', ')}`;
|
|
302
360
|
}).join('; ');
|
|
303
361
|
}
|
|
@@ -305,11 +363,19 @@ function writeChoice(choice) {
|
|
|
305
363
|
if (!Array.isArray(stored) || !stored.length) return null;
|
|
306
364
|
const groups = stored.map((group)=>{
|
|
307
365
|
var _ref;
|
|
308
|
-
return {
|
|
366
|
+
return _extends({
|
|
309
367
|
name: String((_ref = group == null ? void 0 : group.name) != null ? _ref : ''),
|
|
310
368
|
min: Number(group == null ? void 0 : group.min) || 0,
|
|
311
369
|
max: Number(group == null ? void 0 : group.max) || 0,
|
|
312
|
-
online: (group == null ? void 0 : group.online) === true
|
|
370
|
+
online: (group == null ? void 0 : group.online) === true
|
|
371
|
+
}, (group == null ? void 0 : group.kind) === 'text' ? {
|
|
372
|
+
writeIn: {
|
|
373
|
+
maxLength: Number(group.maxLength) || null,
|
|
374
|
+
digitsOnly: group.digitsOnly === true
|
|
375
|
+
}
|
|
376
|
+
} : {}, (group == null ? void 0 : group.nameOnOrder) === true ? {
|
|
377
|
+
nameOnOrder: true
|
|
378
|
+
} : {}, {
|
|
313
379
|
choices: (Array.isArray(group == null ? void 0 : group.options) ? group.options : []).map((option)=>{
|
|
314
380
|
var _ref;
|
|
315
381
|
const byVariant = [];
|
|
@@ -331,7 +397,7 @@ function writeChoice(choice) {
|
|
|
331
397
|
byVariant
|
|
332
398
|
};
|
|
333
399
|
})
|
|
334
|
-
};
|
|
400
|
+
});
|
|
335
401
|
});
|
|
336
402
|
return writeAddOnCell(groups);
|
|
337
403
|
}
|
|
@@ -410,7 +476,7 @@ function writeChoice(choice) {
|
|
|
410
476
|
else delete option.priceCentsByVariant;
|
|
411
477
|
return option;
|
|
412
478
|
});
|
|
413
|
-
|
|
479
|
+
const next = _extends({}, held != null ? held : {}, {
|
|
414
480
|
id: (_ref = held == null ? void 0 : held.id) != null ? _ref : freeId('g', group.name, groupIds),
|
|
415
481
|
name: group.name,
|
|
416
482
|
min: group.min,
|
|
@@ -418,6 +484,18 @@ function writeChoice(choice) {
|
|
|
418
484
|
online: group.online,
|
|
419
485
|
options
|
|
420
486
|
});
|
|
487
|
+
// The cell says what the group is: a write-in and its settings, the name on the order.
|
|
488
|
+
delete next.kind;
|
|
489
|
+
delete next.maxLength;
|
|
490
|
+
delete next.digitsOnly;
|
|
491
|
+
delete next.nameOnOrder;
|
|
492
|
+
if (group.writeIn) {
|
|
493
|
+
next.kind = 'text';
|
|
494
|
+
if (group.writeIn.maxLength) next.maxLength = group.writeIn.maxLength;
|
|
495
|
+
if (group.writeIn.digitsOnly) next.digitsOnly = true;
|
|
496
|
+
}
|
|
497
|
+
if (group.nameOnOrder) next.nameOnOrder = true;
|
|
498
|
+
return next;
|
|
421
499
|
});
|
|
422
500
|
return {
|
|
423
501
|
groups,
|