Inventory Debugging: References, Stock, and Valuation
Fix six critical defects in the Código con Criterio warehouse system with Nexo by repairing shared-reference mutations, stock entries/exits, and valuation using find(), map(), reduce(), and spread.
At the Código con Criterio tech warehouse, nightly audits started failing: stock entries overwrote existing quantities, stock exits added units instead of subtracting them, the original inventory was mutated through shared references, and missing products reported a warehouse value of zero. Nexo isolated the solve(input) function and identified six defects.
The function receives an input object with:
productos: array of 0 to 50 objects, each with:
id: unique integer from 1 to 10000.
nombre: non-empty string of 1 to 60 characters.
stock: initial integer from 0 to 1000.
precio: integer from 0 to 1000000 (in cents).
movimiento: object with:
productoId: integer from 1 to 10000 (may not exist in productos).
tipo: "ENTRADA" or "SALIDA".
cantidad: integer from 1 to 1000.
Correct Business Rules
Product lookup: find the product using find(). If it does not exist, reject the operation with movimientoAplicado: false, motivo: "PRODUCTO_NO_ENCONTRADO", stockFinal: null, return in productosActualizados a new array containing copies of the original products, and compute the real warehouse valorInventario.
Upfront validation on exits: if movimiento.tipo === "SALIDA" and movimiento.cantidad > producto.stock, reject the operation before modifying stock with movimientoAplicado: false, motivo: "STOCK_INSUFICIENTE", stockFinal equal to the product's original stock, and a new array in productosActualizados with unchanged quantities.
Immutable movement application:
If "ENTRADA", the new stock is producto.stock + movimiento.cantidad (may exceed 1000).
If a valid "SALIDA" (movimiento.cantidad <= producto.stock), the new stock is producto.stock - movimiento.cantidad.
Build productosActualizados with map(), copying the affected product via spread (...) to update its stock, without mutating input.productos or any of its objects.
Total valuation (valorInventario): use reduce() over productosActualizados to sum precio * stock across all products in every scenario (applied movement, insufficient stock, or product not found).
Return Value
Return an object with exactly five properties:
productosActualizados: new array of { id, nombre, stock, precio } objects in their original order.
movimientoAplicado: boolean.
motivo: "OK", "PRODUCTO_NO_ENCONTRADO", or "STOCK_INSUFICIENTE".
stockFinal: integer with the resulting stock (or original stock on "STOCK_INSUFICIENTE"), or null if the product does not exist.
valorInventario: integer sum in cents of precio * stock across all products in productosActualizados.