print_queue.py 122 KB

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