"""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), ``department_id`` (resolved through ``customer.user_id`` -> ``staff.dept_id``) and ``q`` (substring match on nickname / remark / friend_id / phone, ``%``/``_`` escaped as literals — the 通讯录 search box). Results are ordered by ``last_chat_time desc`` (nulls last) then ``friend_id`` so the most-recently-active contacts surface first. **owner_account_id 维度走 ``customer_account_link``**(2026-09-08):customer 档案 PK=friend_id 全局单行、归属 last-wins,共享客户在其他员工名下会漏 (实测 36 vs 12);link 表每个「渠道×账号×客户」一行,员工维度列表/计数与 云客 per-employee 口径一致。带 department/user/add_time/last_chat 等其余 过滤时回退档案路径(组合场景罕见,保持旧行为)。 """ 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, CustomerAccountLink, 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])}, } async def _list_owner_links( session: AsyncSession, *, page: int, page_size: int, channel: str | None, owner_account_id: str, friend_id: str | None, q: str | None, ) -> Page[CustomerOut]: """员工维度客户列表:读 ``customer_account_link``(渠道×账号×客户一行)。 排序/搜索语义与档案路径一致(last_chat_time desc、四列模糊);link 自带 per-relation 快照(备注/收发计数按员工各一份,与云客 per-employee 列表 相同)。CustomerOut 的档案专属列(raw_json/version/send_today 等)为 None。 """ conditions = [CustomerAccountLink.owner_account_id == owner_account_id] if channel is not None: conditions.append(CustomerAccountLink.channel == channel) if friend_id is not None: conditions.append(CustomerAccountLink.friend_id == friend_id) if q: # LIKE 通配符转义(同档案路径):昵称/备注/微信号/手机号四列任一命中 escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") like = f"%{escaped}%" conditions.append( sa.or_( CustomerAccountLink.friend_nickname.like(like, escape="\\"), CustomerAccountLink.friend_remark.like(like, escape="\\"), CustomerAccountLink.friend_id.like(like, escape="\\"), CustomerAccountLink.phone.like(like, escape="\\"), ) ) total = ( await session.execute( sa.select(sa.func.count()) .select_from(CustomerAccountLink) .where(*conditions) ) ).scalar_one() # LEFT JOIN 档案带 raw_json(2026-09-09):WA 客户列表大量列只存在于 # raw_json(userName/salePhone/createTime 等员工侧字段),link 快照没存; # raw_json 按 friend_id 全局一份,挂谁名下内容相同。注:共享客户的员工 # 侧字段是「最后写入员工」的记录,可能非本员工(客户自身字段不受影响)。 rows = ( await session.execute( sa.select(CustomerAccountLink, Customer.raw_json, Customer.version) .outerjoin(Customer, Customer.friend_id == CustomerAccountLink.friend_id) .where(*conditions) .order_by( sa.nullslast(CustomerAccountLink.last_chat_time.desc()), CustomerAccountLink.friend_id.asc(), ) .limit(page_size) .offset((page - 1) * page_size) ) ).all() items = [] for link, raw_json, version in rows: out = CustomerOut.model_validate(link) out.raw_json = raw_json if version is not None: out.version = version items.append(out) return Page(items=items, total=total, page=page, page_size=page_size) @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, q: Annotated[str | None, Query()] = None, ) -> Page[CustomerOut]: """List customers with optional filters and pagination.""" # 员工维度优先走 link 表(共享好友每账号一行,见模块 docstring);该账号 # link 还无数据时回退档案路径(过渡安全:回填前页面不至于空;也兼容 # 只写档案的理论路径)。与其余仅档案路径支持的过滤组合时同样回退。 if ( owner_account_id is not None and department_id is None and user_id is None and add_time_since is None and last_chat_since is None ): link_exists = ( await session.execute( sa.select(sa.func.count()) .select_from(CustomerAccountLink) .where(CustomerAccountLink.owner_account_id == owner_account_id) ) ).scalar_one() if link_exists: return await _list_owner_links( session, page=page, page_size=page_size, channel=channel, owner_account_id=owner_account_id, friend_id=friend_id, q=q, ) 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 q: # LIKE 通配符转义: %/_ 按字面匹配(镜像 messages.py 的 q 处理)。 # 对齐云客通讯录搜索:昵称/微信号/备注名/手机号四列任一含词即命中。 escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") like = f"%{escaped}%" conditions.append( sa.or_( Customer.friend_nickname.like(like, escape="\\"), Customer.friend_remark.like(like, escape="\\"), Customer.friend_id.like(like, escape="\\"), Customer.phone.like(like, escape="\\"), ) ) 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() # 今日发送/接收条数(对齐云客口径):本地消息表按 Asia/Shanghai 今日聚合, # 一次 GROUP BY 覆盖本页(owner IN 走 ix_message_channel_owner_talker_time 前缀) import datetime as _dt from app.db.models import Message sh_now = _dt.datetime.now(_dt.UTC) + _dt.timedelta(hours=8) today_start_ms = int( (sh_now.replace(hour=0, minute=0, second=0, microsecond=0) - _dt.timedelta(hours=8)).timestamp() * 1000 ) owners = sorted({r.owner_account_id for r in rows if r.owner_account_id}) today_counts: dict[tuple[str, str], tuple[int, int]] = {} if owners: stat_rows = ( await session.execute( sa.select( Message.owner_account_id, Message.talker_id, sa.func.sum(sa.case((Message.is_send.is_(True), 1), else_=0)), sa.func.sum(sa.case((Message.is_send.is_(False), 1), else_=0)), ) .where( Message.channel == (channel or "wechat"), Message.owner_account_id.in_(owners), Message.timestamp >= today_start_ms, ) .group_by(Message.owner_account_id, Message.talker_id) ) ).all() today_counts = {(o, t): (int(s or 0), int(rc or 0)) for o, t, s, rc in stat_rows} items = [] for row in rows: item = CustomerOut.model_validate(row) s, rc = today_counts.get((row.owner_account_id or "", row.friend_id or ""), (0, 0)) item.send_today = s item.receive_today = rc items.append(item) return Page(items=items, total=total, page=page, page_size=page_size)