projects.py 70 KB

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