print_queue.py 124 KB

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