print_queue.py 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366
  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, inspect, 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, PrintBatchPlate
  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. PrintBatchDispatchRequest,
  27. PrintBatchPlateProgress,
  28. PrintBatchPlateTarget,
  29. PrintBatchResponse,
  30. PrintBatchUngroupResponse,
  31. PrintBatchUpdate,
  32. PrintQueueBulkUpdate,
  33. PrintQueueBulkUpdateResponse,
  34. PrintQueueItemCreate,
  35. PrintQueueItemResponse,
  36. PrintQueueItemUpdate,
  37. PrintQueueReorder,
  38. QueueVariantCreate,
  39. QueueVariantSummary,
  40. )
  41. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  42. from backend.app.services.filament_requirements import overrides_for_plate
  43. from backend.app.services.finance_budget import release_budget_reservation, validate_print_budget
  44. from backend.app.services.notification_service import notification_service
  45. from backend.app.services.print_batch import (
  46. BatchDispatchError,
  47. dispatch_remaining,
  48. load_progress,
  49. refresh_batch_status,
  50. )
  51. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  52. from backend.app.utils.printer_models import (
  53. is_gcode_compatible,
  54. )
  55. from backend.app.utils.threemf_tools import (
  56. extract_plate_metadata_from_3mf,
  57. extract_print_time_from_3mf,
  58. )
  59. logger = logging.getLogger(__name__)
  60. router = APIRouter(prefix="/queue", tags=["queue"])
  61. def _variant_summaries(item: PrintQueueItem) -> list[QueueVariantSummary]:
  62. """Cross-model candidates for display (#671), or [] if they weren't loaded.
  63. Every route that builds a queue response eager-loads ``variants``. Reading
  64. the attribute unguarded would still be a landmine for the next one that
  65. doesn't: a lazy load on an async session raises rather than degrading, so a
  66. forgotten ``selectinload`` would turn a card render into a 500.
  67. """
  68. if "variants" in inspect(item).unloaded:
  69. return []
  70. return [
  71. QueueVariantSummary(
  72. library_file_id=v.library_file_id,
  73. filename=v.library_file.filename if v.library_file else "",
  74. target_model=v.target_model,
  75. position=v.position,
  76. )
  77. for v in item.variants
  78. ]
  79. def _extract_filament_types_from_3mf(file_path: Path, plate_id: int | None = None) -> list[str]:
  80. """Extract unique filament types from a 3MF file.
  81. Args:
  82. file_path: Path to the 3MF file
  83. plate_id: Optional plate index to filter for (for multi-plate files)
  84. Returns:
  85. List of unique filament types (e.g., ["PLA", "PETG"])
  86. """
  87. types: set[str] = set()
  88. try:
  89. with zipfile.ZipFile(file_path, "r") as zf:
  90. if "Metadata/slice_info.config" not in zf.namelist():
  91. return []
  92. content = zf.read("Metadata/slice_info.config").decode()
  93. root = ET.fromstring(content)
  94. if plate_id is not None:
  95. # Find the plate element with matching index
  96. for plate_elem in root.findall(".//plate"):
  97. plate_index = None
  98. for meta in plate_elem.findall("metadata"):
  99. if meta.get("key") == "index":
  100. try:
  101. plate_index = int(meta.get("value", "0"))
  102. except ValueError:
  103. pass # Skip plate with unparseable index
  104. break
  105. if plate_index == plate_id:
  106. for filament_elem in plate_elem.findall("filament"):
  107. filament_type = filament_elem.get("type", "")
  108. used_g = filament_elem.get("used_g", "0")
  109. try:
  110. used_grams = float(used_g)
  111. except (ValueError, TypeError):
  112. used_grams = 0
  113. if used_grams > 0 and filament_type:
  114. types.add(filament_type)
  115. break
  116. else:
  117. # No plate_id specified - extract all filaments with used_g > 0
  118. for filament_elem in root.findall(".//filament"):
  119. filament_type = filament_elem.get("type", "")
  120. used_g = filament_elem.get("used_g", "0")
  121. try:
  122. used_grams = float(used_g)
  123. except (ValueError, TypeError):
  124. used_grams = 0
  125. if used_grams > 0 and filament_type:
  126. types.add(filament_type)
  127. except Exception as e:
  128. logger.warning("Failed to extract filament types from %s: %s", file_path, e)
  129. return sorted(types)
  130. # Local alias kept so existing call sites stay compact; the implementation lives
  131. # in utils/threemf_tools.py so the notification path (main.py) can reuse it
  132. # without importing from a routes module (#1785).
  133. _extract_print_time_from_3mf = extract_print_time_from_3mf
  134. def _assert_can_queue_archive(archive: PrintArchive, current_user: User | None) -> None:
  135. """Gate turning *archive* into a print. Raises rather than returning a verdict.
  136. Shared by every route that creates queue items from an archive, so a new
  137. one can't quietly become a weaker door to the same action than
  138. ``POST /queue/`` is.
  139. Two separate checks:
  140. * IDOR fix (maziggy/bambuddy-security #2): without this, a caller with
  141. QUEUE_CREATE could queue any user's archive even without ARCHIVES_READ on
  142. it — Landon's PoC enumerated this on admin's archives as operator1. Gate
  143. on ARCHIVES_READ_ALL OR ownership. 404 (not 403) so we don't leak "this
  144. id exists but you can't queue it" for enumeration.
  145. * Reprint perm gate (#1625): the legacy ``/archives/{id}/reprint`` endpoint
  146. required ARCHIVES_REPRINT_OWN/ALL, and every route that replaces it must
  147. keep that gate or an operator with QUEUE_CREATE could reprint via a
  148. direct API call even when explicitly denied reprint perm. Mirrors the
  149. frontend ``canModify('archives', 'reprint', ...)`` helper: REPRINT_ALL
  150. allows any archive, REPRINT_OWN allows own only, ownerless archives
  151. require REPRINT_ALL (fail-closed).
  152. """
  153. if current_user is None:
  154. return
  155. if not current_user.has_permission(Permission.ARCHIVES_READ_ALL.value) and archive.created_by_id != current_user.id:
  156. raise HTTPException(404, "Archive not found")
  157. owns_archive = archive.created_by_id is not None and archive.created_by_id == current_user.id
  158. has_reprint = current_user.has_permission(Permission.ARCHIVES_REPRINT_ALL.value) or (
  159. owns_archive and current_user.has_permission(Permission.ARCHIVES_REPRINT_OWN.value)
  160. )
  161. if not has_reprint:
  162. raise HTTPException(
  163. status_code=403,
  164. detail="Permission archives:reprint_own or archives:reprint_all required",
  165. )
  166. def _assert_can_queue_library_file(library_file: LibraryFile, current_user: User | None) -> None:
  167. """Gate turning *library_file* into a print — LIBRARY_READ_ALL or ownership."""
  168. if current_user is None:
  169. return
  170. if (
  171. not current_user.has_permission(Permission.LIBRARY_READ_ALL.value)
  172. and library_file.created_by_id != current_user.id
  173. ):
  174. raise HTTPException(404, "Library file not found")
  175. async def _assert_can_dispatch_batch_sources(db: AsyncSession, batch_id: int, current_user: User | None) -> None:
  176. """Apply the ``POST /queue/`` source-file gates to everything a dispatch would print.
  177. Dispatching clones existing queue items, so without this it would be a
  178. weaker door to the same outcome: a caller holding QUEUE_CREATE and
  179. QUEUE_UPDATE_ALL but explicitly denied ``archives:reprint_*`` could start
  180. prints through an order that ``POST /queue/`` would have refused them.
  181. Every distinct source among the batch's items is checked, including the
  182. library files behind cross-model variants — those get cloned too, and any
  183. one of them may be the file that actually runs.
  184. """
  185. archive_ids = set(
  186. (
  187. await db.execute(
  188. select(PrintQueueItem.archive_id)
  189. .where(PrintQueueItem.batch_id == batch_id)
  190. .where(PrintQueueItem.archive_id.is_not(None))
  191. .distinct()
  192. )
  193. )
  194. .scalars()
  195. .all()
  196. )
  197. library_file_ids = set(
  198. (
  199. await db.execute(
  200. select(PrintQueueItem.library_file_id)
  201. .where(PrintQueueItem.batch_id == batch_id)
  202. .where(PrintQueueItem.library_file_id.is_not(None))
  203. .distinct()
  204. )
  205. )
  206. .scalars()
  207. .all()
  208. )
  209. library_file_ids |= set(
  210. (
  211. await db.execute(
  212. select(PrintQueueVariant.library_file_id)
  213. .join(PrintQueueItem, PrintQueueVariant.queue_item_id == PrintQueueItem.id)
  214. .where(PrintQueueItem.batch_id == batch_id)
  215. .distinct()
  216. )
  217. )
  218. .scalars()
  219. .all()
  220. )
  221. for archive_id in archive_ids:
  222. archive = (await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))).scalar_one_or_none()
  223. # A deleted source can't be printed; dispatch will fail on it anyway.
  224. if archive is not None:
  225. _assert_can_queue_archive(archive, current_user)
  226. for library_file_id in library_file_ids:
  227. library_file = (
  228. await db.execute(LibraryFile.active().where(LibraryFile.id == library_file_id))
  229. ).scalar_one_or_none()
  230. if library_file is not None:
  231. _assert_can_queue_library_file(library_file, current_user)
  232. async def _resolve_source_path(db: AsyncSession, item: PrintQueueItem) -> Path | None:
  233. """Resolve an existing queue item's source 3MF on disk, or None."""
  234. if item.archive_id:
  235. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  236. archive = result.scalar_one_or_none()
  237. if archive:
  238. return settings.base_dir / archive.file_path
  239. elif item.library_file_id:
  240. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  241. library_file = result.scalar_one_or_none()
  242. if library_file:
  243. lib_path = Path(library_file.file_path)
  244. return lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  245. return None
  246. async def _trusted_item_estimated_cost(
  247. db: AsyncSession,
  248. item: PrintQueueItem,
  249. *,
  250. printer_id: int | None,
  251. plate_id: int | None,
  252. ams_mapping: list[int] | str | None,
  253. ) -> float | None:
  254. """Recompute an existing queue item's cost from its persisted source."""
  255. if item.archive_id:
  256. archive = await db.scalar(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  257. return await estimate_queue_source_cost(
  258. db,
  259. archive=archive,
  260. plate_id=plate_id,
  261. ams_mapping=ams_mapping,
  262. printer_id=printer_id,
  263. )
  264. if item.library_file_id:
  265. library_file = await db.scalar(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  266. return await estimate_queue_source_cost(
  267. db,
  268. library_file=library_file,
  269. plate_id=plate_id,
  270. ams_mapping=ams_mapping,
  271. printer_id=printer_id,
  272. )
  273. result = await db.execute(
  274. select(PrintQueueVariant, LibraryFile)
  275. .join(LibraryFile, LibraryFile.id == PrintQueueVariant.library_file_id)
  276. .where(PrintQueueVariant.queue_item_id == item.id)
  277. )
  278. estimates = [
  279. await estimate_queue_source_cost(
  280. db,
  281. library_file=library_file,
  282. plate_id=variant.plate_id,
  283. ams_mapping=variant.ams_mapping,
  284. printer_id=printer_id,
  285. )
  286. for variant, library_file in result.all()
  287. ]
  288. if not estimates or any(cost is None for cost in estimates):
  289. return None
  290. return max(cost for cost in estimates if cost is not None)
  291. def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
  292. """Add nested archive/printer/library_file info to response."""
  293. # Parse ams_mapping from JSON string BEFORE model_validate
  294. ams_mapping_parsed = None
  295. if item.ams_mapping:
  296. try:
  297. ams_mapping_parsed = json.loads(item.ams_mapping)
  298. except json.JSONDecodeError:
  299. ams_mapping_parsed = None
  300. # Parse required_filament_types from JSON string
  301. required_filament_types_parsed = None
  302. if item.required_filament_types:
  303. try:
  304. required_filament_types_parsed = json.loads(item.required_filament_types)
  305. except json.JSONDecodeError:
  306. required_filament_types_parsed = None
  307. # Parse filament_overrides from JSON string
  308. filament_overrides_parsed = None
  309. if item.filament_overrides:
  310. try:
  311. filament_overrides_parsed = json.loads(item.filament_overrides)
  312. except json.JSONDecodeError:
  313. filament_overrides_parsed = None
  314. # Parse nozzle_mapping from JSON string (#1780 — H2C rack slicer-pick
  315. # preservation). Nullable opaque JSON blob stored verbatim from
  316. # BambuStudio's project_file; surface it parsed for the response model
  317. # and any future "edit print → nozzle" UI.
  318. nozzle_mapping_parsed = None
  319. if item.nozzle_mapping:
  320. try:
  321. nozzle_mapping_parsed = json.loads(item.nozzle_mapping)
  322. except json.JSONDecodeError:
  323. nozzle_mapping_parsed = None
  324. # The operator's rack-position pick (#1784), keyed by filament group. Sent
  325. # parsed so the print dialog can show which hotend each group will use.
  326. nozzle_rack_choice_parsed = None
  327. if item.nozzle_rack_choice:
  328. try:
  329. nozzle_rack_choice_parsed = json.loads(item.nozzle_rack_choice)
  330. except json.JSONDecodeError:
  331. nozzle_rack_choice_parsed = None
  332. nozzles_info_parsed = None
  333. if item.nozzles_info:
  334. try:
  335. nozzles_info_parsed = json.loads(item.nozzles_info)
  336. except json.JSONDecodeError:
  337. nozzles_info_parsed = None
  338. # Create response with parsed ams_mapping
  339. item_dict = {
  340. "id": item.id,
  341. "printer_id": item.printer_id,
  342. "target_model": item.target_model,
  343. "target_location": item.target_location,
  344. "required_filament_types": required_filament_types_parsed,
  345. "filament_overrides": filament_overrides_parsed,
  346. "waiting_reason": item.waiting_reason,
  347. "archive_id": item.archive_id,
  348. "library_file_id": item.library_file_id,
  349. "cost_center_id": item.cost_center_id,
  350. "estimated_cost": item.estimated_cost,
  351. "position": item.position,
  352. "scheduled_time": item.scheduled_time,
  353. "require_previous_success": item.require_previous_success,
  354. "auto_off_after": item.auto_off_after,
  355. "manual_start": item.manual_start,
  356. "filament_short": bool(item.filament_short),
  357. "skip_filament_check": bool(item.skip_filament_check),
  358. "ams_mapping": ams_mapping_parsed,
  359. "plate_id": item.plate_id,
  360. "bed_levelling": item.bed_levelling,
  361. "flow_cali": item.flow_cali,
  362. "vibration_cali": item.vibration_cali,
  363. "layer_inspect": item.layer_inspect,
  364. "timelapse": item.timelapse,
  365. "use_ams": item.use_ams,
  366. "nozzle_offset_cali": item.nozzle_offset_cali,
  367. "preheat_override": item.preheat_override,
  368. "preheat_chamber_target_override": item.preheat_chamber_target_override,
  369. "status": item.status,
  370. "started_at": item.started_at,
  371. "completed_at": item.completed_at,
  372. "error_message": item.error_message,
  373. "created_at": item.created_at,
  374. # User tracking (Issue #206)
  375. "created_by_id": item.created_by_id,
  376. "created_by_username": item.created_by.username if item.created_by else None,
  377. # Batch grouping
  378. "batch_id": item.batch_id,
  379. "batch_name": item.batch.name if item.batch else None,
  380. # SJF scheduling
  381. "been_jumped": item.been_jumped,
  382. # Auto-print G-code injection
  383. "gcode_injection": item.gcode_injection,
  384. # H2C rack-swap nozzle pick (#1780)
  385. "nozzle_mapping": nozzle_mapping_parsed,
  386. "nozzle_rack_choice": nozzle_rack_choice_parsed,
  387. "nozzles_info": nozzles_info_parsed,
  388. "cleanup_library_after_dispatch": item.cleanup_library_after_dispatch,
  389. # Cross-model alternatives (#671). Guarded rather than read directly:
  390. # every route that reaches here eager-loads the relationship, but a
  391. # caller that forgets would trigger a lazy load, and a lazy load on an
  392. # async session raises rather than degrading. An empty list is the
  393. # correct answer for the ordinary item this would most likely be.
  394. "variants": _variant_summaries(item),
  395. }
  396. response = PrintQueueItemResponse(**item_dict)
  397. if item.archive:
  398. # Soft-deleted archive: files are gone from disk but the row stays
  399. # (its filament/cost contribution still flows into stats per #1343).
  400. # Suppress the archive-derived UI surface so the queue page doesn't
  401. # 404-storm the thumbnail / plates / plate-thumbnail endpoints — the
  402. # frontend's existing truthy gate on archive_thumbnail covers it
  403. # (#1348 follow-up). The archive_deleted flag lets the UI render a
  404. # "source deleted" badge on these rows.
  405. if item.archive.deleted_at is not None:
  406. response.archive_deleted = True
  407. else:
  408. response.archive_name = item.archive.print_name or item.archive.filename
  409. response.archive_thumbnail = item.archive.thumbnail_path
  410. response.print_time_seconds = item.archive.print_time_seconds
  411. response.filament_used_grams = item.archive.filament_used_grams
  412. response.filament_type = item.archive.filament_type
  413. response.filament_color = item.archive.filament_color
  414. response.layer_height = item.archive.layer_height
  415. response.nozzle_diameter = item.archive.nozzle_diameter
  416. response.sliced_for_model = item.archive.sliced_for_model
  417. response.bed_type = item.archive.bed_type
  418. # Marks history/reprint rows whose archive carries the slicer's own
  419. # live-resolved AMS-slot pick (extra_data.slicer_ams_mapping) — see
  420. # `_extract_slicer_ams_mapping_json` in virtual_printer/manager.py.
  421. #
  422. # Only when the saved mapping was resolved against *this* row's
  423. # printer: a global tray ID means nothing on another printer, so
  424. # that's the exact condition under which the mapping is reused. A
  425. # badge on a row where nothing gets reused would be a lie (#2700
  426. # review). Model-based rows (printer_id None) never match, which is
  427. # correct — the mapping is not reused there either.
  428. extra = item.archive.extra_data if isinstance(item.archive.extra_data, dict) else {}
  429. saved_mapping = extra.get("slicer_ams_mapping")
  430. response.archive_has_slicer_ams_mapping = (
  431. isinstance(saved_mapping, dict)
  432. and isinstance(saved_mapping.get("mapping"), list)
  433. and item.printer_id is not None
  434. and saved_mapping.get("printer_id") == item.printer_id
  435. )
  436. if item.plate_id:
  437. archive_path = settings.base_dir / item.archive.file_path
  438. if archive_path.exists():
  439. # One cached parse for all three per-plate overrides (#2573).
  440. plate_meta = extract_plate_metadata_from_3mf(archive_path, item.plate_id)
  441. if plate_meta.print_time_seconds is not None:
  442. response.print_time_seconds = plate_meta.print_time_seconds
  443. if plate_meta.filament_used_grams > 0:
  444. response.filament_used_grams = plate_meta.filament_used_grams
  445. if plate_meta.bed_type:
  446. response.bed_type = plate_meta.bed_type
  447. if item.library_file:
  448. response.library_file_name = (
  449. item.library_file.file_metadata.get("print_name") if item.library_file.file_metadata else None
  450. )
  451. if not response.library_file_name:
  452. response.library_file_name = item.library_file.filename
  453. response.library_file_thumbnail = item.library_file.thumbnail_path
  454. # Get metadata from library file if no archive
  455. if not item.archive and item.library_file.file_metadata:
  456. response.print_time_seconds = item.library_file.file_metadata.get("print_time_seconds")
  457. response.filament_used_grams = item.library_file.file_metadata.get("filament_used_grams")
  458. response.filament_type = item.library_file.file_metadata.get("filament_type")
  459. response.filament_color = item.library_file.file_metadata.get("filament_color")
  460. response.layer_height = item.library_file.file_metadata.get("layer_height")
  461. response.nozzle_diameter = item.library_file.file_metadata.get("nozzle_diameter")
  462. response.sliced_for_model = item.library_file.file_metadata.get("sliced_for_model")
  463. response.bed_type = item.library_file.file_metadata.get("bed_type")
  464. if item.plate_id:
  465. lib_path = Path(item.library_file.file_path)
  466. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / item.library_file.file_path
  467. if library_file_path.exists():
  468. # One cached parse for all three per-plate overrides (#2573).
  469. plate_meta = extract_plate_metadata_from_3mf(library_file_path, item.plate_id)
  470. if plate_meta.print_time_seconds is not None:
  471. response.print_time_seconds = plate_meta.print_time_seconds
  472. if plate_meta.filament_used_grams > 0:
  473. response.filament_used_grams = plate_meta.filament_used_grams
  474. if plate_meta.bed_type:
  475. response.bed_type = plate_meta.bed_type
  476. if item.printer:
  477. response.printer_name = item.printer.name
  478. return response
  479. @router.get("/", response_model=list[PrintQueueItemResponse])
  480. async def list_queue(
  481. printer_id: int | None = Query(None, description="Filter by printer (-1 for unassigned)"),
  482. status: str | None = Query(None, description="Filter by status"),
  483. target_model: str | None = Query(
  484. None, description="Filter by target model (also includes model-based items when combined with printer_id)"
  485. ),
  486. db: AsyncSession = Depends(get_db),
  487. auth_result: tuple[User | None, bool] = Depends(
  488. require_ownership_permission(
  489. Permission.QUEUE_READ_ALL,
  490. Permission.QUEUE_READ_OWN,
  491. )
  492. ),
  493. ):
  494. """List all queue items, optionally filtered by printer or status."""
  495. user, can_read_all = auth_result
  496. query = (
  497. select(PrintQueueItem)
  498. .options(
  499. selectinload(PrintQueueItem.archive),
  500. selectinload(PrintQueueItem.printer),
  501. selectinload(PrintQueueItem.library_file),
  502. selectinload(PrintQueueItem.created_by),
  503. selectinload(PrintQueueItem.batch),
  504. # Cross-model candidates (#671) and their files, for the card label.
  505. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  506. )
  507. .order_by(PrintQueueItem.printer_id.nulls_first(), PrintQueueItem.position)
  508. )
  509. if user is not None and not can_read_all:
  510. query = query.where(PrintQueueItem.created_by_id == user.id)
  511. if printer_id is not None:
  512. if printer_id == -1:
  513. # Special value: filter for unassigned items
  514. query = query.where(PrintQueueItem.printer_id.is_(None))
  515. else:
  516. # Resolve effective model: prefer explicit param, fall back to printer's DB model.
  517. # This ensures model-based "Any X" items are returned even when the frontend
  518. # doesn't send target_model (e.g. printer.model is NULL on the client side).
  519. effective_model = target_model
  520. if not effective_model:
  521. printer_row = (
  522. await db.execute(select(Printer.model).where(Printer.id == printer_id))
  523. ).scalar_one_or_none()
  524. effective_model = printer_row
  525. if effective_model:
  526. # Include both printer-specific items AND model-based (unassigned) items
  527. query = query.where(
  528. or_(
  529. PrintQueueItem.printer_id == printer_id,
  530. and_(
  531. PrintQueueItem.printer_id.is_(None),
  532. func.lower(PrintQueueItem.target_model) == effective_model.lower(),
  533. ),
  534. )
  535. )
  536. else:
  537. query = query.where(PrintQueueItem.printer_id == printer_id)
  538. elif target_model:
  539. query = query.where(func.lower(PrintQueueItem.target_model) == target_model.lower())
  540. if status:
  541. query = query.where(PrintQueueItem.status == status)
  542. result = await db.execute(query)
  543. items = result.scalars().all()
  544. return [_enrich_response(item) for item in items]
  545. async def _resolve_queue_variants(
  546. db: AsyncSession,
  547. specs: list[QueueVariantCreate],
  548. current_user: User | None,
  549. ) -> list[tuple[QueueVariantCreate, LibraryFile, str]]:
  550. """Validate a cross-model candidate set and pair each file with its model (#671).
  551. Validated as a set, not file by file, because the failure modes are about the
  552. set: two candidates for the same printer give the resolver no basis to choose,
  553. and a set where nothing can ever run is a job that waits forever.
  554. At least one candidate must have an active printer — the rest may not, which
  555. is deliberate. Grouping the H2C slice before the H2C arrives is a reasonable
  556. thing to do, and refusing the whole queue action over it would be worse than
  557. letting that candidate simply never match.
  558. """
  559. file_ids = [s.library_file_id for s in specs]
  560. if len(set(file_ids)) != len(file_ids):
  561. raise HTTPException(400, "The same file cannot be listed twice as a variant")
  562. rows = (await db.execute(LibraryFile.active().where(LibraryFile.id.in_(file_ids)))).scalars().all()
  563. by_id = {f.id: f for f in rows}
  564. resolved: list[tuple[QueueVariantCreate, LibraryFile, str]] = []
  565. seen_models: dict[str, str] = {}
  566. any_active_printer = False
  567. for spec in specs:
  568. library_file = by_id.get(spec.library_file_id)
  569. # Same IDOR posture as the single-file path: a file the caller cannot read
  570. # is reported as missing rather than forbidden.
  571. if not library_file or (
  572. current_user
  573. and not current_user.has_permission(Permission.LIBRARY_READ_ALL.value)
  574. and library_file.created_by_id != current_user.id
  575. ):
  576. raise HTTPException(404, f"Library file not found: {spec.library_file_id}")
  577. from backend.app.utils.filename import InvalidFilenameError, validate_print_filename
  578. try:
  579. validate_print_filename(library_file.filename)
  580. except InvalidFilenameError as e:
  581. raise HTTPException(400, str(e)) from e
  582. model = resolve_variant_model(library_file, spec.target_model)
  583. if not model:
  584. raise HTTPException(
  585. 400,
  586. f"{library_file.filename} does not say which printer it was sliced for — "
  587. "set its target model explicitly",
  588. )
  589. # Cross-model safety gate (#2578), per candidate. A set is only as safe as
  590. # its worst member, and model-based dispatch has no human in the loop.
  591. sliced_for = (library_file.file_metadata or {}).get("sliced_for_model")
  592. if not is_gcode_compatible(sliced_for, model):
  593. raise HTTPException(
  594. 400,
  595. f"{library_file.filename} was sliced for {sliced_for} and cannot be dispatched to {model} printers",
  596. )
  597. if model in seen_models:
  598. raise HTTPException(
  599. 400,
  600. f"{library_file.filename} and {seen_models[model]} are both for {model} — "
  601. "variants must target different printers",
  602. )
  603. seen_models[model] = library_file.filename
  604. has_printer = (
  605. (
  606. await db.execute(
  607. select(Printer).where(Printer.model == model).where(Printer.is_active == True) # noqa: E712
  608. )
  609. )
  610. .scalars()
  611. .first()
  612. )
  613. any_active_printer = any_active_printer or bool(has_printer)
  614. resolved.append((spec, library_file, model))
  615. if not any_active_printer:
  616. raise HTTPException(400, f"No active printers for any of: {', '.join(seen_models)}")
  617. return resolved
  618. def _variant_values(
  619. spec: QueueVariantCreate,
  620. library_file: LibraryFile,
  621. model: str,
  622. position: int,
  623. ) -> dict:
  624. """Column values for one candidate, extracted from its own 3MF.
  625. Each candidate is a different slice, so its filament requirements and print
  626. time come from its own file rather than being inherited from the item.
  627. Returns values rather than a row so a quantity>1 batch can build one row per
  628. copy without re-opening the 3MF for each.
  629. """
  630. lib_path = Path(library_file.file_path)
  631. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  632. required_types = None
  633. filament_overrides_json = None
  634. print_time = (library_file.file_metadata or {}).get("print_time_seconds")
  635. if file_path.exists():
  636. types = _extract_filament_types_from_3mf(file_path, spec.plate_id)
  637. if types:
  638. required_types = json.dumps(types)
  639. if spec.plate_id:
  640. plate_time = _extract_print_time_from_3mf(file_path, spec.plate_id)
  641. if plate_time is not None:
  642. print_time = plate_time
  643. if spec.filament_overrides:
  644. plate_overrides = overrides_for_plate(spec.filament_overrides, file_path, spec.plate_id)
  645. if plate_overrides:
  646. filament_overrides_json = json.dumps(plate_overrides)
  647. override_types = sorted({o["type"] for o in plate_overrides if "type" in o})
  648. if override_types:
  649. existing = set(json.loads(required_types)) if required_types else set()
  650. required_types = json.dumps(sorted(existing | set(override_types)))
  651. return {
  652. "position": position,
  653. "library_file_id": library_file.id,
  654. "target_model": model,
  655. "plate_id": spec.plate_id,
  656. "ams_mapping": json.dumps(spec.ams_mapping) if spec.ams_mapping else None,
  657. "nozzle_mapping": json.dumps(spec.nozzle_mapping) if spec.nozzle_mapping else None,
  658. "nozzle_rack_choice": json.dumps(spec.nozzle_rack_choice) if spec.nozzle_rack_choice else None,
  659. "filament_overrides": filament_overrides_json,
  660. "required_filament_types": required_types,
  661. "print_time_seconds": print_time,
  662. }
  663. @router.post("/", response_model=PrintQueueItemResponse)
  664. async def add_to_queue(
  665. data: PrintQueueItemCreate,
  666. db: AsyncSession = Depends(get_db),
  667. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  668. ):
  669. """Add an item to the print queue."""
  670. # Normalize target_model (e.g., "Bambu Lab X1E" / "C13" -> "X1E").
  671. # normalize_model_name resolves internal codes first: the previous
  672. # `normalize_printer_model(x) or normalize_printer_model_id(x)` chain never
  673. # reached the code map, because the first call returns unknown input
  674. # unchanged — so a "C13" target stayed "C13", matched no printer row and
  675. # left the item waiting forever. Identical result for every other spelling.
  676. target_model_norm = normalize_model_name(data.target_model)
  677. # Cross-model alternatives (#671): several sliced files, whichever printer
  678. # frees up first. The whole candidate set is validated before anything is
  679. # written — a half-valid set would produce a job that can only reach some of
  680. # the printers the user asked for, with nothing to say which.
  681. variant_specs: list[tuple[QueueVariantCreate, LibraryFile, str]] = []
  682. if data.variants:
  683. if data.printer_id:
  684. raise HTTPException(
  685. 400, "Cannot specify both printer_id and variants — pick a printer or offer alternatives"
  686. )
  687. if data.archive_id or data.library_file_id:
  688. raise HTTPException(
  689. 400, "Cannot combine variants with archive_id or library_file_id — the variants are the files"
  690. )
  691. variant_specs = await _resolve_queue_variants(db, data.variants, current_user)
  692. # Mirror the first candidate onto the item so the queue listing, the SJF
  693. # grouping and the "Any H2S" label have something before a printer is
  694. # picked. Resolution overwrites it with whichever candidate actually runs.
  695. target_model_norm = variant_specs[0][2]
  696. # Validate that either archive_id or library_file_id is provided.
  697. # A cross-model item deliberately holds neither: its files live on the
  698. # variant rows. Pointing library_file_id at one of them would be worse than
  699. # useless — that FK is ON DELETE CASCADE, so deleting a single alternative
  700. # would take the whole queue item with it.
  701. if not data.archive_id and not data.library_file_id and not data.variants:
  702. raise HTTPException(400, "Either archive_id or library_file_id must be provided")
  703. # Cannot specify both printer_id and target_model
  704. if data.printer_id and target_model_norm:
  705. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  706. # Validate printer exists (if assigned)
  707. if data.printer_id is not None:
  708. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  709. if not result.scalar_one_or_none():
  710. raise HTTPException(400, "Printer not found")
  711. # Validate target_model has active printers. Skipped for cross-model items:
  712. # target_model there is just the first candidate, and _resolve_queue_variants
  713. # has already required that *some* candidate has a printer.
  714. if target_model_norm and not data.variants:
  715. result = await db.execute(
  716. select(Printer).where(Printer.model == target_model_norm).where(Printer.is_active == True) # noqa: E712
  717. )
  718. if not result.scalars().first():
  719. raise HTTPException(400, f"No active printers for model: {target_model_norm}")
  720. # Validate archive exists (if provided) and get it for filament extraction
  721. archive = None
  722. if data.archive_id:
  723. result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  724. archive = result.scalar_one_or_none()
  725. if not archive:
  726. raise HTTPException(400, "Archive not found")
  727. _assert_can_queue_archive(archive, current_user)
  728. # Validate library file exists (if provided) and get it for filament extraction
  729. library_file = None
  730. if data.library_file_id:
  731. result = await db.execute(LibraryFile.active().where(LibraryFile.id == data.library_file_id))
  732. library_file = result.scalar_one_or_none()
  733. if not library_file:
  734. raise HTTPException(400, "Library file not found")
  735. _assert_can_queue_library_file(library_file, current_user)
  736. # Bambu SD card is FAT32/exFAT — illegal filename chars would 553 at
  737. # FTP upload time (#1540). Reject at queue time so the user gets the
  738. # actionable error before waiting in queue.
  739. from backend.app.utils.filename import InvalidFilenameError, validate_print_filename
  740. try:
  741. validate_print_filename(library_file.filename)
  742. except InvalidFilenameError as e:
  743. raise HTTPException(400, str(e)) from e
  744. # Cross-model safety gate (#2578): a G-code 3MF sliced for one model must
  745. # not be queued for dispatch to an incompatible model. The UI can no longer
  746. # produce such rows, but API-created rows must be rejected here too — the
  747. # scheduler assigns model-based items to hardware with no human in the loop.
  748. if target_model_norm:
  749. sliced_for = None
  750. if archive:
  751. sliced_for = archive.sliced_for_model
  752. elif library_file and library_file.file_metadata:
  753. sliced_for = library_file.file_metadata.get("sliced_for_model")
  754. if not is_gcode_compatible(sliced_for, target_model_norm):
  755. raise HTTPException(
  756. 400,
  757. f"File was sliced for {sliced_for} and cannot be dispatched to {target_model_norm} printers",
  758. )
  759. # Extract filament types for model-based assignment (used by scheduler for validation)
  760. required_filament_types = None
  761. file_path = None
  762. if target_model_norm:
  763. # Get file path from archive or library file
  764. if archive:
  765. file_path = settings.base_dir / archive.file_path
  766. elif library_file:
  767. lib_path = Path(library_file.file_path)
  768. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  769. if file_path and file_path.exists():
  770. filament_types = _extract_filament_types_from_3mf(file_path, data.plate_id)
  771. if filament_types:
  772. required_filament_types = json.dumps(filament_types)
  773. logger.info("Extracted filament types for model-based queue: %s", filament_types)
  774. # If filament overrides are provided, update required_filament_types to match override types
  775. filament_overrides_json = None
  776. if data.filament_overrides and target_model_norm:
  777. plate_overrides = overrides_for_plate(data.filament_overrides, file_path, data.plate_id)
  778. if plate_overrides:
  779. filament_overrides_json = json.dumps(plate_overrides)
  780. # Update required_filament_types from overrides so scheduler validates against overridden types
  781. override_types = sorted({o["type"] for o in plate_overrides if "type" in o})
  782. if override_types:
  783. # Merge with existing types (overrides may only cover some slots)
  784. existing_types = set(json.loads(required_filament_types)) if required_filament_types else set()
  785. # Replace types for overridden slots, keep others
  786. all_types = existing_types | set(override_types)
  787. required_filament_types = json.dumps(sorted(all_types))
  788. # Validate quantity
  789. quantity = max(1, data.quantity)
  790. # Validate batch_id if provided. Client passes batch_id when adding items
  791. # into a pre-created batch (multi-plate auto-batch or "Group as batch" flow).
  792. # 404 keeps the existing-id leak surface low.
  793. batch = None
  794. batch_id = None
  795. if data.batch_id is not None:
  796. result = await db.execute(select(PrintBatch).where(PrintBatch.id == data.batch_id))
  797. existing_batch = result.scalar_one_or_none()
  798. if not existing_batch:
  799. raise HTTPException(404, "Batch not found")
  800. if existing_batch.status != "active":
  801. raise HTTPException(400, "Cannot add items to a non-active batch")
  802. if (
  803. current_user is not None
  804. and existing_batch.created_by_id is not None
  805. and existing_batch.created_by_id != current_user.id
  806. and not current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  807. ):
  808. raise HTTPException(404, "Batch not found")
  809. batch = existing_batch
  810. batch_id = existing_batch.id
  811. # Create batch if quantity > 1 and no batch_id provided
  812. if batch_id is None and quantity > 1:
  813. # Derive batch name from source file
  814. batch_name_base = "Batch"
  815. if archive:
  816. batch_name_base = archive.print_name or archive.filename or "Batch"
  817. elif library_file:
  818. if library_file.file_metadata:
  819. batch_name_base = library_file.file_metadata.get("print_name") or library_file.filename
  820. else:
  821. batch_name_base = library_file.filename
  822. batch_name_base = batch_name_base.replace(".gcode.3mf", "").replace(".3mf", "")
  823. batch = PrintBatch(
  824. name=f"{batch_name_base} ×{quantity}",
  825. archive_id=data.archive_id,
  826. library_file_id=data.library_file_id,
  827. quantity=quantity,
  828. status="active",
  829. created_by_id=current_user.id if current_user else None,
  830. )
  831. db.add(batch)
  832. await db.flush() # Get batch.id before creating items
  833. batch_id = batch.id
  834. # Get queue scope for this printer (or for unassigned/model-based items).
  835. if data.printer_id is not None:
  836. queue_scope = (
  837. PrintQueueItem.printer_id == data.printer_id,
  838. PrintQueueItem.status == "pending",
  839. )
  840. else:
  841. # For unassigned/model-based items, scope across all unassigned.
  842. queue_scope = (
  843. PrintQueueItem.printer_id.is_(None),
  844. PrintQueueItem.status == "pending",
  845. )
  846. # Serialize concurrent queue inserts to the same scope (#1625-followup).
  847. # The race: two concurrent ASAP inserts both compute MAX(position) before
  848. # either commits; in an empty scope, both INSERT at position 1 (duplicate).
  849. # In a non-empty scope, Postgres's row-level locks on the UPDATE shift
  850. # serialize naturally, but the empty-scope path has no rows to lock.
  851. # A transaction-scoped advisory lock keyed on the printer_id closes that
  852. # window; the lock is released automatically at commit/rollback. Different
  853. # printers don't contend. SQLite serializes writes implicitly so this is a
  854. # no-op there.
  855. #
  856. # Dialect is checked against the actual session binding, NOT the
  857. # `is_sqlite()` helper, because the test fixture overrides `get_db` with a
  858. # SQLite engine while `settings.database_url` still points at Postgres
  859. # (the helper reads settings). Inspecting the connection directly is the
  860. # right shape for any code that mutates SQL based on the live dialect.
  861. from sqlalchemy import text
  862. bind = db.get_bind()
  863. if bind.dialect.name == "postgresql":
  864. scope_key = data.printer_id if data.printer_id is not None else 0
  865. # 1625 namespaces the lock so it can't collide with other advisory
  866. # locks elsewhere in the codebase.
  867. await db.execute(text("SELECT pg_advisory_xact_lock(1625, :k)"), {"k": scope_key})
  868. insert_position = max(1, data.insert_position or 1)
  869. if data.insert_at_top or data.insert_position is not None:
  870. result = await db.execute(select(func.max(PrintQueueItem.position)).where(*queue_scope))
  871. max_pos = result.scalar() or 0
  872. insert_position = min(insert_position, max_pos + 1)
  873. await db.execute(
  874. update(PrintQueueItem)
  875. .where(*queue_scope)
  876. .where(PrintQueueItem.position >= insert_position)
  877. .values(position=PrintQueueItem.position + quantity)
  878. )
  879. start_position = insert_position
  880. else:
  881. result = await db.execute(select(func.max(PrintQueueItem.position)).where(*queue_scope))
  882. max_pos = result.scalar() or 0
  883. start_position = max_pos + 1
  884. # Resolve print_time_seconds for SJF scheduling (cache on item at creation)
  885. cached_print_time = None
  886. if archive:
  887. cached_print_time = archive.print_time_seconds
  888. if data.plate_id:
  889. archive_path = settings.base_dir / archive.file_path
  890. if archive_path.exists():
  891. plate_time = _extract_print_time_from_3mf(archive_path, data.plate_id)
  892. if plate_time is not None:
  893. cached_print_time = plate_time
  894. elif library_file:
  895. if library_file.file_metadata:
  896. cached_print_time = library_file.file_metadata.get("print_time_seconds")
  897. if data.plate_id:
  898. lib_path = Path(library_file.file_path)
  899. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  900. if library_file_path.exists():
  901. plate_time = _extract_print_time_from_3mf(library_file_path, data.plate_id)
  902. if plate_time is not None:
  903. cached_print_time = plate_time
  904. # Validate project exists before insert so a bogus ID yields 404, not an FK-constraint 500
  905. if data.project_id is not None:
  906. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  907. if not project_result.scalar_one_or_none():
  908. raise HTTPException(status_code=404, detail="Project not found")
  909. # Security boundary: the browser's estimated_cost is only a display hint.
  910. # Budget enforcement and the persisted reservation value must be derived
  911. # from the server-owned archive/library metadata and spool assignments.
  912. if variant_specs:
  913. variant_costs = [
  914. await estimate_queue_source_cost(
  915. db,
  916. library_file=variant_file,
  917. plate_id=spec.plate_id,
  918. ams_mapping=spec.ams_mapping,
  919. printer_id=data.printer_id,
  920. )
  921. for spec, variant_file, _model in variant_specs
  922. ]
  923. trusted_estimated_cost = (
  924. max(cost for cost in variant_costs if cost is not None)
  925. if variant_costs and all(cost is not None for cost in variant_costs)
  926. else None
  927. )
  928. else:
  929. trusted_estimated_cost = await estimate_queue_source_cost(
  930. db,
  931. archive=archive,
  932. library_file=library_file,
  933. plate_id=data.plate_id,
  934. ams_mapping=data.ams_mapping,
  935. printer_id=data.printer_id,
  936. )
  937. await validate_print_budget(
  938. db,
  939. cost_center_id=data.cost_center_id,
  940. estimated_cost=trusted_estimated_cost,
  941. current_user=current_user,
  942. quantity=quantity,
  943. )
  944. ams_mapping_json = json.dumps(data.ams_mapping) if data.ams_mapping else None
  945. # Same Text-as-JSON convention for the rack-position pick (#1784).
  946. nozzle_rack_choice_json = json.dumps(data.nozzle_rack_choice) if data.nozzle_rack_choice else None
  947. # Reprint fallback: the caller didn't specify an explicit ams_mapping (no
  948. # per-slot filament-mapping edit was made), but the archive carries the
  949. # slicer's own live-resolved AMS-slot pick from the original print (see
  950. # `extra_data.slicer_ams_mapping`, written by the VP-queue path via
  951. # `_extract_slicer_ams_mapping_json`). Reuse it so the reprint dispatches
  952. # to the exact same physical spool instead of the scheduler re-deriving a
  953. # (possibly ambiguous) mapping from just the file's static type/color.
  954. #
  955. # Global tray IDs only mean something relative to the specific printer
  956. # they were resolved against, so this only fires when the reprint targets
  957. # that exact printer (`extra_data.slicer_ams_mapping.printer_id`) — never
  958. # for a model-based dispatch (data.printer_id is None) or a reprint aimed
  959. # at a different printer, where the same tray number can hold a
  960. # completely different spool (#2700 review).
  961. #
  962. # It also stands down when the request carries force-color-match overrides:
  963. # those are the caller asking the scheduler to match strictly against the
  964. # printer's live trays, and they are only ever applied inside
  965. # `_compute_ams_mapping_for_printer` — the function a stored mapping makes
  966. # the scheduler skip. Same precedence as the VP-side toggle pair (#2700
  967. # review).
  968. #
  969. # Note this is otherwise unconditional — it applies regardless of whether
  970. # the physical spool in that slot has changed since the original print.
  971. # #1308 covers re-verifying a stored mapping against live AMS state at
  972. # dispatch time; that check is a separate PR and, once merged, will also
  973. # catch a stale slot inherited through this fallback.
  974. wants_live_color_match = any(
  975. isinstance(o, dict) and o.get("force_color_match") for o in (data.filament_overrides or [])
  976. )
  977. if (
  978. ams_mapping_json is None
  979. and not wants_live_color_match
  980. and archive
  981. and archive.extra_data
  982. and data.printer_id is not None
  983. ):
  984. saved = archive.extra_data.get("slicer_ams_mapping")
  985. if (
  986. isinstance(saved, dict)
  987. and saved.get("printer_id") == data.printer_id
  988. and isinstance(saved.get("mapping"), list)
  989. and saved["mapping"]
  990. ):
  991. ams_mapping_json = json.dumps(saved["mapping"])
  992. items = []
  993. for i in range(quantity):
  994. item = PrintQueueItem(
  995. printer_id=data.printer_id,
  996. target_model=target_model_norm,
  997. target_location=data.target_location,
  998. required_filament_types=required_filament_types,
  999. filament_overrides=filament_overrides_json,
  1000. archive_id=data.archive_id,
  1001. library_file_id=data.library_file_id,
  1002. cost_center_id=data.cost_center_id,
  1003. estimated_cost=trusted_estimated_cost,
  1004. scheduled_time=data.scheduled_time,
  1005. require_previous_success=data.require_previous_success,
  1006. auto_off_after=data.auto_off_after,
  1007. manual_start=data.manual_start,
  1008. skip_filament_check=data.skip_filament_check,
  1009. ams_mapping=ams_mapping_json,
  1010. nozzle_rack_choice=nozzle_rack_choice_json,
  1011. plate_id=data.plate_id,
  1012. bed_levelling=data.bed_levelling,
  1013. flow_cali=data.flow_cali,
  1014. vibration_cali=data.vibration_cali,
  1015. layer_inspect=data.layer_inspect,
  1016. timelapse=data.timelapse,
  1017. use_ams=data.use_ams,
  1018. nozzle_offset_cali=data.nozzle_offset_cali,
  1019. preheat_override=data.preheat_override,
  1020. preheat_chamber_target_override=data.preheat_chamber_target_override,
  1021. gcode_injection=data.gcode_injection,
  1022. cleanup_library_after_dispatch=data.cleanup_library_after_dispatch,
  1023. project_id=data.project_id,
  1024. position=start_position + i,
  1025. status="pending",
  1026. created_by_id=current_user.id if current_user else None,
  1027. batch_id=batch_id,
  1028. print_time_seconds=cached_print_time,
  1029. )
  1030. db.add(item)
  1031. items.append(item)
  1032. if variant_specs:
  1033. variant_values = [
  1034. _variant_values(spec, library_file, model, position)
  1035. for position, (spec, library_file, model) in enumerate(variant_specs)
  1036. ]
  1037. # SJF orders pending items before any printer is known, so the row carries
  1038. # the shortest candidate's estimate. Resolution replaces it with the one
  1039. # that actually runs.
  1040. estimates = [v["print_time_seconds"] for v in variant_values if v["print_time_seconds"]]
  1041. for item in items:
  1042. # Each copy in a quantity>1 batch gets its own candidate rows —
  1043. # attempt counts are per-item, and two copies must be free to land on
  1044. # different printers.
  1045. item.variants.extend(PrintQueueVariant(**values) for values in variant_values)
  1046. item.print_time_seconds = min(estimates) if estimates else None
  1047. await db.commit()
  1048. # Refresh the first item for the response
  1049. item = items[0]
  1050. await db.refresh(item)
  1051. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  1052. source_name = f"archive {data.archive_id}" if data.archive_id else f"library file {data.library_file_id}"
  1053. target_desc = data.printer_id or (f"model {target_model_norm}" if target_model_norm else "unassigned")
  1054. qty_desc = f" (×{quantity})" if quantity > 1 else ""
  1055. logger.info("Added %s to queue for %s%s", source_name, target_desc, qty_desc)
  1056. # MQTT relay - publish queue job added
  1057. try:
  1058. from backend.app.services.mqtt_relay import mqtt_relay
  1059. await mqtt_relay.on_queue_job_added(
  1060. job_id=item.id,
  1061. filename=item.archive.filename if item.archive else "",
  1062. printer_id=item.printer_id,
  1063. printer_name=item.printer.name if item.printer else None,
  1064. )
  1065. except Exception:
  1066. pass # Don't fail queue add if MQTT fails
  1067. # Send notification for job added
  1068. try:
  1069. job_name = (
  1070. item.archive.filename
  1071. if item.archive
  1072. else item.library_file.filename
  1073. if item.library_file
  1074. else f"Job #{item.id}"
  1075. )
  1076. job_name = job_name.replace(".gcode.3mf", "").replace(".3mf", "")
  1077. if quantity > 1:
  1078. job_name = f"{job_name} ×{quantity}"
  1079. target = (
  1080. item.printer.name if item.printer else (f"Any {item.target_model}" if target_model_norm else "Unassigned")
  1081. )
  1082. await notification_service.on_queue_job_added(
  1083. job_name=job_name,
  1084. target=target,
  1085. db=db,
  1086. printer_id=item.printer_id,
  1087. printer_name=item.printer.name if item.printer else None,
  1088. )
  1089. except Exception:
  1090. pass # Don't fail queue add if notification fails
  1091. return _enrich_response(item)
  1092. @router.patch("/bulk", response_model=PrintQueueBulkUpdateResponse)
  1093. async def bulk_update_queue_items(
  1094. data: PrintQueueBulkUpdate,
  1095. db: AsyncSession = Depends(get_db),
  1096. auth_result: tuple[User | None, bool] = Depends(
  1097. require_ownership_permission(
  1098. Permission.QUEUE_UPDATE_ALL,
  1099. Permission.QUEUE_UPDATE_OWN,
  1100. )
  1101. ),
  1102. ):
  1103. """Bulk update multiple queue items with the same values.
  1104. Only pending items can be updated. Non-pending items are skipped.
  1105. Items not owned by the user are also skipped (unless user has *_all permission).
  1106. """
  1107. user, can_modify_all = auth_result
  1108. if not data.item_ids:
  1109. raise HTTPException(400, "No item IDs provided")
  1110. # Get fields to update (exclude item_ids and unset fields)
  1111. update_data = data.model_dump(exclude={"item_ids"}, exclude_unset=True)
  1112. if not update_data:
  1113. raise HTTPException(400, "No fields to update")
  1114. # Validate printer_id if being changed
  1115. if "printer_id" in update_data and update_data["printer_id"] is not None:
  1116. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  1117. if not result.scalar_one_or_none():
  1118. raise HTTPException(400, "Printer not found")
  1119. # Fetch all items
  1120. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  1121. items = result.scalars().all()
  1122. updated_count = 0
  1123. skipped_count = 0
  1124. validates_billing_fields = "cost_center_id" in update_data or "estimated_cost" in update_data
  1125. for item in items:
  1126. # Skip non-pending rows and rows a dispatch worker has claimed (#2615) —
  1127. # editing a claimed row mid-upload would split it from the in-flight
  1128. # dispatch, so it's excluded from the bulk change (cancel to move it).
  1129. if item.status != "pending" or item.dispatching_at is not None:
  1130. skipped_count += 1
  1131. continue
  1132. # Ownership check
  1133. if not can_modify_all and item.created_by_id != user.id:
  1134. skipped_count += 1
  1135. continue
  1136. item_update_data = update_data.copy()
  1137. if validates_billing_fields:
  1138. trusted_estimated_cost = await _trusted_item_estimated_cost(
  1139. db,
  1140. item,
  1141. printer_id=item_update_data.get("printer_id", item.printer_id),
  1142. plate_id=item.plate_id,
  1143. ams_mapping=item.ams_mapping,
  1144. )
  1145. item_update_data["estimated_cost"] = trusted_estimated_cost
  1146. await validate_print_budget(
  1147. db,
  1148. cost_center_id=item_update_data.get("cost_center_id", item.cost_center_id),
  1149. estimated_cost=trusted_estimated_cost,
  1150. current_user=user,
  1151. exclude_queue_item_id=item.id,
  1152. )
  1153. for field, value in item_update_data.items():
  1154. setattr(item, field, value)
  1155. updated_count += 1
  1156. await db.commit()
  1157. logger.info("Bulk updated %s queue items, skipped %s", updated_count, skipped_count)
  1158. return PrintQueueBulkUpdateResponse(
  1159. updated_count=updated_count,
  1160. skipped_count=skipped_count,
  1161. message=f"Updated {updated_count} items"
  1162. + (f", skipped {skipped_count} non-pending/not-owned" if skipped_count else ""),
  1163. )
  1164. # --- Batch endpoints ---
  1165. def _validate_plate_targets(
  1166. plates: list[PrintBatchPlateTarget] | None,
  1167. ) -> list[PrintBatchPlateTarget] | None:
  1168. """Reject duplicate plates and orders that ask for nothing at all.
  1169. A duplicate would violate the (batch_id, plate_id) unique constraint at
  1170. flush time — and on SQLite/PostgreSQL a NULL plate_id slips past that
  1171. constraint entirely, so the check has to happen here to catch two
  1172. "whole file" rows in one order.
  1173. """
  1174. if plates is None:
  1175. return None
  1176. if not plates:
  1177. raise HTTPException(400, "plates must contain at least one plate")
  1178. seen: set[int | None] = set()
  1179. for target in plates:
  1180. if target.plate_id in seen:
  1181. label = target.plate_id if target.plate_id is not None else "whole file"
  1182. raise HTTPException(400, f"Duplicate plate in order: {label}")
  1183. seen.add(target.plate_id)
  1184. if all(target.quantity_target == 0 for target in plates):
  1185. raise HTTPException(400, "Order must request at least one print")
  1186. return plates
  1187. async def _validate_batch_project(db: AsyncSession, project_id: int | None, current_user: User | None) -> None:
  1188. """404 on a bogus project id rather than letting the FK blow up as a 500."""
  1189. if project_id is None:
  1190. return
  1191. result = await db.execute(select(Project).where(Project.id == project_id))
  1192. if not result.scalar_one_or_none():
  1193. raise HTTPException(404, "Project not found")
  1194. async def _load_batch_for_write(
  1195. db: AsyncSession, batch_id: int, current_user: User | None, permission: Permission
  1196. ) -> PrintBatch:
  1197. """Fetch a batch the caller is allowed to modify, or 404.
  1198. 404 rather than 403 on the ownership miss, matching the rest of this
  1199. module: a 403 would confirm the id exists to someone enumerating.
  1200. """
  1201. result = await db.execute(
  1202. select(PrintBatch).options(selectinload(PrintBatch.plates)).where(PrintBatch.id == batch_id)
  1203. )
  1204. batch = result.scalar_one_or_none()
  1205. if not batch:
  1206. raise HTTPException(404, "Batch not found")
  1207. if (
  1208. current_user is not None
  1209. and batch.created_by_id is not None
  1210. and batch.created_by_id != current_user.id
  1211. and not current_user.has_permission(permission.value)
  1212. ):
  1213. raise HTTPException(404, "Batch not found")
  1214. return batch
  1215. @router.post("/batches", response_model=PrintBatchResponse)
  1216. async def create_batch(
  1217. data: PrintBatchCreate,
  1218. db: AsyncSession = Depends(get_db),
  1219. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  1220. ):
  1221. """Create a batch.
  1222. Two modes:
  1223. * ``item_ids`` provided: assign the listed pending queue items to a new
  1224. batch ("Group as batch" UI action).
  1225. * ``item_ids`` omitted/empty: create an empty batch so the client can
  1226. pass the returned ``id`` on subsequent ``POST /queue/`` calls. Used by
  1227. the multi-plate auto-batch flow in PrintModal.
  1228. ``plates`` turns the batch into an order with per-plate targets (#342):
  1229. progress is then measured against what was asked for rather than against
  1230. what happened to be queued, so a failed run still counts as owed. Omitting
  1231. it keeps the pre-#342 behaviour exactly.
  1232. """
  1233. if not data.name or not data.name.strip():
  1234. raise HTTPException(400, "Batch name is required")
  1235. plate_targets = _validate_plate_targets(data.plates)
  1236. await _validate_batch_project(db, data.project_id, current_user)
  1237. batch = PrintBatch(
  1238. name=data.name.strip()[:255],
  1239. archive_id=data.archive_id,
  1240. library_file_id=data.library_file_id,
  1241. quantity=len(data.item_ids) if data.item_ids else 1,
  1242. status="active",
  1243. created_by_id=current_user.id if current_user else None,
  1244. project_id=data.project_id,
  1245. due_date=data.due_date,
  1246. notes=data.notes,
  1247. )
  1248. db.add(batch)
  1249. await db.flush() # Need batch.id before assigning to items
  1250. if plate_targets is not None:
  1251. for target in plate_targets:
  1252. db.add(
  1253. PrintBatchPlate(
  1254. batch_id=batch.id,
  1255. plate_id=target.plate_id,
  1256. plate_name=target.plate_name,
  1257. quantity_target=target.quantity_target,
  1258. sort_order=target.sort_order,
  1259. )
  1260. )
  1261. # The legacy `quantity` column is display-only; keep it meaningful for
  1262. # anything still reading it by making it the order's total.
  1263. batch.quantity = max(1, sum(t.quantity_target for t in plate_targets))
  1264. assigned = 0
  1265. if data.item_ids:
  1266. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  1267. items = result.scalars().all()
  1268. for item in items:
  1269. if item.status != "pending":
  1270. continue
  1271. if item.batch_id is not None:
  1272. continue
  1273. if (
  1274. current_user is not None
  1275. and item.created_by_id != current_user.id
  1276. and not current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  1277. ):
  1278. continue
  1279. item.batch_id = batch.id
  1280. assigned += 1
  1281. batch.quantity = max(assigned, 1)
  1282. await db.commit()
  1283. await db.refresh(batch)
  1284. logger.info("Created batch %s '%s' with %s assigned items", batch.id, batch.name, assigned)
  1285. return await _build_batch_response(db, batch)
  1286. @router.patch("/batches/{batch_id}", response_model=PrintBatchResponse)
  1287. async def update_batch(
  1288. batch_id: int,
  1289. data: PrintBatchUpdate,
  1290. db: AsyncSession = Depends(get_db),
  1291. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_OWN),
  1292. ):
  1293. """Edit an order's header or its per-plate targets while it runs (#342).
  1294. Production requirements change mid-run, so targets are editable. Lowering a
  1295. target below what has already been dispatched is allowed and simply leaves
  1296. ``remaining`` at zero — cancelling the surplus queue items is a separate,
  1297. explicit action, because silently deleting queued work on a number change
  1298. would be a nasty surprise.
  1299. """
  1300. batch = await _load_batch_for_write(db, batch_id, current_user, Permission.QUEUE_UPDATE_ALL)
  1301. plate_targets = _validate_plate_targets(data.plates)
  1302. if data.project_id is not None:
  1303. await _validate_batch_project(db, data.project_id, current_user)
  1304. if data.name is not None:
  1305. if not data.name.strip():
  1306. raise HTTPException(400, "Batch name is required")
  1307. batch.name = data.name.strip()[:255]
  1308. if data.project_id is not None:
  1309. batch.project_id = data.project_id
  1310. if data.due_date is not None:
  1311. batch.due_date = data.due_date
  1312. if data.notes is not None:
  1313. batch.notes = data.notes
  1314. if data.status is not None:
  1315. batch.status = data.status
  1316. if plate_targets is not None:
  1317. existing = {row.plate_id: row for row in batch.plates}
  1318. for target in plate_targets:
  1319. row = existing.pop(target.plate_id, None)
  1320. if row is None:
  1321. db.add(
  1322. PrintBatchPlate(
  1323. batch_id=batch.id,
  1324. plate_id=target.plate_id,
  1325. plate_name=target.plate_name,
  1326. quantity_target=target.quantity_target,
  1327. sort_order=target.sort_order,
  1328. )
  1329. )
  1330. else:
  1331. row.quantity_target = target.quantity_target
  1332. row.sort_order = target.sort_order
  1333. if target.plate_name is not None:
  1334. row.plate_name = target.plate_name
  1335. # Plates absent from the payload are dropped — the list is the order.
  1336. for orphan in existing.values():
  1337. await db.delete(orphan)
  1338. batch.quantity = max(1, sum(t.quantity_target for t in plate_targets))
  1339. await db.flush()
  1340. await db.refresh(batch)
  1341. # Raising a target on a finished order reopens it; lowering one on a
  1342. # running order can complete it.
  1343. await refresh_batch_status(db, batch)
  1344. await db.commit()
  1345. await db.refresh(batch)
  1346. logger.info("Updated batch %s", batch.id)
  1347. return await _build_batch_response(db, batch)
  1348. @router.post("/batches/{batch_id}/dispatch", response_model=PrintBatchResponse)
  1349. async def dispatch_batch(
  1350. batch_id: int,
  1351. data: PrintBatchDispatchRequest,
  1352. db: AsyncSession = Depends(get_db),
  1353. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  1354. ):
  1355. """Queue the runs this order still owes (#342).
  1356. Each new item is cloned from the most recent item for the same plate in
  1357. this batch, so it inherits the printer/model target, AMS mapping, filament
  1358. overrides and print options the user already chose — and the validation
  1359. those went through at creation time.
  1360. """
  1361. batch = await _load_batch_for_write(db, batch_id, current_user, Permission.QUEUE_UPDATE_ALL)
  1362. if batch.status == "cancelled":
  1363. raise HTTPException(400, "Cannot dispatch a cancelled batch")
  1364. # Dispatch starts prints, so it must not be a weaker door than POST /queue/.
  1365. await _assert_can_dispatch_batch_sources(db, batch.id, current_user)
  1366. try:
  1367. created = await dispatch_remaining(
  1368. db,
  1369. batch,
  1370. plate_id=data.plate_id,
  1371. only_plate=data.only_plate,
  1372. limit=data.limit,
  1373. created_by_id=current_user.id if current_user else None,
  1374. )
  1375. except BatchDispatchError as exc:
  1376. raise HTTPException(400, str(exc)) from exc
  1377. await db.commit()
  1378. await db.refresh(batch)
  1379. logger.info("Batch %s dispatched %d item(s)", batch.id, len(created))
  1380. return await _build_batch_response(db, batch)
  1381. @router.post("/batches/{batch_id}/ungroup", response_model=PrintBatchUngroupResponse)
  1382. async def ungroup_batch(
  1383. batch_id: int,
  1384. db: AsyncSession = Depends(get_db),
  1385. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_OWN),
  1386. ):
  1387. """Disband a batch: clear batch_id from all members and delete the batch row.
  1388. Items stay in the queue. Only ungroups items the caller owns (unless they
  1389. hold QUEUE_UPDATE_ALL). A batch with all members ungrouped is deleted.
  1390. """
  1391. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  1392. batch = result.scalar_one_or_none()
  1393. if not batch:
  1394. raise HTTPException(404, "Batch not found")
  1395. can_modify_all = current_user is None or current_user.has_permission(Permission.QUEUE_UPDATE_ALL.value)
  1396. if not can_modify_all and batch.created_by_id != (current_user.id if current_user else None):
  1397. raise HTTPException(404, "Batch not found")
  1398. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.batch_id == batch_id))
  1399. items = result.scalars().all()
  1400. ungrouped = 0
  1401. remaining = 0
  1402. for item in items:
  1403. if not can_modify_all and item.created_by_id != (current_user.id if current_user else None):
  1404. remaining += 1
  1405. continue
  1406. item.batch_id = None
  1407. ungrouped += 1
  1408. # Delete the batch row only when all members were ungrouped — otherwise it
  1409. # still owns the items the caller couldn't touch.
  1410. if remaining == 0:
  1411. await db.delete(batch)
  1412. await db.commit()
  1413. logger.info("Ungrouped batch %s (%s items)", batch_id, ungrouped)
  1414. return PrintBatchUngroupResponse(
  1415. ungrouped_count=ungrouped,
  1416. message=f"Ungrouped {ungrouped} item(s)",
  1417. )
  1418. @router.get("/batches", response_model=list[PrintBatchResponse])
  1419. async def list_batches(
  1420. status: str | None = Query(None, description="Filter by status (active, completed, cancelled)"),
  1421. db: AsyncSession = Depends(get_db),
  1422. auth_result: tuple[User | None, bool] = Depends(
  1423. require_ownership_permission(
  1424. Permission.QUEUE_READ_ALL,
  1425. Permission.QUEUE_READ_OWN,
  1426. )
  1427. ),
  1428. ):
  1429. """List print batches with progress stats.
  1430. Batches with neither queue items nor per-plate targets are omitted. Those
  1431. are empty shells — a grouping whose items were deleted with their source
  1432. archive, or a create that never got as far as adding any — and they carry
  1433. nothing to show, track or dispatch. A brand-new order is still listed
  1434. before its first dispatch, because its targets say what it owes.
  1435. """
  1436. current_user, can_read_all = auth_result
  1437. query = (
  1438. select(PrintBatch)
  1439. .where(
  1440. select(PrintQueueItem.id).where(PrintQueueItem.batch_id == PrintBatch.id).exists()
  1441. | select(PrintBatchPlate.id).where(PrintBatchPlate.batch_id == PrintBatch.id).exists()
  1442. )
  1443. .order_by(PrintBatch.created_at.desc())
  1444. )
  1445. if status:
  1446. query = query.where(PrintBatch.status == status)
  1447. if current_user is not None and not can_read_all:
  1448. query = query.where(PrintBatch.created_by_id == current_user.id)
  1449. result = await db.execute(query)
  1450. batches = result.scalars().all()
  1451. # Resolve creator names in one query rather than one per batch.
  1452. creator_ids = {b.created_by_id for b in batches if b.created_by_id is not None}
  1453. usernames: dict[int, str] = {}
  1454. if creator_ids:
  1455. rows = await db.execute(select(User.id, User.username).where(User.id.in_(creator_ids)))
  1456. usernames = {row[0]: row[1] for row in rows.all()}
  1457. return [await _build_batch_response(db, batch, usernames=usernames) for batch in batches]
  1458. @router.get("/batches/{batch_id}", response_model=PrintBatchResponse)
  1459. async def get_batch(
  1460. batch_id: int,
  1461. db: AsyncSession = Depends(get_db),
  1462. auth_result: tuple[User | None, bool] = Depends(
  1463. require_ownership_permission(
  1464. Permission.QUEUE_READ_ALL,
  1465. Permission.QUEUE_READ_OWN,
  1466. )
  1467. ),
  1468. ):
  1469. """Get a print batch with progress stats."""
  1470. current_user, can_read_all = auth_result
  1471. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  1472. batch = result.scalar_one_or_none()
  1473. if not batch:
  1474. raise HTTPException(404, "Batch not found")
  1475. if (
  1476. current_user is not None
  1477. and not can_read_all
  1478. and (batch.created_by_id is None or batch.created_by_id != current_user.id)
  1479. ):
  1480. raise HTTPException(404, "Batch not found")
  1481. return await _build_batch_response(db, batch)
  1482. @router.delete("/batches/{batch_id}")
  1483. async def cancel_batch(
  1484. batch_id: int,
  1485. db: AsyncSession = Depends(get_db),
  1486. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_DELETE_ALL),
  1487. ):
  1488. """Cancel all pending items in a batch and mark batch as cancelled."""
  1489. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  1490. batch = result.scalar_one_or_none()
  1491. if not batch:
  1492. raise HTTPException(404, "Batch not found")
  1493. # Cancel all pending queue items in this batch
  1494. result = await db.execute(
  1495. select(PrintQueueItem).where(and_(PrintQueueItem.batch_id == batch_id, PrintQueueItem.status == "pending"))
  1496. )
  1497. pending_items = result.scalars().all()
  1498. cancelled_count = 0
  1499. cancelled_ids: list[int] = []
  1500. for item in pending_items:
  1501. item.status = "cancelled"
  1502. await release_budget_reservation(
  1503. db,
  1504. source_type="print_queue",
  1505. source_id=item.id,
  1506. status="released",
  1507. )
  1508. cancelled_ids.append(item.id)
  1509. cancelled_count += 1
  1510. batch.status = "cancelled"
  1511. await db.commit()
  1512. # Same as the single-item path: a dispatch already preheating for one of
  1513. # these cannot see the status change on its own (#2727).
  1514. from backend.app.services.print_scheduler import scheduler as _scheduler
  1515. for _cancelled_id in cancelled_ids:
  1516. _scheduler.notify_dispatch_cancelled(_cancelled_id)
  1517. return {"message": f"Batch cancelled, {cancelled_count} pending items cancelled"}
  1518. async def _build_batch_response(
  1519. db: AsyncSession, batch: PrintBatch, *, usernames: dict[int, str] | None = None
  1520. ) -> PrintBatchResponse:
  1521. """Build a batch response with per-plate progress derived from queue items.
  1522. ``usernames`` lets the list endpoint resolve every creator in one query
  1523. instead of one per batch.
  1524. """
  1525. progress = await load_progress(db, batch)
  1526. created_by_username = None
  1527. if batch.created_by_id:
  1528. if usernames is not None:
  1529. created_by_username = usernames.get(batch.created_by_id)
  1530. else:
  1531. result = await db.execute(select(User).where(User.id == batch.created_by_id))
  1532. user = result.scalar_one_or_none()
  1533. if user:
  1534. created_by_username = user.username
  1535. return PrintBatchResponse(
  1536. id=batch.id,
  1537. name=batch.name,
  1538. archive_id=batch.archive_id,
  1539. library_file_id=batch.library_file_id,
  1540. quantity=batch.quantity,
  1541. status=batch.status,
  1542. created_at=batch.created_at,
  1543. completed_at=batch.completed_at,
  1544. created_by_id=batch.created_by_id,
  1545. created_by_username=created_by_username,
  1546. project_id=batch.project_id,
  1547. due_date=batch.due_date,
  1548. notes=batch.notes,
  1549. pending_count=progress.pending,
  1550. printing_count=progress.printing,
  1551. completed_count=progress.completed,
  1552. failed_count=progress.failed,
  1553. cancelled_count=progress.cancelled,
  1554. skipped_count=progress.skipped,
  1555. has_targets=progress.has_targets,
  1556. target_count=progress.target,
  1557. remaining_count=progress.remaining,
  1558. actual_cost=progress.actual_cost,
  1559. estimated_remaining_cost=progress.estimated_remaining_cost,
  1560. filament_used_grams=progress.filament_used_grams,
  1561. print_time_seconds=progress.print_time_seconds,
  1562. plates=[
  1563. PrintBatchPlateProgress(
  1564. plate_id=plate.plate_id,
  1565. plate_name=plate.plate_name,
  1566. quantity_target=plate.quantity_target,
  1567. dispatched=plate.dispatched,
  1568. remaining=plate.remaining,
  1569. pending_count=plate.pending,
  1570. printing_count=plate.printing,
  1571. completed_count=plate.completed,
  1572. failed_count=plate.failed,
  1573. cancelled_count=plate.cancelled,
  1574. skipped_count=plate.skipped,
  1575. actual_cost=plate.actual_cost,
  1576. estimated_remaining_cost=plate.estimated_remaining_cost,
  1577. filament_used_grams=plate.filament_used_grams,
  1578. print_time_seconds=plate.print_time_seconds,
  1579. )
  1580. for plate in progress.plates
  1581. ],
  1582. )
  1583. @router.get("/{item_id}", response_model=PrintQueueItemResponse)
  1584. async def get_queue_item(
  1585. item_id: int,
  1586. db: AsyncSession = Depends(get_db),
  1587. auth_result: tuple[User | None, bool] = Depends(
  1588. require_ownership_permission(
  1589. Permission.QUEUE_READ_ALL,
  1590. Permission.QUEUE_READ_OWN,
  1591. )
  1592. ),
  1593. ):
  1594. """Get a specific queue item."""
  1595. current_user, can_read_all = auth_result
  1596. result = await db.execute(
  1597. select(PrintQueueItem)
  1598. .options(
  1599. selectinload(PrintQueueItem.archive),
  1600. selectinload(PrintQueueItem.printer),
  1601. selectinload(PrintQueueItem.library_file),
  1602. selectinload(PrintQueueItem.created_by),
  1603. selectinload(PrintQueueItem.batch),
  1604. # Cross-model candidates (#671) and their files, for the card label.
  1605. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1606. )
  1607. .where(PrintQueueItem.id == item_id)
  1608. )
  1609. item = result.scalar_one_or_none()
  1610. if not item:
  1611. raise HTTPException(404, "Queue item not found")
  1612. if (
  1613. current_user is not None
  1614. and not can_read_all
  1615. and (item.created_by_id is None or item.created_by_id != current_user.id)
  1616. ):
  1617. raise HTTPException(404, "Queue item not found")
  1618. return _enrich_response(item)
  1619. @router.patch("/{item_id}", response_model=PrintQueueItemResponse)
  1620. async def update_queue_item(
  1621. item_id: int,
  1622. data: PrintQueueItemUpdate,
  1623. db: AsyncSession = Depends(get_db),
  1624. auth_result: tuple[User | None, bool] = Depends(
  1625. require_ownership_permission(
  1626. Permission.QUEUE_UPDATE_ALL,
  1627. Permission.QUEUE_UPDATE_OWN,
  1628. )
  1629. ),
  1630. ):
  1631. """Update a queue item."""
  1632. user, can_modify_all = auth_result
  1633. result = await db.execute(
  1634. select(PrintQueueItem)
  1635. # Needed by the cross-model guard below, and by the response builder —
  1636. # without it _variant_summaries falls back to [] and a PATCH would strip
  1637. # the alternatives out of the payload it echoes back.
  1638. .options(selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file))
  1639. .where(PrintQueueItem.id == item_id)
  1640. )
  1641. item = result.scalar_one_or_none()
  1642. if not item:
  1643. raise HTTPException(404, "Queue item not found")
  1644. # Ownership check
  1645. if not can_modify_all:
  1646. if item.created_by_id != user.id:
  1647. raise HTTPException(403, "You can only update your own queue items")
  1648. if item.status != "pending":
  1649. raise HTTPException(400, "Can only update pending items")
  1650. # Dispatch claim (#2615): the row is pending but a scheduler worker has
  1651. # already claimed it and is uploading to its printer. Editing now (e.g.
  1652. # reassigning printer_id) would split the queue row from the in-flight
  1653. # archive/expected-print/physical command. Reject until dispatch finishes;
  1654. # to move it, cancel first (the coordinated escape) and re-queue.
  1655. if item.dispatching_at is not None:
  1656. raise HTTPException(409, "Item is being dispatched — cancel it first to make changes")
  1657. update_data = data.model_dump(exclude_unset=True)
  1658. # Normalize target_model if being updated (see add_to_queue for why the
  1659. # code map has to run first).
  1660. if "target_model" in update_data and update_data["target_model"]:
  1661. update_data["target_model"] = normalize_model_name(update_data["target_model"])
  1662. # A cross-model item (#671) owns its own printer decision: each candidate
  1663. # carries its model, and the resolver folds the winner onto the row at
  1664. # dispatch. Assigning a printer here would leave a row with variants *and* a
  1665. # printer_id, and the fixed-printer branch of the scheduler wins that race —
  1666. # so it would dispatch a row whose library_file_id is still null and die in
  1667. # the upload. Narrowing target_model is refused for the same reason: it
  1668. # would silently discard every alternative the user queued.
  1669. #
  1670. # Compared against the current value rather than merely present, because the
  1671. # edit dialog re-sends target_model unchanged on every save.
  1672. if item.variants:
  1673. for field in ("printer_id", "target_model"):
  1674. if field in update_data and update_data[field] != getattr(item, field):
  1675. raise HTTPException(
  1676. 400,
  1677. "This job has printer alternatives — remove them before assigning a printer or model",
  1678. )
  1679. # Cannot specify both printer_id and target_model
  1680. new_printer_id = update_data.get("printer_id", item.printer_id)
  1681. new_target_model = update_data.get("target_model", item.target_model)
  1682. if new_printer_id and new_target_model:
  1683. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  1684. # Validate new printer_id if being changed (and not None)
  1685. if "printer_id" in update_data and update_data["printer_id"] is not None:
  1686. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  1687. if not result.scalar_one_or_none():
  1688. raise HTTPException(400, "Printer not found")
  1689. # Validate target_model has active printers
  1690. if "target_model" in update_data and update_data["target_model"]:
  1691. result = await db.execute(
  1692. select(Printer).where(Printer.model == update_data["target_model"]).where(Printer.is_active == True) # noqa: E712
  1693. )
  1694. if not result.scalars().first():
  1695. raise HTTPException(400, f"No active printers for model: {update_data['target_model']}")
  1696. # Cross-model safety gate (#2578) — same check as the create route, so
  1697. # a mismatched target can't be introduced by editing either.
  1698. sliced_for = None
  1699. if item.archive_id:
  1700. result = await db.execute(select(PrintArchive.sliced_for_model).where(PrintArchive.id == item.archive_id))
  1701. sliced_for = result.scalar_one_or_none()
  1702. elif item.library_file_id:
  1703. result = await db.execute(select(LibraryFile).where(LibraryFile.id == item.library_file_id))
  1704. lib = result.scalar_one_or_none()
  1705. if lib and lib.file_metadata:
  1706. sliced_for = lib.file_metadata.get("sliced_for_model")
  1707. if not is_gcode_compatible(sliced_for, update_data["target_model"]):
  1708. raise HTTPException(
  1709. 400,
  1710. f"File was sliced for {sliced_for} and cannot be dispatched to {update_data['target_model']} printers",
  1711. )
  1712. # Serialize ams_mapping to JSON for TEXT column storage
  1713. if "ams_mapping" in update_data:
  1714. update_data["ams_mapping"] = json.dumps(update_data["ams_mapping"]) if update_data["ams_mapping"] else None
  1715. # Serialize filament_overrides to JSON for TEXT column storage, keeping only
  1716. # the slots this item's plate actually prints (#2551 — same shared-override
  1717. # list the create path narrows).
  1718. if "filament_overrides" in update_data:
  1719. overrides = update_data["filament_overrides"]
  1720. if overrides:
  1721. overrides = overrides_for_plate(
  1722. overrides,
  1723. await _resolve_source_path(db, item),
  1724. update_data.get("plate_id", item.plate_id),
  1725. )
  1726. update_data["filament_overrides"] = json.dumps(overrides) if overrides else None
  1727. # Serialize H2C rack-swap nozzle pick (#1780) to JSON for TEXT column
  1728. # storage; same Text-as-opaque-blob convention as ams_mapping above.
  1729. if "nozzle_mapping" in update_data:
  1730. update_data["nozzle_mapping"] = (
  1731. json.dumps(update_data["nozzle_mapping"]) if update_data["nozzle_mapping"] else None
  1732. )
  1733. # Same Text-as-JSON convention for the rack-position pick (#1784). An empty
  1734. # object clears it, which is how the UI says "assign these for me again".
  1735. if "nozzle_rack_choice" in update_data:
  1736. update_data["nozzle_rack_choice"] = (
  1737. json.dumps(update_data["nozzle_rack_choice"]) if update_data["nozzle_rack_choice"] else None
  1738. )
  1739. trusted_estimated_cost = await _trusted_item_estimated_cost(
  1740. db,
  1741. item,
  1742. printer_id=update_data.get("printer_id", item.printer_id),
  1743. plate_id=update_data.get("plate_id", item.plate_id),
  1744. ams_mapping=update_data.get("ams_mapping", item.ams_mapping),
  1745. )
  1746. update_data["estimated_cost"] = trusted_estimated_cost
  1747. await validate_print_budget(
  1748. db,
  1749. cost_center_id=update_data.get("cost_center_id", item.cost_center_id),
  1750. estimated_cost=trusted_estimated_cost,
  1751. current_user=user,
  1752. exclude_queue_item_id=item.id,
  1753. )
  1754. # Re-check the dispatch claim right before mutating (#2615). Several awaited
  1755. # validations ran since the guard above, and a scheduler worker may have
  1756. # claimed the row in that gap. A fresh read (item isn't dirty yet, so no
  1757. # autoflush races the check) narrows the window to effectively nothing.
  1758. claimed = (
  1759. await db.execute(select(PrintQueueItem.dispatching_at).where(PrintQueueItem.id == item_id))
  1760. ).scalar_one_or_none()
  1761. if claimed is not None:
  1762. raise HTTPException(409, "Item is being dispatched — cancel it first to make changes")
  1763. for field, value in update_data.items():
  1764. setattr(item, field, value)
  1765. await db.commit()
  1766. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  1767. logger.info("Updated queue item %s", item_id)
  1768. return _enrich_response(item)
  1769. @router.delete("/{item_id}")
  1770. async def delete_queue_item(
  1771. item_id: int,
  1772. db: AsyncSession = Depends(get_db),
  1773. auth_result: tuple[User | None, bool] = Depends(
  1774. require_ownership_permission(
  1775. Permission.QUEUE_DELETE_ALL,
  1776. Permission.QUEUE_DELETE_OWN,
  1777. )
  1778. ),
  1779. ):
  1780. """Remove an item from the queue."""
  1781. user, can_modify_all = auth_result
  1782. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1783. item = result.scalar_one_or_none()
  1784. if not item:
  1785. raise HTTPException(404, "Queue item not found")
  1786. # Ownership check
  1787. if not can_modify_all:
  1788. if item.created_by_id != user.id:
  1789. raise HTTPException(403, "You can only delete your own queue items")
  1790. if item.status == "printing":
  1791. raise HTTPException(400, "Cannot delete item that is currently printing")
  1792. await release_budget_reservation(
  1793. db,
  1794. source_type="print_queue",
  1795. source_id=item.id,
  1796. status="released",
  1797. )
  1798. await db.delete(item)
  1799. await db.commit()
  1800. # Stop an in-flight preheat for this item: the dispatch coroutine is
  1801. # parked in a sleep and cannot see the status we just wrote (#2727).
  1802. from backend.app.services.print_scheduler import scheduler as _scheduler
  1803. _scheduler.notify_dispatch_cancelled(item_id)
  1804. logger.info("Deleted queue item %s", item_id)
  1805. return {"message": "Queue item deleted"}
  1806. @router.post("/reorder")
  1807. async def reorder_queue(
  1808. data: PrintQueueReorder,
  1809. db: AsyncSession = Depends(get_db),
  1810. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  1811. ):
  1812. """Bulk update positions for queue items."""
  1813. for reorder_item in data.items:
  1814. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == reorder_item.id))
  1815. item = result.scalar_one_or_none()
  1816. if item and item.status == "pending":
  1817. item.position = reorder_item.position
  1818. await db.commit()
  1819. logger.info("Reordered %s queue items", len(data.items))
  1820. return {"message": f"Reordered {len(data.items)} items"}
  1821. @router.post("/printer/{printer_id}/resume")
  1822. async def resume_queue_after_failure(
  1823. printer_id: int,
  1824. db: AsyncSession = Depends(get_db),
  1825. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  1826. ):
  1827. """Clear the previous-success gate for a printer and restore skipped items.
  1828. Single atomic op (#1818):
  1829. * Sets ``gate_acknowledged=True`` on every ``failed`` / ``aborted`` queue
  1830. item for this printer that's still in the scheduler's lookback window,
  1831. so the next ``_check_previous_success`` call ignores them.
  1832. * Restores ``skipped`` items whose ``error_message`` matches the
  1833. scheduler's exact "Previous print failed or was aborted" gate string
  1834. back to ``pending`` (clears ``error_message`` + ``completed_at``).
  1835. Returns counts so the UI can render a precise toast. No-op endpoint
  1836. (zero counts) when called against a printer with no gate to clear.
  1837. """
  1838. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1839. printer = result.scalar_one_or_none()
  1840. if not printer:
  1841. raise HTTPException(404, "Printer not found")
  1842. ack_result = await db.execute(
  1843. select(PrintQueueItem)
  1844. .where(PrintQueueItem.printer_id == printer_id)
  1845. .where(PrintQueueItem.status.in_(["failed", "aborted"]))
  1846. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  1847. )
  1848. to_ack = ack_result.scalars().all()
  1849. for failed_item in to_ack:
  1850. failed_item.gate_acknowledged = True
  1851. restore_result = await db.execute(
  1852. select(PrintQueueItem)
  1853. .where(PrintQueueItem.printer_id == printer_id)
  1854. .where(PrintQueueItem.status == "skipped")
  1855. .where(PrintQueueItem.error_message == "Previous print failed or was aborted")
  1856. )
  1857. to_restore = restore_result.scalars().all()
  1858. for skipped_item in to_restore:
  1859. skipped_item.status = "pending"
  1860. skipped_item.error_message = None
  1861. skipped_item.completed_at = None
  1862. await db.commit()
  1863. logger.info(
  1864. "Resume after failure on printer %s: acknowledged %d failure(s), restored %d skipped item(s)",
  1865. printer_id,
  1866. len(to_ack),
  1867. len(to_restore),
  1868. )
  1869. return {"acknowledged": len(to_ack), "restored": len(to_restore)}
  1870. @router.post("/{item_id}/cancel")
  1871. async def cancel_queue_item(
  1872. item_id: int,
  1873. db: AsyncSession = Depends(get_db),
  1874. auth_result: tuple[User | None, bool] = Depends(
  1875. require_ownership_permission(
  1876. Permission.QUEUE_UPDATE_ALL,
  1877. Permission.QUEUE_UPDATE_OWN,
  1878. )
  1879. ),
  1880. ):
  1881. """Cancel a pending queue item."""
  1882. user, can_modify_all = auth_result
  1883. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1884. item = result.scalar_one_or_none()
  1885. if not item:
  1886. raise HTTPException(404, "Queue item not found")
  1887. # Ownership check
  1888. if not can_modify_all:
  1889. if item.created_by_id != user.id:
  1890. raise HTTPException(403, "You can only cancel your own queue items")
  1891. if item.status not in ("pending",):
  1892. raise HTTPException(400, f"Cannot cancel item with status '{item.status}'")
  1893. item.status = "cancelled"
  1894. item.completed_at = datetime.now(timezone.utc)
  1895. await release_budget_reservation(
  1896. db,
  1897. source_type="print_queue",
  1898. source_id=item.id,
  1899. status="released",
  1900. )
  1901. await db.commit()
  1902. # Stop an in-flight preheat for this item: the dispatch coroutine is
  1903. # parked in a sleep and cannot see the status we just wrote (#2727).
  1904. from backend.app.services.print_scheduler import scheduler as _scheduler
  1905. _scheduler.notify_dispatch_cancelled(item_id)
  1906. logger.info("Cancelled queue item %s", item_id)
  1907. return {"message": "Queue item cancelled"}
  1908. @router.post("/{item_id}/stop")
  1909. async def stop_queue_item(
  1910. item_id: int,
  1911. db: AsyncSession = Depends(get_db),
  1912. auth_result: tuple[User | None, bool] = Depends(
  1913. require_ownership_permission(
  1914. Permission.QUEUE_UPDATE_ALL,
  1915. Permission.QUEUE_UPDATE_OWN,
  1916. )
  1917. ),
  1918. ):
  1919. """Stop an actively printing queue item.
  1920. Ownership-scoped (#1625-followup): callers with QUEUE_UPDATE_OWN can stop
  1921. their own items; callers with QUEUE_UPDATE_ALL can stop any item. Mirrors
  1922. the /cancel shape. Pre-fix this required QUEUE_UPDATE_ALL — Operators
  1923. holding only _OWN saw the Stop button in the queue UI but got 403 on click.
  1924. """
  1925. from backend.app.services.printer_manager import printer_manager
  1926. user, can_modify_all = auth_result
  1927. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  1928. item = result.scalar_one_or_none()
  1929. if not item:
  1930. raise HTTPException(404, "Queue item not found")
  1931. # Ownership check — mirrors /cancel. Ownerless items (created_by_id IS NULL)
  1932. # require _ALL: stop is destructive and an _OWN holder can't claim "they
  1933. # own it" the way /start does (#1670).
  1934. if not can_modify_all and user is not None:
  1935. if item.created_by_id is None or item.created_by_id != user.id:
  1936. raise HTTPException(403, "You can only stop your own queue items")
  1937. if item.status != "printing":
  1938. raise HTTPException(400, f"Can only stop items that are printing, current status: '{item.status}'")
  1939. # Capture values we need for background task
  1940. printer_id = item.printer_id
  1941. auto_off_after = item.auto_off_after
  1942. # Try to send stop command to printer
  1943. stop_sent = False
  1944. try:
  1945. stop_sent = printer_manager.stop_print(printer_id)
  1946. if not stop_sent:
  1947. logger.warning("stop_print returned False for printer %s - printer may not be connected", printer_id)
  1948. except Exception as e:
  1949. logger.error("Error sending stop command for queue item %s: %s", item_id, e)
  1950. # Mark this printer as user-stopped BEFORE the first await so that if the
  1951. # MQTT on_print_complete callback fires during the db.commit() yield the flag
  1952. # is already set and the "failed" status will be correctly overridden to
  1953. # "cancelled" (preventing a spurious "print failed" notification).
  1954. try:
  1955. from backend.app.main import mark_printer_stopped_by_user
  1956. mark_printer_stopped_by_user(printer_id)
  1957. except Exception as _mark_err:
  1958. logger.warning("Failed to mark printer %s as user-stopped: %s", printer_id, _mark_err)
  1959. # Update queue item status regardless - if printer is off, print is already stopped
  1960. item.status = "cancelled"
  1961. item.completed_at = datetime.now(timezone.utc)
  1962. item.error_message = "Stopped by user" if stop_sent else "Stopped by user (printer was offline)"
  1963. # Reconcile the linked archive when the printer is offline (#2603). When the
  1964. # stop command reaches the printer it later reports the stop over MQTT and
  1965. # on_print_complete flips the archive to cancelled/failed. When the printer is
  1966. # offline no such event ever arrives, so the archive would stay "printing"
  1967. # forever (queue row cancelled, archive still printing — the reporter's
  1968. # archive 436). Close it out here, mirroring what the MQTT path would have
  1969. # done. Only touch a still-"printing" archive so we never overwrite a real
  1970. # completion that raced in.
  1971. if not stop_sent and item.archive_id:
  1972. archive = await db.get(PrintArchive, item.archive_id)
  1973. if archive and archive.status == "printing":
  1974. archive.status = "cancelled"
  1975. archive.completed_at = datetime.now(timezone.utc)
  1976. archive.failure_reason = "Stopped by user (printer was offline)"
  1977. await db.commit()
  1978. logger.info("Stopped printing queue item %s (stop command sent: %s)", item_id, stop_sent)
  1979. # Schedule power-off if the queue item opted in. Delegates to the smart-plug
  1980. # manager so the off honours each plug's configured strategy (time delay or
  1981. # temperature threshold), is cancelled if the printer starts printing again,
  1982. # and never cuts power on a loaded print (#1890). Previously an inline block
  1983. # hardcoded a 50°C / 600s cooldown wait and powered off on the timeout
  1984. # regardless of print state.
  1985. if auto_off_after:
  1986. from backend.app.services.smart_plug_manager import smart_plug_manager
  1987. try:
  1988. await smart_plug_manager.schedule_off_after_queue_job(printer_id, db)
  1989. except Exception as e:
  1990. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", printer_id, e)
  1991. return {"message": "Print stopped" if stop_sent else "Queue item cancelled (printer was offline)"}
  1992. @router.post("/{item_id}/start")
  1993. async def start_queue_item(
  1994. item_id: int,
  1995. skip_filament_check: bool = Query(default=False),
  1996. db: AsyncSession = Depends(get_db),
  1997. auth_result: tuple[User | None, bool] = Depends(
  1998. require_ownership_permission(
  1999. Permission.QUEUE_UPDATE_ALL,
  2000. Permission.QUEUE_UPDATE_OWN,
  2001. )
  2002. ),
  2003. ):
  2004. """Manually start a staged (manual_start) queue item.
  2005. Ownership-scoped (#1625-followup): callers with QUEUE_UPDATE_OWN can
  2006. start their own items + claim ownership of NULL-owner items (VP-uploaded
  2007. items arrive unattributed per #1670). Callers with QUEUE_UPDATE_ALL can
  2008. start any item. Pre-fix this required QUEUE_UPDATE_OWN with no ownership
  2009. check, so _OWN holders could start anyone's queue items via direct API.
  2010. Clears the manual_start flag so the scheduler picks it up. When
  2011. ``skip_filament_check`` is false (the default) the live filament
  2012. deficit (#1496) is checked first — if the assigned spool can't satisfy
  2013. a slot's required grams, the route returns ``409`` with the deficit
  2014. payload so the caller can show a confirm dialog and retry with
  2015. ``skip_filament_check=true``.
  2016. """
  2017. user, can_modify_all = auth_result
  2018. result = await db.execute(
  2019. select(PrintQueueItem)
  2020. .options(
  2021. selectinload(PrintQueueItem.archive),
  2022. selectinload(PrintQueueItem.printer),
  2023. selectinload(PrintQueueItem.library_file),
  2024. selectinload(PrintQueueItem.batch),
  2025. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  2026. )
  2027. .where(PrintQueueItem.id == item_id)
  2028. )
  2029. item = result.scalar_one_or_none()
  2030. if not item:
  2031. raise HTTPException(404, "Queue item not found")
  2032. # Ownership check — softer than /cancel because /start is the entry point
  2033. # for #1670's VP-import flow: an unowned item is claimable by the first
  2034. # _OWN holder who clicks ▶, and the route below credits them as owner.
  2035. # An item with a DIFFERENT owner → 403.
  2036. if not can_modify_all and user is not None:
  2037. if item.created_by_id is not None and item.created_by_id != user.id:
  2038. raise HTTPException(403, "You can only start your own queue items")
  2039. if item.status != "pending":
  2040. raise HTTPException(400, f"Can only start pending items, current status: '{item.status}'")
  2041. item.estimated_cost = await _trusted_item_estimated_cost(
  2042. db,
  2043. item,
  2044. printer_id=item.printer_id,
  2045. plate_id=item.plate_id,
  2046. ams_mapping=item.ams_mapping,
  2047. )
  2048. await validate_print_budget(
  2049. db,
  2050. cost_center_id=item.cost_center_id,
  2051. estimated_cost=item.estimated_cost,
  2052. current_user=user,
  2053. exclude_queue_item_id=item.id,
  2054. )
  2055. # Live deficit check — re-evaluated against current spool state, so a
  2056. # spool swap between scheduler flagging and the user clicking ▶ clears
  2057. # the block automatically.
  2058. if not skip_filament_check:
  2059. deficit = await compute_deficit_for_queue_item(db, item)
  2060. if deficit:
  2061. raise HTTPException(
  2062. status_code=409,
  2063. detail={
  2064. "code": "insufficient_filament",
  2065. "deficit": [d.to_dict() for d in deficit],
  2066. },
  2067. )
  2068. # Print Anyway / no deficit: clear the flags and let the scheduler dispatch.
  2069. item.manual_start = False
  2070. item.filament_short = False
  2071. # Persist the user's "Print Anyway" decision so the scheduler does not
  2072. # immediately re-flag this item on the next tick (#1698-followup). The
  2073. # pre-fix behaviour bounced between "user said anyway" and
  2074. # "scheduler re-blocked on same deficit" forever.
  2075. if skip_filament_check:
  2076. item.skip_filament_check = True
  2077. # Credit the clicker as the item's owner when no prior owner is set —
  2078. # VP-uploaded queue items arrive over FTP unattributed, so without this
  2079. # the print log's User column stays blank even when auth is on
  2080. # (#1670). An item that already has a creator (UI-added queue items)
  2081. # keeps that attribution; the dispatcher is not promoted over the
  2082. # original uploader.
  2083. if user is not None and item.created_by_id is None:
  2084. item.created_by_id = user.id
  2085. await db.commit()
  2086. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  2087. logger.info(
  2088. "Manually started queue item %s (cleared manual_start; skip_filament_check=%s)",
  2089. item_id,
  2090. skip_filament_check,
  2091. )
  2092. return _enrich_response(item)