Files
yunke/yunke-server/app/api/routers/customer.py
T
浅念 edca9b4c77 fix(customers): WA客户破1万上限(逐员工uid过滤,8585→11931全量)+双渠道页脚云客口径+消息同步刷新最近沟通时间
- wa-friends 逐员工抓取:全局查询~1万行硬上限(云客11931只翻到10000),
  uid=员工WA号过滤(真机验证 declared 1145→1149),total-aware翻页
- declared-total 分渠道:Σ wechat/whatsapp_account.contacts_num(8590/11915)
- 消息增量同步顺带刷新 customer.last_chat_time(云客列表按最近沟通实时
  排序,快照每日一次导致顺序滞后;微信1:1+WA都加)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-20 14:04:06 +08:00

117 lines
4.4 KiB
Python

"""GET /api/customers — paginated, filterable customer list.
Read-only query over the mirrored ``customer`` table. Supports filtering by
``channel``, ``owner_account_id``, ``user_id``, ``add_time_since`` and
``last_chat_since`` (direct columns) and ``department_id`` (resolved through
``customer.user_id`` -> ``staff.dept_id``). Results are ordered by
``last_chat_time desc`` (nulls last) then ``friend_id`` so the
most-recently-active contacts surface first.
"""
from __future__ import annotations
from typing import Annotated
import sqlalchemy as sa
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_session
from app.api.schemas import CustomerOut, Page
from app.db.models import Customer, Staff, WechatAccount
router = APIRouter(prefix="/api", tags=["customers"])
SessionDep = Annotated[AsyncSession, Depends(get_session)]
PageParam = Annotated[int, Query(ge=1)]
PageSizeParam = Annotated[int, Query(ge=1, le=100)]
@router.get("/customers/declared-total")
async def customers_declared_total(session: SessionDep) -> dict:
"""云客口径的客户合计(分渠道)= Σ 员工账号表的 contacts_num 声明值。
云客列表的页脚数字含 ES 索引重复条目(实测 csf 员工声明 1999 vs 真实
distinct 1449,连行 id 都相同的重复 doc,2026-08-20;WA 同理 11931 vs
8674);本地表存去重真实客户,此端点把「与云客页脚一字不差」的声明口径
给前端展示。
"""
from app.db.models import WhatsappAccount
wechat = (
await session.execute(
sa.select(
sa.func.coalesce(sa.func.sum(WechatAccount.contacts_num), 0),
sa.func.count(WechatAccount.contacts_num),
)
)
).one()
whatsapp = (
await session.execute(
sa.select(
sa.func.coalesce(sa.func.sum(WhatsappAccount.contacts_num), 0),
sa.func.count(WhatsappAccount.contacts_num),
)
)
).one()
return {
"wechat": {"declared_total": int(wechat[0]), "account_count": int(wechat[1])},
"whatsapp": {"declared_total": int(whatsapp[0]), "account_count": int(whatsapp[1])},
}
@router.get("/customers")
async def list_customers(
session: SessionDep,
page: PageParam = 1,
page_size: PageSizeParam = 20,
channel: Annotated[str | None, Query()] = None,
department_id: Annotated[str | None, Query()] = None,
owner_account_id: Annotated[str | None, Query()] = None,
friend_id: Annotated[str | None, Query()] = None,
user_id: Annotated[str | None, Query()] = None,
add_time_since: Annotated[int | None, Query(ge=0)] = None,
last_chat_since: Annotated[int | None, Query(ge=0)] = None,
) -> Page[CustomerOut]:
"""List customers with optional filters and pagination."""
conditions = []
if channel is not None:
conditions.append(Customer.channel == channel)
if owner_account_id is not None:
conditions.append(Customer.owner_account_id == owner_account_id)
if department_id is not None:
# Customer has no dept column; resolve via the owning staff member.
dept_user_ids = sa.select(Staff.user_id).where(
Staff.dept_id == department_id
)
conditions.append(Customer.user_id.in_(dept_user_ids))
if friend_id is not None:
conditions.append(Customer.friend_id == friend_id)
if user_id is not None:
conditions.append(Customer.user_id == user_id)
if add_time_since is not None:
conditions.append(Customer.add_time >= add_time_since)
if last_chat_since is not None:
conditions.append(Customer.last_chat_time >= last_chat_since)
total_stmt = sa.select(sa.func.count()).select_from(Customer)
if conditions:
total_stmt = total_stmt.where(*conditions)
total = (await session.execute(total_stmt)).scalar_one()
list_stmt = sa.select(Customer)
if conditions:
list_stmt = list_stmt.where(*conditions)
list_stmt = (
list_stmt.order_by(
sa.nullslast(Customer.last_chat_time.desc()),
Customer.friend_id.asc(),
)
.limit(page_size)
.offset((page - 1) * page_size)
)
rows = (await session.execute(list_stmt)).scalars().all()
items = [CustomerOut.model_validate(row) for row in rows]
return Page(items=items, total=total, page=page, page_size=page_size)