This commit is contained in:
张成
2026-02-28 16:28:28 +08:00
parent 96da90daa8
commit 5ec4e7f440
9 changed files with 242 additions and 127 deletions

View File

@@ -68,99 +68,16 @@ class ChatHandler extends BaseHandler {
return { chatCount: 0, message: '没有可沟通的会话', detail: { total_contacts: 0 } };
}
this._syncFriendListToChatRecords(sn_code, platform_type, friend_list);
let replied_count = 0;
const details = [];
// 2. 将会话列表同步到聊天记录表(按会话维度做一条摘要记录)
try {
const chatRecordsModel = db.getModel('chat_records');
for (const friend of friend_list) {
const friend_id = friend.friendId;
if (!friend_id) continue;
const encryptId = friend.encryptFriendId || '';
const existing = await chatRecordsModel.findOne({
where: {
sn_code,
platform: platform_type,
encryptBossId: encryptId,
direction: 'received',
chatType: 'session'
}
});
const baseData = {
sn_code,
platform: platform_type,
encryptBossId: encryptId,
jobTitle: friend.jobName || '',
companyName: friend.brandName || '',
hrName: friend.name || '',
hrTitle: friend.bossTitle || '',
hrId: String(friend_id),
chatType: 'session',
direction: 'received',
content: '',
contentType: 'text',
receiveTime: friend.updateTime ? new Date(friend.updateTime) : new Date()
};
if (existing) {
await existing.update(baseData);
} else {
await chatRecordsModel.create(baseData);
}
}
} catch (e) {
console.warn('[自动沟通] 同步聊天会话列表到 chat_records 失败:', e.message);
}
// 3. 对每个会话:下发「获取详情」→ 若需回复则下发「发送消息」
for (const friend of friend_list) {
const friend_id = friend.friendId;
if (!friend_id) continue;
if (!friend.friendId) continue;
const item = await this._processOneFriend(task, friend, sn_code, platform_type);
details.push(item);
if (item.replied) replied_count++;
try {
const detail_command = {
command_type: 'get_chat_detail',
command_name: '获取聊天详情',
command_params: { platform: platform_type, friendId: friend_id },
priority: config.getTaskPriority('auto_chat') || 6
};
const detail_exec = await command.executeCommands(task.id, [detail_command], this.mqttClient);
const detail = detail_exec?.results?.[0]?.result;
const decision = await chatManager.getReplyContentFromDetail(detail || {});
if (decision.replied && decision.reply_content) {
const send_command = {
command_type: 'send_chat_message',
command_name: '发送聊天消息',
command_params: {
platform: platform_type,
friendId: friend_id,
messages: [{ type: 'text', content: decision.reply_content }],
chatType: 'reply'
},
priority: config.getTaskPriority('auto_chat') || 6
};
await command.executeCommands(task.id, [send_command], this.mqttClient);
replied_count++;
}
details.push({
friendId: friend_id,
replied: !!decision.replied,
reason: decision.reason || null
});
} catch (err) {
details.push({
friendId: friend_id,
replied: false,
reason: err.message || '处理失败'
});
}
}
console.log(`[自动沟通] 完成 - 设备: ${sn_code},会话 ${friend_list.length},回复 ${replied_count}`);
@@ -175,6 +92,129 @@ class ChatHandler extends BaseHandler {
}
};
}
/** 将会话列表同步到 chat_records内部 catch 仅打日志 */
async _syncFriendListToChatRecords(sn_code, platform_type, friend_list) {
try {
const chatRecordsModel = db.getModel('chat_records');
for (const friend of friend_list) {
const friend_id = friend.friendId;
if (friend_id == null) continue;
const encryptId = friend.encryptFriendId || '';
const existing = await chatRecordsModel.findOne({
where: { sn_code, platform: platform_type, encryptFriendId: encryptId }
});
const baseData = {
sn_code,
platform: platform_type,
friendId: friend_id,
encryptFriendId: encryptId,
name: friend.name || '',
updateTime: friend.updateTime != null ? friend.updateTime : null,
brandName: friend.brandName || '',
jobName: friend.jobName || '',
jobCity: friend.jobCity || '',
positionName: friend.positionName || '',
bossTitle: friend.bossTitle || '',
friendSource: friend.friendSource != null ? friend.friendSource : 0,
jobTypeDesc: friend.jobTypeDesc || '',
waterLevel: friend.waterLevel != null ? friend.waterLevel : 0
};
if (existing) await existing.update(baseData);
else await chatRecordsModel.create(baseData);
}
console.log(`[自动沟通] 已同步 ${friend_list.length} 条会话到 chat_records`);
} catch (e) {
console.warn('[自动沟通] 同步聊天会话列表到 chat_records 失败:', e.message);
}
}
/**
* 落库 chat_message入参为解析后格式 { variant, messages, data, job }
* 有 messages 则每条一条记录;仅会话时 mid=0 存 { data, job }
*/
async _saveChatMessagesToDb(parsed, friend, sn_code, platform_type) {
if (!parsed) return;
const messages = Array.isArray(parsed.messages) ? parsed.messages : [];
const has_session = parsed.data != null || parsed.job != null;
if (messages.length === 0 && !has_session) return;
try {
const chatMessageModel = db.getModel('chat_message');
const friend_id = friend.friendId;
const encrypt_id = friend.encryptFriendId || '';
const fetch_time = new Date();
const base = { sn_code, platform: platform_type, friendId: friend_id, encryptFriendId: encrypt_id, fetch_time };
if (messages.length > 0) {
for (const msg of messages) {
const mid = msg.mid != null ? msg.mid : 0;
const existing = await chatMessageModel.findOne({
where: { sn_code, platform: platform_type, friendId: friend_id, mid }
});
const row = { ...base, mid, message_data: msg };
if (existing) await existing.update(row);
else await chatMessageModel.create(row);
}
} else {
const boss_payload = { data: parsed.data || null, job: parsed.job || null };
const existing = await chatMessageModel.findOne({
where: { sn_code, platform: platform_type, friendId: friend_id, mid: 0 }
});
const row = { ...base, mid: 0, message_data: boss_payload };
if (existing) await existing.update(row);
else await chatMessageModel.create(row);
}
} catch (e) {
console.warn('[自动沟通] 写入 chat_message 失败:', e.message);
}
}
/**
* 处理单个会话:获取详情 → 落库 → 判断是否回复 → 若需则发送消息
* @returns {{ friendId: number, replied: boolean, reason: string|null }}
*/
async _processOneFriend(task, friend, sn_code, platform_type) {
const friend_id = friend.friendId;
try {
const detail_command = {
command_type: 'get_chat_detail',
command_name: '获取聊天详情',
command_params: { platform: platform_type, friendId: friend_id },
priority: config.getTaskPriority('auto_chat') || 6
};
const detail_exec = await command.executeCommands(task.id, [detail_command], this.mqttClient);
const result = detail_exec?.results?.[0]?.result;
const parsed = chatManager.parseDetailResponse(result || {});
await this._saveChatMessagesToDb(parsed, friend, sn_code, platform_type);
const decision = await chatManager.getReplyContentFromDetail(parsed || {});
if (decision.replied && decision.reply_content) {
const send_command = {
command_type: 'send_chat_message',
command_name: '发送聊天消息',
command_params: {
platform: platform_type,
friendId: friend_id,
messages: [{ type: 'text', content: decision.reply_content }],
chatType: 'reply'
},
priority: config.getTaskPriority('auto_chat') || 6
};
await command.executeCommands(task.id, [send_command], this.mqttClient);
}
return {
friendId: friend_id,
replied: !!decision.replied,
reason: decision.reason || null
};
} catch (err) {
return { friendId: friend_id, replied: false, reason: err.message || '处理失败' };
}
}
}
module.exports = ChatHandler;

View File

@@ -89,7 +89,7 @@ class SearchHandler extends BaseHandler {
command_type: 'get_job_list',
command_name: '获取职位列表',
command_params: JSON.stringify(commandParams),
priority: config.getTaskPriority('search_jobs') || 8
priority: config.getTaskPriority('auto_search') || 8
};
// 5. 执行搜索指令

View File

@@ -29,7 +29,7 @@ class TaskHandlers {
register(taskQueue) {
console.log('[任务处理器] 开始注册处理器...');
// 注册自动搜索处理器
// 注册自动搜索处理器(唯一搜索任务类型)
taskQueue.registerHandler('auto_search', async (task) => {
return await this.handleAutoSearchTask(task);
});
@@ -39,11 +39,6 @@ class TaskHandlers {
return await this.handleAutoDeliverTask(task);
});
// 注册搜索职位列表处理器(与 auto_search 相同)
taskQueue.registerHandler('search_jobs', async (task) => {
return await this.handleAutoSearchTask(task);
});
// 注册自动沟通处理器
taskQueue.registerHandler('auto_chat', async (task) => {
return await this.handleAutoChatTask(task);