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.

The /stats/ endpoints provide operational analytics and report generation for the cafeteria management system. Dashboard and summary endpoints return JSON designed for display in the admin panel and mobile app — covering daily KPIs, monthly financial summaries, chart-ready time-series data, product performance rankings, and inventory status. Report endpoints return binary file downloads in PDF (via ReportLab) or XLSX (via openpyxl) format, with appropriate Content-Disposition headers so clients can save them directly to disk. All endpoints require authentication; role requirements vary per endpoint as documented below.

Dashboard and Summaries

Dashboard KPIs

Authorization
string
required
Bearer <token> — Roles: admin, caja.

GET /stats/dashboard
Returns a snapshot of today’s key performance indicators plus the top 5 best-selling products over the last 30 days. Intended for the main dashboard widget row. Example response
{
  "ventas_hoy": 3240.50,
  "pedidos_activos": 4,
  "stock_bajo": 2,
  "gastos_hoy": 580.00,
  "productos_mas_vendidos": [
    { "id": 7, "nombre": "Café Americano", "total_vendido": 142 },
    { "id": 3, "nombre": "Torta de Jamón",  "total_vendido": 98  },
    { "id": 12, "nombre": "Agua 500ml",     "total_vendido": 87  },
    { "id": 5, "nombre": "Jugo de Naranja", "total_vendido": 74  },
    { "id": 9, "nombre": "Sandwich Club",   "total_vendido": 61  }
  ]
}
ventas_hoy
float
Total sales revenue recorded today (sum of monto_total across all sales with a fecha matching today’s date).
pedidos_activos
integer
Count of orders currently in an active state: pendiente, en_preparacion, listo, or entregado. Paid and cancelled orders are excluded.
stock_bajo
integer
Count of ingredients whose stock_actual is at or below their stock_minimo threshold.
gastos_hoy
float
Total expenses recorded today (sum of monto across all expenses with a fecha matching today’s date).
productos_mas_vendidos
array
Top 5 products by total units sold in the last 30 days, across all paid orders. Each entry: {id, nombre, total_vendido}.

Monthly summary

Authorization
string
required
Bearer <token> — Roles: admin, caja.

GET /stats/resumen-mes
Calculates a financial summary from the 1st of the current calendar month through today. All monetary values are rounded to 2 decimal places. Example response
{
  "total_ventas": 12500.00,
  "total_pedidos": 87,
  "ticket_promedio": 143.68,
  "gastos_totales": 3200.00,
  "ganancia_neta": 9300.00,
  "fecha_inicio": "2024-01-01",
  "fecha_fin": "2024-01-31"
}
total_ventas
float
Sum of all sale monto_total values within the period.
total_pedidos
integer
Number of sales (paid orders) within the period.
ticket_promedio
float
Average sale amount (total_ventas / total_pedidos). Returns 0.0 if there are no sales.
gastos_totales
float
Sum of all expense monto values within the period.
ganancia_neta
float
Net gain: total_ventas - gastos_totales. Does not include ingredient purchase costs (/compras/).
fecha_inicio
string
First day of the current month in YYYY-MM-DD format.
fecha_fin
string
Today’s date in YYYY-MM-DD format.

Chart Data

Daily sales chart

Authorization
string
required
Bearer <token> — Roles: admin, caja.

GET /stats/ventas-diarias
Returns an array of {fecha, total} entries suitable for rendering a bar or line chart. Each entry represents one day, and the array always covers exactly dias days ending today (including today), even if a day had no sales (in which case total is 0.0). Query parameters
dias
integer
Number of days to look back, including today. Defaults to 7. For a 30-day view, pass ?dias=30.
Example response (with dias=7)
[
  { "fecha": "09/01", "total": 1840.00 },
  { "fecha": "10/01", "total": 2100.50 },
  { "fecha": "11/01", "total": 950.00  },
  { "fecha": "12/01", "total": 0.00    },
  { "fecha": "13/01", "total": 2450.75 },
  { "fecha": "14/01", "total": 3100.00 },
  { "fecha": "15/01", "total": 3240.50 }
]
fecha
string
Day label formatted as DD/MM (e.g. "15/01").
total
float
Total sales revenue for that day. 0.0 for days with no sales.

Daily expenses chart

Authorization
string
required
Bearer <token> — Roles: admin, caja.

GET /stats/gastos-diarios
Same shape as GET /stats/ventas-diarias but aggregated from the expenses table. Each entry represents total operational expenses for that day. Query parameters
dias
integer
Number of days to look back, including today. Defaults to 7.
Example response
[
  { "fecha": "09/01", "total": 120.00 },
  { "fecha": "10/01", "total": 0.00   },
  { "fecha": "11/01", "total": 450.00 },
  { "fecha": "12/01", "total": 0.00   },
  { "fecha": "13/01", "total": 85.50  },
  { "fecha": "14/01", "total": 200.00 },
  { "fecha": "15/01", "total": 580.00 }
]

