Files
yunke/yunke-server/app/api/routers/groups.py
T
浅念 b0ebe8a15a feat(group-stats): 微信群列表对齐云客「微信群统计」——getChatroomList 数据源+窗内统计
用户报微信群列表数据/内容不对,应对齐云客「沟通→微信号管理→微信群统计」
(/cms/wechat/wechatgroup)。真机探明(表单登录+页面导航抓 network):

- 数据源=POST /wechatweb/chatroom/getChatroomList(form:departmentId+
  startTime/endTime 窗+分页;信封 data.overviews[]/totalCount 1,854 行)
- 云客窗是任意时间窗实时算:沟通消息数实测同群全史 417/7天 36/单日 6
- **修正存量映射错误**:member_count 原存 friendNum(员工好友数),真群成员
  数是 friendCount/getChatroomList.memberCount
- 新增/退出成员数云客按窗实时算,本地无事件流 → 按天积累

实现:
- ChatGroup 补 group_remark 列(备注仅 friend_list/es 携带,两归一化均
  「有值才写」防互清);迁移含存量 raw_json 回填(须先于基线抓取执行)
- 新表 chat_group_member_stats(渠道×账号×群×天一行 added/lost)
- 新实体 chatroom-stats:全窗刷档案列(真成员数/群备注/员工信息,owner
  经 wechat_account alias 解析)+ --day 单日窗落进出日行;full_sync 5c 步
- /api/groups 扩展:msg_start/msg_end 窗内聚合(window_msg_count=
  msg_daily_stats 按天和、window_added/lost=日表和)、last_start/end
  最新消息窗、group_remark 子串;行补员工微信/员工信息关联列
- GroupList 微信 tab:统计时段(默认近7天)/最新消息时间段/群名称/群备注/
  员工下拉/查询 + 9 列(群信息|群备注|员工微信|员工信息|群成员数量|
  新增成员数|退出成员数|沟通消息数|操作);WA tab 不动

700 测试绿(新增窗聚合/筛选/员工列 3 例)。本地实测:基线 1,854 群=云客
total 一字不差,今日日窗 added 407/lost 166 落表,页面 9 列/员工列渲染正常。

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-09 18:09:20 +08:00

221 lines
9.5 KiB
Python

