StatsPage.tsx 54 KB

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