From d9fc579f7b3a13db52feb4532e59c511797b3295 Mon Sep 17 00:00:00 2001 From: shafi54 <108669266+shafi-aviz@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:31:33 +0530 Subject: [PATCH] enh --- .../app/(drawer)/dashboard/coupons/index.tsx | 52 +- .../src/routes/dashboard.coupons.tsx | 52 +- .../superadmin-ui/src/components/AppShell.tsx | 3 +- apps/superadmin-ui/src/routeTree.gen.ts | 21 + apps/superadmin-ui/src/routes/coupons.tsx | 445 ++++++++++++++++++ change-log.txt | 20 + .../drizzle/0006_regions_and_superadmins.sql | 3 +- .../db_helper_sqlite/src/admin-apis/coupon.ts | 10 +- 8 files changed, 567 insertions(+), 39 deletions(-) create mode 100644 apps/superadmin-ui/src/routes/coupons.tsx diff --git a/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx b/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx index d2d167e..6c7098f 100644 --- a/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx +++ b/apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx @@ -18,6 +18,9 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v }; const status = getCouponStatus(item); + // Global coupons (region_id NULL) are created by the superadmin and apply to + // every region, so a region admin can only view them. + const isGlobal = item.regionId == null; const getBorderColor = () => { if (status === 'active') return 'border-green-500'; @@ -54,7 +57,14 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v /> - {item.couponCode} + + {item.couponCode} + {isGlobal && ( + + Global + + )} + ID: {item.id} @@ -88,22 +98,30 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v )} - - router.push(`/(drawer)/dashboard/coupons/edit/${item.id}`)} - style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`} - > - - Edit - - onDelete(item.id)} - style={tw`bg-red-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`} - > - - Delete - - + {isGlobal ? ( + + + Applies to all regions — created and managed by the superadmin. + + + ) : ( + + router.push(`/(drawer)/dashboard/coupons/edit/${item.id}`)} + style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`} + > + + Edit + + onDelete(item.id)} + style={tw`bg-red-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`} + > + + Delete + + + )} ); }; diff --git a/apps/admin-web/src/routes/dashboard.coupons.tsx b/apps/admin-web/src/routes/dashboard.coupons.tsx index 9c719ad..b825087 100644 --- a/apps/admin-web/src/routes/dashboard.coupons.tsx +++ b/apps/admin-web/src/routes/dashboard.coupons.tsx @@ -21,6 +21,9 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v } const status = getCouponStatus(item) + // Global coupons (region_id NULL) are created by the superadmin and apply to + // every region, so a region admin can only view them. + const isGlobal = item.regionId == null const getBorderColor = () => { if (status === 'active') return 'border-green-500' @@ -57,7 +60,14 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v )}
- {item.couponCode} +
+ {item.couponCode} + {isGlobal && ( + + Global + + )} +
ID: {item.id}
@@ -91,22 +101,30 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v )} -
- - -
+ {isGlobal ? ( +
+ + Applies to all regions — created and managed by the superadmin. + +
+ ) : ( +
+ + +
+ )} ) } diff --git a/apps/superadmin-ui/src/components/AppShell.tsx b/apps/superadmin-ui/src/components/AppShell.tsx index 8833a01..cab27a5 100644 --- a/apps/superadmin-ui/src/components/AppShell.tsx +++ b/apps/superadmin-ui/src/components/AppShell.tsx @@ -1,6 +1,6 @@ import React, { useState } from 'react' import { Link } from '@tanstack/react-router' -import { LayoutDashboard, Send, Settings2, Menu, X, LogOut, Map, UserCog, Store, Package, MessageSquare } from 'lucide-react' +import { LayoutDashboard, Send, Settings2, Menu, X, LogOut, Map, UserCog, Store, Package, MessageSquare, TicketPercent } from 'lucide-react' import { useAuth } from '../lib/auth-context' const NAV = [ @@ -8,6 +8,7 @@ const NAV = [ { to: '/regions', label: 'Regions', icon: Map }, { to: '/global-stores', label: 'Stores', icon: Store }, { to: '/global-products', label: 'Products', icon: Package }, + { to: '/coupons', label: 'Coupons', icon: TicketPercent }, { to: '/staff', label: 'Admin Users', icon: UserCog }, { to: '/complaints', label: 'Complaints', icon: MessageSquare }, { to: '/send-notifications', label: 'Admin Notifs', icon: Send }, diff --git a/apps/superadmin-ui/src/routeTree.gen.ts b/apps/superadmin-ui/src/routeTree.gen.ts index db0ef85..ff9fe03 100644 --- a/apps/superadmin-ui/src/routeTree.gen.ts +++ b/apps/superadmin-ui/src/routeTree.gen.ts @@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as ComplaintsRouteImport } from './routes/complaints' import { Route as ConstantsRouteImport } from './routes/constants' +import { Route as CouponsRouteImport } from './routes/coupons' import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as GlobalProductsRouteImport } from './routes/global-products' import { Route as GlobalStoresRouteImport } from './routes/global-stores' @@ -35,6 +36,11 @@ const ConstantsRoute = ConstantsRouteImport.update({ path: '/constants', getParentRoute: () => rootRouteImport, } as any) +const CouponsRoute = CouponsRouteImport.update({ + id: '/coupons', + path: '/coupons', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRoute = DashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', @@ -75,6 +81,7 @@ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/complaints': typeof ComplaintsRoute '/constants': typeof ConstantsRoute + '/coupons': typeof CouponsRoute '/dashboard': typeof DashboardRoute '/global-products': typeof GlobalProductsRoute '/global-stores': typeof GlobalStoresRoute @@ -87,6 +94,7 @@ export interface FileRoutesByTo { '/': typeof IndexRoute '/complaints': typeof ComplaintsRoute '/constants': typeof ConstantsRoute + '/coupons': typeof CouponsRoute '/dashboard': typeof DashboardRoute '/global-products': typeof GlobalProductsRoute '/global-stores': typeof GlobalStoresRoute @@ -100,6 +108,7 @@ export interface FileRoutesById { '/': typeof IndexRoute '/complaints': typeof ComplaintsRoute '/constants': typeof ConstantsRoute + '/coupons': typeof CouponsRoute '/dashboard': typeof DashboardRoute '/global-products': typeof GlobalProductsRoute '/global-stores': typeof GlobalStoresRoute @@ -114,6 +123,7 @@ export interface FileRouteTypes { | '/' | '/complaints' | '/constants' + | '/coupons' | '/dashboard' | '/global-products' | '/global-stores' @@ -126,6 +136,7 @@ export interface FileRouteTypes { | '/' | '/complaints' | '/constants' + | '/coupons' | '/dashboard' | '/global-products' | '/global-stores' @@ -138,6 +149,7 @@ export interface FileRouteTypes { | '/' | '/complaints' | '/constants' + | '/coupons' | '/dashboard' | '/global-products' | '/global-stores' @@ -151,6 +163,7 @@ export interface RootRouteChildren { IndexRoute: typeof IndexRoute ComplaintsRoute: typeof ComplaintsRoute ConstantsRoute: typeof ConstantsRoute + CouponsRoute: typeof CouponsRoute DashboardRoute: typeof DashboardRoute GlobalProductsRoute: typeof GlobalProductsRoute GlobalStoresRoute: typeof GlobalStoresRoute @@ -183,6 +196,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ConstantsRouteImport parentRoute: typeof rootRouteImport } + '/coupons': { + id: '/coupons' + path: '/coupons' + fullPath: '/coupons' + preLoaderRoute: typeof CouponsRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -239,6 +259,7 @@ const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, ComplaintsRoute: ComplaintsRoute, ConstantsRoute: ConstantsRoute, + CouponsRoute: CouponsRoute, DashboardRoute: DashboardRoute, GlobalProductsRoute: GlobalProductsRoute, GlobalStoresRoute: GlobalStoresRoute, diff --git a/apps/superadmin-ui/src/routes/coupons.tsx b/apps/superadmin-ui/src/routes/coupons.tsx new file mode 100644 index 0000000..87fb195 --- /dev/null +++ b/apps/superadmin-ui/src/routes/coupons.tsx @@ -0,0 +1,445 @@ +import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' +import { AppContainer, MyButton, p as MyText, pInput as PInput } from 'web-components' +import { X } from 'lucide-react' +import { ProtectedRoute } from '../components/ProtectedRoute' +import { AppShell } from '../components/AppShell' +import { SimpleSelect } from '@/components/ui/simple-select' +import { confirm } from '@/components/ui/dialog-host' +import { trpc } from '../lib/trpc-client' + +export const Route = createFileRoute('/coupons')({ + component: () => ( + + + + + + ), +}) + +interface CouponFormState { + couponCode: string + discountType: 'percent' | 'flat' + discountValue: string + minOrder: string + maxValue: string + validTill: string + maxLimitForUser: string + exclusiveApply: boolean + isFirstOrderOnly: boolean + skuIds: number[] +} + +const emptyForm = (): CouponFormState => ({ + couponCode: '', + discountType: 'percent', + discountValue: '', + minOrder: '', + maxValue: '', + validTill: '', + maxLimitForUser: '', + exclusiveApply: false, + isFirstOrderOnly: false, + skuIds: [], +}) + +const toDateInput = (value: unknown): string => { + if (!value) return '' + const d = new Date(value as string) + return Number.isNaN(d.getTime()) ? '' : d.toISOString().slice(0, 10) +} + +function CouponsPage() { + const utils = trpc.useUtils() + const listQuery = trpc.superadmin.globalCoupons.list.useQuery() + const coupons = (listQuery.data?.coupons ?? []) as any[] + + const [form, setForm] = useState(emptyForm()) + const [editingId, setEditingId] = useState(null) + const [error, setError] = useState(null) + + const createCoupon = trpc.superadmin.globalCoupons.create.useMutation() + const updateCoupon = trpc.superadmin.globalCoupons.update.useMutation() + const invalidateCoupon = trpc.superadmin.globalCoupons.delete.useMutation() + + const refresh = () => utils.superadmin.globalCoupons.list.invalidate() + + const set = (key: K, value: CouponFormState[K]) => + setForm((prev) => ({ ...prev, [key]: value })) + + const num = (value: string): number | undefined => { + const n = Number(value) + return value.trim() !== '' && Number.isFinite(n) ? n : undefined + } + + const resetForm = () => { + setEditingId(null) + setForm(emptyForm()) + setError(null) + } + + const startEdit = (coupon: any) => { + setEditingId(coupon.id) + setError(null) + setForm({ + couponCode: coupon.couponCode ?? '', + discountType: coupon.discountPercent != null ? 'percent' : 'flat', + discountValue: String(coupon.discountPercent ?? coupon.flatDiscount ?? ''), + minOrder: coupon.minOrder != null ? String(coupon.minOrder) : '', + maxValue: coupon.maxValue != null ? String(coupon.maxValue) : '', + validTill: toDateInput(coupon.validTill), + maxLimitForUser: coupon.maxLimitForUser != null ? String(coupon.maxLimitForUser) : '', + exclusiveApply: !!coupon.exclusiveApply, + isFirstOrderOnly: !!coupon.isFirstOrderOnly, + skuIds: Array.isArray(coupon.skuIds) ? coupon.skuIds.map(Number) : [], + }) + } + + const buildPayload = () => ({ + couponCode: form.couponCode.trim() || undefined, + discountPercent: form.discountType === 'percent' ? num(form.discountValue) : undefined, + flatDiscount: form.discountType === 'flat' ? num(form.discountValue) : undefined, + minOrder: form.minOrder.trim() ? num(form.minOrder) : undefined, + maxValue: form.maxValue.trim() ? num(form.maxValue) : undefined, + validTill: form.validTill || undefined, + maxLimitForUser: form.maxLimitForUser.trim() ? num(form.maxLimitForUser) : undefined, + exclusiveApply: form.exclusiveApply, + isFirstOrderOnly: form.isFirstOrderOnly, + skuIds: form.skuIds.length > 0 ? form.skuIds : null, + }) + + const handleSubmit = async () => { + setError(null) + if (num(form.discountValue) == null) { + setError('Enter a discount value.') + return + } + try { + if (editingId != null) { + await updateCoupon.mutateAsync({ id: editingId, ...buildPayload() }) + } else { + await createCoupon.mutateAsync(buildPayload()) + } + resetForm() + refresh() + } catch (e) { + setError((e as Error).message || 'Could not save the coupon') + } + } + + const handleInvalidate = async (coupon: any) => { + if (!(await confirm(`Invalidate coupon "${coupon.couponCode}"? It will stop applying in every region.`))) return + setError(null) + try { + await invalidateCoupon.mutateAsync({ id: coupon.id }) + if (editingId === coupon.id) resetForm() + refresh() + } catch (e) { + setError((e as Error).message || 'Could not invalidate the coupon') + } + } + + return ( + +
+ Coupons + + Global coupons apply in every region. They are created here (and only here) and appear + read-only in each region's admin app. + + +
+ + {editingId != null ? `Edit coupon #${editingId}` : 'Create a global coupon'} + + +
+ set('couponCode', e.target.value)} + placeholder="e.g. FRESH50 (blank = auto-generate)" + /> +
+ Discount type + set('discountType', v === 'flat' ? 'flat' : 'percent')} + options={[ + { value: 'percent', label: 'Percent off' }, + { value: 'flat', label: 'Flat ₹ off' }, + ]} + /> +
+ set('discountValue', e.target.value)} + placeholder="e.g. 10" + /> + set('minOrder', e.target.value)} + placeholder="e.g. 500" + /> + set('maxValue', e.target.value)} + placeholder="e.g. 100" + /> + set('validTill', e.target.value)} + /> + set('maxLimitForUser', e.target.value)} + placeholder="e.g. 1" + /> +
+ +
+ + +
+ + set('skuIds', ids)} /> + {form.skuIds.length === 0 && ( + + No products selected — this coupon applies to the whole cart. + + )} + + {error && {error}} + +
+ + {editingId != null + ? updateCoupon.isPending + ? 'Saving…' + : 'Save changes' + : createCoupon.isPending + ? 'Creating…' + : 'Create coupon'} + + {editingId != null && ( + + Cancel + + )} +
+
+ +
+ Global coupons + {listQuery.isLoading && Loading coupons…} + {!listQuery.isLoading && coupons.length === 0 && ( + No global coupons yet. + )} +
+ {coupons.map((coupon) => ( + startEdit(coupon)} + onInvalidate={() => handleInvalidate(coupon)} + /> + ))} +
+
+
+
+ ) +} + +function CouponRow({ + coupon, + busy, + onEdit, + onInvalidate, +}: { + coupon: any + busy: boolean + onEdit: () => void + onInvalidate: () => void +}) { + const status = coupon.isInvalidated + ? 'inactive' + : coupon.validTill && new Date(coupon.validTill) <= new Date() + ? 'expired' + : 'active' + + const discount = + coupon.discountPercent != null + ? `${coupon.discountPercent}% off` + : coupon.flatDiscount != null + ? `₹${coupon.flatDiscount} off` + : '—' + + return ( +
+
+
+ {coupon.couponCode} + + {status === 'active' ? 'Active' : status === 'expired' ? 'Expired' : 'Inactive'} + +
+
+ + Edit + + + Invalidate + +
+
+ + {discount} + {coupon.minOrder != null ? ` · Min ₹${coupon.minOrder}` : ''} + {coupon.maxValue != null ? ` · Max ₹${coupon.maxValue}` : ''} + {coupon.validTill ? ` · Till ${new Date(coupon.validTill).toLocaleDateString()}` : ' · No expiry'} + {Array.isArray(coupon.skuIds) && coupon.skuIds.length > 0 + ? ` · ${coupon.skuIds.length} product(s)` + : ' · Whole cart'} + {coupon.exclusiveApply ? ' · Exclusive' : ''} + {coupon.isFirstOrderOnly ? ' · First order only' : ''} + +
+ ) +} + +function SkuPicker({ selected, onChange }: { selected: number[]; onChange: (ids: number[]) => void }) { + const [open, setOpen] = useState(false) + const [search, setSearch] = useState('') + const [names, setNames] = useState>({}) + + const productsQuery = trpc.superadmin.products.list.useQuery( + { search: search.trim() || undefined, limit: 20 }, + { enabled: open } + ) + const products = (productsQuery.data?.products ?? []) as any[] + + const toggle = (skuId: number, name: string) => { + setNames((prev) => ({ ...prev, [skuId]: name })) + onChange(selected.includes(skuId) ? selected.filter((id) => id !== skuId) : [...selected, skuId]) + } + + return ( +
+
+ Target products (optional) + setOpen((v) => !v)} + className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm text-gray-700" + > + {open ? 'Close' : 'Choose products'} + +
+ + {selected.length > 0 && ( +
+ {selected.map((id) => ( + + {names[id] ?? `SKU #${id}`} + + + ))} +
+ )} + + {open && ( +
+ setSearch(e.target.value)} + placeholder="Search products by name…" + /> + {productsQuery.isLoading && Loading products…} +
+ {products.map((product) => ( +
+ + {product.name} + {product.region ? ` · ${product.region.name}` : ' · Global'} + +
+ {(product.skus ?? []).map((sku: any) => { + const isSelected = selected.includes(sku.id) + return ( + + ) + })} +
+
+ ))} + {!productsQuery.isLoading && products.length === 0 && ( + No products found. + )} +
+
+ )} +
+ ) +} diff --git a/change-log.txt b/change-log.txt index 1348c7a..f0a58a4 100644 --- a/change-log.txt +++ b/change-log.txt @@ -5229,3 +5229,23 @@ user-ui 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. + - Timestamp: 2026-10-16 22:27:35 + Feature: global coupons (valid in every region, created only by superadmin). + The backend already modelled these as coupons.region_id IS NULL; this change + makes them creatable/visible end-to-end. + Files: + * packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql + __new_coupons.region_id: drop NOT NULL (NULL = global). + * packages/db_helper_sqlite/src/admin-apis/coupon.ts + getAllCoupons: include region_id IS NULL (region admins see global coupons + read-only). assertApplicableSkusInRegion: skip region check when + regionId == null (global coupon may target any SKU). + * apps/superadmin-ui/src/routes/coupons.tsx (new): global coupons list + + create/edit form + invalidate, SKU multi-select via superadmin.products.list. + * apps/superadmin-ui/src/components/AppShell.tsx: Coupons nav entry. + * apps/admin-ui/app/(drawer)/dashboard/coupons/index.tsx + apps/admin-web/src/routes/dashboard.coupons.tsx + Global badge; hide Edit/Delete for region_id == null. + * temp local D1 delta (outside repo): rebuild coupons + coupon_usage + + coupon_applicable_users + order_status to drop the NOT NULL. + No tests run; migrations not run. 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 b86adf9..1ee80af 100644 --- a/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql +++ b/packages/db_helper_sqlite/drizzle/0006_regions_and_superadmins.sql @@ -342,7 +342,8 @@ CREATE TABLE `__new_coupons` ( `exclusive_apply` integer DEFAULT false NOT NULL, `is_first_order_only` integer DEFAULT false NOT NULL, `created_at` text DEFAULT CURRENT_TIMESTAMP NOT NULL, - `region_id` integer NOT NULL, + -- Nullable: NULL means the coupon is global (valid in every region, created by superadmin). + `region_id` integer, FOREIGN KEY (`created_by`) REFERENCES `__new_staff_users`(`id`) ON UPDATE no action ON DELETE no action, FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action ); diff --git a/packages/db_helper_sqlite/src/admin-apis/coupon.ts b/packages/db_helper_sqlite/src/admin-apis/coupon.ts index ebf79df..c9d2c6c 100644 --- a/packages/db_helper_sqlite/src/admin-apis/coupon.ts +++ b/packages/db_helper_sqlite/src/admin-apis/coupon.ts @@ -22,8 +22,10 @@ const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regio const found = new Set(rows.map((r: { id: number }) => r.id)) throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`) } - // A global SKU (product regionId null) belongs to no region and may be attached anywhere. - const foreign = rows.filter((r: any) => { + // A global SKU (product regionId null) belongs to no region and may be attached + // anywhere. A global coupon (regionId null) may attach any SKU, including + // region-specific ones, so only enforce the region match for regional coupons. + const foreign = regionId == null ? [] : rows.filter((r: any) => { const skuRegionId = r.product?.regionId ?? null return skuRegionId !== null && skuRegionId !== regionId }) @@ -41,7 +43,9 @@ export async function getAllCoupons( let whereCondition = undefined const conditions = [] - conditions.push(eq(coupons.regionId, regionId)) + // Region admins see their own coupons plus the global ones (region_id IS NULL), + // which are read-only for them. + conditions.push(or(isNull(coupons.regionId), eq(coupons.regionId, regionId))) if (cursor) { conditions.push(lt(coupons.id, cursor))