Commit 97a47fde by sunqi02

feat: 添加按手机号发送消息功能,重构相关服务和请求模型

1 parent 14b54102
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session
from app.agent_core.im_service import IMService
from app.infrastructure.database import get_db
from app.schema.common import ApiResponse, success_response_payload, SuccessFlagData
from app.customer_info.schema import CustomerGroupPhoneResponse, PhoneBindingSubmitRequest
from app.customer_info.schema import (
CustomerGroupPhoneResponse,
PhoneBindingSubmitRequest,
SendByPhoneRequest,
)
from app.customer_info.send_service import PhoneMessageSender, SendByPhoneError
from app.customer_info.service import CustomerInfoService
router = APIRouter(prefix="/api/v1/customer-info", tags=["customer-info"])
......@@ -39,3 +45,30 @@ def get_phone(
if record is None:
raise HTTPException(status_code=404, detail="未找到匹配的客户群组记录")
return success_response_payload(200, record)
def _get_im_service(request: Request) -> IMService:
im = getattr(request.app.state, "im_service", None)
if im is None:
raise HTTPException(status_code=503, detail="IM 服务未就绪")
return im
@router.post("/send-by-phone")
async def send_by_phone(
req: SendByPhoneRequest,
request: Request,
db: Session = Depends(get_db),
):
"""外部服务按手机号查找群组并发送消息。"""
im_service = _get_im_service(request)
sender = PhoneMessageSender(db=db, im_service=im_service)
try:
result = await sender.send_by_phone(phone=req.phone, content=req.content)
except SendByPhoneError as e:
raise HTTPException(status_code=400, detail=str(e))
if result["success"]:
return success_response_payload(200, result)
raise HTTPException(status_code=502, detail=result["message"])
......@@ -12,6 +12,16 @@ class PhoneBindingSubmitRequest(BaseModel):
phone: str = Field(..., max_length=20, description="手机号码")
class SendByPhoneRequest(BaseModel):
phone: str = Field(..., max_length=20, description="客户手机号")
content: str = Field(..., description="消息内容")
class SendByPhoneResponse(BaseModel):
success: bool
message: str
class CustomerGroupPhoneResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
......
from __future__ import annotations
import logging
from typing import Dict, List, Tuple
from sqlalchemy.orm import Session
from sqlalchemy import text
from app.agent_core.im_service import IMService, IMServiceError
logger = logging.getLogger(__name__)
class SendByPhoneError(Exception):
"""Raised when send-by-phone operation fails."""
pass
class PhoneMessageSender:
"""通过手机号查找群组并发送消息。"""
# language=MySQL
_QUERY = """
SELECT cgp.group_id, wcg.bot_id
FROM customer_group_phones cgp
JOIN wecom_customer_groups wcg ON cgp.group_id = wcg.group_id
WHERE cgp.phone = :phone AND wcg.is_deleted = 0
"""
def __init__(self, db: Session, im_service: IMService):
self.db = db
self.im_service = im_service
def _lookup_targets(self, phone: str) -> List[Tuple[str, str]]:
"""联表查询获取 phone 对应的 (group_id, bot_id) 对。"""
rows = self.db.execute(text(self._QUERY), {"phone": phone}).fetchall()
if not rows:
raise SendByPhoneError("号码未绑定微信群")
return [(row.group_id, row.bot_id) for row in rows] # type: ignore[union-attr]
async def send_by_phone(self, phone: str, content: str) -> Dict[str, object]:
"""按手机号查找群组并发送消息。"""
targets = self._lookup_targets(phone)
results: List[Tuple[str, bool, str]] = []
for group_id, bot_id in targets:
try:
resp = await self.im_service.send_message(
bot_id=bot_id,
content=content,
contact_id=group_id,
)
logger.info("发送成功: group_id=%s, bot_id=%s, resp=%s", group_id, bot_id, resp)
results.append((group_id, True, "ok"))
except IMServiceError as e:
logger.error("发送失败: group_id=%s, bot_id=%s, err=%s", group_id, bot_id, e)
results.append((group_id, False, str(e)))
success_count = sum(1 for _, ok, _ in results if ok)
return {
"success": success_count > 0,
"message": f"处理完成:共 {len(targets)} 个群,成功 {success_count} 个",
"details": [
{"group_id": gid, "success": ok, "error": msg if not ok else None}
for gid, ok, msg in results
],
}
......@@ -93,6 +93,8 @@ async def lifespan(app: FastAPI):
api_key=os.getenv("IM_API_KEY", settings.im.api_key),
)
app.state.im_service = im_service
agent_hub_instance = AgentHub(
config_loader=config_loader,
session_service=session_service,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!