projects.py 84 KB

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