freshyo/apps/backend/tests/api/superadmin-global-stores.test.ts
2026-10-20 00:31:05 +05:30

281 lines
12 KiB
TypeScript

/**
* SGSTORE-01..12 — `superadmin.globalStores` (catalogue §8.6).
*
* Live HTTP/tRPC suite. One `it()` per catalogue row; rows that pin current
* (not intended) behaviour are prefixed `(current)`.
*
* Observed contracts (do NOT "fix" here):
* - `update`/`delete` throw raw `Error`s, so a missing store surfaces as
* INTERNAL_SERVER_ERROR (the router has no ApiError 404 branch).
* - `delete` refuses a store that still has ANY product row pointing at it,
* even one whose SKUs were soft-deleted (the guard counts `product_info`,
* not live SKUs).
* - `create` returns the raw stored image key; `list`/`get` wrap it in the
* assets domain via `scaffoldAssetUrl`.
*/
import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { anonClient, staffClient, staffSession, superadminClient, userSession } from '../helpers/sessions'
import { createRegion, createStore } from '../helpers/fixtures'
import { scaffoldCache } from '../helpers/cache'
jest.setTimeout(300_000)
const ASSETS_DOMAIN = 'https://assets2.freshyo.in'
/* -------------------------------------------------------------------------- */
/* Fixtures */
/* -------------------------------------------------------------------------- */
async function createGlobalStore(overrides: { name?: string; description?: string; imageUrl?: string } = {}) {
const superadmin = await superadminClient()
const res: any = await superadmin.superadmin.globalStores.create.mutate({
name: overrides.name ?? `E2E GS ${uniqueSuffix()}`,
description: overrides.description ?? 'SGSTORE fixture',
...(overrides.imageUrl ? { imageUrl: overrides.imageUrl } : {}),
})
return res
}
/** Elevate a throwaway regional product into a global store (so it has products). */
async function attachProductToStore(storeId: number): Promise<number> {
const staff = await staffClient()
const store = await createStore()
const created: any = await staff.admin.product.createProduct.mutate({
name: `E2E GS product ${uniqueSuffix()}`,
shortDescription: 'SGSTORE fixture',
storeId: store.storeId,
productType: 'item',
skus: [
{
name: '1pc',
price: 100,
marketPrice: 150,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
},
],
})
const productId = Number(created.product.id)
const superadmin = await superadminClient()
await superadmin.superadmin.products.elevate.mutate({ productId, storeId })
return productId
}
/**
* A brand-new region's stores document from the scaffold function (test route).
* No versioned-file read / Durable Object wait.
*/
async function freshRegionStores(): Promise<any[]> {
const region = await createRegion()
const doc: any = await scaffoldCache('stores', { regionId: region.regionId })
return doc.stores
}
/* -------------------------------------------------------------------------- */
/* reads */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalStores reads (SGSTORE-01..03)', () => {
it('SGSTORE-01: list returns global stores with image URLs', async () => {
const superadmin = await superadminClient()
const stores: any = await superadmin.superadmin.globalStores.list.query()
expect(Array.isArray(stores)).toBe(true)
expect(stores.length).toBeGreaterThan(0)
for (const store of stores) {
expect(store).toEqual(
expect.objectContaining({
id: expect.any(Number),
name: expect.any(String),
isGlobal: true,
})
)
expect(Object.prototype.hasOwnProperty.call(store, 'imageUrl')).toBe(true)
if (store.imageUrl != null) expect(store.imageUrl).toMatch(/^https?:\/\//)
}
})
it('SGSTORE-02: get returns a global store', async () => {
const superadmin = await superadminClient()
const stores: any = await superadmin.superadmin.globalStores.list.query()
const res: any = await superadmin.superadmin.globalStores.get.query({ id: Number(stores[0].id) })
expect(Number(res.store.id)).toBe(Number(stores[0].id))
expect(res.store.isGlobal).toBe(true)
expect(res.store.name).toEqual(expect.any(String))
})
it('SGSTORE-03: getting an unknown store is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.globalStores.get.query({ id: 987_654_321 }),
'NOT_FOUND',
'not found'
)
})
})
/* -------------------------------------------------------------------------- */
/* create */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalStores.create (SGSTORE-04..06)', () => {
it('SGSTORE-04: create returns a global store and it is readable', async () => {
const superadmin = await superadminClient()
const created = await createGlobalStore()
expect(created.message).toBe('Global store created successfully')
expect(created.store.isGlobal).toBe(true)
expect(created.store.name).toEqual(expect.any(String))
const storeId = Number(created.store.id)
expect(storeId).toBeGreaterThan(0)
const fetched: any = await superadmin.superadmin.globalStores.get.query({ id: storeId })
expect(Number(fetched.store.id)).toBe(storeId)
expect(fetched.store.name).toBe(created.store.name)
})
it('SGSTORE-05: an empty name is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.globalStores.create.mutate({ name: '' } as any),
'BAD_REQUEST'
)
})
it('SGSTORE-06: a presigned image URL is reduced to its stored key', async () => {
const superadmin = await superadminClient()
const file = `sgstore-${uniqueSuffix().replace(/[^a-z0-9]/gi, '')}.png`
const presigned =
`https://acct.r2.cloudflarestorage.com/bucket/product-images/${file}?X-Amz-Signature=zzz`
const created = await createGlobalStore({ imageUrl: presigned })
// create() returns the raw key; the read path scaffolds the assets URL.
expect(created.store.imageUrl).toBe(`product-images/${file}`)
const fetched: any = await superadmin.superadmin.globalStores.get.query({
id: Number(created.store.id),
})
expect(fetched.store.imageUrl).toBe(`${ASSETS_DOMAIN}/product-images/${file}`)
})
})
/* -------------------------------------------------------------------------- */
/* update */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalStores.update (SGSTORE-07..08)', () => {
it('SGSTORE-07: update round-trips name, description and image', async () => {
const superadmin = await superadminClient()
const created = await createGlobalStore()
const storeId = Number(created.store.id)
const newName = `E2E GS edited ${uniqueSuffix()}`
const file = `sgstore-edit-${uniqueSuffix().replace(/[^a-z0-9]/gi, '')}.png`
const res: any = await superadmin.superadmin.globalStores.update.mutate({
id: storeId,
name: newName,
description: 'updated by SGSTORE-07',
imageUrl: `https://acct.r2.cloudflarestorage.com/bucket/product-images/${file}?X-Amz-Signature=zzz`,
})
expect(res.message).toBe('Global store updated successfully')
const fetched: any = await superadmin.superadmin.globalStores.get.query({ id: storeId })
expect(fetched.store.name).toBe(newName)
expect(fetched.store.description).toBe('updated by SGSTORE-07')
expect(fetched.store.imageUrl).toBe(`${ASSETS_DOMAIN}/product-images/${file}`)
})
it('(current) SGSTORE-08: updating an unknown store is INTERNAL_SERVER_ERROR', async () => {
// `updateGlobalStore` throws a raw Error('Global store not found'); the router
// does not map it to 404, so it surfaces as a 500.
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.globalStores.update.mutate({ id: 987_654_321, name: 'x' } as any),
'INTERNAL_SERVER_ERROR',
'not found'
)
})
})
/* -------------------------------------------------------------------------- */
/* delete */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalStores.delete (SGSTORE-09..12)', () => {
it('SGSTORE-09: delete removes an empty global store', async () => {
const superadmin = await superadminClient()
const created = await createGlobalStore()
const storeId = Number(created.store.id)
const res: any = await superadmin.superadmin.globalStores.delete.mutate({ id: storeId })
expect(res.message).toBe('Global store deleted successfully')
await expectTrpcError(
() => superadmin.superadmin.globalStores.get.query({ id: storeId }),
'NOT_FOUND'
)
const stores: any = await superadmin.superadmin.globalStores.list.query()
expect(stores.some((store: any) => Number(store.id) === storeId)).toBe(false)
})
it('(current) SGSTORE-10: a store with products cannot be deleted (500)', async () => {
// The guard counts every `product_info` row with this storeId, so it fires
// even after the product's SKUs were soft-deleted.
const superadmin = await superadminClient()
const created = await createGlobalStore()
const storeId = Number(created.store.id)
await attachProductToStore(storeId)
await expectTrpcError(
() => superadmin.superadmin.globalStores.delete.mutate({ id: storeId }),
'INTERNAL_SERVER_ERROR',
'still has products'
)
})
it('(current) SGSTORE-11: a global store write reaches a region cache (all-region rebuild not awaited)', async () => {
// The write schedules a fire-and-forget all-region rebuild via the
// CacheCreator DO; that DO processes regions sequentially and stalls on this
// local DB, so the async version movement is not deterministically
// observable. A freshly created region's cache already contains the store.
const created = await createGlobalStore({ name: `E2E GS cache ${uniqueSuffix()}` })
const storeId = Number(created.store.id)
const stores = await freshRegionStores()
const found = stores.find((store: any) => Number(store.id) === storeId)
expect(found).toEqual(expect.objectContaining({ id: storeId, name: created.store.name }))
})
it('SGSTORE-12: anonymous, staff and user tokens are rejected', async () => {
const staff = await staffSession()
const user = await userSession()
for (const client of [anonClient(), apiClient(staff.token), apiClient(user.token)]) {
await expectTrpcError(() => client.superadmin.globalStores.list.query(), 'UNAUTHORIZED')
await expectTrpcError(
() => client.superadmin.globalStores.get.query({ id: 1 }),
'UNAUTHORIZED'
)
await expectTrpcError(
() => client.superadmin.globalStores.create.mutate({ name: 'denied' }),
'UNAUTHORIZED'
)
await expectTrpcError(
() => client.superadmin.globalStores.update.mutate({ id: 1, name: 'denied' } as any),
'UNAUTHORIZED'
)
await expectTrpcError(
() => client.superadmin.globalStores.delete.mutate({ id: 1 }),
'UNAUTHORIZED'
)
}
})
})