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
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
_pycache_/
*.pyc
.env
.venv/
pgdata/
.mypy_cache/
.pytest_cache/
13 changes: 13 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Define como se construye la imagen de la aplicación
FROM python:3.11-slim

WORKDIR /app
# Copia el archivo de requerimientos y lo instala
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copia el resto de los archivos de la aplicación
COPY . .

# Expone el puerto 8000
EXPOSE 8000
138 changes: 49 additions & 89 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,112 +1,72 @@
# Backend Project Plan — Jesus (Beginner Track)
# Setup — Reviewass

**Project:** "TicketBox" — Event Ticketing & Checkout API
---
Reproducir el entorno con Docker (Python 3.11 en la imagen; no uses el Python del host).

## 1. Objective
## Requisitos

Build a REST API for a small event-ticketing platform where users can browse events, reserve seats, and "pay" for tickets through a fake payment gateway. The goal is to demonstrate solid fundamentals: clean project structure, correct HTTP semantics, relational data modeling, basic caching, and testable business logic.
- Docker + Docker Compose
- Una API key de TMDB (gratuita): https://www.themoviedb.org/settings/api

---
## Config

## 2. Guard Rails (Non-Negotiable Constraints)
Crea `.env` en la raíz del repo:

1. **Pick exactly ONE framework** and stick with it for the entire project:
- Python → FastAPI (or Django REST Framework)
- Node.js → NestJS
- Go → Gin
2. **Database:** PostgreSQL only. No SQLite, no MongoDB, no "temporary" alternatives.
3. **Cache:** Redis only, and it must be used for at least the use cases listed in §6.
5. All infrastructure must run locally via **docker-compose** (app + Postgres + Redis).
6. **Migrations are mandatory** (Alembic / TypeORM migrations / golang-migrate). No `CREATE TABLE` by hand in psql.
```env
DATABASE_URL=postgresql://reviewass:reviewass@db:5432/reviewass
REDIS_URL=redis://redis:6379/0
SECRET_KEY=IMEKTKQ94CqBWqWgOue00JRn
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30
TMDB_API_KEY=tu-api-key-de-tmdb
TMDB_BASE_URL=https://api.themoviedb.org/3
```

---
## Arranque

## 3. Functional Requirements
Primera vez (o si cambias `Dockerfile` / `requirements.txt`):

### FR-1: Users
- Register (email + password, hashed with bcrypt/argon2).
- Login returning a JWT (access token only is fine at this level).
- Get own profile (`GET /me`) — authenticated.
```bash
docker compose up --build
```

### FR-2: Events
- CRUD for events (create/update/delete restricted to an `admin` role; seed one admin user).
- Event fields: name, description, venue, starts_at, total_capacity, price_cents, currency, status (`draft`, `published`, `cancelled`).
- Public listing endpoint with pagination (`GET /events?page=&limit=`) and filtering by date range and status.
Día a día (la imagen ya existe):

### FR-3: Ticket Reservation
- Authenticated user reserves N tickets for an event (`POST /events/{id}/reservations`).
- A reservation holds tickets for **10 minutes**. If not paid within that window, the tickets return to the available pool.
- The system must never oversell: capacity checks must be race-safe (use a DB transaction with row locking — `SELECT ... FOR UPDATE` — and be prepared to explain why).
```bash
docker compose up
# o en segundo plano:
docker compose up -d
```

### FR-4: Fake Payment Gateway
You will build a **separate mock payment module/service** inside the same codebase (a `payments` module with its own routes, simulating an external provider):
- `POST /mock-gateway/charges` accepts `{ amount_cents, currency, card_number, reservation_ref }`.
- Behavior rules (deterministic, so it can be tested):
- Card ending in `0000` → always **declined**.
- Card ending in `9999` → responds after a 5-second delay (simulates timeout handling).
- Any other card → **approved**, returns a fake `charge_id`.
- The main API consumes this gateway over HTTP (yes, HTTP call to itself/localhost — the point is to practice integrating an external provider: timeouts, error mapping, retries **are not** required at this level, but a timeout on the HTTP client is).
- API: http://localhost:8000
- Health: http://localhost:8000/health
- Docs: http://localhost:8000/docs

### FR-5: Checkout
- `POST /reservations/{id}/pay` with card details → calls the mock gateway → on success, reservation becomes a confirmed `order` with generated ticket codes (UUIDs).
- On decline, reservation stays active until it expires.
- `GET /orders` and `GET /orders/{id}` for the authenticated user.
Servicios: app (`8000`), Postgres (`5432`), Redis (`6379`).

---
## Estado

## 4. Non-Functional Requirements
```bash
docker compose ps
curl http://localhost:8000/health
```

