Обновление приложения
This commit is contained in:
51
backend/app/api/v1/relations.py
Normal file
51
backend/app/api/v1/relations.py
Normal file
@@ -0,0 +1,51 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from app.auth.dependencies import get_current_user
|
||||
from app.database import get_db
|
||||
from app.models.operation import Operation, OperationRelation
|
||||
from app.models.user import User
|
||||
from app.schemas.operation import OperationRelationCreate, OperationRelationOut
|
||||
|
||||
router = APIRouter(prefix="/operation-relations", tags=["operation-relations"])
|
||||
|
||||
|
||||
@router.get("/{operation_id}", response_model=list[OperationRelationOut])
|
||||
def list_relations(
|
||||
operation_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
|
||||
):
|
||||
op = db.get(Operation, operation_id)
|
||||
if not op or op.user_id != current_user.id:
|
||||
raise HTTPException(status_code=404, detail="Operation not found")
|
||||
return db.query(OperationRelation).filter(
|
||||
(OperationRelation.operation_from_id == operation_id) |
|
||||
(OperationRelation.operation_to_id == operation_id)
|
||||
).all()
|
||||
|
||||
|
||||
@router.post("", response_model=OperationRelationOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_relation(
|
||||
body: OperationRelationCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
|
||||
):
|
||||
for op_id in (body.operation_from_id, body.operation_to_id):
|
||||
op = db.get(Operation, op_id)
|
||||
if not op or op.user_id != current_user.id:
|
||||
raise HTTPException(status_code=404, detail=f"Operation {op_id} not found")
|
||||
obj = OperationRelation(**body.model_dump())
|
||||
db.add(obj)
|
||||
db.commit()
|
||||
db.refresh(obj)
|
||||
return obj
|
||||
|
||||
|
||||
@router.delete("/{relation_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_relation(
|
||||
relation_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)
|
||||
):
|
||||
obj = db.get(OperationRelation, relation_id)
|
||||
if not obj:
|
||||
raise HTTPException(status_code=404, detail="Relation not found")
|
||||
op = db.get(Operation, obj.operation_from_id)
|
||||
if not op or op.user_id != current_user.id:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
db.delete(obj)
|
||||
db.commit()
|
||||
Reference in New Issue
Block a user