freshyo/apps/backend/tests/api/common-product.test.ts
2026-10-24 15:19:39 +05:30

475 lines
19 KiB
TypeScript
Raw 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.

/**
* COMMON-01..18 — `common.product.getAllProductsSummary` / `getAllSkusSummary`
* (catalogue §5.1/§5.2).
*
* Both reads are `protectedProcedure` scoped to `ctx.staffUser.regionId` and read
* D1 directly (no cache layer), so fixtures appear immediately. A user token
* passes the `protectedProcedure` guard but has no `staffUser`, so the handler
* dereferences null — pinned `(current)`.
*/
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
import { anonClient, staffClient, superadminClient } from '../helpers/sessions'
import { createProduct, createStore, PASSWORD } from '../helpers/fixtures'
import { getEssentialConsts } from '../helpers/cache'
import { TEST_OTHER_REGION_ID } from '../helpers/env'
jest.setTimeout(180_000)
const assetsDomain = () => getEssentialConsts().then((c) => String(c.assetsDomain).replace(/\/+$/, ''))
/** Create a staff admin in `regionId` (superadmin) and return a login token. */
async function createStaffToken(regionId: number): Promise<string> {
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_prod_${regionId}_${uniqueSuffix()}`
await superadmin.superadmin.staff.create.mutate({ name, password: PASSWORD, roleId, regionId })
const login: any = await apiClient().admin.staffUser.login.mutate({ name, password: PASSWORD })
if (!login?.token) throw new Error('[api-tests] region staff login returned no token')
return login.token
}
/** A region-2 staff + one store, created once and reused. */
let region2Promise: Promise<{ token: string; client: ApiClient; storeId: number }> | null = null
function region2(): Promise<{ token: string; client: ApiClient; storeId: number }> {
region2Promise ??= (async () => {
const token = await createStaffToken(TEST_OTHER_REGION_ID)
const client = apiClient(token)
const res: any = await client.admin.store.createStore.mutate({
name: `E2E R2 Store ${uniqueSuffix()}`,
})
return { token, client, storeId: Number(res.store.id) }
})()
return region2Promise
}
/** Create a one-SKU product through any region's staff client. */
async function createProductVia(
client: ApiClient,
storeId: number,
options: { price?: number; skuName?: string } = {}
): Promise<{ productId: number; skuId: number; name: string }> {
const price = options.price ?? 199
const name = `E2E R2 Product ${uniqueSuffix()}`
const res: any = await client.admin.product.createProduct.mutate({
name,
shortDescription: 'Created by backend API tests',
storeId,
productType: 'item',
skus: [
{
name: options.skuName ?? '1pc',
price,
marketPrice: price + 50,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: options.skuName ?? '1pc' }],
},
],
})
return { productId: Number(res.product.id), skuId: Number(res.product.skus[0].id), name }
}
/** A two-SKU product in the staff region (multi-SKU coverage). */
async function createMultiSkuProduct(
storeId: number
): Promise<{ productId: number; skuIds: number[]; name: string }> {
const admin = await staffClient()
const name = `E2E MultiSku ${uniqueSuffix()}`
const res: any = await admin.admin.product.createProduct.mutate({
name,
shortDescription: 'Created by backend API tests',
storeId,
productType: 'item',
skus: [
{
name: '1pc',
price: 150,
marketPrice: 170,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
},
{
name: '2pc',
price: 260,
marketPrice: 300,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '2pc' }],
},
],
})
return {
productId: Number(res.product.id),
skuIds: res.product.skus.map((s: any) => Number(s.id)),
name,
}
}
/** Ids of the global stores (products of a brand-new region surface globals). */
async function globalStoreIds(): Promise<Set<number>> {
const superadmin = await superadminClient()
const stores: any = await superadmin.superadmin.globalStores.list.query()
const list = Array.isArray(stores) ? stores : stores.stores ?? []
return new Set(list.map((s: any) => Number(s.id)))
}
/* -------------------------------------------------------------------------- */
/* 5.1 getAllProductsSummary */
/* -------------------------------------------------------------------------- */
describe('common.product.getAllProductsSummary (COMMON-01..10)', () => {
it('COMMON-01: staff call returns the staff region’s SKUs and excludes region 2', async () => {
const admin = await staffClient()
const store = await createStore()
const local = await createProduct({ storeId: store.storeId, price: 321 })
const r2 = await region2()
const foreign = await createProductVia(r2.client, r2.storeId)
const summary: any = await admin.common.product.getAllProductsSummary.query()
expect(summary.count).toBe(summary.products.length)
expect(summary.products.some((p: any) => p.id === local.skuId)).toBe(true)
expect(summary.products.some((p: any) => p.id === foreign.skuId)).toBe(false)
})
it('COMMON-02 (current): a region with no own products still surfaces global SKUs', async () => {
// Global products (region_id NULL) are visible in every region, so a fresh
// region is never `{products:[]}`; the pinned contract is that no regional
// product leaks in (every store is global or null).
const { createRegion } = await import('../helpers/fixtures')
const region = await createRegion()
const token = await createStaffToken(region.regionId)
const localStore = await createStore()
const local = await createProduct({ storeId: localStore.storeId })
const summary: any = await apiClient(token).common.product.getAllProductsSummary.query()
expect(summary.count).toBe(summary.products.length)
const globals = await globalStoreIds()
expect(summary.products.every((p: any) => p.storeId == null || globals.has(p.storeId))).toBe(true)
expect(summary.products.some((p: any) => p.id === local.skuId)).toBe(false)
})
it('COMMON-03: a suspended SKU is filtered out of the summary', async () => {
const admin = await staffClient()
const store = await createStore()
const visible = await createProduct({ storeId: store.storeId })
const suspended = await createProduct({ storeId: store.storeId, isSuspended: true })
const summary: any = await admin.common.product.getAllProductsSummary.query()
expect(summary.products.some((p: any) => p.id === visible.skuId)).toBe(true)
expect(summary.products.some((p: any) => p.id === suspended.skuId)).toBe(false)
})
it('COMMON-04: tags are ordered by the region’s tagsOrder constant', async () => {
const admin = await staffClient()
// tagsOrder is region-scoped; read it back the same way the handler does.
const constants: any = await admin.admin.region.getRegionConstants.query()
const rows = Array.isArray(constants) ? constants : []
const tagsOrderRaw = rows.find((row: any) => row.key === 'tagsOrder')?.value
const tagsOrderIds = String(tagsOrderRaw ?? '')
.split(',')
.map((id: string) => parseInt(id.trim(), 10))
.filter((id: number) => !Number.isNaN(id))
const summary: any = await admin.common.product.getAllProductsSummary.query()
const returnedIds = summary.tags.map((t: any) => Number(t.id))
const expectedPrefix = tagsOrderIds.filter((id: number) => returnedIds.includes(id))
expect(returnedIds.slice(0, expectedPrefix.length)).toEqual(expectedPrefix)
// Every tag listed in tagsOrder appears before every tag that is not.
const rest = returnedIds.slice(expectedPrefix.length)
expect(rest.some((id: number) => tagsOrderIds.includes(id))).toBe(false)
})
it('COMMON-05: a tag’s productIds follow the supplied sortOrder (productIds)', async () => {
const admin = await staffClient()
const store = await createStore()
const a = await createProduct({ storeId: store.storeId })
const b = await createProduct({ storeId: store.storeId })
const tagName = `E2E TagOrder ${uniqueSuffix()}`
// createProductTag stores `sortOrder = productIds`, so the returned order is
// exactly the order the admin supplied.
const created: any = await admin.admin.product.createProductTag.mutate({
tagName,
productIds: [b.skuId, a.skuId],
})
const summary: any = await admin.common.product.getAllProductsSummary.query()
const tag = summary.tags.find((t: any) => Number(t.id) === Number(created.tag.id))
expect(tag).toBeTruthy()
expect(tag.productIds).toEqual([b.skuId, a.skuId])
})
it('COMMON-06: image keys are exposed as public asset URLs', async () => {
const admin = await staffClient()
const domain = await assetsDomain()
const store = await createStore()
// Images must come from a claimed upload URL, so request one first.
const gen: any = await admin.common.generateUploadUrls.mutate({
contextString: 'product_info',
mimeTypes: ['image/png'],
})
const p = await createProduct({ storeId: store.storeId, images: [gen.uploadUrls[0]] })
const summary: any = await admin.common.product.getAllProductsSummary.query()
const entry = summary.products.find((x: any) => x.id === p.skuId)
expect(entry.images).toHaveLength(1)
expect(entry.images[0]).toMatch(new RegExp(`^${domain}/product-images/`))
expect(entry.images[0].endsWith('.png')).toBe(true)
expect(entry.images[0]).not.toContain('X-Amz-')
})
it('COMMON-07 (current): a user token passes the guard but null staffUser → 500', async () => {
const user = await apiClient(
(await (await import('../helpers/sessions')).userSession()).token
)
await expectTrpcError(
() => user.common.product.getAllProductsSummary.query(),
'INTERNAL_SERVER_ERROR',
'regionId'
)
})
it('COMMON-08: no token is 401', async () => {
await expectTrpcError(
() => anonClient().common.product.getAllProductsSummary.query(),
'UNAUTHORIZED'
)
})
it('COMMON-09: other-region staff sees only its own region', async () => {
const r2 = await region2()
const localStore = await createStore()
const local = await createProduct({ storeId: localStore.storeId })
const foreign = await createProductVia(r2.client, r2.storeId)
const r2Summary: any = await r2.client.common.product.getAllProductsSummary.query()
expect(r2Summary.products.some((p: any) => p.id === foreign.skuId)).toBe(true)
expect(r2Summary.products.some((p: any) => p.id === local.skuId)).toBe(false)
})
it('COMMON-10: each SKU of a multi-SKU product is its own entry', async () => {
const admin = await staffClient()
const store = await createStore()
const multi = await createMultiSkuProduct(store.storeId)
const summary: any = await admin.common.product.getAllProductsSummary.query()
const ids = new Set(summary.products.map((p: any) => p.id))
expect(ids.has(multi.skuIds[0])).toBe(true)
expect(ids.has(multi.skuIds[1])).toBe(true)
const entries = summary.products.filter((p: any) => multi.skuIds.includes(p.id))
expect(entries).toHaveLength(2)
})
})
/* -------------------------------------------------------------------------- */
/* 5.2 getAllSkusSummary */
/* -------------------------------------------------------------------------- */
/** A region-1 product elevated to a fresh global store, plus a region-2 staff. */
async function setupGlobalSku(): Promise<{
admin: ApiClient
r2: Awaited<ReturnType<typeof region2>>
product: Awaited<ReturnType<typeof createProduct>>
globalStoreId: number
}> {
const admin = await staffClient()
const superadmin = await superadminClient()
const store = await createStore()
const product = await createProduct({ storeId: store.storeId, price: 222 })
const created: any = await superadmin.superadmin.globalStores.create.mutate({
name: `E2E Global Store ${uniqueSuffix()}`,
description: 'COMMON global fixture',
})
const globalStoreId = Number(created.store.id)
await superadmin.superadmin.products.elevate.mutate({
productId: product.productId,
storeId: globalStoreId,
})
return { admin, r2: await region2(), product, globalStoreId }
}
/**
* A market-data-only update for the elevated global product. A regional admin
* cannot change structural fields, so they must match the stored row.
*/
function globalMarketUpdate(args: {
productId: number
productName: string
skuId: number
globalStoreId: number
price?: number
isSuspendedInRegion?: boolean
}) {
const price = args.price ?? 222
return {
id: args.productId,
name: args.productName,
shortDescription: 'Created by backend API tests',
storeId: args.globalStoreId,
incrementStep: 1,
productType: 'item' as const,
skus: [{
id: args.skuId,
name: '1pc',
price,
marketPrice: price + 50,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isDeleted: false,
isSuspended: false,
isSuspendedInRegion: args.isSuspendedInRegion ?? false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
comboItems: [],
}],
deletedImageKeys: [],
newImageUrls: [],
}
}
describe('common.product.getAllSkusSummary (COMMON-11..18)', () => {
it('COMMON-11 (current): staff call returns id/name/price/images/label per SKU', async () => {
const admin = await staffClient()
const store = await createStore()
const p = await createProduct({ storeId: store.storeId, price: 222, skuName: '1pc' })
const res: any = await admin.common.product.getAllSkusSummary.query()
const sku = res.skus.find((s: any) => s.id === p.skuId)
expect(sku).toEqual(
expect.objectContaining({
id: p.skuId,
productId: p.productId,
productName: p.productName,
price: '222',
storeId: store.storeId,
})
)
expect(Array.isArray(sku.images)).toBe(true)
expect(typeof sku.label).toBe('string')
// The catalogue expects `unit`/`features`; the picker returns neither.
expect(sku.unit).toBeUndefined()
expect(sku.features).toBeUndefined()
})
it('COMMON-12 (current): a region with no own SKUs still surfaces global SKUs', async () => {
const { createRegion } = await import('../helpers/fixtures')
const region = await createRegion()
const token = await createStaffToken(region.regionId)
const localStore = await createStore()
const local = await createProduct({ storeId: localStore.storeId })
const res: any = await apiClient(token).common.product.getAllSkusSummary.query()
const globals = await globalStoreIds()
expect(res.skus.every((s: any) => s.storeId == null || globals.has(s.storeId))).toBe(true)
expect(res.skus.some((s: any) => s.id === local.skuId)).toBe(false)
})
it('COMMON-13 (current): out-of-stock is kept; a suspended SKU is filtered', async () => {
const admin = await staffClient()
const store = await createStore()
const outOfStock = await createProduct({ storeId: store.storeId, isOutOfStock: true })
const suspended = await createProduct({ storeId: store.storeId, isSuspended: true })
const res: any = await admin.common.product.getAllSkusSummary.query()
expect(res.skus.some((s: any) => s.id === outOfStock.skuId)).toBe(true)
expect(res.skus.some((s: any) => s.id === suspended.skuId)).toBe(false)
})
it('COMMON-14: every SKU of a multi-SKU product is present', async () => {
const admin = await staffClient()
const store = await createStore()
const multi = await createMultiSkuProduct(store.storeId)
const res: any = await admin.common.product.getAllSkusSummary.query()
const ids = new Set(res.skus.map((s: any) => s.id))
expect(ids.has(multi.skuIds[0])).toBe(true)
expect(ids.has(multi.skuIds[1])).toBe(true)
})
it('COMMON-15: region isolation — no foreign SKU leaks in', async () => {
const r2 = await region2()
const localStore = await createStore()
const local = await createProduct({ storeId: localStore.storeId })
const foreign = await createProductVia(r2.client, r2.storeId)
const r2Summary: any = await r2.client.common.product.getAllSkusSummary.query()
expect(r2Summary.skus.some((s: any) => s.id === foreign.skuId)).toBe(true)
expect(r2Summary.skus.some((s: any) => s.id === local.skuId)).toBe(false)
})
it('COMMON-16: no token is 401', async () => {
await expectTrpcError(
() => anonClient().common.product.getAllSkusSummary.query(),
'UNAUTHORIZED'
)
})
it("COMMON-17: a global SKU uses the caller region's price, not ₹0", async () => {
const { admin, r2, product, globalStoreId } = await setupGlobalSku()
// Region 2 sets its own market price for the global SKU.
await r2.client.admin.product.updateProduct.mutate(
globalMarketUpdate({
productId: product.productId,
productName: product.productName,
skuId: product.skuId,
globalStoreId,
price: 333,
}) as any
)
const r1: any = await admin.common.product.getAllSkusSummary.query()
const r2Summary: any = await r2.client.common.product.getAllSkusSummary.query()
expect(r1.skus.find((s: any) => s.id === product.skuId)?.price).toBe('222')
expect(r2Summary.skus.find((s: any) => s.id === product.skuId)?.price).toBe('333')
})
it('COMMON-18: a global SKU suspended in one region is hidden there only', async () => {
const { admin, r2, product, globalStoreId } = await setupGlobalSku()
await r2.client.admin.product.updateProduct.mutate(
globalMarketUpdate({
productId: product.productId,
productName: product.productName,
skuId: product.skuId,
globalStoreId,
isSuspendedInRegion: true,
}) as any
)
const r1: any = await admin.common.product.getAllSkusSummary.query()
const r2Summary: any = await r2.client.common.product.getAllSkusSummary.query()
expect(r1.skus.some((s: any) => s.id === product.skuId)).toBe(true)
expect(r2Summary.skus.some((s: any) => s.id === product.skuId)).toBe(false)
})
})