print_queue.py 52 KB

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