代码管理

dashboard/api_connectors.py

← 返回编辑
# -*- coding: utf-8 -*-
"""SCRM / 奥丁 接口连接器注册表(2026-11-16)。

按「品牌 → 门店 → 接口」三级组织。接口分两类状态:
  · 已保存 token  → 直接复用现有 token 调用(云上解密后随任务下发给本地执行器)
  · 未接入        → 点「接入」后由本地执行器拉起该账号的 Chrome Profile 打开授权页,
                     人工完成 SSO 登录,token 自动捕获回传、加密落库

🔒 token 密文存放(crypto_store),任何接口只回传「尾 4 位」给页面核对;
   明文只在「下发任务给本地执行器」这一刻出现(执行器是管理员账号、跑在本机)。
"""
from typing import Any, Dict, List, Optional, Tuple

import json
import time

import crypto_store

CFG_ID = "api_connectors"

# 品牌平台族定义(按 Loomy Workspace 2026-11-17 的 scrm-client 注册表对齐)
#   SCRM:奇瑞系 x-token;亿客:sc_token
#   奥丁:token + refresh_token(三个网关:icarodin / odin.mychery / odin.jetourauto)
FAMILIES = {
    "chery_icar": {
        "label": "iCAR SCRM",
        "gateway": "https://scrm-api.mychery.com",
        "pre_auth_code": "1600000001",
        "auth_url": "https://scrm.mychery.com/login/login?backUrl=%2Fclue%2Fonlyclue",
        "token_key": "x-token",
        "auth_note": "iCAR 主站登录",
    },
    "chery_gf": {
        "label": "奇瑞股份 SCRM(gf)",
        "gateway": "https://scrm-gf-api.mychery.com",
        "pre_auth_code": "160002",
        "auth_url": "https://scrm-gf.mychery.com/login/login?backUrl=%2Fclue%2Fonlyclue",
        "token_key": "x-token",
        "auth_note": "gf 平台登录(QQ / C网 / H网)",
    },
    "jetour_yike": {
        "label": "捷途亿客平台",
        "gateway": "https://digi.jetourauto.com/scrm-clue-api",
        "pre_auth_code": "",
        "auth_url": "https://digi.jetourauto.com/scrm-web/",   # 少末尾斜杠会 404(2026-11-23 实测)
        "token_key": "sc_token",
        "auth_note": "企业微信扫码登录",
    },
    "odin_icar": {
        "label": "奥丁(iCAR 租户)",
        "gateway": "https://icarodin.mychery.com/api",
        "pre_auth_code": "",
        "auth_url": "https://icarodin.mychery.com/dealerSys/org",
        "token_key": "token",
        "auth_note": "奥丁 SSO(只读红线:仅查询)",
    },
    "odin_chery": {
        "label": "奥丁(奇瑞股份租户)",
        "gateway": "https://odin.mychery.com/api",
        "pre_auth_code": "",
        "auth_url": "https://odin.mychery.com/",
        "token_key": "token",
        "auth_note": "奥丁 SSO(只读红线:仅查询)",
    },
    "odin_jetour": {
        "label": "奥丁(捷途租户)",
        "gateway": "https://odin.jetourauto.com/api",
        "pre_auth_code": "",
        "auth_url": "https://odin.jetourauto.com/",
        "token_key": "token",
        "auth_note": "奥丁 SSO(只读红线:仅查询)",
    },
}

