Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- SimpleLinearRegression.js +48 -0
- aiAnalyticsController.js +510 -0
SimpleLinearRegression.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export default class SimpleLinearRegression {
|
| 2 |
+
constructor(x, y) {
|
| 3 |
+
this.x = x.map(val => Array.isArray(val) ? val[0] : val);
|
| 4 |
+
this.y = y;
|
| 5 |
+
this.n = this.x.length;
|
| 6 |
+
|
| 7 |
+
let sumX = 0;
|
| 8 |
+
let sumY = 0;
|
| 9 |
+
let sumXY = 0;
|
| 10 |
+
let sumX2 = 0;
|
| 11 |
+
|
| 12 |
+
for (let i = 0; i < this.n; i++) {
|
| 13 |
+
sumX += this.x[i];
|
| 14 |
+
sumY += this.y[i];
|
| 15 |
+
sumXY += this.x[i] * this.y[i];
|
| 16 |
+
sumX2 += this.x[i] * this.x[i];
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
const denominator = (this.n * sumX2 - sumX * sumX);
|
| 20 |
+
if (denominator === 0) {
|
| 21 |
+
this.slope = 0;
|
| 22 |
+
this.intercept = sumY / this.n || 0;
|
| 23 |
+
} else {
|
| 24 |
+
this.slope = (this.n * sumXY - sumX * sumY) / denominator;
|
| 25 |
+
this.intercept = (sumY - this.slope * sumX) / this.n;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
this.coefficients = [this.slope, this.intercept];
|
| 29 |
+
|
| 30 |
+
// Calculate R2
|
| 31 |
+
const yMean = this.n > 0 ? sumY / this.n : 0;
|
| 32 |
+
let ssTot = 0;
|
| 33 |
+
let ssRes = 0;
|
| 34 |
+
|
| 35 |
+
for (let i = 0; i < this.n; i++) {
|
| 36 |
+
const prediction = this.predict(this.x[i]);
|
| 37 |
+
ssTot += Math.pow(this.y[i] - yMean, 2);
|
| 38 |
+
ssRes += Math.pow(this.y[i] - prediction, 2);
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
this.r2 = ssTot === 0 ? 1 : 1 - (ssRes / ssTot);
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
predict(x) {
|
| 45 |
+
const xVal = Array.isArray(x) ? x[0] : x;
|
| 46 |
+
return this.slope * xVal + this.intercept;
|
| 47 |
+
}
|
| 48 |
+
}
|
aiAnalyticsController.js
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import SimpleLinearRegression from '../utils/SimpleLinearRegression.js';
|
| 2 |
+
import Invoice from '../models/InvoiceModel.js';
|
| 3 |
+
import Product from '../models/ProductModel.js';
|
| 4 |
+
import Service from '../models/ServiceModel.js';
|
| 5 |
+
import CatalogItem from '../models/CatalogItemModel.js';
|
| 6 |
+
import Supplier from '../models/SupplierModel.js';
|
| 7 |
+
import Customer from '../models/CustomerModel.js';
|
| 8 |
+
import { resolveScopedBranch } from '../utils/branchContext.js';
|
| 9 |
+
import aiCache from '../utils/aiCache.js';
|
| 10 |
+
|
| 11 |
+
// AI Analytics Controller
|
| 12 |
+
export const getSalesAnalytics = async (req, res) => {
|
| 13 |
+
try {
|
| 14 |
+
const tenantId = req.user.tenant._id;
|
| 15 |
+
const { branchFilter } = await resolveScopedBranch(req);
|
| 16 |
+
const { period = '30' } = req.query; // days
|
| 17 |
+
|
| 18 |
+
// Check cache first
|
| 19 |
+
const branchId = branchFilter.branch?._id || 'all';
|
| 20 |
+
const cacheKey = { period };
|
| 21 |
+
|
| 22 |
+
const cachedData = aiCache.get('sales', tenantId, branchId, cacheKey);
|
| 23 |
+
// Temporarily bypass cache to ensure fresh data calculation after bugfix
|
| 24 |
+
// if (cachedData) {
|
| 25 |
+
// return res.json(cachedData);
|
| 26 |
+
// }
|
| 27 |
+
|
| 28 |
+
// Get historical sales data
|
| 29 |
+
const startDate = new Date();
|
| 30 |
+
startDate.setDate(startDate.getDate() - parseInt(period));
|
| 31 |
+
|
| 32 |
+
const invoices = await Invoice.find({
|
| 33 |
+
tenant: tenantId,
|
| 34 |
+
...branchFilter,
|
| 35 |
+
createdAt: { $gte: startDate }
|
| 36 |
+
}).populate('customer items.productId');
|
| 37 |
+
|
| 38 |
+
// Process data for ML analysis
|
| 39 |
+
const salesData = [];
|
| 40 |
+
const productPerformance = {};
|
| 41 |
+
const customerBehavior = {};
|
| 42 |
+
const dailySales = {};
|
| 43 |
+
|
| 44 |
+
invoices.forEach(invoice => {
|
| 45 |
+
const date = invoice.createdAt.toISOString().split('T')[0];
|
| 46 |
+
dailySales[date] = (dailySales[date] || 0) + invoice.totalAmount;
|
| 47 |
+
|
| 48 |
+
invoice.items.forEach(item => {
|
| 49 |
+
const rawId = item.productId?._id || item.productId;
|
| 50 |
+
if (rawId) {
|
| 51 |
+
const productId = rawId.toString();
|
| 52 |
+
if (!productPerformance[productId]) {
|
| 53 |
+
productPerformance[productId] = {
|
| 54 |
+
name: item.name,
|
| 55 |
+
totalSales: 0,
|
| 56 |
+
quantity: 0,
|
| 57 |
+
revenue: 0,
|
| 58 |
+
frequency: 0
|
| 59 |
+
};
|
| 60 |
+
}
|
| 61 |
+
productPerformance[productId].totalSales += Number(item.total || 0);
|
| 62 |
+
productPerformance[productId].quantity += Number(item.quantity || 1);
|
| 63 |
+
productPerformance[productId].revenue += Number(item.total || 0);
|
| 64 |
+
productPerformance[productId].frequency += 1;
|
| 65 |
+
}
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
// Customer behavior analysis
|
| 69 |
+
const customerId = invoice.customer._id;
|
| 70 |
+
if (!customerBehavior[customerId]) {
|
| 71 |
+
customerBehavior[customerId] = {
|
| 72 |
+
totalSpent: 0,
|
| 73 |
+
invoiceCount: 0,
|
| 74 |
+
avgInvoiceValue: 0
|
| 75 |
+
};
|
| 76 |
+
}
|
| 77 |
+
customerBehavior[customerId].totalSpent += invoice.totalAmount;
|
| 78 |
+
customerBehavior[customerId].invoiceCount += 1;
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
// Calculate average invoice value
|
| 82 |
+
Object.keys(customerBehavior).forEach(customerId => {
|
| 83 |
+
const behavior = customerBehavior[customerId];
|
| 84 |
+
behavior.avgInvoiceValue = behavior.totalSpent / behavior.invoiceCount;
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
// Popular products identification
|
| 88 |
+
const popularProducts = Object.entries(productPerformance)
|
| 89 |
+
.sort(([,a], [,b]) => b.quantity - a.quantity)
|
| 90 |
+
.slice(0, 10)
|
| 91 |
+
.map(([id, data]) => ({ id, ...data }));
|
| 92 |
+
|
| 93 |
+
// Sales trend analysis using simple linear regression
|
| 94 |
+
const dates = Object.keys(dailySales).sort();
|
| 95 |
+
const salesValues = dates.map(date => dailySales[date]);
|
| 96 |
+
|
| 97 |
+
let salesTrend = { slope: 0, r2: 0, prediction: [] };
|
| 98 |
+
if (salesValues.length > 2) {
|
| 99 |
+
const regression = new SimpleLinearRegression(salesValues.map((_, i) => [i]), salesValues);
|
| 100 |
+
salesTrend = {
|
| 101 |
+
slope: regression.coefficients[0] || 0,
|
| 102 |
+
r2: regression.r2 || 0,
|
| 103 |
+
prediction: dates.map((_, i) => regression.predict([i]))
|
| 104 |
+
};
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
// Customer segmentation (basic clustering)
|
| 108 |
+
const customers = await Customer.find({ tenant: tenantId, ...branchFilter });
|
| 109 |
+
const customerSegments = performCustomerSegmentation(customers, customerBehavior);
|
| 110 |
+
|
| 111 |
+
const result = {
|
| 112 |
+
period: `${period} days`,
|
| 113 |
+
summary: {
|
| 114 |
+
totalRevenue: invoices.reduce((sum, inv) => sum + inv.totalAmount, 0),
|
| 115 |
+
totalInvoices: invoices.length,
|
| 116 |
+
totalCustomers: customers.length,
|
| 117 |
+
avgInvoiceValue: invoices.reduce((sum, inv) => sum + inv.totalAmount, 0) / invoices.length
|
| 118 |
+
},
|
| 119 |
+
popularProducts,
|
| 120 |
+
salesTrend,
|
| 121 |
+
customerSegments,
|
| 122 |
+
dailySales: Object.entries(dailySales).map(([date, sales]) => ({ date, sales })),
|
| 123 |
+
productPerformance: Object.entries(productPerformance).map(([id, data]) => ({ id, ...data }))
|
| 124 |
+
};
|
| 125 |
+
|
| 126 |
+
// Store in cache
|
| 127 |
+
aiCache.set('sales', tenantId, branchId, result, cacheKey);
|
| 128 |
+
|
| 129 |
+
res.json(result);
|
| 130 |
+
|
| 131 |
+
} catch (error) {
|
| 132 |
+
console.error('AI Analytics Error:', error);
|
| 133 |
+
res.status(500).json({ message: 'Failed to generate analytics' });
|
| 134 |
+
}
|
| 135 |
+
};
|
| 136 |
+
|
| 137 |
+
export const getInventoryAnalytics = async (req, res) => {
|
| 138 |
+
try {
|
| 139 |
+
const tenantId = req.user.tenant._id;
|
| 140 |
+
const { branchFilter } = await resolveScopedBranch(req);
|
| 141 |
+
|
| 142 |
+
const products = await Product.find({
|
| 143 |
+
tenant: tenantId,
|
| 144 |
+
...branchFilter
|
| 145 |
+
});
|
| 146 |
+
|
| 147 |
+
const inventoryAnalytics = {
|
| 148 |
+
totalProducts: products.length,
|
| 149 |
+
totalStockValue: products.reduce((sum, p) => sum + (p.stock * p.price), 0),
|
| 150 |
+
lowStockItems: products.filter(p => p.stock <= (p.lowStockThreshold || 5) && p.stock > 0).length,
|
| 151 |
+
outOfStockItems: products.filter(p => p.stock <= 0).length,
|
| 152 |
+
stockTurnover: calculateStockTurnover(products),
|
| 153 |
+
categoryDistribution: calculateCategoryDistribution(products)
|
| 154 |
+
};
|
| 155 |
+
|
| 156 |
+
// Predict stock depletion for critical items
|
| 157 |
+
const stockPredictions = predictStockDepletion(products);
|
| 158 |
+
|
| 159 |
+
res.json({
|
| 160 |
+
...inventoryAnalytics,
|
| 161 |
+
stockPredictions,
|
| 162 |
+
recommendations: generateInventoryRecommendations(products)
|
| 163 |
+
});
|
| 164 |
+
|
| 165 |
+
} catch (error) {
|
| 166 |
+
console.error('Inventory Analytics Error:', error);
|
| 167 |
+
res.status(500).json({ message: 'Failed to generate inventory analytics' });
|
| 168 |
+
}
|
| 169 |
+
};
|
| 170 |
+
|
| 171 |
+
export const getSupplierAnalytics = async (req, res) => {
|
| 172 |
+
try {
|
| 173 |
+
const tenantId = req.user.tenant._id;
|
| 174 |
+
const { branchFilter } = await resolveScopedBranch(req);
|
| 175 |
+
|
| 176 |
+
const suppliers = await Supplier.find({
|
| 177 |
+
tenant: tenantId,
|
| 178 |
+
...branchFilter
|
| 179 |
+
});
|
| 180 |
+
|
| 181 |
+
// Analyze supplier performance
|
| 182 |
+
const supplierPerformance = await analyzeSupplierPerformance(suppliers, tenantId, branchFilter);
|
| 183 |
+
|
| 184 |
+
res.json({
|
| 185 |
+
totalSuppliers: suppliers.length,
|
| 186 |
+
activeSuppliers: suppliers.filter(s => s.isActive).length,
|
| 187 |
+
supplierPerformance,
|
| 188 |
+
topSuppliers: supplierPerformance.sort((a, b) => b.totalValue - a.totalValue).slice(0, 10)
|
| 189 |
+
});
|
| 190 |
+
|
| 191 |
+
} catch (error) {
|
| 192 |
+
console.error('Supplier Analytics Error:', error);
|
| 193 |
+
res.status(500).json({ message: 'Failed to generate supplier analytics' });
|
| 194 |
+
}
|
| 195 |
+
};
|
| 196 |
+
|
| 197 |
+
export const getServiceAnalytics = async (req, res) => {
|
| 198 |
+
try {
|
| 199 |
+
const tenantId = req.user.tenant._id;
|
| 200 |
+
const { branchFilter } = await resolveScopedBranch(req);
|
| 201 |
+
|
| 202 |
+
const services = await Service.find({
|
| 203 |
+
tenant: tenantId,
|
| 204 |
+
...branchFilter
|
| 205 |
+
});
|
| 206 |
+
|
| 207 |
+
const serviceAnalytics = {
|
| 208 |
+
totalServices: services.length,
|
| 209 |
+
avgServicePrice: services.reduce((sum, s) => sum + s.price, 0) / services.length,
|
| 210 |
+
serviceCategories: categorizeServices(services),
|
| 211 |
+
revenueDistribution: calculateServiceRevenueDistribution(services, tenantId, branchFilter)
|
| 212 |
+
};
|
| 213 |
+
|
| 214 |
+
res.json(serviceAnalytics);
|
| 215 |
+
|
| 216 |
+
} catch (error) {
|
| 217 |
+
console.error('Service Analytics Error:', error);
|
| 218 |
+
res.status(500).json({ message: 'Failed to generate service analytics' });
|
| 219 |
+
}
|
| 220 |
+
};
|
| 221 |
+
|
| 222 |
+
export const getPredictiveInsights = async (req, res) => {
|
| 223 |
+
try {
|
| 224 |
+
const tenantId = req.user.tenant._id;
|
| 225 |
+
const { branchFilter } = await resolveScopedBranch(req);
|
| 226 |
+
const { period = '90' } = req.query;
|
| 227 |
+
|
| 228 |
+
// Get comprehensive data for predictions
|
| 229 |
+
const startDate = new Date();
|
| 230 |
+
startDate.setDate(startDate.getDate() - parseInt(period));
|
| 231 |
+
|
| 232 |
+
const invoices = await Invoice.find({
|
| 233 |
+
tenant: tenantId,
|
| 234 |
+
...branchFilter,
|
| 235 |
+
createdAt: { $gte: startDate }
|
| 236 |
+
});
|
| 237 |
+
|
| 238 |
+
// Generate predictions
|
| 239 |
+
const predictions = {
|
| 240 |
+
nextMonthRevenue: predictNextMonthRevenue(invoices),
|
| 241 |
+
popularProductsNextMonth: predictPopularProducts(invoices),
|
| 242 |
+
customerChurnRisk: predictCustomerChurn(invoices),
|
| 243 |
+
optimalStockLevels: predictOptimalStockLevels(invoices)
|
| 244 |
+
};
|
| 245 |
+
|
| 246 |
+
res.json(predictions);
|
| 247 |
+
|
| 248 |
+
} catch (error) {
|
| 249 |
+
console.error('Predictive Insights Error:', error);
|
| 250 |
+
res.status(500).json({ message: 'Failed to generate predictive insights' });
|
| 251 |
+
}
|
| 252 |
+
};
|
| 253 |
+
|
| 254 |
+
// Helper functions
|
| 255 |
+
function performCustomerSegmentation(customers, behavior) {
|
| 256 |
+
// Simple segmentation based on spending patterns
|
| 257 |
+
const segments = {
|
| 258 |
+
highValue: [],
|
| 259 |
+
regular: [],
|
| 260 |
+
occasional: [],
|
| 261 |
+
new: []
|
| 262 |
+
};
|
| 263 |
+
|
| 264 |
+
Object.entries(behavior).forEach(([customerId, data]) => {
|
| 265 |
+
if (data.totalSpent > 10000) {
|
| 266 |
+
segments.highValue.push({ customerId, ...data });
|
| 267 |
+
} else if (data.invoiceCount > 5) {
|
| 268 |
+
segments.regular.push({ customerId, ...data });
|
| 269 |
+
} else if (data.invoiceCount > 1) {
|
| 270 |
+
segments.occasional.push({ customerId, ...data });
|
| 271 |
+
} else {
|
| 272 |
+
segments.new.push({ customerId, ...data });
|
| 273 |
+
}
|
| 274 |
+
});
|
| 275 |
+
|
| 276 |
+
return segments;
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
function calculateStockTurnover(products) {
|
| 280 |
+
const totalValue = products.reduce((sum, p) => sum + (p.stock * p.price), 0);
|
| 281 |
+
const avgStockValue = totalValue / products.length;
|
| 282 |
+
return avgStockValue > 0 ? (totalValue / avgStockValue) : 0;
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
function calculateCategoryDistribution(products) {
|
| 286 |
+
const categories = {};
|
| 287 |
+
products.forEach(product => {
|
| 288 |
+
const category = product.category || 'Uncategorized';
|
| 289 |
+
categories[category] = (categories[category] || 0) + 1;
|
| 290 |
+
});
|
| 291 |
+
return categories;
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
function predictStockDepletion(products) {
|
| 295 |
+
return products
|
| 296 |
+
.filter(p => p.stock > 0 && p.stock <= (p.lowStockThreshold || 5) * 2)
|
| 297 |
+
.map(product => ({
|
| 298 |
+
id: product._id,
|
| 299 |
+
name: product.name,
|
| 300 |
+
currentStock: product.stock,
|
| 301 |
+
reorderPoint: product.lowStockThreshold || 5,
|
| 302 |
+
estimatedDaysUntilDepletion: Math.ceil(product.stock / Math.max(1, product.stock / 30)), // Simple estimation
|
| 303 |
+
urgency: product.stock <= (product.lowStockThreshold || 5) ? 'high' : 'medium'
|
| 304 |
+
}));
|
| 305 |
+
}
|
| 306 |
+
|
| 307 |
+
function generateInventoryRecommendations(products) {
|
| 308 |
+
const recommendations = [];
|
| 309 |
+
|
| 310 |
+
// Low stock recommendations
|
| 311 |
+
const lowStock = products.filter(p => p.stock <= (p.lowStockThreshold || 5));
|
| 312 |
+
if (lowStock.length > 0) {
|
| 313 |
+
recommendations.push({
|
| 314 |
+
type: 'restock',
|
| 315 |
+
priority: 'high',
|
| 316 |
+
message: `${lowStock.length} products need immediate restocking`,
|
| 317 |
+
items: lowStock.slice(0, 5).map(p => ({ id: p._id, name: p.name, stock: p.stock }))
|
| 318 |
+
});
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
// Overstock recommendations
|
| 322 |
+
const overstock = products.filter(p => p.stock > (p.lowStockThreshold || 5) * 5);
|
| 323 |
+
if (overstock.length > 0) {
|
| 324 |
+
recommendations.push({
|
| 325 |
+
type: 'promotion',
|
| 326 |
+
priority: 'medium',
|
| 327 |
+
message: `${overstock.length} products have excess inventory`,
|
| 328 |
+
items: overstock.slice(0, 5).map(p => ({ id: p._id, name: p.name, stock: p.stock }))
|
| 329 |
+
});
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
return recommendations;
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
async function analyzeSupplierPerformance(suppliers, tenantId, branchFilter) {
|
| 336 |
+
// This would analyze supplier invoices, delivery times, quality metrics
|
| 337 |
+
// For now, returning basic performance metrics
|
| 338 |
+
return suppliers.map(supplier => ({
|
| 339 |
+
id: supplier._id,
|
| 340 |
+
name: supplier.name,
|
| 341 |
+
totalValue: 0, // Would calculate from supplier invoices
|
| 342 |
+
orderCount: 0, // Would count supplier orders
|
| 343 |
+
avgDeliveryTime: 0, // Would calculate from order history
|
| 344 |
+
qualityScore: 4.5 // Would calculate from quality metrics
|
| 345 |
+
}));
|
| 346 |
+
}
|
| 347 |
+
|
| 348 |
+
function categorizeServices(services) {
|
| 349 |
+
const categories = {};
|
| 350 |
+
services.forEach(service => {
|
| 351 |
+
const category = service.category || 'General';
|
| 352 |
+
categories[category] = (categories[category] || 0) + 1;
|
| 353 |
+
});
|
| 354 |
+
return categories;
|
| 355 |
+
}
|
| 356 |
+
|
| 357 |
+
async function calculateServiceRevenueDistribution(services, tenantId, branchFilter) {
|
| 358 |
+
// Calculate revenue distribution by service type
|
| 359 |
+
const distribution = {};
|
| 360 |
+
|
| 361 |
+
// Get invoices with service items
|
| 362 |
+
const invoices = await Invoice.find({
|
| 363 |
+
tenant: tenantId,
|
| 364 |
+
...branchFilter,
|
| 365 |
+
'items.type': 'service'
|
| 366 |
+
});
|
| 367 |
+
|
| 368 |
+
invoices.forEach(invoice => {
|
| 369 |
+
invoice.items.forEach(item => {
|
| 370 |
+
if (item.type === 'service') {
|
| 371 |
+
const serviceType = item.name || 'Unknown';
|
| 372 |
+
distribution[serviceType] = (distribution[serviceType] || 0) + item.total;
|
| 373 |
+
}
|
| 374 |
+
});
|
| 375 |
+
});
|
| 376 |
+
|
| 377 |
+
return distribution;
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
function predictNextMonthRevenue(invoices) {
|
| 381 |
+
if (invoices.length < 2) return { prediction: 0, confidence: 0 };
|
| 382 |
+
|
| 383 |
+
// Simple linear regression on monthly revenue
|
| 384 |
+
const monthlyData = {};
|
| 385 |
+
invoices.forEach(invoice => {
|
| 386 |
+
const month = invoice.createdAt.toISOString().substring(0, 7);
|
| 387 |
+
monthlyData[month] = (monthlyData[month] || 0) + invoice.totalAmount;
|
| 388 |
+
});
|
| 389 |
+
|
| 390 |
+
const months = Object.keys(monthlyData).sort();
|
| 391 |
+
const revenues = months.map(month => monthlyData[month]);
|
| 392 |
+
|
| 393 |
+
if (revenues.length < 2) return { prediction: revenues[0] || 0, confidence: 0.5 };
|
| 394 |
+
|
| 395 |
+
const regression = new SimpleLinearRegression(revenues.map((_, i) => [i]), revenues);
|
| 396 |
+
const nextMonthPrediction = regression.predict([revenues.length]);
|
| 397 |
+
|
| 398 |
+
return {
|
| 399 |
+
prediction: Math.max(0, nextMonthPrediction),
|
| 400 |
+
confidence: Math.min(0.9, Math.max(0.1, regression.r2 || 0.5)),
|
| 401 |
+
trend: regression.coefficients[0] > 0 ? 'increasing' : 'decreasing'
|
| 402 |
+
};
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
function predictPopularProducts(invoices) {
|
| 406 |
+
const productFrequency = {};
|
| 407 |
+
|
| 408 |
+
invoices.forEach(invoice => {
|
| 409 |
+
invoice.items.forEach(item => {
|
| 410 |
+
const rawId = item.productId?._id || item.productId;
|
| 411 |
+
if (rawId) {
|
| 412 |
+
const productId = rawId.toString();
|
| 413 |
+
if (!productFrequency[productId]) {
|
| 414 |
+
productFrequency[productId] = {
|
| 415 |
+
name: item.name,
|
| 416 |
+
count: 0,
|
| 417 |
+
quantity: 0,
|
| 418 |
+
revenue: 0
|
| 419 |
+
};
|
| 420 |
+
}
|
| 421 |
+
productFrequency[productId].count += 1;
|
| 422 |
+
productFrequency[productId].quantity += Number(item.quantity || 1);
|
| 423 |
+
productFrequency[productId].revenue += Number(item.total || 0);
|
| 424 |
+
}
|
| 425 |
+
});
|
| 426 |
+
});
|
| 427 |
+
|
| 428 |
+
return Object.entries(productFrequency)
|
| 429 |
+
.sort(([,a], [,b]) => b.count - a.count)
|
| 430 |
+
.slice(0, 10)
|
| 431 |
+
.map(([id, data]) => ({ productId: id, ...data }));
|
| 432 |
+
}
|
| 433 |
+
|
| 434 |
+
function predictCustomerChurn(invoices) {
|
| 435 |
+
const customerActivity = {};
|
| 436 |
+
|
| 437 |
+
invoices.forEach(invoice => {
|
| 438 |
+
const customerId = invoice.customer.toString();
|
| 439 |
+
if (!customerActivity[customerId]) {
|
| 440 |
+
customerActivity[customerId] = {
|
| 441 |
+
lastPurchase: invoice.createdAt,
|
| 442 |
+
purchaseCount: 0,
|
| 443 |
+
totalSpent: 0
|
| 444 |
+
};
|
| 445 |
+
}
|
| 446 |
+
|
| 447 |
+
const activity = customerActivity[customerId];
|
| 448 |
+
if (invoice.createdAt > activity.lastPurchase) {
|
| 449 |
+
activity.lastPurchase = invoice.createdAt;
|
| 450 |
+
}
|
| 451 |
+
activity.purchaseCount += 1;
|
| 452 |
+
activity.totalSpent += invoice.totalAmount;
|
| 453 |
+
});
|
| 454 |
+
|
| 455 |
+
// Identify at-risk customers (no purchase in last 30 days)
|
| 456 |
+
const thirtyDaysAgo = new Date();
|
| 457 |
+
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
|
| 458 |
+
|
| 459 |
+
const atRiskCustomers = Object.entries(customerActivity)
|
| 460 |
+
.filter(([_, activity]) => activity.lastPurchase < thirtyDaysAgo)
|
| 461 |
+
.map(([customerId, activity]) => ({
|
| 462 |
+
customerId,
|
| 463 |
+
lastPurchase: activity.lastPurchase,
|
| 464 |
+
daysSinceLastPurchase: Math.floor((thirtyDaysAgo - activity.lastPurchase) / (1000 * 60 * 60 * 24)),
|
| 465 |
+
riskLevel: activity.daysSinceLastPurchase > 60 ? 'high' : 'medium'
|
| 466 |
+
}));
|
| 467 |
+
|
| 468 |
+
return atRiskCustomers;
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
function predictOptimalStockLevels(invoices) {
|
| 472 |
+
const productDemand = {};
|
| 473 |
+
|
| 474 |
+
invoices.forEach(invoice => {
|
| 475 |
+
invoice.items.forEach(item => {
|
| 476 |
+
if (item.productId) {
|
| 477 |
+
const productId = item.productId.toString();
|
| 478 |
+
if (!productDemand[productId]) {
|
| 479 |
+
productDemand[productId] = {
|
| 480 |
+
name: item.name,
|
| 481 |
+
monthlyDemand: [],
|
| 482 |
+
totalQuantity: 0
|
| 483 |
+
};
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
const month = invoice.createdAt.toISOString().substring(0, 7);
|
| 487 |
+
if (!productDemand[productId].monthlyDemand[month]) {
|
| 488 |
+
productDemand[productId].monthlyDemand[month] = 0;
|
| 489 |
+
}
|
| 490 |
+
productDemand[productId].monthlyDemand[month] += item.quantity;
|
| 491 |
+
productDemand[productId].totalQuantity += item.quantity;
|
| 492 |
+
}
|
| 493 |
+
});
|
| 494 |
+
});
|
| 495 |
+
|
| 496 |
+
return Object.entries(productDemand).map(([productId, data]) => {
|
| 497 |
+
const demandValues = Object.values(data.monthlyDemand);
|
| 498 |
+
const avgMonthlyDemand = demandValues.length > 0
|
| 499 |
+
? demandValues.reduce((sum, val) => sum + val, 0) / demandValues.length
|
| 500 |
+
: 0;
|
| 501 |
+
|
| 502 |
+
return {
|
| 503 |
+
productId,
|
| 504 |
+
name: data.name,
|
| 505 |
+
currentMonthlyDemand: avgMonthlyDemand,
|
| 506 |
+
recommendedStock: Math.ceil(avgMonthlyDemand * 1.5), // 1.5 months buffer
|
| 507 |
+
reorderPoint: Math.ceil(avgMonthlyDemand * 0.5) // 2 weeks buffer
|
| 508 |
+
};
|
| 509 |
+
});
|
| 510 |
+
}
|