Skip to main content

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:
RouterPrefixResponsibility
auth/authLogin, token issuance
users/usuariosUser CRUD (admin only)
products/productosProducts and ingredients (includes /ingredientes sub-routes)
orders/pedidosOrder lifecycle, kitchen queue, state transitions
sales/ventasSale registration and history
stats/statsAggregated statistics and downloadable reports (PDF/Excel)
ws/wsWebSocket 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:
SectionPathDescription
Dashboard/dashboardKey metrics and statistics overview
Users/usuariosCreate, edit, deactivate staff accounts
Menu / Products/menuCreate, edit, toggle availability, delete products
Inventory/inventarioView ingredient stock, adjust quantities, log supply purchases
Orders/pedidosView all orders, change order state, download PDF tickets
Expenses(proxy reports)View and export expense reports (PDF and Excel)
Tables/mesasCreate 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
ScreenPurpose
MeseroMesasScreenView all tables and their current status
MeseroDetalleMesaScreenInspect a table’s active order
MeseroPedidoCatalogoScreenBrowse the product catalogue to build an order
MeseroPedidoResumenScreenReview and confirm an order before submission
MeseroPedidoEstadoScreenTrack an order’s progress through states
MeseroPerfilScreenView and manage the waiter’s own profile
Caja (Cashier) module
ScreenPurpose
CajaPedidosActivosScreenList orders ready for payment
CajaConfirmarPedidoScreenConfirm order details before charging
CajaPagosScreenSelect payment method and enter amount received
CajaTicketScreenDisplay and share the generated sale ticket
CajaBalanceScreenView the daily sales balance and summary
CajaGastosScreenLog operational expenses
Cocina (Kitchen) module
ScreenPurpose
CocinaPedidosScreenReal-time kitchen queue of incoming orders
CocinaDetallePedidoScreenView full item details and notes for a single order
CocinaInventarioScreenBrowse ingredient stock levels and low-stock alerts
CocinaRegistrarCompraScreenLog a new supply purchase to update stock
CocinaMenuScreenView and manage the active product menu
CocinaNuevoProductoScreenCreate 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:
TableDescription
rolesThe four staff roles: admin, mesero, cocina, caja.
usuariosStaff accounts. Each user belongs to exactly one role. Stores a bcrypt password_hash, an activo flag, and a created_at timestamp.
mesasPhysical tables with a unique numero and a seating capacidad.
categoriasProduct and expense categories. A tipo constraint restricts values to producto, gasto, or ambos.
productosMenu items with a name, description, price, category, availability flag (disponible), and optional image URL.
ingredientesInventory ingredients with unidad, stock_actual, stock_minimo, and costo_unitario.
producto_ingredienteRecipe junction table linking products to ingredients with a cantidad (quantity per serving). Cascades deletes from both sides.
pedidosOrders. Each order references a mesa, a mesero, and a current estado_pedido. Timestamps are maintained for both creation and last update.
detalle_pedidoLine items within an order. Stores cantidad, precio_unitario, and a database-generated subtotal.
detalle_observacionesFree-text notes attached to individual order line items (e.g. “no onions”).
estados_pedidoThe possible states an order can move through (e.g. recibido, en preparación, listo, entregado). Each state is owned by a role.
historial_estados_pedidoAudit log of every state transition on every order, recording origin state, destination state, responsible user, and timestamp.
ventasCompleted sales. One-to-one with pedidos. Stores the cashier, payment method, monto_total, monto_recibido, and a computed cambio (change due).
metodos_pagoPayment method catalogue (e.g. cash, card).
gastosOperational expenses logged by cashiers or admins, with amount, category, date, and the recording user.
compras_suministrosSupply 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:
http://localhost:8000
URLDescription
http://localhost:8000/docsInteractive Swagger UI — try every endpoint directly in the browser
http://localhost:8000/redocReDoc 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"
}

Build docs developers (and LLMs) love