print_queue.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  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.api.routes.library_variants import normalize_model_name, resolve_variant_model
  13. from backend.app.core.auth import RequirePermissionIfAuthEnabled, require_ownership_permission
  14. from backend.app.core.config import settings
  15. from backend.app.core.database import get_db
  16. from backend.app.core.permissions import Permission
  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, PrintQueueVariant
  21. from backend.app.models.printer import Printer
  22. from backend.app.models.project import Project
  23. from backend.app.models.user import User
  24. from backend.app.schemas.print_queue import (
  25. PrintBatchCreate,
  26. PrintBatchResponse,
  27. PrintBatchUngroupResponse,
  28. PrintQueueBulkUpdate,
  29. PrintQueueBulkUpdateResponse,
  30. PrintQueueItemCreate,
  31. PrintQueueItemResponse,
  32. PrintQueueItemUpdate,
  33. PrintQueueReorder,
  34. QueueVariantCreate,
  35. )
  36. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  37. from backend.app.services.filament_requirements import overrides_for_plate
  38. from backend.app.services.notification_service import notification_service
  39. from backend.app.utils.printer_models import (
  40. is_gcode_compatible,
  41. )
  42. from backend.app.utils.threemf_tools import (
  43. extract_plate_metadata_from_3mf,
  44. extract_print_time_from_3mf,
  45. )
  46. logger = logging.getLogger(__name__)
  47. router = APIRouter(prefix="/queue", tags=["queue"])
  48. def _extract_filament_types_from_3mf(file_path: Path, plate_id: int | None = None) -> list[str]:
  49. """Extract unique filament types from a 3MF file.
  50. Args:
  51. file_path: Path to the 3MF file
  52. plate_id: Optional plate index to filter for (for multi-plate files)
  53. Returns:
  54. List of unique filament types (e.g., ["PLA", "PETG"])
  55. """
  56. types: set[str] = set()
  57. try:
  58. with zipfile.ZipFile(file_path, "r") as zf:
  59. if "Metadata/slice_info.config" not in zf.namelist():
  60. return []
  61. content = zf.read("Metadata/slice_info.config").decode()
  62. root = ET.fromstring(content)
  63. if plate_id is not None:
  64. # Find the plate element with matching index
  65. for plate_elem in root.findall(".//plate"):
  66. plate_index = None
  67. for meta in plate_elem.findall("metadata"):
  68. if meta.get("key") == "index":
  69. try:
  70. plate_index = int(meta.get("value", "0"))
  71. except ValueError:
  72. pass # Skip plate with unparseable index
  73. break
  74. if plate_index == plate_id:
  75. for filament_elem in plate_elem.findall("filament"):
  76. filament_type = filament_elem.get("type", "")
  77. used_g = filament_elem.get("used_g", "0")
  78. try:
  79. used_grams = float(used_g)
  80. except (ValueError, TypeError):
  81. used_grams = 0
  82. if used_grams > 0 and filament_type:
  83. types.add(filament_type)
  84. break
  85. else:
  86. # No plate_id specified - extract all filaments with used_g > 0
  87. for filament_elem in root.findall(".//filament"):
  88. filament_type = filament_elem.get("type", "")
  89. used_g = filament_elem.get("used_g", "0")
  90. try:
  91. used_grams = float(used_g)
  92. except (ValueError, TypeError):
  93. used_grams = 0
  94. if used_grams > 0 and filament_type:
  95. types.add(filament_type)
  96. except Exception as e:
  97. logger.warning("Failed to extract filament types from %s: %s", file_path, e)
  98. return sorted(types)
  99. # Local alias kept so existing call sites stay compact; the implementation lives
  100. # in utils/threemf_tools.py so the notification path (main.py) can reuse it
  101. # without importing from a routes module (#1785).
  102. _extract_print_time_from_3mf = extract_print_time_from_3mf
  103. async def _resolve_source_path(db: AsyncSession, item: PrintQueueItem) -> Path | None:
  104. """Resolve an existing queue item's source 3MF on disk, or None."""
  105. if item.archive_id:
  106. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  107. archive = result.scalar_one_or_none()
  108. if archive:
  109. return settings.base_dir / archive.file_path
  110. elif item.library_file_id:
  111. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  112. library_file = result.scalar_one_or_none()
  113. if library_file:
  114. lib_path = Path(library_file.file_path)
  115. return lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  116. return None
  117. def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
  118. """Add nested archive/printer/library_file info to response."""
  119. # Parse ams_mapping from JSON string BEFORE model_validate
  120. ams_mapping_parsed = None
  121. if item.ams_mapping:
  122. try:
  123. ams_mapping_parsed = json.loads(item.ams_mapping)
  124. except json.JSONDecodeError:
  125. ams_mapping_parsed = None
  126. # Parse required_filament_types from JSON string
  127. required_filament_types_parsed = None
  128. if item.required_filament_types:
  129. try:
  130. required_filament_types_parsed = json.loads(item.required_filament_types)
  131. except json.JSONDecodeError:
  132. required_filament_types_parsed = None
  133. # Parse filament_overrides from JSON string
  134. filament_overrides_parsed = None
  135. if item.filament_overrides:
  136. try:
  137. filament_overrides_parsed = json.loads(item.filament_overrides)
  138. except json.JSONDecodeError:
  139. filament_overrides_parsed = None
  140. # Parse nozzle_mapping from JSON string (#1780 — H2C rack slicer-pick
  141. # preservation). Nullable opaque JSON blob stored verbatim from
  142. # BambuStudio's project_file; surface it parsed for the response model
  143. # and any future "edit print → nozzle" UI.
  144. nozzle_mapping_parsed = None
  145. if item.nozzle_mapping:
  146. try:
  147. nozzle_mapping_parsed = json.loads(item.nozzle_mapping)
  148. except json.JSONDecodeError:
  149. nozzle_mapping_parsed = None
  150. nozzles_info_parsed = None
  151. if item.nozzles_info:
  152. try:
  153. nozzles_info_parsed = json.loads(item.nozzles_info)
  154. except json.JSONDecodeError:
  155. nozzles_info_parsed = None
  156. # Create response with parsed ams_mapping
  157. item_dict = {
  158. "id": item.id,
  159. "printer_id": item.printer_id,
  160. "target_model": item.target_model,
  161. "target_location": item.target_location,
  162. "required_filament_types": required_filament_types_parsed,
  163. "filament_overrides": filament_overrides_parsed,
  164. "waiting_reason": item.waiting_reason,
  165. "archive_id": item.archive_id,
  166. "library_file_id": item.library_file_id,
  167. "position": item.position,
  168. "scheduled_time": item.scheduled_time,
  169. "require_previous_success": item.require_previous_success,
  170. "auto_off_after": item.auto_off_after,
  171. "manual_start": item.manual_start,
  172. "filament_short": bool(item.filament_short),
  173. "skip_filament_check": bool(item.skip_filament_check),
  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. "preheat_override": item.preheat_override,
  184. "preheat_chamber_target_override": item.preheat_chamber_target_override,
  185. "status": item.status,
  186. "started_at": item.started_at,
  187. "completed_at": item.completed_at,
  188. "error_message": item.error_message,
  189. "created_at": item.created_at,
  190. # User tracking (Issue #206)
  191. "created_by_id": item.created_by_id,
  192. "created_by_username": item.created_by.username if item.created_by else None,
  193. # Batch grouping
  194. "batch_id": item.batch_id,
  195. "batch_name": item.batch.name if item.batch else None,
  196. # SJF scheduling
  197. "been_jumped": item.been_jumped,
  198. # Auto-print G-code injection
  199. "gcode_injection": item.gcode_injection,
  200. # H2C rack-swap nozzle pick (#1780)
  201. "nozzle_mapping": nozzle_mapping_parsed,
  202. "nozzles_info": nozzles_info_parsed,
  203. "cleanup_library_after_dispatch": item.cleanup_library_after_dispatch,
  204. }
  205. response = PrintQueueItemResponse(**item_dict)
  206. if item.archive:
  207. # Soft-deleted archive: files are gone from disk but the row stays
  208. # (its filament/cost contribution still flows into stats per #1343).
  209. # Suppress the archive-derived UI surface so the queue page doesn't
  210. # 404-storm the thumbnail / plates / plate-thumbnail endpoints — the
  211. # frontend's existing truthy gate on archive_thumbnail covers it
  212. # (#1348 follow-up). The archive_deleted flag lets the UI render a
  213. # "source deleted" badge on these rows.
  214. if item.archive.deleted_at is not None:
  215. response.archive_deleted = True
  216. else:
  217. response.archive_name = item.archive.print_name or item.archive.filename
  218. response.archive_thumbnail = item.archive.thumbnail_path
  219. response.print_time_seconds = item.archive.print_time_seconds
  220. response.filament_used_grams = item.archive.filament_used_grams
  221. response.filament_type = item.archive.filament_type
  222. response.filament_color = item.archive.filament_color
  223. response.layer_height = item.archive.layer_height
  224. response.nozzle_diameter = item.archive.nozzle_diameter
  225. response.sliced_for_model = item.archive.sliced_for_model
  226. response.bed_type = item.archive.bed_type
  227. # Marks history/reprint rows whose archive carries the slicer's own
  228. # live-resolved AMS-slot pick (extra_data.slicer_ams_mapping) — see
  229. # `_extract_slicer_ams_mapping_json` in virtual_printer/manager.py.
  230. #
  231. # Only when the saved mapping was resolved against *this* row's
  232. # printer: a global tray ID means nothing on another printer, so
  233. # that's the exact condition under which the mapping is reused. A
  234. # badge on a row where nothing gets reused would be a lie (#2700
  235. # review). Model-based rows (printer_id None) never match, which is
  236. # correct — the mapping is not reused there either.
  237. extra = item.archive.extra_data if isinstance(item.archive.extra_data, dict) else {}
  238. saved_mapping = extra.get("slicer_ams_mapping")
  239. response.archive_has_slicer_ams_mapping = (
  240. isinstance(saved_mapping, dict)
  241. and isinstance(saved_mapping.get("mapping"), list)
  242. and item.printer_id is not None
  243. and saved_mapping.get("printer_id") == item.printer_id
  244. )
  245. if item.plate_id:
  246. archive_path = settings.base_dir / item.archive.file_path
  247. if archive_path.exists():
  248. # One cached parse for all three per-plate overrides (#2573).
  249. plate_meta = extract_plate_metadata_from_3mf(archive_path, item.plate_id)
  250. if plate_meta.print_time_seconds is not None:
  251. response.print_time_seconds = plate_meta.print_time_seconds
  252. if plate_meta.filament_used_grams > 0:
  253. response.filament_used_grams = plate_meta.filament_used_grams
  254. if plate_meta.bed_type:
  255. response.bed_type = plate_meta.bed_type
  256. if item.library_file:
  257. response.library_file_name = (
  258. item.library_file.file_metadata.get("print_name") if item.library_file.file_metadata else None
  259. )
  260. if not response.library_file_name:
  261. response.library_file_name = item.library_file.filename
  262. response.library_file_thumbnail = item.library_file.thumbnail_path
  263. # Get metadata from library file if no archive
  264. if not item.archive and item.library_file.file_metadata:
  265. response.print_time_seconds = item.library_file.file_metadata.get("print_time_seconds")
  266. response.filament_used_grams = item.library_file.file_metadata.get("filament_used_grams")
  267. response.filament_type = item.library_file.file_metadata.get("filament_type")
  268. response.filament_color = item.library_file.file_metadata.get("filament_color")
  269. response.layer_height = item.library_file.file_metadata.get("layer_height")
  270. response.nozzle_diameter = item.library_file.file_metadata.get("nozzle_diameter")
  271. response.sliced_for_model = item.library_file.file_metadata.get("sliced_for_model")
  272. response.bed_type = item.library_file.file_metadata.get("bed_type")
  273. if item.plate_id:
  274. lib_path = Path(item.library_file.file_path)
  275. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / item.library_file.file_path
  276. if library_file_path.exists():
  277. # One cached parse for all three per-plate overrides (#2573).
  278. plate_meta = extract_plate_metadata_from_3mf(library_file_path, item.plate_id)
  279. if plate_meta.print_time_seconds is not None:
  280. response.print_time_seconds = plate_meta.print_time_seconds
  281. if plate_meta.filament_used_grams > 0:
  282. response.filament_used_grams = plate_meta.filament_used_grams
  283. if plate_meta.bed_type:
  284. response.bed_type = plate_meta.bed_type
  285. if item.printer:
  286. response.printer_name = item.printer.name
  287. return response
  288. @router.get("/", response_model=list[PrintQueueItemResponse])
  289. async def list_queue(
  290. printer_id: int | None = Query(None, description="Filter by printer (-1 for unassigned)"),
  291. status: str | None = Query(None, description="Filter by status"),
  292. target_model: str | None = Query(
  293. None, description="Filter by target model (also includes model-based items when combined with printer_id)"
  294. ),
  295. db: AsyncSession = Depends(get_db),
  296. auth_result: tuple[User | None, bool] = Depends(
  297. require_ownership_permission(
  298. Permission.QUEUE_READ_ALL,
  299. Permission.QUEUE_READ_OWN,
  300. )
  301. ),
  302. ):
  303. """List all queue items, optionally filtered by printer or status."""
  304. user, can_read_all = auth_result
  305. query = (
  306. select(PrintQueueItem)
  307. .options(
  308. selectinload(PrintQueueItem.archive),
  309. selectinload(PrintQueueItem.printer),
  310. selectinload(PrintQueueItem.library_file),
  311. selectinload(PrintQueueItem.created_by),
  312. selectinload(PrintQueueItem.batch),
  313. )
  314. .order_by(PrintQueueItem.printer_id.nulls_first(), PrintQueueItem.position)
  315. )
  316. if user is not None and not can_read_all:
  317. query = query.where(PrintQueueItem.created_by_id == user.id)
  318. if printer_id is not None:
  319. if printer_id == -1:
  320. # Special value: filter for unassigned items
  321. query = query.where(PrintQueueItem.printer_id.is_(None))
  322. else:
  323. # Resolve effective model: prefer explicit param, fall back to printer's DB model.
  324. # This ensures model-based "Any X" items are returned even when the frontend
  325. # doesn't send target_model (e.g. printer.model is NULL on the client side).
  326. effective_model = target_model
  327. if not effective_model:
  328. printer_row = (
  329. await db.execute(select(Printer.model).where(Printer.id == printer_id))
  330. ).scalar_one_or_none()
  331. effective_model = printer_row
  332. if effective_model:
  333. # Include both printer-specific items AND model-based (unassigned) items
  334. query = query.where(
  335. or_(
  336. PrintQueueItem.printer_id == printer_id,
  337. and_(
  338. PrintQueueItem.printer_id.is_(None),
  339. func.lower(PrintQueueItem.target_model) == effective_model.lower(),
  340. ),
  341. )
  342. )
  343. else:
  344. query = query.where(PrintQueueItem.printer_id == printer_id)
  345. elif target_model:
  346. query = query.where(func.lower(PrintQueueItem.target_model) == target_model.lower())
  347. if status:
  348. query = query.where(PrintQueueItem.status == status)
  349. result = await db.execute(query)
  350. items = result.scalars().all()
  351. return [_enrich_response(item) for item in items]
  352. async def _resolve_queue_variants(
  353. db: AsyncSession,
  354. specs: list[QueueVariantCreate],
  355. current_user: User | None,
  356. ) -> list[tuple[QueueVariantCreate, LibraryFile, str]]:
  357. """Validate a cross-model candidate set and pair each file with its model (#671).
  358. Validated as a set, not file by file, because the failure modes are about the
  359. set: two candidates for the same printer give the resolver no basis to choose,
  360. and a set where nothing can ever run is a job that waits forever.
  361. At least one candidate must have an active printer — the rest may not, which
  362. is deliberate. Grouping the H2C slice before the H2C arrives is a reasonable
  363. thing to do, and refusing the whole queue action over it would be worse than
  364. letting that candidate simply never match.
  365. """
  366. file_ids = [s.library_file_id for s in specs]
  367. if len(set(file_ids)) != len(file_ids):
  368. raise HTTPException(400, "The same file cannot be listed twice as a variant")
  369. rows = (await db.execute(LibraryFile.active().where(LibraryFile.id.in_(file_ids)))).scalars().all()
  370. by_id = {f.id: f for f in rows}
  371. resolved: list[tuple[QueueVariantCreate, LibraryFile, str]] = []
  372. seen_models: dict[str, str] = {}
  373. any_active_printer = False
  374. for spec in specs:
  375. library_file = by_id.get(spec.library_file_id)
  376. # Same IDOR posture as the single-file path: a file the caller cannot read
  377. # is reported as missing rather than forbidden.
  378. if not library_file or (
  379. current_user
  380. and not current_user.has_permission(Permission.LIBRARY_READ_ALL.value)
  381. and library_file.created_by_id != current_user.id
  382. ):
  383. raise HTTPException(404, f"Library file not found: {spec.library_file_id}")
  384. from backend.app.utils.filename import InvalidFilenameError, validate_print_filename
  385. try:
  386. validate_print_filename(library_file.filename)
  387. except InvalidFilenameError as e:
  388. raise HTTPException(400, str(e)) from e
  389. model = resolve_variant_model(library_file, spec.target_model)
  390. if not model:
  391. raise HTTPException(
  392. 400,
  393. f"{library_file.filename} does not say which printer it was sliced for — "
  394. "set its target model explicitly",
  395. )
  396. # Cross-model safety gate (#2578), per candidate. A set is only as safe as
  397. # its worst member, and model-based dispatch has no human in the loop.
  398. sliced_for = (library_file.file_metadata or {}).get("sliced_for_model")
  399. if not is_gcode_compatible(sliced_for, model):
  400. raise HTTPException(
  401. 400,
  402. f"{library_file.filename} was sliced for {sliced_for} and cannot be dispatched to {model} printers",
  403. )
  404. if model in seen_models:
  405. raise HTTPException(
  406. 400,
  407. f"{library_file.filename} and {seen_models[model]} are both for {model} — "
  408. "variants must target different printers",
  409. )
  410. seen_models[model] = library_file.filename
  411. has_printer = (
  412. (
  413. await db.execute(
  414. select(Printer).where(Printer.model == model).where(Printer.is_active == True) # noqa: E712
  415. )
  416. )
  417. .scalars()
  418. .first()
  419. )
  420. any_active_printer = any_active_printer or bool(has_printer)
  421. resolved.append((spec, library_file, model))
  422. if not any_active_printer:
  423. raise HTTPException(400, f"No active printers for any of: {', '.join(seen_models)}")
  424. return resolved
  425. def _variant_values(
  426. spec: QueueVariantCreate,
  427. library_file: LibraryFile,
  428. model: str,
  429. position: int,
  430. ) -> dict:
  431. """Column values for one candidate, extracted from its own 3MF.
  432. Each candidate is a different slice, so its filament requirements and print
  433. time come from its own file rather than being inherited from the item.
  434. Returns values rather than a row so a quantity>1 batch can build one row per
  435. copy without re-opening the 3MF for each.
  436. """
  437. lib_path = Path(library_file.file_path)
  438. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  439. required_types = None
  440. filament_overrides_json = None
  441. print_time = (library_file.file_metadata or {}).get("print_time_seconds")
  442. if file_path.exists():
  443. types = _extract_filament_types_from_3mf(file_path, spec.plate_id)
  444. if types:
  445. required_types = json.dumps(types)
  446. if spec.plate_id:
  447. plate_time = _extract_print_time_from_3mf(file_path, spec.plate_id)
  448. if plate_time is not None:
  449. print_time = plate_time
  450. if spec.filament_overrides:
  451. plate_overrides = overrides_for_plate(spec.filament_overrides, file_path, spec.plate_id)
  452. if plate_overrides:
  453. filament_overrides_json = json.dumps(plate_overrides)
  454. override_types = sorted({o["type"] for o in plate_overrides if "type" in o})
  455. if override_types:
  456. existing = set(json.loads(required_types)) if required_types else set()
  457. required_types = json.dumps(sorted(existing | set(override_types)))
  458. return {
  459. "position": position,
  460. "library_file_id": library_file.id,
  461. "target_model": model,
  462. "plate_id": spec.plate_id,
  463. "ams_mapping": json.dumps(spec.ams_mapping) if spec.ams_mapping else None,
  464. "nozzle_mapping": json.dumps(spec.nozzle_mapping) if spec.nozzle_mapping else None,
  465. "filament_overrides": filament_overrides_json,
  466. "required_filament_types": required_types,
  467. "print_time_seconds": print_time,
  468. }
  469. @router.post("/", response_model=PrintQueueItemResponse)
  470. async def add_to_queue(
  471. data: PrintQueueItemCreate,
  472. db: AsyncSession = Depends(get_db),
  473. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  474. ):
  475. """Add an item to the print queue."""
  476. # Normalize target_model (e.g., "Bambu Lab X1E" / "C13" -> "X1E").
  477. # normalize_model_name resolves internal codes first: the previous
  478. # `normalize_printer_model(x) or normalize_printer_model_id(x)` chain never
  479. # reached the code map, because the first call returns unknown input
  480. # unchanged — so a "C13" target stayed "C13", matched no printer row and
  481. # left the item waiting forever. Identical result for every other spelling.
  482. target_model_norm = normalize_model_name(data.target_model)
  483. # Cross-model alternatives (#671): several sliced files, whichever printer
  484. # frees up first. The whole candidate set is validated before anything is
  485. # written — a half-valid set would produce a job that can only reach some of
  486. # the printers the user asked for, with nothing to say which.
  487. variant_specs: list[tuple[QueueVariantCreate, LibraryFile, str]] = []
  488. if data.variants:
  489. if data.printer_id:
  490. raise HTTPException(
  491. 400, "Cannot specify both printer_id and variants — pick a printer or offer alternatives"
  492. )
  493. if data.archive_id or data.library_file_id:
  494. raise HTTPException(
  495. 400, "Cannot combine variants with archive_id or library_file_id — the variants are the files"
  496. )
  497. variant_specs = await _resolve_queue_variants(db, data.variants, current_user)
  498. # Mirror the first candidate onto the item so the queue listing, the SJF
  499. # grouping and the "Any H2S" label have something before a printer is
  500. # picked. Resolution overwrites it with whichever candidate actually runs.
  501. target_model_norm = variant_specs[0][2]
  502. # Validate that either archive_id or library_file_id is provided.
  503. # A cross-model item deliberately holds neither: its files live on the
  504. # variant rows. Pointing library_file_id at one of them would be worse than
  505. # useless — that FK is ON DELETE CASCADE, so deleting a single alternative
  506. # would take the whole queue item with it.
  507. if not data.archive_id and not data.library_file_id and not data.variants:
  508. raise HTTPException(400, "Either archive_id or library_file_id must be provided")
  509. # Cannot specify both printer_id and target_model
  510. if data.printer_id and target_model_norm:
  511. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  512. # Validate printer exists (if assigned)
  513. if data.printer_id is not None:
  514. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  515. if not result.scalar_one_or_none():
  516. raise HTTPException(400, "Printer not found")
  517. # Validate target_model has active printers. Skipped for cross-model items:
  518. # target_model there is just the first candidate, and _resolve_queue_variants
  519. # has already required that *some* candidate has a printer.
  520. if target_model_norm and not data.variants:
  521. result = await db.execute(
  522. select(Printer).where(Printer.model == target_model_norm).where(Printer.is_active == True) # noqa: E712
  523. )
  524. if not result.scalars().first():
  525. raise HTTPException(400, f"No active printers for model: {target_model_norm}")
  526. # Validate archive exists (if provided) and get it for filament extraction
  527. archive = None
  528. if data.archive_id:
  529. result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  530. archive = result.scalar_one_or_none()
  531. if not archive:
  532. raise HTTPException(400, "Archive not found")
  533. # IDOR fix (maziggy/bambuddy-security #2): without this check, a
  534. # caller with QUEUE_CREATE could queue any user's archive even
  535. # without ARCHIVES_READ on it — Landon's PoC enumerated this on
  536. # admin's archives as operator1. Gate on ARCHIVES_READ_ALL OR
  537. # ownership of the archive. 404 (not 403) so we don't leak
  538. # "this id exists but you can't queue it" for enumeration.
  539. if (
  540. current_user is not None
  541. and not current_user.has_permission(Permission.ARCHIVES_READ_ALL.value)
  542. and archive.created_by_id != current_user.id
  543. ):
  544. raise HTTPException(404, "Archive not found")
  545. # Reprint perm gate (#1625): the legacy /archives/{id}/reprint endpoint
  546. # required ARCHIVES_REPRINT_OWN/ALL; the unified queue route must keep
  547. # that gate or an operator with QUEUE_CREATE could reprint via direct
  548. # API call even if explicitly denied reprint perm. Mirrors the
  549. # frontend `canModify('archives', 'reprint', ...)` helper:
  550. # REPRINT_ALL allows any archive, REPRINT_OWN allows own only,
  551. # ownerless archives require REPRINT_ALL (fail-closed).
  552. if current_user is not None:
  553. owns_archive = archive.created_by_id is not None and archive.created_by_id == current_user.id
  554. has_reprint = current_user.has_permission(Permission.ARCHIVES_REPRINT_ALL.value) or (
  555. owns_archive and current_user.has_permission(Permission.ARCHIVES_REPRINT_OWN.value)
  556. )
  557. if not has_reprint:
  558. raise HTTPException(
  559. status_code=403,
  560. detail="Permission archives:reprint_own or archives:reprint_all required",
  561. )
  562. # Validate library file exists (if provided) and get it for filament extraction
  563. library_file = None
  564. if data.library_file_id:
  565. result = await db.execute(LibraryFile.active().where(LibraryFile.id == data.library_file_id))
  566. library_file = result.scalar_one_or_none()
  567. if not library_file:
  568. raise HTTPException(400, "Library file not found")
  569. # Same shape: gate cross-user library-file queueing on LIBRARY_READ_ALL.
  570. if (
  571. current_user is not None
  572. and not current_user.has_permission(Permission.LIBRARY_READ_ALL.value)
  573. and library_file.created_by_id != current_user.id
  574. ):
  575. raise HTTPException(404, "Library file not found")
  576. # Bambu SD card is FAT32/exFAT — illegal filename chars would 553 at
  577. # FTP upload time (#1540). Reject at queue time so the user gets the
  578. # actionable error before waiting in queue.
  579. from backend.app.utils.filename import InvalidFilenameError, validate_print_filename
  580. try:
  581. validate_print_filename(library_file.filename)
  582. except InvalidFilenameError as e:
  583. raise HTTPException(400, str(e)) from e
  584. # Cross-model safety gate (#2578): a G-code 3MF sliced for one model must
  585. # not be queued for dispatch to an incompatible model. The UI can no longer
  586. # produce such rows, but API-created rows must be rejected here too — the
  587. # scheduler assigns model-based items to hardware with no human in the loop.
  588. if target_model_norm:
  589. sliced_for = None
  590. if archive:
  591. sliced_for = archive.sliced_for_model
  592. elif library_file and library_file.file_metadata:
  593. sliced_for = library_file.file_metadata.get("sliced_for_model")
  594. if not is_gcode_compatible(sliced_for, target_model_norm):
  595. raise HTTPException(
  596. 400,
  597. f"File was sliced for {sliced_for} and cannot be dispatched to {target_model_norm} printers",
  598. )
  599. # Extract filament types for model-based assignment (used by scheduler for validation)
  600. required_filament_types = None
  601. file_path = None
  602. if target_model_norm:
  603. # Get file path from archive or library file
  604. if archive:
  605. file_path = settings.base_dir / archive.file_path
  606. elif library_file:
  607. lib_path = Path(library_file.file_path)
  608. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  609. if file_path and file_path.exists():
  610. filament_types = _extract_filament_types_from_3mf(file_path, data.plate_id)
  611. if filament_types:
  612. required_filament_types = json.dumps(filament_types)
  613. logger.info("Extracted filament types for model-based queue: %s", filament_types)
  614. # If filament overrides are provided, update required_filament_types to match override types
  615. filament_overrides_json = None
  616. if data.filament_overrides and target_model_norm:
  617. plate_overrides = overrides_for_plate(data.filament_overrides, file_path, data.plate_id)
  618. if plate_overrides:
  619. filament_overrides_json = json.dumps(plate_overrides)
  620. # Update required_filament_types from overrides so scheduler validates against overridden types
  621. override_types = sorted({o["type"] for o in plate_overrides if "type" in o})
  622. if override_types:
  623. # Merge with existing types (overrides may only cover some slots)
  624. existing_types = set(json.loads(required_filament_types)) if required_filament_types else set()
  625. # Replace types for overridden slots, keep others
  626. all_types = existing_types | set(override_types)
  627. required_filament_types = json.dumps(sorted(all_types))
  628. # Validate quantity
  629. quantity = max(1, data.quantity)
  630. # Validate batch_id if provided. Client passes batch_id when adding items
  631. # into a pre-created batch (multi-plate auto-batch or "Group as batch" flow).
  632. # 404 keeps the existing-id leak surface low.
  633. batch = None
  634. batch_id = None
  635. if data.batch_id is not None:
  636. result = await db.execute(select(PrintBatch).where(PrintBatch.id == data.batch_id))
  637. existing_batch = result.scalar_one_or_none()
  638. if not existing_batch:
  639. raise HTTPException(404, "Batch not found")
  640. if existing_batch.status != "active":
  641. raise HTTPException(400, "Cannot add items to a non-active batch")
  642. if (
  643. current_user is not None
  644. and existing_batch.created_by_id is not None
  645. and existing_batch.created_by_id != current_user.id
  646. and not current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  647. ):
  648. raise HTTPException(404, "Batch not found")
  649. batch = existing_batch
  650. batch_id = existing_batch.id
  651. # Create batch if quantity > 1 and no batch_id provided
  652. if batch_id is None and quantity > 1:
  653. # Derive batch name from source file
  654. batch_name_base = "Batch"
  655. if archive:
  656. batch_name_base = archive.print_name or archive.filename or "Batch"
  657. elif library_file:
  658. if library_file.file_metadata:
  659. batch_name_base = library_file.file_metadata.get("print_name") or library_file.filename
  660. else:
  661. batch_name_base = library_file.filename
  662. batch_name_base = batch_name_base.replace(".gcode.3mf", "").replace(".3mf", "")
  663. batch = PrintBatch(
  664. name=f"{batch_name_base} ×{quantity}",
  665. archive_id=data.archive_id,
  666. library_file_id=data.library_file_id,
  667. quantity=quantity,
  668. status="active",
  669. created_by_id=current_user.id if current_user else None,
  670. )
  671. db.add(batch)
  672. await db.flush() # Get batch.id before creating items
  673. batch_id = batch.id
  674. # Get queue scope for this printer (or for unassigned/model-based items).
  675. if data.printer_id is not None:
  676. queue_scope = (
  677. PrintQueueItem.printer_id == data.printer_id,
  678. PrintQueueItem.status == "pending",
  679. )
  680. else:
  681. # For unassigned/model-based items, scope across all unassigned.
  682. queue_scope = (
  683. PrintQueueItem.printer_id.is_(None),
  684. PrintQueueItem.status == "pending",
  685. )
  686. # Serialize concurrent queue inserts to the same scope (#1625-followup).
  687. # The race: two concurrent ASAP inserts both compute MAX(position) before
  688. # either commits; in an empty scope, both INSERT at position 1 (duplicate).
  689. # In a non-empty scope, Postgres's row-level locks on the UPDATE shift
  690. # serialize naturally, but the empty-scope path has no rows to lock.
  691. # A transaction-scoped advisory lock keyed on the printer_id closes that
  692. # window; the lock is released automatically at commit/rollback. Different
  693. # printers don't contend. SQLite serializes writes implicitly so this is a
  694. # no-op there.
  695. #
  696. # Dialect is checked against the actual session binding, NOT the
  697. # `is_sqlite()` helper, because the test fixture overrides `get_db` with a
  698. # SQLite engine while `settings.database_url` still points at Postgres
  699. # (the helper reads settings). Inspecting the connection directly is the
  700. # right shape for any code that mutates SQL based on the live dialect.
  701. from sqlalchemy import text
  702. bind = db.get_bind()
  703. if bind.dialect.name == "postgresql":
  704. scope_key = data.printer_id if data.printer_id is not None else 0
  705. # 1625 namespaces the lock so it can't collide with other advisory
  706. # locks elsewhere in the codebase.
  707. await db.execute(text("SELECT pg_advisory_xact_lock(1625, :k)"), {"k": scope_key})
  708. insert_position = max(1, data.insert_position or 1)
  709. if data.insert_at_top or data.insert_position is not None:
  710. result = await db.execute(select(func.max(PrintQueueItem.position)).where(*queue_scope))
  711. max_pos = result.scalar() or 0
  712. insert_position = min(insert_position, max_pos + 1)
  713. await db.execute(
  714. update(PrintQueueItem)
  715. .where(*queue_scope)
  716. .where(PrintQueueItem.position >= insert_position)
  717. .values(position=PrintQueueItem.position + quantity)
  718. )
  719. start_position = insert_position
  720. else:
  721. result = await db.execute(select(func.max(PrintQueueItem.position)).where(*queue_scope))
  722. max_pos = result.scalar() or 0
  723. start_position = max_pos + 1
  724. # Resolve print_time_seconds for SJF scheduling (cache on item at creation)
  725. cached_print_time = None
  726. if archive:
  727. cached_print_time = archive.print_time_seconds
  728. if data.plate_id:
  729. archive_path = settings.base_dir / archive.file_path
  730. if archive_path.exists():
  731. plate_time = _extract_print_time_from_3mf(archive_path, data.plate_id)
  732. if plate_time is not None:
  733. cached_print_time = plate_time
  734. elif library_file:
  735. if library_file.file_metadata:
  736. cached_print_time = library_file.file_metadata.get("print_time_seconds")
  737. if data.plate_id:
  738. lib_path = Path(library_file.file_path)
  739. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  740. if library_file_path.exists():
  741. plate_time = _extract_print_time_from_3mf(library_file_path, data.plate_id)
  742. if plate_time is not None:
  743. cached_print_time = plate_time
  744. # Validate project exists before insert so a bogus ID yields 404, not an FK-constraint 500
  745. if data.project_id is not None:
  746. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  747. if not project_result.scalar_one_or_none():
  748. raise HTTPException(status_code=404, detail="Project not found")
  749. ams_mapping_json = json.dumps(data.ams_mapping) if data.ams_mapping else None
  750. # Reprint fallback: the caller didn't specify an explicit ams_mapping (no
  751. # per-slot filament-mapping edit was made), but the archive carries the
  752. # slicer's own live-resolved AMS-slot pick from the original print (see
  753. # `extra_data.slicer_ams_mapping`, written by the VP-queue path via
  754. # `_extract_slicer_ams_mapping_json`). Reuse it so the reprint dispatches
  755. # to the exact same physical spool instead of the scheduler re-deriving a
  756. # (possibly ambiguous) mapping from just the file's static type/color.
  757. #
  758. # Global tray IDs only mean something relative to the specific printer
  759. # they were resolved against, so this only fires when the reprint targets
  760. # that exact printer (`extra_data.slicer_ams_mapping.printer_id`) — never
  761. # for a model-based dispatch (data.printer_id is None) or a reprint aimed
  762. # at a different printer, where the same tray number can hold a
  763. # completely different spool (#2700 review).
  764. #
  765. # It also stands down when the request carries force-color-match overrides:
  766. # those are the caller asking the scheduler to match strictly against the
  767. # printer's live trays, and they are only ever applied inside
  768. # `_compute_ams_mapping_for_printer` — the function a stored mapping makes
  769. # the scheduler skip. Same precedence as the VP-side toggle pair (#2700
  770. # review).
  771. #
  772. # Note this is otherwise unconditional — it applies regardless of whether
  773. # the physical spool in that slot has changed since the original print.
  774. # #1308 covers re-verifying a stored mapping against live AMS state at
  775. # dispatch time; that check is a separate PR and, once merged, will also
  776. # catch a stale slot inherited through this fallback.
  777. wants_live_color_match = any(
  778. isinstance(o, dict) and o.get("force_color_match") for o in (data.filament_overrides or [])
  779. )
  780. if (
  781. ams_mapping_json is None
  782. and not wants_live_color_match
  783. and archive
  784. and archive.extra_data
  785. and data.printer_id is not None
  786. ):
  787. saved = archive.extra_data.get("slicer_ams_mapping")
  788. if (
  789. isinstance(saved, dict)
  790. and saved.get("printer_id") == data.printer_id
  791. and isinstance(saved.get("mapping"), list)
  792. and saved["mapping"]
  793. ):
  794. ams_mapping_json = json.dumps(saved["mapping"])
  795. items = []
  796. for i in range(quantity):
  797. item = PrintQueueItem(
  798. printer_id=data.printer_id,
  799. target_model=target_model_norm,
  800. target_location=data.target_location,
  801. required_filament_types=required_filament_types,
  802. filament_overrides=filament_overrides_json,
  803. archive_id=data.archive_id,
  804. library_file_id=data.library_file_id,
  805. scheduled_time=data.scheduled_time,
  806. require_previous_success=data.require_previous_success,
  807. auto_off_after=data.auto_off_after,
  808. manual_start=data.manual_start,
  809. skip_filament_check=data.skip_filament_check,
  810. ams_mapping=ams_mapping_json,
  811. plate_id=data.plate_id,
  812. bed_levelling=data.bed_levelling,
  813. flow_cali=data.flow_cali,
  814. vibration_cali=data.vibration_cali,
  815. layer_inspect=data.layer_inspect,
  816. timelapse=data.timelapse,
  817. use_ams=data.use_ams,
  818. nozzle_offset_cali=data.nozzle_offset_cali,
  819. preheat_override=data.preheat_override,
  820. preheat_chamber_target_override=data.preheat_chamber_target_override,
  821. gcode_injection=data.gcode_injection,
  822. cleanup_library_after_dispatch=data.cleanup_library_after_dispatch,
  823. project_id=data.project_id,
  824. position=start_position + i,
  825. status="pending",
  826. created_by_id=current_user.id if current_user else None,
  827. batch_id=batch_id,
  828. print_time_seconds=cached_print_time,
  829. )
  830. db.add(item)
  831. items.append(item)
  832. if variant_specs:
  833. variant_values = [
  834. _variant_values(spec, library_file, model, position)
  835. for position, (spec, library_file, model) in enumerate(variant_specs)
  836. ]
  837. # SJF orders pending items before any printer is known, so the row carries
  838. # the shortest candidate's estimate. Resolution replaces it with the one
  839. # that actually runs.
  840. estimates = [v["print_time_seconds"] for v in variant_values if v["print_time_seconds"]]
  841. for item in items:
  842. # Each copy in a quantity>1 batch gets its own candidate rows —
  843. # attempt counts are per-item, and two copies must be free to land on
  844. # different printers.
  845. item.variants.extend(PrintQueueVariant(**values) for values in variant_values)
  846. item.print_time_seconds = min(estimates) if estimates else None
  847. await db.commit()
  848. # Refresh the first item for the response
  849. item = items[0]
  850. await db.refresh(item)
  851. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  852. source_name = f"archive {data.archive_id}" if data.archive_id else f"library file {data.library_file_id}"
  853. target_desc = data.printer_id or (f"model {target_model_norm}" if target_model_norm else "unassigned")
  854. qty_desc = f" (×{quantity})" if quantity > 1 else ""
  855. logger.info("Added %s to queue for %s%s", source_name, target_desc, qty_desc)
  856. # MQTT relay - publish queue job added
  857. try:
  858. from backend.app.services.mqtt_relay import mqtt_relay
  859. await mqtt_relay.on_queue_job_added(
  860. job_id=item.id,
  861. filename=item.archive.filename if item.archive else "",
  862. printer_id=item.printer_id,
  863. printer_name=item.printer.name if item.printer else None,
  864. )
  865. except Exception:
  866. pass # Don't fail queue add if MQTT fails
  867. # Send notification for job added
  868. try:
  869. job_name = (
  870. item.archive.filename
  871. if item.archive
  872. else item.library_file.filename
  873. if item.library_file
  874. else f"Job #{item.id}"
  875. )
  876. job_name = job_name.replace(".gcode.3mf", "").replace(".3mf", "")
  877. if quantity > 1:
  878. job_name = f"{job_name} ×{quantity}"
  879. target = (
  880. item.printer.name if item.printer else (f"Any {item.target_model}" if target_model_norm else "Unassigned")
  881. )
  882. await notification_service.on_queue_job_added(
  883. job_name=job_name,
  884. target=target,
  885. db=db,
  886. printer_id=item.printer_id,
  887. printer_name=item.printer.name if item.printer else None,
  888. )
  889. except Exception:
  890. pass # Don't fail queue add if notification fails
  891. return _enrich_response(item)
  892. @router.patch("/bulk", response_model=PrintQueueBulkUpdateResponse)
  893. async def bulk_update_queue_items(
  894. data: PrintQueueBulkUpdate,
  895. db: AsyncSession = Depends(get_db),
  896. auth_result: tuple[User | None, bool] = Depends(
  897. require_ownership_permission(
  898. Permission.QUEUE_UPDATE_ALL,
  899. Permission.QUEUE_UPDATE_OWN,
  900. )
  901. ),
  902. ):
  903. """Bulk update multiple queue items with the same values.
  904. Only pending items can be updated. Non-pending items are skipped.
  905. Items not owned by the user are also skipped (unless user has *_all permission).
  906. """
  907. user, can_modify_all = auth_result
  908. if not data.item_ids:
  909. raise HTTPException(400, "No item IDs provided")
  910. # Get fields to update (exclude item_ids and unset fields)
  911. update_data = data.model_dump(exclude={"item_ids"}, exclude_unset=True)
  912. if not update_data:
  913. raise HTTPException(400, "No fields to update")
  914. # Validate printer_id if being changed
  915. if "printer_id" in update_data and update_data["printer_id"] is not None:
  916. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  917. if not result.scalar_one_or_none():
  918. raise HTTPException(400, "Printer not found")
  919. # Fetch all items
  920. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  921. items = result.scalars().all()
  922. updated_count = 0
  923. skipped_count = 0
  924. for item in items:
  925. # Skip non-pending rows and rows a dispatch worker has claimed (#2615) —
  926. # editing a claimed row mid-upload would split it from the in-flight
  927. # dispatch, so it's excluded from the bulk change (cancel to move it).
  928. if item.status != "pending" or item.dispatching_at is not None:
  929. skipped_count += 1
  930. continue
  931. # Ownership check
  932. if not can_modify_all and item.created_by_id != user.id:
  933. skipped_count += 1
  934. continue
  935. for field, value in update_data.items():
  936. setattr(item, field, value)
  937. updated_count += 1
  938. await db.commit()
  939. logger.info("Bulk updated %s queue items, skipped %s", updated_count, skipped_count)
  940. return PrintQueueBulkUpdateResponse(
  941. updated_count=updated_count,
  942. skipped_count=skipped_count,
  943. message=f"Updated {updated_count} items"
  944. + (f", skipped {skipped_count} non-pending/not-owned" if skipped_count else ""),
  945. )
  946. # --- Batch endpoints ---
  947. @router.post("/batches", response_model=PrintBatchResponse)
  948. async def create_batch(
  949. data: PrintBatchCreate,
  950. db: AsyncSession = Depends(get_db),
  951. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  952. ):
  953. """Create a batch.
  954. Two modes:
  955. * ``item_ids`` provided: assign the listed pending queue items to a new
  956. batch ("Group as batch" UI action).
  957. * ``item_ids`` omitted/empty: create an empty batch so the client can
  958. pass the returned ``id`` on subsequent ``POST /queue/`` calls. Used by
  959. the multi-plate auto-batch flow in PrintModal.
  960. """
  961. if not data.name or not data.name.strip():
  962. raise HTTPException(400, "Batch name is required")
  963. batch = PrintBatch(
  964. name=data.name.strip()[:255],
  965. archive_id=data.archive_id,
  966. library_file_id=data.library_file_id,
  967. quantity=len(data.item_ids) if data.item_ids else 1,
  968. status="active",
  969. created_by_id=current_user.id if current_user else None,
  970. )
  971. db.add(batch)
  972. await db.flush() # Need batch.id before assigning to items
  973. assigned = 0
  974. if data.item_ids:
  975. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  976. items = result.scalars().all()
  977. for item in items:
  978. if item.status != "pending":
  979. continue
  980. if item.batch_id is not None:
  981. continue
  982. if (
  983. current_user is not None
  984. and item.created_by_id != current_user.id
  985. and not current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  986. ):
  987. continue
  988. item.batch_id = batch.id
  989. assigned += 1
  990. batch.quantity = max(assigned, 1)
  991. await db.commit()
  992. await db.refresh(batch)
  993. logger.info("Created batch %s '%s' with %s assigned items", batch.id, batch.name, assigned)
  994. return await _build_batch_response(db, batch)
  995. @router.post("/batches/{batch_id}/ungroup", response_model=PrintBatchUngroupResponse)
  996. async def ungroup_batch(
  997. batch_id: int,
  998. db: AsyncSession = Depends(get_db),
  999. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_OWN),
  1000. ):
  1001. """Disband a batch: clear batch_id from all members and delete the batch row.
  1002. Items stay in the queue. Only ungroups items the caller owns (unless they
  1003. hold QUEUE_UPDATE_ALL). A batch with all members ungrouped is deleted.
  1004. """
  1005. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  1006. batch = result.scalar_one_or_none()
  1007. if not batch:
  1008. raise HTTPException(404, "Batch not found")
  1009. can_modify_all = current_user is None or current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  1010. if not can_modify_all and batch.created_by_id != (current_user.id if current_user else None):
  1011. raise HTTPException(404, "Batch not found")
  1012. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.batch_id == batch_id))
  1013. items = result.scalars().all()
  1014. ungrouped = 0
  1015. remaining = 0
  1016. for item in items:
  1017. if not can_modify_all and item.created_by_id != (current_user.id if current_user else None):
  1018. remaining += 1
  1019. continue
  1020. item.batch_id = None
  1021. ungrouped += 1
  1022. # Delete the batch row only when all members were ungrouped — otherwise it
  1023. # still owns the items the caller couldn't touch.
  1024. if remaining == 0:
  1025. await db.delete(batch)
  1026. await db.commit()
  1027. logger.info("Ungrouped batch %s (%s items)", batch_id, ungrouped)
  1028. return PrintBatchUngroupResponse(
  1029. ungrouped_count=ungrouped,
  1030. message=f"Ungrouped {ungrouped} item(s)",
  1031. )
  1032. @router.get("/batches", response_model=list[PrintBatchResponse])
  1033. async def list_batches(
  1034. status: str | None = Query(None, description="Filter by status (active, completed, cancelled)"),
  1035. db: AsyncSession = Depends(get_db),
  1036. auth_result: tuple[User | None, bool] = Depends(
  1037. require_ownership_permission(
  1038. Permission.QUEUE_READ_ALL,
  1039. Permission.QUEUE_READ_OWN,
  1040. )
  1041. ),
  1042. ):
  1043. """List all print batches with progress stats."""
  1044. current_user, can_read_all = auth_result
  1045. query = select(PrintBatch).order_by(PrintBatch.created_at.desc())
  1046. if status:
  1047. query = query.where(PrintBatch.status == status)
  1048. if current_user is not None and not can_read_all:
  1049. query = query.where(PrintBatch.created_by_id == current_user.id)
  1050. result = await db.execute(query)
  1051. batches = result.scalars().all()
  1052. responses = []
  1053. for batch in batches:
  1054. responses.append(await _build_batch_response(db, batch))
  1055. return responses
  1056. @router.get("/batches/{batch_id}", response_model=PrintBatchResponse)
  1057. async def get_batch(
  1058. batch_id: int,
  1059. db: AsyncSession = Depends(get_db),
  1060. auth_result: tuple[User | None, bool] = Depends(
  1061. require_ownership_permission(
  1062. Permission.QUEUE_READ_ALL,
  1063. Permission.QUEUE_READ_OWN,
  1064. )
  1065. ),
  1066. ):
  1067. """Get a print batch with progress stats."""
  1068. current_user, can_read_all = auth_result
  1069. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  1070. batch = result.scalar_one_or_none()
  1071. if not batch:
  1072. raise HTTPException(404, "Batch not found")
  1073. if (
  1074. current_user is not None
  1075. and not can_read_all
  1076. and (batch.created_by_id is None or batch.created_by_id != current_user.id)
  1077. ):
  1078. raise HTTPException(404, "Batch not found")
  1079. return await _build_batch_response(db, batch)
  1080. @router.delete("/batches/{batch_id}")
  1081. async def cancel_batch(
  1082. batch_id: int,
  1083. db: AsyncSession = Depends(get_db),
  1084. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_DELETE_ALL),
  1085. ):
  1086. """Cancel all pending items in a batch and mark batch as cancelled."""
  1087. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  1088. batch = result.scalar_one_or_none()
  1089. if not batch:
  1090. raise HTTPException(404, "Batch not found")
  1091. # Cancel all pending queue items in this batch
  1092. result = await db.execute(
  1093. select(PrintQueueItem).where(and_(PrintQueueItem.batch_id == batch_id, PrintQueueItem.status == "pending"))
  1094. )
  1095. pending_items = result.scalars().all()
  1096. cancelled_count = 0
  1097. for item in pending_items:
  1098. item.status = "cancelled"
  1099. cancelled_count += 1
  1100. batch.status = "cancelled"
  1101. await db.commit()
  1102. return {"message": f"Batch cancelled, {cancelled_count} pending items cancelled"}
  1103. async def _build_batch_response(db: AsyncSession, batch: PrintBatch) -> PrintBatchResponse:
  1104. """Build a batch response with derived counts from queue items."""
  1105. # Count queue items by status
  1106. result = await db.execute(
  1107. select(PrintQueueItem.status, func.count(PrintQueueItem.id))
  1108. .where(PrintQueueItem.batch_id == batch.id)
  1109. .group_by(PrintQueueItem.status)
  1110. )
  1111. status_counts = {row[0]: row[1] for row in result.fetchall()}
  1112. # Load created_by for username
  1113. created_by_username = None
  1114. if batch.created_by_id:
  1115. result = await db.execute(select(User).where(User.id == batch.created_by_id))
  1116. user = result.scalar_one_or_none()
  1117. if user:
  1118. created_by_username = user.username
  1119. return PrintBatchResponse(
  1120. id=batch.id,
  1121. name=batch.name,
  1122. archive_id=batch.archive_id,
  1123. library_file_id=batch.library_file_id,
  1124. quantity=batch.quantity,
  1125. status=batch.status,
  1126. created_at=batch.created_at,
  1127. created_by_id=batch.created_by_id,
  1128. created_by_username=created_by_username,
  1129. pending_count=status_counts.get("pending", 0),
  1130. printing_count=status_counts.get("printing", 0),
  1131. completed_count=status_counts.get("completed", 0),
  1132. failed_count=status_counts.get("failed", 0),
  1133. cancelled_count=status_counts.get("cancelled", 0),
  1134. )
  1135. @router.get("/{item_id}", response_model=PrintQueueItemResponse)
  1136. async def get_queue_item(
  1137. item_id: int,
  1138. db: AsyncSession = Depends(get_db),
  1139. auth_result: tuple[User | None, bool] = Depends(
  1140. require_ownership_permission(
  1141. Permission.QUEUE_READ_ALL,
  1142. Permission.QUEUE_READ_OWN,
  1143. )
  1144. ),
  1145. ):
  1146. """Get a specific queue item."""
  1147. current_user, can_read_all = auth_result
  1148. result = await db.execute(
  1149. select(PrintQueueItem)
  1150. .options(
  1151. selectinload(PrintQueueItem.archive),
  1152. selectinload(PrintQueueItem.printer),
  1153. selectinload(PrintQueueItem.library_file),
  1154. selectinload(PrintQueueItem.created_by),
  1155. selectinload(PrintQueueItem.batch),
  1156. )
  1157. .where(PrintQueueItem.id == item_id)
  1158. )
  1159. item = result.scalar_one_or_none()
  1160. if not item:
  1161. raise HTTPException(404, "Queue item not found")
  1162. if (
  1163. current_user is not None
  1164. and not can_read_all
  1165. and (item.created_by_id is None or item.created_by_id != current_user.id)
  1166. ):
  1167. raise HTTPException(404, "Queue item not found")
  1168. return _enrich_response(item)
  1169. @router.patch("/{item_id}", response_model=PrintQueueItemResponse)
  1170. async def update_queue_item(
  1171. item_id: int,
  1172. data: PrintQueueItemUpdate,
  1173. db: AsyncSession = Depends(get_db),
  1174. auth_result: tuple[User | None, bool] = Depends(
  1175. require_ownership_permission(
  1176. Permission.QUEUE_UPDATE_ALL,
  1177. Permission.QUEUE_UPDATE_OWN,
  1178. )
  1179. ),
  1180. ):
  1181. """Update a queue item."""
  1182. user, can_modify_all = auth_result
  1183. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1184. item = result.scalar_one_or_none()
  1185. if not item:
  1186. raise HTTPException(404, "Queue item not found")
  1187. # Ownership check
  1188. if not can_modify_all:
  1189. if item.created_by_id != user.id:
  1190. raise HTTPException(403, "You can only update your own queue items")
  1191. if item.status != "pending":
  1192. raise HTTPException(400, "Can only update pending items")
  1193. # Dispatch claim (#2615): the row is pending but a scheduler worker has
  1194. # already claimed it and is uploading to its printer. Editing now (e.g.
  1195. # reassigning printer_id) would split the queue row from the in-flight
  1196. # archive/expected-print/physical command. Reject until dispatch finishes;
  1197. # to move it, cancel first (the coordinated escape) and re-queue.
  1198. if item.dispatching_at is not None:
  1199. raise HTTPException(409, "Item is being dispatched — cancel it first to make changes")
  1200. update_data = data.model_dump(exclude_unset=True)
  1201. # Normalize target_model if being updated (see add_to_queue for why the
  1202. # code map has to run first).
  1203. if "target_model" in update_data and update_data["target_model"]:
  1204. update_data["target_model"] = normalize_model_name(update_data["target_model"])
  1205. # Cannot specify both printer_id and target_model
  1206. new_printer_id = update_data.get("printer_id", item.printer_id)
  1207. new_target_model = update_data.get("target_model", item.target_model)
  1208. if new_printer_id and new_target_model:
  1209. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  1210. # Validate new printer_id if being changed (and not None)
  1211. if "printer_id" in update_data and update_data["printer_id"] is not None:
  1212. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  1213. if not result.scalar_one_or_none():
  1214. raise HTTPException(400, "Printer not found")
  1215. # Validate target_model has active printers
  1216. if "target_model" in update_data and update_data["target_model"]:
  1217. result = await db.execute(
  1218. select(Printer).where(Printer.model == update_data["target_model"]).where(Printer.is_active == True) # noqa: E712
  1219. )
  1220. if not result.scalars().first():
  1221. raise HTTPException(400, f"No active printers for model: {update_data['target_model']}")
  1222. # Cross-model safety gate (#2578) — same check as the create route, so
  1223. # a mismatched target can't be introduced by editing either.
  1224. sliced_for = None
  1225. if item.archive_id:
  1226. result = await db.execute(select(PrintArchive.sliced_for_model).where(PrintArchive.id == item.archive_id))
  1227. sliced_for = result.scalar_one_or_none()
  1228. elif item.library_file_id:
  1229. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1230. lib = result.scalar_one_or_none()
  1231. if lib and lib.file_metadata:
  1232. sliced_for = lib.file_metadata.get("sliced_for_model")
  1233. if not is_gcode_compatible(sliced_for, update_data["target_model"]):
  1234. raise HTTPException(
  1235. 400,
  1236. f"File was sliced for {sliced_for} and cannot be dispatched to {update_data['target_model']} printers",
  1237. )
  1238. # Serialize ams_mapping to JSON for TEXT column storage
  1239. if "ams_mapping" in update_data:
  1240. update_data["ams_mapping"] = json.dumps(update_data["ams_mapping"]) if update_data["ams_mapping"] else None
  1241. # Serialize filament_overrides to JSON for TEXT column storage, keeping only
  1242. # the slots this item's plate actually prints (#2551 — same shared-override
  1243. # list the create path narrows).
  1244. if "filament_overrides" in update_data:
  1245. overrides = update_data["filament_overrides"]
  1246. if overrides:
  1247. overrides = overrides_for_plate(
  1248. overrides,
  1249. await _resolve_source_path(db, item),
  1250. update_data.get("plate_id", item.plate_id),
  1251. )
  1252. update_data["filament_overrides"] = json.dumps(overrides) if overrides else None
  1253. # Serialize H2C rack-swap nozzle pick (#1780) to JSON for TEXT column
  1254. # storage; same Text-as-opaque-blob convention as ams_mapping above.
  1255. if "nozzle_mapping" in update_data:
  1256. update_data["nozzle_mapping"] = (
  1257. json.dumps(update_data["nozzle_mapping"]) if update_data["nozzle_mapping"] else None
  1258. )
  1259. # Re-check the dispatch claim right before mutating (#2615). Several awaited
  1260. # validations ran since the guard above, and a scheduler worker may have
  1261. # claimed the row in that gap. A fresh read (item isn't dirty yet, so no
  1262. # autoflush races the check) narrows the window to effectively nothing.
  1263. claimed = (
  1264. await db.execute(select(PrintQueueItem.dispatching_at).where(PrintQueueItem.id == item_id))
  1265. ).scalar_one_or_none()
  1266. if claimed is not None:
  1267. raise HTTPException(409, "Item is being dispatched — cancel it first to make changes")
  1268. for field, value in update_data.items():
  1269. setattr(item, field, value)
  1270. await db.commit()
  1271. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  1272. logger.info("Updated queue item %s", item_id)
  1273. return _enrich_response(item)
  1274. @router.delete("/{item_id}")
  1275. async def delete_queue_item(
  1276. item_id: int,
  1277. db: AsyncSession = Depends(get_db),
  1278. auth_result: tuple[User | None, bool] = Depends(
  1279. require_ownership_permission(
  1280. Permission.QUEUE_DELETE_ALL,
  1281. Permission.QUEUE_DELETE_OWN,
  1282. )
  1283. ),
  1284. ):
  1285. """Remove an item from the queue."""
  1286. user, can_modify_all = auth_result
  1287. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1288. item = result.scalar_one_or_none()
  1289. if not item:
  1290. raise HTTPException(404, "Queue item not found")
  1291. # Ownership check
  1292. if not can_modify_all:
  1293. if item.created_by_id != user.id:
  1294. raise HTTPException(403, "You can only delete your own queue items")
  1295. if item.status == "printing":
  1296. raise HTTPException(400, "Cannot delete item that is currently printing")
  1297. await db.delete(item)
  1298. await db.commit()
  1299. logger.info("Deleted queue item %s", item_id)
  1300. return {"message": "Queue item deleted"}
  1301. @router.post("/reorder")
  1302. async def reorder_queue(
  1303. data: PrintQueueReorder,
  1304. db: AsyncSession = Depends(get_db),
  1305. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  1306. ):
  1307. """Bulk update positions for queue items."""
  1308. for reorder_item in data.items:
  1309. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == reorder_item.id))
  1310. item = result.scalar_one_or_none()
  1311. if item and item.status == "pending":
  1312. item.position = reorder_item.position
  1313. await db.commit()
  1314. logger.info("Reordered %s queue items", len(data.items))
  1315. return {"message": f"Reordered {len(data.items)} items"}
  1316. @router.post("/printer/{printer_id}/resume")
  1317. async def resume_queue_after_failure(
  1318. printer_id: int,
  1319. db: AsyncSession = Depends(get_db),
  1320. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  1321. ):
  1322. """Clear the previous-success gate for a printer and restore skipped items.
  1323. Single atomic op (#1818):
  1324. * Sets ``gate_acknowledged=True`` on every ``failed`` / ``aborted`` queue
  1325. item for this printer that's still in the scheduler's lookback window,
  1326. so the next ``_check_previous_success`` call ignores them.
  1327. * Restores ``skipped`` items whose ``error_message`` matches the
  1328. scheduler's exact "Previous print failed or was aborted" gate string
  1329. back to ``pending`` (clears ``error_message`` + ``completed_at``).
  1330. Returns counts so the UI can render a precise toast. No-op endpoint
  1331. (zero counts) when called against a printer with no gate to clear.
  1332. """
  1333. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1334. printer = result.scalar_one_or_none()
  1335. if not printer:
  1336. raise HTTPException(404, "Printer not found")
  1337. ack_result = await db.execute(
  1338. select(PrintQueueItem)
  1339. .where(PrintQueueItem.printer_id == printer_id)
  1340. .where(PrintQueueItem.status.in_(["failed", "aborted"]))
  1341. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  1342. )
  1343. to_ack = ack_result.scalars().all()
  1344. for failed_item in to_ack:
  1345. failed_item.gate_acknowledged = True
  1346. restore_result = await db.execute(
  1347. select(PrintQueueItem)
  1348. .where(PrintQueueItem.printer_id == printer_id)
  1349. .where(PrintQueueItem.status == "skipped")
  1350. .where(PrintQueueItem.error_message == "Previous print failed or was aborted")
  1351. )
  1352. to_restore = restore_result.scalars().all()
  1353. for skipped_item in to_restore:
  1354. skipped_item.status = "pending"
  1355. skipped_item.error_message = None
  1356. skipped_item.completed_at = None
  1357. await db.commit()
  1358. logger.info(
  1359. "Resume after failure on printer %s: acknowledged %d failure(s), restored %d skipped item(s)",
  1360. printer_id,
  1361. len(to_ack),
  1362. len(to_restore),
  1363. )
  1364. return {"acknowledged": len(to_ack), "restored": len(to_restore)}
  1365. @router.post("/{item_id}/cancel")
  1366. async def cancel_queue_item(
  1367. item_id: int,
  1368. db: AsyncSession = Depends(get_db),
  1369. auth_result: tuple[User | None, bool] = Depends(
  1370. require_ownership_permission(
  1371. Permission.QUEUE_UPDATE_ALL,
  1372. Permission.QUEUE_UPDATE_OWN,
  1373. )
  1374. ),
  1375. ):
  1376. """Cancel a pending queue item."""
  1377. user, can_modify_all = auth_result
  1378. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1379. item = result.scalar_one_or_none()
  1380. if not item:
  1381. raise HTTPException(404, "Queue item not found")
  1382. # Ownership check
  1383. if not can_modify_all:
  1384. if item.created_by_id != user.id:
  1385. raise HTTPException(403, "You can only cancel your own queue items")
  1386. if item.status not in ("pending",):
  1387. raise HTTPException(400, f"Cannot cancel item with status '{item.status}'")
  1388. item.status = "cancelled"
  1389. item.completed_at = datetime.now(timezone.utc)
  1390. await db.commit()
  1391. logger.info("Cancelled queue item %s", item_id)
  1392. return {"message": "Queue item cancelled"}
  1393. @router.post("/{item_id}/stop")
  1394. async def stop_queue_item(
  1395. item_id: int,
  1396. db: AsyncSession = Depends(get_db),
  1397. auth_result: tuple[User | None, bool] = Depends(
  1398. require_ownership_permission(
  1399. Permission.QUEUE_UPDATE_ALL,
  1400. Permission.QUEUE_UPDATE_OWN,
  1401. )
  1402. ),
  1403. ):
  1404. """Stop an actively printing queue item.
  1405. Ownership-scoped (#1625-followup): callers with QUEUE_UPDATE_OWN can stop
  1406. their own items; callers with QUEUE_UPDATE_ALL can stop any item. Mirrors
  1407. the /cancel shape. Pre-fix this required QUEUE_UPDATE_ALL — Operators
  1408. holding only _OWN saw the Stop button in the queue UI but got 403 on click.
  1409. """
  1410. from backend.app.services.printer_manager import printer_manager
  1411. user, can_modify_all = auth_result
  1412. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1413. item = result.scalar_one_or_none()
  1414. if not item:
  1415. raise HTTPException(404, "Queue item not found")
  1416. # Ownership check — mirrors /cancel. Ownerless items (created_by_id IS NULL)
  1417. # require _ALL: stop is destructive and an _OWN holder can't claim "they
  1418. # own it" the way /start does (#1670).
  1419. if not can_modify_all and user is not None:
  1420. if item.created_by_id is None or item.created_by_id != user.id:
  1421. raise HTTPException(403, "You can only stop your own queue items")
  1422. if item.status != "printing":
  1423. raise HTTPException(400, f"Can only stop items that are printing, current status: '{item.status}'")
  1424. # Capture values we need for background task
  1425. printer_id = item.printer_id
  1426. auto_off_after = item.auto_off_after
  1427. # Try to send stop command to printer
  1428. stop_sent = False
  1429. try:
  1430. stop_sent = printer_manager.stop_print(printer_id)
  1431. if not stop_sent:
  1432. logger.warning("stop_print returned False for printer %s - printer may not be connected", printer_id)
  1433. except Exception as e:
  1434. logger.error("Error sending stop command for queue item %s: %s", item_id, e)
  1435. # Mark this printer as user-stopped BEFORE the first await so that if the
  1436. # MQTT on_print_complete callback fires during the db.commit() yield the flag
  1437. # is already set and the "failed" status will be correctly overridden to
  1438. # "cancelled" (preventing a spurious "print failed" notification).
  1439. try:
  1440. from backend.app.main import mark_printer_stopped_by_user
  1441. mark_printer_stopped_by_user(printer_id)
  1442. except Exception as _mark_err:
  1443. logger.warning("Failed to mark printer %s as user-stopped: %s", printer_id, _mark_err)
  1444. # Update queue item status regardless - if printer is off, print is already stopped
  1445. item.status = "cancelled"
  1446. item.completed_at = datetime.now(timezone.utc)
  1447. item.error_message = "Stopped by user" if stop_sent else "Stopped by user (printer was offline)"
  1448. # Reconcile the linked archive when the printer is offline (#2603). When the
  1449. # stop command reaches the printer it later reports the stop over MQTT and
  1450. # on_print_complete flips the archive to cancelled/failed. When the printer is
  1451. # offline no such event ever arrives, so the archive would stay "printing"
  1452. # forever (queue row cancelled, archive still printing — the reporter's
  1453. # archive 436). Close it out here, mirroring what the MQTT path would have
  1454. # done. Only touch a still-"printing" archive so we never overwrite a real
  1455. # completion that raced in.
  1456. if not stop_sent and item.archive_id:
  1457. archive = await db.get(PrintArchive, item.archive_id)
  1458. if archive and archive.status == "printing":
  1459. archive.status = "cancelled"
  1460. archive.completed_at = datetime.now(timezone.utc)
  1461. archive.failure_reason = "Stopped by user (printer was offline)"
  1462. await db.commit()
  1463. logger.info("Stopped printing queue item %s (stop command sent: %s)", item_id, stop_sent)
  1464. # Schedule power-off if the queue item opted in. Delegates to the smart-plug
  1465. # manager so the off honours each plug's configured strategy (time delay or
  1466. # temperature threshold), is cancelled if the printer starts printing again,
  1467. # and never cuts power on a loaded print (#1890). Previously an inline block
  1468. # hardcoded a 50°C / 600s cooldown wait and powered off on the timeout
  1469. # regardless of print state.
  1470. if auto_off_after:
  1471. from backend.app.services.smart_plug_manager import smart_plug_manager
  1472. try:
  1473. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  1474. except Exception as e:
  1475. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", printer_id, e)
  1476. return {"message": "Print stopped" if stop_sent else "Queue item cancelled (printer was offline)"}
  1477. @router.post("/{item_id}/start")
  1478. async def start_queue_item(
  1479. item_id: int,
  1480. skip_filament_check: bool = Query(default=False),
  1481. db: AsyncSession = Depends(get_db),
  1482. auth_result: tuple[User | None, bool] = Depends(
  1483. require_ownership_permission(
  1484. Permission.QUEUE_UPDATE_ALL,
  1485. Permission.QUEUE_UPDATE_OWN,
  1486. )
  1487. ),
  1488. ):
  1489. """Manually start a staged (manual_start) queue item.
  1490. Ownership-scoped (#1625-followup): callers with QUEUE_UPDATE_OWN can
  1491. start their own items + claim ownership of NULL-owner items (VP-uploaded
  1492. items arrive unattributed per #1670). Callers with QUEUE_UPDATE_ALL can
  1493. start any item. Pre-fix this required QUEUE_UPDATE_OWN with no ownership
  1494. check, so _OWN holders could start anyone's queue items via direct API.
  1495. Clears the manual_start flag so the scheduler picks it up. When
  1496. ``skip_filament_check`` is false (the default) the live filament
  1497. deficit (#1496) is checked first — if the assigned spool can't satisfy
  1498. a slot's required grams, the route returns ``409`` with the deficit
  1499. payload so the caller can show a confirm dialog and retry with
  1500. ``skip_filament_check=true``.
  1501. """
  1502. user, can_modify_all = auth_result
  1503. result = await db.execute(
  1504. select(PrintQueueItem)
  1505. .options(
  1506. selectinload(PrintQueueItem.archive),
  1507. selectinload(PrintQueueItem.printer),
  1508. selectinload(PrintQueueItem.library_file),
  1509. selectinload(PrintQueueItem.batch),
  1510. )
  1511. .where(PrintQueueItem.id == item_id)
  1512. )
  1513. item = result.scalar_one_or_none()
  1514. if not item:
  1515. raise HTTPException(404, "Queue item not found")
  1516. # Ownership check — softer than /cancel because /start is the entry point
  1517. # for #1670's VP-import flow: an unowned item is claimable by the first
  1518. # _OWN holder who clicks ▶, and the route below credits them as owner.
  1519. # An item with a DIFFERENT owner → 403.
  1520. if not can_modify_all and user is not None:
  1521. if item.created_by_id is not None and item.created_by_id != user.id:
  1522. raise HTTPException(403, "You can only start your own queue items")
  1523. if item.status != "pending":
  1524. raise HTTPException(400, f"Can only start pending items, current status: '{item.status}'")
  1525. # Live deficit check — re-evaluated against current spool state, so a
  1526. # spool swap between scheduler flagging and the user clicking ▶ clears
  1527. # the block automatically.
  1528. if not skip_filament_check:
  1529. deficit = await compute_deficit_for_queue_item(db, item)
  1530. if deficit:
  1531. raise HTTPException(
  1532. status_code=409,
  1533. detail={
  1534. "code": "insufficient_filament",
  1535. "deficit": [d.to_dict() for d in deficit],
  1536. },
  1537. )
  1538. # Print Anyway / no deficit: clear the flags and let the scheduler dispatch.
  1539. item.manual_start = False
  1540. item.filament_short = False
  1541. # Persist the user's "Print Anyway" decision so the scheduler does not
  1542. # immediately re-flag this item on the next tick (#1698-followup). The
  1543. # pre-fix behaviour bounced between "user said anyway" and
  1544. # "scheduler re-blocked on same deficit" forever.
  1545. if skip_filament_check:
  1546. item.skip_filament_check = True
  1547. # Credit the clicker as the item's owner when no prior owner is set —
  1548. # VP-uploaded queue items arrive over FTP unattributed, so without this
  1549. # the print log's User column stays blank even when auth is on
  1550. # (#1670). An item that already has a creator (UI-added queue items)
  1551. # keeps that attribution; the dispatcher is not promoted over the
  1552. # original uploader.
  1553. if user is not None and item.created_by_id is None:
  1554. item.created_by_id = user.id
  1555. await db.commit()
  1556. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  1557. logger.info(
  1558. "Manually started queue item %s (cleared manual_start; skip_filament_check=%s)",
  1559. item_id,
  1560. skip_filament_check,
  1561. )
  1562. return _enrich_response(item)