print_queue.py 66 KB

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