print_queue.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. """API routes for print queue management."""
  2. import json
  3. import logging
  4. import zipfile
  5. from datetime import datetime, timezone
  6. from pathlib import Path
  7. import defusedxml.ElementTree as ET
  8. from fastapi import APIRouter, Depends, HTTPException, Query
  9. from sqlalchemy import and_, func, or_, select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from sqlalchemy.orm import selectinload
  12. from backend.app.core.auth import RequirePermissionIfAuthEnabled, require_ownership_permission
  13. from backend.app.core.config import settings
  14. from backend.app.core.database import get_db
  15. from backend.app.core.permissions import Permission
  16. from backend.app.core.tasks import spawn_background_task
  17. from backend.app.models.archive import PrintArchive
  18. from backend.app.models.library import LibraryFile
  19. from backend.app.models.print_batch import PrintBatch
  20. from backend.app.models.print_queue import PrintQueueItem
  21. from backend.app.models.printer import Printer
  22. from backend.app.models.project import Project
  23. from backend.app.models.user import User
  24. from backend.app.schemas.print_queue import (
  25. PrintBatchCreate,
  26. PrintBatchResponse,
  27. PrintBatchUngroupResponse,
  28. PrintQueueBulkUpdate,
  29. PrintQueueBulkUpdateResponse,
  30. PrintQueueItemCreate,
  31. PrintQueueItemResponse,
  32. PrintQueueItemUpdate,
  33. PrintQueueReorder,
  34. )
  35. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  36. from backend.app.services.notification_service import notification_service
  37. from backend.app.utils.printer_models import normalize_printer_model, normalize_printer_model_id
  38. from backend.app.utils.threemf_tools import (
  39. extract_bed_type_from_3mf,
  40. extract_filament_usage_from_3mf,
  41. extract_print_time_from_3mf,
  42. )
  43. logger = logging.getLogger(__name__)
  44. router = APIRouter(prefix="/queue", tags=["queue"])
  45. def _extract_filament_types_from_3mf(file_path: Path, plate_id: int | None = None) -> list[str]:
  46. """Extract unique filament types from a 3MF file.
  47. Args:
  48. file_path: Path to the 3MF file
  49. plate_id: Optional plate index to filter for (for multi-plate files)
  50. Returns:
  51. List of unique filament types (e.g., ["PLA", "PETG"])
  52. """
  53. types: set[str] = set()
  54. try:
  55. with zipfile.ZipFile(file_path, "r") as zf:
  56. if "Metadata/slice_info.config" not in zf.namelist():
  57. return []
  58. content = zf.read("Metadata/slice_info.config").decode()
  59. root = ET.fromstring(content)
  60. if plate_id is not None:
  61. # Find the plate element with matching index
  62. for plate_elem in root.findall(".//plate"):
  63. plate_index = None
  64. for meta in plate_elem.findall("metadata"):
  65. if meta.get("key") == "index":
  66. try:
  67. plate_index = int(meta.get("value", "0"))
  68. except ValueError:
  69. pass # Skip plate with unparseable index
  70. break
  71. if plate_index == plate_id:
  72. for filament_elem in plate_elem.findall("filament"):
  73. filament_type = filament_elem.get("type", "")
  74. used_g = filament_elem.get("used_g", "0")
  75. try:
  76. used_grams = float(used_g)
  77. except (ValueError, TypeError):
  78. used_grams = 0
  79. if used_grams > 0 and filament_type:
  80. types.add(filament_type)
  81. break
  82. else:
  83. # No plate_id specified - extract all filaments with used_g > 0
  84. for filament_elem in root.findall(".//filament"):
  85. filament_type = filament_elem.get("type", "")
  86. used_g = filament_elem.get("used_g", "0")
  87. try:
  88. used_grams = float(used_g)
  89. except (ValueError, TypeError):
  90. used_grams = 0
  91. if used_grams > 0 and filament_type:
  92. types.add(filament_type)
  93. except Exception as e:
  94. logger.warning("Failed to extract filament types from %s: %s", file_path, e)
  95. return sorted(types)
  96. # Local alias kept so existing call sites stay compact; the implementation lives
  97. # in utils/threemf_tools.py so the notification path (main.py) can reuse it
  98. # without importing from a routes module (#1785).
  99. _extract_print_time_from_3mf = extract_print_time_from_3mf
  100. def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
  101. """Add nested archive/printer/library_file info to response."""
  102. # Parse ams_mapping from JSON string BEFORE model_validate
  103. ams_mapping_parsed = None
  104. if item.ams_mapping:
  105. try:
  106. ams_mapping_parsed = json.loads(item.ams_mapping)
  107. except json.JSONDecodeError:
  108. ams_mapping_parsed = None
  109. # Parse required_filament_types from JSON string
  110. required_filament_types_parsed = None
  111. if item.required_filament_types:
  112. try:
  113. required_filament_types_parsed = json.loads(item.required_filament_types)
  114. except json.JSONDecodeError:
  115. required_filament_types_parsed = None
  116. # Parse filament_overrides from JSON string
  117. filament_overrides_parsed = None
  118. if item.filament_overrides:
  119. try:
  120. filament_overrides_parsed = json.loads(item.filament_overrides)
  121. except json.JSONDecodeError:
  122. filament_overrides_parsed = None
  123. # Parse nozzle_mapping from JSON string (#1780 — H2C rack slicer-pick
  124. # preservation). Nullable opaque JSON blob stored verbatim from
  125. # BambuStudio's project_file; surface it parsed for the response model
  126. # and any future "edit print → nozzle" UI.
  127. nozzle_mapping_parsed = None
  128. if item.nozzle_mapping:
  129. try:
  130. nozzle_mapping_parsed = json.loads(item.nozzle_mapping)
  131. except json.JSONDecodeError:
  132. nozzle_mapping_parsed = None
  133. # Create response with parsed ams_mapping
  134. item_dict = {
  135. "id": item.id,
  136. "printer_id": item.printer_id,
  137. "target_model": item.target_model,
  138. "target_location": item.target_location,
  139. "required_filament_types": required_filament_types_parsed,
  140. "filament_overrides": filament_overrides_parsed,
  141. "waiting_reason": item.waiting_reason,
  142. "archive_id": item.archive_id,
  143. "library_file_id": item.library_file_id,
  144. "position": item.position,
  145. "scheduled_time": item.scheduled_time,
  146. "require_previous_success": item.require_previous_success,
  147. "auto_off_after": item.auto_off_after,
  148. "manual_start": item.manual_start,
  149. "filament_short": bool(item.filament_short),
  150. "skip_filament_check": bool(item.skip_filament_check),
  151. "ams_mapping": ams_mapping_parsed,
  152. "plate_id": item.plate_id,
  153. "bed_levelling": item.bed_levelling,
  154. "flow_cali": item.flow_cali,
  155. "vibration_cali": item.vibration_cali,
  156. "layer_inspect": item.layer_inspect,
  157. "timelapse": item.timelapse,
  158. "use_ams": item.use_ams,
  159. "nozzle_offset_cali": item.nozzle_offset_cali,
  160. "status": item.status,
  161. "started_at": item.started_at,
  162. "completed_at": item.completed_at,
  163. "error_message": item.error_message,
  164. "created_at": item.created_at,
  165. # User tracking (Issue #206)
  166. "created_by_id": item.created_by_id,
  167. "created_by_username": item.created_by.username if item.created_by else None,
  168. # Batch grouping
  169. "batch_id": item.batch_id,
  170. "batch_name": item.batch.name if item.batch else None,
  171. # SJF scheduling
  172. "been_jumped": item.been_jumped,
  173. # Auto-print G-code injection
  174. "gcode_injection": item.gcode_injection,
  175. # H2C rack-swap nozzle pick (#1780)
  176. "nozzle_mapping": nozzle_mapping_parsed,
  177. }
  178. response = PrintQueueItemResponse(**item_dict)
  179. if item.archive:
  180. # Soft-deleted archive: files are gone from disk but the row stays
  181. # (its filament/cost contribution still flows into stats per #1343).
  182. # Suppress the archive-derived UI surface so the queue page doesn't
  183. # 404-storm the thumbnail / plates / plate-thumbnail endpoints — the
  184. # frontend's existing truthy gate on archive_thumbnail covers it
  185. # (#1348 follow-up). The archive_deleted flag lets the UI render a
  186. # "source deleted" badge on these rows.
  187. if item.archive.deleted_at is not None:
  188. response.archive_deleted = True
  189. else:
  190. response.archive_name = item.archive.print_name or item.archive.filename
  191. response.archive_thumbnail = item.archive.thumbnail_path
  192. response.print_time_seconds = item.archive.print_time_seconds
  193. response.filament_used_grams = item.archive.filament_used_grams
  194. response.filament_type = item.archive.filament_type
  195. response.filament_color = item.archive.filament_color
  196. response.layer_height = item.archive.layer_height
  197. response.nozzle_diameter = item.archive.nozzle_diameter
  198. response.sliced_for_model = item.archive.sliced_for_model
  199. response.bed_type = item.archive.bed_type
  200. if item.plate_id:
  201. archive_path = settings.base_dir / item.archive.file_path
  202. if archive_path.exists():
  203. plate_time = _extract_print_time_from_3mf(archive_path, item.plate_id)
  204. plate_weight = sum(
  205. f["used_g"] for f in extract_filament_usage_from_3mf(archive_path, item.plate_id)
  206. )
  207. plate_bed = extract_bed_type_from_3mf(archive_path, item.plate_id)
  208. if plate_time is not None:
  209. response.print_time_seconds = plate_time
  210. if plate_weight > 0:
  211. response.filament_used_grams = plate_weight
  212. if plate_bed:
  213. response.bed_type = plate_bed
  214. if item.library_file:
  215. response.library_file_name = (
  216. item.library_file.file_metadata.get("print_name") if item.library_file.file_metadata else None
  217. )
  218. if not response.library_file_name:
  219. response.library_file_name = item.library_file.filename
  220. response.library_file_thumbnail = item.library_file.thumbnail_path
  221. # Get metadata from library file if no archive
  222. if not item.archive and item.library_file.file_metadata:
  223. response.print_time_seconds = item.library_file.file_metadata.get("print_time_seconds")
  224. response.filament_used_grams = item.library_file.file_metadata.get("filament_used_grams")
  225. response.filament_type = item.library_file.file_metadata.get("filament_type")
  226. response.filament_color = item.library_file.file_metadata.get("filament_color")
  227. response.layer_height = item.library_file.file_metadata.get("layer_height")
  228. response.nozzle_diameter = item.library_file.file_metadata.get("nozzle_diameter")
  229. response.sliced_for_model = item.library_file.file_metadata.get("sliced_for_model")
  230. response.bed_type = item.library_file.file_metadata.get("bed_type")
  231. if item.plate_id:
  232. lib_path = Path(item.library_file.file_path)
  233. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / item.library_file.file_path
  234. if library_file_path.exists():
  235. plate_time = _extract_print_time_from_3mf(library_file_path, item.plate_id)
  236. plate_weight = sum(
  237. f["used_g"] for f in extract_filament_usage_from_3mf(library_file_path, item.plate_id)
  238. )
  239. plate_bed = extract_bed_type_from_3mf(library_file_path, item.plate_id)
  240. if plate_time is not None:
  241. response.print_time_seconds = plate_time
  242. if plate_weight > 0:
  243. response.filament_used_grams = plate_weight
  244. if plate_bed:
  245. response.bed_type = plate_bed
  246. if item.printer:
  247. response.printer_name = item.printer.name
  248. return response
  249. @router.get("/", response_model=list[PrintQueueItemResponse])
  250. async def list_queue(
  251. printer_id: int | None = Query(None, description="Filter by printer (-1 for unassigned)"),
  252. status: str | None = Query(None, description="Filter by status"),
  253. target_model: str | None = Query(
  254. None, description="Filter by target model (also includes model-based items when combined with printer_id)"
  255. ),
  256. db: AsyncSession = Depends(get_db),
  257. auth_result: tuple[User | None, bool] = Depends(
  258. require_ownership_permission(
  259. Permission.QUEUE_READ_ALL,
  260. Permission.QUEUE_READ_OWN,
  261. )
  262. ),
  263. ):
  264. """List all queue items, optionally filtered by printer or status."""
  265. user, can_read_all = auth_result
  266. query = (
  267. select(PrintQueueItem)
  268. .options(
  269. selectinload(PrintQueueItem.archive),
  270. selectinload(PrintQueueItem.printer),
  271. selectinload(PrintQueueItem.library_file),
  272. selectinload(PrintQueueItem.created_by),
  273. selectinload(PrintQueueItem.batch),
  274. )
  275. .order_by(PrintQueueItem.printer_id.nulls_first(), PrintQueueItem.position)
  276. )
  277. if user is not None and not can_read_all:
  278. query = query.where(PrintQueueItem.created_by_id == user.id)
  279. if printer_id is not None:
  280. if printer_id == -1:
  281. # Special value: filter for unassigned items
  282. query = query.where(PrintQueueItem.printer_id.is_(None))
  283. else:
  284. # Resolve effective model: prefer explicit param, fall back to printer's DB model.
  285. # This ensures model-based "Any X" items are returned even when the frontend
  286. # doesn't send target_model (e.g. printer.model is NULL on the client side).
  287. effective_model = target_model
  288. if not effective_model:
  289. printer_row = (
  290. await db.execute(select(Printer.model).where(Printer.id == printer_id))
  291. ).scalar_one_or_none()
  292. effective_model = printer_row
  293. if effective_model:
  294. # Include both printer-specific items AND model-based (unassigned) items
  295. query = query.where(
  296. or_(
  297. PrintQueueItem.printer_id == printer_id,
  298. and_(
  299. PrintQueueItem.printer_id.is_(None),
  300. func.lower(PrintQueueItem.target_model) == effective_model.lower(),
  301. ),
  302. )
  303. )
  304. else:
  305. query = query.where(PrintQueueItem.printer_id == printer_id)
  306. elif target_model:
  307. query = query.where(func.lower(PrintQueueItem.target_model) == target_model.lower())
  308. if status:
  309. query = query.where(PrintQueueItem.status == status)
  310. result = await db.execute(query)
  311. items = result.scalars().all()
  312. return [_enrich_response(item) for item in items]
  313. @router.post("/", response_model=PrintQueueItemResponse)
  314. async def add_to_queue(
  315. data: PrintQueueItemCreate,
  316. db: AsyncSession = Depends(get_db),
  317. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  318. ):
  319. """Add an item to the print queue."""
  320. # Normalize target_model (e.g., "Bambu Lab X1E" / "C13" -> "X1E")
  321. target_model_norm = None
  322. if data.target_model:
  323. target_model_norm = (
  324. normalize_printer_model(data.target_model)
  325. or normalize_printer_model_id(data.target_model)
  326. or data.target_model
  327. )
  328. # Validate that either archive_id or library_file_id is provided
  329. if not data.archive_id and not data.library_file_id:
  330. raise HTTPException(400, "Either archive_id or library_file_id must be provided")
  331. # Cannot specify both printer_id and target_model
  332. if data.printer_id and target_model_norm:
  333. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  334. # Validate printer exists (if assigned)
  335. if data.printer_id is not None:
  336. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  337. if not result.scalar_one_or_none():
  338. raise HTTPException(400, "Printer not found")
  339. # Validate target_model has active printers
  340. if target_model_norm:
  341. result = await db.execute(
  342. select(Printer).where(Printer.model == target_model_norm).where(Printer.is_active == True) # noqa: E712
  343. )
  344. if not result.scalars().first():
  345. raise HTTPException(400, f"No active printers for model: {target_model_norm}")
  346. # Validate archive exists (if provided) and get it for filament extraction
  347. archive = None
  348. if data.archive_id:
  349. result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  350. archive = result.scalar_one_or_none()
  351. if not archive:
  352. raise HTTPException(400, "Archive not found")
  353. # IDOR fix (maziggy/bambuddy-security #2): without this check, a
  354. # caller with QUEUE_CREATE could queue any user's archive even
  355. # without ARCHIVES_READ on it — Landon's PoC enumerated this on
  356. # admin's archives as operator1. Gate on ARCHIVES_READ_ALL OR
  357. # ownership of the archive. 404 (not 403) so we don't leak
  358. # "this id exists but you can't queue it" for enumeration.
  359. if (
  360. current_user is not None
  361. and not current_user.has_permission(Permission.ARCHIVES_READ_ALL.value)
  362. and archive.created_by_id != current_user.id
  363. ):
  364. raise HTTPException(404, "Archive not found")
  365. # Validate library file exists (if provided) and get it for filament extraction
  366. library_file = None
  367. if data.library_file_id:
  368. result = await db.execute(LibraryFile.active().where(LibraryFile.id == data.library_file_id))
  369. library_file = result.scalar_one_or_none()
  370. if not library_file:
  371. raise HTTPException(400, "Library file not found")
  372. # Same shape: gate cross-user library-file queueing on LIBRARY_READ_ALL.
  373. if (
  374. current_user is not None
  375. and not current_user.has_permission(Permission.LIBRARY_READ_ALL.value)
  376. and library_file.created_by_id != current_user.id
  377. ):
  378. raise HTTPException(404, "Library file not found")
  379. # Bambu SD card is FAT32/exFAT — illegal filename chars would 553 at
  380. # FTP upload time (#1540). Reject at queue time so the user gets the
  381. # actionable error before waiting in queue.
  382. from backend.app.utils.filename import InvalidFilenameError, validate_print_filename
  383. try:
  384. validate_print_filename(library_file.filename)
  385. except InvalidFilenameError as e:
  386. raise HTTPException(400, str(e)) from e
  387. # Extract filament types for model-based assignment (used by scheduler for validation)
  388. required_filament_types = None
  389. if target_model_norm:
  390. # Get file path from archive or library file
  391. file_path = None
  392. if archive:
  393. file_path = settings.base_dir / archive.file_path
  394. elif library_file:
  395. lib_path = Path(library_file.file_path)
  396. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  397. if file_path and file_path.exists():
  398. filament_types = _extract_filament_types_from_3mf(file_path, data.plate_id)
  399. if filament_types:
  400. required_filament_types = json.dumps(filament_types)
  401. logger.info("Extracted filament types for model-based queue: %s", filament_types)
  402. # If filament overrides are provided, update required_filament_types to match override types
  403. filament_overrides_json = None
  404. if data.filament_overrides and target_model_norm:
  405. filament_overrides_json = json.dumps(data.filament_overrides)
  406. # Update required_filament_types from overrides so scheduler validates against overridden types
  407. override_types = sorted({o["type"] for o in data.filament_overrides if "type" in o})
  408. if override_types:
  409. # Merge with existing types (overrides may only cover some slots)
  410. existing_types = set(json.loads(required_filament_types)) if required_filament_types else set()
  411. # Replace types for overridden slots, keep others
  412. all_types = existing_types | set(override_types)
  413. required_filament_types = json.dumps(sorted(all_types))
  414. # Validate quantity
  415. quantity = max(1, data.quantity)
  416. # Validate batch_id if provided. Client passes batch_id when adding items
  417. # into a pre-created batch (multi-plate auto-batch or "Group as batch" flow).
  418. # 404 keeps the existing-id leak surface low.
  419. batch = None
  420. batch_id = None
  421. if data.batch_id is not None:
  422. result = await db.execute(select(PrintBatch).where(PrintBatch.id == data.batch_id))
  423. existing_batch = result.scalar_one_or_none()
  424. if not existing_batch:
  425. raise HTTPException(404, "Batch not found")
  426. if existing_batch.status != "active":
  427. raise HTTPException(400, "Cannot add items to a non-active batch")
  428. if (
  429. current_user is not None
  430. and existing_batch.created_by_id is not None
  431. and existing_batch.created_by_id != current_user.id
  432. and not current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  433. ):
  434. raise HTTPException(404, "Batch not found")
  435. batch = existing_batch
  436. batch_id = existing_batch.id
  437. # Create batch if quantity > 1 and no batch_id provided
  438. if batch_id is None and quantity > 1:
  439. # Derive batch name from source file
  440. batch_name_base = "Batch"
  441. if archive:
  442. batch_name_base = archive.print_name or archive.filename or "Batch"
  443. elif library_file:
  444. if library_file.file_metadata:
  445. batch_name_base = library_file.file_metadata.get("print_name") or library_file.filename
  446. else:
  447. batch_name_base = library_file.filename
  448. batch_name_base = batch_name_base.replace(".gcode.3mf", "").replace(".3mf", "")
  449. batch = PrintBatch(
  450. name=f"{batch_name_base} ×{quantity}",
  451. archive_id=data.archive_id,
  452. library_file_id=data.library_file_id,
  453. quantity=quantity,
  454. status="active",
  455. created_by_id=current_user.id if current_user else None,
  456. )
  457. db.add(batch)
  458. await db.flush() # Get batch.id before creating items
  459. batch_id = batch.id
  460. # Get next position for this printer (or for unassigned/model-based items)
  461. if data.printer_id is not None:
  462. result = await db.execute(
  463. select(func.max(PrintQueueItem.position))
  464. .where(PrintQueueItem.printer_id == data.printer_id)
  465. .where(PrintQueueItem.status == "pending")
  466. )
  467. else:
  468. # For unassigned/model-based items, get max position across all unassigned
  469. result = await db.execute(
  470. select(func.max(PrintQueueItem.position))
  471. .where(PrintQueueItem.printer_id.is_(None))
  472. .where(PrintQueueItem.status == "pending")
  473. )
  474. max_pos = result.scalar() or 0
  475. # Resolve print_time_seconds for SJF scheduling (cache on item at creation)
  476. cached_print_time = None
  477. if archive:
  478. cached_print_time = archive.print_time_seconds
  479. if data.plate_id:
  480. archive_path = settings.base_dir / archive.file_path
  481. if archive_path.exists():
  482. plate_time = _extract_print_time_from_3mf(archive_path, data.plate_id)
  483. if plate_time is not None:
  484. cached_print_time = plate_time
  485. elif library_file:
  486. if library_file.file_metadata:
  487. cached_print_time = library_file.file_metadata.get("print_time_seconds")
  488. if data.plate_id:
  489. lib_path = Path(library_file.file_path)
  490. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  491. if library_file_path.exists():
  492. plate_time = _extract_print_time_from_3mf(library_file_path, data.plate_id)
  493. if plate_time is not None:
  494. cached_print_time = plate_time
  495. # Validate project exists before insert so a bogus ID yields 404, not an FK-constraint 500
  496. if data.project_id is not None:
  497. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  498. if not project_result.scalar_one_or_none():
  499. raise HTTPException(status_code=404, detail="Project not found")
  500. ams_mapping_json = json.dumps(data.ams_mapping) if data.ams_mapping else None
  501. items = []
  502. for i in range(quantity):
  503. item = PrintQueueItem(
  504. printer_id=data.printer_id,
  505. target_model=target_model_norm,
  506. target_location=data.target_location,
  507. required_filament_types=required_filament_types,
  508. filament_overrides=filament_overrides_json,
  509. archive_id=data.archive_id,
  510. library_file_id=data.library_file_id,
  511. scheduled_time=data.scheduled_time,
  512. require_previous_success=data.require_previous_success,
  513. auto_off_after=data.auto_off_after,
  514. manual_start=data.manual_start,
  515. skip_filament_check=data.skip_filament_check,
  516. ams_mapping=ams_mapping_json,
  517. plate_id=data.plate_id,
  518. bed_levelling=data.bed_levelling,
  519. flow_cali=data.flow_cali,
  520. vibration_cali=data.vibration_cali,
  521. layer_inspect=data.layer_inspect,
  522. timelapse=data.timelapse,
  523. use_ams=data.use_ams,
  524. nozzle_offset_cali=data.nozzle_offset_cali,
  525. gcode_injection=data.gcode_injection,
  526. project_id=data.project_id,
  527. position=max_pos + 1 + i,
  528. status="pending",
  529. created_by_id=current_user.id if current_user else None,
  530. batch_id=batch_id,
  531. print_time_seconds=cached_print_time,
  532. )
  533. db.add(item)
  534. items.append(item)
  535. await db.commit()
  536. # Refresh the first item for the response
  537. item = items[0]
  538. await db.refresh(item)
  539. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  540. source_name = f"archive {data.archive_id}" if data.archive_id else f"library file {data.library_file_id}"
  541. target_desc = data.printer_id or (f"model {target_model_norm}" if target_model_norm else "unassigned")
  542. qty_desc = f" (×{quantity})" if quantity > 1 else ""
  543. logger.info("Added %s to queue for %s%s", source_name, target_desc, qty_desc)
  544. # MQTT relay - publish queue job added
  545. try:
  546. from backend.app.services.mqtt_relay import mqtt_relay
  547. await mqtt_relay.on_queue_job_added(
  548. job_id=item.id,
  549. filename=item.archive.filename if item.archive else "",
  550. printer_id=item.printer_id,
  551. printer_name=item.printer.name if item.printer else None,
  552. )
  553. except Exception:
  554. pass # Don't fail queue add if MQTT fails
  555. # Send notification for job added
  556. try:
  557. job_name = (
  558. item.archive.filename
  559. if item.archive
  560. else item.library_file.filename
  561. if item.library_file
  562. else f"Job #{item.id}"
  563. )
  564. job_name = job_name.replace(".gcode.3mf", "").replace(".3mf", "")
  565. if quantity > 1:
  566. job_name = f"{job_name} ×{quantity}"
  567. target = (
  568. item.printer.name if item.printer else (f"Any {item.target_model}" if target_model_norm else "Unassigned")
  569. )
  570. await notification_service.on_queue_job_added(
  571. job_name=job_name,
  572. target=target,
  573. db=db,
  574. printer_id=item.printer_id,
  575. printer_name=item.printer.name if item.printer else None,
  576. )
  577. except Exception:
  578. pass # Don't fail queue add if notification fails
  579. return _enrich_response(item)
  580. @router.patch("/bulk", response_model=PrintQueueBulkUpdateResponse)
  581. async def bulk_update_queue_items(
  582. data: PrintQueueBulkUpdate,
  583. db: AsyncSession = Depends(get_db),
  584. auth_result: tuple[User | None, bool] = Depends(
  585. require_ownership_permission(
  586. Permission.QUEUE_UPDATE_ALL,
  587. Permission.QUEUE_UPDATE_OWN,
  588. )
  589. ),
  590. ):
  591. """Bulk update multiple queue items with the same values.
  592. Only pending items can be updated. Non-pending items are skipped.
  593. Items not owned by the user are also skipped (unless user has *_all permission).
  594. """
  595. user, can_modify_all = auth_result
  596. if not data.item_ids:
  597. raise HTTPException(400, "No item IDs provided")
  598. # Get fields to update (exclude item_ids and unset fields)
  599. update_data = data.model_dump(exclude={"item_ids"}, exclude_unset=True)
  600. if not update_data:
  601. raise HTTPException(400, "No fields to update")
  602. # Validate printer_id if being changed
  603. if "printer_id" in update_data and update_data["printer_id"] is not None:
  604. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  605. if not result.scalar_one_or_none():
  606. raise HTTPException(400, "Printer not found")
  607. # Fetch all items
  608. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  609. items = result.scalars().all()
  610. updated_count = 0
  611. skipped_count = 0
  612. for item in items:
  613. if item.status != "pending":
  614. skipped_count += 1
  615. continue
  616. # Ownership check
  617. if not can_modify_all and item.created_by_id != user.id:
  618. skipped_count += 1
  619. continue
  620. for field, value in update_data.items():
  621. setattr(item, field, value)
  622. updated_count += 1
  623. await db.commit()
  624. logger.info("Bulk updated %s queue items, skipped %s", updated_count, skipped_count)
  625. return PrintQueueBulkUpdateResponse(
  626. updated_count=updated_count,
  627. skipped_count=skipped_count,
  628. message=f"Updated {updated_count} items"
  629. + (f", skipped {skipped_count} non-pending/not-owned" if skipped_count else ""),
  630. )
  631. # --- Batch endpoints ---
  632. @router.post("/batches", response_model=PrintBatchResponse)
  633. async def create_batch(
  634. data: PrintBatchCreate,
  635. db: AsyncSession = Depends(get_db),
  636. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  637. ):
  638. """Create a batch.
  639. Two modes:
  640. * ``item_ids`` provided: assign the listed pending queue items to a new
  641. batch ("Group as batch" UI action).
  642. * ``item_ids`` omitted/empty: create an empty batch so the client can
  643. pass the returned ``id`` on subsequent ``POST /queue/`` calls. Used by
  644. the multi-plate auto-batch flow in PrintModal.
  645. """
  646. if not data.name or not data.name.strip():
  647. raise HTTPException(400, "Batch name is required")
  648. batch = PrintBatch(
  649. name=data.name.strip()[:255],
  650. archive_id=data.archive_id,
  651. library_file_id=data.library_file_id,
  652. quantity=len(data.item_ids) if data.item_ids else 1,
  653. status="active",
  654. created_by_id=current_user.id if current_user else None,
  655. )
  656. db.add(batch)
  657. await db.flush() # Need batch.id before assigning to items
  658. assigned = 0
  659. if data.item_ids:
  660. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  661. items = result.scalars().all()
  662. for item in items:
  663. if item.status != "pending":
  664. continue
  665. if item.batch_id is not None:
  666. continue
  667. if (
  668. current_user is not None
  669. and item.created_by_id != current_user.id
  670. and not current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  671. ):
  672. continue
  673. item.batch_id = batch.id
  674. assigned += 1
  675. batch.quantity = max(assigned, 1)
  676. await db.commit()
  677. await db.refresh(batch)
  678. logger.info("Created batch %s '%s' with %s assigned items", batch.id, batch.name, assigned)
  679. return await _build_batch_response(db, batch)
  680. @router.post("/batches/{batch_id}/ungroup", response_model=PrintBatchUngroupResponse)
  681. async def ungroup_batch(
  682. batch_id: int,
  683. db: AsyncSession = Depends(get_db),
  684. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_OWN),
  685. ):
  686. """Disband a batch: clear batch_id from all members and delete the batch row.
  687. Items stay in the queue. Only ungroups items the caller owns (unless they
  688. hold QUEUE_UPDATE_ALL). A batch with all members ungrouped is deleted.
  689. """
  690. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  691. batch = result.scalar_one_or_none()
  692. if not batch:
  693. raise HTTPException(404, "Batch not found")
  694. can_modify_all = current_user is None or current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  695. if not can_modify_all and batch.created_by_id != (current_user.id if current_user else None):
  696. raise HTTPException(404, "Batch not found")
  697. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.batch_id == batch_id))
  698. items = result.scalars().all()
  699. ungrouped = 0
  700. remaining = 0
  701. for item in items:
  702. if not can_modify_all and item.created_by_id != (current_user.id if current_user else None):
  703. remaining += 1
  704. continue
  705. item.batch_id = None
  706. ungrouped += 1
  707. # Delete the batch row only when all members were ungrouped — otherwise it
  708. # still owns the items the caller couldn't touch.
  709. if remaining == 0:
  710. await db.delete(batch)
  711. await db.commit()
  712. logger.info("Ungrouped batch %s (%s items)", batch_id, ungrouped)
  713. return PrintBatchUngroupResponse(
  714. ungrouped_count=ungrouped,
  715. message=f"Ungrouped {ungrouped} item(s)",
  716. )
  717. @router.get("/batches", response_model=list[PrintBatchResponse])
  718. async def list_batches(
  719. status: str | None = Query(None, description="Filter by status (active, completed, cancelled)"),
  720. db: AsyncSession = Depends(get_db),
  721. auth_result: tuple[User | None, bool] = Depends(
  722. require_ownership_permission(
  723. Permission.QUEUE_READ_ALL,
  724. Permission.QUEUE_READ_OWN,
  725. )
  726. ),
  727. ):
  728. """List all print batches with progress stats."""
  729. current_user, can_read_all = auth_result
  730. query = select(PrintBatch).order_by(PrintBatch.created_at.desc())
  731. if status:
  732. query = query.where(PrintBatch.status == status)
  733. if current_user is not None and not can_read_all:
  734. query = query.where(PrintBatch.created_by_id == current_user.id)
  735. result = await db.execute(query)
  736. batches = result.scalars().all()
  737. responses = []
  738. for batch in batches:
  739. responses.append(await _build_batch_response(db, batch))
  740. return responses
  741. @router.get("/batches/{batch_id}", response_model=PrintBatchResponse)
  742. async def get_batch(
  743. batch_id: int,
  744. db: AsyncSession = Depends(get_db),
  745. auth_result: tuple[User | None, bool] = Depends(
  746. require_ownership_permission(
  747. Permission.QUEUE_READ_ALL,
  748. Permission.QUEUE_READ_OWN,
  749. )
  750. ),
  751. ):
  752. """Get a print batch with progress stats."""
  753. current_user, can_read_all = auth_result
  754. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  755. batch = result.scalar_one_or_none()
  756. if not batch:
  757. raise HTTPException(404, "Batch not found")
  758. if (
  759. current_user is not None
  760. and not can_read_all
  761. and (batch.created_by_id is None or batch.created_by_id != current_user.id)
  762. ):
  763. raise HTTPException(404, "Batch not found")
  764. return await _build_batch_response(db, batch)
  765. @router.delete("/batches/{batch_id}")
  766. async def cancel_batch(
  767. batch_id: int,
  768. db: AsyncSession = Depends(get_db),
  769. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_DELETE_ALL),
  770. ):
  771. """Cancel all pending items in a batch and mark batch as cancelled."""
  772. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  773. batch = result.scalar_one_or_none()
  774. if not batch:
  775. raise HTTPException(404, "Batch not found")
  776. # Cancel all pending queue items in this batch
  777. result = await db.execute(
  778. select(PrintQueueItem).where(and_(PrintQueueItem.batch_id == batch_id, PrintQueueItem.status == "pending"))
  779. )
  780. pending_items = result.scalars().all()
  781. cancelled_count = 0
  782. for item in pending_items:
  783. item.status = "cancelled"
  784. cancelled_count += 1
  785. batch.status = "cancelled"
  786. await db.commit()
  787. return {"message": f"Batch cancelled, {cancelled_count} pending items cancelled"}
  788. async def _build_batch_response(db: AsyncSession, batch: PrintBatch) -> PrintBatchResponse:
  789. """Build a batch response with derived counts from queue items."""
  790. # Count queue items by status
  791. result = await db.execute(
  792. select(PrintQueueItem.status, func.count(PrintQueueItem.id))
  793. .where(PrintQueueItem.batch_id == batch.id)
  794. .group_by(PrintQueueItem.status)
  795. )
  796. status_counts = {row[0]: row[1] for row in result.fetchall()}
  797. # Load created_by for username
  798. created_by_username = None
  799. if batch.created_by_id:
  800. result = await db.execute(select(User).where(User.id == batch.created_by_id))
  801. user = result.scalar_one_or_none()
  802. if user:
  803. created_by_username = user.username
  804. return PrintBatchResponse(
  805. id=batch.id,
  806. name=batch.name,
  807. archive_id=batch.archive_id,
  808. library_file_id=batch.library_file_id,
  809. quantity=batch.quantity,
  810. status=batch.status,
  811. created_at=batch.created_at,
  812. created_by_id=batch.created_by_id,
  813. created_by_username=created_by_username,
  814. pending_count=status_counts.get("pending", 0),
  815. printing_count=status_counts.get("printing", 0),
  816. completed_count=status_counts.get("completed", 0),
  817. failed_count=status_counts.get("failed", 0),
  818. cancelled_count=status_counts.get("cancelled", 0),
  819. )
  820. @router.get("/{item_id}", response_model=PrintQueueItemResponse)
  821. async def get_queue_item(
  822. item_id: int,
  823. db: AsyncSession = Depends(get_db),
  824. auth_result: tuple[User | None, bool] = Depends(
  825. require_ownership_permission(
  826. Permission.QUEUE_READ_ALL,
  827. Permission.QUEUE_READ_OWN,
  828. )
  829. ),
  830. ):
  831. """Get a specific queue item."""
  832. current_user, can_read_all = auth_result
  833. result = await db.execute(
  834. select(PrintQueueItem)
  835. .options(
  836. selectinload(PrintQueueItem.archive),
  837. selectinload(PrintQueueItem.printer),
  838. selectinload(PrintQueueItem.library_file),
  839. selectinload(PrintQueueItem.created_by),
  840. selectinload(PrintQueueItem.batch),
  841. )
  842. .where(PrintQueueItem.id == item_id)
  843. )
  844. item = result.scalar_one_or_none()
  845. if not item:
  846. raise HTTPException(404, "Queue item not found")
  847. if (
  848. current_user is not None
  849. and not can_read_all
  850. and (item.created_by_id is None or item.created_by_id != current_user.id)
  851. ):
  852. raise HTTPException(404, "Queue item not found")
  853. return _enrich_response(item)
  854. @router.patch("/{item_id}", response_model=PrintQueueItemResponse)
  855. async def update_queue_item(
  856. item_id: int,
  857. data: PrintQueueItemUpdate,
  858. db: AsyncSession = Depends(get_db),
  859. auth_result: tuple[User | None, bool] = Depends(
  860. require_ownership_permission(
  861. Permission.QUEUE_UPDATE_ALL,
  862. Permission.QUEUE_UPDATE_OWN,
  863. )
  864. ),
  865. ):
  866. """Update a queue item."""
  867. user, can_modify_all = auth_result
  868. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  869. item = result.scalar_one_or_none()
  870. if not item:
  871. raise HTTPException(404, "Queue item not found")
  872. # Ownership check
  873. if not can_modify_all:
  874. if item.created_by_id != user.id:
  875. raise HTTPException(403, "You can only update your own queue items")
  876. if item.status != "pending":
  877. raise HTTPException(400, "Can only update pending items")
  878. update_data = data.model_dump(exclude_unset=True)
  879. # Normalize target_model if being updated
  880. if "target_model" in update_data and update_data["target_model"]:
  881. update_data["target_model"] = (
  882. normalize_printer_model(update_data["target_model"])
  883. or normalize_printer_model_id(update_data["target_model"])
  884. or update_data["target_model"]
  885. )
  886. # Cannot specify both printer_id and target_model
  887. new_printer_id = update_data.get("printer_id", item.printer_id)
  888. new_target_model = update_data.get("target_model", item.target_model)
  889. if new_printer_id and new_target_model:
  890. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  891. # Validate new printer_id if being changed (and not None)
  892. if "printer_id" in update_data and update_data["printer_id"] is not None:
  893. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  894. if not result.scalar_one_or_none():
  895. raise HTTPException(400, "Printer not found")
  896. # Validate target_model has active printers
  897. if "target_model" in update_data and update_data["target_model"]:
  898. result = await db.execute(
  899. select(Printer).where(Printer.model == update_data["target_model"]).where(Printer.is_active == True) # noqa: E712
  900. )
  901. if not result.scalars().first():
  902. raise HTTPException(400, f"No active printers for model: {update_data['target_model']}")
  903. # Serialize ams_mapping to JSON for TEXT column storage
  904. if "ams_mapping" in update_data:
  905. update_data["ams_mapping"] = json.dumps(update_data["ams_mapping"]) if update_data["ams_mapping"] else None
  906. # Serialize filament_overrides to JSON for TEXT column storage
  907. if "filament_overrides" in update_data:
  908. update_data["filament_overrides"] = (
  909. json.dumps(update_data["filament_overrides"]) if update_data["filament_overrides"] else None
  910. )
  911. # Serialize H2C rack-swap nozzle pick (#1780) to JSON for TEXT column
  912. # storage; same Text-as-opaque-blob convention as ams_mapping above.
  913. if "nozzle_mapping" in update_data:
  914. update_data["nozzle_mapping"] = (
  915. json.dumps(update_data["nozzle_mapping"]) if update_data["nozzle_mapping"] else None
  916. )
  917. for field, value in update_data.items():
  918. setattr(item, field, value)
  919. await db.commit()
  920. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  921. logger.info("Updated queue item %s", item_id)
  922. return _enrich_response(item)
  923. @router.delete("/{item_id}")
  924. async def delete_queue_item(
  925. item_id: int,
  926. db: AsyncSession = Depends(get_db),
  927. auth_result: tuple[User | None, bool] = Depends(
  928. require_ownership_permission(
  929. Permission.QUEUE_DELETE_ALL,
  930. Permission.QUEUE_DELETE_OWN,
  931. )
  932. ),
  933. ):
  934. """Remove an item from the queue."""
  935. user, can_modify_all = auth_result
  936. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  937. item = result.scalar_one_or_none()
  938. if not item:
  939. raise HTTPException(404, "Queue item not found")
  940. # Ownership check
  941. if not can_modify_all:
  942. if item.created_by_id != user.id:
  943. raise HTTPException(403, "You can only delete your own queue items")
  944. if item.status == "printing":
  945. raise HTTPException(400, "Cannot delete item that is currently printing")
  946. await db.delete(item)
  947. await db.commit()
  948. logger.info("Deleted queue item %s", item_id)
  949. return {"message": "Queue item deleted"}
  950. @router.post("/reorder")
  951. async def reorder_queue(
  952. data: PrintQueueReorder,
  953. db: AsyncSession = Depends(get_db),
  954. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  955. ):
  956. """Bulk update positions for queue items."""
  957. for reorder_item in data.items:
  958. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == reorder_item.id))
  959. item = result.scalar_one_or_none()
  960. if item and item.status == "pending":
  961. item.position = reorder_item.position
  962. await db.commit()
  963. logger.info("Reordered %s queue items", len(data.items))
  964. return {"message": f"Reordered {len(data.items)} items"}
  965. @router.post("/{item_id}/cancel")
  966. async def cancel_queue_item(
  967. item_id: int,
  968. db: AsyncSession = Depends(get_db),
  969. auth_result: tuple[User | None, bool] = Depends(
  970. require_ownership_permission(
  971. Permission.QUEUE_UPDATE_ALL,
  972. Permission.QUEUE_UPDATE_OWN,
  973. )
  974. ),
  975. ):
  976. """Cancel a pending queue item."""
  977. user, can_modify_all = auth_result
  978. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  979. item = result.scalar_one_or_none()
  980. if not item:
  981. raise HTTPException(404, "Queue item not found")
  982. # Ownership check
  983. if not can_modify_all:
  984. if item.created_by_id != user.id:
  985. raise HTTPException(403, "You can only cancel your own queue items")
  986. if item.status not in ("pending",):
  987. raise HTTPException(400, f"Cannot cancel item with status '{item.status}'")
  988. item.status = "cancelled"
  989. item.completed_at = datetime.now(timezone.utc)
  990. await db.commit()
  991. logger.info("Cancelled queue item %s", item_id)
  992. return {"message": "Queue item cancelled"}
  993. @router.post("/{item_id}/stop")
  994. async def stop_queue_item(
  995. item_id: int,
  996. db: AsyncSession = Depends(get_db),
  997. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  998. ):
  999. """Stop an actively printing queue item."""
  1000. from backend.app.models.smart_plug import SmartPlug
  1001. from backend.app.services.printer_manager import printer_manager
  1002. from backend.app.services.tasmota import tasmota_service
  1003. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1004. item = result.scalar_one_or_none()
  1005. if not item:
  1006. raise HTTPException(404, "Queue item not found")
  1007. if item.status != "printing":
  1008. raise HTTPException(400, f"Can only stop items that are printing, current status: '{item.status}'")
  1009. # Capture values we need for background task
  1010. printer_id = item.printer_id
  1011. auto_off_after = item.auto_off_after
  1012. # Try to send stop command to printer
  1013. stop_sent = False
  1014. try:
  1015. stop_sent = printer_manager.stop_print(printer_id)
  1016. if not stop_sent:
  1017. logger.warning("stop_print returned False for printer %s - printer may not be connected", printer_id)
  1018. except Exception as e:
  1019. logger.error("Error sending stop command for queue item %s: %s", item_id, e)
  1020. # Mark this printer as user-stopped BEFORE the first await so that if the
  1021. # MQTT on_print_complete callback fires during the db.commit() yield the flag
  1022. # is already set and the "failed" status will be correctly overridden to
  1023. # "cancelled" (preventing a spurious "print failed" notification).
  1024. try:
  1025. from backend.app.main import mark_printer_stopped_by_user
  1026. mark_printer_stopped_by_user(printer_id)
  1027. except Exception as _mark_err:
  1028. logger.warning("Failed to mark printer %s as user-stopped: %s", printer_id, _mark_err)
  1029. # Update queue item status regardless - if printer is off, print is already stopped
  1030. item.status = "cancelled"
  1031. item.completed_at = datetime.now(timezone.utc)
  1032. item.error_message = "Stopped by user" if stop_sent else "Stopped by user (printer was offline)"
  1033. await db.commit()
  1034. # Get smart plug info if auto-off is enabled
  1035. plug_ip = None
  1036. if auto_off_after:
  1037. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1038. plug = result.scalar_one_or_none()
  1039. if plug and plug.enabled:
  1040. plug_ip = plug.ip_address
  1041. logger.info("Stopped printing queue item %s (stop command sent: %s)", item_id, stop_sent)
  1042. # Schedule background task for cooldown + power off
  1043. if plug_ip:
  1044. async def cooldown_and_poweroff():
  1045. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", printer_id)
  1046. await printer_manager.wait_for_cooldown(printer_id, target_temp=50.0, timeout=600)
  1047. # Re-fetch plug since we're in a new async context
  1048. from backend.app.core.database import async_session
  1049. async with async_session() as new_db:
  1050. result = await new_db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1051. plug = result.scalar_one_or_none()
  1052. if plug and plug.enabled:
  1053. logger.info("Auto-off: Powering off printer %s", printer_id)
  1054. await tasmota_service.turn_off(plug)
  1055. spawn_background_task(cooldown_and_poweroff(), name=f"queue-cooldown-poweroff-{printer_id}")
  1056. return {"message": "Print stopped" if stop_sent else "Queue item cancelled (printer was offline)"}
  1057. @router.post("/{item_id}/start")
  1058. async def start_queue_item(
  1059. item_id: int,
  1060. skip_filament_check: bool = Query(default=False),
  1061. db: AsyncSession = Depends(get_db),
  1062. user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_OWN),
  1063. ):
  1064. """Manually start a staged (manual_start) queue item.
  1065. Clears the manual_start flag so the scheduler picks it up. When
  1066. ``skip_filament_check`` is false (the default) the live filament
  1067. deficit (#1496) is checked first — if the assigned spool can't satisfy
  1068. a slot's required grams, the route returns ``409`` with the deficit
  1069. payload so the caller can show a confirm dialog and retry with
  1070. ``skip_filament_check=true``.
  1071. """
  1072. result = await db.execute(
  1073. select(PrintQueueItem)
  1074. .options(
  1075. selectinload(PrintQueueItem.archive),
  1076. selectinload(PrintQueueItem.printer),
  1077. selectinload(PrintQueueItem.library_file),
  1078. selectinload(PrintQueueItem.batch),
  1079. )
  1080. .where(PrintQueueItem.id == item_id)
  1081. )
  1082. item = result.scalar_one_or_none()
  1083. if not item:
  1084. raise HTTPException(404, "Queue item not found")
  1085. if item.status != "pending":
  1086. raise HTTPException(400, f"Can only start pending items, current status: '{item.status}'")
  1087. # Live deficit check — re-evaluated against current spool state, so a
  1088. # spool swap between scheduler flagging and the user clicking ▶ clears
  1089. # the block automatically.
  1090. if not skip_filament_check:
  1091. deficit = await compute_deficit_for_queue_item(db, item)
  1092. if deficit:
  1093. raise HTTPException(
  1094. status_code=409,
  1095. detail={
  1096. "code": "insufficient_filament",
  1097. "deficit": [d.to_dict() for d in deficit],
  1098. },
  1099. )
  1100. # Print Anyway / no deficit: clear the flags and let the scheduler dispatch.
  1101. item.manual_start = False
  1102. item.filament_short = False
  1103. # Persist the user's "Print Anyway" decision so the scheduler does not
  1104. # immediately re-flag this item on the next tick (#1698-followup). The
  1105. # pre-fix behaviour bounced between "user said anyway" and
  1106. # "scheduler re-blocked on same deficit" forever.
  1107. if skip_filament_check:
  1108. item.skip_filament_check = True
  1109. # Credit the clicker as the item's owner when no prior owner is set —
  1110. # VP-uploaded queue items arrive over FTP unattributed, so without this
  1111. # the print log's User column stays blank even when auth is on
  1112. # (#1670). An item that already has a creator (UI-added queue items)
  1113. # keeps that attribution; the dispatcher is not promoted over the
  1114. # original uploader.
  1115. if user is not None and item.created_by_id is None:
  1116. item.created_by_id = user.id
  1117. await db.commit()
  1118. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  1119. logger.info(
  1120. "Manually started queue item %s (cleared manual_start; skip_filament_check=%s)",
  1121. item_id,
  1122. skip_filament_check,
  1123. )
  1124. return _enrich_response(item)