From c9003dff321df3233ad3ec62756805210fd5bf38 Mon Sep 17 00:00:00 2001 From: mathcolombo Date: Wed, 11 Nov 2026 15:35:17 -0300 Subject: [PATCH 1/6] feat(catalog): T1 Contrato do evento `stock.low` e RN-07 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Demanda: CAT-FEAT-01 Execução: 20261111T183041-cat-feat-01 --- docs/backlog/CAT-FEAT-01.md | 190 +++++++++++++++++++++++++ libs/events/skynet_events/__init__.py | 2 + libs/events/skynet_events/contracts.py | 9 ++ libs/events/tests/test_contracts.py | 93 +++++++++++- 4 files changed, 293 insertions(+), 1 deletion(-) create mode 100644 docs/backlog/CAT-FEAT-01.md diff --git a/docs/backlog/CAT-FEAT-01.md b/docs/backlog/CAT-FEAT-01.md new file mode 100644 index 0000000..e32b7ef --- /dev/null +++ b/docs/backlog/CAT-FEAT-01.md @@ -0,0 +1,190 @@ +# CAT-FEAT-01: Aviso de estoque baixo no catálogo + +Regra: RN-07 + +Regra nova (próximo número livre; a incluir em `docs/regras-de-negocio.md`): + +- **RN-07**: Cada produto pode ter um limite de estoque baixo opcional (inteiro >= 0). O produto está com estoque baixo quando tem limite e estoque < limite (estoque igual ao limite não é baixo). O catálogo publica `stock.low` uma única vez a cada cruzamento de "normal" para "baixo", qualquer que seja a origem (alteração manual de estoque, alteração do limite ou reserva de pedido). Enquanto continuar baixo não há novo aviso; ao voltar a estoque >= limite (ou sem limite) o produto volta ao normal e um novo cruzamento avisa de novo. Produto sem limite nunca gera aviso. + +## História +Como integrante da equipe de compras (e de quem opera a loja), quero que o catálogo avise quando o estoque de um produto cair abaixo do limite configurado para ele, para reagir antes de o produto zerar. + +## Critérios de aceitação + +Cenário: Cadastrar produto com limite + Dado que não existe o produto + Quando crio um produto com estoque 10 e limite 3 + Então o produto é criado com limite 3 e low_stock falso + E nenhum evento stock.low é publicado + +Cenário: Cadastrar produto sem limite + Dado que não existe o produto + Quando crio um produto sem informar limite + Então o limite do produto é nulo e low_stock é falso + +Cenário: Cadastrar produto já abaixo do limite + Dado que não existe o produto + Quando crio um produto com estoque 2 e limite 5 + Então o produto fica com low_stock verdadeiro + E um evento stock.low é publicado com estoque 2 e limite 5 + +Cenário: Alteração manual de estoque cruza o limite + Dado um produto com estoque 5 e limite 3 + Quando altero o estoque para 2 + Então um evento stock.low é publicado com product_id, nome, estoque 2 e limite 3 + E a consulta do produto mostra low_stock verdadeiro + +Cenário: Estoque igual ao limite não é baixo + Dado um produto com estoque 5 e limite 3 + Quando altero o estoque para 3 + Então nenhum evento stock.low é publicado + E low_stock é falso + +Cenário: Reserva de pedido cruza o limite + Dado um produto com estoque 5 e limite 3 + Quando chega order.created reservando 3 unidades desse produto + Então um evento stock.low é publicado com estoque 2 e limite 3, com o correlation_id do pedido + E stock.reserved também é publicado + +Cenário: Reserva de pedido com vários produtos + Dado dois produtos com limite, ambos prestes a cruzá-lo + Quando chega order.created reservando os dois + Então é publicado um stock.low para cada produto que cruzou o limite + +Cenário: Reserva rejeitada não avisa + Dado um produto com estoque 5 e limite 3 e outro sem estoque suficiente no mesmo pedido + Quando chega order.created e a reserva é rejeitada + Então nenhum stock.low é publicado e o estoque não muda + E stock.rejected é publicado + +Cenário: Sem repetição enquanto continua baixo + Dado um produto já com estoque baixo (estoque 2, limite 3) + Quando o estoque cai para 1 por alteração manual ou por reserva + Então nenhum novo stock.low é publicado + +Cenário: Reposição e novo cruzamento + Dado um produto com estoque baixo (estoque 2, limite 3) + Quando o estoque é reposto para 3 ou mais e depois cai de novo abaixo do limite + Então low_stock volta a falso na reposição + E um novo stock.low é publicado no segundo cruzamento + +Cenário: Configurar limite acima do estoque atual + Dado um produto com estoque 5 sem limite + Quando defino o limite como 8 + Então um evento stock.low é publicado com estoque 5 e limite 8 + E low_stock é verdadeiro + +Cenário: Aumentar o limite com produto já baixo + Dado um produto com estoque 2 e limite 3 já em estoque baixo + Quando altero o limite para 6 + Então nenhum novo stock.low é publicado + +Cenário: Reduzir o limite tira o produto de estoque baixo + Dado um produto com estoque 2 e limite 3 + Quando altero o limite para 2 + Então low_stock é falso e nenhum evento é publicado + +Cenário: Remover o limite + Dado um produto com limite 3 e estoque baixo + Quando envio o limite nulo + Então o limite passa a nulo e low_stock é falso + E nenhum evento é publicado + +Cenário: Alteração sem mencionar o limite preserva o limite + Dado um produto com limite 3 + Quando altero apenas o preço + Então o limite continua 3 + +Cenário: Produto sem limite nunca avisa + Dado um produto sem limite + Quando o estoque cai a zero por alteração manual ou por reserva + Então nenhum stock.low é publicado e low_stock é falso + +Cenário: Limite inválido + Dado um produto existente + Quando informo limite negativo (no cadastro ou na alteração) + Então a API responde 422 e nada muda + +Cenário: Reentrega de order.created não duplica aviso + Dado um order.created já processado que gerou stock.low + Quando o mesmo evento é entregue de novo + Então nenhum evento adicional é publicado + +Cenário: Consulta informa limite e situação + Dado produtos com e sem limite, alguns abaixo dele + Quando listo ou consulto produtos + Então cada produto traz low_stock_threshold (inteiro ou nulo) e low_stock (booleano) + +Cenário: Toast quando produto passa a ficar baixo + Dado a tela aberta com um produto normal + Quando uma alteração de estoque ou limite, ou a atualização periódica, mostra que ele passou a estar baixo + Então aparece um toast no canto superior direito: "Estoque baixo: — un. (limite )" + E ele tem role="status" e aria-live="polite", usa --warn, some após 5 segundos e tem botão "×" + +Cenário: Produto já baixo ao abrir a página não gera toast + Dado um produto já em estoque baixo quando a página abre + Quando a lista é carregada e atualizada sem mudança de situação + Então nenhum toast é exibido + +Cenário: Limite de toasts visíveis + Dado 3 toasts visíveis + Quando um quarto produto passa a ficar baixo + Então o toast mais antigo sai e no máximo 3 ficam visíveis, empilhados de cima para baixo + +Cenário: Configurar limite pela tela + Dado a lista do catálogo + Quando clico em "Limite" e informo um número + Então o limite é salvo; se deixo vazio, o limite é removido + E se informo valor inválido (negativo ou não inteiro), vejo erro em português e nada muda + +Cenário: Indicação visual na lista + Dado um produto com estoque baixo + Quando vejo a lista + Então o número do estoque aparece na cor --warn + +## Eventos +| Tipo | Campos | Novo ou alterado | +|---|---|---| +| `stock.low` | `product_id: str`, `name: str`, `stock: int`, `threshold: int` (envelope com `correlation_id`, `producer=catalog`, `VERSION=1`) | Novo (`StockLow`) | +| `product.created` | sem alteração (limite não faz parte do contrato) | Inalterado | + +## Questões em aberto +- Nome do evento na classe: `StockLow` com `EVENT_TYPE = "stock.low"`, campos `stock` e `threshold` (em inglês, conforme convenção). Confirmar no G3. +- Nomes dos campos da API: `low_stock_threshold` e `low_stock`. Confirmar no G3. +- Alteração manual (PATCH) não tem correlation_id de origem; o evento usa um novo, como `ProductPriceChanged`. Confirmar. +- Estado de "estoque baixo" a persistir ou derivar? Proposta: derivar comparando antes e depois de cada mudança, sem coluna extra. Confirmar. +- Produtos já abaixo do limite em bancos existentes (migração da coluna nova, nula por padrão): sem aviso retroativo. Confirmar. +- O toast da atualização periódica depende de a tela já ter polling; verificar `web/public/app.js`. Se não houver, definir o intervalo (fora da ``). +- Mensagem de erro de limite inválido na tela e rótulo do prompt "Limite": texto livre da equipe técnica. + +## Tasks + +### T1: Contrato do evento `stock.low` e RN-07 +Cenários: Nenhum cenário de comportamento direto (contrato validado por testes de contrato). +Arquivos: `libs/events/skynet_events/contracts.py`, `libs/events/skynet_events/__init__.py`, `libs/events/tests/`, `docs/regras-de-negocio.md` +Pronto quando: `StockLow` (EVENT_TYPE `stock.low`, VERSION 1) existe, está exportado, é codificado e decodificado em teste do envelope, RN-07 está na tabela e `pytest libs/events/tests` passa. + +### T2: Limite por produto no cadastro, na alteração e na consulta +Cenários: Cadastrar produto com limite; Cadastrar produto sem limite; Alteração sem mencionar o limite preserva o limite; Remover o limite; Limite inválido; Consulta informa limite e situação +Arquivos: `services/catalog/catalog_service/db.py`, `services/catalog/catalog_service/app.py`, `services/catalog/tests/test_catalog.py` +Pronto quando: coluna `low_stock_threshold` (nula, CHECK >= 0, com migração para bancos existentes); POST aceita o limite opcional; PATCH distingue limite ausente de nulo (`model_fields_set`); GET retorna `low_stock_threshold` e `low_stock`; `pytest services/catalog/tests` passa. + +### T3: Aviso por alteração manual de estoque ou de limite +Cenários: Cadastrar produto já abaixo do limite; Alteração manual de estoque cruza o limite; Estoque igual ao limite não é baixo; Sem repetição enquanto continua baixo; Reposição e novo cruzamento; Configurar limite acima do estoque atual; Aumentar o limite com produto já baixo; Reduzir o limite tira o produto de estoque baixo; Produto sem limite nunca avisa +Arquivos: `services/catalog/catalog_service/app.py`, `services/catalog/catalog_service/db.py`, `services/catalog/tests/test_catalog.py` +Pronto quando: POST e PATCH publicam `stock.low` somente na transição de não-baixo para baixo (comparando antes e depois), e os cenários acima passam com `InMemoryBus.published`. + +### T4: Aviso na reserva de estoque de pedidos +Cenários: Reserva de pedido cruza o limite; Reserva de pedido com vários produtos; Reserva rejeitada não avisa; Reentrega de order.created não duplica aviso; Sem repetição enquanto continua baixo +Arquivos: `services/catalog/catalog_service/db.py`, `services/catalog/catalog_service/app.py`, `services/catalog/tests/test_catalog.py` +Pronto quando: `reserve_stock` informa quais produtos cruzaram o limite (só quando a reserva é confirmada); `on_order_created` publica um `stock.low` por produto com o `correlation_id` do evento, depois de `stock.reserved`; a reentrega via `InMemoryBus.deliver` não publica nada novo; `bash scripts/ci.sh catalog` passa. + +### T5: Front: configurar limite e indicar estoque baixo +Cenários: Configurar limite pela tela; Indicação visual na lista +Arquivos: `web/public/index.html`, `web/public/app.js`, `web/public/lib.js`, `web/public/styles.css`, `web/tests/lib.test.js` +Pronto quando: o formulário tem o campo opcional "Limite" (mesmo tamanho do estoque); a lista tem o botão "Limite" ao lado de "Estoque" (vazio remove, inválido mostra erro); o estoque baixo aparece em `--warn`; a lógica pura (validação do limite e entrada para o payload) está em `lib.js` com testes; `node --test "web/tests/*.test.js"` passa. + +### T6: Front: toast de estoque baixo +Cenários: Toast quando produto passa a ficar baixo; Produto já baixo ao abrir a página não gera toast; Limite de toasts visíveis +Arquivos: `web/public/app.js`, `web/public/lib.js`, `web/public/styles.css`, `web/public/index.html`, `web/tests/lib.test.js` +Pronto quando: função pura em `lib.js` compara listas anteriores e atuais e devolve os produtos que passaram a ficar baixos (ignorando a primeira carga); o toast é montado com `createElement`/`textContent`, no canto superior direito, com `role="status"`, `aria-live="polite"`, `--warn`, botão "×", fechamento em 5 s e máximo de 3 visíveis; disparado após alterar estoque ou limite e na atualização periódica; `node --test "web/tests/*.test.js"` passa. diff --git a/libs/events/skynet_events/__init__.py b/libs/events/skynet_events/__init__.py index f8c7fcb..5ea1b66 100644 --- a/libs/events/skynet_events/__init__.py +++ b/libs/events/skynet_events/__init__.py @@ -8,6 +8,7 @@ OrderRejected, ProductCreated, ProductPriceChanged, + StockLow, StockRejected, StockReserved, decode, @@ -28,6 +29,7 @@ "ProductCreated", "ProductPriceChanged", "RabbitMqBus", + "StockLow", "StockRejected", "StockReserved", "decode", diff --git a/libs/events/skynet_events/contracts.py b/libs/events/skynet_events/contracts.py index 11f71ae..55328b1 100644 --- a/libs/events/skynet_events/contracts.py +++ b/libs/events/skynet_events/contracts.py @@ -78,6 +78,15 @@ class StockRejected(EventPayload): reason: str +class StockLow(EventPayload): + EVENT_TYPE: ClassVar[str] = "stock.low" + + product_id: str + name: str + stock: int + threshold: int + + P = TypeVar("P", bound=EventPayload) diff --git a/libs/events/tests/test_contracts.py b/libs/events/tests/test_contracts.py index 760a1e5..6e8f17b 100644 --- a/libs/events/tests/test_contracts.py +++ b/libs/events/tests/test_contracts.py @@ -1,6 +1,18 @@ +from pathlib import Path +from uuid import uuid4 + import pytest +from pydantic import ValidationError -from skynet_events import InMemoryBus, ProductPriceChanged, StockReserved, decode, new_event +from skynet_events import ( + EventEnvelope, + InMemoryBus, + ProductPriceChanged, + StockLow, + StockReserved, + decode, + new_event, +) def test_decode_round_trip(): @@ -19,6 +31,85 @@ def test_decode_rejects_wrong_type(): decode(event, ProductPriceChanged) +def test_stock_low_contract_metadata_and_export(): + """CAT-FEAT-01 T1: contrato StockLow (stock.low, versão 1) exportado.""" + import skynet_events + + assert "StockLow" in skynet_events.__all__ + assert skynet_events.StockLow.EVENT_TYPE == "stock.low" + assert skynet_events.StockLow.VERSION == 1 + + +def test_stock_low_envelope_round_trip(): + """CAT-FEAT-01 T1: StockLow é codificado no envelope e decodificado.""" + correlation_id = uuid4() + event = new_event( + StockLow(product_id="p1", name="Caneta", stock=2, threshold=5), + "catalog", + correlation_id, + ) + + assert event.event_type == "stock.low" + assert event.version == 1 + assert event.producer == "catalog" + assert event.correlation_id == correlation_id + assert event.payload == {"product_id": "p1", "name": "Caneta", "stock": 2, "threshold": 5} + + decoded = decode(event, StockLow) + assert decoded.product_id == "p1" + assert decoded.name == "Caneta" + assert decoded.stock == 2 + assert decoded.threshold == 5 + + +def test_stock_low_survives_json_serialization(): + """CAT-FEAT-01 T1: envelope com StockLow sobrevive a ida e volta em JSON.""" + event = new_event(StockLow(product_id="p1", name="Caneta", stock=0, threshold=3), "catalog") + + restored = EventEnvelope.model_validate_json(event.model_dump_json()) + + assert restored == event + assert decode(restored, StockLow).threshold == 3 + + +def test_stock_low_requires_all_fields(): + """CAT-FEAT-01 T1: campos do contrato são obrigatórios.""" + with pytest.raises(ValidationError): + StockLow.model_validate({"product_id": "p1", "name": "Caneta", "stock": 1}) + + +def test_decode_stock_low_rejects_other_type(): + """CAT-FEAT-01 T1: decode de StockLow rejeita outro tipo de evento.""" + event = new_event(StockReserved(order_id="o1"), "catalog") + + with pytest.raises(ValueError): + decode(event, StockLow) + + +async def test_in_memory_bus_delivers_stock_low_to_subscriber(): + """CAT-FEAT-01 T1: barramento em memória entrega stock.low a assinantes.""" + bus = InMemoryBus() + received = [] + + async def handler(event): + received.append(event) + + await bus.subscribe("purchasing", ["stock.low"], handler) + await bus.publish(new_event(StockLow(product_id="p1", name="Caneta", stock=1, threshold=4), "catalog")) + + assert [decode(e, StockLow).stock for e in received] == [1] + assert [e.event_type for e in bus.published] == ["stock.low"] + + +def test_rn07_in_business_rules(): + """CAT-FEAT-01 T1: RN-07 consta na tabela de regras de negócio.""" + rules = (Path(__file__).parents[3] / "docs" / "regras-de-negocio.md").read_text( + encoding="utf-8" + ) + + assert "| RN-07 |" in rules + + async def test_in_memory_bus_dispatches_by_event_type(): bus = InMemoryBus() received = [] From 03ed6afc3663d8ccc755f20d6d0e450190158c9e Mon Sep 17 00:00:00 2001 From: mathcolombo Date: Wed, 11 Nov 2026 15:36:58 -0300 Subject: [PATCH 2/6] =?UTF-8?q?feat(catalog):=20T2=20Limite=20por=20produt?= =?UTF-8?q?o=20no=20cadastro,=20na=20altera=C3=A7=C3=A3o=20e=20na=20consul?= =?UTF-8?q?ta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Demanda: CAT-FEAT-01 Execução: 20261111T183041-cat-feat-01 --- services/catalog/catalog_service/app.py | 28 +++- services/catalog/catalog_service/db.py | 34 ++++- services/catalog/tests/test_catalog.py | 180 ++++++++++++++++++++++++ 3 files changed, 231 insertions(+), 11 deletions(-) diff --git a/services/catalog/catalog_service/app.py b/services/catalog/catalog_service/app.py index dd82dd9..ea2ef95 100644 --- a/services/catalog/catalog_service/app.py +++ b/services/catalog/catalog_service/app.py @@ -24,12 +24,21 @@ class ProductCreate(BaseModel): name: str = Field(min_length=1) price_cents: int = Field(ge=0) stock: int = Field(ge=0) + low_stock_threshold: int | None = Field(default=None, ge=0) class ProductUpdate(BaseModel): name: str | None = Field(default=None, min_length=1) price_cents: int | None = Field(default=None, ge=0) stock: int | None = Field(default=None, ge=0) + low_stock_threshold: int | None = Field(default=None, ge=0) + + +def product_view(product) -> dict: + data = dict(product) + threshold = data["low_stock_threshold"] + data["low_stock"] = threshold is not None and data["stock"] < threshold + return data def create_app(database_path: str, bus: EventBus) -> FastAPI: @@ -62,7 +71,9 @@ async def health() -> dict[str, str]: @app.post("/products", status_code=201) async def create_product(body: ProductCreate) -> dict: - product = db.create_product(body.name, body.price_cents, body.stock) + product = db.create_product( + body.name, body.price_cents, body.stock, body.low_stock_threshold + ) await bus.publish( new_event( ProductCreated( @@ -73,18 +84,18 @@ async def create_product(body: ProductCreate) -> dict: PRODUCER, ) ) - return dict(product) + return product_view(product) @app.get("/products") async def list_products() -> list[dict]: - return [dict(product) for product in db.list_products()] + return [product_view(product) for product in db.list_products()] @app.get("/products/{product_id}") async def get_product(product_id: str) -> dict: product = db.get_product(product_id) if product is None: raise HTTPException(status_code=404, detail="produto não encontrado") - return dict(product) + return product_view(product) @app.patch("/products/{product_id}") async def update_product(product_id: str, body: ProductUpdate) -> dict: @@ -92,7 +103,14 @@ async def update_product(product_id: str, body: ProductUpdate) -> dict: if previous is None: raise HTTPException(status_code=404, detail="produto não encontrado") old_price_cents = previous["price_cents"] - product = db.update_product(product_id, body.name, body.price_cents, body.stock) + product = db.update_product( + product_id, + body.name, + body.price_cents, + body.stock, + body.low_stock_threshold, + set_threshold="low_stock_threshold" in body.model_fields_set, + ) if body.price_cents is not None and body.price_cents != old_price_cents: await bus.publish( new_event( diff --git a/services/catalog/catalog_service/db.py b/services/catalog/catalog_service/db.py index b165efa..48e16b9 100644 --- a/services/catalog/catalog_service/db.py +++ b/services/catalog/catalog_service/db.py @@ -6,7 +6,8 @@ id TEXT PRIMARY KEY, name TEXT NOT NULL, price_cents INTEGER NOT NULL CHECK (price_cents >= 0), - stock INTEGER NOT NULL CHECK (stock >= 0) + stock INTEGER NOT NULL CHECK (stock >= 0), + low_stock_threshold INTEGER CHECK (low_stock_threshold >= 0) ); CREATE TABLE IF NOT EXISTS processed_events (event_id TEXT PRIMARY KEY); """ @@ -17,13 +18,30 @@ def __init__(self, path: str) -> None: self.conn = sqlite3.connect(path, check_same_thread=False) self.conn.row_factory = sqlite3.Row self.conn.executescript(SCHEMA) + self._migrate() - def create_product(self, name: str, price_cents: int, stock: int) -> sqlite3.Row: + def _migrate(self) -> None: + columns = {row["name"] for row in self.conn.execute("PRAGMA table_info(products)")} + if "low_stock_threshold" not in columns: + with self.conn: + self.conn.execute( + "ALTER TABLE products ADD COLUMN low_stock_threshold INTEGER " + "CHECK (low_stock_threshold >= 0)" + ) + + def create_product( + self, + name: str, + price_cents: int, + stock: int, + low_stock_threshold: int | None = None, + ) -> sqlite3.Row: product_id = str(uuid4()) with self.conn: self.conn.execute( - "INSERT INTO products (id, name, price_cents, stock) VALUES (?, ?, ?, ?)", - (product_id, name, price_cents, stock), + "INSERT INTO products (id, name, price_cents, stock, low_stock_threshold) " + "VALUES (?, ?, ?, ?, ?)", + (product_id, name, price_cents, stock, low_stock_threshold), ) return self.get_product(product_id) @@ -41,17 +59,21 @@ def update_product( name: str | None = None, price_cents: int | None = None, stock: int | None = None, + low_stock_threshold: int | None = None, + set_threshold: bool = False, ) -> sqlite3.Row | None: + """`set_threshold` indica que o limite foi informado (inclusive como nulo).""" with self.conn: self.conn.execute( """ UPDATE products SET name = COALESCE(?, name), price_cents = COALESCE(?, price_cents), - stock = COALESCE(?, stock) + stock = COALESCE(?, stock), + low_stock_threshold = CASE WHEN ? THEN ? ELSE low_stock_threshold END WHERE id = ? """, - (name, price_cents, stock, product_id), + (name, price_cents, stock, int(set_threshold), low_stock_threshold, product_id), ) return self.get_product(product_id) diff --git a/services/catalog/tests/test_catalog.py b/services/catalog/tests/test_catalog.py index fd55d66..afefaca 100644 --- a/services/catalog/tests/test_catalog.py +++ b/services/catalog/tests/test_catalog.py @@ -1,7 +1,11 @@ +import sqlite3 + +import pytest from fastapi.testclient import TestClient from skynet_events import InMemoryBus from catalog_service.app import create_app +from catalog_service.db import CatalogDb def test_create_product_publishes_event(): @@ -44,3 +48,179 @@ def test_patch_without_price_change_does_not_publish_price_changed(): client.patch(f"/products/{created['id']}", json={"price_cents": 5000}) assert [event.event_type for event in bus.published] == ["product.created"] + + +# ---------------------------------------------------------------- CAT-FEAT-01 / T2 + + +def _create(client, **overrides): + body = {"name": "Cabo", "price_cents": 1000, "stock": 10} + body.update(overrides) + return client.post("/products", json=body) + + +def test_create_product_with_threshold(): + """CAT-FEAT-01, cenário "Cadastrar produto com limite".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + response = _create(client, stock=10, low_stock_threshold=3) + assert response.status_code == 201 + body = response.json() + assert body["low_stock_threshold"] == 3 + assert body["low_stock"] is False + assert client.get(f"/products/{body['id']}").json()["low_stock_threshold"] == 3 + + assert "stock.low" not in [event.event_type for event in bus.published] + + +def test_create_product_without_threshold(): + """CAT-FEAT-01, cenário "Cadastrar produto sem limite".""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + body = _create(client).json() + assert body["low_stock_threshold"] is None + assert body["low_stock"] is False + assert client.get(f"/products/{body['id']}").json()["low_stock_threshold"] is None + + +def test_patch_without_threshold_preserves_it(): + """CAT-FEAT-01, cenário "Alteração sem mencionar o limite preserva o limite".""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + product = _create(client, low_stock_threshold=3).json() + response = client.patch(f"/products/{product['id']}", json={"price_cents": 2000}) + + assert response.status_code == 200 + assert response.json()["low_stock_threshold"] == 3 + fetched = client.get(f"/products/{product['id']}").json() + assert fetched["low_stock_threshold"] == 3 + assert fetched["price_cents"] == 2000 + + +def test_patch_null_threshold_removes_it(): + """CAT-FEAT-01, cenário "Remover o limite".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=2, low_stock_threshold=3).json() + published_before = len(bus.published) + response = client.patch(f"/products/{product['id']}", json={"low_stock_threshold": None}) + + assert response.status_code == 200 + assert response.json()["low_stock_threshold"] is None + fetched = client.get(f"/products/{product['id']}").json() + assert fetched["low_stock_threshold"] is None + assert fetched["low_stock"] is False + + assert len(bus.published) == published_before + + +def test_patch_sets_and_changes_threshold(): + """CAT-FEAT-01, cenário "Remover o limite" (complemento): limite informado é gravado.""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + product = _create(client, stock=10).json() + response = client.patch(f"/products/{product['id']}", json={"low_stock_threshold": 4}) + assert response.json()["low_stock_threshold"] == 4 + assert client.get(f"/products/{product['id']}").json()["low_stock_threshold"] == 4 + + +def test_create_with_negative_threshold_is_rejected(): + """CAT-FEAT-01, cenário "Limite inválido" (cadastro).""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + response = _create(client, low_stock_threshold=-1) + assert response.status_code == 422 + assert client.get("/products").json() == [] + + assert bus.published == [] + + +def test_patch_with_negative_threshold_is_rejected_and_changes_nothing(): + """CAT-FEAT-01, cenário "Limite inválido" (alteração).""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + product = _create(client, low_stock_threshold=3).json() + response = client.patch( + f"/products/{product['id']}", json={"low_stock_threshold": -5, "price_cents": 1} + ) + assert response.status_code == 422 + assert client.get(f"/products/{product['id']}").json() == product + + +def test_create_with_non_integer_threshold_is_rejected(): + """CAT-FEAT-01, cenário "Limite inválido": valor não inteiro.""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + assert _create(client, low_stock_threshold="muito").status_code == 422 + assert _create(client, low_stock_threshold=1.5).status_code == 422 + + +def test_zero_threshold_is_valid_and_never_low(): + """CAT-FEAT-01, "Limite inválido": zero é aceito (inteiro >= 0); estoque 0 não é menor que 0.""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + body = _create(client, stock=0, low_stock_threshold=0).json() + assert body["low_stock_threshold"] == 0 + assert body["low_stock"] is False + + +def test_query_reports_threshold_and_low_stock_for_list_and_detail(): + """CAT-FEAT-01, cenário "Consulta informa limite e situação".""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + low = _create(client, name="A-baixo", stock=2, low_stock_threshold=5).json() + equal = _create(client, name="B-igual", stock=5, low_stock_threshold=5).json() + above = _create(client, name="C-acima", stock=9, low_stock_threshold=5).json() + none = _create(client, name="D-sem", stock=0).json() + + listed = {p["id"]: p for p in client.get("/products").json()} + expected = { + low["id"]: (5, True), + equal["id"]: (5, False), + above["id"]: (5, False), + none["id"]: (None, False), + } + for product_id, (threshold, is_low) in expected.items(): + for view in (listed[product_id], client.get(f"/products/{product_id}").json()): + assert view["low_stock_threshold"] == threshold + assert view["low_stock"] is is_low + + +def test_low_stock_reflects_threshold_patch(): + """CAT-FEAT-01, "Consulta informa limite e situação": low_stock acompanha mudança do limite.""" + with TestClient(create_app(":memory:", InMemoryBus())) as client: + product = _create(client, stock=5).json() + client.patch(f"/products/{product['id']}", json={"low_stock_threshold": 8}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is True + client.patch(f"/products/{product['id']}", json={"low_stock_threshold": 5}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is False + + +def test_existing_database_without_column_is_migrated(tmp_path): + """CAT-FEAT-01, T2: migração de banco existente sem a coluna `low_stock_threshold`.""" + path = str(tmp_path / "old.db") + old = sqlite3.connect(path) + old.executescript( + """ + CREATE TABLE products ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + price_cents INTEGER NOT NULL CHECK (price_cents >= 0), + stock INTEGER NOT NULL CHECK (stock >= 0) + ); + CREATE TABLE processed_events (event_id TEXT PRIMARY KEY); + INSERT INTO products VALUES ('legacy-1', 'Antigo', 100, 4); + """ + ) + old.commit() + old.close() + + with TestClient(create_app(path, InMemoryBus())) as client: + legacy = client.get("/products/legacy-1").json() + assert legacy["low_stock_threshold"] is None + assert legacy["low_stock"] is False + + client.patch("/products/legacy-1", json={"low_stock_threshold": 9}) + migrated = client.get("/products/legacy-1").json() + assert migrated["low_stock_threshold"] == 9 + assert migrated["low_stock"] is True + + +def test_database_rejects_negative_threshold_directly(): + """CAT-FEAT-01, T2: a coluna tem CHECK (>= 0), independentemente da validação da API.""" + db = CatalogDb(":memory:") + with pytest.raises(sqlite3.IntegrityError): + db.create_product("X", 1, 1, -1) From 3b2e64b1959155b4b30084f2bdc0f267a64b299a Mon Sep 17 00:00:00 2001 From: mathcolombo Date: Wed, 11 Nov 2026 15:38:18 -0300 Subject: [PATCH 3/6] =?UTF-8?q?feat(catalog):=20T3=20Aviso=20por=20altera?= =?UTF-8?q?=C3=A7=C3=A3o=20manual=20de=20estoque=20ou=20de=20limite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Demanda: CAT-FEAT-01 Execução: 20261111T183041-cat-feat-01 --- services/catalog/catalog_service/app.py | 27 +++- services/catalog/tests/test_catalog.py | 166 ++++++++++++++++++++++++ 2 files changed, 190 insertions(+), 3 deletions(-) diff --git a/services/catalog/catalog_service/app.py b/services/catalog/catalog_service/app.py index ea2ef95..80d1f17 100644 --- a/services/catalog/catalog_service/app.py +++ b/services/catalog/catalog_service/app.py @@ -10,6 +10,7 @@ ProductCreated, ProductPriceChanged, StockRejected, + StockLow, StockReserved, decode, new_event, @@ -34,13 +35,29 @@ class ProductUpdate(BaseModel): low_stock_threshold: int | None = Field(default=None, ge=0) +def is_low_stock(product) -> bool: + threshold = product["low_stock_threshold"] + return threshold is not None and product["stock"] < threshold + + def product_view(product) -> dict: data = dict(product) - threshold = data["low_stock_threshold"] - data["low_stock"] = threshold is not None and data["stock"] < threshold + data["low_stock"] = is_low_stock(product) return data +def stock_low_event(product): + return new_event( + StockLow( + product_id=product["id"], + name=product["name"], + stock=product["stock"], + threshold=product["low_stock_threshold"], + ), + PRODUCER, + ) + + def create_app(database_path: str, bus: EventBus) -> FastAPI: db = CatalogDb(database_path) @@ -84,6 +101,8 @@ async def create_product(body: ProductCreate) -> dict: PRODUCER, ) ) + if is_low_stock(product): + await bus.publish(stock_low_event(product)) return product_view(product) @app.get("/products") @@ -122,6 +141,8 @@ async def update_product(product_id: str, body: ProductUpdate) -> dict: PRODUCER, ) ) - return dict(product) + if is_low_stock(product) and not is_low_stock(previous): + await bus.publish(stock_low_event(product)) + return product_view(product) return app diff --git a/services/catalog/tests/test_catalog.py b/services/catalog/tests/test_catalog.py index afefaca..3516d13 100644 --- a/services/catalog/tests/test_catalog.py +++ b/services/catalog/tests/test_catalog.py @@ -224,3 +224,169 @@ def test_database_rejects_negative_threshold_directly(): db = CatalogDb(":memory:") with pytest.raises(sqlite3.IntegrityError): db.create_product("X", 1, 1, -1) + + +# ---------------------------------------------------------------- CAT-FEAT-01 / T3 + + +def _low_events(bus): + return [event for event in bus.published if event.event_type == "stock.low"] + + +def test_create_product_already_below_threshold_publishes_stock_low(): + """CAT-FEAT-01, cenário "Cadastrar produto já abaixo do limite".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, name="Pilha", stock=2, low_stock_threshold=5).json() + + assert product["low_stock"] is True + low = _low_events(bus) + assert len(low) == 1 + assert low[0].producer == "catalog" + assert low[0].payload == { + "product_id": product["id"], + "name": "Pilha", + "stock": 2, + "threshold": 5, + } + + +def test_manual_stock_change_crossing_threshold_publishes_stock_low(): + """CAT-FEAT-01, cenário "Alteração manual de estoque cruza o limite".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, name="Fita", stock=5, low_stock_threshold=3).json() + assert _low_events(bus) == [] + response = client.patch(f"/products/{product['id']}", json={"stock": 2}) + assert response.status_code == 200 + assert client.get(f"/products/{product['id']}").json()["low_stock"] is True + + low = _low_events(bus) + assert len(low) == 1 + assert low[0].payload == { + "product_id": product["id"], + "name": "Fita", + "stock": 2, + "threshold": 3, + } + + +def test_stock_equal_to_threshold_is_not_low(): + """CAT-FEAT-01, cenário "Estoque igual ao limite não é baixo".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=5, low_stock_threshold=3).json() + client.patch(f"/products/{product['id']}", json={"stock": 3}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is False + + assert _low_events(bus) == [] + + +def test_no_repeated_stock_low_while_still_low(): + """CAT-FEAT-01, cenário "Sem repetição enquanto continua baixo" (alteração manual).""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=5, low_stock_threshold=3).json() + client.patch(f"/products/{product['id']}", json={"stock": 2}) + client.patch(f"/products/{product['id']}", json={"stock": 1}) + client.patch(f"/products/{product['id']}", json={"stock": 0}) + client.patch(f"/products/{product['id']}", json={"price_cents": 1}) + + assert len(_low_events(bus)) == 1 + + +def test_replenish_then_new_crossing_publishes_again(): + """CAT-FEAT-01, cenário "Reposição e novo cruzamento".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=2, low_stock_threshold=3).json() + assert len(_low_events(bus)) == 1 + + client.patch(f"/products/{product['id']}", json={"stock": 3}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is False + assert len(_low_events(bus)) == 1 + + client.patch(f"/products/{product['id']}", json={"stock": 1}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is True + + low = _low_events(bus) + assert len(low) == 2 + assert low[1].payload["stock"] == 1 + assert low[1].payload["threshold"] == 3 + + +def test_replenish_above_threshold_then_cross_again(): + """CAT-FEAT-01, "Reposição e novo cruzamento": reposição acima do limite.""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=1, low_stock_threshold=3).json() + client.patch(f"/products/{product['id']}", json={"stock": 20}) + client.patch(f"/products/{product['id']}", json={"stock": 2}) + + assert len(_low_events(bus)) == 2 + + +def test_setting_threshold_above_current_stock_publishes_stock_low(): + """CAT-FEAT-01, cenário "Configurar limite acima do estoque atual".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, name="Bateria", stock=5).json() + assert _low_events(bus) == [] + client.patch(f"/products/{product['id']}", json={"low_stock_threshold": 8}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is True + + low = _low_events(bus) + assert len(low) == 1 + assert low[0].payload == { + "product_id": product["id"], + "name": "Bateria", + "stock": 5, + "threshold": 8, + } + + +def test_raising_threshold_when_already_low_does_not_publish_again(): + """CAT-FEAT-01, cenário "Aumentar o limite com produto já baixo".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=2, low_stock_threshold=3).json() + assert len(_low_events(bus)) == 1 + client.patch(f"/products/{product['id']}", json={"low_stock_threshold": 6}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is True + + assert len(_low_events(bus)) == 1 + + +def test_lowering_threshold_takes_product_out_of_low_without_event(): + """CAT-FEAT-01, cenário "Reduzir o limite tira o produto de estoque baixo".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=2, low_stock_threshold=3).json() + published_before = len(bus.published) + client.patch(f"/products/{product['id']}", json={"low_stock_threshold": 2}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is False + + assert len(bus.published) == published_before + + +def test_product_without_threshold_never_publishes_stock_low_on_manual_change(): + """CAT-FEAT-01, cenário "Produto sem limite nunca avisa" (alteração manual).""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=5).json() + client.patch(f"/products/{product['id']}", json={"stock": 1}) + client.patch(f"/products/{product['id']}", json={"stock": 0}) + assert client.get(f"/products/{product['id']}").json()["low_stock"] is False + + assert _low_events(bus) == [] + + +def test_removing_threshold_then_stock_drop_does_not_publish(): + """CAT-FEAT-01, "Produto sem limite nunca avisa": limite removido deixa de avisar.""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=5, low_stock_threshold=3).json() + client.patch(f"/products/{product['id']}", json={"low_stock_threshold": None}) + client.patch(f"/products/{product['id']}", json={"stock": 0}) + + assert _low_events(bus) == [] From 7459a7d8c85857f60a3af9dad5746680a0efdc79 Mon Sep 17 00:00:00 2001 From: mathcolombo Date: Wed, 11 Nov 2026 15:39:36 -0300 Subject: [PATCH 4/6] feat(catalog): T4 Aviso na reserva de estoque de pedidos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Demanda: CAT-FEAT-01 Execução: 20261111T183041-cat-feat-01 --- services/catalog/catalog_service/app.py | 13 +- services/catalog/catalog_service/db.py | 23 +++- services/catalog/tests/test_catalog.py | 175 +++++++++++++++++++++++- 3 files changed, 201 insertions(+), 10 deletions(-) diff --git a/services/catalog/catalog_service/app.py b/services/catalog/catalog_service/app.py index 80d1f17..defcd38 100644 --- a/services/catalog/catalog_service/app.py +++ b/services/catalog/catalog_service/app.py @@ -46,7 +46,7 @@ def product_view(product) -> dict: return data -def stock_low_event(product): +def stock_low_event(product, correlation_id=None): return new_event( StockLow( product_id=product["id"], @@ -55,6 +55,7 @@ def stock_low_event(product): threshold=product["low_stock_threshold"], ), PRODUCER, + correlation_id, ) @@ -65,13 +66,15 @@ async def on_order_created(event: EventEnvelope) -> None: if not db.mark_processed(str(event.event_id)): return order = decode(event, OrderCreated) - reserved = db.reserve_stock([(item.product_id, item.quantity) for item in order.items]) + crossed = db.reserve_stock([(item.product_id, item.quantity) for item in order.items]) result = ( - StockReserved(order_id=order.order_id) - if reserved - else StockRejected(order_id=order.order_id, reason="estoque insuficiente") + StockRejected(order_id=order.order_id, reason="estoque insuficiente") + if crossed is None + else StockReserved(order_id=order.order_id) ) await bus.publish(new_event(result, PRODUCER, event.correlation_id)) + for product in crossed or []: + await bus.publish(stock_low_event(product, event.correlation_id)) @asynccontextmanager async def lifespan(_: FastAPI) -> AsyncIterator[None]: diff --git a/services/catalog/catalog_service/db.py b/services/catalog/catalog_service/db.py index 48e16b9..a8fcfe9 100644 --- a/services/catalog/catalog_service/db.py +++ b/services/catalog/catalog_service/db.py @@ -77,9 +77,23 @@ def update_product( ) return self.get_product(product_id) - def reserve_stock(self, items: list[tuple[str, int]]) -> bool: - """Reserva todos os itens ou nenhum.""" + def reserve_stock(self, items: list[tuple[str, int]]) -> list[sqlite3.Row] | None: + """Reserva todos os itens ou nenhum. + + Retorna None se a reserva foi rejeitada; caso contrário, os produtos + (já com o estoque atualizado) que passaram a ter estoque baixo. + """ + + def is_low(row: sqlite3.Row | None) -> bool: + return ( + row is not None + and row["low_stock_threshold"] is not None + and row["stock"] < row["low_stock_threshold"] + ) + + product_ids = list(dict.fromkeys(product_id for product_id, _ in items)) with self.conn: + before = {pid: is_low(self.get_product(pid)) for pid in product_ids} for product_id, quantity in items: updated = self.conn.execute( "UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?", @@ -87,8 +101,9 @@ def reserve_stock(self, items: list[tuple[str, int]]) -> bool: ) if updated.rowcount == 0: self.conn.rollback() - return False - return True + return None + after = {pid: self.get_product(pid) for pid in product_ids} + return [row for pid, row in after.items() if is_low(row) and not before[pid]] def mark_processed(self, event_id: str) -> bool: """Retorna False se o evento já foi processado.""" diff --git a/services/catalog/tests/test_catalog.py b/services/catalog/tests/test_catalog.py index 3516d13..3fd8783 100644 --- a/services/catalog/tests/test_catalog.py +++ b/services/catalog/tests/test_catalog.py @@ -1,8 +1,10 @@ +import asyncio import sqlite3 +from uuid import uuid4 import pytest from fastapi.testclient import TestClient -from skynet_events import InMemoryBus +from skynet_events import InMemoryBus, LineItem, OrderCreated, new_event from catalog_service.app import create_app from catalog_service.db import CatalogDb @@ -390,3 +392,174 @@ def test_removing_threshold_then_stock_drop_does_not_publish(): client.patch(f"/products/{product['id']}", json={"stock": 0}) assert _low_events(bus) == [] + + +# ---------------------------------------------------------------- CAT-FEAT-01 / T4 + + +def _order_created(items, correlation_id=None): + payload = OrderCreated( + order_id="order-1", + cart_id="cart-1", + customer_id="cliente-1", + items=[ + LineItem(product_id=product_id, quantity=quantity, unit_price_cents=1000) + for product_id, quantity in items + ], + total_cents=1000, + ) + return new_event(payload, "orders", correlation_id or uuid4()) + + +def _types(bus): + return [event.event_type for event in bus.published] + + +def test_order_reservation_crossing_threshold_publishes_stock_low_after_reserved(): + """CAT-FEAT-01, cenário "Reserva de pedido cruza o limite".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, name="Lampada", stock=5, low_stock_threshold=3).json() + published_before = len(bus.published) + order = _order_created([(product["id"], 3)]) + + asyncio.run(bus.publish(order)) + + new_types = _types(bus)[published_before:] + assert new_types == ["order.created", "stock.reserved", "stock.low"] + fetched = client.get(f"/products/{product['id']}").json() + assert fetched["stock"] == 2 + assert fetched["low_stock"] is True + + low = _low_events(bus) + assert len(low) == 1 + assert low[0].correlation_id == order.correlation_id + assert low[0].producer == "catalog" + assert low[0].payload == { + "product_id": product["id"], + "name": "Lampada", + "stock": 2, + "threshold": 3, + } + + +def test_order_reservation_with_several_products_publishes_one_stock_low_each(): + """CAT-FEAT-01, cenário "Reserva de pedido com vários produtos".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + first = _create(client, name="Alfa", stock=5, low_stock_threshold=3).json() + second = _create(client, name="Beta", stock=4, low_stock_threshold=4).json() + untouched = _create(client, name="Gama", stock=9, low_stock_threshold=3).json() + order = _order_created([(first["id"], 3), (second["id"], 1), (untouched["id"], 1)]) + + asyncio.run(bus.publish(order)) + + low = _low_events(bus) + assert sorted(event.payload["product_id"] for event in low) == sorted( + [first["id"], second["id"]] + ) + by_product = {event.payload["product_id"]: event.payload for event in low} + assert by_product[first["id"]]["stock"] == 2 + assert by_product[second["id"]]["stock"] == 3 + assert all(event.correlation_id == order.correlation_id for event in low) + assert _types(bus).count("stock.reserved") == 1 + + +def test_order_reservation_same_product_in_two_lines_publishes_single_stock_low(): + """CAT-FEAT-01, "Reserva de pedido com vários produtos": um aviso por produto, não por linha.""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=6, low_stock_threshold=3).json() + asyncio.run(bus.publish(_order_created([(product["id"], 2), (product["id"], 2)]))) + + assert len(_low_events(bus)) == 1 + assert _low_events(bus)[0].payload["stock"] == 2 + + +def test_rejected_reservation_publishes_no_stock_low_and_keeps_stock(): + """CAT-FEAT-01, cenário "Reserva rejeitada não avisa".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + ok = _create(client, name="Ok", stock=5, low_stock_threshold=3).json() + short = _create(client, name="Curto", stock=1).json() + published_before = len(bus.published) + + asyncio.run(bus.publish(_order_created([(ok["id"], 3), (short["id"], 2)]))) + + assert _types(bus)[published_before:] == ["order.created", "stock.rejected"] + assert client.get(f"/products/{ok['id']}").json()["stock"] == 5 + assert client.get(f"/products/{ok['id']}").json()["low_stock"] is False + assert client.get(f"/products/{short['id']}").json()["stock"] == 1 + + assert _low_events(bus) == [] + + +def test_redelivered_order_created_does_not_duplicate_stock_low(): + """CAT-FEAT-01, cenário "Reentrega de order.created não duplica aviso".""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=5, low_stock_threshold=3).json() + order = _order_created([(product["id"], 3)]) + asyncio.run(bus.publish(order)) + published_before = len(bus.published) + + asyncio.run(bus.deliver(order)) + + assert len(bus.published) == published_before + assert client.get(f"/products/{product['id']}").json()["stock"] == 2 + + assert len(_low_events(bus)) == 1 + + +def test_order_reservation_while_already_low_does_not_publish_again(): + """CAT-FEAT-01, cenário "Sem repetição enquanto continua baixo" (reserva).""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=2, low_stock_threshold=3).json() + assert len(_low_events(bus)) == 1 + + asyncio.run(bus.publish(_order_created([(product["id"], 1)]))) + + assert client.get(f"/products/{product['id']}").json()["stock"] == 1 + assert "stock.reserved" in _types(bus) + + assert len(_low_events(bus)) == 1 + + +def test_order_reservation_without_threshold_never_publishes_stock_low(): + """CAT-FEAT-01, cenário "Produto sem limite nunca avisa" (reserva).""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=3).json() + asyncio.run(bus.publish(_order_created([(product["id"], 3)]))) + + assert client.get(f"/products/{product['id']}").json()["stock"] == 0 + assert client.get(f"/products/{product['id']}").json()["low_stock"] is False + + assert _low_events(bus) == [] + assert "stock.reserved" in _types(bus) + + +def test_reservation_not_crossing_threshold_does_not_publish(): + """CAT-FEAT-01, T4: reserva que deixa estoque igual ao limite não avisa.""" + bus = InMemoryBus() + with TestClient(create_app(":memory:", bus)) as client: + product = _create(client, stock=5, low_stock_threshold=3).json() + asyncio.run(bus.publish(_order_created([(product["id"], 2)]))) + + assert _low_events(bus) == [] + + +def test_reserve_stock_db_reports_crossed_products_only_when_confirmed(): + """CAT-FEAT-01, T4: `reserve_stock` devolve os produtos que cruzaram o limite, ou None se rejeitada.""" + db = CatalogDb(":memory:") + crossing = db.create_product("Cruza", 100, 5, 3) + plain = db.create_product("Sem", 100, 5) + + crossed = db.reserve_stock([(crossing["id"], 3), (plain["id"], 5)]) + assert [row["id"] for row in crossed] == [crossing["id"]] + assert crossed[0]["stock"] == 2 + + assert db.reserve_stock([(crossing["id"], 1), (plain["id"], 1)]) is None + assert db.get_product(crossing["id"])["stock"] == 2 + assert db.reserve_stock([(crossing["id"], 1)]) == [] From c57faab6b759e9e4fde163ea2979ed256f7fd38d Mon Sep 17 00:00:00 2001 From: mathcolombo Date: Wed, 11 Nov 2026 15:40:34 -0300 Subject: [PATCH 5/6] feat(catalog): T5 Front: configurar limite e indicar estoque baixo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Demanda: CAT-FEAT-01 Execução: 20261111T183041-cat-feat-01 --- web/public/app.js | 21 +++++++++-- web/public/index.html | 1 + web/public/lib.js | 16 +++++++++ web/public/styles.css | 1 + web/tests/limite.test.js | 78 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 115 insertions(+), 2 deletions(-) create mode 100644 web/tests/limite.test.js diff --git a/web/public/app.js b/web/public/app.js index 2a73393..a274f1f 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -5,9 +5,12 @@ import { nextQuantity, orderStatusClass, parseMoneyToCents, + parseLimit, parseQuantity, + productBody, requestInit, shortId, + stockClass, } from "./lib.js"; const $ = id => document.getElementById(id); @@ -53,13 +56,14 @@ async function loadProducts() { body.replaceChildren(); for (const product of products) { const row = document.createElement("tr"); - row.append(cell(product.name), cell(money(product.price_cents), "num"), cell(product.stock, "num")); + row.append(cell(product.name), cell(money(product.price_cents), "num"), cell(product.stock, `num ${stockClass(product)}`.trim())); const actions = document.createElement("td"); actions.className = "row-actions"; actions.append( button("Adicionar", () => addToCart(product.id)), button("Alterar preço", () => changePrice(product)), button("Estoque", () => changeStock(product)), + button("Limite", () => changeLimit(product)), ); row.append(actions); body.append(row); @@ -151,6 +155,17 @@ async function changeStock(product) { } catch (error) { toast(error.message); } } +async function changeLimit(product) { + const answer = prompt(`Novo limite de estoque baixo de ${product.name} (vazio remove o limite)`, product.low_stock_threshold ?? ""); + if (answer === null) return; + const limit = parseLimit(answer); + if (Number.isNaN(limit)) return toast("Limite inválido. Use um número inteiro ou deixe vazio."); + try { + await api("catalog", `/products/${product.id}`, { method: "PATCH", body: { low_stock_threshold: limit } }); + await loadProducts(); + } catch (error) { toast(error.message); } +} + async function refresh() { await Promise.all([loadProducts(), loadCart(), loadOrders()]).catch(error => toast(error.message)); } @@ -160,11 +175,13 @@ $("product-form").addEventListener("submit", async event => { const form = new FormData(event.target); const priceCents = parseMoneyToCents(form.get("price")); const stock = parseQuantity(form.get("stock")); + const limit = parseLimit(form.get("limit")); if (Number.isNaN(priceCents) || Number.isNaN(stock)) return toast("Informe preço (ex.: 149,90) e estoque inteiro."); + if (Number.isNaN(limit)) return toast("Limite inválido. Use um número inteiro ou deixe vazio."); try { await api("catalog", "/products", { method: "POST", - body: { name: form.get("name"), price_cents: priceCents, stock }, + body: productBody({ name: form.get("name"), priceCents, stock, limit }), }); event.target.reset(); await loadProducts(); diff --git a/web/public/index.html b/web/public/index.html index d85aa7a..8f46738 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -19,6 +19,7 @@

