projects.py 87 KB

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