projects.py 69 KB

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