print_queue.py 106 KB

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