adision de bases para trabajo completo de back-v1.0.0
This commit is contained in:
BIN
app/modules/coments/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/coments/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/coments/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/coments/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/coments/__pycache__/services.cpython-311.pyc
Normal file
BIN
app/modules/coments/__pycache__/services.cpython-311.pyc
Normal file
Binary file not shown.
@@ -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.coments.models import Coments
|
||||
from app.modules.coments.schema import Commentupdate, CommentCreate, CommentResponse, MessageResponse
|
||||
from app.modules.coments.services import ComentsService
|
||||
|
||||
router = APIRouter(prefix="/coments", tags=["coments"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=CommentResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_coments(
|
||||
data: CommentCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a coments - 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 coments")
|
||||
|
||||
try:
|
||||
result = ComentsService.create_coments(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[CommentResponse])
|
||||
def get_comentss(
|
||||
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 ComentsService.get_coments(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=CommentResponse)
|
||||
def get_coments_by_id(
|
||||
coments_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get coments by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = ComentsService.get_coments(db=db, coments_id=coments_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=CommentResponse)
|
||||
async def update_coments(
|
||||
coments_id: int,
|
||||
data: Commentupdate ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing coments - 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 coments")
|
||||
|
||||
try:
|
||||
result = ComentsService.update_coments(
|
||||
db=db,
|
||||
coments_id=coments_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_coments(
|
||||
coments_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete coments 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 coments")
|
||||
|
||||
try:
|
||||
result = ComentsService.delete_coments(db=db, coments_id=coments_id, current_user=current_user)
|
||||
return {"message": "coments deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -6,7 +6,7 @@ import re
|
||||
from enum import Enum
|
||||
|
||||
class CommentCreate(BaseModel):
|
||||
texto: str = Field(..., max(380), min(30))
|
||||
texto: str
|
||||
user_id: Optional[int]
|
||||
feed_id: Optional[int]
|
||||
is_active: bool = True
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.coments.models import Coments
|
||||
from app.modules.coments.schema import CommentCreate, CommentResponse, Commentupdate, MessageResponse
|
||||
|
||||
|
||||
class ComentsService:
|
||||
@staticmethod
|
||||
def create_coments(db: Session, data: CommentCreate):
|
||||
new_coments = Coments(**data.dict())
|
||||
db.add(new_coments)
|
||||
db.commit()
|
||||
db.refresh(new_coments)
|
||||
return new_coments
|
||||
|
||||
@staticmethod
|
||||
def get_coments(db: Session, coments_id: int, current_user):
|
||||
coments = db.query(Coments).filter(Coments.id == coments_id).first()
|
||||
if not coments:
|
||||
raise ValueError("coments no encontrado")
|
||||
return coments
|
||||
|
||||
@staticmethod
|
||||
def update_coments(db: Session, coments_id: int, data:Commentupdate , current_user):
|
||||
coments = db.query(Coments).filter(Coments.id == coments_id).first()
|
||||
if not coments:
|
||||
raise ValueError("coments no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este coments")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(coments, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(coments)
|
||||
return coments
|
||||
|
||||
@staticmethod
|
||||
def delete_coments(db: Session, coments_id: int, current_user):
|
||||
coments = db.query(Coments).filter(Coments.id == coments_id).first()
|
||||
if not coments:
|
||||
raise ValueError("coments no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este coments")
|
||||
|
||||
try:
|
||||
coments.is_active = False
|
||||
coments.deleted_at = datetime.utcnow()
|
||||
coments.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(coments)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el coments: {e}")
|
||||
|
||||
return {"message": "coments eliminado correctamente"}
|
||||
|
||||
|
||||
BIN
app/modules/configuration/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/configuration/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/configuration/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/configuration/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/configuration/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/configuration/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -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.configuration.models import Configuration
|
||||
from app.modules.configuration.schema import Configupdate, ConfigResponse, ConfigCreate, MessageResponse
|
||||
from app.modules.configuration.service import ConfigurationService
|
||||
|
||||
router = APIRouter(prefix="/configuration", tags=["configuration"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=ConfigResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_configuration(
|
||||
data: ConfigCreate ,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a configuration - 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.create_configuration(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[ConfigResponse])
|
||||
def get_configurations(
|
||||
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 ConfigurationService.get_configuration(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=ConfigResponse)
|
||||
def get_configuration_by_id(
|
||||
configuration_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get configuration by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.get_configuration(db=db, configuration_id=configuration_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=ConfigResponse)
|
||||
async def update_configuration(
|
||||
configuration_id: int,
|
||||
data: Configupdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing configuration - 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.update_configuration(
|
||||
db=db,
|
||||
configuration_id=configuration_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_configuration(
|
||||
configuration_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete configuration 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 configuration")
|
||||
|
||||
try:
|
||||
result = ConfigurationService.delete_configuration(db=db, configuration_id=configuration_id, current_user=current_user)
|
||||
return {"message": "configuration deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -12,7 +12,7 @@ class ConfigCreate(BaseModel):
|
||||
smtp_user: Optional[str] = None
|
||||
smtp_password: Optional[str] = None
|
||||
is_active: bool = True
|
||||
class Commentupdate(ConfigCreate):
|
||||
class Configupdate(ConfigCreate):
|
||||
pass
|
||||
class ConfigResponse(ConfigCreate):
|
||||
created_at: datetime
|
||||
|
||||
64
app/modules/configuration/service.py
Normal file
64
app/modules/configuration/service.py
Normal file
@@ -0,0 +1,64 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.configuration.models import Configuration
|
||||
from app.modules.configuration.schema import ConfigCreate, ConfigResponse, Configupdate, MessageResponse
|
||||
|
||||
|
||||
class ConfigurationService:
|
||||
@staticmethod
|
||||
def create_configuration(db: Session, data: ConfigCreate):
|
||||
|
||||
new_configuration = Configuration(**data.dict())
|
||||
db.add(new_configuration)
|
||||
db.commit()
|
||||
db.refresh(new_configuration)
|
||||
return new_configuration
|
||||
|
||||
@staticmethod
|
||||
def get_configuration(db: Session, configuration_id: int, current_user):
|
||||
configuration = db.query(Configuration).filter(Configuration.id == configuration_id).first()
|
||||
if not configuration:
|
||||
raise ValueError("configuration no encontrado")
|
||||
return configuration
|
||||
|
||||
@staticmethod
|
||||
def update_configuration(db: Session, configuration_id: int, data: Configupdate , current_user):
|
||||
configuration = db.query(Configuration).filter(Configuration.id == configuration_id).first()
|
||||
if not configuration:
|
||||
raise ValueError("configuration no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este configuration")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(configuration, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(configuration)
|
||||
return configuration
|
||||
|
||||
@staticmethod
|
||||
def delete_configuration(db: Session, configuration_id: int, current_user):
|
||||
configuration = db.query(Configuration).filter(Configuration.id == configuration_id).first()
|
||||
if not configuration:
|
||||
raise ValueError("configuration no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este configuration")
|
||||
|
||||
try:
|
||||
configuration.is_active = False
|
||||
configuration.deleted_at = datetime.utcnow()
|
||||
configuration.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(configuration)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el configuration: {e}")
|
||||
|
||||
return {"message": "configuration eliminado correctamente"}
|
||||
|
||||
|
||||
Binary file not shown.
@@ -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.credits.models import Credits
|
||||
from app.modules.credits.schema import CreditsCreate, CreditsResponse, CreditsUpdate, MessageResponse
|
||||
from app.modules.credits.service import CreditsService
|
||||
|
||||
router = APIRouter(prefix="/credits", tags=["credits"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=CreditsResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_credits(
|
||||
data: CreditsCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a credits - 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.create_credits(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[CreditsResponse])
|
||||
def get_creditss(
|
||||
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 CreditsService.get_creditss(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=CreditsResponse)
|
||||
def get_credits_by_id(
|
||||
credits_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get credits by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = CreditsService.get_credits(db=db, credits_id=credits_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=CreditsResponse)
|
||||
async def update_credits(
|
||||
credits_id: int,
|
||||
data: CreditsUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing credits - 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.update_credits(
|
||||
db=db,
|
||||
credits_id=credits_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_credits(
|
||||
credits_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete credits 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 credits")
|
||||
|
||||
try:
|
||||
result = CreditsService.delete_credits(db=db, credits_id=credits_id, current_user=current_user)
|
||||
return {"message": "credits deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -3,4 +3,42 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
class Supuestos(Enum):
|
||||
CANCELADOS ="cancelados"
|
||||
CONDONADOS ="condonados"
|
||||
FIRMES ="firmes"
|
||||
SENTENCIAS ="sentencias"
|
||||
EXIGIBLES ="exigibles"
|
||||
RETORNO_INVERSIONES ="retorno_inversiones"
|
||||
FRACCION_X ="fraccion_x"
|
||||
FRACCION_VII ="fraccion_vii"
|
||||
NO_LOCALIZADOS ="no_localizados"
|
||||
|
||||
class CreditsCreate(BaseModel):
|
||||
title:str
|
||||
rfc : str
|
||||
razon_social : str
|
||||
tipo_persona : str
|
||||
supuesto : Supuestos
|
||||
fecha_prim_publicacion : datetime
|
||||
fecha_ley : datetime
|
||||
fecha_cancelacion : datetime
|
||||
fecha_csd : datetime
|
||||
entidad_federativa : str
|
||||
monto : Optional[int] = None
|
||||
motivo : Optional[str] = None
|
||||
location_id : int
|
||||
|
||||
|
||||
class CreditsUpdate(CreditsCreate):
|
||||
pass
|
||||
|
||||
class CreditsResponse(CreditsCreate):
|
||||
creted_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
uploader_at : Optional[datetime]
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
message: str
|
||||
63
app/modules/credits/service.py
Normal file
63
app/modules/credits/service.py
Normal file
@@ -0,0 +1,63 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.credits.models import Credits
|
||||
from app.modules.credits.schema import CreditsCreate, CreditsUpdate, CerditsResponse, MessageResponse
|
||||
|
||||
|
||||
class CreditsService:
|
||||
@staticmethod
|
||||
def create_credits(db: Session, data:CreditsCreate ):
|
||||
new_credits = Credits(**data.dict())
|
||||
db.add(new_credits)
|
||||
db.commit()
|
||||
db.refresh(new_credits)
|
||||
return new_credits
|
||||
|
||||
@staticmethod
|
||||
def get_credits(db: Session, credits_id: int, current_user):
|
||||
credits = db.query(Credits).filter(Credits.id == credits_id).first()
|
||||
if not credits:
|
||||
raise ValueError("credits no encontrado")
|
||||
return credits
|
||||
|
||||
@staticmethod
|
||||
def update_credits(db: Session, credits_id: int, data:CreditsUpdate , current_user):
|
||||
credits = db.query(Credits).filter(Credits.id == credits_id).first()
|
||||
if not credits:
|
||||
raise ValueError("credits no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este credits")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(credits, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(credits)
|
||||
return credits
|
||||
|
||||
@staticmethod
|
||||
def delete_credits(db: Session, credits_id: int, current_user):
|
||||
credits = db.query(Credits).filter(Credits.id == credits_id).first()
|
||||
if not credits:
|
||||
raise ValueError("credits no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este credits")
|
||||
|
||||
try:
|
||||
credits.is_active = False
|
||||
credits.deleted_at = datetime.utcnow()
|
||||
credits.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(credits)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el credits: {e}")
|
||||
|
||||
return {"message": "credits eliminado correctamente"}
|
||||
|
||||
|
||||
Binary file not shown.
BIN
app/modules/edos/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/edos/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/edos/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/edos/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/edos/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/edos/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -20,7 +20,7 @@ class EDOS(Base):
|
||||
razon_social = Column(String(100), nullable=False)
|
||||
situacion = Column(SQLEnum(Situacion, name="situcion", create_type=False), nullable=False)
|
||||
numero_definitivo = Column(String(60), nullable=False)
|
||||
fecha_definitivo = Column(Date, nullable=False )
|
||||
fecha_definitivo = Column(Date, nullable=True )
|
||||
publicaccion_sat = Column(Date, nullable=True)
|
||||
numero_def_dof = Column(String(100), nullable=True)
|
||||
fecha_def_dof = Column(Date, nullable=True)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Body
|
||||
from app.modules.edos.service import XMACSVService
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from app.helpers.extractCsv import CSVExtractor
|
||||
|
||||
router = APIRouter(prefix='/api/csv', tags=['CSV Import'])
|
||||
|
||||
@router.post('/import-from-url')
|
||||
async def import_csv(data: Dict[str, Any] = Body(..., example={"url": "http://example.com/data.csv"})):
|
||||
"""Endpoint to download CSV and process, write and see on DB"""
|
||||
|
||||
|
||||
csv_url = data.get('url')
|
||||
dry_run = data.get('dry_run', True)
|
||||
max_rows = data.get('max_rows')
|
||||
|
||||
if not csv_url:
|
||||
raise HTTPException(400, "url del CSV requerida")
|
||||
|
||||
if not isinstance(csv_url, str):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="la URL debe ser un texto valido"
|
||||
)
|
||||
|
||||
try:
|
||||
result = XMACSVService.process_csv_from_url(
|
||||
csv_url= csv_url,
|
||||
dry_run=dry_run,
|
||||
max_rows=max_rows,
|
||||
)
|
||||
|
||||
return {
|
||||
'status' : 'success',
|
||||
'message': 'Procesamiento completado',
|
||||
'data': result
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error on endpoint: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail=f"Procesing CSV error: {str(e)}"
|
||||
)
|
||||
|
||||
|
||||
@router.post('/import-from-url/v2')
|
||||
async def import_csv(data: dict):
|
||||
"""Endpoint simple para probar el extractor"""
|
||||
csv_url = data.get('url')
|
||||
|
||||
if not csv_url:
|
||||
raise HTTPException(400, "url del CSV requerida")
|
||||
|
||||
try:
|
||||
# Probar extractor
|
||||
content = CSVExtractor.download_csv(csv_url)
|
||||
rows = CSVExtractor.read_csv(content)
|
||||
|
||||
return {
|
||||
'status': 'success',
|
||||
'message': 'CSV procesado correctamente',
|
||||
'data': {
|
||||
'url': csv_url,
|
||||
'total_filas': len(rows),
|
||||
'primeras_filas': rows[:3] if rows else [],
|
||||
'columnas': list(rows[0].keys()) if rows else []
|
||||
}
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(500, detail=str(e))
|
||||
@@ -1,6 +1,33 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
class Situacion(Enum):
|
||||
SENTENCIA_FAVORABLE ="sentencia_favorable"
|
||||
DEFINITIVO="definitivo"
|
||||
|
||||
|
||||
class EdosUpload(BaseModel):
|
||||
numero : str
|
||||
razon_social : str
|
||||
situacion : Situacion
|
||||
numero_definitivo : str
|
||||
fecha_definitivo : date
|
||||
publicaccion_sat : date
|
||||
numero_def_dof : str
|
||||
fecha_def_dof : date
|
||||
publicacion_dof : date
|
||||
numero_fav_sat : str
|
||||
|
||||
|
||||
class EdosResponse(EdosUpload):
|
||||
pass
|
||||
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
|
||||
74
app/modules/edos/service.py
Normal file
74
app/modules/edos/service.py
Normal file
@@ -0,0 +1,74 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.edos.models import EDOS
|
||||
from app.modules.edos.schema import EdosResponse, EdosUpload, messageResponse
|
||||
|
||||
|
||||
from app.helpers.csv_mapper import CSVMapper
|
||||
from app.helpers.db_adapter import DBAdapter
|
||||
from app.helpers.extractCsv import CSVExtractor
|
||||
|
||||
class XMACSVService:
|
||||
""" Orquester"""
|
||||
|
||||
@staticmethod
|
||||
def process_csv_from_url(
|
||||
csv_url: str,
|
||||
dry_run: bool = False,
|
||||
max_rows: int = None
|
||||
) -> dict:
|
||||
""" flow download and parsing, filter and adapt"""
|
||||
|
||||
|
||||
try:
|
||||
# X - EXTRACT
|
||||
print(f"📥 Descargando CSV: {csv_url}")
|
||||
|
||||
# ✅ Ahora download_csv retorna (content, encoding)
|
||||
content, encoding = CSVExtractor.download_csv(csv_url)
|
||||
print(f" ✅ Descargado {len(content)} bytes, encoding: {encoding}")
|
||||
|
||||
# Parsear CSV
|
||||
raw_rows = CSVExtractor.read_csv(content)
|
||||
print(f" ✅ Parseadas {len(raw_rows)} filas")
|
||||
|
||||
if not raw_rows:
|
||||
return {
|
||||
'total_extracted': 0,
|
||||
'total_mapped': 0,
|
||||
'inserted': 0,
|
||||
'errors': ['No se encontraron datos en el CSV']
|
||||
}
|
||||
|
||||
# Mostrar columnas encontradas
|
||||
print(f" 📋 Columnas: {list(raw_rows[0].keys())}")
|
||||
|
||||
# M - MAP (si tienes mapper)
|
||||
# Por ahora, usar datos crudos
|
||||
mapped_rows = raw_rows
|
||||
|
||||
if max_rows:
|
||||
mapped_rows = mapped_rows[:max_rows]
|
||||
print(f" 🔒 Limitado a {max_rows} filas")
|
||||
|
||||
# A - ADAPT
|
||||
if not dry_run:
|
||||
print(f" 💾 Insertando {len(mapped_rows)} filas en BD")
|
||||
# Aquí iría la inserción en BD
|
||||
|
||||
return {
|
||||
'total_extracted': len(raw_rows),
|
||||
'total_mapped': len(mapped_rows),
|
||||
'inserted': len(mapped_rows) if not dry_run else 0,
|
||||
'dry_run': dry_run,
|
||||
'columns': list(raw_rows[0].keys()) if raw_rows else [],
|
||||
'sample': raw_rows[:2] if raw_rows else []
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
raise
|
||||
@@ -1,6 +1,32 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
class Situacion(Enum):
|
||||
DEFINITIVO ="definitivo"
|
||||
DESVIRTUADO ="desvituado"
|
||||
PRESUNTO ="presunto"
|
||||
SENTENCIA_FAVORABLE ="sentencia_favorable"
|
||||
|
||||
class EfosBase(BaseModel):
|
||||
numero: int
|
||||
rfc : str
|
||||
nombre_contribuyente: str
|
||||
situacion: Situacion
|
||||
publi_presuntos_sat: str
|
||||
publi_desvirtuados_sat: date
|
||||
publi_definitivos_sat: date
|
||||
publi_favorable_sat: date
|
||||
|
||||
class EfosResponse(EfosBase):
|
||||
cretaed_at : datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
loader_by: int
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
@@ -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.feed.models import Feed
|
||||
from app.modules.feed.schema import FeedUpdate, FeedCreate, FeedResponse, messageResponse
|
||||
from app.modules.feed.service import FeedService
|
||||
|
||||
router = APIRouter(prefix="/feed", tags=["feed"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=FeedResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_feed(
|
||||
data: FeedCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a feed - 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.create_feed(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[FeedResponse])
|
||||
def get_feeds(
|
||||
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 FeedService.get_feeds(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=FeedResponse)
|
||||
def get_feed_by_id(
|
||||
feed_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get feed by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = FeedService.get_feed(db=db, feed_id=feed_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=FeedResponse)
|
||||
async def update_feed(
|
||||
feed_id: int,
|
||||
data: FeedUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing feed - 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.update_feed(
|
||||
db=db,
|
||||
feed_id=feed_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_feed(
|
||||
feed_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete feed 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 feed")
|
||||
|
||||
try:
|
||||
result = FeedService.delete_feed(db=db, feed_id=feed_id, current_user=current_user)
|
||||
return {"message": "feed deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -1,6 +1,31 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
class FeedBase(BaseModel):
|
||||
title: str
|
||||
body: Optional[str] = None
|
||||
document_url: str
|
||||
publication_date: date
|
||||
is_important : bool = False
|
||||
|
||||
class FeedCreate(FeedBase):
|
||||
user_id: int
|
||||
file_id: Optional[int] = None
|
||||
|
||||
class FeedUpdate(BaseModel):
|
||||
body: str
|
||||
|
||||
class FeedResponse(FeedBase):
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] =None
|
||||
created_by : Optional[int] = None
|
||||
updated_by : Optional[int] = None
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
|
||||
63
app/modules/feed/service.py
Normal file
63
app/modules/feed/service.py
Normal file
@@ -0,0 +1,63 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.feed.models import Feed
|
||||
from app.modules.feed.schema import FeedCreate, FeedResponse, FeedUpdate, messageResponse
|
||||
|
||||
|
||||
class FeedService:
|
||||
@staticmethod
|
||||
def create_feed(db: Session, data: FeedCreate ):
|
||||
new_feed = Feed(**data.dict())
|
||||
db.add(new_feed)
|
||||
db.commit()
|
||||
db.refresh(new_feed)
|
||||
return new_feed
|
||||
|
||||
@staticmethod
|
||||
def get_feed(db: Session, feed_id: int, current_user):
|
||||
feed = db.query(Feed).filter(Feed.id == feed_id).first()
|
||||
if not feed:
|
||||
raise ValueError("feed no encontrado")
|
||||
return feed
|
||||
|
||||
@staticmethod
|
||||
def update_feed(db: Session, feed_id: int, data: FeedUpdate , current_user):
|
||||
feed = db.query(Feed).filter(Feed.id == feed_id).first()
|
||||
if not feed:
|
||||
raise ValueError("feed no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este feed")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(feed, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(feed)
|
||||
return feed
|
||||
|
||||
@staticmethod
|
||||
def delete_feed(db: Session, feed_id: int, current_user):
|
||||
feed = db.query(Feed).filter(Feed.id == feed_id).first()
|
||||
if not feed:
|
||||
raise ValueError("feed no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este feed")
|
||||
|
||||
try:
|
||||
feed.is_active = False
|
||||
feed.deleted_at = datetime.utcnow()
|
||||
feed.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(feed)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el feed: {e}")
|
||||
|
||||
return {"message": "feed eliminado correctamente"}
|
||||
|
||||
|
||||
@@ -1,6 +1,27 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
class FileBase(BaseModel):
|
||||
title: str
|
||||
summary: str
|
||||
document_url : str
|
||||
file_type : str
|
||||
file_size : str
|
||||
feed_id: str
|
||||
|
||||
class FileCreate(FileBase):
|
||||
feed_id: int
|
||||
|
||||
class FileResponse(FileBase):
|
||||
cretaed_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
uploader_by: int
|
||||
updated_by: Optional[int] = None
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
|
||||
0
app/modules/files/service.py
Normal file
0
app/modules/files/service.py
Normal file
@@ -1,6 +1,26 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from datetime import datetime, date
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Interacction(Enum):
|
||||
LIKE = "like"
|
||||
DONT_LIKE = "dont_like"
|
||||
APPROVED = "approved"
|
||||
DISAPRROVE = "disapproved"
|
||||
NONE = "none"
|
||||
|
||||
|
||||
class InteractionBase(BaseModel):
|
||||
type_interactions: Interacction = "none"
|
||||
|
||||
class InteractionCreate(InteractionBase):
|
||||
feed_id: int
|
||||
user_id: int
|
||||
|
||||
class InteractionResponse(InteractionBase):
|
||||
pass
|
||||
|
||||
|
||||
@@ -3,4 +3,22 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class InvoceRecept(BaseModel):
|
||||
emisor: str
|
||||
receptor: str
|
||||
uuid: str
|
||||
total: int
|
||||
tipo: str
|
||||
date: Optional[datetime]
|
||||
|
||||
class InvoceResponse(InvoceRecept):
|
||||
verified_at: datetime
|
||||
verified_by: Optional[int]
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
message : str
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
@@ -25,7 +25,7 @@ class License(Base):
|
||||
#timestamsp
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False)
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now(), nullable=True)
|
||||
deleted_at = Column(DateTime(timezone=True), nullable=False)
|
||||
deleted_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
#trace
|
||||
created_by = Column(Integer, nullable=True)
|
||||
|
||||
@@ -3,4 +3,25 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
|
||||
class LicenseBase(BaseModel):
|
||||
titular : int
|
||||
begins_at : datetime
|
||||
ends_at: datetime
|
||||
token_license: str
|
||||
location_id : int
|
||||
client_id: int
|
||||
|
||||
class LicenseResponse(LicenseBase):
|
||||
cretaed_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
deleted_at: Optional[datetime]
|
||||
|
||||
created_by: Optional[int]
|
||||
updated_by: Optional[int]
|
||||
deleted_by: Optional[int]
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
message : str
|
||||
63
app/modules/license/service.py
Normal file
63
app/modules/license/service.py
Normal file
@@ -0,0 +1,63 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from fastapi import HTTPException
|
||||
from app.modules.license.models import License
|
||||
from app.modules.license.schema import LicenseResponse, LicenseBase
|
||||
|
||||
|
||||
class LicenseService:
|
||||
@staticmethod
|
||||
def create_license(db: Session, data: ):
|
||||
new_license = License(**data.dict())
|
||||
db.add(new_license)
|
||||
db.commit()
|
||||
db.refresh(new_license)
|
||||
return new_license
|
||||
|
||||
@staticmethod
|
||||
def get_license(db: Session, license_id: int, current_user):
|
||||
license = db.query(License).filter(License.id == license_id).first()
|
||||
if not license:
|
||||
raise ValueError("license no encontrado")
|
||||
return license
|
||||
|
||||
@staticmethod
|
||||
def update_license(db: Session, license_id: int, data: , current_user):
|
||||
license = db.query(License).filter(License.id == license_id).first()
|
||||
if not license:
|
||||
raise ValueError("license no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este license")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(license, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(license)
|
||||
return license
|
||||
|
||||
@staticmethod
|
||||
def delete_license(db: Session, license_id: int, current_user):
|
||||
license = db.query(License).filter(License.id == license_id).first()
|
||||
if not license:
|
||||
raise ValueError("license no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este license")
|
||||
|
||||
try:
|
||||
license.is_active = False
|
||||
license.deleted_at = datetime.utcnow()
|
||||
license.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(license)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el license: {e}")
|
||||
|
||||
return {"message": "license eliminado correctamente"}
|
||||
|
||||
|
||||
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"}
|
||||
|
||||
|
||||
@@ -1,6 +1,56 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from pydantic import BaseModel, EmailStr, Field, validator, ConfigDict
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from typing import Optional, Dict, Any
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
from enum import Enum
|
||||
#
|
||||
|
||||
class Action(Enum):
|
||||
UPLOAD = "upload"
|
||||
MATCH = "match"
|
||||
QUERY = "query"
|
||||
CONSUMPTION = "consumption"
|
||||
CREATE = "create"
|
||||
DELETE = "delete"
|
||||
SOLD = "sold"
|
||||
INTERACTION = "interaction"
|
||||
COMMENT = "comment"
|
||||
CONFIG = "config"
|
||||
EMAIL = "email"
|
||||
|
||||
|
||||
class Target(Enum):
|
||||
CLIENT = "client"
|
||||
INVOICES = "invoices"
|
||||
FEED = "feed"
|
||||
EFOS = "efos"
|
||||
CREDITS = "credits"
|
||||
USERS = "users"
|
||||
EMAIL = "email"
|
||||
|
||||
class MovesBase(BaseModel):
|
||||
action_type: Action
|
||||
target_type : Target
|
||||
description: Optional[str]
|
||||
move_metadata: Optional[Dict[str, Any]] = None
|
||||
ip_address: Optional[str]
|
||||
user_agent: Optional[str]
|
||||
is_active: bool = True
|
||||
|
||||
class MoveCreate(MovesBase):
|
||||
client_id: int
|
||||
user_id: int
|
||||
|
||||
class MoveUpdate(MoveCreate):
|
||||
pass
|
||||
|
||||
class MovesResponse(MoveCreate):
|
||||
id: int
|
||||
created_at: datetime
|
||||
created_by: Optional[int]
|
||||
|
||||
updated_at: Optional[datetime]
|
||||
deleted_by: Optional[int]
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
Binary file not shown.
BIN
app/modules/suppliers/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/suppliers/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/suppliers/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/suppliers/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/suppliers/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/suppliers/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -7,7 +7,7 @@ import enum
|
||||
|
||||
class SupplierType(str, enum.Enum):
|
||||
NACIONAL = "nacional"
|
||||
EXTRANJERO = "exttranjero"
|
||||
EXTRANJERO = "extranjero"
|
||||
GLOBAL = "global"
|
||||
|
||||
|
||||
|
||||
@@ -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.suppliers.models import Suppliers
|
||||
from app.modules.suppliers.schema import SupplierCreate, SupplierResponse, SupplierUpdate, messageResponse
|
||||
from app.modules.suppliers.service import SuppliersService
|
||||
|
||||
router = APIRouter(prefix="/suppliers", tags=["suppliers"])
|
||||
security = HTTPBearer()
|
||||
|
||||
#================ Create ====================
|
||||
@router.post("/create", response_model=SupplierResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_suppliers(
|
||||
data: SupplierCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Create a suppliers - 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.create_suppliers(db=db, data=data)
|
||||
return result
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
#================ Get ====================
|
||||
@router.get("/", response_model=List[SupplierResponse])
|
||||
def get_supplierss(
|
||||
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 SuppliersService.get_suppliers(db=db, skip=skip, limit=limit)
|
||||
|
||||
#================ Get by ID ====================
|
||||
@router.get("/{{{entity_name}}_id}", response_model=SupplierResponse)
|
||||
def get_suppliers_by_id(
|
||||
suppliers_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Get suppliers by ID - requires authentication"""
|
||||
|
||||
if not current_user:
|
||||
raise HTTPException(status_code=401, detail="Authentication required")
|
||||
|
||||
try:
|
||||
result = SuppliersService.get_suppliers(db=db, suppliers_id=suppliers_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=SupplierResponse)
|
||||
async def update_suppliers(
|
||||
suppliers_id: int,
|
||||
data: SupplierUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Update existing suppliers - 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.update_suppliers(
|
||||
db=db,
|
||||
suppliers_id=suppliers_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_suppliers(
|
||||
suppliers_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: Users = Depends(get_current_user)
|
||||
):
|
||||
"""Delete suppliers 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 suppliers")
|
||||
|
||||
try:
|
||||
result = SuppliersService.delete_suppliers(db=db, suppliers_id=suppliers_id, current_user=current_user)
|
||||
return {"message": "suppliers deleted successfully"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=404, detail=str(e))
|
||||
@@ -0,0 +1,42 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator, ConfigDict
|
||||
from datetime import datetime
|
||||
from typing import Optional, Dict, Any
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
#
|
||||
|
||||
|
||||
|
||||
class SupplierType(Enum):
|
||||
NACIONAL = "nacional"
|
||||
EXTRANJERO = "extranjero"
|
||||
GLOBAL = "global"
|
||||
|
||||
class SuppliersBase(BaseModel):
|
||||
rfc: str
|
||||
email : EmailStr
|
||||
short_name : str
|
||||
razon_social : str
|
||||
fiscal_number : str
|
||||
cellphone: str
|
||||
supplier_type : SupplierType
|
||||
is_active : bool = True
|
||||
|
||||
class SupplierCreate(SuppliersBase):
|
||||
location_id: int
|
||||
client_id: int
|
||||
|
||||
class SupplierUpdate(SuppliersBase):
|
||||
pass
|
||||
|
||||
class SupplierResponse(SupplierCreate):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime]
|
||||
deleted_at: Optional[datetime]
|
||||
created_by: int
|
||||
updated_by: Optional[int]
|
||||
deleted_by: Optional[int]
|
||||
class messageResponse(BaseModel):
|
||||
message : str
|
||||
@@ -3,4 +3,68 @@ 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.suppliers.models import Suppliers
|
||||
from app.modules.suppliers.schema import SupplierCreate, SupplierUpdate
|
||||
|
||||
|
||||
class SuppliersService:
|
||||
@staticmethod
|
||||
def create_suppliers(db: Session, data:SupplierCreate ):
|
||||
new_suppliers = Suppliers(**data.dict())
|
||||
db.add(new_suppliers)
|
||||
db.commit()
|
||||
db.refresh(new_suppliers)
|
||||
return new_suppliers
|
||||
|
||||
@staticmethod
|
||||
def get_suppliers(db: Session, suppliers_id: int, current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
return suppliers
|
||||
|
||||
@staticmethod
|
||||
def update_suppliers(db: Session, suppliers_id: int, data:SupplierUpdate , current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para actualizar este suppliers")
|
||||
|
||||
update_data = data.dict(exclude_unset=True)
|
||||
for key, value in update_data.items():
|
||||
setattr(suppliers, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(suppliers)
|
||||
return suppliers
|
||||
|
||||
@staticmethod
|
||||
def delete_suppliers(db: Session, suppliers_id: int, current_user):
|
||||
suppliers = db.query(Suppliers).filter(Suppliers.id == suppliers_id).first()
|
||||
if not suppliers:
|
||||
raise ValueError("suppliers no encontrado")
|
||||
|
||||
if current_user.role not in ["ROOT", "ADMIN"]:
|
||||
raise ValueError("No tienes permisos para eliminar este suppliers")
|
||||
|
||||
try:
|
||||
suppliers.is_active = False
|
||||
suppliers.deleted_at = datetime.utcnow()
|
||||
suppliers.deleted_by = current_user.id
|
||||
db.commit()
|
||||
db.refresh(suppliers)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al eliminar el suppliers: {e}")
|
||||
|
||||
return {"message": "suppliers eliminado correctamente"}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user