"""GET /api/groups, /api/groups/{room_id}/members — chat-group browse endpoints.
* ``GET /api/groups`` -> ``Page[GroupOut]`` filtered by ``channel`` /
``owner_account_id`` / ``user_id`` (the latter mapping to the
``owner_user_id`` column) and ``q`` (substring match on ``room_name``,
``%``/``_`` escaped as literals — the 通讯录群 tab search box), ordered by
``last_chat_time desc`` (nulls last) so recently-active groups surface first.
微信群统计扩展(2026-09-09,云客「微信群统计」同款):``msg_start``/``msg_end``
统计时段(窗内输出沟通消息数/新增/退出成员数聚合)、``last_start``/
``last_end`` 最新消息时间段、``group_remark`` 群备注子串;行补员工微信/
员工信息列(wechat_account/staff 关联)。
* ``GET /api/groups/{room_id}/members`` -> ``list[GroupMemberOut]`` — the
members of a single group (small set, no pagination needed).
"""
from __future__ import annotations
from typing import Annotated
import sqlalchemy as sa
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_session
from app.api.schemas import GroupMemberOut, GroupOut, Page
from app.db.models import (
ChatGroup,
ChatGroupMemberStats,
GroupMember,
MsgDailyStats,
Staff,
WechatAccount,
)
from app.storage.summary import day_key
router = APIRouter(prefix="/api", tags=["groups"])
SessionDep = Annotated[AsyncSession, Depends(get_session)]
PageParam = Annotated[int, Query(ge=1)]
PageSizeParam = Annotated[int, Query(ge=1, le=100)]
@router.get("/groups")
async def list_groups(
session: SessionDep,
page: PageParam = 1,
page_size: PageSizeParam = 20,
channel: Annotated[str | None, Query()] = None,
owner_account_id: Annotated[str | None, Query()] = None,
user_id: Annotated[str | None, Query()] = None,
room_id: Annotated[str | None, Query()] = None,
q: Annotated[str | None, Query()] = None,
group_remark: Annotated[str | None, Query()] = None,
last_start: Annotated[int | None, Query(ge=0)] = None,
last_end: Annotated[int | None, Query(ge=0)] = None,
msg_start: Annotated[int | None, Query(ge=0)] = None,
msg_end: Annotated[int | None, Query(ge=0)] = None,
) -> Page[GroupOut]:
"""List chat groups with optional ``channel`` / ``owner_account_id`` /
``user_id`` / ``room_id`` / ``q`` filters.
``user_id`` maps to the ``ChatGroup.owner_user_id`` column (the staff
``userId`` who owns the chatroom account), mirroring the ``user_id``
filter on ``GET /api/customers``. ``room_id`` is an exact-match lookup
(composite PK: the same room may return one row per owner; chat page
group-name resolution). ``q`` is a substring match on ``room_name``.
微信群统计参数(2026-09-09):``last_start``/``last_end`` 过滤
``last_chat_time`` 范围(最新消息时间段);``msg_start``/``msg_end``
统计时段——窗内聚合三列(``window_msg_count`` 沟通消息数=
msg_daily_stats 按天求和、``window_added``/``window_lost`` 成员进出=
chat_group_member_stats 按天求和,上线日起有数据);``group_remark``
群备注子串。员工微信/员工信息列经 wechat_account/staff 关联补齐。
"""
conditions = []
if channel is not None:
conditions.append(ChatGroup.channel == channel)
if owner_account_id is not None:
conditions.append(ChatGroup.owner_account_id == owner_account_id)
if q:
# LIKE 通配符转义: %/_ 按字面匹配(镜像 customers/messages 的 q 处理)
escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
conditions.append(ChatGroup.room_name.like(f"%{escaped}%", escape="\\"))
if group_remark:
escaped_r = group_remark.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
conditions.append(ChatGroup.group_remark.like(f"%{escaped_r}%", escape="\\"))
if room_id is not None:
conditions.append(ChatGroup.room_id == room_id)
if user_id is not None:
conditions.append(ChatGroup.owner_user_id == user_id)
if last_start is not None:
conditions.append(ChatGroup.last_chat_time >= last_start)
if last_end is not None:
conditions.append(ChatGroup.last_chat_time <= last_end)
total_stmt = sa.select(sa.func.count()).select_from(ChatGroup)
if conditions:
total_stmt = total_stmt.where(*conditions)
total = (await session.execute(total_stmt)).scalar_one()
list_stmt = sa.select(ChatGroup)
if conditions:
list_stmt = list_stmt.where(*conditions)
list_stmt = (
list_stmt.order_by(
sa.nullslast(ChatGroup.last_chat_time.desc()),
ChatGroup.room_id.asc(),
)
.limit(page_size)
.offset((page - 1) * page_size)
)
rows = (await session.execute(list_stmt)).scalars().all()
# ---- 员工微信/员工信息列(wechat_account/staff 关联,本页行集) ----
acc_map: dict[str, tuple[str | None, str | None, str | None]] = {}
owners = {r.owner_account_id for r in rows if r.owner_account_id}
if owners:
for wx, nick, alias, raw in (await session.execute(
sa.select(
WechatAccount.wx_id, WechatAccount.nick_name,
WechatAccount.alias, WechatAccount.raw_json,
).where(WechatAccount.wx_id.in_(owners))
)).all():
avatar = None
if isinstance(raw, dict):
h = raw.get("headImageUrl")
avatar = h if isinstance(h, str) else None
acc_map[wx] = (nick, alias, avatar)
staff_map: dict[str, tuple[str | None, str | None]] = {}
uids = {r.owner_user_id for r in rows if r.owner_user_id}
if uids:
for uid, name, phone in (await session.execute(
sa.select(Staff.user_id, Staff.name, Staff.phone)
.where(Staff.user_id.in_(uids))
)).all():
staff_map[uid] = (name, phone)
# ---- 统计时段窗内聚合(msg_daily_stats 沟通消息数 + member_stats 进出) ----
msg_cnt: dict[tuple[str, str], int] = {}
added_map: dict[tuple[str, str], int] = {}
lost_map: dict[tuple[str, str], int] = {}
if msg_start is not None and msg_end is not None and rows:
d0, d1 = day_key(msg_start), day_key(msg_end)
pairs = [(r.owner_account_id, r.room_id) for r in rows]
owners_in = {p[0] for p in pairs}
rooms_in = {p[1] for p in pairs}
for owner, room, cnt in (await session.execute(
sa.select(
MsgDailyStats.owner_account_id, MsgDailyStats.peer_id,
sa.func.coalesce(sa.func.sum(
MsgDailyStats.send_cnt + MsgDailyStats.recv_cnt), 0),
).where(
MsgDailyStats.channel == (channel or "wechat"),
MsgDailyStats.peer_kind == "room",
MsgDailyStats.owner_account_id.in_(owners_in),
MsgDailyStats.peer_id.in_(rooms_in),
MsgDailyStats.day >= d0, MsgDailyStats.day <= d1,
).group_by(MsgDailyStats.owner_account_id, MsgDailyStats.peer_id)
)).all():
msg_cnt[(owner, room)] = int(cnt)
for owner, room, a, l in (await session.execute(
sa.select(
ChatGroupMemberStats.owner_account_id, ChatGroupMemberStats.room_id,
sa.func.coalesce(sa.func.sum(ChatGroupMemberStats.added), 0),
sa.func.coalesce(sa.func.sum(ChatGroupMemberStats.lost), 0),
).where(
ChatGroupMemberStats.channel == (channel or "wechat"),
ChatGroupMemberStats.owner_account_id.in_(owners_in),
ChatGroupMemberStats.room_id.in_(rooms_in),
ChatGroupMemberStats.day >= d0, ChatGroupMemberStats.day <= d1,
).group_by(ChatGroupMemberStats.owner_account_id, ChatGroupMemberStats.room_id)
)).all():
added_map[(owner, room)] = int(a)
lost_map[(owner, room)] = int(l)
items = []
for r in rows:
out = GroupOut.model_validate(r)
acc = acc_map.get(r.owner_account_id or "")
if acc:
out.staff_nickname, out.staff_wx_alias, out.staff_avatar = acc
st = staff_map.get(r.owner_user_id or "")
if st:
out.staff_name, out.staff_phone = st
if msg_start is not None and msg_end is not None:
key = (r.owner_account_id or "", r.room_id)
out.window_msg_count = msg_cnt.get(key, 0)
out.window_added = added_map.get(key, 0)
out.window_lost = lost_map.get(key, 0)
items.append(out)
return Page(items=items, total=total, page=page, page_size=page_size)
@router.get("/groups/{room_id}/members")
async def list_group_members(
room_id: str, session: SessionDep
) -> list[GroupMemberOut]:
"""Return the members of a single group (plain list).
Ordered by ``member_id`` for stable rendering. Returns ``404`` when no such
group exists so the frontend can distinguish "missing room" from "empty
room".
"""
exists = (
await session.execute(
sa.select(sa.func.count())
.select_from(ChatGroup)
.where(ChatGroup.room_id == room_id)
)
).scalar_one()
if not exists:
raise HTTPException(status_code=404, detail="group not found")
stmt = (
sa.select(GroupMember)
.where(GroupMember.room_id == room_id)
.order_by(GroupMember.member_id.asc())
)
rows = (await session.execute(stmt)).scalars().all()
return [GroupMemberOut.model_validate(row) for row in rows]