print_queue.py 121 KB

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