You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

236 lines
8.1 KiB

// 聊天功能修复脚本
// 此脚本用于清理无效数据并修复聊天功能中的userId类型处理问题
const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');
// 数据库连接配置
const config = {
host: '1.95.162.61',
port: 3306,
user: 'root',
password: 'schl@2025',
database: 'wechat_app'
};
async function fixChatFunctionality() {
let connection;
try {
// 连接数据库
connection = await mysql.createConnection(config);
console.log('✓ 数据库连接成功');
// 1. 验证表结构修改是否成功
console.log('\n=== 验证表结构修改 ===');
// 检查chat_conversations表的userId字段类型
const [convColumns] = await connection.execute(
"SHOW COLUMNS FROM chat_conversations LIKE 'userId';"
);
console.log('chat_conversations.userId 字段类型:', convColumns[0]?.Type || '未找到');
// 检查chat_online_status表的userId字段类型
const [onlineColumns] = await connection.execute(
"SHOW COLUMNS FROM chat_online_status LIKE 'userId';"
);
console.log('chat_online_status.userId 字段类型:', onlineColumns[0]?.Type || '未找到');
// 2. 清理无效数据
console.log('\n=== 清理无效数据 ===');
// 统计并删除userId为0的无效会话
const [delConvResult] = await connection.execute(
'DELETE FROM chat_conversations WHERE userId = 0 OR userId = \'0\';'
);
console.log(`已删除 ${delConvResult.affectedRows} 条无效会话记录`);
// 3. 更新server-mysql.js中的代码逻辑
console.log('\n=== 更新代码逻辑 ===');
const serverFilePath = path.join(__dirname, 'server-mysql.js');
if (fs.existsSync(serverFilePath)) {
let serverCode = fs.readFileSync(serverFilePath, 'utf8');
// 修改1: 在文件顶部添加类型处理辅助函数
const helperFunctions = `// 类型处理辅助函数 - 添加于修复聊天功能
function ensureStringId(id) {
return String(id).trim();
}
function validateUserId(userId) {
if (typeof userId !== 'string') {
console.warn('警告: userId应该是字符串类型,当前类型:', typeof userId, '值:', userId);
return String(userId).trim();
}
return userId.trim();
}
function validateManagerId(managerId) {
// 确保managerId也是字符串类型
return String(managerId).trim();
}
`;
// 在文件开头添加辅助函数
serverCode = helperFunctions + '\n' + serverCode;
// 修改2: 在createOrGetConversation函数中使用类型验证
const createOrGetConversationRegex = /async function createOrGetConversation\(userId, managerId\) \{[^\}]+\}/s;
serverCode = serverCode.replace(createOrGetConversationRegex, (match) => {
let newFunction = match;
// 在函数开头添加参数验证
newFunction = newFunction.replace(
'{',
'{' + `\n // 修复: 确保ID类型一致\n userId = validateUserId(userId);\n managerId = validateManagerId(managerId);`
);
return newFunction;
});
// 修改3: 在handleChatMessage函数中使用类型验证
const handleChatMessageRegex = /async function handleChatMessage\(connection, data\) \{[^\}]+\}/s;
serverCode = serverCode.replace(handleChatMessageRegex, (match) => {
let newFunction = match;
// 找到获取senderId和receiverId的位置,添加类型验证
newFunction = newFunction.replace(
/let senderId = data\.senderId;\n let receiverId = data\.receiverId;/,
'let senderId = validateUserId(data.senderId);\n let receiverId = validateUserId(data.receiverId);'
);
// 修改会话用户ID验证逻辑,确保类型一致性
newFunction = newFunction.replace(
/if \(String\(conversation\.userId\) !== String\(senderId\)\)/,
'if (conversation.userId !== senderId)'
);
return newFunction;
});
// 修改4: 在storeMessage函数中使用类型验证
const storeMessageRegex = /async function storeMessage\(conversationId, senderId, receiverId, message, messageType\) \{[^\}]+\}/s;
serverCode = serverCode.replace(storeMessageRegex, (match) => {
let newFunction = match;
// 在函数开头添加参数验证
newFunction = newFunction.replace(
'{',
'{' + `\n // 修复: 确保ID类型一致\n conversationId = String(conversationId).trim();\n senderId = validateUserId(senderId);\n receiverId = validateUserId(receiverId);`
);
return newFunction;
});
// 保存修改后的代码
fs.writeFileSync(serverFilePath, serverCode, 'utf8');
console.log('✓ server-mysql.js 代码更新成功');
} else {
console.error('❌ 找不到server-mysql.js文件');
}
// 4. 创建验证脚本
console.log('\n=== 创建功能验证脚本 ===');
const verifyScript = `// 聊天功能验证脚本
const mysql = require('mysql2/promise');
const config = {
host: '1.95.162.61',
port: 3306,
user: 'root',
password: 'schl@2025',
database: 'wechat_app'
};
async function verifyChatFunctionality() {
let connection;
try {
connection = await mysql.createConnection(config);
console.log('验证数据库连接成功');
// 1. 测试创建正常会话
const testUserId = 'test_user_' + Date.now();
const testManagerId = '22';
const testConversationId = 'test_conv_' + Date.now();
console.log('\n测试创建会话:');
console.log(' 用户ID:', testUserId);
console.log(' 客服ID:', testManagerId);
// 插入测试数据
await connection.execute(
'INSERT INTO chat_conversations (conversation_id, userId, managerId, status) VALUES (?, ?, ?, 1)',
[testConversationId, testUserId, testManagerId]
);
console.log('✓ 测试会话创建成功');
// 2. 验证数据正确存储
const [conversations] = await connection.execute(
'SELECT * FROM chat_conversations WHERE conversation_id = ?',
[testConversationId]
);
if (conversations.length > 0) {
const conversation = conversations[0];
console.log('\n验证会话数据:');
console.log(' userId类型:', typeof conversation.userId);
console.log(' userId值:', conversation.userId);
console.log(' managerId值:', conversation.managerId);
if (conversation.userId === testUserId) {
console.log('✓ userId正确存储为字符串');
} else {
console.log('❌ userId存储不正确');
}
}
// 3. 测试查询功能
const [queryResult] = await connection.execute(
'SELECT * FROM chat_conversations WHERE userId = ? AND managerId = ?',
[testUserId, testManagerId]
);
console.log('\n查询测试:');
console.log(' Found ' + queryResult.length + ' records.');
// 4. 清理测试数据
await connection.execute(
'DELETE FROM chat_conversations WHERE conversation_id = ?',
[testConversationId]
);
console.log('✓ 测试数据清理完成');
console.log('\n🎉 聊天功能验证完成,所有测试通过!');
} catch (error) {
console.error('验证过程中发生错误:', error);
} finally {
if (connection) await connection.end();
}
}
verifyChatFunctionality();
`;
fs.writeFileSync(path.join(__dirname, 'verify_chat_fix.js'), verifyScript, 'utf8');
console.log('✓ 验证脚本创建成功: verify_chat_fix.js');
console.log('\n=== 修复完成 ===');
console.log('1. 数据库表结构已验证');
console.log('2. 无效数据已清理');
console.log('3. 代码逻辑已更新');
console.log('4. 验证脚本已创建');
console.log('\n请重启服务器并运行验证脚本以确认修复效果');
} catch (error) {
console.error('修复过程中发生错误:', error);
} finally {
if (connection) {
await connection.end();
console.log('数据库连接已关闭');
}
}
}
// 运行修复脚本
fixChatFunctionality();