projects.py 57 KB

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