feat: customer list API
Minimal read-only FastAPI surface over the mirrored DB: - GET /api/customers with pagination (page/page_size) and optional channel / owner_account_id / department_id filters, ordered by last_chat_time desc (nulls last) then friend_id. - GET /api/health liveness probe. - Pydantic v2 CustomerOut + generic Page[T] envelope. - CORS configured permissively for the local frontend. - Tests override get_session to an in-memory async SQLite session (StaticPool) and drive the app via httpx ASGITransport. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
"""FastAPI layer for the yunke data-mirror viewing API.
|
||||
|
||||
Read-only HTTP surface over the mirrored DB. Public entrypoint is
|
||||
:mod:`app.api.main` (``app = FastAPI(...)``). Routers live under
|
||||
:mod:`app.api.routers` and share dependencies from :mod:`app.api.deps`.
|
||||
"""
|
||||
@@ -0,0 +1,10 @@
|
||||
"""FastAPI dependencies for the yunke data-mirror API.
|
||||
|
||||
Re-exports :func:`app.db.base.get_session` so route code (and tests) depend on
|
||||
a single API-layer seam. Tests override ``app.api.deps.get_session`` to swap in
|
||||
an isolated in-memory SQLite session.
|
||||
"""
|
||||
|
||||
from app.db.base import get_session
|
||||
|
||||
__all__ = ["get_session"]
|
||||
@@ -0,0 +1,37 @@
|
||||
"""FastAPI app for the yunke data-mirror viewing API.
|
||||
|
||||
Run locally with::
|
||||
|
||||
uvicorn app.api.main:app --reload
|
||||
|
||||
Includes:
|
||||
* ``GET /api/health`` -> ``{"status": "ok"}`` liveness probe.
|
||||
* ``GET /api/customers`` (see :mod:`app.api.routers.customer`).
|
||||
|
||||
CORS is configured permissively (wildcard origin, no credentials) so the local
|
||||
frontend can call the API during development. Auth / finer CORS are LATER tasks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api.routers import customer
|
||||
|
||||
app = FastAPI(title="yunke data mirror")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(customer.router)
|
||||
|
||||
|
||||
@app.get("/api/health")
|
||||
async def health() -> dict[str, str]:
|
||||
"""Trivial liveness probe."""
|
||||
return {"status": "ok"}
|
||||
@@ -0,0 +1 @@
|
||||
"""HTTP routers for the yunke data-mirror API."""
|
||||
@@ -0,0 +1,70 @@
|
||||
"""GET /api/customers — paginated, filterable customer list.
|
||||
|
||||
Read-only query over the mirrored ``customer`` table. Supports filtering by
|
||||
``channel``, ``owner_account_id`` (direct columns) and ``department_id``
|
||||
(resolved through ``customer.user_id`` -> ``staff.dept_id``). Results are
|
||||
ordered by ``last_chat_time desc`` (nulls last) then ``friend_id`` so the
|
||||
most-recently-active contacts surface first.
|
||||
"""
|
||||
|
||||
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, Staff
|
||||
|
||||
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")
|
||||
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,
|
||||
) -> Page[CustomerOut]:
|
||||
"""List customers with optional filters and pagination."""
|
||||
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 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))
|
||||
|
||||
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()
|
||||
items = [CustomerOut.model_validate(row) for row in rows]
|
||||
return Page(items=items, total=total, page=page, page_size=page_size)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Pydantic v2 response models for the yunke data-mirror API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user