diff --git a/app/(admin)/analytics/google/page.tsx b/app/(admin)/analytics/google/page.tsx new file mode 100644 index 0000000..153f198 --- /dev/null +++ b/app/(admin)/analytics/google/page.tsx @@ -0,0 +1,319 @@ +'use client'; + +import React, { useState, useEffect } from 'react'; +import { + BarChart3, + Users, + Eye, + Clock, + Globe, + TrendingUp, + RefreshCw, + CheckCircle2, + Radio, + ArrowUpRight, + Compass +} from 'lucide-react'; +import { apiFetch } from '@/services/api/client'; +import { API_ENDPOINTS } from '@/services/api/config'; +import { toast } from 'sonner'; + +interface GA4Status { + enabled: boolean; + property_id: string; + is_ready: boolean; + credentials_configured: boolean; +} + +interface GA4Overview { + property_id: string; + period: string; + metrics: { + active_users: number; + sessions: number; + screen_page_views: number; + engaged_sessions: number; + average_session_duration: number; + bounce_rate: number; + }; + realtime_active_users: number; +} + +interface GA4Source { + source_medium: string; + users: number; + sessions: number; + engaged_sessions: number; +} + +export default function GoogleAnalyticsPage() { + const [status, setStatus] = useState(null); + const [overview, setOverview] = useState(null); + const [sources, setSources] = useState([]); + const [loading, setLoading] = useState(true); + + const fetchData = async () => { + try { + setLoading(true); + const [statusRes, overviewRes, sourcesRes] = await Promise.all([ + apiFetch(API_ENDPOINTS.GOOGLE_ANALYTICS_STATUS), + apiFetch<{ status: string; data: GA4Overview }>(`${API_ENDPOINTS.GOOGLE_ANALYTICS_OVERVIEW}?days=30`), + apiFetch<{ status: string; data: GA4Source[] }>(`${API_ENDPOINTS.GOOGLE_ANALYTICS_SOURCES}?days=30`), + ]); + + if (statusRes) setStatus(statusRes); + if (overviewRes && overviewRes.data) setOverview(overviewRes.data); + if (sourcesRes && sourcesRes.data) setSources(sourcesRes.data); + } catch (err: unknown) { + console.error('Failed to load GA4 data:', err); + toast.error('Could not load Google Analytics data'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchData(); + }, []); + + const realtimeUsers = overview?.realtime_active_users ?? 0; + + return ( +
+ {/* Top Header */} +
+
+
+ + Google Analytics 4 (GA4) Service +
+

+ Web & App Analytics +

+

+ Realtime traffic telemetry, 30-day user engagement, and acquisition channel breakdowns. +

+
+ +
+ +
+
+ + {/* Property Status & Realtime Live Banner */} +
+ {/* Realtime Active Ticker */} +
+
+ + + + + + Realtime Active Visitors + + +
+ +
+
+ {loading ? '...' : realtimeUsers} +
+

+ Active users browsing the storefront in the last 30 minutes +

+
+ +
+ + GA4 Measurement Stream Connected +
+
+ + {/* Property Credentials Overview */} +
+
+
+

+ + GA4 Property Profile +

+ + Ready & Ingesting + +
+ +
+
+ GA4 Property ID + + {status?.property_id || '521198579'} + +
+ +
+ Service Account Auth + + + google-analytics-service-account.json + +
+
+
+ +
+ Reporting Window: Last 30 Days + Google Analytics Data API v1beta +
+
+
+ + {/* 30-Day Metrics Cards */} +
+
+
+ Total Active Users +
+ +
+
+
+ {loading ? '...' : (overview?.metrics?.active_users ?? 0).toLocaleString()} +
+

+ Unique storefront visitors +

+
+ +
+
+ Total Sessions +
+ +
+
+
+ {loading ? '...' : (overview?.metrics?.sessions ?? 0).toLocaleString()} +
+

+ {(overview?.metrics?.engaged_sessions ?? 0).toLocaleString()} engaged sessions +

+
+ +
+
+ Page Views +
+ +
+
+
+ {loading ? '...' : (overview?.metrics?.screen_page_views ?? 0).toLocaleString()} +
+

+ Catalog & PDP impressions +

+
+ +
+
+ Avg Session Time +
+ +
+
+
+ {loading ? '...' : `${Math.round(overview?.metrics?.average_session_duration ?? 0)}s`} +
+

+ Bounce rate: {loading ? '...' : `${overview?.metrics?.bounce_rate ?? 0}%`} +

+
+
+ + {/* Traffic Sources & Channels Table */} +
+
+
+

+ + Acquisition Traffic Sources & Mediums +

+

+ Breakdown of visitors arriving via search engines, social media, and direct URLs +

+
+
+ +
+ + + + + + + + + + + + {loading ? ( + + + + ) : sources.length === 0 ? ( + + + + ) : ( + sources.map((src, i) => { + const totalUsers = overview?.metrics?.active_users || 1; + const pct = Math.min(100, Math.round((src.users / totalUsers) * 100)); + return ( + + + + + + + + ); + }) + )} + +
Source / MediumVisitors (Users)SessionsEngaged SessionsShare of Traffic
+ + Loading traffic sources... +
+ No traffic source records available. +
+ {src.source_medium} + + {src.users.toLocaleString()} + + {src.sessions.toLocaleString()} + + {src.engaged_sessions.toLocaleString()} + +
+
+
+
+ {pct}% +
+
+
+
+
+ ); +} diff --git a/app/(admin)/dashboard/b2b/page.tsx b/app/(admin)/dashboard/b2b/page.tsx new file mode 100644 index 0000000..c6eaa5a --- /dev/null +++ b/app/(admin)/dashboard/b2b/page.tsx @@ -0,0 +1,186 @@ +'use client'; + +import { + Building2, + Users, + Boxes, + DollarSign, +} from 'lucide-react'; +import { cn } from '@/lib/utils'; +import Link from 'next/link'; +import { DashboardHeaderNav } from '@/components/dashboard/DashboardHeaderNav'; +import { useDashboardData } from '@/components/dashboard/useDashboardData'; +import { + CARD, + formatInr, + deltaFromWeek, + CardTitle, + DeltaPill, +} from '@/components/dashboard/DashboardShared'; + +export default function B2BDashboardPage() { + const { + stats: displayStats, + loading, + refreshing, + userName, + fetchData, + } = useDashboardData(); + + const totalOrders = displayStats.total_orders ?? 0; + const revenueDelta = deltaFromWeek( + displayStats.revenue_last_7_days ?? 0, + displayStats.revenue_last_30_days ?? 0 + ); + const customersDelta = 2.5; + + if (loading) { + return ( +
+
+
+ {[...Array(4)].map((_, i) => ( +
+ ))} +
+
+ ); + } + + return ( +
+ fetchData(true)} + /> + + {/* KPI Cards Row */} +
+
+
+
+

Total Wholesale Revenue

+

+ {formatInr(displayStats.revenue_all_time)} +

+
+ + + +
+
+ + B2B volume growth +
+
+ +
+
+
+

Active B2B Accounts

+

+ {displayStats.total_users} +

+
+ + + +
+
+ + Verified clients +
+
+ +
+
+
+

Bulk Orders Volume

+

{totalOrders}

+
+ + + +
+
+ Wholesale fulfillment +
+
+ +
+
+
+

Avg B2B Order Value

+

+ {formatInr((displayStats.revenue_all_time / Math.max(totalOrders, 1)) * 1.5)} +

+
+ + + +
+
+ + High-value basket size +
+
+
+ + {/* Orders Ledger & Top Wholesale Products */} +
+
+
+ B2B Wholesale Orders Ledger + + View All Bulk Orders + +
+
+ + + + + + + + + + + {(displayStats.recent_orders ?? []).map((order) => ( + + + + + + + ))} + +
Bulk Order #Corporate ClientOrder ValueFulfillment
{order.order_no}{order.customer_name}{formatInr(order.amount)}{order.status}
+
+
+ +
+ Top Wholesale Products +
+ {(displayStats.top_products ?? []).length === 0 ? ( +

No wholesale data yet

+ ) : ( + (displayStats.top_products ?? []).slice(0, 5).map((product) => ( +
+
+

{product.name}

+

{product.total_sold} units sold

+
+ {formatInr(product.total_revenue)} +
+ )) + )} +
+
+
+
+ ); +} diff --git a/app/(admin)/dashboard/executive/page.tsx b/app/(admin)/dashboard/executive/page.tsx new file mode 100644 index 0000000..3ef9062 --- /dev/null +++ b/app/(admin)/dashboard/executive/page.tsx @@ -0,0 +1,315 @@ +'use client'; + +import { + ArrowRight, + TrendingUp, + DollarSign, + Activity, + PackageCheck, + Users, + Boxes, + Building2, + Layers, +} from 'lucide-react'; +import { + ComposedChart, + Bar, + Area, + XAxis, + YAxis, + Tooltip, + ResponsiveContainer, + CartesianGrid, +} from 'recharts'; +import { + DashboardRevenuePoint, + DashboardMonthlyPoint, +} from '@/services/api/adminService'; +import { cn } from '@/lib/utils'; +import Link from 'next/link'; +import { DashboardHeaderNav } from '@/components/dashboard/DashboardHeaderNav'; +import { useDashboardData } from '@/components/dashboard/useDashboardData'; +import { + CARD, + formatCompact, + formatInr, + samplePoints, + CardTitle, + PeriodPills, + DeltaPill, +} from '@/components/dashboard/DashboardShared'; + +export default function ExecutiveDashboardPage() { + const { + stats: displayStats, + loading, + refreshing, + userName, + chartMode, + setChartMode, + fetchData, + } = useDashboardData(); + + const byStatus = displayStats.orders_by_status ?? {}; + const countOf = (key: string) => byStatus[key] ?? 0; + const totalOrders = displayStats.total_orders ?? 0; + const delivered = countOf('delivered'); + const conversion = totalOrders > 0 ? (delivered / totalOrders) * 100 : 0; + const conversionDelta = 15.5; + + const daily: DashboardRevenuePoint[] = displayStats.revenue_chart_daily ?? []; + const monthly: DashboardMonthlyPoint[] = displayStats.revenue_chart_monthly ?? []; + const sourceChart: Array = + chartMode === 'weekly' ? samplePoints(daily, 12) : monthly; + + const rawPoints = sourceChart.map((row) => ({ + name: + 'date' in row + ? row.date?.replace('08-', '') ?? '' + : row.label?.slice(0, 3) ?? '', + revenue: row.revenue, + orders: row.orders, + })); + const maxRev = Math.max(...rawPoints.map((row) => row.revenue), 1); + const maxOrd = Math.max(...rawPoints.map((row) => row.orders), 1); + const salesScale = (maxRev * 0.72) / maxOrd; + const chartPoints = rawPoints.map((row) => ({ + ...row, + sales: row.orders * salesScale, + })); + + if (loading) { + return ( +
+
+
+ {[...Array(4)].map((_, i) => ( +
+ ))} +
+
+ ); + } + + return ( +
+ fetchData(true)} + /> + + {/* KPI Cards Row */} +
+
+
+
+

Gross Revenue (All Time)

+

+ {formatInr(displayStats.revenue_all_time)} +

+
+ + + +
+
+ + Target Exceeded +
+
+ +
+
+
+

30-Day Enterprise Run-Rate

+

+ {formatInr(displayStats.revenue_last_30_days)} +

+
+ + + +
+
+ + Vs previous month +
+
+ +
+
+
+

Average Order Value (AOV)

+

+ {formatInr(displayStats.revenue_all_time / Math.max(totalOrders, 1))} +

+
+ + + +
+
+ + Order basket size gain +
+
+ +
+
+
+

Gross Fulfillment Rate

+

+ {conversion.toFixed(1)}% +

+
+ + + +
+
+ + Delivered vs Total +
+
+
+ + {/* Analytics & Portfolio Scope */} +
+
+
+ Executive Revenue Analytics & Projections + +
+
+
+

+ {formatCompact(displayStats.revenue_last_30_days).replace('₹', '')} +

+

30-Day Consolidated Turnover (INR)

+
+
+
+ + + + + (v >= 1000 ? `₹${(v / 1000).toFixed(0)}k` : `₹${v}`)} /> + { + if (!active || !payload?.length) return null; + const row = payload[0]?.payload as { revenue: number; orders: number }; + return ( +
+

{label}

+

{formatInr(row.revenue)}

+

{row.orders} corporate transactions

+
+ ); + }} /> + + +
+
+
+
+ +
+ Enterprise Portfolio Scope +
+
+
+ + + +
+

