print_queue.py 139 KB

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