An intelligent inventory and sales forecasting system for ERPNext that uses AI algorithms to predict stock consumption patterns, analyze sales trends, generate reorder alerts, and optimize inventory management across multiple companies with comprehensive sales analytics and financial forecasting capabilities.
- Sync System Overhaul: Complete redesign of the forecast synchronization system
- Error Handling: Robust error management with detailed logging and recovery mechanisms
- Field Validation: Fixed Dynamic Link field configurations and select field value validations
- Sync Logs: Comprehensive tracking of all forecast sync operations with detailed status reporting
- DocType Improvements: Enhanced AI Forecast Accuracy and AI Forecast Sync Log DocTypes
- Multi-Type Financial Forecasting: Support for Financial, Cashflow, Revenue, and Expense forecasts
- Accuracy Tracking: Real-time monitoring of forecast accuracy with historical analysis
- Smart Error Recovery: Automatic retry mechanisms for failed sync operations
- Enhanced Logging: Detailed sync logs with success/failure analytics and timing information
- Fixed "No Label must be set first" validation errors
- Resolved Dynamic Link field misconfigurations
- Corrected select field value mappings
- Fixed sync log creation field name mismatches
- Improved error propagation and user feedback
- ✅ AI Forecast Sync Log creation errors
- ✅ Dynamic Link validation failures
- ✅ Missing required field validations
- ✅ Sync operation error handling
- ✅ Field name mapping inconsistencies
- Smart Consumption Analysis: Analyzes historical stock movements to predict future demand
- Movement Classification: Automatically categorizes items as Fast Moving, Slow Moving, Non Moving, or Critical
- Confidence Scoring: Provides prediction confidence levels (0-100%)
- Dynamic Forecasting: Adjusts predictions based on recent consumption patterns
- Sales Forecasting: Advanced predictive analytics for sales trends and customer demand patterns
- Revenue Prediction: Forecasts future sales revenue with trend analysis and seasonal adjustments
- Financial Forecasting: Comprehensive financial forecasting including cashflow, revenue, and expense predictions
- Multi-Type Sync: Synchronized forecasting across all financial forecast types with accuracy tracking
- Company-Specific Forecasting: Separate forecasting logic for each company
- Cross-Company Analysis: Compare performance across multiple companies
- Company-Aware Workflows: All operations respect company boundaries
- Consolidated Reporting: View combined insights across companies
- Reorder Alerts: Automatic alerts when stock falls below optimal levels
- Auto Purchase Order Creation: Generate POs automatically when reorder points are reached
- Email Notifications: Notify stock managers of critical stock situations
- Background Processing: Non-blocking sync operations for large datasets
- Smart Error Handling: Robust error management with detailed logging and recovery mechanisms
- Sync Status Tracking: Real-time monitoring of forecast synchronization with comprehensive logs
- Real-time Dashboards: Live status of inventory across all companies
- Forecast Accuracy Tracking: Monitor and improve prediction performance with detailed accuracy metrics
- Stock Movement Analysis: Detailed insights into consumption patterns
- Company Performance Comparison: Benchmark performance across companies
- AI Sales Dashboard: Comprehensive sales analytics with predictive insights per item and customer
- Sales Trend Analysis: Advanced metrics including growth rates, volatility, and seasonal patterns
- Customer Demand Forecasting: Predict customer purchasing behavior and seasonal demands
- AI Financial Forecasting: Complete financial forecasting system with multi-currency support
- Financial Analytics: Complete financial forecasting dashboard with cashflow, revenue, and expense analysis
- Multi-Currency Support: Automatic currency detection and proper formatting for global operations
- View Analytics: Currency-aware reporting with proper symbol display (₹, $, €, etc.)
- Sync Logs & Monitoring: Comprehensive tracking of all forecast sync operations with success/failure analytics
- Bulk Operations: Process thousands of items efficiently
- Background Sync: Queue-based processing for large inventories
- Optimized Queries: Company-aware database queries for better performance
- Caching: Smart caching for frequently accessed data
- Error Recovery: Automatic retry mechanisms and graceful error handling
- Robust Validation: Comprehensive field validation and data integrity checks
The AI Financial Forecast system provides comprehensive financial forecasting capabilities with advanced analytics, multi-currency support, and intelligent predictions for cash flow, revenue, and expense planning.
- Cash Flow Forecasting: Predict future cash positions with high accuracy
- Revenue Forecasting: Analyze income trends and predict future earnings
- Expense Forecasting: Monitor and predict operational expenses
- Balance Sheet Forecasting: Comprehensive asset and liability predictions
- Automatic Currency Detection: System automatically detects currency from:
- Account-specific currency settings
- Company default currency
- System default currency (fallback: INR)
- Multi-Currency Support: Full support for global currencies (INR, USD, EUR, GBP, JPY, CNY, etc.)
- Proper Currency Formatting: Displays amounts with correct currency symbols and locale formatting
- Real-time Dashboards: Live financial health monitoring
- Confidence Scoring: AI confidence levels (0-100%) for all predictions
- Risk Analysis: Automatic categorization (Low, Medium, High, Critical)
- Trend Analysis: Direction indicators (Increasing, Decreasing, Stable, Volatile)
- Accuracy Tracking: Historical accuracy measurement and improvement suggestions
The system automatically displays the correct currency symbol based on the following priority:
- Account Currency: If the forecasted account has a specific currency
- Company Default Currency: Company's default currency setting
- System Default: System-wide default currency (usually INR)
INR: ₹1,23,456.78 (Indian Rupee)
USD: $1,234.56 (US Dollar)
EUR: €1.234,56 (Euro)
GBP: £1,234.56 (British Pound)
JPY: ¥123,456 (Japanese Yen)
CNY: ¥1,234.56 (Chinese Yuan)
// Navigate to AI Financial Forecast
frappe.set_route("List", "AI Financial Forecast");
// Or create new forecast
frappe.new_doc("AI Financial Forecast");- Company: Select the company for forecasting
- Account: Choose specific account (auto-sets currency)
- Forecast Type: Select from Cash Flow, Revenue, Expense
- Currency: Automatically populated, can be manually overridden
- Forecast Period: Set prediction timeframe (days)
- Confidence Threshold: Minimum confidence level (default: 70%)
-- Set currency for specific accounts
UPDATE `tabAccount`
SET account_currency = 'INR'
WHERE name = 'Main Bank Account';# Set company default currency
company = frappe.get_doc("Company", "Your Company")
company.default_currency = "INR"
company.save()# Set system-wide default
frappe.db.set_single_value("System Settings", "currency", "INR")- From DocType: Go to AI Financial Forecast → View Analytics
- From Reports: Reports → AI Financial Analytics
- From Dashboard: AI Analytics Workspace → Financial Forecasts
- Summary Metrics: Total forecasts, average confidence, prediction values
- Performance Charts: Trend analysis with proper currency formatting
- Risk Assessment: Color-coded risk categories with explanations
- Accuracy Tracking: Historical accuracy with improvement suggestions
Problem: Currency shows as $ instead of ₹ or correct local currency
Solutions:
-
Check Account Currency:
account_currency = frappe.db.get_value("Account", "account_name", "account_currency") print(f"Account Currency: {account_currency}")
-
Verify Company Default:
company_currency = frappe.db.get_value("Company", "company_name", "default_currency") print(f"Company Currency: {company_currency}")
-
Update Existing Forecasts:
# Run the currency update patch bench --site your-site execute ai_inventory.patches.v2_0.add_currency_to_financial_forecasts.execute
Problem: Low confidence scores or inaccurate predictions
Solutions:
- Increase Historical Data: Ensure sufficient transaction history (minimum 90 days)
- Adjust Model Parameters: Fine-tune confidence threshold and seasonal adjustments
- Verify Data Quality: Check for incomplete or inconsistent account data
- Review External Factors: Update external factor configurations
Problem: Sync errors or failed integrations
Solutions:
- Check Sync Logs: AI Financial Forecast → View Sync Status
- Verify Permissions: Ensure user has "AI Inventory Manager" role
- Review Error Logs: System logs for detailed error information
- Manual Sync: Use "Sync Now" button to force synchronization
- Always set account-specific currencies for multi-currency operations
- Configure company default currencies before creating forecasts
- Use consistent currency codes (ISO 4217 standard)
- Regularly update exchange rates for multi-currency environments
- Maintain clean, consistent account data
- Regular historical data validation
- Periodic model parameter adjustment
- Monitor and act on accuracy feedback
- Limit forecast scope for large datasets
- Use background sync for bulk operations
- Regular cleanup of old forecast data
- Monitor system resource usage during peak operations
- ERPNext v14+ or v15+
- Python 3.8+
- Frappe Framework v14+
- Access to ERPNext site with System Manager privileges
# Navigate to your ERPNext bench
cd /path/to/your/bench
# STEP 1: Install required packages FIRST
./env/bin/pip install numpy>=1.21.0 pandas>=1.3.0 scikit-learn>=1.0.0 matplotlib>=3.3.0 scipy>=1.7.0
# STEP 2: Get the app
bench get-app https://github.com/yourusername/ai_inventory.git
# STEP 3: Install on your site
bench --site your-site-name install-app ai_inventory
# STEP 4: Migrate database
bench --site your-site-name migrate
# STEP 5: Restart services
bench restart
# STEP 6: Clear cache
bench --site your-site-name clear-cache# Download and run the automated installation script
cd /path/to/your/bench
wget https://raw.githubusercontent.com/yourusername/ai_inventory/main/install.sh
chmod +x install.sh
./install.sh-
Clone the Repository
git clone https://github.com/yourusername/ai_inventory.git cd ai_inventory -
Install Dependencies
pip install -r requirements.txt
-
Setup in ERPNext
bench get-app /path/to/ai_inventory bench --site your-site-name install-app ai_inventory bench --site your-site-name migrate
-
Configure Permissions
- Assign "AI Inventory Manager" role to relevant users
- Configure company-specific permissions as needed
-
Navigate to AI Financial Settings
ERPNext → AI Inventory → AI Financial Settings -
Configure Basic Settings
- Enable auto-sync
- Set sync frequency (hourly/daily)
- Configure default forecast parameters
// Bulk create for all items
Click: Bulk Creation → Create for All Items
// Or create only for items with stock
Click: Bulk Creation → Create for Items with Stock
// Access AI Financial Settings for comprehensive forecasting
Navigate: AI Inventory → AI Financial Settings
// Sync all forecast types (Financial, Cashflow, Revenue, Expense)
Click: Sync All Forecasts
// Access AI Sales Dashboard
Navigate: Reports → AI Sales Dashboard# Set up company-specific forecasting
companies = ["Company A", "Company B", "Company C"]
for company in companies:
# Create forecasts for each company
create_forecasts_for_company(company)
# Configure company-specific parameters
setup_company_parameters(company)# Single item forecast
forecast = frappe.get_doc("AI Inventory Forecast", "FORECAST-001")
result = forecast.run_ai_forecast()
# Bulk forecast for a company
sync_ai_forecasts_now(company="Your Company Name")The AI Financial Settings provide comprehensive forecasting capabilities across multiple financial types:
# Access financial forecast data
financial_data = frappe.call({
'method': 'ai_inventory.forecasting.sync_manager.sync_all_forecasts',
'args': {
'company': 'Your Company'
}
})
# Available forecast types:
# - AI Financial Forecast: General financial predictions
# - AI Cashflow Forecast: Cash flow analysis and predictions
# - AI Revenue Forecast: Revenue projections and trends
# - AI Expense Forecast: Expense planning and forecasting
# Monitor sync operations
sync_logs = frappe.get_list('AI Forecast Sync Log',
filters={'company': 'Your Company'},
fields=['sync_time', 'sync_type', 'status', 'total_items', 'successful_items']
)- Multi-Type Sync: Synchronize all forecast types with a single operation
- Accuracy Tracking: Monitor forecast performance with detailed accuracy metrics
- Error Handling: Robust error management with detailed logging
- Progress Monitoring: Real-time sync status and completion tracking
- Historical Analysis: Track forecast accuracy over time for continuous improvement
This section provides comprehensive user documentation for all AI forecasting modules in the AI Inventory system.
The AI Inventory Forecasting module predicts item consumption patterns and generates intelligent reorder recommendations.
ERPNext → AI Inventory → AI Inventory Forecast
- Click New to create a forecast
- Select Item Code, Warehouse, and Company
- Set Forecast Period Days (default: 30 days)
- Set Lead Time Days (default: 14 days)
- Enable Auto Create Purchase Order if desired
- Click Save
- Open your forecast record
- Click Run AI Forecast button
- Review the AI predictions:
- Predicted Consumption: Expected units to be consumed
- Movement Type: Fast Moving, Slow Moving, Critical, or Normal
- Confidence Score: AI prediction confidence (0-100%)
- Reorder Level: Suggested reorder point
- Suggested Qty: Recommended purchase quantity
- Smart Algorithm: Analyzes historical stock ledger entries to predict future consumption
- Movement Classification: Automatically categorizes items based on usage patterns
- Confidence Scoring: Provides reliability indicators for each prediction
- Trend Analysis: Identifies seasonal patterns and consumption trends
- Auto-Sync: Scheduled background updates of all forecasts
- Smart Alerts: Automatic reorder notifications when stock falls below optimal levels
- Purchase Order Creation: One-click PO generation with AI-optimized quantities
- Multi-Company Support: Company-isolated forecasting and reporting
- Real-time Status: Live inventory status across all companies
- Company Comparison: Benchmark performance across multiple entities
- Movement Analysis: Detailed insights into stock consumption patterns
- Alert Management: Centralized view of all reorder alerts
-
Setup Phase
- Configure AI settings for your company
- Define forecast parameters (period, lead time, safety factors)
- Set up automated sync schedules
-
Daily Operations
- Monitor reorder alerts in the dashboard
- Review AI recommendations before creating POs
- Analyze forecast accuracy and adjust parameters
-
Analysis & Optimization
- Use reports to identify trends and patterns
- Adjust forecasting parameters based on accuracy
- Optimize inventory levels using AI insights
- AI Inventory Dashboard: Real-time overview of all forecasts
- Forecast Accuracy Analysis: Track prediction performance
- Stock Movement Prediction: Analyze consumption trends
- Company-wise Summary: Multi-company performance comparison
The AI Sales Forecasting module provides advanced sales analytics and customer demand predictions.
ERPNext → Reports → AI Sales Dashboard
- Company: Select your company
- Date Range: Set from/to dates for analysis
- Customer: Filter by specific customer (optional)
- Item Code: Analyze specific items (optional)
The dashboard provides comprehensive sales analytics including:
- Total Sales: Revenue figures with growth trends
- Growth Rate: Period-over-period growth percentages
- Volatility Index: Sales stability indicators
- Forecast Accuracy: AI prediction performance
- Customer Demand Trends: Buying pattern analysis
- Predictive Sales Models: AI-powered sales forecasting algorithms
- Customer Behavior Analysis: Detailed customer purchasing patterns
- Seasonal Trend Detection: Identifies cyclical sales patterns
- Growth Rate Calculations: Automatic growth trend analysis
- Demand Forecasting: Predict future customer requirements
- Purchase Pattern Analysis: Understand buying behaviors
- Customer Segmentation: AI-driven customer classification
- Retention Analytics: Customer lifetime value predictions
- Sales Growth Tracking: Monitor sales performance trends
- Volatility Indicators: Measure sales stability
- Accuracy Scoring: Track forecast precision
- Comparative Analysis: Benchmark against historical data
-
Daily Monitoring
- Check AI Sales Dashboard for current performance
- Review growth trends and volatility indicators
- Identify customers with changing demand patterns
-
Strategic Planning
- Use sales forecasts for capacity planning
- Adjust marketing strategies based on customer insights
- Plan inventory levels using demand predictions
-
Performance Review
- Analyze forecast accuracy monthly
- Adjust forecasting models based on performance
- Generate executive reports using AI insights
The AI Financial Forecasting module provides comprehensive financial predictions across multiple forecast types.
ERPNext → AI Inventory → AI Financial Settings
- Select Company for financial analysis
- Choose Forecast Types:
- Financial Forecast: General financial predictions
- Cashflow Forecast: Cash flow analysis and predictions
- Revenue Forecast: Revenue projections and trends
- Expense Forecast: Expense planning and forecasting
- Set forecasting parameters and sync schedules
- Click Sync All Forecasts to run comprehensive analysis
- Monitor sync progress in real-time
- Review sync logs for detailed operation status
- Financial Forecasting: Comprehensive financial trend analysis
- Cashflow Predictions: Cash flow projections with timing analysis
- Revenue Forecasting: Sales revenue predictions with growth trends
- Expense Planning: Cost forecasting and budget optimization
- Unified Sync Operations: Single-click synchronization across all forecast types
- Progress Monitoring: Real-time sync status and completion tracking
- Error Handling: Robust error management with detailed logging
- Accuracy Tracking: Performance monitoring for continuous improvement
- Trend Analysis: Identify financial patterns and cycles
- Variance Analysis: Compare actual vs. predicted performance
- Risk Assessment: Financial risk indicators and alerts
- Performance Metrics: Comprehensive financial health indicators
-
Initial Setup
- Configure financial forecasting parameters
- Set up automated sync schedules
- Define accuracy targets and alert thresholds
-
Regular Operations
- Monitor sync operations and logs
- Review financial forecasts and trends
- Adjust parameters based on accuracy feedback
-
Financial Planning
- Use cashflow forecasts for liquidity planning
- Apply revenue predictions for budgeting
- Utilize expense forecasts for cost control
- Purpose: General financial trend analysis and predictions
- Data Sources: General ledger, profit & loss statements
- Outputs: Financial health indicators, trend predictions
- Purpose: Cash flow timing and liquidity predictions
- Data Sources: Accounts receivable, accounts payable, cash transactions
- Outputs: Cash flow projections, liquidity alerts
- Purpose: Sales revenue predictions and growth analysis
- Data Sources: Sales invoices, sales orders, customer data
- Outputs: Revenue projections, growth trends, seasonal patterns
- Purpose: Cost planning and expense optimization
- Data Sources: Purchase invoices, expense claims, budget data
- Outputs: Expense predictions, cost trend analysis, budget variance
This section documents the AI Expense Forecast form fields and how values are computed and saved.
- ERPNext → AI Inventory → AI Expense Forecast
- Total Predicted Expense
- Computed on save as the sum of Expense Types and Inventory Integration fields:
- Expense Types: Fixed, Variable, Semi Variable, Inventory Related, Operational, Administrative
- Inventory Integration: Storage, Handling, Purchase Related, Reorder, Carrying, Stockout Costs
- Confidence Score
- Derived from data completeness and stability; a base value is adjusted for variance and trend stability.
- Seasonal Adjustment, Inflation Factor, Efficiency Factor
- Light, conservative placeholders: seasonal uplift in Nov/Dec, inflation set neutral by default, efficiency inferred from operational share.
- Expense Growth Rate
- Calculated vs the previous Expense Forecast for the same company prior to the current Forecast Date.
- Budget Variance
- Percent variance of total_actual_expenses vs total_predicted_expense, displayed in Analysis & Performance.
- Alert Status
- Derived from risk_score: Normal, Warning (≥40), Critical (≥70).
- Expense Breakdown (JSON)
- Stored on save for transparency; includes per-field amounts and totals.
- Last Updated
- Timestamp set on every save.
- On save, the document syncs to AI Financial Forecast using:
- forecast_start_date = Expense Forecast’s forecast_date
- forecast_type = Expense
- predicted_amount = total_predicted_expense
- confidence_score mirrored
- forecast_details JSON includes: expense_breakdown, total_expenses, expense_growth_rate, risk_factors, and the source ID.
- You can edit any input fields and Save to recompute totals and re-sync.
- If you maintain actuals, set total_actual_expenses to enable Budget Variance and utilization metrics.
Interactive, script-powered report to analyze revenue trends with growth and seasonality insights.
- Reports → Revenue Trend Analysis Report
- Workspace: AI Analytics → “Revenue Trend Analysis Report” link
- Company (optional)
- Analysis Period (Months): 6, 12, 18, 24, 36
- Include Revenue Breakdown (checkbox)
- Month, Revenue, MoM Growth %, Confidence %, Volatility %, Trend, Forecast Count, Seasonal Factor.
- Visual indicators for growth direction, volatility, and confidence.
- Revenue Breakdown: Opens a dialog with top revenue sources, shares, and confidence.
- Growth Analysis: Current growth rate, CAGR, consistency, trend direction, volatility.
- Seasonal Analysis: Peak/low months, seasonal intensity, factors.
- Export Report: Exports to Excel (and PDF via server method) with multi-sheet detail.
- Excel/PDF generation lives in report backend and returns file content and filename; the UI triggers Excel by default.
Note: If there’s no recent revenue data, the report gracefully shows sample data to avoid an empty report.
# For newer versions use the single DocType "AI Financial Settings" in the UI.
# The following snippet is for legacy installs that still have "AI Settings".
# Prefer configuring via the "AI Financial Settings" form instead of code.
# ai_settings = frappe.get_single("AI Settings")
# ai_settings.auto_sync_enabled = 1
# ai_settings.sync_frequency = "Daily"
# ai_settings.default_forecast_period = 30
# ai_settings.default_lead_time = 14
# ai_settings.confidence_threshold = 70
# ai_settings.save()# Set up company-specific parameters
company_config = {
"Company A": {
"forecast_period": 30,
"lead_time": 10,
"safety_factor": 1.5
},
"Company B": {
"forecast_period": 45,
"lead_time": 21,
"safety_factor": 2.0
}
}# Create forecast for specific item-warehouse-company combination
forecast = frappe.get_doc({
"doctype": "AI Inventory Forecast",
"item_code": "ITEM-001",
"warehouse": "WH-001",
"company": "Company A",
"forecast_period_days": 30,
"lead_time_days": 14
})
forecast.save()# Run AI forecast
result = forecast.run_ai_forecast()
print(f"Prediction: {result['predicted_consumption']} units")
print(f"Movement Type: {result['movement_type']}")
print(f"Confidence: {result['confidence_score']}%")# Sync all forecasts for a company
frappe.call({
'method': 'ai_inventory.ai_inventory.doctype.ai_inventory_forecast.ai_inventory_forecast.sync_ai_forecasts_now',
'args': {'company': 'Company A'}
})
# Create forecasts for items with stock
frappe.call({
'method': 'ai_inventory.ai_inventory.doctype.ai_inventory_forecast.ai_inventory_forecast.auto_create_forecasts_for_items_with_stock',
'args': {'company': 'Company A'}
})
# Sync all financial forecasts
frappe.call({
'method': 'ai_inventory.forecasting.sync_manager.sync_all_forecasts',
'args': {'company': 'Company A'}
})def custom_forecast_algorithm(historical_data, item_code, company):
"""
Implement your custom forecasting logic
"""
# Your algorithm here
return {
'predicted_consumption': predicted_value,
'confidence_score': confidence,
'movement_type': classification
}# Get company-wise summary
summary = get_company_wise_summary()
for company_data in summary:
print(f"Company: {company_data['company']}")
print(f"Total Forecasts: {company_data['total_forecasts']}")
print(f"Reorder Alerts: {company_data['reorder_alerts']}")- Ensure accurate historical data in stock ledger entries
- Maintain consistent item naming and coding
- Regular data cleanup and validation
- Start with default parameters and adjust based on accuracy
- Consider seasonal patterns when setting forecast periods
- Use appropriate lead times for your supply chain
- Review forecast accuracy weekly
- Adjust parameters based on performance metrics
- Monitor sync logs for any issues
- Configure company-specific parameters
- Use company-aware reporting
- Ensure data isolation between companies
- Regular sync operations for up-to-date predictions
- Monitor accuracy metrics for continuous improvement
- Use multiple forecast types for comprehensive analysis
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Frontend UI │ │ Backend API │ │ Database │
│ │ │ │ │ │
│ • Form Scripts │◄──►│ • Python Logic │◄──►│ • MariaDB │
│ • List Views │ │ • AI Algorithms │ │ • DocTypes │
│ • Dashboards │ │ • Sync Engine │ │ • Indexes │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Multi-Company │ │ Queue System │ │ External APIs │
│ Management │ │ │ │ │
│ │ │ • Background │ │ • Email Service │
│ • Company Filter│ │ Jobs │ │ • Notifications │
│ • Cross-Company │ │ • Sync Tasks │ │ • Integrations │
│ Analysis │ │ • Cleanup │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
graph TD
A[Stock Ledger Entry] --> B[Trigger Forecast Update]
B --> C{Company Match?}
C -->|Yes| D[Update AI Forecast]
C -->|No| E[Skip Update]
D --> F[Run AI Algorithm]
F --> G[Calculate Predictions]
G --> H[Generate Alerts]
H --> I[Send Notifications]
I --> J[Update Dashboard]
AI Inventory Forecast
├── Basic Info
│ ├── item_code (Link to Item)
│ ├── warehouse (Link to Warehouse)
│ ├── company (Link to Company)
│ └── item_name (Read Only)
├── Forecast Parameters
│ ├── forecast_period_days (Int)
│ ├── lead_time_days (Int)
│ └── auto_create_po (Check)
├── Current Status
│ ├── current_stock (Float)
│ ├── last_purchase_date (Date)
│ └── movement_type (Select)
├── AI Predictions
│ ├── predicted_consumption (Float)
│ ├── confidence_score (Percent)
│ ├── reorder_level (Float)
│ ├── suggested_qty (Float)
│ └── reorder_alert (Check)
├── Historical Data
│ ├── historical_data (Long Text)
│ ├── forecast_details (Long Text)
│ └── last_forecast_date (Datetime)
└── Purchase Order
├── supplier (Link to Supplier)
├── last_po_date (Date)
└── auto_po_created (Check)
Executes AI forecasting algorithm for a single item.
result = forecast_doc.run_ai_forecast()
# Returns: {
# "status": "success",
# "predicted_consumption": 150.5,
# "movement_type": "Fast Moving",
# "confidence_score": 87.3,
# "reorder_alert": True
# }Synchronizes all financial forecast types for specified company.
result = sync_all_forecasts(company="Company A")
# Returns: {
# "status": "success",
# "total_items": 125,
# "successful": 120,
# "failed": 5,
# "success_rate": 96.0,
# "forecast_types": ["Financial", "Cashflow", "Revenue", "Expense"],
# "sync_log_id": "AI-FSYNC-2025-00001"
# }Creates accuracy tracking records for forecast validation.
result = create_forecast_accuracy("Financial", "AI-FIN-FCST-00001")
# Returns: {
# "status": "success",
# "accuracy_id": "AI-FACC-2025-00001",
# "forecast_reference": "AI-FIN-FCST-00001"
# }Automatically creates purchase order based on forecast recommendations.
result = forecast_doc.create_purchase_order()
# Returns: {
# "status": "success",
# "message": "Created new PO: PUR-ORD-2024-00001 for Company A"
# }Returns summary statistics for all companies.
summary = get_company_wise_summary()
# Returns: [
# {
# "company": "Company A",
# "total_forecasts": 500,
# "reorder_alerts": 25,
# "avg_confidence": 82.5,
# "fast_moving": 150,
# "slow_moving": 200,
# "critical": 10
# }
# ]Creates forecast records for all stock items.
result = bulk_create_forecasts_for_existing_items(company="Company A")
# Returns: {
# "status": "success",
# "forecasts_created": 1500,
# "company_breakdown": {"Company A": 1500}
# }Generates AI Sales Dashboard with predictive analytics.
result = execute_sales_dashboard({
"company": "Company A",
"from_date": "2024-01-01",
"to_date": "2024-12-31",
"customer": None,
"item_code": None
})
# Returns: {
# "columns": [...],
# "data": [
# {
# "item_code": "ITEM-001",
# "total_sales": 50000.0,
# "growth_rate": 15.5,
# "volatility_index": 0.23,
# "forecast_accuracy": 87.3,
# "customer_demand_trend": "Increasing"
# }
# ],
# "chart": {...}
# }Retrieves current sync operation status and logs.
status = get_sync_status(company="Company A")
# Returns: {
# "status": "completed",
# "last_sync": "2025-08-06 10:30:00",
# "total_operations": 125,
# "success_rate": 96.0,
# "active_sync": False,
# "recent_logs": [...]
# }POST /api/method/ai_inventory.forecasting.sync_manager.sync_all_forecasts
Content-Type: application/json
{
"company": "Company A"
}GET /api/method/ai_inventory.forecasting.sync_manager.get_sync_status?company=Company%20APOST /api/method/ai_inventory.ai_inventory.report.ai_sales_dashboard.ai_sales_dashboard.execute
Content-Type: application/json
{
"filters": {
"company": "Company A",
"from_date": "2024-01-01",
"to_date": "2024-12-31",
"customer": null,
"item_code": "ITEM-001"
}
}# Configure global AI settings
ai_settings = frappe.get_single("AI Settings")
ai_settings.auto_sync_enabled = 1
ai_settings.sync_frequency = "Daily"
ai_settings.default_forecast_period = 30
ai_settings.default_lead_time = 14
ai_settings.confidence_threshold = 70
ai_settings.save()# Set up company-specific parameters
company_config = {
"Company A": {
"forecast_period": 30,
"lead_time": 10,
"safety_factor": 1.5
},
"Company B": {
"forecast_period": 45,
"lead_time": 21,
"safety_factor": 2.0
}
}# Configure background jobs
scheduler_events = {
"daily": [
"ai_inventory.scheduled_tasks.daily_ai_forecast",
"ai_inventory.hooks_handlers.daily_create_missing_forecasts"
],
"hourly": [
"ai_inventory.scheduled_tasks.hourly_critical_stock_check"
],
"weekly": [
"ai_inventory.scheduled_tasks.weekly_forecast_analysis"
]
}# Run all tests
bench --site your-site-name run-tests ai_inventory
# Run specific test
bench --site your-site-name run-tests ai_inventory.tests.test_ai_forecast
# Run with coverage
bench --site your-site-name run-tests ai_inventory --coverage# Test AI forecasting accuracy
def test_ai_forecast_accuracy():
forecast = create_test_forecast()
result = forecast.run_ai_forecast()
assert result["status"] == "success"
assert result["confidence_score"] > 0
assert result["predicted_consumption"] >= 0
# Test multi-company isolation
def test_company_isolation():
company_a_forecasts = get_forecasts_for_company("Company A")
company_b_forecasts = get_forecasts_for_company("Company B")
# Ensure no cross-company data mixing
for forecast in company_a_forecasts:
assert forecast.company == "Company A"# Test bulk operations performance
def test_bulk_sync_performance():
import time
start_time = time.time()
result = sync_ai_forecasts_now()
end_time = time.time()
execution_time = end_time - start_time
# Should complete within reasonable time
assert execution_time < 300 # 5 minutes max
assert result["success_rate"] > 90Cause: Required packages not installed before app installation.
Solution:
# Install packages first, then retry migration
./env/bin/pip install numpy pandas scikit-learn matplotlib scipy
bench --site your-site-name migrateCause: Field validation errors or missing required data.
Solution:
# Check sync logs for detailed error information
sync_logs = frappe.get_list('AI Forecast Sync Log',
filters={'status': 'Failed'},
fields=['sync_time', 'error_details', 'failed_items']
)
# Fix common field validation issues
frappe.call('ai_inventory.forecasting.sync_manager.fix_validation_issues')Previous Issue: Dynamic Link field configuration errors.
Resolution: Updated to use Data field type for forecast references and fixed all select field value validations.
Previous Issue: Field name mismatches in AI Forecast Accuracy DocType.
Resolution: Standardized field names and updated all references to use forecast_reference instead of Dynamic Link fields.
# Check for missing companies
missing_companies = frappe.db.sql("""
SELECT DISTINCT aif.company
FROM `tabAI Inventory Forecast` aif
WHERE aif.company NOT IN (SELECT name FROM `tabCompany`)
""")
# Check for disabled items/warehouses
disabled_refs = frappe.db.sql("""
SELECT aif.name, i.disabled as item_disabled, w.disabled as warehouse_disabled
FROM `tabAI Inventory Forecast` aif
LEFT JOIN `tabItem` i ON i.name = aif.item_code
LEFT JOIN `tabWarehouse` w ON w.name = aif.warehouse
WHERE i.disabled = 1 OR w.disabled = 1
""")
# Monitor sync operations
recent_syncs = frappe.get_list('AI Forecast Sync Log',
fields=['sync_time', 'sync_type', 'status', 'total_items', 'successful_items', 'error_details'],
order_by='sync_time desc',
limit=10
)# Add database indexes
frappe.db.sql("""
CREATE INDEX idx_ai_forecast_company_item
ON `tabAI Inventory Forecast` (company, item_code)
""")
frappe.db.sql("""
CREATE INDEX idx_ai_forecast_reorder
ON `tabAI Inventory Forecast` (reorder_alert, company)
""")- Symptom: “ is not a valid Email Address” in Error Log when sending alerts/reports.
- Cause: Misconfigured Notification/Auto Email Report recipient or passing user IDs instead of emails.
- Fixes in code: All senders now resolve users → emails, dedupe, and filter invalid addresses; sends are skipped when no valid recipients remain.
- What you can check:
- Settings → Notifications and Auto Email Reports: ensure Recipients are valid email addresses or roles that map to enabled users with emails.
- Company.default_finance_email and user records: confirm valid emails.
- If a legacy custom script injects recipients, remove non-email strings.
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Debug sync operations
def debug_sync_operation(company):
print(f"🔍 Debugging sync for {company}")
# Check sync status
status = frappe.call('ai_inventory.forecasting.sync_manager.get_sync_status',
company=company)
print(f"📊 Sync Status: {status}")
# Check recent logs
logs = frappe.get_list('AI Forecast Sync Log',
filters={'company': company},
fields=['sync_time', 'sync_type', 'status', 'error_details'],
order_by='sync_time desc',
limit=5
)
print(f"📋 Recent Logs: {logs}")
# Test specific forecast accuracy
def debug_forecast_accuracy(forecast_id):
accuracy_records = frappe.get_list('AI Forecast Accuracy',
filters={'forecast_reference': forecast_id},
fields=['accuracy_score', 'prediction_error', 'last_updated']
)
print(f"🎯 Accuracy Records: {accuracy_records}")# Check ERPNext logs for errors
tail -f /path/to/frappe-bench/logs/worker.error.log | grep ai_inventory
# Check database slow queries
tail -f /path/to/mysql/slow-query.log | grep AI_Inventory_Forecast
# Monitor background jobs
bench --site your-site-name doctor
# Check sync operation logs
bench --site your-site-name console
>>> frappe.get_list('AI Forecast Sync Log', fields=['sync_time', 'status', 'total_items'], order_by='sync_time desc', limit=10)# Real-time sync monitoring
def monitor_sync_operations():
# Get active sync operations
active_syncs = frappe.db.sql("""
SELECT name, sync_type, sync_time, status
FROM `tabAI Forecast Sync Log`
WHERE status = 'In Progress'
ORDER BY sync_time DESC
""", as_dict=True)
# Get recent completed syncs
recent_syncs = frappe.db.sql("""
SELECT name, sync_type, sync_time, status, total_items, successful_items
FROM `tabAI Forecast Sync Log`
WHERE status IN ('Completed', 'Failed')
ORDER BY sync_time DESC
LIMIT 10
""", as_dict=True)
return {
'active_syncs': active_syncs,
'recent_syncs': recent_syncs
}# Migration script
def migrate_to_multicompany():
# Add company field to existing forecasts
forecasts_without_company = frappe.db.sql("""
SELECT name, warehouse
FROM `tabAI Inventory Forecast`
WHERE company IS NULL OR company = ''
""", as_dict=True)
for forecast in forecasts_without_company:
# Get company from warehouse
warehouse_company = frappe.db.get_value("Warehouse", forecast.warehouse, "company")
if warehouse_company:
frappe.db.set_value("AI Inventory Forecast", forecast.name, "company", warehouse_company)
print(f"✅ Migrated {len(forecasts_without_company)} forecasts")
# Run migration
migrate_to_multicompany()-- Add company field to AI Inventory Forecast
ALTER TABLE `tabAI Inventory Forecast`
ADD COLUMN company VARCHAR(180) AFTER warehouse;
-- Add indexes for better performance
CREATE INDEX idx_ai_forecast_company ON `tabAI Inventory Forecast` (company);
CREATE INDEX idx_ai_forecast_company_item ON `tabAI Inventory Forecast` (company, item_code);
CREATE INDEX idx_ai_forecast_reorder_company ON `tabAI Inventory Forecast` (reorder_alert, company);
-- Update existing records
UPDATE `tabAI Inventory Forecast` aif
INNER JOIN `tabWarehouse` w ON w.name = aif.warehouse
SET aif.company = w.company
WHERE aif.company IS NULL OR aif.company = '';We welcome contributions! Please follow these guidelines:
# Fork and clone the repository
git clone https://github.com/yourusername/ai_inventory.git
cd ai_inventory
# Create development branch
git checkout -b feature/your-feature-name
# Install development dependencies
pip install -r requirements-dev.txt
# Setup pre-commit hooks
pre-commit install- Python: Follow PEP 8 style guide
- JavaScript: Use ESLint configuration provided
- Commit Messages: Use conventional commit format
- Documentation: Update docs for any new features
-
Create Feature Branch
git checkout -b feature/amazing-feature
-
Make Changes
- Add your code changes
- Include tests for new functionality
- Update documentation
-
Test Your Changes
bench --site test-site run-tests ai_inventory
-
Submit Pull Request
- Provide clear description
- Reference any related issues
- Include screenshots for UI changes
# Use type hints
def run_ai_forecast(self) -> Dict[str, Any]:
"""
Run AI forecasting algorithm for this item.
Returns:
Dict containing forecast results with status, predictions, etc.
"""
pass
# Document complex functions
def complex_algorithm(data: List[Dict]) -> float:
"""
Complex algorithm description here.
Args:
data: List of historical consumption records
Returns:
Predicted consumption value
Raises:
ValueError: If data is insufficient
"""
pass- AI Sales Dashboard with Predictive Analytics
- Customer Demand Forecasting
- Sales Trend Analysis and Growth Metrics
- Financial Forecasting System (Financial, Cashflow, Revenue, Expense)
- Forecast Accuracy Tracking and Monitoring
- Comprehensive Sync System with Error Handling
- Enhanced Logging and Debug Capabilities
- Machine Learning Integration (TensorFlow/PyTorch)
- Advanced Seasonality Detection
- Multi-location Inventory Optimization
- REST API Enhancements
- Supplier Performance Analytics
- Cost Optimization Algorithms
- Mobile App for Stock Managers
- Real-time Alerts via WhatsApp/Slack
- Predictive Maintenance Integration
- IoT Sensor Data Integration
- Advanced Reporting with BI Tools
- Multi-currency Support
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2024 AI Inventory Forecast
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
- GitHub Issues: Report bugs and request features
- Discussions: Community forum
- Wiki: Documentation and guides
- Professional Services: Available for custom implementations
- Training: On-site and remote training sessions
- Consulting: Architecture and optimization consulting
- Email: support@ai-inventory-forecast.com
- Website: https://ai-inventory-forecast.com
- LinkedIn: AI Inventory Forecast
⭐ If this project helped you, please consider giving it a star! ⭐
Made with ❤️ by the AI Inventory Team
🏠 Home • 📖 Docs • 🐛 Issues • 💬 Discussions
This guide provides detailed step-by-step instructions for installing AI Inventory Forecast on ERPNext.
| Component | Minimum | Recommended |
|---|---|---|
| ERPNext | v14.0 | v15.0+ |
| Frappe Framework | v14.0 | v15.0+ |
| Python | 3.8 | 3.10+ |
| MariaDB | 10.4 | 10.6+ |
| RAM | 4GB | 8GB+ |
| Storage | 10GB free | 50GB+ free |
| CPU | 2 cores | 4+ cores |
# Python packages (automatically installed)
pandas>=1.3.0
numpy>=1.21.0
frappe>=14.0.0
erpnext>=14.0.0
# System packages (manual installation required)
sudo apt-get update
sudo apt-get install -y python3-dev python3-pip
sudo apt-get install -y build-essential# 1. Navigate to your bench directory
cd /home/frappe/frappe-bench
# 2. Get the app from GitHub
bench get-app https://github.com/yourusername/ai_inventory.git
# 3. Install on your site
bench --site your-site-name install-app ai_inventory
# 4. Migrate database
bench --site your-site-name migrate
# 5. Restart services
bench restart
# 6. Clear cache
bench --site your-site-name clear-cache# 1. Clone the repository
cd /home/frappe/frappe-bench/apps
git clone https://github.com/yourusername/ai_inventory.git
# 2. Install the app
cd /home/frappe/frappe-bench
bench --site your-site-name install-app ai_inventory
# 3. Migrate and restart
bench --site your-site-name migrate
bench restart# Download the latest release
wget https://github.com/yourusername/ai_inventory/archive/v2.0.0.tar.gz
# Extract
tar -xzf v2.0.0.tar.gz
mv ai_inventory-2.0.0 /home/frappe/frappe-bench/apps/ai_inventorycd /home/frappe/frappe-bench/apps/ai_inventory
pip3 install -r requirements.txtcd /home/frappe/frappe-bench
bench --site your-site-name install-app ai_inventory# Run migrations
bench --site your-site-name migrate
# Rebuild search index
bench --site your-site-name build-search-index
# Clear cache
bench --site your-site-name clear-cache# Run in ERPNext console (bench --site your-site-name console)
# Create AI Inventory Manager role
frappe.get_doc({
"doctype": "Role",
"role_name": "AI Inventory Manager",
"desk_access": 1
}).insert()
# Create AI Inventory User role
frappe.get_doc({
"doctype": "Role",
"role_name": "AI Inventory User",
"desk_access": 1
}).insert()# AI Inventory Forecast permissions
permissions = [
{
"role": "AI Inventory Manager",
"read": 1, "write": 1, "create": 1, "delete": 1,
"submit": 0, "cancel": 0, "amend": 0
},
{
"role": "AI Inventory User",
"read": 1, "write": 0, "create": 0, "delete": 0,
"submit": 0, "cancel": 0, "amend": 0
},
{
"role": "Stock Manager",
"read": 1, "write": 1, "create": 1, "delete": 1,
"submit": 0, "cancel": 0, "amend": 0
}
]
for perm in permissions:
frappe.get_doc({
"doctype": "Custom DocPerm",
"parent": "AI Inventory Forecast",
"parenttype": "DocType",
"role": perm["role"],
**{k: v for k, v in perm.items() if k != "role"}
}).insert()# Assign roles to specific users
users_roles = {
"stock.manager@company.com": ["AI Inventory Manager", "Stock Manager"],
"inventory.user@company.com": ["AI Inventory User"],
"admin@company.com": ["AI Inventory Manager"]
}
for user, roles in users_roles.items():
user_doc = frappe.get_doc("User", user)
for role in roles:
user_doc.append("roles", {"role": role})
user_doc.save()# Enable multi-company features
ai_settings = frappe.get_single("AI Settings")
ai_settings.enable_multi_company = 1
ai_settings.company_isolation = 1
ai_settings.save()companies = ["Company A", "Company B", "Company C"]
for company in companies:
# Create company-specific AI settings
company_settings = frappe.get_doc({
"doctype": "AI Company