Catálogo

+ diff --git a/web/public/lib.js b/web/public/lib.js index ea45247..693df66 100644 --- a/web/public/lib.js +++ b/web/public/lib.js @@ -19,6 +19,22 @@ export function parseQuantity(text) { return Number.isInteger(value) && value >= 0 ? value : NaN; } +/** Limite de estoque baixo: vazio vira null (sem limite); inteiro >= 0 é válido; o resto é NaN. */ +export function parseLimit(text) { + const raw = String(text ?? "").trim(); + return raw === "" ? null : parseQuantity(raw); +} + +export function productBody({ name, priceCents, stock, limit }) { + const body = { name, price_cents: priceCents, stock }; + if (limit !== null && limit !== undefined) body.low_stock_threshold = limit; + return body; +} + +export function stockClass(product) { + return product.low_stock ? "low-stock" : ""; +} + export function shortId(id) { return String(id).slice(0, 8); } diff --git a/web/public/styles.css b/web/public/styles.css index 670d5c4..12e6937 100644 --- a/web/public/styles.css +++ b/web/public/styles.css @@ -26,5 +26,6 @@ th { color: var(--muted); font-weight: 500; font-size: 13px; } td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } .muted { color: var(--muted); font-size: 13px; } .status-CONFIRMED { color: var(--ok); } .status-PENDING { color: var(--warn); } .status-REJECTED, .status-CANCELLED { color: var(--err); } +.low-stock { color: var(--warn); } #toast { position: fixed; bottom: 16px; left: 16px; right: 16px; max-width: 480px; padding: 10px 14px; border-radius: 6px; background: var(--text); color: var(--bg); display: none; } .row-actions { display: flex; gap: 6px; flex-wrap: wrap; } diff --git a/web/tests/limite.test.js b/web/tests/limite.test.js new file mode 100644 index 0000000..e256582 --- /dev/null +++ b/web/tests/limite.test.js @@ -0,0 +1,78 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; + +import { parseLimit, productBody, stockClass } from "../public/lib.js"; + +const read = name => readFileSync(new URL(`../public/${name}`, import.meta.url), "utf8"); + +// Cenário: Configurar limite pela tela + +test("parseLimit aceita inteiros >= 0 (Configurar limite pela tela)", () => { + assert.equal(parseLimit("5"), 5); + assert.equal(parseLimit("0"), 0); + assert.equal(parseLimit(" 12 "), 12); +}); + +test("parseLimit trata vazio como remoção do limite (Configurar limite pela tela)", () => { + assert.equal(parseLimit(""), null); + assert.equal(parseLimit(" "), null); + assert.equal(parseLimit(null), null); + assert.equal(parseLimit(undefined), null); +}); + +test("parseLimit rejeita negativo e não inteiro (Configurar limite pela tela)", () => { + for (const invalid of ["-1", "2.5", "2,5", "abc", "1e", "--3"]) { + assert.ok(Number.isNaN(parseLimit(invalid)), `deveria rejeitar ${invalid}`); + } +}); + +test("productBody inclui low_stock_threshold quando há limite, inclusive 0 (Configurar limite pela tela)", () => { + assert.deepEqual( + productBody({ name: "Teclado", priceCents: 15000, stock: 10, limit: 3 }), + { name: "Teclado", price_cents: 15000, stock: 10, low_stock_threshold: 3 }, + ); + assert.equal(productBody({ name: "Mouse", priceCents: 100, stock: 1, limit: 0 }).low_stock_threshold, 0); +}); + +test("productBody omite o limite quando vazio (Configurar limite pela tela)", () => { + const body = productBody({ name: "Mouse", priceCents: 9990, stock: 4, limit: null }); + assert.deepEqual(body, { name: "Mouse", price_cents: 9990, stock: 4 }); + assert.ok(!("low_stock_threshold" in body)); + assert.ok(!("low_stock_threshold" in productBody({ name: "x", priceCents: 1, stock: 1 }))); +}); + +test("formulário tem campo opcional Limite com a mesma classe do estoque (Configurar limite pela tela)", () => { + const html = read("index.html"); + const stock = html.match(/]*name="stock"[^>]*>/)?.[0]; + const limit = html.match(/]*name="limit"[^>]*>/)?.[0]; + assert.ok(limit, "campo limit ausente"); + assert.match(limit, /placeholder="Limite"/); + assert.doesNotMatch(limit, /\brequired\b/); + assert.match(stock, /class="qty"/); + assert.match(limit, /class="qty"/); +}); + +test("app.js oferece botão Limite que remove com vazio e avisa em português se inválido (Configurar limite pela tela)", () => { + const app = read("app.js"); + assert.match(app, /button\("Limite"/); + assert.match(app, /Limite inválido/); + assert.match(app, /low_stock_threshold/); +}); + +// Cenário: Indicação visual na lista + +test("stockClass marca produto com estoque baixo (Indicação visual na lista)", () => { + assert.equal(stockClass({ stock: 2, low_stock_threshold: 3, low_stock: true }), "low-stock"); +}); + +test("stockClass não marca produto normal ou sem low_stock (Indicação visual na lista)", () => { + assert.equal(stockClass({ stock: 3, low_stock_threshold: 3, low_stock: false }), ""); + assert.equal(stockClass({ stock: 0, low_stock_threshold: null, low_stock: false }), ""); + assert.equal(stockClass({ stock: 5 }), ""); +}); + +test("a classe de estoque baixo usa a cor --warn (Indicação visual na lista)", () => { + const css = read("styles.css"); + assert.match(css, /\.low-stock\s*\{[^}]*color:\s*var\(--warn\)/); +}); From 696cda14ef2872573a3cfb7c12c81e4063d433f6 Mon Sep 17 00:00:00 2001 From: mathcolombo Date: Wed, 11 Nov 2026 15:41:39 -0300 Subject: [PATCH 6/6] feat(catalog): T6 Front: toast de estoque baixo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Demanda: CAT-FEAT-01 Execução: 20261111T183041-cat-feat-01 --- web/public/app.js | 28 +++++++++ web/public/index.html | 1 + web/public/lib.js | 14 +++++ web/public/styles.css | 3 + web/tests/toast.test.js | 122 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 168 insertions(+) create mode 100644 web/tests/toast.test.js diff --git a/web/public/app.js b/web/public/app.js index a274f1f..c585715 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -1,7 +1,11 @@ import { CART_OPEN, + MAX_TOASTS, + TOAST_MS, errorMessage, formatMoney as money, + lowStockMessage, + newlyLowStock, nextQuantity, orderStatusClass, parseMoneyToCents, @@ -28,6 +32,28 @@ function toast(message) { toast.timer = setTimeout(() => (el.style.display = "none"), 4000); } +function lowStockToast(message) { + const box = $("low-stock-toasts"); + const el = document.createElement("div"); + el.className = "low-toast"; + el.setAttribute("role", "status"); + el.setAttribute("aria-live", "polite"); + const text = document.createElement("span"); + text.textContent = message; + const close = document.createElement("button"); + close.className = "ghost"; + close.textContent = "×"; + close.setAttribute("aria-label", "Fechar"); + const remove = () => { clearTimeout(el.timer); el.remove(); }; + close.addEventListener("click", remove); + el.append(text, close); + el.timer = setTimeout(remove, TOAST_MS); + box.append(el); + while (box.children.length > MAX_TOASTS) box.firstElementChild.querySelector("button").click(); +} + +let previousProducts = null; + async function api(service, path, { method = "GET", body } = {}) { const response = await fetch(`/api/${service}${path}`, requestInit(method, body)); const data = await response.json().catch(() => null); @@ -52,6 +78,8 @@ function button(label, onClick, ghost = true) { async function loadProducts() { const products = await api("catalog", "/products"); + for (const product of newlyLowStock(previousProducts, products)) lowStockToast(lowStockMessage(product)); + previousProducts = products; const body = $("products"); body.replaceChildren(); for (const product of products) { diff --git a/web/public/index.html b/web/public/index.html index 8f46738..e6304e5 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -52,6 +52,7 @@

