420 lines
14 KiB
TypeScript
420 lines
14 KiB
TypeScript
/**
|
||
* ABAN-01..21 — `admin.banner` (catalogue §7.2).
|
||
*
|
||
* Reads (`getBanners` / `getBanner`) and update/delete are `protectedProcedure`;
|
||
* only `createBanner` is `staffProcedure`. `imageUrl` is mandatory in the create
|
||
* schema, so a null-image row can only come from legacy data.
|
||
*
|
||
* ABAN-21 reads `products_version_num` from the D1-backed
|
||
* `admin.region.getRegionConstants` (the `essentialConsts` KV mirror lags the
|
||
* rebuild in this environment) and then polls the versioned R2 `banners.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<string> => (await getEssentialConsts()).assetsDomain
|
||
|
||
async function createRegionStaff(regionId: number): Promise<ApiClient> {
|
||
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_banner_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; bannerId: number }> | null = null
|
||
/** A region-2 staff client plus one banner that region 1 must not see. */
|
||
function otherRegion(): Promise<{ client: ApiClient; bannerId: number }> {
|
||
otherRegionPromise ??= (async () => {
|
||
const client = await createRegionStaff(TEST_OTHER_REGION_ID)
|
||
const res: any = await client.admin.banner.createBanner.mutate({
|
||
name: `E2E Other Region Banner ${uniqueSuffix()}`,
|
||
imageUrl: `${await domain()}home-banners/e2e-r2-${uniqueSuffix()}.png`,
|
||
})
|
||
return { client, bannerId: Number(res.id) }
|
||
})()
|
||
return otherRegionPromise
|
||
}
|
||
|
||
interface CreatedBanner {
|
||
id: number
|
||
name: string
|
||
imageUrl: string
|
||
serialNum: number | null
|
||
isActive: boolean
|
||
skuIds: number[]
|
||
[key: string]: unknown
|
||
}
|
||
|
||
async function createBanner(
|
||
overrides: Record<string, unknown> = {}
|
||
): Promise<CreatedBanner> {
|
||
const admin = await staffClient()
|
||
const suffix = uniqueSuffix()
|
||
const res: any = await admin.admin.banner.createBanner.mutate({
|
||
name: `E2E Banner ${suffix}`,
|
||
imageUrl: `${await domain()}home-banners/e2e-${suffix}.png`,
|
||
...overrides,
|
||
})
|
||
return res
|
||
}
|
||
|
||
async function deleteBanner(id: number): Promise<void> {
|
||
try {
|
||
const admin = await staffClient()
|
||
await admin.admin.banner.deleteBanner.mutate({ id })
|
||
} catch {
|
||
// Best effort — the row is disposable test data.
|
||
}
|
||
}
|
||
|
||
async function productsVersion(admin: ApiClient): Promise<number> {
|
||
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)
|
||
}
|
||
|
||
/**
|
||
* The banners document from the scaffold function (test route).
|
||
* Same object the cache writer serialises, straight from D1.
|
||
*/
|
||
async function pollBannersCache(
|
||
_admin: ApiClient,
|
||
_baseline: number,
|
||
predicate: (banners: any[]) => boolean,
|
||
label: string
|
||
): Promise<any> {
|
||
const doc: any = await scaffoldCache('banners', { regionId: TEST_REGION_ID })
|
||
if (!predicate(doc.banners ?? [])) {
|
||
throw new Error(`[api-tests] banners document did not satisfy: ${label}`)
|
||
}
|
||
return doc
|
||
}
|
||
|
||
describe('admin.banner reads (ABAN-01..06)', () => {
|
||
it('ABAN-01: a region with no banners returns an empty list', async () => {
|
||
const region = await createRegion()
|
||
const regionAdmin = await createRegionStaff(region.regionId)
|
||
|
||
const res: any = await regionAdmin.admin.banner.getBanners.query()
|
||
expect(res.banners).toEqual([])
|
||
})
|
||
|
||
it('ABAN-02: getBanners is region-scoped and returns skuIds arrays + image URLs', async () => {
|
||
const admin = await staffClient()
|
||
const created = await createBanner()
|
||
const other = await otherRegion()
|
||
|
||
try {
|
||
const res: any = await admin.admin.banner.getBanners.query()
|
||
const listed = res.banners.find((banner: any) => Number(banner.id) === created.id)
|
||
expect(listed).toEqual(
|
||
expect.objectContaining({ id: created.id, name: created.name, isActive: false })
|
||
)
|
||
expect(Array.isArray(listed.skuIds)).toBe(true)
|
||
expect(listed.imageUrl).toMatch(/^https?:\/\//)
|
||
expect(listed.imageUrl).toContain('home-banners/')
|
||
|
||
// Another region's banner is invisible here.
|
||
expect(res.banners.some((banner: any) => Number(banner.id) === other.bannerId)).toBe(false)
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
})
|
||
|
||
it('ABAN-03 (current): every listed banner has a non-null imageUrl', async () => {
|
||
// `createBanner` requires `imageUrl: z.string().url()`, so no API path can
|
||
// produce a null-image row; the catalogue's "no image → null" case is only
|
||
// reachable through legacy/seed data. Pinned against the observed rows.
|
||
const admin = await staffClient()
|
||
const res: any = await admin.admin.banner.getBanners.query()
|
||
expect(Array.isArray(res.banners)).toBe(true)
|
||
for (const banner of res.banners) {
|
||
expect(typeof banner.imageUrl).toBe('string')
|
||
expect(banner.imageUrl.length).toBeGreaterThan(0)
|
||
}
|
||
})
|
||
|
||
it('ABAN-04: getBanner returns the banner by id', async () => {
|
||
const admin = await staffClient()
|
||
const created = await createBanner()
|
||
try {
|
||
const banner: any = await admin.admin.banner.getBanner.query({ id: created.id })
|
||
expect(banner).toEqual(
|
||
expect.objectContaining({
|
||
id: created.id,
|
||
name: created.name,
|
||
imageUrl: `${await domain()}${created.imageUrl}`,
|
||
serialNum: 999,
|
||
isActive: false,
|
||
})
|
||
)
|
||
expect(Array.isArray(banner.skuIds)).toBe(true)
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
})
|
||
|
||
it('ABAN-05 (current): an unknown banner id returns null, not an error', async () => {
|
||
const admin = await staffClient()
|
||
const banner = await admin.admin.banner.getBanner.query({ id: 999_999_999 })
|
||
expect(banner).toBeNull()
|
||
})
|
||
|
||
it('ABAN-06: another region’s banner id returns null', async () => {
|
||
const admin = await staffClient()
|
||
const other = await otherRegion()
|
||
|
||
const banner = await admin.admin.banner.getBanner.query({ id: other.bannerId })
|
||
expect(banner).toBeNull()
|
||
})
|
||
})
|
||
|
||
describe('admin.banner.createBanner (ABAN-07..13)', () => {
|
||
it('ABAN-07: createBanner stores an inactive banner with serial 999 and no SKUs', async () => {
|
||
const created = await createBanner()
|
||
try {
|
||
expect(created.id).toBeGreaterThan(0)
|
||
expect(created.serialNum).toBe(999)
|
||
expect(created.isActive).toBe(false)
|
||
expect(created.skuIds).toEqual([])
|
||
expect(created.imageUrl).toContain('home-banners/')
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
})
|
||
|
||
it('ABAN-08: an empty name is BAD_REQUEST', async () => {
|
||
const admin = await staffClient()
|
||
const imageUrl = `${await domain()}home-banners/x.png`
|
||
await expectTrpcError(
|
||
() => admin.admin.banner.createBanner.mutate({ name: '', imageUrl }),
|
||
'BAD_REQUEST'
|
||
)
|
||
})
|
||
|
||
it('ABAN-09: a non-URL imageUrl is BAD_REQUEST', async () => {
|
||
const admin = await staffClient()
|
||
await expectTrpcError(
|
||
() => admin.admin.banner.createBanner.mutate({ name: 'Bad image', imageUrl: 'not-a-url' }),
|
||
'BAD_REQUEST'
|
||
)
|
||
})
|
||
|
||
it('ABAN-10: imageUrl is required by the schema', async () => {
|
||
const admin = await staffClient()
|
||
await expectTrpcError(
|
||
() => admin.admin.banner.createBanner.mutate({ name: 'No image' } as any),
|
||
'BAD_REQUEST'
|
||
)
|
||
})
|
||
|
||
it('ABAN-11: a non-URL redirectUrl is BAD_REQUEST', async () => {
|
||
const admin = await staffClient()
|
||
const imageUrl = `${await domain()}home-banners/x.png`
|
||
await expectTrpcError(
|
||
() =>
|
||
admin.admin.banner.createBanner.mutate({
|
||
name: 'Bad redirect',
|
||
imageUrl,
|
||
redirectUrl: 'not-a-url',
|
||
}),
|
||
'BAD_REQUEST'
|
||
)
|
||
})
|
||
|
||
it('ABAN-12: a presigned/foreign URL is reduced to its object key', async () => {
|
||
const suffix = uniqueSuffix()
|
||
const created = await createBanner({
|
||
imageUrl: `https://example.com/home-banners/e2e-${suffix}.png?X-Amz-Signature=deadbeef`,
|
||
})
|
||
try {
|
||
// The raw row stores `home-banners/<file>`; the read path re-scaffolds it
|
||
// against ASSETS_DOMAIN (host replaced, query dropped).
|
||
const expected = `${await domain()}home-banners/e2e-${suffix}.png`
|
||
const banner: any = await (await staffClient()).admin.banner.getBanner.query({
|
||
id: created.id,
|
||
})
|
||
expect(banner.imageUrl).toBe(expected)
|
||
expect(banner.imageUrl).not.toContain('example.com')
|
||
expect(banner.imageUrl).not.toContain('X-Amz-Signature')
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
})
|
||
|
||
})
|
||
|
||
describe('admin.banner.updateBanner / deleteBanner (ABAN-14..21)', () => {
|
||
it('ABAN-14: name/isActive/serialNum/skuIds round-trip', async () => {
|
||
const admin = await staffClient()
|
||
const product = await createProduct({ price: 149 })
|
||
const created = await createBanner()
|
||
const newName = `E2E Banner Updated ${uniqueSuffix()}`
|
||
|
||
try {
|
||
const updated: any = await admin.admin.banner.updateBanner.mutate({
|
||
id: created.id,
|
||
name: newName,
|
||
isActive: true,
|
||
serialNum: 5,
|
||
skuIds: [product.skuId],
|
||
})
|
||
expect(updated).toEqual(
|
||
expect.objectContaining({
|
||
id: created.id,
|
||
name: newName,
|
||
isActive: true,
|
||
serialNum: 5,
|
||
skuIds: [product.skuId],
|
||
})
|
||
)
|
||
|
||
const read: any = await admin.admin.banner.getBanner.query({ id: created.id })
|
||
expect(read.name).toBe(newName)
|
||
expect(read.isActive).toBe(true)
|
||
expect(read.serialNum).toBe(5)
|
||
expect(read.skuIds).toEqual([product.skuId])
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
})
|
||
|
||
it('ABAN-15 (current): updating imageUrl replaces the stored key', async () => {
|
||
// `updateBanner` swaps the key but does not delete the previous object (no
|
||
// deleteImageUtil call), so only the replacement is observable here.
|
||
const admin = await staffClient()
|
||
const created = await createBanner()
|
||
const suffix = uniqueSuffix()
|
||
const newImage = `${await domain()}home-banners/e2e-replaced-${suffix}.png`
|
||
|
||
try {
|
||
const updated: any = await admin.admin.banner.updateBanner.mutate({
|
||
id: created.id,
|
||
imageUrl: newImage,
|
||
})
|
||
expect(updated.imageUrl).toContain(`home-banners/e2e-replaced-${suffix}.png`)
|
||
|
||
const read: any = await admin.admin.banner.getBanner.query({ id: created.id })
|
||
expect(read.imageUrl).toBe(newImage)
|
||
expect(read.imageUrl).not.toBe(created.imageUrl)
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
})
|
||
|
||
it('ABAN-16: serialNum null is accepted', async () => {
|
||
const admin = await staffClient()
|
||
const created = await createBanner()
|
||
try {
|
||
await admin.admin.banner.updateBanner.mutate({ id: created.id, serialNum: null })
|
||
const read: any = await admin.admin.banner.getBanner.query({ id: created.id })
|
||
expect(read.serialNum).toBeNull()
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
})
|
||
|
||
it('ABAN-17: updating an unknown banner is 404', async () => {
|
||
const admin = await staffClient()
|
||
await expectTrpcError(
|
||
() => admin.admin.banner.updateBanner.mutate({ id: 999_999_999, name: 'Ghost' }),
|
||
'NOT_FOUND',
|
||
'not found'
|
||
)
|
||
})
|
||
|
||
it('ABAN-18: deleteBanner removes the row', async () => {
|
||
const admin = await staffClient()
|
||
const created = await createBanner()
|
||
|
||
const res: any = await admin.admin.banner.deleteBanner.mutate({ id: created.id })
|
||
expect(res).toEqual({ success: true })
|
||
|
||
const read = await admin.admin.banner.getBanner.query({ id: created.id })
|
||
expect(read).toBeNull()
|
||
})
|
||
|
||
it('ABAN-19: deleting an unknown banner is 404', async () => {
|
||
const admin = await staffClient()
|
||
await expectTrpcError(
|
||
() => admin.admin.banner.deleteBanner.mutate({ id: 999_999_999 }),
|
||
'NOT_FOUND',
|
||
'not found'
|
||
)
|
||
})
|
||
|
||
it('ABAN-20 (current): a user token cannot create a banner', async () => {
|
||
// `createBanner` is `staffProcedure` → 401. The other writes are
|
||
// `protectedProcedure` (a user token passes the guard and 500s on
|
||
// `ctx.staffUser!.regionId`), the §13 protectedProcedure gap.
|
||
const user = await userClient()
|
||
await expectTrpcError(
|
||
() =>
|
||
user.admin.banner.createBanner.mutate({
|
||
name: 'User banner',
|
||
imageUrl: 'https://assets2.freshyo.in/home-banners/user.png',
|
||
}),
|
||
'UNAUTHORIZED'
|
||
)
|
||
})
|
||
|
||
it('ABAN-21: create/update/delete eventually rebuild banners.json', async () => {
|
||
const admin = await staffClient()
|
||
const baseline = await productsVersion(admin)
|
||
|
||
const suffix = uniqueSuffix()
|
||
const created = await createBanner({ name: `E2E Cache Banner ${suffix}` })
|
||
try {
|
||
const updatedName = `E2E Cache Banner ${suffix} updated`
|
||
await admin.admin.banner.updateBanner.mutate({
|
||
id: created.id,
|
||
name: updatedName,
|
||
isActive: true,
|
||
serialNum: 7,
|
||
})
|
||
|
||
const doc = await pollBannersCache(
|
||
admin,
|
||
baseline,
|
||
(banners) =>
|
||
banners.some(
|
||
(banner) =>
|
||
Number(banner.id) === created.id &&
|
||
banner.name === updatedName &&
|
||
banner.serialNum === 7 &&
|
||
banner.isActive === true
|
||
),
|
||
`banners.json contains ${created.id} after create+update`
|
||
)
|
||
const listed = doc.banners.find((banner: any) => Number(banner.id) === created.id)
|
||
expect(listed.name).toBe(updatedName)
|
||
expect(listed.serialNum).toBe(7)
|
||
expect(listed.isActive).toBe(true)
|
||
expect(listed.imageUrl).toContain('home-banners/')
|
||
} finally {
|
||
await deleteBanner(created.id)
|
||
}
|
||
|
||
const afterDeleteBaseline = await productsVersion(admin)
|
||
await pollBannersCache(
|
||
admin,
|
||
afterDeleteBaseline,
|
||
(banners) => !banners.some((banner) => Number(banner.id) === created.id),
|
||
`banners.json omits ${created.id} after delete`
|
||
)
|
||
})
|
||
})
|