Total Customer Accounts

+

{displayStats.total_users}

+
+
+ +
+ +
+
+ + + +
+

Product Portfolio

+

{displayStats.total_products} SKUs

+
+
+ {displayStats.total_stock_units} Units +
+ +
+
+ + + +
+

Partner Brands

+

{displayStats.total_brands} Brands

+
+
+ {displayStats.total_categories} Categories +
+ +
+
+ + + +
+

Supported Devices

+

{displayStats.total_device_models} Models

+
+
+ {displayStats.total_device_series} Series +
+
+
+
+ + {/* Transaction Ledger Table */} +
+
+ Executive Transaction Ledger + + Audit Full Orders + +
+
+ + + + + + + + + + + + {(displayStats.recent_orders ?? []).map((order) => ( + + + + + + + + ))} + +
Order RefClient / CustomerTransaction ValueFulfillment StagePriority
{order.order_no}{order.customer_name}{formatInr(order.amount)}{order.status} + + High Priority + +
+
+
+
+ ); +} diff --git a/app/(admin)/dashboard/mockData.ts b/app/(admin)/dashboard/mockData.ts index 08df4a8..d430fc6 100644 --- a/app/(admin)/dashboard/mockData.ts +++ b/app/(admin)/dashboard/mockData.ts @@ -50,11 +50,31 @@ export const MOCK_DASHBOARD_STATS: DashboardStats = { { label: 'August', revenue: 184320, orders: 82 }, ], top_products: [ - { name: 'iPhone 15 OLED Display Assembly', total_sold: 86, total_revenue: 412800 }, - { name: 'Samsung S23 Ultra Battery', total_sold: 64, total_revenue: 198400 }, - { name: 'iPhone 14 Charging Port Flex', total_sold: 51, total_revenue: 86700 }, - { name: 'OnePlus 12 Back Glass Panel', total_sold: 38, total_revenue: 64600 }, - { name: 'Pixel 8 Pro Camera Module', total_sold: 24, total_revenue: 91200 }, + { name: 'Refurbished Sony PlayStation 5 Disc Edition', total_sold: 14, total_revenue: 559986 }, + { name: 'Apple Mobile Camera for iPhone 16 Pro', total_sold: 38, total_revenue: 167230 }, + { name: 'Refurbished Sony WH-1000XM5 Noise Canceling Headphones', total_sold: 11, total_revenue: 219989 }, + { name: 'OLED Display Screen Assembly for Samsung Galaxy S24 Ultra', total_sold: 16, total_revenue: 184000 }, + { name: 'Apple Mobile Display for iPhone 16 Pro Max', total_sold: 18, total_revenue: 164139 }, + { name: 'Apple Mobile Cases for iPhone 15', total_sold: 29, total_revenue: 114246 }, + { name: 'Apple Mobile Display for iPhone 16', total_sold: 15, total_revenue: 71570 }, + { name: 'Apple Camera Lens Guards for iPhone 16 Plus', total_sold: 22, total_revenue: 92117 }, + { name: 'Apple Mobile Display for iPhone 15 Pro', total_sold: 19, total_revenue: 64404 }, + { name: 'Xiaomi Mobile Display for Xiaomi 14 Ultra', total_sold: 12, total_revenue: 22828 }, + { name: 'Apple Mobile Cases for iPhone 13 Mini', total_sold: 17, total_revenue: 29613 }, + { name: 'Samsung Mobile Camera for Samsung Galaxy A53 5G', total_sold: 14, total_revenue: 23433 }, + { name: 'Samsung Mobile Back Panel for Samsung Galaxy S23+', total_sold: 13, total_revenue: 20730 }, + { name: 'Samsung bluetooth speaker for Samsung Galaxy S23 Ultra', total_sold: 25, total_revenue: 34716 }, + { name: 'Samsung Screen Guards for Samsung Galaxy S23', total_sold: 31, total_revenue: 36486 }, + { name: 'Google Pixel Camera Lens Guards for Google Pixel 6', total_sold: 26, total_revenue: 25910 }, + { name: 'Stereo Loudspeaker for iPhone 14 Pro', total_sold: 10, total_revenue: 18990 }, + { name: 'Fast Charging Adapter 65W GaN', total_sold: 34, total_revenue: 33660 }, + { name: 'MagSafe Wireless Power Bank 10000mAh', total_sold: 21, total_revenue: 41790 }, + { name: 'OnePlus 12 Curved AMOLED Display Module', total_sold: 9, total_revenue: 76500 }, + { name: 'iPad Pro 12.9 Liquid Retina Touch Screen', total_sold: 6, total_revenue: 108000 }, + { name: 'Apple Watch Series 9 Sapphire Glass Panel', total_sold: 8, total_revenue: 39920 }, + { name: 'MacBook Pro M3 Pro Magnetic Keyboard Assembly', total_sold: 5, total_revenue: 84500 }, + { name: 'GoPro Hero 12 Black Lens Replacement Kit', total_sold: 7, total_revenue: 27930 }, + { name: 'Universal BGA Reballing Stencil Set 120-in-1', total_sold: 15, total_revenue: 22500 }, ], recent_orders: [ { diff --git a/app/(admin)/dashboard/page.tsx b/app/(admin)/dashboard/page.tsx index c511875..fea43ad 100644 --- a/app/(admin)/dashboard/page.tsx +++ b/app/(admin)/dashboard/page.tsx @@ -1,1545 +1,483 @@ -'use client'; - -import { useEffect, useState, useCallback, type ReactNode } from 'react'; -import { - ArrowUpRight, ArrowDownRight, ArrowRight, RefreshCw, Calendar, ChevronDown, - TrendingUp, Filter, Handshake, Wrench, ShieldCheck, Building2, ShoppingBag, - DollarSign, Users, Boxes, Layers, Activity, CheckCircle2, PackageCheck, - AlertCircle, Clock, -} from 'lucide-react'; -import { - ComposedChart, - Bar, - Area, - XAxis, - YAxis, - Tooltip, - ResponsiveContainer, - CartesianGrid, -} from 'recharts'; -import { - adminService, - DashboardStats, - SessionInfo, - DashboardRevenuePoint, - DashboardMonthlyPoint, - DashboardRecentOrder, - DashboardTopProduct, -} from '@/services/api/adminService'; -import { parseJwt, getAccessToken, apiFetch } from '@/services/api/client'; -import { cn } from '@/lib/utils'; -import Link from 'next/link'; -import { withDashboardMock } from './mockData'; - -const PAGE_DATE_RANGE = 'Live Store & ERP Operations'; - -const CARD = - 'bg-card crm-radius-section border border-border shadow-[0_1px_3px_rgba(16,24,40,0.06)] min-w-0'; - -const PIPELINE = [ - { key: 'pending', label: 'Pending', color: '#5BA4C7' }, - { key: 'processing', label: 'Processing', color: '#3B82F6' }, - { key: 'shipped', label: 'Shipped', color: '#7C3AED' }, - { key: 'delivered', label: 'Delivered', color: '#01B574' }, -] as const; - -const OVERVIEW = [ - { key: 'delivered', label: 'Successful orders', color: '#01B574' }, - { key: 'pending', label: 'Pending orders', color: '#5BA4C7' }, - { key: 'cancelled', label: 'Cancelled', color: '#7C3AED' }, - { key: 'shipped', label: 'In transit', color: '#3B82F6' }, -] as const; - -const DONUT_COLORS: Record = { - delivered: '#01B574', - shipped: '#3B82F6', - processing: '#5BA4C7', - pending: '#7C3AED', -}; - -const PAYMENT_TAG: Record = { - paid: 'border-[#01B574] text-[#01B574] bg-[#01B574]/8', - unpaid: 'border-[#5BA4C7] text-[#5BA4C7] bg-[#5BA4C7]/10', - refunded: 'border-primary text-primary bg-primary/8', -}; - -const PRODUCT_TONES = ['#5BA4C7', '#3B82F6', '#01B574', '#1B2559', '#7C3AED']; - -function formatCompact(val: number) { - if (val >= 1_000_000) return `₹${(val / 1_000_000).toFixed(2)}M`; - if (val >= 1_000) return `₹${(val / 1_000).toFixed(val >= 10_000 ? 0 : 1)}K`; - return `₹${val.toFixed(0)}`; -} - -function formatInr(val: number) { - return new Intl.NumberFormat('en-IN', { - style: 'currency', - currency: 'INR', - maximumFractionDigits: 0, - }).format(val); -} - -function initials(name: string) { - const parts = name.trim().split(/\s+/).filter(Boolean); - return ((parts[0]?.[0] ?? '') + (parts[1]?.[0] ?? '')).toUpperCase() || '•'; -} - -function samplePoints(items: T[], count: number) { - if (items.length <= count) return items; - const step = (items.length - 1) / (count - 1); - return Array.from({ length: count }, (_, i) => items[Math.round(i * step)]); -} - -function deltaFromWeek(week: number, month: number) { - if (!month) return 2.5; - const actual = week / month; - const expected = 7 / 30; - return ((actual - expected) / expected) * 100; -} - -function CardTitle({ children }: { children: ReactNode }) { - return ( -

- - {children} -

- ); -} - -function PeriodPills({ - value, - onChange, -}: { - value: 'weekly' | 'monthly' | 'yearly'; - onChange: (next: 'weekly' | 'monthly' | 'yearly') => void; -}) { - return ( -
- {(['weekly', 'monthly', 'yearly'] as const).map((mode) => ( - - ))} -
- ); -} - -function GhostSelect({ label }: { label: string }) { - return ( - - {label} - - - ); -} - -function DeltaPill({ value }: { value: number }) { - const up = value >= 0; - return ( - - {up ? : } - {up ? '+' : ''} - {Math.abs(value).toFixed(1)}% - - ); -} - -function StatusDonut({ - slices, -}: { - slices: Array<{ label: string; value: number; color: string }>; -}) { - const total = slices.reduce((sum, slice) => sum + slice.value, 0) || 1; - const cx = 90; - const cy = 90; - const r = 58; - const stroke = 26; - const circ = 2 * Math.PI * r; - let offset = 0; - - return ( - - - {slices.map((slice) => { - const pct = slice.value / total; - const dash = Math.max(pct * circ, 0); - const currentOffset = offset; - offset += pct; - const mid = (currentOffset + pct / 2) * 2 * Math.PI - Math.PI / 2; - const lx = cx + Math.cos(mid) * r; - const ly = cy + Math.sin(mid) * r; - return ( - - - {pct >= 0.08 && ( - - {Math.round(pct * 100)}% - - )} - - ); - })} - - ); -} - -export default function DashboardPage() { - const [stats, setStats] = useState(null); - const [sessions, setSessions] = useState([]); - const [loading, setLoading] = useState(true); - const [userName, setUserName] = useState('Admin'); - const [chartMode, setChartMode] = useState<'weekly' | 'monthly' | 'yearly'>('weekly'); - const [refreshing, setRefreshing] = useState(false); - const [activeDashboardRole, setActiveDashboardRole] = useState<'main' | 'executive' | 'store_manager' | 'technician' | 'b2b'>('main'); - - useEffect(() => { - const token = getAccessToken(); - if (token) { - const payload = parseJwt(token); - if (payload) { - setUserName((payload.email as string)?.split('@')[0] || 'Admin'); - } - } - }, []); - - const fetchData = useCallback(async (silent = false) => { - if (!silent) setLoading(true); - else setRefreshing(true); - try { - const [statsRes, ordersRes, productsRes, categoriesRes, brandsRes, sessionsRes] = await Promise.allSettled([ - adminService.getDashboardStats().catch(() => null), - apiFetch('/api/v1/admin/orders').catch(() => []), - apiFetch('/api/v1/catalog/products/all?limit=200').catch(() => []), - apiFetch('/api/v1/catalog/categories/all').catch(() => []), - apiFetch('/api/v1/catalog/brands/all').catch(() => []), - adminService.listSessions(0, 50).catch(() => ({ sessions: [] })), - ]); - - const liveStats = statsRes.status === 'fulfilled' ? statsRes.value : null; - const liveOrders = ordersRes.status === 'fulfilled' && Array.isArray(ordersRes.value) ? ordersRes.value : []; - const liveProductsRaw = productsRes.status === 'fulfilled' ? productsRes.value : []; - const liveProducts = Array.isArray(liveProductsRaw) ? liveProductsRaw : (liveProductsRaw?.products || []); - const liveCategories = categoriesRes.status === 'fulfilled' && Array.isArray(categoriesRes.value) ? categoriesRes.value : []; - const liveBrands = brandsRes.status === 'fulfilled' && Array.isArray(brandsRes.value) ? brandsRes.value : []; - const liveSessions = sessionsRes.status === 'fulfilled' && sessionsRes.value?.sessions ? sessionsRes.value.sessions : []; - - let mergedStats: DashboardStats; - - if (liveStats) { - mergedStats = liveStats; - } else if (liveOrders.length > 0 || liveProducts.length > 0) { - const ordersByStatus: Record = { - pending: 0, - confirmed: 0, - processing: 0, - shipped: 0, - delivered: 0, - cancelled: 0, - returned: 0, - }; - - let totalRevenue = 0; - const recentOrders: DashboardRecentOrder[] = []; - - liveOrders.forEach((o: any) => { - const statusKey = (o.status || 'pending').toLowerCase(); - ordersByStatus[statusKey] = (ordersByStatus[statusKey] || 0) + 1; - - if (['DELIVERED', 'COMPLETED', 'CONFIRMED', 'PROCESSING', 'SHIPPED', 'PAYMENT_CAPTURED', 'PAID'].includes((o.status || '').toUpperCase()) || (o.payment_status || '').toUpperCase() === 'PAID') { - totalRevenue += Number(o.final_amount || 0); - } - - if (recentOrders.length < 10) { - recentOrders.push({ - order_no: o.order_no || 'ORD', - amount: Number(o.final_amount || 0), - status: (o.status || 'pending').toLowerCase(), - payment_status: (o.payment_status || 'paid').toLowerCase(), - created_at: o.created_at || null, - customer_name: o.customer_name || o.customer_email || 'Customer', - customer_email: o.customer_email || null, - }); - } - }); - - // Daily chart points from live orders - const dailyMap = new Map(); - liveOrders.forEach((o: any) => { - if (!o.created_at) return; - const d = new Date(o.created_at); - const dayStr = `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; - const existing = dailyMap.get(dayStr) || { revenue: 0, orders: 0 }; - dailyMap.set(dayStr, { - revenue: existing.revenue + Number(o.final_amount || 0), - orders: existing.orders + 1, - }); - }); - - const dynamicDaily = Array.from(dailyMap.entries()).map(([date, val]) => ({ - date, - revenue: val.revenue, - orders: val.orders, - })); - - const dynamicTopProducts: DashboardTopProduct[] = liveProducts.slice(0, 5).map((p: any) => ({ - name: p.name || 'Product', - total_sold: p.variants?.length || 0, - total_revenue: p.variants?.reduce((s: number, v: any) => s + Number(v.price || 0), 0) || 0, - })); - - mergedStats = { - total_users: liveOrders.length, - total_orders: liveOrders.length, - total_products: liveProducts.length, - total_brands: liveBrands.length, - total_device_models: 0, - total_device_series: 0, - total_categories: liveCategories.length, - revenue_all_time: totalRevenue, - revenue_last_30_days: totalRevenue, - revenue_last_7_days: totalRevenue, - orders_by_status: ordersByStatus, - revenue_chart_daily: dynamicDaily, - revenue_chart_monthly: [], - top_products: dynamicTopProducts, - recent_orders: recentOrders, - low_stock_variants: 0, - out_of_stock_variants: 0, - total_stock_units: liveProducts.reduce((acc: number, p: any) => acc + (p.variants?.length || 0), 0), - }; - } else { - mergedStats = { - total_users: 0, - total_orders: 0, - total_products: 0, - total_brands: 0, - total_device_models: 0, - total_device_series: 0, - total_categories: 0, - revenue_all_time: 0, - revenue_last_30_days: 0, - revenue_last_7_days: 0, - orders_by_status: {}, - revenue_chart_daily: [], - revenue_chart_monthly: [], - top_products: [], - recent_orders: [], - low_stock_variants: 0, - out_of_stock_variants: 0, - total_stock_units: 0, - }; - } - - setStats(mergedStats); - setSessions(liveSessions); - } finally { - setLoading(false); - setRefreshing(false); - } - }, []); - - useEffect(() => { - fetchData(); - }, [fetchData]); - - const { stats: displayStats } = withDashboardMock(stats, sessions); - const byStatus = displayStats.orders_by_status ?? {}; - const countOf = (key: string) => byStatus[key] ?? 0; - const totalOrders = displayStats.total_orders ?? 0; - const delivered = countOf('delivered'); - const conversion = totalOrders > 0 ? (delivered / totalOrders) * 100 : 0; - const revenueDelta = deltaFromWeek( - displayStats.revenue_last_7_days ?? 0, - displayStats.revenue_last_30_days ?? 0 - ); - const ordersDelta = conversion >= 40 ? 2.5 : -4.2; - const conversionDelta = 15.5; - const customersDelta = 2.5; - - const daily: DashboardRevenuePoint[] = displayStats.revenue_chart_daily ?? []; - const monthly: DashboardMonthlyPoint[] = displayStats.revenue_chart_monthly ?? []; - const sourceChart: Array = - chartMode === 'weekly' ? samplePoints(daily, 12) : monthly; - - const rawPoints = sourceChart.map((row) => ({ - name: - 'date' in row - ? row.date?.replace('08-', '') ?? '' - : row.label?.slice(0, 3) ?? '', - revenue: row.revenue, - orders: row.orders, - })); - const maxRev = Math.max(...rawPoints.map((row) => row.revenue), 1); - const maxOrd = Math.max(...rawPoints.map((row) => row.orders), 1); - const salesScale = (maxRev * 0.72) / maxOrd; - const chartPoints = rawPoints.map((row) => ({ - ...row, - sales: row.orders * salesScale, - })); - - const pipelineRows = PIPELINE.map((stage) => ({ - ...stage, - count: countOf(stage.key), - value: countOf(stage.key) * (displayStats.revenue_all_time / Math.max(totalOrders, 1)), - })); - const maxPipeline = Math.max(...pipelineRows.map((row) => row.count), 1); - - const overviewRows = OVERVIEW.map((row) => ({ - ...row, - count: countOf(row.key), - })); - const overviewTotal = overviewRows.reduce((sum, row) => sum + row.count, 0) || 1; - - const donutSlices = [ - { label: 'Delivered', value: countOf('delivered'), color: DONUT_COLORS.delivered }, - { label: 'Shipped', value: countOf('shipped'), color: DONUT_COLORS.shipped }, - { label: 'Processing', value: countOf('processing') + countOf('confirmed'), color: DONUT_COLORS.processing }, - { label: 'Pending', value: countOf('pending') + countOf('cancelled') + countOf('returned'), color: DONUT_COLORS.pending }, - ].filter((slice) => slice.value > 0); - - const spark = daily.slice(-14).map((row) => row.orders); - const sparkMax = Math.max(...spark, 1); - const customerAvatars = (displayStats.recent_orders ?? []).slice(0, 4); - - if (loading) { - return ( -
-
-
-
-
-
-
- {[...Array(4)].map((_, i) => ( -
- ))} -
-
- ); - } - - return ( -
-
-
-

Multi-Dashboard Suite

-

- Welcome back, {userName} -

-
-
-
- - {PAGE_DATE_RANGE} - -
- -
-
- - {/* Role Switcher Tabs */} -
- {[ - { id: 'main', label: 'Main Overview' }, - { id: 'executive', label: 'Executive C-Suite' }, - { id: 'store_manager', label: 'Store Manager' }, - { id: 'technician', label: 'Technician Workshop' }, - { id: 'b2b', label: 'B2B Wholesale' }, - ].map((tab) => ( - - ))} -
- - {/* Dynamic Role Views */} - {activeDashboardRole === 'main' && ( - <> -
-
-
- Revenue Analytics - -
-
-
-

- {formatCompact(displayStats.revenue_last_30_days).replace('₹', '')} -

-

Revenue with orders (INR)

-
-
- - Revenue - - - Orders - -
-
-
- {chartPoints.length === 0 ? ( -
- No order revenue data yet -
- ) : ( - - - - - (v >= 1000 ? `₹${(v / 1000).toFixed(0)}k` : `₹${v}`)} - /> - { - if (!active || !payload?.length) return null; - const row = payload[0]?.payload as { revenue: number; orders: number }; - return ( -
-

{label}

-

{formatInr(row.revenue)}

-

{row.orders} orders

-
- ); - }} - /> - - -
-
- )} -
-
- -
-
- Order sources - - - -
-
- {donutSlices.length === 0 ? ( -

No orders yet

- ) : ( - - )} -
-
- {donutSlices.map((slice) => ( -
- - - {slice.label} - - {slice.value} -
- ))} -
-
-
- -
-
-
-

Revenue

- - - -
-

- {formatInr(displayStats.revenue_all_time)} -

-
- - From last week -
-
- -
-
-

Active orders

- - - -
-

{totalOrders}

-
- - From last week -
-
- -
-
-

Fulfillment rate

- - - -
-

- {conversion.toFixed(1)}% -

-
- - Delivered vs total -
-
- -
-
-
-

Total customers

-

- {displayStats.total_users} -

-
- -
-
- {customerAvatars.map((order, index) => ( - - {initials(order.customer_name)} - - ))} - - +{Math.max(displayStats.total_users - customerAvatars.length, 0)} - -
-
-
- {spark.map((value, index) => ( - - ))} -
-
-
-
- -
-
-
- Top products - -
-
- {(displayStats.top_products ?? []).length === 0 ? ( -

No sales data yet

- ) : ( - (displayStats.top_products ?? []).slice(0, 5).map((product, index) => ( -
- - {initials(product.name)} - -
-

{product.name}

-

{product.total_sold} units sold

-
- - {formatInr(product.total_revenue)} - -
- )) - )} -
- - View All - -
- -
-
- Pipeline statistics - -
-
- {pipelineRows.map((row) => ( -
-

{row.label}

-

- {formatCompact(row.value)} -

-

{row.count} orders

-
- ))} -
-
- {pipelineRows.map((row) => ( -
-
-
- ))} -
-
-

- Stock value{' '} - - {(displayStats.total_stock_units ?? 0).toLocaleString()} units - -

-
- {spark.slice(-10).map((value, index) => ( - - ))} -
-
-
- -
-
- Orders overview - - - -
-
- {overviewRows.map((row) => ( - - ))} -
-

{totalOrders}

-
- - compared to last week -
-
- {overviewRows.map((row) => ( -
- - - {row.label} - - {row.count} orders -
- ))} -
-
-

- Orders delivered {delivered} -

- - {customerAvatars.slice(0, 4).map((order, index) => ( - - {initials(order.customer_name)} - - ))} - -
-
-
- -
-
- Recent orders - - View All - -
-
- {(displayStats.recent_orders ?? []).length === 0 ? ( -

No orders yet

- ) : ( - - - - - - - - - - - - {(displayStats.recent_orders ?? []).map((order) => ( - - - - - - - - ))} - -
OrderStageValuePaymentCustomer
- {order.order_no} - {order.status} - {formatInr(order.amount)} - - - {order.payment_status || '—'} - - - - - {initials(order.customer_name)} - - {order.customer_name} - -
- )} -
-
- - )} - - {/* EXECUTIVE C-SUITE VIEW */} - {activeDashboardRole === 'executive' && ( -
-
-
-
-
-

Gross Revenue (All Time)

-

- {formatInr(displayStats.revenue_all_time)} -

-
- - - -
-
- - Target Exceeded -
-
- -
-
-
-

30-Day Enterprise Run-Rate

-

- {formatInr(displayStats.revenue_last_30_days)} -

-
- - - -
-
- - Vs previous month -
-
- -
-
-
-

Average Order Value (AOV)

-

- {formatInr(displayStats.revenue_all_time / Math.max(totalOrders, 1))} -

-
- - - -
-
- - Order basket size gain -
-
- -
-
-
-

Gross Fulfillment Rate

-

- {conversion.toFixed(1)}% -

-
- - - -
-
- - Delivered vs Total -
-
-
- -
-
-
- Executive Revenue Analytics & Projections - -
-
-
-

- {formatCompact(displayStats.revenue_last_30_days).replace('₹', '')} -

-

30-Day Consolidated Turnover (INR)

-
-
-
- - - - - (v >= 1000 ? `₹${(v / 1000).toFixed(0)}k` : `₹${v}`)} /> - { - if (!active || !payload?.length) return null; - const row = payload[0]?.payload as { revenue: number; orders: number }; - return ( -
-

{label}

-

{formatInr(row.revenue)}

-

{row.orders} corporate transactions

-
- ); - }} /> - - -
-
-
-
- -
- Enterprise Portfolio Scope -
-
-
- - - -
-

Total Customer Accounts

-

{displayStats.total_users}

-
-
- -
- -
-
- - - -
-

Product Portfolio

-

{displayStats.total_products} SKUs

-
-
- {displayStats.total_stock_units} Units -
- -
-
- - - -
-

Partner Brands

-

{displayStats.total_brands} Brands

-
-
- {displayStats.total_categories} Categories -
- -
-
- - - -
-

Supported Devices

-

{displayStats.total_device_models} Models

-
-
- {displayStats.total_device_series} Series -
-
-
-
- -
-
- Executive Transaction Ledger - - Audit Full Orders - -
-
- - - - - - - - - - - - {(displayStats.recent_orders ?? []).map((order) => ( - - - - - - - - ))} - -
Order RefClient / CustomerTransaction ValueFulfillment StagePriority
{order.order_no}{order.customer_name}{formatInr(order.amount)}{order.status} - - High Priority - -
-
-
-
- )} - - {/* STORE MANAGER VIEW */} - {activeDashboardRole === 'store_manager' && ( -
-
-
-
-
-

Active Store Orders

-

{totalOrders}

-
- - - -
-
- - Store traffic steady -
-
- -
-
-
-

Pending & In-Transit

-

- {countOf('pending') + countOf('processing') + countOf('shipped')} -

-
- - - -
-
- Requires Dispatch Action -
-
- -
-
-
-

Catalog Stock Units

-

- {(displayStats.total_stock_units ?? 0).toLocaleString()} -

-
- - - -
-
- {displayStats.total_products} Active SKUs -
-
- -
-
-
-

Fulfilled Orders

-

{delivered}

-
- - - -
-
- - Successful deliveries -
-
-
- -
-
- Store Operations & Fulfillment Pipeline -
- {pipelineRows.map((row) => ( -
-

{row.label}

-

{row.count} Orders

-

{formatCompact(row.value)}

-
- ))} -
-
- {pipelineRows.map((row) => ( -
-
- {row.label} -
- ))} -
-
- -
- Store Inventory Overview -
-
-
- - Total Catalog Products -
- {displayStats.total_products} -
- -
-
- - Active Brands -
- {displayStats.total_brands} -
- -
-
- - Categories Listed -
- {displayStats.total_categories} -
- -
-
- - Total Stock Units -
- {displayStats.total_stock_units} -
-
-
-
- -
-
- Store Manager Order Dispatch Queue - - Manage Orders - -
-
- - - - - - - - - - - - {(displayStats.recent_orders ?? []).map((order) => ( - - - - - - - - ))} - -
OrderDispatch StageValuePaymentCustomer
{order.order_no}{order.status}{formatInr(order.amount)} - - {order.payment_status || '—'} - - {order.customer_name}
-
-
-
- )} - - {/* TECHNICIAN WORKSHOP VIEW */} - {activeDashboardRole === 'technician' && ( -
-
-
-
-
-

Supported Device Models

-

{displayStats.total_device_models}

-
- - - -
-
- Repair compatibility list -
-
- -
-
-
-

Supported Device Series

-

{displayStats.total_device_series}

-
- - - -
-
- Across {displayStats.total_brands} brands -
-
- -
-
-
-

Service Intake Orders

-

{totalOrders}

-
- - - -
-
- Warranty & repair jobs -
-
- -
-
-
-

Completed Services

-

{delivered}

-
- - - -
-
- - Inspected & delivered -
-
-
- -
-
-
- Technician Service Queue - - Open Repair Intake - -
-
- - - - - - - - - - - {(displayStats.recent_orders ?? []).map((order) => ( - - - - - - - ))} - -
Job RefCustomerRepair StatusValue
{order.order_no}{order.customer_name} - - {order.status} - - {formatInr(order.amount)}
-
-
- -
- Device Repair Matrix -
-
-
-

Device Models Configured

-

{displayStats.total_device_models}

-
- -
- -
-
-

Device Series Catalog

-

{displayStats.total_device_series}

-
- -
- -
-
-

Supported Brands

-

{displayStats.total_brands}

-
- -
-
-
-
-
- )} - - {/* B2B WHOLESALE VIEW */} - {activeDashboardRole === 'b2b' && ( -
-
-
-
-
-

Total Wholesale Revenue

-

- {formatInr(displayStats.revenue_all_time)} -

-
- - - -
-
- - B2B volume growth -
-
- -
-
-
-

Active B2B Accounts

-

{displayStats.total_users}

-
- - - -
-
- - Verified clients -
-
- -
-
-
-

Bulk Orders Volume

-

{totalOrders}

-
- - - -
-
- Wholesale fulfillment -
-
- -
-
-
-

Avg B2B Order Value

-

- {formatInr((displayStats.revenue_all_time / Math.max(totalOrders, 1)) * 1.5)} -

-
- - - -
-
- - High-value basket size -
-
-
- -
-
-
- B2B Wholesale Orders Ledger - - View All Bulk Orders - -
-
- - - - - - - - - - - {(displayStats.recent_orders ?? []).map((order) => ( - - - - - - - ))} - -
Bulk Order #Corporate ClientOrder ValueFulfillment
{order.order_no}{order.customer_name}{formatInr(order.amount)}{order.status}
-
-
- -
- Top Wholesale Products -
- {(displayStats.top_products ?? []).length === 0 ? ( -

No wholesale data yet

- ) : ( - (displayStats.top_products ?? []).slice(0, 5).map((product) => ( -
-
-

{product.name}

-

{product.total_sold} units sold

-
- {formatInr(product.total_revenue)} -
- )) - )} -
-
-
-
- )} -
- ); -} +'use client'; + +import { + ArrowRight, + TrendingUp, + Filter, + Users, + Activity, + PackageCheck, + ShoppingBag, +} from 'lucide-react'; +import { + ComposedChart, + Bar, + Area, + XAxis, + YAxis, + Tooltip, + ResponsiveContainer, + CartesianGrid, +} from 'recharts'; +import { + DashboardRevenuePoint, + DashboardMonthlyPoint, +} from '@/services/api/adminService'; +import { cn } from '@/lib/utils'; +import Link from 'next/link'; +import { DashboardHeaderNav } from '@/components/dashboard/DashboardHeaderNav'; +import { TopSellingProductsCard } from '@/components/dashboard/TopSellingProductsCard'; +import { useDashboardData } from '@/components/dashboard/useDashboardData'; +import { isRouteAllowed } from '@/lib/rbac'; +import { + CARD, + PIPELINE, + OVERVIEW, + DONUT_COLORS, + PAYMENT_TAG, + PRODUCT_TONES, + formatCompact, + formatInr, + initials, + samplePoints, + deltaFromWeek, + CardTitle, + PeriodPills, + GhostSelect, + DeltaPill, + StatusDonut, +} from '@/components/dashboard/DashboardShared'; + +export default function MainDashboardPage() { + const { + stats: displayStats, + sessions, + loading, + refreshing, + userName, + userRole, + chartMode, + setChartMode, + fetchData, + } = useDashboardData(); + + const byStatus = displayStats.orders_by_status ?? {}; + const countOf = (key: string) => byStatus[key] ?? 0; + const totalOrders = displayStats.total_orders ?? 0; + const delivered = countOf('delivered'); + const conversion = totalOrders > 0 ? (delivered / totalOrders) * 100 : 0; + const revenueDelta = deltaFromWeek( + displayStats.revenue_last_7_days ?? 0, + displayStats.revenue_last_30_days ?? 0 + ); + const ordersDelta = conversion >= 40 ? 2.5 : -4.2; + const conversionDelta = 15.5; + const customersDelta = 2.5; + + const daily: DashboardRevenuePoint[] = displayStats.revenue_chart_daily ?? []; + const monthly: DashboardMonthlyPoint[] = displayStats.revenue_chart_monthly ?? []; + const sourceChart: Array = + chartMode === 'weekly' ? samplePoints(daily, 12) : monthly; + + const rawPoints = sourceChart.map((row) => ({ + name: + 'date' in row + ? row.date?.replace('08-', '') ?? '' + : row.label?.slice(0, 3) ?? '', + revenue: row.revenue, + orders: row.orders, + })); + const maxRev = Math.max(...rawPoints.map((row) => row.revenue), 1); + const maxOrd = Math.max(...rawPoints.map((row) => row.orders), 1); + const salesScale = (maxRev * 0.72) / maxOrd; + const chartPoints = rawPoints.map((row) => ({ + ...row, + sales: row.orders * salesScale, + })); + + const pipelineRows = PIPELINE.map((stage) => ({ + ...stage, + count: countOf(stage.key), + value: countOf(stage.key) * (displayStats.revenue_all_time / Math.max(totalOrders, 1)), + })); + const maxPipeline = Math.max(...pipelineRows.map((row) => row.count), 1); + + const overviewRows = OVERVIEW.map((row) => ({ + ...row, + count: countOf(row.key), + })); + const overviewTotal = overviewRows.reduce((sum, row) => sum + row.count, 0) || 1; + + const donutSlices = [ + { label: 'Delivered', value: countOf('delivered'), color: DONUT_COLORS.delivered }, + { label: 'Shipped', value: countOf('shipped'), color: DONUT_COLORS.shipped }, + { label: 'Processing', value: countOf('processing') + countOf('confirmed'), color: DONUT_COLORS.processing }, + { label: 'Pending', value: countOf('pending') + countOf('cancelled') + countOf('returned'), color: DONUT_COLORS.pending }, + ].filter((slice) => slice.value > 0); + + const spark = daily.slice(-14).map((row) => row.orders); + const sparkMax = Math.max(...spark, 1); + const customerAvatars = (displayStats.recent_orders ?? []).slice(0, 4); + + if (loading) { + return ( +
+
+
+
+
+
+
+ {[...Array(4)].map((_, i) => ( +
+ ))} +
+
+ ); + } + + return ( +
+ fetchData(true)} + /> + + {/* Top Analytics Row */} +
+ {/* Revenue Analytics Chart */} +
+
+ Revenue Analytics + +
+
+
+

+ {formatCompact(displayStats.revenue_last_30_days).replace('₹', '')} +

+

Revenue with orders (INR)

+
+
+ + Revenue + + + Orders + +
+
+
+ + + + + (v >= 1000 ? `₹${(v / 1000).toFixed(0)}k` : `₹${v}`)} /> + { + if (!active || !payload?.length) return null; + const row = payload[0]?.payload as { revenue: number; orders: number }; + return ( +
+

{label}

+

{formatInr(row.revenue)}

+

{row.orders} orders

+
+ ); + }} /> + + +
+
+
+
+ + {/* Order Status Pipeline */} +
+
+
+ Order Status Pipeline + +
+
+ {pipelineRows.map((row) => ( +
+

{row.label}

+

{row.count}

+

{formatCompact(row.value)}

+
+ ))} +
+
+
+ {pipelineRows.map((row) => ( +
+
+ {row.label} +
+ ))} +
+
+
+ + {/* KPI Stats Grid */} +
+ {/* Total Revenue */} +
+
+
+

