731 lines
30 KiB
TypeScript
731 lines
30 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useMemo, useState } from 'react';
|
|
import {
|
|
Tag,
|
|
Plus,
|
|
RefreshCw,
|
|
Search,
|
|
CheckCircle2,
|
|
Trash2,
|
|
Edit2,
|
|
Calendar,
|
|
Users,
|
|
ShoppingBag,
|
|
Percent,
|
|
Copy,
|
|
Info,
|
|
ExternalLink,
|
|
} from 'lucide-react';
|
|
import { toast } from 'sonner';
|
|
import { format } from 'date-fns';
|
|
import { apiFetch } from '@/services/api/client';
|
|
import { SlideOver } from '@/components/ui/SlideOver';
|
|
import { CustomSelect } from '@/components/ui/CustomSelect';
|
|
import { TablePagination, useClientPagination } from '@/components/ui/TablePagination';
|
|
|
|
interface CouponItem {
|
|
coupon_id: string;
|
|
code: string;
|
|
description: string | null;
|
|
discount_type: 'PERCENT' | 'FIXED';
|
|
discount_value: number;
|
|
min_order_amount: number;
|
|
max_discount_cap: number | null;
|
|
first_order_only: boolean;
|
|
channel_scope: 'ALL' | 'STOREFRONT' | 'STORE_POS';
|
|
usage_limit_total: number | null;
|
|
usage_limit_per_customer: number;
|
|
current_usage_count: number;
|
|
applicable_category_ids: string[];
|
|
applicable_brand_ids: string[];
|
|
applicable_model_ids: string[];
|
|
start_date: string | null;
|
|
end_date: string | null;
|
|
is_active: boolean;
|
|
created_at: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
interface CouponUsageAudit {
|
|
usage_id: string;
|
|
customer_id: string;
|
|
order_id: string;
|
|
discount_amount: number;
|
|
used_at: string;
|
|
}
|
|
|
|
type FilterTab = 'all' | 'active' | 'first_order' | 'inactive';
|
|
|
|
export default function AdminCouponsPage() {
|
|
const [coupons, setCoupons] = useState<CouponItem[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [searchQuery, setSearchQuery] = useState('');
|
|
const [activeTab, setActiveTab] = useState<FilterTab>('all');
|
|
|
|
// SlideOver form state
|
|
const [showFormModal, setShowFormModal] = useState(false);
|
|
const [editingCouponId, setEditingCouponId] = useState<string | null>(null);
|
|
const [saving, setSaving] = useState(false);
|
|
|
|
// Form Fields
|
|
const [code, setCode] = useState('');
|
|
const [description, setDescription] = useState('');
|
|
const [discountType, setDiscountType] = useState<'PERCENT' | 'FIXED'>('PERCENT');
|
|
const [discountValue, setDiscountValue] = useState<number>(10);
|
|
const [minOrderAmount, setMinOrderAmount] = useState<number>(0);
|
|
const [maxDiscountCap, setMaxDiscountCap] = useState<number | ''>('');
|
|
const [firstOrderOnly, setFirstOrderOnly] = useState(false);
|
|
const [channelScope, setChannelScope] = useState<'ALL' | 'STOREFRONT' | 'STORE_POS'>('ALL');
|
|
const [usageLimitTotal, setUsageLimitTotal] = useState<number | ''>('');
|
|
const [usageLimitPerCustomer, setUsageLimitPerCustomer] = useState<number>(1);
|
|
const [startDate, setStartDate] = useState('');
|
|
const [endDate, setEndDate] = useState('');
|
|
const [isActive, setIsActive] = useState(true);
|
|
|
|
// Usage Audit Drawer state
|
|
const [inspectCoupon, setInspectCoupon] = useState<CouponItem | null>(null);
|
|
const [usagesList, setUsagesList] = useState<CouponUsageAudit[]>([]);
|
|
const [usagesLoading, setUsagesLoading] = useState(false);
|
|
const [totalDiscountGiven, setTotalDiscountGiven] = useState(0);
|
|
|
|
const fetchCoupons = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const data = await apiFetch<CouponItem[]>('/api/v1/admin/coupons');
|
|
setCoupons(Array.isArray(data) ? data : []);
|
|
} catch (err: any) {
|
|
toast.error(err.message || 'Failed to load promotional coupons');
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
fetchCoupons();
|
|
}, []);
|
|
|
|
const openCreateModal = () => {
|
|
setEditingCouponId(null);
|
|
setCode('');
|
|
setDescription('');
|
|
setDiscountType('PERCENT');
|
|
setDiscountValue(10);
|
|
setMinOrderAmount(0);
|
|
setMaxDiscountCap('');
|
|
setFirstOrderOnly(false);
|
|
setChannelScope('ALL');
|
|
setUsageLimitTotal('');
|
|
setUsageLimitPerCustomer(1);
|
|
setStartDate('');
|
|
setEndDate('');
|
|
setIsActive(true);
|
|
setShowFormModal(true);
|
|
};
|
|
|
|
const openEditModal = (coupon: CouponItem) => {
|
|
setEditingCouponId(coupon.coupon_id);
|
|
setCode(coupon.code);
|
|
setDescription(coupon.description || '');
|
|
setDiscountType(coupon.discount_type);
|
|
setDiscountValue(coupon.discount_value);
|
|
setMinOrderAmount(coupon.min_order_amount || 0);
|
|
setMaxDiscountCap(coupon.max_discount_cap ?? '');
|
|
setFirstOrderOnly(coupon.first_order_only);
|
|
setChannelScope(coupon.channel_scope);
|
|
setUsageLimitTotal(coupon.usage_limit_total ?? '');
|
|
setUsageLimitPerCustomer(coupon.usage_limit_per_customer || 1);
|
|
setStartDate(coupon.start_date ? coupon.start_date.substring(0, 10) : '');
|
|
setEndDate(coupon.end_date ? coupon.end_date.substring(0, 10) : '');
|
|
setIsActive(coupon.is_active);
|
|
setShowFormModal(true);
|
|
};
|
|
|
|
const handleFormSubmit = async (e: React.FormEvent) => {
|
|
e.preventDefault();
|
|
const cleanCode = code.trim().toUpperCase();
|
|
if (!cleanCode) {
|
|
toast.error('Coupon code is required');
|
|
return;
|
|
}
|
|
if (Number(discountValue) <= 0) {
|
|
toast.error('Discount value must be greater than zero');
|
|
return;
|
|
}
|
|
|
|
setSaving(true);
|
|
try {
|
|
const payload: any = {
|
|
code: cleanCode,
|
|
description: description.trim() || undefined,
|
|
discount_type: discountType,
|
|
discount_value: Number(discountValue),
|
|
min_order_amount: Number(minOrderAmount || 0),
|
|
max_discount_cap: maxDiscountCap !== '' ? Number(maxDiscountCap) : null,
|
|
first_order_only: firstOrderOnly,
|
|
channel_scope: channelScope,
|
|
usage_limit_total: usageLimitTotal !== '' ? Number(usageLimitTotal) : null,
|
|
usage_limit_per_customer: Number(usageLimitPerCustomer || 1),
|
|
start_date: startDate ? new Date(startDate).toISOString() : null,
|
|
end_date: endDate ? new Date(endDate + 'T23:59:59').toISOString() : null,
|
|
is_active: isActive,
|
|
};
|
|
|
|
if (editingCouponId) {
|
|
await apiFetch(`/api/v1/admin/coupons/${editingCouponId}`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify(payload),
|
|
});
|
|
toast.success(`Coupon ${cleanCode} updated successfully`);
|
|
} else {
|
|
await apiFetch('/api/v1/admin/coupons', {
|
|
method: 'POST',
|
|
body: JSON.stringify(payload),
|
|
});
|
|
toast.success(`Coupon ${cleanCode} created successfully`);
|
|
}
|
|
|
|
setShowFormModal(false);
|
|
fetchCoupons();
|
|
} catch (err: any) {
|
|
toast.error(err.message || 'Failed to save coupon');
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
};
|
|
|
|
const handleDeleteCoupon = async (coupon: CouponItem) => {
|
|
if (!confirm(`Are you sure you want to delete or deactivate coupon "${coupon.code}"?`)) {
|
|
return;
|
|
}
|
|
try {
|
|
const res = await apiFetch<any>(`/api/v1/admin/coupons/${coupon.coupon_id}`, {
|
|
method: 'DELETE',
|
|
});
|
|
toast.success(res.message || `Coupon ${coupon.code} removed`);
|
|
fetchCoupons();
|
|
} catch (err: any) {
|
|
toast.error(err.message || 'Failed to remove coupon');
|
|
}
|
|
};
|
|
|
|
const handleToggleStatus = async (coupon: CouponItem) => {
|
|
try {
|
|
await apiFetch(`/api/v1/admin/coupons/${coupon.coupon_id}`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify({ is_active: !coupon.is_active }),
|
|
});
|
|
toast.success(`Coupon ${coupon.code} marked ${!coupon.is_active ? 'Active' : 'Inactive'}`);
|
|
fetchCoupons();
|
|
} catch (err: any) {
|
|
toast.error(err.message || 'Failed to change coupon status');
|
|
}
|
|
};
|
|
|
|
const openUsagesDrawer = async (coupon: CouponItem) => {
|
|
setInspectCoupon(coupon);
|
|
setUsagesLoading(true);
|
|
try {
|
|
const res = await apiFetch<any>(`/api/v1/admin/coupons/${coupon.coupon_id}/usages`);
|
|
setUsagesList(res.usages || []);
|
|
setTotalDiscountGiven(res.total_discount_given || 0);
|
|
} catch {
|
|
toast.error('Failed to load redemption audits');
|
|
} finally {
|
|
setUsagesLoading(false);
|
|
}
|
|
};
|
|
|
|
const copyToClipboard = (text: string) => {
|
|
navigator.clipboard.writeText(text);
|
|
toast.success(`Copied "${text}" to clipboard`);
|
|
};
|
|
|
|
const filteredCoupons = useMemo(() => {
|
|
const q = searchQuery.trim().toLowerCase();
|
|
return coupons.filter((c) => {
|
|
const tabMatch =
|
|
activeTab === 'all' ||
|
|
(activeTab === 'active' && c.is_active) ||
|
|
(activeTab === 'first_order' && c.first_order_only) ||
|
|
(activeTab === 'inactive' && !c.is_active);
|
|
|
|
const searchMatch =
|
|
!q ||
|
|
c.code.toLowerCase().includes(q) ||
|
|
(c.description && c.description.toLowerCase().includes(q));
|
|
|
|
return tabMatch && searchMatch;
|
|
});
|
|
}, [coupons, searchQuery, activeTab]);
|
|
|
|
const pager = useClientPagination(filteredCoupons);
|
|
|
|
const inputClass =
|
|
'w-full h-9 px-3 bg-card border border-border crm-radius-control text-[13px] text-foreground focus:outline-none focus:border-primary';
|
|
const labelClass = 'block text-[11px] font-semibold text-muted-foreground uppercase mb-1.5';
|
|
const primaryButton =
|
|
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control bg-primary hover:bg-primary/90 text-white text-[13px] font-semibold cursor-pointer disabled:opacity-50';
|
|
const secondaryButton =
|
|
'inline-flex items-center justify-center gap-2 h-9 px-4 crm-radius-control border border-border bg-card text-foreground text-[13px] font-medium hover:bg-muted cursor-pointer disabled:opacity-50';
|
|
|
|
return (
|
|
<div className="flex flex-col gap-5 min-w-0">
|
|
{/* Page Header */}
|
|
<div className="flex flex-wrap items-start justify-between gap-3 min-w-0">
|
|
<div className="min-w-0">
|
|
<div className="flex items-center gap-2">
|
|
<h1 className="text-lg font-semibold text-foreground">Promotions & Coupon Rules</h1>
|
|
<span className="inline-flex items-center justify-center min-w-5 h-5 px-1.5 crm-radius-toggle bg-primary/10 text-primary text-[11px] font-semibold leading-none">
|
|
{coupons.length}
|
|
</span>
|
|
</div>
|
|
<p className="text-[12px] text-muted-foreground mt-0.5">
|
|
Create rule-driven coupon codes, first-time customer checkout discounts, and walk-in POS counter promotions.
|
|
</p>
|
|
</div>
|
|
|
|
<div className="flex items-center gap-2 shrink-0">
|
|
<button
|
|
type="button"
|
|
onClick={fetchCoupons}
|
|
className="w-8 h-8 crm-radius-control border border-border bg-card text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer transition-colors flex items-center justify-center"
|
|
title="Reload"
|
|
>
|
|
<RefreshCw className="w-3.5 h-3.5" />
|
|
</button>
|
|
<button type="button" onClick={openCreateModal} className={primaryButton}>
|
|
<span className="w-[18px] h-[18px] rounded-full bg-white text-primary flex items-center justify-center">
|
|
<Plus className="w-3 h-3" strokeWidth={3} />
|
|
</span>
|
|
Create coupon
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Main Container */}
|
|
<div className="crm-radius-section border border-border bg-card shadow-[0_1px_3px_rgba(16,24,40,0.06)] overflow-hidden min-w-0">
|
|
<div className="px-5 pt-5">
|
|
<div className="-mx-5 px-5 flex flex-wrap items-center justify-between gap-3 min-w-0 pb-4 border-b border-border">
|
|
<div className="relative flex-1 min-w-[180px] max-w-[480px]">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none" />
|
|
<input
|
|
type="text"
|
|
placeholder="Search coupons by code or description..."
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
className="w-full h-9 pl-9 pr-3 crm-radius-control border border-border bg-card text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:border-primary transition-colors"
|
|
/>
|
|
</div>
|
|
|
|
<div className="crm-radius-toggle inline-flex items-center gap-1 border border-border bg-card p-1 shrink-0 overflow-x-auto max-w-full">
|
|
{(
|
|
[
|
|
{ id: 'all', label: `All (${coupons.length})` },
|
|
{ id: 'active', label: `Active (${coupons.filter((c) => c.is_active).length})` },
|
|
{ id: 'first_order', label: `1st Order Only (${coupons.filter((c) => c.first_order_only).length})` },
|
|
{ id: 'inactive', label: `Inactive (${coupons.filter((c) => !c.is_active).length})` },
|
|
] as { id: FilterTab; label: string }[]
|
|
).map((tab) => (
|
|
<button
|
|
key={tab.id}
|
|
type="button"
|
|
onClick={() => setActiveTab(tab.id)}
|
|
className={`h-8 px-3 crm-radius-toggle text-[13px] font-medium cursor-pointer transition-colors whitespace-nowrap ${
|
|
activeTab === tab.id ? 'bg-primary text-white' : 'text-foreground hover:bg-muted'
|
|
}`}
|
|
>
|
|
{tab.label}
|
|
</button>
|
|
))}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<div className="flex flex-col items-center justify-center py-16 gap-2.5">
|
|
<RefreshCw className="w-6 h-6 text-primary animate-spin" />
|
|
<span className="text-[13px] text-muted-foreground">Loading coupons...</span>
|
|
</div>
|
|
) : (
|
|
<div className="overflow-x-auto">
|
|
<table className="crm-data-table min-w-[860px]">
|
|
<thead>
|
|
<tr className="bg-gray-50 border-y border-gray-200">
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700">Coupon code</th>
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700">Discount rule</th>
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700">Channel & Limits</th>
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700">Redemptions</th>
|
|
<th className="px-5 py-3 text-left text-[13px] font-semibold text-gray-700">Status</th>
|
|
<th className="px-5 py-3 text-center text-[13px] font-semibold text-gray-700">Action</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody className="bg-card">
|
|
{filteredCoupons.length === 0 ? (
|
|
<tr>
|
|
<td colSpan={6} className="text-center py-12 text-[13px] text-muted-foreground">
|
|
{searchQuery || activeTab !== 'all' ? 'No coupons match your filter.' : 'No promotional coupons found.'}
|
|
</td>
|
|
</tr>
|
|
) : (
|
|
pager.items.map((coupon) => (
|
|
<tr key={coupon.coupon_id} className="border-t border-border hover:bg-muted/10">
|
|
<td className="px-5 py-3.5">
|
|
<div className="flex items-center gap-1.5">
|
|
<span className="font-mono font-bold text-[14px] text-foreground tracking-wider bg-muted/40 px-2 py-0.5 rounded border border-border">
|
|
{coupon.code}
|
|
</span>
|
|
<button
|
|
type="button"
|
|
onClick={() => copyToClipboard(coupon.code)}
|
|
className="text-muted-foreground hover:text-foreground cursor-pointer p-1"
|
|
title="Copy code"
|
|
>
|
|
<Copy className="w-3.5 h-3.5" />
|
|
</button>
|
|
</div>
|
|
{coupon.description && (
|
|
<p className="text-[12px] text-muted-foreground mt-1 max-w-[260px] truncate">
|
|
{coupon.description}
|
|
</p>
|
|
)}
|
|
{coupon.first_order_only && (
|
|
<div className="mt-1">
|
|
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold bg-amber-500/10 text-amber-700 border border-amber-500/25">
|
|
⭐ 1st Order Customer Only
|
|
</span>
|
|
</div>
|
|
)}
|
|
</td>
|
|
|
|
<td className="px-5 py-3.5">
|
|
<div className="text-[13px] font-semibold text-emerald-600">
|
|
{coupon.discount_type === 'PERCENT'
|
|
? `${coupon.discount_value}% OFF`
|
|
: `₹${coupon.discount_value.toFixed(2)} FLAT OFF`}
|
|
</div>
|
|
<div className="text-[11px] text-muted-foreground mt-0.5 space-y-0.5">
|
|
{coupon.max_discount_cap && (
|
|
<p>Max discount: ₹{coupon.max_discount_cap}</p>
|
|
)}
|
|
<p>Min order: ₹{coupon.min_order_amount || 0}</p>
|
|
</div>
|
|
</td>
|
|
|
|
<td className="px-5 py-3.5">
|
|
<span className="inline-block px-2 py-0.5 text-[10px] font-semibold uppercase rounded bg-muted text-muted-foreground border border-border">
|
|
{coupon.channel_scope === 'ALL'
|
|
? '🌐 Global Omnichannel'
|
|
: coupon.channel_scope === 'STOREFRONT'
|
|
? '💻 Storefront Online'
|
|
: '🏬 Walk-in POS'}
|
|
</span>
|
|
<p className="text-[11px] text-muted-foreground mt-1">
|
|
Limit per user: {coupon.usage_limit_per_customer || 1}
|
|
</p>
|
|
</td>
|
|
|
|
<td className="px-5 py-3.5">
|
|
<button
|
|
type="button"
|
|
onClick={() => openUsagesDrawer(coupon)}
|
|
className="font-mono text-[13px] font-semibold text-primary hover:underline cursor-pointer flex items-center gap-1"
|
|
>
|
|
<span>{coupon.current_usage_count} uses</span>
|
|
<ExternalLink className="w-3 h-3" />
|
|
</button>
|
|
{coupon.usage_limit_total && (
|
|
<p className="text-[11px] text-muted-foreground mt-0.5">
|
|
Max {coupon.usage_limit_total} total
|
|
</p>
|
|
)}
|
|
</td>
|
|
|
|
<td className="px-5 py-3.5">
|
|
<button
|
|
type="button"
|
|
onClick={() => handleToggleStatus(coupon)}
|
|
className={`inline-flex items-center px-2 py-0.5 rounded text-[11px] font-semibold cursor-pointer transition-colors ${
|
|
coupon.is_active
|
|
? 'bg-emerald-500/10 text-emerald-700 border border-emerald-500/25 hover:bg-emerald-500/20'
|
|
: 'bg-muted text-muted-foreground border border-border hover:bg-muted/80'
|
|
}`}
|
|
>
|
|
{coupon.is_active ? 'Active' : 'Inactive'}
|
|
</button>
|
|
</td>
|
|
|
|
<td className="px-5 py-3.5">
|
|
<div className="flex items-center justify-center gap-1.5">
|
|
<button
|
|
type="button"
|
|
onClick={() => openEditModal(coupon)}
|
|
className="w-8 h-8 crm-radius-control border border-border text-muted-foreground hover:text-foreground hover:bg-muted cursor-pointer flex items-center justify-center"
|
|
title="Edit coupon"
|
|
>
|
|
<Edit2 className="w-3.5 h-3.5" />
|
|
</button>
|
|
<button
|
|
type="button"
|
|
onClick={() => handleDeleteCoupon(coupon)}
|
|
className="w-8 h-8 crm-radius-control border border-border text-muted-foreground hover:text-destructive hover:bg-muted cursor-pointer flex items-center justify-center"
|
|
title="Delete or deactivate"
|
|
>
|
|
<Trash2 className="w-3.5 h-3.5" />
|
|
</button>
|
|
</div>
|
|
</td>
|
|
</tr>
|
|
))
|
|
)}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
<TablePagination {...pager} />
|
|
</div>
|
|
|
|
{/* SlideOver for Create / Edit Coupon */}
|
|
<SlideOver
|
|
open={showFormModal}
|
|
onClose={() => setShowFormModal(false)}
|
|
title={editingCouponId ? `Edit Coupon ${code}` : 'Create Promotional Coupon'}
|
|
icon={<Tag className="w-4 h-4 text-primary shrink-0" />}
|
|
>
|
|
<form onSubmit={handleFormSubmit} className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
|
|
<div>
|
|
<label className={labelClass}>Coupon Code (Uppercase)</label>
|
|
<input
|
|
type="text"
|
|
required
|
|
value={code}
|
|
onChange={(e) => setCode(e.target.value.toUpperCase())}
|
|
placeholder="e.g. WELCOME10 or FLAT200"
|
|
className={`${inputClass} font-mono uppercase font-bold tracking-wider`}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className={labelClass}>Description / Promo Title</label>
|
|
<input
|
|
type="text"
|
|
value={description}
|
|
onChange={(e) => setDescription(e.target.value)}
|
|
placeholder="e.g. 10% off for first time customer checkout"
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label className={labelClass}>Discount Type</label>
|
|
<CustomSelect
|
|
value={discountType}
|
|
onChange={(val) => setDiscountType(val as any)}
|
|
options={[
|
|
{ value: 'PERCENT', label: 'Percentage (%) Off' },
|
|
{ value: 'FIXED', label: 'Flat (₹) Amount Off' },
|
|
]}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className={labelClass}>Discount Value ({discountType === 'PERCENT' ? '%' : '₹'})</label>
|
|
<input
|
|
type="number"
|
|
min={0.01}
|
|
step={discountType === 'PERCENT' ? '0.1' : '1'}
|
|
required
|
|
value={discountValue}
|
|
onChange={(e) => setDiscountValue(Number(e.target.value))}
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{discountType === 'PERCENT' && (
|
|
<div>
|
|
<label className={labelClass}>Max Discount Cap (₹) (Optional)</label>
|
|
<input
|
|
type="number"
|
|
min={1}
|
|
value={maxDiscountCap}
|
|
onChange={(e) => setMaxDiscountCap(e.target.value === '' ? '' : Number(e.target.value))}
|
|
placeholder="e.g. 500 (Leave empty for no cap)"
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
)}
|
|
|
|
<div>
|
|
<label className={labelClass}>Minimum Order Amount (₹)</label>
|
|
<input
|
|
type="number"
|
|
min={0}
|
|
value={minOrderAmount}
|
|
onChange={(e) => setMinOrderAmount(Number(e.target.value))}
|
|
placeholder="e.g. 999"
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
|
|
{/* 🌟 First-time Customer Checkout Rule */}
|
|
<div className="p-3.5 rounded-lg border border-amber-500/30 bg-amber-500/5 space-y-2">
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<p className="text-[13px] font-bold text-foreground">1st Time Customer Only</p>
|
|
<p className="text-[11px] text-muted-foreground">
|
|
Restricts this coupon to customers making their very first order.
|
|
</p>
|
|
</div>
|
|
<input
|
|
type="checkbox"
|
|
checked={firstOrderOnly}
|
|
onChange={(e) => setFirstOrderOnly(e.target.checked)}
|
|
className="w-4 h-4 text-primary rounded border-border cursor-pointer"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<label className={labelClass}>Sales Channel Scope</label>
|
|
<CustomSelect
|
|
value={channelScope}
|
|
onChange={(val) => setChannelScope(val as any)}
|
|
options={[
|
|
{ value: 'ALL', label: '🌐 All Channels (Storefront & Walk-in POS)' },
|
|
{ value: 'STOREFRONT', label: '💻 Storefront Online Checkout Only' },
|
|
{ value: 'STORE_POS', label: '🏬 Walk-in Counter POS Only' },
|
|
]}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label className={labelClass}>Total Max Usage Limit</label>
|
|
<input
|
|
type="number"
|
|
min={1}
|
|
value={usageLimitTotal}
|
|
onChange={(e) => setUsageLimitTotal(e.target.value === '' ? '' : Number(e.target.value))}
|
|
placeholder="Unlimited"
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className={labelClass}>Usage Limit Per Customer</label>
|
|
<input
|
|
type="number"
|
|
min={1}
|
|
value={usageLimitPerCustomer}
|
|
onChange={(e) => setUsageLimitPerCustomer(Number(e.target.value))}
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<label className={labelClass}>Start Date</label>
|
|
<input
|
|
type="date"
|
|
value={startDate}
|
|
onChange={(e) => setStartDate(e.target.value)}
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
|
|
<div>
|
|
<label className={labelClass}>End Date</label>
|
|
<input
|
|
type="date"
|
|
value={endDate}
|
|
onChange={(e) => setEndDate(e.target.value)}
|
|
className={inputClass}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex items-center justify-between pt-2 border-t border-border">
|
|
<label className="text-[13px] font-medium text-foreground cursor-pointer">
|
|
Active & Redeemable
|
|
</label>
|
|
<input
|
|
type="checkbox"
|
|
checked={isActive}
|
|
onChange={(e) => setIsActive(e.target.checked)}
|
|
className="w-4 h-4 text-primary rounded border-border cursor-pointer"
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="shrink-0 border-t border-border px-5 py-3 flex items-center justify-end gap-2 bg-card">
|
|
<button
|
|
type="button"
|
|
onClick={() => setShowFormModal(false)}
|
|
disabled={saving}
|
|
className={secondaryButton}
|
|
>
|
|
Cancel
|
|
</button>
|
|
<button type="submit" disabled={saving} className={primaryButton}>
|
|
{saving ? 'Saving...' : editingCouponId ? 'Update Coupon' : 'Create Coupon'}
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</SlideOver>
|
|
|
|
{/* SlideOver for Redemption Audits */}
|
|
<SlideOver
|
|
open={!!inspectCoupon}
|
|
onClose={() => setInspectCoupon(null)}
|
|
title={inspectCoupon ? `Redemptions for ${inspectCoupon.code}` : 'Coupon Usages'}
|
|
icon={<Users className="w-4 h-4 text-primary shrink-0" />}
|
|
>
|
|
<div className="flex min-h-0 flex-1 flex-col">
|
|
<div className="flex-1 min-h-0 overflow-y-auto px-5 py-4 space-y-4">
|
|
<div className="p-3 border border-border crm-radius-card bg-muted/20 flex justify-between items-center text-[13px]">
|
|
<div>
|
|
<p className="font-bold text-foreground font-mono">{inspectCoupon?.code}</p>
|
|
<p className="text-[11px] text-muted-foreground">Total Redemptions: {usagesList.length}</p>
|
|
</div>
|
|
<div className="text-right">
|
|
<p className="font-semibold text-emerald-600">Total Savings</p>
|
|
<p className="font-mono font-bold text-[15px] text-emerald-700">₹{totalDiscountGiven.toFixed(2)}</p>
|
|
</div>
|
|
</div>
|
|
|
|
{usagesLoading ? (
|
|
<div className="flex flex-col items-center justify-center py-12 gap-2">
|
|
<RefreshCw className="w-5 h-5 text-primary animate-spin" />
|
|
<span className="text-[12px] text-muted-foreground">Loading audit log...</span>
|
|
</div>
|
|
) : usagesList.length === 0 ? (
|
|
<div className="text-center py-12 text-[13px] text-muted-foreground">
|
|
No redemptions recorded for this coupon yet.
|
|
</div>
|
|
) : (
|
|
<div className="space-y-2">
|
|
{usagesList.map((usage) => (
|
|
<div key={usage.usage_id} className="p-3 border border-border crm-radius-card text-[12px] space-y-1">
|
|
<div className="flex justify-between items-center">
|
|
<span className="font-mono text-foreground font-semibold">Order ID: {usage.order_id}</span>
|
|
<span className="font-bold text-emerald-600">-₹{Number(usage.discount_amount).toFixed(2)}</span>
|
|
</div>
|
|
<div className="flex justify-between items-center text-muted-foreground text-[11px]">
|
|
<span>Customer: {usage.customer_id}</span>
|
|
<span>{usage.used_at ? format(new Date(usage.used_at), 'dd-MMM-yyyy HH:mm') : '—'}</span>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
</div>
|
|
</div>
|
|
</SlideOver>
|
|
</div>
|
|
);
|
|
}
|
|
|