Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions code-smells-project/.claude/skills/refactor-arch/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
name: refactor-arch
description: Refactor the architecture of the project MVC to improve performance, maintainability, and scalability independently of stack technology.
---

# Refactor Architecture

summary: Refactor the architecture of the project to improve performance, maintainability, and scalability independently of stack technology.
general: Save all output reports in the `/docs` folder of the project.

## Phase 1: Detect tecnology stack and architecture
- Detect the technology stack used in the project (e.g., programming languages, frameworks, libraries, databases, etc.).

### Input
- Project source code and configuration files.

### Output (Sample)
- [project_analises_tpl](./templates/project_analysis.txt)


## Phase 2: Detect code smells and architecture issues antipatterns
- Detect code smells and architecture issues antipatterns in the project.
- Order findings by severity level (Critical, High, Medium, Low) based on the [issues_severity_ref](./references/issues_severity.md).
- Identify minimal of 5 code smells and architecture issues antipatterns in the project.
- Detect deprecated APIs if aplicable.

### Input
- Project source code and configuration files.
- [issues_severity_ref](./references/issues_severity.md)

### Output (Sample)
- [project_issues_tpl_report](./templates/project_issues.txt)

- Present the findings in a structured format, including the severity level, description, and location of each issue.
- Ask the user to confirm to proceed to phase 3 (Refactor the architecture) or to stop the process.

## Phase 3: Refactor the architecture
- Refactor the project fixing the detected code smells and architecture issues antipatterns.
- Refactor the project to adopt **MVC (Model-View-Controller)** architecture pattern, ensuring a clear separation of concerns between the Model, View, and Controller components.
- Validate the refactored code to ensure that project functionallity is preserved and that the project still run.
- Update the `README.md` and `AGENTS.md` files to reflect the new architecture and any changes made during the refactoring process.

### Output (Sample of the refactored code report)
- [project_refactored_tpl_report](./templates/project_refactored.txt)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Severity Levels for Code Issues

- **CRITICAL**: Falhas graves de arquitetura ou segurança que impedem o funcionamento correto, expõem dados sensíveis (ex: credenciais hardcoded, SQL Injection) ou violam completamente a separação de responsabilidades (ex: "God Class" contendo banco de dados, lógicas complexas e roteamento no mesmo arquivo).
- **HIGH**: Fortes violações do padrão MVC ou princípios SOLID que dificultam muito a manutenção e testes (ex: lógicas de negócio pesadas presas dentro de Controllers, forte acoplamento sem Injeção de Dependência, ou uso de estado global mutável em toda a aplicação).
- **MEDIUM**: Problemas de padronização, duplicação de código ou gargalos de performance moderada (ex: Queries N+1 no banco de dados, uso inadequado de middlewares, validações ausentes nas rotas).
- **LOW**: Melhorias de legibilidade, nomenclatura de variáveis ruins, ou "magic numbers" soltos pelo código.
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
================================
PHASE 1: PROJECT ANALYSIS
================================
Language: Python
Framework: Flask 3.1.1
Dependencies: flask-cors
Domain: E-commerce API (produtos, pedidos, usuários)
Architecture: Monolítica — tudo em 4 arquivos, sem separação de camadas
Source files: 4 files analyzed
DB tables: produtos, usuarios, pedidos, itens_pedido
================================================
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
================================
PHASE 2: CODE SMELLS DETECTION
================================
Code Smells Detected:
- Long Method: 2 instances
- Large Class: 1 instance
- Duplicated Code: 3 instances
- God Object: 1 instance
- Feature Envy: 2 instances
- Shotgun Surgery: 1 instance

Architecture Issues Detected:
- Tight Coupling between modules
- Lack of Separation of Concerns
- Inconsistent Naming Conventions
- Poor Error Handling and Logging
================================================
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
[... refatoração executada ...]

================================
PHASE 3: REFACTORING COMPLETE
================================
New Project Structure:
src/
├── config/settings.py
├── models/
│ ├── produto_model.py
│ └── usuario_model.py
├── views/
│ └── routes.py
├── controllers/
│ ├── produto_controller.py
│ └── pedido_controller.py
├── middlewares/error_handler.py
└── app.py (composition root)

