print_queue.py 111 KB

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