Spaces:
Sleeping
Sleeping
Download controller/aiAnalyticsController.js from Mahmoud7456/MultiUsersSalesSystem: direct link, hf CLI and curl.
- Browser
- Download file 18 kB
-
https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/controller/aiAnalyticsController.js
- Command line
-
hf download hf://spaces/Mahmoud7456/MultiUsersSalesSystem/controller/aiAnalyticsController.js
-
curl -L -o aiAnalyticsController.js https://huggingface.co/spaces/Mahmoud7456/MultiUsersSalesSystem/resolve/main/controller/aiAnalyticsController.js
18 kB
| import pkg from 'ml.js'; | |
| const { MLRegression, MLClassification, MLClustering } = pkg; | |
| import Invoice from '../models/InvoiceModel.js'; | |
| import Product from '../models/ProductModel.js'; | |
| import Service from '../models/ServiceModel.js'; | |
| import CatalogItem from '../models/CatalogItemModel.js'; | |
| import Supplier from '../models/SupplierModel.js'; | |
| import Customer from '../models/CustomerModel.js'; | |
| import { resolveScopedBranch } from '../utils/branchContext.js'; | |
| import aiCache from '../utils/aiCache.js'; | |
| // AI Analytics Controller | |
| export const getSalesAnalytics = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { period = '30' } = req.query; // days | |
| // Check cache first | |
| const branchId = branchFilter.branch?._id || 'all'; | |
| const cacheKey = { period }; | |
| const cachedData = aiCache.get('sales', tenantId, branchId, cacheKey); | |
| if (cachedData) { | |
| return res.json(cachedData); | |
| } | |
| // Get historical sales data | |
| const startDate = new Date(); | |
| startDate.setDate(startDate.getDate() - parseInt(period)); | |
| const invoices = await Invoice.find({ | |
| tenant: tenantId, | |
| ...branchFilter, | |
| createdAt: { $gte: startDate } | |
| }).populate('customer items.productId'); | |
| // Process data for ML analysis | |
| const salesData = []; | |
| const productPerformance = {}; | |
| const customerBehavior = {}; | |
| const dailySales = {}; | |
| invoices.forEach(invoice => { | |
| const date = invoice.createdAt.toISOString().split('T')[0]; | |
| dailySales[date] = (dailySales[date] || 0) + invoice.totalAmount; | |
| invoice.items.forEach(item => { | |
| const productId = item.productId?._id || item.productId; | |
| if (productId) { | |
| if (!productPerformance[productId]) { | |
| productPerformance[productId] = { | |
| name: item.name, | |
| totalSales: 0, | |
| quantity: 0, | |
| revenue: 0, | |
| frequency: 0 | |
| }; | |
| } | |
| productPerformance[productId].totalSales += item.total; | |
| productPerformance[productId].quantity += item.quantity; | |
| productPerformance[productId].revenue += item.total; | |
| productPerformance[productId].frequency += 1; | |
| } | |
| }); | |
| // Customer behavior analysis | |
| const customerId = invoice.customer._id; | |
| if (!customerBehavior[customerId]) { | |
| customerBehavior[customerId] = { | |
| totalSpent: 0, | |
| invoiceCount: 0, | |
| avgInvoiceValue: 0 | |
| }; | |
| } | |
| customerBehavior[customerId].totalSpent += invoice.totalAmount; | |
| customerBehavior[customerId].invoiceCount += 1; | |
| }); | |
| // Calculate average invoice value | |
| Object.keys(customerBehavior).forEach(customerId => { | |
| const behavior = customerBehavior[customerId]; | |
| behavior.avgInvoiceValue = behavior.totalSpent / behavior.invoiceCount; | |
| }); | |
| // Popular products identification | |
| const popularProducts = Object.entries(productPerformance) | |
| .sort(([,a], [,b]) => b.quantity - a.quantity) | |
| .slice(0, 10) | |
| .map(([id, data]) => ({ id, ...data })); | |
| // Sales trend analysis using simple linear regression | |
| const dates = Object.keys(dailySales).sort(); | |
| const salesValues = dates.map(date => dailySales[date]); | |
| let salesTrend = { slope: 0, r2: 0, prediction: [] }; | |
| if (salesValues.length > 2) { | |
| const regression = new MLRegression(salesValues.map((_, i) => [i]), salesValues); | |
| salesTrend = { | |
| slope: regression.coefficients[0] || 0, | |
| r2: regression.r2 || 0, | |
| prediction: dates.map((_, i) => regression.predict([i])) | |
| }; | |
| } | |
| // Customer segmentation (basic clustering) | |
| const customers = await Customer.find({ tenant: tenantId, ...branchFilter }); | |
| const customerSegments = performCustomerSegmentation(customers, customerBehavior); | |
| const result = { | |
| period: `${period} days`, | |
| summary: { | |
| totalRevenue: invoices.reduce((sum, inv) => sum + inv.totalAmount, 0), | |
| totalInvoices: invoices.length, | |
| totalCustomers: customers.length, | |
| avgInvoiceValue: invoices.reduce((sum, inv) => sum + inv.totalAmount, 0) / invoices.length | |
| }, | |
| popularProducts, | |
| salesTrend, | |
| customerSegments, | |
| dailySales: Object.entries(dailySales).map(([date, sales]) => ({ date, sales })), | |
| productPerformance: Object.entries(productPerformance).map(([id, data]) => ({ id, ...data })) | |
| }; | |
| // Store in cache | |
| aiCache.set('sales', tenantId, branchId, result, cacheKey); | |
| res.json(result); | |
| } catch (error) { | |
| console.error('AI Analytics Error:', error); | |
| res.status(500).json({ message: 'Failed to generate analytics' }); | |
| } | |
| }; | |
| export const getInventoryAnalytics = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const products = await Product.find({ | |
| tenant: tenantId, | |
| ...branchFilter | |
| }); | |
| const inventoryAnalytics = { | |
| totalProducts: products.length, | |
| totalStockValue: products.reduce((sum, p) => sum + (p.stock * p.price), 0), | |
| lowStockItems: products.filter(p => p.stock <= p.reorderPoint || 0).length, | |
| outOfStockItems: products.filter(p => p.stock === 0).length, | |
| stockTurnover: calculateStockTurnover(products), | |
| categoryDistribution: calculateCategoryDistribution(products) | |
| }; | |
| // Predict stock depletion for critical items | |
| const stockPredictions = predictStockDepletion(products); | |
| res.json({ | |
| ...inventoryAnalytics, | |
| stockPredictions, | |
| recommendations: generateInventoryRecommendations(products) | |
| }); | |
| } catch (error) { | |
| console.error('Inventory Analytics Error:', error); | |
| res.status(500).json({ message: 'Failed to generate inventory analytics' }); | |
| } | |
| }; | |
| export const getSupplierAnalytics = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const suppliers = await Supplier.find({ | |
| tenant: tenantId, | |
| ...branchFilter | |
| }); | |
| // Analyze supplier performance | |
| const supplierPerformance = await analyzeSupplierPerformance(suppliers, tenantId, branchFilter); | |
| res.json({ | |
| totalSuppliers: suppliers.length, | |
| activeSuppliers: suppliers.filter(s => s.isActive).length, | |
| supplierPerformance, | |
| topSuppliers: supplierPerformance.sort((a, b) => b.totalValue - a.totalValue).slice(0, 10) | |
| }); | |
| } catch (error) { | |
| console.error('Supplier Analytics Error:', error); | |
| res.status(500).json({ message: 'Failed to generate supplier analytics' }); | |
| } | |
| }; | |
| export const getServiceAnalytics = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const services = await Service.find({ | |
| tenant: tenantId, | |
| ...branchFilter | |
| }); | |
| const serviceAnalytics = { | |
| totalServices: services.length, | |
| avgServicePrice: services.reduce((sum, s) => sum + s.price, 0) / services.length, | |
| serviceCategories: categorizeServices(services), | |
| revenueDistribution: calculateServiceRevenueDistribution(services, tenantId, branchFilter) | |
| }; | |
| res.json(serviceAnalytics); | |
| } catch (error) { | |
| console.error('Service Analytics Error:', error); | |
| res.status(500).json({ message: 'Failed to generate service analytics' }); | |
| } | |
| }; | |
| export const getPredictiveInsights = async (req, res) => { | |
| try { | |
| const tenantId = req.user.tenant._id; | |
| const { branchFilter } = await resolveScopedBranch(req); | |
| const { period = '90' } = req.query; | |
| // Get comprehensive data for predictions | |
| const startDate = new Date(); | |
| startDate.setDate(startDate.getDate() - parseInt(period)); | |
| const invoices = await Invoice.find({ | |
| tenant: tenantId, | |
| ...branchFilter, | |
| createdAt: { $gte: startDate } | |
| }); | |
| // Generate predictions | |
| const predictions = { | |
| nextMonthRevenue: predictNextMonthRevenue(invoices), | |
| popularProductsNextMonth: predictPopularProducts(invoices), | |
| customerChurnRisk: predictCustomerChurn(invoices), | |
| optimalStockLevels: predictOptimalStockLevels(invoices) | |
| }; | |
| res.json(predictions); | |
| } catch (error) { | |
| console.error('Predictive Insights Error:', error); | |
| res.status(500).json({ message: 'Failed to generate predictive insights' }); | |
| } | |
| }; | |
| // Helper functions | |
| function performCustomerSegmentation(customers, behavior) { | |
| // Simple segmentation based on spending patterns | |
| const segments = { | |
| highValue: [], | |
| regular: [], | |
| occasional: [], | |
| new: [] | |
| }; | |
| Object.entries(behavior).forEach(([customerId, data]) => { | |
| if (data.totalSpent > 10000) { | |
| segments.highValue.push({ customerId, ...data }); | |
| } else if (data.invoiceCount > 5) { | |
| segments.regular.push({ customerId, ...data }); | |
| } else if (data.invoiceCount > 1) { | |
| segments.occasional.push({ customerId, ...data }); | |
| } else { | |
| segments.new.push({ customerId, ...data }); | |
| } | |
| }); | |
| return segments; | |
| } | |
| function calculateStockTurnover(products) { | |
| const totalValue = products.reduce((sum, p) => sum + (p.stock * p.price), 0); | |
| const avgStockValue = totalValue / products.length; | |
| return avgStockValue > 0 ? (totalValue / avgStockValue) : 0; | |
| } | |
| function calculateCategoryDistribution(products) { | |
| const categories = {}; | |
| products.forEach(product => { | |
| const category = product.category || 'Uncategorized'; | |
| categories[category] = (categories[category] || 0) + 1; | |
| }); | |
| return categories; | |
| } | |
| function predictStockDepletion(products) { | |
| return products | |
| .filter(p => p.stock > 0 && p.stock <= p.reorderPoint * 2) | |
| .map(product => ({ | |
| id: product._id, | |
| name: product.name, | |
| currentStock: product.stock, | |
| reorderPoint: product.reorderPoint, | |
| estimatedDaysUntilDepletion: Math.ceil(product.stock / Math.max(1, product.stock / 30)), // Simple estimation | |
| urgency: product.stock <= product.reorderPoint ? 'high' : 'medium' | |
| })); | |
| } | |
| function generateInventoryRecommendations(products) { | |
| const recommendations = []; | |
| // Low stock recommendations | |
| const lowStock = products.filter(p => p.stock <= p.reorderPoint); | |
| if (lowStock.length > 0) { | |
| recommendations.push({ | |
| type: 'restock', | |
| priority: 'high', | |
| message: `${lowStock.length} products need immediate restocking`, | |
| items: lowStock.slice(0, 5).map(p => ({ id: p._id, name: p.name, stock: p.stock })) | |
| }); | |
| } | |
| // Overstock recommendations | |
| const overstock = products.filter(p => p.stock > p.reorderPoint * 5); | |
| if (overstock.length > 0) { | |
| recommendations.push({ | |
| type: 'promotion', | |
| priority: 'medium', | |
| message: `${overstock.length} products have excess inventory`, | |
| items: overstock.slice(0, 5).map(p => ({ id: p._id, name: p.name, stock: p.stock })) | |
| }); | |
| } | |
| return recommendations; | |
| } | |
| async function analyzeSupplierPerformance(suppliers, tenantId, branchFilter) { | |
| // This would analyze supplier invoices, delivery times, quality metrics | |
| // For now, returning basic performance metrics | |
| return suppliers.map(supplier => ({ | |
| id: supplier._id, | |
| name: supplier.name, | |
| totalValue: 0, // Would calculate from supplier invoices | |
| orderCount: 0, // Would count supplier orders | |
| avgDeliveryTime: 0, // Would calculate from order history | |
| qualityScore: 4.5 // Would calculate from quality metrics | |
| })); | |
| } | |
| function categorizeServices(services) { | |
| const categories = {}; | |
| services.forEach(service => { | |
| const category = service.category || 'General'; | |
| categories[category] = (categories[category] || 0) + 1; | |
| }); | |
| return categories; | |
| } | |
| async function calculateServiceRevenueDistribution(services, tenantId, branchFilter) { | |
| // Calculate revenue distribution by service type | |
| const distribution = {}; | |
| // Get invoices with service items | |
| const invoices = await Invoice.find({ | |
| tenant: tenantId, | |
| ...branchFilter, | |
| 'items.type': 'service' | |
| }); | |
| invoices.forEach(invoice => { | |
| invoice.items.forEach(item => { | |
| if (item.type === 'service') { | |
| const serviceType = item.name || 'Unknown'; | |
| distribution[serviceType] = (distribution[serviceType] || 0) + item.total; | |
| } | |
| }); | |
| }); | |
| return distribution; | |
| } | |
| function predictNextMonthRevenue(invoices) { | |
| if (invoices.length < 2) return { prediction: 0, confidence: 0 }; | |
| // Simple linear regression on monthly revenue | |
| const monthlyData = {}; | |
| invoices.forEach(invoice => { | |
| const month = invoice.createdAt.toISOString().substring(0, 7); | |
| monthlyData[month] = (monthlyData[month] || 0) + invoice.totalAmount; | |
| }); | |
| const months = Object.keys(monthlyData).sort(); | |
| const revenues = months.map(month => monthlyData[month]); | |
| if (revenues.length < 2) return { prediction: revenues[0] || 0, confidence: 0.5 }; | |
| const regression = new MLRegression(revenues.map((_, i) => [i]), revenues); | |
| const nextMonthPrediction = regression.predict([revenues.length]); | |
| return { | |
| prediction: Math.max(0, nextMonthPrediction), | |
| confidence: Math.min(0.9, Math.max(0.1, regression.r2 || 0.5)), | |
| trend: regression.coefficients[0] > 0 ? 'increasing' : 'decreasing' | |
| }; | |
| } | |
| function predictPopularProducts(invoices) { | |
| const productFrequency = {}; | |
| invoices.forEach(invoice => { | |
| invoice.items.forEach(item => { | |
| if (item.productId) { | |
| const productId = item.productId.toString(); | |
| productFrequency[productId] = { | |
| name: item.name, | |
| count: (productFrequency[productId]?.count || 0) + 1, | |
| quantity: (productFrequency[productId]?.quantity || 0) + item.quantity, | |
| revenue: (productFrequency[productId]?.revenue || 0) + item.total | |
| }; | |
| } | |
| }); | |
| }); | |
| return Object.entries(productFrequency) | |
| .sort(([,a], [,b]) => b.count - a.count) | |
| .slice(0, 10) | |
| .map(([id, data]) => ({ productId: id, ...data })); | |
| } | |
| function predictCustomerChurn(invoices) { | |
| const customerActivity = {}; | |
| invoices.forEach(invoice => { | |
| const customerId = invoice.customer.toString(); | |
| if (!customerActivity[customerId]) { | |
| customerActivity[customerId] = { | |
| lastPurchase: invoice.createdAt, | |
| purchaseCount: 0, | |
| totalSpent: 0 | |
| }; | |
| } | |
| const activity = customerActivity[customerId]; | |
| if (invoice.createdAt > activity.lastPurchase) { | |
| activity.lastPurchase = invoice.createdAt; | |
| } | |
| activity.purchaseCount += 1; | |
| activity.totalSpent += invoice.totalAmount; | |
| }); | |
| // Identify at-risk customers (no purchase in last 30 days) | |
| const thirtyDaysAgo = new Date(); | |
| thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30); | |
| const atRiskCustomers = Object.entries(customerActivity) | |
| .filter(([_, activity]) => activity.lastPurchase < thirtyDaysAgo) | |
| .map(([customerId, activity]) => ({ | |
| customerId, | |
| lastPurchase: activity.lastPurchase, | |
| daysSinceLastPurchase: Math.floor((thirtyDaysAgo - activity.lastPurchase) / (1000 * 60 * 60 * 24)), | |
| riskLevel: activity.daysSinceLastPurchase > 60 ? 'high' : 'medium' | |
| })); | |
| return atRiskCustomers; | |
| } | |
| function predictOptimalStockLevels(invoices) { | |
| const productDemand = {}; | |
| invoices.forEach(invoice => { | |
| invoice.items.forEach(item => { | |
| if (item.productId) { | |
| const productId = item.productId.toString(); | |
| if (!productDemand[productId]) { | |
| productDemand[productId] = { | |
| name: item.name, | |
| monthlyDemand: [], | |
| totalQuantity: 0 | |
| }; | |
| } | |
| const month = invoice.createdAt.toISOString().substring(0, 7); | |
| if (!productDemand[productId].monthlyDemand[month]) { | |
| productDemand[productId].monthlyDemand[month] = 0; | |
| } | |
| productDemand[productId].monthlyDemand[month] += item.quantity; | |
| productDemand[productId].totalQuantity += item.quantity; | |
| } | |
| }); | |
| }); | |
| return Object.entries(productDemand).map(([productId, data]) => { | |
| const demandValues = Object.values(data.monthlyDemand); | |
| const avgMonthlyDemand = demandValues.length > 0 | |
| ? demandValues.reduce((sum, val) => sum + val, 0) / demandValues.length | |
| : 0; | |
| return { | |
| productId, | |
| name: data.name, | |
| currentMonthlyDemand: avgMonthlyDemand, | |
| recommendedStock: Math.ceil(avgMonthlyDemand * 1.5), // 1.5 months buffer | |
| reorderPoint: Math.ceil(avgMonthlyDemand * 0.5) // 2 weeks buffer | |
| }; | |
| }); | |
| } | |