StatsPage.tsx 58 KB

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