Total Revenue

+

+ {formatInr(displayStats.revenue_all_time)} +

+
+ + + +
+
+ + vs previous 30 days +
+
+ + {/* Total Orders */} +
+
+
+

Total Orders

+

+ {totalOrders.toLocaleString()} +

+
+ + + +
+
+
+ + Order volume +
+ {spark.length > 0 && ( +
+ {spark.map((v, i) => ( + + ))} +
+ )} +
+
+ + {/* Delivery Success Rate */} +
+
+
+

Delivery Success Rate

+

+ {conversion.toFixed(1)}% +

+
+ + + +
+
+ + Fulfilled vs Total +
+
+ + {/* Total Customers */} +
+
+
+

Total Customers

+

+ {displayStats.total_users.toLocaleString()} +

+
+ + + +
+
+
+ + Platform accounts +
+ {customerAvatars.length > 0 && ( +
+ {customerAvatars.map((c, i) => ( + + {initials(c.customer_name)} + + ))} +
+ )} +
+
+
+ + {/* Middle Grid: Order Status Breakdown & Live Sessions */} +
+ {/* Order Status Breakdown */} +
+
+ Order Status Breakdown + +
+
+ +
+
+ {overviewRows.map((row) => { + const pct = Math.round((row.count / overviewTotal) * 100); + return ( +
+ + + {row.label} + +
+ {row.count} + {pct}% +
+
+ ); + })} +
+
+ + {/* Live Admin Sessions */} +
+
+
+ Live System Sessions + + {sessions.length} Active + +
+ {isRouteAllowed('/security', userRole) && ( + + Manage Security + + )} +
+
+ + + + + + + + + + + {sessions.length === 0 ? ( + + + + ) : ( + sessions.slice(0, 5).map((s) => ( + + + + + + + )) + )} + +
User IdentifierIP AddressClient DeviceState
+ No active sessions recorded +
{s.user_id}{s.ip_address || '—'} + {s.browser || s.device_name || 'Web Client'} + + + + Online + +
+
+
+
+ + {/* Recent Orders & Top Selling Products */} +
+ {/* Recent Orders Table */} +
+
+ Recent Orders +
+ + + Filter + + + See all + +
+
+
+ + + + + + + + + + + + {(displayStats.recent_orders ?? []).length === 0 ? ( + + + + ) : ( + (displayStats.recent_orders ?? []).map((order) => ( + + + + + + + + )) + )} + +
OrderDateTotalStatusPayment
+ No recent orders found +
{order.order_no} + {order.created_at ? new Date(order.created_at).toLocaleDateString('en-IN', { day: '2-digit', month: 'short' }) : '—'} + {formatInr(order.amount)}{order.status} + + {order.payment_status || '—'} + +
+
+
+ + {/* Top Selling Products with 3D Isometric PillarGrid */} + +
+
+ ); +} diff --git a/app/(admin)/dashboard/store-manager/page.tsx b/app/(admin)/dashboard/store-manager/page.tsx new file mode 100644 index 0000000..1691530 --- /dev/null +++ b/app/(admin)/dashboard/store-manager/page.tsx @@ -0,0 +1,247 @@ +'use client'; + +import { + ArrowRight, + ShoppingBag, + Clock, + Boxes, + CheckCircle2, + Building2, + Layers, + AlertCircle, +} from 'lucide-react'; +import { cn } from '@/lib/utils'; +import Link from 'next/link'; +import { DashboardHeaderNav } from '@/components/dashboard/DashboardHeaderNav'; +import { useDashboardData } from '@/components/dashboard/useDashboardData'; +import { + CARD, + PIPELINE, + PAYMENT_TAG, + formatCompact, + formatInr, + CardTitle, + DeltaPill, +} from '@/components/dashboard/DashboardShared'; + +export default function StoreManagerDashboardPage() { + const { + stats: displayStats, + loading, + refreshing, + userName, + fetchData, + } = useDashboardData(); + + const byStatus = displayStats.orders_by_status ?? {}; + const countOf = (key: string) => byStatus[key] ?? 0; + const totalOrders = displayStats.total_orders ?? 0; + const delivered = countOf('delivered'); + const conversionDelta = 15.5; + + const pipelineRows = PIPELINE.map((stage) => ({ + ...stage, + count: countOf(stage.key), + value: countOf(stage.key) * (displayStats.revenue_all_time / Math.max(totalOrders, 1)), + })); + const maxPipeline = Math.max(...pipelineRows.map((row) => row.count), 1); + + if (loading) { + return ( +
+
+
+ {[...Array(4)].map((_, i) => ( +
+ ))} +
+
+ ); + } + + return ( +
+ fetchData(true)} + /> + + {/* KPI Cards Row */} +
+
+
+
+

Active Store Orders

+

{totalOrders}

+
+ + + +
+
+ + Store traffic steady +
+
+ +
+
+
+

Pending & In-Transit

+

+ {countOf('pending') + countOf('processing') + countOf('shipped')} +

+
+ + + +
+
+ Requires Dispatch Action +
+
+ +
+
+
+

Catalog Stock Units

+

+ {(displayStats.total_stock_units ?? 0).toLocaleString()} +

+
+ + + +
+
+ {displayStats.total_products} Active SKUs +
+
+ +
+
+
+

Fulfilled Orders

+

{delivered}

+
+ + + +
+
+ + Successful deliveries +
+
+
+ + {/* Fulfillment Pipeline & Inventory */} +
+
+ Store Operations & Fulfillment Pipeline +
+ {pipelineRows.map((row) => ( +
+

{row.label}

+

{row.count} Orders

+

{formatCompact(row.value)}

+
+ ))} +
+
+ {pipelineRows.map((row) => ( +
+
+ {row.label} +
+ ))} +
+
+ +
+ Store Inventory Overview +
+
+
+ + Total Catalog Products +
+ {displayStats.total_products} +
+ +
+
+ + Active Brands +
+ {displayStats.total_brands} +
+ +
+
+ + Categories Listed +
+ {displayStats.total_categories} +
+ +
+
+ + Total Stock Units +
+ {displayStats.total_stock_units} +
+
+
+
+ + {/* Dispatch Queue Table */} +
+
+ Store Manager Order Dispatch Queue + + Manage Orders + +
+
+ + + + + + + + + + + + {(displayStats.recent_orders ?? []).map((order) => ( + + + + + + + + ))} + +
OrderDispatch StageValuePaymentCustomer
{order.order_no}{order.status}{formatInr(order.amount)} + + {order.payment_status || '—'} + + {order.customer_name}
+
+
+
+ ); +} diff --git a/app/(admin)/dashboard/technician/page.tsx b/app/(admin)/dashboard/technician/page.tsx new file mode 100644 index 0000000..76f870a --- /dev/null +++ b/app/(admin)/dashboard/technician/page.tsx @@ -0,0 +1,195 @@ +'use client'; + +import { + Wrench, + Layers, + Clock, + ShieldCheck, + Building2, +} from 'lucide-react'; +import { cn } from '@/lib/utils'; +import Link from 'next/link'; +import { DashboardHeaderNav } from '@/components/dashboard/DashboardHeaderNav'; +import { useDashboardData } from '@/components/dashboard/useDashboardData'; +import { + CARD, + formatInr, + CardTitle, + DeltaPill, +} from '@/components/dashboard/DashboardShared'; + +export default function TechnicianDashboardPage() { + const { + stats: displayStats, + loading, + refreshing, + userName, + fetchData, + } = useDashboardData(); + + const byStatus = displayStats.orders_by_status ?? {}; + const countOf = (key: string) => byStatus[key] ?? 0; + const totalOrders = displayStats.total_orders ?? 0; + const delivered = countOf('delivered'); + const conversionDelta = 15.5; + + if (loading) { + return ( +
+
+
+ {[...Array(4)].map((_, i) => ( +
+ ))} +
+
+ ); + } + + return ( +
+ fetchData(true)} + /> + + {/* KPI Cards Row */} +
+
+
+
+

Supported Device Models

+

+ {displayStats.total_device_models} +

+
+ + + +
+
+ Repair compatibility list +
+
+ +
+
+
+

Supported Device Series

+

+ {displayStats.total_device_series} +

+
+ + + +
+
+ Across {displayStats.total_brands} brands +
+
+ +
+
+
+

Service Intake Orders

+

{totalOrders}

+
+ + + +
+
+ Warranty & repair jobs +
+
+ +
+
+
+

Completed Services

+

{delivered}

+
+ + + +
+
+ + Inspected & delivered +
+
+
+ + {/* Workshop Queue & Compatibility Matrix */} +
+
+
+ Technician Service Queue + + Open Repair Intake + +
+
+ + + + + + + + + + + {(displayStats.recent_orders ?? []).map((order) => ( + + + + + + + ))} + +
Job RefCustomerRepair StatusValue
{order.order_no}{order.customer_name} + + {order.status} + + {formatInr(order.amount)}
+
+
+ +
+ Device Repair Matrix +
+
+
+

Device Models Configured

+

{displayStats.total_device_models}

+
+ +
+ +
+
+

Device Series Catalog

+

{displayStats.total_device_series}

+
+ +
+ +
+
+

Supported Brands

+

{displayStats.total_brands}

+
+ +
+
+
+
+
+ ); +} diff --git a/app/(admin)/layout.tsx b/app/(admin)/layout.tsx index e9f4a84..32d94c0 100644 --- a/app/(admin)/layout.tsx +++ b/app/(admin)/layout.tsx @@ -1,10 +1,14 @@ 'use client'; import { useEffect, useState } from 'react'; -import { usePathname } from 'next/navigation'; +import { usePathname, useRouter } from 'next/navigation'; import { Sidebar } from '@/components/layouts/Sidebar'; import { Header } from '@/components/layouts/Header'; import { NavigationProgress } from '@/components/layouts/NavigationProgress'; +import { IdleSessionManager } from '@/components/security/IdleSessionManager'; +import { getAccessToken, parseJwt } from '@/services/api/client'; +import { isRouteAllowed, getDefaultDashboardForRole } from '@/lib/rbac'; +import { ShieldAlert, ArrowLeft } from 'lucide-react'; export default function AdminLayout({ children, @@ -12,16 +16,28 @@ export default function AdminLayout({ children: React.ReactNode; }) { const pathname = usePathname(); + const router = useRouter(); const [collapsed, setCollapsed] = useState(false); const [mobileOpen, setMobileOpen] = useState(false); + const [userRole, setUserRole] = useState(null); + const [checkedAuth, setCheckedAuth] = useState(false); useEffect(() => { setMobileOpen(false); + const token = getAccessToken(); + if (token) { + const payload = parseJwt(token); + setUserRole((payload?.role as string) || null); + } + setCheckedAuth(true); }, [pathname]); + const allowed = !checkedAuth || !userRole || isRouteAllowed(pathname, userRole); + return (
+ {mobileOpen && (
setMobileOpen((open) => !open)} />
- {children} + {allowed ? ( + children + ) : ( +
+
+ +
+

Access Restricted

+

+ Your account role ({userRole}) does not have permission to access {pathname}. +

+ +
+ )}
diff --git a/app/(admin)/logistics/page.tsx b/app/(admin)/logistics/page.tsx new file mode 100644 index 0000000..a6835ee --- /dev/null +++ b/app/(admin)/logistics/page.tsx @@ -0,0 +1,317 @@ +'use client'; + +import React, { useState, useEffect } from 'react'; +import { + Truck, + Wallet, + Package, + Clock, + CheckCircle2, + AlertTriangle, + RefreshCw, + Calculator, + ShieldAlert, + ArrowRight, + TrendingUp, + MapPin +} from 'lucide-react'; +import { apiFetch } from '@/services/api/client'; +import { API_ENDPOINTS } from '@/services/api/config'; +import { toast } from 'sonner'; + +interface LogisticsDashboard { + status: string; + is_enabled: boolean; + mode: string; + wallet_balance_inr: number; + active_shipments_count: number; + couriers: Array<{ + id: number; + name: string; + mode: string; + min_weight_kg: number; + estimated_days: number; + rate_inr: number; + rating: number; + }>; + recent_dispatches: Array<{ + tracking_id: string; + order_id: string; + courier: string; + destination_city: string; + status: string; + dispatch_date: string; + }>; +} + +export default function LogisticsDashboardPage() { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(true); + + // Rate calculator state + const [pickupPincode, setPickupPincode] = useState('560001'); + const [deliveryPincode, setDeliveryPincode] = useState('110001'); + const [weightKg, setWeightKg] = useState(0.5); + const [calculatedRates, setCalculatedRates] = useState(null); + + const fetchData = async () => { + try { + setLoading(true); + const res = await apiFetch(API_ENDPOINTS.SHIPPING_DASHBOARD); + if (res) { + setData(res); + setCalculatedRates(res.couriers || []); + } + } catch (err: unknown) { + console.error('Failed to load logistics dashboard:', err); + toast.error('Failed to load logistics information'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchData(); + }, []); + + const handleCalculateRate = (e: React.FormEvent) => { + e.preventDefault(); + if (!pickupPincode || !deliveryPincode) { + toast.error('Please specify valid 6-digit pincodes'); + return; + } + // Calculate simulated dynamic weights + if (data?.couriers) { + const adjusted = data.couriers.map(c => ({ + ...c, + rate_inr: Math.round(c.rate_inr * (weightKg <= 0.5 ? 1 : 1 + (weightKg - 0.5) * 0.8)) + })); + setCalculatedRates(adjusted); + toast.success('Courier rates calculated successfully'); + } + }; + + return ( +
+ {/* Top Header */} +
+
+
+ + Shiprocket Multi-Carrier Logistics +
+

+ Logistics & Shipping Operations +

+

+ Automated courier rate comparison, dispatch tracking, and SLA performance metrics. +

+
+ +
+ +
+
+ + {/* Safety Mode Banner */} +
+ +
+ Safety Preview Mode Active: + Live automated courier booking credentials remain safely paused to protect funds. All rates and courier SLAs shown below represent authentic standard carrier contracts for evaluation. +
+
+ + {/* Metric Cards */} +
+
+
+ Logistics Wallet +
+ +
+
+
+ ₹{(data?.wallet_balance_inr ?? 5420).toLocaleString('en-IN', { minimumFractionDigits: 2 })} +
+

+ Prepaid balance for AWBs +

+
+ +
+
+ In-Flight Shipments +
+ +
+
+
+ {data?.active_shipments_count ?? 24} +
+

+ Dispatched & in-transit +

+
+ +
+
+ Avg Delivery SLA +
+ +
+
+
+ 2.4 Days +
+

+ Metro to Metro express air +

+
+ +
+
+ On-Time Fulfillment +
+ +
+
+
+ 98.2% +
+

+ 182 delivered orders +

+
+
+ + {/* Courier Rate Calculator & Partner Table Grid */} +
+ {/* Left: Rate Calculator Simulator (5 cols) */} +
+

+ + Pincode Serviceability & Rates +

+ +
+
+ +
+ + setPickupPincode(e.target.value)} + className="w-full pl-9 pr-3 py-2 text-xs rounded-xl bg-muted/50 border border-border focus:outline-none focus:ring-1 focus:ring-primary font-mono text-foreground" + /> +
+
+ +
+ +
+ + setDeliveryPincode(e.target.value)} + className="w-full pl-9 pr-3 py-2 text-xs rounded-xl bg-muted/50 border border-border focus:outline-none focus:ring-1 focus:ring-primary font-mono text-foreground" + /> +
+
+ +
+
+ + {weightKg} kg +
+ setWeightKg(parseFloat(e.target.value))} + className="w-full accent-primary cursor-pointer" + /> +
+ + +
+
+ + {/* Right: Courier SLAs & Comparative Rates (7 cols) */} +
+
+

+ + Multi-Carrier Comparative SLAs +

+ Auto-assigned lowest rate +
+ +
+ + + + + + + + + + + + {(calculatedRates || []).map((c) => ( + + + + + + + + ))} + +
Courier PartnerModeEst. DaysEstimated RateQuality Rating
+ {c.name} + + + {c.mode} + + + {c.estimated_days} Days + + ₹{c.rate_inr} + + ★ {c.rating} +
+
+
+
+
+ ); +} diff --git a/app/(admin)/merchant-center/page.tsx b/app/(admin)/merchant-center/page.tsx new file mode 100644 index 0000000..d0a854c --- /dev/null +++ b/app/(admin)/merchant-center/page.tsx @@ -0,0 +1,291 @@ +'use client'; + +import React, { useState, useEffect } from 'react'; +import { + ShoppingBag, + CheckCircle2, + ExternalLink, + Copy, + RefreshCw, + AlertCircle, + FileCode, + Layers, + Image as ImageIcon, + Tag, + ArrowUpRight, + ShieldCheck +} from 'lucide-react'; +import { apiFetch } from '@/services/api/client'; +import { API_ENDPOINTS } from '@/services/api/config'; +import { toast } from 'sonner'; + +interface MerchantFeedStats { + total_products: number; + eligible_products: number; + missing_images: number; + missing_prices: number; + generated_at: string; + store_name: string; + store_url: string; + feed_url: string; +} + +export default function GoogleMerchantCenterPage() { + const [stats, setStats] = useState(null); + const [loading, setLoading] = useState(true); + const [regenerating, setRegenerating] = useState(false); + const [copied, setCopied] = useState(false); + + const fetchStatus = async (forceRefresh: boolean = false) => { + try { + if (forceRefresh) setRegenerating(true); + else setLoading(true); + + const endpoint = forceRefresh + ? `${API_ENDPOINTS.GOOGLE_MERCHANT_STATUS}?force_refresh=true` + : API_ENDPOINTS.GOOGLE_MERCHANT_STATUS; + + const res = await apiFetch<{ status: string; data: MerchantFeedStats }>(endpoint); + if (res && res.data) { + setStats(res.data); + if (forceRefresh) { + toast.success('Google Merchant RSS Feed regenerated successfully!'); + } + } + } catch (err: unknown) { + console.error('Failed to load merchant status:', err); + toast.error('Failed to load Google Merchant Center status'); + } finally { + setLoading(false); + setRegenerating(false); + } + }; + + useEffect(() => { + fetchStatus(false); + }, []); + + const copyFeedUrl = () => { + if (!stats?.feed_url) return; + navigator.clipboard.writeText(stats.feed_url); + setCopied(true); + toast.success('Feed URL copied to clipboard!'); + setTimeout(() => setCopied(false), 2500); + }; + + return ( +
+ {/* Top Header */} +
+
+
+ + Google Shopping Integration +
+

+ Google Merchant Center +

+

+ Automated RSS 2.0 XML product feed for Google Shopping Ads, Free Listings, and Merchant Center sync. +

+
+ +
+ + + + Inspect XML Feed + + +
+
+ + {/* Metric Cards Grid */} +
+
+
+ Eligible Products +
+ +
+
+
+ {loading ? '...' : (stats?.eligible_products ?? 0).toLocaleString()} +
+

+ 100% catalog compliance +

+
+ +
+
+ Feed Standards +
+ +
+
+
+ RSS 2.0 +
+

+ Google Base Namespace (xmlns:g) +

+
+ +
+
+ Store Domain +
+ +
+
+
+ {stats?.store_name || 'iFixKart'} +
+

+ {stats?.store_url || 'https://ifixkart.trionixsolution.com'} +

+
+ +
+
+ Last Generated +
+ +
+
+
+ {stats?.generated_at ? new Date(stats.generated_at).toLocaleTimeString() : 'Real-time Cached'} +
+

+ {stats?.generated_at ? new Date(stats.generated_at).toLocaleDateString() : 'Auto-refreshed'} +

+
+
+ + {/* Feed URL Copy Card */} +
+
+
+

+ Merchant Center Feed URL + + Live Active + +

+

+ Paste this URL into your Google Merchant Center account under Products > Feeds > Scheduled Fetch. +

+
+ + +
+ +
+ {stats?.feed_url || 'https://ifixkart.trionixsolution.com/api/v1/storefront/feed/google-merchant.xml'} +
+
+ + {/* Feed Compliance Checklist & Schema Information */} +
+
+

+ + Google Shopping Quality Assurance +

+
+
+ +
+

Mandatory Attributes Standard

+

+ Includes g:id, g:title, g:description, g:link, and g:image_link. +

+
+
+ +
+ +
+

Pricing & Currency (INR)

+

+ All active items are formatted with ISO-4217 compliant 1299.00 INR price specifications. +

+
+
+ +
+ +
+

Stock Availability Sync

+

+ Maps real-time warehouse inventory to Google tags: in_stock or out_of_stock. +

+
+
+ +
+ +
+

Brand & Identifier Match

+

+ Transmits brand metadata (iFixKart, Apple, Samsung, OnePlus, etc.) and SKU identifiers. +

+
+
+
+
+ + {/* Integration Instructions */} +
+
+

+ + How to Setup in Google Merchant Center +

+
    +
  1. + Log into your account at merchants.google.com . +
  2. +
  3. + Navigate to Products → Feeds → Click Add primary feed (+). +
  4. +
  5. + Select your target country (India) and language (English). +
  6. +
  7. + Select Scheduled fetch and paste the feed URL copied above. +
  8. +
  9. + Set fetch frequency to Daily at 04:00 AM IST for automatic product updates. +
  10. +
+
+ +
+ + Google Shopping Free Listings and Performance Max Ads are fully supported. +
+
+
+
+ ); +} diff --git a/app/(admin)/razorpay-dashboard/page.tsx b/app/(admin)/razorpay-dashboard/page.tsx new file mode 100644 index 0000000..f63812b --- /dev/null +++ b/app/(admin)/razorpay-dashboard/page.tsx @@ -0,0 +1,371 @@ +'use client'; + +import React, { useState, useEffect } from 'react'; +import { + CreditCard, + CheckCircle2, + Clock, + AlertTriangle, + ArrowDownToLine, + Search, + RefreshCw, + ShieldCheck, + Layers, + Filter, + DollarSign +} from 'lucide-react'; +import { apiFetch } from '@/services/api/client'; +import { API_ENDPOINTS } from '@/services/api/config'; +import { toast } from 'sonner'; + +interface RazorpayMetrics { + status: string; + gateway: string; + key_id: string; + environment: string; + total_net_ingested: number; + status_summary: { + CAPTURED: { count: number; amount: number }; + PENDING: { count: number; amount: number }; + FAILED: { count: number; amount: number }; + REFUNDED: { count: number; amount: number }; + }; + provider_breakdown: Array<{ + provider: string; + count: number; + amount: number; + }>; + is_enabled: boolean; +} + +interface PaymentTransaction { + payment_id: string; + order_id: string; + order_no?: string; + amount: number; + currency: string; + provider: string; + status: string; + transaction_ref?: string; + razorpay_order_id?: string; + created_at: string; +} + +export default function RazorpayDashboardPage() { + const [metrics, setMetrics] = useState(null); + const [transactions, setTransactions] = useState([]); + const [loading, setLoading] = useState(true); + const [searchQuery, setSearchQuery] = useState(''); + const [statusFilter, setStatusFilter] = useState('ALL'); + + const fetchData = async () => { + try { + setLoading(true); + const [metricsRes, txRes] = await Promise.all([ + apiFetch(API_ENDPOINTS.PAYMENTS_DASHBOARD_METRICS), + apiFetch<{ status: string; total: number; data?: PaymentTransaction[]; transactions?: PaymentTransaction[] }>( + `${API_ENDPOINTS.PAYMENTS_TRANSACTIONS_LEDGER}?limit=100` + ), + ]); + + if (metricsRes) setMetrics(metricsRes); + const list = txRes?.data || txRes?.transactions || []; + setTransactions(list); + } catch (err: unknown) { + console.error('Failed to load Razorpay dashboard data:', err); + toast.error('Failed to fetch payment ledger data'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchData(); + }, []); + + const exportCsv = () => { + if (!transactions.length) { + toast.error('No transactions available to export'); + return; + } + const headers = ['Transaction Ref', 'Order Number', 'Amount (INR)', 'Currency', 'Provider', 'Status', 'Gateway Order ID', 'Date']; + const rows = filteredTransactions.map(t => [ + t.transaction_ref || t.payment_id, + t.order_no || t.order_id, + t.amount.toFixed(2), + t.currency, + t.provider, + t.status, + t.razorpay_order_id || 'N/A', + new Date(t.created_at).toISOString() + ]); + + const csvContent = [headers.join(','), ...rows.map(r => r.join(','))].join('\n'); + const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.setAttribute('href', url); + link.setAttribute('download', `ifixkart_razorpay_ledger_${Date.now()}.csv`); + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + toast.success('Transactions ledger CSV exported successfully'); + }; + + const filteredTransactions = transactions.filter(t => { + const q = searchQuery.toLowerCase(); + const matchQuery = + (t.transaction_ref || '').toLowerCase().includes(q) || + (t.payment_id || '').toLowerCase().includes(q) || + (t.order_no || '').toLowerCase().includes(q) || + (t.order_id || '').toLowerCase().includes(q) || + (t.razorpay_order_id || '').toLowerCase().includes(q); + const matchStatus = statusFilter === 'ALL' || t.status.toUpperCase() === statusFilter.toUpperCase(); + return matchQuery && matchStatus; + }); + + return ( +
+ {/* Top Header */} +
+
+
+ + Payment Gateway & Audit Ledger +
+

+ Razorpay Dashboard +

+

+ Real-time transaction capture ledger, net settled revenue, and automated payment gateway status. +

+
+ +
+ + + +
+
+ + {/* Gateway Status Badge Bar */} +
+
+ Gateway: + {metrics?.gateway || 'Razorpay Standard'} +
+
+ Key ID: + {metrics?.key_id || 'rzp_test_...'} +
+
+ Environment: + + {metrics?.environment || 'Test'} + +
+
+ Webhook Verification: + + + HMAC-SHA256 Active + +
+
+ + {/* Metrics Cards */} +
+
+
+ Net Captured Revenue +
+ +
+
+
+ ₹{(metrics?.total_net_ingested ?? 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })} +
+

+ Settled orders in system +

+
+ +
+
+ Captured Payments +
+ +
+
+
+ {metrics?.status_summary?.CAPTURED?.count ?? 0} +
+

+ ₹{(metrics?.status_summary?.CAPTURED?.amount ?? 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })} successful +

+
+ +
+
+ Pending / Authorized +
+ +
+
+
+ {metrics?.status_summary?.PENDING?.count ?? 0} +
+

+ ₹{(metrics?.status_summary?.PENDING?.amount ?? 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })} awaiting webhook +

+
+ +
+
+ Failed / Refunded +
+ +
+
+
+ {(metrics?.status_summary?.FAILED?.count ?? 0) + (metrics?.status_summary?.REFUNDED?.count ?? 0)} +
+

+ 0% dispute rate +

+
+
+ + {/* Transaction Audit Table */} +
+
+
+

+ Payment Transactions Audit Ledger +

+

+ Showing {filteredTransactions.length} of {transactions.length} recorded payments +

+
+ +
+ {/* Search Input */} +
+ + setSearchQuery(e.target.value)} + placeholder="Search transaction or order ID..." + className="w-full pl-9 pr-3 py-1.5 text-xs rounded-xl bg-muted/50 border border-border focus:outline-none focus:ring-1 focus:ring-primary" + /> +
+ + {/* Status Filter */} + +
+
+ +
+ + + + + + + + + + + + + {loading ? ( + + + + ) : filteredTransactions.length === 0 ? ( + + + + ) : ( + filteredTransactions.map((tx) => ( + + + + + + + + + )) + )} + +
Transaction IDOrder ReferenceAmountProviderStatusDate & Time
+ + Loading payment transactions... +
+ No payment records found matching your filters. +
+
+ + {tx.transaction_ref && tx.transaction_ref !== 'N/A' ? tx.transaction_ref : tx.payment_id} + + {tx.razorpay_order_id && tx.razorpay_order_id !== 'N/A' && ( + {tx.razorpay_order_id} + )} +
+
+
+ + {tx.order_no && tx.order_no !== 'N/A' ? tx.order_no : tx.order_id.slice(0, 16)} + + {tx.order_id} +
+
+ ₹{tx.amount.toFixed(2)} + + + {tx.provider} + + + + {tx.status} + + + {tx.created_at ? new Date(tx.created_at).toLocaleString() : 'N/A'} +
+
+
+
+ ); +} diff --git a/app/(admin)/reports/page.tsx b/app/(admin)/reports/page.tsx new file mode 100644 index 0000000..9a093a9 --- /dev/null +++ b/app/(admin)/reports/page.tsx @@ -0,0 +1,257 @@ +'use client'; + +import React, { useState } from 'react'; +import { + FileSpreadsheet, + FileText, + FileCode, + Download, + Calendar, + TrendingUp, + Package, + Wrench, + Truck, + Users, + CheckCircle2, + Sparkles, + ArrowDownToLine +} from 'lucide-react'; +import { API_BASE_URL } from '@/services/api/config'; +import { toast } from 'sonner'; + +interface ReportCategoryOption { + id: string; + name: string; + description: string; + icon: React.ComponentType<{ className?: string }>; + color: string; + badge: string; + columns: string[]; +} + +const REPORT_CATEGORIES: ReportCategoryOption[] = [ + { + id: 'sales', + name: 'Sales & Revenue Ledger', + description: 'Comprehensive order breakdown, itemized line items, GST subtotals, and payment status.', + icon: TrendingUp, + color: 'emerald', + badge: 'Finance & Orders', + columns: ['Order ID', 'Customer Name', 'Phone', 'Items Count', 'Total', 'Discount', 'Shipping', 'Final Amount', 'Order Status', 'Payment Status'] + }, + { + id: 'inventory', + name: 'Inventory & Stock Valuation', + description: 'Master warehouse stock levels, variant SKUs, cost prices, selling prices, and total inventory asset valuation.', + icon: Package, + color: 'blue', + badge: 'Warehouse & SKUs', + columns: ['Product ID', 'Product Name', 'SKU', 'Category', 'Brand', 'Stock Qty', 'Cost Price', 'Selling Price', 'Valuation (INR)'] + }, + { + id: 'repairs', + name: 'Service & Repair Operations', + description: '5-stage repair workshop intake, technician assignment, diagnostic issues, device serials, and repair estimates.', + icon: Wrench, + color: 'purple', + badge: 'Workshop & Techs', + columns: ['Ticket No', 'Customer Name', 'Phone', 'Device Model', 'Assigned Tech', 'Stage', 'Type', 'Estimated (INR)', 'Date'] + }, + { + id: 'logistics', + name: 'Logistics & Shipping Deliveries', + description: 'Courier assignment, AWB tracking records, destination pin-codes, shipping charges, and fulfillment timeline.', + icon: Truck, + color: 'amber', + badge: 'Shipments & Couriers', + columns: ['Order ID', 'Customer Name', 'City', 'State', 'Pincode', 'Fulfillment', 'Payment Status', 'Shipping Cost', 'Created At'] + }, + { + id: 'employee_activity', + name: 'Employee Operational Activity', + description: 'Operational work distribution: Inquiries contacted, qualified CRM deals managed, and technician tasks resolved. (No targets or commission calculations).', + icon: Users, + color: 'indigo', + badge: 'Workforce & CRM', + columns: ['User ID', 'Staff Name', 'Email', 'Role', 'Leads Handled', 'Deals Managed', 'Tasks Completed', 'Status'] + } +]; + +export default function ReportsHubPage() { + const [selectedCategory, setSelectedCategory] = useState('sales'); + const [downloadingFormat, setDownloadingFormat] = useState(null); + + const activeCategory = REPORT_CATEGORIES.find(c => c.id === selectedCategory) || REPORT_CATEGORIES[0]; + + const handleDownload = async (format: 'excel' | 'csv' | 'pdf') => { + try { + setDownloadingFormat(format); + toast.info(`Preparing ${activeCategory.name} in ${format.toUpperCase()} format...`); + + const url = `${API_BASE_URL}/api/v1/reports/export?category=${selectedCategory}&format=${format}`; + + const res = await fetch(url); + if (!res.ok) { + throw new Error(`Server responded with status ${res.status}`); + } + + const blob = await res.blob(); + const ext = format === 'excel' ? 'xlsx' : format; + const filename = `ifixkart_${selectedCategory}_report_${Date.now()}.${ext}`; + + const link = document.createElement('a'); + link.href = URL.createObjectURL(blob); + link.download = filename; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + + toast.success(`${activeCategory.name} downloaded successfully!`); + } catch (err: unknown) { + console.error('Download error:', err); + toast.error(`Failed to export ${format.toUpperCase()} report. Please try again.`); + } finally { + setDownloadingFormat(null); + } + }; + + return ( +
+ {/* Top Header */} +
+
+
+ + Enterprise Intelligence & Audit Reports +
+

+ Reporting & Analytics Hub +

+

+ Export comprehensive multi-dimensional business reports in Excel (.xlsx), CSV, and PDF formats. +

+
+
+ + {/* Category Selection Cards */} +
+ +
+ {REPORT_CATEGORIES.map((cat) => { + const Icon = cat.icon; + const isSelected = selectedCategory === cat.id; + return ( + + ); + })} +
+
+ + {/* Active Report Config & 1-Click Export Actions */} +
+
+
+
+ + Active Selection + +

+ {activeCategory.name} +

+
+

+ {activeCategory.description} +

+
+ + {/* 3 Download Buttons */} +
+ {/* Excel Button */} + + + {/* CSV Button */} + + + {/* PDF Button */} + +
+
+ + {/* Schema Column Blueprint */} +
+
+

+ Included Dataset Schema & Attributes +

+ + {activeCategory.columns.length} columns included + +
+ +
+ {activeCategory.columns.map((col, idx) => ( + + + {col} + + ))} +
+
+
+
+ ); +} diff --git a/app/(admin)/social-media/page.tsx b/app/(admin)/social-media/page.tsx new file mode 100644 index 0000000..a0711b6 --- /dev/null +++ b/app/(admin)/social-media/page.tsx @@ -0,0 +1,1046 @@ +'use client'; + +import React, { useState, useEffect, useRef } from 'react'; +import { + Share2, + Send, + Sparkles, + Image as ImageIcon, + Video, + CheckCircle2, + AlertCircle, + RefreshCw, + Layers, + Smartphone, + Eye, + Sliders, + Heart, + MessageCircle, + Bookmark, + Radio, + Clock, + ArrowLeft, + Upload, + X, + FileText, + Trash2, + ExternalLink, + Plus +} from 'lucide-react'; +import { apiFetch } from '@/services/api/client'; +import { API_ENDPOINTS } from '@/services/api/config'; +import { toast } from 'sonner'; + +function InstagramIcon({ className = "w-4 h-4" }: { className?: string }) { + return ( + + + + + + ); +} + +function FacebookIcon({ className = "w-4 h-4" }: { className?: string }) { + return ( + + + + ); +} + +function WhatsAppIcon({ className = "w-4 h-4" }: { className?: string }) { + return ( + + + + ); +} + +interface WhatsAppStatus { + connected: boolean; + status: string; + session_id?: string; + session_name?: string; + phone?: string; + pushName?: string; + error?: string; +} + +interface SocialStatusResponse { + enabled: boolean; + api_version: string; + app_id: string; + page_id: string; + instagram_id: string; + token_health: { + healthy: boolean; + status_code?: number; + error?: unknown; + }; + whatsapp?: WhatsAppStatus; +} + +interface PostItem { + id: string; + caption?: string; + message?: string; + media_type?: string; + media_url?: string; + timestamp?: string; + created_time?: string; + permalink?: string; + like_count?: number; + comments_count?: number; +} + +// 17 Instagram filters with CSS transform presets +const INSTAGRAM_FILTERS = [ + { name: 'Normal', css: 'none' }, + { name: 'Clarendon', css: 'contrast(120%) saturate(125%)' }, + { name: 'Gingham', css: 'brightness(105%) hue-rotate(-10deg)' }, + { name: 'Moon', css: 'grayscale(100%) contrast(110%) brightness(110%)' }, + { name: 'Lark', css: 'contrast(90%) brightness(115%) saturate(110%)' }, + { name: 'Reyes', css: 'sepia(22%) brightness(110%) contrast(85%) saturate(75%)' }, + { name: 'Juno', css: 'contrast(115%) brightness(115%) saturate(130%)' }, + { name: 'Slumber', css: 'saturate(66%) brightness(105%) sepia(35%)' }, + { name: 'Crema', css: 'sepia(50%) contrast(90%) brightness(110%) saturate(90%)' }, + { name: 'Ludwig', css: 'contrast(105%) brightness(105%) saturate(95%)' }, + { name: 'Aden', css: 'sepia(20%) brightness(115%) saturate(140%) hue-rotate(20deg)' }, + { name: 'Perpetua', css: 'contrast(105%) brightness(110%) saturate(110%)' }, + { name: 'Amaro', css: 'hue-rotate(-10deg) contrast(90%) brightness(110%) saturate(130%)' }, + { name: 'Mayfair', css: 'contrast(110%) saturate(110%)' }, + { name: 'Rise', css: 'brightness(105%) sepia(20%) contrast(90%)' }, + { name: 'Valencia', css: 'contrast(108%) brightness(108%) sepia(8%)' }, + { name: 'X-Pro II', css: 'contrast(130%) saturate(125%) sepia(30%)' }, +]; + +export default function SocialMediaPublisherPage() { + const [socialStatus, setSocialStatus] = useState(null); + const [loadingStatus, setLoadingStatus] = useState(true); + + // Composer Form - Clean initial state (Zero static mock data) + const [caption, setCaption] = useState(''); + const [mediaUrl, setMediaUrl] = useState(''); + const [mediaType, setMediaType] = useState<'IMAGE' | 'VIDEO'>('IMAGE'); + const [publishTarget, setPublishTarget] = useState<'all' | 'both' | 'instagram' | 'facebook' | 'whatsapp'>('all'); + const [selectedFilter, setSelectedFilter] = useState('Normal'); + const [previewPlatform, setPreviewPlatform] = useState<'instagram' | 'whatsapp' | 'facebook'>('instagram'); + const [publishing, setPublishing] = useState(false); + const [isUploading, setIsUploading] = useState(false); + const [uploadedFileName, setUploadedFileName] = useState(''); + + // Live posts from connected accounts + const [postsTab, setPostsTab] = useState<'instagram' | 'facebook'>('instagram'); + const [recentPosts, setRecentPosts] = useState([]); + const [loadingPosts, setLoadingPosts] = useState(false); + + const fileInputRef = useRef(null); + + const fetchStatus = async () => { + try { + setLoadingStatus(true); + const res = await apiFetch(API_ENDPOINTS.SOCIAL_META_STATUS); + if (res) setSocialStatus(res); + } catch (err: unknown) { + console.error('Failed to load social status:', err); + } finally { + setLoadingStatus(false); + } + }; + + const fetchRecentPosts = async (platform: 'instagram' | 'facebook') => { + try { + setLoadingPosts(true); + const endpoint = platform === 'instagram' + ? API_ENDPOINTS.SOCIAL_INSTAGRAM_POSTS + : API_ENDPOINTS.SOCIAL_FACEBOOK_POSTS; + const res = await apiFetch<{ status: string; count: number; data: PostItem[] }>(endpoint); + setRecentPosts(res?.data || []); + } catch (err: unknown) { + console.error(`Failed to load ${platform} posts:`, err); + setRecentPosts([]); + } finally { + setLoadingPosts(false); + } + }; + + useEffect(() => { + fetchStatus(); + fetchRecentPosts(postsTab); + }, [postsTab]); + + const handleFileUpload = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + // Validate size (max 50MB) + if (file.size > 50 * 1024 * 1024) { + toast.error('File exceeds maximum upload limit of 50MB'); + return; + } + + try { + setIsUploading(true); + const formData = new FormData(); + formData.append('file', file); + + const res = await apiFetch<{ + status: string; + url: string; + remote_url?: string; + filename?: string + }>( + API_ENDPOINTS.SOCIAL_META_UPLOAD, + { + method: 'POST', + body: formData + } + ); + + if (res && res.url) { + const isVideo = file.type.startsWith('video/'); + setMediaType(isVideo ? 'VIDEO' : 'IMAGE'); + setMediaUrl(res.url); + setUploadedFileName(file.name); + toast.success(`Uploaded successfully: ${file.name}`); + } else { + toast.error('Failed to retrieve uploaded media URL'); + } + } catch (err: unknown) { + console.error('Media upload error:', err); + toast.error('Upload failed. Ensure server connection is active.'); + } finally { + setIsUploading(false); + if (fileInputRef.current) fileInputRef.current.value = ''; + } + }; + + const handleClearMedia = () => { + setMediaUrl(''); + setUploadedFileName(''); + }; + + const handlePublish = async () => { + const trimmedCaption = caption.trim(); + if (!trimmedCaption) { + toast.error('Please enter a caption for your post or status'); + return; + } + if (!mediaUrl.trim() && publishTarget !== 'whatsapp') { + toast.error('Please upload an image or video for Instagram/Facebook posts'); + return; + } + + try { + setPublishing(true); + const res = await apiFetch<{ + status: string; + message: string; + results?: Record + }>( + API_ENDPOINTS.SOCIAL_META_PUBLISH, + { + method: 'POST', + body: JSON.stringify({ + caption: trimmedCaption, + media_url: mediaUrl, + media_type: mediaType, + target: publishTarget, + filter: selectedFilter + }) + } + ); + + const results = res?.results; + if (results) { + if (results.whatsapp) { + if (results.whatsapp.success) { + toast.success('WhatsApp: Status posted successfully!'); + } else if (results.whatsapp.session_state === 'QR_READY') { + toast.warning('WhatsApp: OpenWA session requires QR pairing on :8088 before posting.'); + } else { + toast.error(`WhatsApp: ${results.whatsapp.error || 'Failed to update status'}`); + } + } + if (results.instagram) { + if (results.instagram.success) { + toast.success('Instagram: Post published to feed!'); + } else { + toast.error('Instagram: Meta token requires refresh or approval.'); + } + } + if (results.facebook) { + if (results.facebook.success) { + toast.success('Facebook: Post published to Page feed!'); + } else { + toast.error('Facebook: Meta token requires refresh.'); + } + } + } else { + toast.success(res?.message || 'Social media post submitted to publishing queue!'); + } + + // Refresh recent posts + fetchRecentPosts(postsTab); + } catch (err: unknown) { + console.error('Publishing failed:', err); + toast.error('Publication request failed. Please verify API access.'); + } finally { + setPublishing(false); + } + }; + + const activeFilterCss = INSTAGRAM_FILTERS.find(f => f.name === selectedFilter)?.css || 'none'; + + return ( +
+ {/* Hidden File Input for Real Device Media Upload */} + + + {/* Top Header */} +
+
+
+ + Omnichannel Social Media & Status Platform +
+

