477 lines
13 KiB
TypeScript
477 lines
13 KiB
TypeScript
import { db } from '../db/db_index'
|
|
import { coupons, reservedCoupons, users, orders, orderStatus, couponApplicableUsers, couponApplicableProducts, productSkus } from '../db/schema'
|
|
import { eq, and, like, or, inArray, lt, desc, asc, sql, isNull } from 'drizzle-orm'
|
|
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
|
|
|
const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null): Promise<void> => {
|
|
const unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))]
|
|
if (unique.length === 0) return
|
|
const rows = await txOrDb.query.productSkus.findMany({
|
|
where: inArray(productSkus.id, unique),
|
|
with: { product: { columns: { regionId: true } } },
|
|
columns: { id: true },
|
|
})
|
|
if (rows.length !== unique.length) {
|
|
const found = new Set(rows.map((r: { id: number }) => r.id))
|
|
throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`)
|
|
}
|
|
// A global SKU (product regionId null) belongs to no region and may be attached anywhere.
|
|
const foreign = rows.filter((r: any) => {
|
|
const skuRegionId = r.product?.regionId ?? null
|
|
return skuRegionId !== null && skuRegionId !== regionId
|
|
})
|
|
if (foreign.length > 0) {
|
|
throw new Error(`SKU ${foreign.map((r: any) => r.id).join(', ')} belongs to a different region`)
|
|
}
|
|
}
|
|
|
|
export async function getAllCoupons(
|
|
regionId: number,
|
|
cursor?: number,
|
|
limit: number = 50,
|
|
search?: string
|
|
): Promise<{ coupons: any[]; hasMore: boolean }> {
|
|
let whereCondition = undefined
|
|
const conditions = []
|
|
|
|
conditions.push(eq(coupons.regionId, regionId))
|
|
|
|
if (cursor) {
|
|
conditions.push(lt(coupons.id, cursor))
|
|
}
|
|
|
|
if (search && search.trim()) {
|
|
conditions.push(like(coupons.couponCode, `%${search}%`))
|
|
}
|
|
|
|
if (conditions.length > 0) {
|
|
whereCondition = and(...conditions)
|
|
}
|
|
|
|
const result = await db.query.coupons.findMany({
|
|
where: whereCondition,
|
|
with: {
|
|
creator: true,
|
|
applicableUsers: {
|
|
with: {
|
|
user: true,
|
|
},
|
|
},
|
|
applicableProducts: {
|
|
with: {
|
|
sku: {
|
|
with: { product: true },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
orderBy: desc(coupons.createdAt),
|
|
limit: limit + 1,
|
|
})
|
|
|
|
const hasMore = result.length > limit
|
|
const couponsList = hasMore ? result.slice(0, limit) : result
|
|
|
|
return { coupons: couponsList, hasMore }
|
|
}
|
|
|
|
export async function getCouponById(regionId: number, id: number): Promise<any | null> {
|
|
return await db.query.coupons.findFirst({
|
|
where: and(
|
|
eq(coupons.id, id),
|
|
eq(coupons.regionId, regionId)
|
|
),
|
|
with: {
|
|
creator: true,
|
|
applicableUsers: {
|
|
with: {
|
|
user: true,
|
|
},
|
|
},
|
|
applicableProducts: {
|
|
with: {
|
|
sku: {
|
|
with: { product: true },
|
|
},
|
|
},
|
|
},
|
|
},
|
|
})
|
|
}
|
|
|
|
export async function createCouponWithRelations(
|
|
input: CouponFormInput,
|
|
applicableUsers: number[] | undefined,
|
|
applicableProducts: number[] | undefined,
|
|
regionId: number | null
|
|
): Promise<Coupon> {
|
|
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
|
|
|
return await db.transaction(async (tx) => {
|
|
const [coupon] = await tx.insert(coupons).values({
|
|
regionId,
|
|
couponCode: input.couponCode,
|
|
isUserBased: input.isUserBased,
|
|
discountPercent: input.discountPercent,
|
|
flatDiscount: input.flatDiscount,
|
|
minOrder: input.minOrder,
|
|
skuIds: input.skuIds,
|
|
createdBy: input.createdBy,
|
|
maxValue: input.maxValue,
|
|
isApplyForAll: input.isApplyForAll,
|
|
validTill: input.validTill,
|
|
maxLimitForUser: input.maxLimitForUser,
|
|
exclusiveApply: input.exclusiveApply,
|
|
isFirstOrderOnly: input.isFirstOrderOnly,
|
|
}).returning()
|
|
|
|
if (applicableUsers && applicableUsers.length > 0) {
|
|
await tx.insert(couponApplicableUsers).values(
|
|
applicableUsers.map(userId => ({
|
|
couponId: coupon.id,
|
|
userId,
|
|
}))
|
|
)
|
|
}
|
|
|
|
if (applicableProducts && applicableProducts.length > 0) {
|
|
await tx.insert(couponApplicableProducts).values(
|
|
applicableProducts.map(skuId => ({
|
|
couponId: coupon.id,
|
|
skuId,
|
|
}))
|
|
)
|
|
}
|
|
|
|
return coupon as Coupon
|
|
})
|
|
}
|
|
|
|
export async function updateCouponWithRelations(
|
|
regionId: number | null,
|
|
id: number,
|
|
input: CouponFormInput,
|
|
applicableUsers?: number[],
|
|
applicableProducts?: number[]
|
|
): Promise<Coupon | null> {
|
|
const existing = await db.query.coupons.findFirst({
|
|
where: and(
|
|
eq(coupons.id, id),
|
|
regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId)
|
|
),
|
|
columns: { id: true },
|
|
})
|
|
if (!existing) {
|
|
return null
|
|
}
|
|
if (applicableProducts !== undefined) {
|
|
await assertApplicableSkusInRegion(db, applicableProducts, regionId)
|
|
}
|
|
|
|
return await db.transaction(async (tx) => {
|
|
// createdBy is always sent (complete payload) but never rewritten on update
|
|
const { createdBy: _createdBy, ...updateFields } = input
|
|
|
|
const [coupon] = await tx.update(coupons)
|
|
.set({
|
|
...updateFields,
|
|
})
|
|
.where(
|
|
and(
|
|
eq(coupons.id, id),
|
|
regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId)
|
|
)
|
|
)
|
|
.returning()
|
|
|
|
if (applicableUsers !== undefined) {
|
|
await tx.delete(couponApplicableUsers).where(eq(couponApplicableUsers.couponId, id))
|
|
if (applicableUsers.length > 0) {
|
|
await tx.insert(couponApplicableUsers).values(
|
|
applicableUsers.map(userId => ({
|
|
couponId: id,
|
|
userId,
|
|
}))
|
|
)
|
|
}
|
|
}
|
|
|
|
if (applicableProducts !== undefined) {
|
|
await tx.delete(couponApplicableProducts).where(eq(couponApplicableProducts.couponId, id))
|
|
if (applicableProducts.length > 0) {
|
|
await tx.insert(couponApplicableProducts).values(
|
|
applicableProducts.map(skuId => ({
|
|
couponId: id,
|
|
skuId,
|
|
}))
|
|
)
|
|
}
|
|
}
|
|
|
|
return coupon as Coupon
|
|
})
|
|
}
|
|
|
|
export async function invalidateCoupon(regionId: number | null, id: number): Promise<Coupon | null> {
|
|
const result = await db.update(coupons)
|
|
.set({ isInvalidated: true })
|
|
.where(
|
|
and(
|
|
eq(coupons.id, id),
|
|
regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId)
|
|
)
|
|
)
|
|
.returning()
|
|
|
|
return (result[0] ?? null) as Coupon | null
|
|
}
|
|
|
|
export async function getReservedCoupons(
|
|
regionId: number,
|
|
cursor?: number,
|
|
limit: number = 50,
|
|
search?: string
|
|
): Promise<{ coupons: any[]; hasMore: boolean }> {
|
|
let whereCondition = undefined
|
|
const conditions = []
|
|
|
|
conditions.push(eq(reservedCoupons.regionId, regionId))
|
|
|
|
if (cursor) {
|
|
conditions.push(lt(reservedCoupons.id, cursor))
|
|
}
|
|
|
|
if (search && search.trim()) {
|
|
conditions.push(or(
|
|
like(reservedCoupons.secretCode, `%${search}%`),
|
|
like(reservedCoupons.couponCode, `%${search}%`)
|
|
))
|
|
}
|
|
|
|
if (conditions.length > 0) {
|
|
whereCondition = and(...conditions)
|
|
}
|
|
|
|
const result = await db.query.reservedCoupons.findMany({
|
|
where: whereCondition,
|
|
with: {
|
|
redeemedUser: true,
|
|
creator: true,
|
|
},
|
|
orderBy: desc(reservedCoupons.createdAt),
|
|
limit: limit + 1,
|
|
})
|
|
|
|
const hasMore = result.length > limit
|
|
const couponsList = hasMore ? result.slice(0, limit) : result
|
|
|
|
return { coupons: couponsList, hasMore }
|
|
}
|
|
|
|
export async function createReservedCouponWithProducts(
|
|
input: any,
|
|
applicableProducts: number[] | undefined,
|
|
regionId: number
|
|
): Promise<any> {
|
|
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
|
|
|
return await db.transaction(async (tx) => {
|
|
const [coupon] = await tx.insert(reservedCoupons).values({
|
|
regionId,
|
|
secretCode: input.secretCode,
|
|
couponCode: input.couponCode,
|
|
discountPercent: input.discountPercent,
|
|
flatDiscount: input.flatDiscount,
|
|
minOrder: input.minOrder,
|
|
skuIds: input.skuIds,
|
|
maxValue: input.maxValue,
|
|
validTill: input.validTill,
|
|
maxLimitForUser: input.maxLimitForUser,
|
|
exclusiveApply: input.exclusiveApply,
|
|
isFirstOrderOnly: input.isFirstOrderOnly ?? false,
|
|
createdBy: input.createdBy,
|
|
}).returning()
|
|
|
|
if (applicableProducts && applicableProducts.length > 0) {
|
|
await tx.insert(couponApplicableProducts).values(
|
|
applicableProducts.map(skuId => ({
|
|
couponId: coupon.id,
|
|
skuId,
|
|
}))
|
|
)
|
|
}
|
|
|
|
return coupon
|
|
})
|
|
}
|
|
|
|
export async function checkUsersExist(userIds: number[]): Promise<boolean> {
|
|
const existingUsers = await db.query.users.findMany({
|
|
where: inArray(users.id, userIds),
|
|
columns: { id: true },
|
|
})
|
|
return existingUsers.length === userIds.length
|
|
}
|
|
|
|
export async function checkCouponExists(couponCode: string): Promise<boolean> {
|
|
const existing = await db.query.coupons.findFirst({
|
|
where: eq(coupons.couponCode, couponCode),
|
|
})
|
|
return !!existing
|
|
}
|
|
|
|
export async function checkReservedCouponExists(secretCode: string): Promise<boolean> {
|
|
const existing = await db.query.reservedCoupons.findFirst({
|
|
where: eq(reservedCoupons.secretCode, secretCode),
|
|
})
|
|
return !!existing
|
|
}
|
|
|
|
export async function generateCancellationCoupon(
|
|
orderId: number,
|
|
staffUserId: number,
|
|
userId: number,
|
|
orderAmount: number,
|
|
couponCode: string,
|
|
regionId: number
|
|
): Promise<Coupon> {
|
|
const order = await db.query.orders.findFirst({
|
|
where: eq(orders.id, orderId),
|
|
columns: { id: true, regionId: true },
|
|
})
|
|
if (!order) {
|
|
throw new Error('Order not found')
|
|
}
|
|
if (order.regionId !== regionId) {
|
|
throw new Error('Order belongs to a different region')
|
|
}
|
|
|
|
return await db.transaction(async (tx) => {
|
|
const expiryDate = new Date()
|
|
expiryDate.setDate(expiryDate.getDate() + 30)
|
|
|
|
const [coupon] = await tx.insert(coupons).values({
|
|
regionId,
|
|
couponCode,
|
|
isUserBased: true,
|
|
flatDiscount: orderAmount.toString(),
|
|
minOrder: orderAmount.toString(),
|
|
maxValue: orderAmount.toString(),
|
|
validTill: expiryDate,
|
|
maxLimitForUser: 1,
|
|
createdBy: staffUserId,
|
|
isApplyForAll: false,
|
|
}).returning()
|
|
|
|
await tx.insert(couponApplicableUsers).values({
|
|
couponId: coupon.id,
|
|
userId,
|
|
})
|
|
|
|
await tx.update(orderStatus)
|
|
.set({ refundCouponId: coupon.id })
|
|
.where(eq(orderStatus.orderId, orderId))
|
|
|
|
return coupon as Coupon
|
|
})
|
|
}
|
|
|
|
export async function getOrderWithUser(regionId: number, orderId: number): Promise<any | null> {
|
|
return await db.query.orders.findFirst({
|
|
where: and(
|
|
eq(orders.id, orderId),
|
|
eq(orders.regionId, regionId)
|
|
),
|
|
with: {
|
|
user: true,
|
|
},
|
|
})
|
|
}
|
|
|
|
export async function createCouponForUser(
|
|
mobile: string,
|
|
couponCode: string,
|
|
staffUserId: number,
|
|
regionId: number
|
|
): Promise<{ coupon: Coupon; user: { id: number; mobile: string; name: string | null } }> {
|
|
return await db.transaction(async (tx) => {
|
|
let user = await tx.query.users.findFirst({
|
|
where: eq(users.mobile, mobile),
|
|
})
|
|
|
|
if (!user) {
|
|
const [newUser] = await tx.insert(users).values({
|
|
name: null,
|
|
email: null,
|
|
mobile,
|
|
}).returning()
|
|
user = newUser
|
|
}
|
|
|
|
const [coupon] = await tx.insert(coupons).values({
|
|
regionId,
|
|
couponCode,
|
|
isUserBased: true,
|
|
discountPercent: '20',
|
|
minOrder: '1000',
|
|
maxValue: '500',
|
|
maxLimitForUser: 1,
|
|
isApplyForAll: false,
|
|
exclusiveApply: false,
|
|
createdBy: staffUserId,
|
|
validTill: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000),
|
|
}).returning()
|
|
|
|
await tx.insert(couponApplicableUsers).values({
|
|
couponId: coupon.id,
|
|
userId: user.id,
|
|
})
|
|
|
|
return {
|
|
coupon: coupon as Coupon,
|
|
user: {
|
|
id: user.id,
|
|
mobile: user.mobile as string,
|
|
name: user.name,
|
|
},
|
|
}
|
|
})
|
|
}
|
|
|
|
export async function getUsersForCoupon(
|
|
regionId: number,
|
|
search?: string,
|
|
limit: number = 20,
|
|
offset: number = 0
|
|
): Promise<{ users: UserMiniInfo[] }> {
|
|
// Plain select, NOT db.query.users: the relational builder re-points every
|
|
// column reference inside a raw `where` fragment at the aliased main table,
|
|
// which turned this subquery into `users.user_id` / `users.region_id` — neither
|
|
// exists on users. A plain select renders the orders columns correctly.
|
|
const inRegion = sql`EXISTS (SELECT 1 FROM ${orders} WHERE ${orders.userId} = ${users.id} AND ${orders.regionId} = ${regionId})`
|
|
|
|
const term = search?.trim()
|
|
const whereCondition = term
|
|
? and(inRegion, or(like(users.name, `%${term}%`), like(users.mobile, `%${term}%`)))
|
|
: inRegion
|
|
|
|
const userList = await db
|
|
.select({
|
|
id: users.id,
|
|
name: users.name,
|
|
mobile: users.mobile,
|
|
})
|
|
.from(users)
|
|
.where(whereCondition)
|
|
.orderBy(asc(users.name))
|
|
.limit(limit)
|
|
.offset(offset)
|
|
|
|
return {
|
|
users: userList.map((user) => ({
|
|
id: user.id,
|
|
name: user.name || 'Unknown',
|
|
mobile: user.mobile,
|
|
}))
|
|
}
|
|
}
|