Product Analytics

Top products (last 30 days)

Authorization
string
required
Bearer <token> — Role: admin.

GET /stats/productos-mas-vendidos
Returns the products with the highest total unit sales across all paid orders in the last 30 days, sorted descending by total_vendido. Query parameters
limit
integer
Maximum number of products to return. Defaults to 10.
Example response
[
  { "id": 7,  "nombre": "Café Americano", "total_vendido": 284 },
  { "id": 3,  "nombre": "Torta de Jamón", "total_vendido": 196 },
  { "id": 12, "nombre": "Agua 500ml",     "total_vendido": 174 }
]
id
integer
Product ID.
nombre
string
Product name.
total_vendido
integer
Total units sold in paid orders over the last 30 days.

Full product statistics

Authorization
string
required
Bearer <token> — Role: admin.

GET /stats/productos-estadisticas
Returns a single object with three ranked lists for a complete product performance overview. The rentabilidad list is computed in Python by multiplying each ingredient’s costo_unitario by its quantity in the product’s recipe. Example response
{
  "mas_vendidos": [
    { "id": 7, "nombre": "Café Americano", "total_vendido": 284 }
  ],
  "menos_vendidos": [
    { "id": 15, "nombre": "Té Verde", "total_vendido": 3 }
  ],
  "rentabilidad": [
    { "id": 7, "nombre": "Café Americano", "precio": 35.00, "costo": 4.20, "margen": 30.80 }
  ]
}
mas_vendidos
array
Top 10 products by total units sold across all paid orders (no 30-day limit for this endpoint). Each entry: {id, nombre, total_vendido}.
menos_vendidos
array
Bottom 5 products by total units sold across all paid orders. Useful for identifying underperforming items. Each entry: {id, nombre, total_vendido}.
rentabilidad
array
Top 10 products by profit margin, calculated as precio - costo_ingredientes. Each entry: {id, nombre, precio, costo, margen}. costo is the sum of (ingrediente.cantidad × ingrediente.costo_unitario) across all recipe items.

Inventory and Activity

Inventory status

Authorization
string
required
Bearer <token> — Roles: admin, cocina.

GET /stats/inventario-estado
Returns a complete snapshot of the ingredient inventory plus the 10 most recent supply purchase movements. Example response
{
  "total_items": 24,
  "criticos": 3,
  "ingredientes": [
    {
      "id": 5,
      "nombre": "Harina de trigo",
      "unidad": "kg",
      "stock_actual": 8.5,
      "stock_minimo": 10.0,
      "estado": "Crítico"
    },
    {
      "id": 6,
      "nombre": "Azúcar",
      "unidad": "kg",
      "stock_actual": 22.0,
      "stock_minimo": 5.0,
      "estado": "Ok"
    }
  ],
  "movimientos": [
    {
      "ingrediente": "Harina de trigo",
      "cantidad": 25.0,
      "costo_total": 150.00,
      "fecha": "2024-01-15T08:45:12"
    }
  ]
}
total_items
integer
Total number of ingredients configured in the system.
criticos
integer
Count of ingredients where stock_actual <= stock_minimo.
ingredientes
array
Full ingredient list with current stock levels. Each entry: {id, nombre, unidad, stock_actual, stock_minimo, estado}. estado is "Crítico" when stock_actual <= stock_minimo, otherwise "Ok".
movimientos
array
The 10 most recent supply purchases. Each entry: {ingrediente, cantidad, costo_total, fecha}.

Recent activity history

Authorization
string
required
Bearer <token> — Role: admin.

GET /stats/historial-actividad
Returns the most recent orders, sales, and expenses combined into a single response object. Useful for the admin activity feed. Query parameters
limite
integer
Maximum number of records to return per category. Defaults to 20. Each of pedidos, ventas, and gastos independently returns up to limite records.
Example response
{
  "pedidos": [
    { "id": 88, "mesa": 4, "estado": "pagado", "created_at": "2024-01-15T14:30:00" }
  ],
  "ventas": [
    { "id": 101, "pedido_id": 88, "monto_total": 95.50, "fecha": "2024-01-15T14:32:00" }
  ],
  "gastos": [
    { "id": 14, "descripcion": "Pago de servicio eléctrico", "monto": 450.00, "fecha": "2024-01-15" }
  ]
}

Sales list with filters

Authorization
string
required
Bearer <token> — Roles: admin, caja.

GET /stats/ventas-lista
Returns a flat list of sales records for report display, optimized for tabular views. Unlike GET /ventas/, this endpoint returns denormalized strings for cashier name and payment method name rather than nested objects. Query parameters
fecha_inicio
string
Start of the date range filter (YYYY-MM-DD). Inclusive.
fecha_fin
string
End of the date range filter (YYYY-MM-DD). Inclusive.
Example response
[
  {
    "id": 101,
    "pedido_id": 42,
    "cajero": "Ana García",
    "metodo_pago": "Efectivo",
    "monto_total": 95.50,
    "fecha": "2024-01-15T14:32:00"
  }
]

