Casi todo lo que haces dentro de StockAI también se puede hacer por API: subir ventas, entrenar y leer el pronóstico, leer el semáforo, registrar órdenes, administrar proveedores y bodegas. Así puedes conectarlo a tu ERP, tu POS o cualquier sistema propio. Y con el servidor MCP, Claude, ChatGPT o tu asistente de IA lo hace conversando contigo.
Cada llamada lleva una API key en la cabecera Authorization. Las claves se crean en la app, en Automatización → API Keys, y se muestran una sola vez: StockAI guarda solo un hash.
Una clave actúa como sí misma, no como la persona que la creó: sigue funcionando si esa persona deja la empresa.
Claves de lectura y de escritura
Al crear una clave eliges qué puede hacer. Cada endpoint de la referencia dice qué tipo de clave necesita.
Lectura
Lee todo lo que un usuario visor ve: semáforo, pronósticos, proveedores, órdenes, reportes.
Lectura y escritura
Además crea y modifica, como un analista: sube archivos, entrena, registra órdenes, edita inventario y proveedores.
Una clave de lectura que intenta escribir recibe 403 con error_code api_key_scope_insufficient, y no cambia nada.
Lo que una clave nunca puede hacer
Algunas acciones son de personas, no de sistemas. Con una API key responden 403 api_key_route_not_exposed:
Iniciar sesión, refrescar tokens o recuperar contraseñas.
Crear, invitar o modificar usuarios y sus permisos.
Crear, listar o revocar API keys: una clave no puede crear otra.
Configurar la instalación o los canales de la cuenta.
Exportar o borrar la cuenta.
Lo que es de una persona: su bandeja de mensajes, sus conversaciones con el asistente, sus preferencias.
Lo que solo un administrador puede hacer (por ejemplo, cambiar la moneda o el período activo).
Enviar una orden o una alerta por correo o WhatsApp con una clave de escritura exige que la cuenta tenga al menos un administrador con el correo verificado (si no: 403 api_key_tenant_unverified).
Límites
Autenticación
/ min
120 llamadas por minuto por clave.
API
La API y el servidor MCP vienen con los planes Pro, Max y Corporativo; el plan Gratis no los incluye.
Al pasarte recibes 429 con la cabecera Retry-After (segundos). El mismo 429 sirve para el límite por minuto y para el tope diario, y su cuerpo no trae error_code.
No hay cabeceras X-RateLimit-*: la única señal es el 429 con Retry-After. Cuenta tus llamadas o espera el 429.
Medición y compra
La API viene con los planes Pro (2.000 llamadas al día por clave), Max (20.000) y Corporativo (sin tope diario). Contamos cada llamada con una API key que llegó a un endpoint, por día (UTC) y por clave; las rechazadas (clave inválida, sin permiso o por encima del límite) no cuentan. Un administrador ve el consumo del mes en la app, en la pantalla API.
Casi todo error trae un error_code estable y, si aplica, error_params con los valores: ramifica por el código, no por el texto de detail, que es una ayuda en inglés y puede cambiar. Las respuestas del propio framework (cabecera ausente, ruta inexistente, método incorrecto) y el 429 solo traen detail.
api_key_invalid
401 la clave no existe, fue revocada o venció.
api_key_route_not_exposed
403 ese endpoint no se puede usar con una API key.
api_key_scope_insufficient
403 la clave es de lectura y el endpoint escribe.
api_key_tenant_unverified
403 enviar algo fuera de StockAI exige un administrador verificado.
validation_error
422 el cuerpo o los parámetros no son válidos; detail es una lista con un objeto por campo.
PLAN_LIMIT_REACHED
403 llegaste a un tope de uso; detail es un objeto y error_params dice cuál.
server_busy
503 el servidor está saturado; reintenta según Retry-After.
(sin error_code)
401 falta la cabecera Authorization o no es “Bearer sk_live_…”: detail es “Not authenticated”.
(sin error_code)
429 límite por minuto o tope diario: espera Retry-After segundos.
(sin error_code)
404 / 405 ruta inexistente o método no permitido.
La forma de detail
texto
La mayoría de los errores: una frase en inglés.
lista
422 validation_error: [{ type, loc, msg, input }], uno por campo inválido; loc dice dónde (por ejemplo ["body", "name"]).
objeto
PLAN_LIMIT_REACHED: { code, limit, current, max, tier }, el mismo contenido que error_params.
403 Ejemplo: clave de lectura que escribe
{"detail":"This endpoint writes and the API key is read-only. Use a write key.","error_code":"api_key_scope_insufficient","error_params":{"required_scope":"write","key_scope":"read"}}
El formato de respuesta
Toda respuesta JSON viene envuelta: { "success": true, "data": …, "meta": { "timestamp": … } }. Lo tuyo está en data, que según el endpoint es un objeto o una lista; los listados paginados traen la lista en data.items.
Los endpoints que devuelven un archivo (Excel, PDF, CSV) responden el archivo directamente, sin envoltorio.
El endpoint MCP (POST /mcp) habla JSON-RPC 2.0 y no usa este envoltorio.
Tipos y formatos
Fechas
Las fechas son YYYY-MM-DD; los instantes, ISO 8601 en UTC, por ejemplo 2026-10-01T08:00:00+00:00.
Números
Cantidades y montos son números JSON, no textos. Los montos van en la moneda de la cuenta (GET /tenant/currency).
Sin valor
Un campo sin valor suele llegar como null en lugar de omitirse.
Identificadores
Cadenas opacas con prefijo (sess_…, ds_…, sup_…): guárdalas tal cual.
Señales
El semáforo usa PEDIR_YA, PEDIR_PRONTO, OK y SOBRESTOCK: valores fijos que no se traducen.
Paginación
Hay tres formas, y cada endpoint la declara en sus parámetros:
skip y limit
Sesiones, resumen de sesiones, fuentes de datos y datasets. La respuesta trae items, total, skip y limit.
limit y offset
La actividad de alertas (/alerts/activity). La respuesta trae items, total, limit y offset.
solo limit
Los más recientes primero, hasta limit: alertas, historial de órdenes, brechas de configuración, mermas e historial de reentrenamientos.
sin paginación
El resto devuelve el conjunto completo y se acota con sus filtros, por ejemplo signal o supplier en /inventory/status.
Idempotencia
POST /inventory/log-po y POST /inventory/po aceptan la cabecera Idempotency-Key: un valor único (un UUID) por orden que quieres colocar. Si repites la petición con la misma clave recibes la orden que ya se creó (200 con replayed: true) en vez de una segunda; la misma clave con otras líneas responde 409 po_idempotency_key_reused. Los demás endpoints de escritura no son idempotentes: antes de reintentar una escritura cuyo resultado no viste, consulta si ya se aplicó.
StockAI se conecta a Claude, ChatGPT y cualquier asistente de IA que hable MCP (Model Context Protocol). Por esa conexión el asistente puede hacer lo mismo que la API, conversando contigo: decirte qué pedir, preparar y enviar órdenes de compra, revisar la precisión del pronóstico o lanzar un reentrenamiento. Los cambios los apruebas tú.
Servidor MCP
https://app.stockai.es/api/v1/mcp
Acceso
Inicias sesión con tu cuenta de StockAI (OAuth) o usas una API key
Herramientas
Alcanzan las 307 operaciones de la API21 de lectura8 de escritura
Lo que le puedes pedir
«¿Qué tengo que pedir hoy, y por qué?»
«Arma la orden para Distribuidora Andina con las cantidades sugeridas.»
«Envía la orden de Distribuidora Andina al proveedor.»
«¿Qué tan preciso fue el pronóstico del mes pasado?»
«¿Qué productos están en sobrestock y cuánto dinero tienen parado?»
«Reentrena el pronóstico con las ventas de esta semana.»
Cómo se protege tu cuenta
Leer o escribir
Con una credencial de lectura el asistente solo consulta. Para crear o cambiar algo necesita una de escritura: la misma regla que en la API.
Confirmación en lo destructivo
Una acción que no se deshace, como cancelar una orden, se rechaza si no llega con confirm: true. El asistente te pregunta antes de enviarla.
Medido y registrado
Cada llamada cuenta en el consumo de la API, con el mismo límite por minuto, y cada cambio queda en el registro de actividad de la cuenta.
Revocable
Retiras el acceso desde la app cuando quieras, y la siguiente llamada ya no entra.
Lo que nunca hace
Nada que una API key no pueda hacer: ni usuarios, ni llaves, ni la configuración de la instalación.
Planes
Viene con los planes Pro, Max y Corporativo, igual que la API.
Conecta tu cliente
La misma URL sirve para todos. Elige tu cliente:
En claude.ai abre Customize → Connectors, pulsa «+ Add» y elige «Add custom connector».
Ponle de nombre StockAI, pega la URL de abajo y pulsa «Add». No hace falta nada en «Advanced settings».
Pulsa «Connect» junto a StockAI. Claude te lleva a StockAI: entras con tu cuenta y apruebas el acceso.
Actívalo en un chat desde «+» → Connectors. En Claude Desktop aparece solo, porque los conectores van con tu cuenta de Claude.
URL
https://app.stockai.es/api/v1/mcp
En los planes Team y Enterprise de Claude, el conector lo agrega un Owner en Organization settings → Connectors; cada persona luego pulsa «Connect».
En ChatGPT, agrega un servidor MCP propio (custom MCP server). Según tu plan, primero tienes que activar el modo desarrollador en la configuración.
Pega la URL de abajo y elige OAuth como autenticación.
ChatGPT te lleva a StockAI: entras con tu cuenta y apruebas el acceso.
URL
https://app.stockai.es/api/v1/mcp
Los menús de ChatGPT cambian a menudo y dependen del plan; lo que no cambia es la URL y el inicio de sesión.
Con tu cuenta: agrega el servidor con el primer comando y escribe /mcp dentro de Claude Code. Se abre el navegador para entrar a StockAI y aprobar el acceso.
Con una API key: créala en Automatización → API Keys y pásala en la cabecera, como en el segundo comando.
shell · OAuth
claude mcp add --transport http stockai https://app.stockai.es/api/v1/mcp
# then, inside Claude Code, sign in:
/mcp
shell · API key
claude mcp add --transport http stockai https://app.stockai.es/api/v1/mcp \--header"Authorization: Bearer sk_live_…"
Si pasas la cabecera Authorization, Claude Code no intenta el inicio de sesión: usa una forma o la otra.
Abre ~/.cursor/mcp.json (para todos tus proyectos) o .cursor/mcp.json (para uno) y agrega el bloque de abajo.
Define la variable de entorno STOCKAI_API_KEY con tu llave: así la llave no queda escrita en el archivo.
Si prefieres entrar con tu cuenta, quita el bloque headers: Cursor te ofrece iniciar sesión en StockAI la primera vez.
Crea .vscode/mcp.json en tu proyecto con el bloque de abajo.
Al iniciar el servidor, VS Code te pide la llave una vez y la guarda cifrada: no queda en el archivo.
Usa las herramientas desde el chat de Copilot en modo agente.
.vscode/mcp.json
{"inputs":[{"type":"promptString","id":"stockai-key","description":"StockAI API key (sk_live_…)","password":true}],"servers":{"stockai":{"type":"http","url":"https://app.stockai.es/api/v1/mcp","headers":{"Authorization":"Bearer ${input:stockai-key}"}}}}
Un cliente que habla Streamable HTTP solo necesita la URL, y el inicio de sesión (OAuth 2.1) o la cabecera Authorization: Bearer sk_live_….
Un cliente que solo lanza procesos (stdio): copia mcp_server/stockai_mcp.py del código fuente de StockAI, un archivo de Python sin dependencias, y define STOCKAI_URL (la raíz de la instalación, sin /api/v1) y STOCKAI_API_KEY.
Para probar una llave a mano, el último ejemplo pide la lista de herramientas.
Streamable HTTP
URL https://app.stockai.es/api/v1/mcp
Transport Streamable HTTP(POST,JSON-RPC2.0)
Auth OAuth 2.1(sign in to StockAI)
or Authorization: Bearer sk_live_…
Transporte Streamable HTTP sin estado: cada mensaje es un POST con JSON-RPC 2.0 y la respuesta vuelve en el mismo POST. Un GET responde 405: el servidor no abre un flujo hacia el cliente.
Comparte con la API el límite por minuto y el tope diario, y responde 429 con Retry-After al pasarte.
Una herramienta que se niega responde con un error que el asistente puede leer, con su error_code, no con un fallo de transporte.
Revisión del protocolo: 2025-11-25, 2025-06-18, 2025-03-26, 2024-11-05.
Herramientas
Generada a partir del propio servidor: si una herramienta está aquí, tu asistente la ve. Las herramientas del grupo «Toda la API» buscan, describen y llaman cualquier operación de la referencia de endpoints. Las descripciones están en inglés, como el código.
29 herramientas: 21 de lectura y 8 de escritura (4 destructivas, piden confirmación).
Planificación 3
get_planning_contextLecturaStart here. Returns which forecast session is active, at what granularity (daily/weekly/monthly) and over how many periods the numbers in the other tools were computed. `active_session_id` is what the other tools accept as `session_id`; read it each time rather than storing it, because it changes when a new run trains.
get_morning_briefingLecturaThe day's purchasing work: the risks worth acting on, the reason behind each recommendation, the suggested supplier and the estimated value. This is the tool for "what should I buy today?"; get_inventory_status is for "what is the state of X?".
Argumentos
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
get_purchase_planLecturaThe purchase plan grouped by supplier, after the constraints are applied (MOQ, order multiples, joint replenishment, budget). Use it for "what should I order from each supplier?" — it returns what to buy per supplier with quantities and values, not the per-SKU traffic light.
Argumentos
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
window_daysintegeropcionalmín. 1máx. 90
How far ahead a product counts as 'needs ordering soon' when grouping a supplier's order.
get_inventory_statusLecturaThe stock traffic light for every product: what state it is in and how much to order.
Signals: PEDIR_YA (order now), PEDIR_PRONTO (order soon), OK, SOBRESTOCK (too much), SIN_DATOS (no stock on record — which means unknown, NOT safe).
Per row, `recommended_qty` is how much to order, `coverage_days` how long the stock lasts at the forecast rate, and `lead_time_source` / `unit_cost_source` / `moq_source` say where each assumption came from: `user` (typed into StockAI), `file` (their own export), `supplier_rule`, `learned` (from their receptions) or `default` (StockAI had nothing and assumed). Treat a `default` as an assumption when you report it, not as the customer's own figure.
Answers are capped and ordered by urgency; `summary` always counts the whole matching set, and `truncated` says when rows were left out. Filter with `signal` or `supplier` rather than raising `limit` when you can.
If a filter matches nothing the answer carries `empty_reason`. That is the filter finding nothing, NOT a catalogue with nothing to order — never report stock as fine on the strength of it.
Argumentos
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
signalenumopcional
Return only SKUs carrying this signal.
PEDIR_YAPEDIR_PRONTOOKSOBRESTOCKSIN_DATOS
supplierstringopcional
Return only SKUs whose supplier matches this name.
search_productsLecturaFind products in the stock catalogue by SKU, category or supplier text, with stock on hand, minimum, lead time, cost and supplier per row. Paged: `total` says how many matched. Use it to find the exact SKU code before calling a per-SKU tool.
get_sku_detailLecturaEverything about one SKU in one call: its traffic-light signal, coverage and recommended order quantity from the active forecast (`signal_and_recommendation`), and its stock record — on hand, minimum, lead time, cost, MOQ and supplier (`stock_record`). Use the exact SKU code (search_products finds it).
Argumentos
skustringobligatorio
The exact SKU code.
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
list_purchase_ordersLecturaThe tenant's purchase orders, newest first, with number, supplier, status, value, sent and reception state. Paged (`limit`/`offset`); filter by `status` or search the order number with `query`. get_purchase_order returns one order's lines.
Argumentos
statusstringopcional
Status filter, e.g. all, pending, received (default all).
get_purchase_orderLecturaOne purchase order's lines: SKU, ordered and received quantities, unit cost and supplier. `po_log_id` comes from list_purchase_orders.
list_overdue_purchase_ordersLecturaOrders whose expected arrival date has passed without a full reception, with how many days late each is. The list to chase suppliers with.
create_purchase_orderDestructiva · pide confirmaciónRecords a purchase order written by hand: one supplier, the lines typed in, no forecast behind it. DESTRUCTIVE: a recorded order cannot be voided through the API and its units start counting as stock on the way. Without `confirm: true` it only describes what it would record. It does NOT send anything to the supplier (send_purchase_order does). Get `supplier_id` from list_suppliers.
Argumentos
supplier_idstringobligatorio
The supplier's id.
linesarray of objectobligatorio
Cada elemento de la lista
skustringobligatorio
qtynumberobligatoriomín. > 0
unit_costnumberopcionalmín. 0
destination_warehousestringopcional
Warehouse it goes to (default: the default warehouse).
idempotency_keystringopcional
Optional. A unique value (a UUID) for this one order. Retrying with the same value returns the order already created instead of creating a second one.
confirmbooleanopcional
Must be true for this to run. Without it nothing changes and the answer describes exactly what would happen — show that to the person and only repeat the call with confirm: true after they agree.
record_recommended_purchase_orderDestructiva · pide confirmaciónRecords the order StockAI recommended for the forecast session as placed. With no `items`, every SKU StockAI says to order is recorded at its recommended quantity; with `items`, exactly those lines (`final_qty` is what was ordered). DESTRUCTIVE: a recorded order cannot be voided through the API. Without `confirm: true` it only describes what it would record. It does NOT send anything to the supplier.
Argumentos
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
itemsarray of objectopcional
Only these lines. Omit to record every recommended SKU.
Cada elemento de la lista
skustringobligatorio
final_qtynumberopcionalmín. 0
recommended_qtynumberopcionalmín. 0
unit_costnumberopcionalmín. 0
supplierstringopcional
destination_warehousestringopcional
idempotency_keystringopcional
Optional. A unique value (a UUID) for this one order. Retrying with the same value returns the order already created instead of creating a second one.
confirmbooleanopcional
Must be true for this to run. Without it nothing changes and the answer describes exactly what would happen — show that to the person and only repeat the call with confirm: true after they agree.
send_purchase_orderDestructiva · pide confirmaciónEmails and WhatsApps the order's PDF to each of its suppliers and marks it sent. DESTRUCTIVE: a message that left cannot be recalled. Without `confirm: true` it only describes what it would send. Lines whose supplier has no contact details are reported as not sent.
Must be true for this to run. Without it nothing changes and the answer describes exactly what would happen — show that to the person and only repeat the call with confirm: true after they agree.
receive_purchase_orderEscrituraRecords that an order arrived — fully (no `lines`) or partially (the received quantity per SKU). Stock on hand rises by the received units and the supplier's real lead time is learned. Reversible: the REST operation post-inventory-po-po_log_id-unreceive undoes it.
Argumentos
po_log_idstringobligatorio
The order's id.
linesarray of objectopcional
Received quantity per SKU. Omit for a full reception.
list_suppliersLecturaThe tenant's suppliers with id, contact details, lead time and payment terms. Paged; `query` matches name, phone or email. The `id` is what create_purchase_order takes as `supplier_id`.
get_supplier_scorecardLecturaHow each supplier actually performs: promised vs learned lead time, on-time and fill rate from the receptions recorded. Use it to answer "which supplier is reliable?".
create_supplierEscrituraAdds a supplier with contact details, lead time and payment terms. Returns the new supplier with its id. Not destructive: a supplier can be edited or deactivated later.
get_sku_forecastLecturaThe demand forecast for one SKU: past actuals and forecast values per period, with the prediction interval and the model that produced it. Periods are in the session's granularity (get_planning_context says which).
Argumentos
skustringobligatorio
The exact SKU code.
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
modelstringopcional
Only this model's forecast (default: the selected one).
get_forecast_accuracyLecturaHow accurate the forecast session is: error metrics overall and per SKU, compared against simple baselines, and which SKUs are least reliable. Use it before trusting a recommendation for a product with a large error.
Argumentos
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
get_training_statusLecturaWhether a forecast session has finished training. `status` goes QUEUED -> RUNNING -> COMPLETED or FAILED. Useful to say whether the numbers being read are the latest run or the previous one.
start_trainingEscrituraQueues a training run for a configured session, or a retrain of a completed one (same configuration, current data). Returns at once; poll get_training_status. Training takes minutes and counts against the plan's job limits.
list_data_sourcesLecturaThe sales-history sources this tenant's forecasts are trained on, with the id, the file name and when each was last updated. Use it to answer whether the numbers are based on fresh data.
upload_sales_csvEscrituraCreates a NEW data source from sales history given as CSV text (header row first; columns such as date, sku, quantity). StockAI detects the columns. It replaces nothing: existing sources and forecasts are untouched. Train on it by creating a session that uses it.
get_dashboard_summaryLecturaThe headline numbers of the inventory dashboard for a forecast session: how many SKUs are in each signal, the value to order, stock value and coverage. One call for "how are we doing?".
Argumentos
session_idstringopcional
Forecast session to read. Omit it to use the tenant's active session — the same one the StockAI app is showing on screen.
search_operationsLecturaFinds any of StockAI's ~300 public API operations by text, beyond the curated tools: warehouses, transfers, stock counts, demand events, scenarios, webhooks, reports, data-source SQL, inventory sync and more. Returns operation ids with a one-line summary and their kind (read / write / destructive), paginated. Then describe_operation, then call_operation or call_write_operation.
Argumentos
querystringopcional
Words to match, e.g. "transfer warehouse".
tagstringopcional
Only this API area (e.g. inventory, sessions, webhooks).
describe_operationLecturaEverything needed to call one operation: method and path, each parameter with its type, the request body's shape, the scope it needs, whether it is destructive (and why), and ready-to-use example arguments for call_operation / call_write_operation.
call_operationLecturaRuns any READ operation of the public API by id (kind=read in search_operations), exactly as the REST API would with this connection's credential. Large answers are cut with a note saying how to page; file downloads are described, not returned. Operations that change data are refused here — they run through call_write_operation.
Argumentos
operation_idstringobligatorio
The operation id from search_operations, e.g. "get-inventory-stock-sku".
path_paramsobjectopcional
Values for the {placeholders} in the operation's path.
Objeto libre: no declara campos.
queryobjectopcional
Query parameters, by name. Only the operation's declared ones.
Objeto libre: no declara campos.
bodyanyopcional
JSON body, for the few read operations that take one (previews, simulations).
call_write_operationDestructiva · pide confirmaciónRuns any operation that CHANGES data (kind=write or destructive in search_operations), exactly as the REST API would with this connection's credential; needs a write-scope credential. A destructive operation (every delete, recording or sending a purchase order, overwriting stock, and the others describe_operation marks) does not run without `confirm: true`: without it the answer states exactly what would happen and nothing changes. Form uploads take the file in `body` as its text, or as {filename, content | content_base64}.
Argumentos
operation_idstringobligatorio
The operation id from search_operations, e.g. "get-inventory-stock-sku".
path_paramsobjectopcional
Values for the {placeholders} in the operation's path.
Objeto libre: no declara campos.
queryobjectopcional
Query parameters, by name. Only the operation's declared ones.
Objeto libre: no declara campos.
bodyanyopcional
The JSON body (object or list), or for a form upload an object of form fields.
idempotency_keystringopcional
Sent as Idempotency-Key, for operations that accept one: a retry with the same value does not act twice.
confirmbooleanopcional
Must be true for this to run. Without it nothing changes and the answer describes exactly what would happen — show that to the person and only repeat the call with confirm: true after they agree.
Generada a partir del propio servicio: si un endpoint está aquí, se puede llamar con una API key. Las respuestas de ejemplo son llamadas reales a una cuenta de prueba. Las descripciones están en inglés, como el código.
POSTExplain a SKU's recommendation
Narrativas con IA
Explain a SKU's recommendation
POST/api/v1/ai/narrative/forecast-explanation
Clave de lecturaResponde 200 · application/json
Explains a specific SKU's inventory signal and recommendation in plain language.
Petición
Cabeceras
AuthorizationBearer sk_live_…obligatorio
Tu API key. Siempre obligatoria.
Content-Typeapplication/jsonobligatorio
Cuerpo
application/jsonEl cuerpo es obligatorio.
objectUn objeto.
skustringobligatorio
session_idstringobligatorio
profilestringopcionalpor defecto "distributor"
languagestringopcionalpor defecto "es"
Respuestas
200 Si sale bien
Para este endpoint no se capturó una respuesta de ejemplo. Toda respuesta JSON trae este envoltorio; lo que va en data depende del endpoint.
Errores posibles
Además de los errores de cada endpoint, toda llamada con clave puede responder:
401Authorization header missing, or API key invalid, revoked or expired.
403Key may not call this endpoint, is read-only on a write, or a permission check refused it.
429Per-minute limit or daily ceiling reached; honour Retry-After.
Return hyperparameter schemas for all available models.
Configuración de sesión
Dataset profile (alias)
GET/api/v1/sessions/{session_id}/profile
Clave de lecturaResponde 200 · application/json
Alias of GET /sessions/{session_id}/inspect.
Configuración de sesión
Upload and attach a dataset
POST/api/v1/sessions/{session_id}/upload
Clave de escrituraResponde 201 · application/json
Uploads a file (multipart) and attaches it to the session in one call.
Moneda
Read the currency
GET/api/v1/tenant/currency
Clave de lecturaResponde 200 · application/json
Readable by every role: it is needed to render any figure on any screen.
Fuentes de datos
List data sources
GET/api/v1/data-sources
Clave de lecturaResponde 200 · application/json
The tenant's file and SQL data sources. Paginated with skip and limit.
Fuentes de datos
Create a file data source
POST/api/v1/data-sources/file
Clave de escrituraResponde 200 · application/json
Uploads a CSV/Excel file (multipart) as a new data source.
Fuentes de datos
Create a SQL data source
POST/api/v1/data-sources/sql
Clave de escrituraResponde 200 · application/json
Registers a database connection as a data source. Fields may come from a pasted `connection_string` (URL, JDBC, ADO.NET or libpq form); typed fields win. `ssl_mode` is disable, prefer, require, verify-ca or verify-full; `ssl_ca` is the server's CA certificate (PEM), stored encrypted like the password. Private and link-local hosts are refused unless the installation allows them (`data_source_host_not_allowed`).
Fuentes de datos
Parse a connection string
POST/api/v1/data-sources/sql/parse
Clave de escrituraResponde 200 · application/json
Reads a connection string into engine, host, port, database, user and TLS mode. The password is never returned, only `has_password`.
Fuentes de datos
Delete a data source
DEL/api/v1/data-sources/{source_id}
Clave de escrituraResponde 200 · application/json
Removes the data source.
Fuentes de datos
Get a data source
GET/api/v1/data-sources/{source_id}
Clave de lecturaResponde 200 · application/json
One data source's metadata.
Fuentes de datos
Rename a data source
PATCH/api/v1/data-sources/{source_id}
Clave de escrituraResponde 200 · application/json
Changes the data source's name and description.
Fuentes de datos
Analyze a data source
GET/api/v1/data-sources/{source_id}/analyze
Clave de lecturaResponde 200 · application/json
Demand statistics over the source: totals, seasonality and per-SKU summaries, optionally within a date range.
The same analysis for a single SKU, with its time series.
Fuentes de datos
Append File
POST/api/v1/data-sources/{source_id}/append
Clave de escrituraResponde 200 · application/json
Add new sales (new days, a new product) to this file source instead of replacing it. Rows are matched by date and product (and store): new ones are added, existing ones are updated, none are removed. The answer carries `append` with what happened (added / replaced / total_rows).
Fuentes de datos
Load a data source as an editable table
GET/api/v1/data-sources/{source_id}/edit-table
Clave de lecturaResponde 200 · application/json
Columns and rows of the source, for editing and saving as a new source.
Executes ONE read statement (SELECT or WITH ... SELECT) on the customer's database, inside a read-only transaction that is always rolled back, and returns up to `limit` rows starting at `offset`, with `has_more`. Needs a `write`-scope key: it runs caller-written SQL on the customer's database. Anything else is refused with `sql_multiple_statements`, `sql_not_a_select`, `sql_forbidden_keyword`, `sql_forbidden_function` or `sql_unsupported_syntax`.
Fuentes de datos
Export a SQL query as Excel or CSV
POST/api/v1/data-sources/{source_id}/export-query
Clave de escrituraResponde 200 · application/json
Runs the query (same read-only rules as execute-query) and returns the FULL result as an .xlsx (default) or .csv file, refusing rather than truncating past the row ceiling. Needs a `write`-scope key.
Fuentes de datos
Replace a data source's file
POST/api/v1/data-sources/{source_id}/file
Clave de escrituraResponde 200 · application/json
Uploads a new file (multipart) IN PLACE: the source keeps its id and column mapping, so the next training run needs no reconfiguration. The nightly-export endpoint.
Fuentes de datos
Materialize a SQL query as a dataset
POST/api/v1/data-sources/{source_id}/materialize
Clave de escrituraResponde 200 · application/json
Runs the query and stores the result as a dataset that sessions can train on.
Fuentes de datos
Preview a data source
GET/api/v1/data-sources/{source_id}/preview
Clave de lecturaResponde 200 · application/json
The first rows of the source (and of a given sheet, for Excel).
Fuentes de datos
Save a SQL source's query
PATCH/api/v1/data-sources/{source_id}/query
Clave de escrituraResponde 200 · application/json
Stores the query the SQL source materializes.
Fuentes de datos
Sales Suggest
GET/api/v1/data-sources/{source_id}/sales-suggest
Clave de escrituraResponde 200 · application/json
Where this database keeps its sales, and the query that imports them (date, product, units per day), ranked, each with the columns it read and why. The first proposal comes with a few real rows. Reads only.
Fuentes de datos
Delete Sales Sync
DEL/api/v1/data-sources/{source_id}/sales-sync
Clave de escrituraResponde 200 · application/json
Stop keeping the dataset in step. The dataset and its forecasts stay.
Fuentes de datos
Get Sales Sync
GET/api/v1/data-sources/{source_id}/sales-sync
Clave de lecturaResponde 200 · application/json
The sync of this source, or null when it has none.
Fuentes de datos
Update Sales Sync
PATCH/api/v1/data-sources/{source_id}/sales-sync
Clave de escrituraResponde 200 · application/json
Change how often the sync runs, how many days it re-reads, which column dates the sales, whether new sales wake the forecast, or pause it. Turning a stopped sync back on runs it at once.
Fuentes de datos
Create Sales Sync
POST/api/v1/data-sources/{source_id}/sales-sync
Clave de escrituraResponde 200 · application/json
Load the saved query in full into a new dataset and keep it in step: every interval the last days are re-read from the database.
Sync now instead of waiting for the interval. Returns the run's numbers and the sync's state after it (a failed run is a state, not a 500).
Fuentes de datos
Save an edited table as a new source
POST/api/v1/data-sources/{source_id}/save-as-new
Clave de escrituraResponde 200 · application/json
Creates a new data source from edited columns and rows.
Fuentes de datos
List a SQL source's tables
GET/api/v1/data-sources/{source_id}/schema
Clave de escrituraResponde 200 · application/json
Tables and views the connection can read, with row estimates and a safely quoted preview statement for each. Cached for a few minutes; `refresh=true` re-reads.
Column names, types and nullability of one table of a SQL source.
Fuentes de datos
Update a SQL source's connection
PATCH/api/v1/data-sources/{source_id}/sql-config
Clave de escrituraResponde 200 · application/json
Changes any connection field of a SQL source. Omitted fields keep their stored value, the password included, except when the engine, host or port changes: then the password must be sent again (`data_source_password_required`).
Runs a staged test (dns, tcp, tls, auth, privileges, select, tables) and reports each stage as ok, warning, failed or skipped with a code. Warns when the login can write, with the least-privilege GRANT statements.
Datasets
List datasets
GET/api/v1/datasets
Clave de lecturaResponde 200 · application/json
Uploaded datasets. Paginated with skip and limit.
Datasets
Upload a dataset
POST/api/v1/datasets
Clave de escrituraResponde 201 · application/json
Uploads a sales-history file (multipart) and profiles it.
Datasets
Get a dataset
GET/api/v1/datasets/{dataset_id}
Clave de lecturaResponde 200 · application/json
One dataset's metadata and profile.
Documentos
List documents
GET/api/v1/documents
Clave de lecturaResponde 200 · application/json
Documents uploaded for the analyst to read.
Documentos
Upload a document
POST/api/v1/documents
Clave de escrituraResponde 200 · application/json
Upload a document (PDF, DOCX, TXT up to 50 MB). File is saved to storage and indexed asynchronously. Returns doc metadata with status=PENDING immediately.
Documentos
Delete a document
DEL/api/v1/documents/{doc_id}
Clave de escrituraResponde 200 · application/json
Removes the document and its index.
Documentos
Get a document
GET/api/v1/documents/{doc_id}
Clave de lecturaResponde 200 · application/json
One document's metadata.
Documentos
Download a document
GET/api/v1/documents/{doc_id}/content
Clave de lecturaResponde 200 · application/json
Serve the raw file for in-browser viewing or download.
Documentos
Document indexing status
GET/api/v1/documents/{doc_id}/status
Clave de lecturaResponde 200 · application/json
Whether the document has been processed and indexed.
Límites de uso
Read plan and limits
GET/api/v1/entitlements
Clave de lecturaResponde 200 · application/json
This tenant's tier, its ceilings, and how close it is to them.
Pronósticos
Configuration schema
GET/api/v1/config/schema
Clave de lecturaResponde 200 · application/json
The JSON schema of every configuration block, independent of a session.
Pronósticos
Available forecasting models
GET/api/v1/models/available
Clave de lecturaResponde 200 · application/json
The forecasting models this deployment can train.
Pronósticos
Forecast accuracy
GET/api/v1/sessions/{session_id}/accuracy
Clave de lecturaResponde 200 · application/json
Accuracy of the session's forecasts against baselines, per SKU and overall.
The latest automatic reading of how this forecast is doing against the sales uploaded after it was made, next to its accuracy at training time.
Pronósticos
Models available to a session
GET/api/v1/sessions/{session_id}/available-models
Clave de lecturaResponde 200 · application/json
The models that can be trained on this session's data.
Pronósticos
Start Backtest
POST/api/v1/sessions/{session_id}/backtest
Clave de escrituraResponde 202 · application/json
Train a back-test of a completed session: the same configuration on a copy of its dataset with the last `holdout_periods` periods held out. Its forecast then covers those periods and can be graded against the full dataset with `forecast-vs-actual`. The source session and dataset are not modified; the run counts against the plan's saved-forecast ceiling and is refused (nothing deleted) when that is full.
Pronósticos
Session configuration schema
GET/api/v1/sessions/{session_id}/config-schema
Clave de lecturaResponde 200 · application/json
The configuration schema with this session's current values.
History and forecast (with quantiles) for one SKU, optionally for a given model.
Pronósticos
Get Forecast Total
GET/api/v1/sessions/{session_id}/forecast-total
Clave de lecturaResponde 200 · application/json
The whole catalogue as one series: every SKU's champion forecast and history summed per date. Feeds the session-comparison chart's "all SKUs" option, where two sessions are only comparable as totals.
What this session predicted vs. what the tenant's LATER sales uploads say actually happened: per-SKU and pooled WAPE / MAPE / bias, the predicted-vs- actual series, and a verdict code the frontend renders in words.
Pronósticos
Session inventory recommendations
GET/api/v1/sessions/{session_id}/inventory
Clave de lecturaResponde 200 · application/json
Per-SKU inventory recommendations computed from this session's forecast.
Pronósticos
Training metrics
GET/api/v1/sessions/{session_id}/metrics
Clave de lecturaResponde 200 · application/json
Validation metrics per model and SKU.
Pronósticos
List forecast overrides
GET/api/v1/sessions/{session_id}/overrides
Clave de lecturaResponde 200 · application/json
Manual adjustments made to the session's forecast.
Pronósticos
Save forecast overrides
PATCH/api/v1/sessions/{session_id}/overrides
Clave de escrituraResponde 200 · application/json
Upserts manual forecast values per SKU and date, with a reason. The body is a list.
Pronósticos
Predict on demand
POST/api/v1/sessions/{session_id}/predict
Clave de lecturaResponde 200 · application/json
Runs the trained model for one SKU with the given inputs and horizon.
Pronósticos
Data quality
GET/api/v1/sessions/{session_id}/quality
Clave de lecturaResponde 200 · application/json
Data-quality findings for the session's dataset.
Pronósticos
Reconcile actual values
POST/api/v1/sessions/{session_id}/reconcile
Clave de escrituraResponde 200 · application/json
Upload a CSV of actual values to compare against the stored forecast.
Pronósticos
Session report (alias)
GET/api/v1/sessions/{session_id}/report
Clave de lecturaResponde 200 · application/json
The session's results summarized as one report document.
Pronósticos
Training results
GET/api/v1/sessions/{session_id}/results
Clave de lecturaResponde 200 · application/json
Forecasts and per-model results of a completed session, at SKU or aggregate level.
Pronósticos
Model routing
GET/api/v1/sessions/{session_id}/routing
Clave de lecturaResponde 200 · application/json
Which model was routed to each SKU and why.
Pronósticos
Model routing plan (alias)
GET/api/v1/sessions/{session_id}/routing-plan
Clave de lecturaResponde 200 · application/json
The routing decisions as a plan, per SKU segment.
Pronósticos
Read a SKU's feature importances
GET/api/v1/sessions/{session_id}/shap/{sku}
Clave de lecturaResponde 200 · application/json
Return SHAP feature importances for the best model for the given SKU.
Everything known about one SKU in the session: series, model, drivers and recommendation.
Pronósticos
List run warnings
GET/api/v1/sessions/{session_id}/warnings
Clave de lecturaResponde 200 · application/json
Data problems the validation layers found while training this session.
Frescura de datos
Read data freshness
GET/api/v1/data-freshness
Clave de lecturaResponde 200 · application/json
Age of the sales history and of the stock table, plus whether the semáforo may still claim a colour.
Inventario, compras y proveedores
Send the daily alert now
POST/api/v1/inventory/alerts/send-now
Clave de escrituraResponde 202 · application/json
Fire the daily inventory alert immediately for this tenant — email to the admins, WhatsApp to the ones who opted in. Lets the user verify their channels without waiting for the 8:00 UTC scheduler run.
Inventario, compras y proveedores
List where a component is used
GET/api/v1/inventory/bom/{child_sku}/used-in
Clave de lecturaResponde 200 · application/json
Returns all finished goods that use this component.
Inventario, compras y proveedores
Read a bill of materials
GET/api/v1/inventory/bom/{parent_sku}
Clave de lecturaResponde 200 · application/json
Returns BOM (Bill of Materials) for a finished good.
Inventario, compras y proveedores
Remove a bill-of-materials line
DEL/api/v1/inventory/bom/{parent_sku}/{child_sku}
Clave de escrituraResponde 204 · application/json
Removes a component from a parent SKU's bill of materials.
Inventario, compras y proveedores
Set a bill-of-materials line
PUT/api/v1/inventory/bom/{parent_sku}/{child_sku}
Clave de escrituraResponde 200 · application/json
Creates or updates how much of a component one unit of the parent SKU uses.
Inventario, compras y proveedores
Import stock from a file
POST/api/v1/inventory/bulk
Clave de escrituraResponde 200 · application/json
Import stock from a CSV or Excel file.
Inventario, compras y proveedores
Preview a stock import
POST/api/v1/inventory/bulk/preview
Clave de escrituraResponde 200 · application/json
Dry run of POST /bulk: what we detected in the file and what we would write, without touching a single row. This is what makes the mapping wizard possible — the user corrects our column guesses BEFORE importing, the same way the sales upload works.
Inventario, compras y proveedores
Read the cash calendar
GET/api/v1/inventory/cash-calendar
Clave de lecturaResponde 200 · application/json
Invoices falling due from POs already sent, dated by each supplier's credit terms. Read-only, so viewers may call it.
Inventario, compras y proveedores
Fit a purchase into a budget
POST/api/v1/inventory/cash-calendar/fit
Clave de lecturaResponde 200 · application/json
"Does the recommended purchase fit in the cash I have?"
Inventario, compras y proveedores
Read the dashboard summary
GET/api/v1/inventory/dashboard-summary
Clave de lecturaResponde 200 · application/json
Lightweight endpoint for the dashboard widget. Returns only the summary counts without the full item list.
Inventario, compras y proveedores
List dead capital
GET/api/v1/inventory/dead-capital
Clave de lecturaResponde 200 · application/json
Every SKU on hand whose stock level has not fallen in at least `window_days`, ranked worst first by money, with the tenant's total at the top. Needs no session — it reads real stock-level history, not a forecast.
Inventario, compras y proveedores
List demand events
GET/api/v1/inventory/events
Clave de lecturaResponde 200 · application/json
Promotions and seasonal events that multiply expected demand.
Inventario, compras y proveedores
Create a demand event
POST/api/v1/inventory/events
Clave de escrituraResponde 201 · application/json
Adds an event with a date range and a demand multiplier.
Inventario, compras y proveedores
Read the event catalog
GET/api/v1/inventory/events/catalog
Clave de lecturaResponde 200 · application/json
Which commercial events StockAI knows for a country, and whether this tenant has them seeded / switched on. Read-only.
Inventario, compras y proveedores
Seed the event catalog
POST/api/v1/inventory/events/catalog/seed
Clave de escrituraResponde 200 · application/json
Preload the LatAm commercial calendar into this tenant's events.
Drop the override: the product falls back to the event multiplier.
Inventario, compras y proveedores
Project revenue, cost and margin
GET/api/v1/inventory/forecast-money
Clave de lecturaResponde 200 · application/json
Projected revenue, cost and gross margin over the active session's forecast horizon, per SKU and in total, ranked so the top contributors are visible — "your next N periods: X in sales, Y in margin, and these products carry it." The horizon is `horizon_periods` forecast steps of `period` (daily, weekly or monthly); `horizon_days` is deprecated, kept for older clients as the same horizon in calendar days.
Inventario, compras y proveedores
Record a purchase order
POST/api/v1/inventory/log-po
Clave de escrituraResponde 201 · application/json
Records that an order was placed, with its lines. Reception tracking and supplier lead-time learning read it. A body without `items` records every actionable SKU of the session.
Inventario, compras y proveedores
List margin erosion
GET/api/v1/inventory/margin-erosion
Clave de lecturaResponde 200 · application/json
SKUs whose margin eroded because their cost rose while the product's sale_price is the only price StockAI has ever stored. `price_history_available: false` in the response is load-bearing: the "before" margin is today's price against a past cost, not a historical fact — see `cost_alerts.get_margin_erosion`'s docstring.
Inventario, compras y proveedores
Read the morning briefing
GET/api/v1/inventory/morning-briefing
Clave de lecturaResponde 200 · application/json
Daily operations briefing: risks, recommendations, demand changes, KPIs. Designed to be the first thing a manager opens every morning. Reflects the tenant's ACTIVE planning period — coverage and the signal in that unit — so /hoy agrees with /inventory (a weekly session must be read as weekly).
Inventario, compras y proveedores
Optimize purchases and transfers
GET/api/v1/inventory/optimize
Clave de lecturaResponde 200 · application/json
Runs the MILP purchasing/transfers optimizer for this session and returns suggested purchase quantities per SKU x warehouse, plus recommended inter-warehouse transfers, collapsed to one total per line over the full horizon.
Inventario, compras y proveedores
Create a manual purchase order
POST/api/v1/inventory/po
Clave de escrituraResponde 201 · application/json
A purchase order the buyer writes from scratch — supplier chosen explicitly, lines typed in, no forecast session behind it. Persisted with source='manual' so adoption metrics stay clean. `Idempotency-Key`: same contract as /log-po.
Inventario, compras y proveedores
List recent purchase orders
GET/api/v1/inventory/po-history
Clave de lecturaResponde 200 · application/json
Returns recent PO generation events for the history panel.
Inventario, compras y proveedores
Po History Page
GET/api/v1/inventory/po-history/page
Clave de lecturaResponde 200 · application/json
The PO history, filtered and paged on the server. `total` counts the filtered set; `awaiting_reception` counts every open order of the tenant.
Inventario, compras y proveedores
Import purchase orders from a file
POST/api/v1/inventory/po/import
Clave de escrituraResponde 200 · application/json
Create purchase orders from a CSV / Excel file, one order per (order reference, supplier, destination warehouse).
Inventario, compras y proveedores
Preview a purchase-order import
POST/api/v1/inventory/po/import/preview
Clave de escrituraResponde 200 · application/json
Dry run of POST /po/import: the orders the file would create, and every row whose supplier / product / warehouse did not resolve. Writes nothing.
Inventario, compras y proveedores
Download the purchase-order import template
GET/api/v1/inventory/po/import/template
Clave de lecturaResponde 200 · application/json
Purchase-order import template: header row plus example lines (two orders, the first with two lines).
Inventario, compras y proveedores
List overdue purchase orders
GET/api/v1/inventory/po/overdue
Clave de lecturaResponde 200 · application/json
POs still pending/partial whose expected arrival — order date plus the supplier's already-learned lead time — has passed with no reception recorded. Powers the /hoy 'did it arrive?' nudge.
Inventario, compras y proveedores
List a purchase order's lines
GET/api/v1/inventory/po/{po_log_id}/items
Clave de lecturaResponde 200 · application/json
Lines of a PO with ordered vs received quantities (reception form).
Inventario, compras y proveedores
Receive a purchase order
POST/api/v1/inventory/po/{po_log_id}/receive
Clave de escrituraResponde 200 · application/json
Record that a PO arrived (fully, partially, or not at all). Side effects: current_stock increases by the received units, and StockAI logs the supplier's REAL lead time (order date → reception date).
Inventario, compras y proveedores
Send a purchase order to suppliers
POST/api/v1/inventory/po/{po_log_id}/send
Clave de escrituraResponde 200 · application/json
Sends a PO's PDF to each of its suppliers by email and WhatsApp, grouping the PO's lines by supplier name (a PO can span more than one supplier). Lines with no supplier name, or whose supplier has no saved contact info, are skipped and reported back — never a 500.
Inventario, compras y proveedores
List price breaks
GET/api/v1/inventory/price-breaks
Clave de lecturaResponde 200 · application/json
Supplier quantity scales, optionally filtered by supplier and/or SKU.
Inventario, compras y proveedores
Evaluate price breaks for a cart
POST/api/v1/inventory/price-breaks/evaluate
Clave de lecturaResponde 200 · application/json
Given the cart the buyer currently has on screen, which lines are one step away from a better unit price AND would still be a good idea to step up to.
The valid product types, as the English keys the frontend translates.
Inventario, compras y proveedores
Explode demand into components
GET/api/v1/inventory/production-requirements
Clave de lecturaResponde 200 · application/json
MRP Level 1 explosion: given forecast demand + BOM, returns required quantities of each component and raw material, flagging shortages and purchase requirements.
Inventario, compras y proveedores
Constrained Purchase Plan
GET/api/v1/inventory/purchase-plan
Clave de lecturaResponde 200 · application/json
The Panel's current recommendations fitted to the purchase budget, MOQs, case packs, price breaks, supplier minimum orders, container capacity and joint replenishment in one optimisation. Read-only: it changes no recommendation and creates no order. `binding` says which constraint bound and what it cost.
Inventario, compras y proveedores
Download the inventory PDF
GET/api/v1/inventory/report/pdf
Clave de lecturaResponde 200 · application/json
Generates and streams a one-page executive PDF inventory summary.
Inventario, compras y proveedores
Read accumulated ROI
GET/api/v1/inventory/roi
Clave de lecturaResponde 200 · application/json
Returns accumulated ROI metrics across all time.
Inventario, compras y proveedores
Read one month's ROI report
GET/api/v1/inventory/roi/month-report
Clave de lecturaResponde 200 · application/json
Recap of a single calendar month (feature 3.2). Defaults to the month that just closed — the same period the monthly recap email covers.
Inventario, compras y proveedores
List monthly ROI
GET/api/v1/inventory/roi/monthly
Clave de lecturaResponde 200 · application/json
Last N months: orders, stockout risks handled, adoption, capital freed from overstock.
Inventario, compras y proveedores
Replay recent months with StockAI's policy
GET/api/v1/inventory/roi/what-if
Clave de lecturaResponde 200 · application/json
Replay the last N months of the company's own sales twice — once with StockAI's policy, once with a stated simple rule — and set both against what its own records show it did. Read-only; every number carries its assumptions (see backend/inventory/what_if_service.py).
Inventario, compras y proveedores
List SKUs missing setup
GET/api/v1/inventory/setup-gaps
Clave de lecturaResponde 200 · application/json
Unconfigured SKUs ordered by the money they move, with the running cumulative share of projected spend.
Inventario, compras y proveedores
List shrinkage
GET/api/v1/inventory/shrinkage
Clave de lecturaResponde 200 · application/json
Recent history of recorded shrinkage (input to the future monthly summary).
Inventario, compras y proveedores
Record shrinkage
POST/api/v1/inventory/shrinkage
Clave de escrituraResponde 201 · application/json
Record a stock-out that is NOT a sale — breakage, expiry, self-consumption or a gift/sample. Decrements the SKU's theoretical stock through the same path PO reception uses (so the signal stays accurate) and accumulates the cost (quantity x unit cost) for a future monthly shrinkage summary.
Inventario, compras y proveedores
List shrinkage reasons
GET/api/v1/inventory/shrinkage/reasons
Clave de lecturaResponde 200 · application/json
Returns the valid shrinkage reason codes (labels are handled client-side via i18n).
Inventario, compras y proveedores
Read the inventory traffic light
GET/api/v1/inventory/status
Clave de lecturaResponde 200 · application/json
Returns per-SKU inventory status in the tenant's ACTIVE planning period:
- coverage (in the active period's units — see `coverage_unit`)
- traffic-light signal (PEDIR_YA / PEDIR_PRONTO / OK / SOBRESTOCK / SIN_DATOS)
- recommended order quantity
- inventory value
Inventario, compras y proveedores
Export the purchase order as CSV
GET/api/v1/inventory/status/export-po
Clave de lecturaResponde 200 · application/json
Export purchase order as CSV, filtered to actionable SKUs.
Inventario, compras y proveedores
List stock
GET/api/v1/inventory/stock
Clave de lecturaResponde 200 · application/json
Every SKU's stock record: on hand, minimum, lead time, cost, supplier and catalogue fields.
Inventario, compras y proveedores
List Counts
GET/api/v1/inventory/stock-counts
Clave de lecturaResponde 200 · application/json
List stock counts, newest first, with how many products each holds.
Inventario, compras y proveedores
Create Count
POST/api/v1/inventory/stock-counts
Clave de escrituraResponde 201 · application/json
Open a count session for one warehouse, optionally scoped to a category or supplier.
Inventario, compras y proveedores
Get Count
GET/api/v1/inventory/stock-counts/{count_id}
Clave de lecturaResponde 200 · application/json
One count with every line (counted quantity next to the system quantity at the first scan).
Write the differences into stock, exactly once, and record each adjustment with reason 'physical_count'. Omit skus to apply every line; a list applies only those. All or nothing.
Sets the supplier's cost, MOQ, lead time and primary flag for the SKU.
Inventario, compras y proveedores
List supplier cost inflation
GET/api/v1/inventory/supplier-cost-inflation
Clave de lecturaResponde 200 · application/json
Suppliers who raised a SKU's cost at least once in the window, worst first, with the products each one hit hardest. Built only from POs that were actually received — a quoted or rejected order proves nothing was paid.
Inventario, compras y proveedores
List suppliers
GET/api/v1/inventory/suppliers
Clave de lecturaResponde 200 · application/json
The tenant's suppliers with contact details, lead times and payment terms.
Inventario, compras y proveedores
Create a supplier
POST/api/v1/inventory/suppliers
Clave de escrituraResponde 201 · application/json
Adds a supplier with contact details, lead time and payment terms.
Inventario, compras y proveedores
Check supplier contact details
GET/api/v1/inventory/suppliers/contact-health
Clave de lecturaResponde 200 · application/json
Suppliers that POST /po/{id}/send would silently skip — no email and no WhatsApp on file, or a supplier name on PO lines with no record at all (feature 2.5).
Inventario, compras y proveedores
Import suppliers from a file
POST/api/v1/inventory/suppliers/import
Clave de escrituraResponde 200 · application/json
Create suppliers from a CSV / Excel file.
Inventario, compras y proveedores
Preview a suppliers import
POST/api/v1/inventory/suppliers/import/preview
Clave de escrituraResponde 200 · application/json
Dry run of POST /suppliers/import: what was detected and what would be written. Touches no row.
Inventario, compras y proveedores
Download the suppliers import template
GET/api/v1/inventory/suppliers/import/template
Clave de lecturaResponde 200 · application/json
Suppliers import template: the header row plus two example rows.
Inventario, compras y proveedores
List supplier lead-time alerts
GET/api/v1/inventory/suppliers/lead-time-alerts
Clave de lecturaResponde 200 · application/json
Suppliers whose recent lead time is significantly slower than their own history — "Acme is taking 12 days, not 7" (feature 3.3).
Inventario, compras y proveedores
List Suppliers Page
GET/api/v1/inventory/suppliers/page
Clave de lecturaResponde 200 · application/json
Active suppliers, searched and paged on the server (the plain list stays whole for the dropdowns that need every supplier).
Inventario, compras y proveedores
Read the supplier scorecard
GET/api/v1/inventory/suppliers/scorecard
Clave de lecturaResponde 200 · application/json
Per-supplier performance: real lead time range, on-time rate, fill rate.
Inventario, compras y proveedores
Deactivate a supplier
DEL/api/v1/inventory/suppliers/{supplier_id}
Clave de escrituraResponde 204 · application/json
Deactivates the supplier (see the reactivate endpoint).
Inventario, compras y proveedores
Update a supplier
PATCH/api/v1/inventory/suppliers/{supplier_id}
Clave de escrituraResponde 200 · application/json
Changes a supplier's contact details, lead time, review period or payment terms.
Records the quantities that arrived at the destination warehouse.
Inventario, compras y proveedores
List warehouses
GET/api/v1/inventory/warehouses
Clave de lecturaResponde 200 · application/json
The tenant's warehouses.
Inventario, compras y proveedores
Create a warehouse
POST/api/v1/inventory/warehouses
Clave de escrituraResponde 201 · application/json
Adds a warehouse, optionally as the default.
Inventario, compras y proveedores
Delete a transfer lane
DEL/api/v1/inventory/warehouses/lanes
Clave de escrituraResponde 204 · application/json
Names travel as query params, not path segments: a warehouse name may contain a slash and would break path matching once encoded.
Inventario, compras y proveedores
List transfer lanes
GET/api/v1/inventory/warehouses/lanes
Clave de lecturaResponde 200 · application/json
Configured lanes only. A pair with no row falls back to the documented default (lead_time_days=1, cost_per_unit=0, fixed_cost=0) everywhere it is consumed — see backend/inventory/transfer_lane_service.py.
Inventario, compras y proveedores
Set a transfer lane
PUT/api/v1/inventory/warehouses/lanes
Clave de escrituraResponde 200 · application/json
Creates or updates the lead time and costs of moving stock between two warehouses.
Inventario, compras y proveedores
Update a warehouse
PATCH/api/v1/inventory/warehouses/{name}
Clave de escrituraResponde 200 · application/json
Set or clear the manual demand share for one warehouse (feature 5.4).
inventory-decision-quality
Decision Quality
GET/api/v1/inventory/decision-quality
Clave de lecturaResponde 200 · application/json
Decisions (one SKU on one standing purchase order) placed in the window, summarised and broken down by ABC class, supplier, SKU and order month. Open orders are counted but never scored; a completed order with no stock reading during its lead time is `unmeasured`, never a success. `measuring_since` names the first day each input was recorded.
Every SKU that carried an ordering signal (PEDIR_YA/PEDIR_PRONTO) in the window: whether a purchase order followed, and — only where it did not and stock was later observed at or below zero — the estimated unserved units and their value. See `recommendation_reports.cost_of_ignoring` for the conservatism rules (no PO + no observed stockout => no loss claimed; no sale price => units reported, value null).
The SKU's latest recorded recommendation against the previous recorded one, decomposed into avg daily demand, lead time, stock on hand and safety stock — each tagged with whether it came from a new training session (a model opinion) or the tenant's own operational data. Returns `available: false` with a `reason` when there is not yet a previous row to compare against.
Reversas de órdenes
Undo a purchase-order reception
POST/api/v1/inventory/po/{po_log_id}/unreceive
Clave de escrituraResponde 200 · application/json
Undo a reception: take the received units back out of stock, reset the PO line's `received_qty` and the order's `reception_status`, and remove the lead-time observation(s) that reception taught the supplier scorecard. Refuses (409, with the offending SKU/warehouse named) rather than go negative if some of the received units are no longer in stock. See `reception_service.unreceive_po` for the full reasoning.
Reversas de órdenes
Undo marking a purchase order as sent
POST/api/v1/inventory/po/{po_log_id}/unsend
Clave de escrituraResponde 200 · application/json
Undo `mark_po_sent`: clear `sent_at` so the order stops counting as incoming stock and drops off the cash-payables calendar. Does NOT recall the email/WhatsApp message a prior `/send` may have delivered — that left the system and nothing can pull it back. Refuses once a reception exists against this PO (undo that first). See `reception_service.unsend_po`.
inventory-sync
Draft Doctor
POST/api/v1/inventory-sync/doctor
Clave de escrituraResponde 200 · application/json
The connection doctor for an unsaved configuration.
inventory-sync
Dry Run Unsaved
POST/api/v1/inventory-sync/dry-run
Clave de escrituraResponde 200 · application/json
Preview a configuration that is not saved yet. Writes nothing.
inventory-sync
List Presets
GET/api/v1/inventory-sync/presets
Clave de escrituraResponde 200 · application/json
ERP recipe presets (SAP, Oracle EBS, Dynamics, Business Central, JD Edwards, Infor M3, Odoo, Magento, WooCommerce, generic SCD2 / UNION ledgers): parameters, stock model, the gotchas each one guards against, and whether it was verified against a live system. Also the systems read another way (push, or a warehouse through an existing engine).
The profile body a preset produces for one engine and its parameters (client, company, organisations...). Nothing is saved: the body goes through the wizard's dry run like any other.
inventory-sync
Create Profile
POST/api/v1/inventory-sync/profiles
Clave de escrituraResponde 201 · application/json
Create a profile (off until previewed and enabled). Send `Idempotency-Key` to make a retried POST create it once.
inventory-sync
Apply Document
POST/api/v1/inventory-sync/profiles/apply
Clave de escrituraResponde 200 · application/json
Apply a profile document (JSON or YAML): created, or updated by its `slug` — idempotent, so CI can re-apply the file on every deploy and the second time answers `action: unchanged`. Errors name the exact path (`mapping.current_stock.cast: 'int' is not one of ...`). `dry_run=true` validates and previews without saving.
inventory-sync
Validate Document
POST/api/v1/inventory-sync/profiles/validate
Clave de escrituraResponde 200 · application/json
Validate a profile document without touching anything: every problem with its path.
inventory-sync
Delete Profile
DEL/api/v1/inventory-sync/profiles/{profile_id}
Clave de escrituraResponde 200 · application/json
Delete a profile with its run log. The stock it synced stays as it is.
inventory-sync
Update Profile
PATCH/api/v1/inventory-sync/profiles/{profile_id}
Clave de escrituraResponde 200 · application/json
Change a profile. Changing what it writes turns it off until previewed again (`disabled_by_edit: true`).
The connection doctor for a saved profile: source, connection (dns, tcp, tls, auth, privileges, select, tables), object, columns, sample read, row estimate, index on the incremental column (with the CREATE INDEX to run), supported change capture. `first_failure` names the stage and code; `diagnostic` is a secret-free bundle to paste to a DBA.
'Sync now'. Answers at once with the run row (status `running`); poll `GET .../runs/{run_id}` for the outcome. `override_brake` runs once past the safety brake (audited). With `Idempotency-Key`, a retry does not start a second run.
inventory-sync
Recipes
GET/api/v1/inventory-sync/recipes
Clave de escrituraResponde 200 · application/json
Copy-paste material: least-privilege read-only GRANTs per engine (or for one data source), StockAI's egress IPs, example queries for common ERP schemas, a `stockai_inventory` view template and push forwarders.
inventory-sync
Refresh
POST/api/v1/inventory-sync/refresh
Clave de escrituraResponde 200 · application/json
'Refresh now': make the displayed stock current. Coalesces (a refresh that finds a run in flight joins it), honours a per-profile cooldown (`status: cooldown`, `retry_after_s`), refreshes only `skus` when given, and waits at most `wait_seconds` before answering `status: running` with the `data_as_of` of the last success — the stock shown is never blanked. Paused or blocked profiles answer with their reason instead of running.
The CREATE VIEW stockai_inventory statement (or MongoDB view pipeline) for this source and mapping: hand it to the DBA, then map the view at confidence 1.0. StockAI never runs it.
inventory-sync
Transform Test
POST/api/v1/inventory-sync/transform-test
Clave de escrituraResponde 200 · application/json
Try a field's transforms on one sample value: the output, or the rejection code a run would report.
inventory-sync-status
Get Fields
GET/api/v1/inventory-sync/fields
Clave de lecturaResponde 200 · application/json
The canonical fields, transforms, policies and limits the editor offers.
inventory-sync-status
Get Freshness
GET/api/v1/inventory-sync/freshness
Clave de lecturaResponde 200 · application/json
How current the stock is: `state` is `fresh`, `stale` (a profile has not succeeded within its expected window), `blocked` (a profile is paused or blocked and needs someone) or `none` (no sync). `data_as_of` is the oldest last success among live profiles: the stock is at least that fresh. Each profile lists its own state and the reason code when not fresh.
inventory-sync-status
Tenant Health
GET/api/v1/inventory-sync/health
Clave de lecturaResponde 200 · application/json
Every profile's health in one call; `status` is the worst of them.
inventory-sync-status
Overview
GET/api/v1/inventory-sync/overview
Clave de lecturaResponde 200 · application/json
The sync screen's one answer: is the stock current, and what is waiting for a person. `state` is none / waiting / fresh / attention / blocked; `attention` lists what only a person can settle (a stock file held for a decision, a sync the safety brake paused, a source that refuses us, a sync that is late, rows a run refused), worst first, each with the ids the action needs; `sources` is every database, file-drop and push source with its freshness and last run. Unlike `/health` it never answers 503: it is for reading, not for an uptime checker.
inventory-sync-status
Get Ownership
GET/api/v1/inventory-sync/ownership
Clave de lecturaResponde 200 · application/json
Which stock fields of which (sku, warehouse) a live sync will overwrite at its next run, and which sync: the editors warn before a person saves a value the source will replace (the source wins; the replacement is counted and audit-logged). `items[].fields` are the fields the owning profile writes; `profiles[]` carries its name and `next_sync_at` (null for a push sync or an on-demand one: nobody can tell when it will write).
inventory-sync-status
List Profiles
GET/api/v1/inventory-sync/profiles
Clave de lecturaResponde 200 · application/json
Every inventory sync profile with its status: enabled, last success and its age, `stale` (no success within twice the interval), `braked` (the safety brake stopped the last run), the last error code and the fields the source owns.
inventory-sync-status
Get Profile
GET/api/v1/inventory-sync/profiles/{profile_id}
Clave de lecturaResponde 200 · application/json
One inventory sync profile with the same status fields as the list.
Machine-readable health for monitoring: `status` ok / stale / degraded / paused / blocked, `http_status` 200 or 503, the reason code with its category and whether it retries on its own, the last-success age and the next run. `strict=true` answers with that HTTP status itself (a 503 for an uptime checker), the same body either way.
The run log of a profile, newest first: rows read, created, updated, unchanged and rejected, the outcome (success / failed / braked), the error code and the watermark each run started from and reached.
The run's rejected rows as CSV (row, sku, code, params): bounded to the sample the run kept.
inventory-sync-status
Profile Schema
GET/api/v1/inventory-sync/schema/profile.json
Clave de lecturaResponde 200 · application/json
The JSON Schema (draft 2020-12) of a profile document, `stockai.inventory-sync/v1`. The importer validates against the same spec.
MCP (clientes de IA)
Call the MCP server (JSON-RPC)
POST/api/v1/mcp
Clave de lecturaResponde 200 · application/json
Model Context Protocol endpoint, for an AI client the customer runs.
Planificación
Planning context
GET/api/v1/planning
Clave de lecturaResponde 200 · application/json
The active planning period and `active_session_id` — the session the app's own screens show.
purchase-orders-erp
Export Feed
GET/api/v1/purchase-orders/export
Clave de lecturaResponde 200 · application/json
Approved orders changed after `since`, oldest change first, with a cursor to resume from. A cancelled order comes back with `state = "cancelled"`. An order still waiting for approval is not here until it is approved.
purchase-orders-erp
Export File
GET/api/v1/purchase-orders/export/file
Clave de lecturaResponde 200 · application/json
The chosen orders as the file the ERP imports. One document per supplier.
purchase-orders-erp
Export Formats
GET/api/v1/purchase-orders/export/formats
Clave de lecturaResponde 200 · application/json
The ERP file layouts, and which of them have been run against a real system.
purchase-orders-erp
Unacknowledged
GET/api/v1/purchase-orders/unacknowledged
Clave de lecturaResponde 200 · application/json
Open approved orders whose ERP document number nobody has written back.
Run a saved scenario and return the BASE vs SCENARIO comparison.
Reentrenamiento programado
List retraining schedules
GET/api/v1/schedules
Clave de lecturaResponde 200 · application/json
Every schedule this tenant has, with the session's name.
Reentrenamiento programado
List scheduler history
GET/api/v1/schedules/history
Clave de lecturaResponde 200 · application/json
What the scheduler has actually done, newest first.
Reentrenamiento programado
Delete a retraining schedule
DEL/api/v1/sessions/{session_id}/schedule
Clave de escrituraResponde 200 · application/json
Stops the session's scheduled retraining.
Reentrenamiento programado
Get a retraining schedule
GET/api/v1/sessions/{session_id}/schedule
Clave de lecturaResponde 200 · application/json
The session's cron schedule for automatic retraining.
Reentrenamiento programado
Save a retraining schedule
POST/api/v1/sessions/{session_id}/schedule
Clave de escrituraResponde 200 · application/json
Sets a cron expression for automatic retraining, and whether it is enabled.
Sesiones
List sessions
GET/api/v1/sessions
Clave de lecturaResponde 200 · application/json
Forecast sessions with their state. Paginated with skip and limit.
Sesiones
Create a session
POST/api/v1/sessions
Clave de escrituraResponde 201 · application/json
Creates a forecast session in DRAFT.
Sesiones
List session summaries
GET/api/v1/sessions/summary
Clave de lecturaResponde 200 · application/json
The sessions library: every session of the tenant, enriched (dataset name, horizon, SKU count, granularity, headline accuracy, models), searchable, filterable, sortable and paginated. `total` counts the rows matching the filters, so a pager can be drawn.
Sesiones
Delete a session
DEL/api/v1/sessions/{session_id}
Clave de escrituraResponde 204 · application/json
Deletes the session and its results.
Sesiones
Get a session
GET/api/v1/sessions/{session_id}
Clave de lecturaResponde 200 · application/json
One session's metadata and state.
Sesiones
Update a session
PATCH/api/v1/sessions/{session_id}
Clave de escrituraResponde 200 · application/json
Changes a session's name, description or tags.
Sesiones
Get Manifest
GET/api/v1/sessions/{session_id}/manifest
Clave de lecturaResponde 200 · application/json
How this forecast was produced: who or what started the run, the dataset's content hash and size, the full configuration, engine and library versions, per-model outcomes, stage timings and a hash of the forecast. Written once when the run ends and never changed. 404 `manifest_not_available` for a session that has not finished a run since manifests were introduced.
Sesiones
Restore Session
POST/api/v1/sessions/{session_id}/restore
Clave de escrituraResponde 200 · application/json
Bring an archived session back into the working list. Counts against the plan's saved-forecast ceiling like a new one: at the ceiling it is refused with the same message, and the session stays archived and intact.
Sesiones
Get Run Durations
GET/api/v1/training/run-durations
Clave de lecturaResponde 200 · application/json
Median and p95 training duration over the tenant's last `limit` runs, by catalogue-size bucket and by granularity, read from the lineage manifests (no new storage). For choosing a retrain cadence from evidence.
Zona horaria
Read the time zone
GET/api/v1/tenant/timezone
Clave de lecturaResponde 200 · application/json
Readable by every role: any screen showing a scheduled time needs it.
Entrenamiento
List active jobs
GET/api/v1/jobs/active
Clave de lecturaResponde 200 · application/json
Training runs of this tenant that are queued or running right now.
Entrenamiento
Cancel a job
DEL/api/v1/jobs/{job_id}
Clave de escrituraResponde 200 · application/json
Cancels a queued or running training job.
Entrenamiento
Get a job
GET/api/v1/jobs/{job_id}
Clave de lecturaResponde 200 · application/json
A training job's state and progress.
Entrenamiento
Job logs
GET/api/v1/jobs/{job_id}/logs
Clave de lecturaResponde 200 · application/json
The last `tail` log lines of a training job.
Entrenamiento
List a session's jobs
GET/api/v1/sessions/{session_id}/jobs
Clave de lecturaResponde 200 · application/json
Training jobs run for the session.
Entrenamiento
Start Reforecast
POST/api/v1/sessions/{session_id}/reforecast
Clave de escrituraResponde 202 · application/json
Create a NEW session that forecasts from this session's stored models over newer sales, without retraining. The source session is never modified. Counts against the plan's saved-forecast ceiling; runs on the job queue.
Whether a re-forecast with newer sales is on offer for this session: stored models present, newer data than the forecast used, and the refit age of the models. `reason` is a stable code when it is not.
Entrenamiento
Start training
POST/api/v1/sessions/{session_id}/train
Clave de escrituraResponde 202 · application/json
Queues a training run for a configured session. Poll /sessions/{session_id}/train/status.
Entrenamiento
Read training status
GET/api/v1/sessions/{session_id}/train/status
Clave de lecturaResponde 200 · application/json
Returns the latest job status for this session. Alias used by the Frontend — maps to GET /jobs/{job_id} for the most recent job.
Webhooks
List webhooks
GET/api/v1/webhooks
Clave de lecturaResponde 200 · application/json
Outgoing webhooks and the events they subscribe to.
Webhooks
Create a webhook
POST/api/v1/webhooks
Clave de escrituraResponde 200 · application/json
Subscribes an https URL to business events (purchase orders, stockouts, commitments, jobs). The signing secret is returned once.
Webhooks
List webhook events
GET/api/v1/webhooks/events
Clave de lecturaResponde 200 · application/json
The events a webhook can subscribe to and the data keys each carries.
Webhooks
Delete a webhook
DEL/api/v1/webhooks/{webhook_id}
Clave de escrituraResponde 200 · application/json
Removes the webhook and its delivery log.
Webhooks
List webhook deliveries
GET/api/v1/webhooks/{webhook_id}/deliveries
Clave de lecturaResponde 200 · application/json
The delivery log: status, attempts, last status code, last error and next retry.
Webhooks
Re-enable a webhook
POST/api/v1/webhooks/{webhook_id}/enable
Clave de escrituraResponde 200 · application/json
Switches a webhook back on after it was disabled for repeated failures.
Webhooks
Rotate a webhook secret
POST/api/v1/webhooks/{webhook_id}/rotate-secret
Clave de escrituraResponde 200 · application/json
Issues a new signing secret, returned once. The old one stops verifying at once.
Webhooks
Send a test event
POST/api/v1/webhooks/{webhook_id}/test
Clave de escrituraResponde 200 · application/json
Queues a signed webhook.test delivery to the webhook.
Petición
curl-X POST "$STOCKAI/ai/narrative/forecast-explanation"\-H"Authorization: Bearer $STOCKAI_KEY"\-H"Content-Type: application/json"\-d'{"sku":"SKU-001","session_id":"<session_id>","profile":"distributor","language":"es"}'