enh
This commit is contained in:
parent
9a7bb09228
commit
d9fc579f7b
8 changed files with 567 additions and 39 deletions
|
|
@ -18,6 +18,9 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
|
||||||
};
|
};
|
||||||
|
|
||||||
const status = getCouponStatus(item);
|
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 = () => {
|
const getBorderColor = () => {
|
||||||
if (status === 'active') return 'border-green-500';
|
if (status === 'active') return 'border-green-500';
|
||||||
|
|
@ -54,7 +57,14 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
|
||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
<View style={tw`flex-1`}>
|
<View style={tw`flex-1`}>
|
||||||
<MyText style={tw`text-lg font-bold text-gray-800`}>{item.couponCode}</MyText>
|
<View style={tw`flex-row items-center flex-wrap`}>
|
||||||
|
<MyText style={tw`text-lg font-bold text-gray-800`}>{item.couponCode}</MyText>
|
||||||
|
{isGlobal && (
|
||||||
|
<View style={tw`ml-2 px-2 py-0.5 rounded-full bg-indigo-100 border border-indigo-200`}>
|
||||||
|
<MyText style={tw`text-[10px] font-bold text-indigo-700`}>Global</MyText>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
|
</View>
|
||||||
<MyText style={tw`text-sm text-gray-500`}>ID: {item.id}</MyText>
|
<MyText style={tw`text-sm text-gray-500`}>ID: {item.id}</MyText>
|
||||||
</View>
|
</View>
|
||||||
<View style={tw`px-2 py-1 rounded-full ${getBgColor()}`}>
|
<View style={tw`px-2 py-1 rounded-full ${getBgColor()}`}>
|
||||||
|
|
@ -88,22 +98,30 @@ const CouponItem = ({ item, onDelete }: { item: any; onDelete: (id: number) => v
|
||||||
)}
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
|
||||||
<View style={tw`flex-row mt-3 gap-2`}>
|
{isGlobal ? (
|
||||||
<TouchableOpacity
|
<View style={tw`mt-3 bg-indigo-50 border border-indigo-100 rounded-lg p-3`}>
|
||||||
onPress={() => router.push(`/(drawer)/dashboard/coupons/edit/${item.id}`)}
|
<MyText style={tw`text-xs text-indigo-700`}>
|
||||||
style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
|
Applies to all regions — created and managed by the superadmin.
|
||||||
>
|
</MyText>
|
||||||
<MaterialCommunityIcons name="pencil" size={16} color="white" />
|
</View>
|
||||||
<MyText style={tw`text-white text-center font-semibold ml-1`}>Edit</MyText>
|
) : (
|
||||||
</TouchableOpacity>
|
<View style={tw`flex-row mt-3 gap-2`}>
|
||||||
<TouchableOpacity
|
<TouchableOpacity
|
||||||
onPress={() => onDelete(item.id)}
|
onPress={() => router.push(`/(drawer)/dashboard/coupons/edit/${item.id}`)}
|
||||||
style={tw`bg-red-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
|
style={tw`bg-blue-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
|
||||||
>
|
>
|
||||||
<MaterialCommunityIcons name="delete" size={16} color="white" />
|
<MaterialCommunityIcons name="pencil" size={16} color="white" />
|
||||||
<MyText style={tw`text-white text-center font-semibold ml-1`}>Delete</MyText>
|
<MyText style={tw`text-white text-center font-semibold ml-1`}>Edit</MyText>
|
||||||
</TouchableOpacity>
|
</TouchableOpacity>
|
||||||
</View>
|
<TouchableOpacity
|
||||||
|
onPress={() => onDelete(item.id)}
|
||||||
|
style={tw`bg-red-500 p-3 rounded-lg shadow-md flex-1 flex-row items-center justify-center`}
|
||||||
|
>
|
||||||
|
<MaterialCommunityIcons name="delete" size={16} color="white" />
|
||||||
|
<MyText style={tw`text-white text-center font-semibold ml-1`}>Delete</MyText>
|
||||||
|
</TouchableOpacity>
|
||||||
|
</View>
|
||||||
|
)}
|
||||||
</View>
|
</View>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -21,6 +21,9 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v
|
||||||
}
|
}
|
||||||
|
|
||||||
const status = getCouponStatus(item)
|
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 = () => {
|
const getBorderColor = () => {
|
||||||
if (status === 'active') return 'border-green-500'
|
if (status === 'active') return 'border-green-500'
|
||||||
|
|
@ -57,7 +60,14 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<MyText className="block text-lg font-bold text-gray-800">{item.couponCode}</MyText>
|
<div className="flex flex-row flex-wrap items-center gap-2">
|
||||||
|
<MyText className="block text-lg font-bold text-gray-800">{item.couponCode}</MyText>
|
||||||
|
{isGlobal && (
|
||||||
|
<span className="rounded-full border border-indigo-200 bg-indigo-100 px-2 py-0.5 text-[10px] font-bold text-indigo-700">
|
||||||
|
Global
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<MyText className="block text-sm text-gray-500">ID: {item.id}</MyText>
|
<MyText className="block text-sm text-gray-500">ID: {item.id}</MyText>
|
||||||
</div>
|
</div>
|
||||||
<span className={`rounded-full px-2 py-1 ${getBgColor()}`}>
|
<span className={`rounded-full px-2 py-1 ${getBgColor()}`}>
|
||||||
|
|
@ -91,22 +101,30 @@ const CouponItem = ({ item, onDelete }: { item: any, onDelete: (id: number) => v
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-3 flex flex-row gap-2">
|
{isGlobal ? (
|
||||||
<button
|
<div className="mt-3 rounded-lg border border-indigo-100 bg-indigo-50 p-3">
|
||||||
onClick={() => navigate({ to: '/dashboard/coupons/$id/edit', params: { id: String(item.id) } })}
|
<MyText className="block text-xs text-indigo-700">
|
||||||
className="flex flex-1 flex-row items-center justify-center rounded-lg bg-blue-500 p-3 shadow-md"
|
Applies to all regions — created and managed by the superadmin.
|
||||||
>
|
</MyText>
|
||||||
<Pencil size={16} color="white" />
|
</div>
|
||||||
<MyText className="ml-1 text-center font-semibold text-white">Edit</MyText>
|
) : (
|
||||||
</button>
|
<div className="mt-3 flex flex-row gap-2">
|
||||||
<button
|
<button
|
||||||
onClick={() => onDelete(item.id)}
|
onClick={() => navigate({ to: '/dashboard/coupons/$id/edit', params: { id: String(item.id) } })}
|
||||||
className="flex flex-1 flex-row items-center justify-center rounded-lg bg-red-500 p-3 shadow-md"
|
className="flex flex-1 flex-row items-center justify-center rounded-lg bg-blue-500 p-3 shadow-md"
|
||||||
>
|
>
|
||||||
<Trash2 size={16} color="white" />
|
<Pencil size={16} color="white" />
|
||||||
<MyText className="ml-1 text-center font-semibold text-white">Delete</MyText>
|
<MyText className="ml-1 text-center font-semibold text-white">Edit</MyText>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
<button
|
||||||
|
onClick={() => onDelete(item.id)}
|
||||||
|
className="flex flex-1 flex-row items-center justify-center rounded-lg bg-red-500 p-3 shadow-md"
|
||||||
|
>
|
||||||
|
<Trash2 size={16} color="white" />
|
||||||
|
<MyText className="ml-1 text-center font-semibold text-white">Delete</MyText>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
import React, { useState } from 'react'
|
import React, { useState } from 'react'
|
||||||
import { Link } from '@tanstack/react-router'
|
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'
|
import { useAuth } from '../lib/auth-context'
|
||||||
|
|
||||||
const NAV = [
|
const NAV = [
|
||||||
|
|
@ -8,6 +8,7 @@ const NAV = [
|
||||||
{ to: '/regions', label: 'Regions', icon: Map },
|
{ to: '/regions', label: 'Regions', icon: Map },
|
||||||
{ to: '/global-stores', label: 'Stores', icon: Store },
|
{ to: '/global-stores', label: 'Stores', icon: Store },
|
||||||
{ to: '/global-products', label: 'Products', icon: Package },
|
{ to: '/global-products', label: 'Products', icon: Package },
|
||||||
|
{ to: '/coupons', label: 'Coupons', icon: TicketPercent },
|
||||||
{ to: '/staff', label: 'Admin Users', icon: UserCog },
|
{ to: '/staff', label: 'Admin Users', icon: UserCog },
|
||||||
{ to: '/complaints', label: 'Complaints', icon: MessageSquare },
|
{ to: '/complaints', label: 'Complaints', icon: MessageSquare },
|
||||||
{ to: '/send-notifications', label: 'Admin Notifs', icon: Send },
|
{ to: '/send-notifications', label: 'Admin Notifs', icon: Send },
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||||
import { Route as IndexRouteImport } from './routes/index'
|
import { Route as IndexRouteImport } from './routes/index'
|
||||||
import { Route as ComplaintsRouteImport } from './routes/complaints'
|
import { Route as ComplaintsRouteImport } from './routes/complaints'
|
||||||
import { Route as ConstantsRouteImport } from './routes/constants'
|
import { Route as ConstantsRouteImport } from './routes/constants'
|
||||||
|
import { Route as CouponsRouteImport } from './routes/coupons'
|
||||||
import { Route as DashboardRouteImport } from './routes/dashboard'
|
import { Route as DashboardRouteImport } from './routes/dashboard'
|
||||||
import { Route as GlobalProductsRouteImport } from './routes/global-products'
|
import { Route as GlobalProductsRouteImport } from './routes/global-products'
|
||||||
import { Route as GlobalStoresRouteImport } from './routes/global-stores'
|
import { Route as GlobalStoresRouteImport } from './routes/global-stores'
|
||||||
|
|
@ -35,6 +36,11 @@ const ConstantsRoute = ConstantsRouteImport.update({
|
||||||
path: '/constants',
|
path: '/constants',
|
||||||
getParentRoute: () => rootRouteImport,
|
getParentRoute: () => rootRouteImport,
|
||||||
} as any)
|
} as any)
|
||||||
|
const CouponsRoute = CouponsRouteImport.update({
|
||||||
|
id: '/coupons',
|
||||||
|
path: '/coupons',
|
||||||
|
getParentRoute: () => rootRouteImport,
|
||||||
|
} as any)
|
||||||
const DashboardRoute = DashboardRouteImport.update({
|
const DashboardRoute = DashboardRouteImport.update({
|
||||||
id: '/dashboard',
|
id: '/dashboard',
|
||||||
path: '/dashboard',
|
path: '/dashboard',
|
||||||
|
|
@ -75,6 +81,7 @@ export interface FileRoutesByFullPath {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/complaints': typeof ComplaintsRoute
|
'/complaints': typeof ComplaintsRoute
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
|
'/coupons': typeof CouponsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/global-products': typeof GlobalProductsRoute
|
'/global-products': typeof GlobalProductsRoute
|
||||||
'/global-stores': typeof GlobalStoresRoute
|
'/global-stores': typeof GlobalStoresRoute
|
||||||
|
|
@ -87,6 +94,7 @@ export interface FileRoutesByTo {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/complaints': typeof ComplaintsRoute
|
'/complaints': typeof ComplaintsRoute
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
|
'/coupons': typeof CouponsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/global-products': typeof GlobalProductsRoute
|
'/global-products': typeof GlobalProductsRoute
|
||||||
'/global-stores': typeof GlobalStoresRoute
|
'/global-stores': typeof GlobalStoresRoute
|
||||||
|
|
@ -100,6 +108,7 @@ export interface FileRoutesById {
|
||||||
'/': typeof IndexRoute
|
'/': typeof IndexRoute
|
||||||
'/complaints': typeof ComplaintsRoute
|
'/complaints': typeof ComplaintsRoute
|
||||||
'/constants': typeof ConstantsRoute
|
'/constants': typeof ConstantsRoute
|
||||||
|
'/coupons': typeof CouponsRoute
|
||||||
'/dashboard': typeof DashboardRoute
|
'/dashboard': typeof DashboardRoute
|
||||||
'/global-products': typeof GlobalProductsRoute
|
'/global-products': typeof GlobalProductsRoute
|
||||||
'/global-stores': typeof GlobalStoresRoute
|
'/global-stores': typeof GlobalStoresRoute
|
||||||
|
|
@ -114,6 +123,7 @@ export interface FileRouteTypes {
|
||||||
| '/'
|
| '/'
|
||||||
| '/complaints'
|
| '/complaints'
|
||||||
| '/constants'
|
| '/constants'
|
||||||
|
| '/coupons'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/global-products'
|
| '/global-products'
|
||||||
| '/global-stores'
|
| '/global-stores'
|
||||||
|
|
@ -126,6 +136,7 @@ export interface FileRouteTypes {
|
||||||
| '/'
|
| '/'
|
||||||
| '/complaints'
|
| '/complaints'
|
||||||
| '/constants'
|
| '/constants'
|
||||||
|
| '/coupons'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/global-products'
|
| '/global-products'
|
||||||
| '/global-stores'
|
| '/global-stores'
|
||||||
|
|
@ -138,6 +149,7 @@ export interface FileRouteTypes {
|
||||||
| '/'
|
| '/'
|
||||||
| '/complaints'
|
| '/complaints'
|
||||||
| '/constants'
|
| '/constants'
|
||||||
|
| '/coupons'
|
||||||
| '/dashboard'
|
| '/dashboard'
|
||||||
| '/global-products'
|
| '/global-products'
|
||||||
| '/global-stores'
|
| '/global-stores'
|
||||||
|
|
@ -151,6 +163,7 @@ export interface RootRouteChildren {
|
||||||
IndexRoute: typeof IndexRoute
|
IndexRoute: typeof IndexRoute
|
||||||
ComplaintsRoute: typeof ComplaintsRoute
|
ComplaintsRoute: typeof ComplaintsRoute
|
||||||
ConstantsRoute: typeof ConstantsRoute
|
ConstantsRoute: typeof ConstantsRoute
|
||||||
|
CouponsRoute: typeof CouponsRoute
|
||||||
DashboardRoute: typeof DashboardRoute
|
DashboardRoute: typeof DashboardRoute
|
||||||
GlobalProductsRoute: typeof GlobalProductsRoute
|
GlobalProductsRoute: typeof GlobalProductsRoute
|
||||||
GlobalStoresRoute: typeof GlobalStoresRoute
|
GlobalStoresRoute: typeof GlobalStoresRoute
|
||||||
|
|
@ -183,6 +196,13 @@ declare module '@tanstack/react-router' {
|
||||||
preLoaderRoute: typeof ConstantsRouteImport
|
preLoaderRoute: typeof ConstantsRouteImport
|
||||||
parentRoute: typeof rootRouteImport
|
parentRoute: typeof rootRouteImport
|
||||||
}
|
}
|
||||||
|
'/coupons': {
|
||||||
|
id: '/coupons'
|
||||||
|
path: '/coupons'
|
||||||
|
fullPath: '/coupons'
|
||||||
|
preLoaderRoute: typeof CouponsRouteImport
|
||||||
|
parentRoute: typeof rootRouteImport
|
||||||
|
}
|
||||||
'/dashboard': {
|
'/dashboard': {
|
||||||
id: '/dashboard'
|
id: '/dashboard'
|
||||||
path: '/dashboard'
|
path: '/dashboard'
|
||||||
|
|
@ -239,6 +259,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||||
IndexRoute: IndexRoute,
|
IndexRoute: IndexRoute,
|
||||||
ComplaintsRoute: ComplaintsRoute,
|
ComplaintsRoute: ComplaintsRoute,
|
||||||
ConstantsRoute: ConstantsRoute,
|
ConstantsRoute: ConstantsRoute,
|
||||||
|
CouponsRoute: CouponsRoute,
|
||||||
DashboardRoute: DashboardRoute,
|
DashboardRoute: DashboardRoute,
|
||||||
GlobalProductsRoute: GlobalProductsRoute,
|
GlobalProductsRoute: GlobalProductsRoute,
|
||||||
GlobalStoresRoute: GlobalStoresRoute,
|
GlobalStoresRoute: GlobalStoresRoute,
|
||||||
|
|
|
||||||
445
apps/superadmin-ui/src/routes/coupons.tsx
Normal file
445
apps/superadmin-ui/src/routes/coupons.tsx
Normal file
|
|
@ -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: () => (
|
||||||
|
<ProtectedRoute>
|
||||||
|
<AppShell>
|
||||||
|
<CouponsPage />
|
||||||
|
</AppShell>
|
||||||
|
</ProtectedRoute>
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|
||||||
|
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<CouponFormState>(emptyForm())
|
||||||
|
const [editingId, setEditingId] = useState<number | null>(null)
|
||||||
|
const [error, setError] = useState<string | null>(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 = <K extends keyof CouponFormState>(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 (
|
||||||
|
<AppContainer>
|
||||||
|
<div className="bg-gray-50 p-4">
|
||||||
|
<MyText className="mb-1 block text-2xl font-bold text-gray-900">Coupons</MyText>
|
||||||
|
<MyText className="mb-6 block text-gray-600">
|
||||||
|
Global coupons apply in every region. They are created here (and only here) and appear
|
||||||
|
read-only in each region's admin app.
|
||||||
|
</MyText>
|
||||||
|
|
||||||
|
<div className="mb-8 rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||||
|
<MyText className="mb-3 block font-semibold text-gray-900">
|
||||||
|
{editingId != null ? `Edit coupon #${editingId}` : 'Create a global coupon'}
|
||||||
|
</MyText>
|
||||||
|
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
<PInput
|
||||||
|
topLabel="Coupon code"
|
||||||
|
value={form.couponCode}
|
||||||
|
onChange={(e) => set('couponCode', e.target.value)}
|
||||||
|
placeholder="e.g. FRESH50 (blank = auto-generate)"
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<MyText className="mb-1 block text-sm font-medium text-gray-700">Discount type</MyText>
|
||||||
|
<SimpleSelect
|
||||||
|
value={form.discountType}
|
||||||
|
onValueChange={(v) => set('discountType', v === 'flat' ? 'flat' : 'percent')}
|
||||||
|
options={[
|
||||||
|
{ value: 'percent', label: 'Percent off' },
|
||||||
|
{ value: 'flat', label: 'Flat ₹ off' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<PInput
|
||||||
|
topLabel={form.discountType === 'percent' ? 'Percent off' : 'Flat ₹ off'}
|
||||||
|
type="number"
|
||||||
|
value={form.discountValue}
|
||||||
|
onChange={(e) => set('discountValue', e.target.value)}
|
||||||
|
placeholder="e.g. 10"
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Min order (₹, optional)"
|
||||||
|
type="number"
|
||||||
|
value={form.minOrder}
|
||||||
|
onChange={(e) => set('minOrder', e.target.value)}
|
||||||
|
placeholder="e.g. 500"
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Max discount (₹, optional)"
|
||||||
|
type="number"
|
||||||
|
value={form.maxValue}
|
||||||
|
onChange={(e) => set('maxValue', e.target.value)}
|
||||||
|
placeholder="e.g. 100"
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Valid till (optional)"
|
||||||
|
type="date"
|
||||||
|
value={form.validTill}
|
||||||
|
onChange={(e) => set('validTill', e.target.value)}
|
||||||
|
/>
|
||||||
|
<PInput
|
||||||
|
topLabel="Per-user limit (optional)"
|
||||||
|
type="number"
|
||||||
|
value={form.maxLimitForUser}
|
||||||
|
onChange={(e) => set('maxLimitForUser', e.target.value)}
|
||||||
|
placeholder="e.g. 1"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3 flex flex-wrap gap-4">
|
||||||
|
<label className="flex items-center gap-2 text-sm text-gray-700">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.exclusiveApply}
|
||||||
|
onChange={() => set('exclusiveApply', !form.exclusiveApply)}
|
||||||
|
/>
|
||||||
|
Exclusive (can't combine with other coupons)
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2 text-sm text-gray-700">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.isFirstOrderOnly}
|
||||||
|
onChange={() => set('isFirstOrderOnly', !form.isFirstOrderOnly)}
|
||||||
|
/>
|
||||||
|
First order only
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SkuPicker selected={form.skuIds} onChange={(ids) => set('skuIds', ids)} />
|
||||||
|
{form.skuIds.length === 0 && (
|
||||||
|
<MyText className="mt-2 block text-xs text-gray-500">
|
||||||
|
No products selected — this coupon applies to the whole cart.
|
||||||
|
</MyText>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && <MyText className="mt-3 block text-sm text-red-600">{error}</MyText>}
|
||||||
|
|
||||||
|
<div className="mt-4 flex items-center gap-2">
|
||||||
|
<MyButton
|
||||||
|
onClick={handleSubmit}
|
||||||
|
disabled={createCoupon.isPending || updateCoupon.isPending}
|
||||||
|
className="rounded-lg bg-blue-500 px-4 py-2 text-white disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{editingId != null
|
||||||
|
? updateCoupon.isPending
|
||||||
|
? 'Saving…'
|
||||||
|
: 'Save changes'
|
||||||
|
: createCoupon.isPending
|
||||||
|
? 'Creating…'
|
||||||
|
: 'Create coupon'}
|
||||||
|
</MyButton>
|
||||||
|
{editingId != null && (
|
||||||
|
<MyButton onClick={resetForm} className="rounded-lg border border-gray-300 px-4 py-2 text-gray-700">
|
||||||
|
Cancel
|
||||||
|
</MyButton>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-xl border border-gray-200 bg-white p-5 shadow-sm">
|
||||||
|
<MyText className="mb-4 block font-semibold text-gray-900">Global coupons</MyText>
|
||||||
|
{listQuery.isLoading && <MyText className="block text-gray-500">Loading coupons…</MyText>}
|
||||||
|
{!listQuery.isLoading && coupons.length === 0 && (
|
||||||
|
<MyText className="block text-gray-500">No global coupons yet.</MyText>
|
||||||
|
)}
|
||||||
|
<div className="space-y-3">
|
||||||
|
{coupons.map((coupon) => (
|
||||||
|
<CouponRow
|
||||||
|
key={coupon.id}
|
||||||
|
coupon={coupon}
|
||||||
|
busy={invalidateCoupon.isPending}
|
||||||
|
onEdit={() => startEdit(coupon)}
|
||||||
|
onInvalidate={() => handleInvalidate(coupon)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</AppContainer>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<div className="rounded-lg border border-gray-100 bg-gray-50 px-4 py-3">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<MyText className="block font-semibold text-gray-900">{coupon.couponCode}</MyText>
|
||||||
|
<span
|
||||||
|
className={`rounded-full px-2 py-0.5 text-[10px] font-bold ${
|
||||||
|
status === 'active'
|
||||||
|
? 'bg-green-100 text-green-700'
|
||||||
|
: status === 'expired'
|
||||||
|
? 'bg-amber-100 text-amber-700'
|
||||||
|
: 'bg-red-100 text-red-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{status === 'active' ? 'Active' : status === 'expired' ? 'Expired' : 'Inactive'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<MyButton onClick={onEdit} className="rounded-lg bg-blue-500 px-3 py-1.5 text-sm text-white">
|
||||||
|
Edit
|
||||||
|
</MyButton>
|
||||||
|
<MyButton
|
||||||
|
onClick={onInvalidate}
|
||||||
|
disabled={busy || coupon.isInvalidated}
|
||||||
|
className="rounded-lg border border-red-200 px-3 py-1.5 text-sm text-red-600 hover:bg-red-50 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
Invalidate
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<MyText className="mt-1 block text-xs text-gray-600">
|
||||||
|
{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' : ''}
|
||||||
|
</MyText>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
function SkuPicker({ selected, onChange }: { selected: number[]; onChange: (ids: number[]) => void }) {
|
||||||
|
const [open, setOpen] = useState(false)
|
||||||
|
const [search, setSearch] = useState('')
|
||||||
|
const [names, setNames] = useState<Record<number, string>>({})
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<div className="mt-4">
|
||||||
|
<div className="mb-2 flex items-center justify-between">
|
||||||
|
<MyText className="block text-sm font-medium text-gray-700">Target products (optional)</MyText>
|
||||||
|
<MyButton
|
||||||
|
onClick={() => setOpen((v) => !v)}
|
||||||
|
className="rounded-lg border border-gray-300 px-3 py-1.5 text-sm text-gray-700"
|
||||||
|
>
|
||||||
|
{open ? 'Close' : 'Choose products'}
|
||||||
|
</MyButton>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selected.length > 0 && (
|
||||||
|
<div className="mb-2 flex flex-wrap gap-2">
|
||||||
|
{selected.map((id) => (
|
||||||
|
<span
|
||||||
|
key={id}
|
||||||
|
className="flex items-center gap-1 rounded-full bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700"
|
||||||
|
>
|
||||||
|
{names[id] ?? `SKU #${id}`}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label="Remove"
|
||||||
|
onClick={() => onChange(selected.filter((s) => s !== id))}
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div className="rounded-lg border border-gray-200 p-3">
|
||||||
|
<PInput
|
||||||
|
value={search}
|
||||||
|
onChange={(e) => setSearch(e.target.value)}
|
||||||
|
placeholder="Search products by name…"
|
||||||
|
/>
|
||||||
|
{productsQuery.isLoading && <MyText className="mt-2 block text-sm text-gray-500">Loading products…</MyText>}
|
||||||
|
<div className="mt-2 max-h-64 space-y-2 overflow-y-auto">
|
||||||
|
{products.map((product) => (
|
||||||
|
<div key={product.id} className="rounded-md border border-gray-100 p-2">
|
||||||
|
<MyText className="mb-1 block text-xs font-semibold text-gray-600">
|
||||||
|
{product.name}
|
||||||
|
{product.region ? ` · ${product.region.name}` : ' · Global'}
|
||||||
|
</MyText>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{(product.skus ?? []).map((sku: any) => {
|
||||||
|
const isSelected = selected.includes(sku.id)
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={sku.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => toggle(sku.id, sku.name ?? `SKU #${sku.id}`)}
|
||||||
|
className={`rounded-full border px-2 py-0.5 text-xs ${
|
||||||
|
isSelected
|
||||||
|
? 'border-blue-500 bg-blue-500 text-white'
|
||||||
|
: 'border-gray-300 text-gray-700 hover:bg-gray-50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{sku.name ?? `SKU #${sku.id}`}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{!productsQuery.isLoading && products.length === 0 && (
|
||||||
|
<MyText className="block text-sm text-gray-500">No products found.</MyText>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
@ -5229,3 +5229,23 @@ user-ui
|
||||||
EMPTY_ARRAY [] + 9 -> [9];
|
EMPTY_ARRAY [] + 9 -> [9];
|
||||||
sqlite_master count of coupon_applicable_products = 0; reserved_coupons.sku_ids still present.
|
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.
|
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.
|
||||||
|
|
|
||||||
|
|
@ -342,7 +342,8 @@ CREATE TABLE `__new_coupons` (
|
||||||
`exclusive_apply` integer DEFAULT false NOT NULL,
|
`exclusive_apply` integer DEFAULT false NOT NULL,
|
||||||
`is_first_order_only` integer DEFAULT false NOT NULL,
|
`is_first_order_only` integer DEFAULT false NOT NULL,
|
||||||
`created_at` text DEFAULT CURRENT_TIMESTAMP 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 (`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
|
FOREIGN KEY (`region_id`) REFERENCES `regions`(`id`) ON UPDATE no action ON DELETE no action
|
||||||
);
|
);
|
||||||
|
|
|
||||||
|
|
@ -22,8 +22,10 @@ const assertApplicableSkusInRegion = async (txOrDb: any, skuIds: number[], regio
|
||||||
const found = new Set(rows.map((r: { id: number }) => r.id))
|
const found = new Set(rows.map((r: { id: number }) => r.id))
|
||||||
throw new Error(`Invalid SKU IDs: ${unique.filter((id) => !found.has(id)).join(', ')}`)
|
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.
|
// A global SKU (product regionId null) belongs to no region and may be attached
|
||||||
const foreign = rows.filter((r: any) => {
|
// 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
|
const skuRegionId = r.product?.regionId ?? null
|
||||||
return skuRegionId !== null && skuRegionId !== regionId
|
return skuRegionId !== null && skuRegionId !== regionId
|
||||||
})
|
})
|
||||||
|
|
@ -41,7 +43,9 @@ export async function getAllCoupons(
|
||||||
let whereCondition = undefined
|
let whereCondition = undefined
|
||||||
const conditions = []
|
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) {
|
if (cursor) {
|
||||||
conditions.push(lt(coupons.id, cursor))
|
conditions.push(lt(coupons.id, cursor))
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue