From 9a7bb09228de371f636c63cf38bb7a74db0cbdea Mon Sep 17 00:00:00 2001
From: shafi54 <108669266+shafi-aviz@users.noreply.github.com>
Date: Fri, 16 Oct 2026 21:34:52 +0530
Subject: [PATCH] enh
---
.../(drawer)/dashboard/coupons/edit/[id].tsx | 2 +-
.../app/(drawer)/dashboard/coupons/index.tsx | 4 +-
apps/admin-ui/src/components/CouponForm.tsx | 28 ++++-
.../tests/components/coupon-form.test.tsx | 2 +-
.../tests/screens/coupons-edit.test.tsx | 1 -
.../tests/screens/coupons-index.test.tsx | 1 -
apps/admin-web/src/components/CouponForm.tsx | 30 ++++-
.../src/routes/dashboard.coupons.$id.edit.tsx | 5 +-
.../src/routes/dashboard.coupons.tsx | 4 +-
apps/backend/src/dbService.ts | 1 -
apps/backend/src/sqliteImporter.ts | 2 +-
.../src/trpc/apis/admin-apis/apis/coupon.ts | 16 +--
.../superadmin-apis/apis/global-coupons.ts | 7 +-
apps/user-ui/components/cart-page.tsx | 6 +-
apps/user-ui/components/checkout-page.tsx | 5 +-
change-log.txt | 108 ++++++++++++++++++
docs/test-cases/coupon-management.md | 12 +-
docs/test-cases/reserved-coupons.md | 2 +-
.../drizzle/0006_regions_and_superadmins.sql | 55 ++++++---
packages/db_helper_sqlite/index.ts | 2 +-
.../db_helper_sqlite/src/admin-apis/coupon.ts | 76 +++---------
.../src/admin-apis/product.ts | 6 +-
packages/db_helper_sqlite/src/db/schema.ts | 19 +--
.../src/superadmin-apis/global-coupons.ts | 11 +-
.../db_helper_sqlite/src/user-apis/coupon.ts | 14 +--
.../db_helper_sqlite/src/user-apis/order.ts | 13 ++-
packages/shared/types/user.ts | 10 +-
packages/ui/shared-types.ts | 3 +-
scripts/clear-db-old.sql | 1 -
scripts/clear-db.sql | 1 -
30 files changed, 271 insertions(+), 176 deletions(-)
diff --git a/apps/admin-ui/app/(drawer)/dashboard/coupons/edit/[id].tsx b/apps/admin-ui/app/(drawer)/dashboard/coupons/edit/[id].tsx
index 9f54750..416bb96 100644
--- a/apps/admin-ui/app/(drawer)/dashboard/coupons/edit/[id].tsx
+++ b/apps/admin-ui/app/(drawer)/dashboard/coupons/edit/[id].tsx
@@ -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
};
diff --git a/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx b/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx
index 07f5d3f..d2d167e 100644
--- a/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx
+++ b/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx
@@ -81,9 +81,9 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
- {item.applicableProducts && item.applicableProducts.length > 0 && (
+ {item.skuIds && item.skuIds.length > 0 && (
- Products: {item.applicableProducts.length} selected
+ Products: {item.skuIds.length} selected
)}
diff --git a/apps/admin-ui/src/components/CouponForm.tsx b/apps/admin-ui/src/components/CouponForm.tsx
index fd13af9..4b27766 100644
--- a/apps/admin-ui/src/components/CouponForm.tsx
+++ b/apps/admin-ui/src/components/CouponForm.tsx
@@ -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
+ {/* 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). */}
+
+ Applicable Products (Optional)
+
+ setFieldValue('skuIds', Array.isArray(selected) ? selected : [])
+ }
+ />
+
+ {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.'}
+
+
+
{/* Add Multiple Coupons Dialog */}
setMultiDialogOpen(false)}>
diff --git a/apps/admin-ui/tests/components/coupon-form.test.tsx b/apps/admin-ui/tests/components/coupon-form.test.tsx
index c6d3e33..988ce56 100644
--- a/apps/admin-ui/tests/components/coupon-form.test.tsx
+++ b/apps/admin-ui/tests/components/coupon-form.test.tsx
@@ -30,7 +30,7 @@ const validInitialValues = {
targetUsers: [],
discountPercent: 10,
applicableUsers: [],
- applicableProducts: [],
+ skuIds: [],
exclusiveApply: false,
isFirstOrderOnly: false,
isReservedCoupon: false,
diff --git a/apps/admin-ui/tests/screens/coupons-edit.test.tsx b/apps/admin-ui/tests/screens/coupons-edit.test.tsx
index 4635a41..ee72635 100644
--- a/apps/admin-ui/tests/screens/coupons-edit.test.tsx
+++ b/apps/admin-ui/tests/screens/coupons-edit.test.tsx
@@ -38,7 +38,6 @@ const coupon = {
createdBy: 1,
targetUser: { id: 3, name: 'shafi', mobile: '9999999999' },
applicableUsers: [],
- applicableProducts: [],
}
const pressLastAlertButton = (label: string) => {
diff --git a/apps/admin-ui/tests/screens/coupons-index.test.tsx b/apps/admin-ui/tests/screens/coupons-index.test.tsx
index 1b44d73..682508e 100644
--- a/apps/admin-ui/tests/screens/coupons-index.test.tsx
+++ b/apps/admin-ui/tests/screens/coupons-index.test.tsx
@@ -80,7 +80,6 @@ const activeCoupon = {
isInvalidated: false,
createdBy: 1,
applicableUsers: [],
- applicableProducts: [],
}
const expiredCoupon = {
diff --git a/apps/admin-web/src/components/CouponForm.tsx b/apps/admin-web/src/components/CouponForm.tsx
index 1dfda47..282d330 100644
--- a/apps/admin-web/src/components/CouponForm.tsx
+++ b/apps/admin-web/src/components/CouponForm.tsx
@@ -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
+ {/* 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). */}
+
+
Applicable Products (Optional)
+
+ setFieldValue('skuIds', Array.isArray(selected) ? selected : [])
+ }
+ />
+
+ {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.'}
+
+
+
{/* Add Multiple Coupons Dialog */}
setMultiDialogOpen(false)}>
diff --git a/apps/admin-web/src/routes/dashboard.coupons.$id.edit.tsx b/apps/admin-web/src/routes/dashboard.coupons.$id.edit.tsx
index 8f61633..5e42352 100644
--- a/apps/admin-web/src/routes/dashboard.coupons.$id.edit.tsx
+++ b/apps/admin-web/src/routes/dashboard.coupons.$id.edit.tsx
@@ -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
}
diff --git a/apps/admin-web/src/routes/dashboard.coupons.tsx b/apps/admin-web/src/routes/dashboard.coupons.tsx
index 53966ef..9c719ad 100644
--- a/apps/admin-web/src/routes/dashboard.coupons.tsx
+++ b/apps/admin-web/src/routes/dashboard.coupons.tsx
@@ -84,9 +84,9 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v
Target: {item.isApplyForAll ? 'All Users' : item.applicableUsers?.length > 0 ? `${item.applicableUsers.length} Users` : 'All Users'}
- {item.applicableProducts && item.applicableProducts.length > 0 && (
+ {item.skuIds && item.skuIds.length > 0 && (
- Products: {item.applicableProducts.length} selected
+ Products: {item.skuIds.length} selected
)}
diff --git a/apps/backend/src/dbService.ts b/apps/backend/src/dbService.ts
index eda362c..19d394a 100644
--- a/apps/backend/src/dbService.ts
+++ b/apps/backend/src/dbService.ts
@@ -128,7 +128,6 @@ export type {
UserDeleteAccountResponse,
UserCouponUsage,
UserCouponApplicableUser,
- UserCouponApplicableProduct,
UserCoupon,
UserCouponWithRelations,
UserEligibleCouponsResponse,
diff --git a/apps/backend/src/sqliteImporter.ts b/apps/backend/src/sqliteImporter.ts
index f969b0c..9dd1333 100644
--- a/apps/backend/src/sqliteImporter.ts
+++ b/apps/backend/src/sqliteImporter.ts
@@ -40,7 +40,7 @@ export {
createCouponWithRelations,
updateCouponWithRelations,
generateCancellationCoupon,
- createReservedCouponWithProducts,
+ createReservedCoupon,
createCouponForUser,
checkUsersExist,
checkCouponExists,
diff --git a/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts b/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts
index 881e5a8..813d211 100644
--- a/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts
+++ b/apps/backend/src/trpc/apis/admin-apis/apis/coupon.ts
@@ -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 => {
- 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 => {
- 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
);
diff --git a/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts
index 7dc78ab..9629d39 100644
--- a/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts
+++ b/apps/backend/src/trpc/apis/superadmin-apis/apis/global-coupons.ts
@@ -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' }
diff --git a/apps/user-ui/components/cart-page.tsx b/apps/user-ui/components/cart-page.tsx
index ee1b013..5e79026 100644
--- a/apps/user-ui/components/cart-page.tsx
+++ b/apps/user-ui/components/cart-page.tsx
@@ -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) {
diff --git a/apps/user-ui/components/checkout-page.tsx b/apps/user-ui/components/checkout-page.tsx
index b0ff271..f9cee5d 100644
--- a/apps/user-ui/components/checkout-page.tsx
+++ b/apps/user-ui/components/checkout-page.tsx
@@ -194,10 +194,7 @@ const CheckoutPage: React.FC = ({ 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,
};
diff --git a/change-log.txt b/change-log.txt
index f7a163d..1348c7a 100644
--- a/change-log.txt
+++ b/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.
diff --git a/docs/test-cases/coupon-management.md b/docs/test-cases/coupon-management.md
index 4e0ce86..6fd39a2 100644
--- a/docs/test-cases/coupon-management.md
+++ b/docs/test-cases/coupon-management.md
@@ -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.
diff --git a/docs/test-cases/reserved-coupons.md b/docs/test-cases/reserved-coupons.md
index 95aad7c..0651acd 100644
--- a/docs/test-cases/reserved-coupons.md
+++ b/docs/test-cases/reserved-coupons.md
@@ -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. |
diff --git a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
index 209bf6d..b86adf9 100644
--- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
+++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql
@@ -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`;
diff --git a/packages/db_helper_sqlite/index.ts b/packages/db_helper_sqlite/index.ts
index 5761448..2d83194 100644
--- a/packages/db_helper_sqlite/index.ts
+++ b/packages/db_helper_sqlite/index.ts
@@ -47,7 +47,7 @@ export {
createCouponWithRelations,
updateCouponWithRelations,
generateCancellationCoupon,
- createReservedCouponWithProducts,
+ createReservedCoupon,
createCouponForUser,
checkUsersExist,
checkCouponExists,
diff --git a/packages/db_helper_sqlite/src/admin-apis/coupon.ts b/packages/db_helper_sqlite/src/admin-apis/coupon.ts
index edc0b4d..ebf79df 100644
--- a/packages/db_helper_sqlite/src/admin-apis/coupon.ts
+++ b/packages/db_helper_sqlite/src/admin-apis/coupon.ts
@@ -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 => {
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 {
- 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 {
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 {
- 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
})
}
diff --git a/packages/db_helper_sqlite/src/admin-apis/product.ts b/packages/db_helper_sqlite/src/admin-apis/product.ts
index 269b9d9..f35956c 100644
--- a/packages/db_helper_sqlite/src/admin-apis/product.ts
+++ b/packages/db_helper_sqlite/src/admin-apis/product.ts
@@ -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 {
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)),
diff --git a/packages/db_helper_sqlite/src/db/schema.ts b/packages/db_helper_sqlite/src/db/schema.ts
index 91e799d..9fd6c05 100644
--- a/packages/db_helper_sqlite/src/db/schema.ts
+++ b/packages/db_helper_sqlite/src/db/schema.ts
@@ -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('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('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] }),
diff --git a/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts b/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts
index f10a7e8..d33cd0a 100644
--- a/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts
+++ b/packages/db_helper_sqlite/src/superadmin-apis/global-coupons.ts
@@ -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 {
- 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 {
- return updateCouponWithRelations(null, id, input, applicableUsers, applicableProducts)
+ return updateCouponWithRelations(null, id, input, applicableUsers)
}
export async function invalidateGlobalCoupon(id: number): Promise {
diff --git a/packages/db_helper_sqlite/src/user-apis/coupon.ts b/packages/db_helper_sqlite/src/user-apis/coupon.ts
index e511b3a..95d17c3 100644
--- a/packages/db_helper_sqlite/src/user-apis/coupon.ts
+++ b/packages/db_helper_sqlite/src/user-apis/coupon.ts
@@ -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
type CouponUsageRow = InferSelectModel
type CouponApplicableUserRow = InferSelectModel
-type CouponApplicableProductRow = InferSelectModel
type ReservedCouponRow = InferSelectModel
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,
},
})
diff --git a/packages/db_helper_sqlite/src/user-apis/order.ts b/packages/db_helper_sqlite/src/user-apis/order.ts
index 5b6ef69..9680cac 100644
--- a/packages/db_helper_sqlite/src/user-apis/order.ts
+++ b/packages/db_helper_sqlite/src/user-apis/order.ts
@@ -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,
diff --git a/packages/shared/types/user.ts b/packages/shared/types/user.ts
index cb253a3..f68c57f 100644
--- a/packages/shared/types/user.ts
+++ b/packages/shared/types/user.ts
@@ -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 {
diff --git a/packages/ui/shared-types.ts b/packages/ui/shared-types.ts
index 8f0caed..7f12c42 100755
--- a/packages/ui/shared-types.ts
+++ b/packages/ui/shared-types.ts
@@ -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;
}
diff --git a/scripts/clear-db-old.sql b/scripts/clear-db-old.sql
index 62c75c2..d444641 100644
--- a/scripts/clear-db-old.sql
+++ b/scripts/clear-db-old.sql
@@ -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;
diff --git a/scripts/clear-db.sql b/scripts/clear-db.sql
index ad8d98d..65fcc42 100644
--- a/scripts/clear-db.sql
+++ b/scripts/clear-db.sql
@@ -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 ----