Criação da tela de clientes.
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
72
app/routes/clientes.py
Normal file
72
app/routes/clientes.py
Normal file
@@ -0,0 +1,72 @@
|
||||
# app/routes/clientes.py
|
||||
from fastapi import APIRouter, Request, Depends, HTTPException, Query
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select, or_
|
||||
from app.database import get_session
|
||||
from app.models import Cliente
|
||||
from pydantic import BaseModel
|
||||
from uuid import UUID
|
||||
import uuid
|
||||
from fastapi.responses import HTMLResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/clientes")
|
||||
async def clientes_page(request: Request):
|
||||
return request.app.state.templates.TemplateResponse("clientes.html", {"request": request})
|
||||
|
||||
class ClienteIn(BaseModel):
|
||||
nome_fantasia: str
|
||||
cnpj: str | None = None
|
||||
ativo: bool = True
|
||||
|
||||
@router.get("/api/clientes")
|
||||
async def listar(
|
||||
busca: str = Query(default="", description="Filtro por nome ou CNPJ"),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
stmt = select(Cliente).order_by(Cliente.nome_fantasia)
|
||||
if busca:
|
||||
pattern = f"%{busca}%"
|
||||
stmt = select(Cliente).where(
|
||||
or_(
|
||||
Cliente.nome_fantasia.ilike(pattern),
|
||||
Cliente.cnpj.ilike(pattern),
|
||||
)
|
||||
).order_by(Cliente.nome_fantasia)
|
||||
|
||||
res = await session.execute(stmt)
|
||||
clientes = res.scalars().all()
|
||||
return [
|
||||
{
|
||||
"id": str(c.id),
|
||||
"nome_fantasia": c.nome_fantasia,
|
||||
"cnpj": c.cnpj,
|
||||
"ativo": c.ativo,
|
||||
}
|
||||
for c in clientes
|
||||
]
|
||||
|
||||
@router.post("/api/clientes")
|
||||
async def criar_cliente(body: ClienteIn, session: AsyncSession = Depends(get_session)):
|
||||
cliente = Cliente(**body.dict())
|
||||
session.add(cliente)
|
||||
await session.commit()
|
||||
return {"id": str(cliente.id)}
|
||||
|
||||
@router.put("/api/clientes/{id}")
|
||||
async def editar_cliente(id: UUID, body: ClienteIn, session: AsyncSession = Depends(get_session)):
|
||||
await session.execute(
|
||||
Cliente.__table__.update().where(Cliente.id == id).values(**body.dict())
|
||||
)
|
||||
await session.commit()
|
||||
return {"ok": True}
|
||||
|
||||
@router.delete("/api/clientes/{id}")
|
||||
async def excluir(id: uuid.UUID, session: AsyncSession = Depends(get_session)):
|
||||
obj = await session.get(Cliente, id)
|
||||
if not obj:
|
||||
raise HTTPException(404, "Cliente não encontrado")
|
||||
await session.delete(obj)
|
||||
await session.commit()
|
||||
return {"ok": True}
|
||||
Reference in New Issue
Block a user