Documentation Index
Fetch the complete documentation index at: https://mintlify.com/123048152-JJDS/CafeteriaPM_S203/llms.txt
Use this file to discover all available pages before exploring further.
CafeteriaPM follows a three-tier architecture built around a single source of truth: a PostgreSQL database accessed exclusively through the FastAPI backend. No client — whether the Flask admin panel or the React Native mobile app — ever queries the database directly. Every read and write flows through the REST API, which enforces authentication via JWT and authorisation via role-based access control. This design means business logic, validation, and data integrity rules live in one place and benefit all clients equally.
Backend (FastAPI API)
The FastAPI backend is the core of the system. It is the only tier with a direct connection to the PostgreSQL database, managed entirely through the SQLAlchemy 2.0 ORM.
Entry point — main.py
main.py bootstraps the application by calling Base.metadata.create_all() on startup (which ensures any missing tables are created), configuring CORS middleware, and registering all router modules. CORS is intentionally open (allow_origins=["*"]) to accommodate development and the mobile app:
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Router modules
Each domain area is encapsulated in its own router module. The table below lists every router, its URL prefix, and its primary responsibility:
| Router | Prefix | Responsibility |
|---|
auth | /auth | Login, token issuance |
users | /usuarios | User CRUD (admin only) |
products | /productos | Products and ingredients (includes /ingredientes sub-routes) |
orders | /pedidos | Order lifecycle, kitchen queue, state transitions |
sales | /ventas | Sale registration and history |
stats | /stats | Aggregated statistics and downloadable reports (PDF/Excel) |
ws | /ws | WebSocket stub (not yet implemented) |
mesas | (prefix set in router) | Table management |
gastos | (prefix set in router) | Expense logging |
compras | (prefix set in router) | Supply purchase logging |
Authentication and authorisation
All protected endpoints use FastAPI’s Depends system. The get_current_user dependency decodes and validates the incoming JWT. The require_roles dependency builds on top of it to restrict access by role name — for example require_roles("admin", "cocina") rejects requests from users with any other role and returns 403 Forbidden.
Configuration
All runtime configuration is loaded from the .env file via python-decouple. The _Settings class in app/core/config.py surfaces these as typed attributes (settings.SECRET_KEY, settings.DB_HOST, etc.) consumed throughout the codebase.
Admin Web Panel (Flask)
The Flask admin panel runs on port 5050 and is restricted exclusively to users whose role is admin. It is a server-side rendered application — not a single-page app — that stores the admin’s JWT access token in the Flask server-side session after login.
Every data operation performed in the panel goes through the api_request helper, which attaches the stored Bearer token to the outgoing HTTP request and forwards it to the FastAPI backend at http://localhost:8000:
def api_request(method, endpoint, data=None, json=None, params=None):
headers = {"Authorization": f"Bearer {session.get('access_token')}"}
url = f"{API_BASE_URL}{endpoint}"
# ... dispatches GET / POST / PUT / PATCH / DELETE
The panel provides the following sections:
| Section | Path | Description |
|---|
| Dashboard | /dashboard | Key metrics and statistics overview |
| Users | /usuarios | Create, edit, deactivate staff accounts |
| Menu / Products | /menu | Create, edit, toggle availability, delete products |
| Inventory | /inventario | View ingredient stock, adjust quantities, log supply purchases |
| Orders | /pedidos | View all orders, change order state, download PDF tickets |
| Expenses | (proxy reports) | View and export expense reports (PDF and Excel) |
| Tables | /mesas | Create tables, set occupancy status, manage reservations |
| Reports | /proxy/reporte-* | Download sales, expenses, products, inventory, and history reports in PDF or Excel |
The panel enforces its own login_required decorator which independently checks both the presence of the session token and that the user’s role is admin, providing a second layer of access control before any request reaches the API.
Mobile App (React Native / Expo)
The mobile application is built with React Native 0.81.5 and Expo 54.0.36, using the expo-router library for file-based navigation. The app targets iOS, Android, and web. It is organised into three role-specific modules — each a collection of screens that map to exactly the workflows that role performs day to day.
Mesero (Waiter) module
| Screen | Purpose |
|---|
MeseroMesasScreen | View all tables and their current status |
MeseroDetalleMesaScreen | Inspect a table’s active order |
MeseroPedidoCatalogoScreen | Browse the product catalogue to build an order |
MeseroPedidoResumenScreen | Review and confirm an order before submission |
MeseroPedidoEstadoScreen | Track an order’s progress through states |
MeseroPerfilScreen | View and manage the waiter’s own profile |
Caja (Cashier) module
| Screen | Purpose |
|---|
CajaPedidosActivosScreen | List orders ready for payment |
CajaConfirmarPedidoScreen | Confirm order details before charging |
CajaPagosScreen | Select payment method and enter amount received |
CajaTicketScreen | Display and share the generated sale ticket |
CajaBalanceScreen | View the daily sales balance and summary |
CajaGastosScreen | Log operational expenses |
Cocina (Kitchen) module
| Screen | Purpose |
|---|
CocinaPedidosScreen | Real-time kitchen queue of incoming orders |
CocinaDetallePedidoScreen | View full item details and notes for a single order |
CocinaInventarioScreen | Browse ingredient stock levels and low-stock alerts |
CocinaRegistrarCompraScreen | Log a new supply purchase to update stock |
CocinaMenuScreen | View and manage the active product menu |
CocinaNuevoProductoScreen | Create a new product with ingredients |
Token persistence between app sessions is handled by @react-native-async-storage/async-storage (version 2.2.0), so staff do not need to log in again after closing the app.
Database Schema
The PostgreSQL database is defined entirely through SQLAlchemy ORM models. The following entities make up the core schema:
| Table | Description |
|---|
roles | The four staff roles: admin, mesero, cocina, caja. |
usuarios | Staff accounts. Each user belongs to exactly one role. Stores a bcrypt password_hash, an activo flag, and a created_at timestamp. |
mesas | Physical tables with a unique numero and a seating capacidad. |
categorias | Product and expense categories. A tipo constraint restricts values to producto, gasto, or ambos. |
productos | Menu items with a name, description, price, category, availability flag (disponible), and optional image URL. |
ingredientes | Inventory ingredients with unidad, stock_actual, stock_minimo, and costo_unitario. |
producto_ingrediente | Recipe junction table linking products to ingredients with a cantidad (quantity per serving). Cascades deletes from both sides. |
pedidos | Orders. Each order references a mesa, a mesero, and a current estado_pedido. Timestamps are maintained for both creation and last update. |
detalle_pedido | Line items within an order. Stores cantidad, precio_unitario, and a database-generated subtotal. |
detalle_observaciones | Free-text notes attached to individual order line items (e.g. “no onions”). |
estados_pedido | The possible states an order can move through (e.g. recibido, en preparación, listo, entregado). Each state is owned by a role. |
historial_estados_pedido | Audit log of every state transition on every order, recording origin state, destination state, responsible user, and timestamp. |
ventas | Completed sales. One-to-one with pedidos. Stores the cashier, payment method, monto_total, monto_recibido, and a computed cambio (change due). |
metodos_pago | Payment method catalogue (e.g. cash, card). |
gastos | Operational expenses logged by cashiers or admins, with amount, category, date, and the recording user. |
compras_suministros | Supply purchases that increment ingredient stock. Records ingredient, quantity, total cost, date, and the user who logged the purchase. |
The WebSocket router is mounted at /ws in main.py but its implementation is currently a stub. Real-time push notifications for kitchen queue updates are not yet active. Poll the /pedidos/cola-cocina endpoint for current queue state in the meantime.
API Base URL
The default base URL for all API requests when running locally is:
| URL | Description |
|---|
http://localhost:8000/docs | Interactive Swagger UI — try every endpoint directly in the browser |
http://localhost:8000/redoc | ReDoc documentation — clean read-only reference |
http://localhost:8000/ | Health check endpoint |
The health check (GET /) confirms the API is running and returns the configured application name and version:
{
"app": "CafeteriaPM API",
"version": "1.0.0",
"status": "ok",
"docs": "/docs"
}