freshyo/apps/backend/tests/api/superadmin-regions.test.ts
2026-10-24 16:05:06 +05:30

790 lines
29 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* SREG-01..37 — `superadmin.regions` (catalogue §8.3).
*
* Region/bound CRUD is exercised on throwaway regions only; the seeded regions
* 1/2/3 and their bounds are never mutated or deleted. `create` awaits cache
* generation (`createRegionCacheFiles`), so a fresh region's versioned files are
* fetchable immediately (SREG-04/36).
*
* Region-scoped keys live in `region_consts` and bound-scoped keys in
* `region_bound_consts`; writing a key through the wrong endpoint is a
* BAD_REQUEST (SREG-28/32). A null value deletes the row (SREG-29) and
* `updateBoundSettings`/`updateRegionConstants` await the KV mirror refresh, so
* `common.essentialConsts` reflects the change synchronously (SREG-27/31).
*/
import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { anonClient, staffSession, superadminClient, userSession } from '../helpers/sessions'
import {
createAddress,
createRegion,
registerThrowawayUser,
squareGeojson,
} from '../helpers/fixtures'
import {
essentialConstsCacheUrl,
getEssentialConsts,
pollCacheJson,
pollUntil,
productsCacheUrl,
} from '../helpers/cache'
import { TEST_BOUND_ID, TEST_REGION_ID } from '../helpers/env'
jest.setTimeout(300_000)
/* -------------------------------------------------------------------------- */
/* Helpers */
/* -------------------------------------------------------------------------- */
interface BoundSpec {
description?: string
lat: number
lng: number
priority: string
geojson?: unknown
}
/** Create a region through the API with an arbitrary bound set. */
async function createRegionRaw(opts: {
name?: string
description?: string
center?: { lat: number; lng: number }
bounds: BoundSpec[]
}): Promise<{ regionId: number; boundIds: number[]; name: string; bounds: any[] }> {
const superadmin = await superadminClient()
const name = opts.name ?? `E2E Region ${uniqueSuffix()}`
const res = (await superadmin.superadmin.regions.create.mutate({
name,
description: opts.description ?? 'Created by backend API tests',
...(opts.center ? { center: opts.center } : {}),
bounds: opts.bounds.map((bound) => ({
description: bound.description ?? 'E2E bound',
geojson: bound.geojson ?? squareGeojson(bound.lat, bound.lng),
priority: bound.priority,
})),
} as any)) as any
const regionId = Number(res?.id)
if (!regionId) throw new Error(`[api-tests] regions.create returned no id: ${JSON.stringify(res)}`)
return {
regionId,
boundIds: (res.bounds ?? []).map((bound: any) => Number(bound.id)),
name,
bounds: res.bounds ?? [],
}
}
async function regionConstRows(regionId: number) {
const superadmin = await superadminClient()
return (await superadmin.superadmin.regions.getRegionConstants.query({ regionId })) as Array<{
key: string
value: string | null
}>
}
async function regionConstMap(regionId: number): Promise<Record<string, string | null>> {
return Object.fromEntries((await regionConstRows(regionId)).map((row) => [row.key, row.value]))
}
async function setRegionConstants(
regionId: number,
constants: Array<{ key: string; value: string | null }>
) {
const superadmin = await superadminClient()
return (await superadmin.superadmin.regions.updateRegionConstants.mutate({
regionId,
constants,
})) as any
}
async function boundSettingsMap(boundId: number): Promise<Record<string, string | null>> {
const superadmin = await superadminClient()
return (await superadmin.superadmin.regions.boundSettings.query({ boundId })) as Record<
string,
string | null
>
}
async function setBoundSettings(
boundId: number,
settings: Array<{ key: string; value: string | null }>
) {
const superadmin = await superadminClient()
return (await superadmin.superadmin.regions.updateBoundSettings.mutate({ boundId, settings })) as any
}
/* -------------------------------------------------------------------------- */
/* Reads */
/* -------------------------------------------------------------------------- */
describe('superadmin.regions reads (SREG-01..03)', () => {
it('SREG-01: list returns every region with its effective bound and centre', async () => {
const superadmin = await superadminClient()
const regions = (await superadmin.superadmin.regions.list.query()) as any[]
expect(Array.isArray(regions)).toBe(true)
expect(regions.length).toBeGreaterThanOrEqual(3)
const seeded = regions.find((region) => Number(region.id) === TEST_REGION_ID)
expect(seeded).toEqual(
expect.objectContaining({
id: TEST_REGION_ID,
name: expect.any(String),
effectiveBoundId: expect.any(Number),
center: expect.objectContaining({ lat: expect.any(Number), lng: expect.any(Number) }),
})
)
})
it('SREG-02: get returns the region with its bounds', async () => {
const superadmin = await superadminClient()
const region: any = await superadmin.superadmin.regions.get.query({ id: TEST_REGION_ID })
expect(region).toEqual(
expect.objectContaining({ id: TEST_REGION_ID, name: expect.any(String) })
)
expect(Array.isArray(region.bounds)).toBe(true)
expect(region.bounds.length).toBeGreaterThan(0)
expect(region.effectiveBoundId).toBe(region.bounds[0].id)
const priorities = region.bounds.map((bound: any) => Number(bound.priority))
expect(priorities).toEqual([...priorities].sort((a, b) => a - b))
})
it('SREG-03: get with an unknown id is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.regions.get.query({ id: 987_654_321 }),
'NOT_FOUND'
)
})
})
/* -------------------------------------------------------------------------- */
/* create */
/* -------------------------------------------------------------------------- */
describe('superadmin.regions.create (SREG-04..11)', () => {
it('SREG-04: create with one bound returns the region + bound and generates cache files', async () => {
const superadmin = await superadminClient()
const region = await createRegion()
expect(region.regionId).toBeGreaterThan(0)
expect(region.boundId).toBeGreaterThan(0)
const fetched: any = await superadmin.superadmin.regions.get.query({ id: region.regionId })
expect(fetched.name).toBe(region.name)
expect(fetched.bounds).toHaveLength(1)
expect(fetched.bounds[0].id).toBe(Number(region.boundId))
expect(fetched.effectiveBoundId).toBe(Number(region.boundId))
// create() awaits createRegionCacheFiles, so the versioned files are live.
const consts = await getEssentialConsts(Number(region.boundId))
expect(consts.regionId).toBe(region.regionId)
expect(consts.boundId).toBe(Number(region.boundId))
const products = await pollCacheJson<any>(
'SREG-04 products.json',
() => productsCacheUrl(consts),
(doc) => Array.isArray(doc?.products)
)
expect(Array.isArray(products.products)).toBe(true)
})
it('SREG-05: creating a region with no bounds is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.create.mutate({
name: `E2E no-bounds ${uniqueSuffix()}`,
bounds: [],
} as any),
'BAD_REQUEST'
)
})
it('SREG-06: duplicate priorities in the create payload are 409', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.create.mutate({
name: `E2E dup-priority ${uniqueSuffix()}`,
bounds: [
{ geojson: squareGeojson(15.5, 77.5), priority: '1' },
{ geojson: squareGeojson(15.6, 77.6), priority: '1' },
],
} as any),
'CONFLICT'
)
})
it('SREG-07: an explicit center is stored as the region centre', async () => {
const center = { lat: 14.25, lng: 76.75 }
const region = await createRegionRaw({
center,
bounds: [{ lat: 14.5, lng: 77.0, priority: '1' }],
})
const superadmin = await superadminClient()
const fetched: any = await superadmin.superadmin.regions.get.query({ id: region.regionId })
expect(fetched.center.lat).toBeCloseTo(center.lat, 6)
expect(fetched.center.lng).toBeCloseTo(center.lng, 6)
})
it('SREG-08: without a center it is computed from the first bound', async () => {
const lat = 13.5
const lng = 78.25
const region = await createRegionRaw({ bounds: [{ lat, lng, priority: '1' }] })
const superadmin = await superadminClient()
const fetched: any = await superadmin.superadmin.regions.get.query({ id: region.regionId })
expect(fetched.center.lat).toBeCloseTo(lat, 6)
expect(fetched.center.lng).toBeCloseTo(lng, 6)
})
it('SREG-09: an invalid geojson shape is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.create.mutate({
name: `E2E bad-geojson ${uniqueSuffix()}`,
bounds: [{ geojson: { type: 'Polygon', coordinates: [] }, priority: '1' }],
} as any),
'BAD_REQUEST'
)
})
it('SREG-10: a numeric-string priority is stored verbatim', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 12.5, lng: 79.5, priority: '1.5' }] })
const superadmin = await superadminClient()
const bounds = (await superadmin.superadmin.regions.bounds.query({
regionId: region.regionId,
})) as any[]
expect(bounds).toHaveLength(1)
expect(bounds[0].priority).toBe('1.5')
})
it('SREG-11: a non-numeric priority is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.create.mutate({
name: `E2E bad-priority ${uniqueSuffix()}`,
bounds: [{ geojson: squareGeojson(15.5, 77.5), priority: 'abc' }],
} as any),
'BAD_REQUEST'
)
})
it('SREG-11b (regression): a region with 17 bounds batches both seed inserts', async () => {
// 6 bounds used to build a 120-parameter region_bound_consts insert, past
// D1's 100-parameter cap; 17 bounds also splits the region_bounds insert.
const bounds = Array.from({ length: 17 }, (_, index) => ({
lat: 15.5 + index * 0.01,
lng: 77.5 + index * 0.01,
priority: String(index + 1),
}))
const region = await createRegionRaw({ bounds })
expect(region.boundIds).toHaveLength(bounds.length)
for (const boundId of region.boundIds) {
const settings = await boundSettingsMap(boundId)
expect(Object.keys(settings).sort()).toEqual([
'deliveryCharge',
'flashDeliveryCharge',
'flashFreeDeliveryThreshold',
'freeDeliveryThreshold',
'isFlashDeliveryEnabled',
])
expect(settings.deliveryCharge).toBe('20')
}
})
})
/* -------------------------------------------------------------------------- */
/* update */
/* -------------------------------------------------------------------------- */
describe('superadmin.regions.update (SREG-12..13)', () => {
it('SREG-12: update name/description round-trips', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 11.5, lng: 80.5, priority: '1' }] })
const superadmin = await superadminClient()
const nextName = `E2E Renamed ${uniqueSuffix()}`
const nextDescription = `E2E description ${uniqueSuffix()}`
const updated: any = await superadmin.superadmin.regions.update.mutate({
id: region.regionId,
name: nextName,
description: nextDescription,
})
expect(updated).toEqual(expect.objectContaining({ id: region.regionId, name: nextName }))
const fetched: any = await superadmin.superadmin.regions.get.query({ id: region.regionId })
expect(fetched.name).toBe(nextName)
expect(fetched.description).toBe(nextDescription)
})
it('SREG-13: updating an unknown region is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.update.mutate({
id: 987_654_321,
name: `E2E ghost ${uniqueSuffix()}`,
}),
'NOT_FOUND'
)
})
})
/* -------------------------------------------------------------------------- */
/* bounds */
/* -------------------------------------------------------------------------- */
describe('superadmin.regions.bounds + createBound (SREG-14..17)', () => {
it('SREG-14: bounds are returned priority ascending', async () => {
const region = await createRegionRaw({
bounds: [
{ lat: 16.0, lng: 78.0, priority: '2' },
{ lat: 16.1, lng: 78.1, priority: '1' },
],
})
const superadmin = await superadminClient()
const bounds = (await superadmin.superadmin.regions.bounds.query({
regionId: region.regionId,
})) as any[]
expect(bounds.map((bound) => Number(bound.priority))).toEqual([1, 2])
})
it('SREG-15: createBound adds the bound and refreshes the effective bound', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 16.5, lng: 78.5, priority: '1' }] })
const superadmin = await superadminClient()
const created: any = await superadmin.superadmin.regions.createBound.mutate({
regionId: region.regionId,
description: 'lower priority',
geojson: squareGeojson(16.6, 78.6),
priority: '0',
})
expect(created.regionId).toBe(region.regionId)
expect(created.priority).toBe('0')
const newBoundId = Number(created.id)
const bounds = (await superadmin.superadmin.regions.bounds.query({
regionId: region.regionId,
})) as any[]
expect(bounds.map((bound) => Number(bound.id))).toContain(newBoundId)
// refreshGenKvForRegion ran, so the new effective bound resolves publicly.
const fetched: any = await superadmin.superadmin.regions.get.query({ id: region.regionId })
expect(fetched.effectiveBoundId).toBe(newBoundId)
const consts = await getEssentialConsts(newBoundId)
expect(consts.boundId).toBe(newBoundId)
})
it('SREG-16: createBound with a duplicate priority is 409', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 16.5, lng: 78.5, priority: '1' }] })
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.createBound.mutate({
regionId: region.regionId,
geojson: squareGeojson(16.7, 78.7),
priority: '1',
}),
'CONFLICT'
)
})
it('SREG-17: createBound for an unknown region is 409/404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.createBound.mutate({
regionId: 987_654_321,
geojson: squareGeojson(16.5, 78.5),
priority: '1',
}),
['CONFLICT', 'NOT_FOUND']
)
})
})
describe('superadmin.regions.updateBound (SREG-18..20)', () => {
it('SREG-18: updateBound changes description/geojson/priority', async () => {
const region = await createRegionRaw({
bounds: [
{ lat: 17.0, lng: 78.0, priority: '1' },
{ lat: 17.5, lng: 78.5, priority: '2' },
],
})
const superadmin = await superadminClient()
const targetId = region.boundIds[1]
const nextLat = 17.9
const nextLng = 78.9
const updated: any = await superadmin.superadmin.regions.updateBound.mutate({
id: targetId,
description: 'edited bound',
geojson: squareGeojson(nextLat, nextLng),
priority: '5',
})
expect(updated.id).toBe(targetId)
expect(updated.priority).toBe('5')
expect(updated.center.lat).toBeCloseTo(nextLat, 6)
const fetched: any = await superadmin.superadmin.regions.get.query({ id: region.regionId })
const bound = fetched.bounds.find((entry: any) => Number(entry.id) === targetId)
expect(bound.description).toBe('edited bound')
expect(bound.priority).toBe('5')
})
it('SREG-19: updateBound to a duplicate priority is 409', async () => {
const region = await createRegionRaw({
bounds: [
{ lat: 17.0, lng: 78.0, priority: '1' },
{ lat: 17.5, lng: 78.5, priority: '2' },
],
})
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.updateBound.mutate({
id: region.boundIds[1],
priority: '1',
}),
'CONFLICT'
)
})
it('SREG-20: updateBound with an unknown id is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.updateBound.mutate({
id: 987_654_321,
description: 'ghost',
}),
'NOT_FOUND'
)
})
})
describe('superadmin.regions.deleteBound (SREG-21..25)', () => {
it('SREG-21: deleteBound removes a bound and reports the remainder', async () => {
const region = await createRegionRaw({
bounds: [
{ lat: 18.0, lng: 78.0, priority: '1' },
{ lat: 18.5, lng: 78.5, priority: '2' },
],
})
const superadmin = await superadminClient()
const result: any = await superadmin.superadmin.regions.deleteBound.mutate({
id: region.boundIds[1],
})
expect(result.success).toBe(true)
expect(result.deletedId).toBe(region.boundIds[1])
expect(result.remainingBounds).toBe(1)
const bounds = (await superadmin.superadmin.regions.bounds.query({
regionId: region.regionId,
})) as any[]
expect(bounds.map((bound) => Number(bound.id))).toEqual([region.boundIds[0]])
})
it('SREG-22: deleting a region’s only bound is 409', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 18.5, lng: 78.5, priority: '1' }] })
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.regions.deleteBound.mutate({ id: region.boundIds[0] }),
'CONFLICT',
'only bound'
)
})
it('SREG-23: deleting a bound that an address points at is 409', async () => {
const region = await createRegionRaw({
bounds: [
{ lat: 19.0, lng: 78.0, priority: '1' },
{ lat: 19.5, lng: 78.5, priority: '2' },
],
})
const user = await registerThrowawayUser()
await createAddress(user.token, {
regionId: region.regionId,
latitude: 19.0,
longitude: 78.0,
})
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.regions.deleteBound.mutate({ id: region.boundIds[0] }),
'CONFLICT',
'address'
)
})
it('SREG-24: deleting an unknown bound is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.regions.deleteBound.mutate({ id: 987_654_321 }),
'NOT_FOUND'
)
})
it('SREG-25: deleting a bound drops its KV payload (essentialConsts is 404)', async () => {
const region = await createRegionRaw({
bounds: [
{ lat: 19.9, lng: 78.0, priority: '1' },
{ lat: 19.95, lng: 78.05, priority: '2' },
],
})
const doomedBoundId = region.boundIds[1]
// Backfill the KV entry first so the deletion has something to drop.
expect((await getEssentialConsts(doomedBoundId)).boundId).toBe(doomedBoundId)
const superadmin = await superadminClient()
const deleted: any = await superadmin.superadmin.regions.deleteBound.mutate({
id: doomedBoundId,
})
expect(deleted.success).toBe(true)
// The stale blob is gone; the read path rebuilds and finds no bound -> 404.
await expectTrpcError(
() => anonClient().common.essentialConsts.query({ boundId: doomedBoundId }),
'NOT_FOUND'
)
})
})
/* -------------------------------------------------------------------------- */
/* bound settings */
/* -------------------------------------------------------------------------- */
describe('superadmin.regions bound settings (SREG-26..29)', () => {
it('SREG-26: boundSettings returns the bound’s settings map', async () => {
const superadmin = await superadminClient()
const settings: any = await superadmin.superadmin.regions.boundSettings.query({
boundId: TEST_BOUND_ID,
})
expect(settings).toEqual(
expect.objectContaining({
freeDeliveryThreshold: expect.any(String),
deliveryCharge: expect.any(String),
flashFreeDeliveryThreshold: expect.any(String),
flashDeliveryCharge: expect.any(String),
isFlashDeliveryEnabled: expect.anything(),
})
)
})
it('SREG-27: updateBoundSettings returns counts and refreshes the KV mirror', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 20.0, lng: 78.0, priority: '1' }] })
const boundId = region.boundIds[0]
const before = (await boundSettingsMap(boundId)).deliveryCharge ?? null
try {
const result: any = await setBoundSettings(boundId, [{ key: 'deliveryCharge', value: '77' }])
expect(result.success).toBe(true)
expect(result.updatedCount).toBe(1)
expect(result.deletedCount).toBe(0)
// updateBoundSettings awaits refreshGenKvForRegion.
const consts = await getEssentialConsts(boundId)
expect(Number(consts.deliveryCharge)).toBe(77)
expect((await boundSettingsMap(boundId)).deliveryCharge).toBe('77')
} finally {
await setBoundSettings(boundId, [{ key: 'deliveryCharge', value: before }])
}
})
it('SREG-28: a region-scoped key on updateBoundSettings is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.updateBoundSettings.mutate({
boundId: TEST_BOUND_ID,
settings: [{ key: 'supportMobile', value: '123' }],
}),
'BAD_REQUEST',
'region constant'
)
})
it('SREG-29: a null value deletes the bound setting', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 20.5, lng: 78.5, priority: '1' }] })
const boundId = region.boundIds[0]
const before = (await boundSettingsMap(boundId)).deliveryCharge ?? null
try {
await setBoundSettings(boundId, [{ key: 'deliveryCharge', value: '88' }])
expect((await boundSettingsMap(boundId)).deliveryCharge).toBe('88')
const result: any = await setBoundSettings(boundId, [{ key: 'deliveryCharge', value: null }])
expect(result.deletedCount).toBe(1)
const map = await boundSettingsMap(boundId)
expect(Object.prototype.hasOwnProperty.call(map, 'deliveryCharge')).toBe(false)
// essentialConsts substitutes the built-in default (0) for a missing row.
expect(Number((await getEssentialConsts(boundId)).deliveryCharge)).toBe(0)
} finally {
await setBoundSettings(boundId, [{ key: 'deliveryCharge', value: before }])
}
})
})
/* -------------------------------------------------------------------------- */
/* region constants */
/* -------------------------------------------------------------------------- */
describe('superadmin.regions region constants (SREG-30..33)', () => {
it('SREG-30: getRegionConstants returns a key/value list', async () => {
const rows = await regionConstRows(TEST_REGION_ID)
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)
}
expect(Object.fromEntries(rows.map((row) => [row.key, row.value]))).toEqual(
expect.objectContaining({
products_version_num: expect.anything(),
slots_version_num: expect.anything(),
tagsOrder: expect.anything(),
supportMobile: expect.anything(),
})
)
})
it('SREG-31: updateRegionConstants returns counts and refreshes the KV mirror', async () => {
const region = await createRegionRaw({ bounds: [{ lat: 21.0, lng: 78.0, priority: '1' }] })
const boundId = region.boundIds[0]
const before = (await regionConstMap(region.regionId)).supportMobile ?? null
try {
const result: any = await setRegionConstants(region.regionId, [
{ key: 'supportMobile', value: '9090909090' },
])
expect(result.success).toBe(true)
expect(result.updatedCount).toBe(1)
expect(result.deletedCount).toBe(0)
// updateRegionConstants awaits refreshGenKvForRegion for non-cache keys.
const consts = await getEssentialConsts(boundId)
expect(consts.supportMobile).toBe('9090909090')
} finally {
await setRegionConstants(region.regionId, [{ key: 'supportMobile', value: before }])
}
})
it('SREG-32: a bound-scoped key on updateRegionConstants is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.regions.updateRegionConstants.mutate({
regionId: TEST_REGION_ID,
constants: [{ key: 'deliveryCharge', value: '55' }],
}),
'BAD_REQUEST',
'bound constant'
)
})
it.skip('SREG-33: updating tagsOrder schedules a region store-cache rebuild (DO scheduling; covered by tests/unit/cache-creator.test.ts)', () => {})
})
/* -------------------------------------------------------------------------- */
/* effective settings + isolation + auth */
/* -------------------------------------------------------------------------- */
describe('superadmin.regions effectiveSettings (SREG-34..35)', () => {
it('SREG-34: effectiveSettings uses the lowest-priority bound', async () => {
const region = await createRegionRaw({
bounds: [
{ lat: 22.0, lng: 78.0, priority: '1' },
{ lat: 22.5, lng: 78.5, priority: '2' },
],
})
const [firstBoundId, secondBoundId] = region.boundIds
await setBoundSettings(firstBoundId, [{ key: 'deliveryCharge', value: '111' }])
await setBoundSettings(secondBoundId, [{ key: 'deliveryCharge', value: '222' }])
const superadmin = await superadminClient()
const effective: any = await superadmin.superadmin.regions.effectiveSettings.query({
regionId: region.regionId,
})
expect(effective.boundId).toBe(firstBoundId)
expect(effective.priority).toBe('1')
expect(effective.settings.deliveryCharge).toBe('111')
})
it('(current) SREG-35: a region with no bound is 422, but that state is unreachable', async () => {
// getEffectiveRegionSettings returns null only when the region has zero
// bounds. The API cannot create that state (create needs >= 1 bound and the
// last bound cannot be deleted), so the reachable 422 is an unknown region.
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.regions.effectiveSettings.query({ regionId: 987_654_321 }),
'UNPROCESSABLE_CONTENT',
'no configured bound'
)
})
})
describe('superadmin.regions cache + auth (SREG-36..37)', () => {
it('SREG-36: two new regions generate isolated cache files', async () => {
const regionA = await createRegionRaw({ bounds: [{ lat: 23.0, lng: 78.0, priority: '1' }] })
const regionB = await createRegionRaw({ bounds: [{ lat: 23.5, lng: 78.5, priority: '1' }] })
const constsA = await getEssentialConsts(regionA.boundIds[0])
const constsB = await getEssentialConsts(regionB.boundIds[0])
const docA = await pollCacheJson<any>(
'SREG-36 essential-consts A',
() => essentialConstsCacheUrl(constsA),
(doc) => Number(doc?.regionId) === regionA.regionId
)
const docB = await pollCacheJson<any>(
'SREG-36 essential-consts B',
() => essentialConstsCacheUrl(constsB),
(doc) => Number(doc?.regionId) === regionB.regionId
)
expect(docA.regionId).toBe(regionA.regionId)
expect(docA.boundId).toBe(regionA.boundIds[0])
expect(docB.regionId).toBe(regionB.regionId)
expect(docB.boundId).toBe(regionB.boundIds[0])
expect(docA.regionId).not.toBe(docB.regionId)
})
it('SREG-37: anonymous, staff and user tokens are 401', async () => {
const staff = await staffSession()
const user = await userSession()
for (const client of [anonClient(), apiClient(staff.token), apiClient(user.token)]) {
await expectTrpcError(() => client.superadmin.regions.list.query(), 'UNAUTHORIZED')
await expectTrpcError(
() =>
client.superadmin.regions.create.mutate({
name: `E2E denied ${uniqueSuffix()}`,
bounds: [{ geojson: squareGeojson(15.5, 77.5), priority: '1' }],
} as any),
'UNAUTHORIZED'
)
await expectTrpcError(
() => client.superadmin.regions.deleteBound.mutate({ id: TEST_BOUND_ID }),
'UNAUTHORIZED'
)
}
})
})