Commit d457ba85 by sunqi02

feat: 添加企业微信群机器人 webhook URL 配置

1 parent 45f6b9ad
...@@ -14,6 +14,9 @@ COURSE_BASE_URL=http://lessonjump.test.glsx.com.cn/ ...@@ -14,6 +14,9 @@ COURSE_BASE_URL=http://lessonjump.test.glsx.com.cn/
# 检索接口(query) # 检索接口(query)
QUERY_URL=http://192.168.1.71:8104/wiki/query/json QUERY_URL=http://192.168.1.71:8104/wiki/query/json
# 企业微信群机器人 webhook(周报推送)
WECOM_WEBHOOK_URL=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_webhook_key_here
# 数据库 # 数据库
DB_HOST=192.168.3.92 DB_HOST=192.168.3.92
DB_PORT=3308 DB_PORT=3308
......
# customer_info — 客户号码与群组关系服务
客户手机号绑定、推送候选筛选、按推送类型路由消息发送。独立于 Agent 核心运行时,由运营/企微同步触发。
## 目录结构
| 文件 | 职责 |
|------|------|
| `api.py` | FastAPI 路由,4 个端点 |
| `schema.py` | Pydantic 请求/响应 DTO |
| `model.py` | ORM 模型 `CustomerGroupPhone` |
| `service.py` | 核心业务逻辑:同步、绑定、推送候选 |
| `send_service.py` | 按手机号+推送类型查找目标群并发送消息 |
| `weekly_report_service.py` | 客户群周报统计与企业微信群机器人推送 |
| `CLAUDE.md` | 开发指引 |
---
## API 端点
所有端点前缀:`/api/v1/customer-info`
### 1. POST /phone — 手机号绑定
用户在小程序/页面填写手机号后提交绑定。
**请求体:**
```json
{
"group_id": "4BD6DE10053F765A7F161DF36A6E0031901A2DDBF0758730A19ADA8F0B6DD9F8",
"phone": "13800138000"
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `group_id` | string(255) | 群 ID,即 `wecom_customer_groups.group_id` |
| `phone` | string(20) | 手机号码 |
**响应 `200`:**
```json
{
"code": 200,
"message": "success",
"data": { "success": true }
}
```
**错误响应:**
| 状态码 | 说明 |
|--------|------|
| `404` | `group_id` 在 `customer_group_phones` 中不存在 |
**处理逻辑:** 通过 `group_id` 唯一匹配 `CustomerGroupPhone` 记录,写入 `phone` 字段。不要求手机号唯一,一个手机号可绑定多个群。
---
### 2. GET /phone — 查询手机号绑定信息
查询指定群的手机号绑定状态。
**查询参数:**
| 参数 | 类型 | 说明 |
|------|------|------|
| `group_id` | string | 群 ID |
**响应 `200`:**
```json
{
"code": 200,
"message": "success",
"data": {
"id": 1,
"customer_name": "客户名称",
"group_id": "4BD6DE10053F765A7F161DF36A6E0031901A2DDBF0758730A19ADA8F0B6DD9F8",
"group_status": "active",
"phone": "138****8000",
"last_pushed_at": "2026-07-20T10:00:00",
"create_time": "2026-07-01T00:00:00",
"update_time": "2026-07-20T10:00:00"
}
```
> `phone` 字段自动脱敏:11 位手机号中间 4 位替换为 `****`。
**错误响应:**
| 状态码 | 说明 |
|--------|------|
| `404` | 未找到匹配的群记录 |
---
### 3. POST /send-by-phone — 按手机号发送消息
外部服务(运营后台、定时任务等)按手机号查找目标群并通过 IM 发送消息。
**请求体:**
```json
{
"phone": "13800138000",
"content": "您好,这是您关注岗位的最新推送",
"push_type": "course_promotion"
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `phone` | string(20) | 客户手机号 |
| `content` | string | 消息内容 |
| `push_type` | string(50) | 推送类型标识,如 `course_promotion` |
**消息发送链路:**
```
phone → customer_group_phones → [group_id, group_id, ...]
│
push_type → push_type_routes → managed_user_id → wecom_bots.id → bot_id
│
└── wecom_customer_groups.member_bot_ids 过滤
(只保留 group 的 member_bot_ids 包含 bot_id 的群)
```
处理完成后通过 `IMService.send_message()` 逐群发送。
**响应 `200`:**
```json
{
"code": 200,
"message": "success",
"data": {
"success": true,
"message": "处理完成:共 3 个群,成功 2 个",
"details": [
{ "group_id": "group_001", "success": true, "error": null },
{ "group_id": "group_002", "success": true, "error": null },
{ "group_id": "group_003", "success": false, "error": "bot_not_found" }
]
}
}
```
**错误响应:**
| 状态码 | 说明 |
|--------|------|
| `400` | `push_type` 不存在(`SendByPhoneError`),或 `phone` 未绑定任何群 |
| `502` | 所有目标群发送均失败(`IMService` 不可用等) |
**注意事项:**
- `member_bot_ids` 不含目标 `bot_id` 的群静默跳过
- 全部跳过时返回 `200` + `"无匹配的可推送群组"`
- 部分成功时 `data.success` 为 `true`(至少一个群发送成功)
---
### 4. POST /weekly-report/trigger — 触发周报推送
手动触发客户群周报统计并推送到企业微信群机器人(测试用)。
**请求体:** 空
**响应 `200`:**
```json
{
"code": 200,
"message": "success",
"data": {
"stats": {
"total_groups": 120,
"new_groups": 15,
"bound_groups": 80,
"pass_rate": 66.67
},
"content": "# 客户群周报(2026-07-20)\n> 统计周期:过去7天\n\n**新增群数:** 15 个\n**绑定手机号的群数:** 80 个\n**认证通过率:** 66.67%\n**当前总群数:** 120 个\n",
"send_result": { "success": true, "message": "推送成功", "detail": { "errcode": 0 } }
}
}
```
| 字段 | 类型 | 说明 |
|------|------|------|
| `stats.total_groups` | int | 非 `deleted` 状态的总群数 |
| `stats.new_groups` | int | 过去 7 天新增的群数 |
| `stats.bound_groups` | int | 已绑定手机号的群数 |
| `stats.pass_rate` | float | 认证通过率(已绑定 / 总群数 * 100%) |
| `content` | string | 已生成的 Markdown 消息内容 |
| `send_result` | object | 企业微信群机器人 webhook 推送结果 |
> 推送目标为固定 webhook URL,配置在 `weekly_report_service.py:WECOM_WEBHOOK_URL`。
**错误响应:**
| 状态码 | 说明 |
|--------|------|
| `502` | 企业微信群机器人推送 HTTP 请求失败 |
---
## 数据同步流程
```
wecom_customer_groups ──sync_from_customer_groups()──▶ customer_group_phones
│
POST /phone ──bind_phone()──────┤ (phone 字段填充)
│
get_push_candidates() ──────────┤ (phone IS NULL 的记录)
│
mark_pushed() ──────────────────┤ (命中后标记推送时间)
```
同步策略:
1. **Upsert**:`INSERT ... ON DUPLICATE KEY UPDATE`,以 `group_id` 为关联键,更新 `group_status` / `customer_name`
2. **对账**:源表逻辑删除或不存在的群,将目标行标记 `group_status = 'deleted'`
## 推送候选筛选
`get_push_candidates(mode)` 筛选 `phone IS NULL AND group_status = 'active'` 的记录:
| mode | 条件 | 用途 |
|------|------|------|
| `sync` | `last_pushed_at IS NULL` | 同步触发推送 |
| `daily` | 从未推送或上次推送日期非今天 | 每日定时任务 |
## 数据库表:customer_group_phones
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | BIGINT PK | 自增主键 |
| `customer_name` | VARCHAR(255) | 客户名称 |
| `group_id` | VARCHAR(255) UNIQUE | 群 ID(稳定标识) |
| `group_status` | VARCHAR(50) | `active` / `deleted` |
| `phone` | VARCHAR(20) NULL | 手机号 |
| `last_pushed_at` | DATETIME NULL | 最后一次推送时间 |
| `create_time` | DATETIME | 创建时间 |
| `update_time` | DATETIME | 更新时间 |
索引:
| 索引名 | 字段 | 说明 |
|--------|------|------|
| `uk_group_id` | `group_id` | 唯一约束 |
| `idx_phone` | `phone` | 手机号查询加速 |
| `idx_push_candidates` | `group_status + phone + last_pushed_at` | 复合条件查询 |
## 推送类型路由表:push_type_routes
| 字段 | 类型 | 说明 |
|------|------|------|
| `push_type` | VARCHAR(50) UNIQUE | 推送类型标识 |
| `agents_id` | BIGINT | 关联 `ai_agents.id`,仅用于运营管理 |
| `managed_user_id` | INT | 关联 `wecom_bots.id`,定位 bot |
| `is_active` | TINYINT(1) | 是否启用 |
## 被读取方
- **AgentHub**(`app/agent_core/agent_hub.py`)在 `process_message()` 中以 `session_id`(= `group_id`)查询 `phone`,结果缓存在 `_phone_cache` 实例 dict 中,供 `course_recommend` 工具注入到推荐链接 URL。
## 测试
```bash
# 所有 customer_info 测试
PYTHONPATH=. python -m pytest tests/test_customer_info.py tests/test_customer_info_send.py -v --tb=short
# 仅发送测试
PYTHONPATH=. python -m pytest tests/test_customer_info_send.py -v --tb=short
```
from __future__ import annotations from __future__ import annotations
import logging import logging
import os
from datetime import timedelta from datetime import timedelta
from typing import Dict, Any from typing import Dict, Any
...@@ -12,8 +13,9 @@ from app.infrastructure.time import china_now ...@@ -12,8 +13,9 @@ from app.infrastructure.time import china_now
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
WECOM_WEBHOOK_URL = ( WECOM_WEBHOOK_URL = os.getenv(
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=c1357c4b-c802-4b93-93d9-e871301a4015" "WECOM_WEBHOOK_URL",
"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=6a4a519c-db14-41c9-8ef7-8ab780c4ec0b",
) )
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!