print_queue.py 108 KB

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