projects.py 84 KB

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