maintenance.py 25 KB

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