495 lines
19 KiB
TypeScript
495 lines
19 KiB
TypeScript
/**
|
|
* E2E-41..50 — golden catalog mutation → cache flow (catalogue §2.4).
|
|
*
|
|
* Live HTTP/tRPC suite. Each `it()` maps to one catalogue row.
|
|
*
|
|
* products/stores/banners are rebuilt asynchronously by the CacheCreator DO and
|
|
* share `products_version_num`; availability and slots are written
|
|
* synchronously. To keep the (heavy, ~490-store) rebuild count low — and avoid
|
|
* exhausting the local workerd heap — the mutations for E2E-41..43, 46..48 and
|
|
* 50 are issued in TWO debounce windows: a "create/update" batch (batch 1) and
|
|
* a "delete/reorder" batch (batch 2). Each window is polled once and every row
|
|
* reads the resulting versioned files.
|
|
*
|
|
* `E2E-48` uses the region-scoped `tagsOrder` constant and restores the original
|
|
* value in `finally`; it never triggers an all-region rebuild.
|
|
*/
|
|
|
|
import { SIXTY_SECONDS_MS } from '../constants'
|
|
import { uniqueSuffix, type ApiClient } from '../helpers/api'
|
|
import { staffClient } from '../helpers/sessions'
|
|
import {
|
|
createAddress,
|
|
createFutureSlot,
|
|
createProduct,
|
|
createStore,
|
|
getRegionConstant,
|
|
placeOrder,
|
|
registerThrowawayUser,
|
|
withBoundSetting,
|
|
} from '../helpers/fixtures'
|
|
import {
|
|
getEssentialConsts,
|
|
scaffoldCache,
|
|
type EssentialConsts,
|
|
} from '../helpers/cache'
|
|
import { TEST_BOUND_ID, TEST_REGION_ID } from '../helpers/env'
|
|
|
|
jest.setTimeout(900_000)
|
|
|
|
const REGION_1 = TEST_REGION_ID
|
|
const FAR_FUTURE = '2030-06-01T10:00:00.000Z'
|
|
const FAR_FUTURE_FREEZE = '2030-06-01T08:00:00.000Z'
|
|
const hoursFromNow = (hours: number) => new Date(Date.now() + hours * 3_600_000).toISOString()
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Helpers */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
async function d1Version(admin: ApiClient, key: string): Promise<number> {
|
|
const rows: any = await admin.admin.region.getRegionConstants.query()
|
|
return Number((rows as any[]).find((entry: any) => entry.key === key)?.value ?? 0)
|
|
}
|
|
|
|
const productsVersion = (admin: ApiClient) => d1Version(admin, 'products_version_num')
|
|
const availabilityVersion = (admin: ApiClient) => d1Version(admin, 'availability_version_num')
|
|
const slotsVersion = (admin: ApiClient) => d1Version(admin, 'slots_version_num')
|
|
|
|
/**
|
|
* Read a cache document from the scaffold function (test route).
|
|
* Same object the cache writer serialises, straight from D1.
|
|
*/
|
|
async function scaffoldDoc(kind: any, predicate: (doc: any) => boolean, label: string): Promise<any> {
|
|
const doc = await scaffoldCache(kind, { regionId: REGION_1 })
|
|
if (!predicate(doc)) throw new Error(`[api-tests] ${kind} document did not satisfy: ${label}`)
|
|
return doc
|
|
}
|
|
|
|
const pollProducts = (_a: ApiClient, p: (d: any) => boolean, l: string, _o = {}) => scaffoldDoc('products', p, l)
|
|
const pollStores = (_a: ApiClient, p: (d: any) => boolean, l: string, _o = {}) => scaffoldDoc('stores', p, l)
|
|
const pollBanners = (_a: ApiClient, p: (d: any) => boolean, l: string, _o = {}) => scaffoldDoc('banners', p, l)
|
|
const pollSlots = (_a: ApiClient, p: (d: any) => boolean, l: string, _o = {}) => scaffoldDoc('slots', p, l)
|
|
const pollAvailability = (_a: ApiClient, p: (d: any) => boolean, l: string, _o = {}) => scaffoldDoc('availability', p, l)
|
|
|
|
const skuIn = (doc: any, skuId: number) =>
|
|
(doc?.products ?? []).find((product: any) => Number(product.id) === skuId)
|
|
const availIn = (doc: any, skuId: number) =>
|
|
(doc?.availability ?? []).find((entry: any) => Number(entry.id) === skuId)
|
|
const slotIn = (doc: any, slotId: number) =>
|
|
(doc?.slots ?? []).find((slot: any) => Number(slot.id) === slotId)
|
|
const tagIn = (doc: any, tagId: number) =>
|
|
(doc?.tags ?? []).find((tag: any) => Number(tag.id) === tagId)
|
|
const storeIn = (doc: any, storeId: number) =>
|
|
(doc?.stores ?? []).find((store: any) => Number(store.id) === storeId)
|
|
const bannerIn = (doc: any, bannerId: number) =>
|
|
(doc?.banners ?? []).find((b: any) => Number(b.id) === bannerId)
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Batch 1 — create/update window (E2E-41..43, 46..48, 50 setup) */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
interface Shared {
|
|
admin: ApiClient
|
|
store: { storeId: number; storeName: string }
|
|
product: Awaited<ReturnType<typeof createProduct>>
|
|
updatedName: string
|
|
adminRead: any
|
|
priceSkuId: number
|
|
stockProductId: number
|
|
stockSkuId: number
|
|
bannerId: number
|
|
bannerName: string
|
|
bannerUpdatedName: string
|
|
tagId: number
|
|
tagRenamed: string
|
|
tagProductSkuB: number
|
|
tagA: number
|
|
tagB: number
|
|
deletedProductId: number
|
|
deletedSkuId: number
|
|
deletedStoreId: number
|
|
orderId: number
|
|
orderToken: string
|
|
productsDoc: any
|
|
storesDoc: any
|
|
bannersDoc: any
|
|
availabilityDoc: any
|
|
}
|
|
|
|
let shared: Shared
|
|
|
|
async function buildBatch1(): Promise<Shared> {
|
|
const admin = await staffClient()
|
|
const store = await createStore()
|
|
const product = await createProduct({ storeId: store.storeId, price: 100, skuName: '1pc' })
|
|
|
|
// E2E-41: update the product name + SKU price.
|
|
const updatedName = `E2E Mutated Product ${uniqueSuffix()}`
|
|
await admin.admin.product.updateProduct.mutate({
|
|
id: product.productId,
|
|
name: updatedName,
|
|
storeId: store.storeId,
|
|
skus: [
|
|
{
|
|
id: product.skuId,
|
|
name: '2pc',
|
|
price: 777,
|
|
marketPrice: 827,
|
|
images: [],
|
|
isFlashAvailable: false,
|
|
flashPrice: null,
|
|
isOutOfStock: false,
|
|
isOffer: false,
|
|
isComboOnly: false,
|
|
isSuspended: false,
|
|
features: [{ featureName: 'quantity', featureValue: '2pc' }],
|
|
},
|
|
],
|
|
})
|
|
const adminRead: any = await admin.admin.product.getProductById.query({ id: product.productId })
|
|
|
|
// E2E-42: synchronous availability price update (a dedicated SKU).
|
|
const priceProduct = await createProduct({ storeId: store.storeId, price: 100 })
|
|
await admin.admin.product.updateProductPrices.mutate({
|
|
updates: [{ skuId: priceProduct.skuId, price: 888 }],
|
|
})
|
|
|
|
// E2E-43: synchronous availability stock flip (a dedicated SKU).
|
|
const stockProduct = await createProduct({ storeId: store.storeId, price: 100 })
|
|
await admin.admin.product.toggleOutOfStock.mutate({ id: stockProduct.productId })
|
|
|
|
// E2E-46: banner create + update.
|
|
const suffix = uniqueSuffix()
|
|
const domain = (await getEssentialConsts()).assetsDomain
|
|
const bannerName = `E2E Mut Banner ${suffix}`
|
|
const banner: any = await admin.admin.banner.createBanner.mutate({
|
|
name: bannerName,
|
|
imageUrl: `${domain}home-banners/e2e-${suffix}.png`,
|
|
description: 'mutation probe',
|
|
})
|
|
const bannerUpdatedName = `${bannerName} active`
|
|
await admin.admin.banner.updateBanner.mutate({
|
|
id: banner.id,
|
|
name: bannerUpdatedName,
|
|
isActive: true,
|
|
serialNum: 7,
|
|
})
|
|
|
|
// E2E-47: tag create + update.
|
|
const tagStore = await createStore()
|
|
const tagAProduct = await createProduct({ storeId: tagStore.storeId })
|
|
const tagBProduct = await createProduct({ storeId: tagStore.storeId })
|
|
const tagName = `E2E Mut Tag ${uniqueSuffix()}`
|
|
const tag: any = await admin.admin.product.createProductTag.mutate({
|
|
tagName,
|
|
productIds: [tagAProduct.skuId],
|
|
})
|
|
const tagRenamed = `${tagName} renamed`
|
|
await admin.admin.product.updateProductTag.mutate({
|
|
id: tag.tag.id,
|
|
tagName: tagRenamed,
|
|
productIds: [tagBProduct.skuId],
|
|
})
|
|
|
|
// E2E-48: two tags whose order we later pin.
|
|
const orderStore = await createStore()
|
|
const orderA = await createProduct({ storeId: orderStore.storeId })
|
|
const orderB = await createProduct({ storeId: orderStore.storeId })
|
|
const tagA: any = await admin.admin.product.createProductTag.mutate({
|
|
tagName: `E2E Order A ${uniqueSuffix()}`,
|
|
productIds: [orderA.skuId],
|
|
})
|
|
const tagB: any = await admin.admin.product.createProductTag.mutate({
|
|
tagName: `E2E Order B ${uniqueSuffix()}`,
|
|
productIds: [orderB.skuId],
|
|
})
|
|
|
|
// E2E-50: a store/product (with an order) to delete, plus an empty store.
|
|
const deleteStore = await createStore()
|
|
const deleteProduct = await createProduct({ storeId: deleteStore.storeId, price: 199 })
|
|
const emptyStore = await createStore()
|
|
const slot = await createFutureSlot([deleteProduct.skuId])
|
|
const user = await registerThrowawayUser()
|
|
const address = await createAddress(user.token)
|
|
const placed = await placeOrder(user.token, {
|
|
addressId: address.id,
|
|
skuId: deleteProduct.skuId,
|
|
slotId: slot.slotId,
|
|
})
|
|
const orderId = Number(placed[0].id)
|
|
|
|
// Poll the single batch-1 rebuild (all of the above writes share one window).
|
|
const productsDoc = await pollProducts(
|
|
admin,
|
|
(d) =>
|
|
Number(skuIn(d, product.skuId)?.price) === 777 &&
|
|
skuIn(d, stockProduct.skuId)?.isOutOfStock === true &&
|
|
tagIn(d, Number(tag.tag.id))?.tagName === tagRenamed &&
|
|
tagIn(d, Number(tag.tag.id))?.productIds.map(Number).includes(tagBProduct.skuId) &&
|
|
Boolean(tagIn(d, Number(tagA.tag.id))) &&
|
|
Boolean(tagIn(d, Number(tagB.tag.id))) &&
|
|
Boolean(skuIn(d, deleteProduct.skuId)),
|
|
'batch 1 products.json reflects every write'
|
|
)
|
|
const storesDoc = await pollStores(
|
|
admin,
|
|
(d) => Boolean(storeIn(d, emptyStore.storeId)),
|
|
`batch 1 stores.json contains store ${emptyStore.storeId}`
|
|
)
|
|
const bannersDoc = await pollBanners(
|
|
admin,
|
|
(d) => {
|
|
const b = bannerIn(d, Number(banner.id))
|
|
return Boolean(b && b.name === bannerUpdatedName && b.isActive === true)
|
|
},
|
|
`batch 1 banners.json contains banner ${banner.id}`
|
|
)
|
|
const availabilityDoc = await pollAvailability(
|
|
admin,
|
|
(d) =>
|
|
Number(availIn(d, priceProduct.skuId)?.price) === 888 &&
|
|
availIn(d, stockProduct.skuId)?.isOutOfStock === true,
|
|
'batch 1 availability.json reflects the price + stock flip',
|
|
{ timeoutMs: 120_000 }
|
|
)
|
|
|
|
return {
|
|
admin,
|
|
store,
|
|
product,
|
|
updatedName,
|
|
adminRead,
|
|
priceSkuId: priceProduct.skuId,
|
|
stockProductId: stockProduct.productId,
|
|
stockSkuId: stockProduct.skuId,
|
|
bannerId: Number(banner.id),
|
|
bannerName,
|
|
bannerUpdatedName,
|
|
tagId: Number(tag.tag.id),
|
|
tagRenamed,
|
|
tagProductSkuB: tagBProduct.skuId,
|
|
tagA: Number(tagA.tag.id),
|
|
tagB: Number(tagB.tag.id),
|
|
deletedProductId: deleteProduct.productId,
|
|
deletedSkuId: deleteProduct.skuId,
|
|
deletedStoreId: emptyStore.storeId,
|
|
orderId,
|
|
orderToken: user.token,
|
|
productsDoc,
|
|
storesDoc,
|
|
bannersDoc,
|
|
availabilityDoc,
|
|
}
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
shared = await buildBatch1()
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Batch 2 — delete/reorder window (memoized) */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
interface Batch2 {
|
|
productsDoc: any
|
|
bannersDoc: any
|
|
storesDoc: any
|
|
}
|
|
|
|
let batch2Promise: Promise<Batch2> | null = null
|
|
|
|
function runBatch2(): Promise<Batch2> {
|
|
batch2Promise ??= (async (): Promise<Batch2> => {
|
|
const admin = await staffClient()
|
|
const original = await getRegionConstant(REGION_1, 'tagsOrder')
|
|
const baseline = await productsVersion(admin)
|
|
|
|
try {
|
|
await admin.admin.banner.deleteBanner.mutate({ id: shared.bannerId })
|
|
await admin.admin.product.deleteProductTag.mutate({ id: shared.tagId })
|
|
await admin.admin.product.deleteProduct.mutate({ id: shared.deletedProductId })
|
|
await admin.admin.store.deleteStore.mutate({ storeId: shared.deletedStoreId })
|
|
await admin.admin.region.updateRegionConstants.mutate({
|
|
constants: [{ key: 'tagsOrder', value: `${shared.tagB},${shared.tagA}` }],
|
|
})
|
|
|
|
const productsDoc = await pollProducts(
|
|
admin,
|
|
(d) => {
|
|
const ids = (d.tags ?? []).map((tag: any) => Number(tag.id))
|
|
return (
|
|
!tagIn(d, shared.tagId) &&
|
|
!skuIn(d, shared.deletedSkuId) &&
|
|
ids[0] === shared.tagB &&
|
|
ids[1] === shared.tagA
|
|
)
|
|
},
|
|
'batch 2 products.json reflects the deletes + tagsOrder',
|
|
{ minVersion: baseline }
|
|
)
|
|
const bannersDoc = await pollBanners(
|
|
admin,
|
|
(d) => !bannerIn(d, shared.bannerId),
|
|
`batch 2 banners.json omits banner ${shared.bannerId}`,
|
|
{ minVersion: baseline }
|
|
)
|
|
const storesDoc = await pollStores(
|
|
admin,
|
|
(d) => !storeIn(d, shared.deletedStoreId),
|
|
`batch 2 stores.json omits store ${shared.deletedStoreId}`,
|
|
{ minVersion: baseline }
|
|
)
|
|
return { productsDoc, bannersDoc, storesDoc }
|
|
} finally {
|
|
await admin.admin.region.updateRegionConstants.mutate({
|
|
constants: [{ key: 'tagsOrder', value: original }],
|
|
})
|
|
}
|
|
})()
|
|
return batch2Promise
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Product mutations (E2E-41..43) */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
describe('catalog mutation — product (E2E-41..43)', () => {
|
|
it('E2E-41: a product name/price update is immediate in admin and eventual in the cache', () => {
|
|
expect(shared.adminRead.product.name).toBe(shared.updatedName)
|
|
expect(Number(shared.adminRead.product.skus[0].price)).toBe(777)
|
|
|
|
const product = skuIn(shared.productsDoc, shared.product.skuId)
|
|
expect(Number(product.price)).toBe(777)
|
|
expect(product.name).toBe('2pc')
|
|
})
|
|
|
|
it('E2E-42: a SKU price update bumps availability synchronously and the value updates', () => {
|
|
expect(Number(availIn(shared.availabilityDoc, shared.priceSkuId).price)).toBe(888)
|
|
})
|
|
|
|
it('E2E-43: toggling out of stock updates availability synchronously and products eventually', () => {
|
|
expect(availIn(shared.availabilityDoc, shared.stockSkuId).isOutOfStock).toBe(true)
|
|
expect(skuIn(shared.productsDoc, shared.stockSkuId).isOutOfStock).toBe(true)
|
|
})
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Slot mutations (E2E-44..45) */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
describe('catalog mutation — slot (E2E-44..45)', () => {
|
|
it('E2E-44: a slot update bumps slots_version_num and the new time appears', async () => {
|
|
const admin = await staffClient()
|
|
const slot = await createFutureSlot([], { deliveryInHours: 4, freezeInHours: 3 })
|
|
const newDelivery = hoursFromNow(9)
|
|
const newFreeze = hoursFromNow(8)
|
|
|
|
const before = await slotsVersion(admin)
|
|
await admin.admin.slots.updateSlot.mutate({
|
|
id: slot.slotId,
|
|
deliveryTime: newDelivery,
|
|
freezeTime: newFreeze,
|
|
isActive: true,
|
|
})
|
|
expect(await slotsVersion(admin)).toBeGreaterThan(before)
|
|
|
|
const doc = await pollSlots(
|
|
admin,
|
|
(d) => slotIn(d, slot.slotId)?.deliveryTime === newDelivery,
|
|
`slots.json shows the updated slot ${slot.slotId}`,
|
|
{ timeoutMs: 120_000 }
|
|
)
|
|
expect(slotIn(doc, slot.slotId).deliveryTime).toBe(newDelivery)
|
|
expect(slotIn(doc, slot.slotId).freezeTime).toBe(newFreeze)
|
|
})
|
|
|
|
it('E2E-45: setting a slot capacity-full removes it from slots.json', async () => {
|
|
const admin = await staffClient()
|
|
const slot = await createFutureSlot([])
|
|
await admin.admin.slots.updateSlot.mutate({
|
|
id: slot.slotId,
|
|
deliveryTime: FAR_FUTURE,
|
|
freezeTime: FAR_FUTURE_FREEZE,
|
|
isActive: true,
|
|
})
|
|
await pollSlots(admin, (d) => Boolean(slotIn(d, slot.slotId)), `slot ${slot.slotId} is present`, {
|
|
timeoutMs: 120_000,
|
|
})
|
|
|
|
const baseline = await slotsVersion(admin)
|
|
await admin.admin.slots.updateSlotCapacity.mutate({ slotId: slot.slotId, isCapacityFull: true })
|
|
expect(await slotsVersion(admin)).toBeGreaterThan(baseline)
|
|
|
|
const doc = await pollSlots(
|
|
admin,
|
|
(d) => !slotIn(d, slot.slotId),
|
|
`slots.json omits capacity-full slot ${slot.slotId}`,
|
|
{ minVersion: baseline, timeoutMs: 120_000 }
|
|
)
|
|
expect(slotIn(doc, slot.slotId)).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Banner / tag mutations (E2E-46..48) */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
describe('catalog mutation — banner (E2E-46)', () => {
|
|
it('E2E-46: a banner create/update/delete is reflected in banners.json', async () => {
|
|
const present = bannerIn(shared.bannersDoc, shared.bannerId)
|
|
expect(present.name).toBe(shared.bannerUpdatedName)
|
|
expect(present.isActive).toBe(true)
|
|
|
|
const after = await runBatch2()
|
|
expect(bannerIn(after.bannersDoc, shared.bannerId)).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('catalog mutation — tag (E2E-47..48)', () => {
|
|
it('E2E-47: a tag create/update/delete is reflected in products.json', async () => {
|
|
const tag = tagIn(shared.productsDoc, shared.tagId)
|
|
expect(tag.tagName).toBe(shared.tagRenamed)
|
|
expect(tag.productIds.map(Number)).toContain(shared.tagProductSkuB)
|
|
|
|
const after = await runBatch2()
|
|
expect(tagIn(after.productsDoc, shared.tagId)).toBeUndefined()
|
|
})
|
|
|
|
it('E2E-48: a region tagsOrder update reorders products.json tags', async () => {
|
|
const after = await runBatch2()
|
|
const ids = (after.productsDoc.tags ?? []).map((tag: any) => Number(tag.id))
|
|
expect(ids.slice(0, 2)).toEqual([shared.tagB, shared.tagA])
|
|
})
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Bound constants + delete (E2E-49..50) */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
describe('catalog mutation — consts + delete (E2E-49..50)', () => {
|
|
it('E2E-49: a bound delivery-charge update is reflected by common.essentialConsts', async () => {
|
|
await withBoundSetting(TEST_BOUND_ID, 'deliveryCharge', '77', async () => {
|
|
const consts = await getEssentialConsts(TEST_BOUND_ID)
|
|
expect(Number(consts.deliveryCharge)).toBe(77)
|
|
})
|
|
})
|
|
|
|
it('E2E-50: deleting a store/product removes it from the cache but keeps order history', async () => {
|
|
// Present before the delete window.
|
|
expect(skuIn(shared.productsDoc, shared.deletedSkuId)).toBeTruthy()
|
|
expect(storeIn(shared.storesDoc, shared.deletedStoreId)).toBeTruthy()
|
|
|
|
const after = await runBatch2()
|
|
expect(skuIn(after.productsDoc, shared.deletedSkuId)).toBeUndefined()
|
|
expect(storeIn(after.storesDoc, shared.deletedStoreId)).toBeUndefined()
|
|
|
|
// Historical order still resolves its item after the product was deleted.
|
|
const { apiClient } = await import('../helpers/api')
|
|
const detail: any = await apiClient(shared.orderToken).user.order.getOrderById.query({
|
|
orderId: String(shared.orderId),
|
|
})
|
|
expect(detail.items).toHaveLength(1)
|
|
expect(detail.totalAmount).toBeGreaterThan(0)
|
|
expect(typeof detail.items[0].productName).toBe('string')
|
|
})
|
|
})
|