feat(link): customer_account_link 账号↔客户多对多——共享好友员工维度对齐云客

用户报「Lily 好友数 36,点进员工客户页只有 12」。真机探明根因:那 24 个
是共享客户(同一人加多个员工),云客 per-employee 各算一个;而 customer
表 PK=friend_id 全局单行、归属 last-wins,其他员工名下必然「消失」。
抓取器本身每员工都拿全了(日志 declared=36 rows=36),丢在入库模型层。

- 新表 customer_account_link(渠道×账号×客户一行,per-relation 快照:
  昵称/备注/头像/手机号/收发计数/最近沟通/add_time/fromType/isDel)
- 写:repos.upsert_customer 随档案同事务维护(所有好友抓取路径一处挂全);
  新增 prune_customer_links 对账
- 读:/api/customers?owner_account_id= 改读 link(与云客 contacts_num 口径
  一致);该账号 link 为空时回退档案路径(过渡安全);与 dept/user 等
  过滤组合时维持旧行为;CustomerOut 透传 from_type
- 抓取器:friends/wa-friends 逐员工整批 upsert 后按名单对账(取满声明
  total 才删,防半份名单误删)
- 前端:StaffFriends 数据来源列优先 link 的 from_type

611 测试绿(link 新 6 例);本地验证空表回退/造数接管/from_type 透传。
上线后需重跑 friends+wa-friends 回填 link(存量关系无法从档案反推)。

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
浅念
2026-09-08 17:17:06 +08:00
parent 4ad239597e
commit d42895337d
10 changed files with 489 additions and 10 deletions
+78
View File
@@ -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"]
+112
View File
@@ -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()