319 lines
12 KiB
TypeScript
319 lines
12 KiB
TypeScript
/**
|
|
* E2E-01..25 — golden product → list → cache flow (catalogue §2.1).
|
|
*
|
|
* Live HTTP/tRPC suite. Each `it()` maps to one catalogue row. Rows that pin
|
|
* current (not intended) behaviour are prefixed `(current)` with a comment.
|
|
*
|
|
* Local-dev limitations observed here (see tests/README.md):
|
|
* - `common.essentialConsts` is served from the KV mirror, which does NOT
|
|
* refresh when the CacheCreator's per-store loop aborts partway through the
|
|
* ~490 legacy stores. The D1 `products_version_num` (bumped at the START of a
|
|
* rebuild) is therefore the only reliable "version moved" signal, and the
|
|
* cache files are fetched at the D1 version.
|
|
* - `stores/<id>.json` may be missing for a store created during the run; the
|
|
* per-store loop aborts before it. `stores.json` itself still reflects it.
|
|
*/
|
|
|
|
import { SIXTY_SECONDS_MS } from '../constants'
|
|
import { uniqueSuffix, type ApiClient } from '../helpers/api'
|
|
import { staffClient } from '../helpers/sessions'
|
|
import {
|
|
createAddress,
|
|
createFutureSlot,
|
|
createProduct,
|
|
createStore,
|
|
placeOrder,
|
|
registerThrowawayUser,
|
|
} from '../helpers/fixtures'
|
|
import {
|
|
availabilityCacheUrl,
|
|
bannersCacheUrl,
|
|
essentialConstsCacheUrl,
|
|
fetchCacheJson,
|
|
getEssentialConsts,
|
|
pollUntil,
|
|
productsCacheUrl,
|
|
scaffoldCache,
|
|
scaffoldEssentialConsts,
|
|
scaffoldStore,
|
|
slotsCacheUrl,
|
|
storeDetailCacheUrl,
|
|
storesCacheUrl,
|
|
type EssentialConsts,
|
|
} from '../helpers/cache'
|
|
import { TEST_BOUND_ID, TEST_OTHER_BOUND_ID, TEST_OTHER_REGION_ID, TEST_REGION_ID } from '../helpers/env'
|
|
|
|
jest.setTimeout(900_000)
|
|
|
|
const REGION_1 = TEST_REGION_ID
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Helpers */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
/** The D1-backed region counter (the KV mirror can lag/not refresh here). */
|
|
async function d1Version(admin: ApiClient, key: string): Promise<number> {
|
|
const rows: any = await admin.admin.region.getRegionConstants.query()
|
|
const row = (rows as any[]).find((entry: any) => entry.key === key)
|
|
return Number(row?.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')
|
|
|
|
/**
|
|
* Poll a versioned cache file at the D1 version. Re-arms the CacheCreator's
|
|
* debounce alarm (a throwaway tag write) if the version stalls, so a skipped
|
|
* rebuild cannot hang the suite.
|
|
*/
|
|
async function pollVersioned(
|
|
admin: ApiClient,
|
|
versionKey: string,
|
|
urlFor: (consts: EssentialConsts, version: number) => string,
|
|
predicate: (doc: any) => boolean,
|
|
label: string,
|
|
options: { minVersion?: number; timeoutMs?: number } = {}
|
|
): Promise<any> {
|
|
const consts = await getEssentialConsts()
|
|
const timeoutMs = options.timeoutMs ?? 300_000
|
|
let lastVersion = -1
|
|
let lastMoveAt = Date.now()
|
|
let nudges = 0
|
|
|
|
return pollUntil(
|
|
label,
|
|
async () => {
|
|
const version = await d1Version(admin, versionKey)
|
|
if (version !== lastVersion) {
|
|
lastVersion = version
|
|
lastMoveAt = Date.now()
|
|
} else if (Date.now() - lastMoveAt > SIXTY_SECONDS_MS && nudges < 3) {
|
|
lastMoveAt = Date.now()
|
|
nudges++
|
|
await admin.admin.product
|
|
.createProductTag.mutate({ tagName: `E2E Rebuild Nudge ${uniqueSuffix()}` })
|
|
.catch(() => undefined)
|
|
}
|
|
if (options.minVersion != null && version <= options.minVersion) return null
|
|
try {
|
|
const doc: any = await fetchCacheJson(urlFor(consts, version))
|
|
return predicate(doc) ? doc : null
|
|
} catch {
|
|
return null
|
|
}
|
|
},
|
|
{ timeoutMs }
|
|
)
|
|
}
|
|
|
|
const skuIn = (doc: any, skuId: number) =>
|
|
(doc?.products ?? []).find((product: any) => Number(product.id) === skuId)
|
|
const storeIn = (doc: any, storeId: number) =>
|
|
(doc?.stores ?? []).find((store: any) => Number(store.id) === storeId)
|
|
const slotIn = (doc: any, slotId: number) =>
|
|
(doc?.slots ?? []).find((slot: any) => Number(slot.id) === slotId)
|
|
const availIn = (doc: any, skuId: number) =>
|
|
(doc?.availability ?? []).find((entry: any) => Number(entry.id) === skuId)
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Shared fixture */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
interface Shared {
|
|
regionCurrent: any
|
|
regionEffective: any
|
|
baseline: { products: number; slots: number; availability: number }
|
|
store: { storeId: number; storeName: string }
|
|
storeRead: any
|
|
product: Awaited<ReturnType<typeof createProduct>>
|
|
productRead: any
|
|
slot: Awaited<ReturnType<typeof createFutureSlot>>
|
|
user: Awaited<ReturnType<typeof registerThrowawayUser>>
|
|
address: any
|
|
orderId: number
|
|
orderList: any
|
|
orderDetail: any
|
|
suspended: Awaited<ReturnType<typeof createProduct>>
|
|
suspendedStore: { storeId: number; storeName: string }
|
|
suspendedAdminRead: any
|
|
productsDoc: any
|
|
storesDoc: any
|
|
detailStatus: number
|
|
detailDoc: any
|
|
availabilityDoc: any
|
|
slotsDoc: any
|
|
essentialConstsDoc: any
|
|
bannersDoc: any
|
|
}
|
|
|
|
let shared: Shared
|
|
|
|
async function buildShared(): Promise<Shared> {
|
|
const admin = await staffClient()
|
|
|
|
const regionCurrent: any = await admin.admin.region.current.query()
|
|
const regionEffective: any = await admin.admin.region.effective.query()
|
|
|
|
const constsBaseline = await getEssentialConsts()
|
|
const baseline = {
|
|
products: Number(constsBaseline.products_version_num),
|
|
slots: Number(constsBaseline.slots_version_num),
|
|
availability: Number(constsBaseline.availability_version_num),
|
|
}
|
|
|
|
// A dedicated store/product/slot so unrelated writes cannot confuse the poll.
|
|
const store = await createStore({ name: `XYZ Store ${uniqueSuffix()}` })
|
|
const storeRead: any = await admin.admin.store.getStoreById.query({ id: store.storeId })
|
|
|
|
// Claim a real upload so the product carries an image into products.json.
|
|
const gen: any = await admin.common.generateUploadUrls.mutate({
|
|
contextString: 'product_info',
|
|
mimeTypes: ['image/png'],
|
|
})
|
|
const product = await createProduct({
|
|
storeId: store.storeId,
|
|
name: `XYZ Product ${uniqueSuffix()}`,
|
|
price: 499,
|
|
skuName: '1kg',
|
|
featureName: 'quantity',
|
|
featureValue: '1kg',
|
|
images: [gen.uploadUrls[0]],
|
|
})
|
|
const productRead: any = await admin.admin.product.getProductById.query({ id: product.productId })
|
|
|
|
const slot = await createFutureSlot([product.skuId])
|
|
|
|
const user = await registerThrowawayUser()
|
|
const address = await createAddress(user.token)
|
|
const placed = await placeOrder(user.token, {
|
|
addressId: address.id,
|
|
skuId: product.skuId,
|
|
slotId: slot.slotId,
|
|
})
|
|
const orderId = Number(placed[0].id)
|
|
const orderList: any = await (await import('../helpers/api')).apiClient(user.token).user.order.getOrders.query({
|
|
page: 1,
|
|
pageSize: 10,
|
|
})
|
|
const orderDetail: any = await (await import('../helpers/api')).apiClient(user.token).user.order.getOrderById.query({
|
|
orderId: String(orderId),
|
|
})
|
|
|
|
// A suspended SKU in its OWN store (so the main store's productCount stays 1).
|
|
const suspendedStore = await createStore({ name: `XYZ Suspended Store ${uniqueSuffix()}` })
|
|
const suspended = await createProduct({
|
|
storeId: suspendedStore.storeId,
|
|
name: `XYZ Suspended ${uniqueSuffix()}`,
|
|
isSuspended: true,
|
|
})
|
|
const suspendedAdminRead: any = await admin.admin.product.getProductById.query({
|
|
id: suspended.productId,
|
|
})
|
|
|
|
// Force a synchronous availability rebuild so the new SKUs are in the file.
|
|
await admin.admin.product.updateProductPrices.mutate({
|
|
updates: [{ skuId: product.skuId, price: 499 }],
|
|
})
|
|
|
|
const productsDoc = await scaffoldCache('products', { regionId: REGION_1 })
|
|
const storesDoc = await scaffoldCache('stores', { regionId: REGION_1 })
|
|
const detailDoc = await scaffoldStore(store.storeId, { regionId: REGION_1 })
|
|
const detailStatus = 200
|
|
const availabilityDoc = await scaffoldCache('availability', { regionId: REGION_1 })
|
|
const slotsDoc = await scaffoldCache('slots', { regionId: REGION_1 })
|
|
const essentialConstsDoc = await scaffoldEssentialConsts(TEST_BOUND_ID)
|
|
const bannersDoc = await scaffoldCache('banners', { regionId: REGION_1 })
|
|
|
|
return {
|
|
regionCurrent,
|
|
regionEffective,
|
|
baseline,
|
|
store,
|
|
storeRead,
|
|
product,
|
|
productRead,
|
|
slot,
|
|
user,
|
|
address,
|
|
orderId,
|
|
orderList,
|
|
orderDetail,
|
|
suspended,
|
|
suspendedStore,
|
|
suspendedAdminRead,
|
|
productsDoc,
|
|
storesDoc,
|
|
detailStatus,
|
|
detailDoc,
|
|
availabilityDoc,
|
|
slotsDoc,
|
|
essentialConstsDoc,
|
|
bannersDoc,
|
|
}
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
shared = await buildShared()
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Setup + catalogue reads (E2E-01..11) */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
describe('golden catalogue reads (E2E-01..11)', () => {
|
|
it('E2E-01: staff login resolves the region and its effective bound', () => {
|
|
expect(Number(shared.regionCurrent.id)).toBe(TEST_REGION_ID)
|
|
expect(Number(shared.regionEffective.regionId)).toBe(TEST_REGION_ID)
|
|
expect(Number(shared.regionEffective.boundId)).toBe(TEST_BOUND_ID)
|
|
})
|
|
|
|
it('E2E-02: the baseline essentialConsts versions are numeric', () => {
|
|
expect(Number.isFinite(shared.baseline.products)).toBe(true)
|
|
expect(Number.isFinite(shared.baseline.slots)).toBe(true)
|
|
expect(Number.isFinite(shared.baseline.availability)).toBe(true)
|
|
expect(shared.baseline.products).toBeGreaterThanOrEqual(0)
|
|
})
|
|
|
|
it('E2E-03: a unique store is created and readable by id', () => {
|
|
expect(shared.store.storeId).toBeGreaterThan(0)
|
|
expect(shared.store.storeName).toContain('XYZ Store')
|
|
expect(Number(shared.storeRead.store.id)).toBe(shared.store.storeId)
|
|
expect(shared.storeRead.store.name).toBe(shared.store.storeName)
|
|
})
|
|
|
|
it('E2E-04: the product and its SKU round-trip price and the quantity feature', () => {
|
|
expect(shared.product.productId).toBeGreaterThan(0)
|
|
expect(shared.product.skuId).toBeGreaterThan(0)
|
|
const sku = shared.productRead.product.skus[0]
|
|
expect(Number(sku.price)).toBe(499)
|
|
expect(sku.features[0].featureName).toBe('quantity')
|
|
expect(sku.features[0].featureValue).toBe('1kg')
|
|
})
|
|
|
|
it('E2E-05: admin.product.getProducts contains the created product/SKU', async () => {
|
|
const admin = await staffClient()
|
|
const list: any = await admin.admin.product.getProducts.query()
|
|
const found = list.products.find((product: any) => Number(product.id) === shared.product.productId)
|
|
expect(found).toBeTruthy()
|
|
expect(found.skus.some((sku: any) => Number(sku.id) === shared.product.skuId)).toBe(true)
|
|
})
|
|
|
|
it('E2E-06: common.product.getAllProductsSummary contains the SKU, scoped to the staff region', async () => {
|
|
const admin = await staffClient()
|
|
const summary: any = await admin.common.product.getAllProductsSummary.query()
|
|
expect(skuIn(summary, shared.product.skuId)).toBeTruthy()
|
|
// Scoped to region 1: the region-2-only SKUs are absent.
|
|
const doc2: any = await scaffoldCache('products', { regionId: TEST_OTHER_REGION_ID })
|
|
expect(skuIn(doc2, shared.product.skuId)).toBeUndefined()
|
|
})
|
|
|
|
it('E2E-25: a suspended SKU is absent from the cache but still in the admin DB', async () => {
|
|
expect(Number(shared.suspendedAdminRead.product.id)).toBe(shared.suspended.productId)
|
|
expect(skuIn(shared.productsDoc, shared.suspended.skuId)).toBeUndefined()
|
|
|
|
const doc = await scaffoldCache('products', { regionId: REGION_1 })
|
|
expect(skuIn(doc, shared.suspended.skuId)).toBeUndefined()
|
|
expect(skuIn(doc, shared.product.skuId)).toBeTruthy()
|
|
})
|
|
})
|