ifixkart-admin/components/dashboard/useDashboardData.ts

214 lines
7.8 KiB
TypeScript

'use client';
import { useEffect, useState, useCallback } from 'react';
import {
adminService,
DashboardStats,
SessionInfo,
DashboardRevenuePoint,
DashboardMonthlyPoint,
DashboardRecentOrder,
DashboardTopProduct,
} from '@/services/api/adminService';
import { parseJwt, getAccessToken, apiFetch } from '@/services/api/client';
import { withDashboardMock } from '@/app/(admin)/dashboard/mockData';
import {
ActivitySnapshot,
deriveActivity,
EMPTY_ACTIVITY,
} from '@/components/dashboard/DashboardShared';
export function useDashboardData() {
const [stats, setStats] = useState<DashboardStats | null>(null);
const [sessions, setSessions] = useState<SessionInfo[]>([]);
const [loading, setLoading] = useState(true);
const [userName, setUserName] = useState('Admin');
const [userRole, setUserRole] = useState('');
const [chartMode, setChartMode] = useState<'weekly' | 'monthly' | 'yearly'>('weekly');
const [refreshing, setRefreshing] = useState(false);
const [activity, setActivity] = useState<ActivitySnapshot>(EMPTY_ACTIVITY);
useEffect(() => {
const token = getAccessToken();
if (token) {
const payload = parseJwt(token);
if (payload) {
setUserName((payload.email as string)?.split('@')[0] || 'Admin');
setUserRole((payload.role as string) || '');
}
}
}, []);
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<any[]>('/api/v1/admin/orders').catch(() => []),
apiFetch<any>('/api/v1/catalog/products/all?limit=200').catch(() => []),
apiFetch<any[]>('/api/v1/catalog/categories/all').catch(() => []),
apiFetch<any[]>('/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<string, number> = {
pending: 0,
confirmed: 0,
processing: 0,
shipped: 0,
delivered: 0,
cancelled: 0,
returned: 0,
};
let totalRevenue = 0;
let revenue7 = 0;
let revenue30 = 0;
const recentOrders: DashboardRecentOrder[] = [];
const now = Date.now();
const dayMs = 86400000;
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'
) {
const amount = Number(o.final_amount || 0);
totalRevenue += amount;
const created = o.created_at ? new Date(o.created_at).getTime() : NaN;
if (!Number.isNaN(created)) {
const age = now - created;
if (age >= 0 && age < 7 * dayMs) revenue7 += amount;
if (age >= 0 && age < 30 * dayMs) revenue30 += amount;
}
}
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<string, { revenue: number; orders: number }>();
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, 25).map((p: any) => ({
name: p.name || p.title || 'Product',
total_sold: p.variants?.length || 1,
total_revenue: p.variants?.reduce((s: number, v: any) => s + Number(v.price || 0), 0) || Number(p.base_price || 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: revenue30,
revenue_last_7_days: revenue7,
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);
setActivity(deriveActivity(mergedStats, liveOrders));
setSessions(liveSessions);
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
const { stats: displayStats } = withDashboardMock(stats, sessions);
return {
stats: displayStats,
rawStats: stats,
sessions,
activity,
loading,
refreshing,
userName,
userRole,
chartMode,
setChartMode,
fetchData,
};
}