Lookback for MO generation misses some consumption #6

Closed
opened 2026-02-11 17:18:53 +00:00 by chris-kreidl · 8 comments
chris-kreidl commented 2026-02-11 17:18:53 +00:00 (Migrated from github.com)

We currently examine only sales order rows to determine usage for purposes of generating manufacturing orders.

When calculating usage for generating purchase orders we also consider units consumed in assemblies.

Manufacturing order calculations should also consider units consumed via assembly as those are still units that need to be made.

We should probably refactor to utilize the same Katana endpoint as we do to calculate consumption for purchase orders.

We currently examine only sales order rows to determine usage for purposes of generating manufacturing orders. When calculating usage for generating purchase orders we also consider units consumed in assemblies. Manufacturing order calculations should also consider units consumed via assembly as those are still units that need to be made. We should probably refactor to utilize the same Katana endpoint as we do to calculate consumption for purchase orders.
chris-kreidl commented 2026-02-11 17:19:18 +00:00 (Migrated from github.com)

@coderabbitai plan

@coderabbitai plan
coderabbitai[bot] commented 2026-02-11 17:24:43 +00:00 (Migrated from github.com)

Coding Plan

Summary

  • Refactor fetchHistoricalDemand() to separate data fetching from calculation logic, enabling code reuse and testability
  • Create pure calculation functions in the compute/ directory following existing codebase patterns
  • Reuse the existing fetchConsumptionFromInventoryMovements() function, avoiding code duplication
  • Add assembly consumption to sales-based demand (additive approach), preserving weighted velocity forecasting for direct sales
  • Three-phase approach ensures each change is isolated and testable before integration
Design Choices
Design Choice 1: How should assembly consumption be combined with sales-based demand?

Options Considered:

  1. Replace sales-based demand entirely with inventory movements consumption (like PO generation does)
  2. Add assembly consumption to sales-based demand (additive approach preserving sales forecasting)
  3. Use the maximum of sales demand and consumption-based demand for each variant

Chosen Option: 2

Rationale: Additive approach - Add assembly consumption to the existing sales-based demand horizon. This preserves the weighted velocity forecasting for direct sales while ensuring assembly consumption is also captured. A variant's total demand = direct sales demand + units consumed in assemblies.

💡 User Tips

Regenerate the plan with different choices with @coderabbitai <feedback>.

Implementation Steps

Phase 1: Data Layer Refactoring

Separate data fetching from calculation logic in fetchHistoricalDemand() to enable reuse and testability. This phase preserves all existing functionality while restructuring for better separation of concerns.

Task 1: Extract Sales Row Aggregation Logic

Extract the pure aggregation logic from fetchHistoricalDemand() into a separate function.

  • Create a new pure function aggregateSalesRows() in packages/katana-mo-cli/src/api/katana.ts
  • Move the row processing logic (accumulating totals and recentTotals by variant_id) from fetchHistoricalDemand() lines 323-335 into this function
  • Function should accept an array of sales order rows and a recent start date, returning { totals, recentTotals } objects
  • This function is pure and testable - no API calls
Task 2: Extract Demand Forecast Calculation

Extract the weighted velocity calculation and demand horizon projection into a pure function.

  • Create a new pure function calculateDemandForecasts() in packages/katana-mo-cli/src/compute/ directory to follow existing patterns
  • Move the calculation logic from fetchHistoricalDemand() lines 347-363 (rate calculation, weighted velocity, horizon projection) into this function
  • Function accepts: candidates, aggregated totals, recentTotals, and forecast parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod)
  • Function returns the same Record<number, DemandEntry> structure as current implementation
  • Include the existing edge case handling (division by zero protection, missing data defaults)
Task 3: Refactor fetchHistoricalDemand to Use Extracted Functions

Update fetchHistoricalDemand() to use the newly extracted functions while maintaining identical external behavior.

  • Modify fetchHistoricalDemand() in packages/katana-mo-cli/src/api/katana.ts to call aggregateSalesRows() for row processing
  • Call calculateDemandForecasts() for the final demand calculation
  • The function's signature and return type remain unchanged - this is purely an internal refactor
  • Existing callers (runPipeline.ts) continue to work without modification
🤖 Prompt for AI agents
This phase refactors `fetchHistoricalDemand()` to separate data fetching from
calculation logic, enabling better code reuse and testability. All existing
functionality must be preserved.

**Extract Sales Row Aggregation Logic:**
- Create a new pure function `aggregateSalesRows()` in
`packages/katana-mo-cli/src/api/katana.ts`
- Extract the row processing logic from `fetchHistoricalDemand()` lines 323-335
that accumulates totals and recentTotals by variant_id
- Function signature should accept: an array of sales order rows and a recent
start date parameter
- Function should return an object with `{ totals, recentTotals }` structure
- This function should be pure (no side effects, no API calls) and testable

**Extract Demand Forecast Calculation:**
- Create a new pure function `calculateDemandForecasts()` in
`packages/katana-mo-cli/src/compute/` directory (following existing codebase
patterns for computation logic)
- Extract the calculation logic from `fetchHistoricalDemand()` lines 347-363,
including: rate calculation, weighted velocity computation, and horizon
projection
- Function parameters: candidates, aggregated totals, recentTotals, and forecast
parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod)
- Return type: `Record<number, DemandEntry>` (same structure as current
implementation)
- Include all existing edge case handling: division by zero protection, missing
data defaults

**Refactor fetchHistoricalDemand:**
- Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts`
to use the newly extracted functions
- Replace the inline row processing logic with a call to `aggregateSalesRows()`
- Replace the inline calculation logic with a call to
`calculateDemandForecasts()`
- The function's signature and return type must remain unchanged - this is
purely an internal refactor
- Ensure existing callers in `runPipeline.ts` continue to work without any
modifications

Phase 2: Calculation Layer for Assembly Consumption

Create the calculation function for converting assembly consumption data into demand horizon values, mirroring the approach used in PO generation.

Task 1: Create Consumption-to-Demand Calculation Function

Create a pure function to convert raw consumption totals into demand horizon projections.

  • Create calculateConsumptionDemand() function in packages/katana-mo-cli/src/compute/ directory
  • Function accepts: consumption totals (Record<number, number> from fetchConsumptionFromInventoryMovements), lookbackDays, horizonDays
  • Apply the same formula used in PO generation: demand_horizon = (total_consumed / lookbackDays) * horizonDays
  • Return a structure compatible with the existing demand format for easy merging
  • Handle edge cases: zero consumption, invalid lookback periods
Task 2: Create Demand Merging Function

Create a pure function to combine sales-based demand with assembly consumption demand.

  • Create mergeDemandSources() function in packages/katana-mo-cli/src/compute/ directory
  • Accept two demand sources: sales-based demand and consumption-based demand (both as Record<number, DemandEntry> or compatible structure)
  • For each variant, add the assembly consumption demand_horizon to the sales-based demand_horizon
  • Handle variants that appear in only one source (preserve the available demand value)
  • Return the merged demand in the same format expected by computeMoDryRun()
🤖 Prompt for AI agents
This phase creates pure calculation functions for converting assembly
consumption data into demand values and merging it with sales-based demand.

**Create Consumption-to-Demand Calculation Function:**
- Create `calculateConsumptionDemand()` function in
`packages/katana-mo-cli/src/compute/` directory
- Function parameters: consumption totals as `Record<number, number>` (from
`fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays
- Apply the PO generation formula: `demand_horizon = (total_consumed /
lookbackDays) * horizonDays`
- Return a structure compatible with the existing demand format to enable easy
merging
- Handle edge cases: zero consumption values, invalid lookback periods (avoid
division by zero)

**Create Demand Merging Function:**
- Create `mergeDemandSources()` function in
`packages/katana-mo-cli/src/compute/` directory
- Function parameters: two demand sources - sales-based demand and
consumption-based demand (both as `Record<number, DemandEntry>` or compatible
structure)
- Merging logic: For each variant, add the assembly consumption demand_horizon
value to the sales-based demand_horizon value
- Handle variants that only appear in one source by preserving the available
demand value
- Return format: merged demand in the same format expected by
`computeMoDryRun()`

Phase 3: Pipeline Integration

Wire the new data fetching and calculation functions into the MO pipeline, enabling assembly consumption to be included in demand calculations.

Task 1: Fetch Assembly Consumption Data in MO Pipeline

Add inventory movement data fetching to the MO pipeline data gathering phase.

  • In packages/katana-mo-cli/src/runPipeline.ts, within fetchMoPipelineData(), add a call to existing fetchConsumptionFromInventoryMovements() after fetching historical demand
  • Pass the producible variant IDs (from the candidates list) to the consumption fetch
  • Use resource type ["ProductionIngredient"] to capture consumption of finished goods used as ingredients in other assemblies
  • Apply the same lookback period configuration (settings.lookbackDays) used for sales-based demand
  • Include zero-consumption fallback logic similar to PO generation (extended lookback for variants with zero consumption)
Task 2: Compose and Integrate Merged Demand

Wire the calculation functions together to produce the final merged demand for MO generation.

  • In fetchMoPipelineData(), after fetching both data sources:
    • Call calculateConsumptionDemand() with the assembly consumption data
    • Call mergeDemandSources() to combine with existing sales-based demand
  • Update fetchMoPipelineData() return to use the merged demand
  • No changes needed to computeMoDryRun() in packages/katana-mo-cli/src/compute/dryRun.ts - it already consumes demand_horizon values; the values will now include assembly consumption
🤖 Prompt for AI agents
This phase integrates assembly consumption data fetching and the new calculation
functions into the MO pipeline to produce merged demand values.

**Fetch Assembly Consumption Data:**
- In `packages/katana-mo-cli/src/runPipeline.ts`, locate the
`fetchMoPipelineData()` function
- After the existing call to `fetchHistoricalDemand()`, add a call to the
existing `fetchConsumptionFromInventoryMovements()` function
- Pass the producible variant IDs from the candidates list as the variant IDs
parameter
- Use resource type `["ProductionIngredient"]` to capture consumption of
finished goods used as ingredients in assemblies
- Apply the same lookback period (`settings.lookbackDays`) used for sales-based
demand
- Implement zero-consumption fallback logic similar to PO generation: for
variants with zero consumption in the primary lookback period, use an extended
lookback period

**Compose and Integrate Merged Demand:**
- In `fetchMoPipelineData()`, after fetching both sales demand and assembly
consumption data:
- Call `calculateConsumptionDemand()` with the assembly consumption data,
lookbackDays, and horizonDays
- Call `mergeDemandSources()` to combine the consumption-based demand with the
existing sales-based demand
- Update the `fetchMoPipelineData()` return value to use the merged demand
instead of only sales-based demand
- Note: No changes are needed to `computeMoDryRun()` in
`packages/katana-mo-cli/src/compute/dryRun.ts` - it already processes
`demand_horizon` values and will now receive values that include assembly
consumption
Research

The katana-mo-cli package handles both MO and PO generation through a pipeline architecture. MO generation in runPipeline.ts fetches demand via fetchHistoricalDemand() in api/katana.ts, which queries sales order rows. PO generation correctly uses fetchConsumptionFromInventoryMovements() to capture all consumption including assembly usage. The compute/dryRun.ts module calculates MO quantities based on the demand data it receives. The existing inventory movements API wrapper already supports the required resource types (ProductionIngredient, Production). Critically, fetchHistoricalDemand() currently couples API data fetching with calculation logic, making it difficult to add new data sources without code duplication.


🚀 Next Steps

🤖 All AI agent prompts combined
Task: 1

This phase refactors `fetchHistoricalDemand()` to separate data fetching from
calculation logic, enabling better code reuse and testability. All existing
functionality must be preserved.

**Extract Sales Row Aggregation Logic:**
- Create a new pure function `aggregateSalesRows()` in
`packages/katana-mo-cli/src/api/katana.ts`
- Extract the row processing logic from `fetchHistoricalDemand()` lines 323-335
that accumulates totals and recentTotals by variant_id
- Function signature should accept: an array of sales order rows and a recent
start date parameter
- Function should return an object with `{ totals, recentTotals }` structure
- This function should be pure (no side effects, no API calls) and testable

**Extract Demand Forecast Calculation:**
- Create a new pure function `calculateDemandForecasts()` in
`packages/katana-mo-cli/src/compute/` directory (following existing codebase
patterns for computation logic)
- Extract the calculation logic from `fetchHistoricalDemand()` lines 347-363,
including: rate calculation, weighted velocity computation, and horizon
projection
- Function parameters: candidates, aggregated totals, recentTotals, and forecast
parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod)
- Return type: `Record<number, DemandEntry>` (same structure as current
implementation)
- Include all existing edge case handling: division by zero protection, missing
data defaults

**Refactor fetchHistoricalDemand:**
- Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts`
to use the newly extracted functions
- Replace the inline row processing logic with a call to `aggregateSalesRows()`
- Replace the inline calculation logic with a call to
`calculateDemandForecasts()`
- The function's signature and return type must remain unchanged - this is
purely an internal refactor
- Ensure existing callers in `runPipeline.ts` continue to work without any
modifications
===============================================================================

Task: 2

This phase creates pure calculation functions for converting assembly
consumption data into demand values and merging it with sales-based demand.

**Create Consumption-to-Demand Calculation Function:**
- Create `calculateConsumptionDemand()` function in
`packages/katana-mo-cli/src/compute/` directory
- Function parameters: consumption totals as `Record<number, number>` (from
`fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays
- Apply the PO generation formula: `demand_horizon = (total_consumed /
lookbackDays) * horizonDays`
- Return a structure compatible with the existing demand format to enable easy
merging
- Handle edge cases: zero consumption values, invalid lookback periods (avoid
division by zero)

**Create Demand Merging Function:**
- Create `mergeDemandSources()` function in
`packages/katana-mo-cli/src/compute/` directory
- Function parameters: two demand sources - sales-based demand and
consumption-based demand (both as `Record<number, DemandEntry>` or compatible
structure)
- Merging logic: For each variant, add the assembly consumption demand_horizon
value to the sales-based demand_horizon value
- Handle variants that only appear in one source by preserving the available
demand value
- Return format: merged demand in the same format expected by
`computeMoDryRun()`
===============================================================================

Task: 3

This phase integrates assembly consumption data fetching and the new calculation
functions into the MO pipeline to produce merged demand values.

**Fetch Assembly Consumption Data:**
- In `packages/katana-mo-cli/src/runPipeline.ts`, locate the
`fetchMoPipelineData()` function
- After the existing call to `fetchHistoricalDemand()`, add a call to the
existing `fetchConsumptionFromInventoryMovements()` function
- Pass the producible variant IDs from the candidates list as the variant IDs
parameter
- Use resource type `["ProductionIngredient"]` to capture consumption of
finished goods used as ingredients in assemblies
- Apply the same lookback period (`settings.lookbackDays`) used for sales-based
demand
- Implement zero-consumption fallback logic similar to PO generation: for
variants with zero consumption in the primary lookback period, use an extended
lookback period

**Compose and Integrate Merged Demand:**
- In `fetchMoPipelineData()`, after fetching both sales demand and assembly
consumption data:
- Call `calculateConsumptionDemand()` with the assembly consumption data,
lookbackDays, and horizonDays
- Call `mergeDemandSources()` to combine the consumption-based demand with the
existing sales-based demand
- Update the `fetchMoPipelineData()` return value to use the merged demand
instead of only sales-based demand
- Note: No changes are needed to `computeMoDryRun()` in
`packages/katana-mo-cli/src/compute/dryRun.ts` - it already processes
`demand_horizon` values and will now receive values that include assembly
consumption
💡 Iterate on the plan with: @coderabbitai <feedback>
Example Feedback
- @coderabbitai You can skip phase 3. Add a simple unit test case for phase 2.
- @coderabbitai For design choice 1 go ahead with option 3 and replan.

💬 Have feedback or questions? Drop into our discord!

<!-- This is an auto-generated reply by CodeRabbit --> ## Coding Plan ### Summary - Refactor `fetchHistoricalDemand()` to separate data fetching from calculation logic, enabling code reuse and testability - Create pure calculation functions in the `compute/` directory following existing codebase patterns - Reuse the existing `fetchConsumptionFromInventoryMovements()` function, avoiding code duplication - Add assembly consumption to sales-based demand (additive approach), preserving weighted velocity forecasting for direct sales - Three-phase approach ensures each change is isolated and testable before integration <details> <summary><b>Design Choices</b></summary> <details> <summary><b>Design Choice 1: How should assembly consumption be combined with sales-based demand?</b></summary> **Options Considered:** 1. Replace sales-based demand entirely with inventory movements consumption (like PO generation does) 2. Add assembly consumption to sales-based demand (additive approach preserving sales forecasting) 3. Use the maximum of sales demand and consumption-based demand for each variant **Chosen Option:** 2 **Rationale:** Additive approach - Add assembly consumption to the existing sales-based demand horizon. This preserves the weighted velocity forecasting for direct sales while ensuring assembly consumption is also captured. A variant's total demand = direct sales demand + units consumed in assemblies. </details> </details> <b>💡 User Tips</b> Regenerate the plan with different choices with `@coderabbitai <feedback>`. ## Implementation Steps ### Phase 1: Data Layer Refactoring Separate data fetching from calculation logic in `fetchHistoricalDemand()` to enable reuse and testability. This phase preserves all existing functionality while restructuring for better separation of concerns. <details> <summary><b>Task 1: Extract Sales Row Aggregation Logic</b></summary> Extract the pure aggregation logic from `fetchHistoricalDemand()` into a separate function. - Create a new pure function `aggregateSalesRows()` in `packages/katana-mo-cli/src/api/katana.ts` - Move the row processing logic (accumulating totals and recentTotals by variant_id) from `fetchHistoricalDemand()` lines 323-335 into this function - Function should accept an array of sales order rows and a recent start date, returning `{ totals, recentTotals }` objects - This function is pure and testable - no API calls </details> <details> <summary><b>Task 2: Extract Demand Forecast Calculation</b></summary> Extract the weighted velocity calculation and demand horizon projection into a pure function. - Create a new pure function `calculateDemandForecasts()` in `packages/katana-mo-cli/src/compute/` directory to follow existing patterns - Move the calculation logic from `fetchHistoricalDemand()` lines 347-363 (rate calculation, weighted velocity, horizon projection) into this function - Function accepts: candidates, aggregated totals, recentTotals, and forecast parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod) - Function returns the same `Record<number, DemandEntry>` structure as current implementation - Include the existing edge case handling (division by zero protection, missing data defaults) </details> <details> <summary><b>Task 3: Refactor fetchHistoricalDemand to Use Extracted Functions</b></summary> Update `fetchHistoricalDemand()` to use the newly extracted functions while maintaining identical external behavior. - Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts` to call `aggregateSalesRows()` for row processing - Call `calculateDemandForecasts()` for the final demand calculation - The function's signature and return type remain unchanged - this is purely an internal refactor - Existing callers (`runPipeline.ts`) continue to work without modification </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase refactors `fetchHistoricalDemand()` to separate data fetching from calculation logic, enabling better code reuse and testability. All existing functionality must be preserved. **Extract Sales Row Aggregation Logic:** - Create a new pure function `aggregateSalesRows()` in `packages/katana-mo-cli/src/api/katana.ts` - Extract the row processing logic from `fetchHistoricalDemand()` lines 323-335 that accumulates totals and recentTotals by variant_id - Function signature should accept: an array of sales order rows and a recent start date parameter - Function should return an object with `{ totals, recentTotals }` structure - This function should be pure (no side effects, no API calls) and testable **Extract Demand Forecast Calculation:** - Create a new pure function `calculateDemandForecasts()` in `packages/katana-mo-cli/src/compute/` directory (following existing codebase patterns for computation logic) - Extract the calculation logic from `fetchHistoricalDemand()` lines 347-363, including: rate calculation, weighted velocity computation, and horizon projection - Function parameters: candidates, aggregated totals, recentTotals, and forecast parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod) - Return type: `Record<number, DemandEntry>` (same structure as current implementation) - Include all existing edge case handling: division by zero protection, missing data defaults **Refactor fetchHistoricalDemand:** - Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts` to use the newly extracted functions - Replace the inline row processing logic with a call to `aggregateSalesRows()` - Replace the inline calculation logic with a call to `calculateDemandForecasts()` - The function's signature and return type must remain unchanged - this is purely an internal refactor - Ensure existing callers in `runPipeline.ts` continue to work without any modifications ``` </details> ### Phase 2: Calculation Layer for Assembly Consumption Create the calculation function for converting assembly consumption data into demand horizon values, mirroring the approach used in PO generation. <details> <summary><b>Task 1: Create Consumption-to-Demand Calculation Function</b></summary> Create a pure function to convert raw consumption totals into demand horizon projections. - Create `calculateConsumptionDemand()` function in `packages/katana-mo-cli/src/compute/` directory - Function accepts: consumption totals (Record<number, number> from `fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays - Apply the same formula used in PO generation: `demand_horizon = (total_consumed / lookbackDays) * horizonDays` - Return a structure compatible with the existing demand format for easy merging - Handle edge cases: zero consumption, invalid lookback periods </details> <details> <summary><b>Task 2: Create Demand Merging Function</b></summary> Create a pure function to combine sales-based demand with assembly consumption demand. - Create `mergeDemandSources()` function in `packages/katana-mo-cli/src/compute/` directory - Accept two demand sources: sales-based demand and consumption-based demand (both as `Record<number, DemandEntry>` or compatible structure) - For each variant, add the assembly consumption demand_horizon to the sales-based demand_horizon - Handle variants that appear in only one source (preserve the available demand value) - Return the merged demand in the same format expected by `computeMoDryRun()` </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase creates pure calculation functions for converting assembly consumption data into demand values and merging it with sales-based demand. **Create Consumption-to-Demand Calculation Function:** - Create `calculateConsumptionDemand()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: consumption totals as `Record<number, number>` (from `fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays - Apply the PO generation formula: `demand_horizon = (total_consumed / lookbackDays) * horizonDays` - Return a structure compatible with the existing demand format to enable easy merging - Handle edge cases: zero consumption values, invalid lookback periods (avoid division by zero) **Create Demand Merging Function:** - Create `mergeDemandSources()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: two demand sources - sales-based demand and consumption-based demand (both as `Record<number, DemandEntry>` or compatible structure) - Merging logic: For each variant, add the assembly consumption demand_horizon value to the sales-based demand_horizon value - Handle variants that only appear in one source by preserving the available demand value - Return format: merged demand in the same format expected by `computeMoDryRun()` ``` </details> ### Phase 3: Pipeline Integration Wire the new data fetching and calculation functions into the MO pipeline, enabling assembly consumption to be included in demand calculations. <details> <summary><b>Task 1: Fetch Assembly Consumption Data in MO Pipeline</b></summary> Add inventory movement data fetching to the MO pipeline data gathering phase. - In `packages/katana-mo-cli/src/runPipeline.ts`, within `fetchMoPipelineData()`, add a call to existing `fetchConsumptionFromInventoryMovements()` after fetching historical demand - Pass the producible variant IDs (from the candidates list) to the consumption fetch - Use resource type `["ProductionIngredient"]` to capture consumption of finished goods used as ingredients in other assemblies - Apply the same lookback period configuration (`settings.lookbackDays`) used for sales-based demand - Include zero-consumption fallback logic similar to PO generation (extended lookback for variants with zero consumption) </details> <details> <summary><b>Task 2: Compose and Integrate Merged Demand</b></summary> Wire the calculation functions together to produce the final merged demand for MO generation. - In `fetchMoPipelineData()`, after fetching both data sources: - Call `calculateConsumptionDemand()` with the assembly consumption data - Call `mergeDemandSources()` to combine with existing sales-based demand - Update `fetchMoPipelineData()` return to use the merged demand - No changes needed to `computeMoDryRun()` in `packages/katana-mo-cli/src/compute/dryRun.ts` - it already consumes `demand_horizon` values; the values will now include assembly consumption </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase integrates assembly consumption data fetching and the new calculation functions into the MO pipeline to produce merged demand values. **Fetch Assembly Consumption Data:** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `fetchMoPipelineData()` function - After the existing call to `fetchHistoricalDemand()`, add a call to the existing `fetchConsumptionFromInventoryMovements()` function - Pass the producible variant IDs from the candidates list as the variant IDs parameter - Use resource type `["ProductionIngredient"]` to capture consumption of finished goods used as ingredients in assemblies - Apply the same lookback period (`settings.lookbackDays`) used for sales-based demand - Implement zero-consumption fallback logic similar to PO generation: for variants with zero consumption in the primary lookback period, use an extended lookback period **Compose and Integrate Merged Demand:** - In `fetchMoPipelineData()`, after fetching both sales demand and assembly consumption data: - Call `calculateConsumptionDemand()` with the assembly consumption data, lookbackDays, and horizonDays - Call `mergeDemandSources()` to combine the consumption-based demand with the existing sales-based demand - Update the `fetchMoPipelineData()` return value to use the merged demand instead of only sales-based demand - Note: No changes are needed to `computeMoDryRun()` in `packages/katana-mo-cli/src/compute/dryRun.ts` - it already processes `demand_horizon` values and will now receive values that include assembly consumption ``` </details> <details> <summary><b>Research</b></summary> The `katana-mo-cli` package handles both MO and PO generation through a pipeline architecture. MO generation in `runPipeline.ts` fetches demand via `fetchHistoricalDemand()` in `api/katana.ts`, which queries sales order rows. PO generation correctly uses `fetchConsumptionFromInventoryMovements()` to capture all consumption including assembly usage. The `compute/dryRun.ts` module calculates MO quantities based on the demand data it receives. The existing inventory movements API wrapper already supports the required resource types (`ProductionIngredient`, `Production`). Critically, `fetchHistoricalDemand()` currently couples API data fetching with calculation logic, making it difficult to add new data sources without code duplication. </details> --- ### 🚀 Next Steps <details> <summary><b>🤖 All AI agent prompts combined</b></summary> ``` Task: 1 This phase refactors `fetchHistoricalDemand()` to separate data fetching from calculation logic, enabling better code reuse and testability. All existing functionality must be preserved. **Extract Sales Row Aggregation Logic:** - Create a new pure function `aggregateSalesRows()` in `packages/katana-mo-cli/src/api/katana.ts` - Extract the row processing logic from `fetchHistoricalDemand()` lines 323-335 that accumulates totals and recentTotals by variant_id - Function signature should accept: an array of sales order rows and a recent start date parameter - Function should return an object with `{ totals, recentTotals }` structure - This function should be pure (no side effects, no API calls) and testable **Extract Demand Forecast Calculation:** - Create a new pure function `calculateDemandForecasts()` in `packages/katana-mo-cli/src/compute/` directory (following existing codebase patterns for computation logic) - Extract the calculation logic from `fetchHistoricalDemand()` lines 347-363, including: rate calculation, weighted velocity computation, and horizon projection - Function parameters: candidates, aggregated totals, recentTotals, and forecast parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod) - Return type: `Record<number, DemandEntry>` (same structure as current implementation) - Include all existing edge case handling: division by zero protection, missing data defaults **Refactor fetchHistoricalDemand:** - Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts` to use the newly extracted functions - Replace the inline row processing logic with a call to `aggregateSalesRows()` - Replace the inline calculation logic with a call to `calculateDemandForecasts()` - The function's signature and return type must remain unchanged - this is purely an internal refactor - Ensure existing callers in `runPipeline.ts` continue to work without any modifications =============================================================================== Task: 2 This phase creates pure calculation functions for converting assembly consumption data into demand values and merging it with sales-based demand. **Create Consumption-to-Demand Calculation Function:** - Create `calculateConsumptionDemand()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: consumption totals as `Record<number, number>` (from `fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays - Apply the PO generation formula: `demand_horizon = (total_consumed / lookbackDays) * horizonDays` - Return a structure compatible with the existing demand format to enable easy merging - Handle edge cases: zero consumption values, invalid lookback periods (avoid division by zero) **Create Demand Merging Function:** - Create `mergeDemandSources()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: two demand sources - sales-based demand and consumption-based demand (both as `Record<number, DemandEntry>` or compatible structure) - Merging logic: For each variant, add the assembly consumption demand_horizon value to the sales-based demand_horizon value - Handle variants that only appear in one source by preserving the available demand value - Return format: merged demand in the same format expected by `computeMoDryRun()` =============================================================================== Task: 3 This phase integrates assembly consumption data fetching and the new calculation functions into the MO pipeline to produce merged demand values. **Fetch Assembly Consumption Data:** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `fetchMoPipelineData()` function - After the existing call to `fetchHistoricalDemand()`, add a call to the existing `fetchConsumptionFromInventoryMovements()` function - Pass the producible variant IDs from the candidates list as the variant IDs parameter - Use resource type `["ProductionIngredient"]` to capture consumption of finished goods used as ingredients in assemblies - Apply the same lookback period (`settings.lookbackDays`) used for sales-based demand - Implement zero-consumption fallback logic similar to PO generation: for variants with zero consumption in the primary lookback period, use an extended lookback period **Compose and Integrate Merged Demand:** - In `fetchMoPipelineData()`, after fetching both sales demand and assembly consumption data: - Call `calculateConsumptionDemand()` with the assembly consumption data, lookbackDays, and horizonDays - Call `mergeDemandSources()` to combine the consumption-based demand with the existing sales-based demand - Update the `fetchMoPipelineData()` return value to use the merged demand instead of only sales-based demand - Note: No changes are needed to `computeMoDryRun()` in `packages/katana-mo-cli/src/compute/dryRun.ts` - it already processes `demand_horizon` values and will now receive values that include assembly consumption ``` </details> <details> <summary><b>💡 Iterate on the plan with: <code>@coderabbitai &lt;feedback&gt;</code> </b></summary> ``` Example Feedback - @coderabbitai You can skip phase 3. Add a simple unit test case for phase 2. - @coderabbitai For design choice 1 go ahead with option 3 and replan. ``` </details> --- 💬 Have feedback or questions? Drop into our [discord](https://discord.gg/coderabbit)! <!-- <agentComponentType>plan-edits</agentComponentType> --> <!-- <rawResChunk><planningResult>## Coding Plan ### Summary - Refactor `fetchHistoricalDemand()` to separate data fetching from calculation logic, enabling code reuse and testability - Create pure calculation functions in the `compute/` directory following existing codebase patterns - Reuse the existing `fetchConsumptionFromInventoryMovements()` function, avoiding code duplication - Add assembly consumption to sales-based demand (additive approach), preserving weighted velocity forecasting for direct sales - Three-phase approach ensures each change is isolated and testable before integration <details> <summary><b>Design Choices</b></summary> <details> <summary><b>Design Choice 1: How should assembly consumption be combined with sales-based demand?</b></summary> **Options Considered:** 1. Replace sales-based demand entirely with inventory movements consumption (like PO generation does) 2. Add assembly consumption to sales-based demand (additive approach preserving sales forecasting) 3. Use the maximum of sales demand and consumption-based demand for each variant **Chosen Option:** 2 **Rationale:** Additive approach - Add assembly consumption to the existing sales-based demand horizon. This preserves the weighted velocity forecasting for direct sales while ensuring assembly consumption is also captured. A variant's total demand = direct sales demand + units consumed in assemblies. </details> </details> <b>💡 User Tips</b> Regenerate the plan with different choices with `@coderabbitai <feedback>`. ## Implementation Steps ### Phase 1: Data Layer Refactoring Separate data fetching from calculation logic in `fetchHistoricalDemand()` to enable reuse and testability. This phase preserves all existing functionality while restructuring for better separation of concerns. <details> <summary><b>Task 1: Extract Sales Row Aggregation Logic</b></summary> Extract the pure aggregation logic from `fetchHistoricalDemand()` into a separate function. - Create a new pure function `aggregateSalesRows()` in `packages/katana-mo-cli/src/api/katana.ts` - Move the row processing logic (accumulating totals and recentTotals by variant_id) from `fetchHistoricalDemand()` lines 323-335 into this function - Function should accept an array of sales order rows and a recent start date, returning `{ totals, recentTotals }` objects - This function is pure and testable - no API calls </details> <details> <summary><b>Task 2: Extract Demand Forecast Calculation</b></summary> Extract the weighted velocity calculation and demand horizon projection into a pure function. - Create a new pure function `calculateDemandForecasts()` in `packages/katana-mo-cli/src/compute/` directory to follow existing patterns - Move the calculation logic from `fetchHistoricalDemand()` lines 347-363 (rate calculation, weighted velocity, horizon projection) into this function - Function accepts: candidates, aggregated totals, recentTotals, and forecast parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod) - Function returns the same `Record<number, DemandEntry>` structure as current implementation - Include the existing edge case handling (division by zero protection, missing data defaults) </details> <details> <summary><b>Task 3: Refactor fetchHistoricalDemand to Use Extracted Functions</b></summary> Update `fetchHistoricalDemand()` to use the newly extracted functions while maintaining identical external behavior. - Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts` to call `aggregateSalesRows()` for row processing - Call `calculateDemandForecasts()` for the final demand calculation - The function's signature and return type remain unchanged - this is purely an internal refactor - Existing callers (`runPipeline.ts`) continue to work without modification </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase refactors `fetchHistoricalDemand()` to separate data fetching from calculation logic, enabling better code reuse and testability. All existing functionality must be preserved. **Extract Sales Row Aggregation Logic:** - Create a new pure function `aggregateSalesRows()` in `packages/katana-mo-cli/src/api/katana.ts` - Extract the row processing logic from `fetchHistoricalDemand()` lines 323-335 that accumulates totals and recentTotals by variant_id - Function signature should accept: an array of sales order rows and a recent start date parameter - Function should return an object with `{ totals, recentTotals }` structure - This function should be pure (no side effects, no API calls) and testable **Extract Demand Forecast Calculation:** - Create a new pure function `calculateDemandForecasts()` in `packages/katana-mo-cli/src/compute/` directory (following existing codebase patterns for computation logic) - Extract the calculation logic from `fetchHistoricalDemand()` lines 347-363, including: rate calculation, weighted velocity computation, and horizon projection - Function parameters: candidates, aggregated totals, recentTotals, and forecast parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod) - Return type: `Record<number, DemandEntry>` (same structure as current implementation) - Include all existing edge case handling: division by zero protection, missing data defaults **Refactor fetchHistoricalDemand:** - Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts` to use the newly extracted functions - Replace the inline row processing logic with a call to `aggregateSalesRows()` - Replace the inline calculation logic with a call to `calculateDemandForecasts()` - The function's signature and return type must remain unchanged - this is purely an internal refactor - Ensure existing callers in `runPipeline.ts` continue to work without any modifications ``` </details> ### Phase 2: Calculation Layer for Assembly Consumption Create the calculation function for converting assembly consumption data into demand horizon values, mirroring the approach used in PO generation. <details> <summary><b>Task 1: Create Consumption-to-Demand Calculation Function</b></summary> Create a pure function to convert raw consumption totals into demand horizon projections. - Create `calculateConsumptionDemand()` function in `packages/katana-mo-cli/src/compute/` directory - Function accepts: consumption totals (Record<number, number> from `fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays - Apply the same formula used in PO generation: `demand_horizon = (total_consumed / lookbackDays) * horizonDays` - Return a structure compatible with the existing demand format for easy merging - Handle edge cases: zero consumption, invalid lookback periods </details> <details> <summary><b>Task 2: Create Demand Merging Function</b></summary> Create a pure function to combine sales-based demand with assembly consumption demand. - Create `mergeDemandSources()` function in `packages/katana-mo-cli/src/compute/` directory - Accept two demand sources: sales-based demand and consumption-based demand (both as `Record<number, DemandEntry>` or compatible structure) - For each variant, add the assembly consumption demand_horizon to the sales-based demand_horizon - Handle variants that appear in only one source (preserve the available demand value) - Return the merged demand in the same format expected by `computeMoDryRun()` </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase creates pure calculation functions for converting assembly consumption data into demand values and merging it with sales-based demand. **Create Consumption-to-Demand Calculation Function:** - Create `calculateConsumptionDemand()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: consumption totals as `Record<number, number>` (from `fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays - Apply the PO generation formula: `demand_horizon = (total_consumed / lookbackDays) * horizonDays` - Return a structure compatible with the existing demand format to enable easy merging - Handle edge cases: zero consumption values, invalid lookback periods (avoid division by zero) **Create Demand Merging Function:** - Create `mergeDemandSources()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: two demand sources - sales-based demand and consumption-based demand (both as `Record<number, DemandEntry>` or compatible structure) - Merging logic: For each variant, add the assembly consumption demand_horizon value to the sales-based demand_horizon value - Handle variants that only appear in one source by preserving the available demand value - Return format: merged demand in the same format expected by `computeMoDryRun()` ``` </details> ### Phase 3: Pipeline Integration Wire the new data fetching and calculation functions into the MO pipeline, enabling assembly consumption to be included in demand calculations. <details> <summary><b>Task 1: Fetch Assembly Consumption Data in MO Pipeline</b></summary> Add inventory movement data fetching to the MO pipeline data gathering phase. - In `packages/katana-mo-cli/src/runPipeline.ts`, within `fetchMoPipelineData()`, add a call to existing `fetchConsumptionFromInventoryMovements()` after fetching historical demand - Pass the producible variant IDs (from the candidates list) to the consumption fetch - Use resource type `["ProductionIngredient"]` to capture consumption of finished goods used as ingredients in other assemblies - Apply the same lookback period configuration (`settings.lookbackDays`) used for sales-based demand - Include zero-consumption fallback logic similar to PO generation (extended lookback for variants with zero consumption) </details> <details> <summary><b>Task 2: Compose and Integrate Merged Demand</b></summary> Wire the calculation functions together to produce the final merged demand for MO generation. - In `fetchMoPipelineData()`, after fetching both data sources: - Call `calculateConsumptionDemand()` with the assembly consumption data - Call `mergeDemandSources()` to combine with existing sales-based demand - Update `fetchMoPipelineData()` return to use the merged demand - No changes needed to `computeMoDryRun()` in `packages/katana-mo-cli/src/compute/dryRun.ts` - it already consumes `demand_horizon` values; the values will now include assembly consumption </details> <details> <summary><b>🤖 Prompt for AI agents</b></summary> ``` This phase integrates assembly consumption data fetching and the new calculation functions into the MO pipeline to produce merged demand values. **Fetch Assembly Consumption Data:** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `fetchMoPipelineData()` function - After the existing call to `fetchHistoricalDemand()`, add a call to the existing `fetchConsumptionFromInventoryMovements()` function - Pass the producible variant IDs from the candidates list as the variant IDs parameter - Use resource type `["ProductionIngredient"]` to capture consumption of finished goods used as ingredients in assemblies - Apply the same lookback period (`settings.lookbackDays`) used for sales-based demand - Implement zero-consumption fallback logic similar to PO generation: for variants with zero consumption in the primary lookback period, use an extended lookback period **Compose and Integrate Merged Demand:** - In `fetchMoPipelineData()`, after fetching both sales demand and assembly consumption data: - Call `calculateConsumptionDemand()` with the assembly consumption data, lookbackDays, and horizonDays - Call `mergeDemandSources()` to combine the consumption-based demand with the existing sales-based demand - Update the `fetchMoPipelineData()` return value to use the merged demand instead of only sales-based demand - Note: No changes are needed to `computeMoDryRun()` in `packages/katana-mo-cli/src/compute/dryRun.ts` - it already processes `demand_horizon` values and will now receive values that include assembly consumption ``` </details> <details> <summary><b>Research</b></summary> The `katana-mo-cli` package handles both MO and PO generation through a pipeline architecture. MO generation in `runPipeline.ts` fetches demand via `fetchHistoricalDemand()` in `api/katana.ts`, which queries sales order rows. PO generation correctly uses `fetchConsumptionFromInventoryMovements()` to capture all consumption including assembly usage. The `compute/dryRun.ts` module calculates MO quantities based on the demand data it receives. The existing inventory movements API wrapper already supports the required resource types (`ProductionIngredient`, `Production`). Critically, `fetchHistoricalDemand()` currently couples API data fetching with calculation logic, making it difficult to add new data sources without code duplication. </details> --- ### 🚀 Next Steps <details> <summary><b>🤖 All AI agent prompts combined</b></summary> ``` Task: 1 This phase refactors `fetchHistoricalDemand()` to separate data fetching from calculation logic, enabling better code reuse and testability. All existing functionality must be preserved. **Extract Sales Row Aggregation Logic:** - Create a new pure function `aggregateSalesRows()` in `packages/katana-mo-cli/src/api/katana.ts` - Extract the row processing logic from `fetchHistoricalDemand()` lines 323-335 that accumulates totals and recentTotals by variant_id - Function signature should accept: an array of sales order rows and a recent start date parameter - Function should return an object with `{ totals, recentTotals }` structure - This function should be pure (no side effects, no API calls) and testable **Extract Demand Forecast Calculation:** - Create a new pure function `calculateDemandForecasts()` in `packages/katana-mo-cli/src/compute/` directory (following existing codebase patterns for computation logic) - Extract the calculation logic from `fetchHistoricalDemand()` lines 347-363, including: rate calculation, weighted velocity computation, and horizon projection - Function parameters: candidates, aggregated totals, recentTotals, and forecast parameters (lookbackDays, recentDays, horizonDays, recentWeight, forecastMethod) - Return type: `Record<number, DemandEntry>` (same structure as current implementation) - Include all existing edge case handling: division by zero protection, missing data defaults **Refactor fetchHistoricalDemand:** - Modify `fetchHistoricalDemand()` in `packages/katana-mo-cli/src/api/katana.ts` to use the newly extracted functions - Replace the inline row processing logic with a call to `aggregateSalesRows()` - Replace the inline calculation logic with a call to `calculateDemandForecasts()` - The function's signature and return type must remain unchanged - this is purely an internal refactor - Ensure existing callers in `runPipeline.ts` continue to work without any modifications =============================================================================== Task: 2 This phase creates pure calculation functions for converting assembly consumption data into demand values and merging it with sales-based demand. **Create Consumption-to-Demand Calculation Function:** - Create `calculateConsumptionDemand()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: consumption totals as `Record<number, number>` (from `fetchConsumptionFromInventoryMovements`), lookbackDays, horizonDays - Apply the PO generation formula: `demand_horizon = (total_consumed / lookbackDays) * horizonDays` - Return a structure compatible with the existing demand format to enable easy merging - Handle edge cases: zero consumption values, invalid lookback periods (avoid division by zero) **Create Demand Merging Function:** - Create `mergeDemandSources()` function in `packages/katana-mo-cli/src/compute/` directory - Function parameters: two demand sources - sales-based demand and consumption-based demand (both as `Record<number, DemandEntry>` or compatible structure) - Merging logic: For each variant, add the assembly consumption demand_horizon value to the sales-based demand_horizon value - Handle variants that only appear in one source by preserving the available demand value - Return format: merged demand in the same format expected by `computeMoDryRun()` =============================================================================== Task: 3 This phase integrates assembly consumption data fetching and the new calculation functions into the MO pipeline to produce merged demand values. **Fetch Assembly Consumption Data:** - In `packages/katana-mo-cli/src/runPipeline.ts`, locate the `fetchMoPipelineData()` function - After the existing call to `fetchHistoricalDemand()`, add a call to the existing `fetchConsumptionFromInventoryMovements()` function - Pass the producible variant IDs from the candidates list as the variant IDs parameter - Use resource type `["ProductionIngredient"]` to capture consumption of finished goods used as ingredients in assemblies - Apply the same lookback period (`settings.lookbackDays`) used for sales-based demand - Implement zero-consumption fallback logic similar to PO generation: for variants with zero consumption in the primary lookback period, use an extended lookback period **Compose and Integrate Merged Demand:** - In `fetchMoPipelineData()`, after fetching both sales demand and assembly consumption data: - Call `calculateConsumptionDemand()` with the assembly consumption data, lookbackDays, and horizonDays - Call `mergeDemandSources()` to combine the consumption-based demand with the existing sales-based demand - Update the `fetchMoPipelineData()` return value to use the merged demand instead of only sales-based demand - Note: No changes are needed to `computeMoDryRun()` in `packages/katana-mo-cli/src/compute/dryRun.ts` - it already processes `demand_horizon` values and will now receive values that include assembly consumption ``` </details> <details> <summary><b>💡 Iterate on the plan with: <code>@coderabbitai &lt;feedback&gt;</code> </b></summary> ``` Example Feedback - @coderabbitai You can skip phase 3. Add a simple unit test case for phase 2. - @coderabbitai For design choice 1 go ahead with option 3 and replan. ``` </details> --- 💬 Have feedback or questions? Drop into our [discord](https://discord.gg/coderabbit)!</planningResult></rawResChunk> --> <!-- <agentComponentType>plan-edits</agentComponentType> -->
chris-kreidl commented 2026-02-11 17:27:10 +00:00 (Migrated from github.com)

