/** * AREG-01..18 — `admin.region` (catalogue §7.7). * * The whole router is `staffProcedure` (region always comes from the staff * row), so user/superadmin tokens are 401 here — unlike the `protectedProcedure` * gap noted in §13. Region/bound constants are split by scope: region keys live * in `region_consts`, bound keys in `region_bound_consts`, and writing a key * through the wrong endpoint is a BAD_REQUEST. * * AREG-09/10 observe the cache-schedule side effect on a private fresh region * (`products_version_num`), so they cannot be polluted by other suites. */ import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api' import { staffClient, superadminClient, userClient } from '../helpers/sessions' import { PASSWORD, createRegion, getBoundSetting, setBoundSetting } from '../helpers/fixtures' import { TEST_BOUND_ID, TEST_OTHER_BOUND_ID, TEST_REGION_ID } from '../helpers/env' import { getEssentialConsts, pollUntil } from '../helpers/cache' jest.setTimeout(300_000) /* -------------------------------------------------------------------------- */ /* Helpers */ /* -------------------------------------------------------------------------- */ async function regionConstMap(admin: ApiClient): Promise> { const rows = (await admin.admin.region.getRegionConstants.query()) as Array<{ key: string value: string | null }> return Object.fromEntries(rows.map((row) => [row.key, row.value])) } async function productsVersion(admin: ApiClient): Promise { const constants = await regionConstMap(admin) return Number(constants.products_version_num ?? 0) } async function setConstants( admin: ApiClient, entries: Array<{ key: string; value: string | null }> ): Promise<{ success: boolean; updatedCount: number; deletedCount: number }> { return (await admin.admin.region.updateRegionConstants.mutate({ constants: entries })) as any } async function restoreConstants( admin: ApiClient, previous: Record ): Promise { const entries = Object.entries(previous).map(([key, value]) => ({ key, value })) if (entries.length > 0) await setConstants(admin, entries) } 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_areg_${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) } /** A private region + its own staff, so cache-version tests are isolated. */ let freshPromise: Promise<{ regionId: number; boundId: number; client: ApiClient }> | null = null function freshRegion(): Promise<{ regionId: number; boundId: number; client: ApiClient }> { freshPromise ??= (async () => { const region = await createRegion() const client = await createRegionStaff(region.regionId) return { regionId: region.regionId, boundId: Number(region.boundId), client } })() return freshPromise } /* -------------------------------------------------------------------------- */ /* Reads */ /* -------------------------------------------------------------------------- */ describe('admin.region reads (AREG-01..05)', () => { it('AREG-01: current resolves the authenticated staff region', async () => { const admin = await staffClient() const region: any = await admin.admin.region.current.query() expect(region).toEqual( expect.objectContaining({ id: TEST_REGION_ID, name: expect.any(String) }) ) }) it('AREG-02: bounds are the staff region’s, priority ascending', async () => { const admin = await staffClient() const bounds = (await admin.admin.region.bounds.query()) as any[] expect(bounds.length).toBeGreaterThan(0) expect(bounds.every((bound) => Number(bound.regionId) === TEST_REGION_ID)).toBe(true) expect(bounds.some((bound) => Number(bound.id) === TEST_BOUND_ID)).toBe(true) const priorities = bounds.map((bound) => Number(bound.priority)) const sorted = [...priorities].sort((a, b) => a - b) expect(priorities).toEqual(sorted) }) it('AREG-03: effective merges region + lowest-priority bound settings', async () => { const admin = await staffClient() const bounds = (await admin.admin.region.bounds.query()) as any[] const effectiveBound = bounds[0] const effective: any = await admin.admin.region.effective.query() expect(effective.regionId).toBe(TEST_REGION_ID) expect(effective.boundId).toBe(effectiveBound.id) expect(effective.priority).toBe(effectiveBound.priority) // Region-scoped + bound-scoped keys are flattened into one settings map. expect(effective.settings).toEqual( expect.objectContaining({ supportMobile: expect.any(String), welcomeMessage: expect.any(String), deliveryCharge: expect.any(String), }) ) }) it('AREG-04 (current): the API cannot leave a region without a bound, so 422 is unreachable', async () => { // `effective` throws 422 only when `getEffectiveRegionSettings` returns // null (region has zero bounds). No public endpoint can create that state: // regions are created with >= 1 bound and the last bound cannot be deleted. const superadmin = await superadminClient() const region = await createRegion() const boundCount = await superadmin.superadmin.regions.bounds.query({ regionId: region.regionId, }) expect((boundCount as any[]).length).toBe(1) await expectTrpcError( () => superadmin.superadmin.regions.deleteBound.mutate({ id: Number(region.boundId), }), 'CONFLICT', 'only bound' ) // The region is still usable: effective resolves rather than 422. const client = await createRegionStaff(region.regionId) const effective: any = await client.admin.region.effective.query() expect(effective.boundId).toBe(Number(region.boundId)) }) it('AREG-05: getRegionConstants returns key/value rows for the staff region', async () => { const admin = await staffClient() const rows = (await admin.admin.region.getRegionConstants.query()) as any[] expect(Array.isArray(rows)).toBe(true) expect(rows.length).toBeGreaterThan(0) for (const row of rows) { expect(row).toEqual( expect.objectContaining({ key: expect.any(String) }) ) expect(Object.prototype.hasOwnProperty.call(row, 'value')).toBe(true) } const map = Object.fromEntries(rows.map((row) => [row.key, row.value])) expect(map).toEqual( expect.objectContaining({ products_version_num: expect.anything(), slots_version_num: expect.anything(), supportMobile: expect.anything(), tagsOrder: expect.anything(), }) ) }) }) /* -------------------------------------------------------------------------- */ /* Region constants */ /* -------------------------------------------------------------------------- */ describe('admin.region.updateRegionConstants (AREG-06..10)', () => { it('AREG-06: update returns updated/deleted counts', async () => { const admin = await staffClient() const before = await regionConstMap(admin) // Snapshot the keys this test touches so a failure still restores them. const touched = { supportMobile: before.supportMobile ?? null, welcomeMessage: before.welcomeMessage ?? null, } try { const result = await setConstants(admin, [ { key: 'supportMobile', value: '9999000011' }, { key: 'welcomeMessage', value: null }, ]) expect(result.success).toBe(true) expect(result.updatedCount).toBe(1) expect(result.deletedCount).toBe(1) const after = await regionConstMap(admin) expect(after.supportMobile).toBe('9999000011') expect(after.welcomeMessage).toBeUndefined() } finally { await restoreConstants(admin, touched) } const restored = await regionConstMap(admin) expect(restored.supportMobile).toBe(touched.supportMobile) expect(restored.welcomeMessage).toBe(touched.welcomeMessage) }) it('AREG-07: a null value deletes the key', async () => { const admin = await staffClient() // NOTE: `getRegionConstant()` in helpers/fixtures assumes a map shape, but // this procedure returns key/value rows — read through regionConstMap here. const before = (await regionConstMap(admin)).supportEmail ?? null try { await setConstants(admin, [{ key: 'supportEmail', value: 'e2e-region@example.com' }]) expect((await regionConstMap(admin)).supportEmail).toBe('e2e-region@example.com') const deleted = await setConstants(admin, [{ key: 'supportEmail', value: null }]) expect(deleted.deletedCount).toBe(1) const map = await regionConstMap(admin) expect(map.supportEmail).toBeUndefined() expect(Object.prototype.hasOwnProperty.call(map, 'supportEmail')).toBe(false) } finally { await setConstants(admin, [{ key: 'supportEmail', value: before }]) } expect((await regionConstMap(admin)).supportEmail ?? null).toBe(before) }) it('AREG-08: a key from another scope is BAD_REQUEST', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.region.updateRegionConstants.mutate({ constants: [{ key: 'deliveryCharge', value: '55' }], }), 'BAD_REQUEST', 'bound constant' ) // The cache-pipeline version counters are also rejected for the region scope. await expectTrpcError( () => admin.admin.region.updateRegionConstants.mutate({ constants: [{ key: 'products_version_num', value: '7' }], }), 'BAD_REQUEST', 'version counter' ) }) it.skip('AREG-09: updating tagsOrder schedules a store-cache rebuild (DO scheduling; covered by tests/unit/cache-creator.test.ts)', () => {}) it('AREG-10: updating a non-cache key does not schedule a rebuild', async () => { const { client } = await freshRegion() const baseline = await productsVersion(client) const result = await setConstants(client, [{ key: 'supportMobile', value: '9090909090' }]) expect(result.updatedCount).toBe(1) // `tagsOrder` is the only cache-affecting region key; any other key only // refreshes the KV mirror synchronously and leaves the version counter put. expect(await productsVersion(client)).toBe(baseline) // The synchronous KV refresh is observable immediately. const consts = await getEssentialConsts(Number((await freshRegion()).boundId)) expect(consts.supportMobile).toBe('9090909090') }) }) /* -------------------------------------------------------------------------- */ /* Bound settings */ /* -------------------------------------------------------------------------- */ describe('admin.region bound settings (AREG-11..15)', () => { it('AREG-11: getBoundSettings returns the bound’s settings map', async () => { const admin = await staffClient() const settings: any = await admin.admin.region.getBoundSettings.query({ boundId: TEST_BOUND_ID }) expect(settings).toEqual( expect.objectContaining({ freeDeliveryThreshold: expect.any(String), deliveryCharge: expect.any(String), isFlashDeliveryEnabled: expect.anything(), }) ) expect(await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge')).toBe(settings.deliveryCharge) }) it('AREG-12: a bound from another region is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.region.getBoundSettings.query({ boundId: TEST_OTHER_BOUND_ID }), 'NOT_FOUND' ) }) it('AREG-13: updateBoundSettings returns updated/deleted counts', async () => { const admin = await staffClient() const before = await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge') try { const result: any = await admin.admin.region.updateBoundSettings.mutate({ boundId: TEST_BOUND_ID, settings: [{ key: 'deliveryCharge', value: '42' }], }) expect(result.success).toBe(true) expect(result.updatedCount).toBe(1) expect(result.deletedCount).toBe(0) expect(await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge')).toBe('42') } finally { await setBoundSetting(TEST_BOUND_ID, 'deliveryCharge', before) } expect(await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge')).toBe(before) }) it('AREG-14: a key from another scope is BAD_REQUEST', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.region.updateBoundSettings.mutate({ boundId: TEST_BOUND_ID, settings: [{ key: 'supportMobile', value: '123' }], }), 'BAD_REQUEST', 'region constant' ) }) it('AREG-15: a null value removes the bound setting (falls back to the default)', async () => { const admin = await staffClient() const before = await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge') try { await setBoundSetting(TEST_BOUND_ID, 'deliveryCharge', '88') expect(await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge')).toBe('88') const result: any = await admin.admin.region.updateBoundSettings.mutate({ boundId: TEST_BOUND_ID, settings: [{ key: 'deliveryCharge', value: null }], }) expect(result.deletedCount).toBe(1) const settings: any = await admin.admin.region.getBoundSettings.query({ boundId: TEST_BOUND_ID }) expect(settings.deliveryCharge).toBeUndefined() // essentialConsts substitutes the built-in default (0) for a missing row. const consts = await getEssentialConsts(TEST_BOUND_ID) expect(Number(consts.deliveryCharge)).toBe(0) } finally { await setBoundSetting(TEST_BOUND_ID, 'deliveryCharge', before) } expect(await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge')).toBe(before) }) }) /* -------------------------------------------------------------------------- */ /* Auth + cache */ /* -------------------------------------------------------------------------- */ describe('admin.region auth + cache (AREG-16..18)', () => { it('AREG-16: a user token is 401 (staff-only router)', async () => { const user = await userClient() await expectTrpcError(() => user.admin.region.current.query(), 'UNAUTHORIZED') await expectTrpcError( () => user.admin.region.getBoundSettings.query({ boundId: TEST_BOUND_ID }), 'UNAUTHORIZED' ) }) it('AREG-17: a superadmin token is 401 (staff-only router)', async () => { const superadmin = await superadminClient() await expectTrpcError(() => superadmin.admin.region.current.query(), 'UNAUTHORIZED') await expectTrpcError( () => superadmin.admin.region.getRegionConstants.query(), 'UNAUTHORIZED' ) }) it('AREG-18: a bound setting change is reflected in essentialConsts after the refresh', async () => { const admin = await staffClient() const before = await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge') const nextValue = String(500 + Math.floor(Math.random() * 400)) try { await admin.admin.region.updateBoundSettings.mutate({ boundId: TEST_BOUND_ID, settings: [{ key: 'deliveryCharge', value: nextValue }], }) // updateBoundSettings awaits refreshGenKvForRegion, so the KV mirror the // public read serves from is already up to date. const consts = await getEssentialConsts(TEST_BOUND_ID) expect(Number(consts.deliveryCharge)).toBe(Number(nextValue)) } finally { await setBoundSetting(TEST_BOUND_ID, 'deliveryCharge', before) } expect(await getBoundSetting(TEST_BOUND_ID, 'deliveryCharge')).toBe(before) }) })