maintenance.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. """Maintenance tracking API routes."""
  2. import logging
  3. from datetime import datetime
  4. from typing import List
  5. from fastapi import APIRouter, Depends, HTTPException
  6. from sqlalchemy import select, func
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from sqlalchemy.orm import selectinload
  9. from backend.app.core.database import get_db
  10. from backend.app.models.maintenance import MaintenanceType, PrinterMaintenance, MaintenanceHistory
  11. from backend.app.models.printer import Printer
  12. from backend.app.models.archive import PrintArchive
  13. from backend.app.services.notification_service import notification_service
  14. from backend.app.schemas.maintenance import (
  15. MaintenanceTypeCreate,
  16. MaintenanceTypeUpdate,
  17. MaintenanceTypeResponse,
  18. PrinterMaintenanceCreate,
  19. PrinterMaintenanceUpdate,
  20. PrinterMaintenanceResponse,
  21. MaintenanceHistoryResponse,
  22. MaintenanceStatus,
  23. PrinterMaintenanceOverview,
  24. PerformMaintenanceRequest,
  25. )
  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 print hours for a printer from archives plus offset."""
  69. # Get archive hours
  70. result = await db.execute(
  71. select(func.sum(PrintArchive.print_time_seconds))
  72. .where(PrintArchive.printer_id == printer_id)
  73. .where(PrintArchive.status == "completed")
  74. )
  75. total_seconds = result.scalar() or 0
  76. archive_hours = total_seconds / 3600.0
  77. # Get printer offset
  78. result = await db.execute(
  79. select(Printer.print_hours_offset).where(Printer.id == printer_id)
  80. )
  81. offset = result.scalar() or 0.0
  82. return archive_hours + offset
  83. async def ensure_default_types(db: AsyncSession) -> None:
  84. """Ensure default maintenance types exist."""
  85. result = await db.execute(
  86. select(MaintenanceType).where(MaintenanceType.is_system == True)
  87. )
  88. existing = result.scalars().all()
  89. existing_names = {t.name for t in existing}
  90. for type_def in DEFAULT_MAINTENANCE_TYPES:
  91. if type_def["name"] not in existing_names:
  92. new_type = MaintenanceType(
  93. name=type_def["name"],
  94. description=type_def["description"],
  95. default_interval_hours=type_def["default_interval_hours"],
  96. icon=type_def["icon"],
  97. is_system=True,
  98. )
  99. db.add(new_type)
  100. await db.commit()
  101. # ============== Maintenance Types ==============
  102. @router.get("/types", response_model=List[MaintenanceTypeResponse])
  103. async def get_maintenance_types(db: AsyncSession = Depends(get_db)):
  104. """Get all maintenance types."""
  105. await ensure_default_types(db)
  106. result = await db.execute(
  107. select(MaintenanceType).order_by(MaintenanceType.is_system.desc(), MaintenanceType.name)
  108. )
  109. return result.scalars().all()
  110. @router.post("/types", response_model=MaintenanceTypeResponse)
  111. async def create_maintenance_type(
  112. data: MaintenanceTypeCreate,
  113. db: AsyncSession = Depends(get_db),
  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. ):
  134. """Update a maintenance type."""
  135. result = await db.execute(
  136. select(MaintenanceType).where(MaintenanceType.id == type_id)
  137. )
  138. maint_type = result.scalar_one_or_none()
  139. if not maint_type:
  140. raise HTTPException(status_code=404, detail="Maintenance type not found")
  141. update_data = data.model_dump(exclude_unset=True)
  142. for key, value in update_data.items():
  143. setattr(maint_type, key, value)
  144. await db.commit()
  145. await db.refresh(maint_type)
  146. return maint_type
  147. @router.delete("/types/{type_id}")
  148. async def delete_maintenance_type(
  149. type_id: int,
  150. db: AsyncSession = Depends(get_db),
  151. ):
  152. """Delete a custom maintenance type."""
  153. result = await db.execute(
  154. select(MaintenanceType).where(MaintenanceType.id == type_id)
  155. )
  156. maint_type = result.scalar_one_or_none()
  157. if not maint_type:
  158. raise HTTPException(status_code=404, detail="Maintenance type not found")
  159. if maint_type.is_system:
  160. raise HTTPException(status_code=400, detail="Cannot delete system maintenance type")
  161. await db.delete(maint_type)
  162. await db.commit()
  163. return {"status": "deleted"}
  164. # ============== Printer Maintenance ==============
  165. async def _get_printer_maintenance_internal(
  166. printer_id: int,
  167. db: AsyncSession,
  168. commit: bool = True,
  169. ) -> PrinterMaintenanceOverview:
  170. """Internal helper to get maintenance overview for a specific printer."""
  171. await ensure_default_types(db)
  172. # Get printer
  173. result = await db.execute(
  174. select(Printer).where(Printer.id == printer_id)
  175. )
  176. printer = result.scalar_one_or_none()
  177. if not printer:
  178. raise HTTPException(status_code=404, detail="Printer not found")
  179. total_hours = await get_printer_total_hours(db, printer_id)
  180. # Get all maintenance types
  181. result = await db.execute(select(MaintenanceType))
  182. all_types = result.scalars().all()
  183. # Get printer's maintenance items
  184. result = await db.execute(
  185. select(PrinterMaintenance)
  186. .where(PrinterMaintenance.printer_id == printer_id)
  187. .options(selectinload(PrinterMaintenance.maintenance_type))
  188. )
  189. existing_items = {item.maintenance_type_id: item for item in result.scalars().all()}
  190. maintenance_items = []
  191. due_count = 0
  192. warning_count = 0
  193. now = datetime.utcnow()
  194. for maint_type in all_types:
  195. item = existing_items.get(maint_type.id)
  196. default_interval_type = getattr(maint_type, 'interval_type', 'hours') or 'hours'
  197. if item:
  198. interval = item.custom_interval_hours or maint_type.default_interval_hours
  199. # Use custom interval type if set, otherwise use type's default
  200. interval_type = getattr(item, 'custom_interval_type', None) or default_interval_type
  201. enabled = item.enabled
  202. last_performed_hours = item.last_performed_hours
  203. last_performed_at = item.last_performed_at
  204. item_id = item.id
  205. else:
  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(MaintenanceStatus(
  253. id=item_id,
  254. printer_id=printer_id,
  255. printer_name=printer.name,
  256. maintenance_type_id=maint_type.id,
  257. maintenance_type_name=maint_type.name,
  258. maintenance_type_icon=maint_type.icon,
  259. enabled=enabled,
  260. interval_hours=interval,
  261. interval_type=interval_type,
  262. current_hours=total_hours,
  263. hours_since_maintenance=hours_since,
  264. hours_until_due=hours_until,
  265. days_since_maintenance=days_since if interval_type == "days" else None,
  266. days_until_due=days_until if interval_type == "days" else None,
  267. is_due=is_due,
  268. is_warning=is_warning,
  269. last_performed_at=last_performed_at,
  270. ))
  271. if commit:
  272. await db.commit()
  273. return PrinterMaintenanceOverview(
  274. printer_id=printer_id,
  275. printer_name=printer.name,
  276. total_print_hours=total_hours,
  277. maintenance_items=maintenance_items,
  278. due_count=due_count,
  279. warning_count=warning_count,
  280. )
  281. @router.get("/printers/{printer_id}", response_model=PrinterMaintenanceOverview)
  282. async def get_printer_maintenance(
  283. printer_id: int,
  284. db: AsyncSession = Depends(get_db),
  285. ):
  286. """Get maintenance overview for a specific printer."""
  287. return await _get_printer_maintenance_internal(printer_id, db, commit=True)
  288. @router.get("/overview", response_model=List[PrinterMaintenanceOverview])
  289. async def get_all_maintenance_overview(db: AsyncSession = Depends(get_db)):
  290. """Get maintenance overview for all active printers."""
  291. await ensure_default_types(db)
  292. result = await db.execute(
  293. select(Printer).where(Printer.is_active == True)
  294. )
  295. printers = result.scalars().all()
  296. overviews = []
  297. for printer in printers:
  298. # Don't commit after each printer, commit once at the end
  299. overview = await _get_printer_maintenance_internal(printer.id, db, commit=False)
  300. overviews.append(overview)
  301. # Commit any new maintenance items created
  302. await db.commit()
  303. return overviews
  304. @router.patch("/items/{item_id}", response_model=PrinterMaintenanceResponse)
  305. async def update_printer_maintenance(
  306. item_id: int,
  307. data: PrinterMaintenanceUpdate,
  308. db: AsyncSession = Depends(get_db),
  309. ):
  310. """Update a printer maintenance item (e.g., custom interval, enabled)."""
  311. result = await db.execute(
  312. select(PrinterMaintenance)
  313. .where(PrinterMaintenance.id == item_id)
  314. .options(selectinload(PrinterMaintenance.maintenance_type))
  315. )
  316. item = result.scalar_one_or_none()
  317. if not item:
  318. raise HTTPException(status_code=404, detail="Maintenance item not found")
  319. update_data = data.model_dump(exclude_unset=True)
  320. for key, value in update_data.items():
  321. setattr(item, key, value)
  322. await db.commit()
  323. await db.refresh(item)
  324. return item
  325. @router.post("/items/{item_id}/perform", response_model=MaintenanceStatus)
  326. async def perform_maintenance(
  327. item_id: int,
  328. data: PerformMaintenanceRequest,
  329. db: AsyncSession = Depends(get_db),
  330. ):
  331. """Mark maintenance as performed (reset the counter)."""
  332. result = await db.execute(
  333. select(PrinterMaintenance)
  334. .where(PrinterMaintenance.id == item_id)
  335. .options(selectinload(PrinterMaintenance.maintenance_type))
  336. )
  337. item = result.scalar_one_or_none()
  338. if not item:
  339. raise HTTPException(status_code=404, detail="Maintenance item not found")
  340. # Get printer for name
  341. result = await db.execute(
  342. select(Printer).where(Printer.id == item.printer_id)
  343. )
  344. printer = result.scalar_one()
  345. # Get current hours
  346. current_hours = await get_printer_total_hours(db, item.printer_id)
  347. # Create history entry
  348. history = MaintenanceHistory(
  349. printer_maintenance_id=item.id,
  350. hours_at_maintenance=current_hours,
  351. notes=data.notes,
  352. )
  353. db.add(history)
  354. # Update item
  355. item.last_performed_at = datetime.utcnow()
  356. item.last_performed_hours = current_hours
  357. await db.commit()
  358. # Calculate status
  359. interval = item.custom_interval_hours or item.maintenance_type.default_interval_hours
  360. interval_type = getattr(item.maintenance_type, 'interval_type', 'hours') or 'hours'
  361. hours_since = current_hours - item.last_performed_hours
  362. hours_until = interval - hours_since
  363. return MaintenanceStatus(
  364. id=item.id,
  365. printer_id=item.printer_id,
  366. printer_name=printer.name,
  367. maintenance_type_id=item.maintenance_type_id,
  368. maintenance_type_name=item.maintenance_type.name,
  369. maintenance_type_icon=item.maintenance_type.icon,
  370. enabled=item.enabled,
  371. interval_hours=interval,
  372. interval_type=interval_type,
  373. current_hours=current_hours,
  374. hours_since_maintenance=hours_since,
  375. hours_until_due=hours_until if interval_type == "hours" else 0,
  376. days_since_maintenance=0 if interval_type == "days" else None,
  377. days_until_due=interval if interval_type == "days" else None,
  378. is_due=False,
  379. is_warning=False,
  380. last_performed_at=item.last_performed_at,
  381. )
  382. @router.get("/items/{item_id}/history", response_model=List[MaintenanceHistoryResponse])
  383. async def get_maintenance_history(
  384. item_id: int,
  385. db: AsyncSession = Depends(get_db),
  386. ):
  387. """Get maintenance history for a specific item."""
  388. result = await db.execute(
  389. select(MaintenanceHistory)
  390. .where(MaintenanceHistory.printer_maintenance_id == item_id)
  391. .order_by(MaintenanceHistory.performed_at.desc())
  392. )
  393. return result.scalars().all()
  394. @router.get("/summary")
  395. async def get_maintenance_summary(db: AsyncSession = Depends(get_db)):
  396. """Get a summary of maintenance status across all printers."""
  397. await ensure_default_types(db)
  398. result = await db.execute(
  399. select(Printer).where(Printer.is_active == True)
  400. )
  401. printers = result.scalars().all()
  402. total_due = 0
  403. total_warning = 0
  404. printers_with_issues = []
  405. for printer in printers:
  406. overview = await get_printer_maintenance(printer.id, db)
  407. total_due += overview.due_count
  408. total_warning += overview.warning_count
  409. if overview.due_count > 0 or overview.warning_count > 0:
  410. printers_with_issues.append({
  411. "printer_id": printer.id,
  412. "printer_name": printer.name,
  413. "due_count": overview.due_count,
  414. "warning_count": overview.warning_count,
  415. })
  416. return {
  417. "total_due": total_due,
  418. "total_warning": total_warning,
  419. "printers_with_issues": printers_with_issues,
  420. }
  421. @router.patch("/printers/{printer_id}/hours")
  422. async def set_printer_hours(
  423. printer_id: int,
  424. total_hours: float,
  425. db: AsyncSession = Depends(get_db),
  426. ):
  427. """Set the total print hours for a printer (adjusts offset to match)."""
  428. # Get printer
  429. result = await db.execute(
  430. select(Printer).where(Printer.id == printer_id)
  431. )
  432. printer = result.scalar_one_or_none()
  433. if not printer:
  434. raise HTTPException(status_code=404, detail="Printer not found")
  435. # Get current archive hours
  436. result = await db.execute(
  437. select(func.sum(PrintArchive.print_time_seconds))
  438. .where(PrintArchive.printer_id == printer_id)
  439. .where(PrintArchive.status == "completed")
  440. )
  441. total_seconds = result.scalar() or 0
  442. archive_hours = total_seconds / 3600.0
  443. # Calculate needed offset
  444. printer.print_hours_offset = max(0, total_hours - archive_hours)
  445. await db.commit()
  446. # Check for maintenance items that need attention and send notification
  447. try:
  448. await ensure_default_types(db)
  449. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  450. items_needing_attention = [
  451. {
  452. "name": item.maintenance_type_name,
  453. "is_due": item.is_due,
  454. "is_warning": item.is_warning,
  455. }
  456. for item in overview.maintenance_items
  457. if item.enabled and (item.is_due or item.is_warning)
  458. ]
  459. if items_needing_attention:
  460. await notification_service.on_maintenance_due(
  461. printer_id, printer.name, items_needing_attention, db
  462. )
  463. logger.info(
  464. f"Sent maintenance notification for printer {printer_id}: "
  465. f"{len(items_needing_attention)} items need attention"
  466. )
  467. except Exception as e:
  468. logger.warning(f"Failed to send maintenance notification: {e}")
  469. return {
  470. "printer_id": printer_id,
  471. "total_hours": total_hours,
  472. "archive_hours": archive_hours,
  473. "offset_hours": printer.print_hours_offset,
  474. }