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,
|
||||
maxLimitForUser: coupon.maxLimitForUser || undefined,
|
||||
isFirstOrderOnly: coupon.isFirstOrderOnly,
|
||||
skuIds: coupon.skuIds,
|
||||
skuIds: coupon.skuIds ?? [],
|
||||
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`}>
|
||||
<MaterialCommunityIcons name="account-group" size={14} color="#6b7280" /> Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
|
||||
</MyText>
|
||||
{item.applicableProducts && item.applicableProducts.length > 0 && (
|
||||
{item.skuIds && item.skuIds.length > 0 && (
|
||||
<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>
|
||||
)}
|
||||
</View>
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { Formik } from 'formik';
|
|||
import * as Yup from 'yup';
|
||||
import { MyTextInput, MyButton, tw, AppContainer , DateTimePickerMod, Checkbox, BottomDialog, MyText } from 'common-ui';
|
||||
import { trpc } from '../trpc-client';
|
||||
import ProductsSelector from '@/components/ProductsSelector';
|
||||
|
||||
import { CreateCouponPayload } from 'common-ui/shared-types';
|
||||
|
||||
|
|
@ -46,6 +47,7 @@ const couponValidationSchema = Yup.object().shape({
|
|||
isUserBased: Yup.boolean(),
|
||||
isApplyForAll: Yup.boolean(),
|
||||
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) {
|
||||
const { discountPercent, flatDiscount } = value;
|
||||
const hasPercent = discountPercent !== undefined && discountPercent > 0;
|
||||
|
|
@ -130,9 +132,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
maxValue: undefined,
|
||||
validTill: undefined,
|
||||
maxLimitForUser: undefined,
|
||||
skuIds: undefined,
|
||||
skuIds: [],
|
||||
applicableUsers: [],
|
||||
applicableProducts: [],
|
||||
exclusiveApply: false,
|
||||
isFirstOrderOnly: false,
|
||||
isReservedCoupon: false,
|
||||
|
|
@ -483,6 +484,29 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
</View>
|
||||
</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 */}
|
||||
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
|
||||
<View style={tw`p-4`}>
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ const validInitialValues = {
|
|||
targetUsers: [],
|
||||
discountPercent: 10,
|
||||
applicableUsers: [],
|
||||
applicableProducts: [],
|
||||
skuIds: [],
|
||||
exclusiveApply: false,
|
||||
isFirstOrderOnly: false,
|
||||
isReservedCoupon: false,
|
||||
|
|
|
|||
|
|
@ -38,7 +38,6 @@ const coupon = {
|
|||
createdBy: 1,
|
||||
targetUser: { id: 3, name: 'shafi', mobile: '9999999999' },
|
||||
applicableUsers: [],
|
||||
applicableProducts: [],
|
||||
}
|
||||
|
||||
const pressLastAlertButton = (label: string) => {
|
||||
|
|
|
|||
|
|
@ -80,7 +80,6 @@ const activeCoupon = {
|
|||
isInvalidated: false,
|
||||
createdBy: 1,
|
||||
applicableUsers: [],
|
||||
applicableProducts: [],
|
||||
}
|
||||
|
||||
const expiredCoupon = {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { Formik } from 'formik'
|
|||
import * as Yup from 'yup'
|
||||
import { pInput as PInput, MyButton, AppContainer, Checkbox, BottomDialog, p as P, MyFlatList } from 'web-components'
|
||||
import DateTimeInput from './DateTimeInput'
|
||||
import ProductsSelector from './ProductsSelector'
|
||||
import { trpc } from '@/lib/trpc-client'
|
||||
|
||||
// Local copy of common-ui/shared-types CreateCouponPayload (web cannot import
|
||||
|
|
@ -18,10 +19,9 @@ export interface CreateCouponPayload {
|
|||
isApplyForAll: boolean
|
||||
isUserBased: boolean
|
||||
targetUsers?: number[]
|
||||
productIds?: number[]
|
||||
/** Target SKUs — the single source of product targeting. Empty => whole cart. */
|
||||
skuIds?: number[]
|
||||
applicableUsers?: number[]
|
||||
applicableProducts?: number[]
|
||||
exclusiveApply?: boolean
|
||||
}
|
||||
|
||||
|
|
@ -145,9 +145,8 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
maxValue: undefined,
|
||||
validTill: undefined,
|
||||
maxLimitForUser: undefined,
|
||||
skuIds: undefined,
|
||||
skuIds: [],
|
||||
applicableUsers: [],
|
||||
applicableProducts: [],
|
||||
exclusiveApply: false,
|
||||
isReservedCoupon: false,
|
||||
}
|
||||
|
|
@ -507,6 +506,29 @@ export default function CouponForm({ onSubmit, isLoading, initialValues }: Coupo
|
|||
</div>
|
||||
</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 */}
|
||||
<BottomDialog open={multiDialogOpen} onClose={() => setMultiDialogOpen(false)}>
|
||||
<div className="p-4">
|
||||
|
|
|
|||
|
|
@ -19,10 +19,9 @@ interface CreateCouponPayload {
|
|||
isApplyForAll: boolean,
|
||||
isUserBased: boolean,
|
||||
targetUsers?: number[],
|
||||
productIds?: number[],
|
||||
/** Target SKUs — single source of product targeting (empty => whole cart). */
|
||||
skuIds?: number[],
|
||||
applicableUsers?: number[],
|
||||
applicableProducts?: number[],
|
||||
exclusiveApply?: boolean
|
||||
}
|
||||
|
||||
|
|
@ -110,7 +109,7 @@ function EditCoupon() {
|
|||
maxValue: coupon.maxValue ? parseFloat(coupon.maxValue) : undefined,
|
||||
validTill: coupon.validTill ? dayjs(coupon.validTill).format('YYYY-MM-DD') : undefined,
|
||||
maxLimitForUser: coupon.maxLimitForUser || undefined,
|
||||
skuIds: coupon.skuIds,
|
||||
skuIds: coupon.skuIds ?? [],
|
||||
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">
|
||||
<Users size={14} color="#6b7280" /> Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
|
||||
</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">
|
||||
<Package size={14} color="#6b7280" /> Products: {item.applicableProducts.length} selected
|
||||
<Package size={14} color="#6b7280" /> Products: {item.skuIds.length} selected
|
||||
</MyText>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -128,7 +128,6 @@ export type {
|
|||
UserDeleteAccountResponse,
|
||||
UserCouponUsage,
|
||||
UserCouponApplicableUser,
|
||||
UserCouponApplicableProduct,
|
||||
UserCoupon,
|
||||
UserCouponWithRelations,
|
||||
UserEligibleCouponsResponse,
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ export {
|
|||
createCouponWithRelations,
|
||||
updateCouponWithRelations,
|
||||
generateCancellationCoupon,
|
||||
createReservedCouponWithProducts,
|
||||
createReservedCoupon,
|
||||
createCouponForUser,
|
||||
checkUsersExist,
|
||||
checkCouponExists,
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import {
|
|||
createCouponWithRelations,
|
||||
updateCouponWithRelations,
|
||||
generateCancellationCoupon,
|
||||
createReservedCouponWithProducts,
|
||||
createReservedCoupon,
|
||||
createCouponForUser,
|
||||
checkUsersExist,
|
||||
checkCouponExists,
|
||||
|
|
@ -29,9 +29,9 @@ const createCouponBodySchema = z.object({
|
|||
flatDiscount: z.number().optional(),
|
||||
minOrder: 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(),
|
||||
applicableUsers: z.array(z.number()).optional(),
|
||||
applicableProducts: z.array(z.number()).optional(),
|
||||
maxValue: z.number().optional(),
|
||||
isApplyForAll: z.boolean().optional(),
|
||||
validTill: z.string().optional(),
|
||||
|
|
@ -44,7 +44,7 @@ export const couponRouter = router({
|
|||
create: protectedProcedure
|
||||
.input(createCouponBodySchema)
|
||||
.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
|
||||
if ((!discountPercent && !flatDiscount) || (discountPercent && flatDiscount)) {
|
||||
|
|
@ -113,7 +113,6 @@ export const couponRouter = router({
|
|||
isInvalidated: false,
|
||||
},
|
||||
applicableUsers,
|
||||
applicableProducts,
|
||||
ctx.staffUser!.regionId
|
||||
);
|
||||
|
||||
|
|
@ -154,7 +153,6 @@ export const couponRouter = router({
|
|||
...result,
|
||||
skuIds: (result.skuIds as number[]) || undefined,
|
||||
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,
|
||||
id,
|
||||
updateData,
|
||||
updates.applicableUsers,
|
||||
updates.applicableProducts
|
||||
updates.applicableUsers
|
||||
);
|
||||
|
||||
if (!coupon) {
|
||||
|
|
@ -303,7 +300,7 @@ export const couponRouter = router({
|
|||
createReservedCoupon: protectedProcedure
|
||||
.input(createCouponBodySchema)
|
||||
.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
|
||||
if ((!discountPercent && !flatDiscount) || (discountPercent && flatDiscount)) {
|
||||
|
|
@ -335,7 +332,7 @@ export const couponRouter = router({
|
|||
throw new Error(`Secret code already exists: ${secretCode}`);
|
||||
}
|
||||
|
||||
const coupon = await createReservedCouponWithProducts(
|
||||
const coupon = await createReservedCoupon(
|
||||
{
|
||||
secretCode,
|
||||
couponCode: secretCode,
|
||||
|
|
@ -350,7 +347,6 @@ export const couponRouter = router({
|
|||
isFirstOrderOnly: isFirstOrderOnly || false,
|
||||
createdBy: staffUserId,
|
||||
},
|
||||
applicableProducts,
|
||||
ctx.staffUser!.regionId
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ const couponBodySchema = z.object({
|
|||
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(),
|
||||
|
|
@ -102,8 +101,7 @@ export const superadminGlobalCouponsRouter = router({
|
|||
isFirstOrderOnly: input.isFirstOrderOnly || false,
|
||||
isInvalidated: false,
|
||||
},
|
||||
input.applicableUsers,
|
||||
input.applicableProducts
|
||||
input.applicableUsers
|
||||
)
|
||||
createdCoupons.push(coupon)
|
||||
}
|
||||
|
|
@ -153,8 +151,7 @@ export const superadminGlobalCouponsRouter = router({
|
|||
const coupon = await updateGlobalCoupon(
|
||||
id,
|
||||
updateData,
|
||||
updates.applicableUsers,
|
||||
updates.applicableProducts
|
||||
updates.applicableUsers
|
||||
)
|
||||
if (!coupon) throw new ApiError('Global coupon not found', 404)
|
||||
return { coupon, message: 'Global coupon updated successfully' }
|
||||
|
|
|
|||
|
|
@ -304,10 +304,8 @@ export default function CartPage({ isFlashDelivery = false }: FlashDeliveryProps
|
|||
const isFirstOrder = couponsRaw.isFirstOrder ?? true;
|
||||
|
||||
const mapped = couponsRaw.data.map((coupon) => {
|
||||
const applicableSkuIds = [
|
||||
...(coupon.applicableProducts || []).map((p: any) => p.skuId),
|
||||
...(Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : []),
|
||||
];
|
||||
// Target SKUs live on the coupon row itself (empty => whole cart).
|
||||
const applicableSkuIds = Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [];
|
||||
|
||||
let reason: string | undefined;
|
||||
if (coupon.regionId != null && regionId != null && coupon.regionId !== regionId) {
|
||||
|
|
|
|||
|
|
@ -194,10 +194,7 @@ const CheckoutPage: React.FC<FlashDeliveryProps> = ({ isFlashDelivery = false })
|
|||
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[]) : []),
|
||||
],
|
||||
applicableSkuIds: Array.isArray(coupon.skuIds) ? (coupon.skuIds as number[]) : [],
|
||||
isEligible,
|
||||
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
|
||||
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/).
|
||||
|
||||
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.
|
||||
|
||||
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 |
|
||||
|---|---|---|---|
|
||||
| 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-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-10 | P0 | Target A SKU and global SKU; try B regional SKU in A coupon. | Valid targets allowed; 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-12 | P1 | Replace/remove all product/user targets on edit. | Old relations removed as intended; empty target means whole cart. |
|
||||
| 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 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 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-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-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-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-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.
|
||||
|
|
|
|||
|
|
@ -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-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-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-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. |
|
||||
|
|
|
|||
|
|
@ -7,6 +7,11 @@
|
|||
-- * 0008_user_creds_unique_and_min_order_cleanup -> user_creds unique index and
|
||||
-- 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
|
||||
-- then drop them:
|
||||
-- * `region_bound_settings` (created + seeded in 0006, dropped in 0009)
|
||||
|
|
@ -21,6 +26,7 @@
|
|||
-- 1. regions / region_bounds / superadmins + seeds (from 0006)
|
||||
-- 2. region_id backfill + 31-table rebuild (from 0007)
|
||||
-- 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
|
||||
-- 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`)
|
||||
SELECT `id`,`coupon_id`,`user_id` FROM `coupon_applicable_users`;
|
||||
--> 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` (
|
||||
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
|
||||
`secret_code` text NOT NULL,
|
||||
|
|
@ -676,8 +671,6 @@ DROP TABLE `cart_items`;
|
|||
--> statement-breakpoint
|
||||
DROP TABLE `reserved_coupons`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `coupon_applicable_products`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `coupon_applicable_users`;
|
||||
--> statement-breakpoint
|
||||
DROP TABLE `coupon_usage`;
|
||||
|
|
@ -783,8 +776,6 @@ ALTER TABLE `__new_coupon_usage` RENAME TO `coupon_usage`;
|
|||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_coupon_applicable_users` RENAME TO `coupon_applicable_users`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_coupon_applicable_products` RENAME TO `coupon_applicable_products`;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE `__new_reserved_coupons` RENAME TO `reserved_coupons`;
|
||||
--> statement-breakpoint
|
||||
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
|
||||
CREATE UNIQUE INDEX `unique_coupon_user` ON `coupon_applicable_users` (`coupon_id`,`user_id`);
|
||||
--> 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`);
|
||||
--> statement-breakpoint
|
||||
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.
|
||||
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;
|
||||
--> 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,
|
||||
updateCouponWithRelations,
|
||||
generateCancellationCoupon,
|
||||
createReservedCouponWithProducts,
|
||||
createReservedCoupon,
|
||||
createCouponForUser,
|
||||
checkUsersExist,
|
||||
checkCouponExists,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,15 @@
|
|||
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 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 unique = [...new Set((skuIds || []).map(Number).filter((n) => Number.isFinite(n)))]
|
||||
if (unique.length === 0) return
|
||||
|
|
@ -57,13 +64,6 @@ export async function getAllCoupons(
|
|||
user: true,
|
||||
},
|
||||
},
|
||||
applicableProducts: {
|
||||
with: {
|
||||
sku: {
|
||||
with: { product: true },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: desc(coupons.createdAt),
|
||||
limit: limit + 1,
|
||||
|
|
@ -88,13 +88,6 @@ export async function getCouponById(regionId: number, id: number): Promise<any |
|
|||
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(
|
||||
input: CouponFormInput,
|
||||
applicableUsers: number[] | undefined,
|
||||
applicableProducts: number[] | undefined,
|
||||
regionId: number | null
|
||||
): Promise<Coupon> {
|
||||
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
||||
const skuIds = normalizeSkuIds(input.skuIds)
|
||||
await assertApplicableSkusInRegion(db, skuIds, regionId)
|
||||
|
||||
return await db.transaction(async (tx) => {
|
||||
const [coupon] = await tx.insert(coupons).values({
|
||||
|
|
@ -115,7 +108,7 @@ export async function createCouponWithRelations(
|
|||
discountPercent: input.discountPercent,
|
||||
flatDiscount: input.flatDiscount,
|
||||
minOrder: input.minOrder,
|
||||
skuIds: input.skuIds,
|
||||
skuIds: skuIds.length > 0 ? skuIds : null,
|
||||
createdBy: input.createdBy,
|
||||
maxValue: input.maxValue,
|
||||
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
|
||||
})
|
||||
}
|
||||
|
|
@ -151,8 +135,7 @@ export async function updateCouponWithRelations(
|
|||
regionId: number | null,
|
||||
id: number,
|
||||
input: CouponFormInput,
|
||||
applicableUsers?: number[],
|
||||
applicableProducts?: number[]
|
||||
applicableUsers?: number[]
|
||||
): Promise<Coupon | null> {
|
||||
const existing = await db.query.coupons.findFirst({
|
||||
where: and(
|
||||
|
|
@ -164,9 +147,8 @@ export async function updateCouponWithRelations(
|
|||
if (!existing) {
|
||||
return null
|
||||
}
|
||||
if (applicableProducts !== undefined) {
|
||||
await assertApplicableSkusInRegion(db, applicableProducts, regionId)
|
||||
}
|
||||
const skuIds = normalizeSkuIds(input.skuIds)
|
||||
await assertApplicableSkusInRegion(db, skuIds, regionId)
|
||||
|
||||
return await db.transaction(async (tx) => {
|
||||
// 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)
|
||||
.set({
|
||||
...updateFields,
|
||||
skuIds: skuIds.length > 0 ? skuIds : null,
|
||||
})
|
||||
.where(
|
||||
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
|
||||
})
|
||||
}
|
||||
|
|
@ -268,12 +239,12 @@ export async function getReservedCoupons(
|
|||
return { coupons: couponsList, hasMore }
|
||||
}
|
||||
|
||||
export async function createReservedCouponWithProducts(
|
||||
export async function createReservedCoupon(
|
||||
input: any,
|
||||
applicableProducts: number[] | undefined,
|
||||
regionId: number
|
||||
): Promise<any> {
|
||||
await assertApplicableSkusInRegion(db, applicableProducts || [], regionId)
|
||||
const skuIds = normalizeSkuIds(input.skuIds)
|
||||
await assertApplicableSkusInRegion(db, skuIds, regionId)
|
||||
|
||||
return await db.transaction(async (tx) => {
|
||||
const [coupon] = await tx.insert(reservedCoupons).values({
|
||||
|
|
@ -283,7 +254,7 @@ export async function createReservedCouponWithProducts(
|
|||
discountPercent: input.discountPercent,
|
||||
flatDiscount: input.flatDiscount,
|
||||
minOrder: input.minOrder,
|
||||
skuIds: input.skuIds,
|
||||
skuIds: skuIds.length > 0 ? skuIds : null,
|
||||
maxValue: input.maxValue,
|
||||
validTill: input.validTill,
|
||||
maxLimitForUser: input.maxLimitForUser,
|
||||
|
|
@ -292,15 +263,6 @@ export async function createReservedCouponWithProducts(
|
|||
createdBy: input.createdBy,
|
||||
}).returning()
|
||||
|
||||
if (applicableProducts && applicableProducts.length > 0) {
|
||||
await tx.insert(couponApplicableProducts).values(
|
||||
applicableProducts.map(skuId => ({
|
||||
couponId: coupon.id,
|
||||
skuId,
|
||||
}))
|
||||
)
|
||||
}
|
||||
|
||||
return coupon
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,6 @@ import {
|
|||
vendorSnippets,
|
||||
homeBanners,
|
||||
keyValStore,
|
||||
couponApplicableProducts,
|
||||
} from '../db/schema'
|
||||
import { and, desc, eq, inArray, isNull, or, sql, type SQL } from 'drizzle-orm'
|
||||
import { runBatched } from '../lib/run-batched'
|
||||
|
|
@ -377,7 +376,10 @@ async function softDeleteProduct(where: SQL): Promise<AdminProduct | null> {
|
|||
await db.batch([
|
||||
db.delete(productMarketStats).where(inArray(productMarketStats.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
|
||||
db.delete(productTags).where(inArray(productTags.productId, skuIds)),
|
||||
db.delete(productGroupMembership).where(inArray(productGroupMembership.productId, skuIds)),
|
||||
|
|
|
|||
|
|
@ -541,6 +541,8 @@ export const coupons = sqliteTable('coupons', {
|
|||
discountPercent: numericText('discount_percent'),
|
||||
flatDiscount: numericText('flat_discount'),
|
||||
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'),
|
||||
createdBy: integer('created_by').references(() => staffUsers.id),
|
||||
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),
|
||||
}))
|
||||
|
||||
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', {
|
||||
id: integer().primaryKey({ autoIncrement: true }),
|
||||
userId: integer('user_id').notNull().references(() => users.id),
|
||||
|
|
@ -596,6 +590,8 @@ export const reservedCoupons = sqliteTable('reserved_coupons', {
|
|||
discountPercent: numericText('discount_percent'),
|
||||
flatDiscount: numericText('flat_discount'),
|
||||
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'),
|
||||
maxValue: numericText('max_value'),
|
||||
validTill: timestampText('valid_till'),
|
||||
|
|
@ -704,7 +700,6 @@ export const productSkusRelations = relations(productSkus, ({ one, many }) => ({
|
|||
specialDeals: many(specialDeals),
|
||||
orderItems: many(orderItems),
|
||||
cartItems: many(cartItems),
|
||||
applicableCoupons: many(couponApplicableProducts),
|
||||
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] }),
|
||||
usages: many(couponUsage),
|
||||
applicableUsers: many(couponApplicableUsers),
|
||||
applicableProducts: many(couponApplicableProducts),
|
||||
}))
|
||||
|
||||
export const couponUsageRelations = relations(couponUsage, ({ one }) => ({
|
||||
|
|
@ -835,11 +829,6 @@ export const couponApplicableUsersRelations = relations(couponApplicableUsers, (
|
|||
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 }) => ({
|
||||
redeemedUser: one(users, { fields: [reservedCoupons.redeemedBy], references: [users.id] }),
|
||||
creator: one(staffUsers, { fields: [reservedCoupons.createdBy], references: [staffUsers.id] }),
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import {
|
|||
const globalCouponWith = {
|
||||
creator: true,
|
||||
applicableUsers: { with: { user: true } },
|
||||
applicableProducts: { with: { sku: { with: { product: true } } } },
|
||||
} as const
|
||||
|
||||
/** Global coupons (regionId NULL) — valid in every region. */
|
||||
|
|
@ -33,19 +32,17 @@ export async function getGlobalCoupon(id: number) {
|
|||
|
||||
export async function createGlobalCoupon(
|
||||
input: CouponFormInput,
|
||||
applicableUsers: number[] | undefined,
|
||||
applicableProducts: number[] | undefined
|
||||
applicableUsers: number[] | undefined
|
||||
): Promise<Coupon> {
|
||||
return createCouponWithRelations(input, applicableUsers, applicableProducts, null)
|
||||
return createCouponWithRelations(input, applicableUsers, null)
|
||||
}
|
||||
|
||||
export async function updateGlobalCoupon(
|
||||
id: number,
|
||||
input: CouponFormInput,
|
||||
applicableUsers?: number[],
|
||||
applicableProducts?: number[]
|
||||
applicableUsers?: number[]
|
||||
): 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> {
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
import { db } from '../db/db_index'
|
||||
import {
|
||||
couponApplicableProducts,
|
||||
couponApplicableUsers,
|
||||
couponUsage,
|
||||
coupons,
|
||||
|
|
@ -8,12 +7,11 @@ import {
|
|||
} from '../db/schema'
|
||||
import { and, eq, gt, isNull, or } 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 CouponUsageRow = InferSelectModel<typeof couponUsage>
|
||||
type CouponApplicableUserRow = InferSelectModel<typeof couponApplicableUsers>
|
||||
type CouponApplicableProductRow = InferSelectModel<typeof couponApplicableProducts>
|
||||
type ReservedCouponRow = InferSelectModel<typeof reservedCoupons>
|
||||
|
||||
const mapCoupon = (coupon: CouponRow): UserCoupon => ({
|
||||
|
|
@ -50,21 +48,13 @@ const mapApplicableUser = (applicable: CouponApplicableUserRow): UserCouponAppli
|
|||
userId: applicable.userId,
|
||||
})
|
||||
|
||||
const mapApplicableProduct = (applicable: CouponApplicableProductRow): UserCouponApplicableProduct => ({
|
||||
id: applicable.id,
|
||||
couponId: applicable.couponId,
|
||||
skuId: applicable.skuId,
|
||||
})
|
||||
|
||||
const mapCouponWithRelations = (coupon: CouponRow & {
|
||||
usages: CouponUsageRow[]
|
||||
applicableUsers: CouponApplicableUserRow[]
|
||||
applicableProducts: CouponApplicableProductRow[]
|
||||
}): UserCouponWithRelations => ({
|
||||
...mapCoupon(coupon),
|
||||
usages: coupon.usages.map(mapUsage),
|
||||
applicableUsers: coupon.applicableUsers.map(mapApplicableUser),
|
||||
applicableProducts: coupon.applicableProducts.map(mapApplicableProduct),
|
||||
})
|
||||
|
||||
export async function getActiveCouponsWithRelations(
|
||||
|
|
@ -90,7 +80,6 @@ export async function getActiveCouponsWithRelations(
|
|||
where: eq(couponUsage.userId, userId),
|
||||
},
|
||||
applicableUsers: true,
|
||||
applicableProducts: true,
|
||||
},
|
||||
})
|
||||
|
||||
|
|
@ -113,7 +102,6 @@ export async function getAllCouponsWithRelations(
|
|||
where: eq(couponUsage.userId, userId),
|
||||
},
|
||||
applicableUsers: true,
|
||||
applicableProducts: true,
|
||||
},
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -139,7 +139,6 @@ export async function validateAndGetCoupons(params: {
|
|||
with: {
|
||||
usages: { where: eq(couponUsage.userId, params.userId) },
|
||||
applicableUsers: true,
|
||||
applicableProducts: true,
|
||||
},
|
||||
})
|
||||
|
||||
|
|
@ -185,9 +184,15 @@ export async function validateAndGetCoupons(params: {
|
|||
)
|
||||
}
|
||||
|
||||
const relatedSkuIds = (coupon.applicableProducts ?? []).map((p) => p.skuId)
|
||||
const jsonSkuIds = Array.isArray(coupon.skuIds) ? coupon.skuIds : []
|
||||
const applicableSkuIds = [...new Set([...relatedSkuIds, ...jsonSkuIds])]
|
||||
// Target SKUs live in the coupon's own `sku_ids` array (there is no join
|
||||
// table). Empty/null => the coupon applies to the whole cart.
|
||||
const applicableSkuIds = [
|
||||
...new Set(
|
||||
(Array.isArray(coupon.skuIds) ? coupon.skuIds : [])
|
||||
.map((skuId) => Number(skuId))
|
||||
.filter((skuId) => Number.isFinite(skuId))
|
||||
),
|
||||
]
|
||||
const targets = applicableSkuIds.length > 0 ? applicableSkuIds : null
|
||||
const eligibleSubtotal = computeEligibleSubtotal(params.items, {
|
||||
applicableSkuIds: targets,
|
||||
|
|
|
|||
|
|
@ -414,12 +414,6 @@ export interface UserCouponApplicableUser {
|
|||
userId: number;
|
||||
}
|
||||
|
||||
export interface UserCouponApplicableProduct {
|
||||
id: number;
|
||||
couponId: number;
|
||||
skuId: number;
|
||||
}
|
||||
|
||||
export interface UserCoupon {
|
||||
id: number;
|
||||
couponCode: string;
|
||||
|
|
@ -428,7 +422,8 @@ export interface UserCoupon {
|
|||
discountPercent: string | null;
|
||||
flatDiscount: string | null;
|
||||
minOrder: string | null;
|
||||
skuIds: unknown;
|
||||
/** Target SKUs (single source). Empty/null => applies to the whole cart. */
|
||||
skuIds: number[] | null;
|
||||
maxValue: string | null;
|
||||
isApplyForAll: boolean;
|
||||
validTill: Date | null;
|
||||
|
|
@ -442,7 +437,6 @@ export interface UserCoupon {
|
|||
export interface UserCouponWithRelations extends UserCoupon {
|
||||
usages: UserCouponUsage[];
|
||||
applicableUsers: UserCouponApplicableUser[];
|
||||
applicableProducts: UserCouponApplicableProduct[];
|
||||
}
|
||||
|
||||
export interface UserEligibleCouponsResponse {
|
||||
|
|
|
|||
|
|
@ -9,10 +9,9 @@ export interface CreateCouponPayload {
|
|||
isApplyForAll: boolean;
|
||||
isUserBased: boolean;
|
||||
targetUsers?: number[];
|
||||
productIds?: number[];
|
||||
/** Target SKUs — the single source of product targeting. Empty => whole cart. */
|
||||
skuIds?: number[];
|
||||
applicableUsers?: number[];
|
||||
applicableProducts?: number[];
|
||||
exclusiveApply?: boolean;
|
||||
isFirstOrderOnly?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,6 @@ PRAGMA foreign_keys = OFF;
|
|||
DROP TABLE IF EXISTS order_items;
|
||||
DROP TABLE IF EXISTS cart_items;
|
||||
DROP TABLE IF EXISTS special_deals;
|
||||
DROP TABLE IF EXISTS coupon_applicable_products;
|
||||
DROP TABLE IF EXISTS product_reviews;
|
||||
DROP TABLE IF EXISTS product_tags;
|
||||
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 cart_items;
|
||||
DROP TABLE IF EXISTS special_deals;
|
||||
DROP TABLE IF EXISTS coupon_applicable_products;
|
||||
DROP TABLE IF EXISTS product_reviews;
|
||||
|
||||
-- ---- product/sku hierarchy ----
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue