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 /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 for id_estado_nuevo in state transitions and as the estado_id filter in the list endpoint.

Response

id
integer
required
Unique state identifier. Pass this as id_estado_nuevo when transitioning an order.
nombre
string
required
Internal state name. One of: "pendiente", "en_preparacion", "listo", "entregado", "pagado", "cancelado".
descripcion
string
Human-readable description of the state. May be null.

Example

curl -X GET "https://api.cafeteriapm.com/pedidos/estados" \
  -H "Authorization: Bearer <token>"
[
  { "id": 1, "nombre": "pendiente",       "descripcion": "Pedido recibido, esperando cocina" },
  { "id": 2, "nombre": "en_preparacion",  "descripcion": "Cocina preparando el pedido" },
  { "id": 3, "nombre": "listo",           "descripcion": "Listo para entregar" },
  { "id": 4, "nombre": "entregado",       "descripcion": "Entregado al cliente" },
  { "id": 5, "nombre": "pagado",          "descripcion": "Cobrado y cerrado" },
  { "id": 6, "nombre": "cancelado",       "descripcion": "Pedido cancelado" }
]

Error codes

StatusDetail
401Token missing or expired

GET /pedidos/cola-cocina — Kitchen Queue

Required role: Any authenticated user Returns all orders currently in the pendiente 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 of OrderOut objects. See OrderOut schema below.

Example

curl -X GET "https://api.cafeteriapm.com/pedidos/cola-cocina" \
  -H "Authorization: Bearer <token>"
[
  {
    "id": 42,
    "id_mesa": 3,
    "mesa": { "id": 3, "numero": 3, "capacidad": 4 },
    "id_mesero": 7,
    "estado_actual": { "id": 1, "nombre": "pendiente" },
    "detalles": [
      {
        "id": 101,
        "id_producto": 1,
        "cantidad": 2,
        "precio_unitario": 25.0,
        "subtotal": 50.0,
        "observaciones": ["sin azúcar"]
      }
    ],
    "total": 50.0,
    "created_at": "2024-06-10T12:05:00",
    "updated_at": "2024-06-10T12:05:00"
  }
]

Error codes

StatusDetail
401Token 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

estado_id
integer
Filter to orders in this specific state. Use IDs from GET /pedidos/estados.
mesa_id
integer
Filter to orders placed at this table ID.
fecha_inicio
string
ISO 8601 start date (inclusive). Orders created on or after this date are included. Example: "2024-06-01" or "2024-06-01T08:00:00".
fecha_fin
string
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".
busqueda
string
Search term. If the value is numeric, filters by exact order id. Otherwise performs a case-insensitive match against table number (mesa.numero).
limit
integer
Maximum number of results to return. Used for pagination.
offset
integer
Number of results to skip before returning. Used for pagination. Combine with limit for page-based navigation.

Response

Returns an array of OrderOut objects with computed total fields. See OrderOut schema below.

Example

# Get the 10 most recent orders at table 3
curl -X GET "https://api.cafeteriapm.com/pedidos/?mesa_id=3&limit=10&offset=0" \
  -H "Authorization: Bearer <token>"

# Get all paid orders on June 10th
curl -X GET "https://api.cafeteriapm.com/pedidos/?estado_id=5&fecha_inicio=2024-06-10&fecha_fin=2024-06-10" \
  -H "Authorization: Bearer <token>"

Error codes

StatusDetail
401Token missing or expired
500Unexpected 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 computed total. This is the primary endpoint for polling order status and for rendering the order detail view.

Path Parameters

pedido_id
integer
required
The unique ID of the order to retrieve.

Response

Returns a single OrderOut object with a computed total. See OrderOut schema below.

Example

curl -X GET "https://api.cafeteriapm.com/pedidos/42" \
  -H "Authorization: Bearer <token>"

Error codes

StatusDetail
404"Pedido no encontrado" — no order with the given ID exists
401Token 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_mesa
integer
required
ID of the table placing the order. Must correspond to an existing table.
detalles
array
required
One or more order line items. Must contain at least one item.

Response

Returns the newly created OrderOut 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

curl -X POST "https://api.cafeteriapm.com/pedidos/" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "id_mesa": 3,
    "detalles": [
      {
        "id_producto": 1,
        "cantidad": 2,
        "observacion": "sin azúcar"
      },
      {
        "id_producto": 5,
        "cantidad": 1
      }
    ]
  }'
{
  "id": 43,
  "id_mesa": 3,
  "mesa": { "id": 3, "numero": 3, "capacidad": 4 },
  "id_mesero": 7,
  "estado_actual": { "id": 1, "nombre": "pendiente" },
  "detalles": [
    {
      "id": 103,
      "id_producto": 1,
      "cantidad": 2,
      "precio_unitario": 25.0,
      "subtotal": null,
      "observaciones": ["sin azúcar"]
    },
    {
      "id": 104,
      "id_producto": 5,
      "cantidad": 1,
      "precio_unitario": 45.0,
      "subtotal": null,
      "observaciones": []
    }
  ],
  "total": 0.0,
  "created_at": "2024-06-10T13:00:00",
  "updated_at": "2024-06-10T13:00:00"
}

Error codes

StatusDetail
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
401Token missing or expired
403User 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

pedido_id
integer
required
The unique ID of the order to transition.

Request Body

id_estado_nuevo
integer
required
The ID of the target state. Retrieve valid state IDs from GET /pedidos/estados.

Valid State Transitions

Current stateAllowed next states
pendienteen_preparacion, cancelado
en_preparacionlisto, cancelado
listoentregado, pagado, cancelado
entregadopagado
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 updated OrderOut object reflecting the new state. The updated_at field is refreshed to the current server timestamp. See OrderOut schema below.

Example

# Kitchen accepts an order — move from pendiente to en_preparacion
curl -X PATCH "https://api.cafeteriapm.com/pedidos/43/estado" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"id_estado_nuevo": 2}'

# Kitchen marks order ready — triggers stock deduction
curl -X PATCH "https://api.cafeteriapm.com/pedidos/43/estado" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"id_estado_nuevo": 3}'

Error codes

StatusDetail
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"
401Token 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

pedido_id
integer
required
The unique ID of the order to delete. The order must be in cancelado state.

Example

curl -X DELETE "https://api.cafeteriapm.com/pedidos/43" \
  -H "Authorization: Bearer <token>"
A successful response returns HTTP 204 No Content with an empty body.

Error codes

StatusDetail
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"
401Token missing or expired
403Authenticated 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

pedido_id
integer
required
The unique ID of the order for which to generate a ticket.

Response Headers

HeaderValue
Content-Typeapplication/pdf
Content-Dispositionattachment; filename=ticket_pedido_{id}.pdf

PDF Contents

The generated PDF includes:
  1. Title"CafeteriaPM - Ticket de Venta"
  2. Order headerPedido #{id} | Mesa {numero} | Fecha: {DD/MM/YYYY HH:MM}
  3. Line-item table with columns: Cant, Producto, Precio, Subtotal
  4. Total row — bolded summary row at the bottom of the table
  5. Footer"¡Gracias por su visita!"

Example

# Download the PDF ticket for order 43
curl -X GET "https://api.cafeteriapm.com/pedidos/43/ticket/pdf" \
  -H "Authorization: Bearer <token>" \
  --output ticket_pedido_43.pdf

Error codes

StatusDetail
404"Pedido no encontrado"
401Token missing or expired
403User role is not admin, caja, or mesero

OrderOut Response Shape

All order endpoints return OrderOut 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.
id
integer
required
Auto-incremented unique identifier for the order.
id_mesa
integer
required
ID of the table this order belongs to.
mesa
object
Nested table object.
id_mesero
integer
required
ID of the waiter who created the order. Taken from JWT at order creation time.
mesero
object
Nested UserOut object for the waiter. See the Users API for the full UserOut shape.
estado_actual
object
required
The current state of the order.
detalles
array
required
Array of order line items.
total
float
required
Computed order total: the sum of precio_unitario × cantidad across all line items. Always 0.0 if detalles is empty.
created_at
datetime
required
ISO 8601 timestamp of when the order was created.
updated_at
datetime
required
ISO 8601 timestamp of the most recent state transition. Updated automatically by PATCH /pedidos/{id}/estado.

Build docs developers (and LLMs) love