maintenance.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  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.exc import IntegrityError
  7. from sqlalchemy.ext.asyncio import AsyncSession
  8. from sqlalchemy.orm import selectinload
  9. from backend.app.core.auth import (
  10. RequestPrinterScope,
  11. RequirePermissionIfAuthEnabled,
  12. RequirePrinterPermissionIfAuthEnabled,
  13. )
  14. from backend.app.core.database import get_db
  15. from backend.app.core.permissions import Permission
  16. from backend.app.core.printer_scope import PrinterScope
  17. from backend.app.models.maintenance import MaintenanceHistory, MaintenanceType, PrinterMaintenance
  18. from backend.app.models.printer import Printer
  19. from backend.app.models.user import User
  20. from backend.app.schemas.maintenance import (
  21. MaintenanceHistoryResponse,
  22. MaintenanceStatus,
  23. MaintenanceTypeCreate,
  24. MaintenanceTypeResponse,
  25. MaintenanceTypeUpdate,
  26. PerformMaintenanceRequest,
  27. PrinterMaintenanceOverview,
  28. PrinterMaintenanceResponse,
  29. PrinterMaintenanceUpdate,
  30. )
  31. from backend.app.services.notification_service import notification_service
  32. from backend.app.utils.printer_models import get_rod_type, normalize_printer_model_id
  33. logger = logging.getLogger(__name__)
  34. router = APIRouter(prefix="/maintenance", tags=["maintenance"])
  35. # Default maintenance types
  36. DEFAULT_MAINTENANCE_TYPES = [
  37. # Carbon rod models only (X1/P1)
  38. # Note: carbon rods must NOT be lubricated — they use plain bearings
  39. # and lubrication degrades print quality. Only cleaning is offered.
  40. {
  41. "name": "Clean Carbon Rods",
  42. "description": "Wipe carbon rods with a dry cloth",
  43. "default_interval_hours": 100.0,
  44. "icon": "Sparkles",
  45. },
  46. # Steel rod models only (P2S)
  47. {
  48. "name": "Lubricate Steel Rods",
  49. "description": "Apply lubricant to steel rods for smooth motion",
  50. "default_interval_hours": 50.0,
  51. "icon": "Droplet",
  52. },
  53. {
  54. "name": "Clean Steel Rods",
  55. "description": "Wipe steel rods with a dry cloth",
  56. "default_interval_hours": 100.0,
  57. "icon": "Sparkles",
  58. },
  59. # Linear rail models only (A1/H2)
  60. {
  61. "name": "Lubricate Linear Rails",
  62. "description": "Apply lubricant to linear rails for smooth motion",
  63. "default_interval_hours": 50.0,
  64. "icon": "Droplet",
  65. },
  66. {
  67. "name": "Clean Linear Rails",
  68. "description": "Wipe linear rails with a dry cloth to remove dust and debris",
  69. "default_interval_hours": 100.0,
  70. "icon": "Sparkles",
  71. },
  72. # Universal (all models)
  73. {
  74. "name": "Clean Nozzle/Hotend",
  75. "description": "Clean nozzle exterior and perform cold pull if needed",
  76. "default_interval_hours": 100.0,
  77. "icon": "Flame",
  78. },
  79. {
  80. "name": "Check Belt Tension",
  81. "description": "Verify and adjust belt tension for X/Y axes",
  82. "default_interval_hours": 200.0,
  83. "icon": "Ruler",
  84. },
  85. {
  86. "name": "Clean Build Plate",
  87. "description": "Deep clean build plate with IPA or soap",
  88. "default_interval_hours": 25.0,
  89. "icon": "Square",
  90. },
  91. {
  92. "name": "Check PTFE Tube",
  93. "description": "Inspect PTFE tube for wear or discoloration",
  94. "default_interval_hours": 500.0,
  95. "icon": "Cable",
  96. },
  97. ]
  98. # H3C tasks, from Bambu's H3C and AMS 3H maintenance guides. Those give an
  99. # interval only for the air filter (1440 h of printing); the others follow
  100. # Bambu's H2C table (/en/h2c/maintenance/period-maintenance), and the AMS 3H
  101. # ones, which have none published, use conservative defaults. All intervals are
  102. # editable per printer.
  103. _H3C_WIKI = "https://wiki.bambulab.com/en/h3c"
  104. H3C_MAINTENANCE_TYPES = [
  105. {
  106. "name": "Lubricate X/Y Rails (H3C)",
  107. "description": "Wipe old oil and dust off the X and Y guide rails, put a drop of lubricant oil along "
  108. "each (oil only, no grease), then run Vibration Compensation",
  109. "default_interval_hours": 30.0,
  110. "interval_type": "days",
  111. "icon": "Droplet",
  112. "wiki_url": f"{_H3C_WIKI}/maintenance/lubricate-x-y-z-axis",
  113. },
  114. {
  115. "name": "Grease Z Screws (H3C)",
  116. "description": "Wipe and lightly grease all three Z lead screws, wipe and oil the Z linear rods, "
  117. "then run Vibration Compensation",
  118. "default_interval_hours": 90.0,
  119. "interval_type": "days",
  120. "icon": "Droplet",
  121. "wiki_url": f"{_H3C_WIKI}/maintenance/lubricate-x-y-z-axis",
  122. },
  123. {
  124. "name": "Oil XY Idler Pulleys (H3C)",
  125. "description": "Wipe the 12 XY idler pulleys and oil their bearings; sooner if the toolhead gets noisy",
  126. "default_interval_hours": 90.0,
  127. "interval_type": "days",
  128. "icon": "Cog",
  129. "wiki_url": f"{_H3C_WIKI}/maintenance/idle-gear",
  130. },
  131. {
  132. "name": "Grease Toolhead (H3C)",
  133. "description": "Take off the toolhead front-left cover, grease the pitch change cam and the ToolLock pin, "
  134. "and turn both motors with the release socket to spread it",
  135. "default_interval_hours": 90.0,
  136. "interval_type": "days",
  137. "icon": "Wrench",
  138. "wiki_url": f"{_H3C_WIKI}/maintenance/periodic-maintenance",
  139. },
  140. {
  141. "name": "Oil SwapTek Rack (H3C)",
  142. "description": "Wipe both ends of the SwapTek rack hanger, add a drop of lubricating oil to each bearing "
  143. "and push the hanger up and down",
  144. "default_interval_hours": 30.0,
  145. "interval_type": "days",
  146. "icon": "Layers",
  147. "wiki_url": f"{_H3C_WIKI}/maintenance/periodic-maintenance",
  148. },
  149. {
  150. "name": "Clean Hotends (H3C)",
  151. "description": "Fetch each hotend, heat it above the filament's softening point and wipe it "
  152. "with the nozzle cleaning sponge",
  153. "default_interval_hours": 100.0,
  154. "interval_type": "hours",
  155. "icon": "Flame",
  156. "wiki_url": f"{_H3C_WIKI}/maintenance/periodic-maintenance",
  157. },
  158. {
  159. "name": "Clean Extruder Wheel (H3C)",
  160. "description": "Check the toolhead extruder wheel for filament debris and brush it clean",
  161. "default_interval_hours": 7.0,
  162. "interval_type": "days",
  163. "icon": "CircleDot",
  164. "wiki_url": f"{_H3C_WIKI}/troubleshooting/extruder-cleaning-guide",
  165. },
  166. {
  167. "name": "Clean Cameras (H3C)",
  168. "description": "Wipe the live view, toolhead and BirdsEye camera lenses with a cleaning wipe",
  169. "default_interval_hours": 90.0,
  170. "interval_type": "days",
  171. "icon": "Target",
  172. "wiki_url": f"{_H3C_WIKI}/maintenance/periodic-maintenance",
  173. },
  174. {
  175. "name": "Clean Fans (H3C)",
  176. "description": "Brush the dust off the part cooling, hotend cooling and chamber cooling fans",
  177. "default_interval_hours": 90.0,
  178. "interval_type": "days",
  179. "icon": "Fan",
  180. "wiki_url": f"{_H3C_WIKI}/maintenance/periodic-maintenance",
  181. },
  182. {
  183. "name": "Replace Air Filter (H3C)",
  184. "description": "Bambu rates the filter for 1440 hours of printing (about 60 days)",
  185. "default_interval_hours": 1440.0,
  186. "interval_type": "hours",
  187. "icon": "Filter",
  188. "wiki_url": f"{_H3C_WIKI}/maintenance/replace-air-filter",
  189. },
  190. {
  191. "name": "Check Filament Tubes (H3C)",
  192. "description": "Look for tubes bent out of shape behind the purge wiper and for worn AMS 3H tubes; "
  193. "straighten or replace them",
  194. "default_interval_hours": 500.0,
  195. "interval_type": "hours",
  196. "icon": "Cable",
  197. "wiki_url": f"{_H3C_WIKI}/maintenance/periodic-maintenance",
  198. },
  199. {
  200. "name": "AMS 3H: Check Desiccant",
  201. "description": "Check the desiccant on the drying chamber cover; dry or replace it when it is spent",
  202. "default_interval_hours": 30.0,
  203. "interval_type": "days",
  204. "icon": "Wind",
  205. "wiki_url": f"{_H3C_WIKI}/maintenance/ams_3h",
  206. },
  207. {
  208. "name": "AMS 3H: Inlets & Gears",
  209. "description": "Clear filament debris from the inlet funnels, grease the loading gears and the "
  210. "air inlet/outlet flap gears",
  211. "default_interval_hours": 90.0,
  212. "interval_type": "days",
  213. "icon": "Box",
  214. "wiki_url": f"{_H3C_WIKI}/maintenance/ams_3h",
  215. },
  216. {
  217. "name": "AMS 3H: Clean Dryer Fans",
  218. "description": "Unload all filament, lift the AMS 3H off and brush the dust off the heating unit fans",
  219. "default_interval_hours": 180.0,
  220. "interval_type": "days",
  221. "icon": "Thermometer",
  222. "wiki_url": f"{_H3C_WIKI}/maintenance/ams_3h",
  223. },
  224. ]
  225. # System types of one model (short name): seeded and listed only while a
  226. # printer of that model exists, so other installs see just the defaults above.
  227. MODEL_MAINTENANCE_TYPES: dict[str, list[dict]] = {"H3C": H3C_MAINTENANCE_TYPES}
  228. _MODEL_ONLY_TYPES: dict[str, str] = {t["name"]: m for m, types in MODEL_MAINTENANCE_TYPES.items() for t in types}
  229. _H3C_MODELS = frozenset(["H3C"])
  230. # Generic system types a model's own one replaces there.
  231. _REPLACED_ON_MODELS: dict[str, frozenset[str]] = {
  232. "Lubricate Linear Rails": _H3C_MODELS, # -> X/Y rails + Z lead screws
  233. "Clean Linear Rails": _H3C_MODELS, # -> X/Y rails (wiped before oiling)
  234. "Clean Nozzle/Hotend": _H3C_MODELS, # -> Clean Hotends
  235. "Check PTFE Tube": _H3C_MODELS, # -> Check Filament Tubes
  236. }
  237. # System types that only apply to printers with a specific rod/rail type.
  238. # "carbon" = X1/P1 series (carbon rods), "steel_rod" = P2S (steel rods),
  239. # "linear_rail" = A1/H2 series. Types not listed here apply to all printers.
  240. _ROD_TYPE_REQUIREMENTS: dict[str, str] = {
  241. "Clean Carbon Rods": "carbon",
  242. "Lubricate Steel Rods": "steel_rod",
  243. "Clean Steel Rods": "steel_rod",
  244. "Lubricate Linear Rails": "linear_rail",
  245. "Clean Linear Rails": "linear_rail",
  246. }
  247. def _short_model(printer_model: str | None) -> str:
  248. """ "N10" or "H3C" -> "H3C": the short name, uppercase, no spaces or dashes."""
  249. if not printer_model:
  250. return ""
  251. short = normalize_printer_model_id(printer_model.strip()) or ""
  252. return short.upper().replace(" ", "").replace("-", "")
  253. def _should_apply_to_printer(type_name: str, printer_model: str | None) -> bool:
  254. """Check if a system maintenance type should apply to a given printer model."""
  255. model = _short_model(printer_model)
  256. only_on = _MODEL_ONLY_TYPES.get(type_name)
  257. if only_on is not None:
  258. return model == only_on
  259. if model in _REPLACED_ON_MODELS.get(type_name, frozenset()):
  260. return False
  261. rod_requirement = _ROD_TYPE_REQUIREMENTS.get(type_name)
  262. if rod_requirement is None:
  263. return True # Not model-specific, applies to all
  264. rod_type = get_rod_type(printer_model)
  265. if rod_type is None:
  266. # Unknown model — default to carbon rods (legacy behavior)
  267. return rod_requirement == "carbon"
  268. return rod_type == rod_requirement
  269. async def get_printer_total_hours(db: AsyncSession, printer_id: int) -> float:
  270. """Calculate total active hours for a printer from runtime counter plus offset.
  271. Uses the runtime_seconds counter which tracks actual machine active time
  272. (RUNNING state only — paused time is excluded since maintenance intervals
  273. measure mechanical wear, not wall-clock active time, see #1521).
  274. """
  275. # Get printer runtime and offset
  276. result = await db.execute(
  277. select(Printer.runtime_seconds, Printer.print_hours_offset).where(Printer.id == printer_id)
  278. )
  279. row = result.one_or_none()
  280. if not row:
  281. return 0.0
  282. runtime_seconds = row[0] or 0
  283. offset = row[1] or 0.0
  284. runtime_hours = runtime_seconds / 3600.0
  285. return runtime_hours + offset
  286. async def _printer_models_present(db: AsyncSession) -> set[str]:
  287. """The short model names of the printers this install has."""
  288. models = (await db.execute(select(Printer.model).distinct())).scalars().all()
  289. return {_short_model(m) for m in models if m}
  290. def _hidden_model_type(maint_type: MaintenanceType, models_present: set[str]) -> bool:
  291. """A model's own system type while no printer of that model exists."""
  292. model = _MODEL_ONLY_TYPES.get(maint_type.name)
  293. return bool(maint_type.is_system) and model is not None and model not in models_present
  294. async def ensure_default_types(db: AsyncSession) -> None:
  295. """Ensure default maintenance types exist, remove stale/duplicate ones."""
  296. result = await db.execute(
  297. select(MaintenanceType).where(MaintenanceType.is_system.is_(True)).order_by(MaintenanceType.id)
  298. )
  299. existing = result.scalars().all()
  300. models_present = await _printer_models_present(db)
  301. wanted = DEFAULT_MAINTENANCE_TYPES + [
  302. type_def for model, types in MODEL_MAINTENANCE_TYPES.items() if model in models_present for type_def in types
  303. ]
  304. # A model's types are kept (hidden) while no printer of it exists.
  305. default_names = {t["name"] for t in DEFAULT_MAINTENANCE_TYPES} | set(_MODEL_ONLY_TYPES)
  306. # Remove stale system types no longer in defaults (e.g. renamed types)
  307. # and deduplicate: if concurrent requests created the same type twice,
  308. # keep only the first (lowest id) and delete the rest.
  309. seen_names: set[str] = set()
  310. for t in existing:
  311. if t.name not in default_names or t.name in seen_names:
  312. await db.delete(t)
  313. else:
  314. seen_names.add(t.name)
  315. # Create any missing default types
  316. for type_def in wanted:
  317. if type_def["name"] not in seen_names:
  318. new_type = MaintenanceType(
  319. name=type_def["name"],
  320. description=type_def["description"],
  321. default_interval_hours=type_def["default_interval_hours"],
  322. interval_type=type_def.get("interval_type", "hours"),
  323. icon=type_def["icon"],
  324. wiki_url=type_def.get("wiki_url"),
  325. is_system=True,
  326. )
  327. db.add(new_type)
  328. await db.commit()
  329. # ============== Maintenance Types ==============
  330. @router.get("/types", response_model=list[MaintenanceTypeResponse])
  331. async def get_maintenance_types(
  332. db: AsyncSession = Depends(get_db, scope="function"),
  333. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  334. ):
  335. """Get all maintenance types."""
  336. await ensure_default_types(db)
  337. result = await db.execute(
  338. select(MaintenanceType)
  339. .where(MaintenanceType.is_deleted.is_(False))
  340. .order_by(MaintenanceType.is_system.desc(), MaintenanceType.name)
  341. )
  342. models_present = await _printer_models_present(db)
  343. return [t for t in result.scalars().all() if not _hidden_model_type(t, models_present)]
  344. @router.post("/types", response_model=MaintenanceTypeResponse)
  345. async def create_maintenance_type(
  346. data: MaintenanceTypeCreate,
  347. db: AsyncSession = Depends(get_db, scope="function"),
  348. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_CREATE),
  349. ):
  350. """Create a custom maintenance type."""
  351. new_type = MaintenanceType(
  352. name=data.name,
  353. description=data.description,
  354. default_interval_hours=data.default_interval_hours,
  355. interval_type=data.interval_type,
  356. icon=data.icon,
  357. wiki_url=data.wiki_url,
  358. is_system=False,
  359. )
  360. db.add(new_type)
  361. await db.commit()
  362. await db.refresh(new_type)
  363. return new_type
  364. @router.patch("/types/{type_id}", response_model=MaintenanceTypeResponse)
  365. async def update_maintenance_type(
  366. type_id: int,
  367. data: MaintenanceTypeUpdate,
  368. db: AsyncSession = Depends(get_db, scope="function"),
  369. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  370. ):
  371. """Update a maintenance type."""
  372. result = await db.execute(select(MaintenanceType).where(MaintenanceType.id == type_id))
  373. maint_type = result.scalar_one_or_none()
  374. if not maint_type:
  375. raise HTTPException(status_code=404, detail="Maintenance type not found")
  376. update_data = data.model_dump(exclude_unset=True)
  377. for key, value in update_data.items():
  378. setattr(maint_type, key, value)
  379. await db.commit()
  380. await db.refresh(maint_type)
  381. return maint_type
  382. @router.delete("/types/{type_id}")
  383. async def delete_maintenance_type(
  384. type_id: int,
  385. db: AsyncSession = Depends(get_db, scope="function"),
  386. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
  387. ):
  388. """Delete a maintenance type."""
  389. result = await db.execute(select(MaintenanceType).where(MaintenanceType.id == type_id))
  390. maint_type = result.scalar_one_or_none()
  391. if not maint_type:
  392. raise HTTPException(status_code=404, detail="Maintenance type not found")
  393. if maint_type.is_system:
  394. maint_type.is_deleted = True
  395. await db.commit()
  396. return {"status": "deleted"}
  397. await db.delete(maint_type)
  398. await db.commit()
  399. return {"status": "deleted"}
  400. @router.post("/types/restore-defaults")
  401. async def restore_default_maintenance_types(
  402. db: AsyncSession = Depends(get_db, scope="function"),
  403. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
  404. ):
  405. """Restore deleted default maintenance types."""
  406. await ensure_default_types(db)
  407. result = await db.execute(
  408. select(MaintenanceType).where(MaintenanceType.is_system.is_(True)).where(MaintenanceType.is_deleted.is_(True))
  409. )
  410. deleted_types = result.scalars().all()
  411. for maint_type in deleted_types:
  412. maint_type.is_deleted = False
  413. await db.commit()
  414. return {"restored": len(deleted_types)}
  415. # ============== Printer Maintenance ==============
  416. def maintenance_alert_values(item: MaintenanceStatus) -> tuple[float, float, str]:
  417. """What the MQTT relay's maintenance/alert reports: (value, threshold, unit).
  418. Print-hour items count hours since the last maintenance against the
  419. interval; time-based ones count days, and their interval_hours holds days.
  420. """
  421. if item.interval_type == "days":
  422. return (item.days_since_maintenance or 0.0, item.interval_hours, "days")
  423. return (item.hours_since_maintenance, item.interval_hours, "hours")
  424. async def _get_or_create_maintenance_item(db: AsyncSession, printer_id: int, type_id: int) -> PrinterMaintenance:
  425. """The printer's row for this type, created with defaults if missing.
  426. Insert first, in a savepoint: two reads of a new printer (two dashboards,
  427. or a dashboard and the background check) each used to create the row. The
  428. unique index now refuses the second, which takes the first's (FO-C14).
  429. """
  430. item = PrinterMaintenance(
  431. printer_id=printer_id,
  432. maintenance_type_id=type_id,
  433. enabled=True,
  434. last_performed_hours=0.0,
  435. )
  436. try:
  437. async with db.begin_nested():
  438. db.add(item)
  439. await db.flush()
  440. return item
  441. except IntegrityError:
  442. existing = await db.scalar(
  443. select(PrinterMaintenance).where(
  444. PrinterMaintenance.printer_id == printer_id,
  445. PrinterMaintenance.maintenance_type_id == type_id,
  446. )
  447. )
  448. if existing is None:
  449. raise
  450. return existing
  451. def _start_model_task_clock(item: PrinterMaintenance, maint_type: MaintenanceType, printer: Printer, now) -> None:
  452. """Count a model's own task from when the printer was added, not from "never".
  453. Otherwise a new printer's calendar tasks all open as overdue. Fills only an
  454. empty last_performed_at and writes no history row.
  455. """
  456. if maint_type.name in _MODEL_ONLY_TYPES and item.last_performed_at is None:
  457. item.last_performed_at = printer.created_at or now.replace(tzinfo=None)
  458. async def _get_printer_maintenance_internal(
  459. printer_id: int,
  460. db: AsyncSession,
  461. commit: bool = True,
  462. ) -> PrinterMaintenanceOverview:
  463. """Internal helper to get maintenance overview for a specific printer."""
  464. await ensure_default_types(db)
  465. # Get printer
  466. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  467. printer = result.scalar_one_or_none()
  468. if not printer:
  469. raise HTTPException(status_code=404, detail="Printer not found")
  470. total_hours = await get_printer_total_hours(db, printer_id)
  471. # Get all maintenance types
  472. result = await db.execute(select(MaintenanceType).where(MaintenanceType.is_deleted.is_(False)))
  473. all_types = result.scalars().all()
  474. # Get printer's maintenance items
  475. result = await db.execute(
  476. select(PrinterMaintenance)
  477. .where(PrinterMaintenance.printer_id == printer_id)
  478. .options(selectinload(PrinterMaintenance.maintenance_type))
  479. )
  480. existing_items = {item.maintenance_type_id: item for item in result.scalars().all()}
  481. maintenance_items = []
  482. due_count = 0
  483. warning_count = 0
  484. now = datetime.now(timezone.utc)
  485. for maint_type in all_types:
  486. # Skip system types that don't apply to this printer model
  487. # (e.g., "Clean Carbon Rods" for H2D which has steel rods)
  488. if maint_type.is_system and not _should_apply_to_printer(maint_type.name, printer.model):
  489. continue
  490. item = existing_items.get(maint_type.id)
  491. default_interval_type = getattr(maint_type, "interval_type", "hours") or "hours"
  492. if item:
  493. _start_model_task_clock(item, maint_type, printer, now)
  494. interval = item.custom_interval_hours or maint_type.default_interval_hours
  495. # Use custom interval type if set, otherwise use type's default
  496. interval_type = getattr(item, "custom_interval_type", None) or default_interval_type
  497. enabled = item.enabled
  498. last_performed_hours = item.last_performed_hours
  499. last_performed_at = item.last_performed_at
  500. item_id = item.id
  501. else:
  502. # Only auto-create maintenance items for system types
  503. # Custom types need to be manually assigned per printer
  504. if not maint_type.is_system:
  505. continue
  506. # Create default entry for this printer/type, or take the one a
  507. # concurrent read just created.
  508. item = await _get_or_create_maintenance_item(db, printer_id, maint_type.id)
  509. _start_model_task_clock(item, maint_type, printer, now)
  510. interval = item.custom_interval_hours or maint_type.default_interval_hours
  511. interval_type = getattr(item, "custom_interval_type", None) or default_interval_type
  512. enabled = item.enabled
  513. last_performed_hours = item.last_performed_hours
  514. last_performed_at = item.last_performed_at
  515. item_id = item.id
  516. # Calculate status based on interval type
  517. if interval_type == "days":
  518. # Time-based: calculate days since last performed
  519. if last_performed_at:
  520. # DB stores naive datetimes; treat as UTC for comparison
  521. if last_performed_at.tzinfo is None:
  522. last_performed_at = last_performed_at.replace(tzinfo=timezone.utc)
  523. days_since = (now - last_performed_at).total_seconds() / 86400.0
  524. else:
  525. # Never performed - consider it due
  526. days_since = interval + 1
  527. days_until = interval - days_since
  528. is_due = days_until <= 0
  529. is_warning = days_until <= (interval * 0.1) and not is_due
  530. # For compatibility, also set hours values (but they won't be primary)
  531. hours_since = total_hours - last_performed_hours
  532. hours_until = 0 # Not applicable for time-based
  533. else:
  534. # Print-hours based (default)
  535. hours_since = total_hours - last_performed_hours
  536. hours_until = interval - hours_since
  537. is_due = hours_until <= 0
  538. is_warning = hours_until <= (interval * 0.1) and not is_due
  539. # Calculate days for reference
  540. if last_performed_at:
  541. if last_performed_at.tzinfo is None:
  542. last_performed_at = last_performed_at.replace(tzinfo=timezone.utc)
  543. days_since = (now - last_performed_at).total_seconds() / 86400.0
  544. else:
  545. days_since = None
  546. days_until = None
  547. if enabled:
  548. if is_due:
  549. due_count += 1
  550. elif is_warning:
  551. warning_count += 1
  552. maintenance_items.append(
  553. MaintenanceStatus(
  554. id=item_id,
  555. printer_id=printer_id,
  556. printer_name=printer.name,
  557. printer_model=printer.model,
  558. maintenance_type_id=maint_type.id,
  559. maintenance_type_name=maint_type.name,
  560. maintenance_type_icon=maint_type.icon,
  561. maintenance_type_wiki_url=getattr(maint_type, "wiki_url", None),
  562. enabled=enabled,
  563. interval_hours=interval,
  564. interval_type=interval_type,
  565. current_hours=total_hours,
  566. hours_since_maintenance=hours_since,
  567. hours_until_due=hours_until,
  568. days_since_maintenance=days_since if interval_type == "days" else None,
  569. days_until_due=days_until if interval_type == "days" else None,
  570. is_due=is_due,
  571. is_warning=is_warning,
  572. last_performed_at=last_performed_at,
  573. )
  574. )
  575. if commit:
  576. await db.commit()
  577. return PrinterMaintenanceOverview(
  578. printer_id=printer_id,
  579. printer_name=printer.name,
  580. printer_model=printer.model,
  581. total_print_hours=total_hours,
  582. maintenance_items=maintenance_items,
  583. due_count=due_count,
  584. warning_count=warning_count,
  585. )
  586. @router.get("/printers/{printer_id}", response_model=PrinterMaintenanceOverview)
  587. async def get_printer_maintenance(
  588. printer_id: int,
  589. db: AsyncSession = Depends(get_db, scope="function"),
  590. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  591. ):
  592. """Get maintenance overview for a specific printer."""
  593. return await _get_printer_maintenance_internal(printer_id, db, commit=True)
  594. @router.get("/overview", response_model=list[PrinterMaintenanceOverview])
  595. async def get_all_maintenance_overview(
  596. db: AsyncSession = Depends(get_db, scope="function"),
  597. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  598. printer_scope: PrinterScope = RequestPrinterScope,
  599. ):
  600. """Get maintenance overview for all active printers."""
  601. await ensure_default_types(db)
  602. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  603. printers = [p for p in result.scalars().all() if printer_scope.allows(p.id)]
  604. overviews = []
  605. for printer in printers:
  606. # Don't commit after each printer, commit once at the end
  607. overview = await _get_printer_maintenance_internal(printer.id, db, commit=False)
  608. overviews.append(overview)
  609. # Commit any new maintenance items created
  610. await db.commit()
  611. return overviews
  612. @router.patch("/items/{item_id}", response_model=PrinterMaintenanceResponse)
  613. async def update_printer_maintenance(
  614. item_id: int,
  615. data: PrinterMaintenanceUpdate,
  616. db: AsyncSession = Depends(get_db, scope="function"),
  617. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  618. printer_scope: PrinterScope = RequestPrinterScope,
  619. ):
  620. """Update a printer maintenance item (e.g., custom interval, enabled)."""
  621. result = await db.execute(
  622. select(PrinterMaintenance)
  623. .where(PrinterMaintenance.id == item_id)
  624. .options(selectinload(PrinterMaintenance.maintenance_type))
  625. )
  626. item = result.scalar_one_or_none()
  627. if not item or not printer_scope.allows(item.printer_id):
  628. raise HTTPException(status_code=404, detail="Maintenance item not found")
  629. update_data = data.model_dump(exclude_unset=True)
  630. for key, value in update_data.items():
  631. setattr(item, key, value)
  632. await db.commit()
  633. await db.refresh(item)
  634. return item
  635. @router.post("/printers/{printer_id}/assign/{type_id}", response_model=PrinterMaintenanceResponse)
  636. async def assign_maintenance_type(
  637. printer_id: int,
  638. type_id: int,
  639. db: AsyncSession = Depends(get_db, scope="function"),
  640. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_CREATE),
  641. ):
  642. """Assign a maintenance type to a specific printer (for custom types)."""
  643. # Verify printer exists
  644. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  645. printer = result.scalar_one_or_none()
  646. if not printer:
  647. raise HTTPException(status_code=404, detail="Printer not found")
  648. # Verify maintenance type exists
  649. result = await db.execute(select(MaintenanceType).where(MaintenanceType.id == type_id))
  650. maint_type = result.scalar_one_or_none()
  651. if not maint_type:
  652. raise HTTPException(status_code=404, detail="Maintenance type not found")
  653. # Check if already assigned
  654. result = await db.execute(
  655. select(PrinterMaintenance).where(
  656. PrinterMaintenance.printer_id == printer_id,
  657. PrinterMaintenance.maintenance_type_id == type_id,
  658. )
  659. )
  660. existing = result.scalar_one_or_none()
  661. if existing:
  662. raise HTTPException(status_code=400, detail="Maintenance type already assigned to this printer")
  663. # Create the assignment
  664. item = PrinterMaintenance(
  665. printer_id=printer_id,
  666. maintenance_type_id=type_id,
  667. enabled=True,
  668. last_performed_hours=0.0,
  669. )
  670. db.add(item)
  671. try:
  672. await db.commit()
  673. except IntegrityError:
  674. # A concurrent assign (a double click) passed the check above too; the
  675. # unique index refuses this one (FO-C14).
  676. await db.rollback()
  677. raise HTTPException(status_code=400, detail="Maintenance type already assigned to this printer") from None
  678. # Re-fetch with relationship loaded for response serialization
  679. from sqlalchemy.orm import selectinload
  680. result = await db.execute(
  681. select(PrinterMaintenance)
  682. .options(selectinload(PrinterMaintenance.maintenance_type))
  683. .where(PrinterMaintenance.id == item.id)
  684. )
  685. item = result.scalar_one()
  686. return item
  687. @router.delete("/items/{item_id}")
  688. async def remove_maintenance_item(
  689. item_id: int,
  690. db: AsyncSession = Depends(get_db, scope="function"),
  691. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_DELETE),
  692. printer_scope: PrinterScope = RequestPrinterScope,
  693. ):
  694. """Remove a maintenance item (unassign a custom type from a printer)."""
  695. result = await db.execute(
  696. select(PrinterMaintenance)
  697. .where(PrinterMaintenance.id == item_id)
  698. .options(selectinload(PrinterMaintenance.maintenance_type))
  699. )
  700. item = result.scalar_one_or_none()
  701. if not item or not printer_scope.allows(item.printer_id):
  702. raise HTTPException(status_code=404, detail="Maintenance item not found")
  703. # Only allow removing custom (non-system) types
  704. if item.maintenance_type.is_system:
  705. raise HTTPException(status_code=400, detail="Cannot remove system maintenance types")
  706. await db.delete(item)
  707. await db.commit()
  708. return {"status": "removed"}
  709. @router.post("/items/{item_id}/perform", response_model=MaintenanceStatus)
  710. async def perform_maintenance(
  711. item_id: int,
  712. data: PerformMaintenanceRequest,
  713. db: AsyncSession = Depends(get_db, scope="function"),
  714. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  715. printer_scope: PrinterScope = RequestPrinterScope,
  716. ):
  717. """Mark maintenance as performed (reset the counter)."""
  718. result = await db.execute(
  719. select(PrinterMaintenance)
  720. .where(PrinterMaintenance.id == item_id)
  721. .options(selectinload(PrinterMaintenance.maintenance_type))
  722. )
  723. item = result.scalar_one_or_none()
  724. if not item or not printer_scope.allows(item.printer_id):
  725. raise HTTPException(status_code=404, detail="Maintenance item not found")
  726. # Get printer for name
  727. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  728. printer = result.scalar_one()
  729. # Get current hours
  730. current_hours = await get_printer_total_hours(db, item.printer_id)
  731. # Create history entry
  732. history = MaintenanceHistory(
  733. printer_maintenance_id=item.id,
  734. hours_at_maintenance=current_hours,
  735. notes=data.notes,
  736. )
  737. db.add(history)
  738. # Update item
  739. item.last_performed_at = datetime.now(timezone.utc)
  740. item.last_performed_hours = current_hours
  741. await db.commit()
  742. # MQTT relay - publish maintenance reset
  743. try:
  744. from backend.app.services.mqtt_relay import mqtt_relay
  745. await mqtt_relay.on_maintenance_reset(
  746. printer_id=item.printer_id,
  747. printer_name=printer.name,
  748. maintenance_type=item.maintenance_type.name,
  749. )
  750. except Exception:
  751. pass # Don't fail if MQTT fails
  752. # Calculate status
  753. interval = item.custom_interval_hours or item.maintenance_type.default_interval_hours
  754. # The item's own interval type first, as the status list reads it (dbcol-09).
  755. interval_type = item.custom_interval_type or getattr(item.maintenance_type, "interval_type", "hours") or "hours"
  756. hours_since = current_hours - item.last_performed_hours
  757. hours_until = interval - hours_since
  758. return MaintenanceStatus(
  759. id=item.id,
  760. printer_id=item.printer_id,
  761. printer_name=printer.name,
  762. printer_model=printer.model,
  763. maintenance_type_id=item.maintenance_type_id,
  764. maintenance_type_name=item.maintenance_type.name,
  765. maintenance_type_icon=item.maintenance_type.icon,
  766. maintenance_type_wiki_url=getattr(item.maintenance_type, "wiki_url", None),
  767. enabled=item.enabled,
  768. interval_hours=interval,
  769. interval_type=interval_type,
  770. current_hours=current_hours,
  771. hours_since_maintenance=hours_since,
  772. hours_until_due=hours_until if interval_type == "hours" else 0,
  773. days_since_maintenance=0 if interval_type == "days" else None,
  774. days_until_due=interval if interval_type == "days" else None,
  775. is_due=False,
  776. is_warning=False,
  777. last_performed_at=item.last_performed_at,
  778. )
  779. @router.get("/items/{item_id}/history", response_model=list[MaintenanceHistoryResponse])
  780. async def get_maintenance_history(
  781. item_id: int,
  782. db: AsyncSession = Depends(get_db, scope="function"),
  783. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  784. printer_scope: PrinterScope = RequestPrinterScope,
  785. ):
  786. """Get maintenance history for a specific item."""
  787. item_printer_id = (
  788. await db.execute(select(PrinterMaintenance.printer_id).where(PrinterMaintenance.id == item_id))
  789. ).scalar_one_or_none()
  790. if not printer_scope.allows(item_printer_id):
  791. raise HTTPException(status_code=404, detail="Maintenance item not found")
  792. result = await db.execute(
  793. select(MaintenanceHistory)
  794. .where(MaintenanceHistory.printer_maintenance_id == item_id)
  795. .order_by(MaintenanceHistory.performed_at.desc())
  796. )
  797. return result.scalars().all()
  798. @router.get("/summary")
  799. async def get_maintenance_summary(
  800. db: AsyncSession = Depends(get_db, scope="function"),
  801. _: User | None = RequirePermissionIfAuthEnabled(Permission.MAINTENANCE_READ),
  802. printer_scope: PrinterScope = RequestPrinterScope,
  803. ):
  804. """Get a summary of maintenance status across all printers."""
  805. await ensure_default_types(db)
  806. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  807. printers = [p for p in result.scalars().all() if printer_scope.allows(p.id)]
  808. total_due = 0
  809. total_warning = 0
  810. printers_with_issues = []
  811. for printer in printers:
  812. overview = await get_printer_maintenance(printer.id, db)
  813. total_due += overview.due_count
  814. total_warning += overview.warning_count
  815. if overview.due_count > 0 or overview.warning_count > 0:
  816. printers_with_issues.append(
  817. {
  818. "printer_id": printer.id,
  819. "printer_name": printer.name,
  820. "due_count": overview.due_count,
  821. "warning_count": overview.warning_count,
  822. }
  823. )
  824. return {
  825. "total_due": total_due,
  826. "total_warning": total_warning,
  827. "printers_with_issues": printers_with_issues,
  828. }
  829. @router.patch("/printers/{printer_id}/hours")
  830. async def set_printer_hours(
  831. printer_id: int,
  832. total_hours: float,
  833. db: AsyncSession = Depends(get_db, scope="function"),
  834. _: User | None = RequirePrinterPermissionIfAuthEnabled(Permission.MAINTENANCE_UPDATE),
  835. ):
  836. """Set the total print hours for a printer (adjusts offset to match).
  837. The offset is calculated as: offset = total_hours - runtime_hours
  838. Where runtime_hours comes from the runtime_seconds counter that tracks
  839. actual machine active time (RUNNING state only — paused time excluded, #1521).
  840. """
  841. # Get printer
  842. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  843. printer = result.scalar_one_or_none()
  844. if not printer:
  845. raise HTTPException(status_code=404, detail="Printer not found")
  846. # Get current runtime hours
  847. runtime_hours = (printer.runtime_seconds or 0) / 3600.0
  848. # Calculate needed offset
  849. printer.print_hours_offset = max(0, total_hours - runtime_hours)
  850. await db.commit()
  851. # Check for maintenance items that need attention and send notification
  852. try:
  853. await ensure_default_types(db)
  854. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  855. items_needing_attention = [
  856. {
  857. "name": item.maintenance_type_name,
  858. "is_due": item.is_due,
  859. "is_warning": item.is_warning,
  860. }
  861. for item in overview.maintenance_items
  862. if item.enabled and (item.is_due or item.is_warning)
  863. ]
  864. if items_needing_attention:
  865. await notification_service.on_maintenance_due(printer_id, printer.name, items_needing_attention, db)
  866. logger.info(
  867. f"Sent maintenance notification for printer {printer_id}: "
  868. f"{len(items_needing_attention)} items need attention"
  869. )
  870. except Exception as e:
  871. logger.warning("Failed to send maintenance notification: %s", e)
  872. return {
  873. "printer_id": printer_id,
  874. "total_hours": total_hours,
  875. "runtime_hours": runtime_hours,
  876. "offset_hours": printer.print_hours_offset,
  877. }