customer-master-service.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. const fs = require('fs');
  2. const path = require('path');
  3. const { outputsRoot } = require('../core/output-paths');
  4. const { okResult, errorResult } = require('../core/result-envelope');
  5. const { getConversations, updateCustomerProfile, updateCustomerRecommendation } = require('./agent-service');
  6. const { readState } = require('../core/dashboard-state');
  7. const FIELD_LABELS = {
  8. intent: '客户意图',
  9. purpose: '购置用途',
  10. preferredRegion: '意向区域',
  11. region: '意向区域',
  12. district: '意向区域',
  13. budgetWan: '预算',
  14. budgetRange: '预算范围',
  15. budgetType: '预算口径',
  16. layout: '意向户型',
  17. houseType: '意向户型',
  18. area: '面积偏好',
  19. decoration: '装修偏好',
  20. floorPreference: '楼层偏好',
  21. timeline: '购置时间',
  22. urgency: '紧迫度',
  23. keyConcerns: '核心关注',
  24. schoolRequirement: '学区需求',
  25. decisionMaker: '决策人',
  26. loanCapacity: '贷款能力',
  27. negotiationStage: '谈判阶段',
  28. aiSummary: '画像摘要',
  29. };
  30. function ensureDir(dirPath) { fs.mkdirSync(dirPath, { recursive: true }); return dirPath; }
  31. function writeJsonAtomic(filePath, value) {
  32. ensureDir(path.dirname(filePath));
  33. const tempPath = `${filePath}.${process.pid}.tmp`;
  34. fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
  35. fs.renameSync(tempPath, filePath);
  36. }
  37. function profileValue(value, field) {
  38. if (Array.isArray(value)) return value.join('、');
  39. if (value && typeof value === 'object') return value.note || value.value || JSON.stringify(value);
  40. if (field === 'budgetWan' && Number.isFinite(Number(value))) return `${Number(value)} 万`;
  41. return String(value ?? '');
  42. }
  43. function customerStage(conversation, fieldCount) {
  44. const summary = conversation.customerIntelligence?.summary || {};
  45. if (summary.highAlerts > 0) return { key: 'priority', label: '重点跟进' };
  46. if (summary.openTasks > 0 && Number(conversation.analysis?.completenessScore || 0) >= 50) return { key: 'qualified', label: '需求已成形' };
  47. if (fieldCount > 0) return { key: 'profiling', label: '画像积累中' };
  48. return { key: 'new', label: '待完善' };
  49. }
  50. function hasProfileValue(profile, ...keys) {
  51. return keys.some(key => {
  52. const value = profile?.[key];
  53. return Array.isArray(value) ? value.length > 0 : value !== undefined && value !== null && String(value).trim() !== '' && String(value).trim() !== '待确认';
  54. });
  55. }
  56. function recommendationStatusLabel(status) {
  57. return ({ candidate: 'Agent 候选', recommended: '已推荐·待反馈', interested: '客户感兴趣', rejected: '客户不合适', viewing: '已约带看', viewed: '已带看', closed: '已关闭' })[status] || status || '待确认';
  58. }
  59. function maskPhone(phone) {
  60. const text = String(phone || '').trim();
  61. if (!text) return '';
  62. if (text.length <= 7) return text;
  63. return `${text.slice(0, 3)}****${text.slice(-4)}`;
  64. }
  65. function fallbackConversation(customerOps) {
  66. const displayName = customerOps.name || customerOps.phone || String(customerOps.externalUserId || '').slice(-6) || '未命名客户';
  67. const maskedId = customerOps.phone ? maskPhone(customerOps.phone) : String(customerOps.externalUserId || '');
  68. const source = customerOps.source === 'group-member' ? '群成员发现' : '客户运营导入';
  69. const now = customerOps.updatedAt || new Date().toISOString();
  70. return {
  71. id: `co:${String(customerOps.customerId || customerOps.externalUserId || '')}`,
  72. displayName,
  73. maskedId,
  74. source,
  75. mode: 'customer-ops',
  76. customerIntelligence: {
  77. profile: {},
  78. profileEvidence: {},
  79. tags: Array.isArray(customerOps.tags) ? customerOps.tags : [],
  80. tasks: [],
  81. alerts: [],
  82. recommendations: [],
  83. summary: {},
  84. },
  85. analysis: { completenessScore: 0 },
  86. messages: [],
  87. updatedAt: now,
  88. lastMessageAt: customerOps.lastSeenInGroupAt || now,
  89. };
  90. }
  91. function getFallbackCustomers() {
  92. try {
  93. const state = readState();
  94. const customers = Object.values(state.customers || {});
  95. if (!customers.length) return [];
  96. return customers
  97. .filter(customer => customer.customerId || customer.externalUserId)
  98. .map(customer => {
  99. const normalized = normalizeCustomer(fallbackConversation(customer));
  100. normalized.fallback = true;
  101. normalized.friendRequestStatus = customer.friendRequestStatus;
  102. normalized.groupStatus = customer.groupStatus;
  103. normalized.externalUserId = String(customer.externalUserId || customer.customerId || '');
  104. normalized.phone = customer.phone || '';
  105. normalized.sourceRoomIds = Array.isArray(customer.sourceRoomIds) ? customer.sourceRoomIds : [];
  106. normalized.groupNames = Array.isArray(customer.groupNames) ? customer.groupNames : [];
  107. return normalized;
  108. })
  109. .sort((a, b) => String(b.lastMessageAt || '').localeCompare(String(a.lastMessageAt || '')));
  110. } catch (err) {
  111. return [];
  112. }
  113. }
  114. function buildNextActions(customer) {
  115. const actions = [];
  116. 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' });
  117. const profile = customer.profile || {};
  118. const openTaskEvidence = customer.tasks.find(task => ['open', 'in_progress'].includes(task.status))?.evidence;
  119. if (!hasProfileValue(profile, 'intent', 'purpose')) add('confirm-purpose', '确认购置用途', '询问客户是自住、投资还是为家人购置,再调整房源权重和沟通重点。', [openTaskEvidence, '客户主档中购置用途尚未确认'], 'high');
  120. if (!hasProfileValue(profile, 'timeline')) add('confirm-timeline', '确认购置时间', '确认客户计划何时购置,以判断跟进频率和是否需要安排带看。', [openTaskEvidence, '客户主档中购置时间尚未确认'], 'high');
  121. if (!hasProfileValue(profile, 'floorPreference')) add('confirm-floor', '补充楼层偏好', '在继续扩大推荐前确认楼层、电梯和采光偏好。', ['现有画像已有区域、预算和户型,但没有楼层偏好'], 'medium');
  122. if (String(profile.budgetType || '') === '待确认') add('confirm-budget-type', '确认预算口径', '确认 200 万是总价上限、理想预算还是包含税费装修。', [`预算已记录为 ${profile.budgetWan || '-'} 万,但预算口径为待确认`], 'medium');
  123. const awaitingFeedback = customer.recommendations.filter(item => item.status === 'recommended');
  124. if (awaitingFeedback.length) add('collect-property-feedback', '收集已推荐房源反馈', `已有 ${awaitingFeedback.length} 套房源处于“已推荐·待反馈”,先确认喜欢和排斥点再继续匹配。`, awaitingFeedback.slice(0, 3).map(item => `${item.property.community || item.propertyId} · ${item.property.totalPrice || '-'} 万`), 'high');
  125. if (!customer.recommendations.length && customer.completenessScore >= 50) add('prepare-first-shortlist', '生成首轮重点方案', '核心需求已基本成形,可从房源库筛选 2—3 套差异化方案供客户比较。', customer.fields.slice(0, 4).map(field => `${field.label}:${field.displayValue}`), 'medium');
  126. 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');
  127. return actions.slice(0, 6);
  128. }
  129. function buildTimeline(customer) {
  130. const events = [];
  131. for (const message of customer.messages || []) {
  132. 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 });
  133. }
  134. 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 });
  135. 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 });
  136. 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 });
  137. for (const recommendation of customer.recommendations || []) events.push({ id: `recommendation:${recommendation.id}`, type: 'property', title: `房源${recommendationStatusLabel(recommendation.status)}`, description: `${recommendation.property.community || recommendation.propertyId} · ${recommendation.property.totalPrice || '-'} 万${recommendation.feedbackReason ? ` · ${recommendation.feedbackReason}` : ''}`, occurredAt: recommendation.lastRecommendedAt, source: 'property-recommendation', status: recommendation.status, fact: true });
  138. return events.filter(item => item.occurredAt).sort((a, b) => String(b.occurredAt).localeCompare(String(a.occurredAt))).slice(0, 80);
  139. }
  140. function normalizeCustomer(conversation) {
  141. const intelligence = conversation.customerIntelligence || {};
  142. const profile = intelligence.profile || {};
  143. const profileEvidence = intelligence.profileEvidence || {};
  144. const fields = Object.entries(profile).filter(([key]) => !key.startsWith('__') && key !== 'propertyFeedback').map(([key, value]) => ({
  145. key,
  146. label: FIELD_LABELS[key] || key,
  147. value,
  148. displayValue: profileValue(value, key),
  149. evidence: profileEvidence[key] ? {
  150. text: String(profileEvidence[key].text || ''),
  151. sourceMessageId: profileEvidence[key].sourceMessageId || null,
  152. source: profileEvidence[key].source || (profileEvidence[key].sourceMessageId ? 'live-message' : 'unknown'),
  153. updatedAt: profileEvidence[key].updatedAt || null,
  154. } : null,
  155. }));
  156. const stage = customerStage(conversation, fields.length);
  157. const messages = conversation.messages || [];
  158. const latestMessage = messages.at(-1) || null;
  159. const tasks = intelligence.tasks || [];
  160. const alerts = intelligence.alerts || [];
  161. const recommendations = (intelligence.recommendations || []).map(item => ({ ...item, statusLabel: recommendationStatusLabel(item.status) }));
  162. const evidenced = fields.filter(item => item.evidence?.text).length;
  163. const customer = {
  164. id: conversation.id,
  165. externalUserId: conversation.channelId || conversation.contactId || '',
  166. displayName: conversation.displayName,
  167. maskedId: conversation.maskedId,
  168. source: conversation.source === 'live' ? '真实企微会话' : conversation.source,
  169. mode: conversation.mode,
  170. stage,
  171. profile,
  172. fields,
  173. tags: intelligence.tags || [],
  174. completenessScore: Number(conversation.analysis?.completenessScore || 0),
  175. evidenceCoverage: fields.length ? Math.round(evidenced / fields.length * 100) : 0,
  176. profileUpdatedAt: intelligence.profileUpdatedAt || conversation.updatedAt || null,
  177. lastMessageAt: conversation.lastMessageAt,
  178. latestMessage: latestMessage ? { role: latestMessage.role, content: latestMessage.content, timestamp: latestMessage.timestamp } : null,
  179. messages,
  180. messageCount: messages.length,
  181. tasks,
  182. alerts,
  183. recommendations,
  184. openTaskCount: tasks.filter(item => ['open', 'in_progress'].includes(item.status)).length,
  185. openAlertCount: alerts.filter(item => item.status === 'open').length,
  186. highAlertCount: alerts.filter(item => item.status === 'open' && ['high', 'critical'].includes(item.severity)).length,
  187. recommendationCount: recommendations.length,
  188. pendingFeedbackCount: recommendations.filter(item => item.status === 'recommended').length,
  189. actions: { openConversation: true, editProfile: true },
  190. };
  191. customer.nextActions = buildNextActions(customer);
  192. customer.timeline = buildTimeline(customer);
  193. return customer;
  194. }
  195. function createCustomerMasterService(dependencies = {}) {
  196. const conversationReader = dependencies.getConversations || getConversations;
  197. const profileUpdater = dependencies.updateCustomerProfile || updateCustomerProfile;
  198. const recommendationFeedbackUpdater = dependencies.updateCustomerRecommendation || updateCustomerRecommendation;
  199. const projectionPath = path.resolve(dependencies.projectionPath || path.join(outputsRoot(), 'customers', 'index.json'));
  200. function persistProjection(customers) {
  201. const snapshot = {
  202. version: 1,
  203. updatedAt: new Date().toISOString(),
  204. customers: customers.map(customer => ({
  205. id: customer.id,
  206. displayName: customer.displayName,
  207. maskedId: customer.maskedId,
  208. source: customer.source,
  209. stage: customer.stage,
  210. profile: customer.profile,
  211. tags: customer.tags,
  212. completenessScore: customer.completenessScore,
  213. evidenceCoverage: customer.evidenceCoverage,
  214. profileUpdatedAt: customer.profileUpdatedAt,
  215. lastMessageAt: customer.lastMessageAt,
  216. openTaskCount: customer.openTaskCount,
  217. openAlertCount: customer.openAlertCount,
  218. recommendationCount: customer.recommendationCount,
  219. pendingFeedbackCount: customer.pendingFeedbackCount,
  220. })),
  221. };
  222. writeJsonAtomic(projectionPath, snapshot);
  223. return snapshot.updatedAt;
  224. }
  225. function hub() {
  226. const result = conversationReader() || {};
  227. const conversations = result.data?.conversations || [];
  228. let customers = conversations.map(normalizeCustomer).sort((a, b) => String(b.lastMessageAt || '').localeCompare(String(a.lastMessageAt || '')));
  229. let fallback = false;
  230. if (!customers.length) {
  231. customers = getFallbackCustomers();
  232. fallback = customers.length > 0;
  233. }
  234. const projectedAt = persistProjection(customers);
  235. const profiledCount = customers.filter(item => item.fields.length).length;
  236. return okResult({
  237. assistantMessage: fallback
  238. ? `客户主档暂无真实企微会话客户,已自动从客户运营数据展示 ${customers.length} 位客户作为参考。`
  239. : `客户管理已汇总 ${customers.length} 位真实会话客户,其中 ${profiledCount} 位已形成画像。`,
  240. summary: {
  241. customerCount: customers.length,
  242. profiledCount,
  243. priorityCount: customers.filter(item => item.stage.key === 'priority').length,
  244. openTaskCount: customers.reduce((sum, item) => sum + item.openTaskCount, 0),
  245. openAlertCount: customers.reduce((sum, item) => sum + item.openAlertCount, 0),
  246. recommendationCount: customers.reduce((sum, item) => sum + item.recommendationCount, 0),
  247. pendingFeedbackCount: customers.reduce((sum, item) => sum + item.pendingFeedbackCount, 0),
  248. projectedAt,
  249. fallback,
  250. },
  251. data: {
  252. customers,
  253. policy: {
  254. canonicalStore: fallback ? '客户运营数据(会话主账为空时的参考视图)' : 'SQLite 客户画像主账',
  255. autoSync: fallback
  256. ? '当前展示的是客户运营导入/群成员发现数据;同步真实企微会话后,画像与任务会自动沉淀到这里。'
  257. : '真实企微消息经 Agent 提取后自动更新客户主档;画像与标签工具也回写同一主账。',
  258. evidence: '客户原话证据只在本机管理页面显示;导出的客户投影不复制原话。',
  259. nextAction: '下一步行动属于规则或 AI 建议,不自动发送、不自动改写客户事实。',
  260. },
  261. },
  262. files: [projectionPath],
  263. });
  264. }
  265. function update(conversationId, input = {}) {
  266. const id = String(conversationId || '').trim();
  267. if (!id) return errorResult('缺少客户主档 ID。');
  268. const result = profileUpdater(id, input);
  269. if (result?.status !== 'ok') return result;
  270. const refreshed = hub();
  271. return okResult({
  272. assistantMessage: result.assistantMessage || '客户主档已更新。',
  273. summary: result.summary,
  274. data: { customer: refreshed.data.customers.find(item => item.id === id) || null },
  275. files: refreshed.files,
  276. });
  277. }
  278. function updateRecommendation(conversationId, recommendationId, input = {}) {
  279. const result = recommendationFeedbackUpdater(String(conversationId || ''), String(recommendationId || ''), input);
  280. if (result?.status !== 'ok') return result;
  281. const refreshed = hub();
  282. return okResult({
  283. assistantMessage: result.assistantMessage || '房源反馈已记录。',
  284. summary: result.summary,
  285. data: { customer: refreshed.data.customers.find(item => item.id === String(conversationId)) || null },
  286. files: refreshed.files,
  287. });
  288. }
  289. return { hub, update, updateRecommendation };
  290. }
  291. const service = createCustomerMasterService();
  292. module.exports = {
  293. createCustomerMasterService,
  294. getCustomerMasterHub: service.hub,
  295. updateCustomerMaster: service.update,
  296. updateCustomerRecommendationFeedback: service.updateRecommendation,
  297. __testing: { normalizeCustomer, customerStage, profileValue, buildNextActions, buildTimeline, recommendationStatusLabel },
  298. };