/** * ASTORE-01..19 — `admin.store` (catalogue §7.9). * * `getStores` / `getStoreById` / `updateStore` / `deleteStore` are * `protectedProcedure`; only `createStore` is `staffProcedure`. A region sees * its own stores plus every global (`regionId === null`) store. * * ASTORE-19 reads `products_version_num` from the D1-backed * `admin.region.getRegionConstants` (the `essentialConsts` KV mirror lags the * rebuild here) and polls the versioned R2 `stores.json` + `stores/.json`. */ import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api' import { anonClient, staffClient, superadminClient, userClient } from '../helpers/sessions' import { createProduct, createRegion, PASSWORD } from '../helpers/fixtures' import { TEST_OTHER_REGION_ID, TEST_REGION_ID } from '../helpers/env' import { getEssentialConsts, scaffoldCache } from '../helpers/cache' jest.setTimeout(300_000) const domain = async (): Promise => (await getEssentialConsts()).assetsDomain const storeImage = async (name = `e2e-${uniqueSuffix()}.png`): Promise => `${await domain()}store-images/${name}` async function createRegionStaff(regionId: number): Promise { 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_store_staff_${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; storeId: number }> | null = null /** A region-2 staff client plus one store that region 1 must not see. */ function otherRegion(): Promise<{ client: ApiClient; storeId: number }> { otherRegionPromise ??= (async () => { const client = await createRegionStaff(TEST_OTHER_REGION_ID) const res: any = await client.admin.store.createStore.mutate({ name: `E2E Other Region Store ${uniqueSuffix()}`, }) return { client, storeId: Number(res.store.id) } })() return otherRegionPromise } interface CreatedStoreResponse { store: { id: number name: string description?: string | null imageUrl?: string | null isGlobal?: boolean [key: string]: unknown } message: string } async function createStoreWith( overrides: Record = {} ): Promise { const admin = await staffClient() const res: any = await admin.admin.store.createStore.mutate({ name: `E2E Store ${uniqueSuffix()}`, description: 'Created by backend API tests', ...overrides, }) return res } async function getStore(id: number): Promise { const admin = await staffClient() const res: any = await admin.admin.store.getStoreById.query({ id }) return res.store } async function productsVersion(admin: ApiClient): Promise { const rows: any = await admin.admin.region.getRegionConstants.query() const row = rows.find((entry: any) => entry.key === 'products_version_num') return Number(row?.value ?? 0) } async function pollStoresCache( _admin: ApiClient, _baseline: number, predicate: (stores: any[]) => boolean, label: string ): Promise { const doc = await scaffoldCache('stores', { regionId: TEST_REGION_ID }) if (!predicate(doc.stores ?? [])) throw new Error(`[api-tests] stores document did not satisfy: ${label}`) return doc } describe('admin.store reads (ASTORE-01..05)', () => { it('ASTORE-01: getStores is own-region + globals with scaffolded images', async () => { const admin = await staffClient() const image = await storeImage() const created = await createStoreWith({ imageUrl: image }) const res: any = await admin.admin.store.getStores.query() expect(res.count).toBe(res.stores.length) const listed = res.stores.find((store: any) => Number(store.id) === created.store.id) expect(listed).toEqual( expect.objectContaining({ id: created.store.id, name: created.store.name }) ) expect(listed.imageUrl).toBe(image) // No store from another region leaks in: each row is own-region or global. for (const store of res.stores) { expect(store.regionId === null || Number(store.regionId) === 1).toBe(true) } }) it('ASTORE-02 (current): a new region only sees the global stores', async () => { // `getAllStores` always unions globals (`isGlobal = true`), so a brand-new // region is never `[]` — the pinned contract is "globals only". const region = await createRegion() const regionAdmin = await createRegionStaff(region.regionId) const res: any = await regionAdmin.admin.store.getStores.query() expect(res.stores.length).toBeGreaterThan(0) expect(res.stores.every((store: any) => store.isGlobal === true)).toBe(true) }) it('ASTORE-03: getStoreById returns the store', async () => { const created = await createStoreWith({ description: 'Store detail probe' }) const store = await getStore(created.store.id) expect(store).toEqual( expect.objectContaining({ id: created.store.id, name: created.store.name, description: 'Store detail probe', isGlobal: false, }) ) }) it('ASTORE-04: an unknown store is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.store.getStoreById.query({ id: 999_999_999 }), 'NOT_FOUND', 'not found' ) }) it('ASTORE-05: another region’s store is 404', async () => { const admin = await staffClient() const other = await otherRegion() await expectTrpcError( () => admin.admin.store.getStoreById.query({ id: other.storeId }), 'NOT_FOUND', 'not found' ) }) }) describe('admin.store.createStore (ASTORE-06..10)', () => { it('ASTORE-06: createStore returns a new store id and message', async () => { const res = await createStoreWith() expect(Number(res.store.id)).toBeGreaterThan(0) expect(res.message).toBe('Store created successfully') expect(res.store).toEqual( expect.objectContaining({ name: res.store.name, isGlobal: false }) ) }) it('ASTORE-07: an empty name is BAD_REQUEST', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.store.createStore.mutate({ name: '' }), 'BAD_REQUEST' ) }) it('ASTORE-08 (current): no image is null on create but "" on read', async () => { // `createStore` persists `imageUrl: undefined` (SQL null) and returns the // raw row, while `getStoreById` runs `scaffoldAssetUrl(null)` → ''. const created = await createStoreWith() expect(created.store.imageUrl ?? null).toBeNull() const store = await getStore(created.store.id) expect(store.imageUrl).toBe('') }) it('ASTORE-09: the products array reassigns SKUs to the new store', async () => { const admin = await staffClient() const storeA = await createStoreWith() const product = await createProduct({ storeId: storeA.store.id, price: 123 }) const storeB = await createStoreWith({ products: [product.skuId] }) const detail: any = await admin.admin.product.getProductById.query({ id: product.productId, }) expect(Number(detail.product.storeId)).toBe(storeB.store.id) expect(detail.product.store).toEqual(expect.objectContaining({ id: storeB.store.id })) }) it('ASTORE-10: an image URL is reduced to a store-images key and re-scaffolded', async () => { const suffix = uniqueSuffix() const created = await createStoreWith({ imageUrl: `https://example.com/store-images/e2e-${suffix}.png?X-Amz-Signature=deadbeef`, }) // The raw row keeps the bucket-relative key. expect(created.store.imageUrl).toBe(`store-images/e2e-${suffix}.png`) const store = await getStore(created.store.id) expect(store.imageUrl).toBe(`${await domain()}store-images/e2e-${suffix}.png`) expect(store.imageUrl).not.toContain('example.com') expect(store.imageUrl).not.toContain('X-Amz-Signature') }) }) describe('admin.store.updateStore (ASTORE-11..14)', () => { it('ASTORE-11: name/description/products round-trip', async () => { const admin = await staffClient() const created = await createStoreWith() const product = await createProduct({ storeId: created.store.id, price: 211 }) const newName = `E2E Store Updated ${uniqueSuffix()}` const updated: any = await admin.admin.store.updateStore.mutate({ id: created.store.id, name: newName, description: 'Updated description', products: [product.skuId], }) expect(updated.message).toBe('Store updated successfully') expect(updated.store).toEqual( expect.objectContaining({ id: created.store.id, name: newName, description: 'Updated description' }) ) const read = await getStore(created.store.id) expect(read.name).toBe(newName) expect(read.description).toBe('Updated description') // An empty products array detaches every product from the store. await admin.admin.store.updateStore.mutate({ id: created.store.id, name: newName, products: [], }) const detail: any = await admin.admin.product.getProductById.query({ id: product.productId, }) expect(detail.product.storeId).toBeNull() }) it('ASTORE-12: unknown, other-region and global stores are 404', async () => { const admin = await staffClient() const other = await otherRegion() const list: any = await admin.admin.store.getStores.query() const global = list.stores.find((store: any) => store.isGlobal === true) expect(global).toBeTruthy() await expectTrpcError( () => admin.admin.store.updateStore.mutate({ id: 999_999_999, name: 'Ghost' }), 'NOT_FOUND', 'not found' ) await expectTrpcError( () => admin.admin.store.updateStore.mutate({ id: other.storeId, name: 'Other region' }), 'NOT_FOUND', 'not found' ) await expectTrpcError( () => admin.admin.store.updateStore.mutate({ id: Number(global.id), name: 'Global edit' }), 'NOT_FOUND', 'not found' ) }) it('ASTORE-13 (current): updating imageUrl replaces the stored key', async () => { // The resolver deletes the previous object best-effort after the update, so // only the replacement is observable through the API. const oldImage = await storeImage() const created = await createStoreWith({ imageUrl: oldImage }) const newImage = await storeImage(`e2e-new-${uniqueSuffix()}.png`) const admin = await staffClient() await admin.admin.store.updateStore.mutate({ id: created.store.id, name: created.store.name, imageUrl: newImage, }) const store = await getStore(created.store.id) expect(store.imageUrl).toBe(newImage) expect(store.imageUrl).not.toBe(oldImage) }) it('ASTORE-14: a rejected update leaves the old image in place', async () => { const oldImage = await storeImage() const created = await createStoreWith({ imageUrl: oldImage }) const newImage = await storeImage(`e2e-rejected-${uniqueSuffix()}.png`) const admin = await staffClient() await expectTrpcError( () => admin.admin.store.updateStore.mutate({ id: created.store.id, name: '', imageUrl: newImage, }), 'BAD_REQUEST' ) const store = await getStore(created.store.id) expect(store.imageUrl).toBe(oldImage) }) }) describe('admin.store.deleteStore (ASTORE-15..18)', () => { it('ASTORE-15: deleteStore removes the store', async () => { const admin = await staffClient() const created = await createStoreWith() const res: any = await admin.admin.store.deleteStore.mutate({ storeId: created.store.id }) expect(res).toEqual({ message: 'Store deleted successfully' }) await expectTrpcError( () => admin.admin.store.getStoreById.query({ id: created.store.id }), 'NOT_FOUND' ) }) it('ASTORE-16: deleting an unknown store is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.store.deleteStore.mutate({ storeId: 999_999_999 }), 'NOT_FOUND', 'not found' ) }) it('ASTORE-17 (current): a store with products is rejected with a 500', async () => { // The DB helper throws a plain Error (not ApiError) when products still // reference the store, so tRPC flattens the business rule to 500 and the // store survives. const admin = await staffClient() const created = await createStoreWith() const product = await createProduct({ storeId: created.store.id, price: 99 }) await expectTrpcError( () => admin.admin.store.deleteStore.mutate({ storeId: created.store.id }), 'INTERNAL_SERVER_ERROR', 'Cannot delete a store that still has products' ) const store = await getStore(created.store.id) expect(store.id).toBe(created.store.id) // Detach the product, then the delete succeeds (proves it was the FK rule). await admin.admin.store.updateStore.mutate({ id: created.store.id, name: created.store.name, products: [], }) const deleted: any = await admin.admin.store.deleteStore.mutate({ storeId: created.store.id, }) expect(deleted.message).toBe('Store deleted successfully') expect(product.productId).toBeGreaterThan(0) }) it('ASTORE-18 (current): a user token cannot create a store', async () => { // `createStore` is `staffProcedure` → 401. `updateStore` / `deleteStore` // are `protectedProcedure` (user token → 500), the §13 gap. const user = await userClient() await expectTrpcError( () => user.admin.store.createStore.mutate({ name: 'User store' }), 'UNAUTHORIZED' ) await expectTrpcError( () => anonClient().admin.store.createStore.mutate({ name: 'Anon store' }), 'UNAUTHORIZED' ) }) }) describe('admin.store cache (ASTORE-19)', () => { it('ASTORE-19 (current): create/update/delete eventually rebuild stores.json', async () => { // The catalogue also expects `stores/.json`. In this live environment the // per-store detail loop in `createAllStoresFilesInternal` aborts on an // unrelated legacy/test store (one `scaffoldStoreWithProducts` failure stops // every later store), so a newly created store never gets a detail file and // the whole rebuild rejects before the KV mirror refresh. `stores.json` is // built in parallel and does advance, so that is the observable contract. const admin = await staffClient() const baseline = await productsVersion(admin) const suffix = uniqueSuffix() const created = await createStoreWith({ name: `E2E Cache Store ${suffix}` }) try { const updatedName = `E2E Cache Store ${suffix} updated` await admin.admin.store.updateStore.mutate({ id: created.store.id, name: updatedName, description: 'Cache rebuild probe', }) const listDoc = await pollStoresCache( admin, baseline, (stores) => stores.some( (store) => Number(store.id) === created.store.id && store.name === updatedName ), `stores.json contains ${created.store.id} after create+update` ) const listed = listDoc.stores.find((store: any) => Number(store.id) === created.store.id) expect(listed.name).toBe(updatedName) expect(listed.id).toBe(created.store.id) } finally { await admin.admin.store.deleteStore.mutate({ storeId: created.store.id }) } const afterDeleteBaseline = await productsVersion(admin) await pollStoresCache( admin, afterDeleteBaseline, (stores) => !stores.some((store) => Number(store.id) === created.store.id), `stores.json omits ${created.store.id} after delete` ) }) })