print_queue.py 62 KB

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