Build a dbt mart that predicts near-term stockout risk by SKU and warehouse using the enterprise retail warehouse.
harbor run -t snowflake-labs/dbt-inventory-stockout-riskharbor download snowflake-labs/dbt-inventory-stockout-riskBuild a dbt project that calculates comprehensive near-term stockout risk for each SKU at each warehouse location using advanced analytics including multi-period sales velocity, trend analysis, lead time considerations, safety stock calculations, and statistical measures.
/app/dbt_project (create project here)/app/dbt_project (create project here)analytics/app/dbt_transforms (read-only, for reference)This task supports both DuckDB and Snowflake. Run echo $DB_TYPE in a shell BEFORE you write any code or spawn any subagents — the live env determines which backend the verifier runs against. Do NOT assume a default from this prose. Reference dbt projects exist at /app/dbt_models_duckdb/ and /app/dbt_models_snowflake/ for inspection only. Write your dbt project at /app/dbt_project — outputs in the reference directories are not graded.
DB_TYPE=duckdb$DUCKDB_PATH (default: /app/database/retail.duckdb)DB_TYPE=snowflakeSNOWFLAKE_ACCOUNTSNOWFLAKE_USERSNOWFLAKE_PASSWORDSNOWFLAKE_DATABASE - The clone database to useSNOWFLAKE_SCHEMASNOWFLAKE_WAREHOUSESNOWFLAKE_ROLE (optional)Note: For Snowflake, the entrypoint automatically creates a clone database and sets SNOWFLAKE_DATABASE. The clone is destroyed when the task completes.
You must configure dbt to connect to the database:
profiles.yml in the dbt project directory with profile name inventory_stockout_riskDBT_PROFILES_DIR environment variable to the directory containing profiles.ymlConfigure with type: duckdb and the database path from $DUCKDB_PATH.
Configure with type: snowflake using password authentication:
The database contains the following source tables:
INVENTORY.INVENTORY_LEVELS - Current inventory levels by variant and location
variant_id, warehouse_id, quantity_on_hand, quantity_available, quantity_incomingORDERS.ORDER_LINES - Historical order line items
order_id, variant_id, quantity_ordered, unit_priceORDERS.ORDERS - Order header information
order_id, ordered_at, statusPRODUCT.PRODUCT_VARIANTS - Product variant master data
variant_id, product_id, sku, variant_namePRODUCT.PRODUCTS - Product master data
product_id, product_name, category_idINVENTORY.WAREHOUSES - Warehouse master data
warehouse_id, warehouse_name, warehouse_codeINVENTORY.REORDER_RULES - Reorder configuration rules by variant and warehouse
variant_id, warehouse_id, lead_time_days, SAFETY_STOCK (use as safety_stock_days)PROCUREMENT.PURCHASE_ORDERS - Historical purchase orders for lead time analysis
po_id, warehouse_id, ordered_at, expected_date, statusPROCUREMENT.PURCHASE_ORDER_LINES (contains variant_id per line item, linked via po_id) and PROCUREMENT.PURCHASE_ORDER_RECEIPTS (contains received_at per receipt, linked via po_id)/app/dbt_projectprofiles.yml to connect to the database with schema analytics+schema in dbt_project.yml (only set schema in profiles.yml)stg_orders_clean.sqlLocation: models/staging/stg_orders_clean.sql
Purpose: Clean and normalize order data
Requirements:
status = 'CANCELLED'ordered_at is NULLordered_at to TIMESTAMP as order_tsordered_at as order_dateORDERS.ORDER_LINES to get line-level detailsquantity_ordered <= 0Output columns:
order_id (VARCHAR)order_ts (TIMESTAMP)order_date (DATE)variant_id (VARCHAR)quantity_ordered (DECIMAL)unit_price (DECIMAL)int_sales_velocity.sqlLocation: models/intermediate/int_sales_velocity.sql
Purpose: Calculate multi-period sales velocity metrics with statistical measures
Requirements:
variant_id (not per warehouse)MAX(order_date) from the orders data as the reference date for all time-based calculations (do NOT use CURRENT_DATE)avg_daily_sales_7d: Average over last 7 daysavg_daily_sales_30d: Average over last 30 daysavg_daily_sales_90d: Average over last 90 daysavg_daily_sales_7d / NULLIF(avg_daily_sales_30d, 0)'ACCELERATING' when sales_velocity_ratio > 1.2'STABLE' when sales_velocity_ratio >= 0.8 AND sales_velocity_ratio <= 1.2'DECELERATING' when sales_velocity_ratio < 0.8NULL when avg_daily_sales_30d is NULL or 0sales_volatility_30d: Standard deviation of daily sales over last 30 days (NULL if < 2 data points)sales_volatility_90d: Standard deviation of daily sales over last 90 days (NULL if < 2 data points)p25_daily_sales_30d: 25th percentile of daily sales over last 30 daysp75_daily_sales_30d: 75th percentile of daily sales over last 30 daysmedian_daily_sales_30d: Median of daily sales over last 30 daysOutput columns:
variant_id (VARCHAR)avg_daily_sales_7d (DOUBLE)avg_daily_sales_30d (DOUBLE)avg_daily_sales_90d (DOUBLE)sales_velocity_ratio (DOUBLE)trend_direction (VARCHAR)sales_volatility_30d (DOUBLE)sales_volatility_90d (DOUBLE)p25_daily_sales_30d (DOUBLE)p75_daily_sales_30d (DOUBLE)median_daily_sales_30d (DOUBLE)int_lead_time_calculations.sqlLocation: models/intermediate/int_lead_time_calculations.sql
Purpose: Calculate effective lead times with fallback logic
Requirements:
(variant_id, warehouse_id) combinationREORDER_RULES.lead_time_days if availablePURCHASE_ORDERS (status 'RECEIVED' or 'COMPLETED') in last 180 days: AVG(DATEDIFF('day', ordered_at, COALESCE(received_at, expected_date)))lead_time_days: Effective lead time (clamped between 1 and 365)lead_time_std_dev: Standard deviation of lead times from purchase orders (NULL if < 2 data points)lead_time_min: Minimum lead time from purchase orders (NULL if no data)lead_time_max: Maximum lead time from purchase orders (NULL if no data)REORDER_RULES.SAFETY_STOCK or default 7Output columns:
variant_id (VARCHAR)warehouse_id (VARCHAR)lead_time_days (DOUBLE)lead_time_std_dev (DOUBLE)lead_time_min (DOUBLE)lead_time_max (DOUBLE)safety_stock_days (DOUBLE)reorder_point_multiplier (DOUBLE)fct_stockout_risk.sqlLocation: models/marts/operations/fct_stockout_risk.sql
Purpose: Final stockout risk mart with comprehensive risk analysis
Requirements:
(warehouse_id, variant_id) combinationsafety_stock_quantity = safety_stock_days * avg_daily_sales_30d (NULL if no sales)reorder_point = (lead_time_days * avg_daily_sales_30d * reorder_point_multiplier) + safety_stock_quantity (NULL if no sales)days_until_stockout = quantity_available / NULLIF(avg_daily_sales_30d, 0)days_until_reorder_point = (quantity_available - reorder_point) / NULLIF(avg_daily_sales_30d, 0) when quantity_available < reorder_point, else NULL'NO_RISK': avg_daily_sales_30d IS NULL OR avg_daily_sales_30d = 0'CRITICAL':
quantity_available <= safety_stock_quantity ORdays_until_stockout IS NOT NULL AND days_until_stockout <= lead_time_days AND trend_direction IN ('ACCELERATING', 'STABLE')) ORdays_until_stockout IS NOT NULL AND days_until_stockout <= (lead_time_days + COALESCE(lead_time_std_dev, 0)) AND sales_volatility_30d IS NOT NULL AND sales_volatility_30d > (avg_daily_sales_30d * 0.3))'HIGH':
quantity_available > safety_stock_quantity AND quantity_available <= reorder_point ORdays_until_stockout IS NOT NULL AND days_until_stockout <= (lead_time_days + safety_stock_days) AND trend_direction = 'ACCELERATING') ORdays_until_stockout IS NOT NULL AND days_until_stockout <= (lead_time_days + COALESCE(lead_time_std_dev, 0) + safety_stock_days) AND sales_volatility_30d IS NOT NULL AND sales_volatility_30d > (avg_daily_sales_30d * 0.2))'MEDIUM':
quantity_available > reorder_point AND quantity_available <= (reorder_point * 1.5) ORdays_until_stockout IS NOT NULL AND days_until_stockout <= (lead_time_days * 2) AND trend_direction IN ('ACCELERATING', 'STABLE'))'LOW': otherwise'CRITICAL' -> 'URGENT_REORDER''HIGH' -> 'REORDER_NOW''MEDIUM' -> 'PLAN_REORDER''LOW' -> 'MONITOR''NO_RISK' -> 'NO_ACTION'Output columns (in order):
warehouse_name (VARCHAR)product_name (VARCHAR)sku (VARCHAR)quantity_on_hand (DECIMAL)quantity_available (DECIMAL)quantity_incoming (DECIMAL)avg_daily_sales_7d (DOUBLE)avg_daily_sales_30d (DOUBLE)avg_daily_sales_90d (DOUBLE)sales_velocity_ratio (DOUBLE)trend_direction (VARCHAR)sales_volatility_30d (DOUBLE)sales_volatility_90d (DOUBLE)p25_daily_sales_30d (DOUBLE)p75_daily_sales_30d (DOUBLE)median_daily_sales_30d (DOUBLE)lead_time_days (DOUBLE)lead_time_std_dev (DOUBLE)lead_time_min (DOUBLE)lead_time_max (DOUBLE)safety_stock_days (DOUBLE)safety_stock_quantity (DOUBLE)reorder_point_multiplier (DOUBLE)reorder_point (DOUBLE)days_until_stockout (DOUBLE)days_until_reorder_point (DOUBLE)stockout_risk (VARCHAR)recommended_action (VARCHAR)PERCENTILE_CONT (continuous) for percentile calculations(warehouse_id, variant_id) combinationwarehouse_name, product_name, sku (use COALESCE with defaults if needed)avg_daily_sales_* should be NULL or >= 0 (never negative)sales_velocity_ratio should be NULL when avg_daily_sales_30d is 0 or NULLsales_volatility_* should be NULL or >= 0lead_time_days must be between 1 and 365safety_stock_days and reorder_point_multiplier must be > 0days_until_stockout should be NULL when avg_daily_sales_30d is 0 or NULLdays_until_reorder_point should be NULL when quantity_available >= reorder_point or avg_daily_sales_30d is 0 or NULLp25_daily_sales_30d <= median_daily_sales_30d <= p75_daily_sales_30d (when all are non-NULL)(warehouse_id, variant_id) combination