maintenance.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  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. async def _get_printer_maintenance_internal(
  249. printer_id: int,
  250. db: AsyncSession,
  251. commit: bool = True,
  252. ) -> PrinterMaintenanceOverview:
  253. """Internal helper to get maintenance overview for a specific printer."""
  254. await ensure_default_types(db)
  255. # Get printer
  256. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  257. printer = result.scalar_one_or_none()
  258. if not printer:
  259. raise HTTPException(status_code=404, detail="Printer not found")
  260. total_hours = await get_printer_total_hours(db, printer_id)
  261. # Get all maintenance types
  262. result = await db.execute(select(MaintenanceType).where(MaintenanceType.is_deleted.is_(False)))
  263. all_types = result.scalars().all()
  264. # Get printer's maintenance items
  265. result = await db.execute(
  266. select(PrinterMaintenance)
  267. .where(PrinterMaintenance.printer_id == printer_id)
  268. .options(selectinload(PrinterMaintenance.maintenance_type))
  269. )
  270. existing_items = {item.maintenance_type_id: item for item in result.scalars().all()}
  271. maintenance_items = []
  272. due_count = 0
  273. warning_count = 0
  274. now = datetime.now(timezone.utc)
  275. for maint_type in all_types:
  276. # Skip system types that don't apply to this printer model
  277. # (e.g., "Clean Carbon Rods" for H2D which has steel rods)
  278. if maint_type.is_system and not _should_apply_to_printer(maint_type.name, printer.model):
  279. continue
  280. item = existing_items.get(maint_type.id)
  281. default_interval_type = getattr(maint_type, "interval_type", "hours") or "hours"
  282. if item:
  283. interval = item.custom_interval_hours or maint_type.default_interval_hours
  284. # Use custom interval type if set, otherwise use type's default
  285. interval_type = getattr(item, "custom_interval_type", None) or default_interval_type
  286. enabled = item.enabled
  287. last_performed_hours = item.last_performed_hours
  288. last_performed_at = item.last_performed_at
  289. item_id = item.id
  290. else:
  291. # Only auto-create maintenance items for system types
  292. # Custom types need to be manually assigned per printer
  293. if not maint_type.is_system:
  294. continue
  295. # Create default entry for this printer/type
  296. item = PrinterMaintenance(
  297. printer_id=printer_id,
  298. maintenance_type_id=maint_type.id,
  299. enabled=True,
  300. last_performed_hours=0.0,
  301. )
  302. db.add(item)
  303. await db.flush()
  304. interval = maint_type.default_interval_hours
  305. interval_type = default_interval_type
  306. enabled = True
  307. last_performed_hours = 0.0
  308. last_performed_at = None
  309. item_id = item.id
  310. # Calculate status based on interval type
  311. if interval_type == "days":
  312. # Time-based: calculate days since last performed
  313. if last_performed_at:
  314. # DB stores naive datetimes; treat as UTC for comparison
  315. if last_performed_at.tzinfo is None:
  316. last_performed_at = last_performed_at.replace(tzinfo=timezone.utc)
  317. days_since = (now - last_performed_at).total_seconds() / 86400.0
  318. else:
  319. # Never performed - consider it due
  320. days_since = interval + 1
  321. days_until = interval - days_since
  322. is_due = days_until <= 0
  323. is_warning = days_until <= (interval * 0.1) and not is_due
  324. # For compatibility, also set hours values (but they won't be primary)
  325. hours_since = total_hours - last_performed_hours
  326. hours_until = 0 # Not applicable for time-based
  327. else:
  328. # Print-hours based (default)
  329. hours_since = total_hours - last_performed_hours
  330. hours_until = interval - hours_since
  331. is_due = hours_until <= 0
  332. is_warning = hours_until <= (interval * 0.1) and not is_due
  333. # Calculate days for reference
  334. if last_performed_at:
  335. if last_performed_at.tzinfo is None:
  336. last_performed_at = last_performed_at.replace(tzinfo=timezone.utc)
  337. days_since = (now - last_performed_at).total_seconds() / 86400.0
  338. else:
  339. days_since = None
  340. days_until = None
  341. if enabled:
  342. if is_due:
  343. due_count += 1
  344. elif is_warning:
  345. warning_count += 1
  346. maintenance_items.append(
  347. MaintenanceStatus(
  348. id=item_id,
  349. printer_id=printer_id,
  350. printer_name=printer.name,
  351. printer_model=printer.model,
  352. maintenance_type_id=maint_type.id,
  353. maintenance_type_name=maint_type.name,
  354. maintenance_type_icon=maint_type.icon,
  355. maintenance_type_wiki_url=getattr(maint_type, "wiki_url", None),
  356. enabled=enabled,
  357. interval_hours=interval,
  358. interval_type=interval_type,
  359. current_hours=total_hours,
  360. hours_since_maintenance=hours_since,
  361. hours_until_due=hours_until,
  362. days_since_maintenance=days_since if interval_type == "days" else None,
  363. days_until_due=days_until if interval_type == "days" else None,
  364. is_due=is_due,
  365. is_warning=is_warning,
  366. last_performed_at=last_performed_at,
  367. )
  368. )
  369. if commit:
  370. await db.commit()
  371. return PrinterMaintenanceOverview(
  372. printer_id=printer_id,
  373. printer_name=printer.name,
  374. printer_model=printer.model,
  375. total_print_hours=total_hours,
  376. maintenance_items=maintenance_items,
  377. due_count=due_count,
  378. warning_count=warning_count,
  379. )
  380. @router.get("/printers/{printer_id}", response_model=PrinterMaintenanceOverview)
  381. async def get_printer_maintenance(
  382. printer_id: int,
  383. db: AsyncSession = Depends(get_db),
  384. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  385. ):
  386. """Get maintenance overview for a specific printer."""
  387. return await _get_printer_maintenance_internal(printer_id, db, commit=True)
  388. @router.get("/overview", response_model=list[PrinterMaintenanceOverview])
  389. async def get_all_maintenance_overview(
  390. db: AsyncSession = Depends(get_db),
  391. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  392. printer_scope: PrinterScope = RequestPrinterScope,
  393. ):
  394. """Get maintenance overview for all active printers."""
  395. await ensure_default_types(db)
  396. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  397. printers = [p for p in result.scalars().all() if printer_scope.allows(p.id)]
  398. overviews = []
  399. for printer in printers:
  400. # Don't commit after each printer, commit once at the end
  401. overview = await _get_printer_maintenance_internal(printer.id, db, commit=False)
  402. overviews.append(overview)
  403. # Commit any new maintenance items created
  404. await db.commit()
  405. return overviews
  406. @router.patch("/items/{item_id}", response_model=PrinterMaintenanceResponse)
  407. async def update_printer_maintenance(
  408. item_id: int,
  409. data: PrinterMaintenanceUpdate,
  410. db: AsyncSession = Depends(get_db),
  411. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  412. printer_scope: PrinterScope = RequestPrinterScope,
  413. ):
  414. """Update a printer maintenance item (e.g., custom interval, enabled)."""
  415. result = await db.execute(
  416. select(PrinterMaintenance)
  417. .where(PrinterMaintenance.id == item_id)
  418. .options(selectinload(PrinterMaintenance.maintenance_type))
  419. )
  420. item = result.scalar_one_or_none()
  421. if not item or not printer_scope.allows(item.printer_id):
  422. raise HTTPException(status_code=404, detail="Maintenance item not found")
  423. update_data = data.model_dump(exclude_unset=True)
  424. for key, value in update_data.items():
  425. setattr(item, key, value)
  426. await db.commit()
  427. await db.refresh(item)
  428. return item
  429. @router.post("/printers/{printer_id}/assign/{type_id}", response_model=PrinterMaintenanceResponse)
  430. async def assign_maintenance_type(
  431. printer_id: int,
  432. type_id: int,
  433. db: AsyncSession = Depends(get_db),
  434. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_CREATE),
  435. ):
  436. """Assign a maintenance type to a specific printer (for custom types)."""
  437. # Verify printer exists
  438. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  439. printer = result.scalar_one_or_none()
  440. if not printer:
  441. raise HTTPException(status_code=404, detail="Printer not found")
  442. # Verify maintenance type exists
  443. result = await db.execute(select(MaintenanceType).where(MaintenanceType.id == type_id))
  444. maint_type = result.scalar_one_or_none()
  445. if not maint_type:
  446. raise HTTPException(status_code=404, detail="Maintenance type not found")
  447. # Check if already assigned
  448. result = await db.execute(
  449. select(PrinterMaintenance).where(
  450. PrinterMaintenance.printer_id == printer_id,
  451. PrinterMaintenance.maintenance_type_id == type_id,
  452. )
  453. )
  454. existing = result.scalar_one_or_none()
  455. if existing:
  456. raise HTTPException(status_code=400, detail="Maintenance type already assigned to this printer")
  457. # Create the assignment
  458. item = PrinterMaintenance(
  459. printer_id=printer_id,
  460. maintenance_type_id=type_id,
  461. enabled=True,
  462. last_performed_hours=0.0,
  463. )
  464. db.add(item)
  465. await db.commit()
  466. # Re-fetch with relationship loaded for response serialization
  467. from sqlalchemy.orm import selectinload
  468. result = await db.execute(
  469. select(PrinterMaintenance)
  470. .options(selectinload(PrinterMaintenance.maintenance_type))
  471. .where(PrinterMaintenance.id == item.id)
  472. )
  473. item = result.scalar_one()
  474. return item
  475. @router.delete("/items/{item_id}")
  476. async def remove_maintenance_item(
  477. item_id: int,
  478. db: AsyncSession = Depends(get_db),
  479. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
  480. printer_scope: PrinterScope = RequestPrinterScope,
  481. ):
  482. """Remove a maintenance item (unassign a custom type from a printer)."""
  483. result = await db.execute(
  484. select(PrinterMaintenance)
  485. .where(PrinterMaintenance.id == item_id)
  486. .options(selectinload(PrinterMaintenance.maintenance_type))
  487. )
  488. item = result.scalar_one_or_none()
  489. if not item or not printer_scope.allows(item.printer_id):
  490. raise HTTPException(status_code=404, detail="Maintenance item not found")
  491. # Only allow removing custom (non-system) types
  492. if item.maintenance_type.is_system:
  493. raise HTTPException(status_code=400, detail="Cannot remove system maintenance types")
  494. await db.delete(item)
  495. await db.commit()
  496. return {"status": "removed"}
  497. @router.post("/items/{item_id}/perform", response_model=MaintenanceStatus)
  498. async def perform_maintenance(
  499. item_id: int,
  500. data: PerformMaintenanceRequest,
  501. db: AsyncSession = Depends(get_db),
  502. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  503. printer_scope: PrinterScope = RequestPrinterScope,
  504. ):
  505. """Mark maintenance as performed (reset the counter)."""
  506. result = await db.execute(
  507. select(PrinterMaintenance)
  508. .where(PrinterMaintenance.id == item_id)
  509. .options(selectinload(PrinterMaintenance.maintenance_type))
  510. )
  511. item = result.scalar_one_or_none()
  512. if not item or not printer_scope.allows(item.printer_id):
  513. raise HTTPException(status_code=404, detail="Maintenance item not found")
  514. # Get printer for name
  515. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  516. printer = result.scalar_one()
  517. # Get current hours
  518. current_hours = await get_printer_total_hours(db, item.printer_id)
  519. # Create history entry
  520. history = MaintenanceHistory(
  521. printer_maintenance_id=item.id,
  522. hours_at_maintenance=current_hours,
  523. notes=data.notes,
  524. )
  525. db.add(history)
  526. # Update item
  527. item.last_performed_at = datetime.now(timezone.utc)
  528. item.last_performed_hours = current_hours
  529. await db.commit()
  530. # MQTT relay - publish maintenance reset
  531. try:
  532. from backend.app.services.mqtt_relay import mqtt_relay
  533. await mqtt_relay.on_maintenance_reset(
  534. printer_id=item.printer_id,
  535. printer_name=printer.name,
  536. maintenance_type=item.maintenance_type.name,
  537. )
  538. except Exception:
  539. pass # Don't fail if MQTT fails
  540. # Calculate status
  541. interval = item.custom_interval_hours or item.maintenance_type.default_interval_hours
  542. interval_type = getattr(item.maintenance_type, "interval_type", "hours") or "hours"
  543. hours_since = current_hours - item.last_performed_hours
  544. hours_until = interval - hours_since
  545. return MaintenanceStatus(
  546. id=item.id,
  547. printer_id=item.printer_id,
  548. printer_name=printer.name,
  549. printer_model=printer.model,
  550. maintenance_type_id=item.maintenance_type_id,
  551. maintenance_type_name=item.maintenance_type.name,
  552. maintenance_type_icon=item.maintenance_type.icon,
  553. maintenance_type_wiki_url=getattr(item.maintenance_type, "wiki_url", None),
  554. enabled=item.enabled,
  555. interval_hours=interval,
  556. interval_type=interval_type,
  557. current_hours=current_hours,
  558. hours_since_maintenance=hours_since,
  559. hours_until_due=hours_until if interval_type == "hours" else 0,
  560. days_since_maintenance=0 if interval_type == "days" else None,
  561. days_until_due=interval if interval_type == "days" else None,
  562. is_due=False,
  563. is_warning=False,
  564. last_performed_at=item.last_performed_at,
  565. )
  566. @router.get("/items/{item_id}/history", response_model=list[MaintenanceHistoryResponse])
  567. async def get_maintenance_history(
  568. item_id: int,
  569. db: AsyncSession = Depends(get_db),
  570. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  571. printer_scope: PrinterScope = RequestPrinterScope,
  572. ):
  573. """Get maintenance history for a specific item."""
  574. item_printer_id = (
  575. await db.execute(select(PrinterMaintenance.printer_id).where(PrinterMaintenance.id == item_id))
  576. ).scalar_one_or_none()
  577. if not printer_scope.allows(item_printer_id):
  578. raise HTTPException(status_code=404, detail="Maintenance item not found")
  579. result = await db.execute(
  580. select(MaintenanceHistory)
  581. .where(MaintenanceHistory.printer_maintenance_id == item_id)
  582. .order_by(MaintenanceHistory.performed_at.desc())
  583. )
  584. return result.scalars().all()
  585. @router.get("/summary")
  586. async def get_maintenance_summary(
  587. db: AsyncSession = Depends(get_db),
  588. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  589. printer_scope: PrinterScope = RequestPrinterScope,
  590. ):
  591. """Get a summary of maintenance status across all printers."""
  592. await ensure_default_types(db)
  593. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  594. printers = [p for p in result.scalars().all() if printer_scope.allows(p.id)]
  595. total_due = 0
  596. total_warning = 0
  597. printers_with_issues = []
  598. for printer in printers:
  599. overview = await get_printer_maintenance(printer.id, db)
  600. total_due += overview.due_count
  601. total_warning += overview.warning_count
  602. if overview.due_count > 0 or overview.warning_count > 0:
  603. printers_with_issues.append(
  604. {
  605. "printer_id": printer.id,
  606. "printer_name": printer.name,
  607. "due_count": overview.due_count,
  608. "warning_count": overview.warning_count,
  609. }
  610. )
  611. return {
  612. "total_due": total_due,
  613. "total_warning": total_warning,
  614. "printers_with_issues": printers_with_issues,
  615. }
  616. @router.patch("/printers/{printer_id}/hours")
  617. async def set_printer_hours(
  618. printer_id: int,
  619. total_hours: float,
  620. db: AsyncSession = Depends(get_db),
  621. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  622. ):
  623. """Set the total print hours for a printer (adjusts offset to match).
  624. The offset is calculated as: offset = total_hours - runtime_hours
  625. Where runtime_hours comes from the runtime_seconds counter that tracks
  626. actual machine active time (RUNNING state only — paused time excluded, #1521).
  627. """
  628. # Get printer
  629. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  630. printer = result.scalar_one_or_none()
  631. if not printer:
  632. raise HTTPException(status_code=404, detail="Printer not found")
  633. # Get current runtime hours
  634. runtime_hours = (printer.runtime_seconds or 0) / 3600.0
  635. # Calculate needed offset
  636. printer.print_hours_offset = max(0, total_hours - runtime_hours)
  637. await db.commit()
  638. # Check for maintenance items that need attention and send notification
  639. try:
  640. await ensure_default_types(db)
  641. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  642. items_needing_attention = [
  643. {
  644. "name": item.maintenance_type_name,
  645. "is_due": item.is_due,
  646. "is_warning": item.is_warning,
  647. }
  648. for item in overview.maintenance_items
  649. if item.enabled and (item.is_due or item.is_warning)
  650. ]
  651. if items_needing_attention:
  652. await notification_service.on_maintenance_due(printer_id, printer.name, items_needing_attention, db)
  653. logger.info(
  654. f"Sent maintenance notification for printer {printer_id}: "
  655. f"{len(items_needing_attention)} items need attention"
  656. )
  657. except Exception as e:
  658. logger.warning("Failed to send maintenance notification: %s", e)
  659. return {
  660. "printer_id": printer_id,
  661. "total_hours": total_hours,
  662. "runtime_hours": runtime_hours,
  663. "offset_hours": printer.print_hours_offset,
  664. }