diff --git a/.gitignore b/.gitignore index 6e0fe0d..f750fac 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,29 @@ +# Local-only AI assistant / planning / context documents +# (personal workflow, not needed to run the system) +CLAUDE.md +CLAUDE.*.md +AGENTS.md +GEMINI.md +MEMORY.md +CONTEXT.md +CONTEXT.*.md +PLAN.md +PLAN.*.md +NOTES.md +TODO.md +ROADMAP.md +SPEC.md +DESIGN.md +DECISIONS.md +.cursorrules +.cursor/ +.claude/ +graphify-out/ + # Environment / secrets .env *.env.local -# Personal / local-only files -CLAUDE.local.md -.claude/settings.local.json - # Logs *.log diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 8647d2b..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,61 +0,0 @@ -# CLAUDE.md - -> Project context for Claude Code. See [CONTEXT.md](CONTEXT.md) for the full -> product/design context and [PLAN.md](PLAN.md) for the phase plan. - -## Project - -RUTEX Transportes — Spanish-language transport web app: seat booking (reservas) -and parcel shipping (encomiendas). UI copy is Spanish; code/comments/commits are English. -The `output/` folder is ignored entirely — never read or write it. - -## Stack - -- Frontend: React 19 + Vite + TypeScript, Tailwind CSS v4, Framer Motion (`motion`), - TanStack Query v5, React Router v8, React Hook Form + Zod. Package manager: **pnpm only**. -- Backend: Django 5 + DRF + SimpleJWT + drf-spectacular, in `backend/` with venv at `backend/.venv`. -- DB: SQLite by default (`DATABASE_ENGINE=sqlite`), PostgreSQL 16 via `docker compose up -d`. - -## Commands - -```bash -# Frontend (run inside frontend/) -pnpm dev # dev server at :5173 -pnpm build # typecheck + production build -pnpm lint # oxlint -pnpm test # vitest - -# Backend (run inside backend/; use the venv python) -.venv/Scripts/python manage.py runserver # API at :8000 -.venv/Scripts/python manage.py migrate -.venv/Scripts/python manage.py seed_demo # demo cities/routes/trips -.venv/Scripts/python -m pytest # tests (settings: config.settings.test) -.venv/Scripts/python -m pytest --cov=apps # with coverage -``` - -## Architecture - -- `backend/apps/core` — response envelope (`EnvelopeJSONRenderer`), pagination, throttles. - ALL API responses are `{"success", "data", "error"}`; paginated lists are `{"items", "meta"}`. -- `backend/apps/{accounts,catalog,bookings,parcels}` — domain apps. API mounted at `/api/v1/`. -- `frontend/src/` — `components/` (by feature + `ui/` primitives), `pages/`, `hooks/`, - `lib/` (api client), `styles/` (tokens.css = design tokens, source of truth). -- Auth: JWT (30-min access + 7-day refresh, rotation). Custom user `accounts.User` (email login). - -## Rules - -- ES modules, functional components + hooks, no `any` without a justifying comment. -- `camelCase` variables/functions, `PascalCase` components/types, `kebab-case` filenames - (React component files are `PascalCase.tsx`). -- API error messages shown to users are Spanish; error `code`s are stable English slugs. -- Seats invariant: `UNIQUE(trip, seat_number)` + `select_for_update()` — never bypass. -- Run `pnpm build` (frontend) / `python -m pytest` (backend) before calling work done. -- Never commit `.env`, credentials, or API keys. No `git push` unless explicitly asked. -- Commits in English, short imperative (`Add seat map component`). - -## Gotchas - -- Windows dev machine; PowerShell 5.1 (no `&&` chaining). Backend venv python: - `backend/.venv/Scripts/python.exe`. -- Custom user model means `accounts` migration 0001 must always precede others. -- Brand art lives in `Frames/` (source) and `frontend/public/img/` (served copies). diff --git a/CONTEXT.md b/CONTEXT.md deleted file mode 100644 index 862b3d5..0000000 --- a/CONTEXT.md +++ /dev/null @@ -1,177 +0,0 @@ -# CONTEXT — RUTEX Transportes - -> Living context document for the project. Read this before touching code. -> Companion file: [PLAN.md](PLAN.md) (step-by-step implementation plan). - -## 1. What we are building - -A **transport company web app, fully in Spanish (UI)**, for the fictional brand -**RUTEX Transportes** — tagline: **"Conecta tu mundo"**. - -Two core products: - -1. **Reserva de asientos (seat booking)** — search trips between cities, pick a - seat on an interactive seat map, confirm the booking, get a ticket with a code. -2. **Envío de encomiendas (parcel shipping)** — quote a parcel, create a - shipment, and track it publicly with a tracking code and status timeline. - -Plus: **user accounts** (register / login / "Mis viajes" / "Mis envíos") and a -marketing **landing page** with an animated hero. - -## 2. Brand & design direction (from `Frames/`) - -The three PNGs in `Frames/` are the official brand art and MUST drive the visual -language (they are used as hero/section imagery): - -| File | Content | Use | -|---|---|---| -| `Frames/Primer_frame.png` | Front view of RUTEX minibus on a highway, "Conecta tu mundo" on the display | **Hero** background/visual | -| `Frames/Segundo_frame.png` | Rear view of long-distance coach at sunset, floating UI icon cubes (pin, clock, arrows) | Features / booking section | -| `Frames/Tercer_frame.png` | Minibus + floating 3D icon blocks (alerts, clock, location, traffic) | Tracking / parcels section | - -**Extracted design tokens (source of truth for the UI):** - -- **Style direction:** playful low-poly 3D / "toy world" — rounded geometry, - glassy blue surfaces, soft depth, glowing cyan edge-light accents. NOT a - generic corporate template. Light theme is the primary theme (the art is bright). -- **Palette:** - - `--color-primary`: royal blue `#2557D6` (RUTEX logo blue) - - `--color-primary-deep`: `#1B3FA8` - - `--color-accent`: glow cyan `#3EE6F0` (edge lights on the buses) - - `--color-sky`: `#8EC5F2` / gradients toward `#BFE3FF` - - `--color-surface`: near-white `#F7FAFF`; cards white with soft blue shadows - - `--color-nature`: low-poly green `#5FBF6E` (support/illustrative only) - - `--color-sunset`: warm amber `#FFB65C` (sparingly, e.g. parcels accent) -- **Shape language:** large radii (16–24px), pill buttons, floating "cube" icon - chips like the frames, layered cards with depth. -- **Typography:** geometric rounded sans. Pairing: **Sora** (display/headings) - + **Inter** (body). Max 2 families, `font-display: swap`. -- **Motion:** Framer Motion. Hero entrance (bus art slides/parallax in), - scroll-reveal sections, seat-map micro-interactions, animated tracking - timeline. Compositor-friendly properties only (`transform`, `opacity`); - respect `prefers-reduced-motion`. - -**All user-facing copy is Spanish** (es-PE/es-419 neutral). Code, comments, -commits: English. - -## 3. Tech stack (decided) - -| Layer | Choice | Why | -|---|---|---| -| Frontend | **React 19 + Vite + TypeScript** | Modern SPA, fast DX | -| Styling | **Tailwind CSS v4** + CSS custom-property design tokens | Speed + enforceable token system | -| Animation | **Framer Motion (`motion`)** | Declarative, reduced-motion support | -| Server state | **TanStack Query v5** | Caching, retries, no hand-rolled fetching | -| Client state | React context (auth) + component state; **no Redux** | YAGNI | -| Routing | **React Router v7** | Standard | -| Forms | **React Hook Form + Zod** | Validation at the boundary | -| Backend | **Django 5 + Django REST Framework** | Batteries included: ORM, migrations, auth, and free **admin panel** for operating routes/trips. (Spring Boot was the alternative; Django wins on solo-dev speed and built-in admin.) | -| Auth | **djangorestframework-simplejwt** (JWT access+refresh) | Stateless SPA auth | -| API docs | **drf-spectacular** (OpenAPI) | Contract-first frontend work | -| Database | **PostgreSQL 16** (Docker) — SQLite fallback for quick local runs | Relational integrity for seats/bookings | -| Package managers | **pnpm** (frontend — per CLAUDE.md, never npm/yarn), **uv or pip+venv** (backend) | | -| Testing | Backend: **pytest + pytest-django** · Frontend: **Vitest + React Testing Library** · E2E: **Playwright** | 80% coverage target | - -## 4. Repository layout (target) - -``` -Transporte/ -├── CONTEXT.md ← this file -├── PLAN.md ← implementation plan -├── CLAUDE.md -├── Frames/ ← brand art (source assets, copied into frontend/public) -├── output/ ← IGNORED (do not read/write) -├── docker-compose.yml ← postgres (+ optional backend) -├── backend/ -│ ├── manage.py -│ ├── pyproject.toml / requirements.txt -│ ├── config/ ← settings (base/dev/prod), urls, asgi -│ └── apps/ -│ ├── accounts/ ← custom User, auth endpoints -│ ├── catalog/ ← City, Route, Bus, SeatLayout, Trip -│ ├── bookings/ ← Booking, BookingSeat, ticket codes -│ └── parcels/ ← Shipment, TrackingEvent, quotes -└── frontend/ - ├── package.json ← pnpm - ├── vite.config.ts - └── src/ - ├── components/ ← by feature: hero/, booking/, parcels/, auth/, ui/ - ├── pages/ ← route-level components - ├── hooks/ - ├── lib/ ← api client, utils - ├── styles/ ← tokens.css, global.css - └── types/ -``` - -## 5. Domain model (core entities) - -``` -User (email login, nombre, teléfono; roles: cliente / staff) -City (nombre, región) -Route (origin City → destination City, distance, duración, precio base) -Bus (placa, modelo, seat_layout JSON: filas × columnas + pasillo) -Trip (route, bus, fecha, hora salida/llegada, precio, estado) -Booking (user, trip, estado: pendiente|confirmada|cancelada, - código único p.ej. RTX-8F3K2A, total) -BookingSeat (booking, trip, seat_number) ← UNIQUE(trip, seat_number) -Shipment (sender user, destinatario, origin/destination City, peso, - dimensiones, precio, tracking_code p.ej. RTX-ENV-93XK21, - estado: registrado|en_tránsito|en_destino|entregado) -TrackingEvent (shipment, estado, descripción, timestamp, ubicación) -``` - -**Critical invariant:** a seat can never be double-booked → -`UNIQUE(trip, seat_number)` DB constraint **plus** `select_for_update()` inside -a transaction when confirming. The constraint is the last line of defense. - -## 6. API surface (v1, `/api/v1/`) - -| Endpoint | Method | Auth | Purpose | -|---|---|---|---| -| `/auth/register/` | POST | — | Create account | -| `/auth/token/`, `/auth/token/refresh/` | POST | — | JWT login/refresh | -| `/auth/me/` | GET | ✓ | Current user profile | -| `/cities/` | GET | — | Cities for search selects | -| `/trips/?origin=&destination=&date=` | GET | — | Search trips | -| `/trips/{id}/seats/` | GET | — | Seat map + availability | -| `/bookings/` | POST | ✓ | Create booking (seats, passengers) | -| `/bookings/mine/` | GET | ✓ | "Mis viajes" | -| `/bookings/{code}/` | GET | ✓ | Booking detail / ticket | -| `/parcels/quote/` | POST | — | Price quote (no persistence) | -| `/parcels/` | POST | ✓ | Create shipment | -| `/parcels/mine/` | GET | ✓ | "Mis envíos" | -| `/parcels/track/{tracking_code}/` | GET | — | **Public** tracking timeline | - -Consistent response envelope: `{ "success": bool, "data": ..., "error": ... }` -(pagination metadata where applicable). - -## 7. Frontend pages - -| Route | Page (Spanish UI) | -|---|---| -| `/` | Landing: hero animado (Primer_frame), features, rutas populares, CTA | -| `/reservar` | Search → results → **seat map** → passenger data → confirmation | -| `/reservar/confirmacion/:code` | Ticket / boleto with code | -| `/encomiendas` | Quote + create shipment (Tercer_frame visual) | -| `/rastrear/:code?` | Public tracking timeline | -| `/ingresar`, `/registrarse` | Auth | -| `/mi-cuenta` | Profile, "Mis viajes", "Mis envíos" | - -## 8. Conventions & guardrails - -- Follow root `CLAUDE.md` / `CLAUDE.local.md`: pnpm only, ES modules, no `any` - without justification, functional components + hooks, `kebab-case` filenames, - `camelCase`/`PascalCase` identifiers, commits in English imperative. -- Immutability, early returns, files <800 lines, functions <50 lines. -- Validate at boundaries: Zod on the frontend forms, DRF serializers on the API. -- Security: no secrets in code (`.env` + `django-environ`), CORS restricted to - the frontend origin, rate limiting on auth endpoints, parameterized ORM - queries only, DRF throttling. -- Payment is **mocked** (a "Pago simulado" confirm step) — real gateways out of scope. -- `output/` folder is ignored entirely. - -## 9. Out of scope (v1) - -Real payments, email/SMS notifications, multi-language UI (Spanish only), -operator dashboards beyond Django admin, mobile apps, real-time WebSocket seat -locking (poll/refetch on the seat map is enough for v1). diff --git a/PLAN.md b/PLAN.md deleted file mode 100644 index c40dd57..0000000 --- a/PLAN.md +++ /dev/null @@ -1,193 +0,0 @@ -# PLAN — RUTEX Transportes - -**Source context**: [CONTEXT.md](CONTEXT.md) -**Complexity**: Large (full-stack greenfield) -**Stack**: React 19 + Vite + TS + Tailwind v4 + Framer Motion · Django 5 + DRF + PostgreSQL - -Each phase ends with a working, verifiable state. Do not start a phase until -the previous one's validation passes. - ---- - -## Phase 0 — Scaffolding & tooling - -**Goal:** monorepo skeleton, both dev servers boot, DB runs. - -1. Create `docker-compose.yml` with PostgreSQL 16 (volume, healthcheck) — `.env.example` with DB credentials placeholders. -2. Scaffold backend: `backend/` Django 5 project (`config/` settings split base/dev/prod, `django-environ`), apps `accounts`, `catalog`, `bookings`, `parcels`. Install DRF, simplejwt, drf-spectacular, django-cors-headers, pytest-django. -3. Scaffold frontend: `frontend/` via `pnpm create vite` (react-ts). Install tailwindcss v4, motion, @tanstack/react-query, react-router, react-hook-form, zod. Configure ESLint + Prettier + strict tsconfig. -4. Copy `Frames/*.png` → `frontend/public/img/` (optimize to WebP/AVIF with PNG fallback; hero image gets explicit dimensions + `fetchpriority="high"`). -5. Root scripts documented; update `CLAUDE.md` placeholders with the real stack/commands. -6. `.gitignore` (node_modules, venv, .env, output/), `git init` + initial commit. - -**Validate:** `docker compose up -d` healthy · `python manage.py runserver` responds · `pnpm dev` renders starter page · `pnpm lint && pnpm typecheck` pass. - ---- - -## Phase 1 — Backend: auth & users - -**Goal:** JWT auth works end-to-end via HTTP. - -1. **TDD:** tests first for register/login/me (pytest). -2. Custom `User` model (email as username, nombre, teléfono) — must land in the **first** migration of `accounts`. -3. Endpoints: `POST /auth/register/`, `POST /auth/token/`, `POST /auth/token/refresh/`, `GET /auth/me/`. Response envelope + Spanish error messages (`detail` in Spanish, codes stable). -4. Throttling on auth endpoints; password validation; CORS locked to the Vite origin. -5. OpenAPI schema exposed at `/api/schema/` + Swagger UI. - -**Validate:** `pytest` green, coverage ≥80% on `accounts`; manual curl register→login→me. - ---- - -## Phase 2 — Backend: catalog domain (cities, routes, buses, trips) - -**Goal:** searchable trip data with realistic seeds. - -1. **TDD:** model + endpoint tests first. -2. Models: `City`, `Route`, `Bus` (seat layout: rows/cols/aisle JSON), `Trip` (route, bus, datetime, price, estado). Indexes on `(origin, destination)` and trip date. -3. Endpoints: `GET /cities/`, `GET /trips/?origin&destination&date` (paginated, `select_related` to avoid N+1), `GET /trips/{id}/seats/` (layout + taken seat numbers). -4. Django admin registration for all catalog models (operator back-office). -5. Seed command `manage.py seed_demo`: ~10 Peruvian/generic cities, routes, buses (40-seat coach + 20-seat minibus layouts), 2 weeks of trips. - -**Validate:** `pytest` green ≥80%; search returns seeded trips; admin usable. - ---- - -## Phase 3 — Backend: bookings (seat reservation) - -**Goal:** transactional, double-booking-proof reservations. - -1. **TDD first — including a concurrency test** (two parallel bookings for the same seat: exactly one succeeds). -2. Models: `Booking` (user, trip, estado, unique human code `RTX-XXXXXX`, total), `BookingSeat` with **`UNIQUE(trip, seat_number)`** constraint. -3. `POST /bookings/`: validate seats exist in layout & trip is future → `transaction.atomic()` + `select_for_update()` on trip → create booking + seats → return ticket payload. IntegrityError → friendly Spanish "asiento ya ocupado" 409. -4. `GET /bookings/mine/`, `GET /bookings/{code}/` (owner-only). Mock payment = booking created directly as `confirmada`. - -**Validate:** `pytest` green ≥80%; concurrency test passes; 409 on seat collision. - ---- - -## Phase 4 — Backend: parcels (encomiendas) - -**Goal:** quote, create, and publicly track shipments. - -1. **TDD first.** -2. Models: `Shipment` (tracking code `RTX-ENV-XXXXXX`, sender, destinatario, cities, peso/dimensiones, precio, estado), `TrackingEvent` (auto-created "Registrado" on creation). -3. Pricing rule (named constants, no magic numbers): base by route distance + weight tiers. `POST /parcels/quote/` is pure calculation. -4. Endpoints: quote, create (auth), mine (auth), `GET /parcels/track/{code}/` — **public**, throttled, returns timeline; 404 without leaking existence details. -5. Admin action to advance shipment estado (creates TrackingEvent). - -**Validate:** `pytest` green ≥80%; full quote→create→track flow via curl. - ---- - -## Phase 5 — Frontend: foundation & design system - -**Goal:** tokens, layout shell, API plumbing — no pages yet. - -1. `styles/tokens.css`: the CONTEXT.md palette, fluid type scale (`clamp`), spacing, radii, durations/easings as CSS custom properties wired into Tailwind v4 `@theme`. -2. Fonts: Sora (headings) + Inter (body), self-hosted subsets, `font-display: swap`, preload critical weight. -3. `ui/` primitives: `Button` (pill, glow-on-hover), `Input`, `Select`, `SurfaceCard` (floating cube aesthetic), `Badge`, `Spinner`, `EmptyState` — all with designed hover/focus/active states, Spanish labels via props. -4. `lib/api-client.ts`: typed fetch wrapper honoring the response envelope; JWT storage + auto-refresh interceptor; TanStack Query provider. -5. Auth context (`useAuth`) + protected route wrapper; React Router shell: `Navbar` (glassy, logo RUTEX), `Footer`; routes stubbed. -6. `useReducedMotion` hook wired into a shared motion config. - -**Validate:** `pnpm lint && pnpm typecheck && pnpm build` pass; Vitest for api-client + hooks. - ---- - -## Phase 6 — Frontend: landing page (hero + animations) - -**Goal:** the showpiece — brand landing in Spanish. - -1. **Hero**: `Primer_frame` art as full-bleed visual; headline "Conecta tu mundo", sub "Viaja y envía con RUTEX Transportes"; dual CTA («Reservar asiento» / «Enviar encomienda»). Framer Motion entrance: staggered text reveal + subtle parallax/float on the art; sky-gradient background matching the frame. -2. **Search widget** embedded in hero: origin/destination/date → navigates to `/reservar` with query params (URL as state). -3. **Features section**: floating cube-chip cards (echoing the frames' 3D icon cubes) — Reservas, Encomiendas, Rastreo, Puntualidad — scroll-reveal with stagger; `Segundo_frame` as section visual. -4. **Rutas populares**: cards fed by `GET /trips` popular routes; **CTA banner** + footer. -5. Reduced-motion: all reveals collapse to opacity-only or none. -6. SEO: Spanish meta/OG tags, semantic landmarks (`header/main/section[aria-labelledby]`). - -**Validate:** build passes; Lighthouse on `/` ≥90 perf & a11y; screenshots at 320/768/1024/1440; no layout shift from images (explicit dims). - ---- - -## Phase 7 — Frontend: booking flow - -**Goal:** search → seat map → passenger → ticket, fully wired. - -1. `/reservar`: search form (reads URL params) + results list (trip cards: hora, duración, bus, precio) — TanStack Query, loading skeletons, Spanish empty states («No encontramos viajes para esa fecha»). -2. **Seat map component**: renders bus layout from API (grid + aisle), states libre/ocupado/seleccionado with micro-animations (scale+glow on select), legend, keyboard-navigable + ARIA labels («Asiento 12, libre»). Availability refetched on focus/interval. -3. Passenger details form (RHF+Zod, Spanish validation messages) → mock payment confirm step. -4. `POST /bookings/` with optimistic UI care: on 409 «asiento ocupado», refetch seat map and show friendly toast. -5. Confirmation page `/reservar/confirmacion/:code`: animated ticket card (código, QR-style block, detalles), «Descargar / Ver mis viajes». -6. Requires auth: redirect to `/ingresar?next=…` preserving state. - -**Validate:** Vitest on seat-map logic + forms; Playwright happy path (search→seat→book→ticket) against seeded backend. - ---- - -## Phase 8 — Frontend: parcels & tracking - -**Goal:** encomiendas end-to-end + public tracking. - -1. `/encomiendas`: quote form (ciudades, peso, dimensiones) → live price display (animated count-up), then create shipment (auth) → success screen with tracking code + copy button. `Tercer_frame` as section visual. -2. `/rastrear/:code?`: public page — input for code + **animated vertical timeline** of TrackingEvents (estado icons echoing the cube chips; motion-staggered). Friendly Spanish error for unknown codes. -3. Empty/loading/error states designed, not default. - -**Validate:** Vitest for quote form logic; Playwright: quote→create→track. - ---- - -## Phase 9 — Frontend: auth pages & account - -**Goal:** login/register + «Mi cuenta». - -1. `/ingresar` & `/registrarse`: split-layout cards (brand art side), RHF+Zod, Spanish errors, password visibility toggle, redirect handling. -2. `/mi-cuenta`: profile info, tabs «Mis viajes» (booking cards with estado badges) and «Mis envíos» (shipment cards linking to tracking). -3. Navbar reflects session (avatar/menu, «Cerrar sesión»); token refresh handled silently. - -**Validate:** Vitest auth hooks/forms; Playwright register→login→book→see in Mis viajes. - ---- - -## Phase 10 — Hardening, tests to 80%, polish - -1. Coverage sweep both sides to ≥80% (`pytest --cov`, `vitest --coverage`); fill gaps (esp. bookings concurrency + api-client). -2. Full Playwright suite: booking, parcels, tracking, auth (Chrome/Firefox/WebKit). -3. A11y pass: keyboard nav, focus rings, contrast (blue-on-white AA), reduced-motion audit. -4. Performance: bundle check (landing <150 kb gz JS), lazy-load below-fold routes (`React.lazy` per page), image audit. -5. Security review checklist (security-reviewer agent): auth endpoints, input validation, CORS/headers, no leaked secrets. -6. `README.md` (setup, seeds, commands) + final `CLAUDE.md` accuracy pass. - -**Validate:** full suites green; Lighthouse ≥90 across pages; checklist done. - ---- - -## Dependencies between phases - -``` -0 → 1 → 2 → 3 → 4 (backend chain) -0 → 5 → 6 (frontend foundation → landing) -2 → 6 (rutas populares) 3 → 7 4 → 8 1 → 9 -7,8,9 → 10 -``` -Phases 5–6 can start in parallel with 2–4 once Phase 1 is done. - -## Risks - -| Risk | Level | Mitigation | -|---|---|---| -| Seat double-booking under concurrency | HIGH | DB unique constraint + `select_for_update` + dedicated concurrency test (Phase 3.1) | -| Hero art (large PNGs) tanks LCP | MEDIUM | Convert to AVIF/WebP, explicit dims, preload, `fetchpriority=high` | -| Windows dev friction (Docker/Postgres) | MEDIUM | SQLite fallback setting for quick local runs; Postgres for tests-that-matter | -| Scope creep (payments, notifications) | MEDIUM | Explicitly out of scope in CONTEXT.md §9 | -| JWT in localStorage (XSS surface) | LOW/MED | Short-lived access token, refresh rotation; strict CSP in prod config | - -## Estimated effort - -Backend ~10–14 h · Frontend ~14–18 h · Testing/polish ~5–7 h → **~30–40 h** total, split across the 11 phases. - -## Acceptance - -- [ ] All phases validated with their commands -- [ ] UI 100% Spanish, brand-faithful to `Frames/` -- [ ] Booking + parcels + tracking + auth work end-to-end (Playwright green) -- [ ] Coverage ≥80% both sides; no CRITICAL/HIGH review findings diff --git a/README.md b/README.md index e61ebfa..1c1ab95 100644 --- a/README.md +++ b/README.md @@ -1,112 +1,253 @@ -# RUTEX Transportes 🚌 - -Web app de transporte en español: **reserva de asientos** y **envío de encomiendas** -con rastreo público. Proyecto full-stack de demostración. - -## 📌 About this project / Sobre este proyecto - -**EN** — This is a **personal prototype**, built as a portfolio piece for software -development recruiters. It was created **with AI assistance** (Claude Code), driven by -iterative instruction prompts, and complemented with **manual testing** on my side plus -the automated test suites in the repo. It is **not a production system**: some features -are intentionally not implemented — most notably **payments are simulated** (no real -payment gateway), and there are no email/SMS notifications. The goal is to showcase -full-stack architecture, testing discipline, and AI-assisted development workflow. - -**ES** — Este es un **prototipo personal**, creado como pieza de portafolio para -reclutadores de posiciones de desarrollo de software. Fue construido **con asistencia de -IA** (Claude Code), guiado por prompts de instrucciones iterativos, y complementado con -**pruebas manuales** de mi parte además de las suites automatizadas del repo. **No es un -sistema de producción**: algunas funcionalidades no están implementadas a propósito — en -particular **los pagos son simulados** (sin pasarela real) y no hay notificaciones por -correo/SMS. El objetivo es mostrar arquitectura full-stack, disciplina de testing y un -flujo de desarrollo asistido por IA. +
+ +# 🚌 RUTEX Transportes + +**Reserva de asientos y envíos de encomiendas con rastreo público** + +Aplicación web full-stack en español, construida como pieza de portafolio. + +[![CI](https://github.com/Alex350-coder/TransportApp/actions/workflows/ci.yml/badge.svg)](https://github.com/Alex350-coder/TransportApp/actions/workflows/ci.yml) +[![Licencia](https://img.shields.io/badge/licencia-MIT-2ea44f.svg)](LICENSE) +![React](https://img.shields.io/badge/React-19-61dafb.svg) +![Django](https://img.shields.io/badge/Django-5.2-092e20.svg) +![TypeScript](https://img.shields.io/badge/TypeScript-6-3178c6.svg) + +
+ +--- + +## Vista previa + +
+ Landing page de RUTEX Transportes con hero animado + Landing: hero con animación de buses, rutas populares y acceso a los dos flujos de negocio. +
+ +## Capturas de pantalla + + + + + + + + + + + + + + + + + + + + + + + + + + +
Resultados de búsqueda de viajes por origen, destino y fechaMapa de asientos interactivo con selección
1 · Búsqueda de viajes con disponibilidad en tiempo real2 · Plano de asientos con selección múltiple
Cotización instantánea de encomiendaRastreo público de encomienda por código
3 · Cotización de encomienda por peso y distancia4 · Rastreo público sin necesidad de cuenta
Panel de cuenta con viajes y envíosPanel de administración de Django con acción de advancing de estado
5 · "Mi cuenta": viajes reservados y envíos registrados6 · Back-office en Django Admin con avance de estado de encomiendas
+ +## Qué resuelve + +| Flujo | Descripción | +|---|---| +| 🪑 **Reserva de asientos** | Búsqueda por origen/destino/fecha, selección de hasta 6 asientos en el plano real del bus, datos de pasajeros y ticket con código único. | +| 📦 **Envío de encomiendas** | Cotización instantánea por peso y distancia, registro con código de rastreo `RTX-ENV-XXXXXX` y ciclo de vida de 4 estados. | +| 🔎 **Rastreo público** | Timeline de eventos accesible sin cuenta y **sin exponer datos del remitente ni del destinatario**. | +| 👤 **Cuentas** | Registro/login por correo, panel "Mi cuenta" con historial paginado de viajes y envíos. | +| 🛠 **Back-office** | Django Admin para operar rutas, buses, viajes y encomiendas, con acción masiva para avanzar el estado de un envío. | -> Documentación de contexto: [CONTEXT.md](CONTEXT.md) · Plan de construcción: [PLAN.md](PLAN.md) +## Stack -| Capa | Stack | +| Capa | Tecnologías | |---|---| -| Frontend | React 19 · Vite · TypeScript · Tailwind CSS v4 · Framer Motion · TanStack Query · React Router · RHF + Zod | -| Backend | Django 5 · Django REST Framework · SimpleJWT · drf-spectacular | -| Base de datos | SQLite (dev por defecto) o PostgreSQL 16 vía Docker | -| Tests | pytest (backend) · Vitest + RTL (frontend) · Playwright (E2E) | +| **Frontend** | React 19 · Vite 8 · TypeScript 6 · Tailwind CSS v4 · Motion (Framer Motion) · TanStack Query v5 · React Router v8 · React Hook Form + Zod 4 | +| **Backend** | Django 5.2 · Django REST Framework · SimpleJWT (con blacklist) · drf-spectacular · django-cors-headers | +| **Base de datos** | SQLite por defecto en desarrollo · PostgreSQL 16 vía Docker | +| **Calidad** | pytest + pytest-cov · Vitest + Testing Library · Playwright (E2E) · oxlint · GitHub Actions | ## Puesta en marcha -Requisitos: Python 3.12+, Node 20+, pnpm. (Docker solo si quieres Postgres.) +**Requisitos:** Python 3.12+ · Node 20+ · pnpm · Docker (opcional, solo para PostgreSQL). ```bash -# 1. Variables de entorno +# 1) Variables de entorno cp .env.example .env -# 2. Backend +# 2) Backend cd backend python -m venv .venv -.venv/Scripts/pip install -r requirements.txt # Windows (.venv/bin/pip en Unix) +.venv/Scripts/pip install -r requirements.txt # Unix: .venv/bin/pip install -r requirements.txt .venv/Scripts/python manage.py migrate -.venv/Scripts/python manage.py seed_demo # ciudades, rutas, buses y 2 semanas de viajes -.venv/Scripts/python manage.py createsuperuser # para el panel /admin -.venv/Scripts/python manage.py runserver # http://localhost:8000 +.venv/Scripts/python manage.py seed_demo # 10 ciudades, 20 rutas, 5 buses y 14 días de viajes +.venv/Scripts/python manage.py createsuperuser # para operar en /admin +.venv/Scripts/python manage.py runserver # http://localhost:8000 -# 3. Frontend (en otra terminal) +# 3) Frontend (en otra terminal) cd frontend pnpm install -pnpm dev # http://localhost:5173 +pnpm dev # http://localhost:5173 ``` -¿Prefieres PostgreSQL? `docker compose up -d` y pon `DATABASE_ENGINE=postgres` en `.env`. +| URL | Contenido | +|---|---| +| `http://localhost:5173` | Aplicación web | +| `http://localhost:8000/api/docs/` | Swagger UI (OpenAPI, solo en desarrollo) | +| `http://localhost:8000/admin/` | Back-office de operaciones | -## URLs útiles +
+¿Prefieres PostgreSQL 16? -| URL | Qué hay | -|---|---| -| `http://localhost:5173` | La app | -| `http://localhost:8000/api/docs/` | Swagger UI (OpenAPI) | -| `http://localhost:8000/admin/` | Back-office de operaciones (rutas, viajes, encomiendas) | +```bash +docker compose up -d +# y en .env: DATABASE_ENGINE=postgres +``` + +`docker-compose.yml` solo levanta la base de datos; el backend y el frontend se ejecutan desde tu máquina. +
+ +
+Variables de entorno relevantes + +| Variable | Por defecto | Para qué sirve | +|---|---|---| +| `DJANGO_SECRET_KEY` | — | **Obligatoria en producción**: el servidor no arranca sin ella. | +| `DJANGO_DEBUG` | `True` | Con `False` se activan headers de seguridad y se oculta `/api/docs/`. | +| `DATABASE_ENGINE` | `sqlite` | `postgres` para usar el servicio de `docker-compose.yml`. | +| `FRONTEND_ORIGIN` | `http://localhost:5173` | Única origen permitido por CORS. | +| `VITE_API_BASE_URL` | `http://localhost:8000/api/v1` | Base de la API que consume el frontend. | +
+ +## API + +Todas las rutas viven bajo `/api/v1/` y responden con un envelope uniforme: + +```json +{ "success": true, "data": {}, "error": null } +``` + +Los errores usan códigos estables en inglés y mensajes en español: + +```json +{ "success": false, "data": null, "error": { "detail": "…", "code": "seat_taken", "fields": {} } } +``` -Para avanzar el estado de una encomienda (En tránsito → Entregado): panel admin → -Encomiendas → acción **"Avanzar al siguiente estado"**. +| Método | Endpoint | Auth | Descripción | +|---|---|:--:|---| +| `GET` | `/cities/` | — | Ciudades disponibles | +| `GET` | `/trips/` | — | Búsqueda paginada de viajes programados | +| `GET` | `/trips/{id}/seats/` | — | Plano del bus y asientos ocupados | +| `POST` | `/auth/register/` | — | Crear cuenta | +| `POST` | `/auth/token/` | — | Login (JWT) | +| `POST` | `/auth/token/refresh/` | — | Renovar access token | +| `GET` | `/auth/me/` | ✅ | Perfil del usuario actual | +| `POST` | `/bookings/` | ✅ | Crear reserva (transaccional) | +| `GET` | `/bookings/mine/` | ✅ | Historial paginado de reservas | +| `GET` | `/bookings/{code}/` | ✅ | Detalle de una reserva propia | +| `POST` | `/parcels/quote/` | — | Cotizar sin persistir | +| `POST` | `/parcels/` | ✅ | Registrar encomienda | +| `GET` | `/parcels/mine/` | ✅ | Historial paginado de envíos | +| `GET` | `/parcels/track/{code}/` | — | Rastreo público por código | + +Las listas paginadas devuelven `{ "items": [...], "meta": { "total", "page", "pages", "page_size" } }`. + +## Decisiones de arquitectura -## Tests +``` +frontend/ ──HTTP + JWT──▶ backend/ ──▶ ORM Django ──▶ SQLite | PostgreSQL + SPA React DRF + apps por dominio +``` + +- **Dominio divided por apps**: `core` (envelope, paginación, throttling), `accounts`, `catalog`, `bookings`, `parcels`. La lógica de negocio vive en `services.py` y las consultas en `selectors.py`, no en las vistas. +- **Cero doble reserva**: el asiento se bloquea con `select_for_update()` dentro de una transacción y, como última línea de defensa, existe el constraint `UNIQUE(trip, seat_number)` en la base de datos. Un conflicto devuelve `409 seat_taken`. +- **Aislamiento de recursos**: el detalle de una reserva se filtra siempre por el usuario autenticado; otro usuario recibe `404`, no `403`, para no revelar que el recurso existe. +- **Rastreo sin fuga de datos**: el serializer público expone código, estado, ruta y eventos; nunca remitente ni datos de contacto del destinatario. +- **Sesión JWT**: access token de 30 min + refresh de 7 días con rotación y blacklist; el cliente renueva una sola vez ante un `401` y limpia la sesión si el refresh falla. +- **Rate limiting** por scope: anónimos `60/min`, usuarios `120/min`, `auth` `10/min`, `tracking` `30/min`. +- **Frontend por features** (`components/booking`, `components/parcels`, `components/landing`, `ui/` como primitivas) con design tokens en `frontend/src/styles/tokens.css`; la landing se carga de forma eager por LCP y el resto de páginas con `React.lazy`. +- **Polling e invalidación**: el mapa de asientos se refresca cada 20 s y se invalida al crear una reserva o recibir un `409`. +- **Activos de marca**: los frames originales viven en `Frames/` y se sirven como WebP optimizados desde `frontend/public/img/` (`frontend/scripts/optimize-images.mjs`). + +## Tests y calidad + +| Suite | Cobertura | Comando | +|---|---|---| +| Backend | **38 tests** (accounts 9 · bookings 10 · catalog 8 · parcels 11) | `python -m pytest` | +| Backend + cobertura | umbral de **80 %** en CI | `python -m pytest --cov=apps` | +| Frontend | **82 tests** en 17 archivos (Vitest + Testing Library) | `pnpm test` | +| E2E | 3 specs (landing, reserva completa, encomienda + tracking) | `pnpm e2e` | +| Lint / tipos | oxlint + `tsc -b` | `pnpm lint` · `pnpm build` | ```bash # Backend (desde backend/) -.venv/Scripts/python -m pytest # 38 tests -.venv/Scripts/python -m pytest --cov=apps # con cobertura +.venv/Scripts/python -m pytest +.venv/Scripts/python -m pytest --cov=apps # Frontend (desde frontend/) -pnpm test # unit + componentes (Vitest) -pnpm e2e # E2E (Playwright levanta ambos servidores solo) -pnpm lint # oxlint -pnpm build # typecheck + build de producción +pnpm test +pnpm e2e # Playwright levanta el backend y el frontend por su cuenta +pnpm lint +pnpm build # typecheck + build de producción +``` + +**CI** (`.github/workflows/ci.yml`) corre en cada push y PR: `pytest --cov=apps --cov-fail-under=80` en Python 3.12 y `oxlint + vitest + build` en Node. Los E2E quedan fuera de CI de forma intencionada: el `webServer` de Playwright asume el entorno local de desarrollo. + +## Seguridad + +- **Aplicado**: rotación de refresh tokens **con blacklist**; throttling global y por scope; `SECRET_KEY` obligatoria en producción (el arranque falla si falta); Swagger y `/api/schema/` expuestos **solo** con `DEBUG`; CORS limitado a `FRONTEND_ORIGIN`; validación del parámetro `next` del frontend (solo rutas internas); headers de seguridad en `prod.py` (HSTS, `nosniff`, `X-Frame-Options: DENY`, referrer policy); validación de contraseñas de Django. +- **Tradeoff aceptado para la demo**: el JWT se guarda en `localStorage`, mitigado por la corta vida del access token (30 min) y la rotación con blacklist. +- **Pendiente antes de un uso real**: protección de fuerza bruta en el login de `/admin/`, `SECURE_PROXY_SSL_HEADER` según el proxy y `CSRF_TRUSTED_ORIGINS` si el admin se sirve desde otro origen. + +## Estructura del repositorio + +``` +. +├── backend/ # Django + DRF +│ ├── apps/ +│ │ ├── core/ # envelope, errores, paginación, throttles +│ │ ├── accounts/ # usuario custom (login por correo) + JWT +│ │ ├── catalog/ # ciudades, rutas, buses, viajes +│ │ ├── bookings/ # reservas + invariante de asientos +│ │ └── parcels/ # encomiendas + timeline de rastreo +│ ├── config/settings/ # base · dev · prod · test +│ └── manage.py +├── frontend/ # React + Vite + TypeScript +│ ├── src/ +│ │ ├── components/ # por feature + ui/ (primitivas) +│ │ ├── pages/ # rutas de la SPA +│ │ ├── hooks/ # capa de datos (TanStack Query) +│ │ ├── lib/ # api-client, auth-context, format, motion +│ │ ├── styles/ # tokens.css (fuente de verdad del diseño) +│ │ └── test/ # setup y fixtures +│ ├── e2e/ # specs de Playwright +│ └── public/img/ # marca optimizada en WebP +├── docs/screenshots/ # capturas de este README +├── Frames/ # arte de marca original +├── docker-compose.yml # PostgreSQL 16 +└── .github/workflows/ci.yml ``` -## Arquitectura en 30 segundos - -- **API** en `/api/v1/` con envelope uniforme `{"success", "data", "error"}` y - errores en español con códigos estables (`seat_taken`, `validation_error`…). -- **Asientos sin doble reserva**: constraint `UNIQUE(trip, seat_number)` + - `select_for_update()` transaccional (`backend/apps/bookings/services.py`). -- **Rastreo público** por código `RTX-ENV-XXXXXX`, sin exponer datos personales. -- **Auth JWT** (access 30 min + refresh 7 días con rotación); usuario por email. -- **Frontend** organizado por feature (`components/booking`, `components/parcels`, - `components/landing`, `ui/` primitivas) con design tokens en `src/styles/tokens.css`. -- Los frames de marca (`Frames/`) se sirven optimizados como WebP desde - `frontend/public/img/` (script: `frontend/scripts/optimize-images.mjs`). - -## Notas de seguridad - -Revisión hecha con agentes de seguridad y code review (sin hallazgos críticos). Estado actual: - -- **Aplicado**: rotación de refresh tokens **con blacklist**, throttling global - (`anon 60/min`, `user 120/min`) además de los scopes `auth`/`tracking`, - `SECRET_KEY` obligatorio y fuerte en producción (falla al arrancar si falta), - Swagger/`/api/schema/` solo en desarrollo, validación del parámetro `next` - en el frontend (solo rutas internas), CORS restringido al origen del frontend, - headers de seguridad (HSTS, nosniff, X-Frame-Options DENY) en `prod.py`. -- **Tradeoff aceptado (demo)**: JWT en `localStorage` — mitigado con access token - de 30 min y rotación con blacklist. -- **Pendiente antes de producción real**: protección de fuerza bruta en el login - de `/admin/` (p. ej. `django-axes` o rate limit en el reverse proxy), - `SECURE_PROXY_SSL_HEADER` según tu proxy, y `CSRF_TRUSTED_ORIGINS` si el admin - se sirve desde otro origen. +## Fuera de alcance (por diseño) + +Es un **prototipo**, no un sistema de producción. Queda pendiente a propósito: + +- **Pagos simulados**: la reserva nace directamente en estado `confirmed`, sin pasarela. +- **Sin notificaciones**: no hay correos ni SMS de confirmación o de estado de envío. +- **Sin roles ni multi-oficina**: el back-office es el Django Admin estándar. +- **E2E en un solo navegador**: Playwright está configurado para Chromium. +- **Sin i18n**: la interfaz es solo en español. + +## Sobre este proyecto + +**ES** — Prototipo personal creado como pieza de portafolio para reclutadores de desarrollo de software. Fue construido **con asistencia de IA** (Claude Code), guiado por prompts iterativos, y complementado con **pruebas manuales** y las suites automatizadas del repositorio. El objetivo es mostrar arquitectura full-stack, disciplina de testing y un flujo de desarrollo asistido por IA. + +**EN** — Personal prototype built as a portfolio piece for software development recruiters, created **with AI assistance** (Claude Code) and complemented with **manual testing** plus the automated suites in this repository. Payments are simulated and there are no email/SMS notifications: it is a demonstration of full-stack architecture, testing discipline and an AI-assisted development workflow — not a production system. + +## Licencia + +MIT © 2026 Ander Alexander Aguirre Tejada · [LICENSE](LICENSE) diff --git a/docs/screenshots/01-landing.webp b/docs/screenshots/01-landing.webp new file mode 100644 index 0000000..ebbb2ae Binary files /dev/null and b/docs/screenshots/01-landing.webp differ diff --git a/docs/screenshots/02-busqueda-viajes.webp b/docs/screenshots/02-busqueda-viajes.webp new file mode 100644 index 0000000..552ad59 Binary files /dev/null and b/docs/screenshots/02-busqueda-viajes.webp differ diff --git a/docs/screenshots/03-mapa-asientos.webp b/docs/screenshots/03-mapa-asientos.webp new file mode 100644 index 0000000..63d1ca7 Binary files /dev/null and b/docs/screenshots/03-mapa-asientos.webp differ diff --git a/docs/screenshots/04-encomienda-cotizacion.webp b/docs/screenshots/04-encomienda-cotizacion.webp new file mode 100644 index 0000000..d8e1fc4 Binary files /dev/null and b/docs/screenshots/04-encomienda-cotizacion.webp differ diff --git a/docs/screenshots/05-rastreo.webp b/docs/screenshots/05-rastreo.webp new file mode 100644 index 0000000..778b7aa Binary files /dev/null and b/docs/screenshots/05-rastreo.webp differ diff --git a/docs/screenshots/06-mi-cuenta.webp b/docs/screenshots/06-mi-cuenta.webp new file mode 100644 index 0000000..29ccb4d Binary files /dev/null and b/docs/screenshots/06-mi-cuenta.webp differ diff --git a/docs/screenshots/07-admin-encomiendas.webp b/docs/screenshots/07-admin-encomiendas.webp new file mode 100644 index 0000000..e9f9072 Binary files /dev/null and b/docs/screenshots/07-admin-encomiendas.webp differ