67 lines
2.1 KiB
Python
67 lines
2.1 KiB
Python
from sqlalchemy.orm import Session
|
|
from datetime import datetime
|
|
from typing import Optional
|
|
from fastapi import HTTPException
|
|
from app.modules.client.models import Client
|
|
from app.modules.client.schema import
|
|
|
|
|
|
class ClientService:
|
|
@staticmethod
|
|
def create_client(db: Session, data: ):
|
|
|
|
|
|
|
|
|
|
new_client = Client(**data.dict())
|
|
db.add(new_client)
|
|
db.commit()
|
|
db.refresh(new_client)
|
|
return new_client
|
|
|
|
@staticmethod
|
|
def get_client(db: Session, client_id: int, current_user):
|
|
client = db.query(Client).filter(Client.id == client_id).first()
|
|
if not client:
|
|
raise ValueError("client no encontrado")
|
|
return client
|
|
|
|
@staticmethod
|
|
def update_client(db: Session, client_id: int, data: , current_user):
|
|
client = db.query(Client).filter(Client.id == client_id).first()
|
|
if not client:
|
|
raise ValueError("client no encontrado")
|
|
|
|
if current_user.role not in ["ROOT", "ADMIN"]:
|
|
raise ValueError("No tienes permisos para actualizar este client")
|
|
|
|
update_data = data.dict(exclude_unset=True)
|
|
for key, value in update_data.items():
|
|
setattr(client, key, value)
|
|
|
|
db.commit()
|
|
db.refresh(client)
|
|
return client
|
|
|
|
@staticmethod
|
|
def delete_client(db: Session, client_id: int, current_user):
|
|
client = db.query(Client).filter(Client.id == client_id).first()
|
|
if not client:
|
|
raise ValueError("client no encontrado")
|
|
|
|
if current_user.role not in ["ROOT", "ADMIN"]:
|
|
raise ValueError("No tienes permisos para eliminar este client")
|
|
|
|
try:
|
|
client.is_active = False
|
|
client.deleted_at = datetime.utcnow()
|
|
client.deleted_by = current_user.id
|
|
db.commit()
|
|
db.refresh(client)
|
|
except Exception as e:
|
|
db.rollback()
|
|
raise ValueError(f"Error al eliminar el client: {e}")
|
|
|
|
return {"message": "client eliminado correctamente"}
|
|
|
|
|