Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/juadariasmar/inventory_project/llms.txt

Use this file to discover all available pages before exploring further.

The analytics module aggregates the full state of your inventory and sales data into a single dashboard so you can make informed reorder and pricing decisions. All calculations run on demand against your live Neon Postgres data through src/lib/analisis.ts, with no pre-computed summaries to become stale.

Analytics endpoint

GET /api/analisis
A successful response returns a JSON object with the following top-level keys, all scoped to the authenticated user’s company:

ventasPorDia

Array of VentaDiaria objects — one entry per day for the last 30 days. Each entry contains fecha (ISO date string), numeroVentas (count of non-cancelled sales), and totalIngreso (sum of sale totals, rounded to the nearest integer).

ventasPorCategoria

Top-8 categories ranked by revenue for the last 30 days. Each entry contains categoria (name), unidadesVendidas, and ingresoTotal.

distribucionStock

Three-bucket breakdown of all products: Sin stock (quantity ≤ 0), Stock bajo (quantity ≤ stockMinimo + 2), and Normal. Each bucket contains estado and cantidad (count of products in that state).

altaRotacion

Top-10 products by total units sold in the last 30 days (excluding movements linked to cancelled sales). Each entry includes productoId, nombre, codigo, totalSalidas (number of movement records), and cantidadVendida.

stockCritico

Products at or below their minimum stock threshold. Each entry includes cantidadActual, stockMinimo, consumoDiarioPromedio, and sugerenciaCompra — the recommended reorder quantity.

stockAgotarse

Products projected to run out within 7 days based on average daily consumption over the last 30 days. diasParaAgotarse is null for products without sales history that are already in the critical zone.

sinMovimientos

Products with no stock movement in the last 30 days and a positive quantity, sorted by valorInmovilizado descending. Highlights slow-moving or forgotten inventory.

inventarioGeneral

Full product catalog (up to 500 records) with codigo, nombre, categoria, cantidad, stockMinimo, precio, valorEnStock, estado, and diasDesdeUltimaActividad.

resumen

Daily movement summary for the last 30 days: fecha, entradas, and salidas unit counts. Every day in the window is always present, even if counts are zero.

Dashboard charts

The analytics dashboard renders the above data using Recharts components. The following charts are available:
ComponentData sourceChart type
GraficoVentasDiariasventasPorDiaLine chart — revenue and order count over time
GraficoVentasCategoriaventasPorCategoriaBar chart — top categories by revenue
GraficoDistribucionStockdistribucionStockPie / donut chart — stock health breakdown
GraficoAltaRotacionaltaRotacionHorizontal bar chart — top-10 products by units sold
GraficoMovimientosresumenStacked bar or area chart — daily entries vs. exits

Export

Analytics export

GET /api/analisis/exportar
Returns an .xlsx file containing seven worksheets: Resumen, Inventario general, Por agotarse, Sin movimientos, Alta rotación, Stock crítico, and Movimientos diarios. The filename is timestamped to the America/Bogota timezone (e.g. analisis_inventario_20241120_143022.xlsx). Requires the EXPORTAR_REPORTES permission. Users without it receive a 403 response.

Audit log export

GET /api/auditoria/exportar
Returns an .xlsx file of all Auditoria events for the company — logins, record creations, updates, and deletions — useful for compliance or internal review purposes. Also requires the EXPORTAR_REPORTES permission.

Required permissions

The analytics endpoints are permission-gated. Users must be granted the appropriate permissions by an Admin before they can access these routes.
PermissionGrants access to
VER_ANALISISGET /api/analisis — dashboard data
EXPORTAR_REPORTESGET /api/analisis/exportar and GET /api/auditoria/exportar
Admins (ADMIN and SUPER_ADMIN roles) always have access to both endpoints regardless of their explicit permission set.

Code example — fetch analytics data

const response = await fetch('/api/analisis', {
  method: 'GET',
  headers: { 'Content-Type': 'application/json' },
})

if (!response.ok) {
  // 403 = missing VER_ANALISIS permission
  throw new Error(`Analytics fetch failed: ${response.status}`)
}

const data = await response.json()

// data.ventasPorDia   — VentaDiaria[]
// data.altaRotacion   — ProductoAltaRotacion[]
// data.stockCritico   — AlertaStockCritico[]
// data.distribucionStock — DistribucionStock[]
// data.sinMovimientos — AlertaSinMovimientos[]
// data.stockAgotarse  — AlertaStockAgotarse[]
// data.inventarioGeneral — FilaInventarioGeneral[]
// data.resumen        — ResumenMovimientos[]
// data.ventasPorCategoria — CategoriaVentas[]

console.log(`Productos en stock crítico: ${data.stockCritico.length}`)
console.log(`Ventas hoy: ${data.ventasPorDia.at(-1)?.totalIngreso ?? 0}`)

Build docs developers (and LLMs) love