projects.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  1. import logging
  2. import os
  3. import uuid
  4. from datetime import datetime
  5. from pathlib import Path
  6. from fastapi import APIRouter, Depends, File, HTTPException, UploadFile
  7. from fastapi.responses import FileResponse
  8. from sqlalchemy import case, func, select
  9. from sqlalchemy.ext.asyncio import AsyncSession
  10. from sqlalchemy.orm import selectinload
  11. from backend.app.core.config import settings
  12. from backend.app.core.database import get_db
  13. from backend.app.models.archive import PrintArchive
  14. from backend.app.models.print_queue import PrintQueueItem
  15. from backend.app.models.project import Project
  16. from backend.app.models.project_bom import ProjectBOMItem
  17. from backend.app.schemas.project import (
  18. ArchivePreview,
  19. BatchAddArchives,
  20. BatchAddQueueItems,
  21. BOMItemCreate,
  22. BOMItemResponse,
  23. BOMItemUpdate,
  24. ProjectChildPreview,
  25. ProjectCreate,
  26. ProjectListResponse,
  27. ProjectResponse,
  28. ProjectStats,
  29. ProjectUpdate,
  30. TimelineEvent,
  31. )
  32. logger = logging.getLogger(__name__)
  33. router = APIRouter(prefix="/projects", tags=["projects"])
  34. async def compute_project_stats(db: AsyncSession, project_id: int, target_count: int | None = None) -> ProjectStats:
  35. """Compute statistics for a project."""
  36. # Count total archives (distinct print jobs)
  37. total_result = await db.execute(select(func.count(PrintArchive.id)).where(PrintArchive.project_id == project_id))
  38. total_archives = total_result.scalar() or 0
  39. # Sum total items (using quantity field)
  40. total_items_result = await db.execute(
  41. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(PrintArchive.project_id == project_id)
  42. )
  43. total_items = total_items_result.scalar() or 0
  44. # Sum completed items (using quantity field)
  45. completed_result = await db.execute(
  46. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  47. PrintArchive.project_id == project_id, PrintArchive.status == "completed"
  48. )
  49. )
  50. completed_prints = completed_result.scalar() or 0
  51. # Sum failed items (using quantity field)
  52. failed_result = await db.execute(
  53. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  54. PrintArchive.project_id == project_id, PrintArchive.status == "failed"
  55. )
  56. )
  57. failed_prints = failed_result.scalar() or 0
  58. # Sum print time, filament, and energy
  59. sums_result = await db.execute(
  60. select(
  61. func.coalesce(func.sum(PrintArchive.print_time_seconds), 0).label("total_time"),
  62. func.coalesce(func.sum(PrintArchive.filament_used_grams), 0).label("total_filament"),
  63. func.coalesce(func.sum(PrintArchive.cost), 0).label("total_filament_cost"),
  64. func.coalesce(func.sum(PrintArchive.energy_kwh), 0).label("total_energy"),
  65. func.coalesce(func.sum(PrintArchive.energy_cost), 0).label("total_energy_cost"),
  66. ).where(PrintArchive.project_id == project_id)
  67. )
  68. sums = sums_result.first()
  69. # Count queued items
  70. queued_result = await db.execute(
  71. select(func.count(PrintQueueItem.id)).where(
  72. PrintQueueItem.project_id == project_id, PrintQueueItem.status == "pending"
  73. )
  74. )
  75. queued_prints = queued_result.scalar() or 0
  76. # Count in-progress items
  77. in_progress_result = await db.execute(
  78. select(func.count(PrintQueueItem.id)).where(
  79. PrintQueueItem.project_id == project_id, PrintQueueItem.status == "printing"
  80. )
  81. )
  82. in_progress_prints = in_progress_result.scalar() or 0
  83. # Calculate progress
  84. progress_percent = None
  85. remaining_prints = None
  86. if target_count and target_count > 0:
  87. progress_percent = round((completed_prints / target_count) * 100, 1)
  88. remaining_prints = max(0, target_count - completed_prints)
  89. # BOM stats
  90. bom_result = await db.execute(
  91. select(
  92. func.count(ProjectBOMItem.id).label("total"),
  93. func.sum(case((ProjectBOMItem.quantity_acquired >= ProjectBOMItem.quantity_needed, 1), else_=0)).label(
  94. "completed"
  95. ),
  96. ).where(ProjectBOMItem.project_id == project_id)
  97. )
  98. bom_stats = bom_result.first()
  99. return ProjectStats(
  100. total_archives=total_archives,
  101. total_items=int(total_items),
  102. completed_prints=int(completed_prints),
  103. failed_prints=int(failed_prints),
  104. queued_prints=queued_prints,
  105. in_progress_prints=in_progress_prints,
  106. total_print_time_hours=round((sums.total_time or 0) / 3600, 2),
  107. total_filament_grams=round(sums.total_filament or 0, 2),
  108. progress_percent=progress_percent,
  109. estimated_cost=round((sums.total_filament_cost or 0), 2),
  110. total_energy_kwh=round((sums.total_energy or 0), 3),
  111. total_energy_cost=round((sums.total_energy_cost or 0), 2),
  112. remaining_prints=remaining_prints,
  113. bom_total_items=bom_stats.total or 0,
  114. bom_completed_items=int(bom_stats.completed or 0),
  115. )
  116. @router.get("", response_model=list[ProjectListResponse])
  117. @router.get("/", response_model=list[ProjectListResponse])
  118. async def list_projects(
  119. status: str | None = None,
  120. db: AsyncSession = Depends(get_db),
  121. ):
  122. """List all projects with basic stats."""
  123. query = select(Project)
  124. if status:
  125. query = query.where(Project.status == status)
  126. query = query.order_by(Project.updated_at.desc())
  127. result = await db.execute(query)
  128. projects = result.scalars().all()
  129. # Compute quick stats for each project
  130. response = []
  131. for project in projects:
  132. # Get archive count (number of print jobs)
  133. archive_count_result = await db.execute(
  134. select(func.count(PrintArchive.id)).where(PrintArchive.project_id == project.id)
  135. )
  136. archive_count = archive_count_result.scalar() or 0
  137. # Get total items (sum of quantities)
  138. total_items_result = await db.execute(
  139. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(PrintArchive.project_id == project.id)
  140. )
  141. total_items = int(total_items_result.scalar() or 0)
  142. # Get queue count
  143. queue_count_result = await db.execute(
  144. select(func.count(PrintQueueItem.id)).where(
  145. PrintQueueItem.project_id == project.id,
  146. PrintQueueItem.status.in_(["pending", "printing"]),
  147. )
  148. )
  149. queue_count = queue_count_result.scalar() or 0
  150. # Get completed count for progress (sum of quantities)
  151. completed_result = await db.execute(
  152. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  153. PrintArchive.project_id == project.id,
  154. PrintArchive.status == "completed",
  155. )
  156. )
  157. completed_count = int(completed_result.scalar() or 0)
  158. progress_percent = None
  159. if project.target_count and project.target_count > 0:
  160. progress_percent = round((completed_count / project.target_count) * 100, 1)
  161. # Get archive previews (up to 6 most recent)
  162. archives_result = await db.execute(
  163. select(PrintArchive)
  164. .where(PrintArchive.project_id == project.id)
  165. .order_by(PrintArchive.created_at.desc())
  166. .limit(6)
  167. )
  168. archives = archives_result.scalars().all()
  169. archive_previews = [
  170. ArchivePreview(
  171. id=a.id,
  172. print_name=a.print_name,
  173. thumbnail_path=a.thumbnail_path,
  174. status=a.status,
  175. filament_type=a.filament_type,
  176. filament_color=a.filament_color,
  177. )
  178. for a in archives
  179. ]
  180. response.append(
  181. ProjectListResponse(
  182. id=project.id,
  183. name=project.name,
  184. description=project.description,
  185. color=project.color,
  186. status=project.status,
  187. target_count=project.target_count,
  188. created_at=project.created_at,
  189. archive_count=archive_count,
  190. total_items=total_items,
  191. queue_count=queue_count,
  192. progress_percent=progress_percent,
  193. archives=archive_previews,
  194. )
  195. )
  196. return response
  197. @router.post("/", response_model=ProjectResponse)
  198. async def create_project(
  199. data: ProjectCreate,
  200. db: AsyncSession = Depends(get_db),
  201. ):
  202. """Create a new project."""
  203. # Verify parent exists if specified
  204. parent_name = None
  205. if data.parent_id:
  206. parent_result = await db.execute(select(Project).where(Project.id == data.parent_id))
  207. parent = parent_result.scalar_one_or_none()
  208. if not parent:
  209. raise HTTPException(status_code=400, detail="Parent project not found")
  210. parent_name = parent.name
  211. project = Project(
  212. name=data.name,
  213. description=data.description,
  214. color=data.color,
  215. target_count=data.target_count,
  216. notes=data.notes,
  217. tags=data.tags,
  218. due_date=data.due_date,
  219. priority=data.priority,
  220. budget=data.budget,
  221. parent_id=data.parent_id,
  222. )
  223. db.add(project)
  224. await db.flush()
  225. await db.refresh(project)
  226. stats = await compute_project_stats(db, project.id, project.target_count)
  227. return ProjectResponse(
  228. id=project.id,
  229. name=project.name,
  230. description=project.description,
  231. color=project.color,
  232. status=project.status,
  233. target_count=project.target_count,
  234. notes=project.notes,
  235. attachments=project.attachments,
  236. tags=project.tags,
  237. due_date=project.due_date,
  238. priority=project.priority,
  239. budget=project.budget,
  240. is_template=project.is_template,
  241. template_source_id=project.template_source_id,
  242. parent_id=project.parent_id,
  243. parent_name=parent_name,
  244. children=[],
  245. created_at=project.created_at,
  246. updated_at=project.updated_at,
  247. stats=stats,
  248. )
  249. # ============ Phase 8: Template Endpoints (Static routes BEFORE dynamic {project_id}) ============
  250. @router.get("/templates", response_model=list[ProjectListResponse])
  251. async def list_templates(
  252. db: AsyncSession = Depends(get_db),
  253. ):
  254. """List all project templates."""
  255. result = await db.execute(select(Project).where(Project.is_template.is_(True)).order_by(Project.name))
  256. templates = result.scalars().all()
  257. response = []
  258. for project in templates:
  259. # Get archive count
  260. archive_count_result = await db.execute(
  261. select(func.count(PrintArchive.id)).where(PrintArchive.project_id == project.id)
  262. )
  263. archive_count = archive_count_result.scalar() or 0
  264. response.append(
  265. ProjectListResponse(
  266. id=project.id,
  267. name=project.name,
  268. description=project.description,
  269. color=project.color,
  270. status=project.status,
  271. target_count=project.target_count,
  272. created_at=project.created_at,
  273. archive_count=archive_count,
  274. queue_count=0,
  275. progress_percent=None,
  276. archives=[],
  277. )
  278. )
  279. return response
  280. @router.post("/from-template/{template_id}", response_model=ProjectResponse)
  281. async def create_project_from_template(
  282. template_id: int,
  283. name: str = None,
  284. db: AsyncSession = Depends(get_db),
  285. ):
  286. """Create a new project from a template."""
  287. result = await db.execute(select(Project).where(Project.id == template_id))
  288. template = result.scalar_one_or_none()
  289. if not template:
  290. raise HTTPException(status_code=404, detail="Template not found")
  291. if not template.is_template:
  292. raise HTTPException(status_code=400, detail="Project is not a template")
  293. # Create new project
  294. project = Project(
  295. name=name or template.name.replace(" (Template)", ""),
  296. description=template.description,
  297. color=template.color,
  298. target_count=template.target_count,
  299. notes=template.notes,
  300. tags=template.tags,
  301. priority=template.priority,
  302. budget=template.budget,
  303. is_template=False,
  304. template_source_id=template.id,
  305. )
  306. db.add(project)
  307. await db.flush()
  308. # Copy BOM items
  309. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == template_id))
  310. bom_items = bom_result.scalars().all()
  311. for item in bom_items:
  312. new_item = ProjectBOMItem(
  313. project_id=project.id,
  314. name=item.name,
  315. quantity_needed=item.quantity_needed,
  316. quantity_acquired=0,
  317. unit_price=item.unit_price,
  318. sourcing_url=item.sourcing_url,
  319. stl_filename=item.stl_filename,
  320. remarks=item.remarks,
  321. sort_order=item.sort_order,
  322. )
  323. db.add(new_item)
  324. await db.flush()
  325. await db.refresh(project)
  326. stats = await compute_project_stats(db, project.id, project.target_count)
  327. return ProjectResponse(
  328. id=project.id,
  329. name=project.name,
  330. description=project.description,
  331. color=project.color,
  332. status=project.status,
  333. target_count=project.target_count,
  334. notes=project.notes,
  335. attachments=project.attachments,
  336. tags=project.tags,
  337. due_date=project.due_date,
  338. priority=project.priority,
  339. budget=project.budget,
  340. is_template=project.is_template,
  341. template_source_id=project.template_source_id,
  342. parent_id=project.parent_id,
  343. parent_name=None,
  344. children=[],
  345. created_at=project.created_at,
  346. updated_at=project.updated_at,
  347. stats=stats,
  348. )
  349. # ============ Dynamic {project_id} Routes ============
  350. async def get_child_previews(db: AsyncSession, parent_id: int) -> list[ProjectChildPreview]:
  351. """Get preview info for child projects."""
  352. result = await db.execute(select(Project).where(Project.parent_id == parent_id).order_by(Project.name))
  353. children = result.scalars().all()
  354. previews = []
  355. for child in children:
  356. # Get completed count for progress (sum of quantities)
  357. completed_result = await db.execute(
  358. select(func.coalesce(func.sum(PrintArchive.quantity), 0)).where(
  359. PrintArchive.project_id == child.id,
  360. PrintArchive.status == "completed",
  361. )
  362. )
  363. completed_count = completed_result.scalar() or 0
  364. progress = None
  365. if child.target_count and child.target_count > 0:
  366. progress = round((int(completed_count) / child.target_count) * 100, 1)
  367. previews.append(
  368. ProjectChildPreview(
  369. id=child.id,
  370. name=child.name,
  371. color=child.color,
  372. status=child.status,
  373. progress_percent=progress,
  374. )
  375. )
  376. return previews
  377. @router.get("/{project_id}", response_model=ProjectResponse)
  378. async def get_project(
  379. project_id: int,
  380. db: AsyncSession = Depends(get_db),
  381. ):
  382. """Get a project by ID with detailed stats."""
  383. result = await db.execute(select(Project).where(Project.id == project_id))
  384. project = result.scalar_one_or_none()
  385. if not project:
  386. raise HTTPException(status_code=404, detail="Project not found")
  387. # Get parent name
  388. parent_name = None
  389. if project.parent_id:
  390. parent_result = await db.execute(select(Project.name).where(Project.id == project.parent_id))
  391. parent_name = parent_result.scalar()
  392. # Get children
  393. children = await get_child_previews(db, project.id)
  394. stats = await compute_project_stats(db, project.id, project.target_count)
  395. return ProjectResponse(
  396. id=project.id,
  397. name=project.name,
  398. description=project.description,
  399. color=project.color,
  400. status=project.status,
  401. target_count=project.target_count,
  402. notes=project.notes,
  403. attachments=project.attachments,
  404. tags=project.tags,
  405. due_date=project.due_date,
  406. priority=project.priority,
  407. budget=project.budget,
  408. is_template=project.is_template,
  409. template_source_id=project.template_source_id,
  410. parent_id=project.parent_id,
  411. parent_name=parent_name,
  412. children=children,
  413. created_at=project.created_at,
  414. updated_at=project.updated_at,
  415. stats=stats,
  416. )
  417. @router.patch("/{project_id}", response_model=ProjectResponse)
  418. async def update_project(
  419. project_id: int,
  420. data: ProjectUpdate,
  421. db: AsyncSession = Depends(get_db),
  422. ):
  423. """Update a project."""
  424. result = await db.execute(select(Project).where(Project.id == project_id))
  425. project = result.scalar_one_or_none()
  426. if not project:
  427. raise HTTPException(status_code=404, detail="Project not found")
  428. # Update fields if provided
  429. if data.name is not None:
  430. project.name = data.name
  431. if data.description is not None:
  432. project.description = data.description
  433. if data.color is not None:
  434. project.color = data.color
  435. if data.status is not None:
  436. if data.status not in ["active", "completed", "archived"]:
  437. raise HTTPException(status_code=400, detail="Invalid status")
  438. project.status = data.status
  439. if data.target_count is not None:
  440. project.target_count = data.target_count
  441. if data.notes is not None:
  442. project.notes = data.notes
  443. if data.tags is not None:
  444. project.tags = data.tags
  445. if data.due_date is not None:
  446. project.due_date = data.due_date
  447. if data.priority is not None:
  448. if data.priority not in ["low", "normal", "high", "urgent"]:
  449. raise HTTPException(status_code=400, detail="Invalid priority")
  450. project.priority = data.priority
  451. if data.budget is not None:
  452. project.budget = data.budget
  453. if data.parent_id is not None:
  454. # Verify parent exists and prevent circular reference
  455. if data.parent_id == project_id:
  456. raise HTTPException(status_code=400, detail="Project cannot be its own parent")
  457. if data.parent_id != 0: # 0 means remove parent
  458. parent_result = await db.execute(select(Project).where(Project.id == data.parent_id))
  459. if not parent_result.scalar_one_or_none():
  460. raise HTTPException(status_code=400, detail="Parent project not found")
  461. project.parent_id = data.parent_id
  462. else:
  463. project.parent_id = None
  464. await db.flush()
  465. await db.refresh(project)
  466. # Get parent name
  467. parent_name = None
  468. if project.parent_id:
  469. parent_result = await db.execute(select(Project.name).where(Project.id == project.parent_id))
  470. parent_name = parent_result.scalar()
  471. # Get children
  472. children = await get_child_previews(db, project.id)
  473. stats = await compute_project_stats(db, project.id, project.target_count)
  474. return ProjectResponse(
  475. id=project.id,
  476. name=project.name,
  477. description=project.description,
  478. color=project.color,
  479. status=project.status,
  480. target_count=project.target_count,
  481. notes=project.notes,
  482. attachments=project.attachments,
  483. tags=project.tags,
  484. due_date=project.due_date,
  485. priority=project.priority,
  486. budget=project.budget,
  487. is_template=project.is_template,
  488. template_source_id=project.template_source_id,
  489. parent_id=project.parent_id,
  490. parent_name=parent_name,
  491. children=children,
  492. created_at=project.created_at,
  493. updated_at=project.updated_at,
  494. stats=stats,
  495. )
  496. @router.delete("/{project_id}")
  497. async def delete_project(
  498. project_id: int,
  499. db: AsyncSession = Depends(get_db),
  500. ):
  501. """Delete a project. Archives and queue items will have project_id set to NULL."""
  502. result = await db.execute(select(Project).where(Project.id == project_id))
  503. project = result.scalar_one_or_none()
  504. if not project:
  505. raise HTTPException(status_code=404, detail="Project not found")
  506. await db.delete(project)
  507. return {"message": "Project deleted"}
  508. @router.get("/{project_id}/archives")
  509. async def list_project_archives(
  510. project_id: int,
  511. limit: int = 100,
  512. offset: int = 0,
  513. db: AsyncSession = Depends(get_db),
  514. ):
  515. """List archives in a project."""
  516. # Verify project exists
  517. result = await db.execute(select(Project).where(Project.id == project_id))
  518. if not result.scalar_one_or_none():
  519. raise HTTPException(status_code=404, detail="Project not found")
  520. # Get archives with project relationship eagerly loaded
  521. query = (
  522. select(PrintArchive)
  523. .options(selectinload(PrintArchive.project))
  524. .where(PrintArchive.project_id == project_id)
  525. .order_by(PrintArchive.created_at.desc())
  526. .limit(limit)
  527. .offset(offset)
  528. )
  529. result = await db.execute(query)
  530. archives = result.scalars().all()
  531. # Import the response converter from archives module
  532. from backend.app.api.routes.archives import archive_to_response
  533. return [archive_to_response(a) for a in archives]
  534. @router.get("/{project_id}/queue")
  535. async def list_project_queue(
  536. project_id: int,
  537. db: AsyncSession = Depends(get_db),
  538. ):
  539. """List queue items in a project."""
  540. # Verify project exists
  541. result = await db.execute(select(Project).where(Project.id == project_id))
  542. if not result.scalar_one_or_none():
  543. raise HTTPException(status_code=404, detail="Project not found")
  544. # Get queue items
  545. query = select(PrintQueueItem).where(PrintQueueItem.project_id == project_id).order_by(PrintQueueItem.position)
  546. result = await db.execute(query)
  547. items = result.scalars().all()
  548. return items
  549. @router.post("/{project_id}/add-archives")
  550. async def add_archives_to_project(
  551. project_id: int,
  552. data: BatchAddArchives,
  553. db: AsyncSession = Depends(get_db),
  554. ):
  555. """Batch add archives to a project."""
  556. # Verify project exists
  557. result = await db.execute(select(Project).where(Project.id == project_id))
  558. if not result.scalar_one_or_none():
  559. raise HTTPException(status_code=404, detail="Project not found")
  560. # Update archives
  561. updated = 0
  562. for archive_id in data.archive_ids:
  563. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  564. archive = result.scalar_one_or_none()
  565. if archive:
  566. archive.project_id = project_id
  567. updated += 1
  568. return {"message": f"Added {updated} archives to project"}
  569. @router.post("/{project_id}/add-queue")
  570. async def add_queue_items_to_project(
  571. project_id: int,
  572. data: BatchAddQueueItems,
  573. db: AsyncSession = Depends(get_db),
  574. ):
  575. """Batch add queue items to a project."""
  576. # Verify project exists
  577. result = await db.execute(select(Project).where(Project.id == project_id))
  578. if not result.scalar_one_or_none():
  579. raise HTTPException(status_code=404, detail="Project not found")
  580. # Update queue items
  581. updated = 0
  582. for item_id in data.queue_item_ids:
  583. result = await db.execute(select(PrintQueueItem).where(PrintQueueItem.id == item_id))
  584. item = result.scalar_one_or_none()
  585. if item:
  586. item.project_id = project_id
  587. updated += 1
  588. return {"message": f"Added {updated} queue items to project"}
  589. @router.post("/{project_id}/remove-archives")
  590. async def remove_archives_from_project(
  591. project_id: int,
  592. data: BatchAddArchives,
  593. db: AsyncSession = Depends(get_db),
  594. ):
  595. """Remove archives from a project (sets project_id to NULL)."""
  596. updated = 0
  597. for archive_id in data.archive_ids:
  598. result = await db.execute(
  599. select(PrintArchive).where(
  600. PrintArchive.id == archive_id,
  601. PrintArchive.project_id == project_id,
  602. )
  603. )
  604. archive = result.scalar_one_or_none()
  605. if archive:
  606. archive.project_id = None
  607. updated += 1
  608. return {"message": f"Removed {updated} archives from project"}
  609. def get_project_attachments_dir(project_id: int) -> Path:
  610. """Get the attachments directory for a project."""
  611. base_dir = Path(settings.archive_dir)
  612. return base_dir / "projects" / str(project_id) / "attachments"
  613. # Allowed file extensions for attachments
  614. ALLOWED_ATTACHMENT_EXTENSIONS = {
  615. # Images
  616. ".jpg",
  617. ".jpeg",
  618. ".png",
  619. ".gif",
  620. ".webp",
  621. ".svg",
  622. ".bmp",
  623. ".ico",
  624. # Documents
  625. ".pdf",
  626. ".doc",
  627. ".docx",
  628. ".xls",
  629. ".xlsx",
  630. ".ppt",
  631. ".pptx",
  632. ".odt",
  633. ".ods",
  634. ".odp",
  635. ".txt",
  636. ".rtf",
  637. ".csv",
  638. ".md",
  639. # 3D/CAD files
  640. ".stl",
  641. ".obj",
  642. ".3mf",
  643. ".step",
  644. ".stp",
  645. ".iges",
  646. ".igs",
  647. ".f3d",
  648. ".scad",
  649. # Archives
  650. ".zip",
  651. ".rar",
  652. ".7z",
  653. ".tar",
  654. ".gz",
  655. # Code/scripts (for Klipper macros, scripts, etc.)
  656. ".py",
  657. ".sh",
  658. ".cfg",
  659. ".conf",
  660. ".gcode",
  661. ".ini",
  662. # Other common formats
  663. ".json",
  664. ".xml",
  665. ".yaml",
  666. ".yml",
  667. }
  668. @router.post("/{project_id}/attachments")
  669. async def upload_attachment(
  670. project_id: int,
  671. file: UploadFile = File(...),
  672. db: AsyncSession = Depends(get_db),
  673. ):
  674. """Upload an attachment to a project."""
  675. logger.info(f"=== UPLOAD START: {file.filename} for project {project_id} ===")
  676. # Verify project exists
  677. result = await db.execute(select(Project).where(Project.id == project_id))
  678. project = result.scalar_one_or_none()
  679. if not project:
  680. raise HTTPException(status_code=404, detail="Project not found")
  681. # Validate file extension
  682. original_name = file.filename or "unknown"
  683. ext = os.path.splitext(original_name)[1].lower()
  684. if ext not in ALLOWED_ATTACHMENT_EXTENSIONS:
  685. raise HTTPException(
  686. status_code=400,
  687. detail=f"File type '{ext}' not supported. Allowed: images, PDFs, documents, STL, 3MF, archives.",
  688. )
  689. # Create attachments directory
  690. attachments_dir = get_project_attachments_dir(project_id)
  691. attachments_dir.mkdir(parents=True, exist_ok=True)
  692. # Generate unique filename
  693. unique_filename = f"{uuid.uuid4().hex}{ext}"
  694. file_path = attachments_dir / unique_filename
  695. # Save file
  696. try:
  697. with open(file_path, "wb") as f:
  698. content = await file.read()
  699. f.write(content)
  700. logger.info(f"=== FILE SAVED: {file_path}, size: {len(content)} ===")
  701. except Exception as e:
  702. logger.error(f"Failed to save attachment: {e}")
  703. raise HTTPException(status_code=500, detail="Failed to save attachment")
  704. # Update project attachments JSON
  705. attachments = list(project.attachments or [])
  706. new_attachment = {
  707. "filename": unique_filename,
  708. "original_name": original_name,
  709. "size": len(content),
  710. "uploaded_at": datetime.now().isoformat(),
  711. }
  712. attachments.append(new_attachment)
  713. # Simple ORM update
  714. project.attachments = attachments
  715. db.add(project) # Explicitly add to session
  716. logger.info(f"=== BEFORE COMMIT: {len(attachments)} attachments ===")
  717. await db.flush()
  718. await db.commit()
  719. logger.info("=== AFTER COMMIT ===")
  720. # Verify by re-querying
  721. result = await db.execute(select(Project).where(Project.id == project_id))
  722. fresh_project = result.scalar_one()
  723. logger.info(f"=== VERIFIED: {len(fresh_project.attachments or [])} attachments ===")
  724. return {
  725. "status": "success",
  726. "filename": unique_filename,
  727. "original_name": original_name,
  728. "attachments": fresh_project.attachments,
  729. }
  730. @router.get("/{project_id}/attachments/{filename}")
  731. async def download_attachment(
  732. project_id: int,
  733. filename: str,
  734. db: AsyncSession = Depends(get_db),
  735. ):
  736. """Download an attachment from a project."""
  737. # Verify project exists
  738. result = await db.execute(select(Project).where(Project.id == project_id))
  739. project = result.scalar_one_or_none()
  740. if not project:
  741. raise HTTPException(status_code=404, detail="Project not found")
  742. # Verify attachment exists in project
  743. attachments = project.attachments or []
  744. attachment = next((a for a in attachments if a.get("filename") == filename), None)
  745. if not attachment:
  746. raise HTTPException(status_code=404, detail="Attachment not found")
  747. # Check file exists
  748. file_path = get_project_attachments_dir(project_id) / filename
  749. if not file_path.exists():
  750. raise HTTPException(status_code=404, detail="Attachment file not found")
  751. return FileResponse(
  752. file_path,
  753. filename=attachment.get("original_name", filename),
  754. media_type="application/octet-stream",
  755. )
  756. @router.delete("/{project_id}/attachments/{filename}")
  757. async def delete_attachment(
  758. project_id: int,
  759. filename: str,
  760. db: AsyncSession = Depends(get_db),
  761. ):
  762. """Delete an attachment from a project."""
  763. # Verify project exists
  764. result = await db.execute(select(Project).where(Project.id == project_id))
  765. project = result.scalar_one_or_none()
  766. if not project:
  767. raise HTTPException(status_code=404, detail="Project not found")
  768. # Find and remove attachment from list
  769. attachments = project.attachments or []
  770. attachment = next((a for a in attachments if a.get("filename") == filename), None)
  771. if not attachment:
  772. raise HTTPException(status_code=404, detail="Attachment not found")
  773. # Remove from list
  774. attachments = [a for a in attachments if a.get("filename") != filename]
  775. project.attachments = attachments if attachments else None
  776. # Delete file
  777. file_path = get_project_attachments_dir(project_id) / filename
  778. if file_path.exists():
  779. try:
  780. os.remove(file_path)
  781. except Exception as e:
  782. logger.warning(f"Failed to delete attachment file: {e}")
  783. await db.flush()
  784. await db.refresh(project)
  785. return {
  786. "status": "success",
  787. "message": "Attachment deleted",
  788. "attachments": project.attachments,
  789. }
  790. # ============ Phase 7: BOM Endpoints ============
  791. @router.get("/{project_id}/bom", response_model=list[BOMItemResponse])
  792. async def list_bom_items(
  793. project_id: int,
  794. db: AsyncSession = Depends(get_db),
  795. ):
  796. """List all BOM items for a project."""
  797. # Verify project exists
  798. result = await db.execute(select(Project).where(Project.id == project_id))
  799. if not result.scalar_one_or_none():
  800. raise HTTPException(status_code=404, detail="Project not found")
  801. # Get BOM items
  802. result = await db.execute(
  803. select(ProjectBOMItem)
  804. .where(ProjectBOMItem.project_id == project_id)
  805. .order_by(ProjectBOMItem.sort_order, ProjectBOMItem.id)
  806. )
  807. items = result.scalars().all()
  808. response = []
  809. for item in items:
  810. # Get archive name if linked
  811. archive_name = None
  812. if item.archive_id:
  813. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  814. archive_name = archive_result.scalar()
  815. response.append(
  816. BOMItemResponse(
  817. id=item.id,
  818. project_id=item.project_id,
  819. name=item.name,
  820. quantity_needed=item.quantity_needed,
  821. quantity_acquired=item.quantity_acquired,
  822. unit_price=item.unit_price,
  823. sourcing_url=item.sourcing_url,
  824. archive_id=item.archive_id,
  825. archive_name=archive_name,
  826. stl_filename=item.stl_filename,
  827. remarks=item.remarks,
  828. sort_order=item.sort_order,
  829. is_complete=item.quantity_acquired >= item.quantity_needed,
  830. created_at=item.created_at,
  831. updated_at=item.updated_at,
  832. )
  833. )
  834. return response
  835. @router.post("/{project_id}/bom", response_model=BOMItemResponse)
  836. async def create_bom_item(
  837. project_id: int,
  838. data: BOMItemCreate,
  839. db: AsyncSession = Depends(get_db),
  840. ):
  841. """Add a BOM item to a project."""
  842. # Verify project exists
  843. result = await db.execute(select(Project).where(Project.id == project_id))
  844. if not result.scalar_one_or_none():
  845. raise HTTPException(status_code=404, detail="Project not found")
  846. # Get max sort order
  847. max_order_result = await db.execute(
  848. select(func.max(ProjectBOMItem.sort_order)).where(ProjectBOMItem.project_id == project_id)
  849. )
  850. max_order = max_order_result.scalar() or 0
  851. item = ProjectBOMItem(
  852. project_id=project_id,
  853. name=data.name,
  854. quantity_needed=data.quantity_needed,
  855. unit_price=data.unit_price,
  856. sourcing_url=data.sourcing_url,
  857. archive_id=data.archive_id,
  858. stl_filename=data.stl_filename,
  859. remarks=data.remarks,
  860. sort_order=max_order + 1,
  861. )
  862. db.add(item)
  863. await db.flush()
  864. await db.refresh(item)
  865. # Get archive name if linked
  866. archive_name = None
  867. if item.archive_id:
  868. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  869. archive_name = archive_result.scalar()
  870. return BOMItemResponse(
  871. id=item.id,
  872. project_id=item.project_id,
  873. name=item.name,
  874. quantity_needed=item.quantity_needed,
  875. quantity_acquired=item.quantity_acquired,
  876. unit_price=item.unit_price,
  877. sourcing_url=item.sourcing_url,
  878. archive_id=item.archive_id,
  879. archive_name=archive_name,
  880. stl_filename=item.stl_filename,
  881. remarks=item.remarks,
  882. sort_order=item.sort_order,
  883. is_complete=item.quantity_acquired >= item.quantity_needed,
  884. created_at=item.created_at,
  885. updated_at=item.updated_at,
  886. )
  887. @router.patch("/{project_id}/bom/{item_id}", response_model=BOMItemResponse)
  888. async def update_bom_item(
  889. project_id: int,
  890. item_id: int,
  891. data: BOMItemUpdate,
  892. db: AsyncSession = Depends(get_db),
  893. ):
  894. """Update a BOM item."""
  895. result = await db.execute(
  896. select(ProjectBOMItem).where(
  897. ProjectBOMItem.id == item_id,
  898. ProjectBOMItem.project_id == project_id,
  899. )
  900. )
  901. item = result.scalar_one_or_none()
  902. if not item:
  903. raise HTTPException(status_code=404, detail="BOM item not found")
  904. if data.name is not None:
  905. item.name = data.name
  906. if data.quantity_needed is not None:
  907. item.quantity_needed = data.quantity_needed
  908. if data.quantity_acquired is not None:
  909. item.quantity_acquired = data.quantity_acquired
  910. if data.unit_price is not None:
  911. item.unit_price = data.unit_price if data.unit_price != 0 else None
  912. if data.sourcing_url is not None:
  913. item.sourcing_url = data.sourcing_url if data.sourcing_url else None
  914. if data.archive_id is not None:
  915. item.archive_id = data.archive_id if data.archive_id != 0 else None
  916. if data.stl_filename is not None:
  917. item.stl_filename = data.stl_filename if data.stl_filename else None
  918. if data.remarks is not None:
  919. item.remarks = data.remarks if data.remarks else None
  920. await db.flush()
  921. await db.refresh(item)
  922. # Get archive name if linked
  923. archive_name = None
  924. if item.archive_id:
  925. archive_result = await db.execute(select(PrintArchive.print_name).where(PrintArchive.id == item.archive_id))
  926. archive_name = archive_result.scalar()
  927. return BOMItemResponse(
  928. id=item.id,
  929. project_id=item.project_id,
  930. name=item.name,
  931. quantity_needed=item.quantity_needed,
  932. quantity_acquired=item.quantity_acquired,
  933. unit_price=item.unit_price,
  934. sourcing_url=item.sourcing_url,
  935. archive_id=item.archive_id,
  936. archive_name=archive_name,
  937. stl_filename=item.stl_filename,
  938. remarks=item.remarks,
  939. sort_order=item.sort_order,
  940. is_complete=item.quantity_acquired >= item.quantity_needed,
  941. created_at=item.created_at,
  942. updated_at=item.updated_at,
  943. )
  944. @router.delete("/{project_id}/bom/{item_id}")
  945. async def delete_bom_item(
  946. project_id: int,
  947. item_id: int,
  948. db: AsyncSession = Depends(get_db),
  949. ):
  950. """Delete a BOM item."""
  951. result = await db.execute(
  952. select(ProjectBOMItem).where(
  953. ProjectBOMItem.id == item_id,
  954. ProjectBOMItem.project_id == project_id,
  955. )
  956. )
  957. item = result.scalar_one_or_none()
  958. if not item:
  959. raise HTTPException(status_code=404, detail="BOM item not found")
  960. await db.delete(item)
  961. return {"status": "success", "message": "BOM item deleted"}
  962. @router.post("/{project_id}/create-template", response_model=ProjectResponse)
  963. async def create_template_from_project(
  964. project_id: int,
  965. db: AsyncSession = Depends(get_db),
  966. ):
  967. """Create a template from an existing project."""
  968. result = await db.execute(select(Project).where(Project.id == project_id))
  969. source = result.scalar_one_or_none()
  970. if not source:
  971. raise HTTPException(status_code=404, detail="Project not found")
  972. # Create template
  973. template = Project(
  974. name=f"{source.name} (Template)",
  975. description=source.description,
  976. color=source.color,
  977. target_count=source.target_count,
  978. notes=source.notes,
  979. tags=source.tags,
  980. priority=source.priority,
  981. budget=source.budget,
  982. is_template=True,
  983. template_source_id=source.id,
  984. )
  985. db.add(template)
  986. await db.flush()
  987. # Copy BOM items
  988. bom_result = await db.execute(select(ProjectBOMItem).where(ProjectBOMItem.project_id == project_id))
  989. bom_items = bom_result.scalars().all()
  990. for item in bom_items:
  991. new_item = ProjectBOMItem(
  992. project_id=template.id,
  993. name=item.name,
  994. quantity_needed=item.quantity_needed,
  995. quantity_acquired=0,
  996. unit_price=item.unit_price,
  997. sourcing_url=item.sourcing_url,
  998. stl_filename=item.stl_filename,
  999. remarks=item.remarks,
  1000. sort_order=item.sort_order,
  1001. )
  1002. db.add(new_item)
  1003. await db.flush()
  1004. await db.refresh(template)
  1005. stats = await compute_project_stats(db, template.id, template.target_count)
  1006. return ProjectResponse(
  1007. id=template.id,
  1008. name=template.name,
  1009. description=template.description,
  1010. color=template.color,
  1011. status=template.status,
  1012. target_count=template.target_count,
  1013. notes=template.notes,
  1014. attachments=template.attachments,
  1015. tags=template.tags,
  1016. due_date=template.due_date,
  1017. priority=template.priority,
  1018. budget=template.budget,
  1019. is_template=template.is_template,
  1020. template_source_id=template.template_source_id,
  1021. parent_id=template.parent_id,
  1022. parent_name=None,
  1023. children=[],
  1024. created_at=template.created_at,
  1025. updated_at=template.updated_at,
  1026. stats=stats,
  1027. )
  1028. # ============ Phase 9: Timeline Endpoint ============
  1029. @router.get("/{project_id}/timeline", response_model=list[TimelineEvent])
  1030. async def get_project_timeline(
  1031. project_id: int,
  1032. limit: int = 50,
  1033. db: AsyncSession = Depends(get_db),
  1034. ):
  1035. """Get timeline of events for a project."""
  1036. # Verify project exists
  1037. result = await db.execute(select(Project).where(Project.id == project_id))
  1038. project = result.scalar_one_or_none()
  1039. if not project:
  1040. raise HTTPException(status_code=404, detail="Project not found")
  1041. events = []
  1042. # Project creation event
  1043. events.append(
  1044. TimelineEvent(
  1045. event_type="project_created",
  1046. timestamp=project.created_at,
  1047. title="Project created",
  1048. description=f"Project '{project.name}' was created",
  1049. )
  1050. )
  1051. # Get archives and add events
  1052. archives_result = await db.execute(
  1053. select(PrintArchive)
  1054. .where(PrintArchive.project_id == project_id)
  1055. .order_by(PrintArchive.created_at.desc())
  1056. .limit(limit)
  1057. )
  1058. archives = archives_result.scalars().all()
  1059. for archive in archives:
  1060. if archive.status == "completed":
  1061. events.append(
  1062. TimelineEvent(
  1063. event_type="print_completed",
  1064. timestamp=archive.completed_at or archive.created_at,
  1065. title="Print completed",
  1066. description=archive.print_name,
  1067. metadata={
  1068. "archive_id": archive.id,
  1069. "print_time_hours": round((archive.print_time_seconds or 0) / 3600, 2),
  1070. "filament_grams": round(archive.filament_used_grams or 0, 1),
  1071. },
  1072. )
  1073. )
  1074. elif archive.status == "failed":
  1075. events.append(
  1076. TimelineEvent(
  1077. event_type="print_failed",
  1078. timestamp=archive.completed_at or archive.created_at,
  1079. title="Print failed",
  1080. description=archive.print_name,
  1081. metadata={"archive_id": archive.id},
  1082. )
  1083. )
  1084. # Get queue items
  1085. queue_result = await db.execute(
  1086. select(PrintQueueItem)
  1087. .where(PrintQueueItem.project_id == project_id)
  1088. .order_by(PrintQueueItem.created_at.desc())
  1089. .limit(limit)
  1090. )
  1091. queue_items = queue_result.scalars().all()
  1092. for item in queue_items:
  1093. if item.status == "printing":
  1094. events.append(
  1095. TimelineEvent(
  1096. event_type="print_started",
  1097. timestamp=item.started_at or item.created_at,
  1098. title="Print started",
  1099. description=item.print_name,
  1100. metadata={"queue_item_id": item.id},
  1101. )
  1102. )
  1103. elif item.status == "pending":
  1104. events.append(
  1105. TimelineEvent(
  1106. event_type="queued",
  1107. timestamp=item.created_at,
  1108. title="Added to queue",
  1109. description=item.print_name,
  1110. metadata={"queue_item_id": item.id},
  1111. )
  1112. )
  1113. # Sort by timestamp descending
  1114. events.sort(key=lambda e: e.timestamp, reverse=True)
  1115. return events[:limit]