# 品牌分组:每店两条链接 —— SCRM 唯一线索 + 奥丁在库(用户 2026-11-17 要求
# 「把 SCRM 和奥丁的库存都做链接」)。erp 来自 scrm-client 的 BRANDS 表。
BRAND_GROUPS = [
    {"brand": "iCAR", "stores": [
        {"store_id": "st_guangrui", "erp": "1050FE",
         "leads": {"family": "chery_icar", "profile": "icar", "note": "主店(2418 条已实测)"},
         "stock": {"family": "odin_icar", "profile": "aodin", "note": "在库 + 在途"}},
        {"store_id": "st_faefde27", "erp": "1363VP",
         "leads": {"family": "chery_icar", "profile": "yld", "note": "远大路店"},
         "stock": {"family": "odin_icar", "profile": "yldodin", "note": "在库 + 在途"}},
    ]},
    {"brand": "QQ", "stores": [
        {"store_id": "st_fuxingrui", "erp": "1077FS",
         "leads": {"family": "chery_gf", "profile": "qq", "note": "唯一线索(2657 条已实测)"},
         "stock": {"family": "odin_chery", "profile": "qaodin", "note": "在库 + 在途"}},
    ]},
    {"brand": "奇瑞C网", "stores": [
        {"store_id": "st_305ff66f", "erp": "39454",
         "leads": {"family": "chery_gf", "profile": "cnet", "note": "脸谱门店"},
         "stock": {"family": "odin_chery", "profile": "codin", "note": "在库 + 在途"}},
    ]},
    {"brand": "奇瑞H网", "stores": [
        {"store_id": "st_f8344986", "erp": "37032",
         "leads": {"family": "chery_gf", "profile": "xjn", "note": "新纪元"},
         "stock": {"family": "odin_chery", "profile": "hodin", "note": "在库 + 在途"}},
        {"store_id": "st_7f275cb0", "erp": "22020",
         "leads": {"family": "chery_gf", "profile": "hnet", "note": "蓝胜"},
         "stock": {"family": "odin_chery", "profile": "hlodin", "note": "在库 + 在途"}},
    ]},
    {"brand": "纵横", "stores": [
        {"store_id": "st_bf1b5783", "erp": "1363VP",
         "leads": {"family": "jetour_yike", "profile": "znzh", "note": "中南店"},
         "stock": {"family": "odin_jetour", "profile": "znzodin", "note": "在库 + 在途"}},
        {"store_id": "st_c9284981", "erp": "1060JE",
         "leads": {"family": "jetour_yike", "profile": "zongheng", "note": "麓谷店"},
         "stock": {"family": "odin_jetour", "profile": "lgzodin", "note": "在库 + 在途"}},
    ]},
    {"brand": "捷途", "stores": [
        {"store_id": "st_f412de34", "erp": "39247",
         "leads": {"family": "jetour_yike", "profile": "xianglu", "note": "湘鲁(单一+协同)"},
         "stock": {"family": "odin_jetour", "profile": "jtodin", "note": "在库 + 在途"}},
        {"store_id": "st_425e0ca4", "erp": "22116",
         "leads": {"family": "jetour_yike", "profile": "lvsh", "note": "旅胜"},
         "stock": {"family": "odin_jetour", "profile": "lsodin", "note": "在库 + 在途"}},
        {"store_id": "st_8fb19abf", "erp": "29504",
         "leads": {"family": "jetour_yike", "profile": "ys", "note": "雅胜-山海(喜盈)"},
         "stock": {"family": "odin_jetour", "profile": "ysodin", "note": "在库 + 在途"}},
    ]},
]


def _enc(plain: str) -> str:
    plain = str(plain or "").strip()
    if not plain:
        return ""
    try:
        return crypto_store.encrypt(plain)
    except Exception:
        return plain


def _dec(stored: str) -> str:
    stored = str(stored or "").strip()
    if not stored:
        return ""
    try:
        if crypto_store.is_encrypted(stored):
            return crypto_store.decrypt(stored)
    except Exception:
        return ""
    return stored


def _tail(plain: str) -> str:
    plain = str(plain or "")
    return ("••••" + plain[-4:]) if len(plain) >= 4 else ""


# ---------------------------------------------------------------- 在线状态
# 2026-11-18 用户:掉线的必须显示掉线,不能把掉线的标成「已接入」。
# 所以 status 不再由「有没有 token」决定,而是由**真实探测结果**决定:
#   health="ok"  → 最近一次真打接口成功
#   health="bad" → 最近一次真打失败(token 过期 / 被挤下线 / 网关变更)
# 库里的 status 只保留「接入中 / 未接入」这类流程态,展示态由 eff_status 派生。
def _expired(it: Dict[str, Any]) -> bool:
    """凭据自带过期时间且已过期、又没有 refresh_token 可续 → 真失效。"""
    plain = _dec(str(it.get("token") or ""))
    if not plain.startswith("{"):
        return False
    try:
        d = json.loads(plain)
    except Exception:
        return False
    exp = d.get("expires_at")
    if not exp:
        return False
    try:
        if int(float(exp)) > time.time():
            return False
    except Exception:
        return False
    return not d.get("refresh_token")