- **NFR-1:** All list endpoints paginated; default limit 20, max 100.
- **NFR-2:** Consistent JSON error format: `{ "error": { "code": "...", "message": "..." } }`.
- **NFR-3:** Correct HTTP status codes (201 on create, 409 on capacity conflict, 402 on payment declined, etc.).
- **NFR-4:** Minimum 10 automated tests, covering at least: registration/login, overselling prevention, payment decline path, reservation expiry.
- **NFR-5:** A `README.md` with setup instructions that work from a clean machine (`docker-compose up` + one migration command).
- **NFR-6:** Structured logging (JSON logs or at least consistent log lines) for every payment attempt.
## Migraciones

---
Con los contenedores arriba, una vez que definas tus propios modelos en `app/models/`:

## 5. Data Model (Minimum Entities)
```bash
docker compose exec app alembic -c app/alembic.ini revision --autogenerate -m "mensaje"
docker compose exec app alembic -c app/alembic.ini upgrade head
```

You must deliver an **ERD diagram** and, if using classes, a **class diagram** (Mermaid or draw.io, committed to the repo under `/docs`).
## Parar

Required entities (you may add fields, not remove):
```bash
docker compose down
```

- `users` (id, email unique, password_hash, role, created_at)
- `events` (id, name, description, venue, starts_at, total_capacity, price_cents, currency, status, created_at)
- `reservations` (id, user_id, event_id, quantity, status [`pending`, `expired`, `paid`], expires_at, created_at)
- `orders` (id, reservation_id, user_id, amount_cents, currency, gateway_charge_id, created_at)
- `tickets` (id, order_id, event_id, code UUID, created_at)
Conserva los datos de Postgres. Para borrarlos también: `docker compose down -v`.

Referential integrity enforced with real foreign keys. Explain your indexing choices for at least 2 indexes beyond primary keys.

---

## 6. Redis — Required Uses

1. **Event listing cache:** cache the published-events list for 60 seconds; invalidate on event create/update/delete. Be ready to explain cache invalidation choice.
2. **Reservation expiry:** either (a) a Redis key with TTL + a background sweep, or (b) a scheduled job checking `expires_at`. Justify your choice in the README.
3. **Login rate limiting:** max 5 failed logins per email per 15 minutes, tracked in Redis.

---

## 7. Deliverables Checklist

- [ ] Git repository with meaningful commit history (no single "final commit").
- [ ] `docker-compose.yml` (app, Postgres, Redis).
- [ ] Migrations folder.
- [ ] `/docs/erd.md` (ERD diagram) and `/docs/architecture.md` (module layout + request flow for the checkout: reservation → gateway → order, as a sequence diagram).
- [ ] OpenAPI/Swagger available at `/docs` endpoint (FastAPI/NestJS give this nearly free; Gin: use swaggo).
- [ ] Test suite runnable with a single command.
- [ ] Postman/Insomnia collection or `.http` file to exercise the full happy path.
- [ ] README: setup, design decisions, known limitations.

### Rubric (100 pts)
- Correctness of requirements — 30
- Data modeling & migrations — 15
- Concurrency safety (no overselling) — 15
- Code organization & readability — 15
- Tests — 10
- Redis usage & justification — 10
- Docs & diagrams — 5
## Qué construir

Ver `/docs/README.md` para el plan completo (usuarios/auth, búsqueda de películas vía TMDB, reviews y ratings).
Empty file added app/__init__.py
Empty file.
116 changes: 116 additions & 0 deletions app/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = app/migrations

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to migrations/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = postgresql://ticketbox:ticketbox@db:5432/ticketbox


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
17 changes: 17 additions & 0 deletions app/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from pydantic_settings import BaseSettings

# Configuración de la aplicación
class Settings(BaseSettings):
DATABASE_URL: str
REDIS_URL: str
SECRET_KEY: str
ALGORITHM: str = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
TMDB_API_KEY: str
TMDB_BASE_URL: str = "https://api.themoviedb.org/3"

class Config:
env_file = ".env"

# Instancia de la configuración
settings = Settings()
29 changes: 29 additions & 0 deletions app/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Este import permite crear un motor de base de datos para interactuar con la base de datos
from sqlalchemy import create_engine

# Este import permite crear una sesión de base de datos para interactuar con la base de datos
from sqlalchemy.orm import sessionmaker, DeclarativeBase

# Este import permite obtener la configuración de la base de datos
from app.config import settings

# Este import permite crear un motor de base de datos para interactuar con la base de datos
engine = create_engine(settings.DATABASE_URL)

# Este import permite crear una sesión de base de datos para interactuar con la base de datos
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Esta clase permite crear una base de datos para interactuar con la base de datos
class Base(DeclarativeBase):
pass

# Esta función permite obtener una sesión de base de datos para interactuar con la base de datos
def get_db():
db = SessionLocal()
try:
# Yield entrega algo temporal abre sesion y se usa
yield db
finally:
db.close()


11 changes: 11 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from fastapi import FastAPI

app = FastAPI(title="Reviewass API", version="0.1.0")

@app.get("/health")
def health_check():
return {"status": "ok"}

@app.get("/")
def read_root():
return health_check()
1 change: 1 addition & 0 deletions app/migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
Loading