Validation
✓ Application boots without errors
✓ All endpoints respond correctly
✓ Zero anti-patterns remaining
================================
1 change: 1 addition & 0 deletions code-smells-project/.cursor
196 changes: 196 additions & 0 deletions code-smells-project/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
# AGENTS.md — code-smells-project

Instructions for AI coding agents working in this repository.

This project is a Flask e-commerce API used for the `refactor-arch` challenge. It has been **refactored to MVC** with a service layer. Prefer extending the layered design over reintroducing god modules or string-built SQL.

Authoritative style/security reference: [`python-development-guidelines.md`](./python-development-guidelines.md).
Human runbook: [`README.md`](./README.md).
Skill reports: [`docs/`](./docs/).

---

## 1. Mission

| Goal | Detail |
|------|--------|
| Domain | E-commerce API: produtos, usuários, pedidos, relatório de vendas |
| Architecture | MVC + services (`src/`) |
| Success | Parameterized SQL, no secrets in responses, hashed passwords, testable services |

Preserve API paths and JSON field names unless the task explicitly changes the contract.

---

## 2. Stack

| Layer | Choice | Notes |
|-------|--------|-------|
| Language | Python 3.12+ | |
| Web | Flask `3.1.1` | App factory in `src/app.py` |
| CORS | flask-cors `5.0.1` | |
| DB | SQLite (`loja.db`) | Per-request connection via Flask `g` |
| Persistence | `sqlite3` + parameterized SQL | No ORM |
| Passwords | `werkzeug.security` | Hashed at rest |
| Tests | pytest | `tests/unit`, `tests/integration` |

```text
flask==3.1.1
flask-cors==5.0.1
```

Dev tools: `requirements-dev.txt` (`pytest`, `ruff`).

---

## 3. How to run

```bash
cd code-smells-project
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
python app.py
```

Prefer `.venv` (uv default). If you see `VIRTUAL_ENV=venv does not match ... .venv`, deactivate the old env and activate `.venv`, or run via `uv run`.

- Default bind: `http://127.0.0.1:5003`
- Override with `HOST`, `PORT`, `SECRET_KEY`, `FLASK_DEBUG`, `DB_PATH`, `AMBIENTE`, `ADMIN_TOKEN`

```bash
pip install -r requirements-dev.txt
pytest -q
```

Do not commit `.venv/`, `venv/`, `__pycache__/`, or local DB changes unless asked.

---

## 4. Repository map

```text
code-smells-project/
├── app.py # Entrypoint
├── src/
│ ├── app.py # create_app composition root
│ ├── config/settings.py
│ ├── db/database.py # schema, seed, request-scoped connection
│ ├── models/ # Model / persistence
│ ├── services/ # Business rules
│ ├── controllers/ # HTTP adapters
│ ├── views/routes.py # Route registration
│ └── middlewares/ # Error handlers
├── tests/
├── docs/ # refactor-arch phase reports
├── requirements.txt
├── requirements-dev.txt
├── pyproject.toml
├── README.md
├── AGENTS.md
└── python-development-guidelines.md
```

---

## 5. Architecture

```text
View (routes)
→ Controller (HTTP)
→ Service (domain rules)
→ Model (parameterized SQL)
→ get_db() per request
→ loja.db
```

| Package | Role |
|---------|------|
| `src/views` | URLs → controller callables |
| `src/controllers` | Parse request, status codes, JSON envelope |
| `src/services` | Validation, stock, totals, auth, discounts, notifications |
| `src/models` | Repositories + row mappers (no password in public mappers) |
| `src/db` | Connection lifecycle, DDL, seed, password migration |
| `src/config` | Env-based settings |

---

## 6. Data model

Unchanged tables: `produtos`, `usuarios`, `pedidos`, `itens_pedido`.

- Categorias: `informatica`, `moveis`, `vestuario`, `geral`, `eletronicos`, `livros`
- Status pedido: `pendente`, `aprovado`, `enviado`, `entregue`, `cancelado`
- Seed users (plaintext only for login; stored hashed):

| Email | Password | Tipo |
|-------|----------|------|
| `admin@loja.com` | `admin123` | `admin` |
| `joao@email.com` | `123456` | `cliente` |
| `maria@email.com` | `senha123` | `cliente` |

Foreign keys enabled (`PRAGMA foreign_keys = ON`).

---

## 7. HTTP API surface

Base URL: `http://127.0.0.1:5003`

