Files
yunke/yunke-server/app/api/routers/calls.py
T
浅念 4aeed003a4 feat(calls): 微信语音列表加今日统计卡片+通话时间范围筛选+客户跳转带通话时间定位(对齐云客)
- GET /api/calls/stats:今日(Asia/Shanghai)好友呼入/外呼量+群量+时长聚合(@chatroom判群)
- CallList:5张统计卡片(仅微信语音tab)+datetimerange筛选(服务端start/end)+viewCallCustomer带?start定位
- TDD新增stats聚合测试,全量绿

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-20 11:08:13 +08:00

115 lines
4.6 KiB
Python

"""GET /api/calls — phone-call / voice-call log list.
Read-only query over the mirrored ``phone_call`` table. ``channel`` here is the
**call-type** in {``phone_call``, ``voice_call``} (calls are not tied to a
messaging channel). Filters: ``channel``, ``user_id``, and a ms-epoch
``[start, end]`` window compared against ``start_call_time`` (inclusive).
Ordered by ``start_call_time desc`` (nulls last) — most recent calls first.
"""
from __future__ import annotations
import datetime as dt
from typing import Annotated, Literal
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 CallStatsOut, Page, PhoneCallOut
from app.db.models import PhoneCall
router = APIRouter(prefix="/api", tags=["calls"])
SessionDep = Annotated[AsyncSession, Depends(get_session)]
PageParam = Annotated[int, Query(ge=1)]
PageSizeParam = Annotated[int, Query(ge=1, le=100)]
@router.get("/calls/stats")
async def call_stats(session: SessionDep) -> CallStatsOut:
"""今日(Asia/Shanghai)微信语音统计卡片 — 对齐云客语音列表顶部。
好友/群按 ``call_number`` 是否以 ``@chatroom`` 结尾(与 ``scope`` 同判据,
与云客 isRoom 实测等价);呼入/出按 ``incoming_call``(1=呼入/0=呼出,
None 不计)。
"""
# Asia/Shanghai (UTC+8) 的今日 00:00 → ms epoch,与 /api/sessions 的
# today_start 同一约定(部署时区无关)
shanghai_now = dt.datetime.now(dt.UTC) + dt.timedelta(hours=8)
shanghai_midnight = shanghai_now.replace(hour=0, minute=0, second=0, microsecond=0)
today_start_ms = int((shanghai_midnight - dt.timedelta(hours=8)).timestamp() * 1000)
is_room = PhoneCall.call_number.endswith("@chatroom")
base = [PhoneCall.channel == "voice_call", PhoneCall.start_call_time >= today_start_ms]
async def _count(*extra) -> int:
stmt = sa.select(sa.func.count()).select_from(PhoneCall).where(*base, *extra)
return (await session.execute(stmt)).scalar_one()
async def _duration(*extra) -> int:
stmt = sa.select(sa.func.coalesce(sa.func.sum(PhoneCall.call_duration), 0)).where(*base, *extra)
return (await session.execute(stmt)).scalar_one()
friend = ~is_room
return CallStatsOut(
friend_incoming=await _count(friend, PhoneCall.incoming_call == 1),
friend_outgoing=await _count(friend, PhoneCall.incoming_call == 0),
group_count=await _count(is_room),
friend_incoming_duration=await _duration(friend, PhoneCall.incoming_call == 1),
friend_outgoing_duration=await _duration(friend, PhoneCall.incoming_call == 0),
group_duration=await _duration(is_room),
)
@router.get("/calls")
async def list_calls(
session: SessionDep,
page: PageParam = 1,
page_size: PageSizeParam = 20,
channel: Annotated[str | None, Query()] = None,
user_id: Annotated[str | None, Query()] = None,
start: Annotated[int | None, Query(ge=0)] = None,
end: Annotated[int | None, Query(ge=0)] = None,
scope: Annotated[Literal["friend", "group"] | None, Query()] = None,
) -> Page[PhoneCallOut]:
"""List phone/voice calls with optional filters, newest first.
``scope`` filters voice calls by peer kind: ``group`` keeps only group
calls (``call_number`` ends ``@chatroom``), ``friend`` excludes them —
verified exactly equivalent to the CRM's ``isRoom`` flag (2026-08-18).
"""
conditions = []
if channel is not None:
conditions.append(PhoneCall.channel == channel)
if user_id is not None:
conditions.append(PhoneCall.user_id == user_id)
if scope is not None:
is_room = PhoneCall.call_number.endswith("@chatroom")
conditions.append(is_room if scope == "group" else ~is_room)
if start is not None:
conditions.append(PhoneCall.start_call_time >= start)
if end is not None:
conditions.append(PhoneCall.start_call_time <= end)
total_stmt = sa.select(sa.func.count()).select_from(PhoneCall)
if conditions:
total_stmt = total_stmt.where(*conditions)
total = (await session.execute(total_stmt)).scalar_one()
list_stmt = sa.select(PhoneCall)
if conditions:
list_stmt = list_stmt.where(*conditions)
list_stmt = (
list_stmt.order_by(
sa.nullslast(PhoneCall.start_call_time.desc()),
PhoneCall.call_id.asc(),
)
.limit(page_size)
.offset((page - 1) * page_size)
)
rows = (await session.execute(list_stmt)).scalars().all()
items = [PhoneCallOut.model_validate(row) for row in rows]
return Page(items=items, total=total, page=page, page_size=page_size)