maintenance.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. """Maintenance tracking API routes."""
  2. import logging
  3. from datetime import datetime, timezone
  4. from fastapi import APIRouter, Depends, HTTPException
  5. from sqlalchemy import select
  6. from sqlalchemy.ext.asyncio import AsyncSession
  7. from sqlalchemy.orm import selectinload
  8. from backend.app.core.auth import (
  9. RequestPrinterScope,
  10. RequirePermissionIfAuthEnabled,
  11. RequirePrinterPermissionIfAuthEnabled,
  12. )
  13. from backend.app.core.database import get_db
  14. from backend.app.core.permissions import Permission
  15. from backend.app.core.printer_scope import PrinterScope
  16. from backend.app.models.maintenance import MaintenanceHistory, MaintenanceType, PrinterMaintenance
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.user import User
  19. from backend.app.schemas.maintenance import (
  20. MaintenanceHistoryResponse,
  21. MaintenanceStatus,
  22. MaintenanceTypeCreate,
  23. MaintenanceTypeResponse,
  24. MaintenanceTypeUpdate,
  25. PerformMaintenanceRequest,
  26. PrinterMaintenanceOverview,
  27. PrinterMaintenanceResponse,
  28. PrinterMaintenanceUpdate,
  29. )
  30. from backend.app.services.notification_service import notification_service
  31. from backend.app.utils.printer_models import get_rod_type
  32. logger = logging.getLogger(__name__)
  33. router = APIRouter(prefix="/maintenance", tags=["maintenance"])
  34. # Default maintenance types
  35. DEFAULT_MAINTENANCE_TYPES = [
  36. # Carbon rod models only (X1/P1)
  37. # Note: carbon rods must NOT be lubricated — they use plain bearings
  38. # and lubrication degrades print quality. Only cleaning is offered.
  39. {
  40. "name": "Clean Carbon Rods",
  41. "description": "Wipe carbon rods with a dry cloth",
  42. "default_interval_hours": 100.0,
  43. "icon": "Sparkles",
  44. },
  45. # Steel rod models only (P2S)
  46. {
  47. "name": "Lubricate Steel Rods",
  48. "description": "Apply lubricant to steel rods for smooth motion",
  49. "default_interval_hours": 50.0,
  50. "icon": "Droplet",
  51. },
  52. {
  53. "name": "Clean Steel Rods",
  54. "description": "Wipe steel rods with a dry cloth",
  55. "default_interval_hours": 100.0,
  56. "icon": "Sparkles",
  57. },
  58. # Linear rail models only (A1/H2)
  59. {
  60. "name": "Lubricate Linear Rails",
  61. "description": "Apply lubricant to linear rails for smooth motion",
  62. "default_interval_hours": 50.0,
  63. "icon": "Droplet",
  64. },
  65. {
  66. "name": "Clean Linear Rails",
  67. "description": "Wipe linear rails with a dry cloth to remove dust and debris",
  68. "default_interval_hours": 100.0,
  69. "icon": "Sparkles",
  70. },
  71. # Universal (all models)
  72. {
  73. "name": "Clean Nozzle/Hotend",
  74. "description": "Clean nozzle exterior and perform cold pull if needed",
  75. "default_interval_hours": 100.0,
  76. "icon": "Flame",
  77. },
  78. {
  79. "name": "Check Belt Tension",
  80. "description": "Verify and adjust belt tension for X/Y axes",
  81. "default_interval_hours": 200.0,
  82. "icon": "Ruler",
  83. },
  84. {
  85. "name": "Clean Build Plate",
  86. "description": "Deep clean build plate with IPA or soap",
  87. "default_interval_hours": 25.0,
  88. "icon": "Square",
  89. },
  90. {
  91. "name": "Check PTFE Tube",
  92. "description": "Inspect PTFE tube for wear or discoloration",
  93. "default_interval_hours": 500.0,
  94. "icon": "Cable",
  95. },
  96. ]
  97. # System types that only apply to printers with a specific rod/rail type.
  98. # "carbon" = X1/P1 series (carbon rods), "steel_rod" = P2S (steel rods),
  99. # "linear_rail" = A1/H2 series. Types not listed here apply to all printers.
  100. _ROD_TYPE_REQUIREMENTS: dict[str, str] = {
  101. "Clean Carbon Rods": "carbon",
  102. "Lubricate Steel Rods": "steel_rod",
  103. "Clean Steel Rods": "steel_rod",
  104. "Lubricate Linear Rails": "linear_rail",
  105. "Clean Linear Rails": "linear_rail",
  106. }
  107. def _should_apply_to_printer(type_name: str, printer_model: str | None) -> bool:
  108. """Check if a system maintenance type should apply to a given printer model."""
  109. rod_requirement = _ROD_TYPE_REQUIREMENTS.get(type_name)
  110. if rod_requirement is None:
  111. return True # Not model-specific, applies to all
  112. rod_type = get_rod_type(printer_model)
  113. if rod_type is None:
  114. # Unknown model — default to carbon rods (legacy behavior)
  115. return rod_requirement == "carbon"
  116. return rod_type == rod_requirement
  117. async def get_printer_total_hours(db: AsyncSession, printer_id: int) -> float:
  118. """Calculate total active hours for a printer from runtime counter plus offset.
  119. Uses the runtime_seconds counter which tracks actual machine active time
  120. (RUNNING state only — paused time is excluded since maintenance intervals
  121. measure mechanical wear, not wall-clock active time, see #1521).
  122. """
  123. # Get printer runtime and offset
  124. result = await db.execute(
  125. select(Printer.runtime_seconds, Printer.print_hours_offset).where(Printer.id == printer_id)
  126. )
  127. row = result.one_or_none()
  128. if not row:
  129. return 0.0
  130. runtime_seconds = row[0] or 0
  131. offset = row[1] or 0.0
  132. runtime_hours = runtime_seconds / 3600.0
  133. return runtime_hours + offset
  134. async def ensure_default_types(db: AsyncSession) -> None:
  135. """Ensure default maintenance types exist, remove stale/duplicate ones."""
  136. result = await db.execute(
  137. select(MaintenanceType).where(MaintenanceType.is_system.is_(True)).order_by(MaintenanceType.id)
  138. )
  139. existing = result.scalars().all()
  140. default_names = {t["name"] for t in DEFAULT_MAINTENANCE_TYPES}
  141. # Remove stale system types no longer in defaults (e.g. renamed types)
  142. # and deduplicate: if concurrent requests created the same type twice,
  143. # keep only the first (lowest id) and delete the rest.
  144. seen_names: set[str] = set()
  145. for t in existing:
  146. if t.name not in default_names or t.name in seen_names:
  147. await db.delete(t)
  148. else:
  149. seen_names.add(t.name)
  150. # Create any missing default types
  151. for type_def in DEFAULT_MAINTENANCE_TYPES:
  152. if type_def["name"] not in seen_names:
  153. new_type = MaintenanceType(
  154. name=type_def["name"],
  155. description=type_def["description"],
  156. default_interval_hours=type_def["default_interval_hours"],
  157. icon=type_def["icon"],
  158. is_system=True,
  159. )
  160. db.add(new_type)
  161. await db.commit()
  162. # ============== Maintenance Types ==============
  163. @router.get("/types", response_model=list[MaintenanceTypeResponse])
  164. async def get_maintenance_types(
  165. db: AsyncSession = Depends(get_db),
  166. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  167. ):
  168. """Get all maintenance types."""
  169. await ensure_default_types(db)
  170. result = await db.execute(
  171. select(MaintenanceType)
  172. .where(MaintenanceType.is_deleted.is_(False))
  173. .order_by(MaintenanceType.is_system.desc(), MaintenanceType.name)
  174. )
  175. return result.scalars().all()
  176. @router.post("/types", response_model=MaintenanceTypeResponse)
  177. async def create_maintenance_type(
  178. data: MaintenanceTypeCreate,
  179. db: AsyncSession = Depends(get_db),
  180. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_CREATE),
  181. ):
  182. """Create a custom maintenance type."""
  183. new_type = MaintenanceType(
  184. name=data.name,
  185. description=data.description,
  186. default_interval_hours=data.default_interval_hours,
  187. interval_type=data.interval_type,
  188. icon=data.icon,
  189. wiki_url=data.wiki_url,
  190. is_system=False,
  191. )
  192. db.add(new_type)
  193. await db.commit()
  194. await db.refresh(new_type)
  195. return new_type
  196. @router.patch("/types/{type_id}", response_model=MaintenanceTypeResponse)
  197. async def update_maintenance_type(
  198. type_id: int,
  199. data: MaintenanceTypeUpdate,
  200. db: AsyncSession = Depends(get_db),
  201. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  202. ):
  203. """Update a maintenance type."""
  204. result = await db.execute(select(MaintenanceType).where(MaintenanceType.id == type_id))
  205. maint_type = result.scalar_one_or_none()
  206. if not maint_type:
  207. raise HTTPException(status_code=404, detail="Maintenance type not found")
  208. update_data = data.model_dump(exclude_unset=True)
  209. for key, value in update_data.items():
  210. setattr(maint_type, key, value)
  211. await db.commit()
  212. await db.refresh(maint_type)
  213. return maint_type
  214. @router.delete("/types/{type_id}")
  215. async def delete_maintenance_type(
  216. type_id: int,
  217. db: AsyncSession = Depends(get_db),
  218. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
  219. ):
  220. """Delete a maintenance type."""
  221. result = await db.execute(select(MaintenanceType).where(MaintenanceType.id == type_id))
  222. maint_type = result.scalar_one_or_none()
  223. if not maint_type:
  224. raise HTTPException(status_code=404, detail="Maintenance type not found")
  225. if maint_type.is_system:
  226. maint_type.is_deleted = True
  227. await db.commit()
  228. return {"status": "deleted"}
  229. await db.delete(maint_type)
  230. await db.commit()
  231. return {"status": "deleted"}
  232. @router.post("/types/restore-defaults")
  233. async def restore_default_maintenance_types(
  234. db: AsyncSession = Depends(get_db),
  235. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
  236. ):
  237. """Restore deleted default maintenance types."""
  238. await ensure_default_types(db)
  239. result = await db.execute(
  240. select(MaintenanceType).where(MaintenanceType.is_system.is_(True)).where(MaintenanceType.is_deleted.is_(True))
  241. )
  242. deleted_types = result.scalars().all()
  243. for maint_type in deleted_types:
  244. maint_type.is_deleted = False
  245. await db.commit()
  246. return {"restored": len(deleted_types)}
  247. # ============== Printer Maintenance ==============
  248. def maintenance_alert_values(item: MaintenanceStatus) -> tuple[float, float, str]:
  249. """What the MQTT relay's maintenance/alert reports: (value, threshold, unit).
  250. Print-hour items count hours since the last maintenance against the
  251. interval; time-based ones count days, and their interval_hours holds days.
  252. """
  253. if item.interval_type == "days":
  254. return (item.days_since_maintenance or 0.0, item.interval_hours, "days")
  255. return (item.hours_since_maintenance, item.interval_hours, "hours")
  256. async def _get_printer_maintenance_internal(
  257. printer_id: int,
  258. db: AsyncSession,
  259. commit: bool = True,
  260. ) -> PrinterMaintenanceOverview:
  261. """Internal helper to get maintenance overview for a specific printer."""
  262. await ensure_default_types(db)
  263. # Get printer
  264. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  265. printer = result.scalar_one_or_none()
  266. if not printer:
  267. raise HTTPException(status_code=404, detail="Printer not found")
  268. total_hours = await get_printer_total_hours(db, printer_id)
  269. # Get all maintenance types
  270. result = await db.execute(select(MaintenanceType).where(MaintenanceType.is_deleted.is_(False)))
  271. all_types = result.scalars().all()
  272. # Get printer's maintenance items
  273. result = await db.execute(
  274. select(PrinterMaintenance)
  275. .where(PrinterMaintenance.printer_id == printer_id)
  276. .options(selectinload(PrinterMaintenance.maintenance_type))
  277. )
  278. existing_items = {item.maintenance_type_id: item for item in result.scalars().all()}
  279. maintenance_items = []
  280. due_count = 0
  281. warning_count = 0
  282. now = datetime.now(timezone.utc)
  283. for maint_type in all_types:
  284. # Skip system types that don't apply to this printer model
  285. # (e.g., "Clean Carbon Rods" for H2D which has steel rods)
  286. if maint_type.is_system and not _should_apply_to_printer(maint_type.name, printer.model):
  287. continue
  288. item = existing_items.get(maint_type.id)
  289. default_interval_type = getattr(maint_type, "interval_type", "hours") or "hours"
  290. if item:
  291. interval = item.custom_interval_hours or maint_type.default_interval_hours
  292. # Use custom interval type if set, otherwise use type's default
  293. interval_type = getattr(item, "custom_interval_type", None) or default_interval_type
  294. enabled = item.enabled
  295. last_performed_hours = item.last_performed_hours
  296. last_performed_at = item.last_performed_at
  297. item_id = item.id
  298. else:
  299. # Only auto-create maintenance items for system types
  300. # Custom types need to be manually assigned per printer
  301. if not maint_type.is_system:
  302. continue
  303. # Create default entry for this printer/type
  304. item = PrinterMaintenance(
  305. printer_id=printer_id,
  306. maintenance_type_id=maint_type.id,
  307. enabled=True,
  308. last_performed_hours=0.0,
  309. )
  310. db.add(item)
  311. await db.flush()
  312. interval = maint_type.default_interval_hours
  313. interval_type = default_interval_type
  314. enabled = True
  315. last_performed_hours = 0.0
  316. last_performed_at = None
  317. item_id = item.id
  318. # Calculate status based on interval type
  319. if interval_type == "days":
  320. # Time-based: calculate days since last performed
  321. if last_performed_at:
  322. # DB stores naive datetimes; treat as UTC for comparison
  323. if last_performed_at.tzinfo is None:
  324. last_performed_at = last_performed_at.replace(tzinfo=timezone.utc)
  325. days_since = (now - last_performed_at).total_seconds() / 86400.0
  326. else:
  327. # Never performed - consider it due
  328. days_since = interval + 1
  329. days_until = interval - days_since
  330. is_due = days_until <= 0
  331. is_warning = days_until <= (interval * 0.1) and not is_due
  332. # For compatibility, also set hours values (but they won't be primary)
  333. hours_since = total_hours - last_performed_hours
  334. hours_until = 0 # Not applicable for time-based
  335. else:
  336. # Print-hours based (default)
  337. hours_since = total_hours - last_performed_hours
  338. hours_until = interval - hours_since
  339. is_due = hours_until <= 0
  340. is_warning = hours_until <= (interval * 0.1) and not is_due
  341. # Calculate days for reference
  342. if last_performed_at:
  343. if last_performed_at.tzinfo is None:
  344. last_performed_at = last_performed_at.replace(tzinfo=timezone.utc)
  345. days_since = (now - last_performed_at).total_seconds() / 86400.0
  346. else:
  347. days_since = None
  348. days_until = None
  349. if enabled:
  350. if is_due:
  351. due_count += 1
  352. elif is_warning:
  353. warning_count += 1
  354. maintenance_items.append(
  355. MaintenanceStatus(
  356. id=item_id,
  357. printer_id=printer_id,
  358. printer_name=printer.name,
  359. printer_model=printer.model,
  360. maintenance_type_id=maint_type.id,
  361. maintenance_type_name=maint_type.name,
  362. maintenance_type_icon=maint_type.icon,
  363. maintenance_type_wiki_url=getattr(maint_type, "wiki_url", None),
  364. enabled=enabled,
  365. interval_hours=interval,
  366. interval_type=interval_type,
  367. current_hours=total_hours,
  368. hours_since_maintenance=hours_since,
  369. hours_until_due=hours_until,
  370. days_since_maintenance=days_since if interval_type == "days" else None,
  371. days_until_due=days_until if interval_type == "days" else None,
  372. is_due=is_due,
  373. is_warning=is_warning,
  374. last_performed_at=last_performed_at,
  375. )
  376. )
  377. if commit:
  378. await db.commit()
  379. return PrinterMaintenanceOverview(
  380. printer_id=printer_id,
  381. printer_name=printer.name,
  382. printer_model=printer.model,
  383. total_print_hours=total_hours,
  384. maintenance_items=maintenance_items,
  385. due_count=due_count,
  386. warning_count=warning_count,
  387. )
  388. @router.get("/printers/{printer_id}", response_model=PrinterMaintenanceOverview)
  389. async def get_printer_maintenance(
  390. printer_id: int,
  391. db: AsyncSession = Depends(get_db),
  392. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  393. ):
  394. """Get maintenance overview for a specific printer."""
  395. return await _get_printer_maintenance_internal(printer_id, db, commit=True)
  396. @router.get("/overview", response_model=list[PrinterMaintenanceOverview])
  397. async def get_all_maintenance_overview(
  398. db: AsyncSession = Depends(get_db),
  399. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  400. printer_scope: PrinterScope = RequestPrinterScope,
  401. ):
  402. """Get maintenance overview for all active printers."""
  403. await ensure_default_types(db)
  404. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  405. printers = [p for p in result.scalars().all() if printer_scope.allows(p.id)]
  406. overviews = []
  407. for printer in printers:
  408. # Don't commit after each printer, commit once at the end
  409. overview = await _get_printer_maintenance_internal(printer.id, db, commit=False)
  410. overviews.append(overview)
  411. # Commit any new maintenance items created
  412. await db.commit()
  413. return overviews
  414. @router.patch("/items/{item_id}", response_model=PrinterMaintenanceResponse)
  415. async def update_printer_maintenance(
  416. item_id: int,
  417. data: PrinterMaintenanceUpdate,
  418. db: AsyncSession = Depends(get_db),
  419. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  420. printer_scope: PrinterScope = RequestPrinterScope,
  421. ):
  422. """Update a printer maintenance item (e.g., custom interval, enabled)."""
  423. result = await db.execute(
  424. select(PrinterMaintenance)
  425. .where(PrinterMaintenance.id == item_id)
  426. .options(selectinload(PrinterMaintenance.maintenance_type))
  427. )
  428. item = result.scalar_one_or_none()
  429. if not item or not printer_scope.allows(item.printer_id):
  430. raise HTTPException(status_code=404, detail="Maintenance item not found")
  431. update_data = data.model_dump(exclude_unset=True)
  432. for key, value in update_data.items():
  433. setattr(item, key, value)
  434. await db.commit()
  435. await db.refresh(item)
  436. return item
  437. @router.post("/printers/{printer_id}/assign/{type_id}", response_model=PrinterMaintenanceResponse)
  438. async def assign_maintenance_type(
  439. printer_id: int,
  440. type_id: int,
  441. db: AsyncSession = Depends(get_db),
  442. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_CREATE),
  443. ):
  444. """Assign a maintenance type to a specific printer (for custom types)."""
  445. # Verify printer exists
  446. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  447. printer = result.scalar_one_or_none()
  448. if not printer:
  449. raise HTTPException(status_code=404, detail="Printer not found")
  450. # Verify maintenance type exists
  451. result = await db.execute(select(MaintenanceType).where(MaintenanceType.id == type_id))
  452. maint_type = result.scalar_one_or_none()
  453. if not maint_type:
  454. raise HTTPException(status_code=404, detail="Maintenance type not found")
  455. # Check if already assigned
  456. result = await db.execute(
  457. select(PrinterMaintenance).where(
  458. PrinterMaintenance.printer_id == printer_id,
  459. PrinterMaintenance.maintenance_type_id == type_id,
  460. )
  461. )
  462. existing = result.scalar_one_or_none()
  463. if existing:
  464. raise HTTPException(status_code=400, detail="Maintenance type already assigned to this printer")
  465. # Create the assignment
  466. item = PrinterMaintenance(
  467. printer_id=printer_id,
  468. maintenance_type_id=type_id,
  469. enabled=True,
  470. last_performed_hours=0.0,
  471. )
  472. db.add(item)
  473. await db.commit()
  474. # Re-fetch with relationship loaded for response serialization
  475. from sqlalchemy.orm import selectinload
  476. result = await db.execute(
  477. select(PrinterMaintenance)
  478. .options(selectinload(PrinterMaintenance.maintenance_type))
  479. .where(PrinterMaintenance.id == item.id)
  480. )
  481. item = result.scalar_one()
  482. return item
  483. @router.delete("/items/{item_id}")
  484. async def remove_maintenance_item(
  485. item_id: int,
  486. db: AsyncSession = Depends(get_db),
  487. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
  488. printer_scope: PrinterScope = RequestPrinterScope,
  489. ):
  490. """Remove a maintenance item (unassign a custom type from a printer)."""
  491. result = await db.execute(
  492. select(PrinterMaintenance)
  493. .where(PrinterMaintenance.id == item_id)
  494. .options(selectinload(PrinterMaintenance.maintenance_type))
  495. )
  496. item = result.scalar_one_or_none()
  497. if not item or not printer_scope.allows(item.printer_id):
  498. raise HTTPException(status_code=404, detail="Maintenance item not found")
  499. # Only allow removing custom (non-system) types
  500. if item.maintenance_type.is_system:
  501. raise HTTPException(status_code=400, detail="Cannot remove system maintenance types")
  502. await db.delete(item)
  503. await db.commit()
  504. return {"status": "removed"}
  505. @router.post("/items/{item_id}/perform", response_model=MaintenanceStatus)
  506. async def perform_maintenance(
  507. item_id: int,
  508. data: PerformMaintenanceRequest,
  509. db: AsyncSession = Depends(get_db),
  510. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  511. printer_scope: PrinterScope = RequestPrinterScope,
  512. ):
  513. """Mark maintenance as performed (reset the counter)."""
  514. result = await db.execute(
  515. select(PrinterMaintenance)
  516. .where(PrinterMaintenance.id == item_id)
  517. .options(selectinload(PrinterMaintenance.maintenance_type))
  518. )
  519. item = result.scalar_one_or_none()
  520. if not item or not printer_scope.allows(item.printer_id):
  521. raise HTTPException(status_code=404, detail="Maintenance item not found")
  522. # Get printer for name
  523. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  524. printer = result.scalar_one()
  525. # Get current hours
  526. current_hours = await get_printer_total_hours(db, item.printer_id)
  527. # Create history entry
  528. history = MaintenanceHistory(
  529. printer_maintenance_id=item.id,
  530. hours_at_maintenance=current_hours,
  531. notes=data.notes,
  532. )
  533. db.add(history)
  534. # Update item
  535. item.last_performed_at = datetime.now(timezone.utc)
  536. item.last_performed_hours = current_hours
  537. await db.commit()
  538. # MQTT relay - publish maintenance reset
  539. try:
  540. from backend.app.services.mqtt_relay import mqtt_relay
  541. await mqtt_relay.on_maintenance_reset(
  542. printer_id=item.printer_id,
  543. printer_name=printer.name,
  544. maintenance_type=item.maintenance_type.name,
  545. )
  546. except Exception:
  547. pass # Don't fail if MQTT fails
  548. # Calculate status
  549. interval = item.custom_interval_hours or item.maintenance_type.default_interval_hours
  550. interval_type = getattr(item.maintenance_type, "interval_type", "hours") or "hours"
  551. hours_since = current_hours - item.last_performed_hours
  552. hours_until = interval - hours_since
  553. return MaintenanceStatus(
  554. id=item.id,
  555. printer_id=item.printer_id,
  556. printer_name=printer.name,
  557. printer_model=printer.model,
  558. maintenance_type_id=item.maintenance_type_id,
  559. maintenance_type_name=item.maintenance_type.name,
  560. maintenance_type_icon=item.maintenance_type.icon,
  561. maintenance_type_wiki_url=getattr(item.maintenance_type, "wiki_url", None),
  562. enabled=item.enabled,
  563. interval_hours=interval,
  564. interval_type=interval_type,
  565. current_hours=current_hours,
  566. hours_since_maintenance=hours_since,
  567. hours_until_due=hours_until if interval_type == "hours" else 0,
  568. days_since_maintenance=0 if interval_type == "days" else None,
  569. days_until_due=interval if interval_type == "days" else None,
  570. is_due=False,
  571. is_warning=False,
  572. last_performed_at=item.last_performed_at,
  573. )
  574. @router.get("/items/{item_id}/history", response_model=list[MaintenanceHistoryResponse])
  575. async def get_maintenance_history(
  576. item_id: int,
  577. db: AsyncSession = Depends(get_db),
  578. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  579. printer_scope: PrinterScope = RequestPrinterScope,
  580. ):
  581. """Get maintenance history for a specific item."""
  582. item_printer_id = (
  583. await db.execute(select(PrinterMaintenance.printer_id).where(PrinterMaintenance.id == item_id))
  584. ).scalar_one_or_none()
  585. if not printer_scope.allows(item_printer_id):
  586. raise HTTPException(status_code=404, detail="Maintenance item not found")
  587. result = await db.execute(
  588. select(MaintenanceHistory)
  589. .where(MaintenanceHistory.printer_maintenance_id == item_id)
  590. .order_by(MaintenanceHistory.performed_at.desc())
  591. )
  592. return result.scalars().all()
  593. @router.get("/summary")
  594. async def get_maintenance_summary(
  595. db: AsyncSession = Depends(get_db),
  596. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  597. printer_scope: PrinterScope = RequestPrinterScope,
  598. ):
  599. """Get a summary of maintenance status across all printers."""
  600. await ensure_default_types(db)
  601. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  602. printers = [p for p in result.scalars().all() if printer_scope.allows(p.id)]
  603. total_due = 0
  604. total_warning = 0
  605. printers_with_issues = []
  606. for printer in printers:
  607. overview = await get_printer_maintenance(printer.id, db)
  608. total_due += overview.due_count
  609. total_warning += overview.warning_count
  610. if overview.due_count > 0 or overview.warning_count > 0:
  611. printers_with_issues.append(
  612. {
  613. "printer_id": printer.id,
  614. "printer_name": printer.name,
  615. "due_count": overview.due_count,
  616. "warning_count": overview.warning_count,
  617. }
  618. )
  619. return {
  620. "total_due": total_due,
  621. "total_warning": total_warning,
  622. "printers_with_issues": printers_with_issues,
  623. }
  624. @router.patch("/printers/{printer_id}/hours")
  625. async def set_printer_hours(
  626. printer_id: int,
  627. total_hours: float,
  628. db: AsyncSession = Depends(get_db),
  629. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  630. ):
  631. """Set the total print hours for a printer (adjusts offset to match).
  632. The offset is calculated as: offset = total_hours - runtime_hours
  633. Where runtime_hours comes from the runtime_seconds counter that tracks
  634. actual machine active time (RUNNING state only — paused time excluded, #1521).
  635. """
  636. # Get printer
  637. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  638. printer = result.scalar_one_or_none()
  639. if not printer:
  640. raise HTTPException(status_code=404, detail="Printer not found")
  641. # Get current runtime hours
  642. runtime_hours = (printer.runtime_seconds or 0) / 3600.0
  643. # Calculate needed offset
  644. printer.print_hours_offset = max(0, total_hours - runtime_hours)
  645. await db.commit()
  646. # Check for maintenance items that need attention and send notification
  647. try:
  648. await ensure_default_types(db)
  649. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  650. items_needing_attention = [
  651. {
  652. "name": item.maintenance_type_name,
  653. "is_due": item.is_due,
  654. "is_warning": item.is_warning,
  655. }
  656. for item in overview.maintenance_items
  657. if item.enabled and (item.is_due or item.is_warning)
  658. ]
  659. if items_needing_attention:
  660. await notification_service.on_maintenance_due(printer_id, printer.name, items_needing_attention, db)
  661. logger.info(
  662. f"Sent maintenance notification for printer {printer_id}: "
  663. f"{len(items_needing_attention)} items need attention"
  664. )
  665. except Exception as e:
  666. logger.warning("Failed to send maintenance notification: %s", e)
  667. return {
  668. "printer_id": printer_id,
  669. "total_hours": total_hours,
  670. "runtime_hours": runtime_hours,
  671. "offset_hours": printer.print_hours_offset,
  672. }