Files
yunke/yunke-server/app/api/schemas.py
T
浅念 ff7e9cb1d9 feat: backend read api for all entities (messages/groups/calls/sms/org/sync)
Adds the read-only API surface the upcoming Vue frontend needs to browse all
mirrored entities. Follows the existing customer-router pattern: Annotated
deps, Page[T] envelope, select+where+order_by, count() for total.

Endpoints (all GET):
* /api/departments          -> list[DepartmentOut] (path-ordered, plain list)
* /api/staff                -> Page[StaffOut] (department_id, is_on_job filters)
* /api/accounts             -> Page[AccountOut] (channel filter; unified
                             wechat+whatsapp projection built in memory)
* /api/messages             -> Page[MessageOut] (channel/owner/talker/room/
                             [start,end] filters; ordered timestamp asc)
* /api/groups               -> Page[GroupOut] (channel/owner filters)
* /api/groups/{id}/members  -> list[GroupMemberOut] (404 on unknown room)
* /api/calls                -> Page[PhoneCallOut] (channel/user/time window;
                             ordered start_call_time desc)
* /api/sms                  -> Page[SmsOut] (user/time window; create_time desc)
* /api/sync/status          -> {states, recent_runs} monitor payload

Schemas (Pydantic v2, from_attributes=True): MessageOut, GroupOut,
GroupMemberOut, PhoneCallOut, SmsOut, DepartmentOut, StaffOut, AccountOut
(unified across two tables), SyncStateOut, SyncRunOut, SyncStatusOut.
Only human-relevant fields per entity are exposed.

Tests: per-router TDD via httpx ASGITransport against an in-memory SQLite
override of get_session. A shared make_client factory in conftest.py builds
the seeded client, deduping the ~40-line fixture across the six new files.
41 new tests cover shape + every documented filter + pagination + ordering
(nulls-last verified on all desc/asc time columns).

Suite: 226 -> 267 passing. ruff check clean.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-08-01 16:15:40 +08:00

224 lines
5.9 KiB
Python

"""Pydantic v2 response models for the yunke data-mirror API."""
from __future__ import annotations
import datetime as dt
from typing import Generic, TypeVar
from pydantic import BaseModel, ConfigDict
T = TypeVar("T")
class CustomerOut(BaseModel):
"""Public Customer view — a subset of :class:`app.db.models.Customer`.
Only the fields the viewing frontend needs today are exposed; the verbatim
``raw_json`` blob and internal audit columns stay server-side.
"""
model_config = ConfigDict(from_attributes=True)
friend_id: str
channel: str
owner_account_id: str | None = None
friend_nickname: str | None = None
friend_remark: str | None = None
real_name: str | None = None
phone: str | None = None
region: str | None = None
sale_name: str | None = None
dept_name: str | None = None
head_image_url: str | None = None
last_chat_time: int | None = None
message_count: int | None = None
version: str | None = None
class Page(BaseModel, Generic[T]):
"""Generic pagination envelope returned by list endpoints."""
items: list[T]
total: int
page: int
page_size: int
# ---------------------------------------------------------------------------
# Organization & people
# ---------------------------------------------------------------------------
class DepartmentOut(BaseModel):
"""云客 department node — frontend builds the tree from ``parent_id``/``path``."""
model_config = ConfigDict(from_attributes=True)
dept_id: str
parent_id: str | None = None
name: str | None = None
path: str | None = None
class StaffOut(BaseModel):
"""Staff member (employee) row."""
model_config = ConfigDict(from_attributes=True)
user_id: str
name: str | None = None
phone: str | None = None
sale_phone: str | None = None
dept_id: str | None = None
is_on_job: bool | None = None
class AccountOut(BaseModel):
"""Unified staff messaging account (WeChat or WhatsApp).
The two source tables (:class:`WechatAccount`, :class:`WhatsappAccount`)
have different PK / column names; this view projects both onto a single
shape keyed by ``channel`` + ``account_id`` so the frontend can render one
list. Built explicitly in the route handler (not via ``from_attributes``)
because no single ORM row carries this schema.
"""
channel: str
account_id: str
nickname: str | None = None
user_id: str | None = None
user_name: str | None = None
phone: str | None = None
contacts_num: int | None = None
group_num: int | None = None
is_on_job: bool | None = None
# ---------------------------------------------------------------------------
# Communication entities
# ---------------------------------------------------------------------------
class MessageOut(BaseModel):
"""Chat timeline row — a single message (text/media/voice/...)."""
model_config = ConfigDict(from_attributes=True)
msg_id: str
channel: str
owner_account_id: str | None = None
talker_id: str | None = None
room_id: str | None = None
is_send: bool | None = None
type: str | None = None
type_raw: int | None = None
text: str | None = None
file_url: str | None = None
sender_name: str | None = None
sender_head_url: str | None = None
timestamp: int | None = None
class GroupOut(BaseModel):
"""Chat group summary row."""
model_config = ConfigDict(from_attributes=True)
room_id: str
channel: str
room_name: str | None = None
owner_account_id: str | None = None
owner_account_nickname: str | None = None
member_count: int | None = None
message_count: int | None = None
last_chat_time: int | None = None
class GroupMemberOut(BaseModel):
"""Member of a chat group (composite PK: channel + room_id + member_id)."""
model_config = ConfigDict(from_attributes=True)
channel: str
room_id: str
member_id: str
nickname: str | None = None
display_name: str | None = None
avatar: str | None = None
class PhoneCallOut(BaseModel):
"""Phone / voice call record. ``channel`` is the call-type."""
model_config = ConfigDict(from_attributes=True)
call_id: str
channel: str
start_call_time: int | None = None
call_duration: int | None = None
call_status: int | None = None
incoming_call: int | None = None
user_id: str | None = None
user_id_name: str | None = None
call_number: str | None = None
sim_phone: str | None = None
class SmsOut(BaseModel):
"""SMS log row."""
model_config = ConfigDict(from_attributes=True)
sms_id: str
customer_phone: str | None = None
content_preview: str | None = None
sender: str | None = None
direction: int | None = None
user_id: str | None = None
receive_name: str | None = None
create_time: int | None = None
sim_phone: str | None = None
# ---------------------------------------------------------------------------
# Sync monitor
# ---------------------------------------------------------------------------
class SyncStateOut(BaseModel):
"""Resumable sync cursor (one per entity/channel/scope)."""
model_config = ConfigDict(from_attributes=True)
state_id: int
entity_type: str
channel: str | None = None
scope_id: str | None = None
last_version: str | None = None
last_timestamp: int | None = None
last_synced_at: dt.datetime | None = None
class SyncRunOut(BaseModel):
"""Audit row for a single sync execution."""
model_config = ConfigDict(from_attributes=True)
run_id: int
entity_type: str
channel: str | None = None
scope_id: str | None = None
status: str
started_at: dt.datetime
finished_at: dt.datetime | None = None
records_fetched: int
records_upserted: int
error: str | None = None
class SyncStatusOut(BaseModel):
"""Aggregate monitor payload — current cursors plus recent runs."""
states: list[SyncStateOut]
recent_runs: list[SyncRunOut]