print_queue.py 138 KB

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