projects.py 85 KB

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