import { db } from '../db/db_index' import { orders, orderItems, orderStatus, addresses, productInfo, productSkus, coupons, couponUsage, cartItems, units, userDetails, deliverySlotInfo, } from '../db/schema' import { and, eq, inArray, desc, sql } from 'drizzle-orm' import type { UserOrderSummary, UserOrderDetail, PlacedOrder, CouponUsageWithCoupon, } from '@packages/shared' import { coerceDate } from '../lib/date' import { runBatched } from '../lib/run-batched' import { attachOrderItems } from '../lib/order-items' import { composeSkuName, composeUnitNotation } from '../lib/sku-features' import { marketStatsForRegion } from '../lib/market-stats' import { computeEligibleSubtotal, type CartLine } from '@packages/shared' export interface OrderWithRelations { id: number userId: number regionId: number | null region: { id: number name: string } | null addressId: number slotId: number | null totalAmount: string deliveryCharge: string discountAmount: string isFlashDelivery: boolean userNotes: string | null orderGroupId: string | null orderGroupProportion: string | null createdAt: Date orderItems: Array<{ id: number skuId: number quantity: string price: string discountedPrice: string | null is_packaged: boolean sku: { id: number name: string | null images: unknown features: Array<{ featureName: string | null featureValue: string }> product: { name: string } | null } | null }> slot: { deliveryTime: Date } | null orderStatus: Array<{ id: number isCancelled: boolean isDelivered: boolean cancelReason: string | null }> } export type OrderDetailWithRelations = OrderWithRelations; export interface CouponValidationResult { id: number couponCode: string isInvalidated: boolean validTill: Date | null maxLimitForUser: number | null minOrder: string | null discountPercent: string | null flatDiscount: string | null maxValue: string | null usages: Array<{ id: number userId: number }> } export interface ValidatedCoupon extends CouponValidationResult { /** targeted SKU ids; null => applies to the whole cart */ applicableSkuIds: number[] | null /** the goods subtotal this coupon discounts (whole cart or the targeted items) */ eligibleSubtotal: number } /** * Validate every coupon the customer is trying to apply and return them in the * order they were requested (the caller's selection order) — coupons stack * sequentially, so this order is meaningful and must be preserved. Enforces: * - dedupe + existence * - exclusive coupons cannot be combined with any other coupon * - user-based applicability, invalidated, expiry, per-user usage limit * - region: a regional coupon is only valid in its own region * - first-order-only (via countEffectiveOrders) * - product targeting: the coupon must match at least one cart line, and * minOrder is compared against the ELIGIBLE (targeted) subtotal */ export async function validateAndGetCoupons(params: { couponIds: number[] userId: number regionId: number items: CartLine[] }): Promise { const ids = [...new Set(params.couponIds.filter((id) => Number.isFinite(id)))] if (ids.length === 0) return [] const rows = await db.query.coupons.findMany({ where: inArray(coupons.id, ids), with: { usages: { where: eq(couponUsage.userId, params.userId) }, applicableUsers: true, }, }) if (rows.length !== ids.length) { const found = new Set(rows.map((r) => r.id)) throw new Error( `Invalid coupon: ${ids.filter((id) => !found.has(id)).join(', ')}` ) } if (ids.length > 1 && rows.some((r) => r.exclusiveApply)) { throw new Error('An exclusive coupon cannot be combined with other coupons') } const byId = new Map(rows.map((r) => [r.id, r])) const isFirstOrder = (await countEffectiveOrders(params.userId)) === 0 const validated: ValidatedCoupon[] = [] for (const id of ids) { const coupon = byId.get(id)! const usages = coupon.usages ?? [] if (coupon.isUserBased && !coupon.isApplyForAll) { const applicableUsers = coupon.applicableUsers ?? [] if (!applicableUsers.some((au) => au.userId === params.userId)) { throw new Error('This coupon is not applicable to your account') } } if (coupon.isInvalidated) throw new Error('Coupon is no longer valid') if (coupon.validTill && new Date(coupon.validTill) < new Date()) { throw new Error('Coupon has expired') } if (coupon.maxLimitForUser && usages.length >= coupon.maxLimitForUser) { throw new Error('Coupon usage limit exceeded') } if (coupon.regionId != null && coupon.regionId !== params.regionId) { throw new Error('Coupon is not valid in this region') } if (coupon.isFirstOrderOnly && !isFirstOrder) { throw new Error( "This is first order only coupon. You already placed your first order. This coupon doesn't apply to you" ) } // Target SKUs live in the coupon's own `sku_ids` array (there is no join // table). Empty/null => the coupon applies to the whole cart. const applicableSkuIds = [ ...new Set( (Array.isArray(coupon.skuIds) ? coupon.skuIds : []) .map((skuId) => Number(skuId)) .filter((skuId) => Number.isFinite(skuId)) ), ] const targets = applicableSkuIds.length > 0 ? applicableSkuIds : null const eligibleSubtotal = computeEligibleSubtotal(params.items, { applicableSkuIds: targets, }) if (targets && eligibleSubtotal <= 0) { throw new Error('Coupon does not apply to any items in your cart') } if ( coupon.minOrder && parseFloat(coupon.minOrder.toString()) > eligibleSubtotal ) { throw new Error('Order amount does not meet coupon minimum requirement') } validated.push({ id: coupon.id, couponCode: coupon.couponCode, isInvalidated: coupon.isInvalidated, validTill: coupon.validTill ?? null, maxLimitForUser: coupon.maxLimitForUser ?? null, minOrder: coupon.minOrder ?? null, discountPercent: coupon.discountPercent ?? null, flatDiscount: coupon.flatDiscount ?? null, maxValue: coupon.maxValue ?? null, usages: usages.map((u) => ({ id: u.id, userId: u.userId })), applicableSkuIds: targets, eligibleSubtotal, }) } // Preserve the caller's (selection) order: coupons apply sequentially, so the // order changes the result and must not be re-sorted here. return validated } /** The discount fields a coupon row carries. `CouponValidationResult` and the coupon rows * loaded for order history both satisfy this, so callers never need a cast. */ export type CouponDiscountFields = Pick< CouponValidationResult, 'discountPercent' | 'flatDiscount' | 'maxValue' > /** * Applies a coupon to an order/sub-order and returns the post-discount total. * * `orderTotal` must be the item subtotal (sum of price × quantity) — not the paid total, which * already includes the discount and the delivery charge. The cap is prorated by `proportion` * so a multi-slot cart's per-sub-order discount is the same share placeOrder charged. */ export function applyDiscountToOrder( orderTotal: number, appliedCoupon: CouponDiscountFields | null, proportion: number ): { finalOrderTotal: number; discountAmount: number; orderGroupProportion: number } { let finalOrderTotal = orderTotal let discountAmount = 0 if (appliedCoupon) { if (appliedCoupon.discountPercent) { discountAmount = Math.min( (orderTotal * parseFloat(appliedCoupon.discountPercent.toString())) / 100, appliedCoupon.maxValue ? parseFloat(appliedCoupon.maxValue.toString()) * proportion : Infinity ) } else if (appliedCoupon.flatDiscount) { discountAmount = Math.min( parseFloat(appliedCoupon.flatDiscount.toString()) * proportion, appliedCoupon.maxValue ? parseFloat(appliedCoupon.maxValue.toString()) * proportion : orderTotal ) } finalOrderTotal -= discountAmount } return { finalOrderTotal, discountAmount, orderGroupProportion: proportion } } export async function getAddressByIdAndUser( addressId: number, userId: number ) { return db.query.addresses.findFirst({ where: and(eq(addresses.userId, userId), eq(addresses.id, addressId)), }) } export async function getProductById(skuId: number, regionId?: number | null) { const sku = await db.query.productSkus.findFirst({ where: eq(productSkus.id, skuId), with: { marketStats: true, product: true, }, }) if (!sku) { return null } // A global SKU has no product region — the caller's region decides which // market-stats row (and therefore price) applies. const region = regionId ?? sku.product?.regionId ?? null const marketStats = marketStatsForRegion(sku.marketStats, region) return { ...sku, marketStats, price: marketStats?.ourPrice ? String(marketStats.ourPrice) : '0', marketPrice: marketStats?.marketPrice ? String(marketStats.marketPrice) : null, flashPrice: marketStats?.flashPrice ? String(marketStats.flashPrice) : null, isFlashAvailable: marketStats?.isFlashAvailable ?? false, isOutOfStock: marketStats?.isOutOfStock ?? false, } } export async function checkUserSuspended(userId: number): Promise { const userDetail = await db.query.userDetails.findFirst({ where: eq(userDetails.userId, userId), }) return userDetail?.isSuspended ?? false } export async function getSlotCapacityStatus(slotId: number): Promise { const slot = await db.query.deliverySlotInfo.findFirst({ where: eq(deliverySlotInfo.id, slotId), columns: { isCapacityFull: true, }, }) return slot?.isCapacityFull ?? false } export async function placeOrderTransaction(params: { userId: number ordersData: Array<{ order: Omit orderItems: Omit[] orderStatus: Omit }> totalWithDelivery: number }): Promise { const { userId, ordersData } = params return db.transaction(async (tx) => { const ordersToInsert: Omit[] = ordersData.map((od) => ({ ...od.order, })) const insertedOrders = await tx.insert(orders).values(ordersToInsert).returning() const allOrderItems: Omit[] = [] const allOrderStatuses: Omit[] = [] insertedOrders.forEach((order, index) => { const od = ordersData[index] od.orderItems.forEach((item) => { allOrderItems.push({ ...item, orderId: order.id }) }) allOrderStatuses.push({ ...od.orderStatus, orderId: order.id, }) }) const chunkSize = 5 for (let i = 0; i < allOrderItems.length; i += chunkSize) { await tx.insert(orderItems).values(allOrderItems.slice(i, i + chunkSize)) } await tx.insert(orderStatus).values(allOrderStatuses) return insertedOrders as PlacedOrder[] }) } export async function deleteCartItemsForOrder( userId: number, skuIds: number[] ): Promise { await db.delete(cartItems).where( and( eq(cartItems.userId, userId), inArray(cartItems.skuId, skuIds) ) ) } export async function recordCouponUsage( userId: number, couponId: number, orderId: number ): Promise { await db.insert(couponUsage).values({ userId, couponId, orderId, orderItemId: null, usedAt: new Date(), }) } export async function getOrdersWithRelations( userId: number, offset: number, pageSize: number ): Promise { const ordersWithRelations = await db.query.orders.findMany({ where: eq(orders.userId, userId), with: { slot: { columns: { deliveryTime: true, }, }, orderStatus: { columns: { id: true, isCancelled: true, isDelivered: true, cancelReason: true, }, }, region: { columns: { id: true, name: true, }, }, }, orderBy: [desc(orders.createdAt)], limit: pageSize, offset: offset, }) const withItems = await attachOrderItems(ordersWithRelations) return withItems.map((order) => { const createdAt = coerceDate(order.createdAt) ?? new Date(0) const slot = order.slot ? { ...order.slot, deliveryTime: coerceDate(order.slot.deliveryTime) ?? new Date(0), } : null return { ...order, createdAt, slot, } }) as OrderWithRelations[] } export async function getOrderCount(userId: number): Promise { const result = await db .select({ count: sql`count(*)` }) .from(orders) .where(eq(orders.userId, userId)) return Number(result[0]?.count ?? 0) } /** * Number of DISTINCT order groups the user has that are not (fully) cancelled. * A split placement shares one `orderGroupId`, so it counts once; a cancelled * order does not count at all. This is the "has the customer actually ordered * yet?" signal used by first-order-only coupons — unlike `getOrderCount`, which * counts order rows (including cancelled ones) for pagination. */ export async function countEffectiveOrders(userId: number): Promise { const rows = await db .select({ id: orders.id, orderGroupId: orders.orderGroupId, isCancelled: orderStatus.isCancelled, }) .from(orders) .leftJoin(orderStatus, eq(orderStatus.orderId, orders.id)) .where(eq(orders.userId, userId)) const groups = new Set() for (const row of rows) { if (row.isCancelled === true) continue groups.add(row.orderGroupId ?? `order-${row.id}`) } return groups.size } export async function getOrderByIdWithRelations( orderId: number, userId: number ): Promise { const order = await db.query.orders.findFirst({ where: and(eq(orders.id, orderId), eq(orders.userId, userId)), with: { slot: { columns: { deliveryTime: true, }, }, orderStatus: { columns: { id: true, isCancelled: true, isDelivered: true, cancelReason: true, }, }, region: { columns: { id: true, name: true, }, }, }, }) if (!order) { return null } const [orderWithItems] = await attachOrderItems([order]) const createdAt = coerceDate(orderWithItems.createdAt) ?? new Date(0) const slot = orderWithItems.slot ? { ...orderWithItems.slot, deliveryTime: coerceDate(orderWithItems.slot.deliveryTime) ?? new Date(0), } : null return { ...orderWithItems, createdAt, slot, } as OrderDetailWithRelations } export async function getCouponUsageForOrder( orderId: number ): Promise { return db.query.couponUsage.findMany({ where: eq(couponUsage.orderId, orderId), with: { coupon: { columns: { id: true, couponCode: true, discountPercent: true, flatDiscount: true, maxValue: true, }, }, }, }) as Promise } /** * Coupon usages for a whole order group. A split placement records ONE usage row * (attached to the primary sub-order), so every sibling resolves the coupon via * the group rather than its own orderId. */ export async function getCouponUsageForOrderGroup( orderGroupId: string ): Promise { const groupOrders = await db .select({ id: orders.id }) .from(orders) .where(eq(orders.orderGroupId, orderGroupId)) const ids = groupOrders.map((o) => o.id) if (ids.length === 0) return [] return db.query.couponUsage.findMany({ where: inArray(couponUsage.orderId, ids), with: { coupon: { columns: { id: true, couponCode: true, discountPercent: true, flatDiscount: true, maxValue: true, }, }, }, }) as Promise } export async function getOrderBasic(orderId: number) { return db.query.orders.findFirst({ where: eq(orders.id, orderId), with: { orderStatus: { columns: { id: true, isCancelled: true, isDelivered: true, }, }, }, }) } /** * Deletes the coupon_usage row(s) of an order's group once EVERY sibling order * is cancelled — i.e. the coupon is only "restored" when the whole split * placement is cancelled. Safe to call inside the cancel transaction: the * just-written `is_cancelled = true` is visible to the same transaction. */ export async function releaseCouponUsageIfGroupFullyCancelled( tx: any, orderId: number ): Promise { const orderRows = await tx .select({ id: orders.id, orderGroupId: orders.orderGroupId }) .from(orders) .where(eq(orders.id, orderId)) const order = orderRows[0] if (!order) return const groupId: string | null = order.orderGroupId ?? null const groupOrders: Array<{ id: number }> = groupId ? await tx .select({ id: orders.id }) .from(orders) .where(eq(orders.orderGroupId, groupId)) : [{ id: order.id }] const ids = groupOrders.map((o: { id: number }) => o.id) if (ids.length === 0) return const statuses: Array<{ isCancelled: boolean | null }> = await tx .select({ isCancelled: orderStatus.isCancelled }) .from(orders) .leftJoin(orderStatus, eq(orderStatus.orderId, orders.id)) .where(inArray(orders.id, ids)) const allCancelled = statuses.length > 0 && statuses.every((s) => s.isCancelled === true) if (allCancelled) { await tx.delete(couponUsage).where(inArray(couponUsage.orderId, ids)) } } export async function cancelOrderTransaction( orderId: number, statusId: number, reason: string ): Promise { await db.transaction(async (tx) => { await tx .update(orderStatus) .set({ isCancelled: true, cancelReason: reason, cancellationUserNotes: reason, cancellationReviewed: false, }) .where(eq(orderStatus.id, statusId)) await releaseCouponUsageIfGroupFullyCancelled(tx, orderId) }) } export async function updateOrderNotes( orderId: number, userNotes: string ): Promise { await db .update(orders) .set({ userNotes: userNotes || null, }) .where(eq(orders.id, orderId)) } // ============================================================================ // Post-Order Handler Helpers (for Telegram notifications) // ============================================================================ export interface OrderWithFullData { id: number userId: number totalAmount: string isFlashDelivery: boolean address: { name: string | null addressLine1: string | null addressLine2: string | null city: string | null state: string | null phone: string | null } | null orderItems: Array<{ quantity: string sku: { product: { name: string } | null } | null }> slot: { deliveryTime: Date } | null } export async function getOrdersByIdsWithFullData( orderIds: number[] ): Promise { if (orderIds.length === 0) return [] const orderChunks = await runBatched(db, orderIds, 10, async (tx, chunk) => { return tx.query.orders.findMany({ where: inArray(orders.id, chunk), with: { address: { columns: { name: true, addressLine1: true, addressLine2: true, city: true, state: true, phone: true, }, }, slot: { columns: { deliveryTime: true, }, }, }, }) }) const withItems = await attachOrderItems(orderChunks.flat()) return withItems as unknown as OrderWithFullData[] } export type OrderWithCancellationData = OrderWithFullData export async function getOrderByIdWithFullData( orderId: number ): Promise { const order = await db.query.orders.findFirst({ where: eq(orders.id, orderId), with: { address: { columns: { name: true, addressLine1: true, addressLine2: true, city: true, state: true, phone: true, }, }, slot: { columns: { deliveryTime: true, }, }, }, }) if (!order) return null const [withItems] = await attachOrderItems([order]) return withItems as unknown as OrderWithCancellationData }