print_queue.py 54 KB

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