TheDocumentation 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.
/pedidos/ endpoints manage the full order lifecycle, from creation by a waiter through kitchen preparation to payment. An order moves through a strict state machine — invalid transitions are rejected by the API — and when an order is marked as listo, ingredient stock is automatically deducted based on each product’s recipe. All authenticated users can read orders; creating orders requires the mesero or admin role; deleting cancelled orders requires admin.
GET /pedidos/estados — List Order States
Required role: Any authenticated user Returns the complete list of order states configured in the system. Use the returned IDs as values forid_estado_nuevo in state transitions and as the estado_id filter in the list endpoint.
Response
Unique state identifier. Pass this as
id_estado_nuevo when transitioning an order.Internal state name. One of:
"pendiente", "en_preparacion", "listo", "entregado", "pagado", "cancelado".Human-readable description of the state. May be
null.Example
Error codes
| Status | Detail |
|---|---|
401 | Token missing or expired |
GET /pedidos/cola-cocina — Kitchen Queue
Required role: Any authenticated user Returns all orders currently in thependiente or en_preparacion states, ordered oldest-first (created_at ASC). This endpoint is the primary data source for kitchen display systems and cook-facing interfaces — it shows only the orders that need active attention, in the order they were received.
Response
Returns an array ofOrderOut objects. See OrderOut schema below.
Example
Error codes
| Status | Detail |
|---|---|
401 | Token missing or expired |
GET /pedidos/ — List Orders with Filters
Required role: Any authenticated user Returns a list of orders with optional filtering and pagination. Results are ordered newest-first (id DESC). Multiple query parameters can be combined. The total field in each order is computed server-side as the sum of all line item subtotals (precio_unitario × cantidad).
Query Parameters
Filter to orders in this specific state. Use IDs from
GET /pedidos/estados.Filter to orders placed at this table ID.
ISO 8601 start date (inclusive). Orders created on or after this date are included. Example:
"2024-06-01" or "2024-06-01T08:00:00".ISO 8601 end date (inclusive). Internally the API adds one day to make the filter inclusive of the entire end date. Example:
"2024-06-10".Search term. If the value is numeric, filters by exact order
id. Otherwise performs a case-insensitive match against table number (mesa.numero).Maximum number of results to return. Used for pagination.
Number of results to skip before returning. Used for pagination. Combine with
limit for page-based navigation.Response
Returns an array ofOrderOut objects with computed total fields. See OrderOut schema below.
Example
Error codes
| Status | Detail |
|---|---|
401 | Token missing or expired |
500 | Unexpected internal error — detail includes exception type and message |
GET /pedidos/ — Get Single Order
Required role: Any authenticated user Retrieves a single order by ID with its full details array and computedtotal. This is the primary endpoint for polling order status and for rendering the order detail view.
Path Parameters
The unique ID of the order to retrieve.
Response
Returns a singleOrderOut object with a computed total. See OrderOut schema below.
Example
Error codes
| Status | Detail |
|---|---|
404 | "Pedido no encontrado" — no order with the given ID exists |
401 | Token missing or expired |
POST /pedidos/ — Create Order
Required role:mesero, admin
Creates a new order. The waiter’s identity (id_mesero) is extracted automatically from the JWT token — it is not accepted as a request body field. The order is created in pendiente state. Each product in detalles must be currently available (disponible == true); the price at the time of ordering is captured and stored in precio_unitario.
Request Body
ID of the table placing the order. Must correspond to an existing table.
One or more order line items. Must contain at least one item.
Response
Returns the newly createdOrderOut object with HTTP 201 Created. The response includes the full detalles array with precio_unitario values captured at time of order. See OrderOut schema below.
Example
Error codes
| Status | Detail |
|---|---|
400 | "Mesa no encontrada" — the given id_mesa does not exist |
400 | "Producto ID {id} no existe" — one of the product IDs is invalid |
400 | "Producto '{nombre}' no está disponible" — the product exists but disponible == false |
500 | "Estado 'pendiente' no configurado en BD" — system configuration error |
401 | Token missing or expired |
403 | User role is not mesero or admin |
PATCH /pedidos//estado — Transition Order State
Required role: Any authenticated user Transitions an order from its current state to a new state. The API enforces a strict transition table — requests that violate allowed transitions are rejected.cancelado is always permitted from any non-terminal state as an escape hatch.
When transitioning to listo, the API automatically calls descontar_ingredientes(), which deducts each ingredient’s stock_actual by (quantity_ordered × cantidad_por_unidad) for all products in the order. Every transition is recorded in the OrderStatusHistory table.
Path Parameters
The unique ID of the order to transition.
Request Body
The ID of the target state. Retrieve valid state IDs from
GET /pedidos/estados.Valid State Transitions
| Current state | Allowed next states |
|---|---|
pendiente | en_preparacion, cancelado |
en_preparacion | listo, cancelado |
listo | entregado, pagado, cancelado |
entregado | pagado |
pagado | (terminal — no further transitions allowed) |
cancelado | (terminal — no further transitions allowed) |
Transitioning to
listo triggers automatic ingredient stock deduction via descontar_ingredientes(). If any ingredient has insufficient stock, the transition is rejected with a 400 error and the order state is not changed. Ensure your ingredient recipes are accurate before advancing orders to this state, as successful deductions cannot be automatically reversed.Response
Returns the updatedOrderOut object reflecting the new state. The updated_at field is refreshed to the current server timestamp. See OrderOut schema below.
Example
Error codes
| Status | Detail |
|---|---|
400 | "No se puede cambiar de '{actual}' a '{nuevo}'" — transition not allowed by the state machine |
400 | "Estado destino no válido" — the id_estado_nuevo value does not correspond to any state |
400 | "Stock insuficiente para '{nombre}'. Disponible: {n} {unidad}, Necesario: {n} {unidad}" — raised when transitioning to listo and an ingredient has insufficient stock; order state is unchanged |
404 | "Pedido no encontrado" |
401 | Token missing or expired |
DELETE /pedidos/ — Delete Cancelled Order
Required role:admin
Permanently deletes an order. For data integrity, only orders in the cancelado state can be deleted. Additionally, if the order has an associated sale record (created when the order was pagado), the deletion is blocked by a database integrity constraint.
Returns HTTP 204 No Content on success.
Path Parameters
The unique ID of the order to delete. The order must be in
cancelado state.Example
204 No Content with an empty body.
Error codes
| Status | Detail |
|---|---|
400 | "Solo se pueden eliminar pedidos cancelados" — order is not in cancelado state |
400 | "No se puede eliminar el pedido porque tiene una venta asociada." — database integrity block |
404 | "Pedido no encontrado" |
401 | Token missing or expired |
403 | Authenticated user is not admin |
GET /pedidos//ticket/pdf — Generate PDF Ticket
Required role:admin, caja, mesero
Generates and returns a PDF receipt for the specified order. The PDF is built with ReportLab and includes an order header (order number, table number, date/time) and a formatted line-item table with columns for quantity, product name, unit price, and subtotal, followed by the order total. A ¡Gracias por su visita! footer is appended.
The response is a binary PDF stream — not a JSON object. Clients should handle it as a file download.
Path Parameters
The unique ID of the order for which to generate a ticket.
Response Headers
| Header | Value |
|---|---|
Content-Type | application/pdf |
Content-Disposition | attachment; filename=ticket_pedido_{id}.pdf |
PDF Contents
The generated PDF includes:- Title —
"CafeteriaPM - Ticket de Venta" - Order header —
Pedido #{id} | Mesa {numero} | Fecha: {DD/MM/YYYY HH:MM} - Line-item table with columns:
Cant,Producto,Precio,Subtotal - Total row — bolded summary row at the bottom of the table
- Footer —
"¡Gracias por su visita!"
Example
Error codes
| Status | Detail |
|---|---|
404 | "Pedido no encontrado" |
401 | Token missing or expired |
403 | User role is not admin, caja, or mesero |
OrderOut Response Shape
All order endpoints returnOrderOut objects. The total field is computed server-side and not stored in the database — it is recalculated on every read as the sum of (precio_unitario × cantidad) across all detalles. The current state is accessible via the nested estado_actual object.
Auto-incremented unique identifier for the order.
ID of the table this order belongs to.
Nested table object.
ID of the waiter who created the order. Taken from JWT at order creation time.
The current state of the order.
Array of order line items.
Computed order total: the sum of
precio_unitario × cantidad across all line items. Always 0.0 if detalles is empty.ISO 8601 timestamp of when the order was created.
ISO 8601 timestamp of the most recent state transition. Updated automatically by
PATCH /pedidos/{id}/estado.