adision de bases para trabajo completo de back-v1.0.0
This commit is contained in:
Binary file not shown.
BIN
app/modules/location/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/location/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/location/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/location/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/location/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/location/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -10,11 +10,8 @@ class Locations(Base):
|
||||
id = Column(Integer, primary_key=True, nullable=False)
|
||||
|
||||
country = Column(String(120), nullable=False)
|
||||
country_id = Column(Integer, nullable=False)
|
||||
state = Column(String(100), nullable=False)
|
||||
state_id = Column(Integer, nullable=False)
|
||||
city = Column(String(100), nullable=False)
|
||||
city_id = Column(Integer, nullable=False)
|
||||
cp_zp = Column(Integer, nullable=True)
|
||||
street = Column(String(120), nullable=True)
|
||||
is_department = Column(Boolean, nullable=False, default=False)
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
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.location.models import Locations
|
||||
from app.modules.location.schema import LocationBase, LocationUpdate, LocationResponse, messageResponse
|
||||
from app.modules.location.service import LocationsService
|
||||
|
||||
router = APIRouter(prefix="/locations", tags=["locations"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=LocationResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_locations(
|
||||
data: LocationBase,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a locations - 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.create_locations(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[LocationResponse])
|
||||
def get_locationss(
|
||||
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 LocationsService.get_locations(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=LocationResponse)
|
||||
def get_locations_by_id(
|
||||
locations_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get locations by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = LocationsService.get_locations(db=db, locations_id=locations_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=LocationResponse)
|
||||
async def update_locations(
|
||||
locations_id: int,
|
||||
data: LocationUpdate ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing locations - 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.update_locations(
|
||||
db=db,
|
||||
locations_id=locations_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}", response_model=messageResponse ,status_code=status.HTTP_200_OK)
|
||||
async def delete_locations(
|
||||
locations_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete locations 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 locations")
|
||||
|
||||
try:
|
||||
result = LocationsService.delete_locations(db=db, locations_id=locations_id, current_user=current_user)
|
||||
return {"message": "locations deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -0,0 +1,34 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class LocationBase(BaseModel):
|
||||
country: str
|
||||
state: str
|
||||
city: str
|
||||
cp_zp: int
|
||||
street: str
|
||||
is_department: bool
|
||||
number_ext: int
|
||||
number_int: int
|
||||
is_active: bool
|
||||
|
||||
class LocationResponse(LocationBase):
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
deleted_at: Optional[datetime]
|
||||
created_by: Optional[int]
|
||||
updated_by: Optional[int]
|
||||
deleted_by: Optional[int]
|
||||
|
||||
class LocationUpdate(LocationBase):
|
||||
pass
|
||||
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message : str
|
||||
|
||||
|
||||
@@ -3,4 +3,67 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.location.models import Locations
|
||||
from app.modules.location.schema import LocationBase, LocationUpdate
|
||||
|
||||
class LocationsService:
|
||||
@staticmethod
|
||||
def create_locations(db: Session, data:LocationBase ):
|
||||
new_locations = Locations(**data.dict())
|
||||
db.add(new_locations)
|
||||
db.commit()
|
||||
db.refresh(new_locations)
|
||||
return new_locations
|
||||
|
||||
@staticmethod
|
||||
def get_locations(db: Session, locations_id: int, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
return locations
|
||||
|
||||
@staticmethod
|
||||
def update_locations(db: Session, locations_id: int, data: LocationUpdate, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este locations")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(locations, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(locations)
|
||||
return locations
|
||||
|
||||
@staticmethod
|
||||
def delete_locations(db: Session, locations_id: int, current_user):
|
||||
locations = db.query(Locations).filter(Locations.id == locations_id).first()
|
||||
if not locations:
|
||||
raise ValueError("locations no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este locations")
|
||||
|
||||
try:
|
||||
locations.is_active = False
|
||||
locations.deleted_at = datetime.utcnow()
|
||||
locations.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(locations)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el locations: {e}")
|
||||
|
||||
return {"message": "locations eliminado correctamente"}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user