maintenance.py 26 KB

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