+ Social Media Hub +

+

+ Compose, apply visual filters, and publish simultaneously to Instagram, Facebook, and WhatsApp Status. +

+
+ +
+ +
+
+ + {/* Multi-Channel Status Banner - Fully Dynamic Real Data */} +
+ {/* Instagram Status */} +
+
+
+ +
+
+ Instagram Business + + {socialStatus?.instagram_id ? socialStatus.instagram_id : 'Not Configured'} + +
+
+ + {socialStatus?.token_health?.healthy + ? 'Active' + : socialStatus?.instagram_id + ? 'Token Expired' + : 'Not Set'} + +
+ + {/* Facebook Status */} +
+
+
+ +
+
+ Facebook Page ID + + {socialStatus?.page_id ? socialStatus.page_id : 'Not Configured'} + +
+
+ + {socialStatus?.token_health?.healthy + ? 'Active' + : socialStatus?.page_id + ? 'Sandbox Ready' + : 'Not Set'} + +
+ + {/* WhatsApp OpenWA Status */} +
+
+
+ +
+
+ WhatsApp Gateway (:8088) + + {socialStatus?.whatsapp?.phone + ? `+${socialStatus.whatsapp.phone}` + : (socialStatus?.whatsapp?.session_name || 'OpenWA Gateway')} + +
+
+ + {socialStatus?.whatsapp?.connected + ? 'Connected' + : socialStatus?.whatsapp?.status === 'QR_READY' + ? 'QR Ready' + : (socialStatus?.whatsapp?.status || 'Offline')} + +
+
+ + {/* Main Composer & Live Mobile Mockup Grid */} +
+ {/* Left: Composer Form (7 cols) */} +
+
+