Expenses list with filters

Authorization
string
required
Bearer <token> — Roles: admin, caja.

GET /stats/gastos-lista
Returns a flat list of expense records for tabular display. Category and user names are denormalized as strings. Falls back to "Sin categoría" when no category is assigned. Query parameters
fecha_inicio
string
Start of the date range filter (YYYY-MM-DD). Inclusive.
fecha_fin
string
End of the date range filter (YYYY-MM-DD). Inclusive.
Example response
[
  {
    "id": 14,
    "descripcion": "Pago de servicio eléctrico",
    "monto": 450.00,
    "categoria": "Servicios",
    "usuario": "Carlos López",
    "fecha": "2024-01-15"
  }
]

Downloadable Reports

All report endpoints stream a binary file response. The response includes a Content-Disposition: attachment; filename=<name> header so browsers and HTTP clients can save the file automatically. All report endpoints require authentication via Authorization: Bearer <token>.

Report endpoints reference

EndpointFormatRoleFilter Parameters
GET /stats/reporte-ventas/pdfapplication/pdfadminfecha_inicio, fecha_fin
GET /stats/reporte-ventas/xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheetadminfecha_inicio, fecha_fin
GET /stats/reporte-gastos/pdfapplication/pdfadminfecha_inicio, fecha_fin
GET /stats/reporte-gastos/xlsxXLSXadminfecha_inicio, fecha_fin
GET /stats/reporte-productos/pdfapplication/pdfadmincategoria_id, disponible
GET /stats/reporte-productos/xlsxXLSXadmincategoria_id, disponible
GET /stats/reporte-pedidos/pdfapplication/pdfadminestado_id, fecha_inicio, fecha_fin
GET /stats/reporte-pedidos/xlsxXLSXadminestado_id, fecha_inicio, fecha_fin
GET /stats/reporte-inventario/pdfapplication/pdfadminnone
GET /stats/reporte-inventario/xlsxXLSXadminnone
GET /stats/reporte-historial/pdfapplication/pdfadminfecha_inicio, fecha_fin
GET /stats/reporte-historial/xlsxXLSXadminfecha_inicio, fecha_fin

Report filter parameters

Date range filters (fecha_inicio, fecha_fin)
Both are optional ISO date strings (YYYY-MM-DD). When omitted, the report includes all records with no date boundary. Applied as inclusive >= / <= comparisons against the relevant date column.
Products filters
categoria_id
integer
Filter the products report to a single category ID. Omit to include all categories.
disponible
boolean
Filter the products report by availability (true = available, false = unavailable). Omit to include both.
Orders filter
estado_id
integer
Filter the orders report to a single order status by its internal ID. Omit to include all statuses.

XLSX multi-sheet reports

The historial XLSX report (GET /stats/reporte-historial/xlsx) generates a workbook with three separate sheets:
Sheet nameContents
PedidosRecent orders: ID, mesa, estado, fecha
VentasRecent sales: ID, pedido, monto, fecha
GastosRecent expenses: ID, descripción, monto, fecha
All other XLSX reports contain a single sheet. Column widths are auto-fitted based on content, capped at 30 characters wide.

PDF report structure

PDF reports are generated with ReportLab using US Letter-size pages (8.5” × 11”). Each report includes:
  • A bold title (e.g. "Reporte de Ventas - Cafetería")
  • A generation timestamp ("Generado: YYYY-MM-DD HH:MM")
  • Applied date filter range (when applicable)
  • A styled table with grey header row and black cell borders
  • A totals row at the bottom (for sales and expenses reports)

Download example

# Download a monthly sales report as PDF
curl "http://localhost:8000/stats/reporte-ventas/pdf?fecha_inicio=2024-01-01&fecha_fin=2024-01-31" \
  -H "Authorization: Bearer <token>" \
  -o sales_january.pdf

# Download full inventory status as XLSX
curl "http://localhost:8000/stats/reporte-inventario/xlsx" \
  -H "Authorization: Bearer <token>" \
  -o inventory_snapshot.xlsx

# Download product report filtered to a specific category
curl "http://localhost:8000/stats/reporte-productos/xlsx?categoria_id=2&disponible=true" \
  -H "Authorization: Bearer <token>" \
  -o products_category2.xlsx

# Download activity history report filtered to a date range
curl "http://localhost:8000/stats/reporte-historial/pdf?fecha_inicio=2024-01-01&fecha_fin=2024-01-31" \
  -H "Authorization: Bearer <token>" \
  -o historial_january.pdf
All report endpoints are restricted to the admin role, regardless of whether the equivalent JSON endpoint allows caja or cocina. This ensures that exportable data copies remain under admin control.

Build docs developers (and LLMs) love