@coderabbitai in Task 1 why not extend the call to fetchConsumptionFromInventoryMovements call to include ['ProductionIngredient', 'Production', 'SalesOrderRow'], which should then eliminate the need to fetch sales orders separately, which would then eliminate the need to merge results in tasks 2 and 3?

@coderabbitai in Task 1 why not extend the call to `fetchConsumptionFromInventoryMovements` call to include `['ProductionIngredient', 'Production', 'SalesOrderRow']`, which should then eliminate the need to fetch sales orders separately, which would then eliminate the need to merge results in tasks 2 and 3?
coderabbitai[bot] commented 2026-02-11 17:28:31 +00:00 (Migrated from github.com)
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find and examine the fetchConsumptionFromInventoryMovements function
echo "=== fetchConsumptionFromInventoryMovements implementation ==="
rg -n -A 30 "function fetchConsumptionFromInventoryMovements|const fetchConsumptionFromInventoryMovements|export.*fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/

echo -e "\n=== fetchHistoricalDemand implementation ==="
rg -n -A 30 "function fetchHistoricalDemand|const fetchHistoricalDemand|export.*fetchHistoricalDemand" packages/katana-mo-cli/src/

echo -e "\n=== Check how PO generation uses these functions ==="
rg -n -B 5 -A 10 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/runPipeline.ts

