enh
This commit is contained in:
parent
47653556cd
commit
6239910707
36 changed files with 2037 additions and 297 deletions
|
|
@ -206,7 +206,7 @@ export {
|
||||||
getUserUnloggedToken,
|
getUserUnloggedToken,
|
||||||
upsertUserUnloggedToken,
|
upsertUserUnloggedToken,
|
||||||
// User - Order
|
// User - Order
|
||||||
validateAndGetUserCoupon,
|
validateAndGetUserCoupons,
|
||||||
applyDiscountToUserOrder,
|
applyDiscountToUserOrder,
|
||||||
getUserAddressByIdAndUser,
|
getUserAddressByIdAndUser,
|
||||||
getOrderProductById,
|
getOrderProductById,
|
||||||
|
|
|
||||||
|
|
@ -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<typeof couponBodySchema>
|
||||||
|
|
||||||
|
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' }
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
|
@ -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 { superadminGlobalStoresRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-stores'
|
||||||
import { superadminGlobalProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-products'
|
import { superadminGlobalProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/global-products'
|
||||||
import { superadminProductsRouter } from '@/src/trpc/apis/superadmin-apis/apis/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({
|
export const superadminRouter = router({
|
||||||
auth: superadminAuthRouter,
|
auth: superadminAuthRouter,
|
||||||
|
|
@ -14,6 +15,7 @@ export const superadminRouter = router({
|
||||||
const: superadminConstRouter,
|
const: superadminConstRouter,
|
||||||
globalStores: superadminGlobalStoresRouter,
|
globalStores: superadminGlobalStoresRouter,
|
||||||
globalProducts: superadminGlobalProductsRouter,
|
globalProducts: superadminGlobalProductsRouter,
|
||||||
|
globalCoupons: superadminGlobalCouponsRouter,
|
||||||
products: superadminProductsRouter,
|
products: superadminProductsRouter,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ import {
|
||||||
getUserAllCouponsWithRelations as getUserAllCouponsWithRelationsInDb,
|
getUserAllCouponsWithRelations as getUserAllCouponsWithRelationsInDb,
|
||||||
getUserReservedCouponByCode as getUserReservedCouponByCodeInDb,
|
getUserReservedCouponByCode as getUserReservedCouponByCodeInDb,
|
||||||
redeemUserReservedCoupon as redeemUserReservedCouponInDb,
|
redeemUserReservedCoupon as redeemUserReservedCouponInDb,
|
||||||
getUserOrderCount as getUserOrderCountInDb,
|
getUserEffectiveOrderCount as getUserOrderCountInDb,
|
||||||
} from '@/src/dbService'
|
} from '@/src/dbService'
|
||||||
import type {
|
import type {
|
||||||
UserCouponDisplay,
|
UserCouponDisplay,
|
||||||
|
|
@ -37,12 +37,13 @@ const generateCouponDescription = (coupon: { discountPercent?: string | null; fl
|
||||||
|
|
||||||
export const userCouponRouter = router({
|
export const userCouponRouter = router({
|
||||||
getEligible: protectedProcedure
|
getEligible: protectedProcedure
|
||||||
.query(async ({ ctx }): Promise<UserEligibleCouponsResponse> => {
|
.input(z.object({ regionId: z.number().int().positive().optional() }).optional())
|
||||||
|
.query(async ({ ctx, input }): Promise<UserEligibleCouponsResponse> => {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
const userId = ctx.user.userId;
|
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
|
// Filter to only coupons applicable to current user
|
||||||
const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0;
|
const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0;
|
||||||
|
|
@ -62,10 +63,11 @@ export const userCouponRouter = router({
|
||||||
}),
|
}),
|
||||||
|
|
||||||
getMyCoupons: protectedProcedure
|
getMyCoupons: protectedProcedure
|
||||||
.query(async ({ ctx }): Promise<UserMyCouponsResponse> => {
|
.input(z.object({ regionId: z.number().int().positive().optional() }).optional())
|
||||||
|
.query(async ({ ctx, input }): Promise<UserMyCouponsResponse> => {
|
||||||
const userId = ctx.user.userId;
|
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
|
// Filter coupons in JS: not invalidated, applicable to user, not expired, and first-order eligible
|
||||||
const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0;
|
const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0;
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,6 @@
|
||||||
import { router, protectedProcedure } from "@/src/trpc/trpc-index";
|
import { router, protectedProcedure } from "@/src/trpc/trpc-index";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import {
|
import {
|
||||||
applyDiscountToUserOrder,
|
|
||||||
cancelUserOrderTransaction,
|
cancelUserOrderTransaction,
|
||||||
checkUserSuspended,
|
checkUserSuspended,
|
||||||
composeUnitNotation,
|
composeUnitNotation,
|
||||||
|
|
@ -10,6 +9,7 @@ import {
|
||||||
getOrderProductById,
|
getOrderProductById,
|
||||||
getUserAddressByIdAndUser,
|
getUserAddressByIdAndUser,
|
||||||
getUserCouponUsageForOrder,
|
getUserCouponUsageForOrder,
|
||||||
|
getUserCouponUsageForOrderGroup,
|
||||||
getUserOrderBasic,
|
getUserOrderBasic,
|
||||||
getUserOrderByIdWithRelations,
|
getUserOrderByIdWithRelations,
|
||||||
getUserOrderCount,
|
getUserOrderCount,
|
||||||
|
|
@ -25,11 +25,12 @@ import {
|
||||||
placeUserOrderTransaction,
|
placeUserOrderTransaction,
|
||||||
recordUserCouponUsage,
|
recordUserCouponUsage,
|
||||||
updateUserOrderNotes,
|
updateUserOrderNotes,
|
||||||
validateAndGetUserCoupon,
|
validateAndGetUserCoupons,
|
||||||
} from "@/src/dbService";
|
} from "@/src/dbService";
|
||||||
import { scaffoldAssetUrl } from "@/src/lib/s3-client";
|
import { scaffoldAssetUrl } from "@/src/lib/s3-client";
|
||||||
import { ApiError } from "@/src/lib/api-error";
|
import { ApiError } from "@/src/lib/api-error";
|
||||||
import type { DeliveryStatus, OrderStatus } from "@packages/shared";
|
import type { DeliveryStatus, OrderStatus } from "@packages/shared";
|
||||||
|
import { computeCartPricing, type CartLine } from "@packages/shared";
|
||||||
import { CONST_KEYS } from "@/src/lib/const-store";
|
import { CONST_KEYS } from "@/src/lib/const-store";
|
||||||
import { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler";
|
import { publishFormattedOrder, publishCancellation } from "@/src/lib/post-order-handler";
|
||||||
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
|
import { trackIfFirstOrder, clearFirstOrderIfMatches } from "@/src/lib/order-tracker";
|
||||||
|
|
@ -51,7 +52,7 @@ const placeOrderUtil = async (params: {
|
||||||
}>;
|
}>;
|
||||||
addressId: number;
|
addressId: number;
|
||||||
paymentMethod: "online" | "cod";
|
paymentMethod: "online" | "cod";
|
||||||
couponId?: number;
|
couponIds?: number[];
|
||||||
userNotes?: string;
|
userNotes?: string;
|
||||||
isFlash?: boolean;
|
isFlash?: boolean;
|
||||||
}) => {
|
}) => {
|
||||||
|
|
@ -60,7 +61,7 @@ const placeOrderUtil = async (params: {
|
||||||
selectedItems,
|
selectedItems,
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod,
|
paymentMethod,
|
||||||
couponId,
|
couponIds,
|
||||||
userNotes,
|
userNotes,
|
||||||
} = params;
|
} = params;
|
||||||
|
|
||||||
|
|
@ -200,47 +201,48 @@ const placeOrderUtil = async (params: {
|
||||||
}
|
}
|
||||||
|
|
||||||
let totalAmount = 0;
|
let totalAmount = 0;
|
||||||
|
const subOrderSubtotals: number[] = [];
|
||||||
|
const subOrderInputs: { key: number | null; items: CartLine[] }[] = [];
|
||||||
for (const [slotId, items] of ordersBySlot) {
|
for (const [slotId, items] of ordersBySlot) {
|
||||||
const orderTotal = items.reduce(
|
const lines: CartLine[] = [];
|
||||||
(sum, item) => {
|
let orderTotal = 0;
|
||||||
if (!item.product) return sum
|
for (const item of items) {
|
||||||
|
if (!item.product) continue;
|
||||||
const basePrice = params.isFlash
|
const basePrice = params.isFlash
|
||||||
? (item.product.flashPrice ?? item.product.price)
|
? (item.product.flashPrice ?? item.product.price)
|
||||||
: item.product.price
|
: item.product.price;
|
||||||
const itemPrice = parseFloat((basePrice ?? 0).toString())
|
const unitPrice = parseFloat((basePrice ?? 0).toString());
|
||||||
return sum + itemPrice * item.quantity;
|
lines.push({ skuId: item.skuId, quantity: item.quantity, unitPrice });
|
||||||
},
|
orderTotal += unitPrice * item.quantity;
|
||||||
0
|
}
|
||||||
);
|
subOrderInputs.push({ key: slotId, items: lines });
|
||||||
|
subOrderSubtotals.push(orderTotal);
|
||||||
totalAmount += 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
|
// The discount is computed on GOODS subtotals only (delivery — flash or
|
||||||
// cart subtotal, and delivery is decided on the post-discount total.
|
// scheduled — never enters the base), per sub-order, with multiple coupons
|
||||||
let discountAmount = 0;
|
// stacking percentage-first and each capped by its own maxValue.
|
||||||
if (appliedCoupon) {
|
const pricing = computeCartPricing({
|
||||||
const maxValue = appliedCoupon.maxValue
|
subOrders: subOrderInputs,
|
||||||
? parseFloat(appliedCoupon.maxValue.toString())
|
coupons: validatedCoupons.map((c) => ({
|
||||||
: 0;
|
id: c.id,
|
||||||
|
discountPercent: c.discountPercent,
|
||||||
|
flatDiscount: c.flatDiscount,
|
||||||
|
maxValue: c.maxValue,
|
||||||
|
applicableSkuIds: c.applicableSkuIds,
|
||||||
|
})),
|
||||||
|
delivery: { threshold: freeDeliveryThreshold, charge: deliveryCharge },
|
||||||
|
});
|
||||||
|
|
||||||
if (appliedCoupon.discountPercent) {
|
const totalWithDelivery = pricing.grandTotal;
|
||||||
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;
|
|
||||||
|
|
||||||
type OrderData = {
|
type OrderData = {
|
||||||
order: Omit<typeof orders.$inferInsert, "id">;
|
order: Omit<typeof orders.$inferInsert, "id">;
|
||||||
|
|
@ -249,24 +251,15 @@ const placeOrderUtil = async (params: {
|
||||||
};
|
};
|
||||||
|
|
||||||
const ordersData: OrderData[] = [];
|
const ordersData: OrderData[] = [];
|
||||||
let isFirstOrder = true;
|
let subOrderIndex = 0;
|
||||||
|
|
||||||
for (const [slotId, items] of ordersBySlot) {
|
for (const [slotId, items] of ordersBySlot) {
|
||||||
const subOrderTotal = items.reduce(
|
const pricedSubOrder = pricing.subOrders[subOrderIndex];
|
||||||
(sum, item) => {
|
const subOrderTotal = pricedSubOrder.goodsSubtotal;
|
||||||
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 orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0;
|
const orderGroupProportion = totalAmount > 0 ? subOrderTotal / totalAmount : 0;
|
||||||
const orderDiscount = discountAmount * orderGroupProportion;
|
const orderDiscount = pricedSubOrder.discount;
|
||||||
const orderDelivery = isFirstOrder ? expectedDeliveryCharge : 0;
|
const orderDelivery = pricedSubOrder.delivery;
|
||||||
const finalOrderAmount = subOrderTotal - orderDiscount + orderDelivery;
|
const finalOrderAmount = pricedSubOrder.total;
|
||||||
|
|
||||||
const order: Omit<typeof orders.$inferInsert, "id"> = {
|
const order: Omit<typeof orders.$inferInsert, "id"> = {
|
||||||
userId,
|
userId,
|
||||||
|
|
@ -278,6 +271,7 @@ const placeOrderUtil = async (params: {
|
||||||
paymentInfoId: null,
|
paymentInfoId: null,
|
||||||
totalAmount: finalOrderAmount.toString(),
|
totalAmount: finalOrderAmount.toString(),
|
||||||
deliveryCharge: orderDelivery.toString(),
|
deliveryCharge: orderDelivery.toString(),
|
||||||
|
discountAmount: orderDiscount.toString(),
|
||||||
readableId: -1,
|
readableId: -1,
|
||||||
userNotes: userNotes || null,
|
userNotes: userNotes || null,
|
||||||
orderGroupId,
|
orderGroupId,
|
||||||
|
|
@ -313,7 +307,7 @@ const placeOrderUtil = async (params: {
|
||||||
};
|
};
|
||||||
|
|
||||||
ordersData.push({ order, orderItems: orderItemsData, orderStatus: orderStatusData });
|
ordersData.push({ order, orderItems: orderItemsData, orderStatus: orderStatusData });
|
||||||
isFirstOrder = false;
|
subOrderIndex++;
|
||||||
}
|
}
|
||||||
|
|
||||||
const createdOrders = await placeUserOrderTransaction({
|
const createdOrders = await placeUserOrderTransaction({
|
||||||
|
|
@ -332,12 +326,14 @@ const placeOrderUtil = async (params: {
|
||||||
selectedItems.map((item) => item.skuId)
|
selectedItems.map((item) => item.skuId)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (appliedCoupon && createdOrders.length > 0) {
|
if (validatedCoupons.length > 0 && createdOrders.length > 0) {
|
||||||
await recordUserCouponUsage(
|
// One coupon_usage row per coupon, all attached to the primary sub-order
|
||||||
userId,
|
// (highest goods subtotal). Each sub-order's discount is stored on the order
|
||||||
appliedCoupon.id,
|
// itself (discountAmount), so the split is not re-derived at display time.
|
||||||
createdOrders[0].id
|
const primaryOrder = createdOrders[pricing.primaryIndex] ?? createdOrders[0];
|
||||||
);
|
for (const coupon of validatedCoupons) {
|
||||||
|
await recordUserCouponUsage(userId, coupon.id, primaryOrder.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('publishing the order')
|
console.log('publishing the order')
|
||||||
|
|
@ -361,7 +357,7 @@ export const orderRouter = router({
|
||||||
regionId: z.number().int().positive(),
|
regionId: z.number().int().positive(),
|
||||||
boundId: z.number().int().positive().optional(),
|
boundId: z.number().int().positive().optional(),
|
||||||
paymentMethod: z.enum(["online", "cod"]),
|
paymentMethod: z.enum(["online", "cod"]),
|
||||||
couponId: z.number().int().positive().optional(),
|
couponIds: z.array(z.number().int().positive()).optional(),
|
||||||
userNotes: z.string().optional(),
|
userNotes: z.string().optional(),
|
||||||
isFlashDelivery: z.boolean().optional().default(false),
|
isFlashDelivery: z.boolean().optional().default(false),
|
||||||
})
|
})
|
||||||
|
|
@ -380,7 +376,7 @@ export const orderRouter = router({
|
||||||
regionId,
|
regionId,
|
||||||
boundId,
|
boundId,
|
||||||
paymentMethod,
|
paymentMethod,
|
||||||
couponId,
|
couponIds,
|
||||||
userNotes,
|
userNotes,
|
||||||
isFlashDelivery,
|
isFlashDelivery,
|
||||||
} = input;
|
} = input;
|
||||||
|
|
@ -420,7 +416,7 @@ export const orderRouter = router({
|
||||||
selectedItems: processedItems,
|
selectedItems: processedItems,
|
||||||
addressId,
|
addressId,
|
||||||
paymentMethod,
|
paymentMethod,
|
||||||
couponId,
|
couponIds,
|
||||||
userNotes,
|
userNotes,
|
||||||
isFlash: isFlashDelivery,
|
isFlash: isFlashDelivery,
|
||||||
});
|
});
|
||||||
|
|
@ -547,36 +543,18 @@ export const orderRouter = router({
|
||||||
throw new Error("Order not found");
|
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;
|
let couponData = null;
|
||||||
if (couponUsageData.length > 0) {
|
if (couponUsageData.length > 0) {
|
||||||
// The coupon discounts the item subtotal, not the paid total: orders.total_amount
|
// The per-order discount is stored on the order itself (`discount_amount`),
|
||||||
// stores items − discount + delivery, so using it as the base inflated the discount.
|
// so the displayed amount always equals what was charged.
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
couponData = {
|
couponData = {
|
||||||
couponCode: couponUsageData
|
couponCode: couponUsageData.map((u) => u.coupon.couponCode).join(", "),
|
||||||
.map((u) => u.coupon.couponCode)
|
|
||||||
.join(", "),
|
|
||||||
couponDescription: `${couponUsageData.length} coupons applied`,
|
couponDescription: `${couponUsageData.length} coupons applied`,
|
||||||
discountAmount: totalDiscountAmount,
|
discountAmount: parseFloat(order.discountAmount?.toString() || "0"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -173,12 +173,12 @@ passing its id to `placeOrder`.
|
||||||
**Pinned by:** `tests/api/coupon-ux.test.ts` — "rejects user B applying a coupon
|
**Pinned by:** `tests/api/coupon-ux.test.ts` — "rejects user B applying a coupon
|
||||||
issued to user A".
|
issued to user A".
|
||||||
|
|
||||||
> **Partially fixed (FC-04/SEC-06):** `validateAndGetCoupon` now loads
|
> **FIXED 2026-10-11:** `validateAndGetCoupons` now enforces, per coupon: user-based
|
||||||
> `applicableUsers` and rejects a user-based coupon for anyone not listed (unless
|
> applicability, `skuIds`/`coupon_applicable_products` product targeting (the coupon must
|
||||||
> `isApplyForAll`). `skuIds` and region are **not** enforced, and that is now
|
> match at least one cart line, and `minOrder` compares against the targeted subtotal),
|
||||||
> **policy, not a gap** (2026-10-10): coupons are global — neither region-based
|
> region (`coupons.regionId` null = global, else the order's region), and `exclusiveApply`
|
||||||
> nor product/SKU-based — so they apply to any cart in any region.
|
> (an exclusive coupon cannot be combined with any other). The customer coupon list
|
||||||
> `exclusiveApply` remains unenforced.
|
> (`getEligible`/`getMyCoupons`) is region-filtered too.
|
||||||
|
|
||||||
### 9. Cancelling an order does not release its coupon usage
|
### 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
|
**Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: cancelling an
|
||||||
order does not release its coupon usage".
|
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
|
### 10. A cancelled first order poisons an `isFirstOrderOnly` coupon
|
||||||
|
|
||||||
`getOrderCount` counts every order including cancelled ones, and
|
`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
|
**Pinned by:** `tests/api/order-lifecycle-gaps.test.ts` — "pins: a cancelled
|
||||||
first order poisons an isFirstOrderOnly coupon".
|
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**
|
### 11. Reserved-coupon expiry is not checked at redemption — **FIXED 2026-10-10**
|
||||||
|
|
||||||
`redeemReservedCoupon` checked "already redeemed" and first-order-only, but not
|
`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
|
the flag has no effect anywhere. (Observation from reading the code; no runtime
|
||||||
test.)
|
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
|
## Medium — placeOrder guards
|
||||||
|
|
|
||||||
|
|
@ -95,7 +95,7 @@ describe('coupon discount maths', () => {
|
||||||
addressId,
|
addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
...(couponId ? { couponId } : {}),
|
...(couponId ? { couponIds: [couponId] } : {}),
|
||||||
}) as unknown as Promise<Placed>
|
}) as unknown as Promise<Placed>
|
||||||
|
|
||||||
const total = (res: Placed) => parseFloat(res.data[0].totalAmount)
|
const total = (res: Placed) => parseFloat(res.data[0].totalAmount)
|
||||||
|
|
|
||||||
|
|
@ -73,7 +73,7 @@ describe('coupon UX', () => {
|
||||||
addressId: user.addressId,
|
addressId: user.addressId,
|
||||||
regionId: 1,
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
...(couponId ? { couponId } : {}),
|
...(couponId ? { couponIds: [couponId] } : {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
describe('redeemReservedCoupon', () => {
|
describe('redeemReservedCoupon', () => {
|
||||||
|
|
|
||||||
|
|
@ -80,8 +80,9 @@ describe('coupon CRUD + apply', () => {
|
||||||
const placed = await user.user.order.placeOrder.mutate({
|
const placed = await user.user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
couponId,
|
couponIds: [couponId],
|
||||||
})
|
})
|
||||||
|
|
||||||
const orderId = placed.data[0].id
|
const orderId = placed.data[0].id
|
||||||
|
|
@ -103,8 +104,9 @@ describe('coupon CRUD + apply', () => {
|
||||||
user.user.order.placeOrder.mutate({
|
user.user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
couponId,
|
couponIds: [couponId],
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -42,8 +42,9 @@ describe('order lifecycle gaps', () => {
|
||||||
apiClient(userToken).user.order.placeOrder.mutate({
|
apiClient(userToken).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId,
|
addressId,
|
||||||
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
...(couponId ? { couponId } : {}),
|
...(couponId ? { couponIds: [couponId] } : {}),
|
||||||
})
|
})
|
||||||
|
|
||||||
const cancel = (id: number, reason = 'lifecycle test') =>
|
const cancel = (id: number, reason = 'lifecycle test') =>
|
||||||
|
|
@ -60,19 +61,19 @@ describe('order lifecycle gaps', () => {
|
||||||
return created[0]
|
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 coupon = await createCoupon({ flatDiscount: 5, maxLimitForUser: 1 })
|
||||||
|
|
||||||
const placed = await place(coupon.id)
|
const placed = await place(coupon.id)
|
||||||
await cancel(placed.data[0].id)
|
await cancel(placed.data[0].id)
|
||||||
|
|
||||||
// The usage row recorded at placement is not removed on cancel, so the
|
// The usage row is deleted once every sibling order is cancelled, so the
|
||||||
// (now unused) coupon is already exhausted for this user.
|
// (now unused) coupon is spendable again.
|
||||||
const error = await captureError(() => place(coupon.id))
|
const again = await place(coupon.id)
|
||||||
expect(error.message).toMatch(/usage limit/i)
|
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 buyer = await registerUserWithAddress()
|
||||||
const coupon = await createCoupon({ flatDiscount: 5, isFirstOrderOnly: true })
|
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({
|
const first = await apiClient(buyer.token).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
})
|
})
|
||||||
await apiClient(buyer.token).user.order.cancelOrder.mutate({
|
await apiClient(buyer.token).user.order.cancelOrder.mutate({
|
||||||
|
|
@ -87,16 +89,59 @@ describe('order lifecycle gaps', () => {
|
||||||
reason: 'changed mind',
|
reason: 'changed mind',
|
||||||
})
|
})
|
||||||
|
|
||||||
// getOrderCount counts cancelled orders too, so the coupon is now refused.
|
// countEffectiveOrders ignores cancelled orders, so the user is still a
|
||||||
const error = await captureError(() =>
|
// 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({
|
apiClient(buyer.token).user.order.placeOrder.mutate({
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
|
regionId: 1,
|
||||||
paymentMethod: 'cod',
|
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 () => {
|
it('applies an isFirstOrderOnly coupon to a genuinely new user', async () => {
|
||||||
|
|
@ -107,7 +152,7 @@ describe('order lifecycle gaps', () => {
|
||||||
selectedItems: [{ skuId, quantity: 1, slotId }],
|
selectedItems: [{ skuId, quantity: 1, slotId }],
|
||||||
addressId: buyer.addressId,
|
addressId: buyer.addressId,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
couponId: coupon.id,
|
couponIds: [coupon.id],
|
||||||
})
|
})
|
||||||
|
|
||||||
expect(res.success).toBe(true)
|
expect(res.success).toBe(true)
|
||||||
|
|
|
||||||
|
|
@ -15,7 +15,7 @@ import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
|
||||||
interface PaymentAndOrderProps {
|
interface PaymentAndOrderProps {
|
||||||
selectedAddress: number | null;
|
selectedAddress: number | null;
|
||||||
selectedSlots: Record<number, number>;
|
selectedSlots: Record<number, number>;
|
||||||
selectedCouponId: number | null;
|
selectedCouponIds: number[];
|
||||||
cartItems: any[];
|
cartItems: any[];
|
||||||
totalPrice: number;
|
totalPrice: number;
|
||||||
totalSavings?: number;
|
totalSavings?: number;
|
||||||
|
|
@ -32,7 +32,7 @@ interface PaymentAndOrderProps {
|
||||||
const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
selectedAddress,
|
selectedAddress,
|
||||||
selectedSlots,
|
selectedSlots,
|
||||||
selectedCouponId,
|
selectedCouponIds,
|
||||||
cartItems,
|
cartItems,
|
||||||
totalPrice,
|
totalPrice,
|
||||||
totalSavings = 0,
|
totalSavings = 0,
|
||||||
|
|
@ -89,12 +89,18 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
if (!firstOrder.isCod) {
|
if (!firstOrder.isCod) {
|
||||||
// createRazorpayOrderMutation.mutate({ orderId: firstOrder.id.toString() });
|
// createRazorpayOrderMutation.mutate({ orderId: firstOrder.id.toString() });
|
||||||
} else {
|
} 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');
|
clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular');
|
||||||
const successPath = isFlashDelivery
|
const successPath = isFlashDelivery
|
||||||
? '/(drawer)/(tabs)/flash-delivery/order-success'
|
? '/(drawer)/(tabs)/flash-delivery/order-success'
|
||||||
: './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) => {
|
onError: (error: any) => {
|
||||||
|
|
@ -117,12 +123,17 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
const orders = placeOrderMutation.data?.data || [];
|
const orders = placeOrderMutation.data?.data || [];
|
||||||
const firstOrder = orders[0];
|
const firstOrder = orders[0];
|
||||||
utils.user.order.getOrders.invalidate();
|
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');
|
clearCartAndInvalidateQueries(isFlashDelivery ? 'flash' : 'regular');
|
||||||
const successPath = isFlashDelivery
|
const successPath = isFlashDelivery
|
||||||
? '/(drawer)/(tabs)/flash-delivery/order-success'
|
? '/(drawer)/(tabs)/flash-delivery/order-success'
|
||||||
: './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) => {
|
onError: (error: any) => {
|
||||||
Alert.alert('Error', error.message || 'Payment verification failed');
|
Alert.alert('Error', error.message || 'Payment verification failed');
|
||||||
|
|
@ -179,7 +190,7 @@ const PaymentAndOrderComponent: React.FC<PaymentAndOrderProps> = ({
|
||||||
regionId: selectedRegionId,
|
regionId: selectedRegionId,
|
||||||
boundId: constsData?.boundId ?? activeBoundId ?? undefined,
|
boundId: constsData?.boundId ?? activeBoundId ?? undefined,
|
||||||
paymentMethod: paymentMethod,
|
paymentMethod: paymentMethod,
|
||||||
couponId: selectedCouponId || undefined,
|
couponIds: selectedCouponIds.length ? selectedCouponIds : undefined,
|
||||||
userNotes: userNotes,
|
userNotes: userNotes,
|
||||||
isFlashDelivery: isFlashDelivery,
|
isFlashDelivery: isFlashDelivery,
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -29,11 +29,13 @@ import { useCentralProductStore } from '@/src/store/centralProductStore';
|
||||||
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
import { useCentralSlotStore } from '@/src/store/centralSlotStore';
|
||||||
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
|
import { useGetCart, useUpdateCartItem, useRemoveFromCart } from '@/hooks/cart-query-hooks';
|
||||||
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
|
import { useRegionalConsts } from '@/src/hooks/prominent-api-hooks';
|
||||||
|
import { useRegion } from '@/src/hooks/useRegion';
|
||||||
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
|
import CheckoutAddressSelector from '@/components/CheckoutAddressSelector';
|
||||||
import LoginWall from '@/components/LoginWall';
|
import LoginWall from '@/components/LoginWall';
|
||||||
import { useAddressStore } from '@/src/store/addressStore';
|
import { useAddressStore } from '@/src/store/addressStore';
|
||||||
import { useCheckoutStore } from '@/src/store/checkoutStore';
|
import { useCheckoutStore } from '@/src/store/checkoutStore';
|
||||||
import type { FlashDeliveryProps } from '@packages/shared';
|
import type { FlashDeliveryProps } from '@packages/shared';
|
||||||
|
import { computeCouponDiscount, computeEligibleSubtotal, type CartLine } from '@packages/shared';
|
||||||
|
|
||||||
const formatDeliverySlot = (deliveryTime: string): string => {
|
const formatDeliverySlot = (deliveryTime: string): string => {
|
||||||
const time = dayjs(deliveryTime);
|
const time = dayjs(deliveryTime);
|
||||||
|
|
@ -187,6 +189,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
|
const cartType: "regular" | "flash" = isFlashDelivery ? "flash" : "regular";
|
||||||
|
|
||||||
const { selectedAddressId, setSelectedAddressId } = useAddressStore();
|
const { selectedAddressId, setSelectedAddressId } = useAddressStore();
|
||||||
|
const { regionId } = useRegion();
|
||||||
const userNotes = useCheckoutStore((state) => state.userNotes);
|
const userNotes = useCheckoutStore((state) => state.userNotes);
|
||||||
const setUserNotes = useCheckoutStore((state) => state.setUserNotes);
|
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(
|
const { data: couponsRaw, error: couponsError } = trpc.user.coupon.getEligible.useQuery(
|
||||||
undefined,
|
{ regionId: regionId ?? undefined },
|
||||||
{ enabled: isAuthenticated }
|
{ enabled: isAuthenticated }
|
||||||
);
|
);
|
||||||
const constsData = useRegionalConsts();
|
const constsData = useRegionalConsts();
|
||||||
|
|
@ -293,6 +296,13 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined,
|
minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined,
|
||||||
description: generateCouponDescription(coupon),
|
description: generateCouponDescription(coupon),
|
||||||
exclusiveApply: coupon.exclusiveApply,
|
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,
|
isEligible,
|
||||||
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
||||||
};
|
};
|
||||||
|
|
@ -314,7 +324,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
refetchSlots();
|
refetchSlots();
|
||||||
});
|
});
|
||||||
const [selectedSlots, setSelectedSlots] = useState<Record<number, number>>({});
|
const [selectedSlots, setSelectedSlots] = useState<Record<number, number>>({});
|
||||||
const [selectedCouponId, setSelectedCouponId] = useState<number | null>(null);
|
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
|
||||||
const [couponDialogOpen, setCouponDialogOpen] = useState(false);
|
const [couponDialogOpen, setCouponDialogOpen] = useState(false);
|
||||||
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
@ -353,12 +363,30 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
// Calculate coupon discount
|
// Calculate coupon discount
|
||||||
const selectedCoupons = useMemo(
|
const selectedCoupons = useMemo(
|
||||||
() =>
|
() =>
|
||||||
selectedCouponId
|
eligibleCoupons?.filter(
|
||||||
? eligibleCoupons?.filter(
|
(coupon) => selectedCouponIds.includes(coupon.id) && coupon.isEligible
|
||||||
(coupon) => coupon.id === selectedCouponId && coupon.isEligible
|
) ?? [],
|
||||||
)
|
[eligibleCoupons, selectedCouponIds]
|
||||||
: [],
|
);
|
||||||
[eligibleCoupons, selectedCouponId]
|
|
||||||
|
// Cart lines (in-stock only) with their effective unit price, in the shared
|
||||||
|
// shape the coupon helpers expect.
|
||||||
|
const cartLines = useMemo<CartLine[]>(
|
||||||
|
() =>
|
||||||
|
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
|
const totalPrice = cartItems
|
||||||
|
|
@ -384,13 +412,10 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
const dropdownData = useMemo(
|
const dropdownData = useMemo(
|
||||||
() =>
|
() =>
|
||||||
eligibleCoupons?.map((coupon) => {
|
eligibleCoupons?.map((coupon) => {
|
||||||
const discount =
|
const discount = computeCouponDiscount(
|
||||||
coupon.discountType === "percentage"
|
computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }),
|
||||||
? Math.min(
|
coupon
|
||||||
(totalPrice * coupon.discountValue) / 100,
|
);
|
||||||
coupon.maxValue || Infinity
|
|
||||||
)
|
|
||||||
: Math.min(coupon.discountValue, coupon.maxValue || totalPrice);
|
|
||||||
const saveString = !isNaN(discount) ? ` (Save ₹${discount})` : "";
|
const saveString = !isNaN(discount) ? ` (Save ₹${discount})` : "";
|
||||||
const baseLabel = `${coupon.code} - ${coupon.description}${coupon.isEligible ? saveString : ""
|
const baseLabel = `${coupon.code} - ${coupon.description}${coupon.isEligible ? saveString : ""
|
||||||
}`;
|
}`;
|
||||||
|
|
@ -403,7 +428,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
disabled: !coupon.isEligible,
|
disabled: !coupon.isEligible,
|
||||||
};
|
};
|
||||||
}) || [],
|
}) || [],
|
||||||
[eligibleCoupons, totalPrice]
|
[eligibleCoupons, cartLines]
|
||||||
);
|
);
|
||||||
|
|
||||||
const discountAmount = useMemo(
|
const discountAmount = useMemo(
|
||||||
|
|
@ -411,15 +436,13 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
selectedCoupons?.reduce(
|
selectedCoupons?.reduce(
|
||||||
(sum, coupon) =>
|
(sum, coupon) =>
|
||||||
sum +
|
sum +
|
||||||
(coupon.discountType === "percentage"
|
computeCouponDiscount(
|
||||||
? Math.min(
|
computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }),
|
||||||
(totalPrice * coupon.discountValue) / 100,
|
coupon
|
||||||
coupon.maxValue || Infinity
|
),
|
||||||
)
|
|
||||||
: Math.min(coupon.discountValue, coupon.maxValue || totalPrice)),
|
|
||||||
0
|
0
|
||||||
) || 0,
|
) || 0,
|
||||||
[selectedCoupons, totalPrice]
|
[selectedCoupons, cartLines]
|
||||||
);
|
);
|
||||||
|
|
||||||
const finalTotal = totalPrice - discountAmount;
|
const finalTotal = totalPrice - discountAmount;
|
||||||
|
|
@ -1066,10 +1089,21 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
<BottomDropdown
|
<BottomDropdown
|
||||||
label="Available Coupons"
|
label="Available Coupons"
|
||||||
options={dropdownData}
|
options={dropdownData}
|
||||||
value={selectedCouponId || ""}
|
value={""}
|
||||||
// disabled={eligibleCoupons.length === 0}
|
|
||||||
onValueChange={(value) => {
|
onValueChange={(value) => {
|
||||||
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={
|
placeholder={
|
||||||
eligibleCoupons.length === 0
|
eligibleCoupons.length === 0
|
||||||
|
|
@ -1086,13 +1120,13 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
{selectedCouponId && (
|
{selectedCouponIds.length > 0 && (
|
||||||
<MyTouchableOpacity
|
<MyTouchableOpacity
|
||||||
style={tw`mt-3 self-end`}
|
style={tw`mt-3 self-end`}
|
||||||
onPress={() => setSelectedCouponId(null)}
|
onPress={() => setSelectedCouponIds([])}
|
||||||
>
|
>
|
||||||
<MyText style={tw`text-gray-400 text-xs font-medium`}>
|
<MyText style={tw`text-gray-400 text-xs font-medium`}>
|
||||||
Remove coupon
|
Remove coupons
|
||||||
</MyText>
|
</MyText>
|
||||||
</MyTouchableOpacity>
|
</MyTouchableOpacity>
|
||||||
)}
|
)}
|
||||||
|
|
@ -1176,7 +1210,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
<View style={tw`flex-row justify-between items-center mb-3`}>
|
<View style={tw`flex-row justify-between items-center mb-3`}>
|
||||||
<MyText style={tw`text-gray-500`}>Coupon Applied</MyText>
|
<MyText style={tw`text-gray-500`}>Coupon Applied</MyText>
|
||||||
<MyTouchableOpacity onPress={() => setCouponDialogOpen(true)}>
|
<MyTouchableOpacity onPress={() => setCouponDialogOpen(true)}>
|
||||||
<MyText style={tw`text-pink-600 font-medium`}>{selectedCoupons[0].code}</MyText>
|
<MyText style={tw`text-pink-600 font-medium`}>{selectedCoupons.map((coupon) => coupon.code).join(', ')}</MyText>
|
||||||
</MyTouchableOpacity>
|
</MyTouchableOpacity>
|
||||||
</View>
|
</View>
|
||||||
)}
|
)}
|
||||||
|
|
@ -1321,7 +1355,7 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
.join(';');
|
.join(';');
|
||||||
|
|
||||||
router.push(
|
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
|
||||||
);
|
);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -17,6 +17,7 @@ import PaymentAndOrderComponent from '@/components/PaymentAndOrderComponent';
|
||||||
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
|
import CheckoutAddressDisplay from '@/components/CheckoutAddressDisplay';
|
||||||
import { useAddressStore } from '@/src/store/addressStore';
|
import { useAddressStore } from '@/src/store/addressStore';
|
||||||
import type { FlashDeliveryProps } from '@packages/shared';
|
import type { FlashDeliveryProps } from '@packages/shared';
|
||||||
|
import { computeCouponDiscount, computeEligibleSubtotal, type CartLine } from '@packages/shared';
|
||||||
|
|
||||||
const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false }) => {
|
const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false }) => {
|
||||||
const params = useLocalSearchParams();
|
const params = useLocalSearchParams();
|
||||||
|
|
@ -56,7 +57,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
});
|
});
|
||||||
|
|
||||||
const { selectedAddressId } = useAddressStore();
|
const { selectedAddressId } = useAddressStore();
|
||||||
const [selectedCouponId, setSelectedCouponId] = useState<number | null>(null);
|
const [selectedCouponIds, setSelectedCouponIds] = useState<number[]>([]);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -131,8 +132,11 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (params.coupons) {
|
if (params.coupons) {
|
||||||
const couponId = Number(params.coupons as string);
|
const ids = String(params.coupons)
|
||||||
setSelectedCouponId(couponId);
|
.split(',')
|
||||||
|
.map((value) => Number(value))
|
||||||
|
.filter((value) => Number.isFinite(value));
|
||||||
|
setSelectedCouponIds(ids);
|
||||||
}
|
}
|
||||||
}, [params.coupons]);
|
}, [params.coupons]);
|
||||||
|
|
||||||
|
|
@ -162,7 +166,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
);
|
);
|
||||||
|
|
||||||
const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery(
|
const { data: couponsRaw } = trpc.user.coupon.getEligible.useQuery(
|
||||||
undefined,
|
{ regionId: regionId ?? undefined },
|
||||||
{ enabled: isAuthenticated }
|
{ enabled: isAuthenticated }
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -188,6 +192,12 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined,
|
minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined,
|
||||||
description: '',
|
description: '',
|
||||||
exclusiveApply: coupon.exclusiveApply,
|
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,
|
isEligible,
|
||||||
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
ineligibilityReason: isEligible ? undefined : ineligibilityReason,
|
||||||
};
|
};
|
||||||
|
|
@ -196,12 +206,25 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
|
|
||||||
const selectedCoupons = useMemo(
|
const selectedCoupons = useMemo(
|
||||||
() =>
|
() =>
|
||||||
selectedCouponId
|
eligibleCoupons?.filter(
|
||||||
? eligibleCoupons?.filter(
|
(coupon) => selectedCouponIds.includes(coupon.id) && coupon.isEligible
|
||||||
(coupon) => coupon.id === selectedCouponId && coupon.isEligible
|
) ?? [],
|
||||||
)
|
[eligibleCoupons, selectedCouponIds]
|
||||||
: [],
|
);
|
||||||
[eligibleCoupons, selectedCouponId]
|
|
||||||
|
// Lines being ordered, with their effective unit price, for the shared helpers.
|
||||||
|
const cartLines = useMemo<CartLine[]>(
|
||||||
|
() =>
|
||||||
|
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(
|
const discountAmount = useMemo(
|
||||||
|
|
@ -209,15 +232,13 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
selectedCoupons?.reduce(
|
selectedCoupons?.reduce(
|
||||||
(sum, coupon) =>
|
(sum, coupon) =>
|
||||||
sum +
|
sum +
|
||||||
(coupon.discountType === "percentage"
|
computeCouponDiscount(
|
||||||
? Math.min(
|
computeEligibleSubtotal(cartLines, { applicableSkuIds: coupon.applicableSkuIds }),
|
||||||
(totalPrice * coupon.discountValue) / 100,
|
coupon
|
||||||
coupon.maxValue || Infinity
|
),
|
||||||
)
|
|
||||||
: Math.min(coupon.discountValue, coupon.maxValue || totalPrice)),
|
|
||||||
0
|
0
|
||||||
) || 0,
|
) || 0,
|
||||||
[selectedCoupons, totalPrice]
|
[selectedCoupons, cartLines]
|
||||||
);
|
);
|
||||||
|
|
||||||
const finalTotal = totalPrice - discountAmount;
|
const finalTotal = totalPrice - discountAmount;
|
||||||
|
|
@ -365,7 +386,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
<PaymentAndOrderComponent
|
<PaymentAndOrderComponent
|
||||||
selectedAddress={selectedAddressId}
|
selectedAddress={selectedAddressId}
|
||||||
selectedSlots={selectedSlots}
|
selectedSlots={selectedSlots}
|
||||||
selectedCouponId={selectedCouponId}
|
selectedCouponIds={selectedCouponIds}
|
||||||
cartItems={selectedItems}
|
cartItems={selectedItems}
|
||||||
totalPrice={totalPrice}
|
totalPrice={totalPrice}
|
||||||
totalSavings={totalSavings}
|
totalSavings={totalSavings}
|
||||||
|
|
|
||||||
|
|
@ -77,13 +77,18 @@ by `orderGroupProportion` for multi-slot orders and the client does not
|
||||||
(`orderGroupProportion` has zero occurrences in `apps/user-ui`). For a multi-slot
|
(`orderGroupProportion` has zero occurrences in `apps/user-ui`). For a multi-slot
|
||||||
group the two disagree.
|
group the two disagree.
|
||||||
|
|
||||||
The same screen also shows only `orders[0].id` for a group of orders created by
|
**FIXED (amount) 2026-10-11:** `PaymentAndOrderComponent` now sums the
|
||||||
one `placeOrder` call.
|
server-returned orders' `totalAmount` and writes that into the success URL,
|
||||||
|
falling back to `finalTotalWithDelivery` only when the response omits it. The
|
||||||
|
cart/checkout discount is also computed with the shared `computeCartDiscount`
|
||||||
|
helper, so the local preview now matches the server for the single-coupon case.
|
||||||
|
|
||||||
**Fix:** read the amount and the order group from the server after placement.
|
The screen still shows only `orders[0].id` for a group of orders created by one
|
||||||
|
`placeOrder` call (not yet addressed).
|
||||||
|
|
||||||
**Pinned by:** `tests/screens/order-amounts.test.tsx` — "renders whatever amount
|
**Pinned by:** `tests/screens/order-amounts.test.tsx` — "renders whatever amount
|
||||||
the caller put in the query string".
|
the caller put in the query string"; `tests/components/payment-and-order-money.test.tsx`
|
||||||
|
— "uses the server-stored order amount for the success URL when present".
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -26,7 +26,7 @@ const PLACE_ORDER_OK = { data: [{ id: 99, isCod: true }] }
|
||||||
const baseProps = {
|
const baseProps = {
|
||||||
selectedAddress: 1,
|
selectedAddress: 1,
|
||||||
selectedSlots: { 1: 1849 },
|
selectedSlots: { 1: 1849 },
|
||||||
selectedCouponId: null,
|
selectedCouponIds: [],
|
||||||
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
|
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
|
||||||
totalPrice: 215,
|
totalPrice: 215,
|
||||||
totalSavings: 0,
|
totalSavings: 0,
|
||||||
|
|
@ -66,7 +66,7 @@ describe('PaymentAndOrderComponent money', () => {
|
||||||
discountAmount={20}
|
discountAmount={20}
|
||||||
finalTotal={195}
|
finalTotal={195}
|
||||||
finalTotalWithDelivery={210}
|
finalTotalWithDelivery={210}
|
||||||
selectedCouponId={77}
|
selectedCouponIds={[77]}
|
||||||
/>,
|
/>,
|
||||||
{ centralStores: false }
|
{ centralStores: false }
|
||||||
)
|
)
|
||||||
|
|
@ -125,7 +125,7 @@ describe('PaymentAndOrderComponent money', () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
renderWithProviders(
|
renderWithProviders(
|
||||||
<PaymentAndOrderComponent {...baseProps} selectedCouponId={77} />,
|
<PaymentAndOrderComponent {...baseProps} selectedCouponIds={[77]} />,
|
||||||
{ centralStores: false }
|
{ centralStores: false }
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -133,10 +133,30 @@ describe('PaymentAndOrderComponent money', () => {
|
||||||
|
|
||||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder'))
|
await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder'))
|
||||||
const input = lastProcedureInput(api.fetchMock, 'user.order.placeOrder') as Record<string, unknown>
|
const input = lastProcedureInput(api.fetchMock, 'user.order.placeOrder') as Record<string, unknown>
|
||||||
expect(input.couponId).toBe(77)
|
expect(input.couponIds).toEqual([77])
|
||||||
expect(input.isFlashDelivery).toBe(false)
|
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(<PaymentAndOrderComponent {...baseProps} />, { 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 () => {
|
it('places a flash order with null slots and clears the flash cart only', async () => {
|
||||||
const api = setupApiMocks({
|
const api = setupApiMocks({
|
||||||
procedures: { 'user.order.placeOrder': PLACE_ORDER_OK },
|
procedures: { 'user.order.placeOrder': PLACE_ORDER_OK },
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ import { renderWithProviders } from '../helpers/render'
|
||||||
const baseProps = {
|
const baseProps = {
|
||||||
selectedAddress: 1,
|
selectedAddress: 1,
|
||||||
selectedSlots: { 1: 1849 },
|
selectedSlots: { 1: 1849 },
|
||||||
selectedCouponId: null,
|
selectedCouponIds: [],
|
||||||
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
|
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
|
||||||
totalPrice: 215,
|
totalPrice: 215,
|
||||||
totalSavings: 0,
|
totalSavings: 0,
|
||||||
|
|
@ -87,7 +87,7 @@ describe('PaymentAndOrderComponent', () => {
|
||||||
selectedItems: [{ skuId: 2, quantity: 1, slotId: 1849 }],
|
selectedItems: [{ skuId: 2, quantity: 1, slotId: 1849 }],
|
||||||
addressId: 1,
|
addressId: 1,
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
couponId: undefined,
|
couponIds: undefined,
|
||||||
userNotes: '',
|
userNotes: '',
|
||||||
isFlashDelivery: false,
|
isFlashDelivery: false,
|
||||||
})
|
})
|
||||||
|
|
@ -105,7 +105,7 @@ describe('PaymentAndOrderComponent', () => {
|
||||||
renderWithProviders(
|
renderWithProviders(
|
||||||
<PaymentAndOrderComponent
|
<PaymentAndOrderComponent
|
||||||
{...baseProps}
|
{...baseProps}
|
||||||
selectedCouponId={77}
|
selectedCouponIds={[77]}
|
||||||
selectedCoupons={[{ id: 77, code: 'SAVE10' }]}
|
selectedCoupons={[{ id: 77, code: 'SAVE10' }]}
|
||||||
totalPrice={430}
|
totalPrice={430}
|
||||||
discountAmount={43}
|
discountAmount={43}
|
||||||
|
|
@ -131,7 +131,7 @@ describe('PaymentAndOrderComponent', () => {
|
||||||
renderWithProviders(
|
renderWithProviders(
|
||||||
<PaymentAndOrderComponent
|
<PaymentAndOrderComponent
|
||||||
{...baseProps}
|
{...baseProps}
|
||||||
selectedCouponId={77}
|
selectedCouponIds={[77]}
|
||||||
selectedCoupons={[{ id: 77, code: 'SAVE10' }]}
|
selectedCoupons={[{ id: 77, code: 'SAVE10' }]}
|
||||||
discountAmount={43}
|
discountAmount={43}
|
||||||
finalTotal={387}
|
finalTotal={387}
|
||||||
|
|
@ -144,7 +144,7 @@ describe('PaymentAndOrderComponent', () => {
|
||||||
|
|
||||||
await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder'))
|
await waitFor(() => expectProcedureCalled(api.fetchMock, 'user.order.placeOrder'))
|
||||||
expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({
|
expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({
|
||||||
couponId: 77,
|
couponIds: [77],
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -171,7 +171,7 @@ describe('Cart coupon application', () => {
|
||||||
await selectCoupon()
|
await selectCoupon()
|
||||||
expect(screen.getByText('-₹43')).toBeVisible()
|
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('Product Discount')).toBeNull()
|
||||||
expect(screen.queryByText('Coupon Applied')).toBeNull()
|
expect(screen.queryByText('Coupon Applied')).toBeNull()
|
||||||
|
|
|
||||||
|
|
@ -197,7 +197,7 @@ describe('Checkout coupon discount calculation', () => {
|
||||||
expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({
|
expect(lastProcedureInput(api.fetchMock, 'user.order.placeOrder')).toMatchObject({
|
||||||
selectedItems: [{ skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID }],
|
selectedItems: [{ skuId: PRODUCT_ID, quantity: 2, slotId: SLOT_ID }],
|
||||||
addressId: 1,
|
addressId: 1,
|
||||||
couponId: COUPON_ID,
|
couponIds: [COUPON_ID],
|
||||||
paymentMethod: 'cod',
|
paymentMethod: 'cod',
|
||||||
})
|
})
|
||||||
await waitFor(() =>
|
await waitFor(() =>
|
||||||
|
|
|
||||||
|
|
@ -80,7 +80,7 @@ const ORDER = {
|
||||||
const baseProps = {
|
const baseProps = {
|
||||||
selectedAddress: 1,
|
selectedAddress: 1,
|
||||||
selectedSlots: { 1: 1849 },
|
selectedSlots: { 1: 1849 },
|
||||||
selectedCouponId: null,
|
selectedCouponIds: [],
|
||||||
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
|
cartItems: [{ id: 1, skuId: 2, quantity: 1, slotId: 1849 }],
|
||||||
totalPrice: 215,
|
totalPrice: 215,
|
||||||
totalSavings: 0,
|
totalSavings: 0,
|
||||||
|
|
|
||||||
|
|
@ -66,11 +66,10 @@ describe('Order success amounts', () => {
|
||||||
})
|
})
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* KNOWN GAP: `totalAmount` is the frontend's `finalTotalWithDelivery` written
|
* The success screen renders whatever `totalAmount` sits in the route params.
|
||||||
* into the query string by PaymentAndOrderComponent, not the amount the
|
* Since 2026-10-11 `PaymentAndOrderComponent` writes the server-stored order
|
||||||
* backend stored on the order. The multi-slot discount is scaled by
|
* total there (see payment-and-order-money.test.tsx "uses the server-stored
|
||||||
* `orderGroupProportion` server-side but not in the UI, so this number can
|
* order amount…"), but this screen itself still just prints the param.
|
||||||
* differ from what was charged. Pinned as-is.
|
|
||||||
*/
|
*/
|
||||||
it('renders whatever amount the caller put in the query string', async () => {
|
it('renders whatever amount the caller put in the query string', async () => {
|
||||||
searchParamsMock.current = { orderId: '99', totalAmount: '1234.56' }
|
searchParamsMock.current = { orderId: '99', totalAmount: '1234.56' }
|
||||||
|
|
|
||||||
868
change-log.txt
868
change-log.txt
|
|
@ -3457,3 +3457,871 @@ user-ui
|
||||||
regional product, so products/tags/groups needed no change.
|
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
|
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.
|
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<CouponUsageWithCoupon[]>
|
||||||
|
+export async function countEffectiveOrders(userId: number): Promise<number> // distinct non-cancelled groups
|
||||||
|
+export async function releaseCouponUsageIfGroupFullyCancelled(tx, orderId): Promise<void>
|
||||||
|
@@ 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(<PaymentAndOrderComponent {...baseProps} />, { 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<unknown> | 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<AdminProduct | null> {
|
||||||
|
- 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<AdminProduct | null> {
|
||||||
|
- 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<ValidatedCoupon[]> {
|
||||||
|
+ // 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<UserCouponWithRelations[]> {
|
||||||
|
+export async function getActiveCouponsWithRelations(userId: number, regionId?: number): Promise<UserCouponWithRelations[]> {
|
||||||
|
+ 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<UserEligibleCouponsResponse> => {
|
||||||
|
+ .query(async ({ ctx, input }): Promise<UserEligibleCouponsResponse> => {
|
||||||
|
- 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<UserMyCouponsResponse> => {
|
||||||
|
+ .query(async ({ ctx, input }): Promise<UserMyCouponsResponse> => {
|
||||||
|
- 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<void> => {
|
||||||
|
+const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null): Promise<void> => {
|
||||||
|
@@
|
||||||
|
- 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<Coupon>
|
||||||
|
@@
|
||||||
|
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.
|
||||||
|
|
|
||||||
|
|
@ -266,10 +266,13 @@ export {
|
||||||
recordCouponUsage as recordUserCouponUsage,
|
recordCouponUsage as recordUserCouponUsage,
|
||||||
getOrdersWithRelations as getUserOrdersWithRelations,
|
getOrdersWithRelations as getUserOrdersWithRelations,
|
||||||
getOrderCount as getUserOrderCount,
|
getOrderCount as getUserOrderCount,
|
||||||
|
countEffectiveOrders as getUserEffectiveOrderCount,
|
||||||
getOrderByIdWithRelations as getUserOrderByIdWithRelations,
|
getOrderByIdWithRelations as getUserOrderByIdWithRelations,
|
||||||
getCouponUsageForOrder as getUserCouponUsageForOrder,
|
getCouponUsageForOrder as getUserCouponUsageForOrder,
|
||||||
|
getCouponUsageForOrderGroup as getUserCouponUsageForOrderGroup,
|
||||||
getOrderBasic as getUserOrderBasic,
|
getOrderBasic as getUserOrderBasic,
|
||||||
cancelOrderTransaction as cancelUserOrderTransaction,
|
cancelOrderTransaction as cancelUserOrderTransaction,
|
||||||
|
releaseCouponUsageIfGroupFullyCancelled,
|
||||||
updateOrderNotes as updateUserOrderNotes,
|
updateOrderNotes as updateUserOrderNotes,
|
||||||
// Post-order handler helpers
|
// Post-order handler helpers
|
||||||
getOrdersByIdsWithFullData,
|
getOrdersByIdsWithFullData,
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@ import {
|
||||||
refunds,
|
refunds,
|
||||||
} from '../db/schema'
|
} from '../db/schema'
|
||||||
import { and, desc, eq, inArray, lt, SQL } from 'drizzle-orm'
|
import { and, desc, eq, inArray, lt, SQL } from 'drizzle-orm'
|
||||||
|
import { releaseCouponUsageIfGroupFullyCancelled } from '../user-apis/order'
|
||||||
import type {
|
import type {
|
||||||
AdminOrderDetails,
|
AdminOrderDetails,
|
||||||
AdminOrderRow,
|
AdminOrderRow,
|
||||||
|
|
@ -134,8 +135,18 @@ export async function getOrderDetails(orderId: number): Promise<AdminOrderDetail
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let couponOrderIds: number[] = [orderData.id]
|
||||||
|
const orderGroupId = (orderData as any).orderGroupId as string | null
|
||||||
|
if (orderGroupId) {
|
||||||
|
const groupOrders = await db
|
||||||
|
.select({ id: orders.id })
|
||||||
|
.from(orders)
|
||||||
|
.where(eq(orders.orderGroupId, orderGroupId))
|
||||||
|
couponOrderIds = groupOrders.map((o) => o.id)
|
||||||
|
}
|
||||||
|
|
||||||
const couponUsageData = await db.query.couponUsage.findMany({
|
const couponUsageData = await db.query.couponUsage.findMany({
|
||||||
where: eq(couponUsage.orderId, orderData.id),
|
where: inArray(couponUsage.orderId, couponOrderIds),
|
||||||
with: {
|
with: {
|
||||||
coupon: true,
|
coupon: true,
|
||||||
},
|
},
|
||||||
|
|
@ -143,34 +154,11 @@ export async function getOrderDetails(orderId: number): Promise<AdminOrderDetail
|
||||||
|
|
||||||
let couponData = null
|
let couponData = null
|
||||||
if (couponUsageData.length > 0) {
|
if (couponUsageData.length > 0) {
|
||||||
let totalDiscountAmount = 0
|
// The per-order discount is stored on the order (`discount_amount`).
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
couponData = {
|
couponData = {
|
||||||
couponCode: couponUsageData.map((u) => u.coupon.couponCode).join(', '),
|
couponCode: couponUsageData.map((u) => u.coupon.couponCode).join(', '),
|
||||||
couponDescription: `${couponUsageData.length} coupons applied`,
|
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<Admi
|
||||||
refundStatus,
|
refundStatus,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await releaseCouponUsageIfGroupFullyCancelled(tx, order.id)
|
||||||
|
|
||||||
return { orderId: order.id, userId: order.userId }
|
return { orderId: order.id, userId: order.userId }
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -217,6 +217,7 @@ export const orders = mf.table('orders', {
|
||||||
paymentInfoId: integer('payment_info_id').references(() => paymentInfoTable.id),
|
paymentInfoId: integer('payment_info_id').references(() => paymentInfoTable.id),
|
||||||
totalAmount: numeric('total_amount', { precision: 10, scale: 2 }).notNull(),
|
totalAmount: numeric('total_amount', { precision: 10, scale: 2 }).notNull(),
|
||||||
deliveryCharge: numeric('delivery_charge', { precision: 10, scale: 2 }).notNull().default('0'),
|
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(),
|
readableId: integer('readable_id').notNull(),
|
||||||
adminNotes: text('admin_notes'),
|
adminNotes: text('admin_notes'),
|
||||||
userNotes: text('user_notes'),
|
userNotes: text('user_notes'),
|
||||||
|
|
|
||||||
|
|
@ -323,6 +323,28 @@ export async function getOrderCount(userId: number): Promise<number> {
|
||||||
return result[0]?.count ?? 0
|
return result[0]?.count ?? 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Distinct non-cancelled order groups (see the sqlite driver for the rationale).
|
||||||
|
*/
|
||||||
|
export async function countEffectiveOrders(userId: number): Promise<number> {
|
||||||
|
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<string>()
|
||||||
|
for (const row of rows) {
|
||||||
|
if (row.isCancelled === true) continue
|
||||||
|
groups.add(row.orderGroupId ?? `order-${row.id}`)
|
||||||
|
}
|
||||||
|
return groups.size
|
||||||
|
}
|
||||||
|
|
||||||
export async function getOrderByIdWithRelations(
|
export async function getOrderByIdWithRelations(
|
||||||
orderId: number,
|
orderId: number,
|
||||||
userId: number
|
userId: number
|
||||||
|
|
@ -400,6 +422,34 @@ export async function getCouponUsageForOrder(
|
||||||
}) as Promise<CouponUsageWithCoupon[]>
|
}) as Promise<CouponUsageWithCoupon[]>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Coupon usages for a whole order group (see the sqlite driver). */
|
||||||
|
export async function getCouponUsageForOrderGroup(
|
||||||
|
orderGroupId: string
|
||||||
|
): Promise<CouponUsageWithCoupon[]> {
|
||||||
|
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<CouponUsageWithCoupon[]>
|
||||||
|
}
|
||||||
|
|
||||||
export async function getOrderBasic(orderId: number) {
|
export async function getOrderBasic(orderId: number) {
|
||||||
return db.query.orders.findFirst({
|
return db.query.orders.findFirst({
|
||||||
where: eq(orders.id, orderId),
|
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<void> {
|
||||||
|
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(
|
export async function cancelOrderTransaction(
|
||||||
orderId: number,
|
orderId: number,
|
||||||
statusId: number,
|
statusId: number,
|
||||||
|
|
@ -438,6 +526,8 @@ export async function cancelOrderTransaction(
|
||||||
orderId,
|
orderId,
|
||||||
refundStatus,
|
refundStatus,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await releaseCouponUsageIfGroupFullyCancelled(tx, orderId)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -324,7 +324,7 @@ CREATE TABLE `__new_coupons` (
|
||||||
`flat_discount` text,
|
`flat_discount` text,
|
||||||
`min_order` text,
|
`min_order` text,
|
||||||
`sku_ids` text,
|
`sku_ids` text,
|
||||||
`created_by` integer NOT NULL,
|
`created_by` integer,
|
||||||
`max_value` text,
|
`max_value` text,
|
||||||
`is_apply_for_all` integer DEFAULT false NOT NULL,
|
`is_apply_for_all` integer DEFAULT false NOT NULL,
|
||||||
`valid_till` text,
|
`valid_till` text,
|
||||||
|
|
@ -460,6 +460,7 @@ CREATE TABLE `__new_orders` (
|
||||||
`payment_info_id` integer,
|
`payment_info_id` integer,
|
||||||
`total_amount` text NOT NULL,
|
`total_amount` text NOT NULL,
|
||||||
`delivery_charge` text DEFAULT '0' NOT NULL,
|
`delivery_charge` text DEFAULT '0' NOT NULL,
|
||||||
|
`discount_amount` text DEFAULT '0' NOT NULL,
|
||||||
`readable_id` integer NOT NULL,
|
`readable_id` integer NOT NULL,
|
||||||
`admin_notes` text,
|
`admin_notes` text,
|
||||||
`user_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
|
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||||
);
|
);
|
||||||
--> statement-breakpoint
|
--> 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`)
|
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`,`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`;
|
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
|
--> statement-breakpoint
|
||||||
CREATE TABLE `__new_order_items` (
|
CREATE TABLE `__new_order_items` (
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||||
|
|
|
||||||
|
|
@ -272,7 +272,8 @@ export {
|
||||||
|
|
||||||
export {
|
export {
|
||||||
// User Order
|
// User Order
|
||||||
validateAndGetCoupon as validateAndGetUserCoupon,
|
validateAndGetCoupons as validateAndGetUserCoupons,
|
||||||
|
type ValidatedCoupon,
|
||||||
applyDiscountToOrder as applyDiscountToUserOrder,
|
applyDiscountToOrder as applyDiscountToUserOrder,
|
||||||
getAddressByIdAndUser as getUserAddressByIdAndUser,
|
getAddressByIdAndUser as getUserAddressByIdAndUser,
|
||||||
getProductById as getOrderProductById,
|
getProductById as getOrderProductById,
|
||||||
|
|
@ -283,10 +284,13 @@ export {
|
||||||
recordCouponUsage as recordUserCouponUsage,
|
recordCouponUsage as recordUserCouponUsage,
|
||||||
getOrdersWithRelations as getUserOrdersWithRelations,
|
getOrdersWithRelations as getUserOrdersWithRelations,
|
||||||
getOrderCount as getUserOrderCount,
|
getOrderCount as getUserOrderCount,
|
||||||
|
countEffectiveOrders as getUserEffectiveOrderCount,
|
||||||
getOrderByIdWithRelations as getUserOrderByIdWithRelations,
|
getOrderByIdWithRelations as getUserOrderByIdWithRelations,
|
||||||
getCouponUsageForOrder as getUserCouponUsageForOrder,
|
getCouponUsageForOrder as getUserCouponUsageForOrder,
|
||||||
|
getCouponUsageForOrderGroup as getUserCouponUsageForOrderGroup,
|
||||||
getOrderBasic as getUserOrderBasic,
|
getOrderBasic as getUserOrderBasic,
|
||||||
cancelOrderTransaction as cancelUserOrderTransaction,
|
cancelOrderTransaction as cancelUserOrderTransaction,
|
||||||
|
releaseCouponUsageIfGroupFullyCancelled,
|
||||||
updateOrderNotes as updateUserOrderNotes,
|
updateOrderNotes as updateUserOrderNotes,
|
||||||
// Post-order handler helpers
|
// Post-order handler helpers
|
||||||
getOrdersByIdsWithFullData,
|
getOrdersByIdsWithFullData,
|
||||||
|
|
@ -436,6 +440,14 @@ export {
|
||||||
deleteGlobalProductById,
|
deleteGlobalProductById,
|
||||||
} from './src/superadmin-apis/global-products'
|
} from './src/superadmin-apis/global-products'
|
||||||
|
|
||||||
|
export {
|
||||||
|
listGlobalCoupons,
|
||||||
|
getGlobalCoupon,
|
||||||
|
createGlobalCoupon,
|
||||||
|
updateGlobalCoupon,
|
||||||
|
invalidateGlobalCoupon,
|
||||||
|
} from './src/superadmin-apis/global-coupons'
|
||||||
|
|
||||||
export {
|
export {
|
||||||
listAllProducts,
|
listAllProducts,
|
||||||
elevateProductToGlobal,
|
elevateProductToGlobal,
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
import { db } from '../db/db_index'
|
import { db } from '../db/db_index'
|
||||||
import { coupons, reservedCoupons, users, orders, orderStatus, couponApplicableUsers, couponApplicableProducts, productSkus } from '../db/schema'
|
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'
|
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
||||||
|
|
||||||
const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number): Promise<void> => {
|
const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null): Promise<void> => {
|
||||||
const unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))]
|
const unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))]
|
||||||
if (unique.length === 0) return
|
if (unique.length === 0) return
|
||||||
const rows = await txOrDb.query.productSkus.findMany({
|
const rows = await txOrDb.query.productSkus.findMany({
|
||||||
|
|
@ -103,7 +103,7 @@ export async function createCouponWithRelations(
|
||||||
input: CouponFormInput,
|
input: CouponFormInput,
|
||||||
applicableUsers: number[] | undefined,
|
applicableUsers: number[] | undefined,
|
||||||
applicableProducts: number[] | undefined,
|
applicableProducts: number[] | undefined,
|
||||||
regionId: number
|
regionId: number | null
|
||||||
): Promise<Coupon> {
|
): Promise<Coupon> {
|
||||||
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
||||||
|
|
||||||
|
|
@ -148,14 +148,17 @@ export async function createCouponWithRelations(
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateCouponWithRelations(
|
export async function updateCouponWithRelations(
|
||||||
regionId: number,
|
regionId: number | null,
|
||||||
id: number,
|
id: number,
|
||||||
input: CouponFormInput,
|
input: CouponFormInput,
|
||||||
applicableUsers?: number[],
|
applicableUsers?: number[],
|
||||||
applicableProducts?: number[]
|
applicableProducts?: number[]
|
||||||
): Promise<Coupon | null> {
|
): Promise<Coupon | null> {
|
||||||
const existing = await db.query.coupons.findFirst({
|
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 },
|
columns: { id: true },
|
||||||
})
|
})
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
|
|
@ -173,7 +176,12 @@ export async function updateCouponWithRelations(
|
||||||
.set({
|
.set({
|
||||||
...updateFields,
|
...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()
|
.returning()
|
||||||
|
|
||||||
if (applicableUsers !== undefined) {
|
if (applicableUsers !== undefined) {
|
||||||
|
|
@ -204,10 +212,15 @@ export async function updateCouponWithRelations(
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function invalidateCoupon(regionId: number, id: number): Promise<Coupon | null> {
|
export async function invalidateCoupon(regionId: number | null, id: number): Promise<Coupon | null> {
|
||||||
const result = await db.update(coupons)
|
const result = await db.update(coupons)
|
||||||
.set({ isInvalidated: true })
|
.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()
|
.returning()
|
||||||
|
|
||||||
return (result[0] ?? null) as Coupon | null
|
return (result[0] ?? null) as Coupon | null
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import {
|
||||||
refunds,
|
refunds,
|
||||||
} from '../db/schema'
|
} from '../db/schema'
|
||||||
import { and, desc, eq, gt, inArray, lt, SQL } from 'drizzle-orm'
|
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 {
|
import type {
|
||||||
AdminOrderDetails,
|
AdminOrderDetails,
|
||||||
AdminOrderRow,
|
AdminOrderRow,
|
||||||
|
|
@ -159,8 +159,17 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
||||||
return null
|
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({
|
const couponUsageData = await db.query.couponUsage.findMany({
|
||||||
where: eq(couponUsage.orderId, orderData.id),
|
where: inArray(couponUsage.orderId, couponOrderIds),
|
||||||
with: {
|
with: {
|
||||||
coupon: true,
|
coupon: true,
|
||||||
},
|
},
|
||||||
|
|
@ -168,26 +177,11 @@ export async function getOrderDetails(regionId: number, orderId: number): Promis
|
||||||
|
|
||||||
let couponData = null
|
let couponData = null
|
||||||
if (couponUsageData.length > 0) {
|
if (couponUsageData.length > 0) {
|
||||||
// The coupon discounts the item subtotal, not the paid total: orders.total_amount
|
// The per-order discount is stored on the order (`discount_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
|
|
||||||
}
|
|
||||||
|
|
||||||
couponData = {
|
couponData = {
|
||||||
couponCode: couponUsageData.map((u: any) => u.coupon.couponCode).join(', '),
|
couponCode: couponUsageData.map((u: any) => u.coupon.couponCode).join(', '),
|
||||||
couponDescription: `${couponUsageData.length} coupons applied`,
|
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) {
|
for (const item of updatedOrderItems) {
|
||||||
const price = priceById.get(item.id)
|
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
|
await tx
|
||||||
.update(orderItems)
|
.update(orderItems)
|
||||||
.set({
|
.set({
|
||||||
price,
|
price: String(price),
|
||||||
discountedPrice: price,
|
discountedPrice: String(price),
|
||||||
})
|
})
|
||||||
.where(eq(orderItems.id, item.id))
|
.where(eq(orderItems.id, item.id))
|
||||||
}
|
}
|
||||||
|
|
@ -765,6 +761,8 @@ export async function cancelOrder(regionId: number, orderId: number, reason: str
|
||||||
refundStatus,
|
refundStatus,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await releaseCouponUsageIfGroupFullyCancelled(tx, order.id)
|
||||||
|
|
||||||
return { orderId: order.id, userId: order.userId }
|
return { orderId: order.id, userId: order.userId }
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -391,11 +391,15 @@ async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function deleteProduct(regionId: number, id: number): Promise<AdminProduct | null> {
|
export async function deleteProduct(regionId: number, id: number): Promise<AdminProduct | null> {
|
||||||
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<AdminProduct | null> {
|
export async function deleteGlobalProduct(id: number): Promise<AdminProduct | null> {
|
||||||
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<AdminProductWithRelations> {
|
export async function createProduct(input: CreateProductInput, regionId: number | null): Promise<AdminProductWithRelations> {
|
||||||
|
|
|
||||||
|
|
@ -362,6 +362,7 @@ export const orders = sqliteTable('orders', {
|
||||||
paymentInfoId: integer('payment_info_id').references(() => paymentInfoTable.id),
|
paymentInfoId: integer('payment_info_id').references(() => paymentInfoTable.id),
|
||||||
totalAmount: numericText('total_amount').notNull(),
|
totalAmount: numericText('total_amount').notNull(),
|
||||||
deliveryCharge: numericText('delivery_charge').notNull().default('0'),
|
deliveryCharge: numericText('delivery_charge').notNull().default('0'),
|
||||||
|
discountAmount: numericText('discount_amount').notNull().default('0'),
|
||||||
readableId: integer('readable_id').notNull(),
|
readableId: integer('readable_id').notNull(),
|
||||||
adminNotes: text('admin_notes'),
|
adminNotes: text('admin_notes'),
|
||||||
userNotes: text('user_notes'),
|
userNotes: text('user_notes'),
|
||||||
|
|
@ -533,7 +534,7 @@ export const coupons = sqliteTable('coupons', {
|
||||||
flatDiscount: numericText('flat_discount'),
|
flatDiscount: numericText('flat_discount'),
|
||||||
minOrder: numericText('min_order'),
|
minOrder: numericText('min_order'),
|
||||||
skuIds: jsonText<number[] | null>('sku_ids'),
|
skuIds: jsonText<number[] | null>('sku_ids'),
|
||||||
createdBy: integer('created_by').notNull().references(() => staffUsers.id),
|
createdBy: integer('created_by').references(() => staffUsers.id),
|
||||||
maxValue: numericText('max_value'),
|
maxValue: numericText('max_value'),
|
||||||
isApplyForAll: integer('is_apply_for_all', { mode: 'boolean' }).notNull().default(false),
|
isApplyForAll: integer('is_apply_for_all', { mode: 'boolean' }).notNull().default(false),
|
||||||
validTill: timestampText('valid_till'),
|
validTill: timestampText('valid_till'),
|
||||||
|
|
|
||||||
|
|
@ -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<Coupon> {
|
||||||
|
return createCouponWithRelations(input, applicableUsers, applicableProducts, null)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateGlobalCoupon(
|
||||||
|
id: number,
|
||||||
|
input: CouponFormInput,
|
||||||
|
applicableUsers?: number[],
|
||||||
|
applicableProducts?: number[]
|
||||||
|
): Promise<Coupon | null> {
|
||||||
|
return updateCouponWithRelations(null, id, input, applicableUsers, applicableProducts)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function invalidateGlobalCoupon(id: number): Promise<Coupon | null> {
|
||||||
|
return invalidateCoupon(null, id)
|
||||||
|
}
|
||||||
|
|
@ -66,14 +66,23 @@ const mapCouponWithRelations = (coupon: CouponRow & {
|
||||||
applicableProducts: coupon.applicableProducts.map(mapApplicableProduct),
|
applicableProducts: coupon.applicableProducts.map(mapApplicableProduct),
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function getActiveCouponsWithRelations(userId: number): Promise<UserCouponWithRelations[]> {
|
export async function getActiveCouponsWithRelations(
|
||||||
|
userId: number,
|
||||||
|
regionId?: number
|
||||||
|
): Promise<UserCouponWithRelations[]> {
|
||||||
|
const regionCondition =
|
||||||
|
regionId != null
|
||||||
|
? or(isNull(coupons.regionId), eq(coupons.regionId, regionId))
|
||||||
|
: undefined
|
||||||
|
|
||||||
const allCoupons = await db.query.coupons.findMany({
|
const allCoupons = await db.query.coupons.findMany({
|
||||||
where: and(
|
where: and(
|
||||||
eq(coupons.isInvalidated, false),
|
eq(coupons.isInvalidated, false),
|
||||||
or(
|
or(
|
||||||
isNull(coupons.validTill),
|
isNull(coupons.validTill),
|
||||||
gt(coupons.validTill, new Date())
|
gt(coupons.validTill, new Date())
|
||||||
)
|
),
|
||||||
|
regionCondition
|
||||||
),
|
),
|
||||||
with: {
|
with: {
|
||||||
usages: {
|
usages: {
|
||||||
|
|
@ -87,8 +96,17 @@ export async function getActiveCouponsWithRelations(userId: number): Promise<Use
|
||||||
return allCoupons.map(mapCouponWithRelations)
|
return allCoupons.map(mapCouponWithRelations)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getAllCouponsWithRelations(userId: number): Promise<UserCouponWithRelations[]> {
|
export async function getAllCouponsWithRelations(
|
||||||
|
userId: number,
|
||||||
|
regionId?: number
|
||||||
|
): Promise<UserCouponWithRelations[]> {
|
||||||
|
const regionCondition =
|
||||||
|
regionId != null
|
||||||
|
? or(isNull(coupons.regionId), eq(coupons.regionId, regionId))
|
||||||
|
: undefined
|
||||||
|
|
||||||
const allCoupons = await db.query.coupons.findMany({
|
const allCoupons = await db.query.coupons.findMany({
|
||||||
|
where: regionCondition,
|
||||||
with: {
|
with: {
|
||||||
usages: {
|
usages: {
|
||||||
where: eq(couponUsage.userId, userId),
|
where: eq(couponUsage.userId, userId),
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ import { coerceDate } from '../lib/date'
|
||||||
import { runBatched } from '../lib/run-batched'
|
import { runBatched } from '../lib/run-batched'
|
||||||
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
|
import { composeSkuName, composeUnitNotation } from '../lib/sku-features'
|
||||||
import { marketStatsForRegion } from '../lib/market-stats'
|
import { marketStatsForRegion } from '../lib/market-stats'
|
||||||
|
import { computeEligibleSubtotal, type CartLine } from '@packages/shared'
|
||||||
|
|
||||||
export interface OrderWithRelations {
|
export interface OrderWithRelations {
|
||||||
id: number
|
id: number
|
||||||
|
|
@ -39,10 +40,13 @@ export interface OrderWithRelations {
|
||||||
slotId: number | null
|
slotId: number | null
|
||||||
totalAmount: string
|
totalAmount: string
|
||||||
deliveryCharge: string
|
deliveryCharge: string
|
||||||
|
discountAmount: string
|
||||||
isCod: boolean
|
isCod: boolean
|
||||||
isOnlinePayment: boolean
|
isOnlinePayment: boolean
|
||||||
isFlashDelivery: boolean
|
isFlashDelivery: boolean
|
||||||
userNotes: string | null
|
userNotes: string | null
|
||||||
|
orderGroupId: string | null
|
||||||
|
orderGroupProportion: string | null
|
||||||
createdAt: Date
|
createdAt: Date
|
||||||
orderItems: Array<{
|
orderItems: Array<{
|
||||||
id: number
|
id: number
|
||||||
|
|
@ -102,57 +106,125 @@ export interface CouponValidationResult {
|
||||||
}>
|
}>
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function validateAndGetCoupon(
|
export interface ValidatedCoupon extends CouponValidationResult {
|
||||||
couponId: number | undefined,
|
/** targeted SKU ids; null => applies to the whole cart */
|
||||||
userId: number,
|
applicableSkuIds: number[] | null
|
||||||
totalAmount: number
|
/** the goods subtotal this coupon discounts (whole cart or the targeted items) */
|
||||||
): Promise<CouponValidationResult | null> {
|
eligibleSubtotal: number
|
||||||
if (!couponId) return null
|
}
|
||||||
|
|
||||||
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<ValidatedCoupon[]> {
|
||||||
|
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: {
|
with: {
|
||||||
usages: { where: eq(couponUsage.userId, userId) },
|
usages: { where: eq(couponUsage.userId, params.userId) },
|
||||||
applicableUsers: true,
|
applicableUsers: true,
|
||||||
|
applicableProducts: true,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!coupon) throw new Error('Invalid coupon')
|
if (rows.length !== ids.length) {
|
||||||
|
const found = new Set(rows.map((r) => r.id))
|
||||||
|
throw new Error(
|
||||||
|
`Invalid coupon: ${ids.filter((id) => !found.has(id)).join(', ')}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ids.length > 1 && rows.some((r) => r.exclusiveApply)) {
|
||||||
|
throw new Error('An exclusive coupon cannot be combined with other coupons')
|
||||||
|
}
|
||||||
|
|
||||||
|
const byId = new Map(rows.map((r) => [r.id, r]))
|
||||||
|
const isFirstOrder = (await countEffectiveOrders(params.userId)) === 0
|
||||||
|
const validated: ValidatedCoupon[] = []
|
||||||
|
|
||||||
|
for (const id of ids) {
|
||||||
|
const coupon = byId.get(id)!
|
||||||
|
const usages = coupon.usages ?? []
|
||||||
|
|
||||||
// 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) {
|
if (coupon.isUserBased && !coupon.isApplyForAll) {
|
||||||
const applicableUsers = coupon.applicableUsers ?? []
|
const applicableUsers = coupon.applicableUsers ?? []
|
||||||
if (!applicableUsers.some((au) => au.userId === userId)) {
|
if (!applicableUsers.some((au) => au.userId === params.userId)) {
|
||||||
throw new Error('This coupon is not applicable to your account')
|
throw new Error('This coupon is not applicable to your account')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (coupon.isInvalidated) throw new Error('Coupon is no longer valid')
|
if (coupon.isInvalidated) throw new Error('Coupon is no longer valid')
|
||||||
if (coupon.validTill && new Date(coupon.validTill) < new Date())
|
if (coupon.validTill && new Date(coupon.validTill) < new Date()) {
|
||||||
throw new Error('Coupon has expired')
|
throw new Error('Coupon has expired')
|
||||||
if (
|
}
|
||||||
coupon.maxLimitForUser &&
|
if (coupon.maxLimitForUser && usages.length >= coupon.maxLimitForUser) {
|
||||||
coupon.usages.length >= coupon.maxLimitForUser
|
|
||||||
)
|
|
||||||
throw new Error('Coupon usage limit exceeded')
|
throw new Error('Coupon usage limit exceeded')
|
||||||
if (
|
}
|
||||||
coupon.minOrder &&
|
if (coupon.regionId != null && coupon.regionId !== params.regionId) {
|
||||||
parseFloat(coupon.minOrder.toString()) > totalAmount
|
throw new Error('Coupon is not valid in this region')
|
||||||
)
|
}
|
||||||
throw new Error('Order amount does not meet coupon minimum requirement')
|
if (coupon.isFirstOrderOnly && !isFirstOrder) {
|
||||||
|
|
||||||
if (coupon.isFirstOrderOnly) {
|
|
||||||
const orderCount = await getOrderCount(userId)
|
|
||||||
if (orderCount > 0) {
|
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"This is first order only coupon. You already placed your first order. This coupon doesn't apply to you"
|
"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')
|
||||||
}
|
}
|
||||||
|
|
||||||
return coupon as CouponValidationResult
|
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
/** The discount fields a coupon row carries. `CouponValidationResult` and the coupon rows
|
||||||
|
|
@ -436,6 +508,32 @@ export async function getOrderCount(userId: number): Promise<number> {
|
||||||
return Number(result[0]?.count ?? 0)
|
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<number> {
|
||||||
|
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<string>()
|
||||||
|
for (const row of rows) {
|
||||||
|
if (row.isCancelled === true) continue
|
||||||
|
groups.add(row.orderGroupId ?? `order-${row.id}`)
|
||||||
|
}
|
||||||
|
return groups.size
|
||||||
|
}
|
||||||
|
|
||||||
export async function getOrderByIdWithRelations(
|
export async function getOrderByIdWithRelations(
|
||||||
orderId: number,
|
orderId: number,
|
||||||
userId: number
|
userId: number
|
||||||
|
|
@ -548,6 +646,38 @@ export async function getCouponUsageForOrder(
|
||||||
}) as Promise<CouponUsageWithCoupon[]>
|
}) as Promise<CouponUsageWithCoupon[]>
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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<CouponUsageWithCoupon[]> {
|
||||||
|
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<CouponUsageWithCoupon[]>
|
||||||
|
}
|
||||||
|
|
||||||
export async function getOrderBasic(orderId: number) {
|
export async function getOrderBasic(orderId: number) {
|
||||||
return db.query.orders.findFirst({
|
return db.query.orders.findFirst({
|
||||||
where: eq(orders.id, orderId),
|
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<void> {
|
||||||
|
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(
|
export async function cancelOrderTransaction(
|
||||||
orderId: number,
|
orderId: number,
|
||||||
statusId: number,
|
statusId: number,
|
||||||
|
|
@ -586,6 +759,8 @@ export async function cancelOrderTransaction(
|
||||||
orderId,
|
orderId,
|
||||||
refundStatus,
|
refundStatus,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
await releaseCouponUsageIfGroupFullyCancelled(tx, orderId)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
209
packages/shared/cart-pricing.ts
Normal file
209
packages/shared/cart-pricing.ts
Normal file
|
|
@ -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<TargetedCoupon, 'applicableSkuIds'>
|
||||||
|
): 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<TargetedCoupon, 'applicableSkuIds'>
|
||||||
|
): 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -22,7 +22,7 @@ export interface Coupon {
|
||||||
isFirstOrderOnly: boolean;
|
isFirstOrderOnly: boolean;
|
||||||
isInvalidated: boolean;
|
isInvalidated: boolean;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
createdBy: number;
|
createdBy: number | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Complete form payload for BOTH create and update — callers always send
|
// Complete form payload for BOTH create and update — callers always send
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue