print_queue.py 64 KB

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