Pedidos

+
diff --git a/web/public/lib.js b/web/public/lib.js index 693df66..1a7aa9a 100644 --- a/web/public/lib.js +++ b/web/public/lib.js @@ -35,6 +35,20 @@ export function stockClass(product) { return product.low_stock ? "low-stock" : ""; } +/** Produtos que passaram a ficar com estoque baixo entre duas cargas; a primeira carga (previous nulo) não gera nada. */ +export function newlyLowStock(previous, current) { + if (!Array.isArray(previous)) return []; + const wasLow = new Map(previous.map(p => [p.id, Boolean(p.low_stock)])); + return current.filter(p => p.low_stock && wasLow.get(p.id) === false); +} + +export function lowStockMessage(product) { + return `Estoque baixo: ${product.name} — ${product.stock} un. (limite ${product.low_stock_threshold})`; +} + +export const MAX_TOASTS = 3; +export const TOAST_MS = 5000; + export function shortId(id) { return String(id).slice(0, 8); } diff --git a/web/public/styles.css b/web/public/styles.css index 12e6937..0de3d80 100644 --- a/web/public/styles.css +++ b/web/public/styles.css @@ -28,4 +28,7 @@ td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; } .status-CONFIRMED { color: var(--ok); } .status-PENDING { color: var(--warn); } .status-REJECTED, .status-CANCELLED { color: var(--err); } .low-stock { color: var(--warn); } #toast { position: fixed; bottom: 16px; left: 16px; right: 16px; max-width: 480px; padding: 10px 14px; border-radius: 6px; background: var(--text); color: var(--bg); display: none; } +#low-stock-toasts { position: fixed; top: 16px; right: 16px; width: 360px; max-width: calc(100vw - 32px); display: flex; flex-direction: column; gap: 8px; } +.low-toast { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; padding: 10px 14px; border-radius: 6px; background: var(--warn); color: var(--bg); } +.low-toast button { padding: 0 6px; border-color: currentColor; color: inherit; line-height: 1.4; } .row-actions { display: flex; gap: 6px; flex-wrap: wrap; } diff --git a/web/tests/toast.test.js b/web/tests/toast.test.js new file mode 100644 index 0000000..8c6c74d --- /dev/null +++ b/web/tests/toast.test.js @@ -0,0 +1,122 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { test } from "node:test"; + +import { MAX_TOASTS, TOAST_MS, lowStockMessage, newlyLowStock } from "../public/lib.js"; + +const read = name => readFileSync(new URL(`../public/${name}`, import.meta.url), "utf8"); + +const p = (id, stock, threshold, low) => ({ + id, name: `Produto ${id}`, stock, low_stock_threshold: threshold, low_stock: low, +}); + +// Cenário: Toast quando produto passa a ficar baixo + +test("newlyLowStock devolve produto que passou de normal para baixo (Toast quando produto passa a ficar baixo)", () => { + const previous = [p("a", 5, 3, false), p("b", 9, null, false)]; + const current = [p("a", 2, 3, true), p("b", 9, null, false)]; + const result = newlyLowStock(previous, current); + assert.deepEqual(result.map(x => x.id), ["a"]); +}); + +test("newlyLowStock detecta limite alterado que coloca produto em baixo (Toast quando produto passa a ficar baixo)", () => { + const result = newlyLowStock([p("a", 5, null, false)], [p("a", 5, 10, true)]); + assert.equal(result.length, 1); + assert.equal(result[0].low_stock_threshold, 10); +}); + +test("newlyLowStock não repete enquanto continua baixo e reavisa após voltar ao normal (Toast quando produto passa a ficar baixo)", () => { + const low = [p("a", 1, 3, true)]; + assert.deepEqual(newlyLowStock(low, [p("a", 0, 3, true)]), []); + const normal = [p("a", 10, 3, false)]; + assert.deepEqual(newlyLowStock(low, normal), []); + assert.equal(newlyLowStock(normal, low).length, 1); +}); + +test("newlyLowStock ignora produto que não existia antes (Toast quando produto passa a ficar baixo)", () => { + assert.deepEqual(newlyLowStock([p("a", 5, 3, false)], [p("a", 5, 3, false), p("n", 1, 3, true)]), []); +}); + +test("lowStockMessage segue o texto da interface (Toast quando produto passa a ficar baixo)", () => { + assert.equal( + lowStockMessage(p("x", 2, 5, true)), + "Estoque baixo: Produto x — 2 un. (limite 5)", + ); +}); + +test("toast é montado com createElement/textContent, role, aria-live e botão × (Toast quando produto passa a ficar baixo)", () => { + const app = read("app.js"); + const fn = app.match(/function lowStockToast[\s\S]*?\n}\n/)?.[0]; + assert.ok(fn, "função lowStockToast ausente"); + assert.match(fn, /createElement\("div"\)/); + assert.match(fn, /setAttribute\("role", "status"\)/); + assert.match(fn, /setAttribute\("aria-live", "polite"\)/); + assert.match(fn, /textContent = message/); + assert.match(fn, /textContent = "×"/); + assert.match(fn, /setTimeout\(remove, TOAST_MS\)/); + assert.doesNotMatch(fn, /innerHTML/); +}); + +test("TOAST_MS é 5 segundos (Toast quando produto passa a ficar baixo)", () => { + assert.equal(TOAST_MS, 5000); +}); + +test("toast fica no canto superior direito com --warn (Toast quando produto passa a ficar baixo)", () => { + const css = read("styles.css"); + const box = css.match(/#low-stock-toasts\s*\{([^}]*)\}/)?.[1]; + assert.ok(box, "container ausente no CSS"); + assert.match(box, /position:\s*fixed/); + assert.match(box, /top:\s*16px/); + assert.match(box, /right:\s*16px/); + assert.match(css, /\.low-toast\s*\{[^}]*var\(--warn\)/); + assert.match(read("index.html"), /id="low-stock-toasts"/); +}); + +test("toast é disparado na carga de produtos, usada após alterar estoque/limite e no polling (Toast quando produto passa a ficar baixo)", () => { + const app = read("app.js"); + const load = app.match(/async function loadProducts[\s\S]*?previousProducts = products;/)?.[0]; + assert.ok(load, "loadProducts não compara cargas"); + assert.match(load, /newlyLowStock\(previousProducts, products\)/); + assert.match(load, /lowStockToast\(lowStockMessage\(product\)\)/); + assert.match(app, /setInterval\([^\n]*loadProducts\(\)/); + // estoque e limite recarregam a lista após o PATCH + assert.ok((app.match(/await loadProducts\(\)/g) ?? []).length >= 3); +}); + +// Cenário: Produto já baixo ao abrir a página não gera toast + +test("primeira carga (previous nulo) não gera toast mesmo com produtos baixos (Produto já baixo ao abrir a página não gera toast)", () => { + assert.deepEqual(newlyLowStock(null, [p("a", 1, 3, true)]), []); + assert.deepEqual(newlyLowStock(undefined, [p("a", 1, 3, true)]), []); +}); + +test("recarga sem mudança de situação não gera toast (Produto já baixo ao abrir a página não gera toast)", () => { + const list = [p("a", 1, 3, true), p("b", 8, 3, false)]; + assert.deepEqual(newlyLowStock(list, list.map(x => ({ ...x }))), []); +}); + +test("primeira carga vazia ainda conta como carga: baixo depois dela gera toast (Produto já baixo ao abrir a página não gera toast)", () => { + assert.deepEqual(newlyLowStock([], [p("a", 1, 3, true)]), []); +}); + +// Cenário: Limite de toasts visíveis + +test("MAX_TOASTS é 3 (Limite de toasts visíveis)", () => { + assert.equal(MAX_TOASTS, 3); +}); + +test("quarto toast remove o mais antigo e empilha em ordem de chegada (Limite de toasts visíveis)", () => { + const app = read("app.js"); + const fn = app.match(/function lowStockToast[\s\S]*?\n}\n/)[0]; + assert.match(fn, /box\.append\(el\)/); + assert.match(fn, /while \(box\.children\.length > MAX_TOASTS\)/); + assert.match(fn, /box\.firstElementChild/); + const css = read("styles.css"); + assert.match(css.match(/#low-stock-toasts\s*\{([^}]*)\}/)[1], /flex-direction:\s*column(?!-reverse)/); +}); + +test("quatro produtos passando a baixo de uma vez são todos detectados (Limite de toasts visíveis)", () => { + const prev = ["a", "b", "c", "d"].map(id => p(id, 5, 3, false)); + const cur = ["a", "b", "c", "d"].map(id => p(id, 1, 3, true)); + assert.deepEqual(newlyLowStock(prev, cur).map(x => x.id), ["a", "b", "c", "d"]); +});