Commit 3f7742c4 by sunqi02

feat: Implement customer group phone management service

- 增加同步数据到
- 增加推送链接到功能
- 增加定时任务
1 parent 0c471504
from fastapi import APIRouter from fastapi import APIRouter
from app.api.v1.endpoints import agent_group_helper, agent_hub, agents, position_tags, skills, routing, analytics, qrcode_channel, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology, wecom_sync, wecom_jobs, wecom_debug from app.api.v1.endpoints import agent_group_helper, agent_hub, agents, position_tags, skills, routing, analytics, qrcode_channel, official_site_tab, official_site_agent_display, official_site_upload, official_site_home, methodology, wecom_sync, wecom_jobs, wecom_debug
from app.customer_info import api as customer_info_api
api_router = APIRouter() api_router = APIRouter()
api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"]) api_router.include_router(agent_group_helper.router, tags=["agent-group-helper"])
...@@ -17,4 +18,5 @@ api_router.include_router(methodology.router, tags=["methodology"]) ...@@ -17,4 +18,5 @@ api_router.include_router(methodology.router, tags=["methodology"])
api_router.include_router(wecom_sync.router, tags=["wecom-sync"]) api_router.include_router(wecom_sync.router, tags=["wecom-sync"])
api_router.include_router(wecom_jobs.router, tags=["wecom-jobs"]) api_router.include_router(wecom_jobs.router, tags=["wecom-jobs"])
api_router.include_router(wecom_debug.router, tags=["wecom-debug"]) api_router.include_router(wecom_debug.router, tags=["wecom-debug"])
api_router.include_router(customer_info_api.router, tags=["customer-info"])
api_router.include_router(agent_hub.router, prefix="/api/v1/chat", tags=["chat"]) api_router.include_router(agent_hub.router, prefix="/api/v1/chat", tags=["chat"])
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse, success_response_payload, SuccessFlagData
from app.customer_info.schema import PhoneBindingSubmitRequest
from app.customer_info.service import CustomerInfoService
router = APIRouter(prefix="/api/v1/customer-info", tags=["customer-info"])
def get_customer_info_service(db: Session = Depends(get_db)) -> CustomerInfoService:
return CustomerInfoService(db)
@router.post("/phone", response_model=ApiResponse[SuccessFlagData])
def submit_phone(
req: PhoneBindingSubmitRequest,
service: CustomerInfoService = Depends(get_customer_info_service),
):
"""用户提交手机号绑定。"""
record = service.bind_phone(
customer_name=req.customer_name, group_id=req.group_id, phone=req.phone
)
if record is None:
raise HTTPException(status_code=404, detail="未找到匹配的客户群组记录")
return success_response_payload(200, SuccessFlagData(success=True))
from __future__ import annotations
from sqlalchemy import BigInteger, Column, String, DateTime, UniqueConstraint, Index, text
from app.infrastructure.database import Base
class CustomerGroupPhone(Base):
__tablename__ = "customer_group_phones"
id = Column(BigInteger, primary_key=True, autoincrement=True)
customer_name = Column(String(255), nullable=False)
group_id = Column(String(255), nullable=False)
group_status = Column(String(50), nullable=False, default="active")
phone = Column(String(20), nullable=True)
last_pushed_at = Column(DateTime, nullable=True)
create_time = Column(DateTime, server_default=text("CURRENT_TIMESTAMP"), nullable=False)
update_time = Column(DateTime, server_default=text("CURRENT_TIMESTAMP"), onupdate=text("CURRENT_TIMESTAMP"), nullable=False)
__table_args__ = (
UniqueConstraint("customer_name", "group_id", name="uk_customer_name_group_id"),
Index("idx_group_id", "group_id"),
Index("idx_phone", "phone"),
Index("idx_push_candidates", "group_status", "phone", "last_pushed_at"),
)
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from pydantic.config import ConfigDict
class PhoneBindingSubmitRequest(BaseModel):
customer_name: str = Field(..., max_length=255, description="客户名称")
group_id: str = Field(..., max_length=255, description="群ID")
phone: str = Field(..., max_length=20, description="手机号码")
class CustomerGroupPhoneResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
customer_name: str
group_id: str
group_status: str
phone: Optional[str] = None
last_pushed_at: Optional[datetime] = None
create_time: datetime
update_time: datetime
from __future__ import annotations
import logging
from typing import Optional
from sqlalchemy import func, text
from sqlalchemy.orm import Session
from app.infrastructure.time import china_now
from app.customer_info.model import CustomerGroupPhone
logger = logging.getLogger(__name__)
class CustomerInfoService:
"""客户号码与群组关系维护服务。"""
def __init__(self, db: Session):
self.db = db
def sync_from_customer_groups(self) -> int:
"""从 wecom_customer_groups 同步数据,返回受影响行数。
使用 INSERT ... ON DUPLICATE KEY UPDATE 实现 upsert。
只同步 is_deleted=0 AND group_id IS NOT NULL 的记录。
"""
now = china_now()
result = self.db.execute(
text("""
INSERT INTO customer_group_phones (customer_name, group_id, group_status, create_time, update_time)
SELECT wcg.customer_name, wcg.group_id, wcg.group_status, :now, :now
FROM wecom_customer_groups wcg
WHERE wcg.is_deleted = 0 AND wcg.group_id IS NOT NULL
ON DUPLICATE KEY UPDATE
group_status = VALUES(group_status),
update_time = VALUES(update_time)
"""),
{"now": now},
)
self.db.commit()
affected = result.rowcount
logger.info("同步完成: affected=%s", affected)
return affected
def bind_phone(self, customer_name: str, group_id: str, phone: str) -> Optional[CustomerGroupPhone]:
"""用户填写手机号。"""
record = (
self.db.query(CustomerGroupPhone)
.filter(
CustomerGroupPhone.customer_name == customer_name,
CustomerGroupPhone.group_id == group_id,
)
.first()
)
if not record:
logger.warning("未找到匹配记录: customer_name=%s group_id=%s", customer_name, group_id)
return None
record.phone = phone
self.db.commit()
self.db.refresh(record)
logger.info("手机号绑定成功: customer_name=%s group_id=%s", customer_name, group_id)
return record
def get_push_candidates(self, mode: str = "sync") -> list[CustomerGroupPhone]:
"""获取需要推送的记录。
mode='sync': 同步触发推送, 仅 last_pushed_at IS NULL 的新记录。
mode='daily': 每日推送, 包含从未推送或上次推送日期非今日的记录。
"""
now = china_now()
today = now.date()
base_query = self.db.query(CustomerGroupPhone).filter(
CustomerGroupPhone.phone.is_(None),
CustomerGroupPhone.group_status == "active",
)
if mode == "sync":
candidates = base_query.filter(CustomerGroupPhone.last_pushed_at.is_(None)).all()
elif mode == "daily":
candidates = base_query.filter(
(CustomerGroupPhone.last_pushed_at.is_(None))
| (func.date(CustomerGroupPhone.last_pushed_at) < today)
).all()
else:
raise ValueError(f"Unknown push mode: {mode}")
return candidates
def mark_pushed(self, record: CustomerGroupPhone) -> None:
"""推送成功后设置 last_pushed_at。"""
record.last_pushed_at = china_now()
self.db.commit()
...@@ -253,6 +253,28 @@ def _ensure_mysql_runtime_schema(conn) -> None: ...@@ -253,6 +253,28 @@ def _ensure_mysql_runtime_schema(conn) -> None:
table_names = _mysql_table_names(conn) table_names = _mysql_table_names(conn)
if "customer_group_phones" not in table_names:
conn.execute(
text(
"""
CREATE TABLE customer_group_phones (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255) NOT NULL,
group_id VARCHAR(255) NOT NULL,
group_status VARCHAR(50) NOT NULL DEFAULT 'active',
phone VARCHAR(20) DEFAULT NULL,
last_pushed_at DATETIME DEFAULT NULL,
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_customer_name_group_id (customer_name, group_id),
KEY idx_group_id (group_id),
KEY idx_phone (phone),
KEY idx_push_candidates (group_status, phone, last_pushed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
)
)
if "wecom_messages" in table_names: if "wecom_messages" in table_names:
columns = _column_names(conn, "mysql", "wecom_messages") columns = _column_names(conn, "mysql", "wecom_messages")
if "customer_group_id" not in columns: if "customer_group_id" not in columns:
......
...@@ -7,6 +7,8 @@ JOB_NAME_MAP = { ...@@ -7,6 +7,8 @@ JOB_NAME_MAP = {
"sync_wecom_bots_groups_messages": "同步机器人与客户群消息", "sync_wecom_bots_groups_messages": "同步机器人与客户群消息",
"sync_customer_groups": "同步一客一群建群编排", "sync_customer_groups": "同步一客一群建群编排",
"dispatch_customer_group_messages": "分发客户群消息到下游", "dispatch_customer_group_messages": "分发客户群消息到下游",
"sync_customer_group_phones": "同步客户号码与群组关系",
"daily_phone_push": "每日手机号收集推送",
} }
_job_key_var: ContextVar[str | None] = ContextVar("job_key", default=None) _job_key_var: ContextVar[str | None] = ContextVar("job_key", default=None)
......
from __future__ import annotations from __future__ import annotations
import logging import logging
import time
from datetime import datetime from datetime import datetime
import httpx
from app.infrastructure.time import china_now from app.infrastructure.time import china_now
from app.config.loader import ConfigLoader
from app.infrastructure.database import SessionLocal from app.infrastructure.database import SessionLocal
from app.infrastructure.wecom_sync_client import HttpWeComSyncClient, WeComSyncClientError from app.infrastructure.wecom_sync_client import HttpWeComSyncClient, WeComSyncClientError
from app.jobs.log_context import JOB_NAME_MAP, format_job_log, reset_job_log_context, set_job_log_context from app.jobs.log_context import JOB_NAME_MAP, format_job_log, reset_job_log_context, set_job_log_context
from app.model.wecom_sync import WeComBot from app.model.wecom_sync import WeComBot, WeComCustomerGroup
from app.service.wecom_customer_group_orchestration_service import ( from app.service.wecom_customer_group_orchestration_service import (
HttpChatCompletionsBatchDispatcher, HttpChatCompletionsBatchDispatcher,
WeComCustomerGroupOrchestrationService, WeComCustomerGroupOrchestrationService,
) )
from app.service.wecom_sync_service import NoopWeComMessageDispatcher, WeComSyncService from app.service.wecom_sync_service import NoopWeComMessageDispatcher, WeComSyncService
from app.customer_info.service import CustomerInfoService
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -27,11 +33,12 @@ def _build_services(): ...@@ -27,11 +33,12 @@ def _build_services():
sync_service, sync_service,
batch_dispatcher=HttpChatCompletionsBatchDispatcher(), batch_dispatcher=HttpChatCompletionsBatchDispatcher(),
) )
return db, sync_service, orchestration_service customer_info_service = CustomerInfoService(db)
return db, sync_service, orchestration_service, customer_info_service
def run_job(job_key: str) -> None: def run_job(job_key: str) -> None:
db, sync_service, orchestration_service = _build_services() db, sync_service, orchestration_service, customer_info_service = _build_services()
token = set_job_log_context(job_key) token = set_job_log_context(job_key)
try: try:
config = sync_service.ensure_job_config(job_key) config = sync_service.ensure_job_config(job_key)
...@@ -59,6 +66,10 @@ def run_job(job_key: str) -> None: ...@@ -59,6 +66,10 @@ def run_job(job_key: str) -> None:
count = sum(result.values()) count = sum(result.values())
elif job_key == "dispatch_customer_group_messages": elif job_key == "dispatch_customer_group_messages":
count = orchestration_service.dispatch_customer_group_messages(bot_ids=None) count = orchestration_service.dispatch_customer_group_messages(bot_ids=None)
elif job_key == "sync_customer_group_phones":
count = _run_sync_customer_group_phones(customer_info_service)
elif job_key == "daily_phone_push":
count = _run_daily_phone_push(customer_info_service)
else: else:
raise ValueError(f"Unsupported job_key: {job_key}") raise ValueError(f"Unsupported job_key: {job_key}")
...@@ -73,3 +84,61 @@ def run_job(job_key: str) -> None: ...@@ -73,3 +84,61 @@ def run_job(job_key: str) -> None:
finally: finally:
reset_job_log_context(token) reset_job_log_context(token)
db.close() db.close()
def _run_sync_customer_group_phones(service: CustomerInfoService) -> int:
"""执行同步 + 同步触发推送。"""
affected = service.sync_from_customer_groups()
candidates = service.get_push_candidates(mode="sync")
for record in candidates:
_do_push(record)
service.mark_pushed(record)
logger.info("同步触发推送: candidates=%s", len(candidates))
return affected
def _run_daily_phone_push(service: CustomerInfoService) -> int:
"""执行每日 9 点推送。"""
candidates = service.get_push_candidates(mode="daily")
for record in candidates:
_do_push(record)
service.mark_pushed(record)
logger.info("每日推送: pushed=%s", len(candidates))
return len(candidates)
def _do_push(record) -> None:
"""向群发送【系统推送】消息,引导用户填写手机号。
通过 IM 业务 API 推送文本消息到 group_id 对应的群。
"""
db = SessionLocal()
try:
cg = db.query(WeComCustomerGroup).filter(
WeComCustomerGroup.group_id == record.group_id,
WeComCustomerGroup.is_deleted == False,
).first()
if not cg or not cg.bot_id:
logger.warning("未找到群对应的 bot_id: group_id=%s", record.group_id)
return
settings = ConfigLoader().load_settings()
payload = {
"contact_id": record.group_id,
"content": "【系统推送】推送信息填写链接",
"bot_id": cg.bot_id,
"msg_type": "text",
"biz_rela_no": f"biz-msg-push-{int(time.time() * 1000)}",
}
headers = {"Content-Type": "application/json"}
if settings.im.api_key:
headers["X-Api-Key"] = settings.im.api_key
url = f"{settings.im.base_url}/api/v1/business/messages/send"
resp = httpx.post(url, json=payload, headers=headers, timeout=10)
resp.raise_for_status()
logger.info("推送成功: group_id=%s bot_id=%s", record.group_id, cg.bot_id)
except Exception:
logger.exception("推送失败: group_id=%s", record.group_id)
finally:
db.close()
...@@ -18,6 +18,8 @@ DEFAULT_JOB_SPECS = [ ...@@ -18,6 +18,8 @@ DEFAULT_JOB_SPECS = [
{"job_key": "sync_wecom_bots_groups_messages", "minutes": 2}, {"job_key": "sync_wecom_bots_groups_messages", "minutes": 2},
{"job_key": "sync_customer_groups", "minutes": 10}, {"job_key": "sync_customer_groups", "minutes": 10},
{"job_key": "dispatch_customer_group_messages", "minutes": 1}, {"job_key": "dispatch_customer_group_messages", "minutes": 1},
{"job_key": "sync_customer_group_phones", "minutes": 1},
# daily_phone_push 需要 cron 触发,单独处理
] ]
...@@ -72,13 +74,26 @@ def build_scheduler() -> BlockingScheduler: ...@@ -72,13 +74,26 @@ def build_scheduler() -> BlockingScheduler:
**interval_kwargs, **interval_kwargs,
) )
scheduler.add_listener(_job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR) scheduler.add_listener(_job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
scheduler.add_job(
run_job,
"cron",
args=["daily_phone_push"],
id="daily_phone_push",
replace_existing=True,
max_instances=1,
coalesce=True,
hour=9,
minute=0,
)
return scheduler return scheduler
def main() -> None: def main() -> None:
job_specs = load_job_specs() job_specs = load_job_specs()
scheduler = build_scheduler() scheduler = build_scheduler()
logger.info("APScheduler starting,当前将注册 3 类任务:同步机器人与客户群消息 / 同步一客一群建群编排 / 分发客户群消息到下游") logger.info("APScheduler starting,当前将注册 %s 类定时任务", len(job_specs))
for spec in job_specs: for spec in job_specs:
logger.info( logger.info(
"Registered job: job_key=%s task=%s interval_%s=%s", "Registered job: job_key=%s task=%s interval_%s=%s",
......
...@@ -39,6 +39,7 @@ from app.model.wecom_sync import ( # noqa: F401 ...@@ -39,6 +39,7 @@ from app.model.wecom_sync import ( # noqa: F401
WeComMessage, WeComMessage,
WeComSyncCheckpoint, WeComSyncCheckpoint,
) )
from app.customer_info.model import CustomerGroupPhone # noqa: F401
from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload from app.schema.common import error_response_payload, is_wrapped_payload, success_response_payload
from app.agent_core.agent_hub import AgentHub from app.agent_core.agent_hub import AgentHub
from app.agent_core.active_session_service import ActiveSessionService from app.agent_core.active_session_service import ActiveSessionService
......
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.agent_group import QrcodeChannel from app.model.agent_group import QrcodeChannel
from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser from app.model.position_tag import PositionTag, OfficialTab, PositionTagUser
from app.customer_info.model import CustomerGroupPhone
from app.model.wecom_sync import ( from app.model.wecom_sync import (
WeComBot, WeComBot,
WeComCustomerGroup, WeComCustomerGroup,
...@@ -16,4 +17,5 @@ __all__ = [ ...@@ -16,4 +17,5 @@ __all__ = [
"PositionTag", "OfficialTab", "PositionTagUser", "PositionTag", "OfficialTab", "PositionTagUser",
"WeComBot", "WeComCustomerGroup", "WeComMessage", "WeComSyncCheckpoint", "WeComBot", "WeComCustomerGroup", "WeComMessage", "WeComSyncCheckpoint",
"WeComGroupCreateRequest", "WeComJobConfig", "WeComGroupCreateRequest", "WeComJobConfig",
"CustomerGroupPhone",
] ]
...@@ -39,6 +39,9 @@ ...@@ -39,6 +39,9 @@
}, },
"dispatch_customer_group_messages": { "dispatch_customer_group_messages": {
"seconds": 5 "seconds": 5
},
"sync_customer_group_phones": {
"minutes": 1
} }
} }
} }
......
# Customer Group Info 服务实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 实现客户号码与群组关系维护服务,含数据同步、手机号收集接口、定时推送框架。
**Architecture:** 独立模块 `app/customer_info/`,与主 Agent 流程完全解耦,仅依赖 infrastructure 层。定时任务复用现有 APScheduler 架构。
**Tech Stack:** Python 3.11+ / FastAPI / SQLAlchemy 2.0 / PyMySQL / APScheduler / pytest
---
### Task 0: Model + Schema + Runtime DDL
**Files:**
- Create: `app/customer_info/__init__.py`
- Create: `app/customer_info/model.py`
- Create: `app/customer_info/schema.py`
- Modify: `app/model/__init__.py`
- Modify: `app/main.py`
- Modify: `app/infrastructure/schema_patch.py`
- [ ] **Step 1: Create `app/customer_info/__init__.py`**
```python
# app/customer_info/__init__.py
```
- [ ] **Step 2: Create `app/customer_info/model.py`**
```python
from __future__ import annotations
from sqlalchemy import BigInteger, Column, String, DateTime, UniqueConstraint, Index
from sqlalchemy.sql import func
from app.infrastructure.database import Base
class CustomerGroupPhone(Base):
__tablename__ = "customer_group_phones"
id = Column(BigInteger, primary_key=True, autoincrement=True)
customer_name = Column(String(255), nullable=False)
group_id = Column(String(255), nullable=False)
group_status = Column(String(50), nullable=False, default="active")
phone = Column(String(20), nullable=True)
last_pushed_at = Column(DateTime, nullable=True)
create_time = Column(DateTime, server_default=func.now(), nullable=False)
update_time = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
__table_args__ = (
UniqueConstraint("customer_name", "group_id", name="uk_customer_name_group_id"),
Index("idx_group_id", "group_id"),
Index("idx_phone", "phone"),
Index("idx_push_candidates", "group_status", "phone", "last_pushed_at"),
)
```
- [ ] **Step 3: Create `app/customer_info/schema.py`**
```python
from __future__ import annotations
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
from pydantic.config import ConfigDict
class PhoneBindingSubmitRequest(BaseModel):
customer_name: str = Field(..., max_length=255, description="客户名称")
group_id: str = Field(..., max_length=255, description="群ID")
phone: str = Field(..., max_length=20, description="手机号码")
class CustomerGroupPhoneResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
customer_name: str
group_id: str
group_status: str
phone: Optional[str] = None
last_pushed_at: Optional[datetime] = None
create_time: datetime
update_time: datetime
```
- [ ] **Step 4: Modify `app/model/__init__.py` — 导出 CustomerGroupPhone**
在文件末尾的 `__all__` 中添加 `"CustomerGroupPhone"`:
```python
from app.customer_info.model import CustomerGroupPhone
__all__ = [
# ... 现有导出 ...
"CustomerGroupPhone",
]
```
- [ ] **Step 5: Modify `app/main.py` — 注册模型到 Base.metadata**
在现有的 model import 块中添加:
```python
from app.customer_info.model import CustomerGroupPhone # noqa: F401
```
放在其他 model import 之后(约第 41 行附近)。
- [ ] **Step 6: Modify `app/infrastructure/schema_patch.py` — 添加表创建 DDL**
在 `_ensure_mysql_runtime_schema()` 中现有的 `table_names = _mysql_table_names(conn)` 之后添加:
```python
if "customer_group_phones" not in table_names:
conn.execute(
text(
"""
CREATE TABLE customer_group_phones (
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
customer_name VARCHAR(255) NOT NULL,
group_id VARCHAR(255) NOT NULL,
group_status VARCHAR(50) NOT NULL DEFAULT 'active',
phone VARCHAR(20) DEFAULT NULL,
last_pushed_at DATETIME DEFAULT NULL,
create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uk_customer_name_group_id (customer_name, group_id),
KEY idx_group_id (group_id),
KEY idx_phone (phone),
KEY idx_push_candidates (group_status, phone, last_pushed_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
)
)
```
注意:插入到 `_ensure_mysql_runtime_schema()` 中现有的 `table_names = _mysql_table_names(conn)` 之后(line ~254),在所有 `if "xxx" in table_names:` 检查之前。
- [ ] **Step 7: 冒烟验证 — 启动确认表创建**
Run: `PYTHONPATH=. python -c "from app.customer_info.model import CustomerGroupPhone; print('OK')"`
Expected: `OK`
---
### Task 1: Service
**Files:**
- Create: `app/customer_info/service.py`
- Test: `tests/test_customer_info_service.py`(Task 4 统一写测试)
- [ ] **Step 1: Create `app/customer_info/service.py`**
```python
from __future__ import annotations
import logging
from typing import Optional
from sqlalchemy import func, text
from sqlalchemy.orm import Session
from app.infrastructure.time import china_now
from app.customer_info.model import CustomerGroupPhone
logger = logging.getLogger(__name__)
class CustomerInfoService:
"""客户号码与群组关系维护服务。"""
def __init__(self, db: Session):
self.db = db
def sync_from_customer_groups(self) -> int:
"""从 wecom_customer_groups 同步数据,返回受影响行数。
使用 INSERT ... ON DUPLICATE KEY UPDATE 实现 upsert。
只同步 is_deleted=0 AND group_id IS NOT NULL 的记录。
"""
now = china_now()
result = self.db.execute(
text("""
INSERT INTO customer_group_phones (customer_name, group_id, group_status, create_time, update_time)
SELECT wcg.customer_name, wcg.group_id, wcg.group_status, :now, :now
FROM wecom_customer_groups wcg
WHERE wcg.is_deleted = 0 AND wcg.group_id IS NOT NULL
ON DUPLICATE KEY UPDATE
group_status = VALUES(group_status),
update_time = VALUES(update_time)
"""),
{"now": now},
)
self.db.commit()
affected = result.rowcount
logger.info("同步完成: affected=%s", affected)
return affected
def bind_phone(self, customer_name: str, group_id: str, phone: str) -> Optional[CustomerGroupPhone]:
"""用户填写手机号。"""
record = (
self.db.query(CustomerGroupPhone)
.filter(
CustomerGroupPhone.customer_name == customer_name,
CustomerGroupPhone.group_id == group_id,
)
.first()
)
if not record:
logger.warning("未找到匹配记录: customer_name=%s group_id=%s", customer_name, group_id)
return None
record.phone = phone
self.db.commit()
self.db.refresh(record)
logger.info("手机号绑定成功: customer_name=%s group_id=%s", customer_name, group_id)
return record
def get_push_candidates(self, mode: str = "sync") -> list[CustomerGroupPhone]:
"""获取需要推送的记录。
mode='sync': 同步触发推送, 仅 last_pushed_at IS NULL 的新记录。
mode='daily': 每日推送, 包含从未推送或上次推送日期非今日的记录。
"""
now = china_now()
today = now.date()
base_query = self.db.query(CustomerGroupPhone).filter(
CustomerGroupPhone.phone.is_(None),
CustomerGroupPhone.group_status == "active",
)
if mode == "sync":
candidates = base_query.filter(CustomerGroupPhone.last_pushed_at.is_(None)).all()
elif mode == "daily":
candidates = base_query.filter(
(CustomerGroupPhone.last_pushed_at.is_(None))
| (func.date(CustomerGroupPhone.last_pushed_at) < today))
.all()
else:
raise ValueError(f"Unknown push mode: {mode}")
return candidates
def mark_pushed(self, record: CustomerGroupPhone) -> None:
"""推送成功后设置 last_pushed_at。"""
record.last_pushed_at = china_now()
self.db.commit()
```
- [ ] **Step 2: 冒烟验证**
Run: `PYTHONPATH=. python -c "from app.customer_info.service import CustomerInfoService; print('OK')"`
Expected: `OK`
---
### Task 2: API Endpoint
**Files:**
- Create: `app/customer_info/api.py`
- Modify: `app/api/v1/router.py`
- [ ] **Step 1: Create `app/customer_info/api.py`**
```python
from __future__ import annotations
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse, success_response_payload, SuccessFlagData
from app.customer_info.schema import PhoneBindingSubmitRequest
from app.customer_info.service import CustomerInfoService
router = APIRouter(prefix="/api/v1/customer-info", tags=["customer-info"])
def get_customer_info_service(db: Session = Depends(get_db)) -> CustomerInfoService:
return CustomerInfoService(db)
@router.post("/phone", response_model=ApiResponse[SuccessFlagData])
def submit_phone(
req: PhoneBindingSubmitRequest,
service: CustomerInfoService = Depends(get_customer_info_service),
):
"""用户提交手机号绑定。"""
record = service.bind_phone(customer_name=req.customer_name, group_id=req.group_id, phone=req.phone)
if record is None:
from fastapi import HTTPException
raise HTTPException(status_code=404, detail="未找到匹配的客户群组记录")
return success_response_payload(200, SuccessFlagData(success=True))
```
- [ ] **Step 2: Modify `app/api/v1/router.py` — 注册路由**
在文件顶部 import 中添加:
```python
from app.customer_info import api as customer_info_api
```
在 `api_router` 注册中添加:
```python
api_router.include_router(customer_info_api.router, tags=["customer-info"])
```
- [ ] **Step 3: 冒烟验证 — API 启动**
Run: `PYTHONPATH=. python -c "from app.customer_info.api import router; print('OK')"`
Expected: `OK`
---
### Task 3: Jobs 配置
**Files:**
- Modify: `app/jobs/log_context.py`
- Modify: `app/jobs/scheduler.py`
- Modify: `app/jobs/runner.py`
- [ ] **Step 1: Modify `app/jobs/log_context.py` — 添加 job 名称映射**
在 `JOB_NAME_MAP` 中添加两个新条目:
```python
JOB_NAME_MAP = {
"sync_wecom_bots_groups_messages": "同步机器人与客户群消息",
"sync_customer_groups": "同步一客一群建群编排",
"dispatch_customer_group_messages": "分发客户群消息到下游",
"sync_customer_group_phones": "同步客户号码与群组关系",
"daily_phone_push": "每日手机号收集推送",
}
```
- [ ] **Step 2: Modify `app/jobs/scheduler.py` — 添加默认 job 规格**
在 `DEFAULT_JOB_SPECS` 中添加:
```python
DEFAULT_JOB_SPECS = [
{"job_key": "sync_wecom_bots_groups_messages", "minutes": 2},
{"job_key": "sync_customer_groups", "minutes": 10},
{"job_key": "dispatch_customer_group_messages", "minutes": 1},
{"job_key": "sync_customer_group_phones", "minutes": 5},
# daily_phone_push 需要 cron 触发,单独处理
]
```
同时在 `build_scheduler()` 中添加 cron job:
```python
scheduler.add_job(
run_job,
"cron",
args=["daily_phone_push"],
id="daily_phone_push",
replace_existing=True,
max_instances=1,
coalesce=True,
hour=9,
minute=0,
)
```
- [ ] **Step 3: Modify `app/jobs/runner.py` — 添加 job 调度逻辑**
在 `_build_services()` 中创建 `CustomerInfoService`,并在 `run_job()` 中添加 dispatch:
```python
from app.customer_info.service import CustomerInfoService
def _build_services():
db = SessionLocal()
client = HttpWeComSyncClient()
sync_service = WeComSyncService(db, client, NoopWeComMessageDispatcher())
orchestration_service = WeComCustomerGroupOrchestrationService(
db,
client,
sync_service,
batch_dispatcher=HttpChatCompletionsBatchDispatcher(),
)
customer_info_service = CustomerInfoService(db)
return db, sync_service, orchestration_service, customer_info_service
```
在 `run_job()` 中的 dispatch chain 添加:
```python
def run_job(job_key: str) -> None:
db, sync_service, orchestration_service, customer_info_service = _build_services()
token = set_job_log_context(job_key)
try:
config = sync_service.ensure_job_config(job_key)
if not config.enabled:
logger.info(format_job_log("任务已禁用,跳过执行"))
return
logger.info(format_job_log("任务开始: %s" % JOB_NAME_MAP.get(job_key, job_key)))
if job_key == "sync_wecom_bots_groups_messages":
# ... 现有逻辑 ...
elif job_key == "sync_customer_groups":
# ... 现有逻辑 ...
elif job_key == "dispatch_customer_group_messages":
# ... 现有逻辑 ...
elif job_key == "sync_customer_group_phones":
count = _run_sync_customer_group_phones(customer_info_service)
elif job_key == "daily_phone_push":
count = _run_daily_phone_push(customer_info_service)
else:
raise ValueError(f"Unsupported job_key: {job_key}")
sync_service.mark_job_result(job_key, "success", None)
logger.info(format_job_log("任务完成: processed_count=%s" % count))
except WeComSyncClientError as exc:
# ... 现有异常处理 ...
finally:
reset_job_log_context(token)
db.close()
def _run_sync_customer_group_phones(service: CustomerInfoService) -> int:
"""执行同步 + 同步触发推送。"""
affected = service.sync_from_customer_groups()
candidates = service.get_push_candidates(mode="sync")
for record in candidates:
_do_push(record)
service.mark_pushed(record)
logger.info("同步触发推送: candidates=%s", len(candidates))
return affected
def _run_daily_phone_push(service: CustomerInfoService) -> int:
"""执行每日 9 点推送。"""
candidates = service.get_push_candidates(mode="daily")
for record in candidates:
_do_push(record)
service.mark_pushed(record)
logger.info("每日推送: pushed=%s", len(candidates))
return len(candidates)
def _do_push(record) -> None:
"""执行推送(TODO: 接入真实 IM 推送,当前只打日志)。"""
logger.info(
"推送消息到群: group_id=%s customer_name=%s",
record.group_id,
record.customer_name,
)
```
注意 `_do_push()` 为桩函数,实际 IM 推送待前端链接确定后实现。
- [ ] **Step 4: 冒烟验证 — job 模块可导入**
Run: `PYTHONPATH=. python -c "from app.jobs.runner import run_job; print('OK')"`
Expected: `OK`
---
### Task 4: 测试
**Files:**
- Create: `tests/test_customer_info_service.py`
- [ ] **Step 1: Create `tests/test_customer_info_service.py`**
```python
from __future__ import annotations
from datetime import timedelta
import pytest
from app.customer_info.model import CustomerGroupPhone
from app.customer_info.service import CustomerInfoService
from app.infrastructure.time import china_now
from app.model.wecom_sync import WeComCustomerGroup
class TestSyncFromCustomerGroups:
"""测试从 wecom_customer_groups 同步数据。"""
def test_sync_insert(self, db_session):
"""同步应插入新记录到 customer_group_phones。"""
# 准备源数据
src = WeComCustomerGroup(
customer_contact_id="cc1",
customer_name="张三",
bot_id="bot1",
bot_code="B001",
group_id="g1",
group_name="测试群",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=False,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
affected = service.sync_from_customer_groups()
assert affected > 0
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "张三",
CustomerGroupPhone.group_id == "g1",
).first()
assert target is not None
assert target.group_status == "active"
assert target.phone is None
def test_sync_skip_deleted(self, db_session):
"""同步应跳过 is_deleted=True 的记录。"""
src = WeComCustomerGroup(
customer_contact_id="cc2",
customer_name="李四",
bot_id="bot1",
bot_code="B001",
group_id="g2",
group_name="测试群2",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=True,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
service.sync_from_customer_groups()
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "李四",
).first()
assert target is None
def test_sync_skip_null_group_id(self, db_session):
"""同步应跳过 group_id IS NULL 的记录。"""
src = WeComCustomerGroup(
customer_contact_id="cc3",
customer_name="王五",
bot_id="bot1",
bot_code="B001",
group_id=None,
group_name="测试群3",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=False,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
service.sync_from_customer_groups()
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "王五",
).first()
assert target is None
def test_sync_update_status(self, db_session):
"""已存在的记录应更新 group_status。"""
# 先插入一条
existing = CustomerGroupPhone(
customer_name="赵六",
group_id="g4",
group_status="pending",
)
db_session.add(existing)
db_session.commit()
# wecom_customer_groups 中对应记录状态为 active
src = WeComCustomerGroup(
customer_contact_id="cc4",
customer_name="赵六",
bot_id="bot1",
bot_code="B001",
group_id="g4",
group_name="测试群4",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=False,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
service.sync_from_customer_groups()
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "赵六",
CustomerGroupPhone.group_id == "g4",
).first()
assert target is not None
assert target.group_status == "active"
class TestBindPhone:
"""测试手机号绑定。"""
def test_bind_phone_success(self, db_session):
"""绑定手机号应更新对应记录。"""
record = CustomerGroupPhone(
customer_name="张三",
group_id="g1",
group_status="active",
)
db_session.add(record)
db_session.commit()
service = CustomerInfoService(db_session)
result = service.bind_phone("张三", "g1", "13800138000")
assert result is not None
assert result.phone == "13800138000"
def test_bind_phone_not_found(self, db_session):
"""绑定时找不到记录应返回 None。"""
service = CustomerInfoService(db_session)
result = service.bind_phone("不存在", "g99", "13800138000")
assert result is None
class TestGetPushCandidates:
"""测试推送候选查询。"""
def test_sync_mode_returns_only_new_records(self, db_session):
"""sync 模式只返回 last_pushed_at IS NULL 的记录。"""
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active")
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active",
last_pushed_at=datetime(2026, 7, 5, 10, 0, 0))
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("sync")
assert len(candidates) == 1
assert candidates[0].customer_name == "A"
def test_sync_mode_skip_not_active(self, db_session):
"""sync 模式应跳过 group_status != 'active' 的记录。"""
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="pending")
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active")
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("sync")
assert len(candidates) == 1
assert candidates[0].customer_name == "B"
def test_sync_mode_skip_has_phone(self, db_session):
"""sync 模式应跳过 phone 已填写的记录。"""
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active", phone="13800138000")
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active")
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("sync")
assert len(candidates) == 1
assert candidates[0].customer_name == "B"
def test_daily_mode_returns_old_pushed_records(self, db_session):
"""daily 模式应返回 last_pushed_at 不是今天的记录。"""
now = china_now()
yesterday = now - timedelta(days=1)
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active",
last_pushed_at=yesterday)
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active",
last_pushed_at=now)
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("daily")
assert len(candidates) == 1
assert candidates[0].customer_name == "A"
class TestMarkPushed:
"""测试标记已推送。"""
def test_mark_pushed_sets_timestamp(self, db_session):
"""mark_pushed 应设置 last_pushed_at。"""
record = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active")
db_session.add(record)
db_session.commit()
assert record.last_pushed_at is None
service = CustomerInfoService(db_session)
service.mark_pushed(record)
assert record.last_pushed_at is not None
# ── SQL 模型 DDL 一致性测试 ──
class TestCustomerGroupPhoneDDL:
"""验证 customer_group_phones 表的 DDL 与 ORM 模型一致。"""
def test_model_attributes(self):
"""验证 ORM 模型字段完整性。"""
mapper = CustomerGroupPhone.__mapper__
columns = {c.name: c for c in mapper.columns}
assert "id" in columns
assert "customer_name" in columns
assert "group_id" in columns
assert "group_status" in columns
assert "phone" in columns
assert "last_pushed_at" in columns
assert "create_time" in columns
assert "update_time" in columns
def test_unique_constraint(self):
"""验证唯一约束存在。"""
constraints = CustomerGroupPhone.__table_args__
names = [c.name for c in constraints if hasattr(c, 'name')]
assert "uk_customer_name_group_id" in names
```
- [ ] **Step 2: 运行测试**
Run: `PYTHONPATH=. python -m pytest tests/test_customer_info_service.py -v --tb=short`
Expected: 13 tests pass
---
### Task 5: 集成验证
- [ ] **Step 1: 启动应用并检查 API**
```bash
PYTHONPATH=. python -m app.main &
sleep 3
curl -X POST http://localhost:8000/api/v1/customer-info/phone \
-H "Content-Type: application/json" \
-d '{"customer_name":"测试","group_id":"g1","phone":"13800138000"}'
```
Expected: `{"code": 200, "message": "success", "data": {"success": true}}`
- [ ] **Step 2: 清理后台进程(如果需要)**
```bash
kill %1 2>/dev/null || true
```
from __future__ import annotations
from datetime import timedelta
import pytest
from app.customer_info.model import CustomerGroupPhone
from app.customer_info.service import CustomerInfoService
from app.infrastructure.time import china_now
from app.model.wecom_sync import WeComCustomerGroup
class TestSyncFromCustomerGroups:
"""测试从 wecom_customer_groups 同步数据。"""
_test_contact_ids: list[str] = []
@pytest.fixture(autouse=True)
def cleanup_sync_data(self, db_session):
"""每个测试前清理之前测试产生的数据,只删特定测试 ID,不清全表。"""
if self._test_contact_ids:
db_session.query(CustomerGroupPhone).delete()
db_session.query(WeComCustomerGroup).filter(
WeComCustomerGroup.customer_contact_id.in_(self._test_contact_ids)
).delete()
db_session.commit()
self._test_contact_ids = []
yield
# 测试结束后清理本次产生的数据
if self._test_contact_ids:
db_session.query(CustomerGroupPhone).delete()
db_session.query(WeComCustomerGroup).filter(
WeComCustomerGroup.customer_contact_id.in_(self._test_contact_ids)
).delete()
db_session.commit()
def _track(self, contact_id: str) -> None:
self._test_contact_ids.append(contact_id)
def test_sync_insert(self, db_session):
"""同步应插入新记录到 customer_group_phones。"""
self._track("cc1")
src = WeComCustomerGroup(
customer_contact_id="cc1",
customer_name="张三",
bot_id="bot1",
bot_code="B001",
group_id="g1",
group_name="测试群",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=False,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
affected = service.sync_from_customer_groups()
assert affected > 0
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "张三",
CustomerGroupPhone.group_id == "g1",
).first()
assert target is not None
assert target.group_status == "active"
assert target.phone is None
def test_sync_skip_deleted(self, db_session):
"""同步应跳过 is_deleted=True 的记录。"""
self._track("cc2")
src = WeComCustomerGroup(
customer_contact_id="cc2",
customer_name="李四",
bot_id="bot1",
bot_code="B001",
group_id="g2",
group_name="测试群2",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=True,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
service.sync_from_customer_groups()
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "李四",
).first()
assert target is None
def test_sync_skip_null_group_id(self, db_session):
"""同步应跳过 group_id IS NULL 的记录。"""
self._track("cc3")
src = WeComCustomerGroup(
customer_contact_id="cc3",
customer_name="王五",
bot_id="bot1",
bot_code="B001",
group_id=None,
group_name="测试群3",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=False,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
service.sync_from_customer_groups()
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "王五",
).first()
assert target is None
def test_sync_update_status(self, db_session):
"""已存在的记录应更新 group_status。"""
self._track("cc4")
# 先插入一条
existing = CustomerGroupPhone(
customer_name="赵六",
group_id="g4",
group_status="pending",
)
db_session.add(existing)
db_session.commit()
# wecom_customer_groups 中对应记录状态为 active
src = WeComCustomerGroup(
customer_contact_id="cc4",
customer_name="赵六",
bot_id="bot1",
bot_code="B001",
group_id="g4",
group_name="测试群4",
group_status="active",
member_bot_ids='["bot1"]',
is_deleted=False,
)
db_session.add(src)
db_session.commit()
service = CustomerInfoService(db_session)
service.sync_from_customer_groups()
target = db_session.query(CustomerGroupPhone).filter(
CustomerGroupPhone.customer_name == "赵六",
CustomerGroupPhone.group_id == "g4",
).first()
assert target is not None
assert target.group_status == "active"
class TestBindPhone:
"""测试手机号绑定。"""
def test_bind_phone_success(self, db_session):
"""绑定手机号应更新对应记录。"""
record = CustomerGroupPhone(
customer_name="绑定测试用户",
group_id="group_phone",
group_status="active",
)
db_session.add(record)
db_session.commit()
service = CustomerInfoService(db_session)
result = service.bind_phone("绑定测试用户", "group_phone", "13800138000")
assert result is not None
assert result.phone == "13800138000"
def test_bind_phone_not_found(self, db_session):
"""绑定时找不到记录应返回 None。"""
service = CustomerInfoService(db_session)
result = service.bind_phone("不存在", "g99", "13800138000")
assert result is None
class TestGetPushCandidates:
"""测试推送候选查询。"""
@pytest.fixture(autouse=True)
def cleanup_push_candidates(self, db_session):
"""每个测试前清理 customer_group_phones,避免唯一约束冲突。"""
db_session.query(CustomerGroupPhone).delete()
db_session.commit()
yield
def test_sync_mode_returns_only_new_records(self, db_session):
"""sync 模式只返回 last_pushed_at IS NULL 的记录。"""
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active")
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active",
last_pushed_at=china_now() - timedelta(days=1))
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("sync")
assert len(candidates) == 1
assert candidates[0].customer_name == "A"
def test_sync_mode_skip_not_active(self, db_session):
"""sync 模式应跳过 group_status != 'active' 的记录。"""
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="pending")
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active")
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("sync")
assert len(candidates) == 1
assert candidates[0].customer_name == "B"
def test_sync_mode_skip_has_phone(self, db_session):
"""sync 模式应跳过 phone 已填写的记录。"""
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active", phone="13800138000")
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active")
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("sync")
assert len(candidates) == 1
assert candidates[0].customer_name == "B"
def test_daily_mode_returns_old_pushed_records(self, db_session):
"""daily 模式应返回 last_pushed_at 不是今天的记录。"""
now = china_now()
yesterday = now - timedelta(days=1)
r1 = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active",
last_pushed_at=yesterday)
r2 = CustomerGroupPhone(customer_name="B", group_id="g2", group_status="active",
last_pushed_at=now)
db_session.add_all([r1, r2])
db_session.commit()
service = CustomerInfoService(db_session)
candidates = service.get_push_candidates("daily")
assert len(candidates) == 1
assert candidates[0].customer_name == "A"
class TestMarkPushed:
"""测试标记已推送。"""
@pytest.fixture(autouse=True)
def cleanup_mark_pushed(self, db_session):
"""每个测试前清理 customer_group_phones,避免与 TestGetPushCandidates 冲突。"""
db_session.query(CustomerGroupPhone).delete()
db_session.commit()
yield
def test_mark_pushed_sets_timestamp(self, db_session):
"""mark_pushed 应设置 last_pushed_at。"""
record = CustomerGroupPhone(customer_name="A", group_id="g1", group_status="active")
db_session.add(record)
db_session.commit()
assert record.last_pushed_at is None
service = CustomerInfoService(db_session)
service.mark_pushed(record)
assert record.last_pushed_at is not None
# ── SQL 模型 DDL 一致性测试 ──
class TestCustomerGroupPhoneDDL:
"""验证 customer_group_phones 表的 DDL 与 ORM 模型一致。"""
def test_model_attributes(self):
"""验证 ORM 模型字段完整性。"""
mapper = CustomerGroupPhone.__mapper__
columns = {c.name: c for c in mapper.columns}
assert "id" in columns
assert "customer_name" in columns
assert "group_id" in columns
assert "group_status" in columns
assert "phone" in columns
assert "last_pushed_at" in columns
assert "create_time" in columns
assert "update_time" in columns
def test_unique_constraint(self):
"""验证唯一约束存在。"""
constraints = CustomerGroupPhone.__table_args__
names = [c.name for c in constraints if hasattr(c, 'name')]
assert "uk_customer_name_group_id" in names
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!