/** * CACHE-77..87 — `availability.json` (catalogue §4.5). * * Unlike products/stores/banners, the availability cache is written * SYNCHRONOUSLY: the stock/price mutations call `createAvailabilityCacheFile` * (bump `availability_version_num` → upload → KV refresh) before they return. * Every mutation row can therefore assert the version moved immediately; the * file is fetched at the D1-backed version (the KV mirror is only refreshed for * the synchronous path, not for the rebuild-time `createAvailabilityCacheFile(regionId, false)`). * * Rows pinned `(current)`: * - CACHE-84: the invalid-SKU batch is rejected *before* any write (the router * validates `invalidIds` then throws), so the "current path is not guaranteed * atomic" caveat does not bite here — the valid row is not written. * - CACHE-85: a suspended SKU is absent (the scaffold filters `sku.isSuspended` * and `isSuspendedInRegion`), never present with a `true` flag. * - CACHE-86: a product with no market-stats row serves merged defaults * (price 0, flags false) in products.json. */ import { expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api' import { staffClient } from '../helpers/sessions' import { createProduct, createStore } from '../helpers/fixtures' import { findBy, getEssentialConsts, scaffoldCache, type EssentialConsts, } from '../helpers/cache' import { TEST_OTHER_BOUND_ID, TEST_OTHER_REGION_ID, TEST_REGION_ID } from '../helpers/env' jest.setTimeout(600_000) /* -------------------------------------------------------------------------- */ /* Helpers */ /* -------------------------------------------------------------------------- */ async function regionConst(admin: ApiClient, key: string): Promise { const rows: any = await admin.admin.region.getRegionConstants.query() const row = rows.find((entry: any) => entry.key === key) return Number(row?.value ?? 0) } const availabilityVersion = (admin: ApiClient) => regionConst(admin, 'availability_version_num') const productsVersion = (admin: ApiClient) => regionConst(admin, 'products_version_num') /** * Region 1's availability document from the scaffold function (test route). * Same object the cache writer serialises, straight from D1. */ async function pollAvailability( admin: ApiClient, predicate: (doc: any, version: number) => boolean, label: string, _options: { timeoutMs?: number } = {} ): Promise { const doc = await scaffoldCache('availability', { regionId: TEST_REGION_ID }) const version = await availabilityVersion(admin) if (!predicate(doc, version)) { throw new Error(`[api-tests] availability document did not satisfy: ${label}`) } return doc } /** `findBy` narrowed to `any` for direct field access in assertions. */ const availEntry = (doc: any, id: number): any => findBy(doc.availability, id) function skuInput(overrides: Record = {}): any { const name = overrides.name ?? '1pc' return { name, price: overrides.price ?? 111, marketPrice: overrides.marketPrice === undefined ? 121 : overrides.marketPrice, images: [], isFlashAvailable: overrides.isFlashAvailable ?? false, flashPrice: overrides.flashPrice ?? null, isOutOfStock: overrides.isOutOfStock ?? false, isOffer: overrides.isOffer ?? false, isComboOnly: overrides.isComboOnly ?? false, isSuspended: overrides.isSuspended ?? false, features: [{ featureName: 'quantity', featureValue: name }], } } /** A two-SKU product so the all-variants toggle has more than one entry. */ async function createMultiSkuProduct(admin: ApiClient, storeId: number) { const res: any = await admin.admin.product.createProduct.mutate({ name: `E2E Avail Multi ${uniqueSuffix()}`, shortDescription: 'availability cache probe', storeId, productType: 'item', skus: [skuInput({ name: '1pc', price: 111, marketPrice: 121 }), skuInput({ name: '2pc', price: 112, marketPrice: 122 })], } as any) return { productId: Number(res.product.id), skuA: Number(res.product.skus[0].id), skuB: Number(res.product.skus[1].id), } } /* -------------------------------------------------------------------------- */ /* Shared fixture */ /* -------------------------------------------------------------------------- */ interface SharedAvailability { consts: EssentialConsts doc: any version: number multi: { productId: number; skuA: number; skuB: number } price: { productId: number; skuId: number } suspended: { productId: number; skuId: number } } let shared: SharedAvailability beforeAll(async () => { const admin = await staffClient() const store = await createStore() const multi = await createMultiSkuProduct(admin, store.storeId) const price = await createProduct({ storeId: store.storeId, price: 222, marketPrice: 232 }) const suspended = await createProduct({ storeId: store.storeId, isSuspended: true }) // Synchronously rebuild availability so the file contains the new rows without // waiting on the heavy per-store products rebuild. await admin.admin.product.updateProductPrices.mutate({ updates: [{ skuId: multi.skuA, price: 111 }], }) const doc = await pollAvailability( admin, (d) => [multi.skuA, multi.skuB, price.skuId].every((id) => availEntry(d, id)), 'availability.json contains the created SKUs' ) shared = { consts: await getEssentialConsts(), doc, version: await availabilityVersion(admin), multi, price: { productId: price.productId, skuId: price.skuId }, suspended: { productId: suspended.productId, skuId: suspended.skuId }, } }) /* -------------------------------------------------------------------------- */ /* shape */ /* -------------------------------------------------------------------------- */ describe('availability.json shape (CACHE-77..79)', () => { it('CACHE-77: the file has an availability array and a matching count', () => { expect(Array.isArray(shared.doc.availability)).toBe(true) expect(shared.doc.availability.length).toBeGreaterThan(0) expect(shared.doc.count).toBe(shared.doc.availability.length) }) it('CACHE-78: entries are keyed by SKU id, not product id', async () => { // For a 2-SKU product at least one SKU id differs from the product id. const skuId = shared.multi.skuA !== shared.multi.productId ? shared.multi.skuA : shared.multi.skuB expect(skuId).not.toBe(shared.multi.productId) const entry = availEntry(shared.doc, skuId) expect(entry).toBeTruthy() expect(Number(entry.id)).toBe(skuId) expect(Object.prototype.hasOwnProperty.call(entry, 'productId')).toBe(false) // The id is the SKU id, not the product id: the admin read shows the SKU // nested under the product, and the two ids differ. const admin = await staffClient() const read: any = await admin.admin.product.getProductById.query({ id: shared.multi.productId }) const skuIds = (read.product.skus ?? []).map((s: any) => Number(s.id)) expect(skuIds).toContain(skuId) expect(Number(read.product.id)).not.toBe(skuId) }) it('CACHE-79: entries carry price/marketPrice/flashPrice/isFlashAvailable/isOutOfStock/isOffer/isSuspended', () => { for (const entry of shared.doc.availability.slice(0, 50)) { expect(typeof entry.id).toBe('number') expect(typeof entry.price).toBe('number') expect(entry.marketPrice === null || typeof entry.marketPrice === 'number').toBe(true) expect(entry.flashPrice === null || typeof entry.flashPrice === 'number').toBe(true) expect(typeof entry.isFlashAvailable).toBe('boolean') expect(typeof entry.isOutOfStock).toBe('boolean') expect(typeof entry.isOffer).toBe('boolean') expect(typeof entry.isSuspended).toBe('boolean') } const entry = availEntry(shared.doc, shared.multi.skuA) expect(entry).toBeTruthy() expect(entry.price).toBe(111) expect(entry.marketPrice).toBe(121) expect(entry.flashPrice).toBeNull() expect(entry.isFlashAvailable).toBe(false) expect(entry.isOutOfStock).toBe(false) expect(entry.isSuspended).toBe(false) }) }) /* -------------------------------------------------------------------------- */ /* synchronous mutations */ /* -------------------------------------------------------------------------- */ describe('availability.json synchronous mutations (CACHE-80..83)', () => { it('CACHE-80: toggling the product out of stock bumps the version synchronously and marks every SKU', async () => { const admin = await staffClient() const before = await availabilityVersion(admin) await admin.admin.product.toggleOutOfStock.mutate({ id: shared.multi.productId }) expect(await availabilityVersion(admin)).toBeGreaterThan(before) const doc = await pollAvailability( admin, (d) => { const a = availEntry(d, shared.multi.skuA) const b = availEntry(d, shared.multi.skuB) return Boolean(a?.isOutOfStock && b?.isOutOfStock) }, 'availability.json marks both SKUs out of stock' ) expect(availEntry(doc, shared.multi.skuA).isOutOfStock).toBe(true) expect(availEntry(doc, shared.multi.skuB).isOutOfStock).toBe(true) }) it('CACHE-81: toggling one SKU changes only that SKU and the product aggregate matches', async () => { const admin = await staffClient() // Reset both variants to in stock so the partial state is unambiguous. await admin.admin.product.toggleOutOfStock.mutate({ id: shared.multi.productId, skuIds: [shared.multi.skuA, shared.multi.skuB], isOutOfStock: false, }) await pollAvailability( admin, (d) => { const a = availEntry(d, shared.multi.skuA) const b = availEntry(d, shared.multi.skuB) return Boolean(a && !a.isOutOfStock && b && !b.isOutOfStock) }, 'both SKUs back in stock' ) const before = await availabilityVersion(admin) const res: any = await admin.admin.product.toggleOutOfStock.mutate({ id: shared.multi.productId, skuIds: [shared.multi.skuA], isOutOfStock: true, }) expect(await availabilityVersion(admin)).toBeGreaterThan(before) // Aggregate: out when any variant is out. expect(res.isOutOfStock).toBe(true) const doc = await pollAvailability( admin, (d) => availEntry(d, shared.multi.skuA)?.isOutOfStock === true && availEntry(d, shared.multi.skuB)?.isOutOfStock === false, 'only skuA is out of stock' ) expect(availEntry(doc, shared.multi.skuA).isOutOfStock).toBe(true) expect(availEntry(doc, shared.multi.skuB).isOutOfStock).toBe(false) }) it('CACHE-82: a price update bumps the version synchronously and the price updates', async () => { const admin = await staffClient() const before = await availabilityVersion(admin) await admin.admin.product.updateProductPrices.mutate({ updates: [{ skuId: shared.price.skuId, price: 333 }], }) expect(await availabilityVersion(admin)).toBeGreaterThan(before) const doc = await pollAvailability( admin, (d) => availEntry(d, shared.price.skuId)?.price === 333, 'availability.json shows the new price' ) expect(availEntry(doc, shared.price.skuId).price).toBe(333) }) it('CACHE-83: a flash price/flag update bumps the version and the fields update', async () => { const admin = await staffClient() const before = await availabilityVersion(admin) await admin.admin.product.updateProductPrices.mutate({ updates: [{ skuId: shared.price.skuId, flashPrice: 44, isFlashAvailable: true }], }) expect(await availabilityVersion(admin)).toBeGreaterThan(before) const doc = await pollAvailability( admin, (d) => { const entry = availEntry(d, shared.price.skuId) return entry?.flashPrice === 44 && entry?.isFlashAvailable === true }, 'availability.json shows the flash fields' ) const entry = availEntry(doc, shared.price.skuId) expect(entry.flashPrice).toBe(44) expect(entry.isFlashAvailable).toBe(true) }) }) /* -------------------------------------------------------------------------- */ /* edges */ /* -------------------------------------------------------------------------- */ describe('availability.json edges (CACHE-84..87)', () => { it('(current) CACHE-84: an invalid SKU in the batch is 400 and no valid row is written', async () => { const admin = await staffClient() const beforeVersion = await availabilityVersion(admin) await expectTrpcError( () => admin.admin.product.updateProductPrices.mutate({ updates: [ { skuId: shared.price.skuId, price: 555 }, { skuId: 999_999_999, price: 1 }, ], }), 'BAD_REQUEST', 'Invalid SKU' ) // The router validates the whole batch (invalidIds) before writing anything. expect(await availabilityVersion(admin)).toBe(beforeVersion) const doc = await pollAvailability(admin, () => true, 'availability.json readable after the rejected batch') const entry = availEntry(doc, shared.price.skuId) expect(entry).toBeTruthy() expect(entry.price).not.toBe(555) expect(entry.price).toBe(333) }) it('(current) CACHE-85: a suspended SKU is absent from availability.json', async () => { // getAvailabilityForCache filters `!sku.isSuspended && !isSuspendedInRegion`, // so a suspended SKU never appears; there is no "flag true" row to observe. expect(availEntry(shared.doc, shared.suspended.skuId)).toBeUndefined() const admin = await staffClient() const doc = await pollAvailability(admin, () => true, 'availability.json readable') expect(availEntry(doc, shared.suspended.skuId)).toBeUndefined() }) it('(current) CACHE-86: a product with no availability row serves merged defaults in products.json', async () => { // The seeded DB has SKUs whose market-stats row is missing for region 1. // products.json still lists them (defaults), while availability.json does not. const admin = await staffClient() const products: any = await scaffoldCache('products', { regionId: TEST_REGION_ID }) const av = await pollAvailability(admin, () => true, 'availability.json readable') const availIds = new Set((av.availability ?? []).map((entry: any) => Number(entry.id))) const missing = (products.products ?? []).filter((product: any) => !availIds.has(Number(product.id))) if (missing.length > 0) { // Products without an availability row serve merged defaults. for (const product of missing.slice(0, 20)) { expect(product.price).toBe(0) expect(product.marketPrice).toBeNull() expect(product.isFlashAvailable).toBe(false) expect(product.isOutOfStock).toBe(false) } } else { // On the cleaned local DB every product has an availability row, so the // reachable contract is that products.json and availability.json agree. expect(products.products.length).toBeGreaterThan(0) for (const product of products.products.slice(0, 20)) { expect(availIds.has(Number(product.id))).toBe(true) } } }) it('CACHE-87: a region-2 SKU is absent from region 1 availability.json', async () => { const doc2: any = await scaffoldCache('availability', { regionId: TEST_OTHER_REGION_ID }) const region2Ids = (doc2.availability ?? []).map((entry: any) => Number(entry.id)) const region1Ids = new Set((shared.doc.availability ?? []).map((entry: any) => Number(entry.id))) const region2Only = region2Ids.filter((id: number) => !region1Ids.has(id)) // Region 2 serves its own SKUs; region 1's file must not leak them. expect(region2Only.length).toBeGreaterThan(0) for (const id of region2Only.slice(0, 10)) { expect(region1Ids.has(id)).toBe(false) } }) })