def eff_status(it: Dict[str, Any], live_ids=()) -> str:
    """对外显示的状态。页面标签一律用它,不要直接读 it["status"]。"""
    if it.get("id") in live_ids:
        return "接入中"
    if not it.get("token"):
        return "未接入"
    if it.get("health") == "bad":
        return "已失效"
    if _expired(it):
        return "已失效"
    if it.get("health") == "ok" or it.get("last_ok_at"):
        return "已接入"
    return "待验证"


def seed_cfg() -> Dict[str, Any]:
    """按 BRAND_GROUPS 生成初始注册表:每店「SCRM 线索 + 奥丁库存」两条接口。"""
    brands: List[Dict[str, Any]] = []
    for g in BRAND_GROUPS:
        stores: List[Dict[str, Any]] = []
        for s in g["stores"]:
            ifaces: List[Dict[str, Any]] = []
            for kind, key, name in (("线索", "leads", "SCRM 唯一线索"),
                                    ("库存", "stock", "奥丁在库")):
                spec = s.get(key) or {}
                fam = FAMILIES.get(spec.get("family") or "", {})
                if not spec:
                    continue
                ifaces.append({
                    "id": ("leads_%s" if kind == "线索" else "stock_%s") % s["store_id"],
                    "family": spec.get("family") or "",
                    "name": name, "kind": kind,
                    "gateway": fam.get("gateway", ""),
                    "auth_url": fam.get("auth_url", ""),
                    "token_key": fam.get("token_key", ""),
                    "pre_auth_code": fam.get("pre_auth_code", ""),
                    "auth_note": fam.get("auth_note", ""),
                    "profile": spec.get("profile") or "",
                    "erp": s.get("erp") or "",
                    "status": "未接入", "token": "", "token_tail": "",
                    "last_ok_at": "", "last_error": "",
                    "health": "", "health_at": "", "health_msg": "",
                    "note": spec.get("note") or "",
                })
            stores.append({
                "store_id": s["store_id"],
                "store_name": s.get("store_name") or "",
                "profile": (s.get("leads") or {}).get("profile") or "",
                "interfaces": ifaces,
            })
        brands.append({"brand": g["brand"], "family":
                       ((g["stores"][0].get("leads") or {}).get("family") or ""),
                       "stores": stores})
    return {"brands": brands, "service": {"base": "", "token": "",
                                          "last_probe": ""}}


def seed_ids() -> set:
    """seed 内置接口的 id 集合(这些行不允许从页面删除,只能「断开」)。"""
    ids = set()
    for b in seed_cfg()["brands"]:
        for s in b["stores"]:
            for it in s["interfaces"]:
                ids.add(it["id"])
        if b.get("inventory"):
            ids.add(b["inventory"]["id"])
    return ids


def norm_cfg(raw: Any) -> Dict[str, Any]:
    """把库里读到的配置洗回 seed 结构;token 等运行时字段按 id 覆盖回去。

    这样将来 seed 里加了新接口(比如新门店),老配置下次保存就自动长出来。
    ⚠️ 用户从页面新增的品牌 / 门店 / 接口**不在 seed 里**,必须原样带回——
       否则下次任何人保存一次配置,新增的行就被静默冲掉了(2026-11-16 修的
       正是这个坑:第一版只按 seed id 合并)。
    """
    out = seed_cfg()
    if not isinstance(raw, dict):
        return out
    # 数据服务地址(scrm_api_service.py 跑在 Windows 上,token 在那里解密)
    if isinstance(raw.get("service"), dict):
        out["service"] = dict(raw["service"])
    saved: Dict[str, Dict[str, Any]] = {}
    for b in (raw.get("brands") or []):
        for s in (b.get("stores") or []):
            for it in (s.get("interfaces") or []):
                if it.get("id"):
                    saved[it["id"]] = it
        inv = b.get("inventory")
        if inv and inv.get("id"):
            saved[inv["id"]] = inv
    seed_brand_names = {b["brand"] for b in out["brands"]}
    for b in out["brands"]:
        for s in b["stores"]:
            for it in s["interfaces"]:
                _merge(it, saved.get(it["id"]))
        if "inventory" in b:
            _merge(b["inventory"], saved.get(b["inventory"]["id"]))
    # —— 用户新增的部分:按 品牌 → 门店 → 接口 三级挂回 ──
    # 先丢掉空壳:没接口的门店、没门店的分组(旧注册表删除后可能留下)
    for b in out["brands"]:
        b["stores"] = [sx for sx in (b.get("stores") or [])
                       if sx.get("interfaces")]
    out["brands"] = [b for b in out["brands"]
                     if b.get("stores") or b.get("inventory")]
    for rb in (raw.get("brands") or []):
        rbrand = str(rb.get("brand") or "").strip()
        if not rbrand:
            continue
        tgt = next((b for b in out["brands"] if b["brand"] == rbrand), None)
        if tgt is None:
            # 整个品牌都是新增的:整块带回(门店/接口保持库里结构)
            nb = {"brand": rbrand, "family": str(rb.get("family") or ""),
                  "stores": []}
            for rs in (rb.get("stores") or []):
                nb["stores"].append({
                    "store_id": str(rs.get("store_id") or ""),
                    "store_name": str(rs.get("store_name") or ""),
                    "profile": str(rs.get("profile") or ""),
                    "interfaces": [dict(it) for it in (rs.get("interfaces") or [])],
                })
            if rb.get("inventory"):
                nb["inventory"] = dict(rb["inventory"])
            out["brands"].append(nb)
            continue
        # 品牌已在 seed 里:把新增的门店 / 接口挂进去
        seed_store_ids = {s["store_id"] for s in tgt["stores"]}
        for rs in (rb.get("stores") or []):
            rsid = str(rs.get("store_id") or "")
            ts = next((s for s in tgt["stores"] if s["store_id"] == rsid), None)
            if ts is None:
                tgt["stores"].append({
                    "store_id": rsid,
                    "store_name": str(rs.get("store_name") or ""),
                    "profile": str(rs.get("profile") or ""),
                    "interfaces": [dict(it) for it in (rs.get("interfaces") or [])],
                })
                continue
            seed_it_ids = {it["id"] for it in ts["interfaces"]}
            for rit in (rs.get("interfaces") or []):
                if rit.get("id") and rit["id"] not in seed_it_ids:
                    ts["interfaces"].append(dict(rit))
    # 收尾再清一次空壳(非 seed 品牌是在上面才带回的)
    for b in out["brands"]:
        b["stores"] = [sx for sx in (b.get("stores") or [])
                       if sx.get("interfaces")]
    out["brands"] = [b for b in out["brands"]
                     if b.get("stores") or b.get("inventory")]
    return out


def _merge(it: Dict[str, Any], old: Optional[Dict[str, Any]]) -> None:
    """把已保存接口的运行时字段并回新结构。

    ⚠️ note / name 也必须搬运:用户在页面上改的备注和名称存在库里,
       但 norm_cfg 每次从 seed 重建,不搬的话下次任何人保存一次配置,
       用户的编辑就静默丢了(2026-11-16 踩过)。
    """
    if not old:
        return
    it["status"] = str(old.get("status") or it["status"])
    it["token"] = str(old.get("token") or "")
    it["token_tail"] = str(old.get("token_tail") or "")
    it["last_ok_at"] = str(old.get("last_ok_at") or "")
    it["last_error"] = str(old.get("last_error") or "")
    # 体检结果必须搬:不搬的话每次有人保存一次配置(改备注/加接口),
    # 所有接口的健康状态就被重置成「待验证」,页面又变成一片未知。
    it["health"] = str(old.get("health") or "")
    it["health_at"] = str(old.get("health_at") or "")
    it["health_msg"] = str(old.get("health_msg") or "")
    if old.get("profile"):
        it["profile"] = str(old["profile"])
    # erp:注册表(scrm-client 的 BRANDS)是权威来源;只有注册表没写时才用旧的
    if old.get("erp") and not it.get("erp"):
        it["erp"] = str(old["erp"])
    if old.get("note") is not None and str(old.get("note")).strip():
        it["note"] = str(old["note"])
    if old.get("name") is not None and str(old.get("name")).strip():
        it["name"] = str(old["name"])


def public_view(cfg: Dict[str, Any], store_names: Dict[str, str],
                live_ids=()) -> Dict[str, Any]:
    """下发前端的视图:token 只给尾 4 位,绝不吐密文。

    status 是**派生**出来的(见 eff_status),不直接读库里那个字段 ——
    库里只记「接入中 / 未接入」流程态,在线与否必须按真实探测结果算。
    """
    def _one(it):
        d = _pub(it)
        d["status"] = eff_status(it, live_ids)
        return d
    out = {"brands": []}
    for b in cfg.get("brands") or []:
        stores = []
        for s in b.get("stores") or []:
            stores.append({
                "store_id": s["store_id"],
                "store_name": (s.get("store_name")
                               or store_names.get(s["store_id"], s["store_id"])),
                "profile": s.get("profile", ""),
                "interfaces": [_one(it) for it in s.get("interfaces") or []],
            })
        entry = {"brand": b["brand"], "family": b["family"], "stores": stores}
        if b.get("inventory"):
            entry["inventory"] = _one(b["inventory"])
        out["brands"].append(entry)
    return out


def _pub(it: Dict[str, Any]) -> Dict[str, Any]:
    d = {k: it.get(k) for k in (
        "id", "name", "kind", "gateway", "auth_url", "token_key", "profile",
        # family(2026-11-23):前端要按平台决定显示「扫码授权」按钮,
        # 之前没下发 family,判断永远不成立,按钮压根渲染不出来
        "family",
        "erp", "pre_auth_code", "auth_note", "status", "token_tail",
        "last_ok_at", "last_error", "health", "health_at", "health_msg", "note")}
    # builtin=True 的行是 seed 内置(只能断开不能删);页面新增的为 False
    d["builtin"] = it.get("id") in seed_ids()
    return d


def families_public() -> Dict[str, Dict[str, str]]:
    """平台预设下拉:选 family 自动带出 网关 / 授权页 / token 键,不用手填。"""
    return {k: {"label": v["label"], "gateway": v["gateway"],
                "auth_url": v["auth_url"], "token_key": v["token_key"],
                "pre_auth_code": v.get("pre_auth_code", ""),
                "auth_note": v.get("auth_note", "")}
            for k, v in FAMILIES.items()}


def add_iface(cfg: Dict[str, Any], spec: Dict[str, Any]) -> Tuple[Optional[Dict[str, Any]], str]:
    """页面新增一个接口。返回 (接口, 错误信息);成功时已挂进 cfg。

    门店可以选已有的,也可以填新名字(store_id 由调用方生成)。
    同平台多账号隔离靠 profile(账号标识),同店同类型不允许重复。
    """
    brand = str(spec.get("brand") or "").strip()
    store_id = str(spec.get("store_id") or "").strip()
    store_name = str(spec.get("store_name") or "").strip()
    kind = str(spec.get("kind") or "线索").strip() or "线索"
    profile = str(spec.get("profile") or "").strip()
    if not brand:
        return None, "请填写品牌"
    if not store_id:
        return None, "请选择或填写门店"
    if not profile:
        return None, "请填写账号标识(同平台多账号靠它隔离登录态)"
    fam_key = str(spec.get("family") or "").strip()
    fam = FAMILIES.get(fam_key) if (fam_key and fam_key != "custom") else None
    if fam:
        family = fam_key
        gateway = fam["gateway"]
        auth_url = fam["auth_url"]
        token_key = fam["token_key"]
        pre_auth_code = fam.get("pre_auth_code", "")
        auth_note = fam.get("auth_note", "")
    else:
        family = ""
        gateway = str(spec.get("gateway") or "").strip()
        auth_url = str(spec.get("auth_url") or "").strip()
        token_key = str(spec.get("token_key") or "").strip()
        pre_auth_code = str(spec.get("pre_auth_code") or "").strip()
        auth_note = ""
        if not (gateway and auth_url and token_key):
            return None, "自定义平台需要填写 网关 / 授权页 / token 存储键"
    # 一个门店只能属于一个品牌
    for b in cfg.get("brands") or []:
        if b.get("brand") == brand:
            continue
        for sx in b.get("stores") or []:
            if sx.get("store_id") == store_id:
                return None, "该门店已在「%s」品牌下,一个门店只能挂一个品牌" % b.get("brand")
    iid = ("leads_%s" % store_id) if kind == "线索" else ("stock_%s" % store_id)
    if find_iface(cfg, iid):
        return None, "该门店的「%s」接口已存在" % kind
    name = (str(spec.get("name") or "").strip()
            or ("SCRM 唯一线索" if kind == "线索" else "库存接口"))
    it = {
        "id": iid, "family": family,
        "name": name, "kind": kind,
        "gateway": gateway, "auth_url": auth_url, "token_key": token_key,
        "profile": profile, "erp": str(spec.get("erp") or "").strip(),
        "pre_auth_code": pre_auth_code, "auth_note": auth_note,
        "status": "未接入", "token": "", "token_tail": "",
        "last_ok_at": "", "last_error": "",
        "health": "", "health_at": "", "health_msg": "",
        "note": str(spec.get("note") or "").strip(),
    }
    tgt = next((b for b in cfg["brands"] if b.get("brand") == brand), None)
    if tgt is None:
        tgt = {"brand": brand, "family": family, "stores": []}
        cfg["brands"].append(tgt)
    ts = next((sx for sx in tgt["stores"] if sx.get("store_id") == store_id), None)
    if ts is None:
        ts = {"store_id": store_id, "store_name": store_name or store_id,
              "profile": profile, "interfaces": []}
        tgt["stores"].append(ts)
    ts["interfaces"].append(it)
    return it, ""


