print_queue.py 60 KB

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