Skip to main content

Overview

The Orders API handles order creation, tracking, status management, and PDF report generation. It includes automatic stock validation and email notifications. Base URL: /api/pedidos Source: PedidoController.java

Authentication

  • Customer endpoints: Create, view own orders - requires authentication
  • Admin endpoints: List all, update status, delete, PDF reports - requires ROLE_ADMIN

Order States

Orders progress through the following states:
  • PENDIENTE - Order placed, awaiting payment
  • PAGADO - Payment confirmed
  • ENVIADO - Order shipped
  • ENTREGADO - Order delivered
  • CANCELADO - Order cancelled (stock restored)

Endpoints

Create Order

POST /api/pedidos
Create a new order. The system automatically calculates the total, validates stock availability, and deducts stock from products. Authentication: Required (any authenticated user) Request Body:
usuario
object
required
User object with id field
detalles
array
required
Array of order detail objects
direccionEnvio
string
Shipping address (optional, can use user’s default address)
Example Request:
cURL
curl -X POST http://localhost:8080/api/pedidos \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "usuario": {"id": 5},
    "direccionEnvio": "123 Main St, City",
    "detalles": [
      {
        "producto": {"id": 1},
        "cantidad": 2,
        "precio": 1299.99
      },
      {
        "producto": {"id": 3},
        "cantidad": 1,
        "precio": 49.99
      }
    ]
  }'
Response: 201 Created
id
long
Order ID
usuario
object
User object
total
double
Calculated order total (sum of precio * cantidad for all details)
estado
string
Order status (initially “PENDIENTE”)
fechaPedido
datetime
Timestamp of order creation
detalles
array
Array of order detail objects with product, cantidad, precio
Error Responses:
  • 400 Bad Request - Stock insufficient or user not found
    "Stock insuficiente para el producto: Laptop Dell XPS 15"
    
  • 500 Internal Server Error - Server error
The createPedido service method automatically:
  • Validates stock availability for each product
  • Deducts ordered quantities from product stock
  • Calculates the total amount
  • Sets order state to “PENDIENTE”

Get Order by ID

GET /api/pedidos/{id}
Retrieve a specific order by ID. Authentication: Required
id
long
required
Order ID
Responses:
  • 200 OK - Order object with user, detalles, and calculated total
  • 404 Not Found - Order does not exist

List Orders by User

GET /api/pedidos/usuario/{usuarioId}
Retrieve all orders for a specific user (order history). Authentication: Required
usuarioId
long
required
User ID
Response: 200 OK - Array of order objects Example Request:
cURL
curl -X GET http://localhost:8080/api/pedidos/usuario/5 \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
Use this endpoint to display a customer’s order history page.

List All Orders (Admin)

GET /api/pedidos
Retrieve all orders in the system. Authentication: Required - ROLE_ADMIN Response: 200 OK - Array of all order objects Use Case: Admin dashboard to view and manage all customer orders.

Update Order Status

PUT /api/pedidos/{id}/estado?nuevoEstado={estado}
Update the status of an order. Authentication: Required - ROLE_ADMIN
id
long
required
Order ID
nuevoEstado
string
required
New order status: PENDIENTE, PAGADO, ENVIADO, ENTREGADO, or CANCELADO
Response: 200 OK - Updated order object Example Request:
cURL
curl -X PUT "http://localhost:8080/api/pedidos/42/estado?nuevoEstado=ENVIADO" \
  -H "Authorization: Bearer ADMIN_JWT_TOKEN"
Cancelling an order (CANCELADO state) automatically restores the stock for all products in the order.

Generate PDF Report

POST /api/pedidos/reporte/pdf
Generate a PDF sales report for a filtered list of orders. Authentication: Required - ROLE_ADMIN Request Body: Array of order objects (filtered by date, status, etc.) Response: 200 OK - Binary PDF file Headers:
  • Content-Type: application/pdf
  • Content-Disposition: attachment; filename="reporte-ventas.pdf"
Example Request:
JavaScript
async function downloadSalesReport(orders, token) {
  const response = await fetch('http://localhost:8080/api/pedidos/reporte/pdf', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(orders)
  });
  
  const blob = await response.blob();
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'reporte-ventas.pdf';
  a.click();
}
The PDF generation uses the OpenPDF library (version 1.3.30). The report includes order details, totals, and summary statistics.

Delete Order

DELETE /api/pedidos/{id}
Delete an order from the system. Authentication: Required - ROLE_ADMIN
id
long
required
Order ID
Responses:
  • 200 OK - “Pedido eliminado correctamente”
  • 500 Internal Server Error - “Error al eliminar el pedido”

Order Workflow

1

Customer Creates Order

Customer adds items to cart and proceeds to checkout. The cart is converted to an order via POST /api/pedidos.
2

Stock Validation

System validates that sufficient stock exists for each product. If stock is insufficient, the order is rejected with a 400 error.
3

Stock Deduction

Upon successful validation, the ordered quantities are deducted from product stock.
4

Order Processing

Admin reviews the order and updates status: PENDIENTEPAGADOENVIADOENTREGADO.
5

Email Notification

Customer receives email confirmation at each status change.

Integration Examples

Customer: Place Order

JavaScript
async function placeOrder(userId, items, address, token) {
  const orderData = {
    usuario: { id: userId },
    direccionEnvio: address,
    detalles: items.map(item => ({
      producto: { id: item.productId },
      cantidad: item.quantity,
      precio: item.price
    }))
  };
  
  try {
    const response = await fetch('http://localhost:8080/api/pedidos', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(orderData)
    });
    
    if (response.ok) {
      const order = await response.json();
      console.log('Order created:', order.id);
      return order;
    } else {
      const error = await response.text();
      console.error('Order failed:', error);
    }
  } catch (error) {
    console.error('Error placing order:', error);
  }
}

Admin: Update Order Status

JavaScript
async function updateOrderStatus(orderId, newStatus, token) {
  const response = await fetch(
    `http://localhost:8080/api/pedidos/${orderId}/estado?nuevoEstado=${newStatus}`,
    {
      method: 'PUT',
      headers: { 'Authorization': `Bearer ${token}` }
    }
  );
  
  return response.json();
}

// Usage
await updateOrderStatus(42, 'ENVIADO', adminToken);

Error Handling

Status CodeScenarioSolution
400 Bad RequestInsufficient stockReduce order quantity or restock product
400 Bad RequestUser not foundVerify user ID exists
401 UnauthorizedMissing/invalid tokenRe-authenticate user
403 ForbiddenNon-admin accessing admin endpointsCheck user role
404 Not FoundOrder does not existVerify order ID
500 Internal Server ErrorDatabase or service errorCheck server logs

Cart API

Convert cart to order

Products API

Manage product stock

Users API

Manage customer accounts

Build docs developers (and LLMs) love