@aglyn/plugins-commerce 1.26.6 → 1.28.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 (34) hide show
  1. package/package.json +13 -13
  2. package/src/lib/components/console/pos-hardware-card.component.js +70 -67
  3. package/src/lib/components/console/pos-hardware-card.component.js.map +1 -1
  4. package/src/lib/components/console/pos-hardware-waiting-card.component.js +19 -17
  5. package/src/lib/components/console/pos-hardware-waiting-card.component.js.map +1 -1
  6. package/src/lib/components/console/product-editor-dialog.component.js +4 -43
  7. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  8. package/src/lib/contracts.d.ts +7 -0
  9. package/src/lib/contracts.js.map +1 -1
  10. package/src/lib/model/pos-hardware-shop.d.ts +152 -0
  11. package/src/lib/model/pos-hardware-shop.js +152 -0
  12. package/src/lib/model/pos-hardware-shop.js.map +1 -0
  13. package/src/lib/model/product-write.d.ts +29 -8
  14. package/src/lib/model/product-write.js +64 -2
  15. package/src/lib/model/product-write.js.map +1 -1
  16. package/src/lib/native-nav.js +13 -1
  17. package/src/lib/native-nav.js.map +1 -1
  18. package/src/lib/server/api-v1/openapi.d.ts +6 -6
  19. package/src/lib/server/api-v1/openapi.js +203 -16
  20. package/src/lib/server/api-v1/openapi.js.map +1 -1
  21. package/src/lib/server/api-v1/order-view.d.ts +8 -0
  22. package/src/lib/server/api-v1/order-view.js +21 -4
  23. package/src/lib/server/api-v1/order-view.js.map +1 -1
  24. package/src/lib/server/api-v1/orders-and-products.js +46 -59
  25. package/src/lib/server/api-v1/orders-and-products.js.map +1 -1
  26. package/src/lib/server/api-v1/product-view.d.ts +76 -0
  27. package/src/lib/server/api-v1/product-view.js +86 -0
  28. package/src/lib/server/api-v1/product-view.js.map +1 -0
  29. package/src/lib/server/api-v1/product-writes.d.ts +149 -0
  30. package/src/lib/server/api-v1/product-writes.js +673 -0
  31. package/src/lib/server/api-v1/product-writes.js.map +1 -0
  32. package/src/lib/server/products-write.d.ts +94 -2
  33. package/src/lib/server/products-write.js +171 -112
  34. package/src/lib/server/products-write.js.map +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/server/api-v1/product-writes.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 { createResourceUid } from '@aglyn/aglyn/app-utils/create-resource-uid'\nimport { SCREEN_SEO_TEXT_GUIDANCE } from '@aglyn/aglyn/app-utils/screen-seo-fields'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { ApiErrors, apiJson } from '@aglyn/tenant-data-admin'\nimport {\n type ApiV1Context,\n apiActorFields,\n claimWrite,\n readJsonBody,\n} from '@aglyn/tenant-data-admin/server/api-v1-kit'\nimport {\n COMMERCE_MAX_OPTIONS,\n COMMERCE_SLUG_MAX_LENGTH,\n commerceSlug,\n liftLegacyProduct,\n type ProductOption,\n type ProductStatus,\n type ProductType,\n type ProductVariant,\n renameProductOptions,\n stockTrackingApplies,\n variantMatrixProblem,\n} from '../../model/commerce'\nimport {\n blankProductDraft,\n type EditedProduct,\n PRODUCT_NAME_MAX_LENGTH,\n variantComboKey,\n variantsForOptions,\n} from '../../model/product-write'\nimport {\n claimProductSlug,\n deleteProduct,\n type ProductBuildRefusal,\n type ProductSaveInput,\n type ProductWriteRefusal,\n saveProduct,\n} from '../products-write'\nimport { productView } from './product-view'\n\n/*\n * A site's products, written over the customer REST API (AGL-4235):\n * `POST /v1/sites/{siteId}/products`, `PATCH` and `DELETE` on one product,\n * and `PATCH` on one of its variants.\n *\n * Every write here is the console editor's own, through `saveProduct` and\n * `deleteProduct` — the functions the native apps' routes call — so a product\n * saved by an integration carries exactly the search keys, stock verdict,\n * price, image, smart-collection membership and cache drop the editor's\n * save would have written, and meets the same checks.\n *\n * What a person can do in the editor is the boundary. Variants are the grid\n * of a product's option values, rebuilt from the options as the editor\n * rebuilds it (`variantsForOptions`); a person cannot add or remove one\n * variant by itself, so neither can a caller. Stock is typed into the grid\n * and written by the save, `null` for untracked and `0` for sold out.\n *\n * Every function here is pre-authorized: `handleProducts` asks the scope,\n * the plan, the plugin's switch for the site and the person's permission\n * before it calls one.\n */\n\n/** The members a product write may carry, in the order the description lists them. */\nexport const PRODUCT_WRITABLE_KEYS = [\n 'name',\n 'description',\n 'status',\n 'type',\n 'slug',\n 'tags',\n 'categoryIds',\n 'mediaUrls',\n 'options',\n 'variants',\n 'seo',\n] as const\n\n/** The members a variant write may carry. */\nexport const VARIANT_WRITABLE_KEYS = [\n 'priceUsd',\n 'compareAtPriceUsd',\n 'sku',\n 'barcode',\n 'weightGrams',\n 'inventory',\n] as const\n\n/** What names the variant one entry of a product write's `variants` changes. */\nconst VARIANT_TARGET_KEYS = ['id', 'options'] as const\n\n/** The search listing members a write may set. */\nconst SEO_WRITABLE_KEYS = ['title', 'description'] as const\n\n/**\n * The kinds of product a caller may make. A digital product delivers files a\n * person uploads in the editor, so it is made there.\n */\nexport const PRODUCT_API_TYPES: readonly ProductType[] = ['physical', 'service']\nexport const PRODUCT_DIGITAL_REFUSAL =\n 'A digital product delivers files uploaded in the console, so it is created and changed to digital there.'\n\nexport const PRODUCT_STATUSES: readonly ProductStatus[] = ['draft', 'active', 'archived']\n\n/** The stock a digital or service subscription cannot keep (AGL-1744), as the editor says it. */\nexport const PRODUCT_STOCK_NOT_TRACKED =\n 'Stock is not tracked on a digital or service subscription. Send `null` to clear it.'\n\n/** One variant's writable fields, as parsed. `null` clears a field; absent leaves it. */\nexport interface VariantWrite {\n priceUsd?: number | null\n compareAtPriceUsd?: number | null\n sku?: string | null\n barcode?: string | null\n weightGrams?: number | null\n inventory?: number | null\n}\n\n/** One entry of a product write's `variants`: the variant it names, and what changes on it. */\nexport interface VariantTargetWrite extends VariantWrite {\n id?: string\n options?: Record<string, string>\n}\n\nexport interface ProductWriteValues {\n name?: string\n description?: string\n status?: ProductStatus\n type?: ProductType\n slug?: string\n tags?: string[]\n categoryIds?: string[]\n mediaUrls?: string[]\n options?: ProductOption[]\n variants?: VariantTargetWrite[]\n seo?: { title?: string | null; description?: string | null }\n}\n\ntype Parsed<T> = { values: T } | { errors: Record<string, string> }\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value)\n\n/** Each key of `body` not in `allowed`, named for the 400. */\nfunction unknownKeys(body: Record<string, unknown>, allowed: readonly string[], prefix = ''): Record<string, string> {\n return Object.fromEntries(\n Object.keys(body)\n .filter((key) => !allowed.includes(key))\n .map((key) => [`${prefix}${key}`, 'Not writable here']),\n )\n}\n\n/** A list of non-empty trimmed strings, or why not. */\nfunction stringList(value: unknown): string[] | string {\n if (!Array.isArray(value)) return 'Must be an array of strings'\n if (value.some((entry) => typeof entry !== 'string')) return 'Must be an array of strings'\n return (value as string[]).map((entry) => entry.trim()).filter(Boolean)\n}\n\n/** A number the field may hold, `null` to clear it, or why not. */\nfunction amount(value: unknown, what: string): number | null | string {\n if (value === null) return null\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) return `${what} must be a number, zero or more, or null`\n return value\n}\n\n/**\n * One variant's writable fields from a body (`VariantWrite`). With `target`,\n * also the `id` or `options` that name which variant it is — an entry of a\n * product write's `variants`.\n */\nexport function readVariantWrite(\n body: unknown,\n options: { target?: boolean; prefix?: string } = {},\n): Parsed<VariantTargetWrite> {\n const prefix = options.prefix ?? ''\n if (!isPlainObject(body)) return { errors: { [prefix || 'body']: 'Must be an object' } }\n const allowed: readonly string[] = options.target ? [...VARIANT_WRITABLE_KEYS, ...VARIANT_TARGET_KEYS] : VARIANT_WRITABLE_KEYS\n const errors: Record<string, string> = unknownKeys(body, allowed, prefix)\n const values: VariantTargetWrite = {}\n for (const field of ['priceUsd', 'compareAtPriceUsd', 'weightGrams'] as const) {\n if (!(field in body)) continue\n const parsed = amount(body[field], field === 'weightGrams' ? 'A weight' : 'A price')\n if (typeof parsed === 'string') errors[`${prefix}${field}`] = parsed\n else values[field] = parsed\n }\n for (const field of ['sku', 'barcode'] as const) {\n if (!(field in body)) continue\n const raw = body[field]\n if (raw !== null && typeof raw !== 'string') errors[`${prefix}${field}`] = 'Must be a string, or null'\n else values[field] = typeof raw === 'string' ? raw.trim() : null\n }\n if ('inventory' in body) {\n const raw = body['inventory']\n if (raw !== null && !(typeof raw === 'number' && Number.isInteger(raw) && raw >= 0)) {\n errors[`${prefix}inventory`] = 'Must be a whole number, zero or more (0 is sold out), or null (stock not tracked)'\n } else values.inventory = raw as number | null\n }\n if (options.target) {\n if ('id' in body) {\n if (typeof body['id'] !== 'string' || !body['id']) errors[`${prefix}id`] = 'Must be a variant id'\n else values.id = body['id']\n }\n if ('options' in body) {\n const raw = body['options']\n if (!isPlainObject(raw) || Object.values(raw).some((value) => typeof value !== 'string')) {\n errors[`${prefix}options`] = 'Must map each option name to one of its values'\n } else values.options = raw as Record<string, string>\n }\n if (!('id' in body) && !('options' in body)) {\n errors[prefix || 'variant'] = 'Name the variant by its `id` or by its `options`'\n }\n }\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/**\n * A product write's body (`ProductWrite`): the members the editor lets a\n * person set without a further plan feature. Every member it does not name\n * is a 400 that names it. `create` requires `name`.\n */\nexport function readProductWrite(body: Record<string, unknown>, options: { create: boolean }): Parsed<ProductWriteValues> {\n const errors: Record<string, string> = unknownKeys(body, PRODUCT_WRITABLE_KEYS)\n const values: ProductWriteValues = {}\n if ('name' in body || options.create) {\n const name = body['name']\n if (typeof name !== 'string' || !name.trim()) errors['name'] = 'Required, and not blank'\n else if (name.trim().length > PRODUCT_NAME_MAX_LENGTH) errors['name'] = `At most ${PRODUCT_NAME_MAX_LENGTH} characters`\n else values.name = name.trim()\n }\n if ('description' in body) {\n const description = body['description']\n if (description !== null && typeof description !== 'string') errors['description'] = 'Must be a string, or null'\n else values.description = typeof description === 'string' ? description : ''\n }\n if ('status' in body) {\n if (!PRODUCT_STATUSES.includes(body['status'] as ProductStatus)) errors['status'] = `Must be one of: ${PRODUCT_STATUSES.join(', ')}`\n else values.status = body['status'] as ProductStatus\n }\n if ('type' in body) {\n const type = body['type']\n if (type === 'digital') errors['type'] = PRODUCT_DIGITAL_REFUSAL\n else if (!PRODUCT_API_TYPES.includes(type as ProductType)) errors['type'] = `Must be one of: ${PRODUCT_API_TYPES.join(', ')}`\n else values.type = type as ProductType\n }\n if ('slug' in body) {\n const slug = body['slug']\n if (typeof slug !== 'string' || !slug || slug !== commerceSlug(slug)) {\n errors['slug'] = `Lowercase letters, numbers and dashes, at most ${COMMERCE_SLUG_MAX_LENGTH} characters`\n } else values.slug = slug\n }\n for (const field of ['tags', 'categoryIds', 'mediaUrls'] as const) {\n if (!(field in body)) continue\n const list = stringList(body[field])\n if (typeof list === 'string') errors[field] = list\n else if (field === 'mediaUrls' && list.some((url) => !/^https?:\\/\\/\\S+$/.test(url))) errors[field] = 'Each must be an http or https URL'\n else values[field] = field === 'tags' ? list : [...new Set(list)]\n }\n if ('options' in body) {\n const raw = body['options']\n if (!Array.isArray(raw)) errors['options'] = 'Must be an array of { name, values }'\n else if (raw.length > COMMERCE_MAX_OPTIONS) errors['options'] = `At most ${COMMERCE_MAX_OPTIONS} options per product`\n else {\n const parsed: ProductOption[] = []\n raw.forEach((option, index) => {\n const optionValues = isPlainObject(option) ? stringList(option['values']) : 'Must be { name, values }'\n if (!isPlainObject(option)) errors[`options[${index}]`] = 'Must be { name, values }'\n else if (Object.keys(unknownKeys(option, ['name', 'values'])).length) errors[`options[${index}]`] = 'Only `name` and `values`'\n else if (typeof option['name'] !== 'string' || !option['name'].trim()) errors[`options[${index}].name`] = 'Required, and not blank'\n else if (typeof optionValues === 'string') errors[`options[${index}].values`] = optionValues\n // Trimmed and blanks dropped, as the editor's value chips are.\n else parsed.push({ name: option['name'].trim(), values: optionValues })\n })\n values.options = parsed\n }\n }\n if ('variants' in body) {\n const raw = body['variants']\n if (!Array.isArray(raw)) errors['variants'] = 'Must be an array of variant changes'\n else {\n const parsed: VariantTargetWrite[] = []\n raw.forEach((entry, index) => {\n const read = readVariantWrite(entry, { target: true, prefix: `variants[${index}].` })\n if ('errors' in read) Object.assign(errors, read.errors)\n else parsed.push(read.values)\n })\n values.variants = parsed\n }\n }\n if ('seo' in body) {\n const raw = body['seo']\n if (!isPlainObject(raw)) errors['seo'] = 'Must be { title, description }'\n else {\n Object.assign(errors, unknownKeys(raw, SEO_WRITABLE_KEYS, 'seo.'))\n const seo: NonNullable<ProductWriteValues['seo']> = {}\n for (const field of SEO_WRITABLE_KEYS) {\n if (!(field in raw)) continue\n const text = raw[field]\n const limit = SCREEN_SEO_TEXT_GUIDANCE[field]\n if (text !== null && typeof text !== 'string') errors[`seo.${field}`] = 'Must be a string, or null'\n else if (typeof text === 'string' && text.trim().length > limit) errors[`seo.${field}`] = `At most ${limit} characters`\n else seo[field] = typeof text === 'string' ? text.trim() : null\n }\n values.seo = seo\n }\n }\n return Object.keys(errors).length ? { errors } : { values }\n}\n\n/** A variant with a variant write applied, as the editor's grid applies a typed cell. */\nexport function applyVariantWrite(variant: ProductVariant, write: VariantWrite): ProductVariant {\n const next: Record<string, unknown> = { ...variant }\n for (const field of ['priceUsd', 'compareAtPriceUsd', 'weightGrams'] as const) {\n if (!(field in write)) continue\n // A cleared number is no number (AGL-3676): the key goes.\n if (write[field] === null) delete next[field]\n else next[field] = write[field]\n }\n for (const field of ['sku', 'barcode'] as const) {\n if (!(field in write)) continue\n if (!write[field]) delete next[field]\n else next[field] = write[field]\n }\n // `null` untracked, a number counted: the grid's Stock cell.\n if ('inventory' in write) next['inventory'] = write.inventory ?? null\n return next as unknown as ProductVariant\n}\n\nconst buildRefusal = (status: number, error: string, detail?: Record<string, string>): ProductBuildRefusal => ({\n refusal: { status, error, ...(detail ? { detail } : {}) },\n})\n\n/** Whether a stock number is asked of a product that cannot keep one. */\nfunction stockRefusal(product: EditedProduct, writes: readonly VariantWrite[], field: (index: number) => string) {\n if (stockTrackingApplies(product)) return null\n const index = writes.findIndex((write) => typeof write.inventory === 'number')\n return index === -1 ? null : buildRefusal(400, 'Product failed validation', { [field(index)]: PRODUCT_STOCK_NOT_TRACKED })\n}\n\n/**\n * The product a write makes of `base`: only the members it carries change,\n * so every field it does not name — the ones this API does not expose\n * included — stays as stored.\n */\nexport function mergeProductWrite(base: EditedProduct, values: ProductWriteValues, nowMs: number): EditedProduct | ProductBuildRefusal {\n let next: EditedProduct = { ...base }\n for (const field of ['name', 'description', 'status', 'type', 'slug', 'tags', 'categoryIds', 'mediaUrls'] as const) {\n if (values[field] !== undefined) (next as unknown as Record<string, unknown>)[field] = values[field]\n }\n if (values.seo) {\n const seo: Record<string, unknown> = { ...(base.seo ?? {}) }\n for (const [field, text] of Object.entries(values.seo)) {\n if (text) seo[field] = text\n else delete seo[field]\n }\n if (Object.keys(seo).length) next.seo = seo as EditedProduct['seo']\n else delete next.seo\n }\n if (values.options) {\n const options = values.options\n // A rename moves each variant's selections to the new name (AGL-3066),\n // as the editor's rename does; then the grid is rebuilt from the values,\n // as the editor's value change does. Past the ceiling the variants are\n // left as they are and the save refuses (AGL-4100).\n if ((next.options ?? []).length === options.length) {\n next = { ...next, ...renameProductOptions(next, options.map((option) => option.name)) }\n }\n if (!variantMatrixProblem(options)) next.variants = variantsForOptions(next, options, nowMs)\n next.options = options\n }\n if (values.variants?.length) {\n const variants = [...next.variants]\n const seen = new Set<number>()\n for (const [index, write] of values.variants.entries()) {\n const at = write.id\n ? variants.findIndex((variant) => variant.id === write.id)\n : variants.findIndex((variant) => variantComboKey(variant.options) === variantComboKey(write.options))\n if (at === -1) {\n return buildRefusal(400, 'Product failed validation', {\n [`variants[${index}]`]: write.id\n ? 'No variant of this product has this id'\n : 'No variant of this product has these options; a product’s variants are every combination of its options',\n })\n }\n if (seen.has(at)) return buildRefusal(400, 'Product failed validation', { [`variants[${index}]`]: 'Names a variant another entry already changes' })\n seen.add(at)\n // Only the variant fields apply; `id` and `options` named the variant.\n variants[at] = applyVariantWrite(variants[at], write)\n }\n next.variants = variants\n const refused = stockRefusal(next, values.variants, (index) => `variants[${index}].inventory`)\n if (refused) return refused\n }\n return next\n}\n\n/** A product write's refusal, in the API's envelope. */\nfunction refusalResponse(ctx: ApiV1Context, refusal: ProductWriteRefusal): Response {\n switch (refusal.code) {\n case 'invalid':\n return ApiErrors.badRequest({ message: refusal.error, code: 'validation_failed', headers: ctx.headers })\n case 'plan':\n return ApiErrors.planRequired({ message: refusal.error, code: 'commerce', headers: ctx.headers })\n case 'quota':\n return ApiErrors.planRequired({ message: refusal.error, code: 'product_quota', headers: ctx.headers })\n case 'slug_taken':\n return ApiErrors.conflict({ message: refusal.error, code: 'slug_taken', headers: ctx.headers })\n case 'missing':\n return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n case 'refused':\n return refusal.status === 404\n ? ApiErrors.notFound({ message: refusal.error, headers: ctx.headers })\n : ApiErrors.badRequest({\n message: refusal.error,\n code: 'validation_failed',\n ...(refusal.detail ? { fields: refusal.detail as Record<string, string> } : {}),\n headers: ctx.headers,\n })\n }\n}\n\nconst validationFailed = (ctx: ApiV1Context, fields: Record<string, string>, message = 'Product failed validation') =>\n ApiErrors.badRequest({ message, code: 'validation_failed', fields, headers: ctx.headers })\n\nfunction productsOf(ctx: ApiV1Context, hostId: string) {\n return ctx.firestore.collection('hosts').doc(hostId).collection('products')\n}\n\n/** The categories a write names that the site does not have. */\nasync function danglingCategories(ctx: ApiV1Context, hostId: string, ids: readonly string[] | undefined) {\n if (!ids?.length) return null\n const categories = ctx.firestore.collection('hosts').doc(hostId).collection('productCategories')\n const missing: string[] = []\n for (const id of ids) {\n if (!/^[A-Za-z0-9_-]{1,128}$/.test(id) || !(await categories.doc(id).get()).exists) missing.push(id)\n }\n return missing.length ? { categoryIds: `No such category on this site: ${missing.join(', ')}` } : null\n}\n\n/** What every save from here hands `saveProduct` beside the product. */\nfunction saveContext(ctx: ApiV1Context, hostId: string, deps: ProductApiDeps) {\n return {\n firestore: ctx.firestore,\n hostId,\n org: ctx.org as Record<string, unknown>,\n nowMs: (deps.now ?? Date.now)(),\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n }\n}\n\n/** Seams for the specs; production passes none. */\nexport interface ProductApiDeps {\n now?: () => number\n dropCache?: ProductSaveInput['dropCache']\n}\n\n/**\n * The product a create starts from: the editor's blank draft, unpriced.\n *\n * The editor opens a new product at its default price for the person looking\n * at it to change or clear. A caller sees no such field: one that sent no\n * price asked for none, so its variant is saved unpriced — \"Price coming\n * soon\", not for sale (`variantHasPrice`) — rather than at a price nobody\n * chose. A grid rebuilt from options takes the first variant's values, as the\n * editor's does, so its new combinations are unpriced too until a variant\n * write prices them.\n */\nexport function unpricedProductDraft(): EditedProduct {\n const draft = blankProductDraft()\n return {\n ...draft,\n variants: draft.variants.map((variant) => {\n const unpriced: Partial<ProductVariant> = { ...variant }\n delete unpriced.priceUsd\n return unpriced as ProductVariant\n }),\n }\n}\n\n/**\n * `POST /v1/sites/{siteId}/products` — the editor's Add product.\n *\n * A draft unless `status` says otherwise, as the editor starts one, so a new\n * product is not on sale until someone means it to be. The id is minted\n * here. The slug is claimed from the name when none is sent, as Duplicate\n * claims one (`claimProductSlug`), and a sent slug another product holds —\n * a deleted one's included, because a deleted product still answers its\n * slug on the storefront — is a 409.\n *\n * Replay-safe on an `Idempotency-Key`, as `createContact` is and for its\n * reasons: validation above the claim, every refusal after it releasing the\n * key, the plan and the allowance counted inside the save's transaction.\n */\nexport async function createProduct(\n request: Request,\n ctx: ApiV1Context,\n hostId: string,\n deps: ProductApiDeps = {},\n): Promise<Response> {\n const parsed = readProductWrite(await readJsonBody(request), { create: true })\n if ('errors' in parsed) return validationFailed(ctx, parsed.errors)\n const values = parsed.values\n const dangling = await danglingCategories(ctx, hostId, values.categoryIds)\n if (dangling) return validationFailed(ctx, dangling)\n const draft = mergeProductWrite(unpricedProductDraft(), values, (deps.now ?? Date.now)())\n if ('refusal' in draft) return refusalResponse(ctx, { ok: false, code: 'refused', ...draft.refusal })\n\n const claimed = await claimWrite(ctx, hostId, request.headers.get('Idempotency-Key'), 'product-creates')\n if ('replay' in claimed) return claimed.replay\n const { claim } = claimed\n try {\n const products = productsOf(ctx, hostId)\n const productId = createResourceUid()\n const base = commerceSlug(draft.name)\n const slug = values.slug ?? (base ? await claimProductSlug(products, base) : '')\n const saved = await saveProduct({\n ...saveContext(ctx, hostId, deps),\n productId,\n create: true,\n product: { ...draft, slug },\n uniqueSlug: true,\n // The person a connected app acts for, where the app's routes stamp the\n // member; an API key is no person, and its name says who made it.\n createdBy: ctx.uid ?? null,\n createStamps: apiActorFields(ctx),\n cacheReason: 'product created over the API',\n })\n if (saved.ok === false) {\n await claim.release()\n return refusalResponse(ctx, saved)\n }\n const view = productView(await products.doc(productId).get())\n // Stored as 200 so a replay is distinguishable from the fresh 201.\n await claim.record(200, view)\n return apiJson(view, { status: 201, headers: ctx.headers })\n } catch (error) {\n await claim.release()\n throw error\n }\n}\n\n/** The stored product a write starts from, read in the save's own transaction. */\nfunction storedProduct(stored: FirebaseFirestore.DocumentSnapshot): EditedProduct | ProductBuildRefusal {\n if (!stored.exists || stored.get('deletedAt')) return buildRefusal(404, 'No such product')\n return liftLegacyProduct((stored.data() ?? {}) as never) as EditedProduct\n}\n\n/**\n * `PATCH /v1/sites/{siteId}/products/{productId}` — the editor's save, for\n * the fields sent. The editor's save is a full replace, so the stored product\n * is read in the save's transaction and only the members sent change on it:\n * subscription terms, add-ons, stock holds, stored timestamps and every other\n * field this API does not expose stay as stored. A slug another product\n * holds is a 409. An empty body changes nothing and answers the product.\n */\nexport async function updateProduct(\n request: Request,\n ctx: ApiV1Context,\n hostId: string,\n productId: string,\n deps: ProductApiDeps = {},\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readProductWrite(body, { create: false })\n if ('errors' in parsed) return validationFailed(ctx, parsed.errors)\n const values = parsed.values\n const products = productsOf(ctx, hostId)\n if (Object.keys(body).length > 0) {\n const dangling = await danglingCategories(ctx, hostId, values.categoryIds)\n if (dangling) return validationFailed(ctx, dangling)\n const context = saveContext(ctx, hostId, deps)\n const saved = await saveProduct({\n ...context,\n productId,\n create: false,\n product: (stored) => {\n const base = storedProduct(stored)\n return 'refusal' in base ? base : mergeProductWrite(base, values, context.nowMs)\n },\n uniqueSlug: values.slug !== undefined,\n createdBy: null,\n cacheReason: 'product updated over the API',\n })\n if (saved.ok === false) return refusalResponse(ctx, saved)\n }\n const snap = await products.doc(productId).get()\n if (!snap.exists || snap.get('deletedAt')) return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n return apiJson(productView(snap), { headers: ctx.headers })\n}\n\n/**\n * `PATCH /v1/sites/{siteId}/products/{productId}/variants/{variantId}` —\n * one row of the editor's variant grid: its price, compare-at price, SKU,\n * barcode, weight and stock, through the same save, so every check runs.\n * Answers the whole product.\n */\nexport async function updateProductVariant(\n request: Request,\n ctx: ApiV1Context,\n hostId: string,\n productId: string,\n variantId: string,\n deps: ProductApiDeps = {},\n): Promise<Response> {\n const body = await readJsonBody(request)\n const parsed = readVariantWrite(body)\n if ('errors' in parsed) return validationFailed(ctx, parsed.errors, 'Variant failed validation')\n const write = parsed.values\n const products = productsOf(ctx, hostId)\n if (Object.keys(write).length > 0) {\n const saved = await saveProduct({\n ...saveContext(ctx, hostId, deps),\n productId,\n create: false,\n product: (stored) => {\n const base = storedProduct(stored)\n if ('refusal' in base) return base\n const at = base.variants.findIndex((variant) => variant.id === variantId)\n if (at === -1) return buildRefusal(404, 'No such variant')\n const variants = [...base.variants]\n variants[at] = applyVariantWrite(variants[at], write)\n const next = { ...base, variants }\n return stockRefusal(next, [write], () => 'inventory') ?? next\n },\n createdBy: null,\n cacheReason: 'product variant updated over the API',\n })\n if (saved.ok === false) return refusalResponse(ctx, saved)\n }\n const snap = await products.doc(productId).get()\n if (!snap.exists || snap.get('deletedAt')) return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n const variants = (snap.get('variants') ?? []) as ProductVariant[]\n if (!variants.some((variant) => variant.id === variantId)) {\n return ApiErrors.notFound({ message: 'No such variant', headers: ctx.headers })\n }\n return apiJson(productView(snap), { headers: ctx.headers })\n}\n\n/**\n * `DELETE /v1/sites/{siteId}/products/{productId}` — the products list's\n * Delete: `deletedAt` on the product, which takes it off sale, and the\n * site's cache drop. Asked again, it answers the same receipt; a product\n * that never existed is a 404.\n */\nexport async function deleteProductOverApi(\n ctx: ApiV1Context,\n hostId: string,\n productId: string,\n deps: ProductApiDeps = {},\n): Promise<Response> {\n const removed = await deleteProduct({\n firestore: ctx.firestore,\n hostId,\n productId,\n dropCache: deps.dropCache ?? dropPluginSiteCache,\n cacheReason: 'product deleted over the API',\n })\n if (removed.ok === false) return ApiErrors.notFound({ message: 'No such product', headers: ctx.headers })\n return apiJson({ id: productId, object: 'product', deleted: true }, { headers: ctx.headers })\n}\n"],"names":["createResourceUid","SCREEN_SEO_TEXT_GUIDANCE","dropPluginSiteCache","ApiErrors","apiJson","apiActorFields","claimWrite","readJsonBody","COMMERCE_MAX_OPTIONS","COMMERCE_SLUG_MAX_LENGTH","commerceSlug","liftLegacyProduct","renameProductOptions","stockTrackingApplies","variantMatrixProblem","blankProductDraft","PRODUCT_NAME_MAX_LENGTH","variantComboKey","variantsForOptions","claimProductSlug","deleteProduct","saveProduct","productView","PRODUCT_WRITABLE_KEYS","VARIANT_WRITABLE_KEYS","VARIANT_TARGET_KEYS","SEO_WRITABLE_KEYS","PRODUCT_API_TYPES","PRODUCT_DIGITAL_REFUSAL","PRODUCT_STATUSES","PRODUCT_STOCK_NOT_TRACKED","isPlainObject","value","Boolean","Array","isArray","unknownKeys","body","allowed","prefix","Object","fromEntries","keys","filter","key","includes","map","stringList","some","entry","trim","amount","what","Number","isFinite","readVariantWrite","options","errors","target","values","field","parsed","raw","isInteger","inventory","id","length","readProductWrite","create","name","description","join","status","type","slug","list","url","test","Set","forEach","option","index","optionValues","push","read","assign","variants","seo","text","limit","applyVariantWrite","variant","write","next","buildRefusal","error","detail","refusal","stockRefusal","product","writes","findIndex","mergeProductWrite","base","nowMs","undefined","entries","seen","at","has","add","refused","refusalResponse","ctx","code","badRequest","message","headers","planRequired","conflict","notFound","fields","validationFailed","productsOf","hostId","firestore","collection","doc","danglingCategories","ids","categories","missing","get","exists","categoryIds","saveContext","deps","org","now","Date","dropCache","unpricedProductDraft","draft","unpriced","priceUsd","createProduct","request","dangling","ok","claimed","replay","claim","products","productId","saved","uniqueSlug","createdBy","uid","createStamps","cacheReason","release","view","record","storedProduct","stored","data","updateProduct","context","snap","updateProductVariant","variantId","deleteProductOverApi","removed","object","deleted"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,iBAAiB,QAAQ,6CAA4C;AAC9E,SAASC,wBAAwB,QAAQ,2CAA0C;AACnF,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,SAAS,EAAEC,OAAO,QAAQ,2BAA0B;AAC7D,SAEEC,cAAc,EACdC,UAAU,EACVC,YAAY,QACP,6CAA4C;AACnD,SACEC,oBAAoB,EACpBC,wBAAwB,EACxBC,YAAY,EACZC,iBAAiB,EAKjBC,oBAAoB,EACpBC,oBAAoB,EACpBC,oBAAoB,QACf,0BAAsB;AAC7B,SACEC,iBAAiB,EAEjBC,uBAAuB,EACvBC,eAAe,EACfC,kBAAkB,QACb,+BAA2B;AAClC,SACEC,gBAAgB,EAChBC,aAAa,EAIbC,WAAW,QACN,uBAAmB;AAC1B,SAASC,WAAW,QAAQ,oBAAgB;AAE5C;;;;;;;;;;;;;;;;;;;;CAoBC,GAED,oFAAoF,GACpF,OAAO,MAAMC,wBAAwB;IAC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OAAO,OAAOjJ,UAAUqH,QAAQ,CAAC;QAAEJ,SAAS;QAAmBC,SAASJ,IAAII,OAAO;IAAC;IACvG,OAAOjH,QAAQ;QAAE6D,IAAIwF;QAAWoB,QAAQ;QAAWC,SAAS;IAAK,GAAG;QAAEzD,SAASJ,IAAII,OAAO;IAAC;AAC7F"}
@@ -19,7 +19,7 @@ import { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cac
19
19
  import { type PluginApiHandler } from '@aglyn/aglyn/server';
20
20
  import { getLockdownVerdict } from '@aglyn/tenant-data-admin';
21
21
  import { FieldValue } from 'firebase-admin/firestore';
22
- import { type InventoryAdjustmentReason } from '../model';
22
+ import { type EditedProduct, type InventoryAdjustmentReason } from '../model';
23
23
  type Firestore = FirebaseFirestore.Firestore;
24
24
  /** Names "Edit site content" (`site.edit`, AGL-4047), never a role. */
25
25
  export declare const ROLE_REFUSAL: string;
@@ -84,8 +84,83 @@ export declare function outboxEntry(firestore: Firestore, hostId: string): {
84
84
  entireHost: boolean;
85
85
  };
86
86
  };
87
- export declare function settleCache(deps: Required<ProductsWriteDeps>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string): Promise<void>;
87
+ export declare function settleCache(deps: Pick<Required<ProductsWriteDeps>, 'dropCache'>, hostId: string, entry: FirebaseFirestore.DocumentReference, reason: string): Promise<void>;
88
88
  export declare function resolved(deps: ProductsWriteDeps): Required<ProductsWriteDeps>;
89
+ /** Why a product save or delete was refused, for its caller to answer in its own words. */
90
+ export type ProductWriteRefusalCode =
91
+ /** The product fails the editor's rules (`variantMatrixProblem`, `validateProductForSave`). */
92
+ 'invalid'
93
+ /** The plan does not include commerce. */
94
+ | 'plan'
95
+ /** The plan's product allowance is used up. */
96
+ | 'quota'
97
+ /** The product does not exist, or was deleted. */
98
+ | 'missing'
99
+ /** Another product holds the slug (only asked with `uniqueSlug`). */
100
+ | 'slug_taken'
101
+ /** A refusal the caller's own `product` builder made. */
102
+ | 'refused';
103
+ export interface ProductWriteRefusal {
104
+ ok: false;
105
+ status: number;
106
+ code: ProductWriteRefusalCode;
107
+ error: string;
108
+ /** What a builder's refusal names, for its caller. */
109
+ detail?: unknown;
110
+ }
111
+ export type ProductSaveResult = {
112
+ ok: true;
113
+ id: string;
114
+ replayed: boolean;
115
+ } | ProductWriteRefusal;
116
+ /** A refusal a {@link ProductSaveInput.product} builder answers instead of a product. */
117
+ export interface ProductBuildRefusal {
118
+ refusal: {
119
+ status: number;
120
+ error: string;
121
+ detail?: unknown;
122
+ };
123
+ }
124
+ /**
125
+ * One product save, already authorized (AGL-4235): the console editor's
126
+ * write, whoever asks for it. The native apps' save route and the public
127
+ * API's product writes both call this, so the derived fields, the checks, the
128
+ * smart-collection membership, the plan and allowance count, the publish
129
+ * outbox and the cache drop are made once.
130
+ *
131
+ * The caller has decided who may write this site. Nothing here asks.
132
+ */
133
+ export interface ProductSaveInput {
134
+ firestore: Firestore;
135
+ hostId: string;
136
+ productId: string;
137
+ /** A new product under `productId` (a retry finds its own and answers `replayed`), or an edit of the live one. */
138
+ create: boolean;
139
+ /**
140
+ * The product to save, or how to make it from the stored document read in
141
+ * the save's own transaction, so an edit merged onto it cannot lose a
142
+ * change made between a read and the write.
143
+ */
144
+ product: EditedProduct | ((stored: FirebaseFirestore.DocumentSnapshot) => EditedProduct | ProductBuildRefusal);
145
+ /** The organization the plan and the allowance are read from. */
146
+ org: Record<string, unknown>;
147
+ /** Who a create is `createdBy`: a person's uid, or null when no person made it. */
148
+ createdBy: string | null;
149
+ /** Further fields a create stamps, such as the API credential that made it. */
150
+ createStamps?: Record<string, unknown>;
151
+ /** Refuse a slug another product of the site holds, live or deleted. */
152
+ uniqueSlug?: boolean;
153
+ nowMs: number;
154
+ dropCache: Required<ProductsWriteDeps>['dropCache'];
155
+ /** What the cache drop says caused it. */
156
+ cacheReason: string;
157
+ }
158
+ /**
159
+ * Saves a product as the console editor does: `create` makes a new product
160
+ * under `productId`; otherwise it replaces the live product, keeping its live
161
+ * stock holds and the stored timestamps the product does not name.
162
+ */
163
+ export declare function saveProduct(input: ProductSaveInput): Promise<ProductSaveResult>;
89
164
  /**
90
165
  * Saves a product as the console editor does. `create: true` makes a new
91
166
  * product under the client-minted `productId` (a retry finds its own product
@@ -126,6 +201,23 @@ export declare function claimProductSlug(products: FirebaseFirestore.CollectionR
126
201
  * its own copy and answers `replayed`.
127
202
  */
128
203
  export declare function createProductDuplicateHandler(options?: ProductsWriteDeps): PluginApiHandler;
204
+ export type ProductDeleteResult = {
205
+ ok: true;
206
+ already: boolean;
207
+ } | ProductWriteRefusal;
208
+ /**
209
+ * The products list's Delete, already authorized (AGL-4235): `deletedAt` on
210
+ * the product, which stops it being purchasable, with the publish outbox
211
+ * entry and the site-wide cache drop. A deleted product answers `already`.
212
+ * The native apps' delete route and the public API both call this.
213
+ */
214
+ export declare function deleteProduct(input: {
215
+ firestore: Firestore;
216
+ hostId: string;
217
+ productId: string;
218
+ dropCache: Required<ProductsWriteDeps>['dropCache'];
219
+ cacheReason: string;
220
+ }): Promise<ProductDeleteResult>;
129
221
  /**
130
222
  * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete
131
223
  * for the native apps, the console's write (`deletedAt` on the product, which
@@ -150,6 +150,113 @@ export function resolved(deps) {
150
150
  now: (_deps_now = deps.now) != null ? _deps_now : ()=>Date.now()
151
151
  };
152
152
  }
153
+ const isBuildRefusal = (value)=>Boolean(value && typeof value === 'object' && 'refusal' in value);
154
+ /**
155
+ * Saves a product as the console editor does: `create` makes a new product
156
+ * under `productId`; otherwise it replaces the live product, keeping its live
157
+ * stock holds and the stored timestamps the product does not name.
158
+ */ export async function saveProduct(input) {
159
+ const { firestore: db, hostId, productId, create, nowMs } = input;
160
+ const hostRef = db.collection('hosts').doc(hostId);
161
+ const products = hostRef.collection('products');
162
+ const productRef = products.doc(productId);
163
+ const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart');
164
+ const outbox = outboxEntry(db, hostId);
165
+ const answer = await db.runTransaction(async (tx)=>{
166
+ var _variantMatrixProblem;
167
+ const [existing, smart] = await Promise.all([
168
+ tx.get(productRef),
169
+ tx.get(smartQuery)
170
+ ]);
171
+ const built = typeof input.product === 'function' ? input.product(existing) : input.product;
172
+ if (isBuildRefusal(built)) {
173
+ return _extends({
174
+ ok: false,
175
+ code: 'refused'
176
+ }, built.refusal);
177
+ }
178
+ const product = built;
179
+ const fields = productSaveFields(product, nowMs);
180
+ // More combinations than a product holds is refused with the count
181
+ // (AGL-4100), never saved short of the options it names.
182
+ const problem = (_variantMatrixProblem = variantMatrixProblem(fields.options)) != null ? _variantMatrixProblem : validateProductForSave(fields);
183
+ if (problem) return {
184
+ ok: false,
185
+ status: 400,
186
+ code: 'invalid',
187
+ error: problem
188
+ };
189
+ if (input.uniqueSlug) {
190
+ const holders = await tx.get(products.where('slug', '==', fields.slug).limit(2));
191
+ if (holders.docs.some((doc)=>doc.id !== productId)) {
192
+ return {
193
+ ok: false,
194
+ status: 409,
195
+ code: 'slug_taken',
196
+ error: `Another product already uses the slug “${fields.slug}”`
197
+ };
198
+ }
199
+ }
200
+ const membership = {
201
+ collectionIds: productCollectionIds(productMembershipInput(fields, product), smart.docs.map((doc)=>smartCollectionRulesOf(doc.id, doc.data())))
202
+ };
203
+ if (create) {
204
+ var _input_createStamps;
205
+ if (existing.exists) return {
206
+ ok: true,
207
+ id: productId,
208
+ replayed: true
209
+ };
210
+ const early = planRefusal(input.org);
211
+ if (early) return {
212
+ ok: false,
213
+ status: early.status,
214
+ code: 'plan',
215
+ error: early.error
216
+ };
217
+ const used = await countLiveDocuments(products, (aggregate)=>tx.get(aggregate));
218
+ const room = roomRefusal(input.org, Number(used) || 0);
219
+ if (room) return {
220
+ ok: false,
221
+ status: room.status,
222
+ code: 'quota',
223
+ error: room.error
224
+ };
225
+ tx.create(productRef, _extends({}, fields, membership, {
226
+ createdAtMs: nowMs,
227
+ deletedAt: null,
228
+ createdAt: FieldValue.serverTimestamp(),
229
+ updatedAt: FieldValue.serverTimestamp(),
230
+ createdBy: input.createdBy
231
+ }, (_input_createStamps = input.createStamps) != null ? _input_createStamps : {}));
232
+ } else {
233
+ var _existing_data;
234
+ if (!existing.exists || existing.get('deletedAt')) {
235
+ return {
236
+ ok: false,
237
+ status: 404,
238
+ code: 'missing',
239
+ error: 'This product was deleted'
240
+ };
241
+ }
242
+ tx.set(productRef, _extends({}, storedTimestamps((_existing_data = existing.data()) != null ? _existing_data : {}, product), productEditWrite(fields, existing.get('stockHolds')), membership, {
243
+ updatedAt: FieldValue.serverTimestamp()
244
+ }));
245
+ }
246
+ tx.set(outbox.ref, outbox.data);
247
+ return {
248
+ ok: true,
249
+ id: productId,
250
+ replayed: false
251
+ };
252
+ });
253
+ if (answer.ok && !answer.replayed) {
254
+ await settleCache({
255
+ dropCache: input.dropCache
256
+ }, hostId, outbox.ref, input.cacheReason);
257
+ }
258
+ return answer;
259
+ }
153
260
  /**
154
261
  * Saves a product as the console editor does. `create: true` makes a new
155
262
  * product under the client-minted `productId` (a retry finds its own product
@@ -174,89 +281,28 @@ export function resolved(deps) {
174
281
  error: 'Product name is required'
175
282
  });
176
283
  try {
177
- var _variantMatrixProblem;
178
284
  const door = await gate(req, res, hostId, deps);
179
285
  if (!door) return;
180
- const nowMs = deps.now();
181
- const fields = productSaveFields(product, nowMs);
182
- // More combinations than a product holds is refused with the count
183
- // (AGL-4100), never saved short of the options it names.
184
- const problem = (_variantMatrixProblem = variantMatrixProblem(fields.options)) != null ? _variantMatrixProblem : validateProductForSave(fields);
185
- if (problem) return res.status(400).json({
186
- error: problem
286
+ const saved = await saveProduct({
287
+ firestore: deps.firestore(),
288
+ hostId,
289
+ productId,
290
+ create: body['create'] === true,
291
+ product,
292
+ org: door.org,
293
+ createdBy: door.uid,
294
+ nowMs: deps.now(),
295
+ dropCache: deps.dropCache,
296
+ cacheReason: 'product saved from the app'
187
297
  });
188
- const db = deps.firestore();
189
- const hostRef = db.collection('hosts').doc(hostId);
190
- const products = hostRef.collection('products');
191
- const productRef = products.doc(productId);
192
- const smartQuery = hostRef.collection('collections').where('kind', '==', 'catalog').where('mode', '==', 'smart');
193
- const outbox = outboxEntry(db, hostId);
194
- const create = body['create'] === true;
195
- const answer = await db.runTransaction(async (tx)=>{
196
- const [existing, smart] = await Promise.all([
197
- tx.get(productRef),
198
- tx.get(smartQuery)
199
- ]);
200
- const membership = {
201
- collectionIds: productCollectionIds(productMembershipInput(fields, product), smart.docs.map((doc)=>smartCollectionRulesOf(doc.id, doc.data())))
202
- };
203
- if (create) {
204
- if (existing.exists) return {
205
- status: 200,
206
- body: {
207
- ok: true,
208
- id: productId,
209
- replayed: true
210
- }
211
- };
212
- const early = planRefusal(door.org);
213
- if (early) return {
214
- status: early.status,
215
- body: {
216
- error: early.error
217
- }
218
- };
219
- const used = await countLiveDocuments(products, (aggregate)=>tx.get(aggregate));
220
- const room = roomRefusal(door.org, Number(used) || 0);
221
- if (room) return {
222
- status: room.status,
223
- body: {
224
- error: room.error
225
- }
226
- };
227
- tx.create(productRef, _extends({}, fields, membership, {
228
- createdAtMs: nowMs,
229
- deletedAt: null,
230
- createdAt: FieldValue.serverTimestamp(),
231
- updatedAt: FieldValue.serverTimestamp(),
232
- createdBy: door.uid
233
- }));
234
- } else {
235
- var _existing_data;
236
- if (!existing.exists || existing.get('deletedAt')) return {
237
- status: 404,
238
- body: {
239
- error: 'This product was deleted'
240
- }
241
- };
242
- tx.set(productRef, _extends({}, storedTimestamps((_existing_data = existing.data()) != null ? _existing_data : {}, product), productEditWrite(fields, existing.get('stockHolds')), membership, {
243
- updatedAt: FieldValue.serverTimestamp()
244
- }));
245
- }
246
- tx.set(outbox.ref, outbox.data);
247
- return {
248
- status: 200,
249
- body: {
250
- ok: true,
251
- id: productId,
252
- replayed: false
253
- }
254
- };
298
+ if (saved.ok === false) return res.status(saved.status).json({
299
+ error: saved.error
300
+ });
301
+ return res.status(200).json({
302
+ ok: true,
303
+ id: saved.id,
304
+ replayed: saved.replayed
255
305
  });
256
- if (answer.status === 200 && !answer.body.replayed) {
257
- await settleCache(deps, hostId, outbox.ref, 'product saved from the app');
258
- }
259
- return res.status(answer.status).json(answer.body);
260
306
  } catch (error) {
261
307
  console.error('[commerce/products/save]', error);
262
308
  return res.status(500).json({
@@ -506,6 +552,39 @@ export function resolved(deps) {
506
552
  }
507
553
  };
508
554
  }
555
+ /**
556
+ * The products list's Delete, already authorized (AGL-4235): `deletedAt` on
557
+ * the product, which stops it being purchasable, with the publish outbox
558
+ * entry and the site-wide cache drop. A deleted product answers `already`.
559
+ * The native apps' delete route and the public API both call this.
560
+ */ export async function deleteProduct(input) {
561
+ const { firestore: db, hostId, productId } = input;
562
+ const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId);
563
+ const outbox = outboxEntry(db, hostId);
564
+ const answer = await db.runTransaction(async (tx)=>{
565
+ const stored = await tx.get(productRef);
566
+ if (!stored.exists) return {
567
+ ok: false,
568
+ status: 404,
569
+ code: 'missing',
570
+ error: 'This product no longer exists'
571
+ };
572
+ if (stored.get('deletedAt')) return {
573
+ ok: true,
574
+ already: true
575
+ };
576
+ tx.update(productRef, {
577
+ deletedAt: FieldValue.serverTimestamp()
578
+ });
579
+ tx.set(outbox.ref, outbox.data);
580
+ return {
581
+ ok: true,
582
+ already: false
583
+ };
584
+ });
585
+ if (answer.ok && !answer.already) await settleCache(input, hostId, outbox.ref, input.cacheReason);
586
+ return answer;
587
+ }
509
588
  /**
510
589
  * `POST /api/commerce/products/delete` (AGL-3841): the products list's Delete
511
590
  * for the native apps, the console's write (`deletedAt` on the product, which
@@ -525,40 +604,20 @@ export function resolved(deps) {
525
604
  try {
526
605
  const door = await gate(req, res, hostId, deps);
527
606
  if (!door) return;
528
- const db = deps.firestore();
529
- const productRef = db.collection('hosts').doc(hostId).collection('products').doc(productId);
530
- const outbox = outboxEntry(db, hostId);
531
- const answer = await db.runTransaction(async (tx)=>{
532
- const stored = await tx.get(productRef);
533
- if (!stored.exists) return {
534
- status: 404,
535
- body: {
536
- error: 'This product no longer exists'
537
- }
538
- };
539
- if (stored.get('deletedAt')) return {
540
- status: 200,
541
- body: {
542
- ok: true,
543
- already: true
544
- }
545
- };
546
- tx.update(productRef, {
547
- deletedAt: FieldValue.serverTimestamp()
548
- });
549
- tx.set(outbox.ref, outbox.data);
550
- return {
551
- status: 200,
552
- body: {
553
- ok: true,
554
- already: false
555
- }
556
- };
607
+ const removed = await deleteProduct({
608
+ firestore: deps.firestore(),
609
+ hostId,
610
+ productId,
611
+ dropCache: deps.dropCache,
612
+ cacheReason: 'product deleted from the app'
613
+ });
614
+ if (removed.ok === false) return res.status(removed.status).json({
615
+ error: removed.error
616
+ });
617
+ return res.status(200).json({
618
+ ok: true,
619
+ already: removed.already
557
620
  });
558
- if (answer.status === 200 && !answer.body.already) {
559
- await settleCache(deps, hostId, outbox.ref, 'product deleted from the app');
560
- }
561
- return res.status(answer.status).json(answer.body);
562
621
  } catch (error) {
563
622
  console.error('[commerce/products/delete]', error);
564
623
  return res.status(500).json({