print_queue.py 59 KB

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