print_queue.py 134 KB

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