freshyo/apps/backend/tests/api/user-product.test.ts
2026-10-20 00:31:05 +05:30

495 lines
18 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.

/**
* UPROD-01..24 — `user.product.*` (catalogue §6.12).
*
* `getProductDetails` / `getProductReviews` are `publicProcedure`; `createReview`
* is `protectedProcedure` (user token). Reviews are keyed by SKU id: the body
* sent as `productId` is the SKU id the picker exposes.
*
* Pinned `(current)`:
* - UPROD-04/05 — the handler throws a raw Error → INTERNAL_SERVER_ERROR, not
* a 404.
* - UPROD-08 — the "cache" is a live D1 read, so the DB fallback is unreachable
* through the public API.
* - UPROD-22 — one user may post multiple reviews.
* - UPROD-23 — review images come back as asset-domain URLs, not X-Amz-signed.
*/
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
import { anonClient, staffClient, superadminClient } from '../helpers/sessions'
import {
createFutureSlot,
createProduct,
createStore,
PASSWORD,
registerThrowawayUser,
} from '../helpers/fixtures'
import { getEssentialConsts } from '../helpers/cache'
import { TEST_OTHER_REGION_ID } from '../helpers/env'
jest.setTimeout(180_000)
const REGION_1 = 1
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_uprod_${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
}
let region2Promise: Promise<{ client: ApiClient; storeId: number }> | null = null
function region2(): Promise<{ client: ApiClient; storeId: number }> {
region2Promise ??= (async () => {
const client = apiClient(await createStaffToken(TEST_OTHER_REGION_ID))
const res: any = await client.admin.store.createStore.mutate({
name: `E2E R2 Store ${uniqueSuffix()}`,
})
return { client, storeId: Number(res.store.id) }
})()
return region2Promise
}
async function createProductVia(
client: ApiClient,
storeId: number,
price = 199
): Promise<{ productId: number; skuId: number }> {
const res: any = await client.admin.product.createProduct.mutate({
name: `E2E R2 Product ${uniqueSuffix()}`,
shortDescription: 'Created by backend API tests',
storeId,
productType: 'item',
skus: [
{
name: '1pc',
price,
marketPrice: price + 50,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
},
],
})
return { productId: Number(res.product.id), skuId: Number(res.product.skus[0].id) }
}
/** `getProductDetails` for a SKU (defaults to region 1). */
async function details(skuId: number, regionId: number = REGION_1): Promise<any> {
return anonClient().user.product.getProductDetails.query({ id: String(skuId), regionId })
}
/**
* `getProductReviews` for a product id.
*
* NOTE (observed gap): reviews are stored against `product_reviews.product_id`,
* which FKs `product_info.id` — so the review id space is the product id, not the
* SKU id `getProductDetails` exposes. `createReview` additionally runs a SKU
* existence check on the same value, which only passes when a SKU with that id
* also exists (true for the seeded/offset id ranges).
*/
async function reviews(
productId: number,
options: { limit?: number; offset?: number } = {}
): Promise<any> {
return anonClient().user.product.getProductReviews.query({
productId,
...options,
})
}
async function assetsDomain(): Promise<string> {
const consts = await getEssentialConsts()
return String(consts.assetsDomain).replace(/\/+$/, '')
}
/** A fresh reviewable product in region 1. */
async function freshProduct(
options: { price?: number; images?: string[] } = {}
): Promise<{ storeId: number; productId: number; skuId: number }> {
const store = await createStore()
const product = await createProduct({
storeId: store.storeId,
price: options.price ?? 199,
images: options.images ?? [],
})
return { storeId: store.storeId, productId: product.productId, skuId: product.skuId }
}
/* -------------------------------------------------------------------------- */
/* 6.12.1 getProductDetails */
/* -------------------------------------------------------------------------- */
describe('user.product.getProductDetails (UPROD-01..10)', () => {
it('UPROD-01: a numeric id + region returns the product detail', async () => {
const p = await freshProduct({ price: 499 })
const detail = await details(p.skuId)
expect(detail.id).toBe(p.skuId)
expect(detail.productId).toBe(p.productId)
expect(typeof detail.price).toBe('string')
expect(Array.isArray(detail.images)).toBe(true)
expect(Array.isArray(detail.deliverySlots)).toBe(true)
expect(detail.store.id).toBe(p.storeId)
})
it('UPROD-02: a non-numeric id is BAD_REQUEST', async () => {
await expectTrpcError(
() => anonClient().user.product.getProductDetails.query({ id: 'abc', regionId: REGION_1 }),
'BAD_REQUEST'
)
})
it('UPROD-03: a missing region is BAD_REQUEST', async () => {
await expectTrpcError(
() => anonClient().user.product.getProductDetails.query({ id: '1' } as any),
'BAD_REQUEST'
)
})
it('UPROD-04 (current): an unknown product throws a raw Error → 500', async () => {
// The handler throws `new Error('Product not found')`, which tRPC flattens to
// INTERNAL_SERVER_ERROR rather than a 404.
await expectTrpcError(
() => details(999_999_999),
'INTERNAL_SERVER_ERROR',
'Product not found'
)
})
it('UPROD-05 (current): a product owned by another region → 500, not served', async () => {
const r2 = await region2()
const foreign = await createProductVia(r2.client, r2.storeId)
await expectTrpcError(
() => details(foreign.skuId, REGION_1),
'INTERNAL_SERVER_ERROR',
'Product not found'
)
// It is served in its own region.
const own = await details(foreign.skuId, TEST_OTHER_REGION_ID)
expect(own.id).toBe(foreign.skuId)
})
it('UPROD-06: a global SKU is served in the requested region', async () => {
// NOTE (observed gap): `superadmin.globalProducts.create` currently 500s on
// this DB — it seeds one market-stats row per region in a single multi-row
// insert, and D1 caps a statement at 100 bound parameters (21 regions × 9 >
// 100). Global SKUs are therefore exercised from the seeded data.
const superadmin = await superadminClient()
const globals: any = await superadmin.superadmin.globalProducts.list.query()
const list = Array.isArray(globals) ? globals : globals.products ?? []
const withSku = list.find((p: any) => Array.isArray(p.skus) && p.skus.length > 0)
expect(withSku).toBeTruthy()
const skuId = Number(withSku.skus[0].id)
const region1 = await details(skuId, REGION_1)
expect(region1.id).toBe(skuId)
// Same global SKU resolves in another region too.
const region2 = await details(skuId, TEST_OTHER_REGION_ID)
expect(region2.id).toBe(skuId)
})
it('UPROD-07: a cache hit filters deliverySlots to future, non-full slots', async () => {
const p = await freshProduct()
const future = await createFutureSlot([p.skuId])
const stale = await createFutureSlot([p.skuId], { deliveryInHours: 5, freezeInHours: -1 })
const detail = await details(p.skuId)
const slotIds = detail.deliverySlots.map((s: any) => s.id)
expect(slotIds).toContain(future.slotId)
expect(slotIds).not.toContain(stale.slotId)
})
it('UPROD-08 (current): the DB fallback is unreachable; the read always serves the row', async () => {
// `getProductByIdFromCache` re-reads D1 on every call (the store is not an
// actual cache), so no product that the handler would accept is ever missing
// from it. The observable contract is a served detail with scaffolded images.
const admin = await staffClient()
const gen: any = await admin.common.generateUploadUrls.mutate({
contextString: 'product_info',
mimeTypes: ['image/png'],
})
const p = await freshProduct({ images: [gen.uploadUrls[0]] })
const domain = await assetsDomain()
const detail = await details(p.skuId)
expect(detail.id).toBe(p.skuId)
expect(detail.images).toHaveLength(1)
expect(detail.images[0]).toMatch(new RegExp(`^${domain}/product-images/`))
expect(detail.images.every((u: string) => !u.includes('X-Amz-'))).toBe(true)
})
it('UPROD-09: a product with no slots has an empty deliverySlots', async () => {
const p = await freshProduct()
const detail = await details(p.skuId)
expect(detail.deliverySlots).toEqual([])
})
it('UPROD-10: combo items, store and specialDeals are present per fixture', async () => {
const store = await createStore()
const base = await createProduct({ storeId: store.storeId })
const admin = await staffClient()
const combo: any = await admin.admin.product.createProduct.mutate({
name: `E2E Combo ${uniqueSuffix()}`,
shortDescription: 'Created by backend API tests',
storeId: store.storeId,
productType: 'combo',
skus: [
{
name: 'combo',
price: 500,
marketPrice: 600,
images: [],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: true,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1 combo' }],
comboItems: [{ skuId: base.skuId }],
},
],
})
const comboSkuId = Number(combo.product.skus[0].id)
const detail = await details(comboSkuId)
expect(detail.store.id).toBe(store.storeId)
expect(detail.productType).toBe('combo')
expect(Array.isArray(detail.comboItems)).toBe(true)
expect(detail.comboItems.some((c: any) => Number(c.skuId) === base.skuId)).toBe(true)
expect(Array.isArray(detail.specialDeals)).toBe(true)
})
})
/* -------------------------------------------------------------------------- */
/* 6.12.2 getProductReviews */
/* -------------------------------------------------------------------------- */
describe('user.product.getProductReviews (UPROD-11..14)', () => {
it('UPROD-11: pagination honours limit/offset and reports hasMore', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const client = apiClient(user.token)
for (let i = 0; i < 3; i++) {
await client.user.product.createReview.mutate({
productId: p.skuId,
reviewBody: `page review ${i} ${uniqueSuffix()}`,
ratings: 5,
})
}
const page1 = await reviews(p.productId, { limit: 2, offset: 0 })
expect(page1.reviews).toHaveLength(2)
expect(page1.hasMore).toBe(true)
const page2 = await reviews(p.productId, { limit: 2, offset: 2 })
expect(page2.reviews).toHaveLength(1)
expect(page2.hasMore).toBe(false)
})
it('UPROD-12: limit 0 / 51 is BAD_REQUEST', async () => {
const p = await freshProduct()
await expectTrpcError(
() => reviews(p.productId, { limit: 0 }),
'BAD_REQUEST'
)
await expectTrpcError(
() => reviews(p.productId, { limit: 51 }),
'BAD_REQUEST'
)
})
it('UPROD-13: a negative offset is BAD_REQUEST', async () => {
const p = await freshProduct()
await expectTrpcError(() => reviews(p.productId, { offset: -1 }), 'BAD_REQUEST')
})
it('UPROD-14: a product with no reviews returns [] and hasMore false', async () => {
const p = await freshProduct()
const res = await reviews(p.productId)
expect(res.reviews).toEqual([])
expect(res.hasMore).toBe(false)
})
})
/* -------------------------------------------------------------------------- */
/* 6.12.3 createReview */
/* -------------------------------------------------------------------------- */
describe('user.product.createReview (UPROD-15..24)', () => {
it('UPROD-15: a created review is visible in the list', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const created: any = await apiClient(user.token).user.product.createReview.mutate({
productId: p.skuId,
reviewBody: `visible ${uniqueSuffix()}`,
ratings: 4,
})
expect(created.success).toBe(true)
const list = await reviews(p.productId)
expect(list.reviews.some((r: any) => r.id === created.review.id)).toBe(true)
})
it('UPROD-16: a rating of 0 or 6 is BAD_REQUEST', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const client = apiClient(user.token)
await expectTrpcError(
() => client.user.product.createReview.mutate({ productId: p.skuId, reviewBody: 'x', ratings: 0 }),
'BAD_REQUEST'
)
await expectTrpcError(
() => client.user.product.createReview.mutate({ productId: p.skuId, reviewBody: 'x', ratings: 6 }),
'BAD_REQUEST'
)
})
it('UPROD-17: an empty review body is BAD_REQUEST', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const client = apiClient(user.token)
await expectTrpcError(
() => client.user.product.createReview.mutate({ productId: p.skuId, reviewBody: '', ratings: 4 }),
'BAD_REQUEST'
)
await expectTrpcError(
() => client.user.product.createReview.mutate({ productId: p.skuId, ratings: 4 } as any),
'BAD_REQUEST'
)
})
it('UPROD-18: an unknown product is 404', async () => {
const user = await registerThrowawayUser()
await expectTrpcError(
() =>
apiClient(user.token).user.product.createReview.mutate({
productId: 999_999_999,
reviewBody: 'nope',
ratings: 4,
}),
'NOT_FOUND'
)
})
it('UPROD-19: a claimed upload URL is stored and returned as a signed URL', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const client = apiClient(user.token)
const gen: any = await client.common.generateUploadUrls.mutate({
contextString: 'review',
mimeTypes: ['image/png'],
})
const uploadUrl = gen.uploadUrls[0]
const created: any = await client.user.product.createReview.mutate({
productId: p.skuId,
reviewBody: `with image ${uniqueSuffix()}`,
ratings: 5,
uploadUrls: [uploadUrl],
})
expect(created.success).toBe(true)
expect(created.review.imageUrls[0]).toContain('review-images/')
const list = await reviews(p.productId)
const stored = list.reviews.find((r: any) => r.id === created.review.id)
expect(stored.signedImageUrls).toHaveLength(1)
expect(stored.signedImageUrls[0]).toContain('review-images/')
})
it('UPROD-20 (current): an unknown upload URL is logged, the review is still created', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const created: any = await apiClient(user.token).user.product.createReview.mutate({
productId: p.skuId,
reviewBody: `lenient ${uniqueSuffix()}`,
ratings: 3,
uploadUrls: ['https://example.com/bogus/unknown.png'],
})
expect(created.success).toBe(true)
const list = await reviews(p.productId)
expect(list.reviews.some((r: any) => r.id === created.review.id)).toBe(true)
})
it('UPROD-21: createReview with no token is 401', async () => {
const p = await freshProduct()
await expectTrpcError(
() =>
anonClient().user.product.createReview.mutate({
productId: p.skuId,
reviewBody: 'anon',
ratings: 4,
}),
'UNAUTHORIZED'
)
})
it('UPROD-22 (current): one user may post multiple reviews for a product', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const client = apiClient(user.token)
const first: any = await client.user.product.createReview.mutate({
productId: p.skuId,
reviewBody: `first ${uniqueSuffix()}`,
ratings: 4,
})
const second: any = await client.user.product.createReview.mutate({
productId: p.skuId,
reviewBody: `second ${uniqueSuffix()}`,
ratings: 2,
})
expect(first.success).toBe(true)
expect(second.success).toBe(true)
expect(second.review.id).not.toBe(first.review.id)
})
it('UPROD-23 (current): review images come back as asset-domain URLs, not X-Amz-signed', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const client = apiClient(user.token)
const gen: any = await client.common.generateUploadUrls.mutate({
contextString: 'review',
mimeTypes: ['image/jpeg'],
})
const created: any = await client.user.product.createReview.mutate({
productId: p.skuId,
reviewBody: `signed ${uniqueSuffix()}`,
ratings: 5,
uploadUrls: [gen.uploadUrls[0]],
})
const domain = await assetsDomain()
const list = await reviews(p.productId)
const stored = list.reviews.find((r: any) => r.id === created.review.id)
expect(stored.signedImageUrls[0].startsWith(`${domain}/review-images/`)).toBe(true)
expect(stored.signedImageUrls[0]).not.toContain('X-Amz-')
})
it('UPROD-24 (current): an XSS review body is stored verbatim, never executed', async () => {
const p = await freshProduct()
const user = await registerThrowawayUser()
const body = `hello <script>alert('xss')</script> ${uniqueSuffix()}`
const created: any = await apiClient(user.token).user.product.createReview.mutate({
productId: p.skuId,
reviewBody: body,
ratings: 4,
})
const list = await reviews(p.productId)
const stored = list.reviews.find((r: any) => r.id === created.review.id)
// Round-trips as data over JSON — no HTML execution surface in the API.
expect(stored.reviewBody).toBe(body)
})
})