print_queue.py 53 KB

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