Commit a45b8b18 by imwangxiaozhou

fix(wecom, analytics): 修复客户群扫描逻辑并优化埋点API文档

优化企微客户群新增客户扫描逻辑,为缺少渠道活码的机器人添加异常捕获,仅记录警告并跳过该机器人,避免整体扫描任务失败
改进内部方法的错误提示文本,使其更直观易懂
为埋点相关的Pydantic模型和API接口添加详细的中文描述、使用示例与接口说明,完善OpenAPI文档内容
新增测试用例,验证无渠道活码机器人的扫描跳过逻辑是否正常工作
1 parent b5770e43
from fastapi import APIRouter, Depends, Query from fastapi import APIRouter, Body, Depends, Query
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from typing import Optional from typing import Optional
from datetime import datetime from datetime import datetime
...@@ -21,17 +21,108 @@ from app.infrastructure.database import get_db ...@@ -21,17 +21,108 @@ from app.infrastructure.database import get_db
router = APIRouter() router = APIRouter()
EVENTS_USAGE = """
用于前端或 H5 批量上报通用行为埋点。
@router.get("/api/v1/logs/conversations", response_model=ConversationLogListResponse) 使用方式:
1. 在页面访问、按钮点击、表单提交、关键业务动作发生后调用。
2. `event_type` 写事件类型,建议使用稳定英文枚举,例如 `page_view`、`button_click`、`form_submit`。
3. `event_data` 放业务字段,例如页面路径、按钮名称、业务 ID、来源渠道。
4. 多条事件可以一次性放入 `events` 数组批量上报。
最小示例:
```json
{
"events": [
{
"event_type": "button_click",
"event_data": {
"page": "official_home",
"button": "open_qrcode"
}
}
]
}
```
"""
PAGE_VIEW_USAGE = """
用于记录页面访问埋点。
使用方式:
1. H5 首页、官网岗位详情页、后台关键页面打开后调用一次。
2. `page_type` 填页面编码,例如 `official_home`、`official_job_tab`。
3. 如果有登录用户或会话,传 `user_id`、`session_id`;匿名访问可以为空。
4. `device_type` 建议传 `pc`、`mobile` 或 `tablet`。
最小示例:
```json
{
"page_type": "official_home",
"session_id": "sess_001",
"device_type": "mobile"
}
```
"""
SCAN_EVENT_USAGE = """
用于记录客户扫码渠道活码的埋点。
使用方式:
1. 客户扫码渠道活码后调用。
2. 优先传 `qrcode_id`;如果当前链路只有渠道编码,也可以传 `channel_code`。
3. 可同时传 `position_code`、`employee_id`、`customer_user_id`,用于后续按岗位、承接员工和客户分析扫码来源。
最小示例:
```json
{
"qrcode_id": 1,
"channel_code": "position_good",
"customer_user_id": "customer_001",
"position_code": "position_good",
"employee_id": "emp_001"
}
```
"""
GROUP_JOIN_USAGE = """
用于记录客户成功入群后的转化埋点。
使用方式:
1. 客户扫码并成功加入企微群后调用。
2. `group_id` 填客户加入的群 ID。
3. `customer_user_id` 填客户用户 ID。
4. `employee_count`、`agent_count` 用于统计该群中的员工和 Agent 配置规模。
5. `channel_code` 用于回溯来源渠道。
最小示例:
```json
{
"group_id": "group_001",
"customer_user_id": "customer_001",
"employee_count": 2,
"agent_count": 1,
"channel_code": "position_good"
}
```
"""
@router.get(
"/api/v1/logs/conversations",
response_model=ConversationLogListResponse,
summary="查询会话日志",
description="查询 Agent 会话日志,用于后台排查用户问题、意图识别、响应内容和错误情况。该接口是日志查询,不是前端埋点上报。",
)
def list_conversation_logs( def list_conversation_logs(
page: int = Query(1, ge=1), page: int = Query(1, ge=1, description="页码,默认 1。"),
page_size: int = Query(20, ge=1, le=100), page_size: int = Query(20, ge=1, le=100, description="每页数量,默认 20,最大 100。"),
user_id: Optional[str] = Query(None), user_id: Optional[str] = Query(None, description="按用户 ID 筛选会话日志。"),
agent_id: Optional[int] = Query(None), agent_id: Optional[int] = Query(None, description="按 Agent ID 筛选会话日志。"),
intent_type: Optional[str] = Query(None), intent_type: Optional[str] = Query(None, description="按意图类型筛选。"),
time_start: Optional[datetime] = Query(None), time_start: Optional[datetime] = Query(None, description="开始时间,ISO datetime。"),
time_end: Optional[datetime] = Query(None), time_end: Optional[datetime] = Query(None, description="结束时间,ISO datetime。"),
has_error: Optional[bool] = Query(None), has_error: Optional[bool] = Query(None, description="是否只查询异常会话。"),
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
svc = AnalyticsService(db) svc = AnalyticsService(db)
...@@ -48,25 +139,76 @@ def list_conversation_logs( ...@@ -48,25 +139,76 @@ def list_conversation_logs(
) )
@router.post("/api/v1/analytics/events", response_model=AnalyticsEventResponse) @router.post(
def upload_analytics_events(req: AnalyticsEventRequest, db: Session = Depends(get_db)): "/api/v1/analytics/events",
response_model=AnalyticsEventResponse,
summary="批量上报通用埋点事件",
description=EVENTS_USAGE,
)
def upload_analytics_events(
req: AnalyticsEventRequest = Body(
...,
openapi_examples={
"button_click": {
"summary": "按钮点击埋点",
"value": {
"events": [
{
"event_type": "button_click",
"event_data": {
"page": "official_home",
"button": "open_qrcode",
},
}
]
},
}
},
),
db: Session = Depends(get_db),
):
svc = AnalyticsService(db) svc = AnalyticsService(db)
events_data = [ev.model_dump() for ev in req.events] events_data = [ev.model_dump() for ev in req.events]
return svc.upload_events(events_data) return svc.upload_events(events_data)
@router.get("/api/v1/analytics/statistics", response_model=AnalyticsStatisticsResponse) @router.get(
"/api/v1/analytics/statistics",
response_model=AnalyticsStatisticsResponse,
summary="查询埋点统计数据",
description="查询埋点和会话统计概览,包括 Agent 调用量、会话数、意图分布、Agent 调用排行和趋势数据。",
)
def get_analytics_statistics( def get_analytics_statistics(
date_range: str = Query("last_7_days"), date_range: str = Query("last_7_days", description="统计时间范围,例如 last_7_days。"),
group_by: Optional[str] = Query(None), group_by: Optional[str] = Query(None, description="可选分组维度。"),
db: Session = Depends(get_db), db: Session = Depends(get_db),
): ):
svc = AnalyticsService(db) svc = AnalyticsService(db)
return svc.get_statistics(date_range=date_range, group_by=group_by) return svc.get_statistics(date_range=date_range, group_by=group_by)
@router.post("/api/v1/agent-group/analytics/page-view", response_model=PageViewResponse) @router.post(
def record_page_view(req: PageViewRequest, db: Session = Depends(get_db)): "/api/v1/agent-group/analytics/page-view",
response_model=PageViewResponse,
summary="上报页面访问埋点",
description=PAGE_VIEW_USAGE,
)
def record_page_view(
req: PageViewRequest = Body(
...,
openapi_examples={
"official_home": {
"summary": "官网首页访问",
"value": {
"page_type": "official_home",
"session_id": "sess_001",
"device_type": "mobile",
},
}
},
),
db: Session = Depends(get_db),
):
svc = AnalyticsService(db) svc = AnalyticsService(db)
return svc.record_page_view( return svc.record_page_view(
page_type=req.page_type, page_type=req.page_type,
...@@ -76,8 +218,30 @@ def record_page_view(req: PageViewRequest, db: Session = Depends(get_db)): ...@@ -76,8 +218,30 @@ def record_page_view(req: PageViewRequest, db: Session = Depends(get_db)):
) )
@router.post("/api/v1/agent-group/analytics/scan-event", response_model=ScanEventResponse) @router.post(
def record_scan_event(req: ScanEventRequest, db: Session = Depends(get_db)): "/api/v1/agent-group/analytics/scan-event",
response_model=ScanEventResponse,
summary="上报扫码埋点",
description=SCAN_EVENT_USAGE,
)
def record_scan_event(
req: ScanEventRequest = Body(
...,
openapi_examples={
"qrcode_scan": {
"summary": "客户扫码渠道活码",
"value": {
"qrcode_id": 1,
"channel_code": "position_good",
"customer_user_id": "customer_001",
"position_code": "position_good",
"employee_id": "emp_001",
},
}
},
),
db: Session = Depends(get_db),
):
svc = AnalyticsService(db) svc = AnalyticsService(db)
return svc.record_scan_event( return svc.record_scan_event(
qrcode_id=req.qrcode_id, qrcode_id=req.qrcode_id,
...@@ -88,8 +252,30 @@ def record_scan_event(req: ScanEventRequest, db: Session = Depends(get_db)): ...@@ -88,8 +252,30 @@ def record_scan_event(req: ScanEventRequest, db: Session = Depends(get_db)):
) )
@router.post("/api/v1/agent-group/analytics/group-join-success", response_model=GroupJoinEventResponse) @router.post(
def record_group_join_event(req: GroupJoinEventRequest, db: Session = Depends(get_db)): "/api/v1/agent-group/analytics/group-join-success",
response_model=GroupJoinEventResponse,
summary="上报入群成功埋点",
description=GROUP_JOIN_USAGE,
)
def record_group_join_event(
req: GroupJoinEventRequest = Body(
...,
openapi_examples={
"group_join": {
"summary": "客户入群成功",
"value": {
"group_id": "group_001",
"customer_user_id": "customer_001",
"employee_count": 2,
"agent_count": 1,
"channel_code": "position_good",
},
}
},
),
db: Session = Depends(get_db),
):
svc = AnalyticsService(db) svc = AnalyticsService(db)
return svc.record_group_join_event( return svc.record_group_join_event(
group_id=req.group_id, group_id=req.group_id,
......
...@@ -26,13 +26,13 @@ class ConversationLogListResponse(BaseModel): ...@@ -26,13 +26,13 @@ class ConversationLogListResponse(BaseModel):
class AnalyticsEventItem(BaseModel): class AnalyticsEventItem(BaseModel):
event_type: str = Field(..., max_length=64) event_type: str = Field(..., max_length=64, description="埋点事件类型,例如 page_view、button_click、scan。")
event_data: Optional[Dict[str, Any]] = None event_data: Optional[Dict[str, Any]] = Field(None, description="事件扩展数据,按 event_type 保存业务字段。")
timestamp: Optional[datetime] = None timestamp: Optional[datetime] = Field(None, description="事件发生时间;不传时以后端接收时间为准。")
class AnalyticsEventRequest(BaseModel): class AnalyticsEventRequest(BaseModel):
events: List[AnalyticsEventItem] = Field(..., min_length=1) events: List[AnalyticsEventItem] = Field(..., min_length=1, description="批量上报的埋点事件列表。")
class AnalyticsEventResponse(BaseModel): class AnalyticsEventResponse(BaseModel):
...@@ -68,11 +68,11 @@ class AnalyticsStatisticsResponse(BaseModel): ...@@ -68,11 +68,11 @@ class AnalyticsStatisticsResponse(BaseModel):
class PageViewRequest(BaseModel): class PageViewRequest(BaseModel):
page_type: str = Field(..., max_length=64) page_type: str = Field(..., max_length=64, description="页面类型或页面编码,例如 official_home。")
user_id: Optional[str] = Field(None, max_length=64) user_id: Optional[str] = Field(None, max_length=64, description="访问用户 ID,匿名访问可为空。")
session_id: Optional[str] = Field(None, max_length=64) session_id: Optional[str] = Field(None, max_length=64, description="访问会话 ID,用于串联同一次访问链路。")
timestamp: Optional[datetime] = None timestamp: Optional[datetime] = Field(None, description="访问发生时间;不传时以后端接收时间为准。")
device_type: Optional[str] = Field(None, max_length=32) device_type: Optional[str] = Field(None, max_length=32, description="设备类型,例如 pc、mobile、tablet。")
class PageViewResponse(BaseModel): class PageViewResponse(BaseModel):
...@@ -80,12 +80,12 @@ class PageViewResponse(BaseModel): ...@@ -80,12 +80,12 @@ class PageViewResponse(BaseModel):
class ScanEventRequest(BaseModel): class ScanEventRequest(BaseModel):
qrcode_id: Optional[int] = None qrcode_id: Optional[int] = Field(None, description="渠道活码 ID。")
channel_code: Optional[str] = Field(None, max_length=128) channel_code: Optional[str] = Field(None, max_length=128, description="渠道编码。")
customer_user_id: Optional[str] = Field(None, max_length=64) customer_user_id: Optional[str] = Field(None, max_length=64, description="客户用户 ID。")
scan_time: Optional[datetime] = None scan_time: Optional[datetime] = Field(None, description="扫码发生时间;不传时以后端接收时间为准。")
position_code: Optional[str] = Field(None, max_length=64) position_code: Optional[str] = Field(None, max_length=64, description="岗位编码。")
employee_id: Optional[str] = Field(None, max_length=64) employee_id: Optional[str] = Field(None, max_length=64, description="承接员工 ID。")
class ScanEventResponse(BaseModel): class ScanEventResponse(BaseModel):
...@@ -93,12 +93,12 @@ class ScanEventResponse(BaseModel): ...@@ -93,12 +93,12 @@ class ScanEventResponse(BaseModel):
class GroupJoinEventRequest(BaseModel): class GroupJoinEventRequest(BaseModel):
group_id: Optional[str] = Field(None, max_length=64) group_id: Optional[str] = Field(None, max_length=64, description="客户加入的群 ID。")
customer_user_id: Optional[str] = Field(None, max_length=64) customer_user_id: Optional[str] = Field(None, max_length=64, description="客户用户 ID。")
employee_count: int = 0 employee_count: int = Field(0, description="入群时群内员工数量。")
agent_count: int = 0 agent_count: int = Field(0, description="入群时关联 Agent 数量。")
join_time: Optional[datetime] = None join_time: Optional[datetime] = Field(None, description="入群成功时间;不传时以后端接收时间为准。")
channel_code: Optional[str] = Field(None, max_length=128) channel_code: Optional[str] = Field(None, max_length=128, description="关联渠道编码。")
class GroupJoinEventResponse(BaseModel): class GroupJoinEventResponse(BaseModel):
......
...@@ -182,7 +182,19 @@ class WeComCustomerGroupOrchestrationService: ...@@ -182,7 +182,19 @@ class WeComCustomerGroupOrchestrationService:
items: list[WeComNewCustomerItem] = [] items: list[WeComNewCustomerItem] = []
seen_contact_ids: set[str] = set() seen_contact_ids: set[str] = set()
for bot_id in resolved_bot_ids: for bot_id in resolved_bot_ids:
for item in self._scan_new_customers_for_bot(bot_id=bot_id): try:
current_items = self._scan_new_customers_for_bot(bot_id=bot_id)
except ValueError as exc:
if "没有对应渠道活码" in str(exc):
logger.warning(
format_job_log(
f"bot_id={bot_id} [当前bot没有对应渠道活码]"
)
)
continue
raise
for item in current_items:
if item.contact_id in seen_contact_ids: if item.contact_id in seen_contact_ids:
continue continue
seen_contact_ids.add(item.contact_id) seen_contact_ids.add(item.contact_id)
...@@ -636,15 +648,15 @@ class WeComCustomerGroupOrchestrationService: ...@@ -636,15 +648,15 @@ class WeComCustomerGroupOrchestrationService:
def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]: def _scan_new_customers_for_bot(self, *, bot_id: str) -> list[WeComNewCustomerItem]:
bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first() bot = self.db.query(WeComBot).filter(WeComBot.bot_id == bot_id).first()
if bot is None: if bot is None:
raise ValueError(f"??? bot_id={bot_id} ??????????") raise ValueError(f"bot_id={bot_id} 不存在对应机器人")
qrcode = self.db.query(QrcodeChannel).filter(QrcodeChannel.wecom_bot_id == bot.id).first() qrcode = self.db.query(QrcodeChannel).filter(QrcodeChannel.wecom_bot_id == bot.id).first()
if qrcode is None: if qrcode is None:
raise ValueError(f"bot_id={bot_id} ???????????????") raise ValueError(f"bot_id={bot_id} 没有对应渠道活码")
position = self.db.query(PositionTag).filter(PositionTag.id == qrcode.position_id).first() position = self.db.query(PositionTag).filter(PositionTag.id == qrcode.position_id).first()
if position is None: if position is None:
raise ValueError(f"bot_id={bot_id} ????????????") raise ValueError(f"bot_id={bot_id} 对应渠道活码未绑定岗位")
resolved_contact_type = WECOM_CUSTOMER_CONTACT_TYPE resolved_contact_type = WECOM_CUSTOMER_CONTACT_TYPE
candidates: list[WeComNewCustomerItem] = [] candidates: list[WeComNewCustomerItem] = []
......
...@@ -1011,6 +1011,59 @@ def test_list_new_customers_raises_clear_error_when_bot_missing(): ...@@ -1011,6 +1011,59 @@ def test_list_new_customers_raises_clear_error_when_bot_missing():
db.close() db.close()
def test_scan_new_customers_skips_bot_without_qrcode_and_continues():
db = _setup_db()
db.add_all(
[
WeComBot(id=1, channel='wt_ww', bot_id='bot_missing_qrcode', bot_code='wt_ww:bot_missing_qrcode', bot_name='bot-missing'),
WeComBot(id=2, channel='wt_ww', bot_id='bot_ok', bot_code='wt_ww:bot_ok', bot_name='bot-ok'),
WeComBot(id=3, channel='wt_ww', bot_id='managed_1', bot_code='wt_ww:managed_1', bot_name='managed-1'),
]
)
position = PositionTag(id=1, name='销售岗', code='sales_role')
db.add(position)
db.add(
QrcodeChannel(
id=1,
qrcode_name='销售岗渠道活码',
position_id=1,
wecom_bot_id=2,
employee_id='bot_ok',
employee_name='bot-ok',
status='enable',
)
)
agent = Agent(id=10, name='复盘 Agent', code='review_agent', managed_user_id=3, status=AgentStatus.enable, is_deleted=False)
db.add(agent)
db.flush()
db.add(AgentPosition(agent_id=10, position_id=1))
db.commit()
class CustomerClient(FakeClient):
def list_customers(self, *, bot_id: str, start_time=None, end_time=None, page: int = 1, page_size: int = 100, contact_type=None, keyword=None):
if bot_id == 'bot_ok':
return {
'items': [
{
'contact_id': 'cust_1',
'contact_name': '张三',
}
],
'meta': {'total': 1, 'page': 1, 'page_size': page_size},
}
return {'items': [], 'meta': {'total': 0, 'page': 1, 'page_size': page_size}}
sync_service = WeComSyncService(db, CustomerClient(), NoopWeComMessageDispatcher())
orchestration_service = WeComCustomerGroupOrchestrationService(db, CustomerClient(), sync_service)
items = orchestration_service.scan_new_customers(bot_ids=['bot_missing_qrcode', 'bot_ok'])
assert len(items) == 1
assert items[0].bot_id == 'bot_ok'
assert items[0].contact_id == 'cust_1'
db.close()
def test_create_groups_raises_clear_error_when_qrcode_missing(): def test_create_groups_raises_clear_error_when_qrcode_missing():
db = _setup_db() db = _setup_db()
bot = WeComBot(id=1, channel='wt_ww', bot_id='bot_1', bot_code='wt_ww:bot_1', bot_name='bot-a') bot = WeComBot(id=1, channel='wt_ww', bot_id='bot_1', bot_code='wt_ww:bot_1', bot_name='bot-a')
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!