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

371 lines
13 KiB
TypeScript

/**
* TX-01..12 — transactions and partial failure (catalogue §11.2).
*
* Each row drives the failure the public API can actually reach and then reads
* back through a follow-up admin query to prove no partial rows were written.
* Failures that need an uninducible mid-transaction crash (D1 here does not
* reliably roll back) are pinned `(current)` with the reachable contract.
*/
import { apiClient, expectTrpcError, uniqueSuffix } from '../helpers/api'
import { staffClient, superadminClient } from '../helpers/sessions'
import {
PASSWORD,
createCatalogOrderFixture,
createCoupon,
createProduct,
createStore,
placeOrder,
registerThrowawayUser,
createAddress,
} from '../helpers/fixtures'
import { TEST_REGION_ID } from '../helpers/env'
jest.setTimeout(180_000)
const REGION_1 = TEST_REGION_ID
const badImage = () => `https://example.com/not-uploaded-${uniqueSuffix()}.png`
async function userOrderCount(token: string): Promise<number> {
const list: any = await apiClient(token).user.order.getOrders.query({ page: 1, pageSize: 1 })
return Number(list.pagination.totalCount)
}
describe('transactions — product/tag writes (TX-01..03)', () => {
it('TX-01: a product create whose image claim fails writes no product/SKU rows', async () => {
const admin = await staffClient()
const store = await createStore()
const name = `E2E TX BadImage ${uniqueSuffix()}`
await expectTrpcError(
() =>
admin.admin.product.createProduct.mutate({
name,
shortDescription: 'bad image',
storeId: store.storeId,
productType: 'item',
skus: [
{
name: '1pc',
price: 100,
marketPrice: 150,
images: [badImage()],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: [{ featureName: 'quantity', featureValue: '1pc' }],
},
],
} as any),
'BAD_REQUEST',
'not uploaded through the app'
)
const products: any = await admin.admin.product.getProducts.query()
expect(products.products.some((p: any) => p.name === name)).toBe(false)
})
it('TX-02: a product update whose image claim fails changes nothing', async () => {
const admin = await staffClient()
const store = await createStore()
const product = await createProduct({ storeId: store.storeId, price: 199 })
const before: any = await admin.admin.product.getProductById.query({ id: product.productId })
const sku = before.product.skus[0]
await expectTrpcError(
() =>
admin.admin.product.updateProduct.mutate({
id: product.productId,
name: before.product.name,
shortDescription: before.product.shortDescription ?? 'x',
storeId: product.storeId as number,
productType: 'item',
skus: [
{
id: sku.id,
name: sku.name,
price: Number(sku.price),
marketPrice: sku.marketPrice != null ? Number(sku.marketPrice) : null,
images: [badImage()],
isFlashAvailable: false,
flashPrice: null,
isOutOfStock: false,
isOffer: false,
isComboOnly: false,
isSuspended: false,
features: (sku.features ?? []).map((f: any) => ({
featureName: f.featureName,
featureValue: f.featureValue,
})),
},
],
} as any),
'BAD_REQUEST',
'not uploaded through the app'
)
const after: any = await admin.admin.product.getProductById.query({ id: product.productId })
expect(after.product.name).toBe(before.product.name)
expect(after.product.skus).toHaveLength(1)
expect(Number(after.product.skus[0].price)).toBe(Number(sku.price))
})
it('TX-03: a tag create whose upload claim fails writes no tag/mapping', async () => {
const admin = await staffClient()
const tagName = `E2E TX BadTag ${uniqueSuffix()}`
await expectTrpcError(
() =>
admin.admin.product.createProductTag.mutate({
tagName,
uploadUrls: [badImage()],
} as any),
'BAD_REQUEST',
'not uploaded through the app'
)
const tags: any = await admin.admin.product.getProductTags.query()
expect(tags.tags.some((t: any) => t.tagName === tagName)).toBe(false)
})
})
describe('transactions — coupon/order writes (TX-04..06)', () => {
it('TX-04 (current): a multi-code coupon create that hits a duplicate leaves the earlier coupon', async () => {
const admin = await staffClient()
const existing = await createCoupon()
const fresh = `TXFRESH${uniqueSuffix().replace(/[^a-z0-9]/gi, '').toUpperCase()}`
await expectTrpcError(
() =>
admin.admin.coupon.create.mutate({
couponCodes: [fresh, existing.couponCode],
skuIds: [],
isApplyForAll: true,
flatDiscount: 10,
} as any),
'INTERNAL_SERVER_ERROR',
'already exists'
)
// The loop creates sequentially with no outer transaction: the first code
// commits before the duplicate aborts the request.
const partial: any = await admin.admin.coupon.getAll.query({ search: fresh, limit: 5 })
expect(partial.coupons.some((c: any) => c.couponCode === fresh)).toBe(true)
})
it('TX-05 (current): an order whose insert fails writes no order/items/usage', async () => {
const fx = await createCatalogOrderFixture({ price: 199 })
const before = await userOrderCount(fx.user.token)
await expectTrpcError(
() =>
placeOrder(fx.user.token, {
addressId: fx.address.id,
skuId: fx.product.skuId,
slotId: fx.slot.slotId,
items: [],
}),
'INTERNAL_SERVER_ERROR',
'at least one value'
)
expect(await userOrderCount(fx.user.token)).toBe(before)
})
it('TX-06 (current): a cancel failure leaves the order status/reason unchanged', async () => {
const fx = await createCatalogOrderFixture()
const placed = await placeOrder(fx.user.token, {
addressId: fx.address.id,
skuId: fx.product.skuId,
slotId: fx.slot.slotId,
})
const orderId = Number(placed[0].id)
// An unknown id makes the cancel handler fail before/around the transaction;
// the router masks every failure as `failed to cancel order` (500).
await expectTrpcError(
() =>
apiClient(fx.user.token).user.order.cancelOrder.mutate({
id: 999_999_999,
reason: 'nope',
}),
'INTERNAL_SERVER_ERROR',
'failed to cancel order'
)
const detail: any = await apiClient(fx.user.token).user.order.getOrderById.query({
orderId: String(orderId),
})
expect(detail.orderStatus).toBe('success')
expect(detail.cancelReason).toBeNull()
})
})
describe('transactions — default address (TX-07..08)', () => {
it('TX-07 (current): a default-setting address create leaves exactly one default', async () => {
// createUserAddress cannot be made to fail after clearDefaultAddress from the
// API, so the failure branch is unreachable; the observable contract is that
// the clear-then-insert sequence converges on a single default.
const user = await registerThrowawayUser()
const first = await createAddress(user.token)
const second = await createAddress(user.token, { isDefault: true })
const addresses: any = await apiClient(user.token).user.address.getUserAddresses.query()
const defaults = addresses.data.filter((a: any) => a.isDefault)
expect(defaults).toHaveLength(1)
expect(Number(defaults[0].id)).toBe(second.id)
expect(Number(first.id)).not.toBe(Number(second.id))
})
it('TX-08 (current): a default-setting address update leaves exactly one default', async () => {
// updateAddress validates the target before clearDefaultAddress, so no API
// input can fail it after the clear; assert the convergence instead.
const user = await registerThrowawayUser()
const first = await createAddress(user.token)
const second = await createAddress(user.token, { isDefault: true })
const existing: any = await apiClient(user.token).user.address.getUserAddresses.query()
const firstRow = existing.data.find((a: any) => Number(a.id) === Number(first.id))
await apiClient(user.token).user.address.updateAddress.mutate({
id: Number(first.id),
regionId: REGION_1,
name: firstRow.name,
phone: firstRow.phone,
addressLine1: firstRow.addressLine1,
city: firstRow.city,
state: firstRow.state,
isDefault: true,
latitude: firstRow.latitude,
longitude: firstRow.longitude,
} as any)
const after: any = await apiClient(user.token).user.address.getUserAddresses.query()
const defaults = after.data.filter((a: any) => a.isDefault)
expect(defaults).toHaveLength(1)
expect(Number(defaults[0].id)).toBe(Number(first.id))
expect(Number(second.id)).not.toBe(Number(first.id))
})
})
describe('transactions — related rows (TX-09..11)', () => {
it('TX-09: deleting a staff member blocked by created coupons removes nothing', async () => {
const sa = await superadminClient()
const roles: any = await sa.superadmin.staff.roles.query()
const roleId = Number(roles.roles.find((r: any) => r.name === 'admin')?.id ?? roles.roles[0].id)
const name = `e2e_tx_${uniqueSuffix().replace(/[^a-z0-9]/gi, '')}`
const created: any = await sa.superadmin.staff.create.mutate({
name,
password: PASSWORD,
roleId,
regionId: REGION_1,
})
const staffId = Number(created.user.id)
const login: any = await apiClient().admin.staffUser.login.mutate({ name, password: PASSWORD })
await apiClient(login.token).admin.coupon.create.mutate({
couponCode: `TXBLOCK${uniqueSuffix().replace(/[^a-z0-9]/gi, '').toUpperCase()}`,
skuIds: [],
isApplyForAll: true,
flatDiscount: 10,
} as any)
await expectTrpcError(() => sa.superadmin.staff.remove.mutate({ id: staffId }), 'CONFLICT')
const list: any = await sa.superadmin.staff.list.query()
expect(list.staff.some((s: any) => Number(s.id) === staffId)).toBe(true)
})
it('TX-10: a region create with duplicate bound priorities writes no region/bounds', async () => {
const sa = await superadminClient()
const before: any = await sa.superadmin.regions.list.query()
const beforeIds = new Set((before as any[]).map((r: any) => Number(r.id)))
const name = `E2E TX DupPriority ${uniqueSuffix()}`
const square = (lat: number, lng: number) => ({
type: 'FeatureCollection' as const,
features: [
{
type: 'Feature' as const,
properties: {},
geometry: {
type: 'Polygon',
coordinates: [
[
[lng - 0.01, lat - 0.01],
[lng + 0.01, lat - 0.01],
[lng + 0.01, lat + 0.01],
[lng - 0.01, lat + 0.01],
[lng - 0.01, lat - 0.01],
],
],
},
},
],
})
await expectTrpcError(
() =>
sa.superadmin.regions.create.mutate({
name,
description: 'duplicate priority',
center: { lat: 15.9, lng: 77.9 },
bounds: [
{ description: 'a', geojson: square(15.9, 77.9), priority: '5' },
{ description: 'b', geojson: square(15.91, 77.91), priority: '5' },
],
} as any),
'CONFLICT'
)
const after: any = await sa.superadmin.regions.list.query()
const afterIds = new Set((after as any[]).map((r: any) => Number(r.id)))
expect(afterIds.size).toBe(beforeIds.size)
expect((after as any[]).some((r: any) => r.name === name)).toBe(false)
})
it('TX-11: a slot create with an invalid product writes no slot relations', async () => {
const admin = await staffClient()
const before: any = await admin.admin.slots.getAll.query()
await expectTrpcError(
() =>
admin.admin.slots.createSlot.mutate({
deliveryTime: new Date(Date.now() + 3 * 3_600_000).toISOString(),
freezeTime: new Date(Date.now() + 2 * 3_600_000).toISOString(),
isActive: true,
skuIds: [999_999_999],
}),
'INTERNAL_SERVER_ERROR',
'Invalid SKU'
)
const after: any = await admin.admin.slots.getAll.query()
expect(after.count).toBe(before.count)
expect(after.slots.every((s: any) => !(s.skuIds ?? []).includes(999_999_999))).toBe(true)
})
})
describe('transactions — publish/queue (TX-12)', () => {
it('TX-12 (current): a committed order survives the (awaited) publish step', async () => {
// A publish/queue failure cannot be induced from the API, and placeOrder
// awaits publishFormattedOrder. The reachable contract: a successful
// response implies a persisted, immediately readable order.
const fx = await createCatalogOrderFixture()
const placed = await placeOrder(fx.user.token, {
addressId: fx.address.id,
skuId: fx.product.skuId,
slotId: fx.slot.slotId,
})
const orderId = Number(placed[0].id)
const detail: any = await apiClient(fx.user.token).user.order.getOrderById.query({
orderId: String(orderId),
})
expect(detail.id).toBe(orderId)
expect(detail.orderStatus).toBe('success')
})
})