Lookback for MO generation misses some consumption #6
Labels
No labels
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
ckreidl/katana#6
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
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.
@coderabbitai plan
Coding Plan
Summary
fetchHistoricalDemand()to separate data fetching from calculation logic, enabling code reuse and testabilitycompute/directory following existing codebase patternsfetchConsumptionFromInventoryMovements()function, avoiding code duplicationDesign Choices
Design Choice 1: How should assembly consumption be combined with sales-based demand?
Options Considered:
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.aggregateSalesRows()inpackages/katana-mo-cli/src/api/katana.tsfetchHistoricalDemand()lines 323-335 into this function{ totals, recentTotals }objectsTask 2: Extract Demand Forecast Calculation
Extract the weighted velocity calculation and demand horizon projection into a pure function.
calculateDemandForecasts()inpackages/katana-mo-cli/src/compute/directory to follow existing patternsfetchHistoricalDemand()lines 347-363 (rate calculation, weighted velocity, horizon projection) into this functionRecord<number, DemandEntry>structure as current implementationTask 3: Refactor fetchHistoricalDemand to Use Extracted Functions
Update
fetchHistoricalDemand()to use the newly extracted functions while maintaining identical external behavior.fetchHistoricalDemand()inpackages/katana-mo-cli/src/api/katana.tsto callaggregateSalesRows()for row processingcalculateDemandForecasts()for the final demand calculationrunPipeline.ts) continue to work without modification🤖 Prompt for AI agents
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.
calculateConsumptionDemand()function inpackages/katana-mo-cli/src/compute/directoryfetchConsumptionFromInventoryMovements), lookbackDays, horizonDaysdemand_horizon = (total_consumed / lookbackDays) * horizonDaysTask 2: Create Demand Merging Function
Create a pure function to combine sales-based demand with assembly consumption demand.
mergeDemandSources()function inpackages/katana-mo-cli/src/compute/directoryRecord<number, DemandEntry>or compatible structure)computeMoDryRun()🤖 Prompt for AI agents
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.
packages/katana-mo-cli/src/runPipeline.ts, withinfetchMoPipelineData(), add a call to existingfetchConsumptionFromInventoryMovements()after fetching historical demand["ProductionIngredient"]to capture consumption of finished goods used as ingredients in other assembliessettings.lookbackDays) used for sales-based demandTask 2: Compose and Integrate Merged Demand
Wire the calculation functions together to produce the final merged demand for MO generation.
fetchMoPipelineData(), after fetching both data sources:calculateConsumptionDemand()with the assembly consumption datamergeDemandSources()to combine with existing sales-based demandfetchMoPipelineData()return to use the merged demandcomputeMoDryRun()inpackages/katana-mo-cli/src/compute/dryRun.ts- it already consumesdemand_horizonvalues; the values will now include assembly consumption🤖 Prompt for AI agents
Research
The
katana-mo-clipackage handles both MO and PO generation through a pipeline architecture. MO generation inrunPipeline.tsfetches demand viafetchHistoricalDemand()inapi/katana.ts, which queries sales order rows. PO generation correctly usesfetchConsumptionFromInventoryMovements()to capture all consumption including assembly usage. Thecompute/dryRun.tsmodule 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
💡 Iterate on the plan with:
@coderabbitai <feedback>💬 Have feedback or questions? Drop into our discord!
@coderabbitai in Task 1 why not extend the call to
fetchConsumptionFromInventoryMovementscall 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?🧩 Analysis chain
🏁 Script executed:
Length of output: 8590
@chris-kreidlGreat observation! You're absolutely right that technically we could use a singlefetchConsumptionFromInventoryMovements()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():Record<number, number>(variant ID → total consumption)(total_consumed / lookback_days) * horizon_daysfetchHistoricalDemand():recentDays,recentWeight, andforecastMethodparametersThe 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:
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).
@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.
🧩 Analysis chain
🏁 Script executed:
Length of output: 3431
@chris-kreidlExcellent 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:A better architecture would be:
Refactored Approach:
Benefits:
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:
fetchHistoricalDemand()into pure functions@coderabbitai Yes, please proceed with that replan.
I've updated the plan above based on your feedback. Ready to proceed when you are!