206 lines
7 KiB
TypeScript
206 lines
7 KiB
TypeScript
import { db } from '../db/db_index'
|
|
import {
|
|
couponApplicableUsers,
|
|
couponUsage,
|
|
coupons,
|
|
reservedCoupons,
|
|
} from '../db/schema'
|
|
import { and, eq, gt, isNull, or, sql } from 'drizzle-orm'
|
|
import type { InferSelectModel } from 'drizzle-orm'
|
|
import type { UserCoupon, UserCouponApplicableUser, UserCouponUsage, UserCouponWithRelations } from '@packages/shared'
|
|
|
|
type CouponRow = InferSelectModel<typeof coupons>
|
|
type CouponUsageRow = InferSelectModel<typeof couponUsage>
|
|
type CouponApplicableUserRow = InferSelectModel<typeof couponApplicableUsers>
|
|
type ReservedCouponRow = InferSelectModel<typeof reservedCoupons>
|
|
|
|
const mapCoupon = (coupon: CouponRow): UserCoupon => ({
|
|
id: coupon.id,
|
|
couponCode: coupon.couponCode,
|
|
isUserBased: coupon.isUserBased,
|
|
regionId: coupon.regionId ?? null,
|
|
discountPercent: coupon.discountPercent ? coupon.discountPercent.toString() : null,
|
|
flatDiscount: coupon.flatDiscount ? coupon.flatDiscount.toString() : null,
|
|
minOrder: coupon.minOrder ? coupon.minOrder.toString() : null,
|
|
skuIds: coupon.skuIds,
|
|
maxValue: coupon.maxValue ? coupon.maxValue.toString() : null,
|
|
isApplyForAll: coupon.isApplyForAll,
|
|
validTill: coupon.validTill ?? null,
|
|
maxLimitForUser: coupon.maxLimitForUser ?? null,
|
|
isInvalidated: coupon.isInvalidated,
|
|
exclusiveApply: coupon.exclusiveApply,
|
|
isFirstOrderOnly: coupon.isFirstOrderOnly,
|
|
createdAt: coupon.createdAt,
|
|
})
|
|
|
|
const mapUsage = (usage: CouponUsageRow): UserCouponUsage => ({
|
|
id: usage.id,
|
|
userId: usage.userId,
|
|
couponId: usage.couponId,
|
|
orderId: usage.orderId ?? null,
|
|
orderItemId: usage.orderItemId ?? null,
|
|
usedAt: usage.usedAt,
|
|
})
|
|
|
|
const mapApplicableUser = (applicable: CouponApplicableUserRow): UserCouponApplicableUser => ({
|
|
id: applicable.id,
|
|
couponId: applicable.couponId,
|
|
userId: applicable.userId,
|
|
})
|
|
|
|
const mapCouponWithRelations = (coupon: CouponRow & {
|
|
usages: CouponUsageRow[]
|
|
applicableUsers: CouponApplicableUserRow[]
|
|
}): UserCouponWithRelations => ({
|
|
...mapCoupon(coupon),
|
|
usages: coupon.usages.map(mapUsage),
|
|
applicableUsers: coupon.applicableUsers.map(mapApplicableUser),
|
|
})
|
|
|
|
export async function getActiveCouponsWithRelations(
|
|
userId: number,
|
|
regionId?: number
|
|
): Promise<UserCouponWithRelations[]> {
|
|
const regionCondition =
|
|
regionId != null
|
|
? or(isNull(coupons.regionId), eq(coupons.regionId, regionId))
|
|
: undefined
|
|
|
|
const allCoupons = await db.query.coupons.findMany({
|
|
where: and(
|
|
eq(coupons.isInvalidated, false),
|
|
or(
|
|
isNull(coupons.validTill),
|
|
gt(coupons.validTill, new Date())
|
|
),
|
|
regionCondition
|
|
),
|
|
with: {
|
|
usages: {
|
|
where: eq(couponUsage.userId, userId),
|
|
},
|
|
applicableUsers: true,
|
|
},
|
|
})
|
|
|
|
return allCoupons.map(mapCouponWithRelations)
|
|
}
|
|
|
|
export async function getAllCouponsWithRelations(
|
|
userId: number,
|
|
regionId?: number
|
|
): Promise<UserCouponWithRelations[]> {
|
|
const regionCondition =
|
|
regionId != null
|
|
? or(isNull(coupons.regionId), eq(coupons.regionId, regionId))
|
|
: undefined
|
|
|
|
const allCoupons = await db.query.coupons.findMany({
|
|
where: regionCondition,
|
|
with: {
|
|
usages: {
|
|
where: eq(couponUsage.userId, userId),
|
|
},
|
|
applicableUsers: true,
|
|
},
|
|
})
|
|
|
|
return allCoupons.map(mapCouponWithRelations)
|
|
}
|
|
|
|
export async function getReservedCouponByCode(secretCode: string): Promise<ReservedCouponRow | null> {
|
|
const reserved = await db.query.reservedCoupons.findFirst({
|
|
where: and(
|
|
eq(reservedCoupons.secretCode, secretCode.toUpperCase()),
|
|
eq(reservedCoupons.isRedeemed, false)
|
|
),
|
|
})
|
|
|
|
return reserved || null
|
|
}
|
|
|
|
export async function redeemReservedCoupon(userId: number, reservedCoupon: ReservedCouponRow): Promise<UserCoupon | null> {
|
|
// D1 has no interactive transactions (the repo's `db.transaction` wrapper is a
|
|
// pass-through), so use `db.batch`: D1 executes the statements as one
|
|
// transaction and rolls every one of them back if any fails. Issuance is tied
|
|
// to the claim by the guarded INSERTs, so a failure (e.g. a coupon_code
|
|
// collision) leaves the secret unredeemed instead of burning it.
|
|
//
|
|
// Every batch item must be a query-builder statement: raw `db.run(sql...)`
|
|
// has no prepared statement and crashes the D1 batch path (`stmt` is
|
|
// undefined), so both inserts are `insert().select()` over the reserved row.
|
|
const claimedGuard = and(
|
|
eq(reservedCoupons.id, reservedCoupon.id),
|
|
eq(reservedCoupons.isRedeemed, true),
|
|
eq(reservedCoupons.redeemedBy, userId)
|
|
)
|
|
const [claimed] = await db.batch([
|
|
// Claim the secret before creating anything: the conditional update closes the gap
|
|
// between getReservedCouponByCode and this write, so two customers racing on the same
|
|
// code can never both receive a coupon. A null return means the race was lost.
|
|
db
|
|
.update(reservedCoupons)
|
|
.set({
|
|
isRedeemed: true,
|
|
redeemedBy: userId,
|
|
redeemedAt: new Date(),
|
|
})
|
|
.where(
|
|
and(
|
|
eq(reservedCoupons.id, reservedCoupon.id),
|
|
eq(reservedCoupons.isRedeemed, false)
|
|
)
|
|
)
|
|
.returning({ id: reservedCoupons.id }),
|
|
|
|
// Only the caller that won the claim inserts a coupon. The values are copied
|
|
// from the reserved row inside the same transaction, so the display object
|
|
// passed in can never affect what is issued. Selected fields follow the
|
|
// coupons column order positionally.
|
|
db.insert(coupons).select(
|
|
db
|
|
.select({
|
|
id: sql`NULL`.as('id'),
|
|
regionId: reservedCoupons.regionId,
|
|
couponCode: reservedCoupons.couponCode,
|
|
isUserBased: sql`1`.as('is_user_based'),
|
|
discountPercent: reservedCoupons.discountPercent,
|
|
flatDiscount: reservedCoupons.flatDiscount,
|
|
minOrder: reservedCoupons.minOrder,
|
|
skuIds: reservedCoupons.skuIds,
|
|
createdBy: reservedCoupons.createdBy,
|
|
maxValue: reservedCoupons.maxValue,
|
|
isApplyForAll: sql`0`.as('is_apply_for_all'),
|
|
validTill: reservedCoupons.validTill,
|
|
maxLimitForUser: reservedCoupons.maxLimitForUser,
|
|
isInvalidated: sql`0`.as('is_invalidated'),
|
|
exclusiveApply: reservedCoupons.exclusiveApply,
|
|
isFirstOrderOnly: reservedCoupons.isFirstOrderOnly,
|
|
createdAt: sql`CURRENT_TIMESTAMP`.as('created_at'),
|
|
})
|
|
.from(reservedCoupons)
|
|
.where(claimedGuard)
|
|
),
|
|
|
|
// The coupon's code is unique, so this links exactly the row inserted above.
|
|
db.insert(couponApplicableUsers).select(
|
|
db
|
|
.select({
|
|
id: sql`NULL`.as('id'),
|
|
couponId: coupons.id,
|
|
userId: sql`${userId}`.as('user_id'),
|
|
})
|
|
.from(coupons)
|
|
.innerJoin(reservedCoupons, eq(coupons.couponCode, reservedCoupons.couponCode))
|
|
.where(claimedGuard)
|
|
),
|
|
])
|
|
|
|
if (claimed.length === 0) return null
|
|
|
|
const coupon = await db.query.coupons.findFirst({
|
|
where: eq(coupons.couponCode, reservedCoupon.couponCode),
|
|
})
|
|
|
|
return coupon ? mapCoupon(coupon) : null
|
|
}
|