customer-master-service.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. const fs = require('fs');
  2. const path = require('path');
  3. const { qiweiAccountKey } = require('../core/credentials');
  4. const { outputsRoot } = require('../core/output-paths');
  5. const { okResult, errorResult } = require('../core/result-envelope');
  6. const { getConversations, updateCustomerProfile } = require('./agent-service');
  7. const { readState } = require('../core/dashboard-state');
  8. const FIELD_LABELS = {
  9. intent: '客户意图',
  10. purpose: '客户目标',
  11. need: '核心需求',
  12. needs: '核心需求',
  13. preferredRegion: '服务区域',
  14. region: '服务区域',
  15. district: '服务区域',
  16. budgetWan: '预算',
  17. budgetRange: '预算范围',
  18. budgetType: '预算口径',
  19. layout: '方案偏好',
  20. houseType: '方案偏好',
  21. timeline: '计划时间',
  22. urgency: '紧迫度',
  23. keyConcerns: '核心关注',
  24. decisionMaker: '决策人',
  25. contactPreference: '沟通偏好',
  26. serviceStage: '服务阶段',
  27. aiSummary: '画像摘要',
  28. };
  29. function ensureDir(dirPath) { fs.mkdirSync(dirPath, { recursive: true }); return dirPath; }
  30. function writeJsonAtomic(filePath, value) {
  31. ensureDir(path.dirname(filePath));
  32. const tempPath = `${filePath}.${process.pid}.tmp`;
  33. fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
  34. fs.renameSync(tempPath, filePath);
  35. }
  36. function profileValue(value, field) {
  37. if (Array.isArray(value)) return value.join('、');
  38. if (value && typeof value === 'object') return value.note || value.value || JSON.stringify(value);
  39. if (field === 'budgetWan' && Number.isFinite(Number(value))) return `${Number(value)} 万`;
  40. return String(value ?? '');
  41. }
  42. function customerStage(conversation, fieldCount) {
  43. const summary = conversation.customerIntelligence?.summary || {};
  44. if (summary.highAlerts > 0) return { key: 'priority', label: '重点跟进' };
  45. if (summary.openTasks > 0 && Number(conversation.analysis?.completenessScore || 0) >= 50) return { key: 'qualified', label: '需求已成形' };
  46. if (fieldCount > 0) return { key: 'profiling', label: '画像积累中' };
  47. return { key: 'new', label: '待完善' };
  48. }
  49. function hasProfileValue(profile, ...keys) {
  50. return keys.some(key => {
  51. const value = profile?.[key];
  52. return Array.isArray(value) ? value.length > 0 : value !== undefined && value !== null && String(value).trim() !== '' && String(value).trim() !== '待确认';
  53. });
  54. }
  55. function maskPhone(phone) {
  56. const text = String(phone || '').trim();
  57. if (!text) return '';
  58. if (text.length <= 7) return text;
  59. return `${text.slice(0, 3)}****${text.slice(-4)}`;
  60. }
  61. function fallbackConversation(customerOps) {
  62. const displayName = customerOps.name || customerOps.phone || String(customerOps.externalUserId || '').slice(-6) || '未命名客户';
  63. const maskedId = customerOps.phone ? maskPhone(customerOps.phone) : String(customerOps.externalUserId || '');
  64. const source = customerOps.source === 'group-member' ? '群成员发现' : '客户运营导入';
  65. const now = customerOps.updatedAt || new Date().toISOString();
  66. return {
  67. id: `co:${String(customerOps.customerId || customerOps.externalUserId || '')}`,
  68. displayName,
  69. maskedId,
  70. source,
  71. mode: 'customer-ops',
  72. customerIntelligence: {
  73. profile: {},
  74. profileEvidence: {},
  75. tags: Array.isArray(customerOps.tags) ? customerOps.tags : [],
  76. tasks: [],
  77. alerts: [],
  78. summary: {},
  79. },
  80. analysis: { completenessScore: 0 },
  81. messages: [],
  82. updatedAt: now,
  83. lastMessageAt: customerOps.lastSeenInGroupAt || now,
  84. };
  85. }
  86. function getFallbackCustomers() {
  87. try {
  88. const state = readState();
  89. const customers = Object.values(state.customers || {});
  90. if (!customers.length) return [];
  91. return customers
  92. .filter(customer => customer.customerId || customer.externalUserId)
  93. .map(customer => {
  94. const normalized = normalizeCustomer(fallbackConversation(customer));
  95. normalized.fallback = true;
  96. normalized.friendRequestStatus = customer.friendRequestStatus;
  97. normalized.groupStatus = customer.groupStatus;
  98. normalized.externalUserId = String(customer.externalUserId || customer.customerId || '');
  99. normalized.phone = customer.phone || '';
  100. normalized.sourceRoomIds = Array.isArray(customer.sourceRoomIds) ? customer.sourceRoomIds : [];
  101. normalized.groupNames = Array.isArray(customer.groupNames) ? customer.groupNames : [];
  102. return normalized;
  103. })
  104. .sort((a, b) => String(b.lastMessageAt || '').localeCompare(String(a.lastMessageAt || '')));
  105. } catch (err) {
  106. return [];
  107. }
  108. }
  109. function buildNextActions(customer) {
  110. const actions = [];
  111. const add = (id, title, description, evidence, priority = 'medium', confidence = 'rule') => actions.push({ id, title, description, evidence: (evidence || []).filter(Boolean), priority, confidence, status: 'suggested', action: 'open-conversation' });
  112. const profile = customer.profile || {};
  113. const openTaskEvidence = customer.tasks.find(task => ['open', 'in_progress'].includes(task.status))?.evidence;
  114. if (!hasProfileValue(profile, 'intent', 'purpose', 'need', 'needs')) add('confirm-purpose', '确认客户目标', '询问客户本次咨询希望解决的核心问题,再确定后续服务重点。', [openTaskEvidence, '客户主档中的目标尚未确认'], 'high');
  115. if (!hasProfileValue(profile, 'timeline')) add('confirm-timeline', '确认计划时间', '确认客户希望何时推进,以判断跟进频率和下一步安排。', [openTaskEvidence, '客户主档中的计划时间尚未确认'], 'high');
  116. if (!hasProfileValue(profile, 'decisionMaker')) add('confirm-decision-maker', '确认决策人', '确认还有哪些人参与决策,避免遗漏关键沟通对象。', ['当前主档没有明确决策人'], 'medium');
  117. if (String(profile.budgetType || '') === '待确认') add('confirm-budget-type', '确认预算口径', '确认当前预算是上限、目标值还是仍可调整。', [`预算已记录为 ${profile.budgetWan || '-'},但预算口径为待确认`], 'medium');
  118. for (const alert of customer.alerts.filter(item => item.status === 'open' && ['high', 'critical'].includes(item.severity)).slice(0, 2)) add(`alert:${alert.id}`, alert.recommendedAction || alert.title, alert.detail || '优先处理高等级客户预警。', [alert.evidence], 'high');
  119. return actions.slice(0, 6);
  120. }
  121. function buildTimeline(customer) {
  122. const events = [];
  123. for (const message of customer.messages || []) {
  124. events.push({ id: `message:${message.id}`, type: message.role === 'customer' ? 'inbound-message' : 'outbound-message', title: message.role === 'customer' ? '收到客户消息' : '发送客户回复', description: String(message.content || '').slice(0, 300), occurredAt: message.timestamp, source: message.source || message.role, fact: true });
  125. }
  126. if (customer.profileUpdatedAt && customer.fields.length) events.push({ id: `profile:${customer.profileUpdatedAt}`, type: 'profile', title: '客户画像已更新', description: customer.fields.slice(0, 5).map(field => `${field.label}:${field.displayValue}`).join(' · '), occurredAt: customer.profileUpdatedAt, source: 'customer-intelligence-db', fact: true });
  127. for (const task of customer.tasks || []) events.push({ id: `task:${task.id}`, type: 'task', title: `内部任务 · ${task.title}`, description: task.evidence || task.reason || '', occurredAt: task.updatedAt, source: 'customer-task', status: task.status, fact: true });
  128. for (const alert of customer.alerts || []) events.push({ id: `alert:${alert.id}`, type: 'alert', title: `客户预警 · ${alert.title}`, description: alert.evidence || alert.detail || '', occurredAt: alert.updatedAt, source: 'customer-alert', status: alert.status, fact: true });
  129. return events.filter(item => item.occurredAt).sort((a, b) => String(b.occurredAt).localeCompare(String(a.occurredAt))).slice(0, 80);
  130. }
  131. function normalizeCustomer(conversation) {
  132. const intelligence = conversation.customerIntelligence || {};
  133. const profile = intelligence.profile || {};
  134. const profileEvidence = intelligence.profileEvidence || {};
  135. const fields = Object.entries(profile).filter(([key]) => !key.startsWith('__') && key !== 'propertyFeedback').map(([key, value]) => ({
  136. key,
  137. label: FIELD_LABELS[key] || key,
  138. value,
  139. displayValue: profileValue(value, key),
  140. evidence: profileEvidence[key] ? {
  141. text: String(profileEvidence[key].text || ''),
  142. sourceMessageId: profileEvidence[key].sourceMessageId || null,
  143. source: profileEvidence[key].source || (profileEvidence[key].sourceMessageId ? 'live-message' : 'unknown'),
  144. updatedAt: profileEvidence[key].updatedAt || null,
  145. } : null,
  146. }));
  147. const stage = customerStage(conversation, fields.length);
  148. const messages = conversation.messages || [];
  149. const latestMessage = messages.at(-1) || null;
  150. const tasks = intelligence.tasks || [];
  151. const alerts = intelligence.alerts || [];
  152. const evidenced = fields.filter(item => item.evidence?.text).length;
  153. const customer = {
  154. id: conversation.id,
  155. externalUserId: conversation.channelId || conversation.contactId || '',
  156. displayName: conversation.displayName,
  157. maskedId: conversation.maskedId,
  158. source: conversation.source === 'live' ? '真实企微会话' : conversation.source,
  159. mode: conversation.mode,
  160. stage,
  161. profile,
  162. fields,
  163. tags: intelligence.tags || [],
  164. completenessScore: Number(conversation.analysis?.completenessScore || 0),
  165. evidenceCoverage: fields.length ? Math.round(evidenced / fields.length * 100) : 0,
  166. profileUpdatedAt: intelligence.profileUpdatedAt || conversation.updatedAt || null,
  167. lastMessageAt: conversation.lastMessageAt,
  168. latestMessage: latestMessage ? { role: latestMessage.role, content: latestMessage.content, timestamp: latestMessage.timestamp } : null,
  169. messages,
  170. messageCount: messages.length,
  171. tasks,
  172. alerts,
  173. openTaskCount: tasks.filter(item => ['open', 'in_progress'].includes(item.status)).length,
  174. openAlertCount: alerts.filter(item => item.status === 'open').length,
  175. highAlertCount: alerts.filter(item => item.status === 'open' && ['high', 'critical'].includes(item.severity)).length,
  176. actions: { openConversation: true, editProfile: true },
  177. };
  178. customer.nextActions = buildNextActions(customer);
  179. customer.timeline = buildTimeline(customer);
  180. return customer;
  181. }
  182. function createCustomerMasterService(dependencies = {}) {
  183. const conversationReader = dependencies.getConversations || getConversations;
  184. const profileUpdater = dependencies.updateCustomerProfile || updateCustomerProfile;
  185. const fixedProjectionPath = dependencies.projectionPath ? path.resolve(dependencies.projectionPath) : '';
  186. const projectionPath = () => fixedProjectionPath
  187. || path.join(outputsRoot(), 'customers', qiweiAccountKey(), 'index.json');
  188. function persistProjection(customers) {
  189. const snapshot = {
  190. version: 1,
  191. updatedAt: new Date().toISOString(),
  192. customers: customers.map(customer => ({
  193. id: customer.id,
  194. displayName: customer.displayName,
  195. maskedId: customer.maskedId,
  196. source: customer.source,
  197. stage: customer.stage,
  198. profile: customer.profile,
  199. tags: customer.tags,
  200. completenessScore: customer.completenessScore,
  201. evidenceCoverage: customer.evidenceCoverage,
  202. profileUpdatedAt: customer.profileUpdatedAt,
  203. lastMessageAt: customer.lastMessageAt,
  204. openTaskCount: customer.openTaskCount,
  205. openAlertCount: customer.openAlertCount,
  206. })),
  207. };
  208. writeJsonAtomic(projectionPath(), snapshot);
  209. return snapshot.updatedAt;
  210. }
  211. function hub() {
  212. const result = conversationReader() || {};
  213. const conversations = result.data?.conversations || [];
  214. let customers = conversations.map(normalizeCustomer).sort((a, b) => String(b.lastMessageAt || '').localeCompare(String(a.lastMessageAt || '')));
  215. let fallback = false;
  216. if (!customers.length) {
  217. customers = getFallbackCustomers();
  218. fallback = customers.length > 0;
  219. }
  220. const projectedAt = persistProjection(customers);
  221. const profiledCount = customers.filter(item => item.fields.length).length;
  222. return okResult({
  223. assistantMessage: fallback
  224. ? `客户主档暂无真实企微会话客户,已自动从客户运营数据展示 ${customers.length} 位客户作为参考。`
  225. : `客户管理已汇总 ${customers.length} 位真实会话客户,其中 ${profiledCount} 位已形成画像。`,
  226. summary: {
  227. customerCount: customers.length,
  228. profiledCount,
  229. priorityCount: customers.filter(item => item.stage.key === 'priority').length,
  230. openTaskCount: customers.reduce((sum, item) => sum + item.openTaskCount, 0),
  231. openAlertCount: customers.reduce((sum, item) => sum + item.openAlertCount, 0),
  232. projectedAt,
  233. fallback,
  234. },
  235. data: {
  236. customers,
  237. policy: {
  238. canonicalStore: fallback ? '客户运营数据(会话主账为空时的参考视图)' : 'SQLite 客户画像主账',
  239. autoSync: fallback
  240. ? '当前展示的是客户运营导入/群成员发现数据;同步真实企微会话后,画像与任务会自动沉淀到这里。'
  241. : '真实企微消息经 Agent 提取后自动更新客户主档;画像与标签工具也回写同一主账。',
  242. evidence: '客户原话证据只在本机管理页面显示;导出的客户投影不复制原话。',
  243. nextAction: '下一步行动属于规则或 AI 建议,不自动发送、不自动改写客户事实。',
  244. },
  245. },
  246. files: [projectionPath()],
  247. });
  248. }
  249. function update(conversationId, input = {}) {
  250. const id = String(conversationId || '').trim();
  251. if (!id) return errorResult('缺少客户主档 ID。');
  252. const result = profileUpdater(id, input);
  253. if (result?.status !== 'ok') return result;
  254. const refreshed = hub();
  255. return okResult({
  256. assistantMessage: result.assistantMessage || '客户主档已更新。',
  257. summary: result.summary,
  258. data: { customer: refreshed.data.customers.find(item => item.id === id) || null },
  259. files: refreshed.files,
  260. });
  261. }
  262. return { hub, update };
  263. }
  264. const service = createCustomerMasterService();
  265. module.exports = {
  266. createCustomerMasterService,
  267. getCustomerMasterHub: service.hub,
  268. updateCustomerMaster: service.update,
  269. __testing: { normalizeCustomer, customerStage, profileValue, buildNextActions, buildTimeline },
  270. };