You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
2.4 KiB
Python
82 lines
2.4 KiB
Python
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from sqlalchemy.exc import OperationalError, SQLAlchemyError
|
|
|
|
from app.db.mock_database import SessionMockLocal
|
|
from app.db.mock_models import Order, Vehicle
|
|
from app.services.domain.common import is_legacy_schema_issue
|
|
|
|
# regra de crédito.
|
|
|
|
|
|
async def consultar_estoque(
|
|
preco_max: float | None = None,
|
|
categoria: str | None = None,
|
|
ordenar_preco: str | None = None,
|
|
limite: int | None = None,
|
|
) -> list[dict[str, Any]]:
|
|
db = SessionMockLocal()
|
|
try:
|
|
reserved_vehicle_ids = set()
|
|
try:
|
|
reserved_vehicle_ids = {
|
|
int(vehicle_id)
|
|
for (vehicle_id,) in (
|
|
db.query(Order.vehicle_id)
|
|
.filter(Order.vehicle_id.isnot(None))
|
|
.filter(Order.status != "Cancelado")
|
|
.all()
|
|
)
|
|
if vehicle_id is not None
|
|
}
|
|
except (OperationalError, SQLAlchemyError) as exc:
|
|
if not is_legacy_schema_issue(exc):
|
|
raise
|
|
db.rollback()
|
|
|
|
query = db.query(Vehicle)
|
|
if reserved_vehicle_ids:
|
|
query = query.filter(~Vehicle.id.in_(reserved_vehicle_ids))
|
|
|
|
if preco_max is not None:
|
|
query = query.filter(Vehicle.preco <= preco_max)
|
|
if categoria:
|
|
query = query.filter(Vehicle.categoria == categoria.lower())
|
|
|
|
if ordenar_preco in {"asc", "desc"}:
|
|
query = query.order_by(Vehicle.preco.asc() if ordenar_preco == "asc" else Vehicle.preco.desc())
|
|
|
|
if limite is not None:
|
|
try:
|
|
query = query.limit(max(1, int(limite)))
|
|
except (TypeError, ValueError):
|
|
pass
|
|
|
|
rows = query.all()
|
|
return [
|
|
{
|
|
"id": row.id,
|
|
"modelo": row.modelo,
|
|
"categoria": row.categoria,
|
|
"preco": float(row.preco),
|
|
}
|
|
for row in rows
|
|
]
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
async def avaliar_veiculo_troca(modelo: str, ano: int, km: int) -> dict[str, Any]:
|
|
ano_atual = datetime.now().year
|
|
idade = max(0, ano_atual - ano)
|
|
base = 80000.0
|
|
valor = base * (0.85 ** idade) - (km * 0.03)
|
|
valor = max(5000.0, valor)
|
|
return {
|
|
"modelo": modelo,
|
|
"ano": ano,
|
|
"km": km,
|
|
"valor_estimado_troca": round(valor, 2),
|
|
}
|