File size: 2,175 Bytes
b34e73d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""
AlgoPharma — Projects API router.
"""

import json
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.orm import Session

from database import get_db
from models import Project, Keyword

router = APIRouter(prefix="/api/projects", tags=["Projects"])


class ProjectCreate(BaseModel):
    name: str
    description: str = ""


class KeywordCreate(BaseModel):
    term: str
    synonyms: list[str] = []


@router.post("")
def create_project(body: ProjectCreate, db: Session = Depends(get_db)):
    existing = db.query(Project).filter(Project.name == body.name).first()
    if existing:
        raise HTTPException(status_code=409, detail="Project with this name already exists")
    project = Project(name=body.name, description=body.description)
    db.add(project)
    db.commit()
    db.refresh(project)
    return {"id": project.id, "name": project.name, "description": project.description}


@router.get("")
def list_projects(db: Session = Depends(get_db)):
    projects = db.query(Project).all()
    return [
        {"id": p.id, "name": p.name, "description": p.description,
         "created_at": str(p.created_at)}
        for p in projects
    ]


@router.post("/{project_id}/keywords")
def add_keyword(project_id: int, body: KeywordCreate, db: Session = Depends(get_db)):
    project = db.get(Project, project_id)
    if not project:
        raise HTTPException(status_code=404, detail="Project not found")
    kw = Keyword(
        project_id=project_id,
        term=body.term,
        synonyms=json.dumps(body.synonyms),
    )
    db.add(kw)
    db.commit()
    db.refresh(kw)
    return {"id": kw.id, "term": kw.term, "synonyms": body.synonyms}


@router.get("/{project_id}/keywords")
def list_keywords(project_id: int, db: Session = Depends(get_db)):
    project = db.get(Project, project_id)
    if not project:
        raise HTTPException(status_code=404, detail="Project not found")
    keywords = db.query(Keyword).filter(Keyword.project_id == project_id).all()
    return [
        {"id": k.id, "term": k.term, "synonyms": json.loads(k.synonyms) if k.synonyms else []}
        for k in keywords
    ]