print_queue.py 53 KB

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