projects.py 89 KB

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