print_queue.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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
  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. PrintBatchResponse,
  26. PrintQueueBulkUpdate,
  27. PrintQueueBulkUpdateResponse,
  28. PrintQueueItemCreate,
  29. PrintQueueItemResponse,
  30. PrintQueueItemUpdate,
  31. PrintQueueReorder,
  32. )
  33. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  34. from backend.app.services.notification_service import notification_service
  35. from backend.app.utils.printer_models import normalize_printer_model, normalize_printer_model_id
  36. from backend.app.utils.threemf_tools import extract_bed_type_from_3mf, extract_filament_usage_from_3mf
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/queue", tags=["queue"])
  39. def _extract_filament_types_from_3mf(file_path: Path, plate_id: int | None = None) -> list[str]:
  40. """Extract unique filament types from a 3MF file.
  41. Args:
  42. file_path: Path to the 3MF file
  43. plate_id: Optional plate index to filter for (for multi-plate files)
  44. Returns:
  45. List of unique filament types (e.g., ["PLA", "PETG"])
  46. """
  47. types: set[str] = set()
  48. try:
  49. with zipfile.ZipFile(file_path, "r") as zf:
  50. if "Metadata/slice_info.config" not in zf.namelist():
  51. return []
  52. content = zf.read("Metadata/slice_info.config").decode()
  53. root = ET.fromstring(content)
  54. if plate_id is not None:
  55. # Find the plate element with matching index
  56. for plate_elem in root.findall(".//plate"):
  57. plate_index = None
  58. for meta in plate_elem.findall("metadata"):
  59. if meta.get("key") == "index":
  60. try:
  61. plate_index = int(meta.get("value", "0"))
  62. except ValueError:
  63. pass # Skip plate with unparseable index
  64. break
  65. if plate_index == plate_id:
  66. for filament_elem in plate_elem.findall("filament"):
  67. filament_type = filament_elem.get("type", "")
  68. used_g = filament_elem.get("used_g", "0")
  69. try:
  70. used_grams = float(used_g)
  71. except (ValueError, TypeError):
  72. used_grams = 0
  73. if used_grams > 0 and filament_type:
  74. types.add(filament_type)
  75. break
  76. else:
  77. # No plate_id specified - extract all filaments with used_g > 0
  78. for filament_elem in root.findall(".//filament"):
  79. filament_type = filament_elem.get("type", "")
  80. used_g = filament_elem.get("used_g", "0")
  81. try:
  82. used_grams = float(used_g)
  83. except (ValueError, TypeError):
  84. used_grams = 0
  85. if used_grams > 0 and filament_type:
  86. types.add(filament_type)
  87. except Exception as e:
  88. logger.warning("Failed to extract filament types from %s: %s", file_path, e)
  89. return sorted(types)
  90. def _extract_print_time_from_3mf(file_path: Path, plate_id: int | None = None) -> int | None:
  91. """Extract print time (prediction) from a 3MF file.
  92. Args:
  93. file_path: Path to the 3MF file
  94. plate_id: Optional plate index to filter for (for multi-plate files)
  95. Returns:
  96. Print time in seconds, or None if not found
  97. """
  98. try:
  99. with zipfile.ZipFile(file_path, "r") as zf:
  100. if "Metadata/slice_info.config" not in zf.namelist():
  101. return None
  102. content = zf.read("Metadata/slice_info.config").decode()
  103. root = ET.fromstring(content)
  104. if plate_id is not None:
  105. for plate_elem in root.findall(".//plate"):
  106. plate_index = None
  107. for meta in plate_elem.findall("metadata"):
  108. if meta.get("key") == "index":
  109. try:
  110. plate_index = int(meta.get("value", "0"))
  111. except ValueError:
  112. pass # Skip plate with unparseable index
  113. break
  114. if plate_index == plate_id:
  115. for meta in plate_elem.findall("metadata"):
  116. if meta.get("key") == "prediction":
  117. try:
  118. return int(meta.get("value", "0"))
  119. except ValueError:
  120. return None
  121. break
  122. else:
  123. plate_elem = root.find(".//plate")
  124. if plate_elem is not None:
  125. for meta in plate_elem.findall("metadata"):
  126. if meta.get("key") == "prediction":
  127. try:
  128. return int(meta.get("value", "0"))
  129. except ValueError:
  130. return None
  131. except Exception as e:
  132. logger.warning("Failed to extract print time from %s: %s", file_path, e)
  133. return None
  134. def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
  135. """Add nested archive/printer/library_file info to response."""
  136. # Parse ams_mapping from JSON string BEFORE model_validate
  137. ams_mapping_parsed = None
  138. if item.ams_mapping:
  139. try:
  140. ams_mapping_parsed = json.loads(item.ams_mapping)
  141. except json.JSONDecodeError:
  142. ams_mapping_parsed = None
  143. # Parse required_filament_types from JSON string
  144. required_filament_types_parsed = None
  145. if item.required_filament_types:
  146. try:
  147. required_filament_types_parsed = json.loads(item.required_filament_types)
  148. except json.JSONDecodeError:
  149. required_filament_types_parsed = None
  150. # Parse filament_overrides from JSON string
  151. filament_overrides_parsed = None
  152. if item.filament_overrides:
  153. try:
  154. filament_overrides_parsed = json.loads(item.filament_overrides)
  155. except json.JSONDecodeError:
  156. filament_overrides_parsed = None
  157. # Create response with parsed ams_mapping
  158. item_dict = {
  159. "id": item.id,
  160. "printer_id": item.printer_id,
  161. "target_model": item.target_model,
  162. "target_location": item.target_location,
  163. "required_filament_types": required_filament_types_parsed,
  164. "filament_overrides": filament_overrides_parsed,
  165. "waiting_reason": item.waiting_reason,
  166. "archive_id": item.archive_id,
  167. "library_file_id": item.library_file_id,
  168. "position": item.position,
  169. "scheduled_time": item.scheduled_time,
  170. "require_previous_success": item.require_previous_success,
  171. "auto_off_after": item.auto_off_after,
  172. "manual_start": item.manual_start,
  173. "filament_short": bool(item.filament_short),
  174. "skip_filament_check": bool(item.skip_filament_check),
  175. "ams_mapping": ams_mapping_parsed,
  176. "plate_id": item.plate_id,
  177. "bed_levelling": item.bed_levelling,
  178. "flow_cali": item.flow_cali,
  179. "vibration_cali": item.vibration_cali,
  180. "layer_inspect": item.layer_inspect,
  181. "timelapse": item.timelapse,
  182. "use_ams": item.use_ams,
  183. "nozzle_offset_cali": item.nozzle_offset_cali,
  184. "status": item.status,
  185. "started_at": item.started_at,
  186. "completed_at": item.completed_at,
  187. "error_message": item.error_message,
  188. "created_at": item.created_at,
  189. # User tracking (Issue #206)
  190. "created_by_id": item.created_by_id,
  191. "created_by_username": item.created_by.username if item.created_by else None,
  192. # Batch grouping
  193. "batch_id": item.batch_id,
  194. "batch_name": item.batch.name if item.batch else None,
  195. # SJF scheduling
  196. "been_jumped": item.been_jumped,
  197. # Auto-print G-code injection
  198. "gcode_injection": item.gcode_injection,
  199. }
  200. response = PrintQueueItemResponse(**item_dict)
  201. if item.archive:
  202. # Soft-deleted archive: files are gone from disk but the row stays
  203. # (its filament/cost contribution still flows into stats per #1343).
  204. # Suppress the archive-derived UI surface so the queue page doesn't
  205. # 404-storm the thumbnail / plates / plate-thumbnail endpoints — the
  206. # frontend's existing truthy gate on archive_thumbnail covers it
  207. # (#1348 follow-up). The archive_deleted flag lets the UI render a
  208. # "source deleted" badge on these rows.
  209. if item.archive.deleted_at is not None:
  210. response.archive_deleted = True
  211. else:
  212. response.archive_name = item.archive.print_name or item.archive.filename
  213. response.archive_thumbnail = item.archive.thumbnail_path
  214. response.print_time_seconds = item.archive.print_time_seconds
  215. response.filament_used_grams = item.archive.filament_used_grams
  216. response.filament_type = item.archive.filament_type
  217. response.filament_color = item.archive.filament_color
  218. response.layer_height = item.archive.layer_height
  219. response.nozzle_diameter = item.archive.nozzle_diameter
  220. response.sliced_for_model = item.archive.sliced_for_model
  221. response.bed_type = item.archive.bed_type
  222. if item.plate_id:
  223. archive_path = settings.base_dir / item.archive.file_path
  224. if archive_path.exists():
  225. plate_time = _extract_print_time_from_3mf(archive_path, item.plate_id)
  226. plate_weight = sum(
  227. f["used_g"] for f in extract_filament_usage_from_3mf(archive_path, item.plate_id)
  228. )
  229. plate_bed = extract_bed_type_from_3mf(archive_path, item.plate_id)
  230. if plate_time is not None:
  231. response.print_time_seconds = plate_time
  232. if plate_weight > 0:
  233. response.filament_used_grams = plate_weight
  234. if plate_bed:
  235. response.bed_type = plate_bed
  236. if item.library_file:
  237. response.library_file_name = (
  238. item.library_file.file_metadata.get("print_name") if item.library_file.file_metadata else None
  239. )
  240. if not response.library_file_name:
  241. response.library_file_name = item.library_file.filename
  242. response.library_file_thumbnail = item.library_file.thumbnail_path
  243. # Get metadata from library file if no archive
  244. if not item.archive and item.library_file.file_metadata:
  245. response.print_time_seconds = item.library_file.file_metadata.get("print_time_seconds")
  246. response.filament_used_grams = item.library_file.file_metadata.get("filament_used_grams")
  247. response.filament_type = item.library_file.file_metadata.get("filament_type")
  248. response.filament_color = item.library_file.file_metadata.get("filament_color")
  249. response.layer_height = item.library_file.file_metadata.get("layer_height")
  250. response.nozzle_diameter = item.library_file.file_metadata.get("nozzle_diameter")
  251. response.sliced_for_model = item.library_file.file_metadata.get("sliced_for_model")
  252. response.bed_type = item.library_file.file_metadata.get("bed_type")
  253. if item.plate_id:
  254. lib_path = Path(item.library_file.file_path)
  255. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / item.library_file.file_path
  256. if library_file_path.exists():
  257. plate_time = _extract_print_time_from_3mf(library_file_path, item.plate_id)
  258. plate_weight = sum(
  259. f["used_g"] for f in extract_filament_usage_from_3mf(library_file_path, item.plate_id)
  260. )
  261. plate_bed = extract_bed_type_from_3mf(library_file_path, item.plate_id)
  262. if plate_time is not None:
  263. response.print_time_seconds = plate_time
  264. if plate_weight > 0:
  265. response.filament_used_grams = plate_weight
  266. if plate_bed:
  267. response.bed_type = plate_bed
  268. if item.printer:
  269. response.printer_name = item.printer.name
  270. return response
  271. @router.get("/", response_model=list[PrintQueueItemResponse])
  272. async def list_queue(
  273. printer_id: int | None = Query(None, description="Filter by printer (-1 for unassigned)"),
  274. status: str | None = Query(None, description="Filter by status"),
  275. target_model: str | None = Query(
  276. None, description="Filter by target model (also includes model-based items when combined with printer_id)"
  277. ),
  278. db: AsyncSession = Depends(get_db),
  279. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_READ),
  280. ):
  281. """List all queue items, optionally filtered by printer or status."""
  282. query = (
  283. select(PrintQueueItem)
  284. .options(
  285. selectinload(PrintQueueItem.archive),
  286. selectinload(PrintQueueItem.printer),
  287. selectinload(PrintQueueItem.library_file),
  288. selectinload(PrintQueueItem.created_by),
  289. selectinload(PrintQueueItem.batch),
  290. )
  291. .order_by(PrintQueueItem.printer_id.nulls_first(), PrintQueueItem.position)
  292. )
  293. if printer_id is not None:
  294. if printer_id == -1:
  295. # Special value: filter for unassigned items
  296. query = query.where(PrintQueueItem.printer_id.is_(None))
  297. else:
  298. # Resolve effective model: prefer explicit param, fall back to printer's DB model.
  299. # This ensures model-based "Any X" items are returned even when the frontend
  300. # doesn't send target_model (e.g. printer.model is NULL on the client side).
  301. effective_model = target_model
  302. if not effective_model:
  303. printer_row = (
  304. await db.execute(select(Printer.model).where(Printer.id == printer_id))
  305. ).scalar_one_or_none()
  306. effective_model = printer_row
  307. if effective_model:
  308. # Include both printer-specific items AND model-based (unassigned) items
  309. query = query.where(
  310. or_(
  311. PrintQueueItem.printer_id == printer_id,
  312. and_(
  313. PrintQueueItem.printer_id.is_(None),
  314. func.lower(PrintQueueItem.target_model) == effective_model.lower(),
  315. ),
  316. )
  317. )
  318. else:
  319. query = query.where(PrintQueueItem.printer_id == printer_id)
  320. elif target_model:
  321. query = query.where(func.lower(PrintQueueItem.target_model) == target_model.lower())
  322. if status:
  323. query = query.where(PrintQueueItem.status == status)
  324. result = await db.execute(query)
  325. items = result.scalars().all()
  326. return [_enrich_response(item) for item in items]
  327. @router.post("/", response_model=PrintQueueItemResponse)
  328. async def add_to_queue(
  329. data: PrintQueueItemCreate,
  330. db: AsyncSession = Depends(get_db),
  331. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  332. ):
  333. """Add an item to the print queue."""
  334. # Normalize target_model (e.g., "Bambu Lab X1E" / "C13" -> "X1E")
  335. target_model_norm = None
  336. if data.target_model:
  337. target_model_norm = (
  338. normalize_printer_model(data.target_model)
  339. or normalize_printer_model_id(data.target_model)
  340. or data.target_model
  341. )
  342. # Validate that either archive_id or library_file_id is provided
  343. if not data.archive_id and not data.library_file_id:
  344. raise HTTPException(400, "Either archive_id or library_file_id must be provided")
  345. # Cannot specify both printer_id and target_model
  346. if data.printer_id and target_model_norm:
  347. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  348. # Validate printer exists (if assigned)
  349. if data.printer_id is not None:
  350. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  351. if not result.scalar_one_or_none():
  352. raise HTTPException(400, "Printer not found")
  353. # Validate target_model has active printers
  354. if target_model_norm:
  355. result = await db.execute(
  356. select(Printer).where(Printer.model == target_model_norm).where(Printer.is_active == True) # noqa: E712
  357. )
  358. if not result.scalars().first():
  359. raise HTTPException(400, f"No active printers for model: {target_model_norm}")
  360. # Validate archive exists (if provided) and get it for filament extraction
  361. archive = None
  362. if data.archive_id:
  363. result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  364. archive = result.scalar_one_or_none()
  365. if not archive:
  366. raise HTTPException(400, "Archive not found")
  367. # Validate library file exists (if provided) and get it for filament extraction
  368. library_file = None
  369. if data.library_file_id:
  370. result = await db.execute(LibraryFile.active().where(LibraryFile.id == data.library_file_id))
  371. library_file = result.scalar_one_or_none()
  372. if not library_file:
  373. raise HTTPException(400, "Library file not found")
  374. # Bambu SD card is FAT32/exFAT — illegal filename chars would 553 at
  375. # FTP upload time (#1540). Reject at queue time so the user gets the
  376. # actionable error before waiting in queue.
  377. from backend.app.utils.filename import InvalidFilenameError, validate_print_filename
  378. try:
  379. validate_print_filename(library_file.filename)
  380. except InvalidFilenameError as e:
  381. raise HTTPException(400, str(e)) from e
  382. # Extract filament types for model-based assignment (used by scheduler for validation)
  383. required_filament_types = None
  384. if target_model_norm:
  385. # Get file path from archive or library file
  386. file_path = None
  387. if archive:
  388. file_path = settings.base_dir / archive.file_path
  389. elif library_file:
  390. lib_path = Path(library_file.file_path)
  391. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  392. if file_path and file_path.exists():
  393. filament_types = _extract_filament_types_from_3mf(file_path, data.plate_id)
  394. if filament_types:
  395. required_filament_types = json.dumps(filament_types)
  396. logger.info("Extracted filament types for model-based queue: %s", filament_types)
  397. # If filament overrides are provided, update required_filament_types to match override types
  398. filament_overrides_json = None
  399. if data.filament_overrides and target_model_norm:
  400. filament_overrides_json = json.dumps(data.filament_overrides)
  401. # Update required_filament_types from overrides so scheduler validates against overridden types
  402. override_types = sorted({o["type"] for o in data.filament_overrides if "type" in o})
  403. if override_types:
  404. # Merge with existing types (overrides may only cover some slots)
  405. existing_types = set(json.loads(required_filament_types)) if required_filament_types else set()
  406. # Replace types for overridden slots, keep others
  407. all_types = existing_types | set(override_types)
  408. required_filament_types = json.dumps(sorted(all_types))
  409. # Validate quantity
  410. quantity = max(1, data.quantity)
  411. # Create batch if quantity > 1
  412. batch = None
  413. batch_id = None
  414. if quantity > 1:
  415. # Derive batch name from source file
  416. batch_name_base = "Batch"
  417. if archive:
  418. batch_name_base = archive.print_name or archive.filename or "Batch"
  419. elif library_file:
  420. if library_file.file_metadata:
  421. batch_name_base = library_file.file_metadata.get("print_name") or library_file.filename
  422. else:
  423. batch_name_base = library_file.filename
  424. batch_name_base = batch_name_base.replace(".gcode.3mf", "").replace(".3mf", "")
  425. batch = PrintBatch(
  426. name=f"{batch_name_base} ×{quantity}",
  427. archive_id=data.archive_id,
  428. library_file_id=data.library_file_id,
  429. quantity=quantity,
  430. status="active",
  431. created_by_id=current_user.id if current_user else None,
  432. )
  433. db.add(batch)
  434. await db.flush() # Get batch.id before creating items
  435. batch_id = batch.id
  436. # Get next position for this printer (or for unassigned/model-based items)
  437. if data.printer_id is not None:
  438. result = await db.execute(
  439. select(func.max(PrintQueueItem.position))
  440. .where(PrintQueueItem.printer_id == data.printer_id)
  441. .where(PrintQueueItem.status == "pending")
  442. )
  443. else:
  444. # For unassigned/model-based items, get max position across all unassigned
  445. result = await db.execute(
  446. select(func.max(PrintQueueItem.position))
  447. .where(PrintQueueItem.printer_id.is_(None))
  448. .where(PrintQueueItem.status == "pending")
  449. )
  450. max_pos = result.scalar() or 0
  451. # Resolve print_time_seconds for SJF scheduling (cache on item at creation)
  452. cached_print_time = None
  453. if archive:
  454. cached_print_time = archive.print_time_seconds
  455. if data.plate_id:
  456. archive_path = settings.base_dir / archive.file_path
  457. if archive_path.exists():
  458. plate_time = _extract_print_time_from_3mf(archive_path, data.plate_id)
  459. if plate_time is not None:
  460. cached_print_time = plate_time
  461. elif library_file:
  462. if library_file.file_metadata:
  463. cached_print_time = library_file.file_metadata.get("print_time_seconds")
  464. if data.plate_id:
  465. lib_path = Path(library_file.file_path)
  466. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  467. if library_file_path.exists():
  468. plate_time = _extract_print_time_from_3mf(library_file_path, data.plate_id)
  469. if plate_time is not None:
  470. cached_print_time = plate_time
  471. # Validate project exists before insert so a bogus ID yields 404, not an FK-constraint 500
  472. if data.project_id is not None:
  473. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  474. if not project_result.scalar_one_or_none():
  475. raise HTTPException(status_code=404, detail="Project not found")
  476. ams_mapping_json = json.dumps(data.ams_mapping) if data.ams_mapping else None
  477. items = []
  478. for i in range(quantity):
  479. item = PrintQueueItem(
  480. printer_id=data.printer_id,
  481. target_model=target_model_norm,
  482. target_location=data.target_location,
  483. required_filament_types=required_filament_types,
  484. filament_overrides=filament_overrides_json,
  485. archive_id=data.archive_id,
  486. library_file_id=data.library_file_id,
  487. scheduled_time=data.scheduled_time,
  488. require_previous_success=data.require_previous_success,
  489. auto_off_after=data.auto_off_after,
  490. manual_start=data.manual_start,
  491. skip_filament_check=data.skip_filament_check,
  492. ams_mapping=ams_mapping_json,
  493. plate_id=data.plate_id,
  494. bed_levelling=data.bed_levelling,
  495. flow_cali=data.flow_cali,
  496. vibration_cali=data.vibration_cali,
  497. layer_inspect=data.layer_inspect,
  498. timelapse=data.timelapse,
  499. use_ams=data.use_ams,
  500. nozzle_offset_cali=data.nozzle_offset_cali,
  501. gcode_injection=data.gcode_injection,
  502. project_id=data.project_id,
  503. position=max_pos + 1 + i,
  504. status="pending",
  505. created_by_id=current_user.id if current_user else None,
  506. batch_id=batch_id,
  507. print_time_seconds=cached_print_time,
  508. )
  509. db.add(item)
  510. items.append(item)
  511. await db.commit()
  512. # Refresh the first item for the response
  513. item = items[0]
  514. await db.refresh(item)
  515. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  516. source_name = f"archive {data.archive_id}" if data.archive_id else f"library file {data.library_file_id}"
  517. target_desc = data.printer_id or (f"model {target_model_norm}" if target_model_norm else "unassigned")
  518. qty_desc = f" (×{quantity})" if quantity > 1 else ""
  519. logger.info("Added %s to queue for %s%s", source_name, target_desc, qty_desc)
  520. # MQTT relay - publish queue job added
  521. try:
  522. from backend.app.services.mqtt_relay import mqtt_relay
  523. await mqtt_relay.on_queue_job_added(
  524. job_id=item.id,
  525. filename=item.archive.filename if item.archive else "",
  526. printer_id=item.printer_id,
  527. printer_name=item.printer.name if item.printer else None,
  528. )
  529. except Exception:
  530. pass # Don't fail queue add if MQTT fails
  531. # Send notification for job added
  532. try:
  533. job_name = (
  534. item.archive.filename
  535. if item.archive
  536. else item.library_file.filename
  537. if item.library_file
  538. else f"Job #{item.id}"
  539. )
  540. job_name = job_name.replace(".gcode.3mf", "").replace(".3mf", "")
  541. if quantity > 1:
  542. job_name = f"{job_name} ×{quantity}"
  543. target = (
  544. item.printer.name if item.printer else (f"Any {item.target_model}" if target_model_norm else "Unassigned")
  545. )
  546. await notification_service.on_queue_job_added(
  547. job_name=job_name,
  548. target=target,
  549. db=db,
  550. printer_id=item.printer_id,
  551. printer_name=item.printer.name if item.printer else None,
  552. )
  553. except Exception:
  554. pass # Don't fail queue add if notification fails
  555. return _enrich_response(item)
  556. @router.patch("/bulk", response_model=PrintQueueBulkUpdateResponse)
  557. async def bulk_update_queue_items(
  558. data: PrintQueueBulkUpdate,
  559. db: AsyncSession = Depends(get_db),
  560. auth_result: tuple[User | None, bool] = Depends(
  561. require_ownership_permission(
  562. Permission.QUEUE_UPDATE_ALL,
  563. Permission.QUEUE_UPDATE_OWN,
  564. )
  565. ),
  566. ):
  567. """Bulk update multiple queue items with the same values.
  568. Only pending items can be updated. Non-pending items are skipped.
  569. Items not owned by the user are also skipped (unless user has *_all permission).
  570. """
  571. user, can_modify_all = auth_result
  572. if not data.item_ids:
  573. raise HTTPException(400, "No item IDs provided")
  574. # Get fields to update (exclude item_ids and unset fields)
  575. update_data = data.model_dump(exclude={"item_ids"}, exclude_unset=True)
  576. if not update_data:
  577. raise HTTPException(400, "No fields to update")
  578. # Validate printer_id if being changed
  579. if "printer_id" in update_data and update_data["printer_id"] is not None:
  580. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  581. if not result.scalar_one_or_none():
  582. raise HTTPException(400, "Printer not found")
  583. # Fetch all items
  584. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  585. items = result.scalars().all()
  586. updated_count = 0
  587. skipped_count = 0
  588. for item in items:
  589. if item.status != "pending":
  590. skipped_count += 1
  591. continue
  592. # Ownership check
  593. if not can_modify_all and item.created_by_id != user.id:
  594. skipped_count += 1
  595. continue
  596. for field, value in update_data.items():
  597. setattr(item, field, value)
  598. updated_count += 1
  599. await db.commit()
  600. logger.info("Bulk updated %s queue items, skipped %s", updated_count, skipped_count)
  601. return PrintQueueBulkUpdateResponse(
  602. updated_count=updated_count,
  603. skipped_count=skipped_count,
  604. message=f"Updated {updated_count} items"
  605. + (f", skipped {skipped_count} non-pending/not-owned" if skipped_count else ""),
  606. )
  607. # --- Batch endpoints ---
  608. @router.get("/batches", response_model=list[PrintBatchResponse])
  609. async def list_batches(
  610. status: str | None = Query(None, description="Filter by status (active, completed, cancelled)"),
  611. db: AsyncSession = Depends(get_db),
  612. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_READ),
  613. ):
  614. """List all print batches with progress stats."""
  615. query = select(PrintBatch).order_by(PrintBatch.created_at.desc())
  616. if status:
  617. query = query.where(PrintBatch.status == status)
  618. result = await db.execute(query)
  619. batches = result.scalars().all()
  620. responses = []
  621. for batch in batches:
  622. responses.append(await _build_batch_response(db, batch))
  623. return responses
  624. @router.get("/batches/{batch_id}", response_model=PrintBatchResponse)
  625. async def get_batch(
  626. batch_id: int,
  627. db: AsyncSession = Depends(get_db),
  628. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_READ),
  629. ):
  630. """Get a print batch with progress stats."""
  631. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  632. batch = result.scalar_one_or_none()
  633. if not batch:
  634. raise HTTPException(404, "Batch not found")
  635. return await _build_batch_response(db, batch)
  636. @router.delete("/batches/{batch_id}")
  637. async def cancel_batch(
  638. batch_id: int,
  639. db: AsyncSession = Depends(get_db),
  640. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_DELETE_ALL),
  641. ):
  642. """Cancel all pending items in a batch and mark batch as cancelled."""
  643. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  644. batch = result.scalar_one_or_none()
  645. if not batch:
  646. raise HTTPException(404, "Batch not found")
  647. # Cancel all pending queue items in this batch
  648. result = await db.execute(
  649. select(PrintQueueItem).where(and_(PrintQueueItem.batch_id == batch_id, PrintQueueItem.status == "pending"))
  650. )
  651. pending_items = result.scalars().all()
  652. cancelled_count = 0
  653. for item in pending_items:
  654. item.status = "cancelled"
  655. cancelled_count += 1
  656. batch.status = "cancelled"
  657. await db.commit()
  658. return {"message": f"Batch cancelled, {cancelled_count} pending items cancelled"}
  659. async def _build_batch_response(db: AsyncSession, batch: PrintBatch) -> PrintBatchResponse:
  660. """Build a batch response with derived counts from queue items."""
  661. # Count queue items by status
  662. result = await db.execute(
  663. select(PrintQueueItem.status, func.count(PrintQueueItem.id))
  664. .where(PrintQueueItem.batch_id == batch.id)
  665. .group_by(PrintQueueItem.status)
  666. )
  667. status_counts = {row[0]: row[1] for row in result.fetchall()}
  668. # Load created_by for username
  669. created_by_username = None
  670. if batch.created_by_id:
  671. result = await db.execute(select(User).where(User.id == batch.created_by_id))
  672. user = result.scalar_one_or_none()
  673. if user:
  674. created_by_username = user.username
  675. return PrintBatchResponse(
  676. id=batch.id,
  677. name=batch.name,
  678. archive_id=batch.archive_id,
  679. library_file_id=batch.library_file_id,
  680. quantity=batch.quantity,
  681. status=batch.status,
  682. created_at=batch.created_at,
  683. created_by_id=batch.created_by_id,
  684. created_by_username=created_by_username,
  685. pending_count=status_counts.get("pending", 0),
  686. printing_count=status_counts.get("printing", 0),
  687. completed_count=status_counts.get("completed", 0),
  688. failed_count=status_counts.get("failed", 0),
  689. cancelled_count=status_counts.get("cancelled", 0),
  690. )
  691. @router.get("/{item_id}", response_model=PrintQueueItemResponse)
  692. async def get_queue_item(
  693. item_id: int,
  694. db: AsyncSession = Depends(get_db),
  695. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_READ),
  696. ):
  697. """Get a specific queue item."""
  698. result = await db.execute(
  699. select(PrintQueueItem)
  700. .options(
  701. selectinload(PrintQueueItem.archive),
  702. selectinload(PrintQueueItem.printer),
  703. selectinload(PrintQueueItem.library_file),
  704. selectinload(PrintQueueItem.created_by),
  705. selectinload(PrintQueueItem.batch),
  706. )
  707. .where(PrintQueueItem.id == item_id)
  708. )
  709. item = result.scalar_one_or_none()
  710. if not item:
  711. raise HTTPException(404, "Queue item not found")
  712. return _enrich_response(item)
  713. @router.patch("/{item_id}", response_model=PrintQueueItemResponse)
  714. async def update_queue_item(
  715. item_id: int,
  716. data: PrintQueueItemUpdate,
  717. db: AsyncSession = Depends(get_db),
  718. auth_result: tuple[User | None, bool] = Depends(
  719. require_ownership_permission(
  720. Permission.QUEUE_UPDATE_ALL,
  721. Permission.QUEUE_UPDATE_OWN,
  722. )
  723. ),
  724. ):
  725. """Update a queue item."""
  726. user, can_modify_all = auth_result
  727. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  728. item = result.scalar_one_or_none()
  729. if not item:
  730. raise HTTPException(404, "Queue item not found")
  731. # Ownership check
  732. if not can_modify_all:
  733. if item.created_by_id != user.id:
  734. raise HTTPException(403, "You can only update your own queue items")
  735. if item.status != "pending":
  736. raise HTTPException(400, "Can only update pending items")
  737. update_data = data.model_dump(exclude_unset=True)
  738. # Normalize target_model if being updated
  739. if "target_model" in update_data and update_data["target_model"]:
  740. update_data["target_model"] = (
  741. normalize_printer_model(update_data["target_model"])
  742. or normalize_printer_model_id(update_data["target_model"])
  743. or update_data["target_model"]
  744. )
  745. # Cannot specify both printer_id and target_model
  746. new_printer_id = update_data.get("printer_id", item.printer_id)
  747. new_target_model = update_data.get("target_model", item.target_model)
  748. if new_printer_id and new_target_model:
  749. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  750. # Validate new printer_id if being changed (and not None)
  751. if "printer_id" in update_data and update_data["printer_id"] is not None:
  752. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  753. if not result.scalar_one_or_none():
  754. raise HTTPException(400, "Printer not found")
  755. # Validate target_model has active printers
  756. if "target_model" in update_data and update_data["target_model"]:
  757. result = await db.execute(
  758. select(Printer).where(Printer.model == update_data["target_model"]).where(Printer.is_active == True) # noqa: E712
  759. )
  760. if not result.scalars().first():
  761. raise HTTPException(400, f"No active printers for model: {update_data['target_model']}")
  762. # Serialize ams_mapping to JSON for TEXT column storage
  763. if "ams_mapping" in update_data:
  764. update_data["ams_mapping"] = json.dumps(update_data["ams_mapping"]) if update_data["ams_mapping"] else None
  765. # Serialize filament_overrides to JSON for TEXT column storage
  766. if "filament_overrides" in update_data:
  767. update_data["filament_overrides"] = (
  768. json.dumps(update_data["filament_overrides"]) if update_data["filament_overrides"] else None
  769. )
  770. for field, value in update_data.items():
  771. setattr(item, field, value)
  772. await db.commit()
  773. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  774. logger.info("Updated queue item %s", item_id)
  775. return _enrich_response(item)
  776. @router.delete("/{item_id}")
  777. async def delete_queue_item(
  778. item_id: int,
  779. db: AsyncSession = Depends(get_db),
  780. auth_result: tuple[User | None, bool] = Depends(
  781. require_ownership_permission(
  782. Permission.QUEUE_DELETE_ALL,
  783. Permission.QUEUE_DELETE_OWN,
  784. )
  785. ),
  786. ):
  787. """Remove an item from the queue."""
  788. user, can_modify_all = auth_result
  789. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  790. item = result.scalar_one_or_none()
  791. if not item:
  792. raise HTTPException(404, "Queue item not found")
  793. # Ownership check
  794. if not can_modify_all:
  795. if item.created_by_id != user.id:
  796. raise HTTPException(403, "You can only delete your own queue items")
  797. if item.status == "printing":
  798. raise HTTPException(400, "Cannot delete item that is currently printing")
  799. await db.delete(item)
  800. await db.commit()
  801. logger.info("Deleted queue item %s", item_id)
  802. return {"message": "Queue item deleted"}
  803. @router.post("/reorder")
  804. async def reorder_queue(
  805. data: PrintQueueReorder,
  806. db: AsyncSession = Depends(get_db),
  807. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  808. ):
  809. """Bulk update positions for queue items."""
  810. for reorder_item in data.items:
  811. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == reorder_item.id))
  812. item = result.scalar_one_or_none()
  813. if item and item.status == "pending":
  814. item.position = reorder_item.position
  815. await db.commit()
  816. logger.info("Reordered %s queue items", len(data.items))
  817. return {"message": f"Reordered {len(data.items)} items"}
  818. @router.post("/{item_id}/cancel")
  819. async def cancel_queue_item(
  820. item_id: int,
  821. db: AsyncSession = Depends(get_db),
  822. auth_result: tuple[User | None, bool] = Depends(
  823. require_ownership_permission(
  824. Permission.QUEUE_UPDATE_ALL,
  825. Permission.QUEUE_UPDATE_OWN,
  826. )
  827. ),
  828. ):
  829. """Cancel a pending queue item."""
  830. user, can_modify_all = auth_result
  831. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  832. item = result.scalar_one_or_none()
  833. if not item:
  834. raise HTTPException(404, "Queue item not found")
  835. # Ownership check
  836. if not can_modify_all:
  837. if item.created_by_id != user.id:
  838. raise HTTPException(403, "You can only cancel your own queue items")
  839. if item.status not in ("pending",):
  840. raise HTTPException(400, f"Cannot cancel item with status '{item.status}'")
  841. item.status = "cancelled"
  842. item.completed_at = datetime.now(timezone.utc)
  843. await db.commit()
  844. logger.info("Cancelled queue item %s", item_id)
  845. return {"message": "Queue item cancelled"}
  846. @router.post("/{item_id}/stop")
  847. async def stop_queue_item(
  848. item_id: int,
  849. db: AsyncSession = Depends(get_db),
  850. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  851. ):
  852. """Stop an actively printing queue item."""
  853. from backend.app.models.smart_plug import SmartPlug
  854. from backend.app.services.printer_manager import printer_manager
  855. from backend.app.services.tasmota import tasmota_service
  856. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  857. item = result.scalar_one_or_none()
  858. if not item:
  859. raise HTTPException(404, "Queue item not found")
  860. if item.status != "printing":
  861. raise HTTPException(400, f"Can only stop items that are printing, current status: '{item.status}'")
  862. # Capture values we need for background task
  863. printer_id = item.printer_id
  864. auto_off_after = item.auto_off_after
  865. # Try to send stop command to printer
  866. stop_sent = False
  867. try:
  868. stop_sent = printer_manager.stop_print(printer_id)
  869. if not stop_sent:
  870. logger.warning("stop_print returned False for printer %s - printer may not be connected", printer_id)
  871. except Exception as e:
  872. logger.error("Error sending stop command for queue item %s: %s", item_id, e)
  873. # Mark this printer as user-stopped BEFORE the first await so that if the
  874. # MQTT on_print_complete callback fires during the db.commit() yield the flag
  875. # is already set and the "failed" status will be correctly overridden to
  876. # "cancelled" (preventing a spurious "print failed" notification).
  877. try:
  878. from backend.app.main import mark_printer_stopped_by_user
  879. mark_printer_stopped_by_user(printer_id)
  880. except Exception as _mark_err:
  881. logger.warning("Failed to mark printer %s as user-stopped: %s", printer_id, _mark_err)
  882. # Update queue item status regardless - if printer is off, print is already stopped
  883. item.status = "cancelled"
  884. item.completed_at = datetime.now(timezone.utc)
  885. item.error_message = "Stopped by user" if stop_sent else "Stopped by user (printer was offline)"
  886. await db.commit()
  887. # Get smart plug info if auto-off is enabled
  888. plug_ip = None
  889. if auto_off_after:
  890. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  891. plug = result.scalar_one_or_none()
  892. if plug and plug.enabled:
  893. plug_ip = plug.ip_address
  894. logger.info("Stopped printing queue item %s (stop command sent: %s)", item_id, stop_sent)
  895. # Schedule background task for cooldown + power off
  896. if plug_ip:
  897. async def cooldown_and_poweroff():
  898. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", printer_id)
  899. await printer_manager.wait_for_cooldown(printer_id, target_temp=50.0, timeout=600)
  900. # Re-fetch plug since we're in a new async context
  901. from backend.app.core.database import async_session
  902. async with async_session() as new_db:
  903. result = await new_db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  904. plug = result.scalar_one_or_none()
  905. if plug and plug.enabled:
  906. logger.info("Auto-off: Powering off printer %s", printer_id)
  907. await tasmota_service.turn_off(plug)
  908. spawn_background_task(cooldown_and_poweroff(), name=f"queue-cooldown-poweroff-{printer_id}")
  909. return {"message": "Print stopped" if stop_sent else "Queue item cancelled (printer was offline)"}
  910. @router.post("/{item_id}/start")
  911. async def start_queue_item(
  912. item_id: int,
  913. skip_filament_check: bool = Query(default=False),
  914. db: AsyncSession = Depends(get_db),
  915. user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_OWN),
  916. ):
  917. """Manually start a staged (manual_start) queue item.
  918. Clears the manual_start flag so the scheduler picks it up. When
  919. ``skip_filament_check`` is false (the default) the live filament
  920. deficit (#1496) is checked first — if the assigned spool can't satisfy
  921. a slot's required grams, the route returns ``409`` with the deficit
  922. payload so the caller can show a confirm dialog and retry with
  923. ``skip_filament_check=true``.
  924. """
  925. result = await db.execute(
  926. select(PrintQueueItem)
  927. .options(
  928. selectinload(PrintQueueItem.archive),
  929. selectinload(PrintQueueItem.printer),
  930. selectinload(PrintQueueItem.library_file),
  931. selectinload(PrintQueueItem.batch),
  932. )
  933. .where(PrintQueueItem.id == item_id)
  934. )
  935. item = result.scalar_one_or_none()
  936. if not item:
  937. raise HTTPException(404, "Queue item not found")
  938. if item.status != "pending":
  939. raise HTTPException(400, f"Can only start pending items, current status: '{item.status}'")
  940. # Live deficit check — re-evaluated against current spool state, so a
  941. # spool swap between scheduler flagging and the user clicking ▶ clears
  942. # the block automatically.
  943. if not skip_filament_check:
  944. deficit = await compute_deficit_for_queue_item(db, item)
  945. if deficit:
  946. raise HTTPException(
  947. status_code=409,
  948. detail={
  949. "code": "insufficient_filament",
  950. "deficit": [d.to_dict() for d in deficit],
  951. },
  952. )
  953. # Print Anyway / no deficit: clear the flags and let the scheduler dispatch.
  954. item.manual_start = False
  955. item.filament_short = False
  956. # Persist the user's "Print Anyway" decision so the scheduler does not
  957. # immediately re-flag this item on the next tick (#1698-followup). The
  958. # pre-fix behaviour bounced between "user said anyway" and
  959. # "scheduler re-blocked on same deficit" forever.
  960. if skip_filament_check:
  961. item.skip_filament_check = True
  962. # Credit the clicker as the item's owner when no prior owner is set —
  963. # VP-uploaded queue items arrive over FTP unattributed, so without this
  964. # the print log's User column stays blank even when auth is on
  965. # (#1670). An item that already has a creator (UI-added queue items)
  966. # keeps that attribution; the dispatcher is not promoted over the
  967. # original uploader.
  968. if user is not None and item.created_by_id is None:
  969. item.created_by_id = user.id
  970. await db.commit()
  971. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  972. logger.info(
  973. "Manually started queue item %s (cleared manual_start; skip_filament_check=%s)",
  974. item_id,
  975. skip_filament_check,
  976. )
  977. return _enrich_response(item)