/** * ASLOT-01..24 — `admin.slots` (catalogue §7.8). * * `getAll` is hard-capped at 20 active slots ordered by delivery time desc. * `createSlot`/`updateSlot`/`updateSlotCapacity` regenerate the slots cache * file synchronously, so `slots_version_num` moves inside the mutation (unlike * the products/stores rebuild). `updateSlot` wraps its whole body in a * try/catch and reports every failure as 500 `Unable to Update Slot` (§13 #4). */ import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api' import { staffClient, userClient } from '../helpers/sessions' import { PASSWORD, createProduct, type CreatedProduct, } from '../helpers/fixtures' import { TEST_OTHER_REGION_ID } from '../helpers/env' import { fetchCacheJson, getEssentialConsts, pollUntil, slotsCacheUrl, } from '../helpers/cache' jest.setTimeout(300_000) /* -------------------------------------------------------------------------- */ /* Helpers */ /* -------------------------------------------------------------------------- */ const hoursFromNow = (hours: number): string => new Date(Date.now() + hours * 3_600_000).toISOString() async function slotsVersion(admin: ApiClient): Promise { const rows = (await admin.admin.region.getRegionConstants.query()) as Array<{ key: string value: string | null }> return Number(rows.find((row) => row.key === 'slots_version_num')?.value ?? 0) } interface SlotInput { deliveryTime?: string freezeTime?: string isActive?: boolean skuIds?: number[] vendorSnippets?: Array<{ name: string; skuIds: number[]; validTill?: string }> groupIds?: number[] } async function createSlotAt(admin: ApiClient, input: SlotInput = {}): Promise { return admin.admin.slots.createSlot.mutate({ deliveryTime: input.deliveryTime ?? hoursFromNow(3), freezeTime: input.freezeTime ?? hoursFromNow(2), ...(input.isActive !== undefined ? { isActive: input.isActive } : {}), ...(input.skuIds !== undefined ? { skuIds: input.skuIds } : {}), ...(input.vendorSnippets !== undefined ? { vendorSnippets: input.vendorSnippets } : {}), ...(input.groupIds !== undefined ? { groupIds: input.groupIds } : {}), } as any) } /** A far-future, active slot always lands in the top-20 getAll window. */ const FAR_FUTURE = '2030-06-01T10:00:00.000Z' const FAR_FUTURE_FREEZE = '2030-06-01T08:00:00.000Z' let catalogPromise: Promise | null = null function catalogProduct(): Promise { catalogPromise ??= createProduct({ price: 149 }) return catalogPromise } async function createRegionStaff(regionId: number): Promise { const { superadminClient } = await import('../helpers/sessions') const superadmin = await superadminClient() const roles: any = await superadmin.superadmin.staff.roles.query() const roleId = Number(roles.roles.find((r: any) => r.name === 'admin')?.id ?? roles.roles[0].id) const name = `e2e_aslot_${uniqueSuffix()}` await superadmin.superadmin.staff.create.mutate({ name, password: PASSWORD, roleId, regionId }) const login: any = await apiClient().admin.staffUser.login.mutate({ name, password: PASSWORD }) return apiClient(login.token) } let otherRegionPromise: Promise<{ client: ApiClient; slotId: number }> | null = null /** A region-2 staff client plus one slot region 1 must never see. */ function otherRegion(): Promise<{ client: ApiClient; slotId: number }> { otherRegionPromise ??= (async () => { const client = await createRegionStaff(TEST_OTHER_REGION_ID) const res: any = await createSlotAt(client, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE }) return { client, slotId: Number(res.slot.id) } })() return otherRegionPromise } /** Poll the public slots.json (re-reading the version each attempt). */ async function pollSlotsCache(predicate: (slots: any[]) => boolean, label: string): Promise { return pollUntil(label, async () => { const consts = await getEssentialConsts() try { const doc: any = await fetchCacheJson(slotsCacheUrl(consts)) return predicate(doc.slots ?? []) ? doc : null } catch { return null } }) } /* -------------------------------------------------------------------------- */ /* getAll */ /* -------------------------------------------------------------------------- */ describe('admin.slots.getAll (ASLOT-01..02)', () => { it('ASLOT-01: getAll returns ≤20 active slots of the staff region only', async () => { const admin = await staffClient() const product = await catalogProduct() // A strictly-later-than-everything delivery time guarantees this slot is the // top row even though `getAll` only tie-breaks nothing (deliveryTime desc). const topDelivery = new Date(Date.now() + 250 * 365.25 * 24 * 3_600_000).toISOString() const topFreeze = new Date(Date.now() + (250 * 365.25 - 1) * 24 * 3_600_000).toISOString() const created: any = await createSlotAt(admin, { deliveryTime: topDelivery, freezeTime: topFreeze, skuIds: [product.skuId], }) const res: any = await admin.admin.slots.getAll.query() expect(res.count).toBe(res.slots.length) expect(res.count).toBeLessThanOrEqual(20) expect(res.slots.every((slot: any) => slot.isActive === true)).toBe(true) expect(res.slots.some((slot: any) => Number(slot.id) === created.slot.id)).toBe(true) // A slot created in region 2 is invisible here. const other = await otherRegion() expect(res.slots.some((slot: any) => Number(slot.id) === other.slotId)).toBe(false) }) it('ASLOT-02: more than 20 active slots are capped at 20', async () => { const admin = await staffClient() // Region 1 already holds far more than 20 active slots in this DB; the // resolver hard-codes `limit 20`, so the page is always exactly full. const res: any = await admin.admin.slots.getAll.query() expect(res.count).toBe(20) expect(res.slots.length).toBe(20) }) }) /* -------------------------------------------------------------------------- */ /* createSlot */ /* -------------------------------------------------------------------------- */ describe('admin.slots.createSlot (ASLOT-03..09)', () => { it('ASLOT-03: createSlot returns the slot, its products and vendor snippets', async () => { const admin = await staffClient() const product = await catalogProduct() const snippetName = `E2E SNIP ${uniqueSuffix()}` const deliveryTime = hoursFromNow(5) const freezeTime = hoursFromNow(4) const res: any = await createSlotAt(admin, { deliveryTime, freezeTime, skuIds: [product.skuId], vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }], groupIds: [], }) expect(res.message).toBe('Slot created successfully') expect(res.slot).toEqual( expect.objectContaining({ id: expect.any(Number), isActive: true, groupIds: [] }) ) expect(res.slot.deliveryTime).toBe(deliveryTime) expect(res.slot.freezeTime).toBe(freezeTime) expect(res.createdSnippets).toHaveLength(1) expect(res.createdSnippets[0]).toEqual( expect.objectContaining({ snippetCode: snippetName, slotId: res.slot.id, skuIds: [product.skuId], }) ) const detail: any = await admin.admin.slots.getSlotById.query({ id: res.slot.id }) expect(detail.slot.products.map((p: any) => Number(p.id))).toContain(product.skuId) expect(detail.slot.vendorSnippets.map((s: any) => s.snippetCode)).toContain(snippetName) }) it('ASLOT-04: missing/empty delivery times are 400', async () => { const admin = await staffClient() await expectTrpcError( () => createSlotAt(admin, { deliveryTime: '', freezeTime: '' }), 'BAD_REQUEST', 'required' ) await expectTrpcError( () => admin.admin.slots.createSlot.mutate({ deliveryTime: hoursFromNow(3) } as any), 'BAD_REQUEST' ) }) it('ASLOT-05 (current): invalid date strings surface as a 500 “Invalid time value”', async () => { // The strings pass zod (plain `z.string()`); `new Date('nope')` fails later // inside the drizzle date column mapper, so the client sees a raw 500. const admin = await staffClient() await expectTrpcError( () => createSlotAt(admin, { deliveryTime: 'not-a-date', freezeTime: 'also-bad' }), 'INTERNAL_SERVER_ERROR', 'Invalid time value' ) }) it('ASLOT-06: a slot with no SKUs is created empty', async () => { const admin = await staffClient() const res: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, }) expect(res.createdSnippets).toEqual([]) const detail: any = await admin.admin.slots.getSlotById.query({ id: res.slot.id }) expect(detail.slot.products).toEqual([]) }) it('ASLOT-07: an unknown SKU id is a 500 validation error', async () => { const admin = await staffClient() await expectTrpcError( () => createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, skuIds: [999_999_999], }), 'INTERNAL_SERVER_ERROR', 'Invalid SKU' ) }) it('ASLOT-08: a vendor snippet created with the slot carries an access URL', async () => { const admin = await staffClient() const product = await catalogProduct() const snippetName = `E2E SNIP ${uniqueSuffix()}` const res: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, skuIds: [product.skuId], vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }], }) const detail: any = await admin.admin.slots.getSlotById.query({ id: res.slot.id }) const snippet = detail.slot.vendorSnippets.find((s: any) => s.snippetCode === snippetName) expect(snippet).toBeTruthy() expect(snippet.accessUrl).toContain('/vendor-order-list?id=') expect(snippet.accessUrl).toContain(snippetName) }) it('ASLOT-09 (current): a duplicate vendor snippet code fails the create with a 500', async () => { // Snippet codes are globally unique (checked with no region filter), and the // failure is a raw Error inside the transaction, so it flattens to 500. const admin = await staffClient() const product = await catalogProduct() const snippetName = `E2E DUP ${uniqueSuffix()}` await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, skuIds: [product.skuId], vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }], }) await expectTrpcError( () => createSlotAt(admin, { deliveryTime: hoursFromNow(6), freezeTime: hoursFromNow(5), skuIds: [product.skuId], vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }], }), 'INTERNAL_SERVER_ERROR', 'already exists' ) }) }) /* -------------------------------------------------------------------------- */ /* getSlotById */ /* -------------------------------------------------------------------------- */ describe('admin.slots.getSlotById (ASLOT-11..12)', () => { it('ASLOT-11: getSlotById returns slot, products and snippet access URLs', async () => { const admin = await staffClient() const product = await catalogProduct() const snippetName = `E2E GET ${uniqueSuffix()}` const created: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, skuIds: [product.skuId], vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }], }) const res: any = await admin.admin.slots.getSlotById.query({ id: created.slot.id }) expect(res.slot.id).toBe(created.slot.id) expect(res.slot.isActive).toBe(true) expect(Array.isArray(res.slot.deliverySequence)).toBe(true) expect(Array.isArray(res.slot.products)).toBe(true) expect(Array.isArray(res.slot.vendorSnippets)).toBe(true) const productSummary = res.slot.products.find((p: any) => Number(p.id) === product.skuId) expect(productSummary).toBeTruthy() expect(typeof productSummary.name).toBe('string') expect(typeof productSummary.skuName).toBe('string') expect(Array.isArray(productSummary.features)).toBe(true) expect(res.slot.vendorSnippets[0].accessUrl).toContain('vendor-order-list?id=') }) it('ASLOT-12: an unknown slot id is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.slots.getSlotById.query({ id: 999_999_999 }), 'NOT_FOUND', 'Slot not found' ) }) }) /* -------------------------------------------------------------------------- */ /* updateSlot */ /* -------------------------------------------------------------------------- */ describe('admin.slots.updateSlot (ASLOT-13..14)', () => { it('ASLOT-13: updateSlot changes times, products and adds snippets', async () => { const admin = await staffClient() const product = await catalogProduct() const created: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, skuIds: [product.skuId], }) const newDelivery = hoursFromNow(9) const newFreeze = hoursFromNow(8) const snippetName = `E2E UPD ${uniqueSuffix()}` const res: any = await admin.admin.slots.updateSlot.mutate({ id: created.slot.id, deliveryTime: newDelivery, freezeTime: newFreeze, skuIds: [product.skuId], vendorSnippets: [{ name: snippetName, skuIds: [product.skuId] }], isActive: true, }) expect(res.message).toBe('Slot updated successfully') expect(res.slot.deliveryTime).toBe(newDelivery) expect(res.slot.freezeTime).toBe(newFreeze) expect(res.createdSnippets.map((s: any) => s.snippetCode)).toContain(snippetName) const detail: any = await admin.admin.slots.getSlotById.query({ id: created.slot.id }) expect(detail.slot.vendorSnippets.map((s: any) => s.snippetCode)).toContain(snippetName) }) it('ASLOT-14 (current): an unknown slot is masked as 500 “Unable to Update Slot”', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.slots.updateSlot.mutate({ id: 999_999_999, deliveryTime: hoursFromNow(3), freezeTime: hoursFromNow(2), }), 'INTERNAL_SERVER_ERROR', 'Unable to Update Slot' ) }) }) /* -------------------------------------------------------------------------- */ /* delivery sequence */ /* -------------------------------------------------------------------------- */ describe('admin.slots delivery sequence (ASLOT-16..19)', () => { it('ASLOT-16: getDeliverySequence returns the slot’s sequence map', async () => { const admin = await staffClient() const created: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, }) const sequence = { 7: [1, 2, 3] } await admin.admin.slots.updateDeliverySequence.mutate({ id: created.slot.id, deliverySequence: sequence, }) const res: any = await admin.admin.slots.getDeliverySequence.query({ id: String(created.slot.id), }) // The stored JSON round-trips (numeric keys become strings). expect(res.deliverySequence).toEqual({ 7: [1, 2, 3] }) }) it('ASLOT-17: an unknown slot id is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.slots.getDeliverySequence.query({ id: '999999999' }), 'NOT_FOUND', 'Slot not found' ) }) it('ASLOT-18: updateDeliverySequence persists the sequence', async () => { const admin = await staffClient() const created: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, }) const res: any = await admin.admin.slots.updateDeliverySequence.mutate({ id: created.slot.id, deliverySequence: { 4: [9, 8] }, }) expect(res.message).toBe('Delivery sequence updated successfully') expect(res.slot.deliverySequence).toEqual({ 4: [9, 8] }) }) it('ASLOT-19: updating the sequence of an unknown slot is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.slots.updateDeliverySequence.mutate({ id: 999_999_999, deliverySequence: {}, }), 'NOT_FOUND', 'Slot not found' ) }) }) /* -------------------------------------------------------------------------- */ /* capacity */ /* -------------------------------------------------------------------------- */ describe('admin.slots.updateSlotCapacity (ASLOT-20..22)', () => { it('ASLOT-20: updateSlotCapacity flips the flag', async () => { const admin = await staffClient() const created: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, }) const full: any = await admin.admin.slots.updateSlotCapacity.mutate({ slotId: created.slot.id, isCapacityFull: true, }) expect(full.success).toBe(true) expect(full.slot.isCapacityFull).toBe(true) expect(full.message).toMatch(/full capacity/i) const reset: any = await admin.admin.slots.updateSlotCapacity.mutate({ slotId: created.slot.id, isCapacityFull: false, }) expect(reset.slot.isCapacityFull).toBe(false) }) it('ASLOT-21: an unknown slot id is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.slots.updateSlotCapacity.mutate({ slotId: 999_999_999, isCapacityFull: true, }), 'NOT_FOUND', 'Slot not found' ) }) it('ASLOT-22: capacity is cache-aware — the slot leaves and returns to slots.json', async () => { const admin = await staffClient() const product = await catalogProduct() const created: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, skuIds: [product.skuId], }) const slotId = Number(created.slot.id) await pollSlotsCache( (slots) => slots.some((slot) => Number(slot.id) === slotId), `slots.json contains ${slotId} after create` ) const baseline = await slotsVersion(admin) await admin.admin.slots.updateSlotCapacity.mutate({ slotId, isCapacityFull: true }) expect(await slotsVersion(admin)).toBeGreaterThan(baseline) await pollSlotsCache( (slots) => !slots.some((slot) => Number(slot.id) === slotId), `slots.json omits capacity-full ${slotId}` ) const fullBaseline = await slotsVersion(admin) await admin.admin.slots.updateSlotCapacity.mutate({ slotId, isCapacityFull: false }) expect(await slotsVersion(admin)).toBeGreaterThan(fullBaseline) await pollSlotsCache( (slots) => slots.some((slot) => Number(slot.id) === slotId), `slots.json re-includes ${slotId} after reset` ) }) }) /* -------------------------------------------------------------------------- */ /* cache version (synchronous) */ /* -------------------------------------------------------------------------- */ describe('admin.slots cache versions (ASLOT-10/15)', () => { it('ASLOT-10: createSlot bumps slots_version_num synchronously', async () => { const admin = await staffClient() const before = await slotsVersion(admin) await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE }) expect(await slotsVersion(admin)).toBeGreaterThan(before) }) it('ASLOT-15: updateSlot bumps slots_version_num synchronously', async () => { const admin = await staffClient() const created: any = await createSlotAt(admin, { deliveryTime: FAR_FUTURE, freezeTime: FAR_FUTURE_FREEZE, }) const before = await slotsVersion(admin) await admin.admin.slots.updateSlot.mutate({ id: created.slot.id, deliveryTime: hoursFromNow(7), freezeTime: hoursFromNow(6), }) expect(await slotsVersion(admin)).toBeGreaterThan(before) }) }) /* -------------------------------------------------------------------------- */ /* auth + isolation */ /* -------------------------------------------------------------------------- */ describe('admin.slots auth + isolation (ASLOT-23..24)', () => { it('ASLOT-23 (current): a user token is 401, not the protectedProcedure 500 gap', async () => { // The router uses `protectedProcedure`, but every resolver re-checks // `ctx.staffUser` and throws UNAUTHORIZED, so the §13 "user token can call // admin protected procedures" gap does not reproduce here. const user = await userClient() await expectTrpcError(() => user.admin.slots.getAll.query(), 'UNAUTHORIZED') await expectTrpcError( () => user.admin.slots.createSlot.mutate({ deliveryTime: hoursFromNow(3), freezeTime: hoursFromNow(2) }), 'UNAUTHORIZED' ) }) it('ASLOT-24: another region’s slot is not found', async () => { const admin = await staffClient() const other = await otherRegion() await expectTrpcError( () => admin.admin.slots.getSlotById.query({ id: other.slotId }), 'NOT_FOUND' ) await expectTrpcError( () => admin.admin.slots.updateSlotCapacity.mutate({ slotId: other.slotId, isCapacityFull: true }), 'NOT_FOUND' ) await expectTrpcError( () => admin.admin.slots.getDeliverySequence.query({ id: String(other.slotId) }), 'NOT_FOUND' ) }) })