revenuechart dynamic

This commit is contained in:
hamid zarghami
2025-12-23 14:09:28 +03:30
parent 860502f160
commit 14bc394801
4 changed files with 257 additions and 136 deletions
+216 -135
View File
@@ -1,5 +1,5 @@
import { ArrowUp, DocumentDownload } from 'iconsax-react'
import { type FC, useState } from 'react'
import { ArrowUp, DocumentDownload, ArrowDown } from 'iconsax-react'
import { type FC, useState, useMemo } from 'react'
import {
Area,
AreaChart,
@@ -11,32 +11,79 @@ import {
} from 'recharts'
import DatePicker from '@/components/DatePicker'
import Button from '@/components/Button'
import { useGetPaymentsChart } from '../hooks/useStatsData'
import { formatPrice } from '@/helpers/func'
import PageLoading from '@/components/PageLoading'
interface RevenueChartProps {
data?: Array<{ month: string; online: number; cash: number }>
}
const RevenueChart: FC<RevenueChartProps> = ({ data }) => {
const RevenueChart: FC = () => {
const [selectedTab, setSelectedTab] = useState<
'daily' | 'monthly' | 'yearly'
>('monthly')
const [startDate, setStartDate] = useState<string>('')
const [endDate, setEndDate] = useState<string>('')
const defaultData = [
{ month: 'فروردین', online: 10000000, cash: 8000000 },
{ month: 'اردیبهشت', online: 15000000, cash: 11000000 },
{ month: 'خرداد', online: 12000000, cash: 9000000 },
{ month: 'تیر', online: 18000000, cash: 13000000 },
{ month: 'مرداد', online: 16000000, cash: 12000000 },
{ month: 'شهریور', online: 22000000, cash: 15000000 },
{ month: 'مهر', online: 20000000, cash: 14000000 },
{ month: 'آبان', online: 17000000, cash: 13000000 },
{ month: 'آذر', online: 14000000, cash: 11000000 },
{ month: 'دی', online: 12000000, cash: 10000000 },
{ month: 'بهمن', online: 18000000, cash: 13000000 },
{ month: 'اسفند', online: 16000000, cash: 12000000 }
]
const apiParams = useMemo(() => {
const params: {
period?: 'daily' | 'monthly' | 'yearly';
startDate?: string;
endDate?: string;
} = {
period: selectedTab,
}
if (startDate) params.startDate = startDate
if (endDate) params.endDate = endDate
return params
}, [selectedTab, startDate, endDate])
const chartData = data || defaultData
const { data: paymentsChartData, isLoading } = useGetPaymentsChart(apiParams)
const formatDateLabel = (dateString: string, period: 'daily' | 'monthly' | 'yearly'): string => {
const date = new Date(dateString)
const options: Intl.DateTimeFormatOptions = {
year: 'numeric',
}
if (period === 'monthly') {
options.month = 'long'
} else if (period === 'daily') {
options.month = 'short'
options.day = 'numeric'
}
const persianDate = new Intl.DateTimeFormat('fa-IR', options).format(date)
return persianDate
}
const chartData = useMemo(() => {
if (!paymentsChartData?.data) return []
return paymentsChartData.data.map((item) => ({
month: formatDateLabel(item.date, selectedTab),
online: item.online,
cash: item.cash,
}))
}, [paymentsChartData?.data, selectedTab])
const xAxisInterval = useMemo(() => {
const dataLength = chartData.length
if (dataLength <= 7) return 0
if (dataLength <= 15) return 1
if (dataLength <= 30) return 2
if (dataLength <= 60) return 4
return Math.floor(dataLength / 12)
}, [chartData.length])
const totalRevenue = useMemo(() => {
return chartData.reduce((sum, item) => sum + item.online + item.cash, 0)
}, [chartData])
const revenueChange = useMemo(() => {
if (chartData.length < 2) return null
const currentPeriod = chartData[chartData.length - 1]
const previousPeriod = chartData[chartData.length - 2]
const currentTotal = currentPeriod.online + currentPeriod.cash
const previousTotal = previousPeriod.online + previousPeriod.cash
if (previousTotal === 0) return null
const change = ((currentTotal - previousTotal) / previousTotal) * 100
return change
}, [chartData])
const formatYAxis = (value: number) => {
if (value === 0) return '۰'
@@ -55,6 +102,14 @@ const RevenueChart: FC<RevenueChartProps> = ({ data }) => {
return value.toLocaleString('fa-IR') + ' تومان'
}
if (isLoading) {
return (
<div className='bg-white rounded-3xl p-6 shadow-sm h-full overflow-visible flex items-center justify-center min-h-[600px]'>
<PageLoading />
</div>
)
}
return (
<div className='bg-white rounded-3xl p-6 shadow-sm h-full overflow-visible'>
{/* Header */}
@@ -67,13 +122,13 @@ const RevenueChart: FC<RevenueChartProps> = ({ data }) => {
<div className='flex items-end gap-2'>
<DatePicker
label='تاریخ شروع'
placeholder='mm/dd/yyyy'
onChange={() => { }}
placeholder='انتخاب تاریخ شروع'
onChange={setStartDate}
/>
<DatePicker
label='تاریخ پایان'
placeholder='mm/dd/yyyy'
onChange={() => { }}
placeholder='انتخاب تاریخ پایان'
onChange={setEndDate}
/>
<Button className=''>
<div className='flex gap-3'>
@@ -121,21 +176,40 @@ const RevenueChart: FC<RevenueChartProps> = ({ data }) => {
<div>
<span className='text-sm text-gray-500'>مجموع درآمد</span>
</div>
<div className='flex items-center justify-between mb-5'>
<div className='flex items-center gap-3'>
<p className='text-2xl font-bold'>۲۰,۰۰۰,۰۰۰ تومان</p>
<div className='flex items-center gap-1 px-2 py-0.5 bg-green-50 rounded-full'>
<ArrowUp
size={12}
color='#10b981'
/>
<span className='text-xs font-medium text-green-600'>
2,5%
</span>
</div>
<p className='text-2xl font-bold'>
{formatPrice(totalRevenue)}
</p>
{revenueChange !== null && (
<div
className={`flex items-center gap-1 px-2 py-0.5 rounded-full ${revenueChange >= 0
? 'bg-green-50'
: 'bg-red-50'
}`}
>
{revenueChange >= 0 ? (
<ArrowUp
size={12}
color='#10b981'
/>
) : (
<ArrowDown
size={12}
color='#ef4444'
/>
)}
<span
className={`text-xs font-medium ${revenueChange >= 0
? 'text-green-600'
: 'text-red-600'
}`}
>
{Math.abs(revenueChange).toFixed(1)}%
</span>
</div>
)}
</div>
<div className='flex items-center gap-3'>
@@ -155,103 +229,110 @@ const RevenueChart: FC<RevenueChartProps> = ({ data }) => {
</div>
{/* نمودار */}
<div className='w-full h-[400px] min-h-[400px]'>
<ResponsiveContainer width='100%' height='100%'>
<AreaChart
data={chartData}
margin={{ top: 10, right: 10, left: 10, bottom: 40 }}
>
<defs>
<linearGradient
id='colorOnline'
x1='0'
y1='0'
x2='0'
y2='1'
>
<stop
offset='5%'
stopColor='#6B7FED'
stopOpacity={0.3}
/>
<stop
offset='95%'
stopColor='#6B7FED'
stopOpacity={0}
/>
</linearGradient>
<linearGradient
id='colorCash'
x1='0'
y1='0'
x2='0'
y2='1'
>
<stop
offset='5%'
stopColor='#B0BAC9'
stopOpacity={0.2}
/>
<stop
offset='95%'
stopColor='#B0BAC9'
stopOpacity={0}
/>
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray='0'
stroke='#f0f0f0'
vertical={false}
/>
<XAxis
dataKey='month'
axisLine={false}
tickLine={false}
tick={{ fill: '#9CA3AF', fontSize: 11 }}
reversed
interval={0}
angle={0}
textAnchor='middle'
height={40}
/>
<YAxis
orientation='right'
axisLine={false}
tickLine={false}
tick={{ fill: '#9CA3AF', fontSize: 10 }}
tickFormatter={formatYAxis}
domain={[0, 'dataMax + 2000000']}
tickMargin={50}
/>
<Tooltip
formatter={formatTooltip}
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '12px',
fontSize: '12px'
}}
/>
<Area
type='natural'
dataKey='cash'
stroke='#B0BAC9'
strokeWidth={2}
fillOpacity={1}
fill='url(#colorCash)'
/>
<Area
type='natural'
dataKey='online'
stroke='#6B7FED'
strokeWidth={2}
fillOpacity={1}
fill='url(#colorOnline)'
/>
</AreaChart>
</ResponsiveContainer>
</div>
{chartData.length === 0 ? (
<div className='w-full h-[400px] min-h-[400px] flex items-center justify-center text-gray-500'>
دادهای برای نمایش وجود ندارد
</div>
) : (
<div className='w-full h-[400px] min-h-[400px]'>
<ResponsiveContainer width='100%' height='100%'>
<AreaChart
data={chartData}
margin={{ top: 10, right: 10, left: 10, bottom: 40 }}
>
<defs>
<linearGradient
id='colorOnline'
x1='0'
y1='0'
x2='0'
y2='1'
>
<stop
offset='5%'
stopColor='#6B7FED'
stopOpacity={0.3}
/>
<stop
offset='95%'
stopColor='#6B7FED'
stopOpacity={0}
/>
</linearGradient>
<linearGradient
id='colorCash'
x1='0'
y1='0'
x2='0'
y2='1'
>
<stop
offset='5%'
stopColor='#B0BAC9'
stopOpacity={0.2}
/>
<stop
offset='95%'
stopColor='#B0BAC9'
stopOpacity={0}
/>
</linearGradient>
</defs>
<CartesianGrid
strokeDasharray='0'
stroke='#f0f0f0'
vertical={false}
/>
<XAxis
dataKey='month'
axisLine={false}
tickLine={false}
tick={{ fill: '#9CA3AF', fontSize: 11 }}
reversed
interval={xAxisInterval}
angle={chartData.length > 15 ? -45 : 0}
textAnchor={chartData.length > 15 ? 'end' : 'middle'}
height={chartData.length > 15 ? 60 : 40}
minTickGap={10}
/>
<YAxis
orientation='right'
axisLine={false}
tickLine={false}
tick={{ fill: '#9CA3AF', fontSize: 10 }}
tickFormatter={formatYAxis}
domain={[0, 'dataMax + 2000000']}
tickMargin={50}
/>
<Tooltip
formatter={formatTooltip}
contentStyle={{
backgroundColor: 'white',
border: '1px solid #e5e7eb',
borderRadius: '12px',
fontSize: '12px'
}}
/>
<Area
type='natural'
dataKey='cash'
stroke='#B0BAC9'
strokeWidth={2}
fillOpacity={1}
fill='url(#colorCash)'
/>
<Area
type='natural'
dataKey='online'
stroke='#6B7FED'
strokeWidth={2}
fillOpacity={1}
fill='url(#colorOnline)'
/>
</AreaChart>
</ResponsiveContainer>
</div>
)}
</div>
)
}
@@ -14,3 +14,16 @@ export const useGetFoodSalesPieChart = () => {
queryFn: api.getFoodSalesPieChart,
});
};
interface GetPaymentsChartParams {
period?: "daily" | "monthly" | "yearly";
startDate?: string;
endDate?: string;
}
export const useGetPaymentsChart = (params?: GetPaymentsChartParams) => {
return useQuery({
queryKey: ["payments-chart", params],
queryFn: () => api.getPaymentsChart(params),
});
};
@@ -1,5 +1,8 @@
import axios from "@/config/axios";
import type { IStatisticsResponse } from "../types/Types";
import type {
IStatisticsResponse,
IPaymentChartResponse,
} from "../types/Types";
export const getStatistics = async (): Promise<IStatisticsResponse> => {
const { data } = await axios.get<IStatisticsResponse>("/admin/orders/stats");
@@ -10,3 +13,19 @@ export const getFoodSalesPieChart = async () => {
const { data } = await axios.get("/admin/orders/food-sales-pie-chart");
return data;
};
interface GetPaymentsChartParams {
period?: "daily" | "monthly" | "yearly";
startDate?: string;
endDate?: string;
}
export const getPaymentsChart = async (
params?: GetPaymentsChartParams
): Promise<IPaymentChartResponse> => {
const { data } = await axios.get<IPaymentChartResponse>(
"/admin/payments/chart",
{ params }
);
return data;
};
+8
View File
@@ -8,3 +8,11 @@ export interface IStatisticsData {
}
export type IStatisticsResponse = IResponse<IStatisticsData>;
export interface IPaymentChartItem {
date: string;
cash: number;
online: number;
}
export type IPaymentChartResponse = IResponse<IPaymentChartItem[]>;