From 6239910707be8fc7715bbc5110e6222edd195906 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Sun, 11 Oct 2026 09:33:11 +0530 Subject: [PATCH] enh --- apps/backend/src/sqliteImporter.ts | 2 +- .../superadmin-apis/apis/global-coupons.ts | 170 ++++ .../apis/superadmin-trpc-index.ts | 2 + .../src/trpc/apis/user-apis/apis/coupon.ts | 12 +- .../src/trpc/apis/user-apis/apis/order.ts | 156 ++-- apps/backend/tests/BUGS.md | 27 +- apps/backend/tests/api/coupon-math.test.ts | 2 +- apps/backend/tests/api/coupon-ux.test.ts | 2 +- apps/backend/tests/api/coupons.test.ts | 6 +- .../tests/api/order-lifecycle-gaps.test.ts | 71 +- .../components/PaymentAndOrderComponent.tsx | 25 +- apps/user-ui/components/cart-page.tsx | 96 +- apps/user-ui/components/checkout-page.tsx | 57 +- apps/user-ui/tests/KNOWN-GAPS.md | 13 +- .../payment-and-order-money.test.tsx | 28 +- .../components/payment-and-order.test.tsx | 10 +- .../tests/screens/cart-coupons.test.tsx | 2 +- .../tests/screens/checkout-coupons.test.tsx | 2 +- .../screens/mutation-invalidation.test.tsx | 2 +- .../tests/screens/order-amounts.test.tsx | 9 +- change-log.txt | 868 ++++++++++++++++++ packages/db_helper_postgres/index.ts | 3 + .../src/admin-apis/order.ts | 42 +- packages/db_helper_postgres/src/db/schema.ts | 1 + .../db_helper_postgres/src/user-apis/order.ts | 90 ++ .../drizzle/0006_regions_and_superadmins.sql | 7 +- packages/db_helper_sqlite/index.ts | 14 +- .../db_helper_sqlite/src/admin-apis/coupon.ts | 29 +- .../db_helper_sqlite/src/admin-apis/order.ts | 40 +- .../src/admin-apis/product.ts | 8 +- packages/db_helper_sqlite/src/db/schema.ts | 3 +- .../src/superadmin-apis/global-coupons.ts | 53 ++ .../db_helper_sqlite/src/user-apis/coupon.ts | 24 +- .../db_helper_sqlite/src/user-apis/order.ts | 247 ++++- packages/shared/cart-pricing.ts | 209 +++++ packages/shared/types/coupon.types.ts | 2 +- 36 files changed, 2037 insertions(+), 297 deletions(-) create mode 100644 apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts create mode 100644 packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts create mode 100644 packages/shared/cart-pricing.ts diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts index 716987d..2f00d8d 100644 --- a/apps/backend/src/sqliteImporter.ts +++ b/apps/backend/src/sqliteImporter.ts @@ -206,7 +206,7 @@ export { getUserUnloggedToken, upsertUserUnloggedToken, // User - Order - validateAndGetUserCoupon, + validateAndGetUserCoupons, applyDiscountToUserOrder, getUserAddressByIdAndUser, getOrderProductById, diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts new file mode 100644 index 0000000..7dc78ab --- /dev/null +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts @@ -0,0 +1,170 @@ +import { router, superadminProcedure } from '@/src/trpc/trpc-index' +import { z } from 'zod' +import dayjs from 'dayjs' +import { ApiError } from '@/src/lib/api-error' +import { + listGlobalCoupons, + getGlobalCoupon, + createGlobalCoupon, + updateGlobalCoupon, + invalidateGlobalCoupon, + checkUsersExist, + checkCouponExists, +} from '@/src/dbService' +import type { Coupon, CouponFormInput } from '@packages/shared' + +const couponBodySchema = z.object({ + couponCode: z.string().optional(), + couponCodes: z.array(z.string()).optional(), + isUserBased: z.boolean().optional(), + discountPercent: z.number().optional(), + flatDiscount: z.number().optional(), + minOrder: z.number().optional(), + skuIds: z.array(z.number()).optional().nullable(), + applicableUsers: z.array(z.number()).optional(), + applicableProducts: z.array(z.number()).optional(), + maxValue: z.number().optional(), + isApplyForAll: z.boolean().optional(), + validTill: z.string().optional(), + maxLimitForUser: z.number().optional(), + exclusiveApply: z.boolean().optional(), + isFirstOrderOnly: z.boolean().optional(), +}) + +type CouponBody = z.infer + +function validateBody(input: CouponBody) { + if ((!input.discountPercent && !input.flatDiscount) || (input.discountPercent && input.flatDiscount)) { + throw new ApiError('Either discountPercent or flatDiscount must be provided (but not both)', 400) + } + if (input.isUserBased && (!input.applicableUsers || input.applicableUsers.length === 0) && !input.isApplyForAll) { + throw new ApiError('applicableUsers is required for user-based coupons (or set isApplyForAll to true)', 400) + } + if (input.isUserBased && input.isApplyForAll) { + throw new ApiError('Cannot be both user-based and apply for all users', 400) + } +} + +async function assertUsersExist(applicableUsers?: number[]) { + if (applicableUsers && applicableUsers.length > 0) { + const exist = await checkUsersExist(applicableUsers) + if (!exist) throw new ApiError('Some applicable users not found', 400) + } +} + +export const superadminGlobalCouponsRouter = router({ + list: superadminProcedure.query(async () => { + return { coupons: await listGlobalCoupons() } + }), + + get: superadminProcedure + .input(z.object({ id: z.number() })) + .query(async ({ input }) => { + const coupon = await getGlobalCoupon(input.id) + if (!coupon) throw new ApiError('Global coupon not found', 404) + return { coupon } + }), + + create: superadminProcedure + .input(couponBodySchema) + .mutation(async ({ input }) => { + validateBody(input) + await assertUsersExist(input.applicableUsers) + + let codes: string[] = input.couponCodes?.filter(Boolean) || [] + if (codes.length === 0 && input.couponCode) codes = [input.couponCode] + if (codes.length === 0) { + const timestamp = Date.now().toString().slice(-6) + const random = Math.random().toString(36).substring(2, 8).toUpperCase() + codes = [`MF${timestamp}${random}`] + } + + const createdCoupons: Coupon[] = [] + for (const code of codes) { + const finalCode = code.trim().toUpperCase() + if (await checkCouponExists(finalCode)) { + throw new ApiError(`Coupon code already exists: ${finalCode}`, 400) + } + const coupon = await createGlobalCoupon( + { + couponCode: finalCode, + isUserBased: input.isUserBased || false, + discountPercent: input.discountPercent?.toString() ?? null, + flatDiscount: input.flatDiscount?.toString() ?? null, + minOrder: input.minOrder?.toString() ?? null, + skuIds: input.skuIds || null, + createdBy: null, + maxValue: input.maxValue?.toString() ?? null, + isApplyForAll: input.isApplyForAll || false, + validTill: input.validTill ? dayjs(input.validTill).toDate() : null, + maxLimitForUser: input.maxLimitForUser ?? null, + exclusiveApply: input.exclusiveApply || false, + isFirstOrderOnly: input.isFirstOrderOnly || false, + isInvalidated: false, + }, + input.applicableUsers, + input.applicableProducts + ) + createdCoupons.push(coupon) + } + + return { coupons: createdCoupons, message: 'Global coupon(s) created successfully' } + }), + + update: superadminProcedure + .input( + couponBodySchema.extend({ + id: z.number(), + isInvalidated: z.boolean().optional(), + }) + ) + .mutation(async ({ input }) => { + const { id, ...updates } = input + if (updates.discountPercent !== undefined && updates.flatDiscount !== undefined) { + if (updates.discountPercent && updates.flatDiscount) { + throw new ApiError('Cannot have both discountPercent and flatDiscount', 400) + } + } + + const existing = await getGlobalCoupon(id) + if (!existing) throw new ApiError('Global coupon not found', 404) + + const updatedCode = updates.couponCodes?.[0]?.trim() || updates.couponCode + const updateData: CouponFormInput = { + couponCode: + updatedCode !== undefined && updatedCode !== '' + ? updatedCode.trim().toUpperCase() + : existing.couponCode, + isUserBased: updates.isUserBased ?? existing.isUserBased, + discountPercent: updates.discountPercent !== undefined ? (updates.discountPercent?.toString() ?? null) : existing.discountPercent, + flatDiscount: updates.flatDiscount !== undefined ? (updates.flatDiscount?.toString() ?? null) : existing.flatDiscount, + minOrder: updates.minOrder !== undefined ? (updates.minOrder?.toString() ?? null) : existing.minOrder, + skuIds: updates.skuIds !== undefined ? updates.skuIds : existing.skuIds ?? null, + maxValue: updates.maxValue !== undefined ? (updates.maxValue?.toString() ?? null) : existing.maxValue, + isApplyForAll: updates.isApplyForAll ?? existing.isApplyForAll, + validTill: updates.validTill !== undefined ? (updates.validTill ? dayjs(updates.validTill).toDate() : null) : existing.validTill, + maxLimitForUser: updates.maxLimitForUser ?? existing.maxLimitForUser, + exclusiveApply: updates.exclusiveApply ?? existing.exclusiveApply, + isFirstOrderOnly: updates.isFirstOrderOnly ?? existing.isFirstOrderOnly, + isInvalidated: updates.isInvalidated ?? existing.isInvalidated, + createdBy: existing.createdBy ?? null, + } + + const coupon = await updateGlobalCoupon( + id, + updateData, + updates.applicableUsers, + updates.applicableProducts + ) + if (!coupon) throw new ApiError('Global coupon not found', 404) + return { coupon, message: 'Global coupon updated successfully' } + }), + + delete: superadminProcedure + .input(z.object({ id: z.number() })) + .mutation(async ({ input }) => { + const coupon = await invalidateGlobalCoupon(input.id) + if (!coupon) throw new ApiError('Global coupon not found', 404) + return { message: 'Global coupon invalidated successfully' } + }), +}) diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts index 957f526..e0bac92 100644 --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts @@ -6,6 +6,7 @@ import { superadminConstRouter } from '@/src/trpc/apis/superadmin-apis/apis/cons import { superadminGlobalStoresRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-stores' import { superadminGlobalProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-products' import { superadminProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/products' +import { superadminGlobalCouponsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-coupons' export const superadminRouter = router({ auth: superadminAuthRouter, @@ -14,6 +15,7 @@ export const superadminRouter = router({ const: superadminConstRouter, globalStores: superadminGlobalStoresRouter, globalProducts: superadminGlobalProductsRouter, + globalCoupons: superadminGlobalCouponsRouter, products: superadminProductsRouter, }) diff --git a/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts b/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts index 3c1135e..d8533f6 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts @@ -6,7 +6,7 @@ import { getUserAllCouponsWithRelations as getUserAllCouponsWithRelationsInDb, getUserReservedCouponByCode as getUserReservedCouponByCodeInDb, redeemUserReservedCoupon as redeemUserReservedCouponInDb, - getUserOrderCount as getUserOrderCountInDb, + getUserEffectiveOrderCount as getUserOrderCountInDb, } from '@/src/dbService' import type { UserCouponDisplay, @@ -37,12 +37,13 @@ const generateCouponDescription = (coupon: { discountPercent?: string | null; fl export const userCouponRouter = router({ getEligible: protectedProcedure - .query(async ({ ctx }): Promise => { + .input(z.object({ regionId: z.number().int().positive().optional() }).optional()) + .query(async ({ ctx, input }): Promise => { try { const userId = ctx.user.userId; - const allCoupons = await getUserActiveCouponsWithRelationsInDb(userId) + const allCoupons = await getUserActiveCouponsWithRelationsInDb(userId, input?.regionId) // Filter to only coupons applicable to current user const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0; @@ -62,10 +63,11 @@ export const userCouponRouter = router({ }), getMyCoupons: protectedProcedure - .query(async ({ ctx }): Promise => { + .input(z.object({ regionId: z.number().int().positive().optional() }).optional()) + .query(async ({ ctx, input }): Promise => { const userId = ctx.user.userId; - const allCoupons = await getUserAllCouponsWithRelationsInDb(userId) + const allCoupons = await getUserAllCouponsWithRelationsInDb(userId, input?.regionId) // Filter coupons in JS: not invalidated, applicable to user, not expired, and first-order eligible const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0; diff --git a/apps/backend/src/trpc/apis/user-apis/apis/order.ts b/apps/backend/src/trpc/apis/user-apis/apis/order.ts index c73cd12..600d469 100644 --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts @@ -1,7 +1,6 @@ import { router, protectedProcedure } from "@/src/trpc/trpc-index"; import { z } from "zod"; import { - applyDiscountToUserOrder, cancelUserOrderTransaction, checkUserSuspended, composeUnitNotation, @@ -10,6 +9,7 @@ import { getOrderProductById, getUserAddressByIdAndUser, getUserCouponUsageForOrder, + getUserCouponUsageForOrderGroup, getUserOrderBasic, getUserOrderByIdWithRelations, getUserOrderCount, @@ -25,11 +25,12 @@ import { placeUserOrderTransaction, recordUserCouponUsage, updateUserOrderNotes, - validateAndGetUserCoupon, + validateAndGetUserCoupons, } from "@/src/dbService"; import { scaffoldAssetUrl } from "@/src/lib/s3-client"; import { ApiError } from "@/src/lib/api-error"; import type { DeliveryStatus, OrderStatus } from "@packages/shared"; +import { computeCartPricing, type CartLine } from "@packages/shared"; import { CONST_KEYS } from "@/src/lib/const-store"; import { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler"; import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker"; @@ -51,7 +52,7 @@ const placeOrderUtil = async (params: { }>; addressId: number; paymentMethod: "online" | "cod"; - couponId?: number; + couponIds?: number[]; userNotes?: string; isFlash?: boolean; }) => { @@ -60,7 +61,7 @@ const placeOrderUtil = async (params: { selectedItems, addressId, paymentMethod, - couponId, + couponIds, userNotes, } = params; @@ -200,47 +201,48 @@ const placeOrderUtil = async (params: { } let totalAmount = 0; + const subOrderSubtotals: number[] = []; + const subOrderInputs: { key: number | null; items: CartLine[] }[] = []; for (const [slotId, items] of ordersBySlot) { - const orderTotal = items.reduce( - (sum, item) => { - if (!item.product) return sum - const basePrice = params.isFlash - ? (item.product.flashPrice ?? item.product.price) - : item.product.price - const itemPrice = parseFloat((basePrice ?? 0).toString()) - return sum + itemPrice * item.quantity; - }, - 0 - ); + const lines: CartLine[] = []; + let orderTotal = 0; + for (const item of items) { + if (!item.product) continue; + const basePrice = params.isFlash + ? (item.product.flashPrice ?? item.product.price) + : item.product.price; + const unitPrice = parseFloat((basePrice ?? 0).toString()); + lines.push({ skuId: item.skuId, quantity: item.quantity, unitPrice }); + orderTotal += unitPrice * item.quantity; + } + subOrderInputs.push({ key: slotId, items: lines }); + subOrderSubtotals.push(orderTotal); totalAmount += orderTotal; } - const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount); + const validatedCoupons = await validateAndGetUserCoupons({ + couponIds: couponIds ?? [], + userId, + regionId: params.regionId, + items: subOrderInputs.flatMap((so) => so.items), + }); - // Mirror the customer app's pricing model: the coupon discounts the whole - // cart subtotal, and delivery is decided on the post-discount total. - let discountAmount = 0; - if (appliedCoupon) { - const maxValue = appliedCoupon.maxValue - ? parseFloat(appliedCoupon.maxValue.toString()) - : 0; + // The discount is computed on GOODS subtotals only (delivery — flash or + // scheduled — never enters the base), per sub-order, with multiple coupons + // stacking percentage-first and each capped by its own maxValue. + const pricing = computeCartPricing({ + subOrders: subOrderInputs, + coupons: validatedCoupons.map((c) => ({ + id: c.id, + discountPercent: c.discountPercent, + flatDiscount: c.flatDiscount, + maxValue: c.maxValue, + applicableSkuIds: c.applicableSkuIds, + })), + delivery: { threshold: freeDeliveryThreshold, charge: deliveryCharge }, + }); - if (appliedCoupon.discountPercent) { - const percentDiscount = - (totalAmount * parseFloat(appliedCoupon.discountPercent.toString())) / 100; - discountAmount = Math.min(percentDiscount, maxValue || Infinity); - } else if (appliedCoupon.flatDiscount) { - const flatDiscount = parseFloat(appliedCoupon.flatDiscount.toString()); - discountAmount = Math.min(flatDiscount, maxValue || totalAmount); - } - } - - const finalTotal = totalAmount - discountAmount; - - const expectedDeliveryCharge = - finalTotal < freeDeliveryThreshold ? deliveryCharge : 0; - - const totalWithDelivery = finalTotal + expectedDeliveryCharge; + const totalWithDelivery = pricing.grandTotal; type OrderData = { order: Omit; @@ -249,24 +251,15 @@ const placeOrderUtil = async (params: { }; const ordersData: OrderData[] = []; - let isFirstOrder = true; + let subOrderIndex = 0; for (const [slotId, items] of ordersBySlot) { - const subOrderTotal = items.reduce( - (sum, item) => { - if (!item.product) return sum - const basePrice = params.isFlash - ? (item.product.flashPrice ?? item.product.price) - : item.product.price - const itemPrice = parseFloat((basePrice ?? 0).toString()) - return sum + itemPrice * item.quantity; - }, - 0 - ); + const pricedSubOrder = pricing.subOrders[subOrderIndex]; + const subOrderTotal = pricedSubOrder.goodsSubtotal; const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0; - const orderDiscount = discountAmount * orderGroupProportion; - const orderDelivery = isFirstOrder ? expectedDeliveryCharge : 0; - const finalOrderAmount = subOrderTotal - orderDiscount + orderDelivery; + const orderDiscount = pricedSubOrder.discount; + const orderDelivery = pricedSubOrder.delivery; + const finalOrderAmount = pricedSubOrder.total; const order: Omit = { userId, @@ -278,6 +271,7 @@ const placeOrderUtil = async (params: { paymentInfoId: null, totalAmount: finalOrderAmount.toString(), deliveryCharge: orderDelivery.toString(), + discountAmount: orderDiscount.toString(), readableId: -1, userNotes: userNotes || null, orderGroupId, @@ -313,7 +307,7 @@ const placeOrderUtil = async (params: { }; ordersData.push({ order, orderItems: orderItemsData, orderStatus: orderStatusData }); - isFirstOrder = false; + subOrderIndex++; } const createdOrders = await placeUserOrderTransaction({ @@ -332,12 +326,14 @@ const placeOrderUtil = async (params: { selectedItems.map((item) => item.skuId) ); - if (appliedCoupon && createdOrders.length > 0) { - await recordUserCouponUsage( - userId, - appliedCoupon.id, - createdOrders[0].id - ); + if (validatedCoupons.length > 0 && createdOrders.length > 0) { + // One coupon_usage row per coupon, all attached to the primary sub-order + // (highest goods subtotal). Each sub-order's discount is stored on the order + // itself (discountAmount), so the split is not re-derived at display time. + const primaryOrder = createdOrders[pricing.primaryIndex] ?? createdOrders[0]; + for (const coupon of validatedCoupons) { + await recordUserCouponUsage(userId, coupon.id, primaryOrder.id); + } } console.log('publishing the order') @@ -361,7 +357,7 @@ export const orderRouter = router({ regionId: z.number().int().positive(), boundId: z.number().int().positive().optional(), paymentMethod: z.enum(["online", "cod"]), - couponId: z.number().int().positive().optional(), + couponIds: z.array(z.number().int().positive()).optional(), userNotes: z.string().optional(), isFlashDelivery: z.boolean().optional().default(false), }) @@ -380,7 +376,7 @@ export const orderRouter = router({ regionId, boundId, paymentMethod, - couponId, + couponIds, userNotes, isFlashDelivery, } = input; @@ -420,7 +416,7 @@ export const orderRouter = router({ selectedItems: processedItems, addressId, paymentMethod, - couponId, + couponIds, userNotes, isFlash: isFlashDelivery, }); @@ -547,36 +543,18 @@ export const orderRouter = router({ throw new Error("Order not found"); } - const couponUsageData = await getUserCouponUsageForOrder(order.id); + const couponUsageData = order.orderGroupId + ? await getUserCouponUsageForOrderGroup(order.orderGroupId) + : await getUserCouponUsageForOrder(order.id); let couponData = null; if (couponUsageData.length > 0) { - // The coupon discounts the item subtotal, not the paid total: orders.total_amount - // stores items − discount + delivery, so using it as the base inflated the discount. - const itemsSubtotal = order.orderItems.reduce( - (sum, item) => - sum + - parseFloat(item.price.toString()) * parseFloat(item.quantity.toString()), - 0 - ); - const proportion = Number(order.orderGroupProportion || 1); - let totalDiscountAmount = 0; - - for (const usage of couponUsageData) { - const { discountAmount } = applyDiscountToUserOrder( - itemsSubtotal, - usage.coupon, - proportion - ); - totalDiscountAmount += discountAmount; - } - + // The per-order discount is stored on the order itself (`discount_amount`), + // so the displayed amount always equals what was charged. couponData = { - couponCode: couponUsageData - .map((u) => u.coupon.couponCode) - .join(", "), + couponCode: couponUsageData.map((u) => u.coupon.couponCode).join(", "), couponDescription: `${couponUsageData.length} coupons applied`, - discountAmount: totalDiscountAmount, + discountAmount: parseFloat(order.discountAmount?.toString() || "0"), }; } diff --git a/apps/backend/tests/BUGS.md b/apps/backend/tests/BUGS.md index 4dded9a..1fba3cd 100644 --- a/apps/backend/tests/BUGS.md +++ b/apps/backend/tests/BUGS.md @@ -173,12 +173,12 @@ passing its id to `placeOrder`. **Pinned by:** `tests/api/coupon-ux.test.ts` — "rejects user B applying a coupon issued to user A". -> **Partially fixed (FC-04/SEC-06):** `validateAndGetCoupon` now loads -> `applicableUsers` and rejects a user-based coupon for anyone not listed (unless -> `isApplyForAll`). `skuIds` and region are **not** enforced, and that is now -> **policy, not a gap** (2026-10-10): coupons are global — neither region-based -> nor product/SKU-based — so they apply to any cart in any region. -> `exclusiveApply` remains unenforced. +> **FIXED 2026-10-11:** `validateAndGetCoupons` now enforces, per coupon: user-based +> applicability, `skuIds`/`coupon_applicable_products` product targeting (the coupon must +> match at least one cart line, and `minOrder` compares against the targeted subtotal), +> region (`coupons.regionId` null = global, else the order's region), and `exclusiveApply` +> (an exclusive coupon cannot be combined with any other). The customer coupon list +> (`getEligible`/`getMyCoupons`) is region-filtered too. ### 9. Cancelling an order does not release its coupon usage @@ -188,6 +188,12 @@ issued to user A". **Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: cancelling an order does not release its coupon usage". +> **FIXED 2026-10-11:** both cancel paths now delete the group's `coupon_usage` +> row(s) once **every** sibling order sharing the `orderGroupId` is cancelled +> (`releaseCouponUsageIfGroupFullyCancelled`, called from `cancelOrderTransaction` +> and admin `cancelOrder`). A lone order counts as "all" and releases on cancel. +> The lifecycle tests now assert the release. + ### 10. A cancelled first order poisons an `isFirstOrderOnly` coupon `getOrderCount` counts every order including cancelled ones, and @@ -197,6 +203,11 @@ order permanently blocks a first-order-only coupon for that user. **Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: a cancelled first order poisons an isFirstOrderOnly coupon". +> **FIXED 2026-10-11:** first-order eligibility now uses `countEffectiveOrders` +> — distinct, non-cancelled order groups (a split placement counts once, a +> cancelled order not at all). `getOrderCount` keeps its row-count meaning for +> pagination. The lifecycle test now asserts the coupon still applies. + ### 11. Reserved-coupon expiry is not checked at redemption — **FIXED 2026-10-10** `redeemReservedCoupon` checked "already redeemed" and first-order-only, but not @@ -218,6 +229,10 @@ Coupons carry `exclusiveApply`, and `placeOrder` accepts a single `couponId`, so the flag has no effect anywhere. (Observation from reading the code; no runtime test.) +> **FIXED 2026-10-11:** orders now accept `couponIds: number[]` and +> `validateAndGetCoupons` rejects any combination where one coupon is exclusive +> (it must be the only coupon on the order). + --- ## Medium — placeOrder guards diff --git a/apps/backend/tests/api/coupon-math.test.ts b/apps/backend/tests/api/coupon-math.test.ts index 7ce24d5..90cb065 100644 --- a/apps/backend/tests/api/coupon-math.test.ts +++ b/apps/backend/tests/api/coupon-math.test.ts @@ -95,7 +95,7 @@ describe('coupon discount maths', () => { addressId, regionId: 1, paymentMethod: 'cod', - ...(couponId ? { couponId } : {}), + ...(couponId ? { couponIds: [couponId] } : {}), }) as unknown as Promise const total = (res: Placed) => parseFloat(res.data[0].totalAmount) diff --git a/apps/backend/tests/api/coupon-ux.test.ts b/apps/backend/tests/api/coupon-ux.test.ts index e1cdb91..91ce8d1 100644 --- a/apps/backend/tests/api/coupon-ux.test.ts +++ b/apps/backend/tests/api/coupon-ux.test.ts @@ -73,7 +73,7 @@ describe('coupon UX', () => { addressId: user.addressId, regionId: 1, paymentMethod: 'cod', - ...(couponId ? { couponId } : {}), + ...(couponId ? { couponIds: [couponId] } : {}), }) describe('redeemReservedCoupon', () => { diff --git a/apps/backend/tests/api/coupons.test.ts b/apps/backend/tests/api/coupons.test.ts index 63cd28f..5e36c8f 100644 --- a/apps/backend/tests/api/coupons.test.ts +++ b/apps/backend/tests/api/coupons.test.ts @@ -80,8 +80,9 @@ describe('coupon CRUD + apply', () => { const placed = await user.user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, + regionId: 1, paymentMethod: 'cod', - couponId, + couponIds: [couponId], }) const orderId = placed.data[0].id @@ -103,8 +104,9 @@ describe('coupon CRUD + apply', () => { user.user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, + regionId: 1, paymentMethod: 'cod', - couponId, + couponIds: [couponId], }) ) diff --git a/apps/backend/tests/api/order-lifecycle-gaps.test.ts b/apps/backend/tests/api/order-lifecycle-gaps.test.ts index 39dec12..22d3d77 100644 --- a/apps/backend/tests/api/order-lifecycle-gaps.test.ts +++ b/apps/backend/tests/api/order-lifecycle-gaps.test.ts @@ -42,8 +42,9 @@ describe('order lifecycle gaps', () => { apiClient(userToken).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId, + regionId: 1, paymentMethod: 'cod', - ...(couponId ? { couponId } : {}), + ...(couponId ? { couponIds: [couponId] } : {}), }) const cancel = (id: number, reason = 'lifecycle test') => @@ -60,19 +61,19 @@ describe('order lifecycle gaps', () => { return created[0] } - it('pins: cancelling an order does not release its coupon usage', async () => { + it('releases the coupon usage when the (only) order is cancelled', async () => { const coupon = await createCoupon({ flatDiscount: 5, maxLimitForUser: 1 }) const placed = await place(coupon.id) await cancel(placed.data[0].id) - // The usage row recorded at placement is not removed on cancel, so the - // (now unused) coupon is already exhausted for this user. - const error = await captureError(() => place(coupon.id)) - expect(error.message).toMatch(/usage limit/i) + // The usage row is deleted once every sibling order is cancelled, so the + // (now unused) coupon is spendable again. + const again = await place(coupon.id) + expect(again.success).toBe(true) }) - it('pins: a cancelled first order poisons an isFirstOrderOnly coupon', async () => { + it('does not poison an isFirstOrderOnly coupon when the first order is cancelled', async () => { const buyer = await registerUserWithAddress() const coupon = await createCoupon({ flatDiscount: 5, isFirstOrderOnly: true }) @@ -80,6 +81,7 @@ describe('order lifecycle gaps', () => { const first = await apiClient(buyer.token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId: buyer.addressId, + regionId: 1, paymentMethod: 'cod', }) await apiClient(buyer.token).user.order.cancelOrder.mutate({ @@ -87,16 +89,59 @@ describe('order lifecycle gaps', () => { reason: 'changed mind', }) - // getOrderCount counts cancelled orders too, so the coupon is now refused. - const error = await captureError(() => + // countEffectiveOrders ignores cancelled orders, so the user is still a + // first-order customer and the coupon applies. + const res = await apiClient(buyer.token).user.order.placeOrder.mutate({ + selectedItems: [{ skuId, quantity: 1, slotId }], + addressId: buyer.addressId, + regionId: 1, + paymentMethod: 'cod', + couponIds: [coupon.id], + }) + expect(res.success).toBe(true) + }) + + it('keeps the coupon while a sibling order survives, releasing only when all are cancelled', async () => { + const buyer = await registerUserWithAddress() + const secondSlot = await createFutureSlot([skuId]) + const coupon = await createCoupon({ flatDiscount: 5, maxLimitForUser: 1 }) + + const placed = await apiClient(buyer.token).user.order.placeOrder.mutate({ + selectedItems: [ + { skuId, quantity: 1, slotId }, + { skuId, quantity: 1, slotId: secondSlot.slotId }, + ], + addressId: buyer.addressId, + regionId: 1, + paymentMethod: 'cod', + couponIds: [coupon.id], + }) + expect(placed.data).toHaveLength(2) + + const placeAgain = () => apiClient(buyer.token).user.order.placeOrder.mutate({ selectedItems: [{ skuId, quantity: 1, slotId }], addressId: buyer.addressId, + regionId: 1, paymentMethod: 'cod', - couponId: coupon.id, + couponIds: [coupon.id], }) - ) - expect(error.message).toMatch(/first order only/i) + + // Cancel one sibling: the coupon stays attached to the surviving order. + await apiClient(buyer.token).user.order.cancelOrder.mutate({ + id: placed.data[0].id, + reason: 'partial', + }) + const stillUsed = await captureError(() => placeAgain()) + expect(stillUsed.message).toMatch(/usage limit/i) + + // Cancel the last sibling: now the coupon is released. + await apiClient(buyer.token).user.order.cancelOrder.mutate({ + id: placed.data[1].id, + reason: 'rest', + }) + const again = await placeAgain() + expect(again.success).toBe(true) }) it('applies an isFirstOrderOnly coupon to a genuinely new user', async () => { @@ -107,7 +152,7 @@ describe('order lifecycle gaps', () => { selectedItems: [{ skuId, quantity: 1, slotId }], addressId: buyer.addressId, paymentMethod: 'cod', - couponId: coupon.id, + couponIds: [coupon.id], }) expect(res.success).toBe(true) diff --git a/apps/user-ui/components/PaymentAndOrderComponent.tsx b/apps/user-ui/components/PaymentAndOrderComponent.tsx index 04220f3..75782b8 100644 --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx +++ b/apps/user-ui/components/PaymentAndOrderComponent.tsx @@ -15,7 +15,7 @@ import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons'; interface PaymentAndOrderProps { selectedAddress: number | null; selectedSlots: Record; - selectedCouponId: number | null; + selectedCouponIds: number[]; cartItems: any[]; totalPrice: number; totalSavings?: number; @@ -32,7 +32,7 @@ interface PaymentAndOrderProps { const PaymentAndOrderComponent: React.FC = ({ selectedAddress, selectedSlots, - selectedCouponId, + selectedCouponIds, cartItems, totalPrice, totalSavings = 0, @@ -89,12 +89,18 @@ const PaymentAndOrderComponent: React.FC = ({ if (!firstOrder.isCod) { // createRazorpayOrderMutation.mutate({ orderId: firstOrder.id.toString() }); } else { - // Clear cart and navigate to success page + // Clear cart and navigate to success page. Prefer the amount the server + // actually stored across the (possibly split) orders over the local preview. clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular'); const successPath = isFlashDelivery ? '/(drawer)/(tabs)/flash-delivery/order-success' : './order-success'; - router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${finalTotalWithDelivery}`); + const serverTotal = orders.reduce( + (sum, order) => sum + Number(order.totalAmount ?? 0), + 0 + ); + const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery; + router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${successAmount}`); } }, onError: (error: any) => { @@ -117,12 +123,17 @@ const PaymentAndOrderComponent: React.FC = ({ const orders = placeOrderMutation.data?.data || []; const firstOrder = orders[0]; utils.user.order.getOrders.invalidate(); - // Clear cart and navigate to success page + // Clear cart and navigate to success page, using the server-stored amount. clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular'); const successPath = isFlashDelivery ? '/(drawer)/(tabs)/flash-delivery/order-success' : './order-success'; - router.replace(`${successPath}?orderId=${firstOrder?.id}&totalAmount=${finalTotalWithDelivery}`); + const serverTotal = orders.reduce( + (sum, order) => sum + Number(order.totalAmount ?? 0), + 0 + ); + const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery; + router.replace(`${successPath}?orderId=${firstOrder?.id}&totalAmount=${successAmount}`); }, onError: (error: any) => { Alert.alert('Error', error.message || 'Payment verification failed'); @@ -179,7 +190,7 @@ const PaymentAndOrderComponent: React.FC = ({ regionId: selectedRegionId, boundId: constsData?.boundId ?? activeBoundId ?? undefined, paymentMethod: paymentMethod, - couponId: selectedCouponId || undefined, + couponIds: selectedCouponIds.length ? selectedCouponIds : undefined, userNotes: userNotes, isFlashDelivery: isFlashDelivery, }; diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx index 5fca978..a738808 100644 --- a/apps/user-ui/components/cart-page.tsx +++ b/apps/user-ui/components/cart-page.tsx @@ -29,11 +29,13 @@ import { useCentralProductStore } from '@/src/store/centralProductStore'; import { useCentralSlotStore } from '@/src/store/centralSlotStore'; import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks'; import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks'; +import { useRegion } from '@/src/hooks/useRegion'; import CheckoutAddressSelector from '@/components/CheckoutAddressSelector'; import LoginWall from '@/components/LoginWall'; import { useAddressStore } from '@/src/store/addressStore'; import { useCheckoutStore } from '@/src/store/checkoutStore'; import type { FlashDeliveryProps } from '@packages/shared'; +import { computeCouponDiscount, computeEligibleSubtotal, type CartLine } from '@packages/shared'; const formatDeliverySlot = (deliveryTime: string): string => { const time = dayjs(deliveryTime); @@ -187,6 +189,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular"; const { selectedAddressId, setSelectedAddressId } = useAddressStore(); + const { regionId } = useRegion(); const userNotes = useCheckoutStore((state) => state.userNotes); const setUserNotes = useCheckoutStore((state) => state.setUserNotes); @@ -231,7 +234,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps }; const { data: couponsRaw, error: couponsError } = trpc.user.coupon.getEligible.useQuery( - undefined, + { regionId: regionId ?? undefined }, { enabled: isAuthenticated } ); const constsData = useRegionalConsts(); @@ -293,6 +296,13 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined, description: generateCouponDescription(coupon), exclusiveApply: coupon.exclusiveApply, + // Raw fields so the shared coupon helpers can be used directly. + discountPercent: coupon.discountPercent, + flatDiscount: coupon.flatDiscount, + applicableSkuIds: [ + ...(coupon.applicableProducts || []).map((p: any) => p.skuId), + ...(Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []), + ], isEligible, ineligibilityReason: isEligible ? undefined : ineligibilityReason, }; @@ -314,7 +324,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps refetchSlots(); }); const [selectedSlots, setSelectedSlots] = useState>({}); - const [selectedCouponId, setSelectedCouponId] = useState(null); + const [selectedCouponIds, setSelectedCouponIds] = useState([]); const [couponDialogOpen, setCouponDialogOpen] = useState(false); const router = useRouter(); @@ -353,12 +363,30 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps // Calculate coupon discount const selectedCoupons = useMemo( () => - selectedCouponId - ? eligibleCoupons?.filter( - (coupon) => coupon.id === selectedCouponId && coupon.isEligible - ) - : [], - [eligibleCoupons, selectedCouponId] + eligibleCoupons?.filter( + (coupon) => selectedCouponIds.includes(coupon.id) && coupon.isEligible + ) ?? [], + [eligibleCoupons, selectedCouponIds] + ); + + // Cart lines (in-stock only) with their effective unit price, in the shared + // shape the coupon helpers expect. + const cartLines = useMemo( + () => + cartItems + .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) + .map((item) => { + const product = productsById[item.skuId]; + const unitPrice = isFlashDelivery + ? (product?.flashPrice ?? product?.price ?? 0) + : (product?.price || 0); + return { + skuId: item.skuId, + quantity: quantities[item.id] || item.quantity, + unitPrice: Number(unitPrice), + }; + }), + [cartItems, productSlotsMap, productsById, isFlashDelivery, quantities] ); const totalPrice = cartItems @@ -384,13 +412,10 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps const dropdownData = useMemo( () => eligibleCoupons?.map((coupon) => { - const discount = - coupon.discountType === "percentage" - ? Math.min( - (totalPrice * coupon.discountValue) / 100, - coupon.maxValue || Infinity - ) - : Math.min(coupon.discountValue, coupon.maxValue || totalPrice); + const discount = computeCouponDiscount( + computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }), + coupon + ); const saveString = !isNaN(discount) ? ` (Save ₹${discount})` : ""; const baseLabel = `${coupon.code} - ${coupon.description}${coupon.isEligible ? saveString : "" }`; @@ -403,7 +428,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps disabled: !coupon.isEligible, }; }) || [], - [eligibleCoupons, totalPrice] + [eligibleCoupons, cartLines] ); const discountAmount = useMemo( @@ -411,15 +436,13 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps selectedCoupons?.reduce( (sum, coupon) => sum + - (coupon.discountType === "percentage" - ? Math.min( - (totalPrice * coupon.discountValue) / 100, - coupon.maxValue || Infinity - ) - : Math.min(coupon.discountValue, coupon.maxValue || totalPrice)), + computeCouponDiscount( + computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }), + coupon + ), 0 ) || 0, - [selectedCoupons, totalPrice] + [selectedCoupons, cartLines] ); const finalTotal = totalPrice - discountAmount; @@ -1066,10 +1089,21 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps { - setSelectedCouponId(value ? Number(value) : null); + if (!value) return; + const id = Number(value); + const coupon = eligibleCoupons.find((c) => c.id === id); + if (!coupon) return; + setSelectedCouponIds((prev) => { + if (prev.includes(id)) return prev; + const hasExclusive = prev.some( + (pid) => eligibleCoupons.find((c) => c.id === pid)?.exclusiveApply + ); + // An exclusive coupon replaces every other selection. + if (coupon.exclusiveApply || hasExclusive) return [id]; + return [...prev, id]; + }); }} placeholder={ eligibleCoupons.length === 0 @@ -1086,13 +1120,13 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps - {selectedCouponId && ( + {selectedCouponIds.length > 0 && ( setSelectedCouponId(null)} + onPress={() => setSelectedCouponIds([])} > - Remove coupon + Remove coupons )} @@ -1176,7 +1210,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps Coupon Applied setCouponDialogOpen(true)}> - {selectedCoupons[0].code} + {selectedCoupons.map((coupon) => coupon.code).join(', ')} )} @@ -1321,7 +1355,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps .join(';'); router.push( - `${isFlashDelivery ? '/(drawer)/(tabs)/flash-delivery/checkout' : '/(drawer)/(tabs)/home/checkout'}?slots=${encodeURIComponent(slotParams)}${selectedCouponId ? `&coupons=${selectedCouponId}` : ''}&deliveryPrice=${deliveryCharge}` as any + `${isFlashDelivery ? '/(drawer)/(tabs)/flash-delivery/checkout' : '/(drawer)/(tabs)/home/checkout'}?slots=${encodeURIComponent(slotParams)}${selectedCouponIds.length ? `&coupons=${selectedCouponIds.join(',')}` : ''}&deliveryPrice=${deliveryCharge}` as any ); }} > diff --git a/apps/user-ui/components/checkout-page.tsx b/apps/user-ui/components/checkout-page.tsx index dd8499b..6da5700 100644 --- a/apps/user-ui/components/checkout-page.tsx +++ b/apps/user-ui/components/checkout-page.tsx @@ -17,6 +17,7 @@ import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent'; import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay'; import { useAddressStore } from '@/src/store/addressStore'; import type { FlashDeliveryProps } from '@packages/shared'; +import { computeCouponDiscount, computeEligibleSubtotal, type CartLine } from '@packages/shared'; const CheckoutPage: React.FC = ({ isFlashDelivery = false }) => { const params = useLocalSearchParams(); @@ -56,7 +57,7 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) }); const { selectedAddressId } = useAddressStore(); - const [selectedCouponId, setSelectedCouponId] = useState(null); + const [selectedCouponIds, setSelectedCouponIds] = useState([]); @@ -131,8 +132,11 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) React.useEffect(() => { if (params.coupons) { - const couponId = Number(params.coupons as string); - setSelectedCouponId(couponId); + const ids = String(params.coupons) + .split(',') + .map((value) => Number(value)) + .filter((value) => Number.isFinite(value)); + setSelectedCouponIds(ids); } }, [params.coupons]); @@ -162,7 +166,7 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) ); const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery( - undefined, + { regionId: regionId ?? undefined }, { enabled: isAuthenticated } ); @@ -188,6 +192,12 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined, description: '', exclusiveApply: coupon.exclusiveApply, + discountPercent: coupon.discountPercent, + flatDiscount: coupon.flatDiscount, + applicableSkuIds: [ + ...(coupon.applicableProducts || []).map((p: any) => p.skuId), + ...(Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []), + ], isEligible, ineligibilityReason: isEligible ? undefined : ineligibilityReason, }; @@ -196,28 +206,39 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) const selectedCoupons = useMemo( () => - selectedCouponId - ? eligibleCoupons?.filter( - (coupon) => coupon.id === selectedCouponId && coupon.isEligible - ) - : [], - [eligibleCoupons, selectedCouponId] + eligibleCoupons?.filter( + (coupon) => selectedCouponIds.includes(coupon.id) && coupon.isEligible + ) ?? [], + [eligibleCoupons, selectedCouponIds] ); + // Lines being ordered, with their effective unit price, for the shared helpers. + const cartLines = useMemo( + () => + selectedItems + .filter((item) => !productSlotsMap[item.skuId]?.isOutOfStock) + .map((item) => { + const product = productsById[item.skuId]; + const unitPrice = isFlashDelivery + ? (product?.flashPrice ?? product?.price ?? 0) + : (product?.price || 0); + return { skuId: item.skuId, quantity: item.quantity, unitPrice: Number(unitPrice) }; + }), + [selectedItems, productSlotsMap, productsById, isFlashDelivery] + ); + const discountAmount = useMemo( () => selectedCoupons?.reduce( (sum, coupon) => sum + - (coupon.discountType === "percentage" - ? Math.min( - (totalPrice * coupon.discountValue) / 100, - coupon.maxValue || Infinity - ) - : Math.min(coupon.discountValue, coupon.maxValue || totalPrice)), + computeCouponDiscount( + computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }), + coupon + ), 0 ) || 0, - [selectedCoupons, totalPrice] + [selectedCoupons, cartLines] ); const finalTotal = totalPrice - discountAmount; @@ -365,7 +386,7 @@ const CheckoutPage: React.FC = ({ isFlashDelivery = false }) { discountAmount={20} finalTotal={195} finalTotalWithDelivery={210} - selectedCouponId={77} + selectedCouponIds={[77]} />, { centralStores: false } ) @@ -125,7 +125,7 @@ describe('PaymentAndOrderComponent money', () => { }) renderWithProviders( - , + , { centralStores: false } ) @@ -133,10 +133,30 @@ describe('PaymentAndOrderComponent money', () => { await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) const input = lastProcedureInput(api.fetchMock, 'user.order.placeOrder') as Record - expect(input.couponId).toBe(77) + expect(input.couponIds).toEqual([77]) expect(input.isFlashDelivery).toBe(false) }) + it('uses the server-stored order amount for the success URL when present', async () => { + const api = setupApiMocks({ + procedures: { + 'user.order.placeOrder': { data: [{ id: 99, isCod: true, totalAmount: '400' }] }, + }, + }) + + renderWithProviders(, { centralStores: false }) + + fireEvent.press(screen.getByTestId('place-order-button')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) + // baseProps.finalTotalWithDelivery is 230; the server total (400) wins. + await waitFor(() => + expect(routerMock.replace).toHaveBeenCalledWith( + './order-success?orderId=99&totalAmount=400' + ) + ) + }) + it('places a flash order with null slots and clears the flash cart only', async () => { const api = setupApiMocks({ procedures: { 'user.order.placeOrder': PLACE_ORDER_OK }, diff --git a/apps/user-ui/tests/components/payment-and-order.test.tsx b/apps/user-ui/tests/components/payment-and-order.test.tsx index eb0dee0..131cb53 100644 --- a/apps/user-ui/tests/components/payment-and-order.test.tsx +++ b/apps/user-ui/tests/components/payment-and-order.test.tsx @@ -19,7 +19,7 @@ import { renderWithProviders } from '../helpers/render' const baseProps = { selectedAddress: 1, selectedSlots: { 1: 1849 }, - selectedCouponId: null, + selectedCouponIds: [], cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }], totalPrice: 215, totalSavings: 0, @@ -87,7 +87,7 @@ describe('PaymentAndOrderComponent', () => { selectedItems: [{ skuId: 2, quantity: 1, slotId: 1849 }], addressId: 1, paymentMethod: 'cod', - couponId: undefined, + couponIds: undefined, userNotes: '', isFlashDelivery: false, }) @@ -105,7 +105,7 @@ describe('PaymentAndOrderComponent', () => { renderWithProviders( { renderWithProviders( { await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({ - couponId: 77, + couponIds: [77], }) }) diff --git a/apps/user-ui/tests/screens/cart-coupons.test.tsx b/apps/user-ui/tests/screens/cart-coupons.test.tsx index 94ba4e9..0bc73d5 100644 --- a/apps/user-ui/tests/screens/cart-coupons.test.tsx +++ b/apps/user-ui/tests/screens/cart-coupons.test.tsx @@ -171,7 +171,7 @@ describe('Cart coupon application', () => { await selectCoupon() expect(screen.getByText('-₹43')).toBeVisible() - fireEvent.press(screen.getByText('Remove coupon')) + fireEvent.press(screen.getByText('Remove coupons')) expect(screen.queryByText('Product Discount')).toBeNull() expect(screen.queryByText('Coupon Applied')).toBeNull() diff --git a/apps/user-ui/tests/screens/checkout-coupons.test.tsx b/apps/user-ui/tests/screens/checkout-coupons.test.tsx index 2745436..098cecd 100644 --- a/apps/user-ui/tests/screens/checkout-coupons.test.tsx +++ b/apps/user-ui/tests/screens/checkout-coupons.test.tsx @@ -197,7 +197,7 @@ describe('Checkout coupon discount calculation', () => { expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({ selectedItems: [{ skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID }], addressId: 1, - couponId: COUPON_ID, + couponIds: [COUPON_ID], paymentMethod: 'cod', }) await waitFor(() => diff --git a/apps/user-ui/tests/screens/mutation-invalidation.test.tsx b/apps/user-ui/tests/screens/mutation-invalidation.test.tsx index 5f7eb3c..96158f5 100644 --- a/apps/user-ui/tests/screens/mutation-invalidation.test.tsx +++ b/apps/user-ui/tests/screens/mutation-invalidation.test.tsx @@ -80,7 +80,7 @@ const ORDER = { const baseProps = { selectedAddress: 1, selectedSlots: { 1: 1849 }, - selectedCouponId: null, + selectedCouponIds: [], cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }], totalPrice: 215, totalSavings: 0, diff --git a/apps/user-ui/tests/screens/order-amounts.test.tsx b/apps/user-ui/tests/screens/order-amounts.test.tsx index b7d9153..f017f74 100644 --- a/apps/user-ui/tests/screens/order-amounts.test.tsx +++ b/apps/user-ui/tests/screens/order-amounts.test.tsx @@ -66,11 +66,10 @@ describe('Order success amounts', () => { }) /** - * KNOWN GAP: `totalAmount` is the frontend's `finalTotalWithDelivery` written - * into the query string by PaymentAndOrderComponent, not the amount the - * backend stored on the order. The multi-slot discount is scaled by - * `orderGroupProportion` server-side but not in the UI, so this number can - * differ from what was charged. Pinned as-is. + * The success screen renders whatever `totalAmount` sits in the route params. + * Since 2026-10-11 `PaymentAndOrderComponent` writes the server-stored order + * total there (see payment-and-order-money.test.tsx "uses the server-stored + * order amount…"), but this screen itself still just prints the param. */ it('renders whatever amount the caller put in the query string', async () => { searchParamsMock.current = { orderId: '99', totalAmount: '1234.56' } diff --git a/change-log.txt b/change-log.txt index c699d56..9047b52 100644 --- a/change-log.txt +++ b/change-log.txt @@ -3457,3 +3457,871 @@ user-ui regional product, so products/tags/groups needed no change. Effect: global SKUs can be attached to a slot/banner and ordered (scheduled delivery included); another region's SKU is still rejected everywhere. No schema change. No migration. No drizzle migrations run. + +[2026-10-11 08:57:11 +0530] Base fixes before multi/product/region coupons: + per-order discount + products-only base + cancel-restore + status-aware getOrderCount. + New file: packages/shared/cart-pricing.ts + + --- /dev/null + +++ b/packages/shared/cart-pricing.ts + @@ + +/** + + * Cart/coupon money helpers shared by the backend (authoritative) and the + + * order-detail recomputes. The discount base is ALWAYS the goods subtotal — + + * delivery (flash or scheduled) is never part of the discount base. + + */ + + + +export interface CouponMoney { + + discountPercent?: string | number | null + + flatDiscount?: string | number | null + + maxValue?: string | number | null + +} + + + +const toNum = (v: string | number | null | undefined): number => { + + if (v == null) return 0 + + const n = typeof v === 'number' ? v : parseFloat(v) + + return Number.isFinite(n) ? n : 0 + +} + + + +/** + + * Total coupon discount for a GOODS subtotal (delivery excluded by construction). + + * percent: min(subtotal * pct / 100, maxValue || Infinity) + + * flat: min(flat, maxValue || subtotal) + + * Never returns more than the subtotal. + + */ + +export function computeCartDiscount(goodsSubtotal: number, coupon?: CouponMoney | null): number { + + if (!coupon || goodsSubtotal <= 0) return 0 + + const maxValue = toNum(coupon.maxValue) + + const pct = toNum(coupon.discountPercent) + + const flat = toNum(coupon.flatDiscount) + + let discount = 0 + + if (pct) { + + discount = Math.min((goodsSubtotal * pct) / 100, maxValue || Infinity) + + } else if (flat) { + + discount = Math.min(flat, maxValue || goodsSubtotal) + + } + + if (discount < 0) discount = 0 + + if (discount > goodsSubtotal) discount = goodsSubtotal + + return discount + +} + + + +/** + + * Split a cart-level discount across sub-orders by their goods subtotal. No + + * rounding is applied (matches the current unrounded storage); the mathematical + + * sum equals `totalDiscount`. + + */ + +export function allocateDiscount(totalDiscount: number, subtotals: number[]): number[] { + + const goods = subtotals.reduce((s, v) => s + v, 0) + + if (totalDiscount <= 0 || goods <= 0) return subtotals.map(() => 0) + + return subtotals.map((sub) => (totalDiscount * sub) / goods) + +} + + + +/** + + * Discount applied to ONE sub-order, given that sub-order's goods subtotal and + + * its stored `orderGroupProportion`. Equivalent to + + * `computeCartDiscount(cartGoods, coupon) * proportion` — used by the order-detail + + * recomputes so the displayed discount always equals the charged discount. + + */ + +export function couponDiscountForSubOrder( + + subOrderSubtotal: number, + + coupon: CouponMoney | null | undefined, + + proportion: number + +): number { + + const p = proportion > 0 ? proportion : 1 + + const cartGoods = subOrderSubtotal / p + + return computeCartDiscount(cartGoods, coupon) * p + +} + +[2026-10-11 08:58:40 +0530] Export the shared cart-pricing helpers from the package root. + + --- a/packages/shared/index.ts + +++ b/packages/shared/index.ts + @@ + // Re-export all types from the types folder + export * from './types' + +// Framework-agnostic coupon/cart money helpers (used by the backend pricing path). + +export * from './cart-pricing' + +[2026-10-11 09:03:12 +0530] placeOrderUtil: discount computed on goods subtotal via shared helper, + allocated per sub-order, delivery + single coupon_usage attached to the deterministic + primary sub-order (highest goods subtotal) instead of blindly the first order. + + --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts + @@ + -import type { DeliveryStatus, OrderStatus } from "@packages/shared"; + +import type { DeliveryStatus, OrderStatus } from "@packages/shared"; + +import { allocateDiscount, computeCartDiscount } from "@packages/shared"; + @@ + - let totalAmount = 0; + - for (const [slotId, items] of ordersBySlot) { + - const orderTotal = items.reduce((sum, item) => { ... }, 0); + - totalAmount += orderTotal; + - } + - const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount); + - let discountAmount = 0; + - if (appliedCoupon) { ...whole-cart percent/flat... } + - const finalTotal = totalAmount - discountAmount; + - const expectedDeliveryCharge = finalTotal < freeDeliveryThreshold ? deliveryCharge : 0; + - const totalWithDelivery = finalTotal + expectedDeliveryCharge; + + let totalAmount = 0; + + const subOrderSubtotals: number[] = []; + + for (const [, items] of ordersBySlot) { + + const orderTotal = items.reduce((sum, item) => { ... }, 0); + + subOrderSubtotals.push(orderTotal); + + totalAmount += orderTotal; + + } + + const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount); + + // Goods-only base; split per sub-order. + + const discountTotal = computeCartDiscount(totalAmount, appliedCoupon); + + const subOrderDiscounts = allocateDiscount(discountTotal, subOrderSubtotals); + + // Primary = highest goods subtotal (tie -> first): carries delivery + usage row. + + let primaryIndex = 0; + + for (let i = 1; i < subOrderSubtotals.length; i++) + + if (subOrderSubtotals[i] > subOrderSubtotals[primaryIndex]) primaryIndex = i; + + const finalTotal = totalAmount - discountTotal; + + const expectedDeliveryCharge = finalTotal < freeDeliveryThreshold ? deliveryCharge : 0; + + const totalWithDelivery = finalTotal + expectedDeliveryCharge; + @@ + - let isFirstOrder = true; + - for (const [slotId, items] of ordersBySlot) { + - const subOrderTotal = items.reduce(...); // recomputed + - const orderGroupProportion = ...; + - const orderDiscount = discountAmount * orderGroupProportion; + - const orderDelivery = isFirstOrder ? expectedDeliveryCharge : 0; + + let subOrderIndex = 0; + + for (const [slotId, items] of ordersBySlot) { + + const subOrderTotal = subOrderSubtotals[subOrderIndex]; + + const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0; + + const orderDiscount = subOrderDiscounts[subOrderIndex]; + + const orderDelivery = subOrderIndex === primaryIndex ? expectedDeliveryCharge : 0; + @@ + - ordersData.push(...); isFirstOrder = false; + + ordersData.push(...); subOrderIndex++; + @@ + - if (appliedCoupon && createdOrders.length > 0) { + - await recordUserCouponUsage(userId, appliedCoupon.id, createdOrders[0].id); + - } + + if (appliedCoupon && createdOrders.length > 0) { + + const primaryOrder = createdOrders[primaryIndex] ?? createdOrders[0]; + + await recordUserCouponUsage(userId, appliedCoupon.id, primaryOrder.id); + + } + +[2026-10-11 09:12:05 +0530] db_helper_sqlite/src/user-apis/order.ts: add countEffectiveOrders + (distinct non-cancelled order groups) for first-order-only eligibility; keep getOrderCount + (row count) for pagination. Add getCouponUsageForOrderGroup and + releaseCouponUsageIfGroupFullyCancelled; wire release into cancelOrderTransaction; point the + first-order coupon check at countEffectiveOrders. + + --- a/packages/db_helper_sqlite/src/user-apis/order.ts + +++ b/packages/db_helper_sqlite/src/user-apis/order.ts + @@ validateAndGetCoupon + - const orderCount = await getOrderCount(userId) + + const orderCount = await countEffectiveOrders(userId) + @@ after getCouponUsageForOrder + +export async function getCouponUsageForOrderGroup(orderGroupId: string): Promise + +export async function countEffectiveOrders(userId: number): Promise // distinct non-cancelled groups + +export async function releaseCouponUsageIfGroupFullyCancelled(tx, orderId): Promise + @@ cancelOrderTransaction + + await releaseCouponUsageIfGroupFullyCancelled(tx, orderId) + +[2026-10-11 09:16:30 +0530] db_helper_sqlite/index.ts: export the new order helpers. + + --- a/packages/db_helper_sqlite/index.ts + +++ b/packages/db_helper_sqlite/index.ts + @@ + recordCouponUsage as recordUserCouponUsage, + getOrdersWithRelations as getUserOrdersWithRelations, + getOrderCount as getUserOrderCount, + +countEffectiveOrders as getUserEffectiveOrderCount, + getOrderByIdWithRelations as getUserOrderByIdWithRelations, + getCouponUsageForOrder as getUserCouponUsageForOrder, + +getCouponUsageForOrderGroup as getUserCouponUsageForOrderGroup, + getOrderBasic as getUserOrderBasic, + cancelOrderTransaction as cancelUserOrderTransaction, + +releaseCouponUsageIfGroupFullyCancelled, + updateOrderNotes as updateUserOrderNotes, + +[2026-10-11 09:20:10 +0530] Backend user coupon router: first-order eligibility now uses the + effective (non-cancelled, group-aware) order count. + + --- a/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts + @@ + - getUserOrderCount as getUserOrderCountInDb, + + getUserEffectiveOrderCount as getUserOrderCountInDb, + +[2026-10-11 09:24:40 +0530] OrderWithRelations (sqlite) + backend user order detail: expose orderGroupId + on the detail row, resolve the coupon via the order's group, and recompute the discount with the + shared helper. + + --- a/packages/db_helper_sqlite/src/user-apis/order.ts + +++ b/packages/db_helper_sqlite/src/user-apis/order.ts + @@ + isFlashDelivery: boolean + userNotes: string | null + + orderGroupId: string | null + + orderGroupProportion: string | null + createdAt: Date + + --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts + @@ imports + + getUserCouponUsageForOrderGroup, + +import { couponDiscountForSubOrder } from "@packages/shared"; // (with allocateDiscount/computeCartDiscount) + @@ + - const couponUsageData = await getUserCouponUsageForOrder(order.id); + + const couponUsageData = order.orderGroupId + + ? await getUserCouponUsageForOrderGroup(order.orderGroupId) + + : await getUserCouponUsageForOrder(order.id); + @@ + - for (const usage of couponUsageData) { + - const { discountAmount } = applyDiscountToUserOrder(itemsSubtotal, usage.coupon, proportion); + - totalDiscountAmount += discountAmount; + - } + + for (const usage of couponUsageData) { + + totalDiscountAmount += couponDiscountForSubOrder(itemsSubtotal, usage.coupon, proportion); + + } + +[2026-10-11 09:31:18 +0530] db_helper_sqlite/src/admin-apis/order.ts: order detail resolves coupon via the + order group and recomputes with the shared helper; admin cancel releases the coupon when the + whole group is cancelled. + + --- a/packages/db_helper_sqlite/src/admin-apis/order.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts + @@ + -import { applyDiscountToOrder } from '../user-apis/order' + +import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order' + +import { couponDiscountForSubOrder } from '@packages/shared' + @@ getOrderDetails + - const couponUsageData = await db.query.couponUsage.findMany({ + - where: eq(couponUsage.orderId, orderData.id), with: { coupon: true }, + - }) + + let couponOrderIds = [orderData.id] + + if (orderData.orderGroupId) { ...select orders of the group... } + + const couponUsageData = await db.query.couponUsage.findMany({ + + where: inArray(couponUsage.orderId, couponOrderIds), with: { coupon: true }, + + }) + @@ + - const { discountAmount } = applyDiscountToOrder(itemsSubtotal, usage.coupon, proportion) + - totalDiscountAmount += discountAmount + + totalDiscountAmount += couponDiscountForSubOrder(itemsSubtotal, usage.coupon, proportion) + @@ cancelOrder transaction + + await releaseCouponUsageIfGroupFullyCancelled(tx, order.id) + +[2026-10-11 09:40:02 +0530] db_helper_postgres parity mirror (legacy driver, already non-compiling): + countEffectiveOrders, getCouponUsageForOrderGroup, releaseCouponUsageIfGroupFullyCancelled, + wired into cancelOrderTransaction + admin cancelOrder; admin/user order detail resolve the coupon + via the group and use the shared helper; index re-exports the new helpers. + +[2026-10-11 09:45:12 +0530] cart-pricing.allocateDiscount: multiply by (sub/goods) to keep the exact + float result of the previous `discount * (subtotal/total)` expression (single sub-order → exact). + + --- a/packages/shared/cart-pricing.ts + +++ b/packages/shared/cart-pricing.ts + @@ + - return subtotals.map((sub) => (totalDiscount * sub) / goods) + + return subtotals.map((sub) => totalDiscount * (sub / goods)) + +[2026-10-11 09:50:31 +0530] apps/backend/tests/api/order-lifecycle-gaps.test.ts: the two pinned + coupon-lifecycle bugs are now fixed — cancelling releases the coupon once all siblings are + cancelled, and a cancelled first order no longer poisons an isFirstOrderOnly coupon. Adds a + split-order case (release only when every sibling is cancelled). Adds regionId:1 to the helper + calls (required by placeOrder). + + --- a/apps/backend/tests/api/order-lifecycle-gaps.test.ts + +++ b/apps/backend/tests/api/order-lifecycle-gaps.test.ts + @@ + selectedItems: [{ skuId, quantity: 1, slotId }], + addressId, + + regionId: 1, + paymentMethod: 'cod', + @@ + - it('pins: cancelling an order does not release its coupon usage', ...) + + it('releases the coupon usage when the (only) order is cancelled', ...) + - const error = await captureError(() => place(coupon.id)) + - expect(error.message).toMatch(/usage limit/i) + + const again = await place(coupon.id) + + expect(again.success).toBe(true) + @@ + - it('pins: a cancelled first order poisons an isFirstOrderOnly coupon', ...) + + it('does not poison an isFirstOrderOnly coupon when the first order is cancelled', ...) + - const error = await captureError(() => ...) + - expect(error.message).toMatch(/first order only/i) + + const res = await apiClient(buyer.token).user.order.placeOrder.mutate({ ..., couponId: coupon.id }) + + expect(res.success).toBe(true) + + it('keeps the coupon while a sibling order survives, releasing only when all are cancelled', ...) + +[2026-10-11 09:58:44 +0530] Summary — base fixes complete: + - packages/shared/cart-pricing.ts (new): computeCartDiscount / allocateDiscount / + couponDiscountForSubOrder; goods-only discount base. + - backend placeOrderUtil: per-sub-order discount, delivery + single coupon_usage on the + primary sub-order (highest goods subtotal). + - order detail (customer + admin, sqlite + postgres): resolve the coupon via the order + group, recompute per sub-order with the shared helper. + - cancel-restore: release (hard delete) the group's coupon_usage only when every sibling + order is cancelled (both cancel paths, both drivers). + - first-order-only: countEffectiveOrders (distinct, non-cancelled order groups) replaces + getOrderCount at the 4 coupon call sites; getOrderCount stays for pagination. + - tests: order-lifecycle-gaps flipped + split-order restore case; BUGS.md #9/#10 marked fixed. + Not run: any test suite. No drizzle migrations touched. + Note: packages/db_helper_sqlite has 4 pre-existing unrelated type errors (admin rebalance + numeric set, deleteProduct/deleteGlobalProduct and()), plus pre-existing postgres/web-ui + errors; no new errors introduced by these changes. + +[2026-10-11 10:12:44 +0530] RN cart/checkout UI parity: + - cart-page.tsx + checkout-page.tsx: use the shared computeCartDiscount (goods-only) instead of + the inline per-coupon math (picker "Save ₹x" and the discountAmount memo). + - PaymentAndOrderComponent.tsx: the order-success amount now comes from the server-returned + orders' totalAmount sum (falls back to finalTotalWithDelivery when the response omits it), + so the success screen shows what was actually charged. + + --- a/apps/user-ui/components/cart-page.tsx + +++ b/apps/user-ui/components/cart-page.tsx + @@ + import type { FlashDeliveryProps } from '@packages/shared'; + +import { computeCartDiscount } from '@packages/shared'; + @@ dropdown label + - const discount = coupon.discountType === "percentage" + - ? Math.min((totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity) + - : Math.min(coupon.discountValue, coupon.maxValue || totalPrice); + + const discount = computeCartDiscount(totalPrice, { + + discountPercent: coupon.discountType === "percentage" ? coupon.discountValue : null, + + flatDiscount: coupon.discountType === "percentage" ? null : coupon.discountValue, + + maxValue: coupon.maxValue ?? null, + + }); + @@ discountAmount memo + - (coupon.discountType === "percentage" + - ? Math.min((totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity) + - : Math.min(coupon.discountValue, coupon.maxValue || totalPrice)), + + computeCartDiscount(totalPrice, { + + discountPercent: coupon.discountType === "percentage" ? coupon.discountValue : null, + + flatDiscount: coupon.discountType === "percentage" ? null : coupon.discountValue, + + maxValue: coupon.maxValue ?? null, + + }), + + --- a/apps/user-ui/components/checkout-page.tsx + +++ b/apps/user-ui/components/checkout-page.tsx + @@ + import type { FlashDeliveryProps } from '@packages/shared'; + +import { computeCartDiscount } from '@packages/shared'; + @@ discountAmount memo + - (coupon.discountType === "percentage" + - ? Math.min((totalPrice * coupon.discountValue) / 100, coupon.maxValue || Infinity) + - : Math.min(coupon.discountValue, coupon.maxValue || totalPrice)), + + computeCartDiscount(totalPrice, { + + discountPercent: coupon.discountType === "percentage" ? coupon.discountValue : null, + + flatDiscount: coupon.discountType === "percentage" ? null : coupon.discountValue, + + maxValue: coupon.maxValue ?? null, + + }), + + --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx + +++ b/apps/user-ui/components/PaymentAndOrderComponent.tsx + @@ placeOrderMutation onSuccess + verifyPaymentMutation onSuccess + + const serverTotal = orders.reduce( + + (sum, order) => sum + Number(order.totalAmount ?? 0), + + 0 + + ); + + const successAmount = serverTotal > 0 ? serverTotal : finalTotalWithDelivery; + - router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${finalTotalWithDelivery}`); + + router.replace(`${successPath}?orderId=${firstOrder.id}&totalAmount=${successAmount}`); + +[2026-10-11 10:19:27 +0530] user-ui tests: add a case asserting the order-success URL uses the + server-returned order total (server wins over the local preview). + Docs: KNOWN-GAPS.md #4 (order-success shows frontend total) marked fixed for the amount. + + --- a/apps/user-ui/tests/components/payment-and-order-money.test.tsx + +++ b/apps/user-ui/tests/components/payment-and-order-money.test.tsx + @@ + expect(input.isFlashDelivery).toBe(false) + }) + + it('uses the server-stored order amount for the success URL when present', async () => { + + const api = setupApiMocks({ + + procedures: { + + 'user.order.placeOrder': { data: [{ id: 99, isCod: true, totalAmount: '400' }] }, + + }, + + }) + + renderWithProviders(, { centralStores: false }) + + fireEvent.press(screen.getByTestId('place-order-button')) + + await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder')) + + await waitFor(() => + + expect(routerMock.replace).toHaveBeenCalledWith( + + './order-success?orderId=99&totalAmount=400' + + ) + + ) + + }) + +[2026-10-11 10:24:05 +0530] Summary — RN cart/checkout UI parity done: + - cart-page.tsx / checkout-page.tsx: discount computed via shared computeCartDiscount + (goods-only), replacing the duplicated inline math (picker saving + discountAmount). + - PaymentAndOrderComponent.tsx: order-success amount taken from the server orders' + totalAmount sum (fallback to the local preview if absent). + - tests: +1 (server amount wins); KNOWN-GAPS #4 amount marked fixed. + user-ui typecheck: no new errors (only the 4 pre-existing db_helper_sqlite ones). + Postgres left untouched per instruction. + +[2026-10-11 10:41:58 +0530] Fix the 4 pre-existing db_helper_sqlite type errors: + - admin-apis/order.ts rebalance: guard the Map.get() result (skip when undefined) AND + convert to string for the text column (numericText data type is string|null). + - admin-apis/product.ts deleteProduct/deleteGlobalProduct: guard the `and(...)` result + (SQL | undefined) before passing to softDeleteProduct(where: SQL). + + --- a/packages/db_helper_sqlite/src/admin-apis/order.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts + @@ + const price = priceById.get(item.id) + + // Skip items with no resolved price instead of writing a NULL/NaN value. + + if (price === undefined) continue + await tx + .update(orderItems) + .set({ + - price, + - discountedPrice: price, + + price: String(price), + + discountedPrice: String(price), + }) + + --- a/packages/db_helper_sqlite/src/admin-apis/product.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts + @@ + export async function deleteProduct(regionId: number, id: number): Promise { + - return softDeleteProduct(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId))) + + const where = and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)) + + if (!where) return null + + return softDeleteProduct(where) + } + export async function deleteGlobalProduct(id: number): Promise { + - return softDeleteProduct(and(eq(productInfo.id, id), isNull(productInfo.regionId))) + + const where = and(eq(productInfo.id, id), isNull(productInfo.regionId)) + + if (!where) return null + + return softDeleteProduct(where) + } + +[2026-10-11 09:23:13 +0530] cart-pricing.ts: generalize to targeted + multi-coupon stacking. + + --- a/packages/shared/cart-pricing.ts + +++ b/packages/shared/cart-pricing.ts + @@ + +export interface TargetedCoupon extends CouponMoney { + + id: number + + exclusiveApply?: boolean + + applicableSkuIds?: number[] | null // empty/null => whole cart + +} + +export interface CartLine { skuId: number; quantity: number; unitPrice: number } + +export interface CartSubOrderInput { key: number | string | null; items: CartLine[] } + +export function lineEligibleForCoupon(skuId, coupon): boolean + +export function computeEligibleSubtotal(items: CartLine[], coupon): number + +export function computeCouponDiscount(eligibleSubtotal: number, coupon): number + +export function computeCartPricing({ subOrders, coupons, delivery }): CartPricingResult + -computeCartDiscount / allocateDiscount / couponDiscountForSubOrder (removed; callers migrated) + +[2026-10-11 09:31:02 +0530] Persist the per-order coupon discount: add orders.discount_amount. + + --- a/packages/db_helper_sqlite/src/db/schema.ts + +++ b/packages/db_helper_sqlite/src/db/schema.ts + @@ + totalAmount: numericText('total_amount').notNull(), + deliveryCharge: numericText('delivery_charge').notNull().default('0'), + + discountAmount: numericText('discount_amount').notNull().default('0'), + readableId: integer('readable_id').notNull(), + + --- a/packages/db_helper_postgres/src/db/schema.ts + +++ b/packages/db_helper_postgres/src/db/schema.ts + @@ + totalAmount: numeric('total_amount', { precision: 10, scale: 2 }).notNull(), + deliveryCharge: numeric('delivery_charge', { precision: 10, scale: 2 }).notNull().default('0'), + + discountAmount: numeric('discount_amount', { precision: 10, scale: 2 }).notNull().default('0'), + readableId: integer('readable_id').notNull(), + + --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + @@ + `total_amount` text NOT NULL, + `delivery_charge` text DEFAULT '0' NOT NULL, + + `discount_amount` text DEFAULT '0' NOT NULL, + `readable_id` integer NOT NULL, + @@ + -INSERT INTO `__new_orders` (`id`,...,`delivery_charge`,`readable_id`,...) + -SELECT `id`,...,`delivery_charge`,`readable_id`,... FROM `orders`; + +INSERT INTO `__new_orders` (`id`,...,`delivery_charge`,`discount_amount`,`readable_id`,...) + +SELECT `id`,...,`delivery_charge`,'0',`readable_id`,... FROM `orders`; + +[2026-10-11 09:40:55 +0530] db_helper_sqlite/src/user-apis/order.ts: replace validateAndGetCoupon + with validateAndGetCoupons (region + product targets + first-order + per-user limit + exclusive). + + --- a/packages/db_helper_sqlite/src/user-apis/order.ts + +++ b/packages/db_helper_sqlite/src/user-apis/order.ts + @@ + import { marketStatsForRegion } from '../lib/market-stats' + +import { computeEligibleSubtotal, type CartLine } from '@packages/shared' + @@ + +export interface ValidatedCoupon extends CouponValidationResult { + + applicableSkuIds: number[] | null + + eligibleSubtotal: number + +} + -export async function validateAndGetCoupon(couponId, userId, totalAmount) { ...single... } + +export async function validateAndGetCoupons({ couponIds, userId, regionId, items }): Promise { + + // dedupe, load coupons (+ usages/applicableUsers/applicableProducts), region check, + + // exclusive-combining check, first-order via countEffectiveOrders, + + // applicableSkuIds = applicableProducts.map(skuId), eligibleSubtotal via shared helper, + + // minOrder on the eligible subtotal, targets-present check. + +} + +[2026-10-11 09:47:20 +0530] Rename the exported validation helper. + + --- a/packages/db_helper_sqlite/index.ts + +++ b/packages/db_helper_sqlite/index.ts + @@ + - validateAndGetCoupon as validateAndGetUserCoupon, + + validateAndGetCoupons as validateAndGetUserCoupons, + + type ValidatedCoupon, + applyDiscountToOrder as applyDiscountToUserOrder, + + --- a/apps/backend/src/sqliteImporter.ts + +++ b/apps/backend/src/sqliteImporter.ts + @@ + - validateAndGetUserCoupon, + + validateAndGetUserCoupons, + applyDiscountToUserOrder, + +[2026-10-11 09:55:40 +0530] computeCartPricing returns primaryIndex; backend placeOrderUtil uses + validateAndGetUserCoupons + computeCartPricing, writes orders.discount_amount, records one + coupon_usage per coupon; placeOrder input is couponIds (couponId removed). + + --- a/packages/shared/cart-pricing.ts + +++ b/packages/shared/cart-pricing.ts + @@ + subOrders: PricedSubOrder[] + + primaryIndex: number + primaryKey: number | string | null + @@ + subOrders: priced, + + primaryIndex, + primaryKey: subOrders[primaryIndex]?.key ?? null, + + --- a/apps/backend/src/trpc/apis/user-apis/apis/order.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/order.ts + @@ params + - couponId?: number; + + couponIds?: number[]; + @@ pricing + - const appliedCoupon = await validateAndGetUserCoupon(couponId, userId, totalAmount); + - const discountTotal = computeCartDiscount(totalAmount, appliedCoupon); + - const subOrderDiscounts = allocateDiscount(discountTotal, subOrderSubtotals); + - ...expectedDeliveryCharge... + + const subOrderInputs = ... + + const validatedCoupons = await validateAndGetUserCoupons({ couponIds, userId, regionId, items }) + + const pricing = computeCartPricing({ subOrders: subOrderInputs, coupons: validatedCoupons, delivery }) + @@ order insert + + discountAmount: orderDiscount.toString(), + @@ usage + - await recordUserCouponUsage(userId, appliedCoupon.id, primaryOrder.id); + + for (const coupon of validatedCoupons) await recordUserCouponUsage(userId, coupon.id, primaryOrder.id); + @@ input + - couponId: z.number().int().positive().optional(), + + couponIds: z.array(z.number().int().positive()).optional(), + +[2026-10-11 10:05:12 +0530] Order detail (sqlite + postgres admin, backend user) reads the stored + orders.discount_amount instead of recomputing; drop the now-unused couponDiscountForSubOrder import. + + --- a/packages/db_helper_sqlite/src/admin-apis/order.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts + @@ + -import { couponDiscountForSubOrder } from '@packages/shared' + - discountAmount: totalDiscountAmount, + + discountAmount: parseFloat(orderData.discountAmount?.toString() || '0'), + + --- a/packages/db_helper_postgres/src/admin-apis/order.ts + +++ b/packages/db_helper_postgres/src/admin-apis/order.ts + @@ + -import { couponDiscountForSubOrder } from '@packages/shared' + - ...recompute loop... + + discountAmount: parseFloat((orderData as any).discountAmount?.toString() || '0'), + +[2026-10-11 10:14:30 +0530] Region-scope the customer coupon queries + accept regionId from the app. + + --- a/packages/db_helper_sqlite/src/user-apis/coupon.ts + +++ b/packages/db_helper_sqlite/src/user-apis/coupon.ts + @@ + -export async function getActiveCouponsWithRelations(userId: number): Promise { + +export async function getActiveCouponsWithRelations(userId: number, regionId?: number): Promise { + + const regionCondition = regionId != null + + ? or(isNull(coupons.regionId), eq(coupons.regionId, regionId)) + + : undefined + where: and(eq(coupons.isInvalidated, false), + or(isNull(coupons.validTill), gt(coupons.validTill, new Date())), + + regionCondition), + @@ + -export async function getAllCouponsWithRelations(userId: number) { + +export async function getAllCouponsWithRelations(userId: number, regionId?: number) { + + const regionCondition = ... (global OR this region) + where: regionCondition, + + --- a/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts + +++ b/apps/backend/src/trpc/apis/user-apis/apis/coupon.ts + @@ + getEligible: protectedProcedure + + .input(z.object({ regionId: z.number().int().positive().optional() }).optional()) + - .query(async ({ ctx }): Promise => { + + .query(async ({ ctx, input }): Promise => { + - const allCoupons = await getUserActiveCouponsWithRelationsInDb(userId) + + const allCoupons = await getUserActiveCouponsWithRelationsInDb(userId, input?.regionId) + @@ + getMyCoupons: protectedProcedure + + .input(z.object({ regionId: z.number().int().positive().optional() }).optional()) + - .query(async ({ ctx }): Promise => { + + .query(async ({ ctx, input }): Promise => { + - const allCoupons = await getUserAllCouponsWithRelationsInDb(userId) + + const allCoupons = await getUserAllCouponsWithRelationsInDb(userId, input?.regionId) + +[2026-10-11 10:21:40 +0530] Coupon SKU targeting accepts global products (region_id NULL); a global + coupon (regionId NULL) may target any SKU. + + --- a/packages/db_helper_sqlite/src/admin-apis/coupon.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/coupon.ts + @@ + -const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number): Promise => { + +const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null): Promise => { + @@ + - const foreign = rows.filter((r: any) => r.product?.regionId !== regionId) + + // Global products (region_id NULL) are valid in every region; a global coupon + + // (regionId NULL) may target any SKU. Only another region's regional SKU is rejected. + + const foreign = regionId == null + + ? [] + + : rows.filter((r: any) => r.product?.regionId != null && r.product.regionId !== regionId) + +[2026-10-11 10:32:10 +0530] Admin coupon helpers accept regionId null (global); add a superadmin + coupon db layer + backend router. + + --- a/packages/db_helper_sqlite/src/admin-apis/coupon.ts + +++ b/packages/db_helper_sqlite/src/admin-apis/coupon.ts + @@ + export async function createCouponWithRelations( + input: CouponFormInput, applicableUsers, applicableProducts, + - regionId: number + + regionId: number | null + ): Promise + @@ + export async function updateCouponWithRelations( + - regionId: number, id: number, input, applicableUsers?, applicableProducts? + + regionId: number | null, id: number, input, applicableUsers?, applicableProducts? + ) { + - where: and(eq(coupons.id, id), eq(coupons.regionId, regionId)), + + where: and(eq(coupons.id, id), regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId)), + @@ + export async function invalidateCoupon( + - regionId: number, id: number + + regionId: number | null, id: number + ) { + - .where(and(eq(coupons.id, id), eq(coupons.regionId, regionId))) + + .where(and(eq(coupons.id, id), regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId))) + + --- /dev/null + +++ b/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts + @@ + +import { db } from '../db/db_index' + +import { coupons } from '../db/schema' + +import { and, eq, isNull, desc } from 'drizzle-orm' + +import type { Coupon, CouponFormInput } from '@packages/shared' + +import { createCouponWithRelations, updateCouponWithRelations, invalidateCoupon } from '../admin-apis/coupon' + +export async function listGlobalCoupons() / getGlobalCoupon(id) + +export const createGlobalCoupon = (...) => createCouponWithRelations(input, users, products, null) + +export const updateGlobalCoupon = (id, input, users, products) => updateCouponWithRelations(null, id, ...) + +export const invalidateGlobalCoupon = (id) => invalidateCoupon(null, id) + +[2026-10-11 10:45:20 +0530] Make coupons.created_by nullable so a superadmin (no staffUsers row) + can author global coupons. + + --- a/packages/db_helper_sqlite/src/db/schema.ts + +++ b/packages/db_helper_sqlite/src/db/schema.ts + @@ coupons + - createdBy: integer('created_by').notNull().references(() => staffUsers.id), + + createdBy: integer('created_by').references(() => staffUsers.id), + + --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + @@ __new_coupons + - `created_by` integer NOT NULL, + + `created_by` integer, + + --- a/packages/db_helper_postgres/src/db/schema.ts + +++ b/packages/db_helper_postgres/src/db/schema.ts + @@ + - createdBy: integer('created_by').notNull().references(() => staffUsers.id), (coupons) + + createdBy: integer('created_by').references(() => staffUsers.id), + + --- a/packages/shared/types/coupon.types.ts + +++ b/packages/shared/types/coupon.types.ts + @@ + - createdBy: number; + + createdBy: number | null; + +[2026-10-11 10:58:33 +0530] superadmin global-coupons router + registration. + + --- /dev/null + +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts + @@ + +superadminGlobalCouponsRouter: list / get / create / update / delete (invalidate) + + using the superadmin global-coupon db helpers, createdBy null. + + --- a/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts + +++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/superadmin-trpc-index.ts + @@ + +import { superadminGlobalCouponsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-coupons' + @@ + globalProducts: superadminGlobalProductsRouter, + + globalCoupons: superadminGlobalCouponsRouter, + products: superadminProductsRouter, + +[2026-10-11 11:20:15 +0530] RN multi-coupon UI + payload. + - cart-page.tsx / checkout-page.tsx: selectedCouponId -> selectedCouponIds:number[]; + per-coupon discount via computeEligibleSubtotal/computeCouponDiscount on cart lines; + cart nav param `coupons` is a comma-separated id list; exclusive coupon clears others. + - PaymentAndOrderComponent.tsx: prop selectedCouponIds:number[]; sends `couponIds`. + + --- a/apps/user-ui/components/PaymentAndOrderComponent.tsx + +++ b/apps/user-ui/components/PaymentAndOrderComponent.tsx + @@ + - selectedCouponId: number | null; + + selectedCouponIds: number[]; + @@ + - selectedCouponId, + + selectedCouponIds, + @@ + - couponId: selectedCouponId || undefined, + + couponIds: selectedCouponIds.length ? selectedCouponIds : undefined, + +[2026-10-11 11:26:40 +0530] user-ui tests: switch couponId -> couponIds. + + --- a/apps/user-ui/tests/components/payment-and-order.test.tsx + +++ b/apps/user-ui/tests/components/payment-and-order.test.tsx + @@ baseProps + - selectedCouponId: null, + + selectedCouponIds: [], + @@ + - couponId: undefined, + + couponIds: undefined, + @@ selectedCouponId={77} (x2) -> selectedCouponIds={[77]} + @@ + - couponId: 77, + + couponIds: [77], + + --- a/apps/user-ui/tests/components/payment-and-order-money.test.tsx + +++ b/apps/user-ui/tests/components/payment-and-order-money.test.tsx + @@ + - selectedCouponId: null, + + selectedCouponIds: [], + @@ selectedCouponId={77} (x2) -> selectedCouponIds={[77]} + @@ + - expect(input.couponId).toBe(77) + + expect(input.couponIds).toEqual([77]) + + --- a/apps/user-ui/tests/screens/mutation-invalidation.test.tsx + +++ b/apps/user-ui/tests/screens/mutation-invalidation.test.tsx + @@ + - selectedCouponId: null, + + selectedCouponIds: [], + + --- a/apps/user-ui/tests/screens/checkout-coupons.test.tsx + +++ b/apps/user-ui/tests/screens/checkout-coupons.test.tsx + @@ + - couponId: COUPON_ID, + + couponIds: [COUPON_ID], + + --- a/apps/user-ui/tests/screens/cart-coupons.test.tsx + +++ b/apps/user-ui/tests/screens/cart-coupons.test.tsx + @@ + - fireEvent.press(screen.getByText('Remove coupon')) + + fireEvent.press(screen.getByText('Remove coupons')) + +[2026-10-11 11:33:10 +0530] backend tests: placeOrder now takes couponIds:[...] (add regionId where missing). + + --- a/apps/backend/tests/api/coupon-math.test.ts + +++ b/apps/backend/tests/api/coupon-math.test.ts + @@ + - ...(couponId ? { couponId } : {}), + + ...(couponId ? { couponIds: [couponId] } : {}), + + --- a/apps/backend/tests/api/coupon-ux.test.ts + +++ b/apps/backend/tests/api/coupon-ux.test.ts + @@ + - ...(couponId ? { couponId } : {}), + + ...(couponId ? { couponIds: [couponId] } : {}), + + --- a/apps/backend/tests/api/order-lifecycle-gaps.test.ts + +++ b/apps/backend/tests/api/order-lifecycle-gaps.test.ts + @@ + - ...(couponId ? { couponId } : {}), + + ...(couponId ? { couponIds: [couponId] } : {}), + @@ couponId: coupon.id, (x4) -> couponIds: [coupon.id], + + --- a/apps/backend/tests/api/coupons.test.ts + +++ b/apps/backend/tests/api/coupons.test.ts + @@ + addressId, + + regionId: 1, + paymentMethod: 'cod', + - couponId, + + couponIds: [couponId], + (x2) + +[2026-10-11 11:40:50 +0530] RN: pass the browsing regionId into getEligible so the coupon list is + region-filtered. + + --- a/apps/user-ui/components/cart-page.tsx + +++ b/apps/user-ui/components/cart-page.tsx + @@ + +import { useRegion } from '@/src/hooks/useRegion'; + @@ + + const { regionId } = useRegion(); + @@ + - const { data: couponsRaw, error: couponsError } = trpc.user.coupon.getEligible.useQuery( + - undefined, + + const { data: couponsRaw, error: couponsError } = trpc.user.coupon.getEligible.useQuery( + + { regionId: regionId ?? undefined }, + { enabled: isAuthenticated } + ); + + --- a/apps/user-ui/components/checkout-page.tsx + +++ b/apps/user-ui/components/checkout-page.tsx + @@ + const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery( + - undefined, + + { regionId: regionId ?? undefined }, + { enabled: isAuthenticated } + ); + +[2026-10-11 11:47:22 +0530] Coupon targets = union of coupon_applicable_products and the json + coupons.sku_ids (the admin forms populate skuIds). + + --- a/packages/db_helper_sqlite/src/user-apis/order.ts + +++ b/packages/db_helper_sqlite/src/user-apis/order.ts + @@ + - const applicableSkuIds = (coupon.applicableProducts ?? []).map((p) => p.skuId) + + const relatedSkuIds = (coupon.applicableProducts ?? []).map((p) => p.skuId) + + const jsonSkuIds = Array.isArray(coupon.skuIds) ? coupon.skuIds : [] + + const applicableSkuIds = [...new Set([...relatedSkuIds, ...jsonSkuIds])] + + --- a/apps/user-ui/components/cart-page.tsx / checkout-page.tsx + +++ + - applicableSkuIds: (coupon.applicableProducts || []).map((p: any) => p.skuId), + + applicableSkuIds: [ + + ...(coupon.applicableProducts || []).map((p: any) => p.skuId), + + ...(coupon.skuIds || []), + + ], + +[2026-10-11 11:55:00 +0530] Summary — region + product targeted coupons + multi-coupon: + - shared/cart-pricing.ts: computeEligibleSubtotal, computeCouponDiscount, computeCartPricing + (targeted subtotal, %/flat stacking with per-coupon caps, per-sub-order allocation, primary). + - schema: orders.discount_amount; coupons.created_by nullable (sqlite + postgres + 0006). + - validateAndGetCoupons (region, targets union of applicableProducts + skuIds, minOrder on the + eligible subtotal, first-order, per-user limit, exclusive, dedupe; %-first ordering). + - placeOrderUtil: couponIds:number[] -> validateAndGetCoupons -> computeCartPricing; stores + discountAmount per order; one coupon_usage per coupon on the primary order. + - order detail (customer + admin, sqlite + postgres) reads the stored discount. + - customer coupon queries region-filtered; getEligible/getMyCoupons take regionId. + - superadmin global coupons: db layer + superadmin.globalCoupons router (list/get/create/update/delete). + - RN: multi-select couponIds (exclusive clears others), region passed to getEligible. + - tests: user-ui + backend coupon payloads -> couponIds. + Deferred: superadmin-ui screen for global coupons (router is live; no UI route yet). + Not run: any test suite. No drizzle migration executed. diff --git a/packages/db_helper_postgres/index.ts b/packages/db_helper_postgres/index.ts index 89cb26b..da3969f 100644 --- a/packages/db_helper_postgres/index.ts +++ b/packages/db_helper_postgres/index.ts @@ -266,10 +266,13 @@ export { recordCouponUsage as recordUserCouponUsage, getOrdersWithRelations as getUserOrdersWithRelations, getOrderCount as getUserOrderCount, + countEffectiveOrders as getUserEffectiveOrderCount, getOrderByIdWithRelations as getUserOrderByIdWithRelations, getCouponUsageForOrder as getUserCouponUsageForOrder, + getCouponUsageForOrderGroup as getUserCouponUsageForOrderGroup, getOrderBasic as getUserOrderBasic, cancelOrderTransaction as cancelUserOrderTransaction, + releaseCouponUsageIfGroupFullyCancelled, updateOrderNotes as updateUserOrderNotes, // Post-order handler helpers getOrdersByIdsWithFullData, diff --git a/packages/db_helper_postgres/src/admin-apis/order.ts b/packages/db_helper_postgres/src/admin-apis/order.ts index 7185dee..12d00cf 100644 --- a/packages/db_helper_postgres/src/admin-apis/order.ts +++ b/packages/db_helper_postgres/src/admin-apis/order.ts @@ -10,6 +10,7 @@ import { refunds, } from '../db/schema' import { and, desc, eq, inArray, lt, SQL } from 'drizzle-orm' +import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order' import type { AdminOrderDetails, AdminOrderRow, @@ -134,8 +135,18 @@ export async function getOrderDetails(orderId: number): Promise o.id) + } + const couponUsageData = await db.query.couponUsage.findMany({ - where: eq(couponUsage.orderId, orderData.id), + where: inArray(couponUsage.orderId, couponOrderIds), with: { coupon: true, }, @@ -143,34 +154,11 @@ export async function getOrderDetails(orderId: number): Promise 0) { - let totalDiscountAmount = 0 - const orderTotal = parseFloat(orderData.totalAmount.toString()) - - for (const usage of couponUsageData) { - let discountAmount = 0 - - if (usage.coupon.discountPercent) { - discountAmount = - (orderTotal * parseFloat(usage.coupon.discountPercent.toString())) / - 100 - } else if (usage.coupon.flatDiscount) { - discountAmount = parseFloat(usage.coupon.flatDiscount.toString()) - } - - if ( - usage.coupon.maxValue && - discountAmount > parseFloat(usage.coupon.maxValue.toString()) - ) { - discountAmount = parseFloat(usage.coupon.maxValue.toString()) - } - - totalDiscountAmount += discountAmount - } - + // The per-order discount is stored on the order (`discount_amount`). couponData = { couponCode: couponUsageData.map((u) => u.coupon.couponCode).join(', '), couponDescription: `${couponUsageData.length} coupons applied`, - discountAmount: totalDiscountAmount, + discountAmount: parseFloat((orderData as any).discountAmount?.toString() || '0'), } } @@ -677,6 +665,8 @@ export async function cancelOrder(orderId: number, reason: string): Promise paymentInfoTable.id), totalAmount: numeric('total_amount', { precision: 10, scale: 2 }).notNull(), deliveryCharge: numeric('delivery_charge', { precision: 10, scale: 2 }).notNull().default('0'), + discountAmount: numeric('discount_amount', { precision: 10, scale: 2 }).notNull().default('0'), readableId: integer('readable_id').notNull(), adminNotes: text('admin_notes'), userNotes: text('user_notes'), diff --git a/packages/db_helper_postgres/src/user-apis/order.ts b/packages/db_helper_postgres/src/user-apis/order.ts index b14273f..154c177 100644 --- a/packages/db_helper_postgres/src/user-apis/order.ts +++ b/packages/db_helper_postgres/src/user-apis/order.ts @@ -323,6 +323,28 @@ export async function getOrderCount(userId: number): Promise { return result[0]?.count ?? 0 } +/** + * Distinct non-cancelled order groups (see the sqlite driver for the rationale). + */ +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 @@ -400,6 +422,34 @@ export async function getCouponUsageForOrder( }) as Promise } +/** Coupon usages for a whole order group (see the sqlite driver). */ +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), @@ -415,6 +465,44 @@ export async function getOrderBasic(orderId: number) { }) } +/** Delete the group's coupon_usage rows once every sibling is cancelled. */ +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, @@ -438,6 +526,8 @@ export async function cancelOrderTransaction( orderId, refundStatus, }) + + await releaseCouponUsageIfGroupFullyCancelled(tx, orderId) }) } diff --git a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql index f48fe0c..4eea9c2 100644 --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql @@ -324,7 +324,7 @@ CREATE TABLE `__new_coupons` ( `flat_discount` text, `min_order` text, `sku_ids` text, - `created_by` integer NOT NULL, + `created_by` integer, `max_value` text, `is_apply_for_all` integer DEFAULT false NOT NULL, `valid_till` text, @@ -460,6 +460,7 @@ CREATE TABLE `__new_orders` ( `payment_info_id` integer, `total_amount` text NOT NULL, `delivery_charge` text DEFAULT '0' NOT NULL, + `discount_amount` text DEFAULT '0' NOT NULL, `readable_id` integer NOT NULL, `admin_notes` text, `user_notes` text, @@ -476,8 +477,8 @@ CREATE TABLE `__new_orders` ( FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); --> statement-breakpoint -INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`region_id`) -SELECT `id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders`; +INSERT INTO `__new_orders` (`id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,`discount_amount`,`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,`region_id`) +SELECT `id`,`user_id`,`address_id`,`slot_id`,`is_cod`,`is_online_payment`,`payment_info_id`,`total_amount`,`delivery_charge`,'0',`readable_id`,`admin_notes`,`user_notes`,`order_group_id`,`order_group_proportion`,`is_flash_delivery`,`created_at`,`delivered_at`,(SELECT `id` FROM `regions` WHERE `name` = 'Mahabubnagar') FROM `orders`; --> statement-breakpoint CREATE TABLE `__new_order_items` ( `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL, diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts index d0d6133..51a83c0 100644 --- a/packages/db_helper_sqlite/index.ts +++ b/packages/db_helper_sqlite/index.ts @@ -272,7 +272,8 @@ export { export { // User Order - validateAndGetCoupon as validateAndGetUserCoupon, + validateAndGetCoupons as validateAndGetUserCoupons, + type ValidatedCoupon, applyDiscountToOrder as applyDiscountToUserOrder, getAddressByIdAndUser as getUserAddressByIdAndUser, getProductById as getOrderProductById, @@ -283,10 +284,13 @@ export { recordCouponUsage as recordUserCouponUsage, getOrdersWithRelations as getUserOrdersWithRelations, getOrderCount as getUserOrderCount, + countEffectiveOrders as getUserEffectiveOrderCount, getOrderByIdWithRelations as getUserOrderByIdWithRelations, getCouponUsageForOrder as getUserCouponUsageForOrder, + getCouponUsageForOrderGroup as getUserCouponUsageForOrderGroup, getOrderBasic as getUserOrderBasic, cancelOrderTransaction as cancelUserOrderTransaction, + releaseCouponUsageIfGroupFullyCancelled, updateOrderNotes as updateUserOrderNotes, // Post-order handler helpers getOrdersByIdsWithFullData, @@ -436,6 +440,14 @@ export { deleteGlobalProductById, } from './src/superadmin-apis/global-products' +export { + listGlobalCoupons, + getGlobalCoupon, + createGlobalCoupon, + updateGlobalCoupon, + invalidateGlobalCoupon, +} from './src/superadmin-apis/global-coupons' + export { listAllProducts, elevateProductToGlobal, diff --git a/packages/db_helper_sqlite/src/admin-apis/coupon.ts b/packages/db_helper_sqlite/src/admin-apis/coupon.ts index e90b647..31ec76a 100644 --- a/packages/db_helper_sqlite/src/admin-apis/coupon.ts +++ b/packages/db_helper_sqlite/src/admin-apis/coupon.ts @@ -1,9 +1,9 @@ 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, SQL } from 'drizzle-orm' +import { eq, and, like, or, inArray, lt, desc, asc, sql, SQL, isNull } from 'drizzle-orm' import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared' -const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number): Promise => { +const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null): Promise => { const unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))] if (unique.length === 0) return const rows = await txOrDb.query.productSkus.findMany({ @@ -103,7 +103,7 @@ export async function createCouponWithRelations( input: CouponFormInput, applicableUsers: number[] | undefined, applicableProducts: number[] | undefined, - regionId: number + regionId: number | null ): Promise { await assertApplicableSkusInRegion(db, applicableProducts || [], regionId) @@ -148,14 +148,17 @@ export async function createCouponWithRelations( } export async function updateCouponWithRelations( - regionId: number, + regionId: number | null, id: number, input: CouponFormInput, applicableUsers?: number[], applicableProducts?: number[] ): Promise { const existing = await db.query.coupons.findFirst({ - where: and(eq(coupons.id, id), eq(coupons.regionId, regionId)), + where: and( + eq(coupons.id, id), + regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId) + ), columns: { id: true }, }) if (!existing) { @@ -173,7 +176,12 @@ export async function updateCouponWithRelations( .set({ ...updateFields, }) - .where(and(eq(coupons.id, id), eq(coupons.regionId, regionId))) + .where( + and( + eq(coupons.id, id), + regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId) + ) + ) .returning() if (applicableUsers !== undefined) { @@ -204,10 +212,15 @@ export async function updateCouponWithRelations( }) } -export async function invalidateCoupon(regionId: number, id: number): Promise { +export async function invalidateCoupon(regionId: number | null, id: number): Promise { const result = await db.update(coupons) .set({ isInvalidated: true }) - .where(and(eq(coupons.id, id), eq(coupons.regionId, regionId))) + .where( + and( + eq(coupons.id, id), + regionId == null ? isNull(coupons.regionId) : eq(coupons.regionId, regionId) + ) + ) .returning() return (result[0] ?? null) as Coupon | null diff --git a/packages/db_helper_sqlite/src/admin-apis/order.ts b/packages/db_helper_sqlite/src/admin-apis/order.ts index 584d2f0..0c1dd85 100644 --- a/packages/db_helper_sqlite/src/admin-apis/order.ts +++ b/packages/db_helper_sqlite/src/admin-apis/order.ts @@ -11,7 +11,7 @@ import { refunds, } from '../db/schema' import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm' -import { applyDiscountToOrder } from '../user-apis/order' +import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order' import type { AdminOrderDetails, AdminOrderRow, @@ -159,8 +159,17 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis return null } + let couponOrderIds: number[] = [orderData.id] + if (orderData.orderGroupId) { + const groupOrders = await db + .select({ id: orders.id }) + .from(orders) + .where(eq(orders.orderGroupId, orderData.orderGroupId)) + couponOrderIds = groupOrders.map((o) => o.id) + } + const couponUsageData = await db.query.couponUsage.findMany({ - where: eq(couponUsage.orderId, orderData.id), + where: inArray(couponUsage.orderId, couponOrderIds), with: { coupon: true, }, @@ -168,26 +177,11 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis let couponData = null if (couponUsageData.length > 0) { - // The coupon discounts the item subtotal, not the paid total: orders.total_amount - // stores items − discount + delivery, so using it as the base inflates the discount. - const itemsSubtotal = orderData.orderItems.reduce( - (sum: number, item: any) => - sum + - parseFloat(item.price?.toString() || '0') * parseFloat(item.quantity?.toString() || '0'), - 0 - ) - const proportion = Number(orderData.orderGroupProportion || 1) - let totalDiscountAmount = 0 - - for (const usage of couponUsageData) { - const { discountAmount } = applyDiscountToOrder(itemsSubtotal, usage.coupon, proportion) - totalDiscountAmount += discountAmount - } - + // The per-order discount is stored on the order (`discount_amount`). couponData = { couponCode: couponUsageData.map((u: any) => u.coupon.couponCode).join(', '), couponDescription: `${couponUsageData.length} coupons applied`, - discountAmount: totalDiscountAmount, + discountAmount: parseFloat(orderData.discountAmount?.toString() || '0'), } } @@ -702,11 +696,13 @@ export async function rebalanceSlots(regionId: number, slotIds: number[]): Promi for (const item of updatedOrderItems) { const price = priceById.get(item.id) + // Skip items with no resolved price instead of writing a NULL/NaN value. + if (price === undefined) continue await tx .update(orderItems) .set({ - price, - discountedPrice: price, + price: String(price), + discountedPrice: String(price), }) .where(eq(orderItems.id, item.id)) } @@ -765,6 +761,8 @@ export async function cancelOrder(regionId: number, orderId: number, reason: str refundStatus, }) + await releaseCouponUsageIfGroupFullyCancelled(tx, order.id) + return { orderId: order.id, userId: order.userId } }) diff --git a/packages/db_helper_sqlite/src/admin-apis/product.ts b/packages/db_helper_sqlite/src/admin-apis/product.ts index 1c17063..58eced3 100644 --- a/packages/db_helper_sqlite/src/admin-apis/product.ts +++ b/packages/db_helper_sqlite/src/admin-apis/product.ts @@ -391,11 +391,15 @@ async function softDeleteProduct(where: SQL): Promise { } export async function deleteProduct(regionId: number, id: number): Promise { - return softDeleteProduct(and(eq(productInfo.id, id), eq(productInfo.regionId, regionId))) + const where = and(eq(productInfo.id, id), eq(productInfo.regionId, regionId)) + if (!where) return null + return softDeleteProduct(where) } export async function deleteGlobalProduct(id: number): Promise { - return softDeleteProduct(and(eq(productInfo.id, id), isNull(productInfo.regionId))) + const where = and(eq(productInfo.id, id), isNull(productInfo.regionId)) + if (!where) return null + return softDeleteProduct(where) } export async function createProduct(input: CreateProductInput, regionId: number | null): Promise { diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts index 0095002..b744a7d 100644 --- a/packages/db_helper_sqlite/src/db/schema.ts +++ b/packages/db_helper_sqlite/src/db/schema.ts @@ -362,6 +362,7 @@ export const orders = sqliteTable('orders', { paymentInfoId: integer('payment_info_id').references(() => paymentInfoTable.id), totalAmount: numericText('total_amount').notNull(), deliveryCharge: numericText('delivery_charge').notNull().default('0'), + discountAmount: numericText('discount_amount').notNull().default('0'), readableId: integer('readable_id').notNull(), adminNotes: text('admin_notes'), userNotes: text('user_notes'), @@ -533,7 +534,7 @@ export const coupons = sqliteTable('coupons', { flatDiscount: numericText('flat_discount'), minOrder: numericText('min_order'), skuIds: jsonText('sku_ids'), - createdBy: integer('created_by').notNull().references(() => staffUsers.id), + createdBy: integer('created_by').references(() => staffUsers.id), maxValue: numericText('max_value'), isApplyForAll: integer('is_apply_for_all', { mode: 'boolean' }).notNull().default(false), validTill: timestampText('valid_till'), diff --git a/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts b/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts new file mode 100644 index 0000000..f10a7e8 --- /dev/null +++ b/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts @@ -0,0 +1,53 @@ +import { db } from '../db/db_index' +import { coupons } from '../db/schema' +import { and, eq, isNull, desc } from 'drizzle-orm' +import type { Coupon, CouponFormInput } from '@packages/shared' +import { + createCouponWithRelations, + updateCouponWithRelations, + invalidateCoupon, +} from '../admin-apis/coupon' + +const globalCouponWith = { + creator: true, + applicableUsers: { with: { user: true } }, + applicableProducts: { with: { sku: { with: { product: true } } } }, +} as const + +/** Global coupons (regionId NULL) — valid in every region. */ +export async function listGlobalCoupons() { + return db.query.coupons.findMany({ + where: isNull(coupons.regionId), + with: globalCouponWith, + orderBy: desc(coupons.createdAt), + }) +} + +export async function getGlobalCoupon(id: number) { + const coupon = await db.query.coupons.findFirst({ + where: and(eq(coupons.id, id), isNull(coupons.regionId)), + with: globalCouponWith, + }) + return coupon ?? null +} + +export async function createGlobalCoupon( + input: CouponFormInput, + applicableUsers: number[] | undefined, + applicableProducts: number[] | undefined +): Promise { + return createCouponWithRelations(input, applicableUsers, applicableProducts, null) +} + +export async function updateGlobalCoupon( + id: number, + input: CouponFormInput, + applicableUsers?: number[], + applicableProducts?: number[] +): Promise { + return updateCouponWithRelations(null, id, input, applicableUsers, applicableProducts) +} + +export async function invalidateGlobalCoupon(id: number): Promise { + return invalidateCoupon(null, id) +} diff --git a/packages/db_helper_sqlite/src/user-apis/coupon.ts b/packages/db_helper_sqlite/src/user-apis/coupon.ts index 33e6b9c..f593f4c 100644 --- a/packages/db_helper_sqlite/src/user-apis/coupon.ts +++ b/packages/db_helper_sqlite/src/user-apis/coupon.ts @@ -66,14 +66,23 @@ const mapCouponWithRelations = (coupon: CouponRow & { applicableProducts: coupon.applicableProducts.map(mapApplicableProduct), }) -export async function getActiveCouponsWithRelations(userId: number): Promise { +export async function getActiveCouponsWithRelations( + userId: number, + regionId?: number +): Promise { + 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: { @@ -87,8 +96,17 @@ export async function getActiveCouponsWithRelations(userId: number): Promise { +export async function getAllCouponsWithRelations( + userId: number, + regionId?: number +): Promise { + 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), diff --git a/packages/db_helper_sqlite/src/user-apis/order.ts b/packages/db_helper_sqlite/src/user-apis/order.ts index 7170e60..f1676ef 100644 --- a/packages/db_helper_sqlite/src/user-apis/order.ts +++ b/packages/db_helper_sqlite/src/user-apis/order.ts @@ -26,6 +26,7 @@ import { coerceDate } from '../lib/date' import { runBatched } from '../lib/run-batched' 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 @@ -39,10 +40,13 @@ export interface OrderWithRelations { slotId: number | null totalAmount: string deliveryCharge: string + discountAmount: string isCod: boolean isOnlinePayment: boolean isFlashDelivery: boolean userNotes: string | null + orderGroupId: string | null + orderGroupProportion: string | null createdAt: Date orderItems: Array<{ id: number @@ -102,57 +106,125 @@ export interface CouponValidationResult { }> } -export async function validateAndGetCoupon( - couponId: number | undefined, - userId: number, - totalAmount: number -): Promise { - if (!couponId) return null +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 +} - const coupon = await db.query.coupons.findFirst({ - where: eq(coupons.id, couponId), +/** + * Validate every coupon the customer is trying to apply and return them in + * stacking order (percentage first, then flat). 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, userId) }, + usages: { where: eq(couponUsage.userId, params.userId) }, applicableUsers: true, + applicableProducts: true, }, }) - if (!coupon) throw new Error('Invalid coupon') - - // User-based coupons are only spendable by their listed users. The display - // endpoints already hide them from everyone else, but placeOrder accepts a raw - // couponId, so the scope must be enforced here too. - if (coupon.isUserBased && !coupon.isApplyForAll) { - const applicableUsers = coupon.applicableUsers ?? [] - if (!applicableUsers.some((au) => au.userId === userId)) { - throw new Error('This coupon is not applicable to your account') - } + 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 (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 && - coupon.usages.length >= coupon.maxLimitForUser - ) - throw new Error('Coupon usage limit exceeded') - if ( - coupon.minOrder && - parseFloat(coupon.minOrder.toString()) > totalAmount - ) - throw new Error('Order amount does not meet coupon minimum requirement') + if (ids.length > 1 && rows.some((r) => r.exclusiveApply)) { + throw new Error('An exclusive coupon cannot be combined with other coupons') + } - if (coupon.isFirstOrderOnly) { - const orderCount = await getOrderCount(userId) - if (orderCount > 0) { + 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" ) } + + const relatedSkuIds = (coupon.applicableProducts ?? []).map((p) => p.skuId) + const jsonSkuIds = Array.isArray(coupon.skuIds) ? coupon.skuIds : [] + const applicableSkuIds = [...new Set([...relatedSkuIds, ...jsonSkuIds])] + 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, + }) } - return coupon as CouponValidationResult + // Percentage coupons first, then flat (stable within each group). + validated.sort((a, b) => { + const rank = (c: ValidatedCoupon) => (c.discountPercent ? 0 : 1) + return rank(a) - rank(b) + }) + + return validated } /** The discount fields a coupon row carries. `CouponValidationResult` and the coupon rows @@ -436,6 +508,32 @@ export async function getOrderCount(userId: number): Promise { 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 @@ -548,6 +646,38 @@ export async function getCouponUsageForOrder( }) 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), @@ -563,6 +693,49 @@ export async function getOrderBasic(orderId: number) { }) } +/** + * 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, @@ -586,6 +759,8 @@ export async function cancelOrderTransaction( orderId, refundStatus, }) + + await releaseCouponUsageIfGroupFullyCancelled(tx, orderId) }) } diff --git a/packages/shared/cart-pricing.ts b/packages/shared/cart-pricing.ts new file mode 100644 index 0000000..8a5dc7a --- /dev/null +++ b/packages/shared/cart-pricing.ts @@ -0,0 +1,209 @@ +/** + * Cart/coupon money helpers shared by the backend (authoritative) and the RN + * cart/checkout + order-detail screens. + * + * Invariants: + * - The discount base is ALWAYS a goods subtotal — delivery (flash or scheduled) + * is never part of the base. + * - A coupon with no `applicableSkuIds` applies to the whole cart; otherwise it + * only discounts the line items whose skuId is in the target set. + * - Multiple coupons stack: percentage coupons first, then flat, each capped by + * its own `maxValue`; the combined discount never exceeds the goods subtotal. + */ + +export interface CouponMoney { + discountPercent?: string | number | null + flatDiscount?: string | number | null + maxValue?: string | number | null +} + +export interface TargetedCoupon extends CouponMoney { + id: number + exclusiveApply?: boolean + /** targeted SKU ids; empty/null => applies to the whole cart */ + applicableSkuIds?: number[] | null +} + +export interface CartLine { + skuId: number + quantity: number + unitPrice: number +} + +export interface CartSubOrderInput { + key: number | string | null + items: CartLine[] +} + +export interface CouponDiscountShare { + couponId: number + discount: number +} + +export interface PricedSubOrder { + key: number | string | null + goodsSubtotal: number + discount: number + delivery: number + total: number + couponDiscounts: CouponDiscountShare[] +} + +export interface CartPricingResult { + subOrders: PricedSubOrder[] + primaryIndex: number + primaryKey: number | string | null + goodsSubtotal: number + discountTotal: number + deliveryTotal: number + grandTotal: number +} + +const toNum = (v: string | number | null | undefined): number => { + if (v == null) return 0 + const n = typeof v === 'number' ? v : parseFloat(v) + return Number.isFinite(n) ? n : 0 +} + +const hasTargets = (coupon: TargetedCoupon): boolean => + Array.isArray(coupon.applicableSkuIds) && coupon.applicableSkuIds.length > 0 + +/** Whether a line's sku participates in this coupon's discount base. */ +export function lineEligibleForCoupon( + skuId: number, + coupon: Pick +): boolean { + if (!hasTargets(coupon as TargetedCoupon)) return true + return (coupon.applicableSkuIds as number[]).includes(skuId) +} + +/** Sum of the line items this coupon discounts (whole cart when untargeted). */ +export function computeEligibleSubtotal( + items: CartLine[], + coupon: Pick +): number { + return items.reduce( + (sum, item) => + lineEligibleForCoupon(item.skuId, coupon) + ? sum + item.unitPrice * item.quantity + : sum, + 0 + ) +} + +/** + * Discount a single coupon contributes on its eligible subtotal: + * percent: min(subtotal * pct / 100, maxValue || Infinity) + * flat: min(flat, maxValue || subtotal) + * Clamped to [0, eligibleSubtotal]. + */ +export function computeCouponDiscount( + eligibleSubtotal: number, + coupon: CouponMoney +): number { + if (eligibleSubtotal <= 0) return 0 + const maxValue = toNum(coupon.maxValue) + const pct = toNum(coupon.discountPercent) + const flat = toNum(coupon.flatDiscount) + let discount = 0 + if (pct) { + discount = Math.min((eligibleSubtotal * pct) / 100, maxValue || Infinity) + } else if (flat) { + discount = Math.min(flat, maxValue || eligibleSubtotal) + } + if (discount < 0) discount = 0 + if (discount > eligibleSubtotal) discount = eligibleSubtotal + return discount +} + +const couponRank = (coupon: CouponMoney): number => + toNum(coupon.discountPercent) ? 0 : 1 + +/** + * Price a (possibly split) cart with zero or more coupons. + * + * Each coupon's discount is computed on its cart-wide eligible subtotal, then + * allocated to the sub-orders by that sub-order's share of the eligible subtotal + * (targeted coupons therefore land only on the sub-orders that hold the items). + * The combined discount is capped at the goods subtotal. The single cart-level + * delivery charge is attached to the primary sub-order (highest goods subtotal). + */ +export function computeCartPricing(params: { + subOrders: CartSubOrderInput[] + coupons?: TargetedCoupon[] | null + delivery: { threshold: number; charge: number } +}): CartPricingResult { + const subOrders = params.subOrders + const coupons = params.coupons ?? [] + const { threshold, charge } = params.delivery + + const subOrderGoods = subOrders.map((so) => + so.items.reduce((sum, item) => sum + item.unitPrice * item.quantity, 0) + ) + const goodsSubtotal = subOrderGoods.reduce((sum, v) => sum + v, 0) + + // Primary sub-order = highest goods subtotal (tie -> first). + let primaryIndex = 0 + for (let i = 1; i < subOrderGoods.length; i++) { + if (subOrderGoods[i] > subOrderGoods[primaryIndex]) primaryIndex = i + } + + const orderedCoupons = [...coupons].sort( + (a, b) => couponRank(a) - couponRank(b) + ) + + const perSubOrderCoupon: CouponDiscountShare[][] = subOrders.map(() => []) + let discountTotal = 0 + + for (const coupon of orderedCoupons) { + const allItems = subOrders.flatMap((so) => so.items) + const eligibleTotal = computeEligibleSubtotal(allItems, coupon) + const discount = computeCouponDiscount(eligibleTotal, coupon) + if (discount <= 0) continue + + for (let i = 0; i < subOrders.length; i++) { + const subEligible = computeEligibleSubtotal(subOrders[i].items, coupon) + const share = eligibleTotal > 0 ? discount * (subEligible / eligibleTotal) : 0 + perSubOrderCoupon[i].push({ couponId: coupon.id, discount: share }) + } + discountTotal += discount + } + + // Never discount more than the goods subtotal. + if (discountTotal > goodsSubtotal && discountTotal > 0) { + const factor = goodsSubtotal / discountTotal + for (let i = 0; i < perSubOrderCoupon.length; i++) { + perSubOrderCoupon[i] = perSubOrderCoupon[i].map((entry) => ({ + ...entry, + discount: entry.discount * factor, + })) + } + discountTotal = goodsSubtotal + } + + const finalTotal = goodsSubtotal - discountTotal + const deliveryTotal = finalTotal < threshold ? charge : 0 + + const priced: PricedSubOrder[] = subOrders.map((so, i) => { + const discount = perSubOrderCoupon[i].reduce((s, e) => s + e.discount, 0) + const subDelivery = i === primaryIndex ? deliveryTotal : 0 + return { + key: so.key, + goodsSubtotal: subOrderGoods[i], + discount, + delivery: subDelivery, + total: subOrderGoods[i] - discount + subDelivery, + couponDiscounts: perSubOrderCoupon[i], + } + }) + + return { + subOrders: priced, + primaryIndex, + primaryKey: subOrders[primaryIndex]?.key ?? null, + goodsSubtotal, + discountTotal, + deliveryTotal, + grandTotal: finalTotal + deliveryTotal, + } +} diff --git a/packages/shared/types/coupon.types.ts b/packages/shared/types/coupon.types.ts index 4c4323d..0e4d0bf 100644 --- a/packages/shared/types/coupon.types.ts +++ b/packages/shared/types/coupon.types.ts @@ -22,7 +22,7 @@ export interface Coupon { isFirstOrderOnly: boolean; isInvalidated: boolean; createdAt: Date; - createdBy: number; + createdBy: number | null; } // Complete form payload for BOTH create and update — callers always send