maintenance.py 47 KB

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