import bcrypt from 'bcryptjs'; import User from '../models/UserModel.js'; import Tenant from '../models/TenantModel.js'; import Invoice from '../models/InvoiceModel.js'; import Customer from '../models/CustomerModel.js'; import Product from '../models/ProductModel.js'; import pkg from 'ml.js'; const { MLRegression, MLClustering } = pkg; // Reset tenant user password export const resetTenantPassword = async (req, res) => { try { const { tenantId, userId } = req.params; const { newPassword, notifyUser } = req.body; // Validate super admin access if (req.user.role !== 'super_admin') { return res.status(403).json({ message: 'Access denied. Super admin required.' }); } // Find the user and verify they belong to the tenant const user = await User.findOne({ _id: userId, tenant: tenantId }); if (!user) { return res.status(404).json({ message: 'User not found' }); } // Validate new password if (!newPassword || newPassword.length < 6) { return res.status(400).json({ message: 'Password must be at least 6 characters long' }); } // Hash the new password const hashedPassword = await bcrypt.hash(newPassword, 12); // Update user password await User.findByIdAndUpdate(userId, { password: hashedPassword, passwordResetAt: new Date(), passwordResetBy: req.user._id }); // Log the password reset action console.log(`Password reset for user ${user.username} (tenant: ${tenantId}) by super admin ${req.user.username}`); res.status(200).json({ message: 'Password reset successfully', user: { id: user._id, username: user.username, fullName: user.fullName, role: user.role } }); } catch (error) { console.error('Password reset error:', error); res.status(500).json({ message: 'Failed to reset password' }); } }; // Get comprehensive tenant analytics for Super Admin export const getTenantAnalytics = async (req, res) => { try { // Validate super admin access if (req.user.role !== 'super_admin') { return res.status(403).json({ message: 'Access denied. Super admin required.' }); } const { period = '30', tenantId } = req.query; const daysAgo = new Date(); daysAgo.setDate(daysAgo.getDate() - parseInt(period)); // Get all tenants with their statistics const tenants = await Tenant.aggregate([ { $lookup: { from: 'users', localField: '_id', foreignField: 'tenant', as: 'users' } }, { $lookup: { from: 'invoices', localField: '_id', foreignField: 'tenant', as: 'invoices' } }, { $lookup: { from: 'customers', localField: '_id', foreignField: 'tenant', as: 'customers' } }, { $lookup: { from: 'products', localField: '_id', foreignField: 'tenant', as: 'products' } } ]); // Calculate analytics for each tenant const tenantAnalytics = tenants.map(tenant => { const activeUsers = tenant.users.filter(user => user.isActive).length; const totalUsers = tenant.users.length; const recentInvoices = tenant.invoices.filter(inv => new Date(inv.createdAt) >= daysAgo ); const recentCustomers = tenant.customers.filter(customer => new Date(customer.createdAt) >= daysAgo ); // Calculate growth metrics const previousPeriodStart = new Date(daysAgo); previousPeriodStart.setDate(previousPeriodStart.getDate() - parseInt(period)); const previousInvoices = tenant.invoices.filter(inv => new Date(inv.createdAt) >= previousPeriodStart && new Date(inv.createdAt) < daysAgo ); const currentRevenue = recentInvoices.reduce((sum, inv) => sum + (inv.totalAmount || 0), 0); const previousRevenue = previousInvoices.reduce((sum, inv) => sum + (inv.totalAmount || 0), 0); const revenueGrowth = previousRevenue > 0 ? ((currentRevenue - previousRevenue) / previousRevenue) * 100 : 0; // Calculate feature adoption const featuresUsed = { invoices: recentInvoices.length > 0, customers: recentCustomers.length > 0, products: tenant.products.length > 0, multipleUsers: totalUsers > 1 }; const adoptionScore = Object.values(featuresUsed).filter(Boolean).length / Object.keys(featuresUsed).length * 100; return { tenantId: tenant._id, tenantName: tenant.name, tenantSlug: tenant.slug, status: tenant.status, subscriptionPackage: tenant.subscriptionPackage, metrics: { totalUsers, activeUsers, totalCustomers: tenant.customers.length, newCustomers: recentCustomers.length, totalProducts: tenant.products.length, totalInvoices: tenant.invoices.length, recentInvoices: recentInvoices.length, currentRevenue, previousRevenue, revenueGrowth: Math.round(revenueGrowth * 100) / 100, adoptionScore: Math.round(adoptionScore), featuresUsed }, createdAt: tenant.createdAt }; }); // Aggregate global analytics const globalMetrics = { totalTenants: tenants.length, activeTenants: tenants.filter(t => t.status === 'active').length, totalUsers: tenants.reduce((sum, t) => sum + t.users.length, 0), totalCustomers: tenants.reduce((sum, t) => sum + t.customers.length, 0), totalProducts: tenants.reduce((sum, t) => sum + t.products.length, 0), totalInvoices: tenants.reduce((sum, t) => sum + t.invoices.length, 0), totalRevenue: tenants.reduce((sum, t) => sum + t.invoices.reduce((invSum, inv) => invSum + (inv.totalAmount || 0), 0), 0) }; // AI-powered insights and recommendations const insights = await generateAIInsights(tenantAnalytics, globalMetrics); res.status(200).json({ period: `${period} days`, globalMetrics, tenantAnalytics, insights, generatedAt: new Date() }); } catch (error) { console.error('Tenant analytics error:', error); res.status(500).json({ message: 'Failed to generate tenant analytics' }); } }; // Generate AI-powered insights and recommendations const generateAIInsights = async (tenantAnalytics, globalMetrics) => { const insights = { performance: [], growth: [], recommendations: [], alerts: [] }; // Performance insights const highPerformers = tenantAnalytics .filter(t => t.metrics.revenueGrowth > 20) .sort((a, b) => b.metrics.revenueGrowth - a.metrics.revenueGrowth) .slice(0, 5); if (highPerformers.length > 0) { insights.performance.push({ type: 'top_performers', title: 'أفضل الأداء', description: 'العملاء الذين حققوا أعلى نمو في الإيرادات', data: highPerformers.map(t => ({ tenantName: t.tenantName, growth: t.metrics.revenueGrowth, revenue: t.metrics.currentRevenue })) }); } // Growth insights const averageGrowth = tenantAnalytics.reduce((sum, t) => sum + t.metrics.revenueGrowth, 0) / tenantAnalytics.length; if (averageGrowth > 0) { insights.growth.push({ type: 'positive_growth', title: 'نمو إيجابي', description: `متوسط نمو الإيرادات: ${averageGrowth.toFixed(1)}%`, level: averageGrowth > 10 ? 'high' : averageGrowth > 5 ? 'medium' : 'low' }); } // Feature adoption insights const averageAdoption = tenantAnalytics.reduce((sum, t) => sum + t.metrics.adoptionScore, 0) / tenantAnalytics.length; if (averageAdoption < 60) { insights.recommendations.push({ type: 'feature_adoption', title: 'تحسين تبني الميزات', description: 'بعض العملاء لا يستخدمون جميع الميزات المتاحة', priority: 'medium', action: 'إرسال دليل استخدام الميزات للعملاء' }); } // Low usage alerts const lowUsageTenants = tenantAnalytics.filter(t => t.metrics.recentInvoices === 0 && t.status === 'active' ); if (lowUsageTenants.length > 0) { insights.alerts.push({ type: 'low_usage', title: 'انخفاض الاستخدام', description: `${lowUsageTenants.length} عملاء نشطين لم يقوموا بأي فواتير مؤخراً`, priority: 'high', data: lowUsageTenants.map(t => t.tenantName) }); } // Package upgrade recommendations const nearLimitTenants = tenantAnalytics.filter(t => { const packageKey = t.subscriptionPackage?.key || 'basic'; const limit = t.subscriptionPackage?.cashierLimit || 1; const usage = t.metrics.activeUsers; return usage >= limit * 0.8; }); if (nearLimitTenants.length > 0) { insights.recommendations.push({ type: 'package_upgrade', title: 'ترقية الباقة', description: `${nearLimitTenants.length} عملاء يقتربون من حدود باقتهم`, priority: 'medium', action: 'اقتراح ترقية الباقة لهؤلاء العملاء' }); } // System optimization suggestions if (globalMetrics.totalTenants > 50) { insights.recommendations.push({ type: 'system_optimization', title: 'تحسين النظام', description: 'عدد كبير من العملاء قد يتطلب تحسينات في الأداء', priority: 'low', action: 'مراجعة تحسينات قاعدة البيانات وذاكرة التخزين المؤقت' }); } // New feature suggestions based on usage patterns const invoiceFrequency = tenantAnalytics.reduce((sum, t) => sum + t.metrics.recentInvoices, 0) / tenantAnalytics.length; if (invoiceFrequency > 50) { insights.recommendations.push({ type: 'feature_suggestion', title: 'اقتراح ميزة جديدة', description: 'العملاء النشطون قد يستفيدون من ميزات الفوترة المتقدمة', priority: 'low', features: ['الفواتير المتكررة', 'الجدولة التلقائية', 'التقارير المتقدمة'] }); } return insights; }; // Get system-wide usage trends export const getUsageTrends = async (req, res) => { try { // Validate super admin access if (req.user.role !== 'super_admin') { return res.status(403).json({ message: 'Access denied. Super admin required.' }); } const { period = '90' } = req.query; const daysAgo = new Date(); daysAgo.setDate(daysAgo.getDate() - parseInt(period)); // Get daily usage data const dailyData = await Invoice.aggregate([ { $match: { createdAt: { $gte: daysAgo } } }, { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }, invoiceCount: { $sum: 1 }, totalRevenue: { $sum: "$totalAmount" }, uniqueTenants: { $addToSet: "$tenant" } } }, { $addFields: { tenantCount: { $size: "$uniqueTenants" } } }, { $sort: { _id: 1 } } ]); // Get tenant registration trends const registrationData = await Tenant.aggregate([ { $match: { createdAt: { $gte: daysAgo } } }, { $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }, newTenants: { $sum: 1 } } }, { $sort: { _id: 1 } } ]); res.status(200).json({ period: `${period} days`, dailyData, registrationData, generatedAt: new Date() }); } catch (error) { console.error('Usage trends error:', error); res.status(500).json({ message: 'Failed to generate usage trends' }); } }; // Update tenant business types (multi-select: restaurant, cafe, sales) export const updateTenantType = async (req, res) => { try { // Validate super admin access if (req.user.role !== 'super_admin') { return res.status(403).json({ status: 'error', message: 'رفع الوصول. مدير النظام فقط' }); } const { tenantId } = req.params; const { tenantTypes } = req.body; // Validate tenant types (must be array) if (!tenantTypes || !Array.isArray(tenantTypes) || tenantTypes.length === 0) { return res.status(400).json({ status: 'error', message: 'يجب تحديد نوع عمل واحد على الأقل. أرسل مصفوفة: ["restaurant", "cafe", "sales"]' }); } // Validate each type const validTypes = ['restaurant', 'cafe', 'sales']; for (const type of tenantTypes) { if (!validTypes.includes(type)) { return res.status(400).json({ status: 'error', message: `نوع عمل غير صحيح: ${type}. الأنواع الصحيحة: restaurant أو cafe أو sales` }); } } // Remove duplicates const uniqueTypes = [...new Set(tenantTypes)]; // Check if tenant exists const tenant = await Tenant.findById(tenantId); if (!tenant) { return res.status(404).json({ status: 'error', message: 'لم يتم العثور على حساب العمل' }); } // Update tenant types const updatedTenant = await Tenant.findByIdAndUpdate( tenantId, { tenantTypes: uniqueTypes }, { new: true, runValidators: true } ); res.status(200).json({ status: 'success', message: 'تم تحديث أنواع العمل بنجاح', data: { tenantId: updatedTenant._id, tenantName: updatedTenant.name, tenantTypes: updatedTenant.tenantTypes, updatedAt: updatedTenant.updatedAt } }); } catch (error) { console.error('Update tenant types error:', error); res.status(500).json({ status: 'error', message: 'فشل تحديث أنواع العمل' }); } }; // Get all tenants with features export const getAllTenants = async (req, res) => { try { // Validate super admin access if (req.user.role !== 'super_admin') { return res.status(403).json({ status: 'error', message: 'رفع الوصول. مدير النظام فقط' }); } const { status, type } = req.query; const filter = {}; if (status) filter.status = status; if (type) filter.tenantType = type; const tenants = await Tenant.find(filter) .select('_id name slug tenantTypes status subscriptionPackage createdAt monthlyFee ownerName ownerEmail') .sort({ createdAt: -1 }); res.status(200).json({ status: 'success', data: tenants, total: tenants.length }); } catch (error) { console.error('Get tenants error:', error); res.status(500).json({ status: 'error', message: 'فشل جلب قائمة العملاء' }); } };