163 lines
6.4 KiB
TypeScript
163 lines
6.4 KiB
TypeScript
import { router, protectedProcedure } from '@/src/trpc/trpc-index'
|
|
import { z } from 'zod'
|
|
import { ApiError } from '@/src/lib/api-error'
|
|
import {
|
|
getUserActiveCouponsWithRelations as getUserActiveCouponsWithRelationsInDb,
|
|
getUserAllCouponsWithRelations as getUserAllCouponsWithRelationsInDb,
|
|
getUserReservedCouponByCode as getUserReservedCouponByCodeInDb,
|
|
redeemUserReservedCoupon as redeemUserReservedCouponInDb,
|
|
getUserEffectiveOrderCount as getUserOrderCountInDb,
|
|
} from '@/src/dbService'
|
|
import type {
|
|
UserCouponDisplay,
|
|
UserEligibleCouponsResponse,
|
|
UserMyCouponsResponse,
|
|
UserRedeemCouponResponse,
|
|
} from '@packages/shared'
|
|
|
|
const generateCouponDescription = (coupon: { discountPercent?: string | null; flatDiscount?: string | null; minOrder?: string | null; maxValue?: string | null }): string => {
|
|
let desc = '';
|
|
|
|
if (coupon.discountPercent) {
|
|
desc += `${coupon.discountPercent}% off`;
|
|
} else if (coupon.flatDiscount) {
|
|
desc += `₹${coupon.flatDiscount} off`;
|
|
}
|
|
|
|
if (coupon.minOrder) {
|
|
desc += ` on orders above ₹${coupon.minOrder}`;
|
|
}
|
|
|
|
if (coupon.maxValue) {
|
|
desc += ` (max discount ₹${coupon.maxValue})`;
|
|
}
|
|
|
|
return desc;
|
|
};
|
|
|
|
export const userCouponRouter = router({
|
|
getEligible: protectedProcedure
|
|
.input(z.object({ regionId: z.number().int().positive().optional() }).optional())
|
|
.query(async ({ ctx, input }): Promise<UserEligibleCouponsResponse> => {
|
|
try {
|
|
|
|
const userId = ctx.user.userId;
|
|
|
|
const allCoupons = await getUserActiveCouponsWithRelationsInDb(userId, input?.regionId)
|
|
|
|
// Filter to only coupons applicable to current user
|
|
const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0;
|
|
const applicableCoupons = allCoupons.filter(coupon => {
|
|
if (coupon.isFirstOrderOnly && !isFirstOrder) return false;
|
|
if(!coupon.isUserBased) return true;
|
|
const applicableUsers = coupon.applicableUsers || [];
|
|
return applicableUsers.some(au => au.userId === userId);
|
|
});
|
|
|
|
return { success: true, data: applicableCoupons };
|
|
}
|
|
catch(e) {
|
|
console.log(e)
|
|
throw new ApiError("Unable to get coupons")
|
|
}
|
|
}),
|
|
|
|
getMyCoupons: protectedProcedure
|
|
.input(z.object({ regionId: z.number().int().positive().optional() }).optional())
|
|
.query(async ({ ctx, input }): Promise<UserMyCouponsResponse> => {
|
|
const userId = ctx.user.userId;
|
|
|
|
const allCoupons = await getUserAllCouponsWithRelationsInDb(userId, input?.regionId)
|
|
|
|
// Filter coupons in JS: not invalidated, applicable to user, not expired, and first-order eligible
|
|
const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0;
|
|
const applicableCoupons = allCoupons.filter(coupon => {
|
|
const isNotInvalidated = !coupon.isInvalidated;
|
|
const applicableUsers = coupon.applicableUsers || [];
|
|
const isApplicable = coupon.isApplyForAll || applicableUsers.some(au => au.userId === userId);
|
|
const isNotExpired = !coupon.validTill || new Date(coupon.validTill) > new Date();
|
|
const isFirstOrderEligible = !coupon.isFirstOrderOnly || isFirstOrder;
|
|
return isNotInvalidated && isApplicable && isNotExpired && isFirstOrderEligible;
|
|
});
|
|
|
|
// Categorize coupons
|
|
const personalCoupons: UserCouponDisplay[] = [];
|
|
const generalCoupons: UserCouponDisplay[] = [];
|
|
|
|
applicableCoupons.forEach(coupon => {
|
|
const usageCount = coupon.usages.length;
|
|
const isExpired = false; // Already filtered out expired coupons
|
|
const isUsedUp = Boolean(coupon.maxLimitForUser && usageCount >= coupon.maxLimitForUser);
|
|
|
|
const couponDisplay: UserCouponDisplay = {
|
|
id: coupon.id,
|
|
code: coupon.couponCode,
|
|
discountType: coupon.discountPercent ? 'percentage' : 'flat',
|
|
discountValue: parseFloat(coupon.discountPercent || coupon.flatDiscount || '0'),
|
|
maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined,
|
|
minOrder: coupon.minOrder ? parseFloat(coupon.minOrder) : undefined,
|
|
description: generateCouponDescription(coupon),
|
|
validTill: coupon.validTill ? new Date(coupon.validTill) : undefined,
|
|
usageCount,
|
|
maxLimitForUser: coupon.maxLimitForUser ? parseInt(coupon.maxLimitForUser.toString()) : undefined,
|
|
isExpired,
|
|
isUsedUp,
|
|
};
|
|
|
|
if ((coupon.applicableUsers || []).some(au => au.userId === userId) && !coupon.isApplyForAll) {
|
|
// Personal coupon
|
|
personalCoupons.push(couponDisplay);
|
|
} else if (coupon.isApplyForAll) {
|
|
// General coupon
|
|
generalCoupons.push(couponDisplay);
|
|
}
|
|
});
|
|
|
|
return {
|
|
success: true,
|
|
data: {
|
|
personal: personalCoupons,
|
|
general: generalCoupons,
|
|
}
|
|
};
|
|
}),
|
|
|
|
redeemReservedCoupon: protectedProcedure
|
|
.input(z.object({ secretCode: z.string() }))
|
|
.mutation(async ({ input, ctx }): Promise<UserRedeemCouponResponse> => {
|
|
const userId = ctx.user.userId;
|
|
const { secretCode } = input;
|
|
|
|
const reservedCoupon = await getUserReservedCouponByCodeInDb(secretCode)
|
|
|
|
if (!reservedCoupon) {
|
|
throw new ApiError("Invalid or already redeemed coupon code", 400);
|
|
}
|
|
|
|
// A reserved coupon's validTill is the deadline for claiming the secret as well as for
|
|
// spending the coupon, so an expired code must not redeem: otherwise the code is burned
|
|
// and the customer is handed an already-expired coupon.
|
|
if (reservedCoupon.validTill && new Date(reservedCoupon.validTill) < new Date()) {
|
|
throw new ApiError("This coupon has expired", 400);
|
|
}
|
|
|
|
// Check if already redeemed by this user (in case of multiple attempts)
|
|
if (reservedCoupon.redeemedBy === userId) {
|
|
throw new ApiError("You have already redeemed this coupon", 400);
|
|
}
|
|
|
|
const isFirstOrder = (await getUserOrderCountInDb(userId)) === 0;
|
|
if (reservedCoupon.isFirstOrderOnly && !isFirstOrder) {
|
|
throw new ApiError("This is first order only coupon. You already placed your first order. This coupon doesn't apply to you", 400);
|
|
}
|
|
|
|
const couponResult = await redeemUserReservedCouponInDb(userId, reservedCoupon)
|
|
|
|
if (!couponResult) {
|
|
// Lost the claim race: another request redeemed the same secret first.
|
|
throw new ApiError("Invalid or already redeemed coupon code", 400);
|
|
}
|
|
|
|
return { success: true, coupon: couponResult };
|
|
}),
|
|
});
|