Length of output: 8590


@chris-kreidl Great observation! You're absolutely right that technically we could use a single fetchConsumptionFromInventoryMovements() call with all three resource types. This would significantly simplify the implementation.

However, there's an important difference in how the two functions calculate demand:

fetchConsumptionFromInventoryMovements():

  • Returns simple totals: Record<number, number> (variant ID → total consumption)
  • Applies a straightforward formula: (total_consumed / lookback_days) * horizon_days
  • Used by PO generation

fetchHistoricalDemand():

  • Implements weighted velocity forecasting with configurable recentDays, recentWeight, and forecastMethod parameters
  • Currently used by MO generation for sales-based demand
  • More sophisticated forecasting that weights recent sales differently from historical averages

The plan's Design Choice 1 rationale specifically chose to "preserve the weighted velocity forecasting for direct sales" while adding assembly consumption. Your approach would replace the weighted forecasting with uniform simple consumption calculation across all demand sources (sales, production consumption, and assembly usage).

Options:

  1. Keep the plan as-is - Preserve weighted velocity for sales, add simple consumption for assemblies
  2. Adopt your simpler approach - Use uniform consumption calculation for all demand sources (sales + production + assemblies), eliminating Tasks 2 and 3

Would you like me to replan with option 2? It would be much simpler to implement, with the tradeoff being that sales forecasting becomes less sophisticated (no more weighted velocity).

<!-- This is an auto-generated reply by CodeRabbit --> <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Find and examine the fetchConsumptionFromInventoryMovements function echo "=== fetchConsumptionFromInventoryMovements implementation ===" rg -n -A 30 "function fetchConsumptionFromInventoryMovements|const fetchConsumptionFromInventoryMovements|export.*fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/ echo -e "\n=== fetchHistoricalDemand implementation ===" rg -n -A 30 "function fetchHistoricalDemand|const fetchHistoricalDemand|export.*fetchHistoricalDemand" packages/katana-mo-cli/src/ echo -e "\n=== Check how PO generation uses these functions ===" rg -n -B 5 -A 10 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/runPipeline.ts ``` Length of output: 8590 --- </details> `@chris-kreidl` Great observation! You're absolutely right that technically we could use a single `fetchConsumptionFromInventoryMovements()` call with all three resource types. This would significantly simplify the implementation. However, there's an important difference in how the two functions calculate demand: **`fetchConsumptionFromInventoryMovements()`:** - Returns simple totals: `Record<number, number>` (variant ID → total consumption) - Applies a straightforward formula: `(total_consumed / lookback_days) * horizon_days` - Used by PO generation **`fetchHistoricalDemand()`:** - Implements **weighted velocity forecasting** with configurable `recentDays`, `recentWeight`, and `forecastMethod` parameters - Currently used by MO generation for sales-based demand - More sophisticated forecasting that weights recent sales differently from historical averages The plan's Design Choice 1 rationale specifically chose to **"preserve the weighted velocity forecasting for direct sales"** while adding assembly consumption. Your approach would replace the weighted forecasting with uniform simple consumption calculation across all demand sources (sales, production consumption, and assembly usage). **Options:** 1. **Keep the plan as-is** - Preserve weighted velocity for sales, add simple consumption for assemblies 2. **Adopt your simpler approach** - Use uniform consumption calculation for all demand sources (sales + production + assemblies), eliminating Tasks 2 and 3 Would you like me to replan with option 2? It would be much simpler to implement, with the tradeoff being that sales forecasting becomes less sophisticated (no more weighted velocity). <!-- <agentComponentType>chat-answer</agentComponentType> --> <!-- <rawResChunk><answer><details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Find and examine the fetchConsumptionFromInventoryMovements function echo "=== fetchConsumptionFromInventoryMovements implementation ===" rg -n -A 30 "function fetchConsumptionFromInventoryMovements|const fetchConsumptionFromInventoryMovements|export.*fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/ echo -e "\n=== fetchHistoricalDemand implementation ===" rg -n -A 30 "function fetchHistoricalDemand|const fetchHistoricalDemand|export.*fetchHistoricalDemand" packages/katana-mo-cli/src/ echo -e "\n=== Check how PO generation uses these functions ===" rg -n -B 5 -A 10 "fetchConsumptionFromInventoryMovements" packages/katana-mo-cli/src/runPipeline.ts ``` Length of output: 8590 --- </details> `@chris-kreidl` Great observation! You're absolutely right that technically we could use a single `fetchConsumptionFromInventoryMovements()` call with all three resource types. This would significantly simplify the implementation. However, there's an important difference in how the two functions calculate demand: **`fetchConsumptionFromInventoryMovements()`:** - Returns simple totals: `Record<number, number>` (variant ID → total consumption) - Applies a straightforward formula: `(total_consumed / lookback_days) * horizon_days` - Used by PO generation **`fetchHistoricalDemand()`:** - Implements **weighted velocity forecasting** with configurable `recentDays`, `recentWeight`, and `forecastMethod` parameters - Currently used by MO generation for sales-based demand - More sophisticated forecasting that weights recent sales differently from historical averages The plan's Design Choice 1 rationale specifically chose to **"preserve the weighted velocity forecasting for direct sales"** while adding assembly consumption. Your approach would replace the weighted forecasting with uniform simple consumption calculation across all demand sources (sales, production consumption, and assembly usage). **Options:** 1. **Keep the plan as-is** - Preserve weighted velocity for sales, add simple consumption for assemblies 2. **Adopt your simpler approach** - Use uniform consumption calculation for all demand sources (sales + production + assemblies), eliminating Tasks 2 and 3 Would you like me to replan with option 2? It would be much simpler to implement, with the tradeoff being that sales forecasting becomes less sophisticated (no more weighted velocity).</answer></rawResChunk> -->
chris-kreidl commented 2026-02-11 17:32:11 +00:00 (Migrated from github.com)

@coderabbitai wouldn't the better approach, in terms of modularity, then be to split the data retrieval logic from the demand calculation logic? seems counter-pattern to have one function handling both tasks.

@coderabbitai wouldn't the better approach, in terms of modularity, then be to split the data retrieval logic from the demand calculation logic? seems counter-pattern to have one function handling both tasks.
coderabbitai[bot] commented 2026-02-11 17:33:15 +00:00 (Migrated from github.com)
🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Examine the current structure of fetchHistoricalDemand to understand the coupling
echo "=== fetchHistoricalDemand full implementation ==="
rg -n -A 50 "export async function fetchHistoricalDemand" packages/katana-mo-cli/src/api/katana.ts

echo -e "\n=== Check if there are any existing separate calculation utilities ==="
rg -n "velocity|forecast|demand.*calculat" packages/katana-mo-cli/src/compute/

echo -e "\n=== Look for any existing calculation patterns ==="
fd -e ts -e js . packages/katana-mo-cli/src/compute/ --exec basename {}

Length of output: 3431


@chris-kreidl Excellent architectural insight! You're absolutely right - this is a classic violation of the single responsibility principle. Looking at the code, fetchHistoricalDemand() is indeed doing two distinct jobs:

  1. Data retrieval (lines 317-334): Paginating through sales order rows API
  2. Demand calculation: Computing weighted velocity forecasting with the retrieved data

A better architecture would be:

Refactored Approach:

1. Data Layer (retrieval only):
   - fetchInventoryMovements() - generic fetch with resource types parameter
   
2. Calculation Layer (pure functions):
   - calculateWeightedVelocityDemand(rawData, config) 
   - calculateSimpleConsumptionDemand(rawData, config)
   
3. Composition:
   - Fetch once with ['SalesOrderRow', 'ProductionIngredient', 'Production']
   - Apply appropriate calculation method to each data subset or combined data

Benefits:

  • ✅ Single data fetch for all sources
  • ✅ Weighted velocity logic becomes reusable (can apply it to sales, assemblies, or combined data)
  • ✅ Pure calculation functions are easily testable without API mocking
  • ✅ No merging step needed - handle at calculation level
  • ✅ More flexible composition of different forecasting strategies

This refactoring would actually make the implementation simpler than the original plan while also being architecturally cleaner.

Would you like me to replan with this refactored architecture? It would involve:

  1. Extract calculation logic from fetchHistoricalDemand() into pure functions
  2. Create/enhance generic inventory movements fetch
  3. Compose them in the pipeline with appropriate calculation methods
<!-- This is an auto-generated reply by CodeRabbit --> <details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Examine the current structure of fetchHistoricalDemand to understand the coupling echo "=== fetchHistoricalDemand full implementation ===" rg -n -A 50 "export async function fetchHistoricalDemand" packages/katana-mo-cli/src/api/katana.ts echo -e "\n=== Check if there are any existing separate calculation utilities ===" rg -n "velocity|forecast|demand.*calculat" packages/katana-mo-cli/src/compute/ echo -e "\n=== Look for any existing calculation patterns ===" fd -e ts -e js . packages/katana-mo-cli/src/compute/ --exec basename {} ``` Length of output: 3431 --- </details> `@chris-kreidl` Excellent architectural insight! You're absolutely right - this is a classic violation of the single responsibility principle. Looking at the code, `fetchHistoricalDemand()` is indeed doing two distinct jobs: 1. **Data retrieval** (lines 317-334): Paginating through sales order rows API 2. **Demand calculation**: Computing weighted velocity forecasting with the retrieved data A better architecture would be: **Refactored Approach:** ``` 1. Data Layer (retrieval only): - fetchInventoryMovements() - generic fetch with resource types parameter 2. Calculation Layer (pure functions): - calculateWeightedVelocityDemand(rawData, config) - calculateSimpleConsumptionDemand(rawData, config) 3. Composition: - Fetch once with ['SalesOrderRow', 'ProductionIngredient', 'Production'] - Apply appropriate calculation method to each data subset or combined data ``` **Benefits:** - ✅ Single data fetch for all sources - ✅ Weighted velocity logic becomes reusable (can apply it to sales, assemblies, or combined data) - ✅ Pure calculation functions are easily testable without API mocking - ✅ No merging step needed - handle at calculation level - ✅ More flexible composition of different forecasting strategies This refactoring would actually make the implementation **simpler** than the original plan while also being architecturally cleaner. Would you like me to **replan with this refactored architecture**? It would involve: 1. Extract calculation logic from `fetchHistoricalDemand()` into pure functions 2. Create/enhance generic inventory movements fetch 3. Compose them in the pipeline with appropriate calculation methods <!-- <agentComponentType>chat-answer</agentComponentType> --> <!-- <rawResChunk><answer><details> <summary>🧩 Analysis chain</summary> 🏁 Script executed: ``` #!/bin/bash # Examine the current structure of fetchHistoricalDemand to understand the coupling echo "=== fetchHistoricalDemand full implementation ===" rg -n -A 50 "export async function fetchHistoricalDemand" packages/katana-mo-cli/src/api/katana.ts echo -e "\n=== Check if there are any existing separate calculation utilities ===" rg -n "velocity|forecast|demand.*calculat" packages/katana-mo-cli/src/compute/ echo -e "\n=== Look for any existing calculation patterns ===" fd -e ts -e js . packages/katana-mo-cli/src/compute/ --exec basename {} ``` Length of output: 3431 --- </details> `@chris-kreidl` Excellent architectural insight! You're absolutely right - this is a classic violation of the single responsibility principle. Looking at the code, `fetchHistoricalDemand()` is indeed doing two distinct jobs: 1. **Data retrieval** (lines 317-334): Paginating through sales order rows API 2. **Demand calculation**: Computing weighted velocity forecasting with the retrieved data A better architecture would be: **Refactored Approach:** ``` 1. Data Layer (retrieval only): - fetchInventoryMovements() - generic fetch with resource types parameter 2. Calculation Layer (pure functions): - calculateWeightedVelocityDemand(rawData, config) - calculateSimpleConsumptionDemand(rawData, config) 3. Composition: - Fetch once with ['SalesOrderRow', 'ProductionIngredient', 'Production'] - Apply appropriate calculation method to each data subset or combined data ``` **Benefits:** - ✅ Single data fetch for all sources - ✅ Weighted velocity logic becomes reusable (can apply it to sales, assemblies, or combined data) - ✅ Pure calculation functions are easily testable without API mocking - ✅ No merging step needed - handle at calculation level - ✅ More flexible composition of different forecasting strategies This refactoring would actually make the implementation **simpler** than the original plan while also being architecturally cleaner. Would you like me to **replan with this refactored architecture**? It would involve: 1. Extract calculation logic from `fetchHistoricalDemand()` into pure functions 2. Create/enhance generic inventory movements fetch 3. Compose them in the pipeline with appropriate calculation methods</answer></rawResChunk> -->
chris-kreidl commented 2026-02-11 17:37:28 +00:00 (Migrated from github.com)

@coderabbitai Yes, please proceed with that replan.

@coderabbitai Yes, please proceed with that replan.
coderabbitai[bot] commented 2026-02-11 17:44:46 +00:00 (Migrated from github.com)

I've updated the plan above based on your feedback. Ready to proceed when you are!

<!-- This is an auto-generated reply by CodeRabbit --> I've updated the plan above based on your feedback. Ready to proceed when you are!
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
ckreidl/katana#6
No description provided.