Add summary statistics endpoint and UI integration

- Introduced a new API endpoint `GET /stats/summary` to retrieve detailed smoking statistics for users, including daily and global averages.
- Updated the API client to support fetching summary statistics.
- Enhanced the statistics page with a new tab for summary statistics, featuring key metrics and visualizations for user comparison.
- Implemented error handling and loading states for the summary statistics fetch operation.
- Refactored the statistics page to separate daily and summary statistics into distinct components for improved organization and readability.
This commit is contained in:
Primakov Alexandr Alexandrovich
2025-11-17 14:30:40 +03:00
parent 71ee0c1c0e
commit 34e994478e
5 changed files with 831 additions and 141 deletions

View File

@@ -11,6 +11,8 @@ import type {
GetCigarettesParams,
DailyStat,
GetDailyStatsParams,
SummaryStats,
GetSummaryStatsParams,
} from '../types/api'
const TOKEN_KEY = 'smokeToken'
@@ -99,5 +101,10 @@ export const statsApi = {
const response = await apiClient.get('/stats/daily', { params })
return response.data
},
getSummary: async (params?: GetSummaryStatsParams): Promise<ApiResponse<SummaryStats>> => {
const response = await apiClient.get('/stats/summary', { params })
return response.data
},
}

View File

@@ -10,11 +10,14 @@ import {
Card,
Input,
Stack,
Table,
} from '@chakra-ui/react'
import { Field } from '../../components/ui/field'
import {
LineChart,
Line,
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
@@ -25,7 +28,7 @@ import {
import { format, subDays, eachDayOfInterval, parseISO } from 'date-fns'
import { statsApi } from '../../api/client'
import { URLs } from '../../__data__/urls'
import type { DailyStat } from '../../types/api'
import type { DailyStat, SummaryStats } from '../../types/api'
interface FilledDailyStat {
date: string
@@ -33,7 +36,8 @@ interface FilledDailyStat {
displayDate: string
}
export const StatsPage: React.FC = () => {
// Daily Stats Tab Component
const DailyStatsTab: React.FC = () => {
const [stats, setStats] = useState<FilledDailyStat[]>([])
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -78,10 +82,11 @@ export const StatsPage: React.FC = () => {
const filled = fillMissingDates(response.body, fromDate, toDate)
setStats(filled)
}
} catch (err: any) {
} catch (err) {
const error = err as { response?: { data?: { errors?: string; message?: string } } }
const errorMessage =
err?.response?.data?.errors ||
err?.response?.data?.message ||
error?.response?.data?.errors ||
error?.response?.data?.message ||
'Ошибка при загрузке статистики'
setError(errorMessage)
} finally {
@@ -97,6 +102,438 @@ export const StatsPage: React.FC = () => {
const averagePerDay = stats.length > 0 ? (totalCigarettes / stats.length).toFixed(1) : 0
const maxPerDay = Math.max(...stats.map((s) => s.count), 0)
return (
<VStack gap={6} w="full">
{/* Date range selector */}
<Card.Root w="full">
<Card.Body p={{ base: 4, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">Выберите период</Heading>
<HStack gap={4} flexWrap="wrap">
<Field label="От">
<Input
type="date"
value={fromDate}
onChange={(e) => setFromDate(e.target.value)}
/>
</Field>
<Field label="До">
<Input
type="date"
value={toDate}
onChange={(e) => setToDate(e.target.value)}
/>
</Field>
<Box>
<Button
colorScheme="teal"
onClick={fetchStats}
disabled={isLoading}
mt={7}
>
{isLoading ? 'Загрузка...' : 'Обновить'}
</Button>
</Box>
</HStack>
</VStack>
</Card.Body>
</Card.Root>
{error && (
<Card.Root w="full" bg="red.50" borderColor="red.500" borderWidth={2}>
<Card.Body>
<Text color="red.700" fontWeight="bold">
{error}
</Text>
</Card.Body>
</Card.Root>
)}
{/* Summary statistics */}
<Card.Root w="full">
<Card.Body p={{ base: 4, md: 6 }}>
<Stack direction={{ base: 'column', md: 'row' }} gap={6} justify="space-around">
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="blue.500">
{totalCigarettes}
</Text>
<Text fontSize="sm" color="gray.600">
Всего сигарет
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="green.500">
{averagePerDay}
</Text>
<Text fontSize="sm" color="gray.600">
В среднем в день
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="orange.500">
{maxPerDay}
</Text>
<Text fontSize="sm" color="gray.600">
Максимум в день
</Text>
</VStack>
</Stack>
</Card.Body>
</Card.Root>
{/* Chart */}
<Card.Root w="full">
<Card.Body p={{ base: 2, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">График по дням</Heading>
{isLoading ? (
<Text textAlign="center" py={8}>
Загрузка...
</Text>
) : stats.length === 0 ? (
<Text textAlign="center" py={8} color="gray.500">
Нет данных за выбранный период
</Text>
) : (
<Box w="full" h="400px">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={stats}
margin={{ top: 5, right: 5, left: 0, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="displayDate"
tick={{ fontSize: 12 }}
interval="preserveStartEnd"
/>
<YAxis allowDecimals={false} />
<Tooltip
contentStyle={{
backgroundColor: '#fff',
border: '1px solid #ccc',
borderRadius: '4px',
}}
labelFormatter={(label) => `Дата: ${label}`}
formatter={(value: number) => [value, 'Сигарет']}
/>
<Legend />
<Line
type="monotone"
dataKey="count"
name="Количество сигарет"
stroke="#3182ce"
strokeWidth={2}
activeDot={{ r: 8 }}
/>
</LineChart>
</ResponsiveContainer>
</Box>
)}
</VStack>
</Card.Body>
</Card.Root>
</VStack>
)
}
// Summary Stats Tab Component
const SummaryStatsTab: React.FC = () => {
const [summaryStats, setSummaryStats] = useState<SummaryStats | null>(null)
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
// Default: last 30 days
const [fromDate, setFromDate] = useState(
format(subDays(new Date(), 30), 'yyyy-MM-dd')
)
const [toDate, setToDate] = useState(format(new Date(), 'yyyy-MM-dd'))
const fetchSummary = async () => {
setIsLoading(true)
setError(null)
try {
const fromISO = new Date(fromDate).toISOString()
const toISO = new Date(toDate + 'T23:59:59').toISOString()
const response = await statsApi.getSummary({
from: fromISO,
to: toISO,
})
if (response.success) {
setSummaryStats(response.body)
}
} catch (err) {
const error = err as { response?: { data?: { errors?: string; message?: string } } }
const errorMessage =
error?.response?.data?.errors ||
error?.response?.data?.message ||
'Ошибка при загрузке сводной статистики'
setError(errorMessage)
} finally {
setIsLoading(false)
}
}
useEffect(() => {
fetchSummary()
}, [])
// Prepare data for weekday bar chart
const prepareWeekdayData = () => {
if (!summaryStats) return []
// Create a map for quick lookup
const userMap = new Map(summaryStats.user.weekday.map(w => [w.dayOfWeek, parseFloat(w.average)]))
const globalMap = new Map(summaryStats.global.weekday.map(w => [w.dayOfWeek, parseFloat(w.average)]))
// Get all unique days and sort them (starting from Monday = 2)
const allDays = new Set([
...summaryStats.user.weekday.map(w => w.dayOfWeek),
...summaryStats.global.weekday.map(w => w.dayOfWeek)
])
const sortedDays = Array.from(allDays).sort((a, b) => {
// Sort: Monday(2) to Sunday(1), so 1 goes to end
if (a === 1) return 1
if (b === 1) return -1
return a - b
})
return sortedDays.map(dayOfWeek => {
const dayName = summaryStats.user.weekday.find(w => w.dayOfWeek === dayOfWeek)?.dayName ||
summaryStats.global.weekday.find(w => w.dayOfWeek === dayOfWeek)?.dayName || ''
return {
dayName,
user: userMap.get(dayOfWeek) || 0,
global: globalMap.get(dayOfWeek) || 0,
}
})
}
const weekdayChartData = prepareWeekdayData()
return (
<VStack gap={6} w="full">
{/* Date range selector */}
<Card.Root w="full">
<Card.Body p={{ base: 4, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">Выберите период</Heading>
<HStack gap={4} flexWrap="wrap">
<Field label="От">
<Input
type="date"
value={fromDate}
onChange={(e) => setFromDate(e.target.value)}
/>
</Field>
<Field label="До">
<Input
type="date"
value={toDate}
onChange={(e) => setToDate(e.target.value)}
/>
</Field>
<Box>
<Button
colorScheme="teal"
onClick={fetchSummary}
disabled={isLoading}
mt={7}
>
{isLoading ? 'Загрузка...' : 'Обновить'}
</Button>
</Box>
</HStack>
</VStack>
</Card.Body>
</Card.Root>
{error && (
<Card.Root w="full" bg="red.50" borderColor="red.500" borderWidth={2}>
<Card.Body>
<Text color="red.700" fontWeight="bold">
{error}
</Text>
</Card.Body>
</Card.Root>
)}
{isLoading ? (
<Text textAlign="center" py={8}>Загрузка...</Text>
) : !summaryStats ? (
<Text textAlign="center" py={8} color="gray.500">Нет данных</Text>
) : (
<>
{/* Key Metrics */}
<Card.Root w="full">
<Card.Body p={{ base: 4, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">Ключевые показатели</Heading>
<Stack direction={{ base: 'column', md: 'row' }} gap={6} justify="space-around">
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="blue.500">
{summaryStats.user.averagePerDay.toFixed(1)}
</Text>
<Text fontSize="sm" color="gray.600" textAlign="center">
Ваш средний в день
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="purple.500">
{summaryStats.global.averagePerDay.toFixed(1)}
</Text>
<Text fontSize="sm" color="gray.600" textAlign="center">
Средний по пользователям
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="green.500">
{summaryStats.user.total}
</Text>
<Text fontSize="sm" color="gray.600" textAlign="center">
Всего за период
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="orange.500">
{summaryStats.global.activeUsers}
</Text>
<Text fontSize="sm" color="gray.600" textAlign="center">
Активных пользователей
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="teal.500">
{summaryStats.user.daysWithData}
</Text>
<Text fontSize="sm" color="gray.600" textAlign="center">
Дней с данными
</Text>
</VStack>
</Stack>
</VStack>
</Card.Body>
</Card.Root>
{/* Weekday Bar Chart */}
<Card.Root w="full">
<Card.Body p={{ base: 2, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">Статистика по дням недели</Heading>
{weekdayChartData.length === 0 ? (
<Text textAlign="center" py={8} color="gray.500">
Нет данных за выбранный период
</Text>
) : (
<Box w="full" h="400px">
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={weekdayChartData}
margin={{ top: 5, right: 5, left: 0, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="dayName"
tick={{ fontSize: 12 }}
/>
<YAxis allowDecimals={false} />
<Tooltip
contentStyle={{
backgroundColor: '#fff',
border: '1px solid #ccc',
borderRadius: '4px',
}}
formatter={(value: number) => value.toFixed(2)}
/>
<Legend />
<Bar
dataKey="user"
name="Вы"
fill="#3182ce"
/>
<Bar
dataKey="global"
name="Среднее по пользователям"
fill="#805ad5"
/>
</BarChart>
</ResponsiveContainer>
</Box>
)}
</VStack>
</Card.Body>
</Card.Root>
{/* Detailed Weekday Table */}
<Card.Root w="full">
<Card.Body p={{ base: 4, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">Детализация по дням недели</Heading>
<Box overflowX="auto">
<Table.Root size={{ base: 'sm', md: 'md' }}>
<Table.Header>
<Table.Row>
<Table.ColumnHeader>День недели</Table.ColumnHeader>
<Table.ColumnHeader textAlign="right">Ваше среднее</Table.ColumnHeader>
<Table.ColumnHeader textAlign="right">Глобальное среднее</Table.ColumnHeader>
<Table.ColumnHeader textAlign="right">Разница, %</Table.ColumnHeader>
</Table.Row>
</Table.Header>
<Table.Body>
{weekdayChartData.map((day) => {
const diff = day.global > 0
? ((day.user - day.global) / day.global * 100).toFixed(1)
: '0'
const diffColor = parseFloat(diff) > 0 ? 'red.600' : parseFloat(diff) < 0 ? 'green.600' : 'gray.600'
return (
<Table.Row key={day.dayName}>
<Table.Cell fontWeight="medium">{day.dayName}</Table.Cell>
<Table.Cell textAlign="right">{day.user.toFixed(2)}</Table.Cell>
<Table.Cell textAlign="right">{day.global.toFixed(2)}</Table.Cell>
<Table.Cell textAlign="right" color={diffColor}>
{parseFloat(diff) > 0 ? '+' : ''}{diff}%
</Table.Cell>
</Table.Row>
)
})}
</Table.Body>
</Table.Root>
</Box>
</VStack>
</Card.Body>
</Card.Root>
</>
)}
</VStack>
)
}
// Main Stats Page with Tabs
export const StatsPage: React.FC = () => {
const [activeTab, setActiveTab] = useState<'daily' | 'summary'>('daily')
return (
<Box minH="100vh" bg="gray.50" p={{ base: 2, md: 8 }}>
<VStack gap={6} maxW="6xl" mx="auto">
@@ -115,141 +552,34 @@ export const StatsPage: React.FC = () => {
</Link>
</HStack>
{/* Date range selector */}
<Card.Root w="full">
<Card.Body p={{ base: 4, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">Выберите период</Heading>
{/* Tab Selector */}
<HStack w="full" gap={2} borderBottomWidth="1px" borderColor="gray.200">
<Button
variant={activeTab === 'daily' ? 'solid' : 'ghost'}
colorScheme={activeTab === 'daily' ? 'teal' : 'gray'}
onClick={() => setActiveTab('daily')}
borderRadius="0"
borderBottomWidth={activeTab === 'daily' ? '2px' : '0'}
borderBottomColor="teal.500"
>
Дневная статистика
</Button>
<Button
variant={activeTab === 'summary' ? 'solid' : 'ghost'}
colorScheme={activeTab === 'summary' ? 'teal' : 'gray'}
onClick={() => setActiveTab('summary')}
borderRadius="0"
borderBottomWidth={activeTab === 'summary' ? '2px' : '0'}
borderBottomColor="teal.500"
>
Сводная статистика
</Button>
</HStack>
<HStack gap={4} flexWrap="wrap">
<Field label="От">
<Input
type="date"
value={fromDate}
onChange={(e) => setFromDate(e.target.value)}
/>
</Field>
<Field label="До">
<Input
type="date"
value={toDate}
onChange={(e) => setToDate(e.target.value)}
/>
</Field>
<Box>
<Button
colorScheme="teal"
onClick={fetchStats}
disabled={isLoading}
mt={7}
>
{isLoading ? 'Загрузка...' : 'Обновить'}
</Button>
</Box>
</HStack>
</VStack>
</Card.Body>
</Card.Root>
{error && (
<Card.Root w="full" bg="red.50" borderColor="red.500" borderWidth={2}>
<Card.Body>
<Text color="red.700" fontWeight="bold">
{error}
</Text>
</Card.Body>
</Card.Root>
)}
{/* Summary statistics */}
<Card.Root w="full">
<Card.Body p={{ base: 4, md: 6 }}>
<Stack direction={{ base: 'column', md: 'row' }} gap={6} justify="space-around">
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="blue.500">
{totalCigarettes}
</Text>
<Text fontSize="sm" color="gray.600">
Всего сигарет
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="green.500">
{averagePerDay}
</Text>
<Text fontSize="sm" color="gray.600">
В среднем в день
</Text>
</VStack>
<VStack>
<Text fontSize="3xl" fontWeight="bold" color="orange.500">
{maxPerDay}
</Text>
<Text fontSize="sm" color="gray.600">
Максимум в день
</Text>
</VStack>
</Stack>
</Card.Body>
</Card.Root>
{/* Chart */}
<Card.Root w="full">
<Card.Body p={{ base: 2, md: 6 }}>
<VStack gap={4} align="stretch">
<Heading size="md">График по дням</Heading>
{isLoading ? (
<Text textAlign="center" py={8}>
Загрузка...
</Text>
) : stats.length === 0 ? (
<Text textAlign="center" py={8} color="gray.500">
Нет данных за выбранный период
</Text>
) : (
<Box w="full" h="400px">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={stats}
margin={{ top: 5, right: 5, left: 0, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis
dataKey="displayDate"
tick={{ fontSize: 12 }}
interval="preserveStartEnd"
/>
<YAxis allowDecimals={false} />
<Tooltip
contentStyle={{
backgroundColor: '#fff',
border: '1px solid #ccc',
borderRadius: '4px',
}}
labelFormatter={(label) => `Дата: ${label}`}
formatter={(value: number) => [value, 'Сигарет']}
/>
<Legend />
<Line
type="monotone"
dataKey="count"
name="Количество сигарет"
stroke="#3182ce"
strokeWidth={2}
activeDot={{ r: 8 }}
/>
</LineChart>
</ResponsiveContainer>
</Box>
)}
</VStack>
</Card.Body>
</Card.Root>
{/* Tab Content */}
<Box w="full">
{activeTab === 'daily' ? <DailyStatsTab /> : <SummaryStatsTab />}
</Box>
</VStack>
</Box>
)

View File

@@ -62,3 +62,42 @@ export interface GetDailyStatsParams {
to?: string
}
// Summary statistics types
export interface WeekdayStat {
dayOfWeek: number // 1 = Sunday, 2 = Monday, ..., 7 = Saturday
dayName: string
count: number
average: string
}
export interface UserSummary {
daily: DailyStat[]
averagePerDay: number
weekday: WeekdayStat[]
total: number
daysWithData: number
}
export interface GlobalSummary {
daily: DailyStat[]
averagePerDay: number
weekday: WeekdayStat[]
total: number
daysWithData: number
activeUsers: number
}
export interface SummaryStats {
user: UserSummary
global: GlobalSummary
period: {
from: string
to: string
}
}
export interface GetSummaryStatsParams {
from?: string
to?: string
}