MaintenancePage.tsx 62 KB

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