maintenance.py 27 KB

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