feat(admin): POS billing counter, trade discounts, order badges, and rule-based coupon management
This commit is contained in:
parent
2309e40871
commit
b7f5f27350
5 changed files with 1202 additions and 39 deletions
730
app/(admin)/coupons/page.tsx
Normal file
730
app/(admin)/coupons/page.tsx
Normal file
|
|
@ -0,0 +1,730 @@
|
||||||
|
'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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -50,6 +50,10 @@ interface AdminOrderDetailResponse {
|
||||||
customer_name: string | null;
|
customer_name: string | null;
|
||||||
total_amount: number;
|
total_amount: number;
|
||||||
discount_amount: number;
|
discount_amount: number;
|
||||||
|
is_discounted?: boolean;
|
||||||
|
discount_type?: string | null;
|
||||||
|
discount_reason?: string | null;
|
||||||
|
coupon_code?: string | null;
|
||||||
tax_amount: number;
|
tax_amount: number;
|
||||||
shipping_cost: number;
|
shipping_cost: number;
|
||||||
final_amount: number;
|
final_amount: number;
|
||||||
|
|
@ -105,12 +109,17 @@ interface AdminOrderListResponse {
|
||||||
customer_name?: string | null;
|
customer_name?: string | null;
|
||||||
customer_phone?: string | null;
|
customer_phone?: string | null;
|
||||||
final_amount: number;
|
final_amount: number;
|
||||||
|
discount_amount?: number;
|
||||||
|
is_discounted?: boolean;
|
||||||
|
discount_type?: string | null;
|
||||||
|
coupon_code?: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
payment_status: string;
|
payment_status: string;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
type StatusFilter = 'all' | 'open' | 'shipped' | 'delivered' | 'cancelled';
|
type StatusFilter = 'all' | 'open' | 'shipped' | 'delivered' | 'cancelled';
|
||||||
|
type DiscountFilter = 'all' | 'discounted' | 'regular';
|
||||||
|
|
||||||
function formatOrderDate(iso: string) {
|
function formatOrderDate(iso: string) {
|
||||||
const normalized = iso.endsWith('Z') || iso.includes('+') ? iso : `${iso}Z`;
|
const normalized = iso.endsWith('Z') || iso.includes('+') ? iso : `${iso}Z`;
|
||||||
|
|
@ -153,6 +162,7 @@ export default function OrderIntelligencePage() {
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all');
|
||||||
|
const [discountFilter, setDiscountFilter] = useState<DiscountFilter>('all');
|
||||||
|
|
||||||
const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);
|
const [selectedOrderId, setSelectedOrderId] = useState<string | null>(null);
|
||||||
const [detailData, setDetailData] = useState<AdminOrderDetailResponse | null>(null);
|
const [detailData, setDetailData] = useState<AdminOrderDetailResponse | null>(null);
|
||||||
|
|
@ -191,6 +201,15 @@ export default function OrderIntelligencePage() {
|
||||||
const [notificationChannel, setNotificationChannel] = useState<'BOTH' | 'WHATSAPP' | 'EMAIL'>('BOTH');
|
const [notificationChannel, setNotificationChannel] = useState<'BOTH' | 'WHATSAPP' | 'EMAIL'>('BOTH');
|
||||||
const [posSuccessData, setPosSuccessData] = useState<any | null>(null);
|
const [posSuccessData, setPosSuccessData] = useState<any | null>(null);
|
||||||
|
|
||||||
|
// --- Real-time POS Billing Discount & Coupon States ---
|
||||||
|
const [posDiscountType, setPosDiscountType] = useState<'NONE' | 'FIXED' | 'PERCENT' | 'COUPON'>('NONE');
|
||||||
|
const [posDiscountValue, setPosDiscountValue] = useState<number>(0);
|
||||||
|
const [posDiscountReason, setPosDiscountReason] = useState<string>('');
|
||||||
|
const [posCouponCode, setPosCouponCode] = useState<string>('');
|
||||||
|
const [posAppliedCoupon, setPosAppliedCoupon] = useState<any | null>(null);
|
||||||
|
const [posCouponsList, setPosCouponsList] = useState<any[]>([]);
|
||||||
|
const [couponApplying, setCouponApplying] = useState<boolean>(false);
|
||||||
|
|
||||||
const effectiveItems = useMemo(() => {
|
const effectiveItems = useMemo(() => {
|
||||||
if (selectedItems.length > 0) return selectedItems;
|
if (selectedItems.length > 0) return selectedItems;
|
||||||
if (selectedProductId && tempSkuId) {
|
if (selectedProductId && tempSkuId) {
|
||||||
|
|
@ -211,21 +230,55 @@ export default function OrderIntelligencePage() {
|
||||||
return [];
|
return [];
|
||||||
}, [selectedItems, selectedProductId, tempSkuId, skuOptions, tempQty, tempPrice, productsList]);
|
}, [selectedItems, selectedProductId, tempSkuId, skuOptions, tempQty, tempPrice, productsList]);
|
||||||
|
|
||||||
const calculateOrderTotalWithTax = useMemo(() => {
|
// --- Real-Time Point-of-Sale Billing Counter Ledger ---
|
||||||
const subtotal = effectiveItems.reduce((acc, item) => acc + item.quantity * item.unit_price, 0);
|
const billBreakdown = useMemo(() => {
|
||||||
const tax = (subtotal * 18) / 100;
|
const grossSubtotal = effectiveItems.reduce((acc, item) => acc + item.quantity * item.unit_price, 0);
|
||||||
return subtotal + tax;
|
let discountAmt = 0;
|
||||||
}, [effectiveItems]);
|
|
||||||
|
if (posDiscountType === 'COUPON' && posAppliedCoupon) {
|
||||||
|
if (posAppliedCoupon.discount_type === 'PERCENT') {
|
||||||
|
discountAmt = (grossSubtotal * Number(posAppliedCoupon.discount_value || 0)) / 100;
|
||||||
|
if (posAppliedCoupon.max_discount_cap) {
|
||||||
|
discountAmt = Math.min(discountAmt, Number(posAppliedCoupon.max_discount_cap));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
discountAmt = Number(posAppliedCoupon.discount_value || 0);
|
||||||
|
}
|
||||||
|
} else if (posDiscountType === 'PERCENT') {
|
||||||
|
discountAmt = (grossSubtotal * (Number(posDiscountValue) || 0)) / 100;
|
||||||
|
} else if (posDiscountType === 'FIXED') {
|
||||||
|
discountAmt = Number(posDiscountValue) || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
discountAmt = Math.min(grossSubtotal, Math.max(0, discountAmt));
|
||||||
|
const netPayable = Math.max(0, grossSubtotal - discountAmt);
|
||||||
|
|
||||||
|
// GST Inclusive Ledger (18% GST: 9% CGST + 9% SGST on post-discount value)
|
||||||
|
const taxableBase = Number((netPayable / 1.18).toFixed(2));
|
||||||
|
const totalTax = Number((netPayable - taxableBase).toFixed(2));
|
||||||
|
const cgst = Number((totalTax / 2).toFixed(2));
|
||||||
|
const sgst = Number((totalTax - cgst).toFixed(2));
|
||||||
|
|
||||||
|
return {
|
||||||
|
grossSubtotal,
|
||||||
|
discountAmt,
|
||||||
|
taxableBase,
|
||||||
|
cgst,
|
||||||
|
sgst,
|
||||||
|
totalTax,
|
||||||
|
netPayable,
|
||||||
|
};
|
||||||
|
}, [effectiveItems, posDiscountType, posDiscountValue, posAppliedCoupon]);
|
||||||
|
|
||||||
const calculatedDigitalAmount = useMemo(() => {
|
const calculatedDigitalAmount = useMemo(() => {
|
||||||
if (paymentMethod === 'MIXED_PAYMENT') {
|
if (paymentMethod === 'MIXED_PAYMENT') {
|
||||||
return Math.max(0, calculateOrderTotalWithTax - Number(cashPaidAmount || 0));
|
return Math.max(0, billBreakdown.netPayable - Number(cashPaidAmount || 0));
|
||||||
}
|
}
|
||||||
if (paymentMethod === 'UPI' || paymentMethod === 'CARD') {
|
if (paymentMethod === 'UPI' || paymentMethod === 'CARD') {
|
||||||
return calculateOrderTotalWithTax;
|
return billBreakdown.netPayable;
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
}, [paymentMethod, calculateOrderTotalWithTax, cashPaidAmount]);
|
}, [paymentMethod, billBreakdown.netPayable, cashPaidAmount]);
|
||||||
|
|
||||||
const loadRazorpayScript = (): Promise<boolean> => {
|
const loadRazorpayScript = (): Promise<boolean> => {
|
||||||
return new Promise((resolve) => {
|
return new Promise((resolve) => {
|
||||||
|
|
@ -244,13 +297,18 @@ export default function OrderIntelligencePage() {
|
||||||
const fetchCatalogProductsAndSkus = async () => {
|
const fetchCatalogProductsAndSkus = async () => {
|
||||||
setSkuLoading(true);
|
setSkuLoading(true);
|
||||||
try {
|
try {
|
||||||
const [catRes, skuRes, categoriesRes, brandsRes] = await Promise.all([
|
const [catRes, skuRes, categoriesRes, brandsRes, couponsRes] = await Promise.all([
|
||||||
apiFetch<any>('/api/v1/catalog/products/all?limit=200').catch(() => []),
|
apiFetch<any>('/api/v1/catalog/products/all?limit=200').catch(() => []),
|
||||||
apiFetch<{ items: any[] }>('/api/v1/inventory/skus?limit=150').catch(() => ({ items: [] })),
|
apiFetch<{ items: any[] }>('/api/v1/inventory/skus?limit=150').catch(() => ({ items: [] })),
|
||||||
apiFetch<any>('/api/v1/catalog/categories/all').catch(() => []),
|
apiFetch<any>('/api/v1/catalog/categories/all').catch(() => []),
|
||||||
apiFetch<any>('/api/v1/catalog/brands/all').catch(() => []),
|
apiFetch<any>('/api/v1/catalog/brands/all').catch(() => []),
|
||||||
|
apiFetch<any>('/api/v1/admin/coupons?is_active=true').catch(() => []),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
if (Array.isArray(couponsRes)) {
|
||||||
|
setPosCouponsList(couponsRes);
|
||||||
|
}
|
||||||
|
|
||||||
const prodsList = Array.isArray(catRes) ? catRes : catRes?.products || [];
|
const prodsList = Array.isArray(catRes) ? catRes : catRes?.products || [];
|
||||||
setProductsList(prodsList);
|
setProductsList(prodsList);
|
||||||
|
|
||||||
|
|
@ -394,6 +452,47 @@ export default function OrderIntelligencePage() {
|
||||||
setTempPrice(0);
|
setTempPrice(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleApplyPosCoupon = async () => {
|
||||||
|
const code = posCouponCode.trim().toUpperCase();
|
||||||
|
if (!code) {
|
||||||
|
toast.error('Please enter a coupon code');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setCouponApplying(true);
|
||||||
|
try {
|
||||||
|
const found = posCouponsList.find((c) => c.code.toUpperCase() === code);
|
||||||
|
if (found) {
|
||||||
|
if (found.min_order_amount && billBreakdown.grossSubtotal < found.min_order_amount) {
|
||||||
|
toast.error(`Minimum order amount for this coupon is ₹${found.min_order_amount}`);
|
||||||
|
setCouponApplying(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPosAppliedCoupon(found);
|
||||||
|
setPosDiscountType('COUPON');
|
||||||
|
toast.success(`Coupon ${code} applied (-₹${found.discount_value}${found.discount_type === 'PERCENT' ? '%' : ''})`);
|
||||||
|
} else {
|
||||||
|
const res = await apiFetch<any>(`/api/v1/admin/coupons?search=${encodeURIComponent(code)}`);
|
||||||
|
const matched = Array.isArray(res) ? res.find((c: any) => c.code.toUpperCase() === code) : null;
|
||||||
|
if (matched && matched.is_active) {
|
||||||
|
if (matched.min_order_amount && billBreakdown.grossSubtotal < matched.min_order_amount) {
|
||||||
|
toast.error(`Minimum order amount for this coupon is ₹${matched.min_order_amount}`);
|
||||||
|
setCouponApplying(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setPosAppliedCoupon(matched);
|
||||||
|
setPosDiscountType('COUPON');
|
||||||
|
toast.success(`Coupon ${code} applied successfully!`);
|
||||||
|
} else {
|
||||||
|
toast.error(`Invalid or inactive coupon code: ${code}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
toast.error(err.message || 'Failed to validate coupon code');
|
||||||
|
} finally {
|
||||||
|
setCouponApplying(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const handleCreateOrderSubmit = async (e: React.FormEvent) => {
|
const handleCreateOrderSubmit = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
let finalOrderItems = [...selectedItems];
|
let finalOrderItems = [...selectedItems];
|
||||||
|
|
@ -427,6 +526,21 @@ export default function OrderIntelligencePage() {
|
||||||
const digitalAmt = calculatedDigitalAmount;
|
const digitalAmt = calculatedDigitalAmount;
|
||||||
const requiresDigitalRzp = (paymentMethod === 'UPI' || paymentMethod === 'CARD' || paymentMethod === 'MIXED_PAYMENT') && digitalAmt > 0;
|
const requiresDigitalRzp = (paymentMethod === 'UPI' || paymentMethod === 'CARD' || paymentMethod === 'MIXED_PAYMENT') && digitalAmt > 0;
|
||||||
|
|
||||||
|
const discountPayload = {
|
||||||
|
discount_amount: billBreakdown.discountAmt,
|
||||||
|
discount_type:
|
||||||
|
posDiscountType === 'COUPON' && posAppliedCoupon
|
||||||
|
? posAppliedCoupon.discount_type
|
||||||
|
: posDiscountType !== 'NONE'
|
||||||
|
? posDiscountType
|
||||||
|
: 'FIXED',
|
||||||
|
discount_reason:
|
||||||
|
posDiscountType === 'COUPON' && posAppliedCoupon
|
||||||
|
? `Coupon: ${posAppliedCoupon.code}`
|
||||||
|
: posDiscountReason || (billBreakdown.discountAmt > 0 ? 'POS Counter Discount' : undefined),
|
||||||
|
coupon_code: posDiscountType === 'COUPON' && posAppliedCoupon ? posAppliedCoupon.code : undefined,
|
||||||
|
};
|
||||||
|
|
||||||
if (requiresDigitalRzp) {
|
if (requiresDigitalRzp) {
|
||||||
const loaded = await loadRazorpayScript();
|
const loaded = await loadRazorpayScript();
|
||||||
if (!loaded) {
|
if (!loaded) {
|
||||||
|
|
@ -477,6 +591,7 @@ export default function OrderIntelligencePage() {
|
||||||
razorpay_payment_id: response.razorpay_payment_id,
|
razorpay_payment_id: response.razorpay_payment_id,
|
||||||
razorpay_signature: response.razorpay_signature,
|
razorpay_signature: response.razorpay_signature,
|
||||||
notification_channel: notificationChannel,
|
notification_channel: notificationChannel,
|
||||||
|
...discountPayload,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -518,9 +633,10 @@ export default function OrderIntelligencePage() {
|
||||||
shipping_address: shippingAddress || undefined,
|
shipping_address: shippingAddress || undefined,
|
||||||
payment_status: paymentStatus,
|
payment_status: paymentStatus,
|
||||||
payment_method: paymentMethod,
|
payment_method: paymentMethod,
|
||||||
cash_amount: calculateOrderTotalWithTax,
|
cash_amount: billBreakdown.netPayable,
|
||||||
digital_amount: 0,
|
digital_amount: 0,
|
||||||
notification_channel: notificationChannel,
|
notification_channel: notificationChannel,
|
||||||
|
...discountPayload,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -552,6 +668,11 @@ export default function OrderIntelligencePage() {
|
||||||
setCashPaidAmount(0);
|
setCashPaidAmount(0);
|
||||||
setNotificationChannel('BOTH');
|
setNotificationChannel('BOTH');
|
||||||
setPosSuccessData(null);
|
setPosSuccessData(null);
|
||||||
|
setPosDiscountType('NONE');
|
||||||
|
setPosDiscountValue(0);
|
||||||
|
setPosDiscountReason('');
|
||||||
|
setPosCouponCode('');
|
||||||
|
setPosAppliedCoupon(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleResetCreateOrderForm = () => {
|
const handleResetCreateOrderForm = () => {
|
||||||
|
|
@ -671,6 +792,7 @@ export default function OrderIntelligencePage() {
|
||||||
const shippedCount = orders.filter((o) => isShippedStatus(o.status)).length;
|
const shippedCount = orders.filter((o) => isShippedStatus(o.status)).length;
|
||||||
const deliveredCount = orders.filter((o) => isDeliveredStatus(o.status)).length;
|
const deliveredCount = orders.filter((o) => isDeliveredStatus(o.status)).length;
|
||||||
const cancelledCount = orders.filter((o) => isCancelledStatus(o.status)).length;
|
const cancelledCount = orders.filter((o) => isCancelledStatus(o.status)).length;
|
||||||
|
const discountedCount = orders.filter((o) => o.is_discounted || (o.discount_amount && o.discount_amount > 0)).length;
|
||||||
|
|
||||||
const filteredOrders = useMemo(() => {
|
const filteredOrders = useMemo(() => {
|
||||||
const q = searchQuery.trim().toLowerCase();
|
const q = searchQuery.trim().toLowerCase();
|
||||||
|
|
@ -681,16 +803,21 @@ export default function OrderIntelligencePage() {
|
||||||
(statusFilter === 'shipped' && isShippedStatus(o.status)) ||
|
(statusFilter === 'shipped' && isShippedStatus(o.status)) ||
|
||||||
(statusFilter === 'delivered' && isDeliveredStatus(o.status)) ||
|
(statusFilter === 'delivered' && isDeliveredStatus(o.status)) ||
|
||||||
(statusFilter === 'cancelled' && isCancelledStatus(o.status));
|
(statusFilter === 'cancelled' && isCancelledStatus(o.status));
|
||||||
|
const discountMatch =
|
||||||
|
discountFilter === 'all' ||
|
||||||
|
(discountFilter === 'discounted' && (o.is_discounted || (o.discount_amount && o.discount_amount > 0))) ||
|
||||||
|
(discountFilter === 'regular' && !(o.is_discounted || (o.discount_amount && o.discount_amount > 0)));
|
||||||
const searchMatch =
|
const searchMatch =
|
||||||
!q ||
|
!q ||
|
||||||
o.order_no.toLowerCase().includes(q) ||
|
o.order_no.toLowerCase().includes(q) ||
|
||||||
(o.customer_email && o.customer_email.toLowerCase().includes(q)) ||
|
(o.customer_email && o.customer_email.toLowerCase().includes(q)) ||
|
||||||
(o.customer_name && o.customer_name.toLowerCase().includes(q)) ||
|
(o.customer_name && o.customer_name.toLowerCase().includes(q)) ||
|
||||||
(o.customer_phone && o.customer_phone.toLowerCase().includes(q)) ||
|
(o.customer_phone && o.customer_phone.toLowerCase().includes(q)) ||
|
||||||
|
(o.coupon_code && o.coupon_code.toLowerCase().includes(q)) ||
|
||||||
o.status.toLowerCase().includes(q);
|
o.status.toLowerCase().includes(q);
|
||||||
return statusMatch && searchMatch;
|
return statusMatch && discountMatch && searchMatch;
|
||||||
});
|
});
|
||||||
}, [orders, searchQuery, statusFilter]);
|
}, [orders, searchQuery, statusFilter, discountFilter]);
|
||||||
|
|
||||||
const pager = useClientPagination(filteredOrders);
|
const pager = useClientPagination(filteredOrders);
|
||||||
|
|
||||||
|
|
@ -765,27 +892,42 @@ export default function OrderIntelligencePage() {
|
||||||
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"
|
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>
|
||||||
<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">
|
<div className="flex flex-wrap items-center gap-2 shrink-0">
|
||||||
{(
|
<button
|
||||||
[
|
type="button"
|
||||||
{ id: 'all', label: `All (${orders.length})` },
|
onClick={() => setDiscountFilter(discountFilter === 'discounted' ? 'all' : 'discounted')}
|
||||||
{ id: 'open', label: `Open (${openCount})` },
|
className={`h-8 px-3 crm-radius-toggle text-[12px] font-semibold cursor-pointer transition-colors inline-flex items-center gap-1.5 ${
|
||||||
{ id: 'shipped', label: `Shipped (${shippedCount})` },
|
discountFilter === 'discounted'
|
||||||
{ id: 'delivered', label: `Delivered (${deliveredCount})` },
|
? 'bg-emerald-600 text-white shadow-sm'
|
||||||
{ id: 'cancelled', label: `Cancelled (${cancelledCount})` },
|
: 'border border-emerald-500/30 bg-emerald-500/10 text-emerald-700 hover:bg-emerald-500/20'
|
||||||
] as { id: StatusFilter; label: string }[]
|
}`}
|
||||||
).map((tab) => (
|
title="Filter discounted orders"
|
||||||
<button
|
>
|
||||||
key={tab.id}
|
<span>🏷️</span>
|
||||||
type="button"
|
<span>Discounted ({discountedCount})</span>
|
||||||
onClick={() => setStatusFilter(tab.id)}
|
</button>
|
||||||
className={`h-8 px-3 crm-radius-toggle text-[13px] font-medium cursor-pointer transition-colors whitespace-nowrap ${
|
<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">
|
||||||
statusFilter === tab.id ? 'bg-primary text-white' : 'text-foreground hover:bg-muted'
|
{(
|
||||||
}`}
|
[
|
||||||
>
|
{ id: 'all', label: `All (${orders.length})` },
|
||||||
{tab.label}
|
{ id: 'open', label: `Open (${openCount})` },
|
||||||
</button>
|
{ id: 'shipped', label: `Shipped (${shippedCount})` },
|
||||||
))}
|
{ id: 'delivered', label: `Delivered (${deliveredCount})` },
|
||||||
|
{ id: 'cancelled', label: `Cancelled (${cancelledCount})` },
|
||||||
|
] as { id: StatusFilter; label: string }[]
|
||||||
|
).map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setStatusFilter(tab.id)}
|
||||||
|
className={`h-8 px-3 crm-radius-toggle text-[13px] font-medium cursor-pointer transition-colors whitespace-nowrap ${
|
||||||
|
statusFilter === tab.id ? 'bg-primary text-white' : 'text-foreground hover:bg-muted'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -835,7 +977,16 @@ export default function OrderIntelligencePage() {
|
||||||
: '—'}
|
: '—'}
|
||||||
</p>
|
</p>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-5 py-3.5 text-[13px] text-muted-foreground">₹{order.final_amount.toFixed(2)}</td>
|
<td className="px-5 py-3.5 text-[13px] text-muted-foreground">
|
||||||
|
<div className="font-semibold text-foreground">₹{order.final_amount.toFixed(2)}</div>
|
||||||
|
{(order.is_discounted || (order.discount_amount && order.discount_amount > 0)) && (
|
||||||
|
<div className="mt-1">
|
||||||
|
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold bg-emerald-500/10 text-emerald-700 border border-emerald-500/25">
|
||||||
|
🏷️ -₹{Number(order.discount_amount || 0).toFixed(0)} {order.coupon_code ? `(${order.coupon_code})` : 'off'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
<td className="px-5 py-3.5 text-[13px] text-muted-foreground">{formatOrderDate(order.created_at)}</td>
|
<td className="px-5 py-3.5 text-[13px] text-muted-foreground">{formatOrderDate(order.created_at)}</td>
|
||||||
<td className="px-5 py-3.5">{renderStatusBadge(order.status)}</td>
|
<td className="px-5 py-3.5">{renderStatusBadge(order.status)}</td>
|
||||||
<td className="px-5 py-3.5">
|
<td className="px-5 py-3.5">
|
||||||
|
|
@ -893,6 +1044,11 @@ export default function OrderIntelligencePage() {
|
||||||
>
|
>
|
||||||
{(detailData.payment_status || 'UNPAID').replace('_', ' ')}
|
{(detailData.payment_status || 'UNPAID').replace('_', ' ')}
|
||||||
</span>
|
</span>
|
||||||
|
{detailData.is_discounted && (
|
||||||
|
<span className="inline-flex items-center px-2.5 py-1 crm-radius-badge text-[11px] font-semibold bg-emerald-500/10 text-emerald-700 border border-emerald-500/25">
|
||||||
|
🏷️ Discounted Order
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{!showStatusForm && (
|
{!showStatusForm && (
|
||||||
|
|
@ -927,8 +1083,10 @@ export default function OrderIntelligencePage() {
|
||||||
<span>₹{detailData.total_amount.toFixed(2)}</span>
|
<span>₹{detailData.total_amount.toFixed(2)}</span>
|
||||||
</div>
|
</div>
|
||||||
{detailData.discount_amount > 0 && (
|
{detailData.discount_amount > 0 && (
|
||||||
<div className="flex justify-between text-success">
|
<div className="flex justify-between text-emerald-600 font-medium">
|
||||||
<span>Discount</span>
|
<span>
|
||||||
|
Discount {detailData.coupon_code ? `(${detailData.coupon_code})` : detailData.discount_reason ? `(${detailData.discount_reason})` : ''}
|
||||||
|
</span>
|
||||||
<span>-₹{detailData.discount_amount.toFixed(2)}</span>
|
<span>-₹{detailData.discount_amount.toFixed(2)}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
@ -1363,6 +1521,277 @@ export default function OrderIntelligencePage() {
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* --- 1. TRADE DISCOUNT & PROMO CODE ENGINE --- */}
|
||||||
|
<div className="p-4 border border-border crm-radius-card bg-muted/20 space-y-3">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<p className="text-[11px] font-semibold text-muted-foreground uppercase flex items-center gap-1.5">
|
||||||
|
<span>🏷️</span>
|
||||||
|
<span>Discounts & Promotions</span>
|
||||||
|
</p>
|
||||||
|
{billBreakdown.discountAmt > 0 && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-bold bg-emerald-500/15 text-emerald-600 border border-emerald-500/30">
|
||||||
|
Saving ₹{billBreakdown.discountAmt.toFixed(2)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Discount Mode Tabs */}
|
||||||
|
<div className="grid grid-cols-4 gap-1 p-1 bg-muted/40 rounded-lg border border-border text-[11px] font-medium">
|
||||||
|
{[
|
||||||
|
{ id: 'NONE', label: 'None' },
|
||||||
|
{ id: 'FIXED', label: 'Flat (₹)' },
|
||||||
|
{ id: 'PERCENT', label: 'Percent (%)' },
|
||||||
|
{ id: 'COUPON', label: 'Coupon' },
|
||||||
|
].map((t) => (
|
||||||
|
<button
|
||||||
|
key={t.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setPosDiscountType(t.id as any);
|
||||||
|
if (t.id === 'NONE') {
|
||||||
|
setPosDiscountValue(0);
|
||||||
|
setPosAppliedCoupon(null);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`py-1.5 px-2 rounded font-semibold cursor-pointer transition-colors text-center ${
|
||||||
|
posDiscountType === t.id
|
||||||
|
? 'bg-primary text-white shadow-xs'
|
||||||
|
: 'text-muted-foreground hover:text-foreground'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{t.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Flat Amount Inputs */}
|
||||||
|
{posDiscountType === 'FIXED' && (
|
||||||
|
<div className="space-y-2 pt-1">
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<label className={labelClass}>Discount Amount (₹)</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={billBreakdown.grossSubtotal}
|
||||||
|
step="1"
|
||||||
|
value={posDiscountValue || ''}
|
||||||
|
onChange={(e) => setPosDiscountValue(Math.max(0, Number(e.target.value)))}
|
||||||
|
placeholder="e.g. 100"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelClass}>Reason / Note</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={posDiscountReason}
|
||||||
|
onChange={(e) => setPosDiscountReason(e.target.value)}
|
||||||
|
placeholder="e.g. Walk-in courtesy discount"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* Quick Presets */}
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5 pt-0.5">
|
||||||
|
<span className="text-[10px] text-muted-foreground font-semibold uppercase">Presets:</span>
|
||||||
|
{[50, 100, 200, 500].map((preset) => (
|
||||||
|
<button
|
||||||
|
key={preset}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPosDiscountValue(preset)}
|
||||||
|
className="px-2 py-0.5 text-[11px] font-semibold crm-radius-control border border-border bg-card hover:bg-muted text-foreground cursor-pointer"
|
||||||
|
>
|
||||||
|
₹{preset}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Percentage Inputs */}
|
||||||
|
{posDiscountType === 'PERCENT' && (
|
||||||
|
<div className="space-y-2 pt-1">
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<label className={labelClass}>Discount Percentage (%)</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={100}
|
||||||
|
step="0.5"
|
||||||
|
value={posDiscountValue || ''}
|
||||||
|
onChange={(e) => setPosDiscountValue(Math.min(100, Math.max(0, Number(e.target.value))))}
|
||||||
|
placeholder="e.g. 10"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelClass}>Reason / Note</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={posDiscountReason}
|
||||||
|
onChange={(e) => setPosDiscountReason(e.target.value)}
|
||||||
|
placeholder="e.g. Festive seasonal offer"
|
||||||
|
className={inputClass}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* Quick Presets */}
|
||||||
|
<div className="flex flex-wrap items-center gap-1.5 pt-0.5">
|
||||||
|
<span className="text-[10px] text-muted-foreground font-semibold uppercase">Presets:</span>
|
||||||
|
{[5, 10, 15, 20, 25].map((preset) => (
|
||||||
|
<button
|
||||||
|
key={preset}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPosDiscountValue(preset)}
|
||||||
|
className="px-2 py-0.5 text-[11px] font-semibold crm-radius-control border border-border bg-card hover:bg-muted text-foreground cursor-pointer"
|
||||||
|
>
|
||||||
|
{preset}%
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Coupon Code Input & Selector */}
|
||||||
|
{posDiscountType === 'COUPON' && (
|
||||||
|
<div className="space-y-2 pt-1">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={posCouponCode}
|
||||||
|
onChange={(e) => setPosCouponCode(e.target.value.toUpperCase())}
|
||||||
|
placeholder="ENTER COUPON CODE"
|
||||||
|
className={`${inputClass} font-mono uppercase tracking-wider`}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handleApplyPosCoupon}
|
||||||
|
disabled={couponApplying || !posCouponCode.trim()}
|
||||||
|
className={`${primaryButton} shrink-0 px-3`}
|
||||||
|
>
|
||||||
|
{couponApplying ? 'Checking...' : 'Apply'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{posAppliedCoupon && (
|
||||||
|
<div className="p-2.5 rounded border border-emerald-500/30 bg-emerald-500/10 flex items-center justify-between text-[12px]">
|
||||||
|
<div>
|
||||||
|
<p className="font-bold text-emerald-800 font-mono">
|
||||||
|
🏷️ {posAppliedCoupon.code}
|
||||||
|
</p>
|
||||||
|
<p className="text-[11px] text-emerald-700">
|
||||||
|
{posAppliedCoupon.discount_type === 'PERCENT'
|
||||||
|
? `${posAppliedCoupon.discount_value}% OFF`
|
||||||
|
: `₹${posAppliedCoupon.discount_value} FLAT OFF`}
|
||||||
|
{posAppliedCoupon.max_discount_cap ? ` (Capped at ₹${posAppliedCoupon.max_discount_cap})` : ''}
|
||||||
|
{posAppliedCoupon.first_order_only ? ' · 1st Order Rule' : ''}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setPosAppliedCoupon(null);
|
||||||
|
setPosCouponCode('');
|
||||||
|
toast.info('Coupon removed');
|
||||||
|
}}
|
||||||
|
className="text-[11px] font-semibold text-destructive hover:underline cursor-pointer"
|
||||||
|
>
|
||||||
|
Remove
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{posCouponsList.length > 0 && !posAppliedCoupon && (
|
||||||
|
<div className="pt-1">
|
||||||
|
<label className="block text-[10px] font-semibold text-muted-foreground uppercase mb-1">
|
||||||
|
Or select available promotional coupon:
|
||||||
|
</label>
|
||||||
|
<CustomSelect
|
||||||
|
value={posCouponCode}
|
||||||
|
onChange={(val) => {
|
||||||
|
setPosCouponCode(val);
|
||||||
|
const found = posCouponsList.find((c) => c.code === val);
|
||||||
|
if (found) {
|
||||||
|
setPosAppliedCoupon(found);
|
||||||
|
toast.success(`Coupon ${found.code} selected!`);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
options={[
|
||||||
|
{ value: '', label: 'Select available coupon' },
|
||||||
|
...posCouponsList.map((c) => ({
|
||||||
|
value: c.code,
|
||||||
|
label: `${c.code} (${c.discount_type === 'PERCENT' ? `${c.discount_value}%` : `₹${c.discount_value}`} off${c.first_order_only ? ' - 1st order' : ''})`,
|
||||||
|
})),
|
||||||
|
]}
|
||||||
|
placeholder="Select available coupon"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* --- 2. REAL-TIME POINT-OF-SALE BILL COUNTER / TAX LEDGER --- */}
|
||||||
|
<div className="p-4 border-2 border-primary/20 bg-primary/5 crm-radius-card space-y-2.5">
|
||||||
|
<div className="flex items-center justify-between border-b border-primary/15 pb-2">
|
||||||
|
<div className="flex items-center gap-1.5 text-[12px] font-bold text-foreground uppercase tracking-wide">
|
||||||
|
<span>🧾</span>
|
||||||
|
<span>POS Real-Time Bill Counter</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-[11px] font-mono text-muted-foreground">
|
||||||
|
{effectiveItems.length} {effectiveItems.length === 1 ? 'item' : 'items'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5 text-[12px]">
|
||||||
|
<div className="flex justify-between text-muted-foreground">
|
||||||
|
<span>Gross Subtotal</span>
|
||||||
|
<span className="font-mono text-foreground">₹{billBreakdown.grossSubtotal.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{billBreakdown.discountAmt > 0 && (
|
||||||
|
<div className="flex justify-between text-emerald-600 font-semibold">
|
||||||
|
<span className="flex items-center gap-1">
|
||||||
|
<span>Trade Discount</span>
|
||||||
|
{posDiscountType === 'COUPON' && posAppliedCoupon && (
|
||||||
|
<span className="text-[10px] px-1 py-0.2 bg-emerald-500/20 rounded">
|
||||||
|
{posAppliedCoupon.code}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<span className="font-mono">-₹{billBreakdown.discountAmt.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex justify-between text-muted-foreground pt-1 border-t border-border/60">
|
||||||
|
<span>Net Taxable Base</span>
|
||||||
|
<span className="font-mono">₹{billBreakdown.taxableBase.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-between text-muted-foreground text-[11px]">
|
||||||
|
<span className="pl-2">Central GST (9% CGST)</span>
|
||||||
|
<span className="font-mono">₹{billBreakdown.cgst.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-between text-muted-foreground text-[11px]">
|
||||||
|
<span className="pl-2">State GST (9% SGST)</span>
|
||||||
|
<span className="font-mono">₹{billBreakdown.sgst.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-between text-muted-foreground text-[11px]">
|
||||||
|
<span className="font-medium">Total 18% GST (Included)</span>
|
||||||
|
<span className="font-mono">₹{billBreakdown.totalTax.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-between font-bold text-foreground border-t-2 border-primary/30 pt-2 text-[15px]">
|
||||||
|
<span className="tracking-tight text-primary">NET PAYABLE (GRAND TOTAL)</span>
|
||||||
|
<span className="font-mono text-lg text-primary">₹{billBreakdown.netPayable.toFixed(2)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
<p className="text-[11px] font-semibold text-muted-foreground uppercase">Payment</p>
|
<p className="text-[11px] font-semibold text-muted-foreground uppercase">Payment</p>
|
||||||
<div>
|
<div>
|
||||||
|
|
|
||||||
|
|
@ -1197,7 +1197,8 @@ export default function ProductsPage() {
|
||||||
};
|
};
|
||||||
|
|
||||||
const renderProductAvatar = (p: ProductResponse) => {
|
const renderProductAvatar = (p: ProductResponse) => {
|
||||||
const imgUrl = getMediaUrl(p.images?.[0]?.image_url);
|
const rawUrl = p.images?.[0]?.image_url || (p as any).thumbnail_url || p.variants?.[0]?.images?.[0]?.image_url;
|
||||||
|
const imgUrl = getMediaUrl(rawUrl);
|
||||||
return (
|
return (
|
||||||
<div className="w-9 h-9 crm-radius-icon bg-primary/10 text-primary flex items-center justify-center shrink-0 overflow-hidden">
|
<div className="w-9 h-9 crm-radius-icon bg-primary/10 text-primary flex items-center justify-center shrink-0 overflow-hidden">
|
||||||
{imgUrl ? (
|
{imgUrl ? (
|
||||||
|
|
@ -1959,9 +1960,9 @@ export default function ProductsPage() {
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-start gap-3 pr-8 min-w-0">
|
<div className="flex items-start gap-3 pr-8 min-w-0">
|
||||||
<div className="w-10 h-10 crm-radius-icon bg-primary/10 text-primary flex items-center justify-center shrink-0 overflow-hidden">
|
<div className="w-10 h-10 crm-radius-icon bg-primary/10 text-primary flex items-center justify-center shrink-0 overflow-hidden">
|
||||||
{p.images?.[0]?.image_url ? (
|
{(p.images?.[0]?.image_url || (p as any).thumbnail_url || p.variants?.[0]?.images?.[0]?.image_url) ? (
|
||||||
<img
|
<img
|
||||||
src={getMediaUrl(p.images[0].image_url)}
|
src={getMediaUrl(p.images?.[0]?.image_url || (p as any).thumbnail_url || p.variants?.[0]?.images?.[0]?.image_url)}
|
||||||
alt={p.name}
|
alt={p.name}
|
||||||
className="w-full h-full object-contain p-0.5"
|
className="w-full h-full object-contain p-0.5"
|
||||||
onError={(e) => { e.currentTarget.style.display = 'none'; }}
|
onError={(e) => { e.currentTarget.style.display = 'none'; }}
|
||||||
|
|
|
||||||
|
|
@ -82,6 +82,7 @@ const NAV_GROUPS: NavGroup[] = [
|
||||||
name: 'Marketing',
|
name: 'Marketing',
|
||||||
icon: Megaphone,
|
icon: Megaphone,
|
||||||
children: [
|
children: [
|
||||||
|
{ name: 'Coupons & Discounts', href: '/coupons' },
|
||||||
{ name: 'Google Merchant Center', href: '/merchant-center' },
|
{ name: 'Google Merchant Center', href: '/merchant-center' },
|
||||||
{ name: 'Social Media Publisher', href: '/social-media' },
|
{ name: 'Social Media Publisher', href: '/social-media' },
|
||||||
{ name: 'Google Analytics GA4', href: '/analytics/google' },
|
{ name: 'Google Analytics GA4', href: '/analytics/google' },
|
||||||
|
|
|
||||||
|
|
@ -57,6 +57,7 @@ export function isRouteAllowed(pathname: string, userRole?: string | null): bool
|
||||||
) return true;
|
) return true;
|
||||||
if (
|
if (
|
||||||
pathname.startsWith('/orders') ||
|
pathname.startsWith('/orders') ||
|
||||||
|
pathname.startsWith('/coupons') ||
|
||||||
pathname.startsWith('/invoices') ||
|
pathname.startsWith('/invoices') ||
|
||||||
pathname.startsWith('/warranties') ||
|
pathname.startsWith('/warranties') ||
|
||||||
pathname.startsWith('/refunds') ||
|
pathname.startsWith('/refunds') ||
|
||||||
|
|
@ -98,6 +99,7 @@ export function isRouteAllowed(pathname: string, userRole?: string | null): bool
|
||||||
) return true;
|
) return true;
|
||||||
if (
|
if (
|
||||||
pathname.startsWith('/orders') ||
|
pathname.startsWith('/orders') ||
|
||||||
|
pathname.startsWith('/coupons') ||
|
||||||
pathname.startsWith('/invoices') ||
|
pathname.startsWith('/invoices') ||
|
||||||
pathname.startsWith('/bulk-quotations')
|
pathname.startsWith('/bulk-quotations')
|
||||||
) return true;
|
) return true;
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue