File size: 5,165 Bytes
d57efd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
from api.router.user import user_dependency
from fastapi.responses import JSONResponse
from fastapi import APIRouter, HTTPException, Depends, Query

from db.models import Category
from db.database import get_db
from service.dto import CategoryCreate

from script.vector_db import IndexManager
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError, IntegrityError

from typing import Annotated

router = APIRouter(tags=["Category"])

index_manager = IndexManager()
db_dependency = Annotated[Session, Depends(get_db)]


@router.get("/category")
async def get_all_categories(user: user_dependency, db: db_dependency):
    if user is None or user.get("role_id") != 1:
        return JSONResponse(status_code=401, content="Authentication Failed")

    try:
        # Logic to retrieve all categories
        categories = db.query(Category).all()
        if not categories:
            return JSONResponse(status_code=404, content="No categories found")

        return {
            "message": "Categories retrieved successfully",
            "categories": [
                {"id": cat.id, "category": cat.category} for cat in categories
            ],
        }

    except SQLAlchemyError as e:
        return JSONResponse(
            status_code=500, content="Database error occurred: " + str(e)
        )


@router.get("/category/{category_id}")
async def get_categories_by_ids(
    user: user_dependency,
    db: db_dependency,
    category_id: int,
):
    if user is None or user.get("role_id") != 1:
        return JSONResponse(status_code=401, content="Authentication Failed")

    try:
        # Fetch categories based on the list of provided category_ids
        category = db.query(Category).filter(Category.id == category_id).first()

        if category is None:
            return JSONResponse(status_code=404, content="No categories found for the given IDs")

        return {
            "message": "Categories retrieved successfully",
            "category": {"id": category.id, "category": category.category},
        }

    except SQLAlchemyError as e:
        return JSONResponse(
            status_code=500, content="Database error occurred: " + str(e)
        )

@router.post("/category")
async def create_category(user: user_dependency, db: db_dependency, category: CategoryCreate):
    if user is None or user.get("role_id") != 1:
        return JSONResponse(status_code=401, content="Authentication Failed")

    try:
        # Check if category already exists
        existing_category = (
            db.query(Category).filter(Category.category == category.category_name).first()
        )
        if existing_category:
            return JSONResponse(status_code=400, content="Category already exists")

        # Logic to create a new category
        new_category = Category(category=category)  # Assuming Category is your model
        db.add(new_category)
        db.commit()
        db.refresh(new_category)

        return {
            "message": "Category created successfully",
            "category_id": new_category.id,
        }

    except IntegrityError:
        db.rollback()
        return JSONResponse(
            status_code=400,
            content="Database integrity error: possibly a duplicate entry.",
        )

    except SQLAlchemyError as e:
        db.rollback()
        return JSONResponse(
            status_code=500, content="Database error occurred: " + str(e)
        )


@router.put("/category/{category_id}")
async def update_category(
    user: user_dependency, db: db_dependency, category_id: int, category: CategoryCreate
):
    if user is None or user.get("role_id") != 1:
        return JSONResponse(status_code=401, content="Authentication Failed")

    try:
        # Logic to update an existing category
        existing_category = (
            db.query(Category).filter(Category.id == category_id).first()
        )
        if not existing_category:
            return JSONResponse(status_code=404, content="Category not found")

        existing_category.category = category.category_name
        db.commit()

        return {"message": "Category updated successfully"}

    except SQLAlchemyError as e:
        db.rollback()
        return JSONResponse(
            status_code=500, content="Database error occurred: " + str(e)
        )


@router.delete("/category/{category_id}")
async def delete_category(user: user_dependency, db: db_dependency, category_id: int):
    if user is None or user.get("role_id") != 1:
        return JSONResponse(status_code=401, content="Authentication Failed")

    try:
        # Logic to delete an existing category
        existing_category = (
            db.query(Category).filter(Category.id == category_id).first()
        )
        if not existing_category:
            return JSONResponse(status_code=404, content="Category not found")

        db.delete(existing_category)
        db.commit()

        return {"message": "Category deleted successfully"}

    except SQLAlchemyError as e:
        db.rollback()
        return JSONResponse(
            status_code=500, content="Database error occurred: " + str(e)
        )