print_queue.py 68 KB

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