Public paths unchanged: `/`, `/health`, `/produtos`, `/usuarios`, `/login`, `/pedidos`, `/relatorios/vendas`.

| Admin | Behavior |
|-------|----------|
| `POST /admin/query` | **Removed** |
| `POST /admin/reset-db` | Requires `X-Admin-Token: $ADMIN_TOKEN` |

`/health` returns status, counts, versão, ambiente — **never** `secret_key`, passwords, or `db_path`.

---

## 8. Fixed issues (do not reintroduce)

1. SQL concatenation → use `?` placeholders only
2. Arbitrary SQL admin endpoint → removed
3. Secrets in `/health` / hardcoded production secret → env config
4. Plaintext passwords / `senha` in list/get → hashed + omitted from responses
5. God `models.py` / fat controllers → split by domain + services
6. Global `db_connection` → Flask `g` per request
7. N+1 on pedidos → JOIN load of itens
8. `print` logging → `logging` module

---

## 9. Coding standards

Follow [`python-development-guidelines.md`](./python-development-guidelines.md).

- Parameterized SQL only
- Thin controllers; rules in services
- `logging.getLogger(__name__)`; never log passwords
- Secrets from environment
- Add pytest coverage for behavior you change

---

## 10. Working agreements

| Topic | Rule |
|-------|------|
| Language in code | Portuguese identifiers / user-facing messages |
| Commits | Only when the user asks |
| Scope | Change only files required by the task |

### Smoke checks

```bash
curl -s http://127.0.0.1:5003/health
curl -s http://127.0.0.1:5003/produtos
curl -s -X POST http://127.0.0.1:5003/login \
-H 'Content-Type: application/json' \
-d '{"email":"joao@email.com","senha":"123456"}'
```

---

*Aligned with MVC refactor (v2.0.0), Flask 3.1.1, and `python-development-guidelines.md`.*
57 changes: 55 additions & 2 deletions code-smells-project/README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,65 @@
# code-smells-project

API de E-commerce em Python/Flask usada como entrada do desafio `refactor-arch`.
API de E-commerce em Python/Flask refatorada para **MVC** (com camada de serviços) no desafio `refactor-arch`.

## Como rodar

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python app.py
```

A aplicação sobe em `http://localhost:5000`. O banco SQLite (`loja.db`) é criado automaticamente no primeiro boot, já com produtos e usuários de exemplo.
Or with uv (uses `.venv` automatically):

```bash
uv sync
uv run python app.py
```

A aplicação sobe em `http://127.0.0.1:5003` por padrão. O banco SQLite (`loja.db`) é criado/migrado no boot, com produtos e usuários de exemplo.

### Variáveis de ambiente

| Variável | Default | Descrição |
|----------|---------|-----------|
| `SECRET_KEY` | `dev-only-change-me` | Chave Flask (não expor) |
| `FLASK_DEBUG` | `0` | `1` habilita debug |
| `HOST` | `127.0.0.1` | Bind address |
| `PORT` | `5003` | Porta HTTP |
| `DB_PATH` | `loja.db` | Caminho do SQLite |
| `AMBIENTE` | `desenvolvimento` | Label no `/health` |
| `ADMIN_TOKEN` | _(vazio)_ | Token para `POST /admin/reset-db` |

## Arquitetura (MVC)

```text
HTTP → views/routes.py → controllers/ → services/ → models/ → db (SQLite)
```

| Camada | Pacote | Responsabilidade |
|--------|--------|------------------|
| View | `src/views` | Registro de rotas |
| Controller | `src/controllers` | HTTP in/out |
| Service | `src/services` | Regras de negócio |
| Model | `src/models` | SQL parametrizado |
| Config/DB | `src/config`, `src/db` | Settings e conexão por request |

## Testes

```bash
pip install -r requirements-dev.txt
pytest -q
```

## Endpoints

Mesmos paths da API original (`/produtos`, `/usuarios`, `/pedidos`, `/login`, `/relatorios/vendas`, `/health`).

- `POST /admin/query` **removido** (SQL arbitrário).
- `POST /admin/reset-db` exige header `X-Admin-Token` igual a `ADMIN_TOKEN`.

Usuários seed: `joao@email.com` / `123456` (senhas agora hasheadas).

Relatórios da skill: pasta [`docs/`](./docs/).
Loading