StatsPage.tsx 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450
  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. Ban,
  10. DollarSign,
  11. Target,
  12. Zap,
  13. Wrench,
  14. AlertTriangle,
  15. TrendingDown,
  16. FileSpreadsheet,
  17. FileText,
  18. Loader2,
  19. Eye,
  20. RotateCcw,
  21. Calculator,
  22. Calendar,
  23. ChevronDown,
  24. Users,
  25. BarChart3,
  26. } from 'lucide-react';
  27. import {
  28. BarChart,
  29. Bar,
  30. XAxis,
  31. YAxis,
  32. CartesianGrid,
  33. Tooltip,
  34. ResponsiveContainer,
  35. } from 'recharts';
  36. import { Button } from '../components/Button';
  37. import { useToast } from '../contexts/ToastContext';
  38. import { useAuth } from '../contexts/AuthContext';
  39. import { api, type ArchiveSlim } from '../api/client';
  40. import { PrintCalendar } from '../components/PrintCalendar';
  41. import { FilamentTrends } from '../components/FilamentTrends';
  42. import { SupplierStats } from '../components/SupplierStats';
  43. import { MaterialNumberStats } from '../components/MaterialNumberStats';
  44. import { Dashboard, type DashboardWidget } from '../components/Dashboard';
  45. import { getCurrencySymbol } from '../utils/currency';
  46. import { formatWeight } from '../utils/weight';
  47. import { parseUTCDate, formatDuration } from '../utils/date';
  48. import { MetricToggle, type Metric } from '../components/MetricToggle';
  49. import { useUiSettings } from '../hooks/useUiSettings';
  50. import { computeDateRange, localDate, type TimeframePreset } from '../utils/statsDateRange';
  51. // Timeframe types and helpers
  52. interface TimeframeState {
  53. preset: TimeframePreset;
  54. dateFrom: string | undefined; // YYYY-MM-DD
  55. dateTo: string | undefined; // YYYY-MM-DD
  56. }
  57. const TIMEFRAME_PRESETS: TimeframePreset[] = [
  58. 'today', 'this-week', 'this-month',
  59. 'last-7', 'last-30', 'last-90',
  60. 'this-year', 'all-time',
  61. ];
  62. // Constants
  63. const DAY_LABELS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  64. const HOUR_LABELS = [
  65. '12am', '1am', '2am', '3am', '4am', '5am',
  66. '6am', '7am', '8am', '9am', '10am', '11am',
  67. '12pm', '1pm', '2pm', '3pm', '4pm', '5pm',
  68. '6pm', '7pm', '8pm', '9pm', '10pm', '11pm',
  69. ];
  70. const DURATION_BUCKETS = [
  71. { key: '<30m', max: 1800 },
  72. { key: '30m-1h', max: 3600 },
  73. { key: '1-2h', max: 7200 },
  74. { key: '2-4h', max: 14400 },
  75. { key: '4-8h', max: 28800 },
  76. { key: '8-12h', max: 43200 },
  77. { key: '12-24h', max: 86400 },
  78. { key: '24h+', max: Infinity },
  79. ];
  80. const RECHARTS_TOOLTIP_STYLE = {
  81. backgroundColor: '#2d2d2d',
  82. border: '1px solid #3d3d3d',
  83. borderRadius: '8px',
  84. };
  85. // Widget Components
  86. function QuickStatsWidget({
  87. stats,
  88. currency,
  89. }: {
  90. stats: {
  91. total_prints: number;
  92. successful_prints: number;
  93. failed_prints: number;
  94. total_print_time_hours: number;
  95. total_filament_grams: number;
  96. total_cost: number;
  97. total_energy_kwh: number;
  98. total_energy_cost: number;
  99. total_wear_cost?: number;
  100. energy_data_warming_up?: boolean;
  101. } | undefined;
  102. currency: string;
  103. }) {
  104. const { t } = useTranslation();
  105. const warmingUp = stats?.energy_data_warming_up === true;
  106. const warmingUpTooltip = warmingUp ? t('stats.energyWarmingUpTooltip') : undefined;
  107. const items = [
  108. { icon: Package, color: 'text-bambu-green', label: t('stats.totalPrints'), value: `${stats?.total_prints || 0}` },
  109. { icon: Clock, color: 'text-blue-600 dark:text-blue-400', label: t('stats.printTime'), value: `${stats?.total_print_time_hours?.toFixed(1) ?? '0'}h` },
  110. { icon: Package, color: 'text-orange-600 dark:text-orange-400', label: t('stats.filamentUsed'), value: formatWeight(stats?.total_filament_grams || 0) },
  111. { icon: DollarSign, color: 'text-green-600 dark:text-green-400', label: t('stats.filamentCost'), value: `${currency} ${stats?.total_cost?.toFixed(2) ?? '0.00'}` },
  112. {
  113. icon: Zap,
  114. color: 'text-yellow-600 dark:text-yellow-400',
  115. label: t('stats.energyUsed'),
  116. value: `${stats?.total_energy_kwh?.toFixed(3) ?? '0.000'} kWh`,
  117. warning: warmingUp,
  118. tooltip: warmingUpTooltip,
  119. },
  120. {
  121. icon: DollarSign,
  122. color: 'text-yellow-500',
  123. label: t('stats.energyCost'),
  124. value: `${currency} ${stats?.total_energy_cost?.toFixed(2) ?? '0.00'}`,
  125. warning: warmingUp,
  126. tooltip: warmingUpTooltip,
  127. },
  128. // Only once a printer has a wear cost set (#694), so installs without one
  129. // don't get a tile that always reads zero.
  130. ...((stats?.total_wear_cost ?? 0) > 0
  131. ? [{
  132. icon: Wrench,
  133. color: 'text-slate-500 dark:text-slate-300',
  134. label: t('stats.wearCost'),
  135. value: `${currency} ${stats?.total_wear_cost?.toFixed(2) ?? '0.00'}`,
  136. warning: false,
  137. tooltip: undefined,
  138. }]
  139. : []),
  140. ];
  141. return (
  142. <div className="grid grid-cols-2 sm:grid-cols-3 gap-4">
  143. {items.map((item) => (
  144. <div key={item.label} className="flex items-start gap-3" title={item.tooltip}>
  145. <div className={`p-2 rounded-lg bg-bambu-dark ${item.color}`}>
  146. <item.icon className="w-5 h-5" />
  147. </div>
  148. <div>
  149. <p className="text-xs text-bambu-gray flex items-center gap-1">
  150. {item.label}
  151. {item.warning && <AlertTriangle className="w-3 h-3 text-yellow-600 dark:text-yellow-400" aria-label={item.tooltip} />}
  152. </p>
  153. <p className="text-xl font-bold text-white">{item.value}</p>
  154. </div>
  155. </div>
  156. ))}
  157. </div>
  158. );
  159. }
  160. function SuccessRateWidget({
  161. stats,
  162. printerMap,
  163. size = 1,
  164. }: {
  165. stats: {
  166. total_prints: number;
  167. successful_prints: number;
  168. failed_prints: number;
  169. cancelled_prints?: number;
  170. prints_by_printer: Record<string, number>;
  171. } | undefined;
  172. printerMap: Map<string, string>;
  173. size?: 1 | 2 | 4;
  174. }) {
  175. const { t } = useTranslation();
  176. // Denominator is completed + failed only — a user/system-cancelled print is
  177. // neither a quality success nor a quality failure, so including it would
  178. // silently lower the rate whenever the user stopped a job. The cancelled
  179. // count is still shown in the breakdown below so it doesn't vanish (#1390).
  180. const outcomePrints = (stats?.successful_prints || 0) + (stats?.failed_prints || 0);
  181. const successRate = outcomePrints
  182. ? Math.round(((stats?.successful_prints || 0) / outcomePrints) * 100)
  183. : 0;
  184. // Scale gauge size based on widget size
  185. const gaugeSize = size === 1 ? 112 : size === 2 ? 128 : 144;
  186. const radius = gaugeSize / 2 - 8;
  187. const circumference = radius * 2 * Math.PI;
  188. return (
  189. <div className="flex items-center gap-6">
  190. <div className="relative flex-shrink-0" style={{ width: gaugeSize, height: gaugeSize }}>
  191. <svg className="w-full h-full -rotate-90">
  192. <circle
  193. cx={gaugeSize / 2}
  194. cy={gaugeSize / 2}
  195. r={radius}
  196. fill="none"
  197. stroke="#3d3d3d"
  198. strokeWidth="10"
  199. />
  200. <circle
  201. cx={gaugeSize / 2}
  202. cy={gaugeSize / 2}
  203. r={radius}
  204. fill="none"
  205. stroke="#00ae42"
  206. strokeWidth="10"
  207. strokeLinecap="round"
  208. strokeDasharray={`${(successRate / 100) * circumference} ${circumference}`}
  209. />
  210. </svg>
  211. <div className="absolute inset-0 flex items-center justify-center">
  212. <span className={`font-bold text-white ${size >= 2 ? 'text-2xl' : 'text-xl'}`}>{successRate}%</span>
  213. </div>
  214. </div>
  215. <div className="flex-1 min-w-0">
  216. <div className="space-y-2">
  217. <div className="flex items-center gap-2">
  218. <CheckCircle className="w-4 h-4 text-status-ok flex-shrink-0" />
  219. <span className="text-sm text-bambu-gray">{t('stats.successful')}</span>
  220. <span className="text-sm text-white font-medium">{stats?.successful_prints || 0}</span>
  221. </div>
  222. <div className="flex items-center gap-2">
  223. <XCircle className="w-4 h-4 text-status-error flex-shrink-0" />
  224. <span className="text-sm text-bambu-gray">{t('stats.failed')}</span>
  225. <span className="text-sm text-white font-medium">{stats?.failed_prints || 0}</span>
  226. </div>
  227. <div className="flex items-center gap-2">
  228. <Ban className="w-4 h-4 text-status-warning flex-shrink-0" />
  229. <span className="text-sm text-bambu-gray">{t('stats.cancelled')}</span>
  230. <span className="text-sm text-white font-medium">{stats?.cancelled_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-700 dark:text-blue-400' : 'text-orange-700 dark: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-700 dark: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. {/* Quality dimension (#1898): completed prints the user rejected.
  725. Only rendered once at least one verdict exists — installs without
  726. the confirmation workflow see the widget unchanged. */}
  727. {(analysis.rejected_prints ?? 0) > 0 && (
  728. <div className="text-sm mt-1">
  729. <span className="text-status-warning">
  730. {t('stats.rejectedPrintsCount', { rejected: analysis.rejected_prints })}
  731. </span>
  732. <span className="text-bambu-gray ml-2">
  733. {t('stats.yieldRate', { rate: (analysis.yield_rate ?? 0).toFixed(1) })}
  734. </span>
  735. </div>
  736. )}
  737. {/* Trend indicator */}
  738. {analysis.trend && analysis.trend.length >= 2 && (
  739. <div className={`${size >= 2 ? 'mt-4' : 'mt-2 pt-2 border-t border-bambu-dark-tertiary'}`}>
  740. <div className="flex items-center gap-2 text-sm">
  741. <TrendingDown className={`w-4 h-4 ${
  742. analysis.trend[analysis.trend.length - 1].failure_rate < analysis.trend[analysis.trend.length - 2].failure_rate
  743. ? 'text-status-ok'
  744. : 'text-status-error'
  745. }`} />
  746. <span className="text-bambu-gray">
  747. {t('stats.lastWeekRate', { rate: analysis.trend[analysis.trend.length - 1].failure_rate.toFixed(1) })}
  748. </span>
  749. </div>
  750. </div>
  751. )}
  752. </div>
  753. {/* Failure Reasons */}
  754. {topReasons.length > 0 && (
  755. <div className={`flex-1 ${size >= 2 ? 'border-l border-bambu-dark-tertiary pl-8' : 'pt-2'}`}>
  756. <p className="text-xs text-bambu-gray font-medium mb-2">
  757. {size >= 2 ? t('stats.failureReasons') : t('stats.topFailureReasons')}
  758. </p>
  759. <div className={`${size === 4 ? 'grid grid-cols-2 gap-x-6 gap-y-1' : 'space-y-1'}`}>
  760. {topReasons.map(([reason, count]) => (
  761. <div key={reason} className="flex items-center justify-between text-sm">
  762. <span className={`text-white truncate ${size === 4 ? 'max-w-[200px]' : 'max-w-[160px]'}`}>
  763. {reason
  764. ? t(`editArchive.failureReasons.${reason}`, { defaultValue: reason })
  765. : t('common.unknown')}
  766. </span>
  767. <span className="text-bambu-gray ml-2">{count}</span>
  768. </div>
  769. ))}
  770. </div>
  771. {hasMore && (
  772. <p className="text-xs text-bambu-gray mt-2">
  773. {t('common.more', { count: allReasons.length - maxReasons })}
  774. </p>
  775. )}
  776. </div>
  777. )}
  778. </div>
  779. );
  780. }
  781. function RecordsWidget({ archives, currency }: { archives: ArchiveSlim[]; currency: string }) {
  782. const { t } = useTranslation();
  783. const records = useMemo(() => {
  784. const result: Array<{
  785. icon: typeof Clock;
  786. iconColor: string;
  787. label: string;
  788. value: string;
  789. detail: string | null;
  790. }> = [];
  791. if (archives.length === 0) return result;
  792. // Find the archive with the highest value for a given field
  793. const findMax = (getter: (a: ArchiveSlim) => number | null | undefined): { archive: ArchiveSlim | null; value: number } => {
  794. let best: ArchiveSlim | null = null;
  795. let bestVal = 0;
  796. archives.forEach(a => {
  797. const v = getter(a);
  798. if (v && v > bestVal) { bestVal = v; best = a; }
  799. });
  800. return { archive: best, value: bestVal };
  801. };
  802. // Only completed prints qualify as the "longest" record. Pre-#1390 this
  803. // happened implicitly because the slim endpoint returned null
  804. // actual_time_seconds for non-completed rows; that gate moved up to the
  805. // backend so failed/cancelled prints now carry their elapsed duration
  806. // (Quick Stats Print Time needs that), but a partially-completed 20-hour
  807. // run shouldn't outrank a successful 18-hour print here.
  808. const longest = findMax(a => (a.status === 'completed' ? a.actual_time_seconds : null));
  809. if (longest.archive) {
  810. result.push({
  811. icon: Clock, iconColor: 'text-blue-600 dark:text-blue-400', label: t('stats.longestPrint'),
  812. value: formatDuration(longest.value),
  813. detail: longest.archive.print_name || null,
  814. });
  815. }
  816. const heaviest = findMax(a => a.filament_used_grams);
  817. if (heaviest.archive) {
  818. result.push({
  819. icon: Package, iconColor: 'text-orange-600 dark:text-orange-400', label: t('stats.heaviestPrint'),
  820. value: formatWeight(heaviest.value),
  821. detail: heaviest.archive.print_name || null,
  822. });
  823. }
  824. // Filament + measured energy (#1432) + printer wear (#694); a cost that
  825. // wasn't recorded is null and simply doesn't add.
  826. const costliest = findMax(a => (a.cost ?? 0) + (a.energy_cost ?? 0) + (a.wear_cost ?? 0));
  827. if (costliest.archive) {
  828. result.push({
  829. icon: DollarSign, iconColor: 'text-green-600 dark:text-green-400', label: t('stats.mostExpensivePrint'),
  830. value: `${currency}${costliest.value.toFixed(2)}`,
  831. detail: costliest.archive.print_name || null,
  832. });
  833. }
  834. // Busiest day
  835. const dayCounts = new Map<string, number>();
  836. archives.forEach(a => {
  837. const date = parseUTCDate(a.created_at) || new Date(a.created_at);
  838. const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
  839. dayCounts.set(key, (dayCounts.get(key) || 0) + 1);
  840. });
  841. let busiestDay = '';
  842. let busiestCount = 0;
  843. dayCounts.forEach((count, day) => {
  844. if (count > busiestCount) {
  845. busiestCount = count;
  846. busiestDay = day;
  847. }
  848. });
  849. if (busiestCount > 1) {
  850. result.push({
  851. icon: Calendar,
  852. iconColor: 'text-purple-600 dark:text-purple-400',
  853. label: t('stats.busiestDay'),
  854. value: `${busiestCount} ${t('common.prints')}`,
  855. detail: (() => { const [y, m, d] = busiestDay.split('-').map(Number); return new Date(y, m - 1, d).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }); })(),
  856. });
  857. }
  858. // Success streak
  859. const sorted = [...archives]
  860. .filter(a => a.status === 'completed' || a.status === 'failed')
  861. .sort((a, b) => new Date(b.completed_at || b.created_at).getTime() - new Date(a.completed_at || a.created_at).getTime());
  862. let streak = 0;
  863. for (const a of sorted) {
  864. if (a.status === 'completed') streak++;
  865. else break;
  866. }
  867. if (streak > 0) {
  868. result.push({
  869. icon: Zap,
  870. iconColor: 'text-yellow-600 dark:text-yellow-400',
  871. label: t('stats.successStreak'),
  872. value: `${streak}`,
  873. detail: streak === 1 ? t('stats.streakPrint') : t('stats.streakPrints', { count: streak }),
  874. });
  875. }
  876. return result;
  877. }, [archives, currency, t]);
  878. if (records.length === 0) {
  879. return <p className="text-bambu-gray text-center py-4">{t('stats.noArchiveData')}</p>;
  880. }
  881. return (
  882. <div className="space-y-3">
  883. {records.map((record, i) => (
  884. <div key={i} className="flex items-center gap-3">
  885. <div className={`p-1.5 rounded-lg bg-bambu-dark ${record.iconColor}`}>
  886. <record.icon className="w-4 h-4" />
  887. </div>
  888. <div className="flex-1 min-w-0">
  889. <p className="text-xs text-bambu-gray">{record.label}</p>
  890. <div className="flex items-baseline gap-2">
  891. <span className="text-sm font-bold text-white">{record.value}</span>
  892. {record.detail && (
  893. <span className="text-xs text-bambu-gray truncate">{record.detail}</span>
  894. )}
  895. </div>
  896. </div>
  897. </div>
  898. ))}
  899. </div>
  900. );
  901. }
  902. export function StatsPage() {
  903. const { t } = useTranslation();
  904. const { showToast } = useToast();
  905. const { hasPermission, authEnabled } = useAuth();
  906. const [isExporting, setIsExporting] = useState(false);
  907. const [showExportMenu, setShowExportMenu] = useState(false);
  908. const [dashboardKey, setDashboardKey] = useState(0);
  909. const [hiddenCount, setHiddenCount] = useState(0);
  910. const [isRecalculating, setIsRecalculating] = useState(false);
  911. const [selectedUserId, setSelectedUserId] = useState<number | null>(null);
  912. const [showUserPicker, setShowUserPicker] = useState(false);
  913. const canFilterByUser = authEnabled && hasPermission('stats:filter_by_user');
  914. const [timeframe, setTimeframe] = useState<TimeframeState>(() => {
  915. try {
  916. const saved = localStorage.getItem('bambusy-stats-timeframe');
  917. if (saved) {
  918. const parsed = JSON.parse(saved);
  919. if (parsed.preset) return parsed;
  920. }
  921. } catch { /* ignore */ }
  922. return { preset: 'all-time', dateFrom: undefined, dateTo: undefined };
  923. });
  924. const [showTimeframePicker, setShowTimeframePicker] = useState(false);
  925. // Persist timeframe selection
  926. useEffect(() => {
  927. localStorage.setItem('bambusy-stats-timeframe', JSON.stringify(timeframe));
  928. }, [timeframe]);
  929. const effectiveDateRange = useMemo(() => {
  930. if (timeframe.preset === 'custom') {
  931. return { dateFrom: timeframe.dateFrom, dateTo: timeframe.dateTo };
  932. }
  933. return computeDateRange(timeframe.preset);
  934. }, [timeframe]);
  935. // Read hidden count from localStorage
  936. useEffect(() => {
  937. const updateHiddenCount = () => {
  938. try {
  939. const saved = localStorage.getItem('bambusy-dashboard-layout-v2');
  940. if (saved) {
  941. const layout = JSON.parse(saved);
  942. setHiddenCount(layout.hidden?.length || 0);
  943. }
  944. } catch {
  945. setHiddenCount(0);
  946. }
  947. };
  948. updateHiddenCount();
  949. // Listen for storage changes
  950. window.addEventListener('storage', updateHiddenCount);
  951. // Also poll for changes (since storage event doesn't fire for same-tab changes)
  952. const interval = setInterval(updateHiddenCount, 2000);
  953. return () => {
  954. window.removeEventListener('storage', updateHiddenCount);
  955. clearInterval(interval);
  956. };
  957. }, [dashboardKey]);
  958. // Only pass createdById when a user is actually selected (not "All Users")
  959. const createdByIdParam = selectedUserId !== null ? selectedUserId : undefined;
  960. const { data: stats, isLoading, isFetching: isStatsFetching, refetch: refetchStats } = useQuery({
  961. queryKey: ['archiveStats', effectiveDateRange.dateFrom, effectiveDateRange.dateTo, createdByIdParam ?? 'all'],
  962. queryFn: () => api.getArchiveStats({
  963. dateFrom: effectiveDateRange.dateFrom,
  964. dateTo: effectiveDateRange.dateTo,
  965. createdById: createdByIdParam,
  966. }),
  967. });
  968. const { data: printers } = useQuery({
  969. queryKey: ['printers'],
  970. queryFn: api.getPrinters,
  971. });
  972. const { data: archives, isFetching: isArchivesFetching, refetch: refetchArchives } = useQuery({
  973. queryKey: ['archivesSlim', effectiveDateRange.dateFrom, effectiveDateRange.dateTo, createdByIdParam ?? 'all'],
  974. queryFn: () => api.getArchivesSlim(effectiveDateRange.dateFrom, effectiveDateRange.dateTo, createdByIdParam),
  975. });
  976. const { data: settings } = useUiSettings();
  977. // The supplier widget aggregates the internal spool table, which is empty
  978. // in Spoolman mode — there the assignments live in the Spoolman twin table.
  979. // Rather than show a permanently empty card next to an inventory that does
  980. // display supplier chips, drop it (#2988).
  981. // The material-number widget shares this gate for the same reason: in
  982. // Spoolman mode the number is Spoolman's filament-level article_number and
  983. // lives in Spoolman itself, not in the internal spool table (#2870).
  984. const { data: spoolmanSettings, isPending: spoolmanSettingsPending } = useQuery({
  985. queryKey: ['spoolman-settings'],
  986. queryFn: api.getSpoolmanSettings,
  987. staleTime: 5 * 60 * 1000,
  988. });
  989. // The rest of the dashboard renders off the archive response, so the card
  990. // would otherwise mount — and hit the aggregate endpoint — while the mode
  991. // is still unknown. "Not loaded yet" is not "internal mode".
  992. const spoolmanModeReady = !spoolmanSettingsPending;
  993. const spoolmanMode =
  994. spoolmanSettings?.spoolman_enabled === 'true' && !!spoolmanSettings?.spoolman_url;
  995. // Slim listing (#1894): the filter only needs id + username, and gating it
  996. // on the admin-level users:read left the dropdown empty for exactly the
  997. // operators who were granted stats:filter_by_user.
  998. const { data: users } = useQuery({
  999. queryKey: ['users', 'slim'],
  1000. queryFn: api.getUsersSlim,
  1001. enabled: canFilterByUser,
  1002. });
  1003. const selectedUserLabel = useMemo(() => {
  1004. if (selectedUserId === null) return t('stats.allUsers', 'All Users');
  1005. if (selectedUserId === -1) return t('stats.noUser', 'No User (System)');
  1006. return users?.find(u => u.id === selectedUserId)?.username ?? '?';
  1007. }, [selectedUserId, users, t]);
  1008. const handleExport = async (format: 'csv' | 'xlsx') => {
  1009. setShowExportMenu(false);
  1010. setIsExporting(true);
  1011. try {
  1012. const { blob, filename } = await api.exportStats({ format, days: 90, createdById: createdByIdParam });
  1013. const url = URL.createObjectURL(blob);
  1014. const a = document.createElement('a');
  1015. a.href = url;
  1016. a.download = filename;
  1017. a.click();
  1018. URL.revokeObjectURL(url);
  1019. showToast(t('stats.exportDownloaded'));
  1020. } catch {
  1021. showToast(t('stats.exportFailed'), 'error');
  1022. } finally {
  1023. setIsExporting(false);
  1024. }
  1025. };
  1026. const handleRecalculateCosts = async () => {
  1027. setIsRecalculating(true);
  1028. try {
  1029. const result = await api.recalculateCosts();
  1030. await Promise.all([refetchStats(), refetchArchives()]);
  1031. showToast(t('stats.recalculatedCosts', { count: result.updated }));
  1032. } catch {
  1033. showToast(t('stats.recalculateFailed'), 'error');
  1034. } finally {
  1035. setIsRecalculating(false);
  1036. }
  1037. };
  1038. const isRefetching = (isStatsFetching || isArchivesFetching) && !isLoading;
  1039. const currency = getCurrencySymbol(settings?.currency || 'USD');
  1040. // History outlives the printer that made it: a deleted printer is gone from
  1041. // `printers`, so its rows fell back to "Printer 1" (#2873). The stats response
  1042. // carries the name each id was last recorded under; a printer that still
  1043. // exists overrides it, so a rename shows up straight away.
  1044. const printerMap = useMemo(
  1045. () =>
  1046. new Map<string, string>([
  1047. ...Object.entries(stats?.printer_names || {}),
  1048. ...(printers?.map((p) => [String(p.id), p.name] as [string, string]) || []),
  1049. ]),
  1050. [stats?.printer_names, printers],
  1051. );
  1052. const printDates = useMemo(() => archives?.map((a) => a.created_at) || [], [archives]);
  1053. if (isLoading) {
  1054. return (
  1055. <div className="p-4 md:p-8">
  1056. <div className="text-center py-12 text-bambu-gray">{t('stats.loadingStats')}</div>
  1057. </div>
  1058. );
  1059. }
  1060. // Define dashboard widgets
  1061. // Sizes: 1 = quarter (1/4), 2 = half (1/2), 4 = full width
  1062. // Widgets can use render functions to receive the current size for responsive content
  1063. const widgets: DashboardWidget[] = [
  1064. {
  1065. id: 'quick-stats',
  1066. title: t('stats.quickStats'),
  1067. component: <QuickStatsWidget stats={stats} currency={currency} />,
  1068. defaultSize: 2,
  1069. },
  1070. {
  1071. id: 'success-rate',
  1072. title: t('stats.successRate'),
  1073. component: (size) => <SuccessRateWidget stats={stats} printerMap={printerMap} size={size} />,
  1074. defaultSize: 1,
  1075. },
  1076. {
  1077. id: 'time-accuracy',
  1078. title: t('stats.timeAccuracy'),
  1079. component: (size) => <TimeAccuracyWidget stats={stats} printerMap={printerMap} size={size} />,
  1080. defaultSize: 1,
  1081. },
  1082. {
  1083. id: 'failure-analysis',
  1084. title: t('stats.failureAnalysis'),
  1085. component: (size) => <FailureAnalysisWidget size={size} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} createdById={createdByIdParam} />,
  1086. defaultSize: 1,
  1087. },
  1088. {
  1089. id: 'print-activity',
  1090. title: t('stats.printActivity'),
  1091. component: (size) => <PrintActivityWidget printDates={printDates} size={size} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} />,
  1092. defaultSize: 2,
  1093. },
  1094. {
  1095. id: 'records',
  1096. title: t('stats.records'),
  1097. component: <RecordsWidget archives={archives || []} currency={currency} />,
  1098. defaultSize: 1,
  1099. },
  1100. {
  1101. id: 'printer-stats',
  1102. title: t('stats.printerStats'),
  1103. component: <PrinterStatsWidget stats={stats} archives={archives || []} printerMap={printerMap} />,
  1104. defaultSize: 4,
  1105. },
  1106. {
  1107. id: 'filament-trends',
  1108. title: t('stats.filamentTrends'),
  1109. component: <FilamentTrendsWidget archives={archives || []} currency={currency} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} />,
  1110. defaultSize: 4,
  1111. },
  1112. ...(!spoolmanModeReady || spoolmanMode ? [] : ([{
  1113. id: 'suppliers',
  1114. title: t('stats.suppliers.title'),
  1115. component: <SupplierStats currency={currency} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} />,
  1116. defaultSize: 2,
  1117. }] as DashboardWidget[])),
  1118. ...(!spoolmanModeReady || spoolmanMode ? [] : ([{
  1119. id: 'material-numbers',
  1120. title: t('stats.materialNumbers.title'),
  1121. component: <MaterialNumberStats currency={currency} dateFrom={effectiveDateRange.dateFrom} dateTo={effectiveDateRange.dateTo} />,
  1122. defaultSize: 2,
  1123. }] as DashboardWidget[])),
  1124. ];
  1125. return (
  1126. <div className="p-4 md:p-8">
  1127. <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
  1128. <div>
  1129. <div className="flex items-center gap-2">
  1130. <h1 className="text-2xl font-bold text-white flex items-center gap-3">
  1131. <BarChart3 className="w-7 h-7 text-bambu-green" />
  1132. {t('stats.title')}
  1133. </h1>
  1134. {isRefetching && <Loader2 className="w-5 h-5 text-bambu-green animate-spin" />}
  1135. </div>
  1136. <p className="text-bambu-gray mt-1">{t('stats.subtitle')}</p>
  1137. </div>
  1138. <div className="flex items-center gap-2 flex-wrap">
  1139. {/* Hidden widgets button - toggles panel in Dashboard */}
  1140. {hiddenCount > 0 && (
  1141. <Button
  1142. variant="secondary"
  1143. onClick={() => {
  1144. // Toggle the hidden panel in Dashboard by triggering a custom event
  1145. window.dispatchEvent(new CustomEvent('toggle-hidden-panel'));
  1146. }}
  1147. >
  1148. <Eye className="w-4 h-4" />
  1149. {t('stats.hiddenCount', { count: hiddenCount })}
  1150. </Button>
  1151. )}
  1152. {/* Reset Layout */}
  1153. <Button
  1154. variant="secondary"
  1155. onClick={() => {
  1156. localStorage.removeItem('bambusy-dashboard-layout-v2');
  1157. setDashboardKey(prev => prev + 1);
  1158. showToast(t('stats.layoutReset'));
  1159. }}
  1160. disabled={!hasPermission('settings:update')}
  1161. title={!hasPermission('settings:update') ? t('stats.noPermissionResetLayout') : undefined}
  1162. >
  1163. <RotateCcw className="w-4 h-4" />
  1164. {t('stats.resetLayout')}
  1165. </Button>
  1166. {/* Recalculate Costs */}
  1167. <Button
  1168. variant="secondary"
  1169. onClick={handleRecalculateCosts}
  1170. disabled={isRecalculating || !hasPermission('archives:update_all')}
  1171. title={!hasPermission('archives:update_all') ? t('stats.noPermissionRecalculate') : t('stats.recalculateCostsHint')}
  1172. >
  1173. {isRecalculating ? (
  1174. <Loader2 className="w-4 h-4 animate-spin" />
  1175. ) : (
  1176. <Calculator className="w-4 h-4" />
  1177. )}
  1178. {t('stats.recalculateCosts')}
  1179. </Button>
  1180. {/* Export dropdown */}
  1181. <div className="relative">
  1182. <Button
  1183. variant="secondary"
  1184. onClick={() => setShowExportMenu(!showExportMenu)}
  1185. disabled={isExporting}
  1186. >
  1187. {isExporting ? (
  1188. <Loader2 className="w-4 h-4 animate-spin" />
  1189. ) : (
  1190. <FileSpreadsheet className="w-4 h-4" />
  1191. )}
  1192. {t('stats.exportStats')}
  1193. </Button>
  1194. {showExportMenu && (
  1195. <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">
  1196. <button
  1197. 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"
  1198. onClick={() => handleExport('csv')}
  1199. >
  1200. <FileText className="w-4 h-4" />
  1201. {t('stats.exportAsCsv')}
  1202. </button>
  1203. <button
  1204. 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"
  1205. onClick={() => handleExport('xlsx')}
  1206. >
  1207. <FileSpreadsheet className="w-4 h-4" />
  1208. {t('stats.exportAsExcel')}
  1209. </button>
  1210. </div>
  1211. )}
  1212. </div>
  1213. {/* User Filter */}
  1214. {canFilterByUser && users && users.length > 0 && (
  1215. <div className="relative">
  1216. <Button
  1217. variant="secondary"
  1218. onClick={() => setShowUserPicker(!showUserPicker)}
  1219. >
  1220. <Users className="w-4 h-4" />
  1221. {selectedUserLabel}
  1222. <ChevronDown className="w-3 h-3" />
  1223. </Button>
  1224. {showUserPicker && (
  1225. <>
  1226. <div
  1227. className="fixed inset-0 z-10"
  1228. onClick={() => setShowUserPicker(false)}
  1229. />
  1230. <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">
  1231. <button
  1232. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1233. selectedUserId === null
  1234. ? 'bg-bambu-green text-white'
  1235. : 'text-white hover:bg-bambu-dark-tertiary'
  1236. }`}
  1237. onClick={() => { setSelectedUserId(null); setShowUserPicker(false); }}
  1238. >
  1239. {t('stats.allUsers', 'All Users')}
  1240. </button>
  1241. <button
  1242. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1243. selectedUserId === -1
  1244. ? 'bg-bambu-green text-white'
  1245. : 'text-white hover:bg-bambu-dark-tertiary'
  1246. }`}
  1247. onClick={() => { setSelectedUserId(-1); setShowUserPicker(false); }}
  1248. >
  1249. {t('stats.noUser', 'No User (System)')}
  1250. </button>
  1251. <div className="border-t border-bambu-dark-tertiary my-1" />
  1252. {users.map(u => (
  1253. <button
  1254. key={u.id}
  1255. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1256. selectedUserId === u.id
  1257. ? 'bg-bambu-green text-white'
  1258. : 'text-white hover:bg-bambu-dark-tertiary'
  1259. }`}
  1260. onClick={() => { setSelectedUserId(u.id); setShowUserPicker(false); }}
  1261. >
  1262. {u.username}
  1263. </button>
  1264. ))}
  1265. </div>
  1266. </>
  1267. )}
  1268. </div>
  1269. )}
  1270. {/* Timeframe Selector */}
  1271. <div className="relative">
  1272. <Button
  1273. variant="secondary"
  1274. onClick={() => setShowTimeframePicker(!showTimeframePicker)}
  1275. >
  1276. <Calendar className="w-4 h-4" />
  1277. {t(`stats.timeframe.${timeframe.preset}`)}
  1278. <ChevronDown className="w-3 h-3" />
  1279. </Button>
  1280. {showTimeframePicker && (
  1281. <>
  1282. <div
  1283. className="fixed inset-0 z-10"
  1284. onClick={() => setShowTimeframePicker(false)}
  1285. />
  1286. <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">
  1287. {TIMEFRAME_PRESETS.map((preset) => (
  1288. <button
  1289. key={preset}
  1290. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1291. timeframe.preset === preset
  1292. ? 'bg-bambu-green text-white'
  1293. : 'text-white hover:bg-bambu-dark-tertiary'
  1294. }`}
  1295. onClick={() => {
  1296. setTimeframe({ preset, dateFrom: undefined, dateTo: undefined });
  1297. setShowTimeframePicker(false);
  1298. }}
  1299. >
  1300. {t(`stats.timeframe.${preset}`)}
  1301. </button>
  1302. ))}
  1303. <div className="border-t border-bambu-dark-tertiary my-2" />
  1304. <button
  1305. className={`w-full px-3 py-2 text-left text-sm rounded-md transition-colors ${
  1306. timeframe.preset === 'custom'
  1307. ? 'bg-bambu-green text-white'
  1308. : 'text-white hover:bg-bambu-dark-tertiary'
  1309. }`}
  1310. onClick={() => setTimeframe(prev => ({ ...prev, preset: 'custom' }))}
  1311. >
  1312. {t('stats.timeframe.custom')}
  1313. </button>
  1314. {timeframe.preset === 'custom' && (
  1315. <div className="mt-2 px-1 pb-1 space-y-2">
  1316. <div>
  1317. <label className="text-xs text-bambu-gray block mb-1">{t('stats.timeframe.from')}</label>
  1318. <input
  1319. type="date"
  1320. value={timeframe.dateFrom || ''}
  1321. max={timeframe.dateTo || localDate(new Date())}
  1322. onChange={(e) => setTimeframe(prev => ({ ...prev, dateFrom: e.target.value || undefined }))}
  1323. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white"
  1324. />
  1325. </div>
  1326. <div>
  1327. <label className="text-xs text-bambu-gray block mb-1">{t('stats.timeframe.to')}</label>
  1328. <input
  1329. type="date"
  1330. value={timeframe.dateTo || ''}
  1331. min={timeframe.dateFrom}
  1332. max={localDate(new Date())}
  1333. onChange={(e) => setTimeframe(prev => ({ ...prev, dateTo: e.target.value || undefined }))}
  1334. className="w-full bg-bambu-dark border border-bambu-dark-tertiary rounded-md px-3 py-1.5 text-sm text-white"
  1335. />
  1336. </div>
  1337. <Button
  1338. variant="primary"
  1339. onClick={() => setShowTimeframePicker(false)}
  1340. className="w-full"
  1341. >
  1342. {t('common.apply')}
  1343. </Button>
  1344. </div>
  1345. )}
  1346. </div>
  1347. </>
  1348. )}
  1349. </div>
  1350. </div>
  1351. </div>
  1352. <Dashboard
  1353. key={dashboardKey}
  1354. widgets={widgets}
  1355. storageKey="bambusy-dashboard-layout-v2"
  1356. stackBelow={640}
  1357. hideControls
  1358. />
  1359. </div>
  1360. );
  1361. }