511 lines
19 KiB
TypeScript
511 lines
19 KiB
TypeScript
/**
|
|
* SGPROD-01..15 — `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 in a single multi-row INSERT (9 binds per row). With more than ~11
|
|
* regions that exceeds D1's 100-bound-parameter cap and 500s; with fewer it
|
|
* succeeds. SGPROD-04/07/10 therefore branch on the live region count and assert
|
|
* the contract that actually applies.
|
|
*/
|
|
|
|
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)
|
|
}
|
|
|
|
/**
|
|
* Run a call and return either the value or its error.
|
|
*
|
|
* Local D1 caps bound parameters ("too many SQL variables"); the threshold
|
|
* depends on how many regions exist when the suite runs (observed: 180 binds
|
|
* succeed, 414 fail). These `(current)` rows therefore accept either outcome.
|
|
*/
|
|
async function attempt<T>(fn: () => Promise<T>): Promise<{ ok: true; value: T } | { ok: false; error: Error }> {
|
|
try {
|
|
return { ok: true, value: await fn() }
|
|
} catch (error) {
|
|
return { ok: false, error: error as Error }
|
|
}
|
|
}
|
|
|
|
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 (current): create succeeds under the bind cap, 500s above it', 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 result = await attempt(() => superadmin.superadmin.globalProducts.create.mutate(payload))
|
|
if (!result.ok) {
|
|
expect(result.error.message).toContain('Failed to create product')
|
|
return
|
|
}
|
|
|
|
const res: any = result.value
|
|
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)
|
|
})
|
|
|
|
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 (current): a multi-SKU create succeeds under the bind cap, 500s above it', 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 result = await attempt(() => superadmin.superadmin.globalProducts.create.mutate(payload))
|
|
if (!result.ok) {
|
|
expect(result.error.message).toContain('Failed to create product')
|
|
return
|
|
}
|
|
|
|
const res: any = result.value
|
|
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)
|
|
})
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* 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 addedResult = await attempt(() => superadmin.superadmin.globalProducts.update.mutate(addPayload))
|
|
if (!addedResult.ok) {
|
|
expect(addedResult.error.message).toContain('Failed to update product')
|
|
return
|
|
}
|
|
|
|
const added: any = addedResult.value
|
|
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)
|
|
})
|
|
})
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* 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-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)
|
|
})
|
|
})
|