print_queue.py 79 KB

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