print_queue.py 45 KB

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