StatsPage.tsx 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384
  1. import { useQuery } from '@tanstack/react-query';
  2. import { useState, useEffect, useMemo } from 'react';
  3. import { useTranslation } from 'react-i18next';
  4. import {
  5. Package,
  6. Clock,
  7. CheckCircle,
  8. XCircle,
  9. DollarSign,
  10. Target,
  11. Zap,
  12. AlertTriangle,
  13. TrendingDown,
  14. FileSpreadsheet,
  15. FileText,
  16. Loader2,
  17. Eye,
  18. RotateCcw,
  19. Calculator,
  20. Calendar,
  21. ChevronDown,
  22. Users,
  23. } from 'lucide-react';
  24. import {
  25. BarChart,
  26. Bar,
  27. XAxis,
  28. YAxis,
  29. CartesianGrid,
  30. Tooltip,
  31. ResponsiveContainer,
  32. } from 'recharts';
  33. import { Button } from '../components/Button';
  34. import { useToast } from '../contexts/ToastContext';
  35. import { useAuth } from '../contexts/AuthContext';
  36. import { api, type ArchiveSlim } from '../api/client';
  37. import { PrintCalendar } from '../components/PrintCalendar';
  38. import { FilamentTrends } from '../components/FilamentTrends';
  39. import { Dashboard, type DashboardWidget } from '../components/Dashboard';
  40. import { getCurrencySymbol } from '../utils/currency';
  41. import { formatWeight } from '../utils/weight';
  42. import { parseUTCDate, formatDuration } from '../utils/date';
  43. import { MetricToggle, type Metric } from '../components/MetricToggle';
  44. // Timeframe types and helpers
  45. type TimeframePreset = 'today' | 'this-week' | 'this-month' | 'last-7' | 'last-30' | 'last-90' | 'this-year' | 'all-time' | 'custom';
  46. interface TimeframeState {
  47. preset: TimeframePreset;
  48. dateFrom: string | undefined; // YYYY-MM-DD
  49. dateTo: string | undefined; // YYYY-MM-DD
  50. }
  51. function computeDateRange(preset: TimeframePreset): { dateFrom?: string; dateTo?: string } {
  52. const now = new Date();
  53. const y = now.getUTCFullYear(), m = now.getUTCMonth(), d = now.getUTCDate();
  54. const fmt = (dt: Date) => dt.toISOString().split('T')[0];
  55. const todayStr = fmt(now);
  56. switch (preset) {
  57. case 'today':
  58. return { dateFrom: todayStr, dateTo: todayStr };
  59. case 'this-week': {
  60. const day = now.getUTCDay();
  61. const start = new Date(Date.UTC(y, m, d - (day === 0 ? 6 : day - 1)));
  62. return { dateFrom: fmt(start), dateTo: todayStr };
  63. }
  64. case 'this-month':
  65. return { dateFrom: fmt(new Date(Date.UTC(y, m, 1))), dateTo: todayStr };
  66. case 'last-7':
  67. return { dateFrom: fmt(new Date(Date.UTC(y, m, d - 6))), dateTo: todayStr };
  68. case 'last-30':
  69. return { dateFrom: fmt(new Date(Date.UTC(y, m, d - 29))), dateTo: todayStr };
  70. case 'last-90':
  71. return { dateFrom: fmt(new Date(Date.UTC(y, m, d - 89))), dateTo: todayStr };
  72. case 'this-year':
  73. return { dateFrom: fmt(new Date(Date.UTC(y, 0, 1))), dateTo: todayStr };
  74. case 'all-time':
  75. return { dateFrom: undefined, dateTo: undefined };
  76. case 'custom':
  77. return {};
  78. }
  79. }
  80. const TIMEFRAME_PRESETS: TimeframePreset[] = [
  81. 'today', 'this-week', 'this-month',
  82. 'last-7', 'last-30', 'last-90',
  83. 'this-year', 'all-time',
  84. ];
  85. // Constants
  86. const DAY_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  87. const HOUR_LABELS = [
  88. '12am', '1am', '2am', '3am', '4am', '5am',
  89. '6am', '7am', '8am', '9am', '10am', '11am',
  90. '12pm', '1pm', '2pm', '3pm', '4pm', '5pm',
  91. '6pm', '7pm', '8pm', '9pm', '10pm', '11pm',
  92. ];
  93. const DURATION_BUCKETS = [
  94. { key: '<30m', max: 1800 },
  95. { key: '30m-1h', max: 3600 },
  96. { key: '1-2h', max: 7200 },
  97. { key: '2-4h', max: 14400 },
  98. { key: '4-8h', max: 28800 },
  99. { key: '8-12h', max: 43200 },
  100. { key: '12-24h', max: 86400 },
  101. { key: '24h+', max: Infinity },
  102. ];
  103. const RECHARTS_TOOLTIP_STYLE = {
  104. backgroundColor: '#2d2d2d',
  105. border: '1px solid #3d3d3d',
  106. borderRadius: '8px',
  107. };
  108. // Widget Components
  109. function QuickStatsWidget({
  110. stats,
  111. currency,
  112. }: {
  113. stats: {
  114. total_prints: number;
  115. successful_prints: number;
  116. failed_prints: number;
  117. total_print_time_hours: number;
  118. total_filament_grams: number;
  119. total_cost: number;
  120. total_energy_kwh: number;
  121. total_energy_cost: number;
  122. energy_data_warming_up?: boolean;
  123. } | undefined;
  124. currency: string;
  125. }) {
  126. const { t } = useTranslation();
  127. const warmingUp = stats?.energy_data_warming_up === true;
  128. const warmingUpTooltip = warmingUp ? t('stats.energyWarmingUpTooltip') : undefined;
  129. const items = [
  130. { icon: Package, color: 'text-bambu-green', label: t('stats.totalPrints'), value: `${stats?.total_prints || 0}` },
  131. { icon: Clock, color: 'text-blue-400', label: t('stats.printTime'), value: `${stats?.total_print_time_hours?.toFixed(1) ?? '0'}h` },
  132. { icon: Package, color: 'text-orange-400', label: t('stats.filamentUsed'), value: formatWeight(stats?.total_filament_grams || 0) },
  133. { icon: DollarSign, color: 'text-green-400', label: t('stats.filamentCost'), value: `${currency} ${stats?.total_cost?.toFixed(2) ?? '0.00'}` },
  134. {
  135. icon: Zap,
  136. color: 'text-yellow-400',
  137. label: t('stats.energyUsed'),
  138. value: `${stats?.total_energy_kwh?.toFixed(3) ?? '0.000'} kWh`,
  139. warning: warmingUp,
  140. tooltip: warmingUpTooltip,
  141. },
  142. {
  143. icon: DollarSign,
  144. color: 'text-yellow-500',
  145. label: t('stats.energyCost'),
  146. value: `${currency} ${stats?.total_energy_cost?.toFixed(2) ?? '0.00'}`,
  147. warning: warmingUp,
  148. tooltip: warmingUpTooltip,
  149. },
  150. ];
  151. return (
  152. <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
  153. {items.map((item) => (
  154. <div key={item.label} className="flex items-start gap-3" title={item.tooltip}>
  155. <div className={`p-2 rounded-lg bg-bambu-dark ${item.color}`}>
  156. <item.icon className="w-5 h-5" />
  157. </div>
  158. <div>
  159. <p className="text-xs text-bambu-gray flex items-center gap-1">
  160. {item.label}
  161. {item.warning && <AlertTriangle className="w-3 h-3 text-yellow-400" aria-label={item.tooltip} />}
  162. </p>
  163. <p className="text-xl font-bold text-white">{item.value}</p>
  164. </div>
  165. </div>
  166. ))}
  167. </div>
  168. );
  169. }
  170. function SuccessRateWidget({
  171. stats,
  172. printerMap,
  173. size = 1,
  174. }: {
  175. stats: {
  176. total_prints: number;
  177. successful_prints: number;
  178. failed_prints: number;
  179. prints_by_printer: Record<string, number>;
  180. } | undefined;
  181. printerMap: Map<string, string>;
  182. size?: 1 | 2 | 4;
  183. }) {
  184. const { t } = useTranslation();
  185. const completedAndFailed = (stats?.successful_prints || 0) + (stats?.failed_prints || 0);
  186. const successRate = completedAndFailed
  187. ? Math.round((stats!.successful_prints / completedAndFailed) * 100)
  188. : 0;
  189. // Scale gauge size based on widget size
  190. const gaugeSize = size === 1 ? 112 : size === 2 ? 128 : 144;
  191. const radius = gaugeSize / 2 - 8;
  192. const circumference = radius * 2 * Math.PI;
  193. return (
  194. <div className="flex items-center gap-6">
  195. <div className="relative flex-shrink-0" style={{ width: gaugeSize, height: gaugeSize }}>
  196. <svg className="w-full h-full -rotate-90">
  197. <circle
  198. cx={gaugeSize / 2}
  199. cy={gaugeSize / 2}
  200. r={radius}
  201. fill="none"
  202. stroke="#3d3d3d"
  203. strokeWidth="10"
  204. />
  205. <circle
  206. cx={gaugeSize / 2}
  207. cy={gaugeSize / 2}
  208. r={radius}
  209. fill="none"
  210. stroke="#00ae42"
  211. strokeWidth="10"
  212. strokeLinecap="round"
  213. strokeDasharray={`${(successRate / 100) * circumference} ${circumference}`}
  214. />
  215. </svg>
  216. <div className="absolute inset-0 flex items-center justify-center">
  217. <span className={`font-bold text-white ${size >= 2 ? 'text-2xl' : 'text-xl'}`}>{successRate}%</span>
  218. </div>
  219. </div>
  220. <div className="flex-1 min-w-0">
  221. <div className="space-y-2">
  222. <div className="flex items-center gap-2">
  223. <CheckCircle className="w-4 h-4 text-status-ok flex-shrink-0" />
  224. <span className="text-sm text-bambu-gray">{t('stats.successful')}</span>
  225. <span className="text-sm text-white font-medium">{stats?.successful_prints || 0}</span>
  226. </div>
  227. <div className="flex items-center gap-2">
  228. <XCircle className="w-4 h-4 text-status-error flex-shrink-0" />
  229. <span className="text-sm text-bambu-gray">{t('stats.failed')}</span>
  230. <span className="text-sm text-white font-medium">{stats?.failed_prints || 0}</span>
  231. </div>
  232. </div>
  233. {/* Show per-printer breakdown when expanded */}
  234. {size >= 2 && stats?.prints_by_printer && Object.keys(stats.prints_by_printer).length > 0 && (
  235. <div className="mt-4 pt-4 border-t border-bambu-dark-tertiary">
  236. <p className="text-xs text-bambu-gray font-medium mb-2">{t('stats.printsByPrinter')}</p>
  237. <div className={`grid gap-x-6 gap-y-1 ${size === 4 ? 'grid-cols-3' : 'grid-cols-2'}`} style={{ width: 'fit-content' }}>
  238. {Object.entries(stats.prints_by_printer).map(([printerId, count]) => (
  239. <div key={printerId} className="flex items-center gap-3 text-sm">
  240. <span className="text-bambu-gray truncate max-w-[120px]">
  241. {printerMap.get(printerId) || `${t('common.printer')} ${printerId}`}
  242. </span>
  243. <span className="text-white font-medium">{count}</span>
  244. </div>
  245. ))}
  246. </div>
  247. </div>
  248. )}
  249. </div>
  250. </div>
  251. );
  252. }
  253. function TimeAccuracyWidget({
  254. stats,
  255. printerMap,
  256. size = 1,
  257. }: {
  258. stats: {
  259. average_time_accuracy: number | null;
  260. time_accuracy_by_printer: Record<string, number> | null;
  261. } | undefined;
  262. printerMap: Map<string, string>;
  263. size?: 1 | 2 | 4;
  264. }) {
  265. const { t } = useTranslation();
  266. const accuracy = stats?.average_time_accuracy;
  267. if (accuracy === null || accuracy === undefined) {
  268. return (
  269. <div className="flex items-center justify-center h-full">
  270. <p className="text-bambu-gray text-center py-4">{t('stats.noTimeAccuracyData')}</p>
  271. </div>
  272. );
  273. }
  274. // Normalize accuracy for display (100% = perfect, clamp between 50-150 for gauge)
  275. const displayValue = Math.min(150, Math.max(50, accuracy));
  276. const normalizedForGauge = ((displayValue - 50) / 100) * 100; // 50-150 -> 0-100
  277. // Color based on accuracy
  278. const getColor = (acc: number) => {
  279. if (acc >= 95 && acc <= 105) return '#00ae42'; // Green - within 5%
  280. if (acc > 105) return '#3b82f6'; // Blue - faster than expected
  281. return '#f97316'; // Orange - slower than expected
  282. };
  283. const color = getColor(accuracy);
  284. const deviation = accuracy - 100;
  285. // Scale gauge size based on widget size
  286. const gaugeSize = size === 1 ? 112 : size === 2 ? 128 : 144;
  287. const radius = gaugeSize / 2 - 8;
  288. const circumference = radius * 2 * Math.PI;
  289. // Show more printers when expanded
  290. const maxPrinters = size === 1 ? 3 : size === 2 ? 6 : 999;
  291. const printerEntries = stats?.time_accuracy_by_printer
  292. ? Object.entries(stats.time_accuracy_by_printer).slice(0, maxPrinters)
  293. : [];
  294. return (
  295. <div className="flex items-center gap-6">
  296. <div className="relative flex-shrink-0" style={{ width: gaugeSize, height: gaugeSize }}>
  297. <svg className="w-full h-full -rotate-90">
  298. <circle
  299. cx={gaugeSize / 2}
  300. cy={gaugeSize / 2}
  301. r={radius}
  302. fill="none"
  303. stroke="#3d3d3d"
  304. strokeWidth="10"
  305. />
  306. <circle
  307. cx={gaugeSize / 2}
  308. cy={gaugeSize / 2}
  309. r={radius}
  310. fill="none"
  311. stroke={color}
  312. strokeWidth="10"
  313. strokeLinecap="round"
  314. strokeDasharray={`${(normalizedForGauge / 100) * circumference} ${circumference}`}
  315. />
  316. </svg>
  317. <div className="absolute inset-0 flex flex-col items-center justify-center">
  318. <span className={`font-bold text-white ${size >= 2 ? 'text-2xl' : 'text-xl'}`}>{accuracy.toFixed(0)}%</span>
  319. <span className={`text-xs ${deviation >= 0 ? 'text-blue-400' : 'text-orange-400'}`}>
  320. {deviation >= 0 ? '+' : ''}{deviation.toFixed(0)}%
  321. </span>
  322. </div>
  323. </div>
  324. <div className="flex-1 min-w-0">
  325. <div className="flex items-center gap-2 text-xs text-bambu-gray">
  326. <Target className="w-3 h-3 flex-shrink-0" />
  327. <span>{t('stats.perfectEstimate')}</span>
  328. </div>
  329. {printerEntries.length > 0 && (
  330. <div className={`mt-2 ${size === 4 ? 'grid grid-cols-3 gap-x-6 gap-y-1' : size === 2 ? 'grid grid-cols-2 gap-x-6 gap-y-1' : 'space-y-1'}`} style={{ width: 'fit-content' }}>
  331. {printerEntries.map(([printerId, acc]) => (
  332. <div key={printerId} className="flex items-center gap-2 text-xs">
  333. <span className="text-bambu-gray truncate max-w-[100px]">
  334. {printerMap.get(printerId) || `${t('common.printer')} ${printerId}`}
  335. </span>
  336. <span className={`font-medium ${
  337. acc >= 95 && acc <= 105 ? 'text-status-ok' :
  338. acc > 105 ? 'text-blue-400' : 'text-status-warning'
  339. }`}>
  340. {acc.toFixed(0)}%
  341. </span>
  342. </div>
  343. ))}
  344. </div>
  345. )}
  346. </div>
  347. </div>
  348. );
  349. }
  350. function HourlyHeatmap({ printDates, dateFrom, dateTo }: { printDates: string[]; dateFrom: string; dateTo: string }) {
  351. const { days, hourlyCounts, maxCount } = useMemo(() => {
  352. const start = new Date(dateFrom + 'T00:00:00');
  353. const end = new Date(dateTo + 'T00:00:00');
  354. const days: { key: string; label: string }[] = [];
  355. const fmtLocal = (d: Date) =>
  356. `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
  357. const current = new Date(start);
  358. while (current <= end) {
  359. days.push({
  360. key: fmtLocal(current),
  361. label: current.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric' }),
  362. });
  363. current.setDate(current.getDate() + 1);
  364. }
  365. // Count prints per (day, hour)
  366. const counts: Record<string, number> = {};
  367. let max = 0;
  368. printDates.forEach(d => {
  369. const date = parseUTCDate(d);
  370. if (!date) return;
  371. const dayKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  372. const k = `${dayKey}-${date.getHours()}`;
  373. counts[k] = (counts[k] || 0) + 1;
  374. if (counts[k] > max) max = counts[k];
  375. });
  376. return { days, hourlyCounts: counts, maxCount: Math.max(1, max) };
  377. }, [printDates, dateFrom, dateTo]);
  378. const getColor = (count: number) => {
  379. if (count === 0) return 'bg-bambu-dark';
  380. const intensity = count / maxCount;
  381. if (intensity <= 0.25) return 'bg-bambu-green/30';
  382. if (intensity <= 0.5) return 'bg-bambu-green/50';
  383. if (intensity <= 0.75) return 'bg-bambu-green/75';
  384. return 'bg-bambu-green';
  385. };
  386. const cellSize = 20;
  387. const gap = 2;
  388. const dayLabelWidth = 80;
  389. return (
  390. <div className="w-full overflow-x-auto">
  391. <div className="inline-flex flex-col" style={{ gap }}>
  392. {/* Hour labels row */}
  393. <div className="flex" style={{ gap, marginLeft: dayLabelWidth + 4 }}>
  394. {HOUR_LABELS.map((label, i) => (
  395. <div
  396. key={i}
  397. className="text-bambu-gray text-[10px] text-center"
  398. style={{ width: cellSize, visibility: i % 2 === 0 ? 'visible' : 'hidden' }}
  399. >
  400. {label}
  401. </div>
  402. ))}
  403. </div>
  404. {/* Day rows */}
  405. {days.map(day => (
  406. <div key={day.key} className="flex items-center" style={{ gap }}>
  407. <div
  408. className="text-bambu-gray text-[10px] flex-shrink-0 truncate"
  409. style={{ width: dayLabelWidth }}
  410. >
  411. {day.label}
  412. </div>
  413. {Array.from({ length: 24 }, (_, hour) => {
  414. const count = hourlyCounts[`${day.key}-${hour}`] || 0;
  415. return (
  416. <div
  417. key={hour}
  418. className={`rounded-sm ${getColor(count)}`}
  419. style={{ width: cellSize, height: cellSize }}
  420. title={`${day.label} ${HOUR_LABELS[hour]}: ${count} print${count !== 1 ? 's' : ''}`}
  421. />
  422. );
  423. })}
  424. </div>
  425. ))}
  426. </div>
  427. {/* Legend */}
  428. <div className="flex items-center gap-2 mt-3 text-bambu-gray text-xs">
  429. <span>Less</span>
  430. <div className="flex" style={{ gap }}>
  431. <div className="rounded-sm bg-bambu-dark" style={{ width: cellSize, height: cellSize }} />
  432. <div className="rounded-sm bg-bambu-green/30" style={{ width: cellSize, height: cellSize }} />
  433. <div className="rounded-sm bg-bambu-green/50" style={{ width: cellSize, height: cellSize }} />
  434. <div className="rounded-sm bg-bambu-green/75" style={{ width: cellSize, height: cellSize }} />
  435. <div className="rounded-sm bg-bambu-green" style={{ width: cellSize, height: cellSize }} />
  436. </div>
  437. <span>More</span>
  438. </div>
  439. </div>
  440. );
  441. }
  442. function PrintActivityWidget({
  443. printDates,
  444. size = 2,
  445. dateFrom,
  446. dateTo,
  447. }: {
  448. printDates: string[];
  449. size?: 1 | 2 | 4;
  450. dateFrom?: string;
  451. dateTo?: string;
  452. }) {
  453. const spanDays = useMemo(() => {
  454. if (dateFrom && dateTo) {
  455. return Math.max((new Date(dateTo).getTime() - new Date(dateFrom).getTime()) / 86400000, 0) + 1;
  456. }
  457. if (dateFrom) {
  458. return Math.max((Date.now() - new Date(dateFrom).getTime()) / 86400000, 0) + 1;
  459. }
  460. return Infinity;
  461. }, [dateFrom, dateTo]);
  462. if (spanDays <= 7 && dateFrom && dateTo) {
  463. return <HourlyHeatmap printDates={printDates} dateFrom={dateFrom} dateTo={dateTo} />;
  464. }
  465. // Calculate months from the timeframe span, fall back to size-based default for all-time
  466. const sizeDefault = size === 1 ? 3 : size === 2 ? 6 : 12;
  467. const months = spanDays === Infinity
  468. ? sizeDefault
  469. : Math.max(1, Math.ceil(spanDays / 30));
  470. return <PrintCalendar printDates={printDates} months={months} />;
  471. }
  472. function PrinterStatsWidget({
  473. stats,
  474. archives,
  475. printerMap,
  476. }: {
  477. stats: { prints_by_printer: Record<string, number> } | undefined;
  478. archives: ArchiveSlim[];
  479. printerMap: Map<string, string>;
  480. }) {
  481. const { t } = useTranslation();
  482. const [printerMetric, setPrinterMetric] = useState<Metric>('weight');
  483. const [habitsMetric, setHabitsMetric] = useState<Metric>('weight');
  484. // Per-printer data
  485. const printerData = useMemo(() => {
  486. const map = new Map<string, { prints: number; weight: number; time: number }>();
  487. if (stats?.prints_by_printer) {
  488. Object.entries(stats.prints_by_printer).forEach(([id, count]) => {
  489. const entry = map.get(id) || { prints: 0, weight: 0, time: 0 };
  490. entry.prints = count;
  491. map.set(id, entry);
  492. });
  493. }
  494. archives.forEach(a => {
  495. if (!a.printer_id) return;
  496. const id = String(a.printer_id);
  497. const entry = map.get(id) || { prints: 0, weight: 0, time: 0 };
  498. entry.weight += a.filament_used_grams || 0;
  499. entry.time += a.actual_time_seconds || a.print_time_seconds || 0;
  500. if (!stats?.prints_by_printer) entry.prints++;
  501. map.set(id, entry);
  502. });
  503. return Array.from(map.entries())
  504. .map(([id, v]) => ({
  505. name: printerMap.get(id) || `${t('common.printer')} ${id}`,
  506. value: printerMetric === 'prints' ? v.prints :
  507. printerMetric === 'weight' ? Math.round(v.weight) :
  508. Math.round((v.time / 3600) * 10) / 10,
  509. }))
  510. .sort((a, b) => b.value - a.value);
  511. }, [stats, archives, printerMap, printerMetric, t]);
  512. // Hourly distribution (time of day)
  513. const hourlyData = useMemo(() => {
  514. const hours = Array.from({ length: 24 }, (_, i) => ({
  515. hour: i,
  516. label: HOUR_LABELS[i],
  517. total: 0,
  518. failures: 0,
  519. }));
  520. archives.forEach(a => {
  521. if (!a.started_at) return;
  522. const date = parseUTCDate(a.started_at);
  523. if (!date) return;
  524. const h = date.getHours();
  525. hours[h].total++;
  526. if (a.status === 'failed') {
  527. hours[h].failures++;
  528. }
  529. });
  530. return hours;
  531. }, [archives]);
  532. // Duration distribution
  533. const durationData = useMemo(() => {
  534. const counts = DURATION_BUCKETS.map(b => ({ name: b.key, count: 0 }));
  535. archives.forEach(a => {
  536. const seconds = a.actual_time_seconds || a.print_time_seconds;
  537. if (!seconds || seconds <= 0) return;
  538. for (let i = 0; i < DURATION_BUCKETS.length; i++) {
  539. if (seconds <= DURATION_BUCKETS[i].max) {
  540. counts[i].count++;
  541. break;
  542. }
  543. }
  544. });
  545. return counts;
  546. }, [archives]);
  547. // Habits (avg per day-of-week)
  548. const habitsData = useMemo(() => {
  549. const dayValues = [0, 0, 0, 0, 0, 0, 0];
  550. const weeksSet = new Set<string>();
  551. archives.forEach(a => {
  552. const date = parseUTCDate(a.created_at) || new Date(a.created_at);
  553. let day = date.getDay() - 1;
  554. if (day < 0) day = 6;
  555. if (habitsMetric === 'prints') dayValues[day]++;
  556. else if (habitsMetric === 'weight') dayValues[day] += a.filament_used_grams || 0;
  557. else dayValues[day] += (a.actual_time_seconds || a.print_time_seconds || 0) / 3600;
  558. const weekStart = new Date(date);
  559. weekStart.setDate(date.getDate() - ((date.getDay() + 6) % 7));
  560. weeksSet.add(`${weekStart.getFullYear()}-${String(weekStart.getMonth() + 1).padStart(2, '0')}-${String(weekStart.getDate()).padStart(2, '0')}`);
  561. });
  562. const numWeeks = Math.max(weeksSet.size, 1);
  563. return DAY_LABELS.map((name, i) => ({
  564. name,
  565. avg: Math.round((dayValues[i] / numWeeks) * 10) / 10,
  566. }));
  567. }, [archives, habitsMetric]);
  568. const metricStyle = (m: Metric) => ({
  569. unit: m === 'weight' ? 'g' : m === 'time' ? 'h' : '',
  570. color: m === 'weight' ? '#00ae42' : m === 'time' ? '#3b82f6' : '#f59e0b',
  571. });
  572. const ps = metricStyle(printerMetric);
  573. const pLabel = printerMetric === 'weight' ? t('stats.filamentByWeight') : printerMetric === 'time' ? t('stats.hours') : t('common.prints');
  574. const hs = metricStyle(habitsMetric);
  575. const hLabel = habitsMetric === 'weight' ? t('stats.avgWeight') : habitsMetric === 'time' ? t('stats.avgTime') : t('stats.avgPrints');
  576. return (
  577. <div className="space-y-4">
  578. {/* By Printer */}
  579. <div className="bg-bambu-dark rounded-lg p-4">
  580. <div className="flex items-center justify-between mb-3">
  581. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.printsByPrinter')}</h4>
  582. <MetricToggle value={printerMetric} onChange={setPrinterMetric} />
  583. </div>
  584. {printerData.length > 0 ? (
  585. <ResponsiveContainer width="100%" height={Math.max(140, printerData.length * 40)}>
  586. <BarChart data={printerData} layout="vertical" margin={{ left: 10 }}>
  587. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  588. <XAxis type="number" stroke="#9ca3af" tick={{ fontSize: 11 }} unit={ps.unit} />
  589. <YAxis type="category" dataKey="name" stroke="#9ca3af" tick={{ fontSize: 11 }} width={100} />
  590. <Tooltip
  591. contentStyle={RECHARTS_TOOLTIP_STYLE}
  592. formatter={(v: number | undefined) => [
  593. printerMetric === 'weight' ? formatWeight(Number(v ?? 0)) : `${v ?? 0}${ps.unit}`,
  594. pLabel,
  595. ]}
  596. />
  597. <Bar dataKey="value" fill={ps.color} radius={[0, 4, 4, 0]} />
  598. </BarChart>
  599. </ResponsiveContainer>
  600. ) : (
  601. <p className="text-bambu-gray text-center py-4">{t('stats.noPrinterData')}</p>
  602. )}
  603. </div>
  604. <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
  605. {/* Print Duration */}
  606. <div className="bg-bambu-dark rounded-lg p-4">
  607. <h4 className="text-sm font-medium text-bambu-gray mb-3">{t('stats.printDuration')}</h4>
  608. {archives.length > 0 ? (
  609. <ResponsiveContainer width="100%" height={160}>
  610. <BarChart data={durationData}>
  611. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  612. <XAxis dataKey="name" stroke="#9ca3af" tick={{ fontSize: 11 }} />
  613. <YAxis stroke="#9ca3af" tick={{ fontSize: 11 }} allowDecimals={false} />
  614. <Tooltip contentStyle={RECHARTS_TOOLTIP_STYLE} />
  615. <Bar dataKey="count" name={t('common.prints')} fill="#00ae42" radius={[4, 4, 0, 0]} />
  616. </BarChart>
  617. </ResponsiveContainer>
  618. ) : (
  619. <p className="text-bambu-gray text-center py-4">{t('stats.noArchiveData')}</p>
  620. )}
  621. </div>
  622. {/* Print Habits */}
  623. <div className="bg-bambu-dark rounded-lg p-4">
  624. <div className="flex items-center justify-between mb-3">
  625. <h4 className="text-sm font-medium text-bambu-gray">{t('stats.printHabits')}</h4>
  626. <MetricToggle value={habitsMetric} onChange={setHabitsMetric} />
  627. </div>
  628. {archives.length > 0 ? (
  629. <ResponsiveContainer width="100%" height={160}>
  630. <BarChart data={habitsData}>
  631. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  632. <XAxis dataKey="name" stroke="#9ca3af" tick={{ fontSize: 11 }} />
  633. <YAxis stroke="#9ca3af" tick={{ fontSize: 11 }} unit={hs.unit} />
  634. <Tooltip contentStyle={RECHARTS_TOOLTIP_STYLE} formatter={(v: number | undefined) => [`${v ?? 0}${hs.unit}`, hLabel]} />
  635. <Bar dataKey="avg" fill={hs.color} radius={[4, 4, 0, 0]} />
  636. </BarChart>
  637. </ResponsiveContainer>
  638. ) : (
  639. <p className="text-bambu-gray text-center py-4">{t('stats.noArchiveData')}</p>
  640. )}
  641. </div>
  642. {/* Print Time of Day */}
  643. <div className="bg-bambu-dark rounded-lg p-4">
  644. <h4 className="text-sm font-medium text-bambu-gray mb-3">{t('stats.printTimeOfDay')}</h4>
  645. {archives.length > 0 ? (
  646. <ResponsiveContainer width="100%" height={160}>
  647. <BarChart data={hourlyData}>
  648. <CartesianGrid strokeDasharray="3 3" stroke="#3d3d3d" />
  649. <XAxis dataKey="label" stroke="#9ca3af" tick={{ fontSize: 10 }} interval={5} />
  650. <YAxis stroke="#9ca3af" tick={{ fontSize: 11 }} allowDecimals={false} />
  651. <Tooltip contentStyle={RECHARTS_TOOLTIP_STYLE} />
  652. <Bar dataKey="total" name={t('stats.totalPrints')} fill="#00ae42" radius={[2, 2, 0, 0]} />
  653. <Bar dataKey="failures" name={t('stats.failed')} fill="#ef4444" radius={[2, 2, 0, 0]} />
  654. </BarChart>
  655. </ResponsiveContainer>
  656. ) : (
  657. <p className="text-bambu-gray text-center py-4">{t('stats.noArchiveData')}</p>
  658. )}
  659. </div>
  660. </div>
  661. </div>
  662. );
  663. }
  664. function FilamentTrendsWidget({
  665. archives,
  666. currency,
  667. dateFrom,
  668. dateTo,
  669. }: {
  670. archives: Parameters<typeof FilamentTrends>[0]['archives'];
  671. currency: string;
  672. dateFrom?: string;
  673. dateTo?: string;
  674. }) {
  675. const { t } = useTranslation();
  676. if (!archives || archives.length === 0) {
  677. return <p className="text-bambu-gray text-center py-4">{t('stats.noPrintData')}</p>;
  678. }
  679. return <FilamentTrends archives={archives} currency={currency} dateFrom={dateFrom} dateTo={dateTo} />;
  680. }
  681. function FailureAnalysisWidget({ size = 1, dateFrom, dateTo, createdById }: {
  682. size?: 1 | 2 | 4;
  683. dateFrom?: string;
  684. dateTo?: string;
  685. createdById?: number;
  686. }) {
  687. const { t } = useTranslation();
  688. const hasDateRange = !!(dateFrom || dateTo);
  689. const { data: analysis, isLoading } = useQuery({
  690. queryKey: ['failureAnalysis', dateFrom, dateTo, createdById ?? 'all'],
  691. queryFn: () => api.getFailureAnalysis({
  692. ...(hasDateRange ? { dateFrom, dateTo } : { days: 30 }),
  693. createdById,
  694. }),
  695. });
  696. if (isLoading) {
  697. return (
  698. <div className="flex justify-center py-4">
  699. <Loader2 className="w-6 h-6 text-bambu-green animate-spin" />
  700. </div>
  701. );
  702. }
  703. if (!analysis || analysis.total_prints === 0) {
  704. return <p className="text-bambu-gray text-center py-4">{hasDateRange ? t('stats.noPrintDataInRange') : t('stats.noPrintDataLast30Days')}</p>;
  705. }
  706. // Show more reasons when expanded
  707. const maxReasons = size === 1 ? 5 : size === 2 ? 8 : 999;
  708. const allReasons = Object.entries(analysis.failures_by_reason).sort(([, a], [, b]) => b - a);
  709. const topReasons = allReasons.slice(0, maxReasons);
  710. const hasMore = allReasons.length > maxReasons;
  711. return (
  712. <div className={`${size >= 2 ? 'flex gap-8' : 'space-y-4'}`}>
  713. {/* Summary */}
  714. <div className={size >= 2 ? 'flex-shrink-0' : ''}>
  715. <div className="flex items-center gap-4">
  716. <div className="flex items-center gap-2">
  717. <AlertTriangle className={`w-5 h-5 ${analysis.failure_rate > 20 ? 'text-status-error' : analysis.failure_rate > 10 ? 'text-status-warning' : 'text-status-ok'}`} />
  718. <span className={`font-bold text-white ${size >= 2 ? 'text-3xl' : 'text-2xl'}`}>{analysis.failure_rate.toFixed(1)}%</span>
  719. </div>
  720. </div>
  721. <div className="text-sm text-bambu-gray mt-1">
  722. {t('stats.failedPrintsCount', { failed: analysis.failed_prints, total: analysis.total_prints })}
  723. </div>
  724. {/* Trend indicator */}
  725. {analysis.trend && analysis.trend.length >= 2 && (
  726. <div className={`${size >= 2 ? 'mt-4' : 'mt-2 pt-2 border-t border-bambu-dark-tertiary'}`}>
  727. <div className="flex items-center gap-2 text-sm">
  728. <TrendingDown className={`w-4 h-4 ${
  729. analysis.trend[analysis.trend.length - 1].failure_rate < analysis.trend[analysis.trend.length - 2].failure_rate
  730. ? 'text-status-ok'
  731. : 'text-status-error'
  732. }`} />
  733. <span className="text-bambu-gray">
  734. {t('stats.lastWeekRate', { rate: analysis.trend[analysis.trend.length - 1].failure_rate.toFixed(1) })}
  735. </span>
  736. </div>
  737. </div>
  738. )}
  739. </div>
  740. {/* Failure Reasons */}
  741. {topReasons.length > 0 && (
  742. <div className={`flex-1 ${size >= 2 ? 'border-l border-bambu-dark-tertiary pl-8' : 'pt-2'}`}>
  743. <p className="text-xs text-bambu-gray font-medium mb-2">
  744. {size >= 2 ? t('stats.failureReasons') : t('stats.topFailureReasons')}
  745. </p>
  746. <div className={`${size === 4 ? 'grid grid-cols-2 gap-x-6 gap-y-1' : 'space-y-1'}`}>
  747. {topReasons.map(([reason, count]) => (
  748. <div key={reason} className="flex items-center justify-between text-sm">
  749. <span className={`text-white truncate ${size === 4 ? 'max-w-[200px]' : 'max-w-[160px]'}`}>
  750. {reason || t('common.unknown')}
  751. </span>
  752. <span className="text-bambu-gray ml-2">{count}</span>
  753. </div>
  754. ))}
  755. </div>
  756. {hasMore && (
  757. <p className="text-xs text-bambu-gray mt-2">
  758. {t('common.more', { count: allReasons.length - maxReasons })}
  759. </p>
  760. )}
  761. </div>
  762. )}
  763. </div>
  764. );
  765. }
  766. function RecordsWidget({ archives, currency }: { archives: ArchiveSlim[]; currency: string }) {
  767. const { t } = useTranslation();
  768. const records = useMemo(() => {
  769. const result: Array<{
  770. icon: typeof Clock;
  771. iconColor: string;
  772. label: string;
  773. value: string;
  774. detail: string | null;
  775. }> = [];
  776. if (archives.length === 0) return result;
  777. // Find the archive with the highest value for a given field
  778. const findMax = (getter: (a: ArchiveSlim) => number | null | undefined): { archive: ArchiveSlim | null; value: number } => {
  779. let best: ArchiveSlim | null = null;
  780. let bestVal = 0;
  781. archives.forEach(a => {
  782. const v = getter(a);
  783. if (v && v > bestVal) { bestVal = v; best = a; }
  784. });
  785. return { archive: best, value: bestVal };
  786. };
  787. const longest = findMax(a => a.actual_time_seconds);
  788. if (longest.archive) {
  789. result.push({
  790. icon: Clock, iconColor: 'text-blue-400', label: t('stats.longestPrint'),
  791. value: formatDuration(longest.value),
  792. detail: longest.archive.print_name || null,
  793. });
  794. }
  795. const heaviest = findMax(a => a.filament_used_grams);
  796. if (heaviest.archive) {
  797. result.push({
  798. icon: Package, iconColor: 'text-orange-400', label: t('stats.heaviestPrint'),
  799. value: formatWeight(heaviest.value),
  800. detail: heaviest.archive.print_name || null,
  801. });
  802. }
  803. const costliest = findMax(a => a.cost);
  804. if (costliest.archive) {
  805. result.push({
  806. icon: DollarSign, iconColor: 'text-green-400', label: t('stats.mostExpensivePrint'),
  807. value: `${currency}${costliest.value.toFixed(2)}`,
  808. detail: costliest.archive.print_name || null,
  809. });
  810. }
  811. // Busiest day
  812. const dayCounts = new Map<string, number>();
  813. archives.forEach(a => {
  814. const date = parseUTCDate(a.created_at) || new Date(a.created_at);
  815. const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  816. dayCounts.set(key, (dayCounts.get(key) || 0) + 1);
  817. });
  818. let busiestDay = '';
  819. let busiestCount = 0;
  820. dayCounts.forEach((count, day) => {
  821. if (count > busiestCount) {
  822. busiestCount = count;
  823. busiestDay = day;
  824. }
  825. });
  826. if (busiestCount > 1) {
  827. result.push({
  828. icon: Calendar,
  829. iconColor: 'text-purple-400',
  830. label: t('stats.busiestDay'),
  831. value: `${busiestCount} ${t('common.prints')}`,
  832. detail: (() => { const [y, m, d] = busiestDay.split('-').map(Number); return new Date(y, m - 1, d).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }); })(),
  833. });
  834. }
  835. // Success streak
  836. const sorted = [...archives]
  837. .filter(a => a.status === 'completed' || a.status === 'failed')
  838. .sort((a, b) => new Date(b.completed_at || b.created_at).getTime() - new Date(a.completed_at || a.created_at).getTime());
  839. let streak = 0;
  840. for (const a of sorted) {
  841. if (a.status === 'completed') streak++;
  842. else break;
  843. }
  844. if (streak > 0) {
  845. result.push({
  846. icon: Zap,
  847. iconColor: 'text-yellow-400',
  848. label: t('stats.successStreak'),
  849. value: `${streak}`,
  850. detail: streak === 1 ? t('stats.streakPrint') : t('stats.streakPrints', { count: streak }),
  851. });
  852. }
  853. return result;
  854. }, [archives, currency, t]);
  855. if (records.length === 0) {
  856. return <p className="text-bambu-gray text-center py-4">{t('stats.noArchiveData')}</p>;
  857. }
  858. return (
  859. <div className="space-y-3">
  860. {records.map((record, i) => (
  861. <div key={i} className="flex items-center gap-3">
  862. <div className={`p-1.5 rounded-lg bg-bambu-dark ${record.iconColor}`}>
  863. <record.icon className="w-4 h-4" />
  864. </div>
  865. <div className="flex-1 min-w-0">
  866. <p className="text-xs text-bambu-gray">{record.label}</p>
  867. <div className="flex items-baseline gap-2">
  868. <span className="text-sm font-bold text-white">{record.value}</span>
  869. {record.detail && (
  870. <span className="text-xs text-bambu-gray truncate">{record.detail}</span>
  871. )}
  872. </div>
  873. </div>
  874. </div>
  875. ))}
  876. </div>
  877. );
  878. }
  879. export function StatsPage() {
  880. const { t } = useTranslation();
  881. const { showToast } = useToast();
  882. const { hasPermission, authEnabled } = useAuth();
  883. const [isExporting, setIsExporting] = useState(false);
  884. const [showExportMenu, setShowExportMenu] = useState(false);
  885. const [dashboardKey, setDashboardKey] = useState(0);
  886. const [hiddenCount, setHiddenCount] = useState(0);
  887. const [isRecalculating, setIsRecalculating] = useState(false);
  888. const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
  889. const [showUserPicker, setShowUserPicker] = useState(false);
  890. const canFilterByUser = authEnabled && hasPermission('stats:filter_by_user');
  891. const [timeframe, setTimeframe] = useState<TimeframeState>(() => {
  892. try {
  893. const saved = localStorage.getItem('bambusy-stats-timeframe');
  894. if (saved) {
  895. const parsed = JSON.parse(saved);
  896. if (parsed.preset) return parsed;
  897. }
  898. } catch { /* ignore */ }
  899. return { preset: 'all-time', dateFrom: undefined, dateTo: undefined };
  900. });
  901. const [showTimeframePicker, setShowTimeframePicker] = useState(false);
  902. // Persist timeframe selection
  903. useEffect(() => {
  904. localStorage.setItem('bambusy-stats-timeframe', JSON.stringify(timeframe));
  905. }, [timeframe]);
  906. const effectiveDateRange = useMemo(() => {
  907. if (timeframe.preset === 'custom') {
  908. return { dateFrom: timeframe.dateFrom, dateTo: timeframe.dateTo };
  909. }
  910. return computeDateRange(timeframe.preset);
  911. }, [timeframe]);
  912. // Read hidden count from localStorage
  913. useEffect(() => {
  914. const updateHiddenCount = () => {
  915. try {
  916. const saved = localStorage.getItem('bambusy-dashboard-layout-v2');
  917. if (saved) {
  918. const layout = JSON.parse(saved);
  919. setHiddenCount(layout.hidden?.length || 0);
  920. }
  921. } catch {
  922. setHiddenCount(0);
  923. }
  924. };
  925. updateHiddenCount();
  926. // Listen for storage changes
  927. window.addEventListener('storage', updateHiddenCount);
  928. // Also poll for changes (since storage event doesn't fire for same-tab changes)
  929. const interval = setInterval(updateHiddenCount, 2000);
  930. return () => {
  931. window.removeEventListener('storage', updateHiddenCount);
  932. clearInterval(interval);
  933. };
  934. }, [dashboardKey]);
  935. // Only pass createdById when a user is actually selected (not "All Users")
  936. const createdByIdParam = selectedUserId !== null ? selectedUserId : undefined;
  937. const { data: stats, isLoading, isFetching: isStatsFetching, refetch: refetchStats } = useQuery({
  938. queryKey: ['archiveStats', effectiveDateRange.dateFrom, effectiveDateRange.dateTo, createdByIdParam ?? 'all'],
  939. queryFn: () => api.getArchiveStats({
  940. dateFrom: effectiveDateRange.dateFrom,
  941. dateTo: effectiveDateRange.dateTo,
  942. createdById: createdByIdParam,
  943. }),
  944. });
  945. const { data: printers } = useQuery({
  946. queryKey: ['printers'],
  947. queryFn: api.getPrinters,
  948. });
  949. const { data: archives, isFetching: isArchivesFetching, refetch: refetchArchives } = useQuery({
  950. queryKey: ['archivesSlim', effectiveDateRange.dateFrom, effectiveDateRange.dateTo, createdByIdParam ?? 'all'],
  951. queryFn: () => api.getArchivesSlim(effectiveDateRange.dateFrom, effectiveDateRange.dateTo, createdByIdParam),
  952. });
  953. const { data: settings } = useQuery({
  954. queryKey: ['settings'],
  955. queryFn: api.getSettings,
  956. });
  957. const { data: users } = useQuery({
  958. queryKey: ['users'],
  959. queryFn: api.getUsers,
  960. enabled: canFilterByUser,
  961. });
  962. const selectedUserLabel = useMemo(() => {
  963. if (selectedUserId === null) return t('stats.allUsers', 'All Users');
  964. if (selectedUserId === -1) return t('stats.noUser', 'No User (System)');
  965. return users?.find(u => u.id === selectedUserId)?.username ?? '?';
  966. }, [selectedUserId, users, t]);
  967. const handleExport = async (format: 'csv' | 'xlsx') => {
  968. setShowExportMenu(false);
  969. setIsExporting(true);
  970. try {
  971. const { blob, filename } = await api.exportStats({ format, days: 90, createdById: createdByIdParam });
  972. const url = URL.createObjectURL(blob);
  973. const a = document.createElement('a');
  974. a.href = url;
  975. a.download = filename;
  976. a.click();
  977. URL.revokeObjectURL(url);
  978. showToast(t('stats.exportDownloaded'));
  979. } catch {
  980. showToast(t('stats.exportFailed'), 'error');
  981. } finally {
  982. setIsExporting(false);
  983. }
  984. };
  985. const handleRecalculateCosts = async () => {
  986. setIsRecalculating(true);
  987. try {
  988. const result = await api.recalculateCosts();
  989. await Promise.all([refetchStats(), refetchArchives()]);
  990. showToast(t('stats.recalculatedCosts', { count: result.updated }));
  991. } catch {
  992. showToast(t('stats.recalculateFailed'), 'error');
  993. } finally {
  994. setIsRecalculating(false);
  995. }
  996. };
  997. const isRefetching = (isStatsFetching || isArchivesFetching) && !isLoading;
  998. const currency = getCurrencySymbol(settings?.currency || 'USD');
  999. const printerMap = new Map(printers?.map((p) => [String(p.id), p.name]) || []);
  1000. const printDates = useMemo(() => archives?.map((a) => a.created_at) || [], [archives]);
  1001. if (isLoading) {
  1002. return (
  1003. <div className="p-4 md:p-8">
  1004. <div className="text-center py-12 text-bambu-gray">{t('stats.loadingStats')}</div>
  1005. </div>
  1006. );
  1007. }
  1008. // Define dashboard widgets
  1009. // Sizes: 1 = quarter (1/4), 2 = half (1/2), 4 = full width
  1010. // Widgets can use render functions to receive the current size for responsive content
  1011. const widgets: DashboardWidget[] = [
  1012. {
  1013. id: 'quick-stats',
  1014. title: t('stats.quickStats'),
  1015. component: <QuickStatsWidget stats={stats} currency={currency} />,
  1016. defaultSize: 2,
  1017. },
  1018. {
  1019. id: 'success-rate',
  1020. title: t('stats.successRate'),
  1021. component: (size) => <SuccessRateWidget stats={stats} printerMap={printerMap} size={size} />,
  1022. defaultSize: 1,
  1023. },
  1024. {
  1025. id: 'time-accuracy',
  1026. title: t('stats.timeAccuracy'),
  1027. component: (size) => <TimeAccuracyWidget stats={stats} printerMap={printerMap} size={size} />,
  1028. defaultSize: 1,
  1029. },
  1030. {
  1031. id: 'failure-analysis',
  1032. title: t('stats.failureAnalysis'),
  1033. component: (size) => <FailureAnalysisWidget size={size} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} createdById={createdByIdParam} />,
  1034. defaultSize: 1,
  1035. },
  1036. {
  1037. id: 'print-activity',
  1038. title: t('stats.printActivity'),
  1039. component: (size) => <PrintActivityWidget printDates={printDates} size={size} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} />,
  1040. defaultSize: 2,
  1041. },
  1042. {
  1043. id: 'records',
  1044. title: t('stats.records'),
  1045. component: <RecordsWidget archives={archives || []} currency={currency} />,
  1046. defaultSize: 1,
  1047. },
  1048. {
  1049. id: 'printer-stats',
  1050. title: t('stats.printerStats'),
  1051. component: <PrinterStatsWidget stats={stats} archives={archives || []} printerMap={printerMap} />,
  1052. defaultSize: 4,
  1053. },
  1054. {
  1055. id: 'filament-trends',
  1056. title: t('stats.filamentTrends'),
  1057. component: <FilamentTrendsWidget archives={archives || []} currency={currency} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} />,
  1058. defaultSize: 4,
  1059. },
  1060. ];
  1061. return (
  1062. <div className="p-4 md:p-8">
  1063. <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
  1064. <div>
  1065. <div className="flex items-center gap-2">
  1066. <h1 className="text-2xl font-bold text-white">{t('stats.title')}</h1>
  1067. {isRefetching && <Loader2 className="w-5 h-5 text-bambu-green animate-spin" />}
  1068. </div>
  1069. <p className="text-bambu-gray">{t('stats.subtitle')}</p>
  1070. </div>
  1071. <div className="flex items-center gap-2 flex-wrap">
  1072. {/* Hidden widgets button - toggles panel in Dashboard */}
  1073. {hiddenCount > 0 && (
  1074. <Button
  1075. variant="secondary"
  1076. onClick={() => {
  1077. // Toggle the hidden panel in Dashboard by triggering a custom event
  1078. window.dispatchEvent(new CustomEvent('toggle-hidden-panel'));
  1079. }}
  1080. >
  1081. <Eye className="w-4 h-4" />
  1082. {t('stats.hiddenCount', { count: hiddenCount })}
  1083. </Button>
  1084. )}
  1085. {/* Reset Layout */}
  1086. <Button
  1087. variant="secondary"
  1088. onClick={() => {
  1089. localStorage.removeItem('bambusy-dashboard-layout-v2');
  1090. setDashboardKey(prev => prev + 1);
  1091. showToast(t('stats.layoutReset'));
  1092. }}
  1093. disabled={!hasPermission('settings:update')}
  1094. title={!hasPermission('settings:update') ? t('stats.noPermissionResetLayout') : undefined}
  1095. >
  1096. <RotateCcw className="w-4 h-4" />
  1097. {t('stats.resetLayout')}
  1098. </Button>
  1099. {/* Recalculate Costs */}
  1100. <Button
  1101. variant="secondary"
  1102. onClick={handleRecalculateCosts}
  1103. disabled={isRecalculating || !hasPermission('archives:update_all')}
  1104. title={!hasPermission('archives:update_all') ? t('stats.noPermissionRecalculate') : t('stats.recalculateCostsHint')}
  1105. >
  1106. {isRecalculating ? (
  1107. <Loader2 className="w-4 h-4 animate-spin" />
  1108. ) : (
  1109. <Calculator className="w-4 h-4" />
  1110. )}
  1111. {t('stats.recalculateCosts')}
  1112. </Button>
  1113. {/* Export dropdown */}
  1114. <div className="relative">
  1115. <Button
  1116. variant="secondary"
  1117. onClick={() => setShowExportMenu(!showExportMenu)}
  1118. disabled={isExporting}
  1119. >
  1120. {isExporting ? (
  1121. <Loader2 className="w-4 h-4 animate-spin" />
  1122. ) : (
  1123. <FileSpreadsheet className="w-4 h-4" />
  1124. )}
  1125. {t('stats.exportStats')}
  1126. </Button>
  1127. {showExportMenu && (
  1128. <div className="absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20">
  1129. <button
  1130. className="w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-t-lg"
  1131. onClick={() => handleExport('csv')}
  1132. >
  1133. <FileText className="w-4 h-4" />
  1134. {t('stats.exportAsCsv')}
  1135. </button>
  1136. <button
  1137. className="w-full px-4 py-2 text-left text-white hover:bg-bambu-dark-tertiary transition-colors flex items-center gap-2 rounded-b-lg"
  1138. onClick={() => handleExport('xlsx')}
  1139. >
  1140. <FileSpreadsheet className="w-4 h-4" />
  1141. {t('stats.exportAsExcel')}
  1142. </button>
  1143. </div>
  1144. )}
  1145. </div>
  1146. {/* User Filter */}
  1147. {canFilterByUser && users && users.length > 0 && (
  1148. <div className="relative">
  1149. <Button
  1150. variant="secondary"
  1151. onClick={() => setShowUserPicker(!showUserPicker)}
  1152. >
  1153. <Users className="w-4 h-4" />
  1154. {selectedUserLabel}
  1155. <ChevronDown className="w-3 h-3" />
  1156. </Button>
  1157. {showUserPicker && (
  1158. <>
  1159. <div
  1160. className="fixed inset-0 z-10"
  1161. onClick={() => setShowUserPicker(false)}
  1162. />
  1163. <div className="absolute right-0 top-full mt-1 w-48 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2 max-h-64 overflow-y-auto">
  1164. <button
  1165. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1166. selectedUserId === null
  1167. ? 'bg-bambu-green text-white'
  1168. : 'text-white hover:bg-bambu-dark-tertiary'
  1169. }`}
  1170. onClick={() => { setSelectedUserId(null); setShowUserPicker(false); }}
  1171. >
  1172. {t('stats.allUsers', 'All Users')}
  1173. </button>
  1174. <button
  1175. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1176. selectedUserId === -1
  1177. ? 'bg-bambu-green text-white'
  1178. : 'text-white hover:bg-bambu-dark-tertiary'
  1179. }`}
  1180. onClick={() => { setSelectedUserId(-1); setShowUserPicker(false); }}
  1181. >
  1182. {t('stats.noUser', 'No User (System)')}
  1183. </button>
  1184. <div className="border-t border-bambu-dark-tertiary my-1" />
  1185. {users.map(u => (
  1186. <button
  1187. key={u.id}
  1188. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1189. selectedUserId === u.id
  1190. ? 'bg-bambu-green text-white'
  1191. : 'text-white hover:bg-bambu-dark-tertiary'
  1192. }`}
  1193. onClick={() => { setSelectedUserId(u.id); setShowUserPicker(false); }}
  1194. >
  1195. {u.username}
  1196. </button>
  1197. ))}
  1198. </div>
  1199. </>
  1200. )}
  1201. </div>
  1202. )}
  1203. {/* Timeframe Selector */}
  1204. <div className="relative">
  1205. <Button
  1206. variant="secondary"
  1207. onClick={() => setShowTimeframePicker(!showTimeframePicker)}
  1208. >
  1209. <Calendar className="w-4 h-4" />
  1210. {t(`stats.timeframe.${timeframe.preset}`)}
  1211. <ChevronDown className="w-3 h-3" />
  1212. </Button>
  1213. {showTimeframePicker && (
  1214. <>
  1215. <div
  1216. className="fixed inset-0 z-10"
  1217. onClick={() => setShowTimeframePicker(false)}
  1218. />
  1219. <div className="absolute right-0 top-full mt-1 w-64 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded-lg shadow-xl z-20 p-2">
  1220. {TIMEFRAME_PRESETS.map((preset) => (
  1221. <button
  1222. key={preset}
  1223. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1224. timeframe.preset === preset
  1225. ? 'bg-bambu-green text-white'
  1226. : 'text-white hover:bg-bambu-dark-tertiary'
  1227. }`}
  1228. onClick={() => {
  1229. setTimeframe({ preset, dateFrom: undefined, dateTo: undefined });
  1230. setShowTimeframePicker(false);
  1231. }}
  1232. >
  1233. {t(`stats.timeframe.${preset}`)}
  1234. </button>
  1235. ))}
  1236. <div className="border-t border-bambu-dark-tertiary my-2" />
  1237. <button
  1238. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1239. timeframe.preset === 'custom'
  1240. ? 'bg-bambu-green text-white'
  1241. : 'text-white hover:bg-bambu-dark-tertiary'
  1242. }`}
  1243. onClick={() => setTimeframe(prev => ({ ...prev, preset: 'custom' }))}
  1244. >
  1245. {t('stats.timeframe.custom')}
  1246. </button>
  1247. {timeframe.preset === 'custom' && (
  1248. <div className="mt-2 px-1 pb-1 space-y-2">
  1249. <div>
  1250. <label className="text-xs text-bambu-gray block mb-1">{t('stats.timeframe.from')}</label>
  1251. <input
  1252. type="date"
  1253. value={timeframe.dateFrom || ''}
  1254. max={timeframe.dateTo || new Date().toISOString().split('T')[0]}
  1255. onChange={(e) => setTimeframe(prev => ({ ...prev, dateFrom: e.target.value || undefined }))}
  1256. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"
  1257. />
  1258. </div>
  1259. <div>
  1260. <label className="text-xs text-bambu-gray block mb-1">{t('stats.timeframe.to')}</label>
  1261. <input
  1262. type="date"
  1263. value={timeframe.dateTo || ''}
  1264. min={timeframe.dateFrom}
  1265. max={new Date().toISOString().split('T')[0]}
  1266. onChange={(e) => setTimeframe(prev => ({ ...prev, dateTo: e.target.value || undefined }))}
  1267. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white [color-scheme:dark]"
  1268. />
  1269. </div>
  1270. <Button
  1271. variant="primary"
  1272. onClick={() => setShowTimeframePicker(false)}
  1273. className="w-full"
  1274. >
  1275. {t('common.apply')}
  1276. </Button>
  1277. </div>
  1278. )}
  1279. </div>
  1280. </>
  1281. )}
  1282. </div>
  1283. </div>
  1284. </div>
  1285. <Dashboard
  1286. key={dashboardKey}
  1287. widgets={widgets}
  1288. storageKey="bambusy-dashboard-layout-v2"
  1289. stackBelow={640}
  1290. hideControls
  1291. />
  1292. </div>
  1293. );
  1294. }