diff --git a/yunke-server/app/api/routers/customer.py b/yunke-server/app/api/routers/customer.py
index 142d40f..0f5716f 100644
--- a/yunke-server/app/api/routers/customer.py
+++ b/yunke-server/app/api/routers/customer.py
@@ -7,6 +7,12 @@ Read-only query over the mirrored ``customer`` table. Supports filtering by
nickname / remark / friend_id / phone, ``%``/``_`` escaped as literals — the
通讯录 search box). Results are ordered by ``last_chat_time desc`` (nulls
last) then ``friend_id`` so the most-recently-active contacts surface first.
+
+**owner_account_id 维度走 ``customer_account_link``**(2026-09-08):customer
+档案 PK=friend_id 全局单行、归属 last-wins,共享客户在其他员工名下会漏
+(实测 36 vs 12);link 表每个「渠道×账号×客户」一行,员工维度列表/计数与
+云客 per-employee 口径一致。带 department/user/add_time/last_chat 等其余
+过滤时回退档案路径(组合场景罕见,保持旧行为)。
"""
from __future__ import annotations
@@ -19,7 +25,7 @@ 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, WechatAccount
+from app.db.models import Customer, CustomerAccountLink, Staff, WechatAccount
router = APIRouter(prefix="/api", tags=["customers"])
@@ -61,6 +67,63 @@ async def customers_declared_total(session: SessionDep) -> dict:
}
+async def _list_owner_links(
+ session: AsyncSession,
+ *,
+ page: int,
+ page_size: int,
+ channel: str | None,
+ owner_account_id: str,
+ friend_id: str | None,
+ q: str | None,
+) -> Page[CustomerOut]:
+ """员工维度客户列表:读 ``customer_account_link``(渠道×账号×客户一行)。
+
+ 排序/搜索语义与档案路径一致(last_chat_time desc、四列模糊);link 自带
+ per-relation 快照(备注/收发计数按员工各一份,与云客 per-employee 列表
+ 相同)。CustomerOut 的档案专属列(raw_json/version/send_today 等)为 None。
+ """
+ conditions = [CustomerAccountLink.owner_account_id == owner_account_id]
+ if channel is not None:
+ conditions.append(CustomerAccountLink.channel == channel)
+ if friend_id is not None:
+ conditions.append(CustomerAccountLink.friend_id == friend_id)
+ if q:
+ # LIKE 通配符转义(同档案路径):昵称/备注/微信号/手机号四列任一命中
+ escaped = q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ like = f"%{escaped}%"
+ conditions.append(
+ sa.or_(
+ CustomerAccountLink.friend_nickname.like(like, escape="\\"),
+ CustomerAccountLink.friend_remark.like(like, escape="\\"),
+ CustomerAccountLink.friend_id.like(like, escape="\\"),
+ CustomerAccountLink.phone.like(like, escape="\\"),
+ )
+ )
+
+ total = (
+ await session.execute(
+ sa.select(sa.func.count())
+ .select_from(CustomerAccountLink)
+ .where(*conditions)
+ )
+ ).scalar_one()
+ rows = (
+ await session.execute(
+ sa.select(CustomerAccountLink)
+ .where(*conditions)
+ .order_by(
+ sa.nullslast(CustomerAccountLink.last_chat_time.desc()),
+ CustomerAccountLink.friend_id.asc(),
+ )
+ .limit(page_size)
+ .offset((page - 1) * page_size)
+ )
+ ).scalars().all()
+ items = [CustomerOut.model_validate(r) for r in rows]
+ return Page(items=items, total=total, page=page, page_size=page_size)
+
+
@router.get("/customers")
async def list_customers(
session: SessionDep,
@@ -76,6 +139,34 @@ async def list_customers(
q: Annotated[str | None, Query()] = None,
) -> Page[CustomerOut]:
"""List customers with optional filters and pagination."""
+ # 员工维度优先走 link 表(共享好友每账号一行,见模块 docstring);该账号
+ # link 还无数据时回退档案路径(过渡安全:回填前页面不至于空;也兼容
+ # 只写档案的理论路径)。与其余仅档案路径支持的过滤组合时同样回退。
+ if (
+ owner_account_id is not None
+ and department_id is None
+ and user_id is None
+ and add_time_since is None
+ and last_chat_since is None
+ ):
+ link_exists = (
+ await session.execute(
+ sa.select(sa.func.count())
+ .select_from(CustomerAccountLink)
+ .where(CustomerAccountLink.owner_account_id == owner_account_id)
+ )
+ ).scalar_one()
+ if link_exists:
+ return await _list_owner_links(
+ session,
+ page=page,
+ page_size=page_size,
+ channel=channel,
+ owner_account_id=owner_account_id,
+ friend_id=friend_id,
+ q=q,
+ )
+
conditions = []
if channel is not None:
conditions.append(Customer.channel == channel)
diff --git a/yunke-server/app/api/schemas.py b/yunke-server/app/api/schemas.py
index a44c288..6f4086b 100644
--- a/yunke-server/app/api/schemas.py
+++ b/yunke-server/app/api/schemas.py
@@ -43,6 +43,9 @@ class CustomerOut(BaseModel):
# 客户页「发送条数/接收条数」列用,2026-09-08)
send_num: int | None = None
receive_num: int | None = None
+ # 云客数据来源代码(customer_account_link 路径直读;档案路径为 None,
+ # 前端回退 raw_json.fromType)
+ from_type: int | None = None
version: str | None = None
# Verbatim upstream friend record (~60 camelCase fields). Surfaced so the
# all-fields drawer can render every column the 云客 source page shows
diff --git a/yunke-server/app/db/models.py b/yunke-server/app/db/models.py
index ac79117..a76568d 100644
--- a/yunke-server/app/db/models.py
+++ b/yunke-server/app/db/models.py
@@ -262,6 +262,46 @@ class Customer(Base):
)
+class CustomerAccountLink(Base):
+ """账号↔客户 多对多关联(customer_account_link,2026-09-08)。
+
+ ``customer`` 表 PK=``friend_id`` 全局一客户一行,归属=最后抓取员工
+ (last-wins)——共享客户(同一人加多个员工)在其他员工名下「消失」:
+ 实测 Lily 云客好友 36 vs 镜像页面 12,24 个全在别的员工名下。云客
+ 的口径是**每个账号各算一个**(per-employee 列表连备注/收发计数都按
+ 关系各存一份);本表每个「渠道×账号×客户」一行,由
+ :func:`app.storage.repos.upsert_customer` 随档案同事务维护,员工维度
+ 的列表/计数(`/api/customers?owner_account_id=`)读这里。
+
+ 快照列为员工客户页所需(昵称/备注/头像 per-relation);全字段档案
+ (raw_json/60 列)仍在 ``customer`` 表按 friend_id 关联。
+ """
+
+ __tablename__ = "customer_account_link"
+
+ channel: Mapped[str] = mapped_column(String(16), primary_key=True)
+ owner_account_id: Mapped[str] = mapped_column(String(128), primary_key=True)
+ friend_id: Mapped[str] = mapped_column(String(128), primary_key=True)
+ # per-relation 展示快照(云客好友记录按员工各一份;备注是员工自己的)
+ friend_nickname: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ friend_remark: Mapped[str | None] = mapped_column(String(255), nullable=True)
+ head_image_url: Mapped[str | None] = mapped_column(String(1024), nullable=True)
+ real_name: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ phone: Mapped[str | None] = mapped_column(String(64), nullable=True)
+ last_chat_time: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
+ add_time: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
+ send_num: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ receive_num: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ message_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # 云客 fromType 代码(数据来源列;int,前端 fromTypeLabel 映射)
+ from_type: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # 同 customer.delete_flag 口径(int 0/1)
+ delete_flag: Mapped[int | None] = mapped_column(Integer, nullable=True)
+
+ fetched_at: Mapped[dt.datetime] = _fetched_at()
+ updated_at: Mapped[dt.datetime] = _updated_at()
+
+
class ChatGroup(Base):
"""聊天群 — source: ``POST /wechatweb/chatroom/getChatroomList``.
diff --git a/yunke-server/app/storage/repos.py b/yunke-server/app/storage/repos.py
index 0421bde..9dedd85 100644
--- a/yunke-server/app/storage/repos.py
+++ b/yunke-server/app/storage/repos.py
@@ -63,6 +63,7 @@ from sqlalchemy.orm import DeclarativeBase
from app.db.models import (
ChatGroup,
Customer,
+ CustomerAccountLink,
Department,
GroupMember,
Media,
@@ -83,6 +84,7 @@ __all__ = [
"upsert_chat_group",
"upsert_customer",
"upsert_customers",
+ "prune_customer_links",
"upsert_department",
"upsert_media",
"upsert_messages",
@@ -380,9 +382,34 @@ async def upsert_customer(session: AsyncSession, rec: dict[str, Any]) -> None:
"""Idempotently upsert one :class:`Customer` (PK = ``friend_id``).
Same ``friend_id`` twice -> one row, with non-PK fields refreshed from the
- later record.
+ later record. 同时维护 ``customer_account_link``(渠道×账号×客户一行,
+ 2026-09-08):customer 档案全局单行 last-wins,共享客户的其他员工关系
+ 靠 link 表保留;员工维度列表/计数读 link(对齐云客 per-employee 口径)。
"""
await _upsert_one(session, Customer, rec)
+ owner = rec.get("owner_account_id")
+ if owner:
+ raw = rec.get("raw_json") or {}
+ link_rec = {
+ "channel": rec.get("channel"),
+ "owner_account_id": owner,
+ "friend_id": rec.get("friend_id"),
+ "friend_nickname": rec.get("friend_nickname"),
+ "friend_remark": rec.get("friend_remark"),
+ "head_image_url": rec.get("head_image_url"),
+ "real_name": rec.get("real_name"),
+ "phone": rec.get("phone"),
+ "last_chat_time": rec.get("last_chat_time"),
+ "add_time": rec.get("add_time"),
+ "send_num": rec.get("send_num"),
+ "receive_num": rec.get("receive_num"),
+ "message_count": rec.get("message_count"),
+ "delete_flag": rec.get("delete_flag"),
+ }
+ # fromType 只在 raw_json(云客数据来源代码,员工客户页列)
+ if isinstance(raw, dict) and raw.get("fromType") is not None:
+ link_rec["from_type"] = raw.get("fromType")
+ await _upsert_one(session, CustomerAccountLink, link_rec)
async def upsert_customers(session: AsyncSession, recs: list[dict[str, Any]]) -> int:
@@ -392,10 +419,33 @@ async def upsert_customers(session: AsyncSession, recs: list[dict[str, Any]]) ->
single row (the last write wins) at the DB layer.
"""
for rec in recs:
- await _upsert_one(session, Customer, rec)
+ await upsert_customer(session, rec)
return len(recs)
+async def prune_customer_links(
+ session: AsyncSession,
+ *,
+ channel: str,
+ owner_account_id: str,
+ keep_friend_ids: list[str],
+) -> int:
+ """删除该账号名下**不在最新名单**里的 customer_account_link 行。
+
+ 云客 isDel=0 只返回当前好友;抓取器逐员工整批 upsert 后调用本函数对账
+ (离开名单=已不是好友,或好友转移)。**调用方必须保证名单完整**(翻满
+ 声明 total)再调——拿到半份名单就 prune 会误删。返回删除行数。
+ """
+ conditions = [
+ CustomerAccountLink.channel == channel,
+ CustomerAccountLink.owner_account_id == owner_account_id,
+ ]
+ if keep_friend_ids:
+ conditions.append(CustomerAccountLink.friend_id.not_in(keep_friend_ids))
+ result = await session.execute(sa.delete(CustomerAccountLink).where(*conditions))
+ return int(result.rowcount or 0)
+
+
async def upsert_messages(session: AsyncSession, recs: list[dict[str, Any]]) -> int:
"""Batch idempotent upsert for :class:`Message` (PK = ``msg_id``).
diff --git a/yunke-server/migrations/versions/f7a8b9c0d1e2_customer_account_link_table.py b/yunke-server/migrations/versions/f7a8b9c0d1e2_customer_account_link_table.py
new file mode 100644
index 0000000..1b1a3c6
--- /dev/null
+++ b/yunke-server/migrations/versions/f7a8b9c0d1e2_customer_account_link_table.py
@@ -0,0 +1,78 @@
+"""customer_account_link 账号↔客户多对多关联表
+
+Revision ID: f7a8b9c0d1e2
+Revises: e6f7a8b9c0d1
+Create Date: 2026-09-08
+
+内容
+----
+customer 表 PK=friend_id 全局一客户一行、归属=最后抓取员工(last-wins)。
+共享客户(同一人加多个员工)在镜像里只挂在最后抓的员工名下——实测 Lily
+云客好友 36,镜像员工客户页只有 12,其余 24 个全在另外 9 个员工名下
+(2026-09-08 用户报「好友数与点进去的数量不一致」真机探明)。
+
+云客口径是**每个账号各算一个**(per-employee 列表连备注/收发计数都按
+关系各一份)。本表每个「渠道×账号×客户」一行:
+
+- 写:repos.upsert_customer 随档案同事务维护(所有好友抓取路径一处挂全);
+- 读:/api/customers?owner_account_id= 改读本表(员工维度列表/计数),
+ 与云客 contacts_num 完全对齐;
+- 对账:scrape_friends 逐员工整批 upsert 后删除该员工名下不在最新名单
+ 里的 link(云客 isDel=0 返回当前好友,删链=已不是好友)。
+
+**上线后需重跑 friends + wa-friends 各一次回填 link**(server:
+`docker compose exec backend python scripts/scrape_via_page.py --entity friends`)
+——存量关系无法从单行档案反推。
+
+幂等:sa.inspect 先查表存在则跳过。SQLite/MySQL 通用。
+"""
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = 'f7a8b9c0d1e2'
+down_revision: str | Sequence[str] | None = 'e6f7a8b9c0d1'
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+_TABLE = 'customer_account_link'
+
+
+def _has_table(table: str) -> bool:
+ insp = sa.inspect(op.get_bind())
+ return table in insp.get_table_names()
+
+
+def upgrade() -> None:
+ """Upgrade schema."""
+ if _has_table(_TABLE):
+ return # 已建过(或先手工建过),幂等跳过
+ op.create_table(
+ _TABLE,
+ sa.Column('channel', sa.String(16), primary_key=True),
+ sa.Column('owner_account_id', sa.String(128), primary_key=True),
+ sa.Column('friend_id', sa.String(128), primary_key=True),
+ sa.Column('friend_nickname', sa.String(255), nullable=True),
+ sa.Column('friend_remark', sa.String(255), nullable=True),
+ sa.Column('head_image_url', sa.String(1024), nullable=True),
+ sa.Column('real_name', sa.String(64), nullable=True),
+ sa.Column('phone', sa.String(64), nullable=True),
+ sa.Column('last_chat_time', sa.BigInteger(), nullable=True),
+ sa.Column('add_time', sa.BigInteger(), nullable=True),
+ sa.Column('send_num', sa.Integer(), nullable=True),
+ sa.Column('receive_num', sa.Integer(), nullable=True),
+ sa.Column('message_count', sa.Integer(), nullable=True),
+ sa.Column('from_type', sa.Integer(), nullable=True),
+ sa.Column('delete_flag', sa.Integer(), nullable=True),
+ sa.Column('fetched_at', sa.DateTime(), nullable=True),
+ sa.Column('updated_at', sa.DateTime(), nullable=True),
+ )
+
+
+def downgrade() -> None:
+ """Downgrade schema."""
+ if not _has_table(_TABLE):
+ return
+ op.drop_table(_TABLE)
diff --git a/yunke-server/scripts/scrape_via_page.py b/yunke-server/scripts/scrape_via_page.py
index c0cf86b..acf17fd 100644
--- a/yunke-server/scripts/scrape_via_page.py
+++ b/yunke-server/scripts/scrape_via_page.py
@@ -267,10 +267,10 @@ async def scrape_friends(cookie_str: str, max_employees: int = 100):
小漂移可忽略,且与云客后台「按员工看客户列表」口径一致。员工清单来自
本地 wechat_account(user_id 列)。
"""
- from app.db.base import async_engine
+ from app.db.base import async_engine, async_session_maker
from sqlalchemy import text as sa_text
from app.scraper.wechat import _normalize
- from app.storage.repos import upsert_customer
+ from app.storage.repos import prune_customer_links, upsert_customer
dept = await _root_dept_id()
async with async_engine.connect() as conn:
@@ -334,9 +334,21 @@ async def scrape_friends(cookie_str: str, max_employees: int = 100):
if records:
await _upsert_all(upsert_customer, records)
total_upserted += len(records)
+ # 对账(2026-09-08):云客 isDel=0 返回当前好友;名单取满(>=声明
+ # total)才可信,删掉该账号名下已不在名单里的 link(转移/删好友)。
+ # 半份名单宁可不对账,防误删。
+ pruned = 0
+ if declared is not None and len(rows) >= declared:
+ keep_ids = [r.get("friendWxId") for r in rows if r.get("friendWxId")]
+ async with async_session_maker() as session:
+ pruned = await prune_customer_links(
+ session, channel="wechat", owner_account_id=wx_id,
+ keep_friend_ids=keep_ids,
+ )
+ await session.commit()
logger.info(
f" [{i+1}/{len(employees)}] {wx_id[:16]}..: declared={declared} "
- f"rows={len(rows)} (total fetched {total_fetched})"
+ f"rows={len(rows)} pruned={pruned} (total fetched {total_fetched})"
)
await asyncio.sleep(2 + (i % 3))
@@ -1463,10 +1475,10 @@ async def scrape_wa_friends(cookie_str: str, max_pages: int = 2000):
全局查询有 ~1 万行硬上限(实测云客声明 11931 vs 全局翻页只到 10000,
2026-08-20);逐员工 ``uid`` 过滤(员工 WA 号)范围小无上限,页码字段是
``page``,total-aware 翻页(短页继续,满声明数或连续空页停)。"""
- from app.db.base import async_engine
+ from app.db.base import async_engine, async_session_maker
from sqlalchemy import text as sa_text
from app.scraper.whatsapp import _normalize_whatsapp_friend
- from app.storage.repos import upsert_customer
+ from app.storage.repos import prune_customer_links, upsert_customer
dept = await _root_dept_id()
async with async_engine.connect() as conn:
@@ -1520,8 +1532,20 @@ async def scrape_wa_friends(cookie_str: str, max_pages: int = 2000):
if records:
await _upsert_all(upsert_customer, records)
total_upserted += len(records)
+ # 对账(2026-09-08,同微信 friends):名单取满才删该账号名下
+ # 不在当前列表里的 link。
+ pruned = 0
+ if declared is not None and len(rows) >= declared:
+ keep_ids = [r.get("friendUid") for r in rows if r.get("friendUid")]
+ async with async_session_maker() as session:
+ pruned = await prune_customer_links(
+ session, channel="whatsapp", owner_account_id=wa_uid,
+ keep_friend_ids=keep_ids,
+ )
+ await session.commit()
logger.info(
- f" [{i+1}/{len(accounts)}] {wa_uid[:18]}..: declared={declared} rows={len(rows)}"
+ f" [{i+1}/{len(accounts)}] {wa_uid[:18]}..: declared={declared} "
+ f"rows={len(rows)} pruned={pruned}"
)
await asyncio.sleep(2 + (i % 3))
diff --git a/yunke-server/tests/test_api_customers.py b/yunke-server/tests/test_api_customers.py
index a47feea..cd6ce6f 100644
--- a/yunke-server/tests/test_api_customers.py
+++ b/yunke-server/tests/test_api_customers.py
@@ -148,3 +148,81 @@ async def test_q_escapes_like_wildcards(make_client):
# 只命中字面含 "100%" 的行;不因 % 通配漏扩到 "1001"
assert body["total"] == 1
assert [it["friend_id"] for it in body["items"]] == ["wx_pct"]
+
+
+# ---------------------------------------------------------------------------
+# owner 维度读 customer_account_link(共享好友,2026-09-08)
+# ---------------------------------------------------------------------------
+
+async def _seed_links(session):
+ from app.db.models import CustomerAccountLink as L
+
+ # 档案路径的旧行:共享好友 f_shared 档案 last-wins 挂在 wx_b 名下
+ session.add_all([
+ L(channel="wechat", owner_account_id="wx_a", friend_id="f_shared",
+ friend_remark="A的备注", friend_nickname="共享客户", last_chat_time=2000,
+ send_num=3, receive_num=1, from_type=1),
+ L(channel="wechat", owner_account_id="wx_b", friend_id="f_shared",
+ friend_remark="B的备注", friend_nickname="共享客户", last_chat_time=1000),
+ L(channel="wechat", owner_account_id="wx_a", friend_id="f_only_a",
+ friend_nickname="A独有", last_chat_time=3000),
+ ])
+ await session.commit()
+
+
+async def test_owner_filter_reads_links(make_client):
+ """owner 过滤走 link:共享好友在两个员工名下各出现,备注各是各的。"""
+ client = await make_client(_seed_links)
+ r_a = await client.get("/api/customers", params={
+ "channel": "wechat", "owner_account_id": "wx_a"})
+ assert r_a.status_code == 200
+ body_a = r_a.json()
+ assert body_a["total"] == 2
+ by_id = {it["friend_id"]: it for it in body_a["items"]}
+ # 排序:last_chat_time desc
+ assert [it["friend_id"] for it in body_a["items"]] == ["f_only_a", "f_shared"]
+ assert by_id["f_shared"]["friend_remark"] == "A的备注"
+ assert by_id["f_shared"]["send_num"] == 3
+ assert by_id["f_shared"]["from_type"] == 1
+
+ r_b = await client.get("/api/customers", params={
+ "channel": "wechat", "owner_account_id": "wx_b"})
+ body_b = r_b.json()
+ assert body_b["total"] == 1
+ assert body_b["items"][0]["friend_remark"] == "B的备注"
+
+
+async def test_owner_filter_q_and_friend_id_on_links(make_client):
+ """link 路径的 q 四列搜索 + friend_id 精确查找(聊天窗名字解析用)。"""
+ client = await make_client(_seed_links)
+ r = await client.get("/api/customers", params={
+ "channel": "wechat", "owner_account_id": "wx_a", "q": "A的备注"})
+ assert r.status_code == 200
+ body = r.json()
+ assert [it["friend_id"] for it in body["items"]] == ["f_shared"]
+
+ r2 = await client.get("/api/customers", params={
+ "channel": "wechat", "owner_account_id": "wx_a", "friend_id": "f_shared"})
+ body2 = r2.json()
+ assert body2["total"] == 1
+ assert body2["items"][0]["friend_nickname"] == "共享客户"
+
+
+async def test_owner_filter_with_dept_falls_back_to_archive(make_client):
+ """owner+department 组合回退档案路径(旧行为;link 不解析部门)。"""
+ from app.db.models import Customer as C, Staff as S
+
+ async def seed(session):
+ await _seed_links(session)
+ session.add(S(user_id="u1", name="员工", dept_id="d1"))
+ session.add(C(channel="wechat", owner_account_id="wx_a",
+ friend_id="f_archived", user_id="u1"))
+ await session.commit()
+
+ client = await make_client(seed)
+ r = await client.get("/api/customers", params={
+ "channel": "wechat", "owner_account_id": "wx_a", "department_id": "d1"})
+ assert r.status_code == 200
+ body = r.json()
+ # 档案路径:只命中 user_id 属于 d1 的档案行(link 行不带 user_id)
+ assert [it["friend_id"] for it in body["items"]] == ["f_archived"]
diff --git a/yunke-server/tests/test_repos.py b/yunke-server/tests/test_repos.py
index 104c501..ee129a7 100644
--- a/yunke-server/tests/test_repos.py
+++ b/yunke-server/tests/test_repos.py
@@ -25,6 +25,7 @@ from app.db.base import Base
from app.db.models import (
ChatGroup,
Customer,
+ CustomerAccountLink,
Department,
GroupMember,
Message,
@@ -39,6 +40,7 @@ from app.storage.repos import (
_build_column_values,
_coerce_bool,
_coerce_int,
+ prune_customer_links,
upsert_chat_group,
upsert_customer,
upsert_customers,
@@ -107,6 +109,116 @@ def test_coerce_int_returns_none_for_non_numeric_string():
# ---------------------------------------------------------------------------
+async def test_upsert_customer_shared_friend_maintains_links():
+ """共享好友:档案全局单行(last-wins),link 每个账号各一行(2026-09-08)。
+
+ 同一 friend_id 先后在 ownerA/ownerB 名下 upsert——customer 只有一行
+ 且归属=后写;customer_account_link 两行,各自带自己的备注快照与
+ fromType(来自 raw_json)。
+ """
+ engine = await _make_engine()
+ try:
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
+ async with SessionLocal() as session:
+ base = {
+ "friend_id": "wxid_shared",
+ "channel": "wechat",
+ "friend_nickname": "共享客户",
+ "phone": "13800000000",
+ "send_num": 10,
+ "receive_num": 4,
+ }
+ await upsert_customer(session, {
+ **base, "owner_account_id": "wx_a",
+ "friend_remark": "A的备注", "raw_json": {"fromType": 1},
+ })
+ await session.commit()
+ await upsert_customer(session, {
+ **base, "owner_account_id": "wx_b",
+ "friend_remark": "B的备注", "raw_json": {"fromType": 2},
+ })
+ await session.commit()
+
+ custs = (await session.execute(
+ sa.select(Customer).execution_options(populate_existing=True)
+ )).scalars().all()
+ assert len(custs) == 1
+ assert custs[0].owner_account_id == "wx_b" # 档案 last-wins
+
+ links = (await session.execute(
+ sa.select(CustomerAccountLink).execution_options(populate_existing=True)
+ )).scalars().all()
+ assert {(l.owner_account_id, l.friend_remark) for l in links} == {
+ ("wx_a", "A的备注"), ("wx_b", "B的备注"),
+ }
+ by_owner = {l.owner_account_id: l for l in links}
+ assert by_owner["wx_a"].from_type == 1
+ assert by_owner["wx_b"].from_type == 2
+ assert by_owner["wx_a"].send_num == 10
+ assert by_owner["wx_a"].phone == "13800000000"
+ finally:
+ await engine.dispose()
+
+
+async def test_upsert_customer_without_owner_skips_link():
+ """无 owner_account_id 的档案 upsert(理论路径)只写 customer,不碰 link。"""
+ engine = await _make_engine()
+ try:
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
+ async with SessionLocal() as session:
+ await upsert_customer(session, {
+ "friend_id": "wxid_solo", "channel": "wechat",
+ })
+ await session.commit()
+ n_links = (await session.execute(
+ sa.select(sa.func.count()).select_from(CustomerAccountLink)
+ )).scalar_one()
+ assert n_links == 0
+ finally:
+ await engine.dispose()
+
+
+async def test_prune_customer_links_removes_departed():
+ """对账:保留名单外的 link 被删;空名单删光;他人名下不动。"""
+ engine = await _make_engine()
+ try:
+ SessionLocal = async_sessionmaker(engine, expire_on_commit=False)
+ async with SessionLocal() as session:
+ for owner, fid in [("wx_a", "f1"), ("wx_a", "f2"), ("wx_a", "f3"),
+ ("wx_b", "f2")]:
+ await upsert_customer(session, {
+ "friend_id": fid, "channel": "wechat",
+ "owner_account_id": owner,
+ })
+ await session.commit()
+
+ deleted = await prune_customer_links(
+ session, channel="wechat", owner_account_id="wx_a",
+ keep_friend_ids=["f1", "f3"],
+ )
+ await session.commit()
+ assert deleted == 1
+
+ left = (await session.execute(
+ sa.select(CustomerAccountLink.friend_id, CustomerAccountLink.owner_account_id)
+ )).all()
+ assert set(left) == {("f1", "wx_a"), ("f3", "wx_a"), ("f2", "wx_b")}
+
+ # 空名单=该账号全部删除(wx_b 的保留)
+ deleted_all = await prune_customer_links(
+ session, channel="wechat", owner_account_id="wx_a",
+ keep_friend_ids=[],
+ )
+ await session.commit()
+ assert deleted_all == 2
+ left2 = (await session.execute(
+ sa.select(CustomerAccountLink.friend_id, CustomerAccountLink.owner_account_id)
+ )).all()
+ assert set(left2) == {("f2", "wx_b")}
+ finally:
+ await engine.dispose()
+
+
async def test_upsert_customer_is_idempotent_and_updates_version():
"""Upsert same friend_id twice with different version -> 1 row, version updated."""
engine = await _make_engine()
diff --git a/yunkes/src/api/types.ts b/yunkes/src/api/types.ts
index df2da78..915a415 100644
--- a/yunkes/src/api/types.ts
+++ b/yunkes/src/api/types.ts
@@ -36,6 +36,9 @@ export interface Customer {
/** 累计发送/接收条数(同步自云客 friend 记录 sendNum/receiveNum;员工客户页列)。 */
send_num?: number | null
receive_num?: number | null
+ /** 云客数据来源代码(customer_account_link 员工维度路径直读;档案路径空,
+ * 前端回退 raw_json.fromType)。 */
+ from_type?: number | null
/** ms epoch of friend add time (from raw_json.addTime). */
add_time?: number | null
message_count?: number | null
diff --git a/yunkes/src/views/StaffFriends.vue b/yunkes/src/views/StaffFriends.vue
index 7dcccf6..179653f 100644
--- a/yunkes/src/views/StaffFriends.vue
+++ b/yunkes/src/views/StaffFriends.vue
@@ -395,7 +395,7 @@ onMounted(() => {
- {{ fromTypeLabel(readField(row, 'fromType')) }}
+ {{ fromTypeLabel(row.from_type ?? readField(row, 'fromType')) }}
{{ row.friend_remark || '-' }}