def update_iface(cfg: Dict[str, Any], iid: str,
                 spec: Dict[str, Any]) -> Tuple[Optional[Dict[str, Any]], str]:
    """编辑接口。返回 (接口, 错误)。

    seed 内置行只能改 账号标识 / ERP / 备注 / 名称(平台与网关是预设,改了会坏);
    页面新增的行还可以改 网关 / 授权页 / token 键 / 平台。
    """
    it = find_iface(cfg, iid)
    if not it:
        return None, "接口不存在"
    seed = iid in seed_ids()
    for k in ("profile", "erp", "note", "name"):
        v = str(spec.get(k) or "").strip()
        if spec.get(k) is not None and v:
            it[k] = v
    if not seed:
        fam_key = str(spec.get("family") or "").strip()
        fam = FAMILIES.get(fam_key) if (fam_key and fam_key != "custom") else None
        if fam:
            it["family"] = fam_key
            it["gateway"] = fam["gateway"]
            it["auth_url"] = fam["auth_url"]
            it["token_key"] = fam["token_key"]
            it["pre_auth_code"] = fam.get("pre_auth_code", "")
            it["auth_note"] = fam.get("auth_note", "")
        elif fam_key == "custom":
            for k in ("gateway", "auth_url", "token_key"):
                v = str(spec.get(k) or "").strip()
                if v:
                    it[k] = v
    return it, ""


def delete_iface(cfg: Dict[str, Any], iid: str) -> Tuple[bool, str]:
    """删除页面新增的接口。seed 内置行不允许删(只能「断开」清 token)。"""
    if iid in seed_ids():
        return False, "内置接口不能删除,可点「断开」清除已保存的 token"
    seed_stores = {s["store_id"] for b in seed_cfg()["brands"]
                   for s in b["stores"]}
    seed_brands = {b["brand"] for b in seed_cfg()["brands"]}
    for b in cfg.get("brands") or []:
        for sx in b.get("stores") or []:
            for it in sx.get("interfaces") or []:
                if it.get("id") == iid:
                    sx["interfaces"].remove(it)
                    # 自定义门店下没接口了 → 连门店一起清;品牌空了 → 连品牌清
                    if not sx["interfaces"] and sx.get("store_id") not in seed_stores:
                        b["stores"].remove(sx)
                    if (not b["stores"] and not b.get("inventory")
                            and b.get("brand") not in seed_brands):
                        cfg["brands"].remove(b)
                    return True, ""
    return False, "接口不存在"


def find_iface(cfg: Dict[str, Any], iid: str) -> Optional[Dict[str, Any]]:
    for b in cfg.get("brands") or []:
        for s in b.get("stores") or []:
            for it in s.get("interfaces") or []:
                if it.get("id") == iid:
                    return it
        if b.get("inventory", {}).get("id") == iid:
            return b["inventory"]
    return None


def iter_ifaces(cfg: Dict[str, Any]):
    for b in cfg.get("brands") or []:
        for s in b.get("stores") or []:
            for it in s.get("interfaces") or []:
                yield b, s, it
        if b.get("inventory"):
            yield b, None, b["inventory"]