print_queue.py 60 KB

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