projects.py 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194
  1. import io
  2. import json
  3. import logging
  4. import os
  5. import uuid
  6. import zipfile
  7. from collections.abc import Sequence
  8. from dataclasses import dataclass, fields
  9. from datetime import datetime
  10. from pathlib import Path
  11. from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
  12. from fastapi.responses import FileResponse, StreamingResponse
  13. from sqlalchemy import and_, case, func, or_, select, update
  14. from sqlalchemy.ext.asyncio import AsyncSession
  15. from sqlalchemy.orm import selectinload
  16. from backend.app.api.routes.library import (
  17. classify_file_type,
  18. get_library_dir,
  19. get_library_files_dir,
  20. to_absolute_path,
  21. to_relative_path,
  22. )
  23. from backend.app.core.auth import (
  24. ApiKeyActor,
  25. RequestActor,
  26. RequestPrinterScope,
  27. RequirePermissionIfAuthEnabled,
  28. require_media_token_permission,
  29. )
  30. from backend.app.core.config import settings
  31. from backend.app.core.database import get_db
  32. from backend.app.core.permissions import Permission
  33. from backend.app.core.printer_scope import PrinterScope
  34. from backend.app.models.archive import PrintArchive
  35. from backend.app.models.library import LibraryFile, LibraryFolder
  36. from backend.app.models.print_log import PrintLogEntry
  37. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  38. from backend.app.models.project import PROJECT_PRIORITIES, PROJECT_STATUSES, Project
  39. from backend.app.models.project_bom import ProjectBOMItem
  40. from backend.app.models.user import User
  41. from backend.app.schemas.project import (
  42. ArchivePreview,
  43. BatchAddArchives,
  44. BatchAddQueueItems,
  45. BOMItemCreate,
  46. BOMItemResponse,
  47. BOMItemUpdate,
  48. ProjectChildPreview,
  49. ProjectCreate,
  50. ProjectFileProgress,
  51. ProjectImport,
  52. ProjectListResponse,
  53. ProjectResponse,
  54. ProjectStats,
  55. ProjectUpdate,
  56. TimelineEvent,
  57. )
  58. from backend.app.services.library_folder_access import load_folder_index, visible_folder_ids
  59. from backend.app.utils.http import build_content_disposition
  60. from backend.app.utils.safe_path import PathTraversalError, safe_join_under
  61. logger = logging.getLogger(__name__)
  62. router = APIRouter(prefix="/projects", tags=["projects"])
  63. def _imported_priority(value: object) -> str:
  64. """An imported project's priority: one the editor accepts, else "normal"."""
  65. return value if isinstance(value, str) and value in PROJECT_PRIORITIES else "normal"
  66. def _imported_status(value: object) -> str:
  67. """An imported project's status: one the editor accepts, else "active"."""
  68. return value if isinstance(value, str) and value in PROJECT_STATUSES else "active"
  69. _FAILURE_STATUSES = ("failed", "aborted", "cancelled", "stopped")
  70. # A completed run whose user verdict is 'reject' (#1898) finished on the
  71. # machine but produced scrap — everywhere a project counts good parts, that
  72. # run must not contribute. NULL verdict (never asked / not answered) counts
  73. # as good, matching behaviour before the feature existed.
  74. _NOT_REJECTED = or_(PrintLogEntry.user_verdict.is_(None), PrintLogEntry.user_verdict != "reject")
  75. # Soft-deleted archives (#1343) keep their row — and therefore their
  76. # ``project_id`` — after their files have been removed from disk, so that global
  77. # Quick Stats can still count their filament / time / cost. Nothing in this
  78. # module filtered on that, which left deleted prints listed on the project with
  79. # thumbnails pointing at files that no longer exist, and no way to unassign them
  80. # (the only unassign UI lives on the Archives page, which correctly hides them)
  81. # — #2731.
  82. #
  83. # Every project-scoped query filters them out, counts included: a project that
  84. # lists 11 prints must not claim 12. That is a deliberate divergence from the
  85. # global Quick Stats behaviour, where the whole point of the soft delete is that
  86. # the contribution survives. A project is a piece of work with a definite
  87. # membership, not a lifetime total, so a print the user deleted has left it.
  88. _LIVE_ARCHIVE = PrintArchive.deleted_at.is_(None)
  89. @dataclass
  90. class _ProjectTotals:
  91. """Raw per-project aggregates, before targets turn them into percentages.
  92. Kept addable so a master project's numbers are the plain sum of its own
  93. and every descendant's (#1264) — no second set of SQL that could drift
  94. from the single-project path.
  95. """
  96. total_runs: int = 0
  97. total_items: int = 0
  98. completed_items: int = 0
  99. failed_runs: int = 0
  100. total_time_seconds: float = 0.0
  101. total_filament_grams: float = 0.0
  102. filament_cost: float = 0.0
  103. energy_kwh: float = 0.0
  104. energy_cost: float = 0.0
  105. wear_cost: float = 0.0
  106. queued_prints: int = 0
  107. in_progress_prints: int = 0
  108. bom_total_items: int = 0
  109. bom_completed_items: int = 0
  110. bom_cost: float = 0.0
  111. def __add__(self, other: "_ProjectTotals") -> "_ProjectTotals":
  112. return _ProjectTotals(
  113. **{f.name: getattr(self, f.name) + getattr(other, f.name) for f in fields(_ProjectTotals)}
  114. )
  115. async def _load_totals(db: AsyncSession, project_ids: Sequence[int]) -> dict[int, _ProjectTotals]:
  116. """Aggregate prints, queue and BOM for several projects at once.
  117. Grouped rather than one round trip per project because a master project
  118. has to aggregate its whole subtree, and the sub-project list shows each
  119. branch's own roll-up alongside it (#1264).
  120. Aggregates from ``print_log_entries`` joined to ``print_archives`` so
  121. every actual run contributes — pre-fix this counted ``print_archives``
  122. (one row per file), which under-reported every reprint by collapsing
  123. runs back into the source file (#1593). The Archive Print Log view
  124. already drives off the same source (``archives.py::list_archives_slim``),
  125. so project stats now stay aligned with the per-archive numbers.
  126. Orphan log entries (``archive_id IS NULL`` after archive deletion via
  127. ``ON DELETE SET NULL``) are excluded by the inner join — they can't
  128. be attributed to a project.
  129. Projects with nothing recorded are absent from every grouped result, so
  130. the caller gets a zeroed ``_ProjectTotals`` for them rather than a KeyError.
  131. """
  132. totals: dict[int, _ProjectTotals] = {pid: _ProjectTotals() for pid in project_ids}
  133. if not totals:
  134. return totals
  135. # Per-run aggregates. Each run's duration, filament, cost, and energy come
  136. # from the log row, not the source archive — so multi-plate 3MFs and
  137. # reprints both count correctly. The total/completed/failed splits are all
  138. # per-run too: quantity is summed per run, while failures are counted as
  139. # runs rather than parts.
  140. log_rows = await db.execute(
  141. select(
  142. PrintArchive.project_id.label("project_id"),
  143. func.count(PrintLogEntry.id).label("total_runs"),
  144. func.coalesce(func.sum(PrintLogEntry.duration_seconds), 0).label("total_time"),
  145. func.coalesce(func.sum(PrintLogEntry.filament_used_grams), 0).label("total_filament"),
  146. func.coalesce(func.sum(PrintLogEntry.cost), 0).label("total_filament_cost"),
  147. func.coalesce(func.sum(PrintLogEntry.energy_kwh), 0).label("total_energy"),
  148. func.coalesce(func.sum(PrintLogEntry.energy_cost), 0).label("total_energy_cost"),
  149. func.coalesce(func.sum(PrintLogEntry.wear_cost), 0).label("total_wear_cost"),
  150. func.coalesce(func.sum(PrintArchive.quantity), 0).label("total_items"),
  151. # A completed run the user marked as reject (#1898) produced no
  152. # usable parts — keep it out of the good-parts count.
  153. func.coalesce(
  154. func.sum(
  155. case((and_(PrintLogEntry.status == "completed", _NOT_REJECTED), PrintArchive.quantity), else_=0)
  156. ),
  157. 0,
  158. ).label("completed_items"),
  159. func.coalesce(
  160. func.sum(case((PrintLogEntry.status.in_(_FAILURE_STATUSES), 1), else_=0)),
  161. 0,
  162. ).label("failed_runs"),
  163. )
  164. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  165. .where(PrintArchive.project_id.in_(list(totals)), _LIVE_ARCHIVE)
  166. .group_by(PrintArchive.project_id)
  167. )
  168. for row in log_rows:
  169. entry = totals[row.project_id]
  170. entry.total_runs = int(row.total_runs or 0)
  171. entry.total_time_seconds = float(row.total_time or 0)
  172. entry.total_filament_grams = float(row.total_filament or 0)
  173. entry.filament_cost = float(row.total_filament_cost or 0)
  174. entry.energy_kwh = float(row.total_energy or 0)
  175. entry.energy_cost = float(row.total_energy_cost or 0)
  176. entry.wear_cost = float(row.total_wear_cost or 0)
  177. entry.total_items = int(row.total_items or 0)
  178. entry.completed_items = int(row.completed_items or 0)
  179. entry.failed_runs = int(row.failed_runs or 0)
  180. queue_rows = await db.execute(
  181. select(
  182. PrintQueueItem.project_id.label("project_id"),
  183. func.coalesce(func.sum(case((PrintQueueItem.status == "pending", 1), else_=0)), 0).label("queued"),
  184. func.coalesce(func.sum(case((PrintQueueItem.status == "printing", 1), else_=0)), 0).label("in_progress"),
  185. )
  186. .where(PrintQueueItem.project_id.in_(list(totals)))
  187. .group_by(PrintQueueItem.project_id)
  188. )
  189. for row in queue_rows:
  190. entry = totals[row.project_id]
  191. entry.queued_prints = int(row.queued or 0)
  192. entry.in_progress_prints = int(row.in_progress or 0)
  193. bom_rows = await db.execute(
  194. select(
  195. ProjectBOMItem.project_id.label("project_id"),
  196. func.count(ProjectBOMItem.id).label("total"),
  197. func.sum(case((ProjectBOMItem.quantity_acquired >= ProjectBOMItem.quantity_needed, 1), else_=0)).label(
  198. "completed"
  199. ),
  200. func.coalesce(func.sum(ProjectBOMItem.unit_price * ProjectBOMItem.quantity_needed), 0).label("bom_cost"),
  201. )
  202. .where(ProjectBOMItem.project_id.in_(list(totals)))
  203. .group_by(ProjectBOMItem.project_id)
  204. )
  205. for row in bom_rows:
  206. entry = totals[row.project_id]
  207. entry.bom_total_items = int(row.total or 0)
  208. entry.bom_completed_items = int(row.completed or 0)
  209. entry.bom_cost = float(row.bom_cost or 0)
  210. return totals
  211. def _stats_from_totals(
  212. totals: _ProjectTotals, target_count: int | None = None, target_parts_count: int | None = None
  213. ) -> ProjectStats:
  214. """Turn raw aggregates into the response shape, applying the targets."""
  215. # Calculate progress for plates (target_count vs total_archives)
  216. progress_percent = None
  217. remaining_prints = None
  218. if target_count and target_count > 0:
  219. progress_percent = round((totals.total_runs / target_count) * 100, 1)
  220. remaining_prints = max(0, target_count - totals.total_runs)
  221. # Calculate progress for parts (target_parts_count vs completed_items)
  222. parts_progress_percent = None
  223. remaining_parts = None
  224. if target_parts_count and target_parts_count > 0:
  225. parts_progress_percent = round((totals.completed_items / target_parts_count) * 100, 1)
  226. remaining_parts = max(0, target_parts_count - totals.completed_items)
  227. return ProjectStats(
  228. total_archives=totals.total_runs,
  229. total_items=totals.total_items,
  230. completed_prints=totals.completed_items, # Sum of quantities for completed prints
  231. failed_prints=totals.failed_runs,
  232. queued_prints=totals.queued_prints,
  233. in_progress_prints=totals.in_progress_prints,
  234. total_print_time_hours=round(totals.total_time_seconds / 3600, 2),
  235. total_filament_grams=round(totals.total_filament_grams, 2),
  236. progress_percent=progress_percent,
  237. parts_progress_percent=parts_progress_percent,
  238. estimated_cost=round(totals.filament_cost, 2),
  239. total_energy_kwh=round(totals.energy_kwh, 3),
  240. total_energy_cost=round(totals.energy_cost, 3),
  241. total_wear_cost=round(totals.wear_cost, 3),
  242. remaining_prints=remaining_prints,
  243. remaining_parts=remaining_parts,
  244. bom_total_items=totals.bom_total_items,
  245. bom_completed_items=totals.bom_completed_items,
  246. bom_cost=round(totals.bom_cost, 2),
  247. )
  248. async def compute_project_stats(
  249. db: AsyncSession, project_id: int, target_count: int | None = None, target_parts_count: int | None = None
  250. ) -> ProjectStats:
  251. """Compute statistics for a single project, excluding any sub-projects.
  252. Sub-project roll-ups go through ``compute_subtree_stats`` instead. This
  253. stays own-prints-only on purpose: it is what every existing caller means
  254. by "this project's numbers", and widening it would silently restate the
  255. figures of anyone who had already nested projects over the API.
  256. """
  257. totals = (await _load_totals(db, [project_id]))[project_id]
  258. return _stats_from_totals(totals, target_count, target_parts_count)
  259. def _descendants_of(children: dict[int, list[int]], root_id: int) -> list[int]:
  260. """Every project nested under ``root_id``, at any depth, root excluded.
  261. Walked in Python off one already-fetched parent map rather than a recursive
  262. CTE, so SQLite and PostgreSQL stay on identical code paths.
  263. ``seen`` is not belt-and-braces. ``update_project`` only ever rejected a
  264. project as its own *direct* parent, so any database written before that
  265. guard was widened can hold A -> B -> A, and an unguarded walk over one
  266. would never terminate.
  267. """
  268. found: list[int] = []
  269. seen = {root_id}
  270. stack = [root_id]
  271. while stack:
  272. for child in children.get(stack.pop(), ()):
  273. if child in seen:
  274. continue
  275. seen.add(child)
  276. found.append(child)
  277. stack.append(child)
  278. return found
  279. async def _project_descendants(db: AsyncSession, root_id: int) -> list[int]:
  280. """``_descendants_of`` for callers that only need the ids, not the totals."""
  281. rows = (await db.execute(select(Project.id, Project.parent_id).where(Project.parent_id.is_not(None)))).all()
  282. children: dict[int, list[int]] = {}
  283. for pid, parent_id in rows:
  284. children.setdefault(parent_id, []).append(pid)
  285. return _descendants_of(children, root_id)
  286. @dataclass
  287. class _SubtreeReport:
  288. """What the detail endpoint needs to describe a project and its tree."""
  289. descendant_count: int
  290. # None when the project has no sub-projects: the roll-up would be identical
  291. # to the project's own stats, and the UI uses its absence to stay quiet
  292. # rather than showing a second, equal set of numbers.
  293. rollup: ProjectStats | None
  294. child_previews: list[ProjectChildPreview]
  295. async def compute_subtree_stats(db: AsyncSession, root_id: int) -> _SubtreeReport:
  296. """Roll a project's own numbers up with every sub-project beneath it (#1264).
  297. Four queries regardless of tree size or depth: one for the parent map, then
  298. the three grouped aggregates in ``_load_totals`` covering the whole subtree
  299. at once. Each direct child's preview carries *its* branch's roll-up, so the
  300. listed rows add up to the master's total minus the master's own prints.
  301. """
  302. rows = (
  303. await db.execute(
  304. select(
  305. Project.id,
  306. Project.parent_id,
  307. Project.name,
  308. Project.color,
  309. Project.status,
  310. Project.target_count,
  311. Project.target_parts_count,
  312. )
  313. )
  314. ).all()
  315. by_id = {row.id: row for row in rows}
  316. children: dict[int, list[int]] = {}
  317. for row in rows:
  318. if row.parent_id is not None:
  319. children.setdefault(row.parent_id, []).append(row.id)
  320. descendants = _descendants_of(children, root_id)
  321. if not descendants:
  322. return _SubtreeReport(descendant_count=0, rollup=None, child_previews=[])
  323. totals = await _load_totals(db, [root_id, *descendants])
  324. def branch(node_id: int) -> tuple[_ProjectTotals, list[int]]:
  325. """Totals for ``node_id`` plus everything under it, and that id list."""
  326. ids = [node_id, *_descendants_of(children, node_id)]
  327. summed = _ProjectTotals()
  328. for pid in ids:
  329. summed = summed + totals[pid]
  330. return summed, ids
  331. def summed_target(ids: Sequence[int], attr: str) -> int | None:
  332. """Targets add up across the tree; all-unset stays unset, not zero."""
  333. total = sum(getattr(by_id[pid], attr) or 0 for pid in ids)
  334. return total or None
  335. subtree_ids = [root_id, *descendants]
  336. root_totals, _ = branch(root_id)
  337. rollup = _stats_from_totals(
  338. root_totals,
  339. summed_target(subtree_ids, "target_count"),
  340. summed_target(subtree_ids, "target_parts_count"),
  341. )
  342. previews: list[ProjectChildPreview] = []
  343. for child_id in sorted(children.get(root_id, ()), key=lambda cid: by_id[cid].name):
  344. child = by_id[child_id]
  345. child_totals, child_ids = branch(child_id)
  346. # Progress here is runs-against-plate-target, matching what the child's
  347. # own page reports. It used to be completed *quantities* against the
  348. # same target, so a row's percentage disagreed with the page it linked
  349. # to.
  350. child_stats = _stats_from_totals(child_totals, summed_target(child_ids, "target_count"))
  351. previews.append(
  352. ProjectChildPreview(
  353. id=child.id,
  354. name=child.name,
  355. color=child.color,
  356. status=child.status,
  357. progress_percent=child_stats.progress_percent,
  358. descendant_count=len(child_ids) - 1,
  359. total_archives=child_stats.total_archives,
  360. completed_prints=child_stats.completed_prints,
  361. total_print_time_hours=child_stats.total_print_time_hours,
  362. total_filament_grams=child_stats.total_filament_grams,
  363. total_cost=round(
  364. child_stats.estimated_cost
  365. + child_stats.total_energy_cost
  366. + child_stats.total_wear_cost
  367. + child_stats.bom_cost,
  368. 2,
  369. ),
  370. )
  371. )
  372. return _SubtreeReport(descendant_count=len(descendants), rollup=rollup, child_previews=previews)
  373. @router.get("", response_model=list[ProjectListResponse])
  374. @router.get("/", response_model=list[ProjectListResponse])
  375. async def list_projects(
  376. status: str | None = None,
  377. db: AsyncSession = Depends(get_db),
  378. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  379. printer_scope: PrinterScope = RequestPrinterScope,
  380. ):
  381. """List all projects with basic stats."""
  382. # Archive previews show only archives of the caller's printers, as the
  383. # project's archive list does.
  384. scope_clause = printer_scope.where(PrintArchive.printer_id)
  385. preview_scope = [scope_clause] if scope_clause is not None else []
  386. query = select(Project)
  387. if status:
  388. query = query.where(Project.status == status)
  389. query = query.order_by(Project.updated_at.desc())
  390. result = await db.execute(query)
  391. projects = result.scalars().all()
  392. # Direct sub-project counts for every project in one pass (#1264). Counted
  393. # across all projects rather than the filtered page: a sub-project hidden
  394. # by the status filter is still a sub-project, and a parent that claimed
  395. # none would invite deleting it as if nothing hung off it.
  396. child_counts = dict(
  397. (
  398. await db.execute(
  399. select(Project.parent_id, func.count(Project.id))
  400. .where(Project.parent_id.is_not(None))
  401. .group_by(Project.parent_id)
  402. )
  403. ).all()
  404. )
  405. # Compute quick stats for each project. Same per-run aggregation as
  406. # ``compute_project_stats`` — counts and quantities come from
  407. # ``print_log_entries`` joined to ``print_archives`` so reprints and
  408. # multi-plate prints contribute every run, not just the source file
  409. # (#1593). Quick stats and the full stats endpoint must agree.
  410. response = []
  411. for project in projects:
  412. log_quick_result = await db.execute(
  413. select(
  414. func.count(PrintLogEntry.id).label("archive_count"),
  415. func.coalesce(func.sum(PrintArchive.quantity), 0).label("total_items"),
  416. func.coalesce(
  417. func.sum(
  418. case((and_(PrintLogEntry.status == "completed", _NOT_REJECTED), PrintArchive.quantity), else_=0)
  419. ),
  420. 0,
  421. ).label("completed_count"),
  422. func.coalesce(
  423. func.sum(case((PrintLogEntry.status.in_(_FAILURE_STATUSES), 1), else_=0)),
  424. 0,
  425. ).label("failed_count"),
  426. )
  427. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  428. .where(PrintArchive.project_id == project.id, _LIVE_ARCHIVE)
  429. )
  430. log_quick = log_quick_result.first()
  431. archive_count = int(log_quick.archive_count or 0)
  432. total_items = int(log_quick.total_items or 0)
  433. completed_count = int(log_quick.completed_count or 0)
  434. failed_count = int(log_quick.failed_count or 0)
  435. # Get queue count
  436. queue_count_result = await db.execute(
  437. select(func.count(PrintQueueItem.id)).where(
  438. PrintQueueItem.project_id == project.id,
  439. PrintQueueItem.status.in_(["pending", "printing"]),
  440. )
  441. )
  442. queue_count = queue_count_result.scalar() or 0
  443. # Plates progress: archive_count / target_count
  444. progress_percent = None
  445. if project.target_count and project.target_count > 0:
  446. progress_percent = round((archive_count / project.target_count) * 100, 1)
  447. # Get archive previews (up to 6 most recent)
  448. archives_result = await db.execute(
  449. select(PrintArchive)
  450. .where(PrintArchive.project_id == project.id, _LIVE_ARCHIVE, *preview_scope)
  451. .order_by(PrintArchive.created_at.desc())
  452. .limit(6)
  453. )
  454. archives = archives_result.scalars().all()
  455. archive_previews = [
  456. ArchivePreview(
  457. id=a.id,
  458. print_name=a.print_name,
  459. thumbnail_path=a.thumbnail_path,
  460. status=a.status,
  461. filament_type=a.filament_type,
  462. filament_color=a.filament_color,
  463. )
  464. for a in archives
  465. ]
  466. response.append(
  467. ProjectListResponse(
  468. id=project.id,
  469. name=project.name,
  470. description=project.description,
  471. color=project.color,
  472. status=project.status,
  473. target_count=project.target_count,
  474. target_parts_count=project.target_parts_count,
  475. target_sets=project.target_sets,
  476. budget=project.budget,
  477. tags=project.tags,
  478. due_date=project.due_date,
  479. priority=project.priority,
  480. created_at=project.created_at,
  481. archive_count=archive_count,
  482. total_items=total_items,
  483. completed_count=completed_count,
  484. failed_count=failed_count,
  485. queue_count=queue_count,
  486. progress_percent=progress_percent,
  487. parent_id=project.parent_id,
  488. child_count=child_counts.get(project.id, 0),
  489. archives=archive_previews,
  490. url=project.url,
  491. cover_image_filename=project.cover_image_filename,
  492. )
  493. )
  494. return response
  495. @router.post("/", response_model=ProjectResponse)
  496. async def create_project(
  497. data: ProjectCreate,
  498. db: AsyncSession = Depends(get_db),
  499. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  500. ):
  501. """Create a new project."""
  502. if data.priority not in PROJECT_PRIORITIES:
  503. raise HTTPException(status_code=400, detail="Invalid priority")
  504. # Verify parent exists if specified; 0 is no parent, as on update
  505. data.parent_id = data.parent_id or None
  506. parent_name = None
  507. if data.parent_id:
  508. parent_result = await db.execute(select(Project).where(Project.id == data.parent_id))
  509. parent = parent_result.scalar_one_or_none()
  510. if not parent:
  511. raise HTTPException(status_code=400, detail="Parent project not found")
  512. parent_name = parent.name
  513. project = Project(
  514. name=data.name,
  515. description=data.description,
  516. color=data.color,
  517. target_count=data.target_count,
  518. target_parts_count=data.target_parts_count,
  519. target_sets=data.target_sets,
  520. notes=data.notes,
  521. tags=data.tags,
  522. due_date=data.due_date,
  523. priority=data.priority,
  524. budget=data.budget,
  525. parent_id=data.parent_id,
  526. url=data.url,
  527. )
  528. db.add(project)
  529. await db.flush()
  530. await db.refresh(project)
  531. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  532. return ProjectResponse(
  533. id=project.id,
  534. name=project.name,
  535. description=project.description,
  536. color=project.color,
  537. status=project.status,
  538. target_count=project.target_count,
  539. target_parts_count=project.target_parts_count,
  540. target_sets=project.target_sets,
  541. notes=project.notes,
  542. attachments=project.attachments,
  543. url=project.url,
  544. cover_image_filename=project.cover_image_filename,
  545. tags=project.tags,
  546. due_date=project.due_date,
  547. priority=project.priority,
  548. budget=project.budget,
  549. is_template=project.is_template,
  550. template_source_id=project.template_source_id,
  551. parent_id=project.parent_id,
  552. parent_name=parent_name,
  553. children=[],
  554. created_at=project.created_at,
  555. updated_at=project.updated_at,
  556. stats=stats,
  557. )
  558. # ============ Phase 8: Template Endpoints (Static routes BEFORE dynamic {project_id}) ============
  559. @router.get("/templates", response_model=list[ProjectListResponse])
  560. async def list_templates(
  561. db: AsyncSession = Depends(get_db),
  562. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  563. ):
  564. """List all project templates."""
  565. result = await db.execute(select(Project).where(Project.is_template.is_(True)).order_by(Project.name))
  566. templates = result.scalars().all()
  567. response = []
  568. for project in templates:
  569. # Get archive count
  570. archive_count_result = await db.execute(
  571. select(func.count(PrintArchive.id)).where(PrintArchive.project_id == project.id, _LIVE_ARCHIVE)
  572. )
  573. archive_count = archive_count_result.scalar() or 0
  574. response.append(
  575. ProjectListResponse(
  576. id=project.id,
  577. name=project.name,
  578. description=project.description,
  579. color=project.color,
  580. status=project.status,
  581. target_count=project.target_count,
  582. target_parts_count=project.target_parts_count,
  583. target_sets=project.target_sets,
  584. budget=project.budget,
  585. tags=project.tags,
  586. due_date=project.due_date,
  587. priority=project.priority,
  588. created_at=project.created_at,
  589. archive_count=archive_count,
  590. queue_count=0,
  591. progress_percent=None,
  592. archives=[],
  593. url=project.url,
  594. cover_image_filename=project.cover_image_filename,
  595. )
  596. )
  597. return response
  598. @router.post("/from-template/{template_id}", response_model=ProjectResponse)
  599. async def create_project_from_template(
  600. template_id: int,
  601. name: str = None,
  602. db: AsyncSession = Depends(get_db),
  603. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  604. ):
  605. """Create a new project from a template."""
  606. result = await db.execute(select(Project).where(Project.id == template_id))
  607. template = result.scalar_one_or_none()
  608. if not template:
  609. raise HTTPException(status_code=404, detail="Template not found")
  610. if not template.is_template:
  611. raise HTTPException(status_code=400, detail="Project is not a template")
  612. # Create new project
  613. project = Project(
  614. name=name or template.name.replace(" (Template)", ""),
  615. description=template.description,
  616. color=template.color,
  617. target_count=template.target_count,
  618. target_parts_count=template.target_parts_count,
  619. target_sets=template.target_sets,
  620. notes=template.notes,
  621. tags=template.tags,
  622. priority=template.priority,
  623. budget=template.budget,
  624. is_template=False,
  625. template_source_id=template.id,
  626. url=template.url,
  627. )
  628. db.add(project)
  629. await db.flush()
  630. # Copy BOM items
  631. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == template_id))
  632. bom_items = bom_result.scalars().all()
  633. for item in bom_items:
  634. new_item = ProjectBOMItem(
  635. project_id=project.id,
  636. name=item.name,
  637. quantity_needed=item.quantity_needed,
  638. quantity_acquired=0,
  639. unit_price=item.unit_price,
  640. sourcing_url=item.sourcing_url,
  641. stl_filename=item.stl_filename,
  642. remarks=item.remarks,
  643. sort_order=item.sort_order,
  644. )
  645. db.add(new_item)
  646. await db.flush()
  647. await db.refresh(project)
  648. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  649. return ProjectResponse(
  650. id=project.id,
  651. name=project.name,
  652. description=project.description,
  653. color=project.color,
  654. status=project.status,
  655. target_count=project.target_count,
  656. target_parts_count=project.target_parts_count,
  657. target_sets=project.target_sets,
  658. notes=project.notes,
  659. attachments=project.attachments,
  660. url=project.url,
  661. cover_image_filename=project.cover_image_filename,
  662. tags=project.tags,
  663. due_date=project.due_date,
  664. priority=project.priority,
  665. budget=project.budget,
  666. is_template=project.is_template,
  667. template_source_id=project.template_source_id,
  668. parent_id=project.parent_id,
  669. parent_name=None,
  670. children=[],
  671. created_at=project.created_at,
  672. updated_at=project.updated_at,
  673. stats=stats,
  674. )
  675. # ============ Dynamic {project_id} Routes ============
  676. @router.get("/{project_id}", response_model=ProjectResponse)
  677. async def get_project(
  678. project_id: int,
  679. db: AsyncSession = Depends(get_db),
  680. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  681. ):
  682. """Get a project by ID with detailed stats."""
  683. result = await db.execute(select(Project).where(Project.id == project_id))
  684. project = result.scalar_one_or_none()
  685. if not project:
  686. raise HTTPException(status_code=404, detail="Project not found")
  687. # Get parent name
  688. parent_name = None
  689. if project.parent_id:
  690. parent_result = await db.execute(select(Project.name).where(Project.id == project.parent_id))
  691. parent_name = parent_result.scalar()
  692. subtree = await compute_subtree_stats(db, project.id)
  693. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  694. return ProjectResponse(
  695. id=project.id,
  696. name=project.name,
  697. description=project.description,
  698. color=project.color,
  699. status=project.status,
  700. target_count=project.target_count,
  701. target_parts_count=project.target_parts_count,
  702. target_sets=project.target_sets,
  703. notes=project.notes,
  704. attachments=project.attachments,
  705. url=project.url,
  706. cover_image_filename=project.cover_image_filename,
  707. tags=project.tags,
  708. due_date=project.due_date,
  709. priority=project.priority,
  710. budget=project.budget,
  711. is_template=project.is_template,
  712. template_source_id=project.template_source_id,
  713. parent_id=project.parent_id,
  714. parent_name=parent_name,
  715. children=subtree.child_previews,
  716. descendant_count=subtree.descendant_count,
  717. created_at=project.created_at,
  718. updated_at=project.updated_at,
  719. stats=stats,
  720. rollup_stats=subtree.rollup,
  721. )
  722. @router.patch("/{project_id}", response_model=ProjectResponse)
  723. async def update_project(
  724. project_id: int,
  725. data: ProjectUpdate,
  726. db: AsyncSession = Depends(get_db),
  727. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  728. ):
  729. """Update a project."""
  730. result = await db.execute(select(Project).where(Project.id == project_id))
  731. project = result.scalar_one_or_none()
  732. if not project:
  733. raise HTTPException(status_code=404, detail="Project not found")
  734. # Update fields if provided
  735. if data.name is not None:
  736. project.name = data.name
  737. if data.description is not None:
  738. project.description = data.description
  739. if data.color is not None:
  740. project.color = data.color
  741. if data.status is not None:
  742. if data.status not in PROJECT_STATUSES:
  743. raise HTTPException(status_code=400, detail="Invalid status")
  744. project.status = data.status
  745. if data.target_count is not None:
  746. project.target_count = data.target_count
  747. if data.target_parts_count is not None:
  748. project.target_parts_count = data.target_parts_count
  749. # Sent-but-null clears the copies-per-file target (#1897); omitted leaves it
  750. # alone (same #2536 semantics as tags/due_date below).
  751. if "target_sets" in data.model_fields_set:
  752. project.target_sets = data.target_sets
  753. if data.notes is not None:
  754. project.notes = data.notes
  755. # Sent-but-null clears the field; omitted leaves it alone. Guarding on
  756. # ``is not None`` would make an emptied tags field or a removed due date
  757. # silently revert to the stored value (#2536).
  758. if "tags" in data.model_fields_set:
  759. project.tags = data.tags
  760. if "due_date" in data.model_fields_set:
  761. project.due_date = data.due_date
  762. if data.priority is not None:
  763. if data.priority not in PROJECT_PRIORITIES:
  764. raise HTTPException(status_code=400, detail="Invalid priority")
  765. project.priority = data.priority
  766. if "budget" in data.model_fields_set:
  767. project.budget = data.budget
  768. if "url" in data.model_fields_set:
  769. # Pydantic validator already guarantees http(s) prefix or None.
  770. project.url = data.url
  771. if data.parent_id is not None:
  772. # Verify parent exists and prevent circular reference
  773. if data.parent_id == project_id:
  774. raise HTTPException(status_code=400, detail="Project cannot be its own parent")
  775. if data.parent_id != 0: # 0 means remove parent
  776. parent_result = await db.execute(select(Project).where(Project.id == data.parent_id))
  777. if not parent_result.scalar_one_or_none():
  778. raise HTTPException(status_code=400, detail="Parent project not found")
  779. # Refusing only the project itself left A -> B -> A reachable in two
  780. # calls, and a cycle has no root to roll figures up to — the walk in
  781. # ``_descendants_of`` would revisit forever without its seen-set
  782. # (#1264).
  783. if data.parent_id in await _project_descendants(db, project_id):
  784. raise HTTPException(status_code=400, detail="Project cannot be moved under one of its own sub-projects")
  785. project.parent_id = data.parent_id
  786. else:
  787. project.parent_id = None
  788. await db.flush()
  789. await db.refresh(project)
  790. # Get parent name
  791. parent_name = None
  792. if project.parent_id:
  793. parent_result = await db.execute(select(Project.name).where(Project.id == project.parent_id))
  794. parent_name = parent_result.scalar()
  795. subtree = await compute_subtree_stats(db, project.id)
  796. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  797. return ProjectResponse(
  798. id=project.id,
  799. name=project.name,
  800. description=project.description,
  801. color=project.color,
  802. status=project.status,
  803. target_count=project.target_count,
  804. target_parts_count=project.target_parts_count,
  805. target_sets=project.target_sets,
  806. notes=project.notes,
  807. attachments=project.attachments,
  808. url=project.url,
  809. cover_image_filename=project.cover_image_filename,
  810. tags=project.tags,
  811. due_date=project.due_date,
  812. priority=project.priority,
  813. budget=project.budget,
  814. is_template=project.is_template,
  815. template_source_id=project.template_source_id,
  816. parent_id=project.parent_id,
  817. parent_name=parent_name,
  818. children=subtree.child_previews,
  819. descendant_count=subtree.descendant_count,
  820. created_at=project.created_at,
  821. updated_at=project.updated_at,
  822. stats=stats,
  823. rollup_stats=subtree.rollup,
  824. )
  825. @router.delete("/{project_id}")
  826. async def delete_project(
  827. project_id: int,
  828. db: AsyncSession = Depends(get_db),
  829. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_DELETE),
  830. ):
  831. """Delete a project. Archives and queue items will have project_id set to NULL."""
  832. result = await db.execute(select(Project).where(Project.id == project_id))
  833. project = result.scalar_one_or_none()
  834. if not project:
  835. raise HTTPException(status_code=404, detail="Project not found")
  836. # Sub-projects move up to the deleted project's own parent rather than
  837. # being cut loose at the top level, so deleting a middle layer collapses
  838. # the tree by one instead of scattering a branch (#1264). Left to the ORM
  839. # this would null their parent_id instead, which loses the grandparent.
  840. await db.execute(update(Project).where(Project.parent_id == project_id).values(parent_id=project.parent_id))
  841. await db.delete(project)
  842. return {"message": "Project deleted"}
  843. @router.get("/{project_id}/archives")
  844. async def list_project_archives(
  845. project_id: int,
  846. limit: int = 100,
  847. offset: int = 0,
  848. db: AsyncSession = Depends(get_db),
  849. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  850. printer_scope: PrinterScope = RequestPrinterScope,
  851. ):
  852. """List archives in a project."""
  853. # Verify project exists
  854. result = await db.execute(select(Project).where(Project.id == project_id))
  855. if not result.scalar_one_or_none():
  856. raise HTTPException(status_code=404, detail="Project not found")
  857. # Get archives with both ``project`` and ``created_by`` eagerly loaded.
  858. # ``archive_to_response`` accesses ``archive.created_by.username`` to
  859. # surface the creator on the archive card; without selectinload that's
  860. # a lazy attribute access on a closed async session, which throws
  861. # ``MissingGreenlet`` and produces a 500. ``ArchiveService.list_archives``
  862. # already loads both — this route just got out of step.
  863. query = (
  864. select(PrintArchive)
  865. .options(selectinload(PrintArchive.project), selectinload(PrintArchive.created_by))
  866. .where(PrintArchive.project_id == project_id, _LIVE_ARCHIVE)
  867. .order_by(PrintArchive.created_at.desc())
  868. .limit(limit)
  869. .offset(offset)
  870. )
  871. # Only archives from printers the caller may see (#1727)
  872. if (clause := printer_scope.where(PrintArchive.printer_id)) is not None:
  873. query = query.where(clause)
  874. result = await db.execute(query)
  875. archives = result.scalars().all()
  876. # Import the response converter from archives module
  877. from backend.app.api.routes.archives import _load_run_aggregates, archive_to_response
  878. # Load run aggregates so multi-run archives' time/accuracy badge is
  879. # suppressed consistently with the main archives list endpoint (#1608).
  880. run_aggregates = await _load_run_aggregates(db, [a.id for a in archives])
  881. return [archive_to_response(a, run_aggregate=run_aggregates.get(a.id)) for a in archives]
  882. @router.get("/{project_id}/queue")
  883. async def list_project_queue(
  884. project_id: int,
  885. db: AsyncSession = Depends(get_db),
  886. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  887. printer_scope: PrinterScope = RequestPrinterScope,
  888. ):
  889. """List queue items in a project."""
  890. # Verify project exists
  891. result = await db.execute(select(Project).where(Project.id == project_id))
  892. if not result.scalar_one_or_none():
  893. raise HTTPException(status_code=404, detail="Project not found")
  894. # Get queue items
  895. query = select(PrintQueueItem).where(PrintQueueItem.project_id == project_id).order_by(PrintQueueItem.position)
  896. if (clause := printer_scope.where(PrintQueueItem.printer_id)) is not None:
  897. query = query.where(clause)
  898. result = await db.execute(query)
  899. items = result.scalars().all()
  900. return items
  901. @router.get("/{project_id}/file-progress", response_model=list[ProjectFileProgress])
  902. async def get_project_file_progress(
  903. project_id: int,
  904. db: AsyncSession = Depends(get_db),
  905. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  906. ):
  907. """Completed-run counts per library file inside a project (#1897).
  908. Counts completed ``PrintLogEntry`` rows (same source as the aggregate
  909. project stats) of archives attributed to this project, and maps each run to
  910. one of the project's library files — the files living in folders linked to
  911. the project, the same set the project detail page renders.
  912. A run is attributed to exactly one file, by the strongest available match:
  913. 1. ``archive.library_file_id`` (stamped at queue dispatch since #1897),
  914. 2. content hash (covers historical rows),
  915. 3. filename (covers hash drift, e.g. re-sliced uploads of the same name).
  916. Files with no completed runs are omitted — the frontend treats absence as 0.
  917. """
  918. result = await db.execute(select(Project.id).where(Project.id == project_id))
  919. if result.scalar_one_or_none() is None:
  920. raise HTTPException(status_code=404, detail="Project not found")
  921. files_result = await db.execute(
  922. select(LibraryFile.id, LibraryFile.file_hash, LibraryFile.filename)
  923. .join(LibraryFolder, LibraryFile.folder_id == LibraryFolder.id)
  924. .where(LibraryFolder.project_id == project_id, LibraryFile.deleted_at.is_(None))
  925. )
  926. file_rows = files_result.all()
  927. if not file_rows:
  928. return []
  929. # First match wins within each tier, so iteration order (file id) is stable
  930. # when duplicates share a hash or filename.
  931. by_id = {fid for fid, _, _ in file_rows}
  932. by_hash: dict[str, int] = {}
  933. by_name: dict[str, int] = {}
  934. for fid, fhash, fname in file_rows:
  935. if fhash and fhash not in by_hash:
  936. by_hash[fhash] = fid
  937. if fname not in by_name:
  938. by_name[fname] = fid
  939. runs_result = await db.execute(
  940. select(
  941. PrintArchive.library_file_id,
  942. PrintArchive.content_hash,
  943. PrintArchive.filename,
  944. func.count(PrintLogEntry.id),
  945. )
  946. .join(PrintArchive, PrintArchive.id == PrintLogEntry.archive_id)
  947. .where(
  948. PrintArchive.project_id == project_id,
  949. PrintLogEntry.status == "completed",
  950. _NOT_REJECTED,
  951. _LIVE_ARCHIVE,
  952. )
  953. .group_by(PrintArchive.library_file_id, PrintArchive.content_hash, PrintArchive.filename)
  954. )
  955. counts: dict[int, int] = {}
  956. for lib_file_id, content_hash, filename, run_count in runs_result.all():
  957. if lib_file_id in by_id:
  958. fid = lib_file_id
  959. elif content_hash and content_hash in by_hash:
  960. fid = by_hash[content_hash]
  961. elif filename in by_name:
  962. fid = by_name[filename]
  963. else:
  964. continue
  965. counts[fid] = counts.get(fid, 0) + run_count
  966. return [ProjectFileProgress(file_id=fid, completed_count=n) for fid, n in sorted(counts.items())]
  967. def _editable_rows(
  968. model: type[PrintArchive] | type[PrintQueueItem],
  969. ids: list[int],
  970. printer_scope: PrinterScope,
  971. actor: User | ApiKeyActor | None,
  972. all_permission: Permission,
  973. own_permission: Permission,
  974. ):
  975. """Select the rows of ``ids`` the caller may relink, or None for none of them.
  976. The same rows the caller could change through the archive or queue edit:
  977. on their printers, and their own unless they may change everyone's. Rows
  978. outside are skipped like missing ones, so the count names no hidden id. An
  979. API key changes what its owner could. Auth off (no actor) changes all.
  980. """
  981. query = select(model).where(model.id.in_(ids))
  982. if (clause := printer_scope.where(model.printer_id)) is not None:
  983. query = query.where(clause)
  984. if actor is None:
  985. return query
  986. # A key acts with its owner's rights to these rows, not with its own scope
  987. # flags (a project key needs no archive or queue flag, #1893), so it never
  988. # reaches a row its owner could not change. A legacy key without an owner
  989. # keeps every row of its printers.
  990. user = actor.owner if isinstance(actor, ApiKeyActor) else actor
  991. if user is None or user.has_permission(all_permission.value):
  992. return query
  993. if user.has_permission(own_permission.value):
  994. return query.where(model.created_by_id == user.id)
  995. return None
  996. @router.post("/{project_id}/add-archives")
  997. async def add_archives_to_project(
  998. project_id: int,
  999. data: BatchAddArchives,
  1000. db: AsyncSession = Depends(get_db),
  1001. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1002. printer_scope: PrinterScope = RequestPrinterScope,
  1003. actor: User | ApiKeyActor | None = RequestActor,
  1004. ):
  1005. """Batch add archives to a project."""
  1006. # Verify project exists
  1007. result = await db.execute(select(Project).where(Project.id == project_id))
  1008. if not result.scalar_one_or_none():
  1009. raise HTTPException(status_code=404, detail="Project not found")
  1010. query = _editable_rows(
  1011. PrintArchive,
  1012. data.archive_ids,
  1013. printer_scope,
  1014. actor,
  1015. Permission.ARCHIVES_UPDATE_ALL,
  1016. Permission.ARCHIVES_UPDATE_OWN,
  1017. )
  1018. archives = (await db.execute(query)).scalars().all() if query is not None else []
  1019. for archive in archives:
  1020. archive.project_id = project_id
  1021. return {"message": f"Added {len(archives)} archives to project", "count": len(archives)}
  1022. @router.post("/{project_id}/add-queue")
  1023. async def add_queue_items_to_project(
  1024. project_id: int,
  1025. data: BatchAddQueueItems,
  1026. db: AsyncSession = Depends(get_db),
  1027. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1028. printer_scope: PrinterScope = RequestPrinterScope,
  1029. actor: User | ApiKeyActor | None = RequestActor,
  1030. ):
  1031. """Batch add queue items to a project."""
  1032. # Verify project exists
  1033. result = await db.execute(select(Project).where(Project.id == project_id))
  1034. if not result.scalar_one_or_none():
  1035. raise HTTPException(status_code=404, detail="Project not found")
  1036. query = _editable_rows(
  1037. PrintQueueItem,
  1038. data.queue_item_ids,
  1039. printer_scope,
  1040. actor,
  1041. Permission.QUEUE_UPDATE_ALL,
  1042. Permission.QUEUE_UPDATE_OWN,
  1043. )
  1044. items = (await db.execute(query)).scalars().all() if query is not None else []
  1045. for item in items:
  1046. item.project_id = project_id
  1047. return {"message": f"Added {len(items)} queue items to project", "count": len(items)}
  1048. @router.post("/{project_id}/remove-archives")
  1049. async def remove_archives_from_project(
  1050. project_id: int,
  1051. data: BatchAddArchives,
  1052. db: AsyncSession = Depends(get_db),
  1053. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1054. printer_scope: PrinterScope = RequestPrinterScope,
  1055. actor: User | ApiKeyActor | None = RequestActor,
  1056. ):
  1057. """Remove archives from a project (sets project_id to NULL)."""
  1058. query = _editable_rows(
  1059. PrintArchive,
  1060. data.archive_ids,
  1061. printer_scope,
  1062. actor,
  1063. Permission.ARCHIVES_UPDATE_ALL,
  1064. Permission.ARCHIVES_UPDATE_OWN,
  1065. )
  1066. archives = (
  1067. (await db.execute(query.where(PrintArchive.project_id == project_id))).scalars().all()
  1068. if query is not None
  1069. else []
  1070. )
  1071. for archive in archives:
  1072. archive.project_id = None
  1073. return {"message": f"Removed {len(archives)} archives from project", "count": len(archives)}
  1074. def get_project_attachments_dir(project_id: int) -> Path:
  1075. """Directory holding a project's cover image (named for the file
  1076. attachments it once held as well)."""
  1077. base_dir = Path(settings.archive_dir)
  1078. return base_dir / "projects" / str(project_id) / "attachments"
  1079. # Cover-image upload accepts only common web-renderable image types (#1155);
  1080. # .svg/.ico don't render well as a card thumbnail.
  1081. COVER_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
  1082. COVER_IMAGE_CONTENT_TYPES = {
  1083. ".jpg": "image/jpeg",
  1084. ".jpeg": "image/jpeg",
  1085. ".png": "image/png",
  1086. ".gif": "image/gif",
  1087. ".webp": "image/webp",
  1088. }
  1089. @router.post("/{project_id}/cover-image")
  1090. async def upload_project_cover_image(
  1091. project_id: int,
  1092. file: UploadFile = File(...),
  1093. db: AsyncSession = Depends(get_db),
  1094. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1095. ):
  1096. """Upload (or replace) the project's cover image (#1155).
  1097. Stored alongside other attachments but tracked via Project.cover_image_filename
  1098. so swap/delete operations don't touch the attachments list. Replaces any
  1099. existing cover image — the prior file is deleted on disk before the new one
  1100. lands so a stuck filesystem reference can't accumulate orphaned images.
  1101. """
  1102. result = await db.execute(select(Project).where(Project.id == project_id))
  1103. project = result.scalar_one_or_none()
  1104. if not project:
  1105. raise HTTPException(status_code=404, detail="Project not found")
  1106. original_name = file.filename or "cover"
  1107. ext = os.path.splitext(original_name)[1].lower()
  1108. if ext not in COVER_IMAGE_EXTENSIONS:
  1109. raise HTTPException(
  1110. status_code=400,
  1111. detail=f"Cover image must be one of {sorted(COVER_IMAGE_EXTENSIONS)}",
  1112. )
  1113. attachments_dir = get_project_attachments_dir(project_id)
  1114. attachments_dir.mkdir(parents=True, exist_ok=True)
  1115. # Remove the previous cover-image file from disk first so we don't accumulate
  1116. # orphans when users repeatedly replace it. Best-effort: a missing/locked file
  1117. # shouldn't block a successful replacement.
  1118. if project.cover_image_filename:
  1119. old_path = attachments_dir / project.cover_image_filename
  1120. if old_path.exists():
  1121. try:
  1122. os.remove(old_path)
  1123. except OSError as e:
  1124. logger.warning("Failed to delete old cover image %s: %s", old_path, e)
  1125. unique_filename = f"cover_{uuid.uuid4().hex}{ext}"
  1126. file_path = attachments_dir / unique_filename # SEC-PATH-OK: unique_filename = f"cover_{uuid.uuid4().hex}{ext}"
  1127. try:
  1128. with open(file_path, "wb") as f:
  1129. content = await file.read()
  1130. f.write(content)
  1131. except OSError as e:
  1132. logger.error("Failed to save cover image: %s", e)
  1133. raise HTTPException(status_code=500, detail="Failed to save cover image")
  1134. project.cover_image_filename = unique_filename
  1135. db.add(project)
  1136. await db.flush()
  1137. await db.commit()
  1138. return {
  1139. "status": "success",
  1140. "filename": unique_filename,
  1141. "size": len(content),
  1142. }
  1143. @router.get("/{project_id}/cover-image")
  1144. async def get_project_cover_image(
  1145. project_id: int,
  1146. db: AsyncSession = Depends(get_db),
  1147. _: User | None = Depends(require_media_token_permission(Permission.PROJECTS_READ)),
  1148. ):
  1149. """Stream the project's cover image (#1155).
  1150. Browsers can't attach `Authorization: Bearer ...` to `<img src>` requests,
  1151. so this route accepts a `?token=` media credential, the same one
  1152. /archives/{id}/thumbnail takes. The frontend wraps URLs with `withMediaToken`.
  1153. Gated on ``projects:read`` like every other project route. It used to take
  1154. the camera-stream token, which required ``camera:view`` instead -- an
  1155. unrelated permission that a user could hold without any project access, and
  1156. that a project reader could easily lack (#3025). Projects carry no
  1157. ``created_by_id``, so there is no per-row owner to check beyond that."""
  1158. result = await db.execute(select(Project).where(Project.id == project_id))
  1159. project = result.scalar_one_or_none()
  1160. if not project:
  1161. raise HTTPException(status_code=404, detail="Project not found")
  1162. if not project.cover_image_filename:
  1163. raise HTTPException(status_code=404, detail="No cover image set")
  1164. file_path = get_project_attachments_dir(project_id) / project.cover_image_filename
  1165. if not file_path.exists():
  1166. # DB references a file that vanished from disk — clear the dangling
  1167. # reference so future GETs get a clean 404 instead of repeatedly
  1168. # touching the filesystem.
  1169. logger.warning("Cover image file missing for project %s: %s", project_id, file_path)
  1170. project.cover_image_filename = None
  1171. await db.commit()
  1172. raise HTTPException(status_code=404, detail="Cover image file not found")
  1173. ext = os.path.splitext(project.cover_image_filename)[1].lower()
  1174. media_type = COVER_IMAGE_CONTENT_TYPES.get(ext, "application/octet-stream")
  1175. return FileResponse(file_path, media_type=media_type)
  1176. @router.delete("/{project_id}/cover-image")
  1177. async def delete_project_cover_image(
  1178. project_id: int,
  1179. db: AsyncSession = Depends(get_db),
  1180. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1181. ):
  1182. """Remove the project's cover image (#1155)."""
  1183. result = await db.execute(select(Project).where(Project.id == project_id))
  1184. project = result.scalar_one_or_none()
  1185. if not project:
  1186. raise HTTPException(status_code=404, detail="Project not found")
  1187. if project.cover_image_filename:
  1188. file_path = get_project_attachments_dir(project_id) / project.cover_image_filename
  1189. if file_path.exists():
  1190. try:
  1191. os.remove(file_path)
  1192. except OSError as e:
  1193. logger.warning("Failed to delete cover image file %s: %s", file_path, e)
  1194. project.cover_image_filename = None
  1195. db.add(project)
  1196. await db.flush()
  1197. await db.commit()
  1198. return {"status": "success"}
  1199. # ============ Phase 7: BOM Endpoints ============
  1200. async def _visible_archive_names(db: AsyncSession, archive_ids, printer_scope: PrinterScope) -> dict[int, str | None]:
  1201. """Print names of the archives among ``archive_ids`` the caller can see.
  1202. As the project's archive list: live archives on the caller's printers
  1203. (#1727). An archive missing from the result reads as missing.
  1204. """
  1205. ids = {i for i in archive_ids if i}
  1206. if not ids:
  1207. return {}
  1208. query = select(PrintArchive.id, PrintArchive.print_name).where(PrintArchive.id.in_(ids), _LIVE_ARCHIVE)
  1209. if (clause := printer_scope.where(PrintArchive.printer_id)) is not None:
  1210. query = query.where(clause)
  1211. return dict((await db.execute(query)).all())
  1212. async def _ensure_linkable_archive(db: AsyncSession, archive_id: int, printer_scope: PrinterScope) -> None:
  1213. """Refuse a link to an archive the caller cannot see; hidden reads as missing."""
  1214. if archive_id not in await _visible_archive_names(db, [archive_id], printer_scope):
  1215. raise HTTPException(status_code=400, detail="Archive not found")
  1216. def _bom_response(item: ProjectBOMItem, visible_names: dict[int, str | None]) -> BOMItemResponse:
  1217. archive_id = item.archive_id if item.archive_id in visible_names else None
  1218. return BOMItemResponse(
  1219. id=item.id,
  1220. project_id=item.project_id,
  1221. name=item.name,
  1222. quantity_needed=item.quantity_needed,
  1223. quantity_acquired=item.quantity_acquired,
  1224. unit_price=item.unit_price,
  1225. sourcing_url=item.sourcing_url,
  1226. archive_id=archive_id,
  1227. archive_name=visible_names[archive_id] if archive_id is not None else None,
  1228. stl_filename=item.stl_filename,
  1229. remarks=item.remarks,
  1230. sort_order=item.sort_order,
  1231. is_complete=item.quantity_acquired >= item.quantity_needed,
  1232. created_at=item.created_at,
  1233. updated_at=item.updated_at,
  1234. )
  1235. @router.get("/{project_id}/bom", response_model=list[BOMItemResponse])
  1236. async def list_bom_items(
  1237. project_id: int,
  1238. db: AsyncSession = Depends(get_db),
  1239. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1240. printer_scope: PrinterScope = RequestPrinterScope,
  1241. ):
  1242. """List all BOM items for a project."""
  1243. # Verify project exists
  1244. result = await db.execute(select(Project).where(Project.id == project_id))
  1245. if not result.scalar_one_or_none():
  1246. raise HTTPException(status_code=404, detail="Project not found")
  1247. # Get BOM items
  1248. result = await db.execute(
  1249. select(ProjectBOMItem)
  1250. .where(ProjectBOMItem.project_id == project_id)
  1251. .order_by(ProjectBOMItem.sort_order, ProjectBOMItem.id)
  1252. )
  1253. items = result.scalars().all()
  1254. names = await _visible_archive_names(db, [item.archive_id for item in items], printer_scope)
  1255. return [_bom_response(item, names) for item in items]
  1256. @router.post("/{project_id}/bom", response_model=BOMItemResponse)
  1257. async def create_bom_item(
  1258. project_id: int,
  1259. data: BOMItemCreate,
  1260. db: AsyncSession = Depends(get_db),
  1261. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1262. printer_scope: PrinterScope = RequestPrinterScope,
  1263. ):
  1264. """Add a BOM item to a project."""
  1265. # Verify project exists
  1266. result = await db.execute(select(Project).where(Project.id == project_id))
  1267. if not result.scalar_one_or_none():
  1268. raise HTTPException(status_code=404, detail="Project not found")
  1269. # 0 means no archive, as on update.
  1270. archive_id = data.archive_id or None
  1271. if archive_id is not None:
  1272. await _ensure_linkable_archive(db, archive_id, printer_scope)
  1273. # Get max sort order
  1274. max_order_result = await db.execute(
  1275. select(func.max(ProjectBOMItem.sort_order)).where(ProjectBOMItem.project_id == project_id)
  1276. )
  1277. max_order = max_order_result.scalar() or 0
  1278. item = ProjectBOMItem(
  1279. project_id=project_id,
  1280. name=data.name,
  1281. quantity_needed=data.quantity_needed,
  1282. unit_price=data.unit_price,
  1283. sourcing_url=data.sourcing_url,
  1284. archive_id=archive_id,
  1285. stl_filename=data.stl_filename,
  1286. remarks=data.remarks,
  1287. sort_order=max_order + 1,
  1288. )
  1289. db.add(item)
  1290. await db.flush()
  1291. await db.refresh(item)
  1292. return _bom_response(item, await _visible_archive_names(db, [item.archive_id], printer_scope))
  1293. @router.patch("/{project_id}/bom/{item_id}", response_model=BOMItemResponse)
  1294. async def update_bom_item(
  1295. project_id: int,
  1296. item_id: int,
  1297. data: BOMItemUpdate,
  1298. db: AsyncSession = Depends(get_db),
  1299. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1300. printer_scope: PrinterScope = RequestPrinterScope,
  1301. ):
  1302. """Update a BOM item."""
  1303. result = await db.execute(
  1304. select(ProjectBOMItem).where(
  1305. ProjectBOMItem.id == item_id,
  1306. ProjectBOMItem.project_id == project_id,
  1307. )
  1308. )
  1309. item = result.scalar_one_or_none()
  1310. if not item:
  1311. raise HTTPException(status_code=404, detail="BOM item not found")
  1312. if data.name is not None:
  1313. item.name = data.name
  1314. if data.quantity_needed is not None:
  1315. item.quantity_needed = data.quantity_needed
  1316. if data.quantity_acquired is not None:
  1317. item.quantity_acquired = data.quantity_acquired
  1318. if data.unit_price is not None:
  1319. item.unit_price = data.unit_price if data.unit_price != 0 else None
  1320. if data.sourcing_url is not None:
  1321. item.sourcing_url = data.sourcing_url if data.sourcing_url else None
  1322. if data.archive_id is not None:
  1323. # Also when unchanged: a hidden current link must answer as a missing one,
  1324. # or resending its id would confirm it.
  1325. if data.archive_id != 0:
  1326. await _ensure_linkable_archive(db, data.archive_id, printer_scope)
  1327. item.archive_id = data.archive_id if data.archive_id != 0 else None
  1328. if data.stl_filename is not None:
  1329. item.stl_filename = data.stl_filename if data.stl_filename else None
  1330. if data.remarks is not None:
  1331. item.remarks = data.remarks if data.remarks else None
  1332. await db.flush()
  1333. await db.refresh(item)
  1334. return _bom_response(item, await _visible_archive_names(db, [item.archive_id], printer_scope))
  1335. @router.delete("/{project_id}/bom/{item_id}")
  1336. async def delete_bom_item(
  1337. project_id: int,
  1338. item_id: int,
  1339. db: AsyncSession = Depends(get_db),
  1340. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_UPDATE),
  1341. ):
  1342. """Delete a BOM item."""
  1343. result = await db.execute(
  1344. select(ProjectBOMItem).where(
  1345. ProjectBOMItem.id == item_id,
  1346. ProjectBOMItem.project_id == project_id,
  1347. )
  1348. )
  1349. item = result.scalar_one_or_none()
  1350. if not item:
  1351. raise HTTPException(status_code=404, detail="BOM item not found")
  1352. await db.delete(item)
  1353. return {"status": "success", "message": "BOM item deleted"}
  1354. @router.post("/{project_id}/create-template", response_model=ProjectResponse)
  1355. async def create_template_from_project(
  1356. project_id: int,
  1357. db: AsyncSession = Depends(get_db),
  1358. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1359. ):
  1360. """Create a template from an existing project."""
  1361. result = await db.execute(select(Project).where(Project.id == project_id))
  1362. source = result.scalar_one_or_none()
  1363. if not source:
  1364. raise HTTPException(status_code=404, detail="Project not found")
  1365. # Create template
  1366. template = Project(
  1367. name=f"{source.name} (Template)",
  1368. description=source.description,
  1369. color=source.color,
  1370. target_count=source.target_count,
  1371. target_parts_count=source.target_parts_count,
  1372. target_sets=source.target_sets,
  1373. notes=source.notes,
  1374. tags=source.tags,
  1375. priority=source.priority,
  1376. budget=source.budget,
  1377. is_template=True,
  1378. template_source_id=source.id,
  1379. url=source.url,
  1380. )
  1381. db.add(template)
  1382. await db.flush()
  1383. # Copy BOM items
  1384. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == project_id))
  1385. bom_items = bom_result.scalars().all()
  1386. for item in bom_items:
  1387. new_item = ProjectBOMItem(
  1388. project_id=template.id,
  1389. name=item.name,
  1390. quantity_needed=item.quantity_needed,
  1391. quantity_acquired=0,
  1392. unit_price=item.unit_price,
  1393. sourcing_url=item.sourcing_url,
  1394. stl_filename=item.stl_filename,
  1395. remarks=item.remarks,
  1396. sort_order=item.sort_order,
  1397. )
  1398. db.add(new_item)
  1399. await db.flush()
  1400. await db.refresh(template)
  1401. stats = await compute_project_stats(db, template.id, template.target_count, template.target_parts_count)
  1402. return ProjectResponse(
  1403. id=template.id,
  1404. name=template.name,
  1405. description=template.description,
  1406. color=template.color,
  1407. status=template.status,
  1408. target_count=template.target_count,
  1409. target_parts_count=template.target_parts_count,
  1410. target_sets=template.target_sets,
  1411. notes=template.notes,
  1412. attachments=template.attachments,
  1413. url=template.url,
  1414. cover_image_filename=template.cover_image_filename,
  1415. tags=template.tags,
  1416. due_date=template.due_date,
  1417. priority=template.priority,
  1418. budget=template.budget,
  1419. is_template=template.is_template,
  1420. template_source_id=template.template_source_id,
  1421. parent_id=template.parent_id,
  1422. parent_name=None,
  1423. children=[],
  1424. created_at=template.created_at,
  1425. updated_at=template.updated_at,
  1426. stats=stats,
  1427. )
  1428. # ============ Phase 9: Timeline Endpoint ============
  1429. def _queue_item_name(item: PrintQueueItem) -> str | None:
  1430. """The name a queued job goes by, from its archive or library file.
  1431. Same sources as the queue page: the archive's print name or file name, but
  1432. not from a deleted archive, then the library file's print name or file name,
  1433. then for a job for any of several models (#671) its first candidate's file.
  1434. """
  1435. if item.archive is not None and item.archive.deleted_at is None:
  1436. name = item.archive.print_name or item.archive.filename
  1437. if name:
  1438. return name
  1439. if item.library_file is not None:
  1440. metadata = item.library_file.file_metadata or {}
  1441. return metadata.get("print_name") or item.library_file.filename
  1442. if item.variants and item.variants[0].library_file is not None:
  1443. return item.variants[0].library_file.filename
  1444. return None
  1445. @router.get("/{project_id}/timeline", response_model=list[TimelineEvent])
  1446. async def get_project_timeline(
  1447. project_id: int,
  1448. limit: int = 50,
  1449. db: AsyncSession = Depends(get_db),
  1450. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1451. printer_scope: PrinterScope = RequestPrinterScope,
  1452. ):
  1453. """Get timeline of events for a project."""
  1454. # Verify project exists
  1455. result = await db.execute(select(Project).where(Project.id == project_id))
  1456. project = result.scalar_one_or_none()
  1457. if not project:
  1458. raise HTTPException(status_code=404, detail="Project not found")
  1459. events = []
  1460. # Project creation event
  1461. events.append(
  1462. TimelineEvent(
  1463. event_type="project_created",
  1464. timestamp=project.created_at,
  1465. title="Project created",
  1466. description=f"Project '{project.name}' was created",
  1467. )
  1468. )
  1469. # Get archives and add events
  1470. archive_query = (
  1471. select(PrintArchive)
  1472. .where(PrintArchive.project_id == project_id, _LIVE_ARCHIVE)
  1473. .order_by(PrintArchive.created_at.desc())
  1474. .limit(limit)
  1475. )
  1476. # Only events from printers the caller may see, as the archive and queue
  1477. # lists of the project (#1727)
  1478. if (clause := printer_scope.where(PrintArchive.printer_id)) is not None:
  1479. archive_query = archive_query.where(clause)
  1480. archives = (await db.execute(archive_query)).scalars().all()
  1481. for archive in archives:
  1482. if archive.status == "completed":
  1483. events.append(
  1484. TimelineEvent(
  1485. event_type="print_completed",
  1486. timestamp=archive.completed_at or archive.created_at,
  1487. title="Print completed",
  1488. description=archive.print_name,
  1489. metadata={
  1490. "archive_id": archive.id,
  1491. "print_time_hours": round((archive.print_time_seconds or 0) / 3600, 2),
  1492. "filament_grams": round(archive.filament_used_grams or 0, 1),
  1493. },
  1494. )
  1495. )
  1496. elif archive.status == "failed":
  1497. events.append(
  1498. TimelineEvent(
  1499. event_type="print_failed",
  1500. timestamp=archive.completed_at or archive.created_at,
  1501. title="Print failed",
  1502. description=archive.print_name,
  1503. metadata={"archive_id": archive.id},
  1504. )
  1505. )
  1506. # Get queue items
  1507. queue_query = (
  1508. select(PrintQueueItem)
  1509. .where(PrintQueueItem.project_id == project_id)
  1510. .options(
  1511. selectinload(PrintQueueItem.archive),
  1512. selectinload(PrintQueueItem.library_file),
  1513. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  1514. )
  1515. .order_by(PrintQueueItem.created_at.desc())
  1516. .limit(limit)
  1517. )
  1518. if (clause := printer_scope.where(PrintQueueItem.printer_id)) is not None:
  1519. queue_query = queue_query.where(clause)
  1520. queue_items = (await db.execute(queue_query)).scalars().all()
  1521. for item in queue_items:
  1522. if item.status == "printing":
  1523. events.append(
  1524. TimelineEvent(
  1525. event_type="print_started",
  1526. timestamp=item.started_at or item.created_at,
  1527. title="Print started",
  1528. description=_queue_item_name(item),
  1529. metadata={"queue_item_id": item.id},
  1530. )
  1531. )
  1532. elif item.status == "pending":
  1533. events.append(
  1534. TimelineEvent(
  1535. event_type="queued",
  1536. timestamp=item.created_at,
  1537. title="Added to queue",
  1538. description=_queue_item_name(item),
  1539. metadata={"queue_item_id": item.id},
  1540. )
  1541. )
  1542. # Sort by timestamp descending
  1543. events.sort(key=lambda e: e.timestamp, reverse=True)
  1544. return events[:limit]
  1545. # ============ Phase 10: Import/Export Endpoints ============
  1546. def _stored_library_path(stored: str | None) -> Path | None:
  1547. """Where a library file's stored path points.
  1548. Paths are relative to the data directory, except those of files imported
  1549. by older versions, which are relative to the library directory.
  1550. """
  1551. try:
  1552. path = to_absolute_path(stored)
  1553. except ValueError:
  1554. return None
  1555. if path is not None and not path.exists() and stored and not Path(stored).is_absolute():
  1556. try:
  1557. legacy = safe_join_under(get_library_dir(), *Path(stored).parts, http=False)
  1558. except PathTraversalError:
  1559. return path
  1560. if legacy.exists():
  1561. return legacy
  1562. return path
  1563. @router.get("/{project_id}/export")
  1564. async def export_project(
  1565. project_id: int,
  1566. format: str = "zip", # "zip" (with files) or "json" (metadata only)
  1567. db: AsyncSession = Depends(get_db),
  1568. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_READ),
  1569. actor: User | ApiKeyActor | None = RequestActor,
  1570. ):
  1571. """Export a project. Use format=zip (default) for full export with files, or format=json for metadata only."""
  1572. result = await db.execute(select(Project).where(Project.id == project_id))
  1573. project = result.scalar_one_or_none()
  1574. if not project:
  1575. raise HTTPException(status_code=404, detail="Project not found")
  1576. # Get BOM items
  1577. bom_result = await db.execute(
  1578. select(ProjectBOMItem).where(ProjectBOMItem.project_id == project_id).order_by(ProjectBOMItem.sort_order)
  1579. )
  1580. bom_items = bom_result.scalars().all()
  1581. bom_export = [
  1582. {
  1583. "name": item.name,
  1584. "quantity_needed": item.quantity_needed,
  1585. "quantity_acquired": item.quantity_acquired,
  1586. "unit_price": item.unit_price,
  1587. "sourcing_url": item.sourcing_url,
  1588. "stl_filename": item.stl_filename,
  1589. "remarks": item.remarks,
  1590. }
  1591. for item in bom_items
  1592. ]
  1593. # Get linked folders and their files
  1594. folders_result = await db.execute(
  1595. select(LibraryFolder).where(LibraryFolder.project_id == project_id).order_by(LibraryFolder.name)
  1596. )
  1597. linked_folders = folders_result.scalars().all()
  1598. # The folders and files the caller could open in the library, and no more.
  1599. reads_all_files = actor is None or actor.has_permission(Permission.LIBRARY_READ_ALL.value)
  1600. if actor is not None and not reads_all_files:
  1601. if actor.has_permission(Permission.LIBRARY_READ_OWN.value):
  1602. visible = visible_folder_ids(await load_folder_index(db), actor)
  1603. linked_folders = [f for f in linked_folders if visible is None or f.id in visible]
  1604. else:
  1605. linked_folders = []
  1606. folders_export = []
  1607. files_to_include = [] # (archive_path, zip_path)
  1608. for folder in linked_folders:
  1609. # Get files in this folder
  1610. own_files = [] if actor is None or reads_all_files else [LibraryFile.created_by_id == actor.id]
  1611. files_result = await db.execute(
  1612. LibraryFile.active().where(LibraryFile.folder_id == folder.id, *own_files).order_by(LibraryFile.filename)
  1613. )
  1614. files = files_result.scalars().all()
  1615. folder_files = []
  1616. for f in files:
  1617. folder_files.append(
  1618. {
  1619. "filename": f.filename,
  1620. "file_type": f.file_type,
  1621. "notes": f.notes,
  1622. }
  1623. )
  1624. # Add file to include in ZIP
  1625. file_path = _stored_library_path(f.file_path)
  1626. if file_path is not None and file_path.exists():
  1627. zip_path = f"files/{folder.name}/{f.filename}"
  1628. files_to_include.append((file_path, zip_path))
  1629. # Also include thumbnail if exists
  1630. if f.thumbnail_path:
  1631. thumb_path = _stored_library_path(f.thumbnail_path)
  1632. if thumb_path is not None and thumb_path.exists():
  1633. thumb_zip_path = f"files/{folder.name}/.thumbnails/{f.filename}.png"
  1634. files_to_include.append((thumb_path, thumb_zip_path))
  1635. folders_export.append(
  1636. {
  1637. "name": folder.name,
  1638. "files": folder_files,
  1639. }
  1640. )
  1641. # Build project JSON
  1642. project_data = {
  1643. "name": project.name,
  1644. "description": project.description,
  1645. "color": project.color,
  1646. "status": project.status,
  1647. "target_count": project.target_count,
  1648. "target_parts_count": project.target_parts_count,
  1649. "target_sets": project.target_sets,
  1650. "notes": project.notes,
  1651. "tags": project.tags,
  1652. "due_date": project.due_date.isoformat() if project.due_date else None,
  1653. "priority": project.priority,
  1654. "budget": project.budget,
  1655. "bom_items": bom_export,
  1656. "linked_folders": folders_export,
  1657. }
  1658. # Return JSON if requested (for bulk export)
  1659. if format == "json":
  1660. return project_data
  1661. # Create ZIP in memory
  1662. zip_buffer = io.BytesIO()
  1663. with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
  1664. # Add project.json
  1665. zf.writestr("project.json", json.dumps(project_data, indent=2))
  1666. # Add files
  1667. for file_path, zip_path in files_to_include:
  1668. zf.write(file_path, zip_path)
  1669. zip_buffer.seek(0)
  1670. # Generate filename
  1671. safe_name = "".join(c if c.isalnum() or c in "-_ " else "_" for c in project.name)
  1672. filename = f"{safe_name}_{datetime.now().strftime('%Y-%m-%d')}.zip"
  1673. return StreamingResponse(
  1674. zip_buffer,
  1675. media_type="application/zip",
  1676. headers={"Content-Disposition": build_content_disposition(filename)},
  1677. )
  1678. async def _import_folder(
  1679. db: AsyncSession, name: str, project_id: int, actor: User | ApiKeyActor | None
  1680. ) -> LibraryFolder:
  1681. """The top-level folder an imported project links, by name.
  1682. An existing one is taken only when the caller could link it themselves,
  1683. which takes library:update_all. Otherwise a new folder of that name is
  1684. made, shared like every project folder (#3201).
  1685. """
  1686. candidates = (
  1687. await db.execute(
  1688. select(LibraryFolder)
  1689. .where(
  1690. LibraryFolder.name == name,
  1691. LibraryFolder.parent_id.is_(None),
  1692. LibraryFolder.is_external.is_(False),
  1693. )
  1694. .order_by(LibraryFolder.id)
  1695. )
  1696. ).scalars()
  1697. for folder in candidates:
  1698. if actor is None or actor.has_permission(Permission.LIBRARY_UPDATE_ALL.value):
  1699. folder.project_id = project_id
  1700. return folder
  1701. folder = LibraryFolder(
  1702. name=name,
  1703. project_id=project_id,
  1704. is_external=False,
  1705. external_readonly=False,
  1706. external_show_hidden=False,
  1707. created_by_id=actor.id if actor else None,
  1708. shared=True,
  1709. )
  1710. db.add(folder)
  1711. await db.flush()
  1712. return folder
  1713. @router.post("/import", response_model=ProjectResponse)
  1714. async def import_project(
  1715. data: ProjectImport,
  1716. db: AsyncSession = Depends(get_db),
  1717. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1718. actor: User | ApiKeyActor | None = RequestActor,
  1719. ):
  1720. """Import a project with optional BOM items and linked folders."""
  1721. # Create the project
  1722. project = Project(
  1723. name=data.name,
  1724. description=data.description,
  1725. color=data.color,
  1726. status=_imported_status(data.status),
  1727. target_count=data.target_count,
  1728. target_parts_count=data.target_parts_count,
  1729. target_sets=data.target_sets,
  1730. notes=data.notes,
  1731. tags=data.tags,
  1732. due_date=data.due_date,
  1733. priority=_imported_priority(data.priority),
  1734. budget=data.budget,
  1735. )
  1736. db.add(project)
  1737. await db.flush()
  1738. # Create BOM items
  1739. for idx, bom_data in enumerate(data.bom_items):
  1740. bom_item = ProjectBOMItem(
  1741. project_id=project.id,
  1742. name=bom_data.name,
  1743. quantity_needed=bom_data.quantity_needed,
  1744. quantity_acquired=bom_data.quantity_acquired,
  1745. unit_price=bom_data.unit_price,
  1746. sourcing_url=bom_data.sourcing_url,
  1747. stl_filename=bom_data.stl_filename,
  1748. remarks=bom_data.remarks,
  1749. sort_order=idx,
  1750. )
  1751. db.add(bom_item)
  1752. # Link a folder in the library for each
  1753. for folder_data in data.linked_folders:
  1754. await _import_folder(db, folder_data.name, project.id, actor)
  1755. await db.flush()
  1756. await db.refresh(project)
  1757. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  1758. return ProjectResponse(
  1759. id=project.id,
  1760. name=project.name,
  1761. description=project.description,
  1762. color=project.color,
  1763. status=project.status,
  1764. target_count=project.target_count,
  1765. target_parts_count=project.target_parts_count,
  1766. target_sets=project.target_sets,
  1767. notes=project.notes,
  1768. attachments=project.attachments,
  1769. url=project.url,
  1770. cover_image_filename=project.cover_image_filename,
  1771. tags=project.tags,
  1772. due_date=project.due_date,
  1773. priority=project.priority,
  1774. budget=project.budget,
  1775. is_template=project.is_template,
  1776. template_source_id=project.template_source_id,
  1777. parent_id=project.parent_id,
  1778. parent_name=None,
  1779. children=[],
  1780. created_at=project.created_at,
  1781. updated_at=project.updated_at,
  1782. stats=stats,
  1783. )
  1784. @router.post("/import/file", response_model=ProjectResponse)
  1785. async def import_project_file(
  1786. file: UploadFile = File(...),
  1787. db: AsyncSession = Depends(get_db),
  1788. _: User | None = RequirePermissionIfAuthEnabled(Permission.PROJECTS_CREATE),
  1789. actor: User | ApiKeyActor | None = RequestActor,
  1790. ):
  1791. """Import a project from a ZIP or JSON file."""
  1792. if not file.filename:
  1793. raise HTTPException(status_code=400, detail="No filename provided")
  1794. # Determine file type
  1795. filename_lower = file.filename.lower()
  1796. content = await file.read()
  1797. if filename_lower.endswith(".zip"):
  1798. # Extract project.json from ZIP
  1799. try:
  1800. with zipfile.ZipFile(io.BytesIO(content)) as zf:
  1801. if "project.json" not in zf.namelist():
  1802. raise HTTPException(status_code=400, detail="ZIP must contain project.json")
  1803. project_json = zf.read("project.json")
  1804. data = json.loads(project_json)
  1805. # Get list of files in the ZIP
  1806. zip_files = {name: zf.read(name) for name in zf.namelist() if name.startswith("files/")}
  1807. except zipfile.BadZipFile:
  1808. raise HTTPException(status_code=400, detail="Invalid ZIP file")
  1809. elif filename_lower.endswith(".json"):
  1810. try:
  1811. data = json.loads(content)
  1812. zip_files = {}
  1813. except json.JSONDecodeError:
  1814. raise HTTPException(status_code=400, detail="Invalid JSON file")
  1815. else:
  1816. raise HTTPException(status_code=400, detail="File must be .zip or .json")
  1817. # Create the project
  1818. project = Project(
  1819. name=data.get("name", "Imported Project"),
  1820. description=data.get("description"),
  1821. color=data.get("color"),
  1822. status=_imported_status(data.get("status")),
  1823. target_count=data.get("target_count"),
  1824. target_parts_count=data.get("target_parts_count"),
  1825. target_sets=data.get("target_sets"),
  1826. notes=data.get("notes"),
  1827. tags=data.get("tags"),
  1828. due_date=datetime.fromisoformat(data["due_date"]) if data.get("due_date") else None,
  1829. priority=_imported_priority(data.get("priority")),
  1830. budget=data.get("budget"),
  1831. )
  1832. db.add(project)
  1833. await db.flush()
  1834. # Create BOM items
  1835. for idx, bom_data in enumerate(data.get("bom_items", [])):
  1836. bom_item = ProjectBOMItem(
  1837. project_id=project.id,
  1838. name=bom_data.get("name", "Unnamed"),
  1839. quantity_needed=bom_data.get("quantity_needed", 1),
  1840. quantity_acquired=bom_data.get("quantity_acquired", 0),
  1841. unit_price=bom_data.get("unit_price"),
  1842. sourcing_url=bom_data.get("sourcing_url"),
  1843. stl_filename=bom_data.get("stl_filename"),
  1844. remarks=bom_data.get("remarks"),
  1845. sort_order=idx,
  1846. )
  1847. db.add(bom_item)
  1848. # Create linked folders and files
  1849. library_dir = get_library_dir()
  1850. for folder_data in data.get("linked_folders", []):
  1851. folder_name = folder_data.get("name")
  1852. if not folder_name:
  1853. continue
  1854. # Containment check on the folder name — refuses absolute paths and
  1855. # ``..`` traversal in ``project.json[linked_folders[*].name]``. The
  1856. # previous code did ``library_dir / folder_name`` directly, which
  1857. # collapses to ``Path(folder_name)`` when folder_name is absolute
  1858. # and lets ``..`` escape after mkdir.
  1859. safe_join_under(library_dir, folder_name)
  1860. folder = await _import_folder(db, folder_name, project.id, actor)
  1861. # Import files for this folder from ZIP
  1862. folder_prefix = f"files/{folder_name}/"
  1863. for zip_path, file_content in zip_files.items():
  1864. if not zip_path.startswith(folder_prefix):
  1865. continue
  1866. if "/.thumbnails/" in zip_path:
  1867. continue # Skip thumbnails, we'll regenerate them
  1868. relative_path = zip_path[len(folder_prefix) :]
  1869. if not relative_path:
  1870. continue
  1871. # Containment check on the per-entry relative path. ZIP names
  1872. # can carry ``..`` segments by spec; without resolve + parent
  1873. # containment, ``files/<folder>/../../../etc/x`` escapes
  1874. # ``library_dir`` entirely. ``relative_path`` is split into
  1875. # parts because ``safe_join_under`` rejects parts that start
  1876. # with ``/``, and a single combined string would hide an
  1877. # embedded ``..`` segment behind a forward slash.
  1878. safe_join_under(library_dir, folder_name, *Path(relative_path).parts)
  1879. # Stored under a name of its own, as an upload is: another folder
  1880. # of the same name must not share (and overwrite) its files.
  1881. suffix = (
  1882. ".gcode.3mf" if relative_path.lower().endswith(".gcode.3mf") else Path(relative_path).suffix.lower()
  1883. )
  1884. file_disk_path = get_library_files_dir() / f"{uuid.uuid4().hex}{suffix}"
  1885. file_disk_path.write_bytes(file_content)
  1886. # Create library file record
  1887. lib_file = LibraryFile(
  1888. folder_id=folder.id,
  1889. filename=relative_path,
  1890. file_path=to_relative_path(file_disk_path),
  1891. file_type=classify_file_type(relative_path, file_disk_path),
  1892. file_size=len(file_content),
  1893. is_external=False,
  1894. created_by_id=actor.id if actor else None,
  1895. )
  1896. db.add(lib_file)
  1897. await db.flush()
  1898. await db.refresh(project)
  1899. stats = await compute_project_stats(db, project.id, project.target_count, project.target_parts_count)
  1900. return ProjectResponse(
  1901. id=project.id,
  1902. name=project.name,
  1903. description=project.description,
  1904. color=project.color,
  1905. status=project.status,
  1906. target_count=project.target_count,
  1907. target_parts_count=project.target_parts_count,
  1908. target_sets=project.target_sets,
  1909. notes=project.notes,
  1910. attachments=project.attachments,
  1911. url=project.url,
  1912. cover_image_filename=project.cover_image_filename,
  1913. tags=project.tags,
  1914. due_date=project.due_date,
  1915. priority=project.priority,
  1916. budget=project.budget,
  1917. is_template=project.is_template,
  1918. template_source_id=project.template_source_id,
  1919. parent_id=project.parent_id,
  1920. parent_name=None,
  1921. children=[],
  1922. created_at=project.created_at,
  1923. updated_at=project.updated_at,
  1924. stats=stats,
  1925. )