Files
canina/frontend/admin-panel/src/pages/Reports.tsx
T
devops ddbf1ca026
Deploy Canina / deploy (push) Successful in 4m1s
E2E Playwright Tests / Run Full E2E & Security Suites (push) Failing after 7s
test: comprehensive test suites and quality gates pass across backend, storefront and admin
- Backend (NestJS): 82 suites, 641 tests passing; 0 ESLint errors; 0 tsc errors. Hardened SSL cert/key matching, SSRF IP pinning, and eBank validation.
- Admin Panel (Vite/React): 48 suites, 300 tests passing; 0 ESLint errors; 0 tsc errors. Full coverage across all pages and settings.
- Storefront (Next.js): 62 suites, 368 tests passing; 0 ESLint errors; 0 tsc errors.
- Fixed unmount lifecycle guards, promise error handling, and component edge cases.
2026-10-13 16:01:00 +00:00

488 lines
23 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
DollarSign,
Download,
Filter,
HeartHandshake,
Receipt,
ShoppingBag,
TrendingUp
} from 'lucide-react';
import { useCallback,useEffect,useState } from 'react';
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
Cell,Legend,
Pie,
PieChart,
Tooltip as RechartsTooltip,ResponsiveContainer,
XAxis,YAxis
} from 'recharts';
import Button from '../components/ui/Button';
import Spinner from '../components/ui/Spinner';
import api from '../services/api';
const COLORS = ['#8B5CF6', '#EC4899', '#3B82F6', '#10B981', '#F59E0B'];
interface CustomTooltipProps {
active?: boolean;
payload?: Array<{ value: number | string; name?: string; color?: string }>;
label?: string;
}
const CustomTooltip = ({ active, payload, label }: CustomTooltipProps) => {
if (active && payload && payload.length) {
return (
<div className="bg-white p-4 rounded-xl shadow-lg border border-gray-100 text-right font-vazir" dir="rtl">
<p className="font-bold text-gray-900 mb-2">{label}</p>
{payload.map((item, idx) => (
<div key={idx} className="flex items-center justify-between gap-4 text-xs font-bold my-1">
<span style={{ color: item.color }}>{item.name || 'مبلغ'}:</span>
<span>{Number(item.value).toLocaleString()} تومان</span>
</div>
))}
</div>
);
}
return null;
};
export interface CategoryDistItem {
name: string;
value: number;
}
export interface BestSellerItem {
name: string;
quantity: number;
}
export interface TopCouponItem {
name: string;
usedCount?: number;
value?: number;
}
export interface ReportData {
overview?: {
totalRevenue: number;
totalCharity?: number;
productSalesRevenue?: number;
totalOrders: number;
totalUsers?: number;
avgOrderValue?: number;
b2bRevenue?: number;
b2cRevenue?: number;
totalTax?: number;
totalShipping?: number;
totalDiscounts?: number;
totalCostOfGoods?: number;
netProfit?: number;
};
salesTimeline?: Array<{ date: string; amount: number; charity?: number; sales?: number }>;
bestSellers?: BestSellerItem[];
categoryDistribution?: CategoryDistItem[];
topCoupons?: TopCouponItem[];
}
export default function Reports() {
const [reportData, setReportData] = useState<ReportData | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Filter States
const [dateFilterType, setDateFilterType] = useState<'all' | 'today' | '7days' | '30days' | 'custom'>('30days');
const [startDate, setStartDate] = useState('');
const [endDate, setEndDate] = useState('');
const [roleFilter, setRoleFilter] = useState('ALL');
const fetchReports = useCallback(async () => {
try {
setIsLoading(true);
const params: Record<string, string> = {};
const now = new Date();
if (dateFilterType === 'today') {
const start = new Date(now);
start.setHours(0, 0, 0, 0);
params.startDate = start.toISOString();
} else if (dateFilterType === '7days') {
const start = new Date(now);
start.setDate(now.getDate() - 7);
params.startDate = start.toISOString();
} else if (dateFilterType === '30days') {
const start = new Date(now);
start.setDate(now.getDate() - 30);
params.startDate = start.toISOString();
} else if (dateFilterType === 'custom') {
if (startDate) params.startDate = startDate;
if (endDate) params.endDate = endDate;
}
if (roleFilter !== 'ALL') {
params.role = roleFilter;
}
const res = await api.get('/admin/reports', { params });
if (res.data?.success) {
setReportData(res.data.data);
}
} catch (err) {
console.error('Failed to fetch reports:', err);
} finally {
setIsLoading(false);
}
}, [dateFilterType, startDate, endDate, roleFilter]);
useEffect(() => {
fetchReports();
}, [fetchReports]);
if (isLoading && !reportData) {
return <div className="flex justify-center items-center h-96"><Spinner size="lg" className="text-purple-600" /></div>;
}
const { overview, salesTimeline, bestSellers, categoryDistribution, topCoupons } = reportData || {};
return (
<div className="space-y-6 font-vazir text-right" dir="rtl">
{/* Header */}
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-white p-6 rounded-3xl border border-gray-200 shadow-xs">
<div>
<h2 className="text-2xl font-black text-gray-900 flex items-center gap-2">
<TrendingUp className="w-6 h-6 text-purple-600" />
گزارشات و تحلیل‌های مالی پیشرفته
</h2>
<p className="text-gray-500 font-medium text-xs sm:text-sm mt-1">
تفکیک درآمد کالاها، مبالغ واریزی مهربانی، مالیات، تخفیف‌ها و سود خالص
</p>
</div>
<Button
variant="outline"
size="sm"
startIcon={Download}
onClick={() => {
if (!reportData) return;
const rows = [
['گزارش مالی و عملکرد فروش کنینا ایران'],
['تاریخ گزارش', new Date().toLocaleDateString('fa-IR')],
[],
['شاخص مالی', 'مبلغ (تومان) / مقدار'],
['درآمد کل واریزی‌ها', overview?.totalRevenue || 0],
['سهم مهربانی (خیریه)', overview?.totalCharity || 0],
['خالص فروش کالاها', overview?.productSalesRevenue || 0],
['بهای تمام‌شده کالاها (COGS)', overview?.totalCostOfGoods || 0],
['مجموع مالیات بر ارزش افزوده', overview?.totalTax || 0],
['مجموع تخفیف‌های اعمال شده', overview?.totalDiscounts || 0],
['سود خالص تخمینی', overview?.netProfit || 0],
['تعداد کل سفارشات', overview?.totalOrders || 0],
['فروش همکاران (B2B)', overview?.b2bRevenue || 0],
['فروش مصرف‌کنندگان (B2C)', overview?.b2cRevenue || 0],
[],
['محصولات پرفروش در این بازه', 'تعداد فروش'],
...(bestSellers || []).map(b => [b.name, b.quantity]),
];
const csvContent = 'data:text/csv;charset=utf-8,\uFEFF' + rows.map(e => e.join(',')).join('\n');
const encodedUri = encodeURI(csvContent);
const link = document.createElement('a');
link.setAttribute('href', encodedUri);
link.setAttribute('download', `Canina_Financial_Report_${new Date().toISOString().split('T')[0]}.csv`);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}}
>
خروجی اکسل مالی (Excel / CSV)
</Button>
</div>
{/* Filter Toolbar */}
<div className="bg-white p-4 rounded-3xl shadow-xs border border-gray-200 flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
<Filter className="w-4 h-4 text-purple-600" />
<span className="text-xs font-black text-gray-700">بازه زمانی:</span>
</div>
<div className="flex flex-wrap items-center gap-1.5 bg-gray-50 p-1 rounded-2xl border border-gray-200 text-xs font-bold">
<button
onClick={() => setDateFilterType('30days')}
className={`px-3 py-1.5 rounded-xl transition-all ${dateFilterType === '30days' ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-600 hover:text-purple-600'}`}
>
۳۰ روز اخیر
</button>
<button
onClick={() => setDateFilterType('7days')}
className={`px-3 py-1.5 rounded-xl transition-all ${dateFilterType === '7days' ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-600 hover:text-purple-600'}`}
>
۷ روز اخیر
</button>
<button
onClick={() => setDateFilterType('today')}
className={`px-3 py-1.5 rounded-xl transition-all ${dateFilterType === 'today' ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-600 hover:text-purple-600'}`}
>
امروز
</button>
<button
onClick={() => setDateFilterType('all')}
className={`px-3 py-1.5 rounded-xl transition-all ${dateFilterType === 'all' ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-600 hover:text-purple-600'}`}
>
کل تاریخچه
</button>
<button
onClick={() => setDateFilterType('custom')}
className={`px-3 py-1.5 rounded-xl transition-all ${dateFilterType === 'custom' ? 'bg-purple-600 text-white shadow-xs' : 'text-gray-600 hover:text-purple-600'}`}
>
بازه سفارشی
</button>
</div>
{dateFilterType === 'custom' && (
<div className="flex items-center gap-2 text-xs">
<input
type="date"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
className="px-3 py-1.5 rounded-xl border border-gray-200 outline-none text-xs"
/>
<span className="text-gray-400">تا</span>
<input
type="date"
value={endDate}
onChange={(e) => setEndDate(e.target.value)}
className="px-3 py-1.5 rounded-xl border border-gray-200 outline-none text-xs"
/>
</div>
)}
<div className="flex items-center gap-2 mr-auto">
<span className="text-xs font-black text-gray-700">نوع مشتری:</span>
<select
value={roleFilter}
onChange={(e) => setRoleFilter(e.target.value)}
className="px-3 py-1.5 rounded-xl border border-gray-200 text-xs font-bold outline-none bg-gray-50/50"
>
<option value="ALL">همه (B2B + B2C)</option>
<option value="B2B">خریداران عمده (B2B)</option>
<option value="User_PetOwner">مصرف‌کنندگان (B2C)</option>
</select>
</div>
</div>
{/* Overview Cards (Core Revenue & Charity) */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{/* Total Deposited */}
<div className="bg-gradient-to-br from-purple-600 to-indigo-700 p-6 rounded-3xl text-white shadow-lg shadow-purple-200">
<div className="flex items-center justify-between mb-4">
<h3 className="font-bold text-purple-100 text-sm">مجموع کل واریزی‌ها</h3>
<div className="p-2.5 bg-white/20 rounded-2xl"><DollarSign className="w-5 h-5" /></div>
</div>
<p className="text-3xl font-black">{Number(overview?.totalRevenue || 0).toLocaleString()}</p>
<p className="text-purple-200 text-xs mt-1">تومان (شامل کالا و مهربانی)</p>
</div>
{/* Charity Share */}
<div className="bg-gradient-to-br from-rose-500 to-pink-600 p-6 rounded-3xl text-white shadow-lg shadow-pink-200">
<div className="flex items-center justify-between mb-4">
<h3 className="font-bold text-rose-100 text-sm">سهم مبالغ مهربانی (خیریه)</h3>
<div className="p-2.5 bg-white/20 rounded-2xl"><HeartHandshake className="w-5 h-5" /></div>
</div>
<p className="text-3xl font-black">{Number(overview?.totalCharity || 0).toLocaleString()}</p>
<p className="text-rose-200 text-xs mt-1">
{overview?.totalRevenue ? `${((Number(overview.totalCharity || 0) / Number(overview.totalRevenue)) * 100).toFixed(1)}% از کل دریافتی` : 'تومان'}
</p>
</div>
{/* Product Sales Only */}
<div className="bg-gradient-to-br from-blue-600 to-cyan-700 p-6 rounded-3xl text-white shadow-lg shadow-blue-200">
<div className="flex items-center justify-between mb-4">
<h3 className="font-bold text-blue-100 text-sm">خالص فروش محصولات</h3>
<div className="p-2.5 bg-white/20 rounded-2xl"><ShoppingBag className="w-5 h-5" /></div>
</div>
<p className="text-3xl font-black">{Number(overview?.productSalesRevenue || (Number(overview?.totalRevenue || 0) - Number(overview?.totalCharity || 0))).toLocaleString()}</p>
<p className="text-blue-200 text-xs mt-1">تومان (بدون احتساب مبالغ خیریه)</p>
</div>
{/* Net Profit */}
<div className="bg-gradient-to-br from-emerald-600 to-teal-700 p-6 rounded-3xl text-white shadow-lg shadow-emerald-200">
<div className="flex items-center justify-between mb-4">
<h3 className="font-bold text-emerald-100 text-sm">سود خالص تخمینی</h3>
<div className="p-2.5 bg-white/20 rounded-2xl"><TrendingUp className="w-5 h-5" /></div>
</div>
<p className="text-3xl font-black">{Number(overview?.netProfit || 0).toLocaleString()}</p>
<p className="text-emerald-200 text-xs mt-1">تومان (پس از کسر خرید، مالیات و تخفیف)</p>
</div>
</div>
{/* Financial Breakdown Section (Item 2 Requirement) */}
<div className="bg-white p-6 rounded-3xl border border-gray-200 shadow-xs">
<h3 className="text-lg font-black text-gray-900 mb-4 flex items-center gap-2">
<Receipt className="w-5 h-5 text-purple-600" />
تراز و تفکیک اجزای مالی
</h3>
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-100">
<span className="text-[11px] font-bold text-gray-400 block mb-1">بهای خرید کالاها (COGS)</span>
<span className="text-base font-black text-gray-800">{Number(overview?.totalCostOfGoods || 0).toLocaleString()}</span>
<span className="text-[10px] text-gray-400 block mt-0.5">تومان</span>
</div>
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-100">
<span className="text-[11px] font-bold text-gray-400 block mb-1">مالیات بر ارزش افزوده</span>
<span className="text-base font-black text-amber-600">{Number(overview?.totalTax || 0).toLocaleString()}</span>
<span className="text-[10px] text-gray-400 block mt-0.5">تومان</span>
</div>
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-100">
<span className="text-[11px] font-bold text-gray-400 block mb-1">مجموع تخفیف‌ها</span>
<span className="text-base font-black text-red-500">{Number(overview?.totalDiscounts || 0).toLocaleString()}</span>
<span className="text-[10px] text-gray-400 block mt-0.5">تومان</span>
</div>
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-100">
<span className="text-[11px] font-bold text-gray-400 block mb-1">فروش عمده (B2B)</span>
<span className="text-base font-black text-blue-600">{Number(overview?.b2bRevenue || 0).toLocaleString()}</span>
<span className="text-[10px] text-gray-400 block mt-0.5">تومان</span>
</div>
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-100">
<span className="text-[11px] font-bold text-gray-400 block mb-1">فروش تکی (B2C)</span>
<span className="text-base font-black text-indigo-600">{Number(overview?.b2cRevenue || 0).toLocaleString()}</span>
<span className="text-[10px] text-gray-400 block mt-0.5">تومان</span>
</div>
<div className="p-4 bg-gray-50 rounded-2xl border border-gray-100">
<span className="text-[11px] font-bold text-gray-400 block mb-1">تعداد کل سفارشات</span>
<span className="text-base font-black text-emerald-600">{overview?.totalOrders || 0}</span>
<span className="text-[10px] text-gray-400 block mt-0.5">سفارش موفق</span>
</div>
</div>
</div>
{/* Charts Section */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* Timeline Chart with Dual Area for Total & Charity */}
<div className="lg:col-span-2 bg-white p-6 rounded-3xl shadow-xs border border-gray-200">
<div className="flex items-center justify-between mb-6">
<h3 className="text-base font-black text-gray-900">روند فروش و واریزی‌های مهربانی</h3>
<div className="flex items-center gap-4 text-xs font-bold">
<span className="flex items-center gap-1.5 text-purple-600">
<span className="w-2.5 h-2.5 rounded-full bg-purple-600" />
کل واریزی
</span>
<span className="flex items-center gap-1.5 text-rose-500">
<span className="w-2.5 h-2.5 rounded-full bg-rose-500" />
سهم مهربانی
</span>
</div>
</div>
<div className="h-80 w-full" dir="ltr">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={salesTimeline} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
<defs>
<linearGradient id="colorSales" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#8B5CF6" stopOpacity={0.3}/>
<stop offset="95%" stopColor="#8B5CF6" stopOpacity={0}/>
</linearGradient>
<linearGradient id="colorCharity" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#F43F5E" stopOpacity={0.3}/>
<stop offset="95%" stopColor="#F43F5E" stopOpacity={0}/>
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f3f4f6" />
<XAxis dataKey="date" stroke="#9ca3af" fontSize={11} tickLine={false} axisLine={false} />
<YAxis stroke="#9ca3af" fontSize={11} tickLine={false} axisLine={false} tickFormatter={(val) => `${val >= 1000000 ? `${(val/1000000).toFixed(1)}M` : `${val / 1000}k`}`} />
<RechartsTooltip content={<CustomTooltip />} />
<Area type="monotone" name="کل دریافتی" dataKey="amount" stroke="#8B5CF6" strokeWidth={2.5} fillOpacity={1} fill="url(#colorSales)" />
<Area type="monotone" name="سهم مهربانی" dataKey="charity" stroke="#F43F5E" strokeWidth={2} fillOpacity={1} fill="url(#colorCharity)" />
</AreaChart>
</ResponsiveContainer>
</div>
</div>
{/* Category Distribution */}
<div className="bg-white p-6 rounded-3xl shadow-xs border border-gray-200">
<h3 className="text-base font-black text-gray-900 mb-6">سهم فروش دسته‌بندی‌ها</h3>
<div className="h-64 w-full flex justify-center">
{categoryDistribution && categoryDistribution.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie data={categoryDistribution} cx="50%" cy="50%" innerRadius={60} outerRadius={80} paddingAngle={5} dataKey="value">
{categoryDistribution.map((_, index: number) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<RechartsTooltip formatter={(value) => [`${value} عدد`, 'تعداد فروش']} />
<Legend verticalAlign="bottom" height={36} />
</PieChart>
</ResponsiveContainer>
) : (
<div className="text-gray-400 font-medium flex items-center justify-center h-full text-xs">داده‌ای موجود نیست</div>
)}
</div>
</div>
</div>
{/* Best Sellers & Top Coupons */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{/* Best Sellers */}
<div className="bg-white p-6 rounded-3xl shadow-xs border border-gray-200">
<h3 className="text-base font-black text-gray-900 mb-6">پرفروش‌ترین محصولات در بازه انتخابی</h3>
<div className="min-h-[300px] w-full" dir="ltr">
{bestSellers && bestSellers.length > 0 ? (
<ResponsiveContainer width="100%" height={Math.max(280, bestSellers.length * 45)}>
<BarChart
data={bestSellers}
layout="vertical"
margin={{ top: 10, right: 30, left: 10, bottom: 10 }}
>
<CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="#f3f4f6" />
<XAxis type="number" stroke="#9ca3af" fontSize={11} allowDecimals={false} />
<YAxis
dataKey="name"
type="category"
width={180}
stroke="#4b5563"
fontSize={11}
tickLine={false}
axisLine={false}
tickFormatter={(val: string) => (val && val.length > 24 ? `${val.slice(0, 22)}...` : val)}
style={{ direction: 'rtl', textAnchor: 'end' }}
/>
<RechartsTooltip
cursor={{ fill: '#fdf2f8' }}
formatter={(val) => [`${(val ?? 0).toLocaleString('fa-IR')} عدد`, 'تعداد فروش']}
labelFormatter={(lbl) => `محصول: ${lbl}`}
/>
<Bar dataKey="quantity" fill="#EC4899" radius={[0, 6, 6, 0]} barSize={18} />
</BarChart>
</ResponsiveContainer>
) : (
<div className="text-gray-400 font-medium flex items-center justify-center h-64 text-xs">داده‌ای موجود نیست</div>
)}
</div>
</div>
{/* Top Coupons */}
<div className="bg-white p-6 rounded-3xl shadow-xs border border-gray-200">
<h3 className="text-base font-black text-gray-900 mb-6">کدهای تخفیف پراستفاده</h3>
<div className="space-y-3">
{topCoupons && topCoupons.length > 0 ? (
topCoupons.map((coupon: TopCouponItem, idx: number) => (
<div key={idx} className="flex items-center justify-between p-4 bg-gray-50 rounded-2xl border border-gray-100">
<div className="flex items-center gap-3">
<div className="w-9 h-9 rounded-xl bg-purple-100 text-purple-600 font-black flex items-center justify-center text-xs">
#{idx + 1}
</div>
<span className="font-mono font-bold tracking-widest text-gray-800 text-sm">{coupon.name}</span>
</div>
<div className="text-gray-600 text-xs font-medium">
<span className="font-black text-gray-900 mx-1 text-sm">{coupon.usedCount ?? coupon.value ?? 0}</span>بار استفاده
</div>
</div>
))
) : (
<div className="text-gray-400 font-medium flex items-center justify-center h-32 text-xs">داده‌ای موجود نیست</div>
)}
</div>
</div>
</div>
</div>
);
}