print_queue.py 109 KB

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