362 lines
14 KiB
TypeScript
362 lines
14 KiB
TypeScript
/**
|
||
* APROD-01..16 — `admin.product` reads (catalogue §7.4).
|
||
*
|
||
* Every read here is `protectedProcedure` scoped to `ctx.staffUser.regionId`
|
||
* and reads D1 directly (no cache layer), so fixtures appear immediately.
|
||
* `getProducts` / `getProductById` include global (`regionId === null`)
|
||
* products as well as the caller's own region.
|
||
*
|
||
* APROD-02 and APROD-04 are pinned `(current)`: globals are always unioned in
|
||
* (a fresh region is never `[]`), and "deleted" is a soft delete that hides the
|
||
* SKUs from `getProducts` while `getProductById` still returns them.
|
||
*/
|
||
|
||
import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api'
|
||
import { staffClient, superadminClient, userClient } from '../helpers/sessions'
|
||
import {
|
||
createProduct,
|
||
createRegion,
|
||
createStore,
|
||
registerThrowawayUser,
|
||
PASSWORD,
|
||
} from '../helpers/fixtures'
|
||
import { TEST_OTHER_REGION_ID } from '../helpers/env'
|
||
import { getEssentialConsts } from '../helpers/cache'
|
||
|
||
jest.setTimeout(300_000)
|
||
|
||
const assetDomain = async (): Promise<string> =>
|
||
String((await getEssentialConsts()).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_read_${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 client plus one store and one product, created once. */
|
||
let region2Promise: Promise<{ client: ApiClient; productId: number; skuId: number }> | null = null
|
||
function region2(): Promise<{ client: ApiClient; productId: number; skuId: number }> {
|
||
region2Promise ??= (async () => {
|
||
const client = apiClient(await createStaffToken(TEST_OTHER_REGION_ID))
|
||
const store: any = await client.admin.store.createStore.mutate({
|
||
name: `E2E R2 Store ${uniqueSuffix()}`,
|
||
})
|
||
const storeId = Number(store.store.id)
|
||
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: '1pc',
|
||
price: 199,
|
||
marketPrice: 249,
|
||
images: [],
|
||
isFlashAvailable: false,
|
||
flashPrice: null,
|
||
isOutOfStock: false,
|
||
isOffer: false,
|
||
isComboOnly: false,
|
||
isSuspended: false,
|
||
features: [{ featureName: 'quantity', featureValue: '1pc' }],
|
||
},
|
||
],
|
||
})
|
||
return {
|
||
client,
|
||
productId: Number(res.product.id),
|
||
skuId: Number(res.product.skus[0].id),
|
||
}
|
||
})()
|
||
return region2Promise
|
||
}
|
||
|
||
/** Create one review through the user API (image keys ride on `uploadUrls`). */
|
||
async function createReview(
|
||
userToken: string,
|
||
productId: number,
|
||
options: { reviewBody?: string; ratings?: number; uploadUrls?: string[] } = {}
|
||
): Promise<any> {
|
||
const client = apiClient(userToken)
|
||
const res: any = await client.user.product.createReview.mutate({
|
||
productId,
|
||
reviewBody: options.reviewBody ?? `E2E review ${uniqueSuffix()}`,
|
||
ratings: options.ratings ?? 5,
|
||
...(options.uploadUrls ? { uploadUrls: options.uploadUrls } : {}),
|
||
})
|
||
return res.review
|
||
}
|
||
|
||
describe('admin.product reads (APROD-01..08)', () => {
|
||
it('APROD-01: getProducts lists region products with their SKUs', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId, price: 259 })
|
||
|
||
const res: any = await admin.admin.product.getProducts.query()
|
||
expect(res.count).toBe(res.products.length)
|
||
|
||
const listed = res.products.find((p: any) => Number(p.id) === product.productId)
|
||
expect(listed).toBeTruthy()
|
||
expect(listed.name).toBe(product.productName)
|
||
expect(Number(listed.storeId)).toBe(store.storeId)
|
||
expect(listed.skus.map((s: any) => Number(s.id))).toContain(product.skuId)
|
||
})
|
||
|
||
it('APROD-02 (current): a fresh region lists only global products (never a guaranteed [])', async () => {
|
||
// `getAllProducts` unions `regionId = <region>` with `region_id IS NULL`, so a
|
||
// brand-new region is never empty when globals exist. The pinned contract is
|
||
// "globals only" — no other region's product leaks in.
|
||
const region = await createRegion()
|
||
const token = await createStaffToken(region.regionId)
|
||
|
||
const res: any = await apiClient(token).admin.product.getProducts.query()
|
||
expect(Array.isArray(res.products)).toBe(true)
|
||
expect(res.products.every((p: any) => p.isGlobal === true)).toBe(true)
|
||
})
|
||
|
||
it('APROD-03: SKU images come back as public asset URLs', async () => {
|
||
const admin = await staffClient()
|
||
const domain = await assetDomain()
|
||
const store = await createStore()
|
||
const gen: any = await admin.common.generateUploadUrls.mutate({
|
||
contextString: 'product_info',
|
||
mimeTypes: ['image/png'],
|
||
})
|
||
const product = await createProduct({ storeId: store.storeId, images: [gen.uploadUrls[0]] })
|
||
|
||
const res: any = await admin.admin.product.getProducts.query()
|
||
const sku = res.products
|
||
.flatMap((p: any) => p.skus)
|
||
.find((s: any) => Number(s.id) === product.skuId)
|
||
|
||
expect(sku.images).toHaveLength(1)
|
||
expect(sku.images[0]).toMatch(new RegExp(`^${domain}/product-images/`))
|
||
expect(sku.images[0]).not.toContain('X-Amz-')
|
||
})
|
||
|
||
it('APROD-04 (current): suspended products stay listed, soft-deleted ones are hidden', async () => {
|
||
// `getProducts` keeps any product with at least one non-deleted SKU, so a
|
||
// suspended product is still returned; `deleteProduct` soft-deletes (flags
|
||
// its SKUs). `getProductById` does NOT filter `isDeleted`, so it still reads.
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const suspended = await createProduct({ storeId: store.storeId, isSuspended: true })
|
||
const doomed = await createProduct({ storeId: store.storeId })
|
||
|
||
await admin.admin.product.deleteProduct.mutate({ id: doomed.productId })
|
||
|
||
const res: any = await admin.admin.product.getProducts.query()
|
||
const ids = res.products.map((p: any) => Number(p.id))
|
||
expect(ids).toContain(suspended.productId)
|
||
expect(ids).not.toContain(doomed.productId)
|
||
|
||
const read: any = await admin.admin.product.getProductById.query({ id: doomed.productId })
|
||
expect(read.product.skus.every((s: any) => s.isDeleted === true)).toBe(true)
|
||
})
|
||
|
||
it('APROD-05: getProductById returns the product with its SKUs', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId, price: 321 })
|
||
|
||
const res: any = await admin.admin.product.getProductById.query({ id: product.productId })
|
||
expect(Number(res.product.id)).toBe(product.productId)
|
||
expect(res.product.name).toBe(product.productName)
|
||
expect(res.product.store).toEqual(expect.objectContaining({ id: store.storeId }))
|
||
expect(res.product.skus.map((s: any) => Number(s.id))).toContain(product.skuId)
|
||
expect(res.product.skus[0].price).toBe('321')
|
||
})
|
||
|
||
it('APROD-06: an unknown product id is 404', async () => {
|
||
const admin = await staffClient()
|
||
await expectTrpcError(
|
||
() => admin.admin.product.getProductById.query({ id: 999_999_999 }),
|
||
'NOT_FOUND',
|
||
'Product not found'
|
||
)
|
||
})
|
||
|
||
it('APROD-07: another region’s product is 404', async () => {
|
||
const admin = await staffClient()
|
||
const other = await region2()
|
||
|
||
await expectTrpcError(
|
||
() => admin.admin.product.getProductById.query({ id: other.productId }),
|
||
'NOT_FOUND',
|
||
'Product not found'
|
||
)
|
||
})
|
||
|
||
it('APROD-08 (current): a user token passes the guard then 500s on staffUser', async () => {
|
||
// `getProductById` is `protectedProcedure`: a user token satisfies the guard,
|
||
// then `ctx.staffUser!.regionId` dereferences undefined → INTERNAL_SERVER_ERROR
|
||
// (§13 protectedProcedure gap).
|
||
const user = await userClient()
|
||
await expectTrpcError(
|
||
() => user.admin.product.getProductById.query({ id: 1 }),
|
||
'INTERNAL_SERVER_ERROR',
|
||
'regionId'
|
||
)
|
||
await expectTrpcError(
|
||
() => user.admin.product.getProducts.query(),
|
||
'INTERNAL_SERVER_ERROR',
|
||
'regionId'
|
||
)
|
||
})
|
||
})
|
||
|
||
describe('admin.product.getProductReviews (APROD-09..12)', () => {
|
||
it('APROD-09: getProductReviews paginates with hasMore', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId })
|
||
const user = await registerThrowawayUser()
|
||
await createReview(user.token, product.skuId, { ratings: 5 })
|
||
await createReview(user.token, product.skuId, { ratings: 4 })
|
||
|
||
const first: any = await admin.admin.product.getProductReviews.query({
|
||
productId: product.productId,
|
||
limit: 1,
|
||
offset: 0,
|
||
})
|
||
expect(first.reviews).toHaveLength(1)
|
||
expect(first.hasMore).toBe(true)
|
||
expect(first.reviews[0].id).toBeGreaterThan(0)
|
||
expect(first.reviews[0].userName).toBe(user.name)
|
||
|
||
const second: any = await admin.admin.product.getProductReviews.query({
|
||
productId: product.productId,
|
||
limit: 1,
|
||
offset: 1,
|
||
})
|
||
expect(second.reviews).toHaveLength(1)
|
||
expect(second.hasMore).toBe(false)
|
||
expect(second.reviews[0].id).not.toBe(first.reviews[0].id)
|
||
})
|
||
|
||
it('APROD-10: limit 0 and limit 51 are BAD_REQUEST', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId })
|
||
|
||
await expectTrpcError(
|
||
() => admin.admin.product.getProductReviews.query({ productId: product.productId, limit: 0 }),
|
||
'BAD_REQUEST'
|
||
)
|
||
await expectTrpcError(
|
||
() => admin.admin.product.getProductReviews.query({ productId: product.productId, limit: 51 }),
|
||
'BAD_REQUEST'
|
||
)
|
||
})
|
||
|
||
it('APROD-11: a product with no reviews returns []', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId })
|
||
|
||
const res: any = await admin.admin.product.getProductReviews.query({
|
||
productId: product.productId,
|
||
})
|
||
expect(res.reviews).toEqual([])
|
||
expect(res.hasMore).toBe(false)
|
||
})
|
||
|
||
it('APROD-12: review image keys are signed into asset URLs', async () => {
|
||
const admin = await staffClient()
|
||
const domain = await assetDomain()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId })
|
||
const user = await registerThrowawayUser()
|
||
const client = apiClient(user.token)
|
||
const gen: any = await client.common.generateUploadUrls.mutate({
|
||
contextString: 'review',
|
||
mimeTypes: ['image/png'],
|
||
})
|
||
|
||
await createReview(user.token, product.skuId, { uploadUrls: [gen.uploadUrls[0]] })
|
||
|
||
const res: any = await admin.admin.product.getProductReviews.query({
|
||
productId: product.productId,
|
||
})
|
||
expect(res.reviews[0].signedImageUrls).toHaveLength(1)
|
||
expect(res.reviews[0].signedImageUrls[0]).toMatch(new RegExp(`^${domain}/review-images/`))
|
||
expect(res.reviews[0].signedImageUrls[0]).not.toContain('X-Amz-')
|
||
})
|
||
})
|
||
|
||
describe('admin.product groups/tags reads (APROD-13..16)', () => {
|
||
it('APROD-13: getGroups returns groups with their SKUs', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId })
|
||
|
||
const created: any = await admin.admin.product.createGroup.mutate({
|
||
group_name: `E2E Group ${uniqueSuffix()}`,
|
||
description: 'Created by backend API tests',
|
||
product_ids: [product.skuId],
|
||
})
|
||
|
||
const res: any = await admin.admin.product.getGroups.query()
|
||
const group = res.groups.find((g: any) => Number(g.id) === Number(created.group.id))
|
||
expect(group).toBeTruthy()
|
||
expect(group.groupName).toBe(created.group.groupName)
|
||
expect(group.productCount).toBe(1)
|
||
expect(group.products.map((s: any) => Number(s.id))).toContain(product.skuId)
|
||
})
|
||
|
||
it('APROD-14: getProductTags returns tags plus a message', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId })
|
||
const tagName = `E2E Tag ${uniqueSuffix()}`
|
||
|
||
const created: any = await admin.admin.product.createProductTag.mutate({
|
||
tagName,
|
||
productIds: [product.skuId],
|
||
})
|
||
|
||
const res: any = await admin.admin.product.getProductTags.query()
|
||
expect(res.message).toBe('Tags retrieved successfully')
|
||
const listed = res.tags.find((t: any) => Number(t.id) === Number(created.tag.id))
|
||
expect(listed).toEqual(expect.objectContaining({ id: created.tag.id, tagName }))
|
||
})
|
||
|
||
it('APROD-15: getProductTagById returns tag, products and productIds', async () => {
|
||
const admin = await staffClient()
|
||
const store = await createStore()
|
||
const product = await createProduct({ storeId: store.storeId })
|
||
const tagName = `E2E Tag ${uniqueSuffix()}`
|
||
|
||
const created: any = await admin.admin.product.createProductTag.mutate({
|
||
tagName,
|
||
productIds: [product.skuId],
|
||
})
|
||
|
||
const res: any = await admin.admin.product.getProductTagById.query({ id: created.tag.id })
|
||
expect(res.message).toBe('Tag retrieved successfully')
|
||
expect(Number(res.tag.id)).toBe(Number(created.tag.id))
|
||
expect(res.tag.tagName).toBe(tagName)
|
||
expect(res.tag.productIds).toEqual([product.skuId])
|
||
expect(Number(res.tag.products[0].productId)).toBe(product.skuId)
|
||
expect(res.tag.products[0].product).toEqual(expect.objectContaining({ id: product.skuId }))
|
||
})
|
||
|
||
it('APROD-16: an unknown tag id is 404', async () => {
|
||
const admin = await staffClient()
|
||
await expectTrpcError(
|
||
() => admin.admin.product.getProductTagById.query({ id: 999_999_999 }),
|
||
'NOT_FOUND',
|
||
'Tag not found'
|
||
)
|
||
})
|
||
})
|