ajuste de cruds incompleto
This commit is contained in:
BIN
app/modules/branches/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/branches/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/branches/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/branches/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/branches/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/branches/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -0,0 +1,118 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Header, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional, List
|
||||
#
|
||||
from database import get_db
|
||||
from app.core.auth import get_current_user
|
||||
from app.modules.users.models import Users
|
||||
# Modelo base de usuario
|
||||
from app.modules.branches.models import Branches
|
||||
from app.modules.branches.schema import BrancheResponse, BranchesCreate, BrancheUpdate, MessageResponse
|
||||
from app.modules.branches.service import BranchesService
|
||||
|
||||
router = APIRouter(prefix="/branches", tags=["branches"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=BrancheResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_branches(
|
||||
data: BranchesCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a branches - Requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="User not found - invalid token")
|
||||
|
||||
if current_user.tipo_usuario not in ["root", "admin"]:
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to create branches")
|
||||
|
||||
try:
|
||||
result = BranchesService.create_branches(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[BrancheResponse])
|
||||
def get_branchess(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user),
|
||||
skip: int = Query(0, ge=0, description="Number of records to skip"),
|
||||
limit: int = Query(100, ge=1, le=1000, description="Max number of records to return")
|
||||
):
|
||||
"""Get list with pagination - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
return BranchesService.get_branchess(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=BrancheResponse)
|
||||
def get_branches_by_id(
|
||||
branches_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get branches by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = BranchesService.get_branches(db=db, branches_id=branches_id, current_user=current_user)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
|
||||
#================ Update ====================
|
||||
@router.patch("/update/{{{entity_name}}_id}", response_model=MessageResponse)
|
||||
async def update_branches(
|
||||
branches_id: int,
|
||||
data: BrancheUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing branches - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
if current_user.tipo_usuario not in ["root", "admin"]:
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to update branches")
|
||||
|
||||
try:
|
||||
result = BranchesService.update_branches(
|
||||
db=db,
|
||||
branches_id=branches_id,
|
||||
data=data,
|
||||
current_user=current_user
|
||||
)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
|
||||
#================ Delete ====================
|
||||
@router.delete("/delete/{{{entity_name}}_id}", status_code=status.HTTP_200_OK)
|
||||
async def delete_branches(
|
||||
branches_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete branches by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
if current_user.tipo_usuario not in ["root", "admin"]:
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to delete branches")
|
||||
|
||||
try:
|
||||
result = BranchesService.delete_branches(db=db, branches_id=branches_id, current_user=current_user)
|
||||
return {"message": "branches deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -0,0 +1,25 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class BranchesCreate(BaseModel):
|
||||
direccion: str
|
||||
cp: int
|
||||
is_phisical: bool
|
||||
location_id: int
|
||||
is_active: bool = True
|
||||
client_id: Optional[int] = None
|
||||
user_id: Optional[int] = None
|
||||
|
||||
|
||||
class BrancheUpdate(BranchesCreate):
|
||||
pass
|
||||
class BrancheResponse(BranchesCreate):
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
class MessageResponse(BaseModel):
|
||||
massage : str
|
||||
|
||||
|
||||
65
app/modules/branches/service.py
Normal file
65
app/modules/branches/service.py
Normal file
@@ -0,0 +1,65 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import HTTPException
|
||||
from app.modules.branches.models import Branches
|
||||
from app.modules.branches.schema import BranchesCreate, BrancheUpdate, BrancheResponse, MessageResponse
|
||||
|
||||
|
||||
class BranchesService:
|
||||
@staticmethod
|
||||
def create_branches(db: Session, data: BranchesCreate):
|
||||
new_branches = Branches(**data.dict())
|
||||
db.add(new_branches)
|
||||
db.commit()
|
||||
db.refresh(new_branches)
|
||||
return new_branches
|
||||
|
||||
@staticmethod
|
||||
def get_branches(db: Session, branches_id: int, current_user):
|
||||
branches = db.query(Branches).filter(Branches.id == branches_id).first()
|
||||
if not branches:
|
||||
raise ValueError("branches no encontrado")
|
||||
return branches
|
||||
|
||||
|
||||
@staticmethod
|
||||
def update_branches(db: Session, branches_id: int, data: BrancheUpdate, current_user):
|
||||
branches = db.query(Branches).filter(Branches.id == branches_id).first()
|
||||
if not branches:
|
||||
raise ValueError("branches no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este branches")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(branches, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(branches)
|
||||
return branches
|
||||
|
||||
@staticmethod
|
||||
def delete_branches(db: Session, branches_id: int, current_user):
|
||||
branches = db.query(Branches).filter(Branches.id == branches_id).first()
|
||||
if not branches:
|
||||
raise ValueError("branches no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este branches")
|
||||
|
||||
try:
|
||||
branches.is_active = False
|
||||
branches.deleted_at = datetime.utcnow()
|
||||
branches.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(branches)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el branches: {e}")
|
||||
|
||||
return {"message": "branches eliminado correctamente"}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user