// 测试账号健康度评分系统 require('module-alias/register'); const Db = require("@src/config/Db"); const MAccountPool = require("@src/modes/MAccountPool"); const MAccountUsageLog = require("@src/modes/MAccountUsageLog"); const MTgAccount = require("@src/modes/MTgAccount"); const AccountHealthService = require("@src/service/AccountHealthService"); const initAssociations = require("@src/modes/initAssociations"); const moment = require("moment"); async function testHealthService() { try { console.log("开始测试账号健康度服务...\n"); // 初始化数据库 await Db.getInstance(); // 等待数据库连接完成 await new Promise(resolve => setTimeout(resolve, 2000)); // 初始化关联关系 initAssociations(); // 确保所有表都创建 const { Sequelize } = require('sequelize'); const db = Db.getInstance().db; await db.sync({ alter: false }); // 获取服务实例 const healthService = AccountHealthService.getInstance(); // 获取或创建测试账号 let tgAccount = await MTgAccount.findOne(); if (!tgAccount) { console.log("创建测试TG账号..."); tgAccount = await MTgAccount.create({ phone: '+1234567890', status: 1, name: 'Test Account' }); } // 创建或获取账号池记录 let accountPool = await MAccountPool.findOne({ where: { accountId: tgAccount.id } }); if (!accountPool) { console.log("创建账号池记录..."); accountPool = await MAccountPool.create({ accountId: tgAccount.id, phone: tgAccount.phone, status: 'active', tier: 'normal', dailyLimit: 50, hourlyLimit: 10, totalSentCount: 150, todaySentCount: 20 }); } console.log(`✅ 使用账号池ID: ${accountPool.id}, 手机号: ${accountPool.phone}\n`); // 创建模拟使用记录 console.log("创建模拟使用记录..."); await createMockUsageLogs(accountPool.id); // 1. 测试单个账号健康度评估 console.log("\n=== 测试单个账号健康度评估 ==="); const healthResult = await healthService.evaluateAccountHealth(accountPool.id); console.log("健康度评估结果:"); console.log(`- 健康分数: ${healthResult.healthScore.toFixed(2)}`); console.log(`- 健康状态: ${healthResult.status}`); console.log(`- 健康趋势: ${healthResult.trend}`); console.log("- 改善建议:"); healthResult.recommendations.forEach(rec => { console.log(` • ${rec}`); }); console.log("\n关键指标:"); console.log(`- 成功率: ${healthResult.metrics.successRate.toFixed(2)}%`); console.log(`- 错误率: ${healthResult.metrics.errorRate.toFixed(2)}%`); console.log(`- 日使用率: ${healthResult.metrics.dailyUsageRate.toFixed(2)}%`); console.log(`- 平均响应时间: ${healthResult.metrics.avgResponseTime.toFixed(0)}ms`); console.log(`- 互动率: ${healthResult.metrics.engagementRate.toFixed(2)}%`); console.log(`- 异常分数: ${healthResult.metrics.anomalyScore.toFixed(2)}`); // 2. 测试健康度报告 console.log("\n=== 测试健康度报告 ==="); const report = await healthService.getHealthReport(accountPool.id, 30); if (report) { console.log("健康度报告:"); console.log(`- 当前分数: ${report.currentScore.toFixed(2)}`); console.log(`- 当前状态: ${report.currentStatus}`); console.log(`- 平均分数: ${report.metrics.avgScore.toFixed(2)}`); console.log(`- 最低分数: ${report.metrics.minScore.toFixed(2)}`); console.log(`- 最高分数: ${report.metrics.maxScore.toFixed(2)}`); } // 3. 测试批量评估 console.log("\n=== 测试批量账号评估 ==="); const batchResult = await healthService.evaluateAllActiveAccounts(); console.log(`批量评估完成: 总计 ${batchResult.total} 个账号`); console.log(`成功评估: ${batchResult.evaluated} 个账号`); // 4. 检查账号状态更新 await accountPool.reload(); console.log("\n=== 账号状态更新 ==="); console.log(`- 账号状态: ${accountPool.status}`); console.log(`- 账号分级: ${accountPool.tier}`); console.log(`- 风险评分: ${accountPool.riskScore.toFixed(2)}`); console.log("\n✅ 所有测试完成!"); } catch (error) { console.error("❌ 测试失败:", error); } finally { process.exit(); } } // 创建模拟使用记录 async function createMockUsageLogs(accountPoolId) { const logs = []; const now = moment(); // 创建过去7天的使用记录 for (let day = 0; day < 7; day++) { const date = moment().subtract(day, 'days'); // 每天创建10-20条记录 const recordCount = 10 + Math.floor(Math.random() * 10); for (let i = 0; i < recordCount; i++) { const hour = 8 + Math.floor(Math.random() * 12); // 8-20点之间 const startTime = date.hour(hour).minute(Math.floor(Math.random() * 60)); const duration = 1000 + Math.floor(Math.random() * 4000); // 1-5秒 // 80%成功率 const isSuccess = Math.random() < 0.8; logs.push({ accountPoolId, taskId: 1, taskType: 'group_send', groupId: null, // 不设置群组ID,避免外键约束 messageContent: '测试消息内容', status: isSuccess ? 'success' : (Math.random() < 0.5 ? 'failed' : 'timeout'), errorCode: isSuccess ? null : 'ERR_SEND_FAILED', errorMessage: isSuccess ? null : '发送失败', startTime: startTime.toDate(), endTime: startTime.add(duration, 'milliseconds').toDate(), duration, riskLevel: Math.random() < 0.7 ? 'low' : (Math.random() < 0.8 ? 'medium' : 'high'), behaviorSimulation: { typingSpeed: 60 + Math.floor(Math.random() * 40), pauseTime: 500 + Math.floor(Math.random() * 1500) }, recipientCount: 20 + Math.floor(Math.random() * 30), readCount: Math.floor(15 + Math.random() * 20), replyCount: Math.floor(Math.random() * 5), reportCount: Math.random() < 0.05 ? 1 : 0 // 5%的举报率 }); } } // 批量创建记录 await MAccountUsageLog.bulkCreate(logs); console.log(`✅ 创建了 ${logs.length} 条模拟使用记录`); } // 运行测试 testHealthService();