MaintenancePage.tsx 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. import { useState, useMemo } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  4. import {
  5. Wrench,
  6. Loader2,
  7. Check,
  8. AlertTriangle,
  9. Clock,
  10. Plus,
  11. Trash2,
  12. ChevronDown,
  13. ChevronUp,
  14. Droplet,
  15. Flame,
  16. Ruler,
  17. Sparkles,
  18. Square,
  19. Cable,
  20. Edit3,
  21. RotateCcw,
  22. Calendar,
  23. Timer,
  24. Cog,
  25. Fan,
  26. Zap,
  27. Wind,
  28. Thermometer,
  29. Layers,
  30. Box,
  31. Target,
  32. RefreshCw,
  33. Settings,
  34. Filter,
  35. CircleDot,
  36. Printer,
  37. ExternalLink,
  38. } from 'lucide-react';
  39. import { api } from '../api/client';
  40. import type { MaintenanceStatus, PrinterMaintenanceOverview, MaintenanceType, Permission } from '../api/client';
  41. import { Card, CardContent } from '../components/Card';
  42. import { Button } from '../components/Button';
  43. import { Toggle } from '../components/Toggle';
  44. import { ConfirmModal } from '../components/ConfirmModal';
  45. import { useToast } from '../contexts/ToastContext';
  46. import { useAuth } from '../contexts/AuthContext';
  47. // Icon mapping for maintenance types
  48. const iconMap: Record<string, React.ComponentType<{ className?: string }>> = {
  49. Droplet,
  50. Flame,
  51. Ruler,
  52. Sparkles,
  53. Square,
  54. Cable,
  55. Wrench,
  56. Calendar,
  57. Timer,
  58. Cog,
  59. Fan,
  60. Zap,
  61. Wind,
  62. Thermometer,
  63. Layers,
  64. Box,
  65. Target,
  66. RefreshCw,
  67. Settings,
  68. Filter,
  69. CircleDot,
  70. };
  71. function getIcon(iconName: string | null) {
  72. if (!iconName) return Wrench;
  73. return iconMap[iconName] || Wrench;
  74. }
  75. type TFunction = (key: string, options?: Record<string, unknown>) => string;
  76. function formatDuration(value: number, type: 'hours' | 'days', t?: TFunction): string {
  77. if (type === 'days') {
  78. if (value < 1) return t ? t('common.today') : 'Today';
  79. if (value === 1) return t ? t('maintenance.day') : '1 day';
  80. if (value < 7) {
  81. const days = Math.round(value);
  82. return t ? t('maintenance.days', { count: days }) : `${days} days`;
  83. }
  84. // Show weeks for anything under 6 months for better precision
  85. if (value < 180) {
  86. const weeks = Math.round(value / 7);
  87. if (weeks === 1) return t ? t('maintenance.week') : '1 week';
  88. return t ? t('maintenance.weeks', { count: weeks }) : `${weeks} weeks`;
  89. }
  90. // 6+ months show as months
  91. const months = Math.round(value / 30);
  92. if (months === 1) return t ? t('maintenance.month') : '1 month';
  93. return t ? t('maintenance.months', { count: months }) : `${months} months`;
  94. } else {
  95. // Print hours - convert to readable units
  96. if (value < 1) return `${Math.round(value * 60)}m`;
  97. if (value < 24) return `${value < 10 ? value.toFixed(1) : Math.round(value)}h`;
  98. // 24+ hours: show as days of print time
  99. const days = value / 24;
  100. if (days < 7) return `${days < 2 ? days.toFixed(1) : Math.round(days)}d`;
  101. // 7+ days: show as weeks of print time
  102. const weeks = days / 7;
  103. if (weeks < 12) return `${weeks < 2 ? weeks.toFixed(1) : Math.round(weeks)}w`;
  104. // 12+ weeks: show as months of print time
  105. return `${Math.round(weeks / 4)}mo`;
  106. }
  107. }
  108. function formatIntervalLabel(value: number, type: 'hours' | 'days', t?: TFunction): string {
  109. if (type === 'days') {
  110. if (value === 1) return t ? t('maintenance.day') : '1 day';
  111. if (value === 7) return t ? t('maintenance.week') : '1 week';
  112. if (value === 14) return t ? t('maintenance.weeks', { count: 2 }) : '2 weeks';
  113. if (value === 30) return t ? t('maintenance.month') : '1 month';
  114. if (value === 60) return t ? t('maintenance.months', { count: 2 }) : '2 months';
  115. if (value === 90) return t ? t('maintenance.months', { count: 3 }) : '3 months';
  116. if (value === 180) return t ? t('maintenance.months', { count: 6 }) : '6 months';
  117. if (value === 365) return t ? t('maintenance.year') : '1 year';
  118. return t ? t('maintenance.days', { count: value }) : `${value} days`;
  119. }
  120. return `${value}h`;
  121. }
  122. // Get Bambu Lab wiki URL for a maintenance task based on printer model
  123. function getMaintenanceWikiUrl(typeName: string, printerModel: string | null): string | null {
  124. const model = (printerModel || '').toUpperCase().replace(/[- ]/g, '');
  125. // Helper to match model families
  126. const isX1 = model.includes('X1');
  127. const isP1 = model.includes('P1');
  128. const isA1Mini = model.includes('A1MINI');
  129. const isA1 = model.includes('A1') && !isA1Mini;
  130. const isH2D = model.includes('H2D');
  131. const isH2C = model.includes('H2C');
  132. const isH2S = model.includes('H2S');
  133. const isH2 = isH2D || isH2C || isH2S;
  134. const isP2S = model.includes('P2S');
  135. switch (typeName) {
  136. case 'Lubricate Carbon Rods':
  137. // X1, P1, P2S series have carbon rods
  138. if (isX1) return 'https://wiki.bambulab.com/en/x1/maintenance/basic-maintenance';
  139. if (isP1) return 'https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance';
  140. if (isP2S) return 'https://wiki.bambulab.com/en/p2s/maintenance/belt-tension';
  141. return null;
  142. case 'Lubricate Linear Rails':
  143. // A1 and H2 series have linear rails
  144. if (isA1Mini) return 'https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis';
  145. if (isA1) return 'https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis';
  146. if (isH2) return 'https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication';
  147. return null;
  148. case 'Clean Nozzle/Hotend':
  149. if (isX1 || isP1) return 'https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog';
  150. if (isA1Mini || isA1) return 'https://wiki.bambulab.com/en/a1-mini/troubleshooting/nozzle-clog';
  151. if (isH2) return 'https://wiki.bambulab.com/en/h2/maintenance/nozzl-cold-pull-maintenance-and-cleaning';
  152. if (isP2S) return 'https://wiki.bambulab.com/en/p2s/maintenance/cold-pull-maintenance-hotend';
  153. return 'https://wiki.bambulab.com/en/x1/troubleshooting/nozzle-clog';
  154. case 'Check Belt Tension':
  155. if (isX1) return 'https://wiki.bambulab.com/en/x1/maintenance/belt-tension';
  156. if (isP1) return 'https://wiki.bambulab.com/en/p1/maintenance/p1p-maintenance';
  157. if (isA1Mini) return 'https://wiki.bambulab.com/en/a1-mini/maintenance/belt_tension';
  158. if (isA1) return 'https://wiki.bambulab.com/en/a1/maintenance/belt_tension';
  159. if (isH2D) return 'https://wiki.bambulab.com/en/h2/maintenance/belt-tension';
  160. if (isH2C) return 'https://wiki.bambulab.com/en/h2c/maintenance/belt-tension';
  161. if (isH2S) return 'https://wiki.bambulab.com/en/h2s/maintenance/belt-tension';
  162. if (isP2S) return 'https://wiki.bambulab.com/en/p2s/maintenance/belt-tension';
  163. return 'https://wiki.bambulab.com/en/x1/maintenance/belt-tension';
  164. case 'Clean Carbon Rods':
  165. // X1, P1, P2S series have carbon rods
  166. if (isX1 || isP1 || isP2S) return 'https://wiki.bambulab.com/en/general/carbon-rods-clearance';
  167. return null;
  168. case 'Clean Linear Rails':
  169. // A1 and H2 series have linear rails
  170. if (isA1Mini) return 'https://wiki.bambulab.com/en/a1-mini/maintenance/lubricate-y-axis';
  171. if (isA1) return 'https://wiki.bambulab.com/en/a1/maintenance/lubricate-y-axis';
  172. if (isH2) return 'https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication';
  173. return null;
  174. case 'Clean Build Plate':
  175. // Same for all printers
  176. return 'https://wiki.bambulab.com/en/filament-acc/acc/pei-plate-clean-guide';
  177. case 'Check PTFE Tube':
  178. if (isX1 || isP1) return 'https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube';
  179. if (isA1Mini || isA1) return 'https://wiki.bambulab.com/en/a1-mini/maintenance/ptfe-tube';
  180. if (isH2D) return 'https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer';
  181. if (isH2S) return 'https://wiki.bambulab.com/en/h2s/maintenance/replace-ptfe-tube-on-h2s-printer';
  182. if (isH2C) return 'https://wiki.bambulab.com/en/h2/maintenance/replace-ptfe-tube-on-h2d-printer'; // H2C uses H2D guide
  183. if (isP2S) return 'https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube'; // P2S uses similar PTFE
  184. return 'https://wiki.bambulab.com/en/x1/maintenance/replace-ptfe-tube';
  185. case 'Replace HEPA Filter':
  186. case 'HEPA Filter':
  187. case 'Replace Carbon Filter':
  188. case 'Carbon Filter':
  189. if (isH2) return 'https://wiki.bambulab.com/en/h2/maintenance/replace-smoke-purifier-air-filte';
  190. // X1/P1 use the activated carbon filter
  191. return 'https://wiki.bambulab.com/en/x1/maintenance/replace-carbon-filter';
  192. case 'Lubricate Left Nozzle Rail':
  193. case 'Left Nozzle Rail':
  194. // H2 series specific - dual nozzle system
  195. if (isH2) return 'https://wiki.bambulab.com/en/h2/maintenance/x-axis-lubrication';
  196. return null;
  197. default:
  198. // Custom maintenance types don't have wiki URLs
  199. return null;
  200. }
  201. }
  202. // Maintenance item card - cleaner, more visual design
  203. function MaintenanceCard({
  204. item,
  205. onPerform,
  206. onToggle,
  207. hasPermission,
  208. t,
  209. }: {
  210. item: MaintenanceStatus;
  211. onPerform: (id: number) => void;
  212. onToggle: (id: number, enabled: boolean) => void;
  213. hasPermission: (permission: Permission) => boolean;
  214. t: TFunction;
  215. }) {
  216. const Icon = getIcon(item.maintenance_type_icon);
  217. const intervalType = item.interval_type || 'hours';
  218. // Calculate progress based on interval type
  219. const getProgress = () => {
  220. if (intervalType === 'days') {
  221. const daysSince = item.days_since_maintenance ?? 0;
  222. return Math.max(0, Math.min(100, (daysSince / item.interval_hours) * 100));
  223. }
  224. return Math.max(0, Math.min(100,
  225. ((item.interval_hours - item.hours_until_due) / item.interval_hours) * 100
  226. ));
  227. };
  228. const progressPercent = getProgress();
  229. const getStatusColor = () => {
  230. if (!item.enabled) return 'text-bambu-gray';
  231. if (item.is_due) return 'text-red-400';
  232. if (item.is_warning) return 'text-amber-400';
  233. return 'text-bambu-green';
  234. };
  235. const getProgressColor = () => {
  236. if (!item.enabled) return 'bg-bambu-gray/30';
  237. if (item.is_due) return 'bg-red-500';
  238. if (item.is_warning) return 'bg-amber-500';
  239. return 'bg-bambu-green';
  240. };
  241. const getBgColor = () => {
  242. if (!item.enabled) return 'bg-bambu-dark-secondary/50';
  243. if (item.is_due) return 'bg-red-500/5 border-red-500/20';
  244. if (item.is_warning) return 'bg-amber-500/5 border-amber-500/20';
  245. return 'bg-bambu-dark-secondary border-bambu-dark-tertiary';
  246. };
  247. const getStatusText = () => {
  248. if (!item.enabled) return t('common.disabled');
  249. if (intervalType === 'days') {
  250. const daysUntil = item.days_until_due ?? 0;
  251. if (item.is_due) return t('maintenance.overdueBy', { duration: formatDuration(Math.abs(daysUntil), 'days', t) });
  252. if (item.is_warning) return t('maintenance.dueIn', { duration: formatDuration(daysUntil, 'days', t) });
  253. return t('maintenance.timeLeft', { duration: formatDuration(daysUntil, 'days', t) });
  254. } else {
  255. if (item.is_due) return t('maintenance.overdueBy', { duration: formatDuration(Math.abs(item.hours_until_due), 'hours', t) });
  256. if (item.is_warning) return t('maintenance.dueIn', { duration: formatDuration(item.hours_until_due, 'hours', t) });
  257. return t('maintenance.timeLeft', { duration: formatDuration(item.hours_until_due, 'hours', t) });
  258. }
  259. };
  260. return (
  261. <div className={`rounded-xl border p-4 transition-all ${getBgColor()}`}>
  262. <div className="flex items-start gap-3 max-[550px]:flex-wrap">
  263. {/* Icon with status indicator */}
  264. <div className={`relative p-2.5 rounded-lg shrink-0 ${
  265. item.is_due ? 'bg-red-500/20' :
  266. item.is_warning ? 'bg-amber-500/20' :
  267. item.enabled ? 'bg-bambu-dark' : 'bg-bambu-dark/50'
  268. }`}>
  269. <Icon className={`w-5 h-5 ${getStatusColor()}`} />
  270. {item.enabled && (item.is_due || item.is_warning) && (
  271. <span className={`absolute -top-1 -right-1 w-2.5 h-2.5 rounded-full ${
  272. item.is_due ? 'bg-red-500' : 'bg-amber-500'
  273. } animate-pulse`} />
  274. )}
  275. </div>
  276. {/* Content */}
  277. <div className="flex-1 min-w-0">
  278. <div className="flex items-center gap-2">
  279. <h3 className={`font-medium truncate ${item.enabled ? 'text-white' : 'text-bambu-gray'}`}>
  280. {item.maintenance_type_name}
  281. </h3>
  282. {intervalType === 'days' && (
  283. <span title={t('maintenance.timeBasedInterval')}>
  284. <Calendar className="w-3.5 h-3.5 text-bambu-gray shrink-0" />
  285. </span>
  286. )}
  287. {/* Wiki link - next to name */}
  288. {(() => {
  289. // Use custom wiki_url from type if available, otherwise use computed URL
  290. const wikiUrl = item.maintenance_type_wiki_url || getMaintenanceWikiUrl(item.maintenance_type_name, item.printer_model);
  291. return wikiUrl ? (
  292. <a
  293. href={wikiUrl}
  294. target="_blank"
  295. rel="noopener noreferrer"
  296. className="text-bambu-gray hover:text-bambu-green transition-colors shrink-0"
  297. title={t('maintenance.viewDocumentation')}
  298. onClick={(e) => e.stopPropagation()}
  299. >
  300. <ExternalLink className="w-3.5 h-3.5" />
  301. </a>
  302. ) : null;
  303. })()}
  304. </div>
  305. {/* Progress bar */}
  306. <div className="mt-2 mb-1.5">
  307. <div className="w-full h-1.5 bg-bambu-dark rounded-full overflow-hidden">
  308. <div
  309. className={`h-full rounded-full transition-all duration-500 ${getProgressColor()}`}
  310. style={{ width: `${progressPercent}%` }}
  311. />
  312. </div>
  313. </div>
  314. {/* Status text */}
  315. <div className={`text-xs flex items-center gap-1 ${getStatusColor()}`}>
  316. {item.is_due && <AlertTriangle className="w-3 h-3" />}
  317. {item.is_warning && !item.is_due && <Clock className="w-3 h-3" />}
  318. {!item.is_due && !item.is_warning && item.enabled && <Check className="w-3 h-3" />}
  319. {getStatusText()}
  320. </div>
  321. </div>
  322. {/* Actions */}
  323. <div className="flex items-center gap-2 shrink-0 max-[550px]:w-full max-[550px]:justify-end max-[550px]:mt-1">
  324. <span title={!hasPermission('maintenance:update') ? t('maintenance.noPermissionUpdate') : undefined}>
  325. <Toggle
  326. checked={item.enabled}
  327. onChange={(checked) => onToggle(item.id, checked)}
  328. disabled={!hasPermission('maintenance:update')}
  329. />
  330. </span>
  331. <Button
  332. size="sm"
  333. variant={item.is_due ? 'primary' : 'secondary'}
  334. onClick={() => onPerform(item.id)}
  335. disabled={!item.enabled || !hasPermission('maintenance:update')}
  336. title={!hasPermission('maintenance:update') ? t('maintenance.noPermissionPerform') : undefined}
  337. className="!px-3"
  338. >
  339. <RotateCcw className="w-3.5 h-3.5" />
  340. {t('common.reset')}
  341. </Button>
  342. </div>
  343. </div>
  344. </div>
  345. );
  346. }
  347. // Printer section with improved visual hierarchy
  348. function PrinterSection({
  349. overview,
  350. onPerform,
  351. onToggle,
  352. onSetHours,
  353. hasPermission,
  354. t,
  355. }: {
  356. overview: PrinterMaintenanceOverview;
  357. onPerform: (id: number) => void;
  358. onToggle: (id: number, enabled: boolean) => void;
  359. onSetHours: (printerId: number, hours: number) => void;
  360. hasPermission: (permission: Permission) => boolean;
  361. t: TFunction;
  362. }) {
  363. const [expanded, setExpanded] = useState(false);
  364. const [editingHours, setEditingHours] = useState(false);
  365. const [hoursInput, setHoursInput] = useState(overview.total_print_hours.toFixed(1));
  366. const sortedItems = [...overview.maintenance_items].sort((a, b) => {
  367. // Sort by urgency first, then by type
  368. if (a.is_due && !b.is_due) return -1;
  369. if (!a.is_due && b.is_due) return 1;
  370. if (a.is_warning && !b.is_warning) return -1;
  371. if (!a.is_warning && b.is_warning) return 1;
  372. return a.maintenance_type_id - b.maintenance_type_id;
  373. });
  374. const nextTask = sortedItems.find(item => item.enabled && (item.is_due || item.is_warning));
  375. const handleSaveHours = () => {
  376. const hours = parseFloat(hoursInput);
  377. if (!isNaN(hours) && hours >= 0) {
  378. onSetHours(overview.printer_id, hours);
  379. setEditingHours(false);
  380. }
  381. };
  382. return (
  383. <Card className="overflow-hidden">
  384. {/* Header */}
  385. <div className="p-5">
  386. <div className="flex items-center justify-between">
  387. <div className="flex items-center gap-4">
  388. <h2 className="text-xl font-semibold text-white">{overview.printer_name}</h2>
  389. <div className="flex items-center gap-2">
  390. {overview.due_count > 0 && (
  391. <span className="px-2.5 py-1 bg-red-500/20 text-red-400 text-xs font-medium rounded-full flex items-center gap-1.5">
  392. <AlertTriangle className="w-3 h-3" />
  393. {t('maintenance.overdueCount', { count: overview.due_count })}
  394. </span>
  395. )}
  396. {overview.warning_count > 0 && (
  397. <span className="px-2.5 py-1 bg-amber-500/20 text-amber-400 text-xs font-medium rounded-full flex items-center gap-1.5">
  398. <Clock className="w-3 h-3" />
  399. {t('maintenance.dueSoonCount', { count: overview.warning_count })}
  400. </span>
  401. )}
  402. {overview.due_count === 0 && overview.warning_count === 0 && (
  403. <span className="px-2.5 py-1 bg-bambu-green/20 text-bambu-green text-xs font-medium rounded-full flex items-center gap-1.5">
  404. <Check className="w-3 h-3" />
  405. {t('maintenance.allGood')}
  406. </span>
  407. )}
  408. </div>
  409. </div>
  410. <button
  411. onClick={() => setExpanded(!expanded)}
  412. className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-bambu-gray hover:text-white hover:bg-bambu-dark rounded-lg transition-colors"
  413. >
  414. {expanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
  415. {expanded ? t('common.collapse') : t('common.expand')}
  416. </button>
  417. </div>
  418. {/* Quick stats row */}
  419. <div className="flex items-center gap-6 mt-4">
  420. {/* Print Hours */}
  421. <div className="flex items-center gap-3">
  422. <div className="p-2 bg-bambu-dark/50 rounded-lg">
  423. <Timer className="w-4 h-4 text-bambu-gray" />
  424. </div>
  425. {editingHours ? (
  426. <div className="flex items-center gap-2">
  427. <input
  428. type="number"
  429. value={hoursInput}
  430. onChange={(e) => setHoursInput(e.target.value)}
  431. onKeyDown={(e) => {
  432. if (e.key === 'Enter') handleSaveHours();
  433. if (e.key === 'Escape') setEditingHours(false);
  434. }}
  435. className="w-24 px-2 py-1 bg-bambu-dark border border-bambu-dark-tertiary rounded text-white text-sm"
  436. min="0"
  437. step="1"
  438. autoFocus
  439. />
  440. <span className="text-xs text-bambu-gray">{t('common.hours')}</span>
  441. <Button size="sm" onClick={handleSaveHours}>{t('common.save')}</Button>
  442. <Button size="sm" variant="secondary" onClick={() => setEditingHours(false)}>{t('common.cancel')}</Button>
  443. </div>
  444. ) : (
  445. <button
  446. onClick={() => {
  447. if (!hasPermission('maintenance:update')) return;
  448. setHoursInput(Math.round(overview.total_print_hours).toString());
  449. setEditingHours(true);
  450. }}
  451. className={`group ${!hasPermission('maintenance:update') ? 'cursor-not-allowed opacity-60' : ''}`}
  452. title={!hasPermission('maintenance:update') ? t('maintenance.noPermissionEditHours') : undefined}
  453. >
  454. <div className={`text-sm font-medium text-white ${hasPermission('maintenance:update') ? 'group-hover:text-bambu-green' : ''} transition-colors flex items-center gap-1`}>
  455. {Math.round(overview.total_print_hours)} {t('common.hours')}
  456. <Edit3 className={`w-3 h-3 text-bambu-gray ${hasPermission('maintenance:update') ? 'group-hover:text-bambu-green' : ''}`} />
  457. </div>
  458. <div className="text-xs text-bambu-gray">{t('maintenance.totalPrintTime')}</div>
  459. </button>
  460. )}
  461. </div>
  462. {/* Divider */}
  463. <div className="w-px h-10 bg-bambu-dark-tertiary" />
  464. {/* Next Maintenance */}
  465. {nextTask && (
  466. <div className="flex items-center gap-3">
  467. <div className={`p-2 rounded-lg ${
  468. nextTask.is_due ? 'bg-red-500/20' : 'bg-amber-500/20'
  469. }`}>
  470. {(() => {
  471. const Icon = getIcon(nextTask.maintenance_type_icon);
  472. return <Icon className={`w-4 h-4 ${nextTask.is_due ? 'text-red-400' : 'text-amber-400'}`} />;
  473. })()}
  474. </div>
  475. <div>
  476. <div className={`text-sm font-medium ${nextTask.is_due ? 'text-red-400' : 'text-amber-400'}`}>
  477. {nextTask.maintenance_type_name}
  478. </div>
  479. <div className={`text-xs ${nextTask.is_due ? 'text-red-400/70' : 'text-amber-400/70'}`}>
  480. {nextTask.is_due ? t('common.overdue') : t('maintenance.dueSoon')}
  481. </div>
  482. </div>
  483. </div>
  484. )}
  485. </div>
  486. </div>
  487. {/* Maintenance items */}
  488. {expanded && (
  489. <CardContent className="pt-0 border-t border-bambu-dark-tertiary">
  490. <div className="grid grid-cols-1 lg:grid-cols-2 gap-3 pt-4">
  491. {sortedItems.map((item) => (
  492. <MaintenanceCard
  493. key={item.id}
  494. item={item}
  495. onPerform={onPerform}
  496. onToggle={onToggle}
  497. hasPermission={hasPermission}
  498. t={t}
  499. />
  500. ))}
  501. </div>
  502. </CardContent>
  503. )}
  504. </Card>
  505. );
  506. }
  507. // Settings section - maintenance types configuration
  508. function SettingsSection({
  509. overview,
  510. types,
  511. onUpdateInterval,
  512. onAddType,
  513. onUpdateType,
  514. onDeleteType,
  515. onRestoreDefaults,
  516. isRestoringDefaults,
  517. onAssignType,
  518. onRemoveItem,
  519. hasPermission,
  520. t,
  521. }: {
  522. overview: PrinterMaintenanceOverview[] | undefined;
  523. types: MaintenanceType[];
  524. onUpdateInterval: (id: number, data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null }) => void;
  525. onAddType: (data: { name: string; description?: string; default_interval_hours: number; interval_type: 'hours' | 'days'; icon?: string; wiki_url?: string | null }, printerIds: number[]) => void;
  526. onUpdateType: (id: number, data: { name?: string; default_interval_hours?: number; interval_type?: 'hours' | 'days'; icon?: string; wiki_url?: string | null }) => void;
  527. onDeleteType: (id: number) => void;
  528. onRestoreDefaults: () => void;
  529. isRestoringDefaults: boolean;
  530. onAssignType: (printerId: number, typeId: number) => void;
  531. onRemoveItem: (itemId: number) => void;
  532. hasPermission: (permission: Permission) => boolean;
  533. t: TFunction;
  534. }) {
  535. const [editingInterval, setEditingInterval] = useState<number | null>(null);
  536. const [intervalInput, setIntervalInput] = useState('');
  537. const [intervalTypeInput, setIntervalTypeInput] = useState<'hours' | 'days'>('hours');
  538. const [showAddType, setShowAddType] = useState(false);
  539. const [newTypeName, setNewTypeName] = useState('');
  540. const [newTypeInterval, setNewTypeInterval] = useState('100');
  541. const [newTypeIntervalType, setNewTypeIntervalType] = useState<'hours' | 'days'>('hours');
  542. const [newTypeIcon, setNewTypeIcon] = useState('Wrench');
  543. const [newTypeWikiUrl, setNewTypeWikiUrl] = useState('');
  544. const [selectedPrinters, setSelectedPrinters] = useState<Set<number>>(new Set());
  545. const [expandedType, setExpandedType] = useState<number | null>(null);
  546. const [pendingSystemDelete, setPendingSystemDelete] = useState<MaintenanceType | null>(null);
  547. // Get unique printers from overview
  548. const printers = useMemo(() => {
  549. if (!overview) return [];
  550. return overview.map(o => ({ id: o.printer_id, name: o.printer_name }));
  551. }, [overview]);
  552. // Get which printers have a specific maintenance type assigned
  553. const getAssignedPrinters = (typeId: number) => {
  554. if (!overview) return [];
  555. return overview
  556. .filter(p => p.maintenance_items.some(item => item.maintenance_type_id === typeId))
  557. .map(p => ({
  558. printerId: p.printer_id,
  559. printerName: p.printer_name,
  560. itemId: p.maintenance_items.find(item => item.maintenance_type_id === typeId)?.id,
  561. }));
  562. };
  563. // Get printers that DON'T have a specific type assigned
  564. const getUnassignedPrinters = (typeId: number) => {
  565. if (!overview) return [];
  566. const assignedIds = new Set(getAssignedPrinters(typeId).map(p => p.printerId));
  567. return printers.filter(p => !assignedIds.has(p.id));
  568. };
  569. // Edit type state
  570. const [editingType, setEditingType] = useState<MaintenanceType | null>(null);
  571. const [editTypeName, setEditTypeName] = useState('');
  572. const [editTypeInterval, setEditTypeInterval] = useState('');
  573. const [editTypeIntervalType, setEditTypeIntervalType] = useState<'hours' | 'days'>('hours');
  574. const [editTypeIcon, setEditTypeIcon] = useState('Wrench');
  575. const [editTypeWikiUrl, setEditTypeWikiUrl] = useState('');
  576. const startEditType = (type: MaintenanceType) => {
  577. setEditingType(type);
  578. setEditTypeName(type.name);
  579. setEditTypeInterval(type.default_interval_hours.toString());
  580. setEditTypeIntervalType(type.interval_type || 'hours');
  581. setEditTypeIcon(type.icon || 'Wrench');
  582. setEditTypeWikiUrl(type.wiki_url || '');
  583. };
  584. const handleSaveEditType = () => {
  585. if (editingType && editTypeName.trim() && parseFloat(editTypeInterval) > 0) {
  586. onUpdateType(editingType.id, {
  587. name: editTypeName.trim(),
  588. default_interval_hours: parseFloat(editTypeInterval),
  589. interval_type: editTypeIntervalType,
  590. icon: editTypeIcon,
  591. wiki_url: editTypeWikiUrl.trim() || null,
  592. });
  593. setEditingType(null);
  594. }
  595. };
  596. const handleSaveInterval = (itemId: number, defaultInterval: number, defaultIntervalType: 'hours' | 'days') => {
  597. const newInterval = parseFloat(intervalInput);
  598. if (!isNaN(newInterval) && newInterval > 0) {
  599. const customInterval = Math.abs(newInterval - defaultInterval) < 0.01 ? null : newInterval;
  600. const customIntervalType = intervalTypeInput !== defaultIntervalType ? intervalTypeInput : null;
  601. onUpdateInterval(itemId, {
  602. custom_interval_hours: customInterval,
  603. custom_interval_type: customIntervalType
  604. });
  605. }
  606. setEditingInterval(null);
  607. };
  608. const handleAddType = (e: React.FormEvent) => {
  609. e.preventDefault();
  610. if (newTypeName.trim() && parseFloat(newTypeInterval) > 0 && selectedPrinters.size > 0) {
  611. onAddType({
  612. name: newTypeName.trim(),
  613. default_interval_hours: parseFloat(newTypeInterval),
  614. interval_type: newTypeIntervalType,
  615. icon: newTypeIcon,
  616. wiki_url: newTypeWikiUrl.trim() || null,
  617. }, Array.from(selectedPrinters));
  618. setNewTypeName('');
  619. setNewTypeInterval('100');
  620. setNewTypeIntervalType('hours');
  621. setNewTypeWikiUrl('');
  622. setSelectedPrinters(new Set());
  623. setShowAddType(false);
  624. }
  625. };
  626. const togglePrinterSelection = (printerId: number) => {
  627. setSelectedPrinters(prev => {
  628. const next = new Set(prev);
  629. if (next.has(printerId)) {
  630. next.delete(printerId);
  631. } else {
  632. next.add(printerId);
  633. }
  634. return next;
  635. });
  636. };
  637. const printerItems = overview?.map(p => ({
  638. printerId: p.printer_id,
  639. printerName: p.printer_name,
  640. items: p.maintenance_items.sort((a, b) => a.maintenance_type_id - b.maintenance_type_id),
  641. })).sort((a, b) => a.printerName.localeCompare(b.printerName)) || [];
  642. const systemTypes = types.filter(t => t.is_system);
  643. const customTypes = types.filter(t => !t.is_system);
  644. return (
  645. <div className="space-y-8">
  646. {/* Maintenance Types */}
  647. <div>
  648. <div className="flex items-center justify-between mb-4">
  649. <div>
  650. <h2 className="text-lg font-semibold text-white">{t('maintenance.maintenanceTypes')}</h2>
  651. <p className="text-sm text-bambu-gray mt-1">{t('maintenance.maintenanceTypesDescription')}</p>
  652. </div>
  653. <div className="flex items-center gap-2">
  654. <Button
  655. variant="secondary"
  656. onClick={onRestoreDefaults}
  657. disabled={!hasPermission('maintenance:delete') || isRestoringDefaults}
  658. title={!hasPermission('maintenance:delete') ? t('maintenance.noPermissionDeleteTypes') : undefined}
  659. >
  660. {t('maintenance.restoreDefaults')}
  661. </Button>
  662. <Button
  663. onClick={() => setShowAddType(!showAddType)}
  664. disabled={!hasPermission('maintenance:create')}
  665. title={!hasPermission('maintenance:create') ? t('maintenance.noPermissionEditTypes') : undefined}
  666. >
  667. <Plus className="w-4 h-4" />
  668. {t('maintenance.addCustomType')}
  669. </Button>
  670. </div>
  671. </div>
  672. {/* Add custom type form */}
  673. {showAddType && (
  674. <Card className="mb-6">
  675. <CardContent className="py-4">
  676. <form onSubmit={handleAddType}>
  677. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
  678. <div className="lg:col-span-2">
  679. <label className="block text-xs text-bambu-gray mb-1.5">{t('common.name')}</label>
  680. <input
  681. type="text"
  682. value={newTypeName}
  683. onChange={(e) => setNewTypeName(e.target.value)}
  684. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  685. placeholder={t('maintenance.exampleName')}
  686. autoFocus
  687. />
  688. </div>
  689. <div>
  690. <label className="block text-xs text-bambu-gray mb-1.5">{t('maintenance.intervalType')}</label>
  691. <select
  692. value={newTypeIntervalType}
  693. onChange={(e) => {
  694. setNewTypeIntervalType(e.target.value as 'hours' | 'days');
  695. // Set sensible default based on type
  696. if (e.target.value === 'days') {
  697. setNewTypeInterval('30');
  698. } else {
  699. setNewTypeInterval('100');
  700. }
  701. }}
  702. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  703. >
  704. <option value="hours">{t('maintenance.printHours')}</option>
  705. <option value="days">{t('maintenance.calendarDays')}</option>
  706. </select>
  707. </div>
  708. <div>
  709. <label className="block text-xs text-bambu-gray mb-1.5">
  710. {t('maintenance.intervalValue', { type: newTypeIntervalType === 'days' ? t('maintenance.calendarDays').toLowerCase() : t('common.hours') })}
  711. </label>
  712. <input
  713. type="number"
  714. value={newTypeInterval}
  715. onChange={(e) => setNewTypeInterval(e.target.value)}
  716. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  717. min="1"
  718. />
  719. </div>
  720. </div>
  721. <div className="mt-4 flex items-end justify-between">
  722. <div>
  723. <label className="block text-xs text-bambu-gray mb-1.5">{t('maintenance.icon')}</label>
  724. <div className="flex gap-1">
  725. {Object.keys(iconMap).map((iconName) => {
  726. const IconComp = iconMap[iconName];
  727. return (
  728. <button
  729. key={iconName}
  730. type="button"
  731. onClick={() => setNewTypeIcon(iconName)}
  732. className={`p-2 rounded-lg transition-colors ${
  733. newTypeIcon === iconName
  734. ? 'bg-bambu-green text-white'
  735. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary'
  736. }`}
  737. >
  738. <IconComp className="w-4 h-4" />
  739. </button>
  740. );
  741. })}
  742. </div>
  743. </div>
  744. </div>
  745. {/* Wiki URL */}
  746. <div className="mt-4">
  747. <label className="block text-xs text-bambu-gray mb-1.5">{t('maintenance.documentationLink')}</label>
  748. <input
  749. type="url"
  750. value={newTypeWikiUrl}
  751. onChange={(e) => setNewTypeWikiUrl(e.target.value)}
  752. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  753. placeholder="https://wiki.bambulab.com/..."
  754. />
  755. </div>
  756. {/* Printer selection */}
  757. <div className="mt-4">
  758. <label className="block text-xs text-bambu-gray mb-1.5">{t('maintenance.assignToPrinters')}</label>
  759. <div className="flex flex-wrap gap-2">
  760. {printers.map(p => (
  761. <button
  762. key={p.id}
  763. type="button"
  764. onClick={() => togglePrinterSelection(p.id)}
  765. className={`px-3 py-1.5 rounded-lg text-sm transition-colors ${
  766. selectedPrinters.has(p.id)
  767. ? 'bg-bambu-green text-white'
  768. : 'bg-bambu-dark text-bambu-gray hover:text-white hover:bg-bambu-dark-tertiary'
  769. }`}
  770. >
  771. {p.name}
  772. </button>
  773. ))}
  774. </div>
  775. {selectedPrinters.size === 0 && (
  776. <p className="text-xs text-orange-400 mt-1">{t('maintenance.selectAtLeastOnePrinter')}</p>
  777. )}
  778. </div>
  779. <div className="mt-4 flex justify-end gap-2">
  780. <Button type="button" variant="secondary" onClick={() => { setShowAddType(false); setSelectedPrinters(new Set()); }}>
  781. {t('common.cancel')}
  782. </Button>
  783. <Button type="submit" disabled={!newTypeName.trim() || selectedPrinters.size === 0}>
  784. {t('maintenance.addType')}
  785. </Button>
  786. </div>
  787. </form>
  788. </CardContent>
  789. </Card>
  790. )}
  791. {/* Types grid */}
  792. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
  793. {/* System types */}
  794. {systemTypes.map((type) => {
  795. const Icon = getIcon(type.icon);
  796. const intervalType = type.interval_type || 'hours';
  797. return (
  798. <div key={type.id} className="bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-dark-tertiary">
  799. <div className="flex items-center gap-3">
  800. <div className="p-2.5 bg-bambu-dark rounded-lg">
  801. <Icon className="w-5 h-5 text-bambu-gray" />
  802. </div>
  803. <div className="flex-1 min-w-0">
  804. <div className="text-sm font-medium text-white truncate">{type.name}</div>
  805. <div className="text-xs text-bambu-gray mt-0.5 flex items-center gap-1">
  806. {intervalType === 'days' ? <Calendar className="w-3 h-3" /> : <Timer className="w-3 h-3" />}
  807. {formatIntervalLabel(type.default_interval_hours, intervalType, t)}
  808. </div>
  809. </div>
  810. <button
  811. onClick={() => {
  812. if (!hasPermission('maintenance:delete')) return;
  813. setPendingSystemDelete(type);
  814. }}
  815. disabled={!hasPermission('maintenance:delete')}
  816. title={!hasPermission('maintenance:delete') ? t('maintenance.noPermissionDeleteTypes') : undefined}
  817. className={`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${!hasPermission('maintenance:delete') ? 'opacity-50 cursor-not-allowed' : ''}`}
  818. >
  819. <Trash2 className="w-4 h-4" />
  820. </button>
  821. </div>
  822. </div>
  823. );
  824. })}
  825. {/* Custom types */}
  826. {customTypes.map((type) => {
  827. const Icon = getIcon(type.icon);
  828. const intervalType = type.interval_type || 'hours';
  829. const isEditing = editingType?.id === type.id;
  830. if (isEditing) {
  831. return (
  832. <div key={type.id} className="bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green">
  833. <div className="space-y-3">
  834. <input
  835. type="text"
  836. value={editTypeName}
  837. onChange={(e) => setEditTypeName(e.target.value)}
  838. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  839. placeholder={t('common.name')}
  840. autoFocus
  841. />
  842. <div className="flex gap-2">
  843. <select
  844. value={editTypeIntervalType}
  845. onChange={(e) => setEditTypeIntervalType(e.target.value as 'hours' | 'days')}
  846. className="flex-1 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  847. >
  848. <option value="hours">{t('maintenance.printHours')}</option>
  849. <option value="days">{t('maintenance.calendarDays')}</option>
  850. </select>
  851. <input
  852. type="number"
  853. value={editTypeInterval}
  854. onChange={(e) => setEditTypeInterval(e.target.value)}
  855. className="w-24 px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  856. min="1"
  857. />
  858. </div>
  859. <div className="flex flex-wrap gap-1">
  860. {Object.keys(iconMap).map((iconName) => {
  861. const IconComp = iconMap[iconName];
  862. return (
  863. <button
  864. key={iconName}
  865. type="button"
  866. onClick={() => setEditTypeIcon(iconName)}
  867. className={`p-1.5 rounded transition-colors ${
  868. editTypeIcon === iconName
  869. ? 'bg-bambu-green text-white'
  870. : 'bg-bambu-dark text-bambu-gray hover:text-white'
  871. }`}
  872. >
  873. <IconComp className="w-3.5 h-3.5" />
  874. </button>
  875. );
  876. })}
  877. </div>
  878. <input
  879. type="url"
  880. value={editTypeWikiUrl}
  881. onChange={(e) => setEditTypeWikiUrl(e.target.value)}
  882. className="w-full px-3 py-2 bg-bambu-dark border border-bambu-dark-tertiary rounded-lg text-white text-sm focus:border-bambu-green focus:outline-none"
  883. placeholder={t('maintenance.documentationLink')}
  884. />
  885. <div className="flex gap-2">
  886. <Button size="sm" onClick={handleSaveEditType} disabled={!editTypeName.trim()}>
  887. {t('common.save')}
  888. </Button>
  889. <Button size="sm" variant="secondary" onClick={() => setEditingType(null)}>
  890. {t('common.cancel')}
  891. </Button>
  892. </div>
  893. </div>
  894. </div>
  895. );
  896. }
  897. const assignedPrinters = getAssignedPrinters(type.id);
  898. const unassignedPrinters = getUnassignedPrinters(type.id);
  899. const isExpanded = expandedType === type.id;
  900. return (
  901. <div key={type.id} className="bg-bambu-dark-secondary rounded-xl p-4 border border-bambu-green/30">
  902. <div className="flex items-center gap-3">
  903. <div className="p-2.5 bg-bambu-green/20 rounded-lg">
  904. <Icon className="w-5 h-5 text-bambu-green" />
  905. </div>
  906. <div className="flex-1 min-w-0">
  907. <div className="flex items-center gap-2">
  908. <span className="text-sm font-medium text-white truncate">{type.name}</span>
  909. <span className="px-1.5 py-0.5 bg-bambu-green/20 text-bambu-green text-[10px] font-medium rounded">
  910. {t('maintenance.custom')}
  911. </span>
  912. </div>
  913. <div className="text-xs text-bambu-gray mt-0.5 flex items-center gap-1">
  914. {intervalType === 'days' ? <Calendar className="w-3 h-3" /> : <Timer className="w-3 h-3" />}
  915. {formatIntervalLabel(type.default_interval_hours, intervalType, t)}
  916. </div>
  917. </div>
  918. <button
  919. onClick={() => setExpandedType(isExpanded ? null : type.id)}
  920. className={`px-2 py-1 rounded-lg border transition-colors flex items-center gap-1 ${
  921. assignedPrinters.length > 0
  922. ? 'border-bambu-green/50 bg-bambu-green/10 text-bambu-green hover:bg-bambu-green/20'
  923. : 'border-orange-400/50 bg-orange-400/10 text-orange-400 hover:bg-orange-400/20'
  924. }`}
  925. title={t('maintenance.printersAssignedClick', { count: assignedPrinters.length })}
  926. >
  927. <Printer className="w-3 h-3" />
  928. <span className="text-xs font-medium">{assignedPrinters.length}</span>
  929. <ChevronDown className={`w-3 h-3 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
  930. </button>
  931. <button
  932. onClick={() => startEditType(type)}
  933. disabled={!hasPermission('maintenance:update')}
  934. title={!hasPermission('maintenance:update') ? t('maintenance.noPermissionEditTypes') : undefined}
  935. className={`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-white transition-colors ${!hasPermission('maintenance:update') ? 'opacity-50 cursor-not-allowed' : ''}`}
  936. >
  937. <Edit3 className="w-4 h-4" />
  938. </button>
  939. <button
  940. onClick={() => {
  941. if (confirm(t('maintenance.deleteTypeConfirm', { name: type.name }))) {
  942. onDeleteType(type.id);
  943. }
  944. }}
  945. disabled={!hasPermission('maintenance:delete')}
  946. title={!hasPermission('maintenance:delete') ? t('maintenance.noPermissionDeleteTypes') : undefined}
  947. className={`p-2 rounded-lg hover:bg-bambu-dark text-bambu-gray hover:text-red-400 transition-colors ${!hasPermission('maintenance:delete') ? 'opacity-50 cursor-not-allowed' : ''}`}
  948. >
  949. <Trash2 className="w-4 h-4" />
  950. </button>
  951. </div>
  952. {/* Printer assignment management */}
  953. {isExpanded && (
  954. <div className="mt-3 pt-3 border-t border-bambu-dark-tertiary">
  955. <p className="text-xs text-bambu-gray mb-2">{t('maintenance.assignedToPrinters')}</p>
  956. {assignedPrinters.length === 0 ? (
  957. <p className="text-xs text-orange-400">{t('maintenance.noPrintersAssigned')}</p>
  958. ) : (
  959. <div className="flex flex-wrap gap-1 mb-2">
  960. {assignedPrinters.map(p => (
  961. <span
  962. key={p.printerId}
  963. className="inline-flex items-center gap-1 px-2 py-1 bg-bambu-dark rounded text-xs text-white"
  964. >
  965. {p.printerName}
  966. <button
  967. onClick={() => p.itemId && onRemoveItem(p.itemId)}
  968. disabled={!hasPermission('maintenance:delete')}
  969. title={!hasPermission('maintenance:delete') ? t('maintenance.noPermissionRemovePrinter') : t('maintenance.removeFromPrinter')}
  970. className={`ml-1 ${hasPermission('maintenance:delete') ? 'hover:text-red-400' : 'opacity-50 cursor-not-allowed'}`}
  971. >
  972. ×
  973. </button>
  974. </span>
  975. ))}
  976. </div>
  977. )}
  978. {unassignedPrinters.length > 0 && (
  979. <div className="flex flex-wrap gap-1">
  980. <span className="text-xs text-bambu-gray mr-1">{t('maintenance.addPrinterShort')}</span>
  981. {unassignedPrinters.map(p => (
  982. <button
  983. key={p.id}
  984. onClick={() => onAssignType(p.id, type.id)}
  985. disabled={!hasPermission('maintenance:create')}
  986. title={!hasPermission('maintenance:create') ? t('maintenance.noPermissionAssignPrinter') : undefined}
  987. className={`px-2 py-1 bg-bambu-dark rounded text-xs transition-colors ${hasPermission('maintenance:create') ? 'hover:bg-bambu-green/20 text-bambu-gray hover:text-bambu-green' : 'opacity-50 cursor-not-allowed text-bambu-gray'}`}
  988. >
  989. + {p.name}
  990. </button>
  991. ))}
  992. </div>
  993. )}
  994. </div>
  995. )}
  996. </div>
  997. );
  998. })}
  999. </div>
  1000. </div>
  1001. {/* Per-printer interval overrides */}
  1002. {printerItems.length > 0 && (
  1003. <div>
  1004. <div className="mb-4">
  1005. <h2 className="text-lg font-semibold text-white">{t('maintenance.intervalOverrides')}</h2>
  1006. <p className="text-sm text-bambu-gray mt-1">{t('maintenance.intervalOverridesDescription')}</p>
  1007. </div>
  1008. <div className="space-y-4">
  1009. {printerItems.map((printer) => (
  1010. <Card key={printer.printerId}>
  1011. <CardContent className="py-4">
  1012. <h3 className="text-sm font-medium text-white mb-3">{printer.printerName}</h3>
  1013. <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
  1014. {printer.items.map((item) => {
  1015. const Icon = getIcon(item.maintenance_type_icon);
  1016. const typeInfo = types.find(t => t.id === item.maintenance_type_id);
  1017. const defaultInterval = typeInfo?.default_interval_hours || item.interval_hours;
  1018. const defaultIntervalType = typeInfo?.interval_type || 'hours';
  1019. const intervalType = item.interval_type || 'hours';
  1020. const isEditing = editingInterval === item.id;
  1021. return (
  1022. <div key={item.id} className="flex items-center gap-2 p-2.5 bg-bambu-dark rounded-lg">
  1023. <Icon className="w-4 h-4 text-bambu-gray shrink-0" />
  1024. <span className="text-xs text-bambu-gray flex-1 truncate">{item.maintenance_type_name}</span>
  1025. {isEditing ? (
  1026. <div className="flex items-center gap-1">
  1027. {intervalTypeInput === 'days' ? (
  1028. <Calendar className="w-3.5 h-3.5 text-bambu-gray shrink-0" />
  1029. ) : (
  1030. <Timer className="w-3.5 h-3.5 text-bambu-gray shrink-0" />
  1031. )}
  1032. <select
  1033. value={intervalTypeInput}
  1034. onChange={(e) => setIntervalTypeInput(e.target.value as 'hours' | 'days')}
  1035. className="px-1.5 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs"
  1036. >
  1037. <option value="hours">{t('maintenance.printHours')}</option>
  1038. <option value="days">{t('maintenance.calendarDays')}</option>
  1039. </select>
  1040. <input
  1041. type="number"
  1042. value={intervalInput}
  1043. onChange={(e) => setIntervalInput(e.target.value)}
  1044. onKeyDown={(e) => {
  1045. if (e.key === 'Enter') handleSaveInterval(item.id, defaultInterval, defaultIntervalType);
  1046. if (e.key === 'Escape') setEditingInterval(null);
  1047. }}
  1048. className="w-16 px-2 py-1 bg-bambu-dark-secondary border border-bambu-dark-tertiary rounded text-white text-xs"
  1049. min="1"
  1050. />
  1051. <Button size="sm" onClick={() => handleSaveInterval(item.id, defaultInterval, defaultIntervalType)}>OK</Button>
  1052. </div>
  1053. ) : (
  1054. <button
  1055. onClick={() => {
  1056. if (!hasPermission('maintenance:update')) return;
  1057. setEditingInterval(item.id);
  1058. setIntervalInput(item.interval_hours.toString());
  1059. setIntervalTypeInput(intervalType);
  1060. }}
  1061. disabled={!hasPermission('maintenance:update')}
  1062. title={!hasPermission('maintenance:update') ? t('maintenance.noPermissionEditIntervals') : undefined}
  1063. className={`px-2 py-1 bg-bambu-dark-tertiary border border-bambu-dark-tertiary rounded text-xs font-medium text-white transition-colors flex items-center gap-1 ${hasPermission('maintenance:update') ? 'hover:bg-bambu-dark-secondary hover:border-bambu-green' : 'opacity-50 cursor-not-allowed'}`}
  1064. >
  1065. {intervalType === 'days' ? <Calendar className="w-3 h-3" /> : <Timer className="w-3 h-3" />}
  1066. {formatIntervalLabel(item.interval_hours, intervalType, t)}
  1067. <Edit3 className="w-3 h-3 text-bambu-gray" />
  1068. </button>
  1069. )}
  1070. </div>
  1071. );
  1072. })}
  1073. </div>
  1074. </CardContent>
  1075. </Card>
  1076. ))}
  1077. </div>
  1078. </div>
  1079. )}
  1080. {printerItems.length === 0 && (
  1081. <Card>
  1082. <CardContent className="text-center py-12">
  1083. <Clock className="w-12 h-12 mx-auto mb-4 text-bambu-gray/30" />
  1084. <p className="text-bambu-gray">{t('common.noPrinters')}</p>
  1085. <p className="text-sm text-bambu-gray/70 mt-1">
  1086. {t('maintenance.intervalOverridesDescription')}
  1087. </p>
  1088. </CardContent>
  1089. </Card>
  1090. )}
  1091. {pendingSystemDelete && (
  1092. <ConfirmModal
  1093. title={t('maintenance.deleteSystemTypeTitle')}
  1094. message={t('maintenance.deleteSystemTypeMessage', { name: pendingSystemDelete.name })}
  1095. confirmText={t('common.delete')}
  1096. cancelText={t('common.cancel')}
  1097. variant="danger"
  1098. cancelVariant="primary"
  1099. cardClassName="bg-red-950/70 border border-red-800/70"
  1100. onConfirm={() => {
  1101. onDeleteType(pendingSystemDelete.id);
  1102. setPendingSystemDelete(null);
  1103. }}
  1104. onCancel={() => setPendingSystemDelete(null)}
  1105. />
  1106. )}
  1107. </div>
  1108. );
  1109. }
  1110. type TabType = 'status' | 'settings';
  1111. export function MaintenancePage() {
  1112. const { t } = useTranslation();
  1113. const queryClient = useQueryClient();
  1114. const { showToast } = useToast();
  1115. const { hasPermission } = useAuth();
  1116. const [activeTab, setActiveTab] = useState<TabType>('status');
  1117. const { data: overview, isLoading } = useQuery({
  1118. queryKey: ['maintenanceOverview'],
  1119. queryFn: api.getMaintenanceOverview,
  1120. });
  1121. const { data: types } = useQuery({
  1122. queryKey: ['maintenanceTypes'],
  1123. queryFn: api.getMaintenanceTypes,
  1124. });
  1125. const performMutation = useMutation({
  1126. mutationFn: ({ id, notes }: { id: number; notes?: string }) =>
  1127. api.performMaintenance(id, notes),
  1128. onSuccess: () => {
  1129. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1130. queryClient.invalidateQueries({ queryKey: ['maintenanceSummary'] });
  1131. showToast(t('maintenance.maintenanceComplete'));
  1132. },
  1133. onError: (error: Error) => {
  1134. showToast(error.message, 'error');
  1135. },
  1136. });
  1137. const updateMutation = useMutation({
  1138. mutationFn: ({ id, data }: { id: number; data: { custom_interval_hours?: number | null; custom_interval_type?: 'hours' | 'days' | null; enabled?: boolean } }) =>
  1139. api.updateMaintenanceItem(id, data),
  1140. onSuccess: () => {
  1141. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1142. },
  1143. onError: (error: Error) => {
  1144. showToast(error.message, 'error');
  1145. },
  1146. });
  1147. // addTypeMutation removed - we now handle type creation with printer assignment
  1148. // directly in onAddType callback
  1149. const updateTypeMutation = useMutation({
  1150. mutationFn: ({ id, data }: { id: number; data: Partial<{ name: string; default_interval_hours: number; interval_type: 'hours' | 'days'; icon: string }> }) =>
  1151. api.updateMaintenanceType(id, data),
  1152. onSuccess: () => {
  1153. queryClient.invalidateQueries({ queryKey: ['maintenanceTypes'] });
  1154. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1155. showToast(t('maintenance.typeUpdated'));
  1156. },
  1157. onError: (error: Error) => {
  1158. showToast(error.message, 'error');
  1159. },
  1160. });
  1161. const deleteTypeMutation = useMutation({
  1162. mutationFn: api.deleteMaintenanceType,
  1163. onSuccess: () => {
  1164. queryClient.invalidateQueries({ queryKey: ['maintenanceTypes'] });
  1165. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1166. showToast(t('maintenance.typeDeleted'));
  1167. },
  1168. onError: (error: Error) => {
  1169. showToast(error.message, 'error');
  1170. },
  1171. });
  1172. const restoreDefaultsMutation = useMutation({
  1173. mutationFn: api.restoreDefaultMaintenanceTypes,
  1174. onSuccess: (data: { restored: number }) => {
  1175. queryClient.invalidateQueries({ queryKey: ['maintenanceTypes'] });
  1176. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1177. showToast(t('maintenance.defaultsRestored', { count: data.restored }));
  1178. },
  1179. onError: (error: Error) => {
  1180. showToast(error.message, 'error');
  1181. },
  1182. });
  1183. const setHoursMutation = useMutation({
  1184. mutationFn: ({ printerId, hours }: { printerId: number; hours: number }) =>
  1185. api.setPrinterHours(printerId, hours),
  1186. onSuccess: () => {
  1187. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1188. queryClient.invalidateQueries({ queryKey: ['maintenanceSummary'] });
  1189. showToast(t('maintenance.printHoursUpdated'));
  1190. },
  1191. onError: (error: Error) => {
  1192. showToast(error.message, 'error');
  1193. },
  1194. });
  1195. const assignTypeMutation = useMutation({
  1196. mutationFn: ({ printerId, typeId }: { printerId: number; typeId: number }) =>
  1197. api.assignMaintenanceType(printerId, typeId),
  1198. onSuccess: () => {
  1199. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1200. showToast(t('maintenance.printerAssigned'));
  1201. },
  1202. onError: (error: Error) => {
  1203. showToast(error.message, 'error');
  1204. },
  1205. });
  1206. const removeItemMutation = useMutation({
  1207. mutationFn: api.removeMaintenanceItem,
  1208. onSuccess: () => {
  1209. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1210. showToast(t('maintenance.printerRemoved'));
  1211. },
  1212. onError: (error: Error) => {
  1213. showToast(error.message, 'error');
  1214. },
  1215. });
  1216. const handlePerform = (id: number) => {
  1217. performMutation.mutate({ id });
  1218. };
  1219. const handleToggle = (id: number, enabled: boolean) => {
  1220. updateMutation.mutate({ id, data: { enabled } });
  1221. };
  1222. const handleSetHours = (printerId: number, hours: number) => {
  1223. setHoursMutation.mutate({ printerId, hours });
  1224. };
  1225. if (isLoading) {
  1226. return (
  1227. <div className="p-4 md:p-8 flex justify-center">
  1228. <Loader2 className="w-8 h-8 text-bambu-green animate-spin" />
  1229. </div>
  1230. );
  1231. }
  1232. const totalDue = overview?.reduce((sum, p) => sum + p.due_count, 0) || 0;
  1233. const totalWarning = overview?.reduce((sum, p) => sum + p.warning_count, 0) || 0;
  1234. return (
  1235. <div className="p-4 md:p-8">
  1236. {/* Header */}
  1237. <div className="mb-6">
  1238. <h1 className="text-2xl font-bold text-white">{t('maintenance.title')}</h1>
  1239. <p className="text-bambu-gray text-sm mt-1">
  1240. {activeTab === 'status' ? (
  1241. <>
  1242. {totalDue > 0 && <span className="text-red-400">{t('maintenance.dueCount', { count: totalDue })}</span>}
  1243. {totalDue > 0 && totalWarning > 0 && ' · '}
  1244. {totalWarning > 0 && <span className="text-amber-400">{t('maintenance.warningCount', { count: totalWarning })}</span>}
  1245. {totalDue === 0 && totalWarning === 0 && <span className="text-bambu-green">{t('maintenance.allOk')}</span>}
  1246. </>
  1247. ) : (
  1248. t('maintenance.configureSettings')
  1249. )}
  1250. </p>
  1251. </div>
  1252. {/* Tabs */}
  1253. <div className="flex gap-1 mb-6 border-b border-bambu-dark-tertiary">
  1254. <button
  1255. onClick={() => setActiveTab('status')}
  1256. className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
  1257. activeTab === 'status'
  1258. ? 'text-bambu-green border-bambu-green'
  1259. : 'text-bambu-gray border-transparent hover:text-white'
  1260. }`}
  1261. >
  1262. {t('maintenance.statusTab')}
  1263. </button>
  1264. <button
  1265. onClick={() => setActiveTab('settings')}
  1266. className={`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${
  1267. activeTab === 'settings'
  1268. ? 'text-bambu-green border-bambu-green'
  1269. : 'text-bambu-gray border-transparent hover:text-white'
  1270. }`}
  1271. >
  1272. {t('maintenance.settingsTab')}
  1273. </button>
  1274. </div>
  1275. {/* Tab content */}
  1276. {activeTab === 'status' ? (
  1277. <div className="space-y-6">
  1278. {overview && overview.length > 0 ? (
  1279. [...overview].sort((a, b) => {
  1280. // Sort printers with issues first
  1281. const aScore = a.due_count * 10 + a.warning_count;
  1282. const bScore = b.due_count * 10 + b.warning_count;
  1283. if (aScore !== bScore) return bScore - aScore;
  1284. return a.printer_name.localeCompare(b.printer_name);
  1285. }).map((printerOverview) => (
  1286. <PrinterSection
  1287. key={printerOverview.printer_id}
  1288. overview={printerOverview}
  1289. onPerform={handlePerform}
  1290. onToggle={handleToggle}
  1291. onSetHours={handleSetHours}
  1292. hasPermission={hasPermission}
  1293. t={t}
  1294. />
  1295. ))
  1296. ) : (
  1297. <Card>
  1298. <CardContent className="text-center py-16">
  1299. <Wrench className="w-16 h-16 mx-auto mb-4 text-bambu-gray/30" />
  1300. <p className="text-lg font-medium text-white mb-2">{t('common.noPrinters')}</p>
  1301. <p className="text-bambu-gray">{t('maintenance.configureSettings')}</p>
  1302. </CardContent>
  1303. </Card>
  1304. )}
  1305. </div>
  1306. ) : (
  1307. <SettingsSection
  1308. overview={overview}
  1309. types={types || []}
  1310. onUpdateInterval={(id, data) =>
  1311. updateMutation.mutate({ id, data })
  1312. }
  1313. onAddType={async (data, printerIds) => {
  1314. // Create the type first, then assign to selected printers
  1315. const newType = await api.createMaintenanceType(data);
  1316. // Assign to each selected printer
  1317. for (const printerId of printerIds) {
  1318. await api.assignMaintenanceType(printerId, newType.id);
  1319. }
  1320. queryClient.invalidateQueries({ queryKey: ['maintenanceTypes'] });
  1321. queryClient.invalidateQueries({ queryKey: ['maintenanceOverview'] });
  1322. showToast(t('maintenance.typeUpdated'));
  1323. }}
  1324. onUpdateType={(id, data) => updateTypeMutation.mutate({ id, data })}
  1325. onDeleteType={(id) => deleteTypeMutation.mutate(id)}
  1326. onRestoreDefaults={() => restoreDefaultsMutation.mutate()}
  1327. isRestoringDefaults={restoreDefaultsMutation.isPending}
  1328. onAssignType={(printerId, typeId) => assignTypeMutation.mutate({ printerId, typeId })}
  1329. onRemoveItem={(itemId) => removeItemMutation.mutate(itemId)}
  1330. hasPermission={hasPermission}
  1331. t={t}
  1332. />
  1333. )}
  1334. </div>
  1335. );
  1336. }