print_queue.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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, or_, select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from sqlalchemy.orm import selectinload
  12. from backend.app.core.auth import RequirePermissionIfAuthEnabled, require_ownership_permission
  13. from backend.app.core.config import settings
  14. from backend.app.core.database import get_db
  15. from backend.app.core.permissions import Permission
  16. from backend.app.core.tasks import spawn_background_task
  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
  20. from backend.app.models.print_queue import PrintQueueItem
  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. PrintBatchResponse,
  26. PrintQueueBulkUpdate,
  27. PrintQueueBulkUpdateResponse,
  28. PrintQueueItemCreate,
  29. PrintQueueItemResponse,
  30. PrintQueueItemUpdate,
  31. PrintQueueReorder,
  32. )
  33. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  34. from backend.app.services.notification_service import notification_service
  35. from backend.app.utils.printer_models import normalize_printer_model, normalize_printer_model_id
  36. from backend.app.utils.threemf_tools import extract_bed_type_from_3mf, extract_filament_usage_from_3mf
  37. logger = logging.getLogger(__name__)
  38. router = APIRouter(prefix="/queue", tags=["queue"])
  39. def _extract_filament_types_from_3mf(file_path: Path, plate_id: int | None = None) -> list[str]:
  40. """Extract unique filament types from a 3MF file.
  41. Args:
  42. file_path: Path to the 3MF file
  43. plate_id: Optional plate index to filter for (for multi-plate files)
  44. Returns:
  45. List of unique filament types (e.g., ["PLA", "PETG"])
  46. """
  47. types: set[str] = set()
  48. try:
  49. with zipfile.ZipFile(file_path, "r") as zf:
  50. if "Metadata/slice_info.config" not in zf.namelist():
  51. return []
  52. content = zf.read("Metadata/slice_info.config").decode()
  53. root = ET.fromstring(content)
  54. if plate_id is not None:
  55. # Find the plate element with matching index
  56. for plate_elem in root.findall(".//plate"):
  57. plate_index = None
  58. for meta in plate_elem.findall("metadata"):
  59. if meta.get("key") == "index":
  60. try:
  61. plate_index = int(meta.get("value", "0"))
  62. except ValueError:
  63. pass # Skip plate with unparseable index
  64. break
  65. if plate_index == plate_id:
  66. for filament_elem in plate_elem.findall("filament"):
  67. filament_type = filament_elem.get("type", "")
  68. used_g = filament_elem.get("used_g", "0")
  69. try:
  70. used_grams = float(used_g)
  71. except (ValueError, TypeError):
  72. used_grams = 0
  73. if used_grams > 0 and filament_type:
  74. types.add(filament_type)
  75. break
  76. else:
  77. # No plate_id specified - extract all filaments with used_g > 0
  78. for filament_elem in root.findall(".//filament"):
  79. filament_type = filament_elem.get("type", "")
  80. used_g = filament_elem.get("used_g", "0")
  81. try:
  82. used_grams = float(used_g)
  83. except (ValueError, TypeError):
  84. used_grams = 0
  85. if used_grams > 0 and filament_type:
  86. types.add(filament_type)
  87. except Exception as e:
  88. logger.warning("Failed to extract filament types from %s: %s", file_path, e)
  89. return sorted(types)
  90. def _extract_print_time_from_3mf(file_path: Path, plate_id: int | None = None) -> int | None:
  91. """Extract print time (prediction) from a 3MF file.
  92. Args:
  93. file_path: Path to the 3MF file
  94. plate_id: Optional plate index to filter for (for multi-plate files)
  95. Returns:
  96. Print time in seconds, or None if not found
  97. """
  98. try:
  99. with zipfile.ZipFile(file_path, "r") as zf:
  100. if "Metadata/slice_info.config" not in zf.namelist():
  101. return None
  102. content = zf.read("Metadata/slice_info.config").decode()
  103. root = ET.fromstring(content)
  104. if plate_id is not None:
  105. for plate_elem in root.findall(".//plate"):
  106. plate_index = None
  107. for meta in plate_elem.findall("metadata"):
  108. if meta.get("key") == "index":
  109. try:
  110. plate_index = int(meta.get("value", "0"))
  111. except ValueError:
  112. pass # Skip plate with unparseable index
  113. break
  114. if plate_index == plate_id:
  115. for meta in plate_elem.findall("metadata"):
  116. if meta.get("key") == "prediction":
  117. try:
  118. return int(meta.get("value", "0"))
  119. except ValueError:
  120. return None
  121. break
  122. else:
  123. plate_elem = root.find(".//plate")
  124. if plate_elem is not None:
  125. for meta in plate_elem.findall("metadata"):
  126. if meta.get("key") == "prediction":
  127. try:
  128. return int(meta.get("value", "0"))
  129. except ValueError:
  130. return None
  131. except Exception as e:
  132. logger.warning("Failed to extract print time from %s: %s", file_path, e)
  133. return None
  134. def _enrich_response(item: PrintQueueItem) -> PrintQueueItemResponse:
  135. """Add nested archive/printer/library_file info to response."""
  136. # Parse ams_mapping from JSON string BEFORE model_validate
  137. ams_mapping_parsed = None
  138. if item.ams_mapping:
  139. try:
  140. ams_mapping_parsed = json.loads(item.ams_mapping)
  141. except json.JSONDecodeError:
  142. ams_mapping_parsed = None
  143. # Parse required_filament_types from JSON string
  144. required_filament_types_parsed = None
  145. if item.required_filament_types:
  146. try:
  147. required_filament_types_parsed = json.loads(item.required_filament_types)
  148. except json.JSONDecodeError:
  149. required_filament_types_parsed = None
  150. # Parse filament_overrides from JSON string
  151. filament_overrides_parsed = None
  152. if item.filament_overrides:
  153. try:
  154. filament_overrides_parsed = json.loads(item.filament_overrides)
  155. except json.JSONDecodeError:
  156. filament_overrides_parsed = None
  157. # Create response with parsed ams_mapping
  158. item_dict = {
  159. "id": item.id,
  160. "printer_id": item.printer_id,
  161. "target_model": item.target_model,
  162. "target_location": item.target_location,
  163. "required_filament_types": required_filament_types_parsed,
  164. "filament_overrides": filament_overrides_parsed,
  165. "waiting_reason": item.waiting_reason,
  166. "archive_id": item.archive_id,
  167. "library_file_id": item.library_file_id,
  168. "position": item.position,
  169. "scheduled_time": item.scheduled_time,
  170. "require_previous_success": item.require_previous_success,
  171. "auto_off_after": item.auto_off_after,
  172. "manual_start": item.manual_start,
  173. "filament_short": bool(item.filament_short),
  174. "skip_filament_check": bool(item.skip_filament_check),
  175. "ams_mapping": ams_mapping_parsed,
  176. "plate_id": item.plate_id,
  177. "bed_levelling": item.bed_levelling,
  178. "flow_cali": item.flow_cali,
  179. "vibration_cali": item.vibration_cali,
  180. "layer_inspect": item.layer_inspect,
  181. "timelapse": item.timelapse,
  182. "use_ams": item.use_ams,
  183. "nozzle_offset_cali": item.nozzle_offset_cali,
  184. "status": item.status,
  185. "started_at": item.started_at,
  186. "completed_at": item.completed_at,
  187. "error_message": item.error_message,
  188. "created_at": item.created_at,
  189. # User tracking (Issue #206)
  190. "created_by_id": item.created_by_id,
  191. "created_by_username": item.created_by.username if item.created_by else None,
  192. # Batch grouping
  193. "batch_id": item.batch_id,
  194. "batch_name": item.batch.name if item.batch else None,
  195. # SJF scheduling
  196. "been_jumped": item.been_jumped,
  197. # Auto-print G-code injection
  198. "gcode_injection": item.gcode_injection,
  199. }
  200. response = PrintQueueItemResponse(**item_dict)
  201. if item.archive:
  202. # Soft-deleted archive: files are gone from disk but the row stays
  203. # (its filament/cost contribution still flows into stats per #1343).
  204. # Suppress the archive-derived UI surface so the queue page doesn't
  205. # 404-storm the thumbnail / plates / plate-thumbnail endpoints — the
  206. # frontend's existing truthy gate on archive_thumbnail covers it
  207. # (#1348 follow-up). The archive_deleted flag lets the UI render a
  208. # "source deleted" badge on these rows.
  209. if item.archive.deleted_at is not None:
  210. response.archive_deleted = True
  211. else:
  212. response.archive_name = item.archive.print_name or item.archive.filename
  213. response.archive_thumbnail = item.archive.thumbnail_path
  214. response.print_time_seconds = item.archive.print_time_seconds
  215. response.filament_used_grams = item.archive.filament_used_grams
  216. response.filament_type = item.archive.filament_type
  217. response.filament_color = item.archive.filament_color
  218. response.layer_height = item.archive.layer_height
  219. response.nozzle_diameter = item.archive.nozzle_diameter
  220. response.sliced_for_model = item.archive.sliced_for_model
  221. response.bed_type = item.archive.bed_type
  222. if item.plate_id:
  223. archive_path = settings.base_dir / item.archive.file_path
  224. if archive_path.exists():
  225. plate_time = _extract_print_time_from_3mf(archive_path, item.plate_id)
  226. plate_weight = sum(
  227. f["used_g"] for f in extract_filament_usage_from_3mf(archive_path, item.plate_id)
  228. )
  229. plate_bed = extract_bed_type_from_3mf(archive_path, item.plate_id)
  230. if plate_time is not None:
  231. response.print_time_seconds = plate_time
  232. if plate_weight > 0:
  233. response.filament_used_grams = plate_weight
  234. if plate_bed:
  235. response.bed_type = plate_bed
  236. if item.library_file:
  237. response.library_file_name = (
  238. item.library_file.file_metadata.get("print_name") if item.library_file.file_metadata else None
  239. )
  240. if not response.library_file_name:
  241. response.library_file_name = item.library_file.filename
  242. response.library_file_thumbnail = item.library_file.thumbnail_path
  243. # Get metadata from library file if no archive
  244. if not item.archive and item.library_file.file_metadata:
  245. response.print_time_seconds = item.library_file.file_metadata.get("print_time_seconds")
  246. response.filament_used_grams = item.library_file.file_metadata.get("filament_used_grams")
  247. response.filament_type = item.library_file.file_metadata.get("filament_type")
  248. response.filament_color = item.library_file.file_metadata.get("filament_color")
  249. response.layer_height = item.library_file.file_metadata.get("layer_height")
  250. response.nozzle_diameter = item.library_file.file_metadata.get("nozzle_diameter")
  251. response.sliced_for_model = item.library_file.file_metadata.get("sliced_for_model")
  252. response.bed_type = item.library_file.file_metadata.get("bed_type")
  253. if item.plate_id:
  254. lib_path = Path(item.library_file.file_path)
  255. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / item.library_file.file_path
  256. if library_file_path.exists():
  257. plate_time = _extract_print_time_from_3mf(library_file_path, item.plate_id)
  258. plate_weight = sum(
  259. f["used_g"] for f in extract_filament_usage_from_3mf(library_file_path, item.plate_id)
  260. )
  261. plate_bed = extract_bed_type_from_3mf(library_file_path, item.plate_id)
  262. if plate_time is not None:
  263. response.print_time_seconds = plate_time
  264. if plate_weight > 0:
  265. response.filament_used_grams = plate_weight
  266. if plate_bed:
  267. response.bed_type = plate_bed
  268. if item.printer:
  269. response.printer_name = item.printer.name
  270. return response
  271. @router.get("/", response_model=list[PrintQueueItemResponse])
  272. async def list_queue(
  273. printer_id: int | None = Query(None, description="Filter by printer (-1 for unassigned)"),
  274. status: str | None = Query(None, description="Filter by status"),
  275. target_model: str | None = Query(
  276. None, description="Filter by target model (also includes model-based items when combined with printer_id)"
  277. ),
  278. db: AsyncSession = Depends(get_db),
  279. auth_result: tuple[User | None, bool] = Depends(
  280. require_ownership_permission(
  281. Permission.QUEUE_READ_ALL,
  282. Permission.QUEUE_READ_OWN,
  283. )
  284. ),
  285. ):
  286. """List all queue items, optionally filtered by printer or status."""
  287. user, can_read_all = auth_result
  288. query = (
  289. select(PrintQueueItem)
  290. .options(
  291. selectinload(PrintQueueItem.archive),
  292. selectinload(PrintQueueItem.printer),
  293. selectinload(PrintQueueItem.library_file),
  294. selectinload(PrintQueueItem.created_by),
  295. selectinload(PrintQueueItem.batch),
  296. )
  297. .order_by(PrintQueueItem.printer_id.nulls_first(), PrintQueueItem.position)
  298. )
  299. if user is not None and not can_read_all:
  300. query = query.where(PrintQueueItem.created_by_id == user.id)
  301. if printer_id is not None:
  302. if printer_id == -1:
  303. # Special value: filter for unassigned items
  304. query = query.where(PrintQueueItem.printer_id.is_(None))
  305. else:
  306. # Resolve effective model: prefer explicit param, fall back to printer's DB model.
  307. # This ensures model-based "Any X" items are returned even when the frontend
  308. # doesn't send target_model (e.g. printer.model is NULL on the client side).
  309. effective_model = target_model
  310. if not effective_model:
  311. printer_row = (
  312. await db.execute(select(Printer.model).where(Printer.id == printer_id))
  313. ).scalar_one_or_none()
  314. effective_model = printer_row
  315. if effective_model:
  316. # Include both printer-specific items AND model-based (unassigned) items
  317. query = query.where(
  318. or_(
  319. PrintQueueItem.printer_id == printer_id,
  320. and_(
  321. PrintQueueItem.printer_id.is_(None),
  322. func.lower(PrintQueueItem.target_model) == effective_model.lower(),
  323. ),
  324. )
  325. )
  326. else:
  327. query = query.where(PrintQueueItem.printer_id == printer_id)
  328. elif target_model:
  329. query = query.where(func.lower(PrintQueueItem.target_model) == target_model.lower())
  330. if status:
  331. query = query.where(PrintQueueItem.status == status)
  332. result = await db.execute(query)
  333. items = result.scalars().all()
  334. return [_enrich_response(item) for item in items]
  335. @router.post("/", response_model=PrintQueueItemResponse)
  336. async def add_to_queue(
  337. data: PrintQueueItemCreate,
  338. db: AsyncSession = Depends(get_db),
  339. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  340. ):
  341. """Add an item to the print queue."""
  342. # Normalize target_model (e.g., "Bambu Lab X1E" / "C13" -> "X1E")
  343. target_model_norm = None
  344. if data.target_model:
  345. target_model_norm = (
  346. normalize_printer_model(data.target_model)
  347. or normalize_printer_model_id(data.target_model)
  348. or data.target_model
  349. )
  350. # Validate that either archive_id or library_file_id is provided
  351. if not data.archive_id and not data.library_file_id:
  352. raise HTTPException(400, "Either archive_id or library_file_id must be provided")
  353. # Cannot specify both printer_id and target_model
  354. if data.printer_id and target_model_norm:
  355. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  356. # Validate printer exists (if assigned)
  357. if data.printer_id is not None:
  358. result = await db.execute(select(Printer).where(Printer.id == data.printer_id))
  359. if not result.scalar_one_or_none():
  360. raise HTTPException(400, "Printer not found")
  361. # Validate target_model has active printers
  362. if target_model_norm:
  363. result = await db.execute(
  364. select(Printer).where(Printer.model == target_model_norm).where(Printer.is_active == True) # noqa: E712
  365. )
  366. if not result.scalars().first():
  367. raise HTTPException(400, f"No active printers for model: {target_model_norm}")
  368. # Validate archive exists (if provided) and get it for filament extraction
  369. archive = None
  370. if data.archive_id:
  371. result = await db.execute(select(PrintArchive).where(PrintArchive.id == data.archive_id))
  372. archive = result.scalar_one_or_none()
  373. if not archive:
  374. raise HTTPException(400, "Archive not found")
  375. # IDOR fix (maziggy/bambuddy-security #2): without this check, a
  376. # caller with QUEUE_CREATE could queue any user's archive even
  377. # without ARCHIVES_READ on it — Landon's PoC enumerated this on
  378. # admin's archives as operator1. Gate on ARCHIVES_READ_ALL OR
  379. # ownership of the archive. 404 (not 403) so we don't leak
  380. # "this id exists but you can't queue it" for enumeration.
  381. if (
  382. current_user is not None
  383. and not current_user.has_permission(Permission.ARCHIVES_READ_ALL.value)
  384. and archive.created_by_id != current_user.id
  385. ):
  386. raise HTTPException(404, "Archive not found")
  387. # Validate library file exists (if provided) and get it for filament extraction
  388. library_file = None
  389. if data.library_file_id:
  390. result = await db.execute(LibraryFile.active().where(LibraryFile.id == data.library_file_id))
  391. library_file = result.scalar_one_or_none()
  392. if not library_file:
  393. raise HTTPException(400, "Library file not found")
  394. # Same shape: gate cross-user library-file queueing on LIBRARY_READ_ALL.
  395. if (
  396. current_user is not None
  397. and not current_user.has_permission(Permission.LIBRARY_READ_ALL.value)
  398. and library_file.created_by_id != current_user.id
  399. ):
  400. raise HTTPException(404, "Library file not found")
  401. # Bambu SD card is FAT32/exFAT — illegal filename chars would 553 at
  402. # FTP upload time (#1540). Reject at queue time so the user gets the
  403. # actionable error before waiting in queue.
  404. from backend.app.utils.filename import InvalidFilenameError, validate_print_filename
  405. try:
  406. validate_print_filename(library_file.filename)
  407. except InvalidFilenameError as e:
  408. raise HTTPException(400, str(e)) from e
  409. # Extract filament types for model-based assignment (used by scheduler for validation)
  410. required_filament_types = None
  411. if target_model_norm:
  412. # Get file path from archive or library file
  413. file_path = None
  414. if archive:
  415. file_path = settings.base_dir / archive.file_path
  416. elif library_file:
  417. lib_path = Path(library_file.file_path)
  418. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  419. if file_path and file_path.exists():
  420. filament_types = _extract_filament_types_from_3mf(file_path, data.plate_id)
  421. if filament_types:
  422. required_filament_types = json.dumps(filament_types)
  423. logger.info("Extracted filament types for model-based queue: %s", filament_types)
  424. # If filament overrides are provided, update required_filament_types to match override types
  425. filament_overrides_json = None
  426. if data.filament_overrides and target_model_norm:
  427. filament_overrides_json = json.dumps(data.filament_overrides)
  428. # Update required_filament_types from overrides so scheduler validates against overridden types
  429. override_types = sorted({o["type"] for o in data.filament_overrides if "type" in o})
  430. if override_types:
  431. # Merge with existing types (overrides may only cover some slots)
  432. existing_types = set(json.loads(required_filament_types)) if required_filament_types else set()
  433. # Replace types for overridden slots, keep others
  434. all_types = existing_types | set(override_types)
  435. required_filament_types = json.dumps(sorted(all_types))
  436. # Validate quantity
  437. quantity = max(1, data.quantity)
  438. # Create batch if quantity > 1
  439. batch = None
  440. batch_id = None
  441. if quantity > 1:
  442. # Derive batch name from source file
  443. batch_name_base = "Batch"
  444. if archive:
  445. batch_name_base = archive.print_name or archive.filename or "Batch"
  446. elif library_file:
  447. if library_file.file_metadata:
  448. batch_name_base = library_file.file_metadata.get("print_name") or library_file.filename
  449. else:
  450. batch_name_base = library_file.filename
  451. batch_name_base = batch_name_base.replace(".gcode.3mf", "").replace(".3mf", "")
  452. batch = PrintBatch(
  453. name=f"{batch_name_base} ×{quantity}",
  454. archive_id=data.archive_id,
  455. library_file_id=data.library_file_id,
  456. quantity=quantity,
  457. status="active",
  458. created_by_id=current_user.id if current_user else None,
  459. )
  460. db.add(batch)
  461. await db.flush() # Get batch.id before creating items
  462. batch_id = batch.id
  463. # Get next position for this printer (or for unassigned/model-based items)
  464. if data.printer_id is not None:
  465. result = await db.execute(
  466. select(func.max(PrintQueueItem.position))
  467. .where(PrintQueueItem.printer_id == data.printer_id)
  468. .where(PrintQueueItem.status == "pending")
  469. )
  470. else:
  471. # For unassigned/model-based items, get max position across all unassigned
  472. result = await db.execute(
  473. select(func.max(PrintQueueItem.position))
  474. .where(PrintQueueItem.printer_id.is_(None))
  475. .where(PrintQueueItem.status == "pending")
  476. )
  477. max_pos = result.scalar() or 0
  478. # Resolve print_time_seconds for SJF scheduling (cache on item at creation)
  479. cached_print_time = None
  480. if archive:
  481. cached_print_time = archive.print_time_seconds
  482. if data.plate_id:
  483. archive_path = settings.base_dir / archive.file_path
  484. if archive_path.exists():
  485. plate_time = _extract_print_time_from_3mf(archive_path, data.plate_id)
  486. if plate_time is not None:
  487. cached_print_time = plate_time
  488. elif library_file:
  489. if library_file.file_metadata:
  490. cached_print_time = library_file.file_metadata.get("print_time_seconds")
  491. if data.plate_id:
  492. lib_path = Path(library_file.file_path)
  493. library_file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  494. if library_file_path.exists():
  495. plate_time = _extract_print_time_from_3mf(library_file_path, data.plate_id)
  496. if plate_time is not None:
  497. cached_print_time = plate_time
  498. # Validate project exists before insert so a bogus ID yields 404, not an FK-constraint 500
  499. if data.project_id is not None:
  500. project_result = await db.execute(select(Project).where(Project.id == data.project_id))
  501. if not project_result.scalar_one_or_none():
  502. raise HTTPException(status_code=404, detail="Project not found")
  503. ams_mapping_json = json.dumps(data.ams_mapping) if data.ams_mapping else None
  504. items = []
  505. for i in range(quantity):
  506. item = PrintQueueItem(
  507. printer_id=data.printer_id,
  508. target_model=target_model_norm,
  509. target_location=data.target_location,
  510. required_filament_types=required_filament_types,
  511. filament_overrides=filament_overrides_json,
  512. archive_id=data.archive_id,
  513. library_file_id=data.library_file_id,
  514. scheduled_time=data.scheduled_time,
  515. require_previous_success=data.require_previous_success,
  516. auto_off_after=data.auto_off_after,
  517. manual_start=data.manual_start,
  518. skip_filament_check=data.skip_filament_check,
  519. ams_mapping=ams_mapping_json,
  520. plate_id=data.plate_id,
  521. bed_levelling=data.bed_levelling,
  522. flow_cali=data.flow_cali,
  523. vibration_cali=data.vibration_cali,
  524. layer_inspect=data.layer_inspect,
  525. timelapse=data.timelapse,
  526. use_ams=data.use_ams,
  527. nozzle_offset_cali=data.nozzle_offset_cali,
  528. gcode_injection=data.gcode_injection,
  529. project_id=data.project_id,
  530. position=max_pos + 1 + i,
  531. status="pending",
  532. created_by_id=current_user.id if current_user else None,
  533. batch_id=batch_id,
  534. print_time_seconds=cached_print_time,
  535. )
  536. db.add(item)
  537. items.append(item)
  538. await db.commit()
  539. # Refresh the first item for the response
  540. item = items[0]
  541. await db.refresh(item)
  542. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  543. source_name = f"archive {data.archive_id}" if data.archive_id else f"library file {data.library_file_id}"
  544. target_desc = data.printer_id or (f"model {target_model_norm}" if target_model_norm else "unassigned")
  545. qty_desc = f" (×{quantity})" if quantity > 1 else ""
  546. logger.info("Added %s to queue for %s%s", source_name, target_desc, qty_desc)
  547. # MQTT relay - publish queue job added
  548. try:
  549. from backend.app.services.mqtt_relay import mqtt_relay
  550. await mqtt_relay.on_queue_job_added(
  551. job_id=item.id,
  552. filename=item.archive.filename if item.archive else "",
  553. printer_id=item.printer_id,
  554. printer_name=item.printer.name if item.printer else None,
  555. )
  556. except Exception:
  557. pass # Don't fail queue add if MQTT fails
  558. # Send notification for job added
  559. try:
  560. job_name = (
  561. item.archive.filename
  562. if item.archive
  563. else item.library_file.filename
  564. if item.library_file
  565. else f"Job #{item.id}"
  566. )
  567. job_name = job_name.replace(".gcode.3mf", "").replace(".3mf", "")
  568. if quantity > 1:
  569. job_name = f"{job_name} ×{quantity}"
  570. target = (
  571. item.printer.name if item.printer else (f"Any {item.target_model}" if target_model_norm else "Unassigned")
  572. )
  573. await notification_service.on_queue_job_added(
  574. job_name=job_name,
  575. target=target,
  576. db=db,
  577. printer_id=item.printer_id,
  578. printer_name=item.printer.name if item.printer else None,
  579. )
  580. except Exception:
  581. pass # Don't fail queue add if notification fails
  582. return _enrich_response(item)
  583. @router.patch("/bulk", response_model=PrintQueueBulkUpdateResponse)
  584. async def bulk_update_queue_items(
  585. data: PrintQueueBulkUpdate,
  586. db: AsyncSession = Depends(get_db),
  587. auth_result: tuple[User | None, bool] = Depends(
  588. require_ownership_permission(
  589. Permission.QUEUE_UPDATE_ALL,
  590. Permission.QUEUE_UPDATE_OWN,
  591. )
  592. ),
  593. ):
  594. """Bulk update multiple queue items with the same values.
  595. Only pending items can be updated. Non-pending items are skipped.
  596. Items not owned by the user are also skipped (unless user has *_all permission).
  597. """
  598. user, can_modify_all = auth_result
  599. if not data.item_ids:
  600. raise HTTPException(400, "No item IDs provided")
  601. # Get fields to update (exclude item_ids and unset fields)
  602. update_data = data.model_dump(exclude={"item_ids"}, exclude_unset=True)
  603. if not update_data:
  604. raise HTTPException(400, "No fields to update")
  605. # Validate printer_id if being changed
  606. if "printer_id" in update_data and update_data["printer_id"] is not None:
  607. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  608. if not result.scalar_one_or_none():
  609. raise HTTPException(400, "Printer not found")
  610. # Fetch all items
  611. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id.in_(data.item_ids)))
  612. items = result.scalars().all()
  613. updated_count = 0
  614. skipped_count = 0
  615. for item in items:
  616. if item.status != "pending":
  617. skipped_count += 1
  618. continue
  619. # Ownership check
  620. if not can_modify_all and item.created_by_id != user.id:
  621. skipped_count += 1
  622. continue
  623. for field, value in update_data.items():
  624. setattr(item, field, value)
  625. updated_count += 1
  626. await db.commit()
  627. logger.info("Bulk updated %s queue items, skipped %s", updated_count, skipped_count)
  628. return PrintQueueBulkUpdateResponse(
  629. updated_count=updated_count,
  630. skipped_count=skipped_count,
  631. message=f"Updated {updated_count} items"
  632. + (f", skipped {skipped_count} non-pending/not-owned" if skipped_count else ""),
  633. )
  634. # --- Batch endpoints ---
  635. @router.get("/batches", response_model=list[PrintBatchResponse])
  636. async def list_batches(
  637. status: str | None = Query(None, description="Filter by status (active, completed, cancelled)"),
  638. db: AsyncSession = Depends(get_db),
  639. auth_result: tuple[User | None, bool] = Depends(
  640. require_ownership_permission(
  641. Permission.QUEUE_READ_ALL,
  642. Permission.QUEUE_READ_OWN,
  643. )
  644. ),
  645. ):
  646. """List all print batches with progress stats."""
  647. current_user, can_read_all = auth_result
  648. query = select(PrintBatch).order_by(PrintBatch.created_at.desc())
  649. if status:
  650. query = query.where(PrintBatch.status == status)
  651. if current_user is not None and not can_read_all:
  652. query = query.where(PrintBatch.created_by_id == current_user.id)
  653. result = await db.execute(query)
  654. batches = result.scalars().all()
  655. responses = []
  656. for batch in batches:
  657. responses.append(await _build_batch_response(db, batch))
  658. return responses
  659. @router.get("/batches/{batch_id}", response_model=PrintBatchResponse)
  660. async def get_batch(
  661. batch_id: int,
  662. db: AsyncSession = Depends(get_db),
  663. auth_result: tuple[User | None, bool] = Depends(
  664. require_ownership_permission(
  665. Permission.QUEUE_READ_ALL,
  666. Permission.QUEUE_READ_OWN,
  667. )
  668. ),
  669. ):
  670. """Get a print batch with progress stats."""
  671. current_user, can_read_all = auth_result
  672. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  673. batch = result.scalar_one_or_none()
  674. if not batch:
  675. raise HTTPException(404, "Batch not found")
  676. if (
  677. current_user is not None
  678. and not can_read_all
  679. and (batch.created_by_id is None or batch.created_by_id != current_user.id)
  680. ):
  681. raise HTTPException(404, "Batch not found")
  682. return await _build_batch_response(db, batch)
  683. @router.delete("/batches/{batch_id}")
  684. async def cancel_batch(
  685. batch_id: int,
  686. db: AsyncSession = Depends(get_db),
  687. current_user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_DELETE_ALL),
  688. ):
  689. """Cancel all pending items in a batch and mark batch as cancelled."""
  690. result = await db.execute(select(PrintBatch).where(PrintBatch.id == batch_id))
  691. batch = result.scalar_one_or_none()
  692. if not batch:
  693. raise HTTPException(404, "Batch not found")
  694. # Cancel all pending queue items in this batch
  695. result = await db.execute(
  696. select(PrintQueueItem).where(and_(PrintQueueItem.batch_id == batch_id, PrintQueueItem.status == "pending"))
  697. )
  698. pending_items = result.scalars().all()
  699. cancelled_count = 0
  700. for item in pending_items:
  701. item.status = "cancelled"
  702. cancelled_count += 1
  703. batch.status = "cancelled"
  704. await db.commit()
  705. return {"message": f"Batch cancelled, {cancelled_count} pending items cancelled"}
  706. async def _build_batch_response(db: AsyncSession, batch: PrintBatch) -> PrintBatchResponse:
  707. """Build a batch response with derived counts from queue items."""
  708. # Count queue items by status
  709. result = await db.execute(
  710. select(PrintQueueItem.status, func.count(PrintQueueItem.id))
  711. .where(PrintQueueItem.batch_id == batch.id)
  712. .group_by(PrintQueueItem.status)
  713. )
  714. status_counts = {row[0]: row[1] for row in result.fetchall()}
  715. # Load created_by for username
  716. created_by_username = None
  717. if batch.created_by_id:
  718. result = await db.execute(select(User).where(User.id == batch.created_by_id))
  719. user = result.scalar_one_or_none()
  720. if user:
  721. created_by_username = user.username
  722. return PrintBatchResponse(
  723. id=batch.id,
  724. name=batch.name,
  725. archive_id=batch.archive_id,
  726. library_file_id=batch.library_file_id,
  727. quantity=batch.quantity,
  728. status=batch.status,
  729. created_at=batch.created_at,
  730. created_by_id=batch.created_by_id,
  731. created_by_username=created_by_username,
  732. pending_count=status_counts.get("pending", 0),
  733. printing_count=status_counts.get("printing", 0),
  734. completed_count=status_counts.get("completed", 0),
  735. failed_count=status_counts.get("failed", 0),
  736. cancelled_count=status_counts.get("cancelled", 0),
  737. )
  738. @router.get("/{item_id}", response_model=PrintQueueItemResponse)
  739. async def get_queue_item(
  740. item_id: int,
  741. db: AsyncSession = Depends(get_db),
  742. auth_result: tuple[User | None, bool] = Depends(
  743. require_ownership_permission(
  744. Permission.QUEUE_READ_ALL,
  745. Permission.QUEUE_READ_OWN,
  746. )
  747. ),
  748. ):
  749. """Get a specific queue item."""
  750. current_user, can_read_all = auth_result
  751. result = await db.execute(
  752. select(PrintQueueItem)
  753. .options(
  754. selectinload(PrintQueueItem.archive),
  755. selectinload(PrintQueueItem.printer),
  756. selectinload(PrintQueueItem.library_file),
  757. selectinload(PrintQueueItem.created_by),
  758. selectinload(PrintQueueItem.batch),
  759. )
  760. .where(PrintQueueItem.id == item_id)
  761. )
  762. item = result.scalar_one_or_none()
  763. if not item:
  764. raise HTTPException(404, "Queue item not found")
  765. if (
  766. current_user is not None
  767. and not can_read_all
  768. and (item.created_by_id is None or item.created_by_id != current_user.id)
  769. ):
  770. raise HTTPException(404, "Queue item not found")
  771. return _enrich_response(item)
  772. @router.patch("/{item_id}", response_model=PrintQueueItemResponse)
  773. async def update_queue_item(
  774. item_id: int,
  775. data: PrintQueueItemUpdate,
  776. db: AsyncSession = Depends(get_db),
  777. auth_result: tuple[User | None, bool] = Depends(
  778. require_ownership_permission(
  779. Permission.QUEUE_UPDATE_ALL,
  780. Permission.QUEUE_UPDATE_OWN,
  781. )
  782. ),
  783. ):
  784. """Update a queue item."""
  785. user, can_modify_all = auth_result
  786. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  787. item = result.scalar_one_or_none()
  788. if not item:
  789. raise HTTPException(404, "Queue item not found")
  790. # Ownership check
  791. if not can_modify_all:
  792. if item.created_by_id != user.id:
  793. raise HTTPException(403, "You can only update your own queue items")
  794. if item.status != "pending":
  795. raise HTTPException(400, "Can only update pending items")
  796. update_data = data.model_dump(exclude_unset=True)
  797. # Normalize target_model if being updated
  798. if "target_model" in update_data and update_data["target_model"]:
  799. update_data["target_model"] = (
  800. normalize_printer_model(update_data["target_model"])
  801. or normalize_printer_model_id(update_data["target_model"])
  802. or update_data["target_model"]
  803. )
  804. # Cannot specify both printer_id and target_model
  805. new_printer_id = update_data.get("printer_id", item.printer_id)
  806. new_target_model = update_data.get("target_model", item.target_model)
  807. if new_printer_id and new_target_model:
  808. raise HTTPException(400, "Cannot specify both printer_id and target_model")
  809. # Validate new printer_id if being changed (and not None)
  810. if "printer_id" in update_data and update_data["printer_id"] is not None:
  811. result = await db.execute(select(Printer).where(Printer.id == update_data["printer_id"]))
  812. if not result.scalar_one_or_none():
  813. raise HTTPException(400, "Printer not found")
  814. # Validate target_model has active printers
  815. if "target_model" in update_data and update_data["target_model"]:
  816. result = await db.execute(
  817. select(Printer).where(Printer.model == update_data["target_model"]).where(Printer.is_active == True) # noqa: E712
  818. )
  819. if not result.scalars().first():
  820. raise HTTPException(400, f"No active printers for model: {update_data['target_model']}")
  821. # Serialize ams_mapping to JSON for TEXT column storage
  822. if "ams_mapping" in update_data:
  823. update_data["ams_mapping"] = json.dumps(update_data["ams_mapping"]) if update_data["ams_mapping"] else None
  824. # Serialize filament_overrides to JSON for TEXT column storage
  825. if "filament_overrides" in update_data:
  826. update_data["filament_overrides"] = (
  827. json.dumps(update_data["filament_overrides"]) if update_data["filament_overrides"] else None
  828. )
  829. for field, value in update_data.items():
  830. setattr(item, field, value)
  831. await db.commit()
  832. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  833. logger.info("Updated queue item %s", item_id)
  834. return _enrich_response(item)
  835. @router.delete("/{item_id}")
  836. async def delete_queue_item(
  837. item_id: int,
  838. db: AsyncSession = Depends(get_db),
  839. auth_result: tuple[User | None, bool] = Depends(
  840. require_ownership_permission(
  841. Permission.QUEUE_DELETE_ALL,
  842. Permission.QUEUE_DELETE_OWN,
  843. )
  844. ),
  845. ):
  846. """Remove an item from the queue."""
  847. user, can_modify_all = auth_result
  848. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  849. item = result.scalar_one_or_none()
  850. if not item:
  851. raise HTTPException(404, "Queue item not found")
  852. # Ownership check
  853. if not can_modify_all:
  854. if item.created_by_id != user.id:
  855. raise HTTPException(403, "You can only delete your own queue items")
  856. if item.status == "printing":
  857. raise HTTPException(400, "Cannot delete item that is currently printing")
  858. await db.delete(item)
  859. await db.commit()
  860. logger.info("Deleted queue item %s", item_id)
  861. return {"message": "Queue item deleted"}
  862. @router.post("/reorder")
  863. async def reorder_queue(
  864. data: PrintQueueReorder,
  865. db: AsyncSession = Depends(get_db),
  866. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  867. ):
  868. """Bulk update positions for queue items."""
  869. for reorder_item in data.items:
  870. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == reorder_item.id))
  871. item = result.scalar_one_or_none()
  872. if item and item.status == "pending":
  873. item.position = reorder_item.position
  874. await db.commit()
  875. logger.info("Reordered %s queue items", len(data.items))
  876. return {"message": f"Reordered {len(data.items)} items"}
  877. @router.post("/{item_id}/cancel")
  878. async def cancel_queue_item(
  879. item_id: int,
  880. db: AsyncSession = Depends(get_db),
  881. auth_result: tuple[User | None, bool] = Depends(
  882. require_ownership_permission(
  883. Permission.QUEUE_UPDATE_ALL,
  884. Permission.QUEUE_UPDATE_OWN,
  885. )
  886. ),
  887. ):
  888. """Cancel a pending queue item."""
  889. user, can_modify_all = auth_result
  890. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  891. item = result.scalar_one_or_none()
  892. if not item:
  893. raise HTTPException(404, "Queue item not found")
  894. # Ownership check
  895. if not can_modify_all:
  896. if item.created_by_id != user.id:
  897. raise HTTPException(403, "You can only cancel your own queue items")
  898. if item.status not in ("pending",):
  899. raise HTTPException(400, f"Cannot cancel item with status '{item.status}'")
  900. item.status = "cancelled"
  901. item.completed_at = datetime.now(timezone.utc)
  902. await db.commit()
  903. logger.info("Cancelled queue item %s", item_id)
  904. return {"message": "Queue item cancelled"}
  905. @router.post("/{item_id}/stop")
  906. async def stop_queue_item(
  907. item_id: int,
  908. db: AsyncSession = Depends(get_db),
  909. _: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_ALL),
  910. ):
  911. """Stop an actively printing queue item."""
  912. from backend.app.models.smart_plug import SmartPlug
  913. from backend.app.services.printer_manager import printer_manager
  914. from backend.app.services.tasmota import tasmota_service
  915. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  916. item = result.scalar_one_or_none()
  917. if not item:
  918. raise HTTPException(404, "Queue item not found")
  919. if item.status != "printing":
  920. raise HTTPException(400, f"Can only stop items that are printing, current status: '{item.status}'")
  921. # Capture values we need for background task
  922. printer_id = item.printer_id
  923. auto_off_after = item.auto_off_after
  924. # Try to send stop command to printer
  925. stop_sent = False
  926. try:
  927. stop_sent = printer_manager.stop_print(printer_id)
  928. if not stop_sent:
  929. logger.warning("stop_print returned False for printer %s - printer may not be connected", printer_id)
  930. except Exception as e:
  931. logger.error("Error sending stop command for queue item %s: %s", item_id, e)
  932. # Mark this printer as user-stopped BEFORE the first await so that if the
  933. # MQTT on_print_complete callback fires during the db.commit() yield the flag
  934. # is already set and the "failed" status will be correctly overridden to
  935. # "cancelled" (preventing a spurious "print failed" notification).
  936. try:
  937. from backend.app.main import mark_printer_stopped_by_user
  938. mark_printer_stopped_by_user(printer_id)
  939. except Exception as _mark_err:
  940. logger.warning("Failed to mark printer %s as user-stopped: %s", printer_id, _mark_err)
  941. # Update queue item status regardless - if printer is off, print is already stopped
  942. item.status = "cancelled"
  943. item.completed_at = datetime.now(timezone.utc)
  944. item.error_message = "Stopped by user" if stop_sent else "Stopped by user (printer was offline)"
  945. await db.commit()
  946. # Get smart plug info if auto-off is enabled
  947. plug_ip = None
  948. if auto_off_after:
  949. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  950. plug = result.scalar_one_or_none()
  951. if plug and plug.enabled:
  952. plug_ip = plug.ip_address
  953. logger.info("Stopped printing queue item %s (stop command sent: %s)", item_id, stop_sent)
  954. # Schedule background task for cooldown + power off
  955. if plug_ip:
  956. async def cooldown_and_poweroff():
  957. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", printer_id)
  958. await printer_manager.wait_for_cooldown(printer_id, target_temp=50.0, timeout=600)
  959. # Re-fetch plug since we're in a new async context
  960. from backend.app.core.database import async_session
  961. async with async_session() as new_db:
  962. result = await new_db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  963. plug = result.scalar_one_or_none()
  964. if plug and plug.enabled:
  965. logger.info("Auto-off: Powering off printer %s", printer_id)
  966. await tasmota_service.turn_off(plug)
  967. spawn_background_task(cooldown_and_poweroff(), name=f"queue-cooldown-poweroff-{printer_id}")
  968. return {"message": "Print stopped" if stop_sent else "Queue item cancelled (printer was offline)"}
  969. @router.post("/{item_id}/start")
  970. async def start_queue_item(
  971. item_id: int,
  972. skip_filament_check: bool = Query(default=False),
  973. db: AsyncSession = Depends(get_db),
  974. user: User | None = RequirePermissionIfAuthEnabled(Permission.QUEUE_UPDATE_OWN),
  975. ):
  976. """Manually start a staged (manual_start) queue item.
  977. Clears the manual_start flag so the scheduler picks it up. When
  978. ``skip_filament_check`` is false (the default) the live filament
  979. deficit (#1496) is checked first — if the assigned spool can't satisfy
  980. a slot's required grams, the route returns ``409`` with the deficit
  981. payload so the caller can show a confirm dialog and retry with
  982. ``skip_filament_check=true``.
  983. """
  984. result = await db.execute(
  985. select(PrintQueueItem)
  986. .options(
  987. selectinload(PrintQueueItem.archive),
  988. selectinload(PrintQueueItem.printer),
  989. selectinload(PrintQueueItem.library_file),
  990. selectinload(PrintQueueItem.batch),
  991. )
  992. .where(PrintQueueItem.id == item_id)
  993. )
  994. item = result.scalar_one_or_none()
  995. if not item:
  996. raise HTTPException(404, "Queue item not found")
  997. if item.status != "pending":
  998. raise HTTPException(400, f"Can only start pending items, current status: '{item.status}'")
  999. # Live deficit check — re-evaluated against current spool state, so a
  1000. # spool swap between scheduler flagging and the user clicking ▶ clears
  1001. # the block automatically.
  1002. if not skip_filament_check:
  1003. deficit = await compute_deficit_for_queue_item(db, item)
  1004. if deficit:
  1005. raise HTTPException(
  1006. status_code=409,
  1007. detail={
  1008. "code": "insufficient_filament",
  1009. "deficit": [d.to_dict() for d in deficit],
  1010. },
  1011. )
  1012. # Print Anyway / no deficit: clear the flags and let the scheduler dispatch.
  1013. item.manual_start = False
  1014. item.filament_short = False
  1015. # Persist the user's "Print Anyway" decision so the scheduler does not
  1016. # immediately re-flag this item on the next tick (#1698-followup). The
  1017. # pre-fix behaviour bounced between "user said anyway" and
  1018. # "scheduler re-blocked on same deficit" forever.
  1019. if skip_filament_check:
  1020. item.skip_filament_check = True
  1021. # Credit the clicker as the item's owner when no prior owner is set —
  1022. # VP-uploaded queue items arrive over FTP unattributed, so without this
  1023. # the print log's User column stays blank even when auth is on
  1024. # (#1670). An item that already has a creator (UI-added queue items)
  1025. # keeps that attribution; the dispatcher is not promoted over the
  1026. # original uploader.
  1027. if user is not None and item.created_by_id is None:
  1028. item.created_by_id = user.id
  1029. await db.commit()
  1030. await db.refresh(item, ["archive", "printer", "library_file", "created_by", "batch"])
  1031. logger.info(
  1032. "Manually started queue item %s (cleared manual_start; skip_filament_check=%s)",
  1033. item_id,
  1034. skip_filament_check,
  1035. )
  1036. return _enrich_response(item)