projects.py 83 KB

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