Inventory Forecasting
Relevant source files
The following files were used as context for generating this wiki page:
Inventory Forecasting in DRX is a predictive system designed to prevent stockouts and optimize stock levels using historical sales data and AI-driven analysis. It enables businesses to project stock depletion dates, receive automated restock recommendations, and identify inventory risks such as overstock or stagnant products.
The system operates through a combination of local utility classes, edge functions for heavy computation, and background health checks that leverage OpenAI for deep business insights. It integrates tightly with the core Inventory Management and Sales Analytics modules.
Sources: README.md:16-17, lib/utils/inventory-engine.ts:241-280
Core Architecture
The forecasting logic is centralized in the InventoryEngine class, which processes raw sales data into actionable metrics. The architecture follows a data flow from sales line items to velocity calculations, which then feed the forecasting models.
Data Flow for Forecast Generation
The following diagram illustrates how raw sales data is transformed into a comprehensive inventory forecast.
The system calculates sales velocity (units sold per day) across three distinct windows: 7 days, 30 days, and 90 days. This multi-window approach allows the engine to detect short-term spikes versus long-term stability.
Sources: lib/utils/inventory-engine.ts:31-68, edge/ai_pricing_inventory/index.ts:70-98
Technical Components
InventoryEngine Class
The InventoryEngine is the primary logic provider. It handles the mathematical modeling required to determine when a product will reach zero quantity.
| Method | Description |
|---|---|
calculateVelocity | Queries sales line items to determine average daily units sold. |
generateForecast | Main entry point that aggregates factors like lead time, current stock, and seasonality. |
calculateStockoutProjection | Projects the specific date of stock depletion based on active velocity. |
calculateRestockQuantity | Recommends order volume based on a target coverage period (typically 45-60 days). |
processForecastAndAlerts | Generates system notifications for demand spikes or critical risks. |
| Sources: lib/utils/inventory-engine.ts:29-307 |
AI Integration
The project utilizes Edge Functions and Supabase Functions to perform AI-enhanced health checks. These functions analyze inventory value, identify low-stock items, and use GPT models to generate specific action recommendations.
Key Forecasting Logic
Velocity Trend Detection
The system classifies sales trends into four categories based on the percentage change between recent (7d) and previous (30d) velocity:
- Accelerating: Growth > 20%
- Declining: Reduction > 20%
- Stable: Change within +/- 20%
- Stagnant: No sales detected or 0 recent velocity.
Sources: lib/utils/inventory-engine.ts:73-92
Urgency and Risk Levels
The engine assigns an inventoryRiskLevel and restockUrgency to each item to prioritize manager attention.
| Level | Condition |
|---|---|
| Critical | Reorder due date (Stockout - Lead Time) <= 0 days. |
| High Risk | Current stock < 50% of reorder level OR Demand > Reorder Level. |
| Medium Risk | Stockout projected within 14-30 days OR Stagnant product. |
| Low Risk | Ample supply (>30 days) and stock above reorder level. |
| Sources: lib/utils/inventory-engine.ts:117-167 |
Data Schema
Forecasts and health metrics are persisted in specialized tables to maintain a historical audit trail of AI decisions.
Inventory Forecast Record
- Table:
inventory_forecasts - Field:
projected_stockout_date(Date) - Field:
velocity_trend(accelerating | stable | declining | stagnant) - Field:
recommended_restock_quantity(Decimal) - Field:
confidence_score(Decimal: 0-95)
Sources: edge/ai_pricing_inventory/index.ts:182-198, lib/utils/inventory-engine.ts:285-300
Inventory Stock Movements
Stock levels are monitored through the stock_movements table, which tracks changes due to sales, shrinkage, or manual adjustments.
Sources: db/migrations/20250228000001_pos_weight_shrinkage_loyalty_consolidated.json:step_10
// Example of a Forecast Result structure
export interface InventoryForecastResult {
projectedStockoutDate: string | null;
daysUntilStockout: number | null;
recommendedRestockQuantity: number;
restockUrgency: "low" | "medium" | "high" | "critical";
inventoryRiskLevel: "low" | "medium" | "high";
reasoning: string;
confidenceScore: number;
}
Sources: lib/utils/inventory-engine.ts:16-27
Conclusion
Inventory Forecasting in DRX provides a proactive layer to retail operations. By transforming historical transaction data into time-based projections and urgency levels, the system ensures that managers can maintain optimal stock levels without manual calculation. The integration of AI insights further enhances this by providing natural language reasoning for complex inventory health scenarios.
Sources: README.md:113-118, lib/utils/inventory-engine.ts:325-360