ajuste de cruds incompleto
This commit is contained in:
BIN
app/core/__pycache__/dependencies.cpython-311.pyc
Normal file
BIN
app/core/__pycache__/dependencies.cpython-311.pyc
Normal file
Binary file not shown.
@@ -0,0 +1,25 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from app.modules.clients.models import Client
|
||||
|
||||
|
||||
|
||||
def fiscal_number_exists(db: Session, fiscal_number: str) -> bool:
|
||||
"""Verify if a client exist in db"""
|
||||
if not fiscal_number:
|
||||
return False
|
||||
exists = db.query(Client).filter(
|
||||
Client.fiscal_number == fiscal_number,
|
||||
).first() is not None
|
||||
|
||||
return exists
|
||||
|
||||
def email_exist(db: Session, email: str) -> bool:
|
||||
if not email:
|
||||
return False
|
||||
|
||||
exist = db.query(Client).filter(
|
||||
Client.email == email
|
||||
).first() is not None
|
||||
|
||||
return exist
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Status(Enum):
|
||||
COMPLETED = "completed"
|
||||
PARTIAL = "partial"
|
||||
INITIAL = "initial"
|
||||
NO_PROCECED = "no_proceced"
|
||||
INVALID = "invalid"
|
||||
|
||||
class Operation(Enum):
|
||||
DELETED ="deleted"
|
||||
CREATED ="created"
|
||||
UPDATED ="updated"
|
||||
TRIED ="tried"
|
||||
MOST ="mosted"
|
||||
LESS ="less"
|
||||
MINUS ="minus"
|
||||
CANCELED ="canceled"
|
||||
|
||||
|
||||
|
||||
class AffidavitCreate(BaseModel):
|
||||
operation: Operation = Operation.TRIED
|
||||
user_id: Optional[int] = None
|
||||
description: str
|
||||
adjustment: Optional[str] = None
|
||||
client_id: Optional[int] = None
|
||||
status: Status = Status.INITIAL
|
||||
sing: str = Field(..., description="Firma digital del usuario tomada desde service")
|
||||
|
||||
|
||||
class AffidavitUpdate(AffidavitCreate):
|
||||
pass
|
||||
|
||||
class AffidavitResponse(AffidavitCreate):
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
deleted_at: datetime
|
||||
|
||||
class messageResponse(BaseModel):
|
||||
message : str
|
||||
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"}
|
||||
|
||||
|
||||
Binary file not shown.
BIN
app/modules/clients/__pycache__/repository.cpython-311.pyc
Normal file
BIN
app/modules/clients/__pycache__/repository.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/clients/__pycache__/route.cpython-311.pyc
Normal file
BIN
app/modules/clients/__pycache__/route.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/clients/__pycache__/schema.cpython-311.pyc
Normal file
BIN
app/modules/clients/__pycache__/schema.cpython-311.pyc
Normal file
Binary file not shown.
BIN
app/modules/clients/__pycache__/service.cpython-311.pyc
Normal file
BIN
app/modules/clients/__pycache__/service.cpython-311.pyc
Normal file
Binary file not shown.
@@ -74,3 +74,4 @@ class Client(Base):
|
||||
return f"<Client(id={self.id}, rfc={self.rfc}, razon_social={self.razon_social})>"
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
from app.core.baseRepository import BaseRepository
|
||||
from app.modules.clients.models import Client
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
class ClientRepository(BaseRepository[Client]):
|
||||
def __init__(self, db: Session):
|
||||
super().__init__(db, Client)
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from database import get_db
|
||||
from app.core.auth import get_current_user
|
||||
from app.modules.clients.models import Client
|
||||
from app.modules.clients.repository import ClientRepository
|
||||
from app.modules.clients.schema import ClientCreate, ClientUpdate, ClientResponse
|
||||
from app.modules.clients.service import ClientService
|
||||
from app.pipelines.crud import CreatePipe, ReadPipe, UpdatePipe, SoftDelete, ListPipe
|
||||
from typing import List
|
||||
|
||||
router = APIRouter(prefix="/clients", tags=["clients"])
|
||||
|
||||
@router.post("/", response_model=ClientResponse)
|
||||
async def create_client(
|
||||
client_data: ClientCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: dict = Depends(get_current_user)
|
||||
):
|
||||
result = await ClientService.create_client(db, client_data, current_user)
|
||||
if result["success"]:
|
||||
return result["data"]
|
||||
raise HTTPException(status_code=400, detail=result["error"])
|
||||
|
||||
@router.get("/{client_id}", response_model=ClientResponse)
|
||||
async def get_client(
|
||||
client_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: dict = Depends(get_current_user)
|
||||
):
|
||||
repo = ClientRepository(db)
|
||||
pipeline = ReadPipe(db, current_user, Client, repo)
|
||||
pipeline.set_input_data({"id": client_id})
|
||||
result = await pipeline.execute()
|
||||
if result["success"]:
|
||||
return result["data"]
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail=result["error"])
|
||||
|
||||
@router.put("/{client_id}", response_model=ClientResponse)
|
||||
async def update_client(
|
||||
client_id: int,
|
||||
client_data: ClientUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: dict = Depends(get_current_user)
|
||||
):
|
||||
repo = ClientRepository(db)
|
||||
pipeline = UpdatePipe(db, current_user, Client, repo)
|
||||
pipeline.set_input_data({"id": client_id, **client_data.dict(exclude_unset=True)})
|
||||
result = await pipeline.execute()
|
||||
if result["success"]:
|
||||
return result["data"]
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail=result["error"])
|
||||
|
||||
@router.delete("/{client_id}")
|
||||
async def delete_client(
|
||||
client_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: dict = Depends(get_current_user)
|
||||
):
|
||||
repo = ClientRepository(db)
|
||||
pipeline = SoftDelete(db, current_user, Client, repo)
|
||||
pipeline.set_input_data({"id": client_id})
|
||||
result = await pipeline.execute()
|
||||
if result["success"]:
|
||||
return result["data"]
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail=result["error"])
|
||||
|
||||
@router.get("/", response_model=List[ClientResponse])
|
||||
async def list_clients(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: dict = Depends(get_current_user)
|
||||
):
|
||||
repo = ClientRepository(db)
|
||||
pipeline = ListPipe(db, current_user, Client, repo)
|
||||
pipeline.set_input_data({"skip": skip, "limit": limit})
|
||||
result = await pipeline.execute()
|
||||
if result["success"]:
|
||||
return result["data"]
|
||||
else:
|
||||
raise HTTPException(status_code=400, detail=result["error"])
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from typing import Optional
|
||||
from app.modules.clients.models import Medio, Tercero, Operacion
|
||||
|
||||
class ClientBase(BaseModel):
|
||||
rfc: str
|
||||
email: EmailStr
|
||||
short_name: Optional[str] = None
|
||||
razon_social: str
|
||||
fiscal_number: str
|
||||
cellphone: str
|
||||
medio: Medio = Medio.MANUAL
|
||||
third_type: Tercero = Tercero.GLOBAL
|
||||
operation_type: Operacion = Operacion.OTROS
|
||||
is_foreign: bool = False
|
||||
user_id: int
|
||||
location_id: Optional[int] = None
|
||||
|
||||
class ClientCreate(ClientBase):
|
||||
pass
|
||||
|
||||
class ClientUpdate(BaseModel):
|
||||
short_name: Optional[str] = None
|
||||
razon_social: Optional[str] = None
|
||||
fiscal_number: Optional[str] = None
|
||||
cellphone: Optional[str] = None
|
||||
medio: Optional[Medio] = None
|
||||
third_type: Optional[Tercero] = None
|
||||
operation_type: Optional[Operacion] = None
|
||||
is_foreign: Optional[bool] = None
|
||||
location_id: Optional[int] = None
|
||||
|
||||
class ClientResponse(ClientBase):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
49
app/modules/clients/service.py
Normal file
49
app/modules/clients/service.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from app.modules.clients.schema import ClientCreate
|
||||
from app.modules.clients.models import Client
|
||||
#
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
from app.core.dependencies import fiscal_number_exists, email_exist
|
||||
|
||||
|
||||
|
||||
|
||||
class ClientService:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
|
||||
@staticmethod
|
||||
def create_client(db:Session, client_data: ClientCreate) -> Client:
|
||||
|
||||
|
||||
if fiscal_number_exists(db, client_data.get("fiscal_number")):
|
||||
raise ValueError("el numero fiscal ya existe")
|
||||
|
||||
if email_exist(db, client_data.get("email")):
|
||||
raise ValueError("este email ya existe")
|
||||
|
||||
new_client = Client(
|
||||
rfc = client_data.get("rfc"),
|
||||
email = client_data.get("email"),
|
||||
short_name = client_data.get("short_name"),
|
||||
razon_social = client_data.get("razon_social"),
|
||||
fiscal_number = client_data.get("fiscal_number"),
|
||||
cellphone = client_data.get("cellphone"),
|
||||
medio = client_data.get("medio"),
|
||||
third_type = client_data.get("third_type"),
|
||||
operation_type = client_data.get("operation_type"),
|
||||
is_foreign = client_data.get("is_foreign", False),
|
||||
user_id = client_data.get("user_id"),
|
||||
location_id = client_data.get("location_id"),
|
||||
)
|
||||
try:
|
||||
db.add(new_client)
|
||||
db.commit()
|
||||
db.refresh(new_client)
|
||||
|
||||
except IntegrityError as e:
|
||||
db.rollback()
|
||||
raise ValueError(f"Error al crear el cliente: {e}")
|
||||
return new_client
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
class CommentCreate(BaseModel):
|
||||
texto: str = Field(..., max(380), min(30))
|
||||
user_id: Optional[int]
|
||||
feed_id: Optional[int]
|
||||
is_active: bool = True
|
||||
|
||||
class Commentupdate(CommentCreate):
|
||||
pass
|
||||
class CommentResponse(CommentCreate):
|
||||
created_at: datetime
|
||||
cretaed_by: int
|
||||
class MessageResponse(BaseModel):
|
||||
message: str
|
||||
@@ -0,0 +1,23 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class ConfigCreate(BaseModel):
|
||||
smtp_host: Optional[str] = None
|
||||
smtp_port: Optional[str] = None
|
||||
smtp_user: Optional[str] = None
|
||||
smtp_password: Optional[str] = None
|
||||
is_active: bool = True
|
||||
class Commentupdate(ConfigCreate):
|
||||
pass
|
||||
class ConfigResponse(ConfigCreate):
|
||||
created_at: datetime
|
||||
last_send: datetime
|
||||
cretaed_by: int
|
||||
class MessageResponse(BaseModel):
|
||||
message: str
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
@@ -0,0 +1,6 @@
|
||||
from pydantic import BaseModel, EmailStr, Field, validator
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
#
|
||||
import re
|
||||
from enum import Enum
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -23,7 +23,6 @@ class Pipeline(Generic[InputT, OutputT]):
|
||||
self._input_data: Any = None
|
||||
self._schema = None
|
||||
self._permission: Optional[str] = None
|
||||
self._affidavit: Optional[Any] = None
|
||||
|
||||
def set_input_data(self, data: Any) -> 'Pipeline':
|
||||
"""Define los datos de entrada"""
|
||||
@@ -40,11 +39,6 @@ class Pipeline(Generic[InputT, OutputT]):
|
||||
self._permission = permission
|
||||
return self
|
||||
|
||||
def with_affidavit(self, affidavit: Any) -> 'Pipeline':
|
||||
"""Define el certificador legal"""
|
||||
self._affidavit = affidavit
|
||||
return self
|
||||
|
||||
def add_step(self, name: str, func: Callable) -> 'Pipeline':
|
||||
"""Agrega un paso al pipeline"""
|
||||
self._steps.append({"name": name, "func": func})
|
||||
@@ -67,7 +61,6 @@ class Pipeline(Generic[InputT, OutputT]):
|
||||
context["input_data"] = self._input_data
|
||||
context["schema"] = self._schema
|
||||
context["permission"] = self._permission
|
||||
context["affidavit"] = self._affidavit
|
||||
|
||||
result = context
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from app.core.auth import CurrentUser
|
||||
|
||||
|
||||
class CreatePipe(Pipeline):
|
||||
"""Pipe prefab to create enititys"""
|
||||
"""Pipe prefab to create entities"""
|
||||
|
||||
def __init__(self, db: Session, user: CurrentUser, model: Type, repository):
|
||||
super().__init__(db, user, f"CREATE_{model.__tablename__.upper()}")
|
||||
@@ -60,9 +60,7 @@ class CreatePipe(Pipeline):
|
||||
if ctx.get("entity"):
|
||||
ctx["output"] = {c.name: getattr(ctx["entity"], c.name)
|
||||
for c in self.model.__table__.columns}
|
||||
print(f"FORMAT: output creado con {len(ctx['output'])} campos")
|
||||
else:
|
||||
print("FORMAT: No hay entity para formatear")
|
||||
ctx["output"] = None
|
||||
return ctx
|
||||
|
||||
@@ -79,11 +77,11 @@ class ReadPipe(Pipeline):
|
||||
def _build(self):
|
||||
self.add_step("validate_id", self._validate_id)
|
||||
self.add_step("check_permissions", self._check_permissions)
|
||||
self.add_step("execurte", self._execute)
|
||||
self.add_step("execute", self._execute)
|
||||
self.add_step("format_output", self._format)
|
||||
|
||||
async def _validate_id(self, ctx):
|
||||
input_data = ctx["input"].raw_data
|
||||
input_data = ctx.get("input_data", {})
|
||||
entity_id = input_data.get("id")
|
||||
if not entity_id:
|
||||
raise ValueError("se requiere ID")
|
||||
@@ -125,14 +123,18 @@ class UpdatePipe(Pipeline):
|
||||
self.add_step("format_output", self._format)
|
||||
|
||||
async def _validate(self, ctx):
|
||||
data = ctx["input"].get_validated()
|
||||
ctx["validated_data"] = data.dict() if data else {}
|
||||
input_data = ctx.get("input_data", {})
|
||||
if ctx.get("schema"):
|
||||
validated = ctx["schema"](**input_data)
|
||||
ctx["validated_data"] = validated.dict()
|
||||
else:
|
||||
ctx["validated_data"] = input_data
|
||||
return ctx
|
||||
|
||||
async def _validate_id(self, ctx):
|
||||
entity_id = ctx["validated_data"].get("id")
|
||||
if not entity_id:
|
||||
raise ValueError("Se rqeuiere ID")
|
||||
raise ValueError("Se requiere ID")
|
||||
ctx["entity_id"] = entity_id
|
||||
return ctx
|
||||
|
||||
@@ -151,10 +153,8 @@ class UpdatePipe(Pipeline):
|
||||
|
||||
|
||||
async def _format(self, ctx):
|
||||
ctx["output"] = {
|
||||
"id": ctx["entity"].id,
|
||||
"message": f"{self.model.__name__} actualizado exitosamente"
|
||||
}
|
||||
ctx["output"] = {c.name: getattr(ctx["entity"], c.name)
|
||||
for c in self.model.__table__.columns}
|
||||
return ctx
|
||||
|
||||
class SoftDelete(Pipeline):
|
||||
@@ -168,7 +168,6 @@ class SoftDelete(Pipeline):
|
||||
self._build()
|
||||
|
||||
def _build(self):
|
||||
self.add_step("validate", self._validate)
|
||||
self.add_step("validate_id", self._validate_id)
|
||||
self.add_step("check_permissions", self._check_permissions)
|
||||
self.add_step("check_already_deleted", self._check_already_deleted)
|
||||
@@ -177,7 +176,7 @@ class SoftDelete(Pipeline):
|
||||
self.add_step("format_output", self._format)
|
||||
|
||||
async def _validate_id(self, ctx):
|
||||
input_data = ctx["input"].raw_data
|
||||
input_data = ctx.get("input_data", {})
|
||||
entity_id = input_data.get("id")
|
||||
if not entity_id:
|
||||
raise ValueError("se requiere ID")
|
||||
@@ -222,14 +221,16 @@ class SoftDelete(Pipeline):
|
||||
|
||||
|
||||
async def _format(self, ctx):
|
||||
|
||||
ctx["output"]["message"] = f"{self.model.__name__} eliminado corectamente"
|
||||
ctx["output"]["deleted_at"] = ctx["entity"].deleted_at.isoformat()
|
||||
ctx["output"]["deleted_by"] = ctx["entity"].delted_by
|
||||
ctx["output"] = {
|
||||
"id": ctx["entity"].id,
|
||||
"message": f"{self.model.__name__} eliminado correctamente",
|
||||
"deleted_at": ctx["entity"].deleted_at.isoformat() if ctx["entity"].deleted_at else None,
|
||||
"deleted_by": ctx["entity"].deleted_by
|
||||
}
|
||||
return ctx
|
||||
|
||||
class ListPipe(Pipeline):
|
||||
"""Pipeline prefab to list entitys"""
|
||||
"""Pipeline prefab to list entities"""
|
||||
|
||||
def __init__(self, db: Session, user: CurrentUser, model: Type, repository):
|
||||
super().__init__(db, user, f"LIST_{model.__tablename__.upper()}")
|
||||
|
||||
Reference in New Issue
Block a user