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
} }
} }
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!