maintenance.py 23 KB

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