StatsPage.tsx 57 KB

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