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

660 lines
24 KiB
TypeScript

/**
* SGPROD-01..17 — `superadmin.globalProducts` (catalogue §8.5).
*
* Live HTTP/tRPC suite. One `it()` per catalogue row; rows that pin current
* (not intended) behaviour are prefixed `(current)` with a comment recording the
* observed contract.
*
* Observed contracts (do NOT "fix" here):
* - `delete` is a soft delete: the `product_info` row survives and every SKU is
* flagged `isDeleted`, so the product still appears in `list`/`get`.
* - Removing an existing SKU by omitting it from `update.skus` is not implemented:
* the omitted SKU is left untouched.
*
* `create` (and an update that adds a SKU) seeds one `product_market_stats` row
* per region; that insert is chunked so it stays under D1's 100-bound-parameter
* cap regardless of how many regions exist.
*/
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)
/* -------------------------------------------------------------------------- */
/* Fixtures */
/* -------------------------------------------------------------------------- */
interface RegionalProduct {
productId: number
skuIds: number[]
name: string
}
/** Create a regional product with `skuCount` SKUs in the staff region. */
async function createRegionalProduct(options: {
storeId: number
skuCount?: number
name?: string
shortDescription?: string
basePrice?: number
}): Promise<RegionalProduct> {
const staff = await staffClient()
const skuCount = options.skuCount ?? 1
const basePrice = options.basePrice ?? 100
const name = options.name ?? `E2E GP product ${uniqueSuffix()}`
const skus = Array.from({ length: skuCount }, (_, index) => {
const label = `${index + 1}pc`
const price = basePrice + index * 100
return {
name: label,
price,
marketPrice: price + 50,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: label }],
}
})
const res: any = await staff.admin.product.createProduct.mutate({
name,
shortDescription: options.shortDescription ?? 'SGPROD fixture',
storeId: options.storeId,
productType: 'item',
skus,
})
return {
productId: Number(res.product.id),
skuIds: res.product.skus.map((sku: any) => Number(sku.id)),
name,
}
}
/** A throwaway global store (never a seeded one). */
async function createGlobalStore(): Promise<number> {
const superadmin = await superadminClient()
const res: any = await superadmin.superadmin.globalStores.create.mutate({
name: `E2E GP store ${uniqueSuffix()}`,
description: 'SGPROD fixture',
})
return Number(res.store.id)
}
/** Ensure the DB has at least `count` regions (the market-row bind cap starts at 12). */
async function ensureAtLeastRegions(count: number): Promise<void> {
const superadmin = await superadminClient()
const regions = (await superadmin.superadmin.regions.list.query()) as any[]
for (let i = regions.length; i < count; i++) {
await createRegion()
}
}
interface OwnedGlobalProduct extends RegionalProduct {
storeId: number
}
/** A global product this suite owns: regional product elevated to a global store. */
async function makeGlobalProduct(
options: { skuCount?: number; shortDescription?: string; basePrice?: number } = {}
): Promise<OwnedGlobalProduct> {
const store = await createStore()
const regional = await createRegionalProduct({ storeId: store.storeId, ...options })
const storeId = await createGlobalStore()
const superadmin = await superadminClient()
await superadmin.superadmin.products.elevate.mutate({
productId: regional.productId,
storeId,
})
return { ...regional, storeId }
}
/** A single `update.skus` entry for an existing SKU. */
function skuUpdate(id: number, overrides: Record<string, unknown> = {}) {
return {
id,
name: '1pc',
price: 321,
marketPrice: 400,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
...overrides,
}
}
/**
* A brand-new region's products document from the scaffold function (test
* route). No versioned-file read / Durable Object wait.
*/
async function freshRegionProducts(): Promise<{ regionId: number; products: any[] }> {
const region = await createRegion()
const doc: any = await scaffoldCache('products', { regionId: region.regionId })
return { regionId: region.regionId, products: doc.products }
}
/* -------------------------------------------------------------------------- */
/* reads */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalProducts reads (SGPROD-01..03)', () => {
it('SGPROD-01: list returns the global products with their SKUs', async () => {
const superadmin = await superadminClient()
const res: any = await superadmin.superadmin.globalProducts.list.query()
expect(Array.isArray(res.products)).toBe(true)
expect(res.products.length).toBeGreaterThan(0)
for (const product of res.products) {
expect(product).toEqual(
expect.objectContaining({
id: expect.any(Number),
name: expect.any(String),
})
)
expect(Array.isArray(product.skus)).toBe(true)
}
})
it('SGPROD-02: get returns a global product with its SKUs', async () => {
const superadmin = await superadminClient()
const list: any = await superadmin.superadmin.globalProducts.list.query()
const target = list.products[0]
const res: any = await superadmin.superadmin.globalProducts.get.query({ id: Number(target.id) })
expect(Number(res.product.id)).toBe(Number(target.id))
expect(res.product.name).toEqual(expect.any(String))
expect(Array.isArray(res.product.skus)).toBe(true)
expect(res.product.skus.length).toBeGreaterThan(0)
})
it('SGPROD-03: getting an unknown product is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.globalProducts.get.query({ id: 987_654_321 }),
'NOT_FOUND',
'not found'
)
})
})
/* -------------------------------------------------------------------------- */
/* create */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalProducts.create (SGPROD-04..07)', () => {
it('SGPROD-04: create succeeds and seeds the region market rows', async () => {
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
const name = `E2E GP create ${uniqueSuffix()}`
const payload = {
name,
shortDescription: 'SGPROD-04',
storeId,
productType: 'item',
skus: [skuUpdate(0, { id: undefined, price: 150 })],
} as any
const res: any = await superadmin.superadmin.globalProducts.create.mutate(payload)
const productId = Number(res.product?.id)
expect(productId).toBeGreaterThan(0)
expect(res.message).toBe('Global product created successfully')
const got: any = await superadmin.superadmin.globalProducts.get.query({ id: productId })
expect(got.product.name).toBe(name)
expect(got.product.skus).toHaveLength(1)
expect(got.product.skus[0].marketStats.length).toBeGreaterThan(0)
})
it('SGPROD-05: an invalid name, price or feature value is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
const base = {
storeId,
productType: 'item' as const,
skus: [skuUpdate(0, { id: undefined, price: 150 })],
}
await expectTrpcError(
() => superadmin.superadmin.globalProducts.create.mutate({ ...base, name: '' } as any),
'BAD_REQUEST'
)
await expectTrpcError(
() =>
superadmin.superadmin.globalProducts.create.mutate({
...base,
name: `E2E GP bad price ${uniqueSuffix()}`,
skus: [skuUpdate(0, { id: undefined, price: -1 })],
} as any),
'BAD_REQUEST'
)
await expectTrpcError(
() =>
superadmin.superadmin.globalProducts.create.mutate({
...base,
name: `E2E GP bad feature ${uniqueSuffix()}`,
skus: [skuUpdate(0, { id: undefined, features: [{ featureName: 'quantity', featureValue: '' }] })],
} as any),
'BAD_REQUEST'
)
})
it('SGPROD-06: a create with no SKUs is BAD_REQUEST', async () => {
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
await expectTrpcError(
() =>
superadmin.superadmin.globalProducts.create.mutate({
name: `E2E GP no skus ${uniqueSuffix()}`,
storeId,
skus: [],
} as any),
'BAD_REQUEST'
)
})
it('SGPROD-07: a multi-SKU create seeds both SKUs', async () => {
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
const payload = {
name: `E2E GP multi ${uniqueSuffix()}`,
storeId,
productType: 'item',
skus: [skuUpdate(0, { id: undefined }), skuUpdate(0, { id: undefined, name: '2pc', price: 250 })],
} as any
const res: any = await superadmin.superadmin.globalProducts.create.mutate(payload)
const productId = Number(res.product?.id)
expect(productId).toBeGreaterThan(0)
const got: any = await superadmin.superadmin.globalProducts.get.query({ id: productId })
expect(got.product.skus).toHaveLength(2)
expect(got.product.skus.every((sku: any) => sku.marketStats.length > 0)).toBe(true)
})
it('SGPROD-16: a global create seeds every region past the D1 bind cap', async () => {
// 12 regions x 9 params used to exceed D1's 100-parameter limit.
await ensureAtLeastRegions(12)
const superadmin = await superadminClient()
const storeId = await createGlobalStore()
const res: any = await superadmin.superadmin.globalProducts.create.mutate({
name: `E2E GP chunked ${uniqueSuffix()}`,
shortDescription: 'SGPROD-16',
storeId,
productType: 'item',
skus: [skuUpdate(0, { id: undefined, price: 150 })],
} as any)
const got: any = await superadmin.superadmin.globalProducts.get.query({
id: Number(res.product.id),
})
expect(got.product.skus[0].marketStats.length).toBeGreaterThanOrEqual(12)
})
})
/* -------------------------------------------------------------------------- */
/* update */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalProducts.update (SGPROD-08..10)', () => {
it('SGPROD-08: update round-trips fields and preserves existing SKU ids', async () => {
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
const newName = `E2E GP updated ${uniqueSuffix()}`
const res: any = await superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: newName,
shortDescription: 'updated by SGPROD-08',
storeId: owned.storeId,
productType: 'item',
skus: [skuUpdate(owned.skuIds[0])],
})
expect(res.message).toBe('Global product updated successfully')
expect(Number(res.product.id)).toBe(owned.productId)
expect(res.product.name).toBe(newName)
expect(res.product.skus.map((sku: any) => Number(sku.id))).toEqual(owned.skuIds)
const fetched: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(fetched.product.name).toBe(newName)
expect(fetched.product.shortDescription).toBe('updated by SGPROD-08')
expect(fetched.product.skus.map((sku: any) => Number(sku.id))).toEqual(owned.skuIds)
})
it('SGPROD-09: updating an unknown product is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() =>
superadmin.superadmin.globalProducts.update.mutate({
id: 987_654_321,
name: `E2E GP unknown ${uniqueSuffix()}`,
storeId: 1,
productType: 'item',
skus: [skuUpdate(0, { id: undefined })],
} as any),
'NOT_FOUND'
)
})
it('SGPROD-10 (current): omitting a SKU leaves it; adding a SKU succeeds', async () => {
// updateProduct never deletes a SKU that is absent from `input.skus`; adding a
// new SKU seeds per-region market rows, which succeeds on the cleaned DB.
const superadmin = await superadminClient()
const owned = await makeGlobalProduct({ skuCount: 2 })
const omitted: any = await superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: owned.name,
storeId: owned.storeId,
productType: 'item',
skus: [skuUpdate(owned.skuIds[0])],
})
expect(omitted.message).toBe('Global product updated successfully')
const after: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(after.product.skus.map((sku: any) => Number(sku.id)).sort()).toEqual([...owned.skuIds].sort())
const addPayload = {
id: owned.productId,
name: owned.name,
storeId: owned.storeId,
productType: 'item',
skus: [
skuUpdate(owned.skuIds[0]),
skuUpdate(owned.skuIds[1]),
skuUpdate(0, { id: undefined, name: '3pc', price: 350 }),
],
} as any
const added: any = await superadmin.superadmin.globalProducts.update.mutate(addPayload)
expect(added.message).toBe('Global product updated successfully')
const afterAdd: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(afterAdd.product.skus).toHaveLength(owned.skuIds.length + 1)
})
it('SGPROD-10b (regression): an existing SKU updates without a price and keeps every region price', async () => {
// Finding #6: price is a create-time seed. The API returns it inside
// marketStats, so the form has no single price to resend for an existing SKU;
// the structural update must not require one or touch any region's row.
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
const before: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
const pricesBefore = before.product.skus[0].marketStats
.map((ms: any) => `${ms.regionId}:${String(ms.ourPrice)}`)
.sort()
const skuWithoutPrice = { ...skuUpdate(owned.skuIds[0]) } as any
delete skuWithoutPrice.price
const newName = `E2E GP price edit ${uniqueSuffix()}`
const res: any = await superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: newName,
storeId: owned.storeId,
productType: 'item',
skus: [skuWithoutPrice],
} as any)
expect(res.message).toBe('Global product updated successfully')
const after: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(after.product.name).toBe(newName)
expect(
after.product.skus[0].marketStats
.map((ms: any) => `${ms.regionId}:${String(ms.ourPrice)}`)
.sort()
).toEqual(pricesBefore)
})
it('SGPROD-10c: a NEW SKU still requires a price', async () => {
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
const newSkuWithoutPrice = { ...skuUpdate(0, { id: undefined, name: '2pc' }) } as any
delete newSkuWithoutPrice.price
await expectTrpcError(
() =>
superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: owned.name,
storeId: owned.storeId,
productType: 'item',
skus: [skuUpdate(owned.skuIds[0]), newSkuWithoutPrice],
} as any),
'BAD_REQUEST',
'price'
)
})
it('SGPROD-17: adding a SKU to a global product seeds every region', async () => {
await ensureAtLeastRegions(12)
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
await superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: owned.name,
storeId: owned.storeId,
productType: 'item',
skus: [
skuUpdate(owned.skuIds[0]),
skuUpdate(0, { id: undefined, name: '2pc', price: 250 }),
],
} as any)
const got: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
const added = got.product.skus.find((sku: any) => !owned.skuIds.includes(Number(sku.id)))
expect(added).toBeTruthy()
expect(added.marketStats.length).toBeGreaterThanOrEqual(12)
})
})
/* -------------------------------------------------------------------------- */
/* delete */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalProducts.delete (SGPROD-11..12)', () => {
it('(current) SGPROD-11: delete soft-deletes the SKUs and schedules a rebuild', async () => {
// The catalogue expects a hard delete. The reachable contract is a soft
// delete: the product_info row survives and every SKU is flagged isDeleted,
// so it is still returned by list/get (only the region caches drop it).
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
const res: any = await superadmin.superadmin.globalProducts.delete.mutate({ id: owned.productId })
expect(res.message).toBe('Global product deleted successfully')
const fetched: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(fetched.product.skus.every((sku: any) => sku.isDeleted === true)).toBe(true)
const list: any = await superadmin.superadmin.globalProducts.list.query()
expect(list.products.some((product: any) => Number(product.id) === owned.productId)).toBe(true)
})
it('SGPROD-11b (regression): delete keeps market rows so a restore is not priced at zero', async () => {
// Keep per-region pricing through a soft delete. Otherwise a restored global
// SKU has no market row in any region and the order path prices it at 0.
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
const before: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
const pricesBefore = before.product.skus[0].marketStats
.map((ms: any) => String(ms.ourPrice))
.sort()
expect(pricesBefore.length).toBeGreaterThan(0)
expect(pricesBefore.every((price: string) => Number(price) > 0)).toBe(true)
await superadmin.superadmin.globalProducts.delete.mutate({ id: owned.productId })
const deleted: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(deleted.product.skus[0].isDeleted).toBe(true)
expect(
deleted.product.skus[0].marketStats.map((ms: any) => String(ms.ourPrice)).sort()
).toEqual(pricesBefore)
await superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: owned.name,
storeId: owned.storeId,
productType: 'item',
skus: [skuUpdate(owned.skuIds[0], { isDeleted: false })],
} as any)
const restored: any = await superadmin.superadmin.globalProducts.get.query({ id: owned.productId })
expect(restored.product.skus[0].isDeleted).toBe(false)
expect(
restored.product.skus[0].marketStats.map((ms: any) => String(ms.ourPrice)).sort()
).toEqual(pricesBefore)
})
it('SGPROD-11c (regression): a structural suspension is blocked while a global combo is active', async () => {
// The superadmin kill-switch reaches every region, so an active global combo
// must be suspended first. Checkout validates the combo SKU, not components.
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
await superadmin.superadmin.globalProducts.create.mutate({
name: `E2E GP combo ${uniqueSuffix()}`,
storeId: owned.storeId,
productType: 'combo',
skus: [{
name: 'combo',
price: 500,
marketPrice: 600,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1 combo' }],
comboItems: [{ skuId: owned.skuIds[0] }],
}],
} as any)
await expectTrpcError(
() =>
superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: owned.name,
storeId: owned.storeId,
productType: 'item',
skus: [skuUpdate(owned.skuIds[0], { isSuspended: true })],
} as any),
'INTERNAL_SERVER_ERROR',
'combo'
)
})
it('SGPROD-12: deleting an unknown product is 404', async () => {
const superadmin = await superadminClient()
await expectTrpcError(
() => superadmin.superadmin.globalProducts.delete.mutate({ id: 987_654_321 }),
'NOT_FOUND'
)
})
})
/* -------------------------------------------------------------------------- */
/* cache + auth */
/* -------------------------------------------------------------------------- */
describe('superadmin.globalProducts cache + auth (SGPROD-13..15)', () => {
it('SGPROD-13: a global product is visible in a region cache after sync', async () => {
const owned = await makeGlobalProduct()
const { products } = await freshRegionProducts()
const found = products.find((product: any) => Number(product.id) === owned.skuIds[0])
expect(found).toEqual(
expect.objectContaining({
id: owned.skuIds[0],
storeId: owned.storeId,
})
)
})
it('SGPROD-14: anonymous, staff and user tokens are rejected', async () => {
const staff = await staffSession()
const user = await userSession()
const clients = [anonClient(), apiClient(staff.token), apiClient(user.token)]
for (const client of clients) {
await expectTrpcError(() => client.superadmin.globalProducts.list.query(), 'UNAUTHORIZED')
await expectTrpcError(
() => client.superadmin.globalProducts.get.query({ id: 1 }),
'UNAUTHORIZED'
)
await expectTrpcError(
() =>
client.superadmin.globalProducts.create.mutate({
name: 'denied',
storeId: 1,
skus: [skuUpdate(0, { id: undefined })],
} as any),
'UNAUTHORIZED'
)
await expectTrpcError(
() =>
client.superadmin.globalProducts.update.mutate({
id: 1,
name: 'denied',
storeId: 1,
skus: [skuUpdate(0, { id: undefined })],
} as any),
'UNAUTHORIZED'
)
await expectTrpcError(
() => client.superadmin.globalProducts.delete.mutate({ id: 1 }),
'UNAUTHORIZED'
)
}
})
it('(current) SGPROD-15: a global update/delete reaches a region cache (all-region rebuild not awaited)', async () => {
// A global write schedules a fire-and-forget rebuild of EVERY region through
// the CacheCreator DO (ALL_REGIONS_PENDING). That DO processes regions
// sequentially and stalls on this local DB, so the async version movement is
// not deterministically observable. The reachable contract is asserted
// instead: a freshly created region's cache already reflects the change.
const superadmin = await superadminClient()
const owned = await makeGlobalProduct()
const marker = `SGPROD-15 ${uniqueSuffix()}`
await superadmin.superadmin.globalProducts.update.mutate({
id: owned.productId,
name: owned.name,
shortDescription: marker,
storeId: owned.storeId,
productType: 'item',
skus: [skuUpdate(owned.skuIds[0])],
})
const afterUpdate = await freshRegionProducts()
const updated = afterUpdate.products.find((product: any) => Number(product.id) === owned.skuIds[0])
expect(updated?.shortDescription).toBe(marker)
await superadmin.superadmin.globalProducts.delete.mutate({ id: owned.productId })
const afterDelete = await freshRegionProducts()
expect(
afterDelete.products.some((product: any) => Number(product.id) === owned.skuIds[0])
).toBe(false)
})
})