enh
This commit is contained in:
parent
60952bfefb
commit
9a7bb09228
30 changed files with 271 additions and 176 deletions
|
|
@ -78,7 +78,7 @@ export default function EditCoupon() {
|
||||||
validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined,
|
validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined,
|
||||||
maxLimitForUser: coupon.maxLimitForUser || undefined,
|
maxLimitForUser: coupon.maxLimitForUser || undefined,
|
||||||
isFirstOrderOnly: coupon.isFirstOrderOnly,
|
isFirstOrderOnly: coupon.isFirstOrderOnly,
|
||||||
skuIds: coupon.skuIds,
|
skuIds: coupon.skuIds ?? [],
|
||||||
isReservedCoupon: false, // Normal coupons
|
isReservedCoupon: false, // Normal coupons
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -81,9 +81,9 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
|
||||||
<MyText style={tw`text-sm text-gray-700 mb-1`}>
|
<MyText style={tw`text-sm text-gray-700 mb-1`}>
|
||||||
<MaterialCommunityIcons name="account-group" size={14} color="#6b7280" /> Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
|
<MaterialCommunityIcons name="account-group" size={14} color="#6b7280" /> Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
|
||||||
</MyText>
|
</MyText>
|
||||||
{item.applicableProducts && item.applicableProducts.length > 0 && (
|
{item.skuIds && item.skuIds.length > 0 && (
|
||||||
<MyText style={tw`text-sm text-gray-700`}>
|
<MyText style={tw`text-sm text-gray-700`}>
|
||||||
<MaterialCommunityIcons name="package-variant" size={14} color="#6b7280" /> Products: {item.applicableProducts.length} selected
|
<MaterialCommunityIcons name="package-variant" size={14} color="#6b7280" /> Products: {item.skuIds.length} selected
|
||||||
</MyText>
|
</MyText>
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,7 @@ import { Formik } from 'formik';
|
||||||
import * as Yup from 'yup';
|
import * as Yup from 'yup';
|
||||||
import { MyTextInput, MyButton, tw, AppContainer , DateTimePickerMod, Checkbox, BottomDialog, MyText } from 'common-ui';
|
import { MyTextInput, MyButton, tw, AppContainer , DateTimePickerMod, Checkbox, BottomDialog, MyText } from 'common-ui';
|
||||||
import { trpc } from '../trpc-client';
|
import { trpc } from '../trpc-client';
|
||||||
|
import ProductsSelector from '@/components/ProductsSelector';
|
||||||
|
|
||||||
import { CreateCouponPayload } from 'common-ui/shared-types';
|
import { CreateCouponPayload } from 'common-ui/shared-types';
|
||||||
|
|
||||||
|
|
@ -46,6 +47,7 @@ const couponValidationSchema = Yup.object().shape({
|
||||||
isUserBased: Yup.boolean(),
|
isUserBased: Yup.boolean(),
|
||||||
isApplyForAll: Yup.boolean(),
|
isApplyForAll: Yup.boolean(),
|
||||||
applicableUsers: Yup.array().of(Yup.number()).optional(),
|
applicableUsers: Yup.array().of(Yup.number()).optional(),
|
||||||
|
skuIds: Yup.array().of(Yup.number()).optional(),
|
||||||
}).test('discount-validation', 'Must provide exactly one discount type with valid value', function(value) {
|
}).test('discount-validation', 'Must provide exactly one discount type with valid value', function(value) {
|
||||||
const { discountPercent, flatDiscount } = value;
|
const { discountPercent, flatDiscount } = value;
|
||||||
const hasPercent = discountPercent !== undefined && discountPercent > 0;
|
const hasPercent = discountPercent !== undefined && discountPercent > 0;
|
||||||
|
|
@ -130,9 +132,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
||||||
maxValue: undefined,
|
maxValue: undefined,
|
||||||
validTill: undefined,
|
validTill: undefined,
|
||||||
maxLimitForUser: undefined,
|
maxLimitForUser: undefined,
|
||||||
skuIds: undefined,
|
skuIds: [],
|
||||||
applicableUsers: [],
|
applicableUsers: [],
|
||||||
applicableProducts: [],
|
|
||||||
exclusiveApply: false,
|
exclusiveApply: false,
|
||||||
isFirstOrderOnly: false,
|
isFirstOrderOnly: false,
|
||||||
isReservedCoupon: false,
|
isReservedCoupon: false,
|
||||||
|
|
@ -483,6 +484,29 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
||||||
</View>
|
</View>
|
||||||
</BottomDialog>
|
</BottomDialog>
|
||||||
|
|
||||||
|
{/* Applicable Products — the coupon's target SKUs. Empty means the
|
||||||
|
whole cart; shown for reserved coupons too (the secret code's
|
||||||
|
targets are copied onto the coupon the customer redeems). */}
|
||||||
|
<View style={tw`mb-4`}>
|
||||||
|
<Text style={tw`text-base font-bold mb-2`}>Applicable Products (Optional)</Text>
|
||||||
|
<ProductsSelector
|
||||||
|
testID="coupon-products-selector"
|
||||||
|
label="Select Products"
|
||||||
|
placeholder="All products (whole cart)"
|
||||||
|
multiple
|
||||||
|
showGroups={false}
|
||||||
|
value={values.skuIds ?? []}
|
||||||
|
onChange={(selected) =>
|
||||||
|
setFieldValue('skuIds', Array.isArray(selected) ? selected : [])
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Text style={tw`text-xs text-gray-500 mt-2`}>
|
||||||
|
{values.skuIds && values.skuIds.length > 0
|
||||||
|
? `${values.skuIds.length} product(s) selected - the coupon discounts only these items.`
|
||||||
|
: 'No products selected - the coupon applies to the whole cart.'}
|
||||||
|
</Text>
|
||||||
|
</View>
|
||||||
|
|
||||||
{/* Add Multiple Coupons Dialog */}
|
{/* Add Multiple Coupons Dialog */}
|
||||||
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
|
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
|
||||||
<View style={tw`p-4`}>
|
<View style={tw`p-4`}>
|
||||||
|
|
|
||||||
|
|
@ -30,7 +30,7 @@ const validInitialValues = {
|
||||||
targetUsers: [],
|
targetUsers: [],
|
||||||
discountPercent: 10,
|
discountPercent: 10,
|
||||||
applicableUsers: [],
|
applicableUsers: [],
|
||||||
applicableProducts: [],
|
skuIds: [],
|
||||||
exclusiveApply: false,
|
exclusiveApply: false,
|
||||||
isFirstOrderOnly: false,
|
isFirstOrderOnly: false,
|
||||||
isReservedCoupon: false,
|
isReservedCoupon: false,
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,6 @@ const coupon = {
|
||||||
createdBy: 1,
|
createdBy: 1,
|
||||||
targetUser: { id: 3, name: 'shafi', mobile: '9999999999' },
|
targetUser: { id: 3, name: 'shafi', mobile: '9999999999' },
|
||||||
applicableUsers: [],
|
applicableUsers: [],
|
||||||
applicableProducts: [],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const pressLastAlertButton = (label: string) => {
|
const pressLastAlertButton = (label: string) => {
|
||||||
|
|
|
||||||
|
|
@ -80,7 +80,6 @@ const activeCoupon = {
|
||||||
isInvalidated: false,
|
isInvalidated: false,
|
||||||
createdBy: 1,
|
createdBy: 1,
|
||||||
applicableUsers: [],
|
applicableUsers: [],
|
||||||
applicableProducts: [],
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const expiredCoupon = {
|
const expiredCoupon = {
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { Formik } from 'formik'
|
||||||
import * as Yup from 'yup'
|
import * as Yup from 'yup'
|
||||||
import { pInput as PInput, MyButton, AppContainer, Checkbox, BottomDialog, p as P, MyFlatList } from 'web-components'
|
import { pInput as PInput, MyButton, AppContainer, Checkbox, BottomDialog, p as P, MyFlatList } from 'web-components'
|
||||||
import DateTimeInput from './DateTimeInput'
|
import DateTimeInput from './DateTimeInput'
|
||||||
|
import ProductsSelector from './ProductsSelector'
|
||||||
import { trpc } from '@/lib/trpc-client'
|
import { trpc } from '@/lib/trpc-client'
|
||||||
|
|
||||||
// Local copy of common-ui/shared-types CreateCouponPayload (web cannot import
|
// Local copy of common-ui/shared-types CreateCouponPayload (web cannot import
|
||||||
|
|
@ -18,10 +19,9 @@ export interface CreateCouponPayload {
|
||||||
isApplyForAll: boolean
|
isApplyForAll: boolean
|
||||||
isUserBased: boolean
|
isUserBased: boolean
|
||||||
targetUsers?: number[]
|
targetUsers?: number[]
|
||||||
productIds?: number[]
|
/** Target SKUs — the single source of product targeting. Empty => whole cart. */
|
||||||
skuIds?: number[]
|
skuIds?: number[]
|
||||||
applicableUsers?: number[]
|
applicableUsers?: number[]
|
||||||
applicableProducts?: number[]
|
|
||||||
exclusiveApply?: boolean
|
exclusiveApply?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -145,9 +145,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
||||||
maxValue: undefined,
|
maxValue: undefined,
|
||||||
validTill: undefined,
|
validTill: undefined,
|
||||||
maxLimitForUser: undefined,
|
maxLimitForUser: undefined,
|
||||||
skuIds: undefined,
|
skuIds: [],
|
||||||
applicableUsers: [],
|
applicableUsers: [],
|
||||||
applicableProducts: [],
|
|
||||||
exclusiveApply: false,
|
exclusiveApply: false,
|
||||||
isReservedCoupon: false,
|
isReservedCoupon: false,
|
||||||
}
|
}
|
||||||
|
|
@ -507,6 +506,29 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
||||||
</div>
|
</div>
|
||||||
</BottomDialog>
|
</BottomDialog>
|
||||||
|
|
||||||
|
{/* Applicable Products — the coupon's target SKUs. Empty means the
|
||||||
|
whole cart; shown for reserved coupons too (the secret code's
|
||||||
|
targets are copied onto the coupon the customer redeems). */}
|
||||||
|
<div className="mb-4">
|
||||||
|
<P className="text-base font-bold mb-2 block">Applicable Products (Optional)</P>
|
||||||
|
<ProductsSelector
|
||||||
|
testID="coupon-products-selector"
|
||||||
|
label="Select Products"
|
||||||
|
placeholder="All products (whole cart)"
|
||||||
|
multiple
|
||||||
|
showGroups={false}
|
||||||
|
value={values.skuIds ?? []}
|
||||||
|
onChange={(selected) =>
|
||||||
|
setFieldValue('skuIds', Array.isArray(selected) ? selected : [])
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<P className="text-xs text-gray-500 mt-2 block">
|
||||||
|
{values.skuIds && values.skuIds.length > 0
|
||||||
|
? `${values.skuIds.length} product(s) selected - the coupon discounts only these items.`
|
||||||
|
: 'No products selected - the coupon applies to the whole cart.'}
|
||||||
|
</P>
|
||||||
|
</div>
|
||||||
|
|
||||||
{/* Add Multiple Coupons Dialog */}
|
{/* Add Multiple Coupons Dialog */}
|
||||||
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
|
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
|
||||||
<div className="p-4">
|
<div className="p-4">
|
||||||
|
|
|
||||||
|
|
@ -19,10 +19,9 @@ interface CreateCouponPayload {
|
||||||
isApplyForAll: boolean,
|
isApplyForAll: boolean,
|
||||||
isUserBased: boolean,
|
isUserBased: boolean,
|
||||||
targetUsers?: number[],
|
targetUsers?: number[],
|
||||||
productIds?: number[],
|
/** Target SKUs — single source of product targeting (empty => whole cart). */
|
||||||
skuIds?: number[],
|
skuIds?: number[],
|
||||||
applicableUsers?: number[],
|
applicableUsers?: number[],
|
||||||
applicableProducts?: number[],
|
|
||||||
exclusiveApply?: boolean
|
exclusiveApply?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -110,7 +109,7 @@ function EditCoupon() {
|
||||||
maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined,
|
maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined,
|
||||||
validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined,
|
validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined,
|
||||||
maxLimitForUser: coupon.maxLimitForUser || undefined,
|
maxLimitForUser: coupon.maxLimitForUser || undefined,
|
||||||
skuIds: coupon.skuIds,
|
skuIds: coupon.skuIds ?? [],
|
||||||
isReservedCoupon: false, // Normal coupons
|
isReservedCoupon: false, // Normal coupons
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -84,9 +84,9 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v
|
||||||
<MyText className="mb-1 flex items-center gap-1 text-sm text-gray-700">
|
<MyText className="mb-1 flex items-center gap-1 text-sm text-gray-700">
|
||||||
<Users size={14} color="#6b7280" /> Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
|
<Users size={14} color="#6b7280" /> Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
|
||||||
</MyText>
|
</MyText>
|
||||||
{item.applicableProducts && item.applicableProducts.length > 0 && (
|
{item.skuIds && item.skuIds.length > 0 && (
|
||||||
<MyText className="flex items-center gap-1 text-sm text-gray-700">
|
<MyText className="flex items-center gap-1 text-sm text-gray-700">
|
||||||
<Package size={14} color="#6b7280" /> Products: {item.applicableProducts.length} selected
|
<Package size={14} color="#6b7280" /> Products: {item.skuIds.length} selected
|
||||||
</MyText>
|
</MyText>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
|
||||||
|
|
@ -128,7 +128,6 @@ export type {
|
||||||
UserDeleteAccountResponse,
|
UserDeleteAccountResponse,
|
||||||
UserCouponUsage,
|
UserCouponUsage,
|
||||||
UserCouponApplicableUser,
|
UserCouponApplicableUser,
|
||||||
UserCouponApplicableProduct,
|
|
||||||
UserCoupon,
|
UserCoupon,
|
||||||
UserCouponWithRelations,
|
UserCouponWithRelations,
|
||||||
UserEligibleCouponsResponse,
|
UserEligibleCouponsResponse,
|
||||||
|
|
|
||||||
|
|
@ -40,7 +40,7 @@ export {
|
||||||
createCouponWithRelations,
|
createCouponWithRelations,
|
||||||
updateCouponWithRelations,
|
updateCouponWithRelations,
|
||||||
generateCancellationCoupon,
|
generateCancellationCoupon,
|
||||||
createReservedCouponWithProducts,
|
createReservedCoupon,
|
||||||
createCouponForUser,
|
createCouponForUser,
|
||||||
checkUsersExist,
|
checkUsersExist,
|
||||||
checkCouponExists,
|
checkCouponExists,
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import {
|
||||||
createCouponWithRelations,
|
createCouponWithRelations,
|
||||||
updateCouponWithRelations,
|
updateCouponWithRelations,
|
||||||
generateCancellationCoupon,
|
generateCancellationCoupon,
|
||||||
createReservedCouponWithProducts,
|
createReservedCoupon,
|
||||||
createCouponForUser,
|
createCouponForUser,
|
||||||
checkUsersExist,
|
checkUsersExist,
|
||||||
checkCouponExists,
|
checkCouponExists,
|
||||||
|
|
@ -29,9 +29,9 @@ const createCouponBodySchema = z.object({
|
||||||
flatDiscount: z.number().optional(),
|
flatDiscount: z.number().optional(),
|
||||||
minOrder: z.number().optional(),
|
minOrder: z.number().optional(),
|
||||||
targetUser: z.number().optional(),
|
targetUser: z.number().optional(),
|
||||||
|
// Target SKUs — the single source of product targeting. Empty/null => whole cart.
|
||||||
skuIds: z.array(z.number()).optional().nullable(),
|
skuIds: z.array(z.number()).optional().nullable(),
|
||||||
applicableUsers: z.array(z.number()).optional(),
|
applicableUsers: z.array(z.number()).optional(),
|
||||||
applicableProducts: z.array(z.number()).optional(),
|
|
||||||
maxValue: z.number().optional(),
|
maxValue: z.number().optional(),
|
||||||
isApplyForAll: z.boolean().optional(),
|
isApplyForAll: z.boolean().optional(),
|
||||||
validTill: z.string().optional(),
|
validTill: z.string().optional(),
|
||||||
|
|
@ -44,7 +44,7 @@ export const couponRouter = router({
|
||||||
create: protectedProcedure
|
create: protectedProcedure
|
||||||
.input(createCouponBodySchema)
|
.input(createCouponBodySchema)
|
||||||
.mutation(async ({ input, ctx }): Promise<Coupon[]> => {
|
.mutation(async ({ input, ctx }): Promise<Coupon[]> => {
|
||||||
const { couponCode, couponCodes, isUserBased, discountPercent, flatDiscount, minOrder, skuIds, applicableUsers, applicableProducts, maxValue, isApplyForAll, validTill, maxLimitForUser, exclusiveApply, isFirstOrderOnly } = input;
|
const { couponCode, couponCodes, isUserBased, discountPercent, flatDiscount, minOrder, skuIds, applicableUsers, maxValue, isApplyForAll, validTill, maxLimitForUser, exclusiveApply, isFirstOrderOnly } = input;
|
||||||
|
|
||||||
// Validation: ensure at least one discount type is provided
|
// Validation: ensure at least one discount type is provided
|
||||||
if ((!discountPercent && !flatDiscount) || (discountPercent && flatDiscount)) {
|
if ((!discountPercent && !flatDiscount) || (discountPercent && flatDiscount)) {
|
||||||
|
|
@ -113,7 +113,6 @@ export const couponRouter = router({
|
||||||
isInvalidated: false,
|
isInvalidated: false,
|
||||||
},
|
},
|
||||||
applicableUsers,
|
applicableUsers,
|
||||||
applicableProducts,
|
|
||||||
ctx.staffUser!.regionId
|
ctx.staffUser!.regionId
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
@ -154,7 +153,6 @@ export const couponRouter = router({
|
||||||
...result,
|
...result,
|
||||||
skuIds: (result.skuIds as number[]) || undefined,
|
skuIds: (result.skuIds as number[]) || undefined,
|
||||||
applicableUsers: result.applicableUsers.map((au: any) => au.user),
|
applicableUsers: result.applicableUsers.map((au: any) => au.user),
|
||||||
applicableProducts: result.applicableProducts.map((ap: any) => ap.product),
|
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
|
|
||||||
|
|
@ -205,8 +203,7 @@ export const couponRouter = router({
|
||||||
ctx.staffUser!.regionId,
|
ctx.staffUser!.regionId,
|
||||||
id,
|
id,
|
||||||
updateData,
|
updateData,
|
||||||
updates.applicableUsers,
|
updates.applicableUsers
|
||||||
updates.applicableProducts
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!coupon) {
|
if (!coupon) {
|
||||||
|
|
@ -303,7 +300,7 @@ export const couponRouter = router({
|
||||||
createReservedCoupon: protectedProcedure
|
createReservedCoupon: protectedProcedure
|
||||||
.input(createCouponBodySchema)
|
.input(createCouponBodySchema)
|
||||||
.mutation(async ({ input, ctx }): Promise<any> => {
|
.mutation(async ({ input, ctx }): Promise<any> => {
|
||||||
const { couponCode, couponCodes, isUserBased, discountPercent, flatDiscount, minOrder, skuIds, applicableProducts, maxValue, validTill, maxLimitForUser, exclusiveApply, isFirstOrderOnly } = input;
|
const { couponCode, couponCodes, isUserBased, discountPercent, flatDiscount, minOrder, skuIds, maxValue, validTill, maxLimitForUser, exclusiveApply, isFirstOrderOnly } = input;
|
||||||
|
|
||||||
// Validation: ensure at least one discount type is provided
|
// Validation: ensure at least one discount type is provided
|
||||||
if ((!discountPercent && !flatDiscount) || (discountPercent && flatDiscount)) {
|
if ((!discountPercent && !flatDiscount) || (discountPercent && flatDiscount)) {
|
||||||
|
|
@ -335,7 +332,7 @@ export const couponRouter = router({
|
||||||
throw new Error(`Secret code already exists: ${secretCode}`);
|
throw new Error(`Secret code already exists: ${secretCode}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const coupon = await createReservedCouponWithProducts(
|
const coupon = await createReservedCoupon(
|
||||||
{
|
{
|
||||||
secretCode,
|
secretCode,
|
||||||
couponCode: secretCode,
|
couponCode: secretCode,
|
||||||
|
|
@ -350,7 +347,6 @@ export const couponRouter = router({
|
||||||
isFirstOrderOnly: isFirstOrderOnly || false,
|
isFirstOrderOnly: isFirstOrderOnly || false,
|
||||||
createdBy: staffUserId,
|
createdBy: staffUserId,
|
||||||
},
|
},
|
||||||
applicableProducts,
|
|
||||||
ctx.staffUser!.regionId
|
ctx.staffUser!.regionId
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -22,7 +22,6 @@ const couponBodySchema = z.object({
|
||||||
minOrder: z.number().optional(),
|
minOrder: z.number().optional(),
|
||||||
skuIds: z.array(z.number()).optional().nullable(),
|
skuIds: z.array(z.number()).optional().nullable(),
|
||||||
applicableUsers: z.array(z.number()).optional(),
|
applicableUsers: z.array(z.number()).optional(),
|
||||||
applicableProducts: z.array(z.number()).optional(),
|
|
||||||
maxValue: z.number().optional(),
|
maxValue: z.number().optional(),
|
||||||
isApplyForAll: z.boolean().optional(),
|
isApplyForAll: z.boolean().optional(),
|
||||||
validTill: z.string().optional(),
|
validTill: z.string().optional(),
|
||||||
|
|
@ -102,8 +101,7 @@ export const superadminGlobalCouponsRouter = router({
|
||||||
isFirstOrderOnly: input.isFirstOrderOnly || false,
|
isFirstOrderOnly: input.isFirstOrderOnly || false,
|
||||||
isInvalidated: false,
|
isInvalidated: false,
|
||||||
},
|
},
|
||||||
input.applicableUsers,
|
input.applicableUsers
|
||||||
input.applicableProducts
|
|
||||||
)
|
)
|
||||||
createdCoupons.push(coupon)
|
createdCoupons.push(coupon)
|
||||||
}
|
}
|
||||||
|
|
@ -153,8 +151,7 @@ export const superadminGlobalCouponsRouter = router({
|
||||||
const coupon = await updateGlobalCoupon(
|
const coupon = await updateGlobalCoupon(
|
||||||
id,
|
id,
|
||||||
updateData,
|
updateData,
|
||||||
updates.applicableUsers,
|
updates.applicableUsers
|
||||||
updates.applicableProducts
|
|
||||||
)
|
)
|
||||||
if (!coupon) throw new ApiError('Global coupon not found', 404)
|
if (!coupon) throw new ApiError('Global coupon not found', 404)
|
||||||
return { coupon, message: 'Global coupon updated successfully' }
|
return { coupon, message: 'Global coupon updated successfully' }
|
||||||
|
|
|
||||||
|
|
@ -304,10 +304,8 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
||||||
const isFirstOrder = couponsRaw.isFirstOrder ?? true;
|
const isFirstOrder = couponsRaw.isFirstOrder ?? true;
|
||||||
|
|
||||||
const mapped = couponsRaw.data.map((coupon) => {
|
const mapped = couponsRaw.data.map((coupon) => {
|
||||||
const applicableSkuIds = [
|
// Target SKUs live on the coupon row itself (empty => whole cart).
|
||||||
...(coupon.applicableProducts || []).map((p: any) => p.skuId),
|
const applicableSkuIds = Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [];
|
||||||
...(Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []),
|
|
||||||
];
|
|
||||||
|
|
||||||
let reason: string | undefined;
|
let reason: string | undefined;
|
||||||
if (coupon.regionId != null && regionId != null && coupon.regionId !== regionId) {
|
if (coupon.regionId != null && regionId != null && coupon.regionId !== regionId) {
|
||||||
|
|
|
||||||
|
|
@ -194,10 +194,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
||||||
exclusiveApply: coupon.exclusiveApply,
|
exclusiveApply: coupon.exclusiveApply,
|
||||||
discountPercent: coupon.discountPercent,
|
discountPercent: coupon.discountPercent,
|
||||||
flatDiscount: coupon.flatDiscount,
|
flatDiscount: coupon.flatDiscount,
|
||||||
applicableSkuIds: [
|
applicableSkuIds: Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [],
|
||||||
...(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,
|
||||||
};
|
};
|
||||||
|
|
|
||||||
108
change-log.txt
108
change-log.txt
|
|
@ -5121,3 +5121,111 @@ user-ui
|
||||||
- The sheet opened from the top region bar (AddressSwitcherSheet) keeps the default true, so it
|
- The sheet opened from the top region bar (AddressSwitcherSheet) keeps the default true, so it
|
||||||
still marks the address the app is actually using (and agrees with the bar).
|
still marks the address the app is actually using (and agrees with the bar).
|
||||||
No store/API changes. No test asserts the highlight (checked tests/).
|
No store/API changes. No test asserts the highlight (checked tests/).
|
||||||
|
|
||||||
|
2026-10-16 22:05:41 coupons: ONE target store - `skuIds` JSON array. `coupon_applicable_products` deleted.
|
||||||
|
|
||||||
|
Decision (user): "keep sku ids. no need to keep deprecated for backward compatibility, all users
|
||||||
|
will be handed new admin-ui apps" -> `applicableProducts` is removed outright from the API/service
|
||||||
|
surface, no alias, no relation table.
|
||||||
|
|
||||||
|
INTENDED DIFF (db_helper_sqlite/src/db/schema.ts)
|
||||||
|
- export const couponApplicableProducts = sqliteTable('coupon_applicable_products', {...}) DELETE
|
||||||
|
- productSkusRelations.applicableCoupons: many(couponApplicableProducts) DELETE
|
||||||
|
- couponsRelations.applicableProducts: many(couponApplicableProducts) DELETE
|
||||||
|
- couponApplicableProductsRelations DELETE
|
||||||
|
~ coupons.skuIds / reservedCoupons.skuIds: comment "canonical target SKUs; empty/null => whole cart"
|
||||||
|
(reserved_coupons.sku_ids already exists - line 599 - and was never written; that is the fix.)
|
||||||
|
|
||||||
|
NEW: drizzle/0007_coupon_targets_json.sql
|
||||||
|
- backfills coupons.sku_ids with the union of its current array and coupon_applicable_products
|
||||||
|
rows (per coupon, deduped), then DROP TABLE coupon_applicable_products (+ its unique index).
|
||||||
|
+ drizzle/meta/_journal.json entry idx 7, tag 0007_coupon_targets_json.
|
||||||
|
NOT RUN - the user applies migrations.
|
||||||
|
|
||||||
|
DEPLOY ORDER: new backend/admin-web first, migration second. Old read paths include the relation on
|
||||||
|
every coupon list/detail, so dropping the table under old code breaks coupon listing.
|
||||||
|
|
||||||
|
Full change list (see the following entries for each group).
|
||||||
|
|
||||||
|
2026-10-16 22:31:08 coupons: product targeting wired into creation, single `skuIds` JSON array end to end.
|
||||||
|
|
||||||
|
DB (packages/db_helper_sqlite/src/db/schema.ts)
|
||||||
|
- couponApplicableProducts table + couponApplicableProductsRelations
|
||||||
|
- productSkusRelations.applicableCoupons, couponsRelations.applicableProducts
|
||||||
|
~ comments on coupons.skuIds / reservedCoupons.skuIds (canonical targets, empty/null => whole cart)
|
||||||
|
NEW packages/db_helper_sqlite/drizzle/0007_coupon_targets_json.sql (+ _journal entry idx 7).
|
||||||
|
Verified against a throwaway in-memory sqlite3 (relation-only -> [10,11]; array+relation -> [5,6];
|
||||||
|
no relation rows -> NULL untouched; dup -> deduped; []+relation -> [9]; table dropped; FK check 0).
|
||||||
|
NOT APPLIED - the user applies migrations.
|
||||||
|
|
||||||
|
db_helper_sqlite
|
||||||
|
~ admin-apis/coupon.ts: new normalizeSkuIds(); createCouponWithRelations(input, users, regionId) and
|
||||||
|
updateCouponWithRelations(regionId, id, input, users?) validate + persist skuIds on the row;
|
||||||
|
createReservedCouponWithProducts -> createReservedCoupon(input, regionId) (writes
|
||||||
|
reserved_coupons.sku_ids - previously it wrote to the join table keyed by the RESERVED coupon id,
|
||||||
|
which was both FK-wrong and never read); getAllCoupons/getCouponById drop the relation include.
|
||||||
|
~ user-apis/coupon.ts: drop mapApplicableProduct + the applicableProducts field/includes.
|
||||||
|
~ user-apis/order.ts validateAndGetCoupons: applicableSkuIds = dedupe(coupon.skuIds ?? []).
|
||||||
|
~ superadmin-apis/global-coupons.ts: create/update drop the applicableProducts arg + include.
|
||||||
|
~ admin-apis/product.ts (delete product): removed the couponApplicableProducts cleanup. Deliberate:
|
||||||
|
coupon targets are a JSON array now, and stripping a deleted SKU out of it could EMPTY it, which
|
||||||
|
means "whole cart" - i.e. silently widening the coupon. A stale id is inert (a deleted SKU can
|
||||||
|
never appear in a cart) and keeps the coupon correctly scoped.
|
||||||
|
~ index.ts export rename.
|
||||||
|
backend
|
||||||
|
~ admin-apis/apis/coupon.ts: createCouponBodySchema drops applicableProducts; create/update/
|
||||||
|
createReservedCoupon use skuIds; getById returns the row's skuIds (the old map(ap => ap.product)
|
||||||
|
returned undefined entries - the bug reported earlier).
|
||||||
|
~ superadmin-apis/apis/global-coupons.ts: same field swap.
|
||||||
|
~ src/dbService.ts: drop the UserCouponApplicableProduct re-export. sqliteImporter: export rename.
|
||||||
|
shared/types
|
||||||
|
~ packages/ui/shared-types.ts CreateCouponPayload: drop productIds + applicableProducts.
|
||||||
|
~ packages/shared/types/user.ts: drop UserCouponApplicableProduct, drop applicableProducts from
|
||||||
|
UserCouponWithRelations, tighten UserCoupon.skuIds to number[] | null.
|
||||||
|
~ user-ui cart-page.tsx / checkout-page.tsx: applicableSkuIds = coupon.skuIds ?? [].
|
||||||
|
UI (creation)
|
||||||
|
~ admin-ui/src/components/CouponForm.tsx: "Applicable Products (Optional)" via
|
||||||
|
admin-ui/components/ProductsSelector (multiple, showGroups=false), bound to values.skuIds,
|
||||||
|
defaultValues skuIds: [], Yup array-of-number. ENABLED for reserved coupons (only Target
|
||||||
|
Audience stays disabled). Helper line says N selected vs whole cart.
|
||||||
|
~ admin-web/src/components/CouponForm.tsx: same via admin-web ProductsSelector; local payload type
|
||||||
|
drops productIds/applicableProducts; edit route hydrates skuIds: coupon.skuIds ?? [].
|
||||||
|
~ admin-ui coupons index + edit, admin-web coupons list + edit: "Products: N selected" now reads
|
||||||
|
skuIds; edit hydration defaults to [].
|
||||||
|
scripts/clear-db.sql + clear-db-old.sql: drop the coupon_applicable_products DROP line.
|
||||||
|
tests: admin-ui coupon fixtures applicableProducts: [] -> skuIds: [] (3 files).
|
||||||
|
docs: coupon-management.md (target model + CPM-10/11/12/18/20), reserved-coupons.md RES-08.
|
||||||
|
|
||||||
|
Deliberately NOT touched: packages/db_helper_postgres (dormant - its tsconfig is commented out of
|
||||||
|
the backend and it already fails its own tsc with dozens of pre-existing errors); apps/backend/
|
||||||
|
migrated.sql + dumps/*.sql (historical dumps).
|
||||||
|
|
||||||
|
Ordering constraint: deploy the new backend/admin-web BEFORE applying 0007 - the old read paths
|
||||||
|
include the relation on every coupon list/detail.
|
||||||
|
|
||||||
|
2026-10-16 22:44:52 CORRECTION to the 22:31:08 entry: the coupon-target work is folded into 0006.
|
||||||
|
|
||||||
|
User: "the 0006 isn't applied yet, move the 0007 code to it". 0006 was never applied anywhere yet, so
|
||||||
|
there is no reason to carry a second migration file.
|
||||||
|
|
||||||
|
packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
|
||||||
|
- deleted the `__new_coupon_applicable_products` CREATE + INSERT (the table is dropped later in the
|
||||||
|
same file, so rebuilding it first was pointless work)
|
||||||
|
- deleted its `DROP TABLE coupon_applicable_products;` from the drop-old-tables sequence, its
|
||||||
|
`ALTER TABLE __new_coupon_applicable_products RENAME TO ...`, and
|
||||||
|
`CREATE UNIQUE INDEX unique_coupon_sku` - the table is never created by this file now
|
||||||
|
+ new "Phase 4 (from 0007_coupon_targets_json)" at the end of the file: backfills coupons.sku_ids
|
||||||
|
with the union of the old array and the relation rows, then `DROP TABLE coupon_applicable_products`
|
||||||
|
~ header: notes the fold + Phase 4 in the phase list
|
||||||
|
DELETE drizzle/0007_coupon_targets_json.sql (a concurrent session had already renamed it to
|
||||||
|
drizzle/0007_coupons.sql; removed under that name)
|
||||||
|
REVERT drizzle/meta/_journal.json: idx 7 / tag 0007_coupon_targets_json removed (json re-validated).
|
||||||
|
NO code changes in this round - only the SQL/journal.
|
||||||
|
|
||||||
|
Verified end to end in a throwaway in-memory sqlite3: the whole chain 0000..0006 applies cleanly
|
||||||
|
(exit 0), with fixtures injected just before Phase 4 ->
|
||||||
|
REL_ONLY NULL + rows 10,11 -> [10,11]; ARRAY_PLUS_REL [5] + 6 -> [5,6];
|
||||||
|
UNTOUCHED NULL, no rows -> NULL (untouched); DUP [7,8] + 7 -> [7,8] (deduped);
|
||||||
|
EMPTY_ARRAY [] + 9 -> [9];
|
||||||
|
sqlite_master count of coupon_applicable_products = 0; reserved_coupons.sku_ids still present.
|
||||||
|
So the only migration to apply for all of this is 0006, as before.
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,8 @@
|
||||||
|
|
||||||
Scope: regional admin coupon CRUD/user targeting/product targeting, superadmin global coupon CRUD and form serialization. Regional coupons have region ID; global coupons have null region and are authored only by superadmin.
|
Scope: regional admin coupon CRUD/user targeting/product targeting, superadmin global coupon CRUD and form serialization. Regional coupons have region ID; global coupons have null region and are authored only by superadmin.
|
||||||
|
|
||||||
|
Product targeting model: a coupon's target SKUs live **only** in its own `sku_ids` JSON array on the coupon row (no join table, no relation). An empty/null array means the coupon applies to the whole cart. `reserved_coupons.sku_ids` is the same field for reserved codes and is copied onto the coupon a customer redeems. Targets are validated in-region on write (a global SKU may be attached anywhere).
|
||||||
|
|
||||||
| ID | Priority | Action / input | Expected result |
|
| ID | Priority | Action / input | Expected result |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| CPM-01 | P0 | Admin A creates general percentage coupon. | A-scoped coupon with exact code/limits/cap; A eligible path works. |
|
| CPM-01 | P0 | Admin A creates general percentage coupon. | A-scoped coupon with exact code/limits/cap; A eligible path works. |
|
||||||
|
|
@ -13,16 +15,16 @@ Scope: regional admin coupon CRUD/user targeting/product targeting, superadmin g
|
||||||
| CPM-07 | P1 | Empty/space/case-variant/duplicate code. | Approved normalization and uniqueness; no accidental empty code. |
|
| CPM-07 | P1 | Empty/space/case-variant/duplicate code. | Approved normalization and uniqueness; no accidental empty code. |
|
||||||
| CPM-08 | P0 | User-only coupon for U1 vs all-users flag. | Eligibility/applicability reflects exact intended scope. |
|
| CPM-08 | P0 | User-only coupon for U1 vs all-users flag. | Eligibility/applicability reflects exact intended scope. |
|
||||||
| CPM-09 | P1 | Missing/nonexistent/duplicate user IDs. | Validation/deduplication; no orphan applicable-user rows. |
|
| CPM-09 | P1 | Missing/nonexistent/duplicate user IDs. | Validation/deduplication; no orphan applicable-user rows. |
|
||||||
| CPM-10 | P0 | Target A SKU and global SKU; try B regional SKU in A coupon. | Valid targets allowed; foreign regional target denied. |
|
| CPM-10 | P0 | Target A SKU and global SKU; try B regional SKU in A coupon. | Valid targets persisted in A's `sku_ids`; foreign regional target denied. |
|
||||||
| CPM-11 | P1 | Empty targets vs relation targets vs legacy `skuIds`. | Defined canonical semantics; no drift that expands target scope unexpectedly. |
|
| CPM-11 | P1 | Empty targets vs populated targets (admin form, API, redeemed reserved code). | Empty => whole cart; populated => only those SKUs discounted. No other target store exists to drift from. |
|
||||||
| CPM-12 | P1 | Replace/remove all product/user targets on edit. | Old relations removed as intended; empty target means whole cart. |
|
| CPM-12 | P1 | Replace/remove all product targets on edit. | Array replaced/cleared as intended; cleared means whole cart. |
|
||||||
| CPM-13 | P1 | Null/zero maxValue/minOrder/max-user-limit. | Defined unlimited/zero behavior; omission differs from explicit clearing. |
|
| CPM-13 | P1 | Null/zero maxValue/minOrder/max-user-limit. | Defined unlimited/zero behavior; omission differs from explicit clearing. |
|
||||||
| CPM-14 | P1 | Expiry past/now/future, invalid date/timezone boundary. | Valid serialization and eligibility deadline. |
|
| CPM-14 | P1 | Expiry past/now/future, invalid date/timezone boundary. | Valid serialization and eligibility deadline. |
|
||||||
| CPM-15 | P0 | B admin reads/edits/invalidates A coupon ID. | Foreign access denied; coupon unchanged. |
|
| CPM-15 | P0 | B admin reads/edits/invalidates A coupon ID. | Foreign access denied; coupon unchanged. |
|
||||||
| CPM-16 | P1 | Invalidate used coupon then inspect old order. | New spend blocked; persisted historical discount unchanged. |
|
| CPM-16 | P1 | Invalidate used coupon then inspect old order. | New spend blocked; persisted historical discount unchanged. |
|
||||||
| CPM-17 | P1 | Multi-code batch has later duplicate/invalid code. | Agreed atomic batch behavior; any committed subset explicitly reported, not hidden partial failure. |
|
| CPM-17 | P1 | Multi-code batch has later duplicate/invalid code. | Agreed atomic batch behavior; any committed subset explicitly reported, not hidden partial failure. |
|
||||||
| CPM-18 | P1 | Concurrent duplicate creation/save failure mid-relations. | One coherent coupon; no duplicate/orphan target relations. |
|
| CPM-18 | P1 | Concurrent duplicate creation/save failure mid-relations. | One coherent coupon; no duplicate/orphan target rows. |
|
||||||
| CPM-19 | P1 | Global coupon creator has no staff-user row. | Supported author metadata persists without FK error; audit policy explicit. |
|
| CPM-19 | P1 | Global coupon creator has no staff-user row. | Supported author metadata persists without FK error; audit policy explicit. |
|
||||||
| CPM-20 | P2 | Product/user picker with same names, global badges and edit hydration. | Correct IDs retained; hidden target selection not lost on unrelated save. |
|
| CPM-20 | P2 | Product picker with same names, global badges and edit hydration. | Correct SKU IDs retained in `sku_ids`; selection shown on the coupon card and reconstructed on edit. |
|
||||||
|
|
||||||
Policy checkpoint: global coupons targeting regional-only products and audit attribution for superadmin creation. Do not assume an unimplemented global-coupon UI exists: API cases remain applicable.
|
Policy checkpoint: global coupons targeting regional-only products and audit attribution for superadmin creation. Do not assume an unimplemented global-coupon UI exists: API cases remain applicable.
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ Scope: reserved coupon creation/listing, redeemReservedCoupon, personal-coupon c
|
||||||
| RES-05 | P0 | Expired code or claimed coupon after same deadline. | Single `validTill` applies to claiming and spending. |
|
| RES-05 | P0 | Expired code or claimed coupon after same deadline. | Single `validTill` applies to claiming and spending. |
|
||||||
| RES-06 | P0 | First-order-only reserved code claimed/spent by existing customer. | Consistent effective-order eligibility; no loophole through redemption. |
|
| RES-06 | P0 | First-order-only reserved code claimed/spent by existing customer. | Consistent effective-order eligibility; no loophole through redemption. |
|
||||||
| RES-07 | P0 | A-regional code redeemed/spent while browsing B. | Region policy enforced on both claim and spend; no region-widened personal coupon. |
|
| RES-07 | P0 | A-regional code redeemed/spent while browsing B. | Region policy enforced on both claim and spend; no region-widened personal coupon. |
|
||||||
| RES-08 | P1 | SKU targets/exclusive/max-user-limit carried into personal coupon. | Exact inherited restrictions, not an unrestricted replacement. |
|
| RES-08 | P1 | SKU targets (`reserved_coupons.sku_ids`)/exclusive/max-user-limit carried into personal coupon. | Exact inherited restrictions, not an unrestricted replacement. |
|
||||||
| RES-09 | P1 | Redemption fails between personal insert and redeemed flag. | Atomic outcome; no burned code without coupon or double claim retry. |
|
| RES-09 | P1 | Redemption fails between personal insert and redeemed flag. | Atomic outcome; no burned code without coupon or double claim retry. |
|
||||||
| RES-10 | P1 | My Coupons/list immediately after claim and after restart. | Fresh personal coupon visible once with accurate state. |
|
| RES-10 | P1 | My Coupons/list immediately after claim and after restart. | Fresh personal coupon visible once with accurate state. |
|
||||||
| RES-11 | P0 | Anonymous redeem; U2 guessed personal coupon ID. | Authentication/ownership enforced. |
|
| RES-11 | P0 | Anonymous redeem; U2 guessed personal coupon ID. | Authentication/ownership enforced. |
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,11 @@
|
||||||
-- * 0008_user_creds_unique_and_min_order_cleanup -> user_creds unique index and
|
-- * 0008_user_creds_unique_and_min_order_cleanup -> user_creds unique index and
|
||||||
-- removal of the retired `minRegularOrderValue`
|
-- removal of the retired `minRegularOrderValue`
|
||||||
--
|
--
|
||||||
|
-- Also folds in 0007_coupon_targets_json (never applied on its own): coupon product
|
||||||
|
-- targeting collapses into `coupons.sku_ids` / `reserved_coupons.sku_ids` and the
|
||||||
|
-- `coupon_applicable_products` table is dropped (Phase 4). The file does not create
|
||||||
|
-- that table at all any more.
|
||||||
|
--
|
||||||
-- The originals created two throwaway staging tables purely to copy from and
|
-- The originals created two throwaway staging tables purely to copy from and
|
||||||
-- then drop them:
|
-- then drop them:
|
||||||
-- * `region_bound_settings` (created + seeded in 0006, dropped in 0009)
|
-- * `region_bound_settings` (created + seeded in 0006, dropped in 0009)
|
||||||
|
|
@ -21,6 +26,7 @@
|
||||||
-- 1. regions / region_bounds / superadmins + seeds (from 0006)
|
-- 1. regions / region_bounds / superadmins + seeds (from 0006)
|
||||||
-- 2. region_id backfill + 31-table rebuild (from 0007)
|
-- 2. region_id backfill + 31-table rebuild (from 0007)
|
||||||
-- 3. global_consts / region_consts / region_bound_consts (from 0008+0009)
|
-- 3. global_consts / region_consts / region_bound_consts (from 0008+0009)
|
||||||
|
-- 4. coupon product targets -> `sku_ids` JSON arrays (from 0007_coupon_targets_json)
|
||||||
--
|
--
|
||||||
-- Verified: applying this file to apps/backend/dumps/latest.sql yields the same
|
-- Verified: applying this file to apps/backend/dumps/latest.sql yields the same
|
||||||
-- schema and the same rows as applying 0006..0009 in order.
|
-- schema and the same rows as applying 0006..0009 in order.
|
||||||
|
|
@ -579,17 +585,6 @@ CREATE TABLE `__new_coupon_applicable_users` (
|
||||||
INSERT INTO `__new_coupon_applicable_users` (`id`,`coupon_id`,`user_id`)
|
INSERT INTO `__new_coupon_applicable_users` (`id`,`coupon_id`,`user_id`)
|
||||||
SELECT `id`,`coupon_id`,`user_id` FROM `coupon_applicable_users`;
|
SELECT `id`,`coupon_id`,`user_id` FROM `coupon_applicable_users`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
CREATE TABLE `__new_coupon_applicable_products` (
|
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
||||||
`coupon_id` integer NOT NULL,
|
|
||||||
`sku_id` integer NOT NULL,
|
|
||||||
FOREIGN KEY (`coupon_id`) REFERENCES `__new_coupons`(`id`) ON UPDATE no action ON DELETE no action,
|
|
||||||
FOREIGN KEY (`sku_id`) REFERENCES `__new_product_skus`(`id`) ON UPDATE no action ON DELETE no action
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
INSERT INTO `__new_coupon_applicable_products` (`id`,`coupon_id`,`sku_id`)
|
|
||||||
SELECT `id`,`coupon_id`,`sku_id` FROM `coupon_applicable_products`;
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE TABLE `__new_reserved_coupons` (
|
CREATE TABLE `__new_reserved_coupons` (
|
||||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||||
`secret_code` text NOT NULL,
|
`secret_code` text NOT NULL,
|
||||||
|
|
@ -676,8 +671,6 @@ DROP TABLE `cart_items`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DROP TABLE `reserved_coupons`;
|
DROP TABLE `reserved_coupons`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DROP TABLE `coupon_applicable_products`;
|
|
||||||
--> statement-breakpoint
|
|
||||||
DROP TABLE `coupon_applicable_users`;
|
DROP TABLE `coupon_applicable_users`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
DROP TABLE `coupon_usage`;
|
DROP TABLE `coupon_usage`;
|
||||||
|
|
@ -783,8 +776,6 @@ ALTER TABLE `__new_coupon_usage` RENAME TO `coupon_usage`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
ALTER TABLE `__new_coupon_applicable_users` RENAME TO `coupon_applicable_users`;
|
ALTER TABLE `__new_coupon_applicable_users` RENAME TO `coupon_applicable_users`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
ALTER TABLE `__new_coupon_applicable_products` RENAME TO `coupon_applicable_products`;
|
|
||||||
--> statement-breakpoint
|
|
||||||
ALTER TABLE `__new_reserved_coupons` RENAME TO `reserved_coupons`;
|
ALTER TABLE `__new_reserved_coupons` RENAME TO `reserved_coupons`;
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
ALTER TABLE `__new_cart_items` RENAME TO `cart_items`;
|
ALTER TABLE `__new_cart_items` RENAME TO `cart_items`;
|
||||||
|
|
@ -814,8 +805,6 @@ CREATE UNIQUE INDEX `payments_merchant_order_id_unique` ON `payments` (`merchant
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
CREATE UNIQUE INDEX `unique_coupon_user` ON `coupon_applicable_users` (`coupon_id`,`user_id`);
|
CREATE UNIQUE INDEX `unique_coupon_user` ON `coupon_applicable_users` (`coupon_id`,`user_id`);
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
CREATE UNIQUE INDEX `unique_coupon_sku` ON `coupon_applicable_products` (`coupon_id`,`sku_id`);
|
|
||||||
--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX `reserved_coupons_secret_code_unique` ON `reserved_coupons` (`secret_code`);
|
CREATE UNIQUE INDEX `reserved_coupons_secret_code_unique` ON `reserved_coupons` (`secret_code`);
|
||||||
--> statement-breakpoint
|
--> statement-breakpoint
|
||||||
CREATE UNIQUE INDEX `unique_user_sku` ON `cart_items` (`user_id`,`sku_id`);
|
CREATE UNIQUE INDEX `unique_user_sku` ON `cart_items` (`user_id`,`sku_id`);
|
||||||
|
|
@ -1004,3 +993,35 @@ ALTER TABLE `unlogged_user_tokens` ADD COLUMN `region_id` integer REFERENCES `re
|
||||||
-- Backfill one row per existing (user, region) pair from the addresses on file.
|
-- Backfill one row per existing (user, region) pair from the addresses on file.
|
||||||
INSERT OR IGNORE INTO `user_regions` (`user_id`, `region_id`, `from_address`, `from_location`)
|
INSERT OR IGNORE INTO `user_regions` (`user_id`, `region_id`, `from_address`, `from_location`)
|
||||||
SELECT DISTINCT `user_id`, `region_id`, 1, 0 FROM `addresses` WHERE `region_id` IS NOT NULL;
|
SELECT DISTINCT `user_id`, `region_id`, 1, 0 FROM `addresses` WHERE `region_id` IS NOT NULL;
|
||||||
|
--> statement-breakpoint
|
||||||
|
-- =====================================================================
|
||||||
|
-- Phase 4 (from 0007_coupon_targets_json): coupon product targets.
|
||||||
|
--
|
||||||
|
-- `coupon_applicable_products` is not rebuilt above and is dropped here: a
|
||||||
|
-- coupon's target SKUs live in its own `coupons.sku_ids` JSON array (and
|
||||||
|
-- `reserved_coupons.sku_ids` for a secret code, copied onto the coupon the
|
||||||
|
-- customer redeems). Empty array / NULL means "applies to the whole cart".
|
||||||
|
--
|
||||||
|
-- Any targets that only ever existed in the relation table are folded into the
|
||||||
|
-- arrays first. The table was never written from a UI (the admin forms had no
|
||||||
|
-- product picker), so on real data this backfill is a no-op.
|
||||||
|
-- =====================================================================
|
||||||
|
UPDATE `coupons`
|
||||||
|
SET `sku_ids` = (
|
||||||
|
SELECT json_group_array(`sku`)
|
||||||
|
FROM (
|
||||||
|
SELECT DISTINCT `sku` FROM (
|
||||||
|
SELECT CAST(je.`value` AS INTEGER) AS `sku`
|
||||||
|
FROM json_each(CASE WHEN json_valid(`coupons`.`sku_ids`) THEN `coupons`.`sku_ids` ELSE '[]' END) AS je
|
||||||
|
UNION
|
||||||
|
SELECT cap.`sku_id` AS `sku`
|
||||||
|
FROM `coupon_applicable_products` AS cap
|
||||||
|
WHERE cap.`coupon_id` = `coupons`.`id`
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
WHERE EXISTS (
|
||||||
|
SELECT 1 FROM `coupon_applicable_products` AS cap WHERE cap.`coupon_id` = `coupons`.`id`
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
DROP TABLE `coupon_applicable_products`;
|
||||||
|
|
|
||||||
|
|
@ -47,7 +47,7 @@ export {
|
||||||
createCouponWithRelations,
|
createCouponWithRelations,
|
||||||
updateCouponWithRelations,
|
updateCouponWithRelations,
|
||||||
generateCancellationCoupon,
|
generateCancellationCoupon,
|
||||||
createReservedCouponWithProducts,
|
createReservedCoupon,
|
||||||
createCouponForUser,
|
createCouponForUser,
|
||||||
checkUsersExist,
|
checkUsersExist,
|
||||||
checkCouponExists,
|
checkCouponExists,
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,15 @@
|
||||||
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, productSkus } from '../db/schema'
|
||||||
import { eq, and, like, or, inArray, lt, desc, asc, sql, isNull } from 'drizzle-orm'
|
import { eq, and, like, or, inArray, lt, desc, asc, sql, isNull } from 'drizzle-orm'
|
||||||
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
import type { Coupon, CouponFormInput, CouponValidationResult, UserMiniInfo } from '@packages/shared'
|
||||||
|
|
||||||
|
/** Deduped, numeric target SKUs. Empty/null input means "whole cart". */
|
||||||
|
const normalizeSkuIds = (value: unknown): number[] => {
|
||||||
|
if (!Array.isArray(value)) return []
|
||||||
|
const ids = value.map((item) => Number(item)).filter((item) => Number.isFinite(item))
|
||||||
|
return Array.from(new Set(ids))
|
||||||
|
}
|
||||||
|
|
||||||
const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regionId: number | null): 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
|
||||||
|
|
@ -57,13 +64,6 @@ export async function getAllCoupons(
|
||||||
user: true,
|
user: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
applicableProducts: {
|
|
||||||
with: {
|
|
||||||
sku: {
|
|
||||||
with: { product: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
orderBy: desc(coupons.createdAt),
|
orderBy: desc(coupons.createdAt),
|
||||||
limit: limit + 1,
|
limit: limit + 1,
|
||||||
|
|
@ -88,13 +88,6 @@ export async function getCouponById(regionId: number, id: number): Promise<any |
|
||||||
user: true,
|
user: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
applicableProducts: {
|
|
||||||
with: {
|
|
||||||
sku: {
|
|
||||||
with: { product: true },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -102,10 +95,10 @@ export async function getCouponById(regionId: number, id: number): Promise<any |
|
||||||
export async function createCouponWithRelations(
|
export async function createCouponWithRelations(
|
||||||
input: CouponFormInput,
|
input: CouponFormInput,
|
||||||
applicableUsers: number[] | undefined,
|
applicableUsers: number[] | undefined,
|
||||||
applicableProducts: number[] | undefined,
|
|
||||||
regionId: number | null
|
regionId: number | null
|
||||||
): Promise<Coupon> {
|
): Promise<Coupon> {
|
||||||
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
const skuIds = normalizeSkuIds(input.skuIds)
|
||||||
|
await assertApplicableSkusInRegion(db, skuIds, regionId)
|
||||||
|
|
||||||
return await db.transaction(async (tx) => {
|
return await db.transaction(async (tx) => {
|
||||||
const [coupon] = await tx.insert(coupons).values({
|
const [coupon] = await tx.insert(coupons).values({
|
||||||
|
|
@ -115,7 +108,7 @@ export async function createCouponWithRelations(
|
||||||
discountPercent: input.discountPercent,
|
discountPercent: input.discountPercent,
|
||||||
flatDiscount: input.flatDiscount,
|
flatDiscount: input.flatDiscount,
|
||||||
minOrder: input.minOrder,
|
minOrder: input.minOrder,
|
||||||
skuIds: input.skuIds,
|
skuIds: skuIds.length > 0 ? skuIds : null,
|
||||||
createdBy: input.createdBy,
|
createdBy: input.createdBy,
|
||||||
maxValue: input.maxValue,
|
maxValue: input.maxValue,
|
||||||
isApplyForAll: input.isApplyForAll,
|
isApplyForAll: input.isApplyForAll,
|
||||||
|
|
@ -134,15 +127,6 @@ export async function createCouponWithRelations(
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (applicableProducts && applicableProducts.length > 0) {
|
|
||||||
await tx.insert(couponApplicableProducts).values(
|
|
||||||
applicableProducts.map(skuId => ({
|
|
||||||
couponId: coupon.id,
|
|
||||||
skuId,
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return coupon as Coupon
|
return coupon as Coupon
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -151,8 +135,7 @@ export async function updateCouponWithRelations(
|
||||||
regionId: number | null,
|
regionId: number | null,
|
||||||
id: number,
|
id: number,
|
||||||
input: CouponFormInput,
|
input: CouponFormInput,
|
||||||
applicableUsers?: number[],
|
applicableUsers?: 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(
|
where: and(
|
||||||
|
|
@ -164,9 +147,8 @@ export async function updateCouponWithRelations(
|
||||||
if (!existing) {
|
if (!existing) {
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
if (applicableProducts !== undefined) {
|
const skuIds = normalizeSkuIds(input.skuIds)
|
||||||
await assertApplicableSkusInRegion(db, applicableProducts, regionId)
|
await assertApplicableSkusInRegion(db, skuIds, regionId)
|
||||||
}
|
|
||||||
|
|
||||||
return await db.transaction(async (tx) => {
|
return await db.transaction(async (tx) => {
|
||||||
// createdBy is always sent (complete payload) but never rewritten on update
|
// createdBy is always sent (complete payload) but never rewritten on update
|
||||||
|
|
@ -175,6 +157,7 @@ export async function updateCouponWithRelations(
|
||||||
const [coupon] = await tx.update(coupons)
|
const [coupon] = await tx.update(coupons)
|
||||||
.set({
|
.set({
|
||||||
...updateFields,
|
...updateFields,
|
||||||
|
skuIds: skuIds.length > 0 ? skuIds : null,
|
||||||
})
|
})
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
|
|
@ -196,18 +179,6 @@ export async function updateCouponWithRelations(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (applicableProducts !== undefined) {
|
|
||||||
await tx.delete(couponApplicableProducts).where(eq(couponApplicableProducts.couponId, id))
|
|
||||||
if (applicableProducts.length > 0) {
|
|
||||||
await tx.insert(couponApplicableProducts).values(
|
|
||||||
applicableProducts.map(skuId => ({
|
|
||||||
couponId: id,
|
|
||||||
skuId,
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return coupon as Coupon
|
return coupon as Coupon
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
@ -268,12 +239,12 @@ export async function getReservedCoupons(
|
||||||
return { coupons: couponsList, hasMore }
|
return { coupons: couponsList, hasMore }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createReservedCouponWithProducts(
|
export async function createReservedCoupon(
|
||||||
input: any,
|
input: any,
|
||||||
applicableProducts: number[] | undefined,
|
|
||||||
regionId: number
|
regionId: number
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
const skuIds = normalizeSkuIds(input.skuIds)
|
||||||
|
await assertApplicableSkusInRegion(db, skuIds, regionId)
|
||||||
|
|
||||||
return await db.transaction(async (tx) => {
|
return await db.transaction(async (tx) => {
|
||||||
const [coupon] = await tx.insert(reservedCoupons).values({
|
const [coupon] = await tx.insert(reservedCoupons).values({
|
||||||
|
|
@ -283,7 +254,7 @@ export async function createReservedCouponWithProducts(
|
||||||
discountPercent: input.discountPercent,
|
discountPercent: input.discountPercent,
|
||||||
flatDiscount: input.flatDiscount,
|
flatDiscount: input.flatDiscount,
|
||||||
minOrder: input.minOrder,
|
minOrder: input.minOrder,
|
||||||
skuIds: input.skuIds,
|
skuIds: skuIds.length > 0 ? skuIds : null,
|
||||||
maxValue: input.maxValue,
|
maxValue: input.maxValue,
|
||||||
validTill: input.validTill,
|
validTill: input.validTill,
|
||||||
maxLimitForUser: input.maxLimitForUser,
|
maxLimitForUser: input.maxLimitForUser,
|
||||||
|
|
@ -292,15 +263,6 @@ export async function createReservedCouponWithProducts(
|
||||||
createdBy: input.createdBy,
|
createdBy: input.createdBy,
|
||||||
}).returning()
|
}).returning()
|
||||||
|
|
||||||
if (applicableProducts && applicableProducts.length > 0) {
|
|
||||||
await tx.insert(couponApplicableProducts).values(
|
|
||||||
applicableProducts.map(skuId => ({
|
|
||||||
couponId: coupon.id,
|
|
||||||
skuId,
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return coupon
|
return coupon
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,6 @@ import {
|
||||||
vendorSnippets,
|
vendorSnippets,
|
||||||
homeBanners,
|
homeBanners,
|
||||||
keyValStore,
|
keyValStore,
|
||||||
couponApplicableProducts,
|
|
||||||
} from '../db/schema'
|
} from '../db/schema'
|
||||||
import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm'
|
import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm'
|
||||||
import { runBatched } from '../lib/run-batched'
|
import { runBatched } from '../lib/run-batched'
|
||||||
|
|
@ -377,7 +376,10 @@ async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
|
||||||
await db.batch([
|
await db.batch([
|
||||||
db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
|
db.delete(productMarketStats).where(inArray(productMarketStats.skuId, skuIds)),
|
||||||
db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
|
db.delete(cartItems).where(inArray(cartItems.skuId, skuIds)),
|
||||||
db.delete(couponApplicableProducts).where(inArray(couponApplicableProducts.skuId, skuIds)),
|
// Coupon product targets are a JSON array on the coupon row itself; a deleted
|
||||||
|
// SKU is deliberately left in it. It can never appear in a cart again, and
|
||||||
|
// stripping it could empty the array — which means "whole cart", silently
|
||||||
|
// widening the coupon. Left as-is, the coupon simply stops matching.
|
||||||
// product_tags / product_group_membership store SKU ids in their `product_id` column
|
// product_tags / product_group_membership store SKU ids in their `product_id` column
|
||||||
db.delete(productTags).where(inArray(productTags.productId, skuIds)),
|
db.delete(productTags).where(inArray(productTags.productId, skuIds)),
|
||||||
db.delete(productGroupMembership).where(inArray(productGroupMembership.productId, skuIds)),
|
db.delete(productGroupMembership).where(inArray(productGroupMembership.productId, skuIds)),
|
||||||
|
|
|
||||||
|
|
@ -541,6 +541,8 @@ export const coupons = sqliteTable('coupons', {
|
||||||
discountPercent: numericText('discount_percent'),
|
discountPercent: numericText('discount_percent'),
|
||||||
flatDiscount: numericText('flat_discount'),
|
flatDiscount: numericText('flat_discount'),
|
||||||
minOrder: numericText('min_order'),
|
minOrder: numericText('min_order'),
|
||||||
|
// The coupon's target SKUs — the ONLY target store (there is no join table).
|
||||||
|
// Empty array or null means "applies to the whole cart".
|
||||||
skuIds: jsonText<number[] | null>('sku_ids'),
|
skuIds: jsonText<number[] | null>('sku_ids'),
|
||||||
createdBy: integer('created_by').references(() => staffUsers.id),
|
createdBy: integer('created_by').references(() => staffUsers.id),
|
||||||
maxValue: numericText('max_value'),
|
maxValue: numericText('max_value'),
|
||||||
|
|
@ -570,14 +572,6 @@ export const couponApplicableUsers = sqliteTable('coupon_applicable_users', {
|
||||||
unq_coupon_user: uniqueIndex('unique_coupon_user').on(t.couponId, t.userId),
|
unq_coupon_user: uniqueIndex('unique_coupon_user').on(t.couponId, t.userId),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
export const couponApplicableProducts = sqliteTable('coupon_applicable_products', {
|
|
||||||
id: integer().primaryKey({ autoIncrement: true }),
|
|
||||||
couponId: integer('coupon_id').notNull().references(() => coupons.id),
|
|
||||||
skuId: integer('sku_id').notNull().references(() => productSkus.id),
|
|
||||||
}, (t) => ({
|
|
||||||
unq_coupon_sku: uniqueIndex('unique_coupon_sku').on(t.couponId, t.skuId),
|
|
||||||
}))
|
|
||||||
|
|
||||||
export const userIncidents = sqliteTable('user_incidents', {
|
export const userIncidents = sqliteTable('user_incidents', {
|
||||||
id: integer().primaryKey({ autoIncrement: true }),
|
id: integer().primaryKey({ autoIncrement: true }),
|
||||||
userId: integer('user_id').notNull().references(() => users.id),
|
userId: integer('user_id').notNull().references(() => users.id),
|
||||||
|
|
@ -596,6 +590,8 @@ export const reservedCoupons = sqliteTable('reserved_coupons', {
|
||||||
discountPercent: numericText('discount_percent'),
|
discountPercent: numericText('discount_percent'),
|
||||||
flatDiscount: numericText('flat_discount'),
|
flatDiscount: numericText('flat_discount'),
|
||||||
minOrder: numericText('min_order'),
|
minOrder: numericText('min_order'),
|
||||||
|
// Target SKUs inherited from the reserved coupon at redemption; same semantics
|
||||||
|
// as coupons.sku_ids (empty/null => whole cart).
|
||||||
skuIds: jsonText<number[] | null>('sku_ids'),
|
skuIds: jsonText<number[] | null>('sku_ids'),
|
||||||
maxValue: numericText('max_value'),
|
maxValue: numericText('max_value'),
|
||||||
validTill: timestampText('valid_till'),
|
validTill: timestampText('valid_till'),
|
||||||
|
|
@ -704,7 +700,6 @@ export const productSkusRelations = relations(productSkus, ({ one, many }) => ({
|
||||||
specialDeals: many(specialDeals),
|
specialDeals: many(specialDeals),
|
||||||
orderItems: many(orderItems),
|
orderItems: many(orderItems),
|
||||||
cartItems: many(cartItems),
|
cartItems: many(cartItems),
|
||||||
applicableCoupons: many(couponApplicableProducts),
|
|
||||||
comboItems: many(productCombos, { relationName: 'comboSku' }),
|
comboItems: many(productCombos, { relationName: 'comboSku' }),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
|
@ -802,7 +797,6 @@ export const couponsRelations = relations(coupons, ({ one, many }) => ({
|
||||||
creator: one(staffUsers, { fields: [coupons.createdBy], references: [staffUsers.id] }),
|
creator: one(staffUsers, { fields: [coupons.createdBy], references: [staffUsers.id] }),
|
||||||
usages: many(couponUsage),
|
usages: many(couponUsage),
|
||||||
applicableUsers: many(couponApplicableUsers),
|
applicableUsers: many(couponApplicableUsers),
|
||||||
applicableProducts: many(couponApplicableProducts),
|
|
||||||
}))
|
}))
|
||||||
|
|
||||||
export const couponUsageRelations = relations(couponUsage, ({ one }) => ({
|
export const couponUsageRelations = relations(couponUsage, ({ one }) => ({
|
||||||
|
|
@ -835,11 +829,6 @@ export const couponApplicableUsersRelations = relations(couponApplicableUsers, (
|
||||||
user: one(users, { fields: [couponApplicableUsers.userId], references: [users.id] }),
|
user: one(users, { fields: [couponApplicableUsers.userId], references: [users.id] }),
|
||||||
}))
|
}))
|
||||||
|
|
||||||
export const couponApplicableProductsRelations = relations(couponApplicableProducts, ({ one }) => ({
|
|
||||||
coupon: one(coupons, { fields: [couponApplicableProducts.couponId], references: [coupons.id] }),
|
|
||||||
sku: one(productSkus, { fields: [couponApplicableProducts.skuId], references: [productSkus.id] }),
|
|
||||||
}))
|
|
||||||
|
|
||||||
export const reservedCouponsRelations = relations(reservedCoupons, ({ one }) => ({
|
export const reservedCouponsRelations = relations(reservedCoupons, ({ one }) => ({
|
||||||
redeemedUser: one(users, { fields: [reservedCoupons.redeemedBy], references: [users.id] }),
|
redeemedUser: one(users, { fields: [reservedCoupons.redeemedBy], references: [users.id] }),
|
||||||
creator: one(staffUsers, { fields: [reservedCoupons.createdBy], references: [staffUsers.id] }),
|
creator: one(staffUsers, { fields: [reservedCoupons.createdBy], references: [staffUsers.id] }),
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,6 @@ import {
|
||||||
const globalCouponWith = {
|
const globalCouponWith = {
|
||||||
creator: true,
|
creator: true,
|
||||||
applicableUsers: { with: { user: true } },
|
applicableUsers: { with: { user: true } },
|
||||||
applicableProducts: { with: { sku: { with: { product: true } } } },
|
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
/** Global coupons (regionId NULL) — valid in every region. */
|
/** Global coupons (regionId NULL) — valid in every region. */
|
||||||
|
|
@ -33,19 +32,17 @@ export async function getGlobalCoupon(id: number) {
|
||||||
|
|
||||||
export async function createGlobalCoupon(
|
export async function createGlobalCoupon(
|
||||||
input: CouponFormInput,
|
input: CouponFormInput,
|
||||||
applicableUsers: number[] | undefined,
|
applicableUsers: number[] | undefined
|
||||||
applicableProducts: number[] | undefined
|
|
||||||
): Promise<Coupon> {
|
): Promise<Coupon> {
|
||||||
return createCouponWithRelations(input, applicableUsers, applicableProducts, null)
|
return createCouponWithRelations(input, applicableUsers, null)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateGlobalCoupon(
|
export async function updateGlobalCoupon(
|
||||||
id: number,
|
id: number,
|
||||||
input: CouponFormInput,
|
input: CouponFormInput,
|
||||||
applicableUsers?: number[],
|
applicableUsers?: number[]
|
||||||
applicableProducts?: number[]
|
|
||||||
): Promise<Coupon | null> {
|
): Promise<Coupon | null> {
|
||||||
return updateCouponWithRelations(null, id, input, applicableUsers, applicableProducts)
|
return updateCouponWithRelations(null, id, input, applicableUsers)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function invalidateGlobalCoupon(id: number): Promise<Coupon | null> {
|
export async function invalidateGlobalCoupon(id: number): Promise<Coupon | null> {
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,5 @@
|
||||||
import { db } from '../db/db_index'
|
import { db } from '../db/db_index'
|
||||||
import {
|
import {
|
||||||
couponApplicableProducts,
|
|
||||||
couponApplicableUsers,
|
couponApplicableUsers,
|
||||||
couponUsage,
|
couponUsage,
|
||||||
coupons,
|
coupons,
|
||||||
|
|
@ -8,12 +7,11 @@ import {
|
||||||
} from '../db/schema'
|
} from '../db/schema'
|
||||||
import { and, eq, gt, isNull, or } from 'drizzle-orm'
|
import { and, eq, gt, isNull, or } from 'drizzle-orm'
|
||||||
import type { InferSelectModel } from 'drizzle-orm'
|
import type { InferSelectModel } from 'drizzle-orm'
|
||||||
import type { UserCoupon, UserCouponApplicableProduct, UserCouponApplicableUser, UserCouponUsage, UserCouponWithRelations } from '@packages/shared'
|
import type { UserCoupon, UserCouponApplicableUser, UserCouponUsage, UserCouponWithRelations } from '@packages/shared'
|
||||||
|
|
||||||
type CouponRow = InferSelectModel<typeof coupons>
|
type CouponRow = InferSelectModel<typeof coupons>
|
||||||
type CouponUsageRow = InferSelectModel<typeof couponUsage>
|
type CouponUsageRow = InferSelectModel<typeof couponUsage>
|
||||||
type CouponApplicableUserRow = InferSelectModel<typeof couponApplicableUsers>
|
type CouponApplicableUserRow = InferSelectModel<typeof couponApplicableUsers>
|
||||||
type CouponApplicableProductRow = InferSelectModel<typeof couponApplicableProducts>
|
|
||||||
type ReservedCouponRow = InferSelectModel<typeof reservedCoupons>
|
type ReservedCouponRow = InferSelectModel<typeof reservedCoupons>
|
||||||
|
|
||||||
const mapCoupon = (coupon: CouponRow): UserCoupon => ({
|
const mapCoupon = (coupon: CouponRow): UserCoupon => ({
|
||||||
|
|
@ -50,21 +48,13 @@ const mapApplicableUser = (applicable: CouponApplicableUserRow): UserCouponAppli
|
||||||
userId: applicable.userId,
|
userId: applicable.userId,
|
||||||
})
|
})
|
||||||
|
|
||||||
const mapApplicableProduct = (applicable: CouponApplicableProductRow): UserCouponApplicableProduct => ({
|
|
||||||
id: applicable.id,
|
|
||||||
couponId: applicable.couponId,
|
|
||||||
skuId: applicable.skuId,
|
|
||||||
})
|
|
||||||
|
|
||||||
const mapCouponWithRelations = (coupon: CouponRow & {
|
const mapCouponWithRelations = (coupon: CouponRow & {
|
||||||
usages: CouponUsageRow[]
|
usages: CouponUsageRow[]
|
||||||
applicableUsers: CouponApplicableUserRow[]
|
applicableUsers: CouponApplicableUserRow[]
|
||||||
applicableProducts: CouponApplicableProductRow[]
|
|
||||||
}): UserCouponWithRelations => ({
|
}): UserCouponWithRelations => ({
|
||||||
...mapCoupon(coupon),
|
...mapCoupon(coupon),
|
||||||
usages: coupon.usages.map(mapUsage),
|
usages: coupon.usages.map(mapUsage),
|
||||||
applicableUsers: coupon.applicableUsers.map(mapApplicableUser),
|
applicableUsers: coupon.applicableUsers.map(mapApplicableUser),
|
||||||
applicableProducts: coupon.applicableProducts.map(mapApplicableProduct),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
export async function getActiveCouponsWithRelations(
|
export async function getActiveCouponsWithRelations(
|
||||||
|
|
@ -90,7 +80,6 @@ export async function getActiveCouponsWithRelations(
|
||||||
where: eq(couponUsage.userId, userId),
|
where: eq(couponUsage.userId, userId),
|
||||||
},
|
},
|
||||||
applicableUsers: true,
|
applicableUsers: true,
|
||||||
applicableProducts: true,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -113,7 +102,6 @@ export async function getAllCouponsWithRelations(
|
||||||
where: eq(couponUsage.userId, userId),
|
where: eq(couponUsage.userId, userId),
|
||||||
},
|
},
|
||||||
applicableUsers: true,
|
applicableUsers: true,
|
||||||
applicableProducts: true,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -139,7 +139,6 @@ export async function validateAndGetCoupons(params: {
|
||||||
with: {
|
with: {
|
||||||
usages: { where: eq(couponUsage.userId, params.userId) },
|
usages: { where: eq(couponUsage.userId, params.userId) },
|
||||||
applicableUsers: true,
|
applicableUsers: true,
|
||||||
applicableProducts: true,
|
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
@ -185,9 +184,15 @@ export async function validateAndGetCoupons(params: {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
const relatedSkuIds = (coupon.applicableProducts ?? []).map((p) => p.skuId)
|
// Target SKUs live in the coupon's own `sku_ids` array (there is no join
|
||||||
const jsonSkuIds = Array.isArray(coupon.skuIds) ? coupon.skuIds : []
|
// table). Empty/null => the coupon applies to the whole cart.
|
||||||
const applicableSkuIds = [...new Set([...relatedSkuIds, ...jsonSkuIds])]
|
const applicableSkuIds = [
|
||||||
|
...new Set(
|
||||||
|
(Array.isArray(coupon.skuIds) ? coupon.skuIds : [])
|
||||||
|
.map((skuId) => Number(skuId))
|
||||||
|
.filter((skuId) => Number.isFinite(skuId))
|
||||||
|
),
|
||||||
|
]
|
||||||
const targets = applicableSkuIds.length > 0 ? applicableSkuIds : null
|
const targets = applicableSkuIds.length > 0 ? applicableSkuIds : null
|
||||||
const eligibleSubtotal = computeEligibleSubtotal(params.items, {
|
const eligibleSubtotal = computeEligibleSubtotal(params.items, {
|
||||||
applicableSkuIds: targets,
|
applicableSkuIds: targets,
|
||||||
|
|
|
||||||
|
|
@ -414,12 +414,6 @@ export interface UserCouponApplicableUser {
|
||||||
userId: number;
|
userId: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserCouponApplicableProduct {
|
|
||||||
id: number;
|
|
||||||
couponId: number;
|
|
||||||
skuId: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface UserCoupon {
|
export interface UserCoupon {
|
||||||
id: number;
|
id: number;
|
||||||
couponCode: string;
|
couponCode: string;
|
||||||
|
|
@ -428,7 +422,8 @@ export interface UserCoupon {
|
||||||
discountPercent: string | null;
|
discountPercent: string | null;
|
||||||
flatDiscount: string | null;
|
flatDiscount: string | null;
|
||||||
minOrder: string | null;
|
minOrder: string | null;
|
||||||
skuIds: unknown;
|
/** Target SKUs (single source). Empty/null => applies to the whole cart. */
|
||||||
|
skuIds: number[] | null;
|
||||||
maxValue: string | null;
|
maxValue: string | null;
|
||||||
isApplyForAll: boolean;
|
isApplyForAll: boolean;
|
||||||
validTill: Date | null;
|
validTill: Date | null;
|
||||||
|
|
@ -442,7 +437,6 @@ export interface UserCoupon {
|
||||||
export interface UserCouponWithRelations extends UserCoupon {
|
export interface UserCouponWithRelations extends UserCoupon {
|
||||||
usages: UserCouponUsage[];
|
usages: UserCouponUsage[];
|
||||||
applicableUsers: UserCouponApplicableUser[];
|
applicableUsers: UserCouponApplicableUser[];
|
||||||
applicableProducts: UserCouponApplicableProduct[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UserEligibleCouponsResponse {
|
export interface UserEligibleCouponsResponse {
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,9 @@ export interface CreateCouponPayload {
|
||||||
isApplyForAll: boolean;
|
isApplyForAll: boolean;
|
||||||
isUserBased: boolean;
|
isUserBased: boolean;
|
||||||
targetUsers?: number[];
|
targetUsers?: number[];
|
||||||
productIds?: number[];
|
/** Target SKUs — the single source of product targeting. Empty => whole cart. */
|
||||||
skuIds?: number[];
|
skuIds?: number[];
|
||||||
applicableUsers?: number[];
|
applicableUsers?: number[];
|
||||||
applicableProducts?: number[];
|
|
||||||
exclusiveApply?: boolean;
|
exclusiveApply?: boolean;
|
||||||
isFirstOrderOnly?: boolean;
|
isFirstOrderOnly?: boolean;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,6 @@ PRAGMA foreign_keys = OFF;
|
||||||
DROP TABLE IF EXISTS order_items;
|
DROP TABLE IF EXISTS order_items;
|
||||||
DROP TABLE IF EXISTS cart_items;
|
DROP TABLE IF EXISTS cart_items;
|
||||||
DROP TABLE IF EXISTS special_deals;
|
DROP TABLE IF EXISTS special_deals;
|
||||||
DROP TABLE IF EXISTS coupon_applicable_products;
|
|
||||||
DROP TABLE IF EXISTS product_reviews;
|
DROP TABLE IF EXISTS product_reviews;
|
||||||
DROP TABLE IF EXISTS product_tags;
|
DROP TABLE IF EXISTS product_tags;
|
||||||
DROP TABLE IF EXISTS product_group_membership;
|
DROP TABLE IF EXISTS product_group_membership;
|
||||||
|
|
|
||||||
|
|
@ -23,7 +23,6 @@ DROP TABLE IF EXISTS product_combos;
|
||||||
DROP TABLE IF EXISTS order_items;
|
DROP TABLE IF EXISTS order_items;
|
||||||
DROP TABLE IF EXISTS cart_items;
|
DROP TABLE IF EXISTS cart_items;
|
||||||
DROP TABLE IF EXISTS special_deals;
|
DROP TABLE IF EXISTS special_deals;
|
||||||
DROP TABLE IF EXISTS coupon_applicable_products;
|
|
||||||
DROP TABLE IF EXISTS product_reviews;
|
DROP TABLE IF EXISTS product_reviews;
|
||||||
|
|
||||||
-- ---- product/sku hierarchy ----
|
-- ---- product/sku hierarchy ----
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue