const fs = require('fs'); const path = require('path'); const { outputsRoot } = require('../core/output-paths'); const { okResult, errorResult } = require('../core/result-envelope'); const { getConversations, updateCustomerProfile, updateCustomerRecommendation } = require('./agent-service'); const { readState } = require('../core/dashboard-state'); const FIELD_LABELS = { intent: '客户意图', purpose: '购置用途', preferredRegion: '意向区域', region: '意向区域', district: '意向区域', budgetWan: '预算', budgetRange: '预算范围', budgetType: '预算口径', layout: '意向户型', houseType: '意向户型', area: '面积偏好', decoration: '装修偏好', floorPreference: '楼层偏好', timeline: '购置时间', urgency: '紧迫度', keyConcerns: '核心关注', schoolRequirement: '学区需求', decisionMaker: '决策人', loanCapacity: '贷款能力', negotiationStage: '谈判阶段', aiSummary: '画像摘要', }; function ensureDir(dirPath) { fs.mkdirSync(dirPath, { recursive: true }); return dirPath; } function writeJsonAtomic(filePath, value) { ensureDir(path.dirname(filePath)); const tempPath = `${filePath}.${process.pid}.tmp`; fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, 'utf8'); fs.renameSync(tempPath, filePath); } function profileValue(value, field) { if (Array.isArray(value)) return value.join('、'); if (value && typeof value === 'object') return value.note || value.value || JSON.stringify(value); if (field === 'budgetWan' && Number.isFinite(Number(value))) return `${Number(value)} 万`; return String(value ?? ''); } function customerStage(conversation, fieldCount) { const summary = conversation.customerIntelligence?.summary || {}; if (summary.highAlerts > 0) return { key: 'priority', label: '重点跟进' }; if (summary.openTasks > 0 && Number(conversation.analysis?.completenessScore || 0) >= 50) return { key: 'qualified', label: '需求已成形' }; if (fieldCount > 0) return { key: 'profiling', label: '画像积累中' }; return { key: 'new', label: '待完善' }; } function hasProfileValue(profile, ...keys) { return keys.some(key => { const value = profile?.[key]; return Array.isArray(value) ? value.length > 0 : value !== undefined && value !== null && String(value).trim() !== '' && String(value).trim() !== '待确认'; }); } function recommendationStatusLabel(status) { return ({ candidate: 'Agent 候选', recommended: '已推荐·待反馈', interested: '客户感兴趣', rejected: '客户不合适', viewing: '已约带看', viewed: '已带看', closed: '已关闭' })[status] || status || '待确认'; } function maskPhone(phone) { const text = String(phone || '').trim(); if (!text) return ''; if (text.length <= 7) return text; return `${text.slice(0, 3)}****${text.slice(-4)}`; } function fallbackConversation(customerOps) { const displayName = customerOps.name || customerOps.phone || String(customerOps.externalUserId || '').slice(-6) || '未命名客户'; const maskedId = customerOps.phone ? maskPhone(customerOps.phone) : String(customerOps.externalUserId || ''); const source = customerOps.source === 'group-member' ? '群成员发现' : '客户运营导入'; const now = customerOps.updatedAt || new Date().toISOString(); return { id: `co:${String(customerOps.customerId || customerOps.externalUserId || '')}`, displayName, maskedId, source, mode: 'customer-ops', customerIntelligence: { profile: {}, profileEvidence: {}, tags: Array.isArray(customerOps.tags) ? customerOps.tags : [], tasks: [], alerts: [], recommendations: [], summary: {}, }, analysis: { completenessScore: 0 }, messages: [], updatedAt: now, lastMessageAt: customerOps.lastSeenInGroupAt || now, }; } function getFallbackCustomers() { try { const state = readState(); const customers = Object.values(state.customers || {}); if (!customers.length) return []; return customers .filter(customer => customer.customerId || customer.externalUserId) .map(customer => { const normalized = normalizeCustomer(fallbackConversation(customer)); normalized.fallback = true; normalized.friendRequestStatus = customer.friendRequestStatus; normalized.groupStatus = customer.groupStatus; normalized.externalUserId = String(customer.externalUserId || customer.customerId || ''); normalized.phone = customer.phone || ''; normalized.sourceRoomIds = Array.isArray(customer.sourceRoomIds) ? customer.sourceRoomIds : []; normalized.groupNames = Array.isArray(customer.groupNames) ? customer.groupNames : []; return normalized; }) .sort((a, b) => String(b.lastMessageAt || '').localeCompare(String(a.lastMessageAt || ''))); } catch (err) { return []; } } function buildNextActions(customer) { const actions = []; 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' }); const profile = customer.profile || {}; const openTaskEvidence = customer.tasks.find(task => ['open', 'in_progress'].includes(task.status))?.evidence; if (!hasProfileValue(profile, 'intent', 'purpose')) add('confirm-purpose', '确认购置用途', '询问客户是自住、投资还是为家人购置,再调整房源权重和沟通重点。', [openTaskEvidence, '客户主档中购置用途尚未确认'], 'high'); if (!hasProfileValue(profile, 'timeline')) add('confirm-timeline', '确认购置时间', '确认客户计划何时购置,以判断跟进频率和是否需要安排带看。', [openTaskEvidence, '客户主档中购置时间尚未确认'], 'high'); if (!hasProfileValue(profile, 'floorPreference')) add('confirm-floor', '补充楼层偏好', '在继续扩大推荐前确认楼层、电梯和采光偏好。', ['现有画像已有区域、预算和户型,但没有楼层偏好'], 'medium'); if (String(profile.budgetType || '') === '待确认') add('confirm-budget-type', '确认预算口径', '确认 200 万是总价上限、理想预算还是包含税费装修。', [`预算已记录为 ${profile.budgetWan || '-'} 万,但预算口径为待确认`], 'medium'); const awaitingFeedback = customer.recommendations.filter(item => item.status === 'recommended'); if (awaitingFeedback.length) add('collect-property-feedback', '收集已推荐房源反馈', `已有 ${awaitingFeedback.length} 套房源处于“已推荐·待反馈”,先确认喜欢和排斥点再继续匹配。`, awaitingFeedback.slice(0, 3).map(item => `${item.property.community || item.propertyId} · ${item.property.totalPrice || '-'} 万`), 'high'); 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'); 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'); return actions.slice(0, 6); } function buildTimeline(customer) { const events = []; for (const message of customer.messages || []) { 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 }); } 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 }); 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 }); 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 }); 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 }); return events.filter(item => item.occurredAt).sort((a, b) => String(b.occurredAt).localeCompare(String(a.occurredAt))).slice(0, 80); } function normalizeCustomer(conversation) { const intelligence = conversation.customerIntelligence || {}; const profile = intelligence.profile || {}; const profileEvidence = intelligence.profileEvidence || {}; const fields = Object.entries(profile).filter(([key]) => !key.startsWith('__') && key !== 'propertyFeedback').map(([key, value]) => ({ key, label: FIELD_LABELS[key] || key, value, displayValue: profileValue(value, key), evidence: profileEvidence[key] ? { text: String(profileEvidence[key].text || ''), sourceMessageId: profileEvidence[key].sourceMessageId || null, source: profileEvidence[key].source || (profileEvidence[key].sourceMessageId ? 'live-message' : 'unknown'), updatedAt: profileEvidence[key].updatedAt || null, } : null, })); const stage = customerStage(conversation, fields.length); const messages = conversation.messages || []; const latestMessage = messages.at(-1) || null; const tasks = intelligence.tasks || []; const alerts = intelligence.alerts || []; const recommendations = (intelligence.recommendations || []).map(item => ({ ...item, statusLabel: recommendationStatusLabel(item.status) })); const evidenced = fields.filter(item => item.evidence?.text).length; const customer = { id: conversation.id, externalUserId: conversation.channelId || conversation.contactId || '', displayName: conversation.displayName, maskedId: conversation.maskedId, source: conversation.source === 'live' ? '真实企微会话' : conversation.source, mode: conversation.mode, stage, profile, fields, tags: intelligence.tags || [], completenessScore: Number(conversation.analysis?.completenessScore || 0), evidenceCoverage: fields.length ? Math.round(evidenced / fields.length * 100) : 0, profileUpdatedAt: intelligence.profileUpdatedAt || conversation.updatedAt || null, lastMessageAt: conversation.lastMessageAt, latestMessage: latestMessage ? { role: latestMessage.role, content: latestMessage.content, timestamp: latestMessage.timestamp } : null, messages, messageCount: messages.length, tasks, alerts, recommendations, openTaskCount: tasks.filter(item => ['open', 'in_progress'].includes(item.status)).length, openAlertCount: alerts.filter(item => item.status === 'open').length, highAlertCount: alerts.filter(item => item.status === 'open' && ['high', 'critical'].includes(item.severity)).length, recommendationCount: recommendations.length, pendingFeedbackCount: recommendations.filter(item => item.status === 'recommended').length, actions: { openConversation: true, editProfile: true }, }; customer.nextActions = buildNextActions(customer); customer.timeline = buildTimeline(customer); return customer; } function createCustomerMasterService(dependencies = {}) { const conversationReader = dependencies.getConversations || getConversations; const profileUpdater = dependencies.updateCustomerProfile || updateCustomerProfile; const recommendationFeedbackUpdater = dependencies.updateCustomerRecommendation || updateCustomerRecommendation; const projectionPath = path.resolve(dependencies.projectionPath || path.join(outputsRoot(), 'customers', 'index.json')); function persistProjection(customers) { const snapshot = { version: 1, updatedAt: new Date().toISOString(), customers: customers.map(customer => ({ id: customer.id, displayName: customer.displayName, maskedId: customer.maskedId, source: customer.source, stage: customer.stage, profile: customer.profile, tags: customer.tags, completenessScore: customer.completenessScore, evidenceCoverage: customer.evidenceCoverage, profileUpdatedAt: customer.profileUpdatedAt, lastMessageAt: customer.lastMessageAt, openTaskCount: customer.openTaskCount, openAlertCount: customer.openAlertCount, recommendationCount: customer.recommendationCount, pendingFeedbackCount: customer.pendingFeedbackCount, })), }; writeJsonAtomic(projectionPath, snapshot); return snapshot.updatedAt; } function hub() { const result = conversationReader() || {}; const conversations = result.data?.conversations || []; let customers = conversations.map(normalizeCustomer).sort((a, b) => String(b.lastMessageAt || '').localeCompare(String(a.lastMessageAt || ''))); let fallback = false; if (!customers.length) { customers = getFallbackCustomers(); fallback = customers.length > 0; } const projectedAt = persistProjection(customers); const profiledCount = customers.filter(item => item.fields.length).length; return okResult({ assistantMessage: fallback ? `客户主档暂无真实企微会话客户,已自动从客户运营数据展示 ${customers.length} 位客户作为参考。` : `客户管理已汇总 ${customers.length} 位真实会话客户,其中 ${profiledCount} 位已形成画像。`, summary: { customerCount: customers.length, profiledCount, priorityCount: customers.filter(item => item.stage.key === 'priority').length, openTaskCount: customers.reduce((sum, item) => sum + item.openTaskCount, 0), openAlertCount: customers.reduce((sum, item) => sum + item.openAlertCount, 0), recommendationCount: customers.reduce((sum, item) => sum + item.recommendationCount, 0), pendingFeedbackCount: customers.reduce((sum, item) => sum + item.pendingFeedbackCount, 0), projectedAt, fallback, }, data: { customers, policy: { canonicalStore: fallback ? '客户运营数据(会话主账为空时的参考视图)' : 'SQLite 客户画像主账', autoSync: fallback ? '当前展示的是客户运营导入/群成员发现数据;同步真实企微会话后,画像与任务会自动沉淀到这里。' : '真实企微消息经 Agent 提取后自动更新客户主档;画像与标签工具也回写同一主账。', evidence: '客户原话证据只在本机管理页面显示;导出的客户投影不复制原话。', nextAction: '下一步行动属于规则或 AI 建议,不自动发送、不自动改写客户事实。', }, }, files: [projectionPath], }); } function update(conversationId, input = {}) { const id = String(conversationId || '').trim(); if (!id) return errorResult('缺少客户主档 ID。'); const result = profileUpdater(id, input); if (result?.status !== 'ok') return result; const refreshed = hub(); return okResult({ assistantMessage: result.assistantMessage || '客户主档已更新。', summary: result.summary, data: { customer: refreshed.data.customers.find(item => item.id === id) || null }, files: refreshed.files, }); } function updateRecommendation(conversationId, recommendationId, input = {}) { const result = recommendationFeedbackUpdater(String(conversationId || ''), String(recommendationId || ''), input); if (result?.status !== 'ok') return result; const refreshed = hub(); return okResult({ assistantMessage: result.assistantMessage || '房源反馈已记录。', summary: result.summary, data: { customer: refreshed.data.customers.find(item => item.id === String(conversationId)) || null }, files: refreshed.files, }); } return { hub, update, updateRecommendation }; } const service = createCustomerMasterService(); module.exports = { createCustomerMasterService, getCustomerMasterHub: service.hub, updateCustomerMaster: service.update, updateCustomerRecommendationFeedback: service.updateRecommendation, __testing: { normalizeCustomer, customerStage, profileValue, buildNextActions, buildTimeline, recommendationStatusLabel }, };