智能客户管理助手 - 销售团队的效率神器
- 项目概述
实际应用场景
在快节奏的商业环境中,销售团队和客户服务人员面临着复杂的客户关系管理挑战。传统CRM系统虽然功能强大,但对于中小团队来说往往过于复杂,而简单的表格管理又无法满足精细化运营的需求。
典型场景:
- 销售代表需要管理数十个潜在客户,每个客户都有不同的跟进周期
- 客户沟通记录散落在微信、邮件、电话中,难以形成完整视图
- 重要客户的生日、续约日、产品到期日容易遗漏
- 销售经理需要定期了解团队客户跟进情况,但缺乏自动化报告
- 新人接手老客户时,需要快速了解历史沟通背景
痛点分析
-
信息碎片化: 客户信息分散在不同平台,缺乏统一管理
-
跟进不及时: 缺乏智能提醒,重要客户被遗漏
-
历史追溯难: 无法快速了解客户完整沟通历史
-
报告制作繁琐: 每周/月需要手工统计客户跟进数据
-
团队协作差: 客户信息共享不及时,容易产生撞单或遗漏
-
数据分析弱: 缺乏对客户转化漏斗的深度分析
-
核心逻辑
系统架构设计
数据输入层 → 业务逻辑层 → 智能提醒层 → 报告生成层 → 可视化展示层 ↓ ↓ ↓ ↓ ↓ 客户录入 跟进逻辑 定时任务 数据分析 图表展示 沟通记录 状态流转 推送通知 模板渲染 仪表盘 标签管理 优先级排序 日历集成 导出功能 实时监控
关键技术算法
- 客户优先级评分算法
priority_score = ( urgency_weight * urgency_score + value_weight * customer_value_score + engagement_weight * engagement_score + stage_weight * pipeline_stage_score + behavior_weight * interaction_frequency_score )
- 智能提醒时机算法
基于客户生命周期和上次互动时间的动态提醒:
- 新客户:3天后初次跟进
- 意向客户:每周跟进
- 报价阶段:48小时内确认
- 成交客户:月度关怀
- RFM客户价值模型
- Recency(最近购买):客户最后一次互动距今天数
- Frequency(购买频次):单位时间内互动次数
- Monetary(互动价值):预估客户价值和影响力
- 沟通有效性评估
通过分析沟通记录的:
- 回复时间间隔
- 互动频率变化
- 关键词情感倾向
- 承诺兑现情况
- 代码实现
项目结构
smart_crm_assistant/ ├── main.py # 主程序入口 ├── config/ # 配置模块 │ ├── settings.py # 系统设置 │ └── constants.py # 常量定义 ├── models/ # 数据模型 │ ├── customer.py # 客户模型 │ ├── communication.py # 沟通记录模型 │ ├── follow_up.py # 跟进计划模型 │ └── report.py # 报告模型 ├── services/ # 业务服务 │ ├── crm_service.py # CRM核心服务 │ ├── notification_service.py # 通知服务 │ ├── report_service.py # 报告服务 │ └── analytics_service.py # 分析服务 ├── utils/ # 工具函数 │ ├── data_validator.py # 数据验证 │ ├── date_utils.py # 日期处理 │ ├── file_exporter.py # 文件导出 │ └── text_analyzer.py # 文本分析 ├── data/ # 数据存储 │ ├── customers.json # 客户数据 │ ├── communications.json # 沟通记录 │ └── follow_ups.json # 跟进计划 ├── templates/ # 报告模板 │ ├── daily_report.html │ ├── weekly_report.html │ └── customer_detail.html ├── exports/ # 导出文件 └── logs/ # 日志文件
核心代码实现
main.py - 主程序
#!/usr/bin/env python3 """ 智能客户管理助手 帮助销售团队高效管理客户关系,提升业绩表现 """
import sys import json import argparse from datetime import datetime, timedelta from typing import List, Dict, Optional, Tuple from pathlib import Path import os import logging from dataclasses import asdict import schedule import time import threading
导入自定义模块
from config.settings import SystemConfig from models.customer import Customer, CustomerStatus, CustomerPriority from models.communication import Communication, CommunicationType from models.follow_up import FollowUpPlan, FollowUpType from services.crm_service import CRMCoreService from services.notification_service import NotificationService from services.report_service import ReportService from services.analytics_service import AnalyticsService from utils.data_validator import DataValidator from utils.date_utils import DateUtils from utils.file_exporter import FileExporter from utils.text_analyzer import TextAnalyzer
class SmartCRMAssistant: """智能CRM助手主控制器"""
def __init__(self, config_path: str = "config/settings.py"):
"""初始化系统"""
# 配置日志
self._setup_logging()
# 加载配置
self.config = SystemConfig(config_path)
# 初始化服务
self.crm_service = CRMCoreService()
self.notification_service = NotificationService()
self.report_service = ReportService()
self.analytics_service = AnalyticsService()
# 初始化工具
self.validator = DataValidator()
self.date_utils = DateUtils()
self.exporter = FileExporter()
self.text_analyzer = TextAnalyzer()
# 启动后台服务
self._start_background_services()
self.logger.info("智能客户管理助手启动成功!")
def run(self, mode: str = "interactive"):
"""
运行主程序
Args:
mode: 运行模式 (interactive/batch/daemon/report)
"""
try:
if mode == "interactive":
self._run_interactive_mode()
elif mode == "batch":
self._run_batch_mode()
elif mode == "daemon":
self._run_daemon_mode()
elif mode == "report":
self._generate_reports()
else:
self.logger.error(f"未知的运行模式: {mode}")
except KeyboardInterrupt:
self.logger.info("用户中断程序")
except Exception as e:
self.logger.error(f"程序运行错误: {e}")
finally:
self._cleanup()
def _run_interactive_mode(self):
"""交互式模式"""
self._clear_screen()
self._print_welcome()
while True:
self._print_main_menu()
choice = input("\n请选择操作 (0-9): ").strip()
if choice == "1":
self._add_customer()
elif choice == "2":
self._view_customers()
elif choice == "3":
self._add_communication()
elif choice == "4":
self._view_communications()
elif choice == "5":
self._manage_follow_ups()
elif choice == "6":
self._generate_daily_report()
elif choice == "7":
self._view_analytics()
elif choice == "8":
self._export_data()
elif choice == "9":
self._system_settings()
elif choice == "0":
break
else:
self._print_error("无效选择,请重新输入")
def _add_customer(self):
"""添加新客户"""
self._clear_screen()
print("👤 添加新客户")
print("=" * 50)
try:
# 基本信息
name = input("客户姓名*: ").strip()
if not name:
self._print_error("客户姓名不能为空")
return
company = input("公司名称: ").strip()
position = input("职位: ").strip()
phone = input("电话: ").strip()
email = input("邮箱: ").strip()
wechat = input("微信号: ").strip()
# 需求信息
print("\n📋 客户需求信息")
industry = input("所属行业: ").strip()
budget = input("预算范围: ").strip()
timeline = input("期望时间: ").strip()
requirements = input("具体需求: ").strip()
pain_points = input("痛点问题: ").strip()
# 客户分类
print("\n🏷️ 客户分类")
print("1. 潜在客户 2. 意向客户 3. 重点客户 4. 战略客户")
category_choice = input("选择客户类别 (1-4): ").strip()
category_map = {"1": "潜在", "2": "意向", "3": "重点", "4": "战略"}
category = category_map.get(category_choice, "潜在")
# 创建客户对象
customer = Customer(
name=name,
company=company,
position=position,
phone=phone,
email=email,
wechat=wechat,
industry=industry,
budget=budget,
timeline=timeline,
requirements=requirements,
pain_points=pain_points,
category=category,
status=CustomerStatus.NEW
)
# 验证客户信息
validation_result = self.validator.validate_customer(customer)
if not validation_result["valid"]:
self._print_validation_errors(validation_result["errors"])
return
# 保存客户
saved_customer = self.crm_service.add_customer(customer)
if saved_customer:
print(f"\n✅ 客户添加成功!")
print(f"🆔 客户编号: {saved_customer.customer_id}")
print(f"📊 优先级评分: {saved_customer.priority_score:.1f}")
# 询问是否立即添加首次沟通记录
add_comm = input("\n是否添加首次沟通记录?(y/n): ").lower().strip()
if add_comm == 'y':
self._add_initial_communication(saved_customer)
else:
self._print_error("客户添加失败")
except Exception as e:
self.logger.error(f"添加客户错误: {e}")
self._print_error(f"添加失败: {str(e)}")
input("\n按回车键继续...")
def _add_initial_communication(self, customer: Customer):
"""添加初始沟通记录"""
print(f"\n📞 添加与{customer.name}的首次沟通记录")
comm_type = input("沟通方式 (电话/微信/邮件/面谈): ").strip()
content = input("沟通内容: ").strip()
sentiment = input("沟通氛围 (积极/中性/消极): ").strip()
communication = Communication(
customer_id=customer.customer_id,
type=CommunicationType(comm_type.upper()),
content=content,
sentiment=sentiment,
outcome=self._analyze_communication_outcome(content)
)
saved_comm = self.crm_service.add_communication(communication)
if saved_comm:
print("✅ 沟通记录添加成功")
# 更新客户状态和优先级
self.crm_service.update_customer_after_communication(customer.customer_id)
def _manage_follow_ups(self):
"""管理跟进计划"""
self._clear_screen()
print("📅 跟进计划管理")
print("=" * 50)
# 显示今日跟进任务
today_tasks = self.crm_service.get_today_follow_ups()
if today_tasks:
print("📋 今日跟进任务:")
for i, task in enumerate(today_tasks, 1):
customer = self.crm_service.get_customer(task.customer_id)
print(f"{i}. {customer.name} - {task.title}")
print(f" 时间: {task.scheduled_time.strftime('%H:%M')}")
print(f" 方式: {task.method}")
print(f" 备注: {task.notes}")
print()
print("\n🛠️ 跟进计划操作:")
print("1. 查看所有跟进计划")
print("2. 创建新的跟进计划")
print("3. 标记已完成")
print("4. 修改跟进计划")
choice = input("\n请选择操作 (1-4): ").strip()
if choice == "1":
self._view_all_follow_ups()
elif choice == "2":
self._create_follow_up_plan()
elif choice == "3":
self._complete_follow_up()
elif choice == "4":
self._modify_follow_up()
def _create_follow_up_plan(self):
"""创建跟进计划"""
print("\n➕ 创建跟进计划")
# 选择客户
customers = self.crm_service.get_active_customers()
if not customers:
print("暂无活跃客户")
return
print("选择客户:")
for i, customer in enumerate(customers[:10], 1): # 显示前10个
print(f"{i}. {customer.name} ({customer.company})")
try:
customer_index = int(input("选择客户序号: ")) - 1
if not (0 <= customer_index < len(customers)):
self._print_error("无效选择")
return
selected_customer = customers[customer_index]
# 跟进详情
title = input("跟进标题*: ").strip()
method = input("跟进方式 (电话/微信/邮件/面谈): ").strip()
scheduled_date = input("计划日期 (YYYY-MM-DD): ").strip()
scheduled_time = input("计划时间 (HH:MM): ").strip()
notes = input("跟进要点: ").strip()
# 创建跟进计划
follow_up = FollowUpPlan(
customer_id=selected_customer.customer_id,
title=title,
method=method,
scheduled_datetime=datetime.strptime(f"{scheduled_date} {scheduled_time}", "%Y-%m-%d %H:%M"),
notes=notes,
priority=self._calculate_follow_up_priority(selected_customer)
)
saved_plan = self.crm_service.add_follow_up_plan(follow_up)
if saved_plan:
print("✅ 跟进计划创建成功")
# 设置提醒
reminder_minutes = int(input("提前多少分钟提醒?(默认60): ") or "60")
self.notification_service.schedule_reminder(saved_plan, reminder_minutes)
except ValueError as e:
self._print_error(f"输入格式错误: {e}")
except Exception as e:
self.logger.error(f"创建跟进计划错误: {e}")
self._print_error(f"创建失败: {str(e)}")
def _generate_daily_report(self):
"""生成日报"""
self._clear_screen()
print("📊 生成客户跟进日报")
print("=" * 50)
# 选择报告日期
date_str = input("报告日期 (YYYY-MM-DD, 留空为今天): ").strip()
report_date = datetime.now().date()
if date_str:
try:
report_date = datetime.strptime(date_str, "%Y-%m-%d").date()
except ValueError:
self._print_error("日期格式错误")
return
# 生成报告
try:
report = self.report_service.generate_daily_report(report_date)
# 显示报告摘要
self._display_daily_report_summary(report)
# 保存报告
save_path = self.exporter.export_daily_report(report, report_date)
print(f"\n📄 报告已保存至: {save_path}")
# 询问是否发送邮件
send_email = input("\n是否发送邮件给团队?(y/n): ").lower().strip()
if send_email == 'y':
recipients = input("收件人邮箱 (多个用逗号分隔): ").strip()
self.report_service.send_report_email(report, recipients.split(","))
print("✅ 邮件发送成功")
except Exception as e:
self.logger.error(f"生成日报错误: {e}")
self._print_error(f"生成失败: {str(e)}")
input("\n按回车键继续...")
def _view_analytics(self):
"""查看数据分析"""
self._clear_screen()
print("📈 数据分析中心")
print("=" * 50)
print("📊 分析维度:")
print("1. 客户转化率分析")
print("2. 销售漏斗分析")
print("3. 客户价值分析")
print("4. 跟进效率分析")
print("5. 沟通效果分析")
print("6. 团队绩效对比")
choice = input("\n请选择分析维度 (1-6): ").strip()
try:
analytics_data = {}
if choice == "1":
analytics_data = self.analytics_service.analyze_conversion_rate()
self._display_conversion_analysis(analytics_data)
elif choice == "2":
analytics_data = self.analytics_service.analyze_sales_funnel()
self._display_funnel_analysis(analytics_data)
elif choice == "3":
analytics_data = self.analytics_service.analyze_customer_value()
self._display_value_analysis(analytics_data)
elif choice == "4":
analytics_data = self.analytics_service.analyze_follow_up_efficiency()
self._display_efficiency_analysis(analytics_data)
elif choice == "5":
analytics_data = self.analytics_service.analyze_communication_effectiveness()
self._display_communication_analysis(analytics_data)
elif choice == "6":
analytics_data = self.analytics_service.analyze_team_performance()
self._display_team_analysis(analytics_data)
# 导出分析数据
export_choice = input("\n是否导出分析数据?(y/n): ").lower().strip()
if export_choice == 'y':
export_format = input("导出格式 (excel/csv/pdf): ").strip() or "excel"
filepath = self.exporter.export_analytics_data(analytics_data, export_format)
print(f"✅ 数据已导出至: {filepath}")
except Exception as e:
self.logger.error(f"数据分析错误: {e}")
self._print_error(f"分析失败: {str(e)}")
input("\n按回车键继续...")
def _calculate_follow_up_priority(self, customer: Customer) -> int:
"""计算跟进优先级"""
priority = 5 # 默认优先级
# 基于客户状态和优先级评分调整
if customer.status == CustomerStatus.HOT:
priority += 3
elif customer.status == CustomerStatus.WARM:
priority += 2
elif customer.status == CustomerStatus.COLD:
priority -= 1
# 基于优先级评分调整
if customer.priority_score > 80:
priority += 2
elif customer.priority_score > 60:
priority += 1
elif customer.priority_score < 40:
priority -= 1
return max(1, min(10, priority))
def _analyze_communication_outcome(self, content: str) -> str:
"""分析沟通结果"""
content_lower = content.lower()
positive_keywords = ["同意", "感兴趣", "考虑", "见面", "试用", "演示"]
negative_keywords = ["不需要", "不考虑", "价格高", "已有供应商", "暂时搁置"]
positive_count = sum(1 for kw in positive_keywords if kw in content_lower)
negative_count = sum(1 for kw in negative_keywords if kw in content_lower)
if positive_count > negative_count:
return "POSITIVE"
elif negative_count > positive_count:
return "NEGATIVE"
else:
return "NEUTRAL"
def _display_daily_report_summary(self, report: Dict):
"""显示日报摘要"""
print("\n📋 日报摘要")
print("-" * 30)
print(f"📅 报告日期: {report['date']}")
print(f"👥 新增客户: {report['new_customers']} 个")
print(f"📞 沟通次数: {report['communications_count']} 次")
print(f"📅 跟进任务: {report['follow_ups_completed']}/{report['follow_ups_planned']} 完成")
print(f"💰 成交金额: ¥{report['deals_closed_amount']:,.2f}")
print(f"🎯 转化率: {report['conversion_rate']:.1f}%")
if report['hot_leads']:
print(f"\n🔥 热门线索 ({len(report['hot_leads'])}个):")
for lead in report['hot_leads'][:3]:
print(f" • {lead['name']} - {lead['company']}")
def _run_daemon_mode(self):
"""守护进程模式"""
print("🔄 启动守护进程模式...")
print("按 Ctrl+C 停止服务")
# 启动定时任务调度器
scheduler_thread = threading.Thread(target=self._run_scheduler)
scheduler_thread.daemon = True
scheduler_thread.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\n👋 守护进程已停止")
def _run_scheduler(self):
"""运行定时任务调度器"""
# 每分钟检查一次待执行的任务
schedule.every().minute.do(self._check_pending_tasks)
# 每天上午9点生成日报
schedule.every().day.at("09:00").do(self._auto_generate_daily_report)
# 每周一上午10点生成周报
schedule.every().monday.at("10:00").do(self._auto_generate_weekly_report)
while True:
schedule.run_pending()
time.sleep(60)
def _check_pending_tasks(self):
"""检查待执行任务"""
# 检查需要提醒的跟进计划
pending_follow_ups = self.crm_service.get_pending_follow_ups()
for follow_up in pending_follow_ups:
if self.notification_service.should_send_reminder(follow_up):
self.notification_service.send_follow_up_reminder(follow_up)
def _auto_generate_daily_report(self):
"""自动生成日报"""
try:
report = self.report_service.generate_daily_report(datetime.now().date())
self.exporter.export_daily_report(report, datetime.now().date())
self.logger.info("日报自动生成完成")
except Exception as e:
self.logger.error(f"自动生成日报失败: {e}")
def _auto_generate_weekly_report(self):
"""自动生成周报"""
try:
report = self.report_service.generate_weekly_report()
self.exporter.export_weekly_report(report)
self.logger.info("周报自动生成完成")
except Exception as e:
self.logger.error(f"自动生成周报失败: {e}")
def _setup_logging(self)
如果你觉得这个工具好用,欢迎关注我!