StatsPage.tsx 52 KB

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