AMSHistoryModal.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. import { useState, useEffect } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { X, Droplets, Thermometer, TrendingUp, TrendingDown, Minus } from 'lucide-react';
  4. import {
  5. LineChart,
  6. Line,
  7. XAxis,
  8. YAxis,
  9. CartesianGrid,
  10. Tooltip,
  11. ResponsiveContainer,
  12. Legend,
  13. ReferenceLine,
  14. } from 'recharts';
  15. import { api, type AMSHistoryResponse } from '../api/client';
  16. import { parseUTCDate, applyTimeFormat, type TimeFormat } from '../utils/date';
  17. import { useTranslation } from 'react-i18next';
  18. import { useTheme } from '../contexts/ThemeContext';
  19. interface AMSHistoryModalProps {
  20. isOpen: boolean;
  21. onClose: () => void;
  22. printerId: number;
  23. printerName: string;
  24. amsId: number;
  25. amsLabel: string;
  26. initialMode?: 'humidity' | 'temperature';
  27. thresholds?: {
  28. humidityGood: number;
  29. humidityFair: number;
  30. tempGood: number;
  31. tempFair: number;
  32. };
  33. }
  34. type TimeRange = '6h' | '24h' | '48h' | '7d';
  35. const TIME_RANGES: { value: TimeRange; label: string; hours: number }[] = [
  36. { value: '6h', label: '6h', hours: 6 },
  37. { value: '24h', label: '24h', hours: 24 },
  38. { value: '48h', label: '48h', hours: 48 },
  39. { value: '7d', label: '7d', hours: 168 },
  40. ];
  41. export function AMSHistoryModal({
  42. isOpen,
  43. onClose,
  44. printerId,
  45. printerName,
  46. amsId,
  47. amsLabel,
  48. initialMode = 'humidity',
  49. thresholds,
  50. }: AMSHistoryModalProps) {
  51. const { t } = useTranslation();
  52. const { mode: themeMode } = useTheme();
  53. const [timeRange, setTimeRange] = useState<TimeRange>('24h');
  54. const [mode, setMode] = useState<'humidity' | 'temperature'>(initialMode);
  55. const isDark = themeMode === 'dark';
  56. const { data: settings } = useQuery({
  57. queryKey: ['settings'],
  58. queryFn: api.getSettings,
  59. });
  60. const timeFormat: TimeFormat = settings?.time_format || 'system';
  61. // Close on Escape key
  62. useEffect(() => {
  63. if (!isOpen) return;
  64. const handleKeyDown = (e: KeyboardEvent) => {
  65. if (e.key === 'Escape') onClose();
  66. };
  67. window.addEventListener('keydown', handleKeyDown);
  68. return () => window.removeEventListener('keydown', handleKeyDown);
  69. }, [isOpen, onClose]);
  70. const hours = TIME_RANGES.find(r => r.value === timeRange)?.hours || 24;
  71. const { data, isLoading, error } = useQuery<AMSHistoryResponse>({
  72. queryKey: ['ams-history', printerId, amsId, hours],
  73. queryFn: () => api.getAMSHistory(printerId, amsId, hours),
  74. enabled: isOpen,
  75. refetchInterval: 60000, // Refresh every minute
  76. });
  77. if (!isOpen) return null;
  78. // Format data for chart
  79. const chartData = data?.data.map(point => {
  80. const date = parseUTCDate(point.recorded_at) || new Date();
  81. const timeOptions: Intl.DateTimeFormatOptions = {
  82. hour: '2-digit',
  83. minute: '2-digit',
  84. ...(hours > 24 ? { day: 'numeric', month: 'short' } : {}),
  85. };
  86. return {
  87. time: date.getTime(),
  88. humidity: point.humidity,
  89. temperature: point.temperature,
  90. timeLabel: date.toLocaleTimeString([], applyTimeFormat(timeOptions, timeFormat)),
  91. };
  92. }) || [];
  93. // Get thresholds
  94. const humidityGood = thresholds?.humidityGood || 40;
  95. const humidityFair = thresholds?.humidityFair || 60;
  96. const tempGood = thresholds?.tempGood || 30;
  97. const tempFair = thresholds?.tempFair || 35;
  98. // Current values (last data point)
  99. const lastPoint = chartData[chartData.length - 1];
  100. const currentHumidity = lastPoint?.humidity;
  101. const currentTemp = lastPoint?.temperature;
  102. // Trend calculation (compare first and last 20% of data)
  103. const getTrend = (values: (number | null)[]) => {
  104. const filtered = values.filter((v): v is number => v != null);
  105. if (filtered.length < 4) return 'stable';
  106. const firstQuarter = filtered.slice(0, Math.floor(filtered.length / 4));
  107. const lastQuarter = filtered.slice(-Math.floor(filtered.length / 4));
  108. const firstAvg = firstQuarter.reduce((a, b) => a + b, 0) / firstQuarter.length;
  109. const lastAvg = lastQuarter.reduce((a, b) => a + b, 0) / lastQuarter.length;
  110. const diff = lastAvg - firstAvg;
  111. if (Math.abs(diff) < 2) return 'stable';
  112. return diff > 0 ? 'up' : 'down';
  113. };
  114. const humidityTrend = getTrend(chartData.map(d => d.humidity));
  115. const tempTrend = getTrend(chartData.map(d => d.temperature));
  116. const TrendIcon = ({ trend }: { trend: string }) => {
  117. if (trend === 'up') return <TrendingUp className="w-4 h-4 text-red-400" />;
  118. if (trend === 'down') return <TrendingDown className="w-4 h-4 text-green-400" />;
  119. return <Minus className="w-4 h-4 text-gray-400 dark:text-bambu-gray" />;
  120. };
  121. // Get status color for current value
  122. const getHumidityColor = (value: number | undefined | null) => {
  123. if (value == null) return '#9ca3af';
  124. if (value <= humidityGood) return '#22a352';
  125. if (value <= humidityFair) return '#d4a017';
  126. return '#c62828';
  127. };
  128. const getTempColor = (value: number | undefined | null) => {
  129. if (value == null) return '#9ca3af';
  130. if (value <= tempGood) return '#22a352';
  131. if (value <= tempFair) return '#d4a017';
  132. return '#c62828';
  133. };
  134. // Theme-aware styles (using isDark since dark: prefix doesn't work in portals)
  135. const modalBg = isDark ? '#2d2d2d' : '#ffffff';
  136. const cardBg = isDark ? '#1d1d1d' : '#f3f4f6';
  137. const borderColor = isDark ? '#3d3d3d' : '#e5e7eb';
  138. const textPrimary = isDark ? '#ffffff' : '#111827';
  139. const textSecondary = isDark ? '#9ca3af' : '#4b5563';
  140. return (
  141. <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={onClose}>
  142. <div
  143. className="rounded-xl w-full max-w-4xl max-h-[90vh] overflow-hidden shadow-xl"
  144. style={{ backgroundColor: modalBg }}
  145. onClick={e => e.stopPropagation()}
  146. >
  147. {/* Header */}
  148. <div
  149. className="flex items-center justify-between px-6 py-4 border-b"
  150. style={{ borderColor }}
  151. >
  152. <div>
  153. <h2 className="text-lg font-semibold" style={{ color: textPrimary }}>
  154. {amsLabel} {t('common.history', 'History')}
  155. </h2>
  156. <p className="text-sm" style={{ color: textSecondary }}>{printerName}</p>
  157. </div>
  158. <button
  159. onClick={onClose}
  160. className="p-2 rounded-lg transition-colors"
  161. style={{ color: textSecondary }}
  162. >
  163. <X className="w-5 h-5" />
  164. </button>
  165. </div>
  166. {/* Content */}
  167. <div className="p-6 space-y-6 overflow-y-auto max-h-[calc(90vh-80px)]">
  168. {/* Time Range & Mode Selector */}
  169. <div className="flex items-center justify-between">
  170. <div className="flex gap-1 rounded-lg p-1" style={{ backgroundColor: cardBg }}>
  171. <button
  172. onClick={() => setMode('humidity')}
  173. className={`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${
  174. mode === 'humidity' ? 'bg-blue-600 text-white' : ''
  175. }`}
  176. style={mode !== 'humidity' ? { color: textSecondary } : undefined}
  177. >
  178. <Droplets className="w-4 h-4" />
  179. {t('common.humidity', 'Humidity')}
  180. </button>
  181. <button
  182. onClick={() => setMode('temperature')}
  183. className={`flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors ${
  184. mode === 'temperature' ? 'bg-orange-600 text-white' : ''
  185. }`}
  186. style={mode !== 'temperature' ? { color: textSecondary } : undefined}
  187. >
  188. <Thermometer className="w-4 h-4" />
  189. {t('common.temperature', 'Temperature')}
  190. </button>
  191. </div>
  192. <div className="flex gap-1 rounded-lg p-1" style={{ backgroundColor: cardBg }}>
  193. {TIME_RANGES.map(range => (
  194. <button
  195. key={range.value}
  196. onClick={() => setTimeRange(range.value)}
  197. className={`px-3 py-1 text-sm rounded-md transition-colors ${
  198. timeRange === range.value ? 'bg-bambu-green text-white' : ''
  199. }`}
  200. style={timeRange !== range.value ? { color: textSecondary } : undefined}
  201. >
  202. {range.label}
  203. </button>
  204. ))}
  205. </div>
  206. </div>
  207. {/* Stats Cards */}
  208. <div className="grid grid-cols-4 gap-4">
  209. {mode === 'humidity' ? (
  210. <>
  211. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  212. <p className="text-xs" style={{ color: textSecondary }}>{t('common.current', 'Current')}</p>
  213. <div className="flex items-center gap-2">
  214. <p className="text-2xl font-bold" style={{ color: getHumidityColor(currentHumidity) }}>
  215. {currentHumidity != null ? `${currentHumidity}%` : '—'}
  216. </p>
  217. <TrendIcon trend={humidityTrend} />
  218. </div>
  219. </div>
  220. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  221. <p className="text-xs" style={{ color: textSecondary }}>{t('common.average', 'Average')}</p>
  222. <p className="text-2xl font-bold" style={{ color: textPrimary }}>
  223. {data?.avg_humidity != null ? `${data.avg_humidity}%` : '—'}
  224. </p>
  225. </div>
  226. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  227. <p className="text-xs" style={{ color: textSecondary }}>{t('common.min', 'Min')}</p>
  228. <p className="text-2xl font-bold text-green-500">
  229. {data?.min_humidity != null ? `${data.min_humidity}%` : '—'}
  230. </p>
  231. </div>
  232. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  233. <p className="text-xs" style={{ color: textSecondary }}>{t('common.max', 'Max')}</p>
  234. <p className="text-2xl font-bold text-red-500">
  235. {data?.max_humidity != null ? `${data.max_humidity}%` : '—'}
  236. </p>
  237. </div>
  238. </>
  239. ) : (
  240. <>
  241. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  242. <p className="text-xs" style={{ color: textSecondary }}>{t('common.current', 'Current')}</p>
  243. <div className="flex items-center gap-2">
  244. <p className="text-2xl font-bold" style={{ color: getTempColor(currentTemp) }}>
  245. {currentTemp != null ? `${currentTemp}°C` : '—'}
  246. </p>
  247. <TrendIcon trend={tempTrend} />
  248. </div>
  249. </div>
  250. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  251. <p className="text-xs" style={{ color: textSecondary }}>{t('common.average', 'Average')}</p>
  252. <p className="text-2xl font-bold" style={{ color: textPrimary }}>
  253. {data?.avg_temperature != null ? `${data.avg_temperature}°C` : '—'}
  254. </p>
  255. </div>
  256. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  257. <p className="text-xs" style={{ color: textSecondary }}>{t('common.min', 'Min')}</p>
  258. <p className="text-2xl font-bold text-blue-500">
  259. {data?.min_temperature != null ? `${data.min_temperature}°C` : '—'}
  260. </p>
  261. </div>
  262. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  263. <p className="text-xs" style={{ color: textSecondary }}>{t('common.max', 'Max')}</p>
  264. <p className="text-2xl font-bold text-red-500">
  265. {data?.max_temperature != null ? `${data.max_temperature}°C` : '—'}
  266. </p>
  267. </div>
  268. </>
  269. )}
  270. </div>
  271. {/* Chart */}
  272. <div className="rounded-lg p-4" style={{ backgroundColor: cardBg }}>
  273. {isLoading ? (
  274. <div className="h-[300px] flex items-center justify-center" style={{ color: textSecondary }}>
  275. {t('common.loading', 'Loading...')}
  276. </div>
  277. ) : error ? (
  278. <div className="h-[300px] flex items-center justify-center text-red-500">
  279. {t('common.error', 'Error loading data')}
  280. </div>
  281. ) : chartData.length === 0 ? (
  282. <div className="h-[300px] flex items-center justify-center" style={{ color: textSecondary }}>
  283. {t('common.noData', 'No data available for this time range')}
  284. </div>
  285. ) : (
  286. <ResponsiveContainer width="100%" height={300}>
  287. <LineChart data={chartData}>
  288. <CartesianGrid strokeDasharray="3 3" stroke={isDark ? '#3d3d3d' : '#e5e7eb'} />
  289. <XAxis
  290. dataKey="time"
  291. type="number"
  292. domain={['dataMin', 'dataMax']}
  293. tickFormatter={(ts) => {
  294. const date = new Date(ts);
  295. if (hours > 24) {
  296. return date.toLocaleDateString([], { day: 'numeric', month: 'short' });
  297. }
  298. return date.toLocaleTimeString([], applyTimeFormat({ hour: '2-digit', minute: '2-digit' }, timeFormat));
  299. }}
  300. stroke={isDark ? '#9ca3af' : '#6b7280'}
  301. tick={{ fontSize: 12 }}
  302. />
  303. <YAxis
  304. stroke={isDark ? '#9ca3af' : '#6b7280'}
  305. tick={{ fontSize: 12 }}
  306. domain={mode === 'humidity' ? [0, 100] : ['auto', 'auto']}
  307. tickFormatter={(value) => mode === 'humidity' ? `${value}%` : `${value}°C`}
  308. />
  309. <Tooltip
  310. contentStyle={{
  311. backgroundColor: isDark ? '#2d2d2d' : '#ffffff',
  312. border: `1px solid ${isDark ? '#3d3d3d' : '#e5e7eb'}`,
  313. borderRadius: '8px',
  314. color: isDark ? '#fff' : '#000',
  315. }}
  316. labelFormatter={(ts) => new Date(ts).toLocaleString(undefined, applyTimeFormat({
  317. year: 'numeric',
  318. month: 'short',
  319. day: 'numeric',
  320. hour: '2-digit',
  321. minute: '2-digit',
  322. }, timeFormat))}
  323. formatter={(value) => [
  324. mode === 'humidity' ? `${value ?? 0}%` : `${value ?? 0}°C`,
  325. mode === 'humidity' ? 'Humidity' : 'Temperature'
  326. ]}
  327. />
  328. <Legend />
  329. {/* Threshold lines */}
  330. {mode === 'humidity' ? (
  331. <>
  332. <ReferenceLine y={humidityGood} stroke="#22a352" strokeDasharray="5 5" label={{ value: 'Good', fill: '#22a352', fontSize: 10 }} />
  333. <ReferenceLine y={humidityFair} stroke="#d4a017" strokeDasharray="5 5" label={{ value: 'Fair', fill: '#d4a017', fontSize: 10 }} />
  334. </>
  335. ) : (
  336. <>
  337. <ReferenceLine y={tempGood} stroke="#22a352" strokeDasharray="5 5" label={{ value: 'Good', fill: '#22a352', fontSize: 10 }} />
  338. <ReferenceLine y={tempFair} stroke="#d4a017" strokeDasharray="5 5" label={{ value: 'Fair', fill: '#d4a017', fontSize: 10 }} />
  339. </>
  340. )}
  341. <Line
  342. type="monotone"
  343. dataKey={mode}
  344. name={mode === 'humidity' ? 'Humidity' : 'Temperature'}
  345. stroke={mode === 'humidity' ? '#3b82f6' : '#f97316'}
  346. strokeWidth={2}
  347. dot={false}
  348. activeDot={{ r: 4 }}
  349. />
  350. </LineChart>
  351. </ResponsiveContainer>
  352. )}
  353. </div>
  354. {/* Info */}
  355. <div className="text-xs text-center" style={{ color: textSecondary }}>
  356. {t('amsHistory.recordingInfo', 'Data is recorded every 5 minutes while the printer is connected')}
  357. </div>
  358. </div>
  359. </div>
  360. </div>
  361. );
  362. }