From 991f7a5fbe3ce83ebc3f48c7c6a724073410e187 Mon Sep 17 00:00:00 2001 From: romhenri Date: Tue, 10 Nov 2026 23:46:47 -0300 Subject: [PATCH] feat(prices): add price alerts with target price and history trend --- backend/app/alertas.py | 53 +++++++++++++++++++++++++++++++++++ backend/app/main.py | 19 ++++++++++++- backend/tests/test_alertas.py | 25 +++++++++++++++++ 3 files changed, 96 insertions(+), 1 deletion(-) create mode 100644 backend/app/alertas.py create mode 100644 backend/tests/test_alertas.py diff --git a/backend/app/alertas.py b/backend/app/alertas.py new file mode 100644 index 0000000..7ff2d27 --- /dev/null +++ b/backend/app/alertas.py @@ -0,0 +1,53 @@ +"""Alerta de preço: o usuário define um preço-alvo por peça; o status usa a pesquisa atual e o histórico.""" + +from __future__ import annotations + +import statistics + +from pydantic import BaseModel, Field + +from .precos import historico, pesquisar +from .store import Store + + +class AlertaCriar(BaseModel): + componente_id: str + preco_alvo: float = Field(gt=0) + + +class StatusAlerta(BaseModel): + componente_id: str + preco_alvo: float + menor_agora: float | None + loja: str | None + url: str | None # fonte do menor preço + atingido: bool + minimo_historico: float | None + tendencia: str # queda | alta | estavel | sem_dados + + +def tendencia(pontos: list[float]) -> str: + """Compara a média da primeira metade com a da segunda (variação acima de 3%).""" + if len(pontos) < 4: + return "sem_dados" + meio = len(pontos) // 2 + a, b = statistics.mean(pontos[:meio]), statistics.mean(pontos[meio:]) + if b < a * 0.97: + return "queda" + if b > a * 1.03: + return "alta" + return "estavel" + + +def status(store: Store, alerta: AlertaCriar) -> StatusAlerta: + r = pesquisar(store, alerta.componente_id) + melhor = min(r.ofertas, key=lambda o: o.preco) if r.ofertas else None + h = historico(store, alerta.componente_id) + por_dia: dict[str, list[float]] = {} + for x in h: + por_dia.setdefault(x["coletado_em"][:10], []).append(x["preco"]) + serie = [statistics.mean(v) for _, v in sorted(por_dia.items())] + return StatusAlerta(componente_id=alerta.componente_id, preco_alvo=alerta.preco_alvo, + menor_agora=melhor.preco if melhor else None, loja=melhor.loja if melhor else None, + url=melhor.url if melhor else None, atingido=bool(melhor and melhor.preco <= alerta.preco_alvo), + minimo_historico=min((x["preco"] for x in h), default=None), tendencia=tendencia(serie)) diff --git a/backend/app/main.py b/backend/app/main.py index 7a4175e..9e1f28d 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -8,7 +8,7 @@ from fastapi import Depends, FastAPI, HTTPException, Query, Response from fastapi.middleware.cors import CORSMiddleware -from . import agente, exportar, importar, precos, resultado +from . import agente, alertas, exportar, importar, precos, resultado from .compat.consolidador import bloqueantes_abertos, revisar_build from .compat.regras import TIPOS_UNICOS, motivo_incompativel from .config import get_settings @@ -282,3 +282,20 @@ def cena(build_id: str, store: Store = Depends(get_store)): return {"pecas": [{"id": c.id, "tipo": c.tipo, "nome": c.nome, "specs": c.specs} for c in comps if c.tipo != "extra"], "conflitos": conflitos, "passos": [{"tipo": t, "texto": txt} for t, txt in PASSOS if t in tipos]} + + +ALERTAS: dict[str, list[alertas.AlertaCriar]] = {} # ponytail: em memória por usuário; tabela no Supabase quando houver login + + +@app.post("/alertas", response_model=alertas.StatusAlerta) +def criar_alerta(dados: alertas.AlertaCriar, usuario: str = "demo", store: Store = Depends(get_store)): + if dados.componente_id not in store.componentes: + raise HTTPException(404, "componente não encontrado") + lista = [a for a in ALERTAS.setdefault(usuario, []) if a.componente_id != dados.componente_id] + ALERTAS[usuario] = lista + [dados] + return alertas.status(store, dados) + + +@app.get("/alertas", response_model=list[alertas.StatusAlerta]) +def ver_alertas(usuario: str = "demo", store: Store = Depends(get_store)): + return [alertas.status(store, a) for a in ALERTAS.get(usuario, [])] diff --git a/backend/tests/test_alertas.py b/backend/tests/test_alertas.py new file mode 100644 index 0000000..388b705 --- /dev/null +++ b/backend/tests/test_alertas.py @@ -0,0 +1,25 @@ +from app import alertas +from app.main import ALERTAS + + +def test_tendencia(): + assert alertas.tendencia([100, 100, 90, 90]) == "queda" + assert alertas.tendencia([90, 90, 100, 100]) == "alta" + assert alertas.tendencia([100, 101, 100, 99]) == "estavel" + assert alertas.tendencia([100]) == "sem_dados" + + +def test_status_com_fonte_e_historico(store): + s = alertas.status(store, alertas.AlertaCriar(componente_id="rx-7600", preco_alvo=99999)) + assert s.atingido and s.url and s.loja + assert s.minimo_historico is not None and s.tendencia == "queda" # seed: preços caem ~1%/semana + assert not alertas.status(store, alertas.AlertaCriar(componente_id="rx-7600", preco_alvo=1)).atingido + + +def test_rotas(client): + ALERTAS.clear() + assert client.post("/alertas", json={"componente_id": "nada", "preco_alvo": 10}).status_code == 404 + client.post("/alertas", json={"componente_id": "rtx-4060-8g", "preco_alvo": 100}) + client.post("/alertas", json={"componente_id": "rtx-4060-8g", "preco_alvo": 5000}) # substitui + lista = client.get("/alertas").json() + assert len(lista) == 1 and lista[0]["preco_alvo"] == 5000 and lista[0]["atingido"]