/** * APROD-17..55 — `admin.product` create/update/delete + stock + prices * (catalogue §7.4). * * Fixtures are created through the live API; nothing seeded is deleted. Upload * URLs come from `common.generateUploadUrls` (they insert a pending * `upload_url_status` row), and the claim happens inside the product write — * so a fabricated or re-used URL is rejected with 400 before anything is * written. Uploading the bytes themselves is not required for the claim. * * Cache rows (APROD-33/42/55): `availability` is bumped synchronously inside * the mutation; `products` is rebuilt asynchronously by the CacheCreator DO, so * those poll `products.json`. */ import { apiClient, expectTrpcError, uniqueSuffix, type ApiClient } from '../helpers/api' import { staffClient, superadminClient } from '../helpers/sessions' import { createProduct, createStore } from '../helpers/fixtures' import { getEssentialConsts, scaffoldCache } from '../helpers/cache' import { TEST_REGION_ID } from '../helpers/env' jest.setTimeout(300_000) const assetDomain = async (): Promise => String((await getEssentialConsts()).assetsDomain).replace(/\/+$/, '') const keyFromUrl = (url: string): string => decodeURIComponent(url.split('?')[0].split('/').filter(Boolean).slice(-2).join('/')) /** Region const value (D1-backed `admin.region.getRegionConstants`). */ async function regionConst(admin: ApiClient, key: string): Promise { const rows: any = await admin.admin.region.getRegionConstants.query() const row = rows.find((entry: any) => entry.key === key) return Number(row?.value ?? 0) } /** * The products document from the scaffold function (test route). * Same object the cache writer serialises, straight from D1. */ async function pollProductsCache( _admin: ApiClient, _baseline: number, predicate: (doc: any) => boolean, label: string ): Promise { const doc = await scaffoldCache('products', { regionId: TEST_REGION_ID }) if (!predicate(doc)) throw new Error(`[api-tests] products document did not satisfy: ${label}`) return doc } function skuInput(overrides: Record = {}): any { const name = overrides.name ?? '1pc' return { name, price: overrides.price ?? 199, marketPrice: overrides.marketPrice === undefined ? 249 : overrides.marketPrice, images: overrides.images ?? [], isFlashAvailable: overrides.isFlashAvailable ?? false, flashPrice: overrides.flashPrice ?? null, isOutOfStock: overrides.isOutOfStock ?? false, isOffer: overrides.isOffer ?? false, isComboOnly: overrides.isComboOnly ?? false, isDeleted: overrides.isDeleted ?? false, isSuspended: overrides.isSuspended ?? false, ...(overrides.isSuspendedInRegion !== undefined ? { isSuspendedInRegion: overrides.isSuspendedInRegion } : {}), features: overrides.features ?? [{ featureName: 'quantity', featureValue: name }], ...(overrides.comboItems ? { comboItems: overrides.comboItems } : {}), ...(overrides.id !== undefined ? { id: overrides.id } : {}), } } async function rawCreate( admin: ApiClient, body: { storeId: number; name?: string; productType?: 'item' | 'combo'; skus: any[] } ): Promise { const res: any = await admin.admin.product.createProduct.mutate({ name: body.name ?? `E2E Product ${uniqueSuffix()}`, shortDescription: 'Created by backend API tests', storeId: body.storeId, productType: body.productType ?? 'item', skus: body.skus, } as any) return res } async function readProduct(admin: ApiClient, id: number): Promise { const res: any = await admin.admin.product.getProductById.query({ id }) return res.product } /** Create one product with a fixed number of SKUs and return ids. */ async function createMultiSku( admin: ApiClient, storeId: number, count: number, price = 199 ): Promise<{ productId: number; skuIds: number[] }> { const skus = Array.from({ length: count }, (_, i) => skuInput({ name: `${i + 1}pc`, price: price + i, marketPrice: price + i + 50 }) ) const res: any = await rawCreate(admin, { storeId, skus }) return { productId: Number(res.product.id), skuIds: res.product.skus.map((s: any) => Number(s.id)), } } /** * Elevate a regional product to a global store (superadmin), returning the store * the product now belongs to. Used by the regional-market-update guard cases. */ async function elevateToGlobal( admin: ApiClient, storeId: number, skus: any[] ): Promise<{ productId: number; skuIds: number[]; storeId: number }> { const created: any = await rawCreate(admin, { storeId, skus }) const productId = Number(created.product.id) const superadmin = await superadminClient() const globalStore: any = await superadmin.superadmin.globalStores.create.mutate({ name: `E2E GP store ${uniqueSuffix()}`, description: 'Global-product fixture', }) const globalStoreId = Number(globalStore.store.id) await superadmin.superadmin.products.elevate.mutate({ productId, storeId: globalStoreId }) return { productId, skuIds: created.product.skus.map((s: any) => Number(s.id)), storeId: globalStoreId, } } describe('admin.product.createProduct (APROD-17..33)', () => { it('APROD-17: createProduct returns product/SKU ids, feature quantity and images', 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 name = `E2E Product ${uniqueSuffix()}` const res: any = await rawCreate(admin, { storeId: store.storeId, name, skus: [skuInput({ price: 345, images: [gen.uploadUrls[0]] })], }) expect(res.message).toBe('Product created successfully') expect(Number(res.product.id)).toBeGreaterThan(0) expect(Number(res.product.skus[0].id)).toBeGreaterThan(0) expect(res.product.name).toBe(name) expect(res.product.skus[0].features[0].featureName).toBe('quantity') expect(res.product.skus[0].features[0].featureValue).toBe('1pc') expect(res.product.skus[0].images[0]).toMatch(new RegExp(`^${domain}/product-images/`)) }) it('APROD-18: a duplicate product name is 400', async () => { const admin = await staffClient() const store = await createStore() const name = `E2E Dup ${uniqueSuffix()}` await rawCreate(admin, { storeId: store.storeId, name, skus: [skuInput()] }) await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, name, skus: [skuInput()] }), 'BAD_REQUEST', 'already exists' ) }) it('APROD-19: an empty name is BAD_REQUEST', async () => { const admin = await staffClient() const store = await createStore() await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, name: '', skus: [skuInput()] }), 'BAD_REQUEST' ) }) it('APROD-20: storeId 0 or missing is BAD_REQUEST', async () => { const admin = await staffClient() await expectTrpcError( () => rawCreate(admin, { storeId: 0, skus: [skuInput()] }), 'BAD_REQUEST' ) await expectTrpcError( () => admin.admin.product.createProduct.mutate({ name: `No store ${uniqueSuffix()}`, skus: [skuInput()] } as any), 'BAD_REQUEST' ) }) it('APROD-21: an empty SKU list is BAD_REQUEST', async () => { const admin = await staffClient() const store = await createStore() await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, skus: [] }), 'BAD_REQUEST' ) }) it('APROD-22: a zero or negative price is BAD_REQUEST', async () => { const admin = await staffClient() const store = await createStore() await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: 0 })] }), 'BAD_REQUEST' ) await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: -5 })] }), 'BAD_REQUEST' ) }) it('APROD-23: a SKU with no features is BAD_REQUEST', async () => { const admin = await staffClient() const store = await createStore() await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ features: [] })] }), 'BAD_REQUEST' ) }) it('APROD-24: an empty feature value is BAD_REQUEST', async () => { const admin = await staffClient() const store = await createStore() await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ features: [{ featureName: 'quantity', featureValue: '' }] })], }), 'BAD_REQUEST' ) }) it('APROD-25: multiple SKUs are all created', async () => { const admin = await staffClient() const store = await createStore() const { productId, skuIds } = await createMultiSku(admin, store.storeId, 3) expect(skuIds).toHaveLength(3) expect(new Set(skuIds).size).toBe(3) const read = await readProduct(admin, productId) expect(read.skus.map((s: any) => Number(s.id)).sort()).toEqual([...skuIds].sort()) }) it('APROD-26: a combo product stores its combo items', async () => { const admin = await staffClient() const store = await createStore() const base = await createProduct({ storeId: store.storeId }) const res: any = await rawCreate(admin, { storeId: store.storeId, productType: 'combo', skus: [skuInput({ comboItems: [{ skuId: base.skuId }] })], }) const read = await readProduct(admin, Number(res.product.id)) expect(read.productType).toBe('combo') expect(read.skus[0].comboItems.map((ci: any) => Number(ci.skuId))).toEqual([base.skuId]) }) it('APROD-27: flash fields are stored', async () => { const admin = await staffClient() const store = await createStore() const res: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ isFlashAvailable: true, flashPrice: 88 })], }) const read = await readProduct(admin, Number(res.product.id)) expect(read.skus[0].isFlashAvailable).toBe(true) expect(read.skus[0].flashPrice).toBe('88') }) it('APROD-28: marketPrice null is stored as null', async () => { const admin = await staffClient() const store = await createStore() const res: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ marketPrice: null })], }) const read = await readProduct(admin, Number(res.product.id)) expect(read.skus[0].marketPrice).toBeNull() }) it('APROD-29: a claimed upload URL is stored as an object key', 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 key = keyFromUrl(gen.uploadUrls[0]) const res: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ images: [gen.uploadUrls[0]] })], }) const read = await readProduct(admin, Number(res.product.id)) expect(read.skus[0].imageKeys).toEqual([key]) expect(read.skus[0].images).toEqual([`${domain}/${key}`]) }) it('APROD-30: a fabricated or re-used image key is rejected before writing', 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 url = gen.uploadUrls[0] // Claim it once. const nameA = `E2E Claim A ${uniqueSuffix()}` await rawCreate(admin, { storeId: store.storeId, name: nameA, skus: [skuInput({ images: [url] })] }) // Re-using the now-claimed URL is rejected. const nameB = `E2E Claim B ${uniqueSuffix()}` await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, name: nameB, skus: [skuInput({ images: [url] })] }), 'BAD_REQUEST', 'not uploaded through the app' ) // A URL that was never issued is rejected too. const nameC = `E2E Claim C ${uniqueSuffix()}` await expectTrpcError( () => rawCreate(admin, { storeId: store.storeId, name: nameC, skus: [skuInput({ images: [`${domain}product-images/never-${uniqueSuffix()}.png`] })], }), 'BAD_REQUEST', 'not uploaded through the app' ) // Neither rejected create left a product behind. const list: any = await admin.admin.product.getProducts.query() const names = list.products.map((p: any) => p.name) expect(names).not.toContain(nameB) expect(names).not.toContain(nameC) }) it('APROD-31: no images is stored as an empty array', async () => { const admin = await staffClient() const store = await createStore() const res: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput()] }) const read = await readProduct(admin, Number(res.product.id)) expect(read.skus[0].images).toEqual([]) }) it('APROD-32 (current): duplicate SKU names are accepted', async () => { // There is no unique constraint on SKU names; both variants are written. const admin = await staffClient() const store = await createStore() const res: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ name: '1pc' }), skuInput({ name: '1pc', price: 210 })], }) const names = res.product.skus.map((s: any) => s.name) expect(names).toEqual(['1pc', '1pc']) expect(new Set(res.product.skus.map((s: any) => Number(s.id))).size).toBe(2) }) it('APROD-33: creating a product schedules a products cache rebuild', async () => { const admin = await staffClient() const baseline = await regionConst(admin, 'products_version_num') const store = await createStore() const res: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: 456 })] }) const productId = Number(res.product.id) const skuId = Number(res.product.skus[0].id) // products.json is SKU-keyed: `id` is the SKU id (there is no productId), // and `name` is the composed SKU name. const doc = await pollProductsCache( admin, baseline, (d) => (d.products ?? []).some((p: any) => Number(p.id) === skuId), `products.json contains SKU ${skuId}` ) const listed = doc.products.find((p: any) => Number(p.id) === skuId) expect(Number(listed.storeId)).toBe(store.storeId) expect(Number(listed.price)).toBe(456) }) it('APROD-82: a regional create marks suspension on the region flag', async () => { const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ isSuspended: true })], }) const read = await readProduct(admin, Number(created.product.id)) expect(read.skus[0].isSuspended).toBe(false) expect(read.skus[0].isSuspendedInRegion).toBe(true) }) }) describe('admin.product.updateProduct (APROD-34..42)', () => { it('APROD-34: updateProduct round-trips fields and SKUs', async () => { const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: 100 })] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) const newName = `E2E Updated ${uniqueSuffix()}` const res: any = await admin.admin.product.updateProduct.mutate({ id: productId, name: newName, shortDescription: 'Updated description', storeId: store.storeId, skus: [skuInput({ id: skuId, price: 250 })], }) expect(res.message).toBe('Product updated successfully') const read = await readProduct(admin, productId) expect(read.name).toBe(newName) expect(read.shortDescription).toBe('Updated description') expect(read.skus[0].price).toBe('250') }) it('APROD-35: updating an unknown product is 404', async () => { const admin = await staffClient() const store = await createStore() await expectTrpcError( () => admin.admin.product.updateProduct.mutate({ id: 999_999_999, name: `Ghost ${uniqueSuffix()}`, storeId: store.storeId, skus: [skuInput()], }), 'NOT_FOUND', 'Product not found' ) }) it('APROD-36: an empty name or an invalid price is BAD_REQUEST', async () => { const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput()] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) await expectTrpcError( () => admin.admin.product.updateProduct.mutate({ id: productId, name: '', storeId: store.storeId, skus: [skuInput({ id: skuId })], }), 'BAD_REQUEST' ) await expectTrpcError( () => admin.admin.product.updateProduct.mutate({ id: productId, name: `E2E ${uniqueSuffix()}`, storeId: store.storeId, skus: [skuInput({ id: skuId, price: 0 })], }), 'BAD_REQUEST' ) }) it('APROD-37 (current): an omitted SKU id creates a new SKU', async () => { // `updateProduct` treats a SKU without `id` as an insert; the existing SKU is // left untouched, so the product ends up with both. const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: 100 })] }) const productId = Number(created.product.id) const originalSkuId = Number(created.product.skus[0].id) await admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, skus: [skuInput({ name: '2pc', price: 300 })], }) const read = await readProduct(admin, productId) const ids = read.skus.map((s: any) => Number(s.id)) expect(ids).toContain(originalSkuId) expect(ids).toHaveLength(2) }) it('APROD-38: deletedImageKeys are removed from the SKU after update', async () => { const admin = await staffClient() const store = await createStore() const gen: any = await admin.common.generateUploadUrls.mutate({ contextString: 'product_info', mimeTypes: ['image/png'], }) const url = gen.uploadUrls[0] const key = keyFromUrl(url) const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ images: [url] })] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) const res: any = await admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, skus: [skuInput({ id: skuId, images: [] })], deletedImageKeys: [key], }) expect(res.message).toBe('Product updated successfully') const read = await readProduct(admin, productId) expect(read.skus[0].images).toEqual([]) }) it('APROD-39: a fabricated newImageUrls entry is rejected before cleaning up', 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 url = gen.uploadUrls[0] const key = keyFromUrl(url) const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ images: [url] })] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) await expectTrpcError( () => admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, skus: [skuInput({ id: skuId, images: [url] })], newImageUrls: [`${domain}product-images/never-${uniqueSuffix()}.png`], deletedImageKeys: [key], }), 'BAD_REQUEST', 'not uploaded through the app' ) const read = await readProduct(admin, productId) expect(read.skus[0].imageKeys).toEqual([key]) }) it('APROD-40: re-sending the current image URL is not treated as a new upload', 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 url = gen.uploadUrls[0] const key = keyFromUrl(url) const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ images: [url] })] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) const res: any = await admin.admin.product.updateProduct.mutate({ id: productId, name: `E2E Resend ${uniqueSuffix()}`, storeId: store.storeId, skus: [skuInput({ id: skuId, images: [url] })], }) expect(res.message).toBe('Product updated successfully') const read = await readProduct(admin, productId) expect(read.skus[0].imageKeys).toEqual([key]) expect(read.skus[0].images).toEqual([`${domain}/${key}`]) }) it('APROD-41: a regional update persists suspension on the region flag, not the global flag', async () => { // The regional update path writes product_market_stats.is_suspended_in_region // for its own region; the structural product_skus.is_suspended kill-switch is // superadmin-owned and stays untouched. const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput()] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) await admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, skus: [skuInput({ id: skuId, isSuspendedInRegion: true })], }) let read = await readProduct(admin, productId) expect(read.skus[0].isSuspendedInRegion).toBe(true) expect(read.skus[0].isSuspended).toBe(false) // And an omitted flag keeps the current regional value. await admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, skus: [skuInput({ id: skuId, price: 250 })], }) read = await readProduct(admin, productId) expect(read.skus[0].isSuspendedInRegion).toBe(true) // Explicitly clearing it un-suspends the region. await admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, skus: [skuInput({ id: skuId, isSuspendedInRegion: false })], }) read = await readProduct(admin, productId) expect(read.skus[0].isSuspendedInRegion).toBe(false) }) it('APROD-81: a regional update cannot set the global suspension flag', async () => { const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput()] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) await admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, // A client that only knows the old structural field must not reach it. skus: [skuInput({ id: skuId, isSuspended: true })], }) const read = await readProduct(admin, productId) expect(read.skus[0].isSuspended).toBe(false) expect(read.skus[0].isSuspendedInRegion).toBe(false) }) it('APROD-42: updating a product schedules a products cache rebuild', async () => { const admin = await staffClient() const baseline = await regionConst(admin, 'products_version_num') const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: 100 })] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) await admin.admin.product.updateProduct.mutate({ id: productId, name: created.product.name, storeId: store.storeId, skus: [skuInput({ id: skuId, price: 777 })], }) await pollProductsCache( admin, baseline, (d) => (d.products ?? []).some( (p: any) => Number(p.id) === skuId && Number(p.price) === 777 ), `products.json shows SKU ${skuId} at price 777` ) }) it('APROD-78: a regional admin can edit a global product market data', async () => { const admin = await staffClient() const store = await createStore() const global = await elevateToGlobal(admin, store.storeId, [skuInput({ price: 100 })]) const before = await readProduct(admin, global.productId) const res: any = await admin.admin.product.updateProduct.mutate({ id: global.productId, name: before.name, shortDescription: before.shortDescription ?? undefined, storeId: before.storeId, incrementStep: before.incrementStep, productType: before.productType, skus: [skuInput({ id: global.skuIds[0], name: before.skus[0].name, price: 175, marketPrice: 220, isSuspendedInRegion: true, })], deletedImageKeys: [], newImageUrls: [], }) expect(res.message).toBe('Product updated successfully') const after = await readProduct(admin, global.productId) expect(after.isGlobal).toBe(true) expect(after.skus[0].price).toBe('175') expect(after.skus[0].isSuspendedInRegion).toBe(true) }) it('APROD-79: a regional admin cannot change a global product structure', async () => { const admin = await staffClient() const store = await createStore() const global = await elevateToGlobal(admin, store.storeId, [skuInput({ price: 100 })]) const before = await readProduct(admin, global.productId) await expectTrpcError( () => admin.admin.product.updateProduct.mutate({ id: global.productId, name: `Renamed by region ${uniqueSuffix()}`, shortDescription: before.shortDescription ?? undefined, storeId: before.storeId, incrementStep: before.incrementStep, productType: before.productType, skus: [skuInput({ id: global.skuIds[0], name: before.skus[0].name, price: 100 })], deletedImageKeys: [], newImageUrls: [], }), 'FORBIDDEN', 'Rejected fields: name' ) const after = await readProduct(admin, global.productId) expect(after.name).toBe(before.name) }) it('APROD-80: a regional admin cannot delete a global product image', async () => { const admin = await staffClient() const store = await createStore() const gen: any = await admin.common.generateUploadUrls.mutate({ contextString: 'product_info', mimeTypes: ['image/png'], }) const url = gen.uploadUrls[0] const key = keyFromUrl(url) const global = await elevateToGlobal(admin, store.storeId, [skuInput({ images: [url] })]) const before = await readProduct(admin, global.productId) await expectTrpcError( () => admin.admin.product.updateProduct.mutate({ id: global.productId, name: before.name, shortDescription: before.shortDescription ?? undefined, storeId: before.storeId, incrementStep: before.incrementStep, productType: before.productType, skus: [skuInput({ id: global.skuIds[0], name: before.skus[0].name, images: [] })], deletedImageKeys: [key], newImageUrls: [], }), 'FORBIDDEN', 'deletedImageKeys' ) const after = await readProduct(admin, global.productId) expect(after.skus[0].imageKeys).toEqual([key]) }) }) describe('admin.product.deleteProduct (APROD-43..45)', () => { it('APROD-43 (current): deleting a product with SKUs soft-deletes instead of failing', async () => { // `softDeleteProduct` flags the SKUs `isDeleted` and clears the dependent // rows; no FK/raw failure is surfaced. `getProducts` then hides it while // `getProductById` still returns the (soft-deleted) row. const admin = await staffClient() const store = await createStore() const { productId, skuIds } = await createMultiSku(admin, store.storeId, 2) const res: any = await admin.admin.product.deleteProduct.mutate({ id: productId }) expect(res.message).toBe('Product deleted successfully') const list: any = await admin.admin.product.getProducts.query() expect(list.products.some((p: any) => Number(p.id) === productId)).toBe(false) const read = await readProduct(admin, productId) expect(read.skus.map((s: any) => Number(s.id)).sort()).toEqual([...skuIds].sort()) expect(read.skus.every((s: any) => s.isDeleted === true)).toBe(true) }) it('APROD-44: deleting an unknown product is 404', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.product.deleteProduct.mutate({ id: 999_999_999 }), 'NOT_FOUND', 'Product not found' ) }) it('APROD-45 (current): deleteProduct does not run image cleanup and still succeeds', async () => { // Unlike banners/tags, `deleteProduct` never calls `deleteImageUtil`; the // soft delete leaves the object untouched but hides the product. const admin = await staffClient() const store = await createStore() const gen: any = await admin.common.generateUploadUrls.mutate({ contextString: 'product_info', mimeTypes: ['image/png'], }) const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ images: [gen.uploadUrls[0]] })], }) const productId = Number(created.product.id) const res: any = await admin.admin.product.deleteProduct.mutate({ id: productId }) expect(res.message).toBe('Product deleted successfully') const list: any = await admin.admin.product.getProducts.query() expect(list.products.some((p: any) => Number(p.id) === productId)).toBe(false) }) }) describe('admin.product stock + prices (APROD-46..55)', () => { it('APROD-46: toggling the whole product flips every SKU and bumps availability', async () => { const admin = await staffClient() const store = await createStore() const { productId, skuIds } = await createMultiSku(admin, store.storeId, 2) const baseline = await regionConst(admin, 'availability_version_num') const res: any = await admin.admin.product.toggleOutOfStock.mutate({ id: productId }) expect(res.isOutOfStock).toBe(true) expect(Number(res.productId)).toBe(productId) const read = await readProduct(admin, productId) expect(read.skus.map((s: any) => Number(s.id)).sort()).toEqual([...skuIds].sort()) expect(read.skus.every((s: any) => s.isOutOfStock === true)).toBe(true) const after = await regionConst(admin, 'availability_version_num') expect(after).toBeGreaterThan(baseline) }) it('APROD-47: toggling specific SKUs flips only those variants', async () => { const admin = await staffClient() const store = await createStore() const { productId, skuIds } = await createMultiSku(admin, store.storeId, 2) const res: any = await admin.admin.product.toggleOutOfStock.mutate({ id: productId, skuIds: [skuIds[0]], isOutOfStock: true, }) expect(res.affectedSkuIds).toEqual([skuIds[0]]) expect(res.isOutOfStock).toBe(true) const read = await readProduct(admin, productId) const byId = new Map(read.skus.map((s: any) => [Number(s.id), s])) expect((byId.get(skuIds[0]) as any).isOutOfStock).toBe(true) expect((byId.get(skuIds[1]) as any).isOutOfStock).toBe(false) }) it('APROD-48: skuIds without isOutOfStock is BAD_REQUEST', async () => { const admin = await staffClient() const store = await createStore() const { productId, skuIds } = await createMultiSku(admin, store.storeId, 1) await expectTrpcError( () => admin.admin.product.toggleOutOfStock.mutate({ id: productId, skuIds: [skuIds[0]] }), 'BAD_REQUEST', 'isOutOfStock' ) }) it('APROD-49: a partial variant toggle reports the aggregate and partial message', async () => { const admin = await staffClient() const store = await createStore() const { productId, skuIds } = await createMultiSku(admin, store.storeId, 2) const res: any = await admin.admin.product.toggleOutOfStock.mutate({ id: productId, skuIds: [skuIds[0]], isOutOfStock: true, }) expect(res.isOutOfStock).toBe(true) expect(res.message).toContain('(other variants unchanged)') }) it('APROD-50: an unknown product is 404 and a foreign SKU id is 400', async () => { const admin = await staffClient() const store = await createStore() const { productId } = await createMultiSku(admin, store.storeId, 1) const other = await createMultiSku(admin, store.storeId, 1) await expectTrpcError( () => admin.admin.product.toggleOutOfStock.mutate({ id: 999_999_999 }), 'NOT_FOUND', 'Product not found' ) await expectTrpcError( () => admin.admin.product.toggleOutOfStock.mutate({ id: productId, skuIds: [other.skuIds[0]], isOutOfStock: true, }), 'BAD_REQUEST', 'do not belong to product' ) }) it('APROD-51: updateProductPrices reports updatedCount and persists the price', async () => { const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: 100 })] }) const productId = Number(created.product.id) const skuId = Number(created.product.skus[0].id) const res: any = await admin.admin.product.updateProductPrices.mutate({ updates: [{ skuId, price: 999 }], }) expect(res.updatedCount).toBe(1) expect(res.message).toBe('Updated prices for 1 SKU(s)') const read = await readProduct(admin, productId) expect(read.skus[0].price).toBe('999') }) it('APROD-52: an empty updates list is 400', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.product.updateProductPrices.mutate({ updates: [] }), 'BAD_REQUEST', 'No updates provided' ) }) it('APROD-53: an invalid SKU id is 400 and names the ids', async () => { const admin = await staffClient() await expectTrpcError( () => admin.admin.product.updateProductPrices.mutate({ updates: [{ skuId: 999_999_999, price: 10 }] }), 'BAD_REQUEST', 'Invalid SKU IDs' ) }) it('APROD-54: an update with no price fields is 400', async () => { const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput()] }) const skuId = Number(created.product.skus[0].id) await expectTrpcError( () => admin.admin.product.updateProductPrices.mutate({ updates: [{ skuId }] }), 'BAD_REQUEST', 'No price fields' ) }) it('APROD-55: a price update bumps the availability version synchronously', async () => { const admin = await staffClient() const store = await createStore() const created: any = await rawCreate(admin, { storeId: store.storeId, skus: [skuInput({ price: 100 })] }) const skuId = Number(created.product.skus[0].id) const baseline = await regionConst(admin, 'availability_version_num') await admin.admin.product.updateProductPrices.mutate({ updates: [{ skuId, price: 321 }] }) const after = await regionConst(admin, 'availability_version_num') expect(after).toBeGreaterThan(baseline) }) })