api.py 2.53 KB
from __future__ import annotations

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,
    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"])


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(
        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))


@router.get("/phone", response_model=ApiResponse[CustomerGroupPhoneResponse])
def get_phone(
    group_id: str,
    service: CustomerInfoService = Depends(get_customer_info_service),
):
    """查询群手机号绑定信息。"""
    record = service.get_phone(group_id)
    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"])