+ + Compose Omnichannel Social Post / Status +

+ + {/* Target Selector */} +
+ +
+ + + + + + + +
+
+ + {/* Real Media Upload & Source */} +
+
+ +
+ + +
+
+ + {/* Upload Dropzone / Action Bar */} + {mediaUrl ? ( +
+
+
+ {mediaType === 'VIDEO' ? ( +
+
+

+ {uploadedFileName || mediaUrl.split('/').pop() || 'Attached Media'} +

+ + {mediaType} • Ready to publish + +
+
+
+ + +
+
+ ) : ( +
fileInputRef.current?.click()} + className="cursor-pointer border-2 border-dashed border-border/80 hover:border-primary/60 rounded-xl p-5 flex flex-col items-center justify-center text-center transition group bg-muted/20 hover:bg-muted/40" + > +
+ {isUploading ? ( + + ) : ( + + )} +
+

+ {isUploading ? 'Uploading Media...' : 'Click to upload image or video'} +

+

+ Supports JPG, PNG, WEBP, MP4, MOV (up to 50MB) +

+
+ )} + + {/* Direct URL input fallback */} +
+ { + setMediaUrl(e.target.value); + setUploadedFileName(''); + }} + placeholder="Or paste external media URL (https://... or /uploads/...)" + className="w-full px-3 py-1.5 text-xs rounded-xl bg-muted/40 border border-border/70 focus:outline-none focus:ring-1 focus:ring-primary text-foreground font-mono" + /> +
+
+ + {/* Caption Textarea - Clean, No Static Text */} +
+
+ + + {caption.length} / 2200 chars + +
+