projects.py 42 KB

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