maintenance.py 27 KB

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