diff --git a/app/(admin)/coupons/page.tsx b/app/(admin)/coupons/page.tsx
new file mode 100644
index 0000000..98b22f5
--- /dev/null
+++ b/app/(admin)/coupons/page.tsx
@@ -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([]);
+ const [loading, setLoading] = useState(true);
+ const [searchQuery, setSearchQuery] = useState('');
+ const [activeTab, setActiveTab] = useState('all');
+
+ // SlideOver form state
+ const [showFormModal, setShowFormModal] = useState(false);
+ const [editingCouponId, setEditingCouponId] = useState(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(10);
+ const [minOrderAmount, setMinOrderAmount] = useState(0);
+ const [maxDiscountCap, setMaxDiscountCap] = useState('');
+ const [firstOrderOnly, setFirstOrderOnly] = useState(false);
+ const [channelScope, setChannelScope] = useState<'ALL' | 'STOREFRONT' | 'STORE_POS'>('ALL');
+ const [usageLimitTotal, setUsageLimitTotal] = useState('');
+ const [usageLimitPerCustomer, setUsageLimitPerCustomer] = useState(1);
+ const [startDate, setStartDate] = useState('');
+ const [endDate, setEndDate] = useState('');
+ const [isActive, setIsActive] = useState(true);
+
+ // Usage Audit Drawer state
+ const [inspectCoupon, setInspectCoupon] = useState(null);
+ const [usagesList, setUsagesList] = useState([]);
+ const [usagesLoading, setUsagesLoading] = useState(false);
+ const [totalDiscountGiven, setTotalDiscountGiven] = useState(0);
+
+ const fetchCoupons = async () => {
+ setLoading(true);
+ try {
+ const data = await apiFetch('/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(`/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(`/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 (
+
+ {/* Page Header */}
+
+
+
+
Promotions & Coupon Rules
+
+ {coupons.length}
+
+
+
+ Create rule-driven coupon codes, first-time customer checkout discounts, and walk-in POS counter promotions.
+
+
+
+
+
+
+
+
+
+ {/* Main Container */}
+
+
+
+
+
+ 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"
+ />
+
+
+
+ {(
+ [
+ { 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) => (
+
+ ))}
+
+
+
+
+ {loading ? (
+
+
+ Loading coupons...
+
+ ) : (
+
+
+
+
+ | Coupon code |
+ Discount rule |
+ Channel & Limits |
+ Redemptions |
+ Status |
+ Action |
+
+
+
+ {filteredCoupons.length === 0 ? (
+
+ |
+ {searchQuery || activeTab !== 'all' ? 'No coupons match your filter.' : 'No promotional coupons found.'}
+ |
+
+ ) : (
+ pager.items.map((coupon) => (
+
+ |
+
+
+ {coupon.code}
+
+
+
+ {coupon.description && (
+
+ {coupon.description}
+
+ )}
+ {coupon.first_order_only && (
+
+
+ ⭐ 1st Order Customer Only
+
+
+ )}
+ |
+
+
+
+ {coupon.discount_type === 'PERCENT'
+ ? `${coupon.discount_value}% OFF`
+ : `₹${coupon.discount_value.toFixed(2)} FLAT OFF`}
+
+
+ {coupon.max_discount_cap && (
+ Max discount: ₹{coupon.max_discount_cap}
+ )}
+ Min order: ₹{coupon.min_order_amount || 0}
+
+ |
+
+
+
+ {coupon.channel_scope === 'ALL'
+ ? '🌐 Global Omnichannel'
+ : coupon.channel_scope === 'STOREFRONT'
+ ? '💻 Storefront Online'
+ : '🏬 Walk-in POS'}
+
+
+ Limit per user: {coupon.usage_limit_per_customer || 1}
+
+ |
+
+
+
+ {coupon.usage_limit_total && (
+
+ Max {coupon.usage_limit_total} total
+
+ )}
+ |
+
+
+
+ |
+
+
+
+
+
+
+ |
+
+ ))
+ )}
+
+
+
+ )}
+
+
+
+ {/* SlideOver for Create / Edit Coupon */}
+
setShowFormModal(false)}
+ title={editingCouponId ? `Edit Coupon ${code}` : 'Create Promotional Coupon'}
+ icon={}
+ >
+
+
+
+ {/* SlideOver for Redemption Audits */}
+
setInspectCoupon(null)}
+ title={inspectCoupon ? `Redemptions for ${inspectCoupon.code}` : 'Coupon Usages'}
+ icon={}
+ >
+
+
+
+
+
{inspectCoupon?.code}
+
Total Redemptions: {usagesList.length}
+
+
+
Total Savings
+
₹{totalDiscountGiven.toFixed(2)}
+
+
+
+ {usagesLoading ? (
+
+
+ Loading audit log...
+
+ ) : usagesList.length === 0 ? (
+
+ No redemptions recorded for this coupon yet.
+
+ ) : (
+
+ {usagesList.map((usage) => (
+
+
+ Order ID: {usage.order_id}
+ -₹{Number(usage.discount_amount).toFixed(2)}
+
+
+ Customer: {usage.customer_id}
+ {usage.used_at ? format(new Date(usage.used_at), 'dd-MMM-yyyy HH:mm') : '—'}
+
+
+ ))}
+
+ )}
+
+
+
+
+ );
+}
diff --git a/app/(admin)/orders/page.tsx b/app/(admin)/orders/page.tsx
index 19e3189..e6d0aa7 100644
--- a/app/(admin)/orders/page.tsx
+++ b/app/(admin)/orders/page.tsx
@@ -50,6 +50,10 @@ interface AdminOrderDetailResponse {
customer_name: string | null;
total_amount: number;
discount_amount: number;
+ is_discounted?: boolean;
+ discount_type?: string | null;
+ discount_reason?: string | null;
+ coupon_code?: string | null;
tax_amount: number;
shipping_cost: number;
final_amount: number;
@@ -105,12 +109,17 @@ interface AdminOrderListResponse {
customer_name?: string | null;
customer_phone?: string | null;
final_amount: number;
+ discount_amount?: number;
+ is_discounted?: boolean;
+ discount_type?: string | null;
+ coupon_code?: string | null;
status: string;
payment_status: string;
created_at: string;
}
type StatusFilter = 'all' | 'open' | 'shipped' | 'delivered' | 'cancelled';
+type DiscountFilter = 'all' | 'discounted' | 'regular';
function formatOrderDate(iso: string) {
const normalized = iso.endsWith('Z') || iso.includes('+') ? iso : `${iso}Z`;
@@ -153,6 +162,7 @@ export default function OrderIntelligencePage() {
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [statusFilter, setStatusFilter] = useState('all');
+ const [discountFilter, setDiscountFilter] = useState('all');
const [selectedOrderId, setSelectedOrderId] = useState(null);
const [detailData, setDetailData] = useState(null);
@@ -191,6 +201,15 @@ export default function OrderIntelligencePage() {
const [notificationChannel, setNotificationChannel] = useState<'BOTH' | 'WHATSAPP' | 'EMAIL'>('BOTH');
const [posSuccessData, setPosSuccessData] = useState(null);
+ // --- Real-time POS Billing Discount & Coupon States ---
+ const [posDiscountType, setPosDiscountType] = useState<'NONE' | 'FIXED' | 'PERCENT' | 'COUPON'>('NONE');
+ const [posDiscountValue, setPosDiscountValue] = useState(0);
+ const [posDiscountReason, setPosDiscountReason] = useState('');
+ const [posCouponCode, setPosCouponCode] = useState('');
+ const [posAppliedCoupon, setPosAppliedCoupon] = useState(null);
+ const [posCouponsList, setPosCouponsList] = useState([]);
+ const [couponApplying, setCouponApplying] = useState(false);
+
const effectiveItems = useMemo(() => {
if (selectedItems.length > 0) return selectedItems;
if (selectedProductId && tempSkuId) {
@@ -211,21 +230,55 @@ export default function OrderIntelligencePage() {
return [];
}, [selectedItems, selectedProductId, tempSkuId, skuOptions, tempQty, tempPrice, productsList]);
- const calculateOrderTotalWithTax = useMemo(() => {
- const subtotal = effectiveItems.reduce((acc, item) => acc + item.quantity * item.unit_price, 0);
- const tax = (subtotal * 18) / 100;
- return subtotal + tax;
- }, [effectiveItems]);
+ // --- Real-Time Point-of-Sale Billing Counter Ledger ---
+ const billBreakdown = useMemo(() => {
+ const grossSubtotal = effectiveItems.reduce((acc, item) => acc + item.quantity * item.unit_price, 0);
+ let discountAmt = 0;
+
+ 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(() => {
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') {
- return calculateOrderTotalWithTax;
+ return billBreakdown.netPayable;
}
return 0;
- }, [paymentMethod, calculateOrderTotalWithTax, cashPaidAmount]);
+ }, [paymentMethod, billBreakdown.netPayable, cashPaidAmount]);
const loadRazorpayScript = (): Promise => {
return new Promise((resolve) => {
@@ -244,13 +297,18 @@ export default function OrderIntelligencePage() {
const fetchCatalogProductsAndSkus = async () => {
setSkuLoading(true);
try {
- const [catRes, skuRes, categoriesRes, brandsRes] = await Promise.all([
+ const [catRes, skuRes, categoriesRes, brandsRes, couponsRes] = await Promise.all([
apiFetch('/api/v1/catalog/products/all?limit=200').catch(() => []),
apiFetch<{ items: any[] }>('/api/v1/inventory/skus?limit=150').catch(() => ({ items: [] })),
apiFetch('/api/v1/catalog/categories/all').catch(() => []),
apiFetch('/api/v1/catalog/brands/all').catch(() => []),
+ apiFetch('/api/v1/admin/coupons?is_active=true').catch(() => []),
]);
+ if (Array.isArray(couponsRes)) {
+ setPosCouponsList(couponsRes);
+ }
+
const prodsList = Array.isArray(catRes) ? catRes : catRes?.products || [];
setProductsList(prodsList);
@@ -394,6 +452,47 @@ export default function OrderIntelligencePage() {
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(`/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) => {
e.preventDefault();
let finalOrderItems = [...selectedItems];
@@ -427,6 +526,21 @@ export default function OrderIntelligencePage() {
const digitalAmt = calculatedDigitalAmount;
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) {
const loaded = await loadRazorpayScript();
if (!loaded) {
@@ -477,6 +591,7 @@ export default function OrderIntelligencePage() {
razorpay_payment_id: response.razorpay_payment_id,
razorpay_signature: response.razorpay_signature,
notification_channel: notificationChannel,
+ ...discountPayload,
}),
});
@@ -518,9 +633,10 @@ export default function OrderIntelligencePage() {
shipping_address: shippingAddress || undefined,
payment_status: paymentStatus,
payment_method: paymentMethod,
- cash_amount: calculateOrderTotalWithTax,
+ cash_amount: billBreakdown.netPayable,
digital_amount: 0,
notification_channel: notificationChannel,
+ ...discountPayload,
}),
});
@@ -552,6 +668,11 @@ export default function OrderIntelligencePage() {
setCashPaidAmount(0);
setNotificationChannel('BOTH');
setPosSuccessData(null);
+ setPosDiscountType('NONE');
+ setPosDiscountValue(0);
+ setPosDiscountReason('');
+ setPosCouponCode('');
+ setPosAppliedCoupon(null);
};
const handleResetCreateOrderForm = () => {
@@ -671,6 +792,7 @@ export default function OrderIntelligencePage() {
const shippedCount = orders.filter((o) => isShippedStatus(o.status)).length;
const deliveredCount = orders.filter((o) => isDeliveredStatus(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 q = searchQuery.trim().toLowerCase();
@@ -681,16 +803,21 @@ export default function OrderIntelligencePage() {
(statusFilter === 'shipped' && isShippedStatus(o.status)) ||
(statusFilter === 'delivered' && isDeliveredStatus(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 =
!q ||
o.order_no.toLowerCase().includes(q) ||
(o.customer_email && o.customer_email.toLowerCase().includes(q)) ||
(o.customer_name && o.customer_name.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);
- return statusMatch && searchMatch;
+ return statusMatch && discountMatch && searchMatch;
});
- }, [orders, searchQuery, statusFilter]);
+ }, [orders, searchQuery, statusFilter, discountFilter]);
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"
/>
-
- {(
- [
- { id: 'all', label: `All (${orders.length})` },
- { id: 'open', label: `Open (${openCount})` },
- { id: 'shipped', label: `Shipped (${shippedCount})` },
- { id: 'delivered', label: `Delivered (${deliveredCount})` },
- { id: 'cancelled', label: `Cancelled (${cancelledCount})` },
- ] as { id: StatusFilter; label: string }[]
- ).map((tab) => (
-
- ))}
+
+
+
+ {(
+ [
+ { id: 'all', label: `All (${orders.length})` },
+ { id: 'open', label: `Open (${openCount})` },
+ { id: 'shipped', label: `Shipped (${shippedCount})` },
+ { id: 'delivered', label: `Delivered (${deliveredCount})` },
+ { id: 'cancelled', label: `Cancelled (${cancelledCount})` },
+ ] as { id: StatusFilter; label: string }[]
+ ).map((tab) => (
+
+ ))}
+
@@ -835,7 +977,16 @@ export default function OrderIntelligencePage() {
: '—'}
- ₹{order.final_amount.toFixed(2)} |
+
+ ₹{order.final_amount.toFixed(2)}
+ {(order.is_discounted || (order.discount_amount && order.discount_amount > 0)) && (
+
+
+ 🏷️ -₹{Number(order.discount_amount || 0).toFixed(0)} {order.coupon_code ? `(${order.coupon_code})` : 'off'}
+
+
+ )}
+ |
{formatOrderDate(order.created_at)} |
{renderStatusBadge(order.status)} |
@@ -893,6 +1044,11 @@ export default function OrderIntelligencePage() {
>
{(detailData.payment_status || 'UNPAID').replace('_', ' ')}
+ {detailData.is_discounted && (
+
+ 🏷️ Discounted Order
+
+ )}
{!showStatusForm && (
@@ -927,8 +1083,10 @@ export default function OrderIntelligencePage() {
₹{detailData.total_amount.toFixed(2)}
{detailData.discount_amount > 0 && (
-
- Discount
+
+
+ Discount {detailData.coupon_code ? `(${detailData.coupon_code})` : detailData.discount_reason ? `(${detailData.discount_reason})` : ''}
+
-₹{detailData.discount_amount.toFixed(2)}
)}
@@ -1363,6 +1521,277 @@ export default function OrderIntelligencePage() {
)}
+ {/* --- 1. TRADE DISCOUNT & PROMO CODE ENGINE --- */}
+
+
+
+ 🏷️
+ Discounts & Promotions
+
+ {billBreakdown.discountAmt > 0 && (
+
+ Saving ₹{billBreakdown.discountAmt.toFixed(2)}
+
+ )}
+
+
+ {/* Discount Mode Tabs */}
+
+ {[
+ { id: 'NONE', label: 'None' },
+ { id: 'FIXED', label: 'Flat (₹)' },
+ { id: 'PERCENT', label: 'Percent (%)' },
+ { id: 'COUPON', label: 'Coupon' },
+ ].map((t) => (
+
+ ))}
+
+
+ {/* Flat Amount Inputs */}
+ {posDiscountType === 'FIXED' && (
+
+
+ {/* Quick Presets */}
+
+ Presets:
+ {[50, 100, 200, 500].map((preset) => (
+
+ ))}
+
+
+ )}
+
+ {/* Percentage Inputs */}
+ {posDiscountType === 'PERCENT' && (
+
+
+ {/* Quick Presets */}
+
+ Presets:
+ {[5, 10, 15, 20, 25].map((preset) => (
+
+ ))}
+
+
+ )}
+
+ {/* Coupon Code Input & Selector */}
+ {posDiscountType === 'COUPON' && (
+
+
+ setPosCouponCode(e.target.value.toUpperCase())}
+ placeholder="ENTER COUPON CODE"
+ className={`${inputClass} font-mono uppercase tracking-wider`}
+ />
+
+
+
+ {posAppliedCoupon && (
+
+
+
+ 🏷️ {posAppliedCoupon.code}
+
+
+ {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' : ''}
+
+
+
+
+ )}
+
+ {posCouponsList.length > 0 && !posAppliedCoupon && (
+
+
+ {
+ 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"
+ />
+
+ )}
+
+ )}
+
+
+ {/* --- 2. REAL-TIME POINT-OF-SALE BILL COUNTER / TAX LEDGER --- */}
+
+
+
+ 🧾
+ POS Real-Time Bill Counter
+
+
+ {effectiveItems.length} {effectiveItems.length === 1 ? 'item' : 'items'}
+
+
+
+
+
+ Gross Subtotal
+ ₹{billBreakdown.grossSubtotal.toFixed(2)}
+
+
+ {billBreakdown.discountAmt > 0 && (
+
+
+ Trade Discount
+ {posDiscountType === 'COUPON' && posAppliedCoupon && (
+
+ {posAppliedCoupon.code}
+
+ )}
+
+ -₹{billBreakdown.discountAmt.toFixed(2)}
+
+ )}
+
+
+ Net Taxable Base
+ ₹{billBreakdown.taxableBase.toFixed(2)}
+
+
+
+ Central GST (9% CGST)
+ ₹{billBreakdown.cgst.toFixed(2)}
+
+
+
+ State GST (9% SGST)
+ ₹{billBreakdown.sgst.toFixed(2)}
+
+
+
+ Total 18% GST (Included)
+ ₹{billBreakdown.totalTax.toFixed(2)}
+
+
+
+ NET PAYABLE (GRAND TOTAL)
+ ₹{billBreakdown.netPayable.toFixed(2)}
+
+
+
+
Payment
diff --git a/app/(admin)/products/(list)/page.tsx b/app/(admin)/products/(list)/page.tsx
index 7c18883..48223da 100644
--- a/app/(admin)/products/(list)/page.tsx
+++ b/app/(admin)/products/(list)/page.tsx
@@ -1197,7 +1197,8 @@ export default function ProductsPage() {
};
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 (
{imgUrl ? (
@@ -1959,9 +1960,9 @@ export default function ProductsPage() {
- {p.images?.[0]?.image_url ? (
+ {(p.images?.[0]?.image_url || (p as any).thumbnail_url || p.variants?.[0]?.images?.[0]?.image_url) ? (
}) { e.currentTarget.style.display = 'none'; }}
diff --git a/components/layouts/Sidebar.tsx b/components/layouts/Sidebar.tsx
index b1be0ec..f0ca2cf 100644
--- a/components/layouts/Sidebar.tsx
+++ b/components/layouts/Sidebar.tsx
@@ -82,6 +82,7 @@ const NAV_GROUPS: NavGroup[] = [
name: 'Marketing',
icon: Megaphone,
children: [
+ { name: 'Coupons & Discounts', href: '/coupons' },
{ name: 'Google Merchant Center', href: '/merchant-center' },
{ name: 'Social Media Publisher', href: '/social-media' },
{ name: 'Google Analytics GA4', href: '/analytics/google' },
diff --git a/lib/rbac.ts b/lib/rbac.ts
index a472c9e..638582c 100644
--- a/lib/rbac.ts
+++ b/lib/rbac.ts
@@ -57,6 +57,7 @@ export function isRouteAllowed(pathname: string, userRole?: string | null): bool
) return true;
if (
pathname.startsWith('/orders') ||
+ pathname.startsWith('/coupons') ||
pathname.startsWith('/invoices') ||
pathname.startsWith('/warranties') ||
pathname.startsWith('/refunds') ||
@@ -98,6 +99,7 @@ export function isRouteAllowed(pathname: string, userRole?: string | null): bool
) return true;
if (
pathname.startsWith('/orders') ||
+ pathname.startsWith('/coupons') ||
pathname.startsWith('/invoices') ||
pathname.startsWith('/bulk-quotations')
) return true;
|