Skip to main content

Production Orders API

The Production Orders API manages manufacturing orders throughout their lifecycle, from creation to closure. It supports both manual entry and bulk import from SAP.

Authentication

All write endpoints require MANAGE_PRODUCTION permission. Read endpoints require authentication but no specific permission.

Get All Orders

GET /api/ordenes-produccion
Returns all production orders, ordered by creation date descending.

Response

Array of production order objects.
id
integer
Production order ID
numero_orden
string
Order number (internal or SAP)
descripcion
string
Product description
cantidad_objetivo
number
Target production quantity
unidad
string
Production unit (kg, m, unidades, etc.)
estado
string
Order state: PENDIENTE, EN_PROCESO, COMPLETADA, CANCELADA
codigo_sap
string
SAP material code (null for manual orders)
proceso
string
Target production process name
fecha_creacion
string
ISO timestamp of order creation

Example Request

cURL
curl -X GET https://api.example.com/api/ordenes-produccion \
  -H "Authorization: Bearer <token>"

Example Response

{
  "success": true,
  "data": [
    {
      "id": 12345,
      "numero_orden": "OP-2026-001",
      "descripcion": "Tela PP 105cm x 10x10",
      "cantidad_objetivo": 5000,
      "unidad": "m",
      "estado": "EN_PROCESO",
      "codigo_sap": "MAT-105-1010",
      "proceso": "Telares",
      "fecha_creacion": "2026-03-01T08:00:00Z"
    }
  ]
}

Get Order by ID

GET /api/ordenes-produccion/:id
Returns detailed information for a specific order.

Path Parameters

id
integer
required
Production order ID

Response

Single production order object with same fields as GET all.

Error Responses

404 Not Found
{
  "success": false,
  "error": "Orden de producción no encontrada."
}

Create Order

POST /api/ordenes-produccion
Permission: MANAGE_PRODUCTION Creates a new production order manually.

Request Body

numero_orden
string
required
Unique order number
descripcion
string
required
Product description
cantidad_objetivo
number
required
Target quantity (must be positive)
unidad
string
required
Unit of measure
proceso
string
required
Production process name (must match valid process)
codigo_sap
string
SAP material code (optional)

Example Request

cURL
curl -X POST https://api.example.com/api/ordenes-produccion \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "numero_orden": "OP-2026-002",
    "descripcion": "Bolsa 50kg Laminada",
    "cantidad_objetivo": 10000,
    "unidad": "unidades",
    "proceso": "Conversión",
    "codigo_sap": "BAG-50-LAM"
  }'

Example Response

{
  "success": true,
  "data": {
    "id": 12346,
    "numero_orden": "OP-2026-002",
    "estado": "PENDIENTE",
    "fecha_creacion": "2026-03-06T10:30:00Z"
  }
}

Update Order

PUT /api/ordenes-produccion/:id
Permission: MANAGE_PRODUCTION Updates an existing production order.

Path Parameters

id
integer
required
Production order ID

Request Body

Same fields as create, all optional. Only provided fields are updated.
Cannot update orders in COMPLETADA or CANCELADA states.

Delete Order

DELETE /api/ordenes-produccion/:id
Permission: MANAGE_PRODUCTION Deletes a production order.

Path Parameters

id
integer
required
Production order ID

Business Rules

  • Cannot delete orders with production history (lineas_ejecucion records)
  • Only PENDIENTE orders can be safely deleted
  • Consider changing state to CANCELADA instead

SAP Import - Preview

POST /api/ordenes-produccion/importar/previsualizar
Permission: MANAGE_PRODUCTION Content-Type: multipart/form-data Uploads an Excel file from SAP and returns parsed orders for preview before confirmation.

Request Body

archivo
file
required
Excel file (.xlsx) from SAP exportMaximum file size: 10 MB

Expected Excel Format

From ordenProduccion.parser.js:30:
ColumnDescriptionRequired
Orden de fabricaciónOrder numberYes
Texto breveProduct descriptionYes
MaterialSAP material codeYes
Cantidad objetivo / Cantidad de entradaTarget quantityYes
UnMedUnit of measureYes

