Usage Guide
Step-by-step guide for using the Suggested Products feature
Usage Guide
This comprehensive guide walks you through all aspects of using the Suggested Products feature, from initial setup to advanced usage scenarios.
Getting Started
Prerequisites
Before using the Suggested Products feature, ensure you have:
- Sufficient Historical Data: At least 3-6 months of order history
- Customer Base: Minimum 50 active customers with multiple orders
- Product Catalog: Well-structured product database
- System Resources: Adequate memory and processing power
- Permissions: Appropriate user roles and access rights
Initial Setup Checklist
- Configure algorithm parameters in
config/eva.php - Set environment variables in
.env - Verify database connections and permissions
- Test with a small dataset first
- Schedule regular generation jobs
Command Line Interface
Basic Generation Command
Generate suggestions for the default time period (24 months):
php artisan generate:suggested-productsAdvanced Command Usage
Generate for Specific Date Range
# Generate for the last 12 months
php artisan generate:suggested-products "2024-01-01" "2024-12-31"
# Generate for a specific quarter
php artisan generate:suggested-products "2024-07-01" "2024-09-30"Generate for Specific Customers
# Generate for specific customer IDs
php artisan generate:suggested-products --customers=123,456,789
# Generate for customers in specific regions
php artisan generate:suggested-products --regions=1,2,3Performance Options
# Use smaller chunk size for limited memory
php artisan generate:suggested-products --chunk-size=10
# Force regeneration (overwrite existing)
php artisan generate:suggested-products --force
# Run in verbose mode for detailed logging
php artisan generate:suggested-products --verboseBackground Processing
# Run in background with nohup
nohup php artisan generate:suggested-products > suggestions.log 2>&1 &
# Using screen for long-running processes
screen -S suggestions
php artisan generate:suggested-products
# Ctrl+A, D to detachCommand Options Reference
| Option | Description | Example |
|---|---|---|
--customers | Specific customer IDs | --customers=1,2,3 |
--regions | Filter by regions | --regions=1,2 |
--chunk-size | Processing chunk size | --chunk-size=20 |
--force | Overwrite existing data | --force |
--verbose | Detailed output | --verbose |
--dry-run | Test without saving | --dry-run |
--support | Override support threshold | --support=0.15 |
--confidence | Override confidence threshold | --confidence=0.6 |
Web Dashboard Interface
Accessing the Dashboard
Navigate to: /eva/suggested-products
The dashboard provides a comprehensive interface for viewing and managing suggested products.
Dashboard Features
1. Main Overview Tab
graph TD
A[Dashboard] --> B[Summary Statistics]
A --> C[Recent Generation Jobs]
A --> D[Top Performing Suggestions]
A --> E[System Health]
B --> B1[Total Customers]
B --> B2[Suggestions Generated]
B --> B3[Conversion Rate]
B --> B4[Last Updated]Key Metrics Displayed:
- Total customers with suggestions
- Number of product sets generated
- Conversion rate (if tracking enabled)
- Last generation timestamp
- Algorithm performance metrics
2. Suggestions Report Tab
Features:
- Paginated table of all suggestions
- Advanced filtering options
- Real-time search functionality
- Export capabilities
Available Filters:
- Customer name/ID
- Product categories
- Date range
- Confidence scores
- Status (active/inactive)
- Region/territory
3. Customer Analysis Tab
Capabilities:
- Customer-specific suggestion details
- Order history visualization
- Suggestion accuracy tracking
- Customer segmentation insights
Using the Filter System
Basic Filtering
- By Customer: Type customer name or ID in the search box
- By Date Range: Use the date picker to select analysis period
- By Status: Choose from active, inactive, or all suggestions
- By Region: Select specific geographical regions
Advanced Filtering
// Example filter configuration
{
"customer_id": 123,
"product_category": ["electronics", "accessories"],
"confidence_min": 0.5,
"date_range": {
"start": "2024-01-01",
"end": "2024-12-31"
},
"sort_by": "confidence_desc"
}Export Functionality
Excel Export
- Apply desired filters
- Click "Export to Excel" button
- Choose export options:
- Include customer details
- Include product details
- Include confidence scores
- Group by customer/product
CSV Export
For large datasets, CSV export provides:
- Faster processing
- Smaller file sizes
- Easy integration with external tools
PDF Reports
Generate formatted reports with:
- Executive summary
- Key metrics
- Top recommendations
- Visualizations
API Integration
Getting Real-time Suggestions
Basic API Call
// Fetch suggestions for a customer
fetch('/api/suggested-products-from-recent-orders?shop_id=123', {
headers: {
'Authorization': 'Bearer ' + token,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log('Suggestions:', data.data);
});Advanced API Usage
// Advanced options
const options = {
shop_id: 123,
limit: 10,
include_pricing: true,
include_substitutes: true,
order_cycles: 5
};
const queryString = new URLSearchParams(options).toString();
const response = await fetch(`/api/suggested-products-from-recent-orders?${queryString}`);Error Handling
try {
const response = await fetch('/api/suggested-products-from-recent-orders?shop_id=123');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching suggestions:', error);
// Fallback to cached or default suggestions
}Integration Patterns
E-commerce Integration
// In your product page controller
public function show($productId)
{
$product = Product::find($productId);
$customer = auth()->user();
// Get suggestions
$suggestions = app(GetSuggestedProductsFromRecentOrdersService::class)
->getSuggestions($customer->id, ['limit' => 5]);
return view('products.show', compact('product', 'suggestions'));
}Mobile App Integration
// Flutter/Dart example
class SuggestedProductsService {
Future<List<Product>> getSuggestions(int customerId) async {
final response = await http.get(
Uri.parse('$baseUrl/suggested-products-from-recent-orders?shop_id=$customerId'),
headers: {'Authorization': 'Bearer $token'},
);
if (response.statusCode == 200) {
final data = json.decode(response.body);
return data['data'].map<Product>((json) => Product.fromJson(json)).toList();
}
throw Exception('Failed to load suggestions');
}
}Advanced Usage Scenarios
Scenario 1: Seasonal Campaign Management
Step 1: Generate Season-Specific Suggestions
# Generate suggestions for holiday season
php artisan generate:suggested-products "2024-11-01" "2024-12-31" \
--categories="gifts,electronics" \
--confidence=0.7Step 2: Apply Seasonal Adjustments
// In your configuration
'seasonal_factors' => [
'electronics' => [
11 => 1.4, // November boost
12 => 1.6, // December boost
]
]Step 3: Monitor Performance
Track conversion rates and adjust parameters:
SELECT
COUNT(*) as total_suggestions,
SUM(CASE WHEN ordered = 1 THEN 1 ELSE 0 END) as conversions,
AVG(confidence_score) as avg_confidence
FROM suggestion_tracking
WHERE created_at >= '2024-11-01';Scenario 2: Customer Onboarding
New Customer Suggestions
For customers with limited history:
// Special handling for new customers
if ($customer->orders()->count() < 3) {
// Use popular products in customer's region/category
$suggestions = $this->getPopularProductsSuggestions($customer);
} else {
// Use ML-based suggestions
$suggestions = $this->getMLSuggestions($customer);
}Gradual Algorithm Transition
// Gradually transition from popular to ML-based
$orderCount = $customer->orders()->count();
$mlWeight = min($orderCount / 10, 1.0); // Max at 10 orders
$popularWeight = 1 - $mlWeight;
$finalSuggestions = $this->combineWeighted([
'ml' => ['suggestions' => $mlSuggestions, 'weight' => $mlWeight],
'popular' => ['suggestions' => $popularSuggestions, 'weight' => $popularWeight]
]);Scenario 3: B2B Bulk Ordering
Configure for B2B Context
// B2B-specific configuration
'b2b_settings' => [
'min_order_count' => 5,
'suggested_products_limit' => 30,
'include_bulk_discounts' => true,
'prioritize_contract_items' => true,
'order_cycles' => 10, // Longer cycles for B2B
]Implementation
// B2B suggestion service
class B2BSuggestedProductsService extends GetSuggestedProductsFromRecentOrdersService
{
protected function enrichWithBusinessData($suggestions, $customerId)
{
$customer = Customer::find($customerId);
foreach ($suggestions as &$suggestion) {
// Add contract pricing
$suggestion['contract_price'] = $this->getContractPrice($customer, $suggestion['product_id']);
// Add bulk tier pricing
$suggestion['bulk_tiers'] = $this->getBulkTiers($suggestion['product_id']);
// Add lead times
$suggestion['lead_time'] = $this->getLeadTime($suggestion['product_id'], $customer->region);
}
return $suggestions;
}
}Scenario 4: Multi-tenant Implementation
Tenant-specific Configuration
// Tenant-aware configuration
foreach ($tenants as $tenant) {
$config = [
'suggested_products_apriori_support' => $tenant->algorithm_support ?? 0.1,
'suggested_products_confidence_support' => $tenant->algorithm_confidence ?? 0.5,
'suggested_products_limit' => $tenant->max_suggestions ?? 20,
];
Config::set('eva', array_merge(Config::get('eva'), $config));
// Generate for this tenant
Artisan::call('generate:suggested-products', [
'--tenant' => $tenant->id,
'--customers' => $tenant->customers()->pluck('id')->implode(',')
]);
}Performance Optimization
Monitoring Commands
Check Generation Status
# Check if generation is running
ps aux | grep "generate:suggested-products"
# Check system resources
htop
free -h
df -hPerformance Metrics
# Check database performance
mysql -e "SHOW PROCESSLIST;"
mysql -e "SHOW TABLE STATUS LIKE 'suggested_products';"
# Check application logs
tail -f storage/logs/laravel.log | grep suggested-productsOptimization Strategies
1. Database Optimization
-- Add indexes for better performance
CREATE INDEX idx_suggested_products_customer_date
ON suggested_products (customer_id, created_at);
CREATE INDEX idx_frequent_product_sets_priority
ON frequent_product_sets (product_set_id, priority);
-- Analyze tables regularly
ANALYZE TABLE suggested_products, frequent_product_sets;2. Memory Optimization
// Process in smaller chunks
$customers->chunk(10)->each(function ($chunk) {
$this->processCustomers($chunk);
gc_collect_cycles(); // Force garbage collection
});3. Caching Strategy
// Cache frequent queries
$suggestions = Cache::remember(
"suggestions_customer_{$customerId}",
3600,
function () use ($customerId) {
return $this->generateSuggestions($customerId);
}
);Troubleshooting Common Issues
Issue: Generation Takes Too Long
Solutions:
- Reduce chunk size:
--chunk-size=10 - Increase memory limit:
'suggested_products_memory_limit' => '4G' - Process fewer customers:
--customers=1,2,3 - Reduce analysis window:
'suggested_products_window_in_months' => 12
Issue: Low Quality Suggestions
Solutions:
- Increase confidence threshold:
'suggested_products_confidence_support' => 0.7 - Increase minimum order count:
'suggested_products_min_order_count' => 5 - Clean data: Remove cancelled/refunded orders
- Verify product categorization
Issue: Memory Errors
Solutions:
- Increase PHP memory limit
- Reduce chunk size
- Process customers in batches
- Clean up old error logs
Issue: No Suggestions Generated
Checklist:
- Sufficient historical data (>3 months)
- Multiple products per order
- Correct date range
- Valid customer IDs
- Proper configuration values
Best Practices
1. Regular Maintenance
# Weekly suggestion regeneration
0 2 * * 0 /usr/bin/php /path/to/artisan generate:suggested-products
# Monthly full regeneration
0 3 1 * * /usr/bin/php /path/to/artisan generate:suggested-products --force
# Daily cleanup of old logs
0 1 * * * /usr/bin/php /path/to/artisan suggested-products:cleanup2. A/B Testing
// Test different parameters
$testGroups = [
'control' => ['support' => 0.1, 'confidence' => 0.5],
'high_confidence' => ['support' => 0.1, 'confidence' => 0.7],
'low_support' => ['support' => 0.05, 'confidence' => 0.5],
];
foreach ($testGroups as $group => $params) {
$this->generateWithParams($params, $group);
}3. Continuous Monitoring
// Track suggestion performance
class SuggestionMetrics
{
public function track($customerId, $suggestions, $actualOrder)
{
$accuracy = $this->calculateAccuracy($suggestions, $actualOrder);
$conversion = $this->calculateConversion($suggestions, $actualOrder);
Metric::create([
'customer_id' => $customerId,
'accuracy' => $accuracy,
'conversion_rate' => $conversion,
'timestamp' => now(),
]);
}
}This comprehensive usage guide provides everything needed to effectively implement and maintain the Suggested Products feature in various business scenarios.