print_queue.py 94 KB

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