503 lines
17 KiB
TypeScript
503 lines
17 KiB
TypeScript
/**
|
|
* Fixtures created through the live API.
|
|
*
|
|
* Everything is uniquely suffixed so reruns never collide, and nothing is
|
|
* deleted that the suite did not create. Cache reads are eventual for
|
|
* products/stores; D1 reads are immediate.
|
|
*/
|
|
|
|
import { apiClient, uniqueSuffix } from './api'
|
|
import { staffClient, superadminClient, userClient } from './sessions'
|
|
import { TEST_BOUND_ID, TEST_OTHER_BOUND_ID, TEST_OTHER_REGION_ID, TEST_REGION_ID } from './env'
|
|
|
|
export const PASSWORD = 'FreshyoTest!2026'
|
|
|
|
/** Centres that are inside the seeded bounds (from region_bounds.center_lat/lng). */
|
|
export const COORDS = {
|
|
region1Bound1: { lat: 16.7421312, lng: 78.01191145 },
|
|
region1Bound2: { lat: 16.7465888, lng: 78.01747365 },
|
|
region2Bound3: { lat: 16.76136485, lng: 78.1397562 },
|
|
} as const
|
|
|
|
export interface CreatedStore {
|
|
storeId: number
|
|
storeName: string
|
|
}
|
|
|
|
/** Create a store in the staff region (+ optional product ids). */
|
|
export async function createStore(
|
|
options: { name?: string; description?: string; products?: number[] } = {}
|
|
): Promise<CreatedStore> {
|
|
const admin = await staffClient()
|
|
const storeName = options.name ?? `E2E Store ${uniqueSuffix()}`
|
|
const res = (await admin.admin.store.createStore.mutate({
|
|
name: storeName,
|
|
description: options.description ?? 'Created by backend API tests',
|
|
...(options.products ? { products: options.products } : {}),
|
|
})) as { store?: { id?: number } }
|
|
const storeId = Number(res?.store?.id)
|
|
if (!storeId) throw new Error(`[api-tests] createStore returned no id: ${JSON.stringify(res)}`)
|
|
return { storeId, storeName }
|
|
}
|
|
|
|
export interface CreatedProduct {
|
|
productId: number
|
|
productName: string
|
|
skuId: number
|
|
skuName: string
|
|
price: number
|
|
storeId: number | null
|
|
}
|
|
|
|
/** Create a one-SKU product (feature `quantity` is mandatory). */
|
|
export async function createProduct(options: {
|
|
storeId?: number
|
|
name?: string
|
|
price?: number
|
|
marketPrice?: number | null
|
|
isOutOfStock?: boolean
|
|
isSuspended?: boolean
|
|
isFlashAvailable?: boolean
|
|
flashPrice?: number | null
|
|
productType?: 'item' | 'combo'
|
|
skuName?: string
|
|
featureName?: string
|
|
featureValue?: string
|
|
images?: string[]
|
|
comboItems?: Array<{ skuId: number }>
|
|
} = {}): Promise<CreatedProduct> {
|
|
const admin = await staffClient()
|
|
const productName = options.name ?? `E2E Product ${uniqueSuffix()}`
|
|
const price = options.price ?? 199
|
|
const skuName = options.skuName ?? '1pc'
|
|
const storeId = options.storeId ?? (await createStore()).storeId
|
|
|
|
const res = (await admin.admin.product.createProduct.mutate({
|
|
name: productName,
|
|
shortDescription: 'Created by backend API tests',
|
|
storeId,
|
|
productType: options.productType ?? 'item',
|
|
skus: [
|
|
{
|
|
name: skuName,
|
|
price,
|
|
marketPrice: options.marketPrice === undefined ? price + 50 : options.marketPrice,
|
|
images: options.images ?? [],
|
|
isFlashAvailable: options.isFlashAvailable ?? false,
|
|
flashPrice: options.flashPrice ?? null,
|
|
isOutOfStock: options.isOutOfStock ?? false,
|
|
isOffer: false,
|
|
isComboOnly: false,
|
|
isSuspended: options.isSuspended ?? false,
|
|
features: [
|
|
{
|
|
featureName: options.featureName ?? 'quantity',
|
|
featureValue: options.featureValue ?? skuName,
|
|
},
|
|
],
|
|
...(options.comboItems ? { comboItems: options.comboItems } : {}),
|
|
},
|
|
],
|
|
})) as { product?: { id?: number; skus?: Array<{ id?: number; name?: string }> } }
|
|
|
|
const productId = Number(res?.product?.id)
|
|
const skuId = Number(res?.product?.skus?.[0]?.id)
|
|
if (!productId || !skuId) {
|
|
throw new Error(`[api-tests] createProduct returned no ids: ${JSON.stringify(res)}`)
|
|
}
|
|
return {
|
|
productId,
|
|
productName,
|
|
skuId,
|
|
skuName: res.product?.skus?.[0]?.name ?? skuName,
|
|
price,
|
|
storeId: options.storeId ?? null,
|
|
}
|
|
}
|
|
|
|
export interface CreatedSlot {
|
|
slotId: number
|
|
deliveryTime: string
|
|
freezeTime: string
|
|
skuIds: number[]
|
|
}
|
|
|
|
/** Create a future, active delivery slot containing the given SKUs. */
|
|
export async function createFutureSlot(
|
|
skuIds: number[] = [],
|
|
options: { deliveryInHours?: number; freezeInHours?: number; isActive?: boolean } = {}
|
|
): Promise<CreatedSlot> {
|
|
const admin = await staffClient()
|
|
const deliveryTime = new Date(Date.now() + (options.deliveryInHours ?? 3) * 3_600_000).toISOString()
|
|
const freezeTime = new Date(Date.now() + (options.freezeInHours ?? 2) * 3_600_000).toISOString()
|
|
|
|
const res = (await admin.admin.slots.createSlot.mutate({
|
|
deliveryTime,
|
|
freezeTime,
|
|
isActive: options.isActive ?? true,
|
|
skuIds,
|
|
})) as { slot?: { id?: number } }
|
|
|
|
const slotId = Number(res?.slot?.id)
|
|
if (!slotId) throw new Error(`[api-tests] createSlot returned no id: ${JSON.stringify(res)}`)
|
|
return { slotId, deliveryTime, freezeTime, skuIds }
|
|
}
|
|
|
|
export interface CreatedUser {
|
|
token: string
|
|
userId: number
|
|
identifier: string
|
|
email: string
|
|
mobile: string
|
|
password: string
|
|
name: string
|
|
}
|
|
|
|
/** Register a throwaway user (token returned immediately). */
|
|
export async function registerThrowawayUser(): Promise<CreatedUser> {
|
|
const suffix = uniqueSuffix()
|
|
const mobile = `9${String(Math.floor(Math.random() * 1e9)).padStart(9, '0')}`
|
|
const email = `e2e-${suffix}@example.com`
|
|
const name = `E2E User ${suffix}`
|
|
|
|
const res = (await apiClient().user.auth.register.mutate({
|
|
name,
|
|
email,
|
|
mobile,
|
|
password: PASSWORD,
|
|
})) as { data?: { token?: string; user?: { id?: number } } }
|
|
|
|
const token = res?.data?.token
|
|
const userId = Number(res?.data?.user?.id)
|
|
if (!token || !userId) {
|
|
throw new Error(`[api-tests] register returned no token/user id: ${JSON.stringify(res)}`)
|
|
}
|
|
return { token, userId, identifier: email, email, mobile, password: PASSWORD, name }
|
|
}
|
|
|
|
export interface CreatedAddress {
|
|
id: number
|
|
regionId: number
|
|
boundId: number | null
|
|
[key: string]: unknown
|
|
}
|
|
|
|
/** Create an address inside the seeded region/bound for the given user token. */
|
|
export async function createAddress(
|
|
userToken: string,
|
|
overrides: Record<string, unknown> = {}
|
|
): Promise<CreatedAddress> {
|
|
const client = apiClient(userToken)
|
|
const coords =
|
|
Number(overrides.regionId ?? TEST_REGION_ID) === TEST_OTHER_REGION_ID
|
|
? COORDS.region2Bound3
|
|
: COORDS.region1Bound1
|
|
|
|
const res = (await client.user.address.createAddress.mutate({
|
|
regionId: TEST_REGION_ID,
|
|
name: 'E2E Home',
|
|
phone: '9876543210',
|
|
addressLine1: `12 E2E Road ${uniqueSuffix()}`,
|
|
addressLine2: 'Near test landmark',
|
|
city: 'Mahabubnagar',
|
|
state: 'Telangana',
|
|
isDefault: true,
|
|
latitude: coords.lat,
|
|
longitude: coords.lng,
|
|
...overrides,
|
|
})) as { data?: { id?: number } }
|
|
|
|
const id = Number(res?.data?.id)
|
|
if (!id) throw new Error(`[api-tests] createAddress returned no id: ${JSON.stringify(res)}`)
|
|
return res.data as CreatedAddress
|
|
}
|
|
|
|
export interface CreatedCoupon {
|
|
id: number
|
|
couponCode: string
|
|
[key: string]: unknown
|
|
}
|
|
|
|
/** Create a flat/percent coupon for the staff region. */
|
|
export async function createCoupon(options: {
|
|
couponCode?: string
|
|
couponCodes?: string[]
|
|
discountPercent?: number | null
|
|
flatDiscount?: number | null
|
|
minOrder?: number | null
|
|
maxValue?: number | null
|
|
skuIds?: number[]
|
|
isUserBased?: boolean
|
|
applicableUsers?: number[]
|
|
targetUser?: number
|
|
isApplyForAll?: boolean
|
|
validTill?: string | null
|
|
maxLimitForUser?: number | null
|
|
exclusiveApply?: boolean
|
|
isFirstOrderOnly?: boolean
|
|
} = {}): Promise<CreatedCoupon> {
|
|
const admin = await staffClient()
|
|
const code = options.couponCode ?? `E2E${uniqueSuffix().replace(/[^a-z0-9]/gi, '').toUpperCase()}`
|
|
|
|
// The admin schema rejects explicit nulls for optional fields, so only send
|
|
// keys the caller actually provided.
|
|
const payload: Record<string, unknown> = {
|
|
couponCode: code,
|
|
skuIds: options.skuIds ?? [],
|
|
isApplyForAll: options.isApplyForAll ?? true,
|
|
}
|
|
if (options.couponCodes) payload.couponCodes = options.couponCodes
|
|
if (options.discountPercent != null) payload.discountPercent = options.discountPercent
|
|
else payload.flatDiscount = options.flatDiscount ?? 50
|
|
if (options.flatDiscount != null && options.discountPercent == null) payload.flatDiscount = options.flatDiscount
|
|
if (options.minOrder != null) payload.minOrder = options.minOrder
|
|
if (options.maxValue != null) payload.maxValue = options.maxValue
|
|
if (options.isUserBased != null) payload.isUserBased = options.isUserBased
|
|
if (options.applicableUsers) payload.applicableUsers = options.applicableUsers
|
|
if (options.targetUser != null) payload.targetUser = options.targetUser
|
|
if (options.validTill != null) payload.validTill = options.validTill
|
|
if (options.maxLimitForUser != null) payload.maxLimitForUser = options.maxLimitForUser
|
|
if (options.exclusiveApply != null) payload.exclusiveApply = options.exclusiveApply
|
|
if (options.isFirstOrderOnly != null) payload.isFirstOrderOnly = options.isFirstOrderOnly
|
|
|
|
const res = (await admin.admin.coupon.create.mutate(payload as any)) as
|
|
| CreatedCoupon[]
|
|
| { coupons?: CreatedCoupon[] }
|
|
|
|
const coupon = Array.isArray(res) ? res[0] : res?.coupons?.[0]
|
|
if (!coupon?.id) {
|
|
throw new Error(`[api-tests] coupon.create returned no coupon: ${JSON.stringify(res)}`)
|
|
}
|
|
return coupon
|
|
}
|
|
|
|
export interface PlacedOrder {
|
|
id: number
|
|
orderId?: string
|
|
readableId?: number
|
|
[key: string]: unknown
|
|
}
|
|
|
|
/** Place one order and return the created order rows. */
|
|
export async function placeOrder(
|
|
userToken: string,
|
|
options: {
|
|
addressId: number
|
|
skuId: number
|
|
slotId: number | null
|
|
quantity?: number
|
|
regionId?: number
|
|
couponIds?: number[]
|
|
userNotes?: string
|
|
isFlashDelivery?: boolean
|
|
items?: Array<{ skuId: number; quantity: number; slotId: number | null }>
|
|
}
|
|
): Promise<PlacedOrder[]> {
|
|
const client = apiClient(userToken)
|
|
const res = (await client.user.order.placeOrder.mutate({
|
|
selectedItems:
|
|
options.items ??
|
|
[{ skuId: options.skuId, quantity: options.quantity ?? 1, slotId: options.slotId }],
|
|
addressId: options.addressId,
|
|
regionId: options.regionId ?? TEST_REGION_ID,
|
|
...(options.couponIds ? { couponIds: options.couponIds } : {}),
|
|
...(options.userNotes ? { userNotes: options.userNotes } : {}),
|
|
isFlashDelivery: options.isFlashDelivery ?? false,
|
|
})) as { success?: boolean; data?: PlacedOrder[] }
|
|
|
|
if (!Array.isArray(res?.data) || res.data.length === 0) {
|
|
throw new Error(`[api-tests] placeOrder returned no orders: ${JSON.stringify(res)}`)
|
|
}
|
|
return res.data
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Complete catalog fixture */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
export interface CatalogOrderFixture {
|
|
user: CreatedUser
|
|
store: CreatedStore
|
|
product: CreatedProduct
|
|
slot: CreatedSlot
|
|
address: CreatedAddress
|
|
}
|
|
|
|
/**
|
|
* A fresh user + store + product + future slot + address, ready for ordering.
|
|
* The product is created before the slot so the slot can reference its SKU.
|
|
*/
|
|
export async function createCatalogOrderFixture(
|
|
options: { price?: number; withInstantSlot?: boolean } = {}
|
|
): Promise<CatalogOrderFixture> {
|
|
const store = await createStore()
|
|
const product = await createProduct({ storeId: store.storeId, price: options.price ?? 199 })
|
|
const slot = await createFutureSlot([product.skuId], options.withInstantSlot ? { deliveryInHours: 1, freezeInHours: 0.5 } : {})
|
|
const user = await registerThrowawayUser()
|
|
const address = await createAddress(user.token)
|
|
return { user, store, product, slot, address }
|
|
}
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Constants + regions */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
export async function getBoundSetting(boundId: number, key: string): Promise<string | null> {
|
|
const admin = await staffClient()
|
|
const res = (await admin.admin.region.getBoundSettings.query({ boundId })) as any
|
|
const raw = res?.settings ?? res?.data ?? res
|
|
const settings: Record<string, unknown> = Array.isArray(raw)
|
|
? Object.fromEntries(raw.map((entry: any) => [entry.key, entry.value]))
|
|
: (raw as Record<string, unknown>)
|
|
const value = settings?.[key]
|
|
return value == null ? null : String(value)
|
|
}
|
|
|
|
export async function setBoundSetting(boundId: number, key: string, value: string | null): Promise<void> {
|
|
const admin = await staffClient()
|
|
await admin.admin.region.updateBoundSettings.mutate({ boundId, settings: [{ key, value }] })
|
|
}
|
|
|
|
/** Run `fn` with a bound setting temporarily set, always restoring the old value. */
|
|
export async function withBoundSetting<T>(
|
|
boundId: number,
|
|
key: string,
|
|
value: string,
|
|
fn: () => Promise<T>
|
|
): Promise<T> {
|
|
const previous = await getBoundSetting(boundId, key)
|
|
await setBoundSetting(boundId, key, value)
|
|
try {
|
|
return await fn()
|
|
} finally {
|
|
await setBoundSetting(boundId, key, previous)
|
|
}
|
|
}
|
|
|
|
export async function getRegionConstant(regionId: number, key: string): Promise<string | null> {
|
|
const admin = await staffClient()
|
|
const res = (await admin.admin.region.getRegionConstants.query()) as any
|
|
const raw = res?.constants ?? res?.data ?? res
|
|
const constants: Record<string, unknown> = Array.isArray(raw)
|
|
? Object.fromEntries(raw.map((entry: any) => [entry.key, entry.value]))
|
|
: ((raw ?? {}) as Record<string, unknown>)
|
|
const value = constants?.[key]
|
|
return value == null ? null : String(value)
|
|
}
|
|
|
|
export async function setRegionConstant(regionId: number, key: string, value: string | null): Promise<void> {
|
|
const admin = await staffClient()
|
|
await admin.admin.region.updateRegionConstants.mutate({ constants: [{ key, value }] })
|
|
}
|
|
|
|
/** Square GeoJSON polygon around a centre (approx 2km). */
|
|
export function squareGeojson(lat: number, lng: number, delta = 0.02) {
|
|
return {
|
|
type: 'FeatureCollection' as const,
|
|
features: [
|
|
{
|
|
type: 'Feature' as const,
|
|
properties: {},
|
|
geometry: {
|
|
type: 'Polygon',
|
|
coordinates: [
|
|
[
|
|
[lng - delta, lat - delta],
|
|
[lng + delta, lat - delta],
|
|
[lng + delta, lat + delta],
|
|
[lng - delta, lat + delta],
|
|
[lng - delta, lat - delta],
|
|
],
|
|
],
|
|
},
|
|
},
|
|
],
|
|
}
|
|
}
|
|
|
|
/** Create a brand-new region with one bound (superadmin). */
|
|
export async function createRegion(options: {
|
|
name?: string
|
|
lat?: number
|
|
lng?: number
|
|
priority?: string
|
|
} = {}): Promise<{ regionId: number; boundId: number | null; name: string }> {
|
|
const superadmin = await superadminClient()
|
|
const name = options.name ?? `E2E Region ${uniqueSuffix()}`
|
|
const lat = options.lat ?? 15.5 + Math.random() * 0.1
|
|
const lng = options.lng ?? 77.5 + Math.random() * 0.1
|
|
|
|
const res = (await superadmin.superadmin.regions.create.mutate({
|
|
name,
|
|
description: 'Created by backend API tests',
|
|
center: { lat, lng },
|
|
bounds: [
|
|
{
|
|
description: 'E2E bound',
|
|
geojson: squareGeojson(lat, lng),
|
|
priority: options.priority ?? '1',
|
|
},
|
|
],
|
|
})) as { id?: number; bounds?: Array<{ id?: number }> }
|
|
|
|
const regionId = Number(res?.id)
|
|
if (!regionId) throw new Error(`[api-tests] regions.create returned no id: ${JSON.stringify(res)}`)
|
|
return { regionId, boundId: res.bounds?.[0]?.id ? Number(res.bounds[0].id) : null, name }
|
|
}
|
|
|
|
/** Region used by isolation tests (seeded). */
|
|
export const OTHER_REGION = { regionId: TEST_OTHER_REGION_ID, boundId: TEST_OTHER_BOUND_ID }
|
|
|
|
/** The standard region/bound used by most suites. */
|
|
export const REGION = { regionId: TEST_REGION_ID, boundId: TEST_BOUND_ID }
|
|
|
|
/* -------------------------------------------------------------------------- */
|
|
/* Superadmin-scoped region/bound constants */
|
|
/* -------------------------------------------------------------------------- */
|
|
|
|
function normalizeConstRows(raw: unknown): Record<string, unknown> {
|
|
if (Array.isArray(raw)) {
|
|
return Object.fromEntries(raw.map((entry: any) => [entry.key, entry.value]))
|
|
}
|
|
return (raw ?? {}) as Record<string, unknown>
|
|
}
|
|
|
|
export async function getSuperadminRegionConstant(regionId: number, key: string): Promise<string | null> {
|
|
const superadmin = await superadminClient()
|
|
const res = (await superadmin.superadmin.regions.getRegionConstants.query({ regionId })) as any
|
|
const value = normalizeConstRows(res?.constants ?? res?.data ?? res)[key]
|
|
return value == null ? null : String(value)
|
|
}
|
|
|
|
export async function setSuperadminRegionConstant(
|
|
regionId: number,
|
|
key: string,
|
|
value: string | null
|
|
): Promise<void> {
|
|
const superadmin = await superadminClient()
|
|
await superadmin.superadmin.regions.updateRegionConstants.mutate({
|
|
regionId,
|
|
constants: [{ key, value }],
|
|
})
|
|
}
|
|
|
|
export async function getSuperadminBoundSetting(boundId: number, key: string): Promise<string | null> {
|
|
const superadmin = await superadminClient()
|
|
const res = (await superadmin.superadmin.regions.boundSettings.query({ boundId })) as any
|
|
const value = normalizeConstRows(res?.settings ?? res?.constants ?? res?.data ?? res)[key]
|
|
return value == null ? null : String(value)
|
|
}
|
|
|
|
export async function setSuperadminBoundSetting(
|
|
boundId: number,
|
|
key: string,
|
|
value: string | null
|
|
): Promise<void> {
|
|
const superadmin = await superadminClient()
|
|
await superadmin.superadmin.regions.updateBoundSettings.mutate({
|
|
boundId,
|
|
settings: [{ key, value }],
|
|
})
|
|
}
|
|
|
|
export { userClient }
|