Response

ordenes
array
Parsed orders ready for confirmation
errores
array
Validation errors (if any)
advertencias
array
Warnings about potential issues

Example Request

cURL
curl -X POST https://api.example.com/api/ordenes-produccion/importar/previsualizar \
  -H "Authorization: Bearer <token>" \
  -F "archivo=@ordenes_sap.xlsx"

Example Response

{
  "success": true,
  "data": {
    "ordenes": [
      {
        "numero_orden": "1000012345",
        "descripcion": "TELA PP 105CM 10X10",
        "cantidad_objetivo": 5000,
        "unidad": "M",
        "codigo_sap": "100123456",
        "proceso": "Telares"
      },
      {
        "numero_orden": "1000012346",
        "descripcion": "BOLSA 50KG LAMINADA",
        "cantidad_objetivo": 10000,
        "unidad": "ST",
        "codigo_sap": "100123457",
        "proceso": "Conversión"
      }
    ],
    "errores": [],
    "advertencias": [
      "Orden 1000012345 ya existe en el sistema (será omitida al confirmar)"
    ]
  }
}

SAP Import - Confirm

POST /api/ordenes-produccion/importar/confirmar
Permission: MANAGE_PRODUCTION Confirms and imports the previewed orders into the system.

Request Body

ordenes
array
required
Array of orders returned from preview endpoint

Response

insertadas
integer
Number of orders successfully inserted
omitidas
integer
Number of orders skipped (duplicates)
errores
array
Any errors during insertion

Example Request

cURL
curl -X POST https://api.example.com/api/ordenes-produccion/importar/confirmar \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "ordenes": [
      {
        "numero_orden": "1000012346",
        "descripcion": "BOLSA 50KG LAMINADA",
        "cantidad_objetivo": 10000,
        "unidad": "ST",
        "codigo_sap": "100123457",
        "proceso": "Conversión"
      }
    ]
  }'

Example Response

{
  "success": true,
  "data": {
    "insertadas": 1,
    "omitidas": 0,
    "errores": []
  }
}

Process Mapping Logic

From ordenProduccion.parser.js:90, the system automatically maps SAP material codes to production processes:
function inferirProceso(codigoSAP, descripcion) {
  const codigo = codigoSAP.toLowerCase();
  const desc = descripcion.toLowerCase();

  // Extrusor PP: códigos que inician con 101 o 102
  if (codigo.startsWith('101') || codigo.startsWith('102')) return 'Extrusor PP';

  // Telares: descripción contiene "tela"
  if (desc.includes('tela')) return 'Telares';

  // Laminado: descripción contiene "laminad"
  if (desc.includes('laminad')) return 'Laminado';

  // Impresión: descripción contiene "impr"
  if (desc.includes('impr')) return 'Impresión';

  // Conversión: bolsas sin liner
  if (desc.includes('bolsa') && !desc.includes('liner') && !desc.includes('vest')) return 'Conversión';

  // Vestidos: bolsas vestidas
  if (desc.includes('vest')) return 'Vestidos';

  // Liner PE: "liner" o códigos 108
  if (desc.includes('liner') || codigo.startsWith('108')) return 'Liner PE';

  return 'Conversión'; // Default
}
Custom Mapping: If your SAP codes don’t match the default patterns, you can manually edit the proceso field after preview.

Order State Machine

State Transitions:
  • PENDIENTEEN_PROCESO: Automatically when first production is recorded
  • EN_PROCESOCOMPLETADA: When total production ≥ target quantity
  • *CANCELADA: Manual cancellation (requires justification)

Best Practices

Batch Import: Use the SAP import endpoints for efficient bulk order creation. This maintains consistency and reduces manual errors.
Duplicate Detection: The system checks for duplicate order numbers. Duplicates are flagged in preview and skipped during confirmation.
Process Validation: Ensure the inferred process is correct during preview. Incorrect process assignment can cause workflow issues.

Build docs developers (and LLMs) love