"""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) if (channel or "wechat") == "wechat": # 云客「微信群统计」同款排序(2026-09-10 真机终判):owner_account_id # (=微信号/wxid 混存,如 Nancyjade < csf7169708 < wxid_01gv…——大写 # 在小写前=区分大小写)**二进制字节序升序**分组,组内 room_id 字符串 # 升序。字节序按方言:MySQL 用 CAST(col AS BINARY)(collate("BINARY") # 会被 SQLAlchemy 反引号成标识符);SQLite 用 COLLATE BINARY(其 CAST # AS BINARY 语义不符)。WA 保持最近活跃优先。 dialect = session.bind.dialect.name if session.bind is not None else "" if dialect == "mysql": owner_order = sa.literal_column( "CAST(chat_group.owner_account_id AS BINARY)" ).asc() else: owner_order = ChatGroup.owner_account_id.collate("BINARY").asc() list_stmt = ( list_stmt.order_by( owner_order, ChatGroup.room_id.asc(), ) .limit(page_size) .offset((page - 1) * page_size) ) else: 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]