代码管理

traffic_openapi.py

← 返回编辑
"""集团客流登记系统 · 开放接口客户端(只读)

用途:把子项目「集团客流登记系统」的**到店客流**实时接进本驾驶舱。

为什么不在本机执行器里抓:
    客流系统是云上的 HTTP 服务,用 client_id/secret 鉴权即可直连。
    走执行器反而要多一个中间环节(还要把 secret 下发到 Mac 上),
    而且执行器不在线时数据就断了。所以这里由 Flask 后端直接调用。

安全约定:
    - 只有 GET,凭证泄露也改不了对方任何业务数据;
    - secret 落库前用 crypto_store 加密(与 WPS/钉钉凭证同一套密钥);
    - 只把「需要的字段」缓存在内存里,不落盘、不下发到浏览器。

缓存策略:
    - 进程内 TTL 缓存(默认 120s),过期后**后台线程刷新**,请求永远不等网络;
    - 冷启动(缓存为空)时同步拉一次(约 0.5~1s),失败则返回空并带上错误原因,
      不抛异常 —— 客流系统挂了不能把整个看板拖下水。
"""

from __future__ import annotations

import json
import threading
import time
from datetime import datetime, timedelta
from typing import Any, Dict, Iterable, List, Optional, Tuple

import requests

# 每线程一个 Session:keep-alive 复用连接。
# 原来直接 requests.get() 等于每次都重新 TLS 握手(4 个接口 ≈ 4 次握手,
# 每次 200~400ms)。Session 的对象内部不是线程安全的,所以必须是 thread-local。
_TS = threading.local()


def _session() -> "requests.Session":
    s = getattr(_TS, "s", None)
    if s is None:
        s = requests.Session()
        s.mount("https://", requests.adapters.HTTPAdapter(
            pool_connections=4, pool_maxsize=8, max_retries=0))
        _TS.s = s
    return s

try:                       # 凭证加密(缺 crypto_store 时降级为明文,仅在本地调试)
    import crypto_store
except Exception:          # pragma: no cover
    crypto_store = None


# ==================== 常量 ====================

CFG_ID = "traffic_openapi"          # dashboard_config 里的一条 JSON 配置

# 首次部署的默认值(客户名就是「集团工作台」,见 /ping 返回)
# 可以在「系统设置 → 接口对接」里改,改完立即生效、无需重启。
DEFAULT_BASE = "https://traffic-system.app.workbuddy.host/api/v1/open/v1"
DEFAULT_CLIENT_ID = "wb_e4f86e20a26ab7ad"
DEFAULT_CLIENT_SECRET = "sk_ph0bbzbdEWMMd8JE49VIeFumxoP1gB1HSvJF4wujrTo"

# 到店口径:void(作废)不计入到店量;incomplete(未离店)仍然算到店
SKIP_STATUS = {"void", "作废"}

# 「下定」口径:ordered = 已下定;delivered = 已交车(必然先下定过)
# 不看 remark 里的自由文本("未订车" 与 "订车" 只差一个字,容易误判)
ORDERED_INTENTS = {"ordered", "delivered", "deposited"}

CACHE_TTL = 120                      # 秒
PAGE_SIZE = 2000
TIMEOUT = 6


class TrafficError(RuntimeError):
    """调用客流接口失败(鉴权 / 网络 / 数据格式)。"""


# ==================== 配置 ====================

def _blank_cfg() -> Dict[str, Any]:
    return {
        "enabled": True,
        "base": DEFAULT_BASE,
        "client_id": DEFAULT_CLIENT_ID,
        "secret": "",                 # 密文;空 = 用内置默认值
        "mode": "prefer",             # prefer=客流系统优先 / only=只认客流系统 / off=关闭
        "stores": {},                 # {客流门店ID(str): 本系统门店ID}
        "sharecode": SHARECODE_DEFAULT,  # 客流系统的平台访问门分享码(2026-11-12 起必须带)
        "ttl": CACHE_TTL,
        "updated_at": "",
        "last_ok_at": "",
        "last_error": "",
    }


def norm_cfg(raw: Any) -> Dict[str, Any]:
    """把配置洗成固定形状:坏字段一律回退默认值,绝不让页面报错。"""
    out = _blank_cfg()
    raw = raw if isinstance(raw, dict) else {}
    if "enabled" in raw:
        out["enabled"] = bool(raw.get("enabled"))
    base = str(raw.get("base") or "").strip().rstrip("/")
    if base.startswith("http://") or base.startswith("https://"):
        out["base"] = base
    cid = str(raw.get("client_id") or "").strip()
    if cid:
        out["client_id"] = cid
    if raw.get("secret"):
        out["secret"] = str(raw.get("secret"))
    mode = str(raw.get("mode") or "").strip()
    if mode in ("prefer", "only", "off"):
        out["mode"] = mode
    sc = str(raw.get("sharecode") or "").strip()
    if sc:
        out["sharecode"] = sc
    stores = raw.get("stores")
    if isinstance(stores, dict):
        clean = {}
        for k, v in stores.items():
            k2, v2 = str(k).strip(), str(v or "").strip()
            if k2 and v2 and v2 != "0":
                clean[k2] = v2
        out["stores"] = clean
    try:
        ttl = int(raw.get("ttl") or CACHE_TTL)
    except Exception:
        ttl = CACHE_TTL
    out["ttl"] = max(30, min(3600, ttl))
    for k in ("updated_at", "last_ok_at", "last_error"):
        if raw.get(k):
            out[k] = str(raw.get(k))
    return out


_CFG_CACHE = {"ts": 0.0, "cfg": None}
_CFG_TTL = 5.0


def load_cfg(conn) -> Dict[str, Any]:
    """读客流对接配置(5 秒内存缓存)。

    /api/stores 每次都会读它,但配置几乎不变 —— 每次都打一次云库纯属浪费。
    保存配置时 `save_cfg` 会主动失效缓存。
    """
    c = _CFG_CACHE
    if c["cfg"] is not None and (time.time() - c["ts"]) < _CFG_TTL:
        return dict(c["cfg"])
    row = None
    try:
        row = conn.execute("SELECT config FROM dashboard_config WHERE id=?",
                           (CFG_ID,)).fetchone()
    except Exception:
        row = None
    if not row:
        cfg = norm_cfg({})
    else:
        try:
            cfg = norm_cfg(json.loads(row["config"] or "{}"))
        except Exception:
            cfg = norm_cfg({})
    c["cfg"], c["ts"] = dict(cfg), time.time()
    return cfg


def save_cfg(conn, cfg: Dict[str, Any]) -> Dict[str, Any]:
    _CFG_CACHE["cfg"] = None          # 保存即失效,避免读到旧配置
    cur = norm_cfg(cfg)
    cur["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    conn.execute(
        "INSERT OR REPLACE INTO dashboard_config(id, config, updated_at) VALUES(?,?,?)",
        (CFG_ID, json.dumps(cur, ensure_ascii=False), cur["updated_at"]),
    )
    return cur


def pack_secret(plain: str) -> str:
    """secret 入库前加密;没有 crypto_store 时原样返回(本地调试用)。"""
    plain = str(plain or "").strip()
    if not plain:
        return ""
    if crypto_store is not None:
        try:
            return crypto_store.encrypt(plain)
        except Exception:
            pass
    return plain


def unpack_secret(stored: str) -> str:
    """解出明文 secret。

    解不开时回落到内置默认凭证,而不是返回空 —— 否则换密钥/换部署包之后
    会变成「凭证未配置」,看板静默丢到店量,用户完全看不出原因。
    """
    stored = str(stored or "").strip()
    if not stored:
        return DEFAULT_CLIENT_SECRET
    if crypto_store is not None and crypto_store.is_encrypted(stored):
        try:
            return crypto_store.decrypt(stored)
        except Exception:
            return DEFAULT_CLIENT_SECRET
    return stored


def _creds(cfg: Dict[str, Any]) -> Tuple[str, str, str]:
    return (str(cfg.get("base") or DEFAULT_BASE).rstrip("/"),
            str(cfg.get("client_id") or DEFAULT_CLIENT_ID),
            unpack_secret(cfg.get("secret") or ""))


# 客流系统的平台 sharecode 访问门(2026-11-12 起):不带 sharecode 的请求
# 会被平台「链接不完整」页整页拦截(403 HTML),连 /api/v1/open/v1 也不例外。
# 优先读配置里的 sharecode(可在「接口对接」页改),缺省用当前有效的分享码。
SHARECODE_DEFAULT = "ONDEZN7NKO"


def _sharecode(cfg: Dict[str, Any]) -> str:
    return str(cfg.get("sharecode") or SHARECODE_DEFAULT).strip()


# ==================== HTTP ====================

def _get(cfg: Dict[str, Any], path: str,
         params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    base, cid, secret = _creds(cfg)
    if not secret:
        raise TrafficError("client_secret 未配置或解密失败(请在「接口对接」重新填写)")
    url = base + path
    headers = {"X-Client-Id": cid, "X-Client-Secret": secret,
               "User-Agent": "xwc-dashboard/1.0"}
    # 每个请求都带 sharecode(平台访问门要求);显式传的同名参数优先。
    _params = {"sharecode": _sharecode(cfg)}
    _params.update(params or {})
    last = ""
    for attempt in range(2):
        try:
            r = _session().get(url, headers=headers, params=_params,
                               timeout=TIMEOUT)
            if r.status_code == 401:
                raise TrafficError("鉴权失败(401):client_id / secret 不正确或凭证已停用")
            if r.status_code == 403:
                # 平台 sharecode 门返回的是 HTML 页(「链接不完整」),
                # 与接口本身的 403(凭证无 data:read 范围)区分开,别再误导排查方向。
                if (r.text or "").lstrip().startswith("<"):
                    raise TrafficError(
                        "被平台访问门拦截(403):客流系统链接已更新,"
                        "请在「接口对接」核对 sharecode(当前 %s)" % _sharecode(cfg))
                raise TrafficError("无权限(403):凭证缺少 data:read 范围或被 IP 白名单拒绝")
            if r.status_code == 429:
                raise TrafficError("被限流(429):稍后再试,或调大缓存 TTL")
            if r.status_code >= 400:
                raise TrafficError("接口返回 HTTP %s:%s"
                                   % (r.status_code, (r.text or "")[:160]))
            data = r.json()
            if not isinstance(data, dict):
                raise TrafficError("接口返回格式异常")
            if data.get("ok") is False:
                raise TrafficError(str(data.get("error") or "接口返回 ok=false"))
            return data
        except TrafficError:
            raise
        except Exception as e:                       # 网络类异常重试一次
            last = "%s: %s" % (type(e).__name__, str(e)[:160])
            if attempt == 0:
                time.sleep(0.4)
                continue
    raise TrafficError(last or "网络异常")


def ping(cfg: Dict[str, Any]) -> Dict[str, Any]:
    d = _get(cfg, "/ping")
    return {"ok": True, "app": d.get("app"), "client": d.get("client"),
            "scopes": d.get("scopes"),
            "server_time_bj": d.get("server_time_bj")}


def fetch_meta(cfg: Dict[str, Any]) -> Dict[str, Any]:
    d = _get(cfg, "/meta")
    return {"counts": d.get("counts") or {},
            "last_visit_update_bj": d.get("last_visit_update_bj"),
            "server_time_bj": d.get("server_time_bj")}


def _paged(cfg: Dict[str, Any], path: str,
           params: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
    """按页拉全量。page_size 上限 2000;防御性设置 50 页上限。"""
    out: List[Dict[str, Any]] = []
    page = 1
    while page <= 50:
        q = dict(params or {})
        q["page"] = page
        q["page_size"] = PAGE_SIZE
        d = _get(cfg, path, q)
        items = d.get("items") or []
        if not isinstance(items, list):
            break
        out.extend([x for x in items if isinstance(x, dict)])
        pages = int(d.get("pages") or 1)
        if page >= pages or not items:
            break
        page += 1
    return out


def fetch_stores(cfg: Dict[str, Any]) -> List[Dict[str, Any]]:
    return _paged(cfg, "/stores")


def fetch_sources(cfg: Dict[str, Any]) -> List[Dict[str, Any]]:
    return _paged(cfg, "/sources")


def fetch_visits(cfg: Dict[str, Any],
                 since: Optional[str] = None) -> List[Dict[str, Any]]:
    params = {}
    if since:
        params["since"] = since
    return _paged(cfg, "/visits", params)


# ==================== 缓存 ====================

_LOCK = threading.RLock()
_CACHE: Dict[str, Any] = {
    "ts": 0.0, "visits": [], "stores": [], "sources": [],
    "meta": {}, "error": "", "loading": False, "took_ms": 0,
}


def _parse_dt(s: Any) -> Optional[datetime]:
    s = str(s or "").strip()
    if not s:
        return None
    s = s.replace("T", " ")
    for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S",
                "%Y-%m-%d %H:%M", "%Y-%m-%d"):
        try:
            return datetime.strptime(s[:26], fmt)
        except Exception:
            continue
    return None


def _norm_visit(v: Dict[str, Any]) -> Dict[str, Any]:
    """只留要用的字段:内存占用小一个数量级,也不会把客户敏感信息带出去。"""
    arrive = v.get("arrive_at_bj") or ""
    dt = _parse_dt(arrive)
    if dt is None:
        # arrive_at 缺失时退回创建时间(UTC → 北京时间)
        c = _parse_dt(v.get("created_at"))
        dt = (c + timedelta(hours=8)) if c else None
    return {
        "id": v.get("id"),
        "cid": v.get("customer_id"),
        "store_cid": v.get("store_id"),
        "store": str(v.get("store_name") or "").strip(),
        "brand": str(v.get("brand_name") or "").strip(),
        "advisor": str(v.get("advisor_name") or "").strip(),
        "date": dt.strftime("%Y-%m-%d") if dt else "",
        "dt": dt,
        "stay": v.get("stay_minutes"),
        "level": str(v.get("lead_level") or "").strip(),
        "source": str(v.get("source_code") or "").strip(),
        "status": str(v.get("status") or "").strip(),
        "purpose": str(v.get("visit_purpose") or "").strip(),
        "situation": str(v.get("customer_situation") or "").strip(),
        "test_drive": str(v.get("test_drive") or "").strip(),
        # deal_intent: follow_up / ordered(下定)/ delivered(已交车)
        # 下定人数 = ordered + delivered(已交车必然先下定过)
        "deal": str(v.get("deal_intent") or "").strip().lower(),
        "wechat": bool(v.get("wechat_added")),
        "seated": bool(v.get("seated")),
        "manager": bool(v.get("manager_joined")),
        "intent": str(v.get("intent_vehicle") or "").strip(),
        "reception": v.get("reception_count"),
        "name": str(v.get("customer_name") or "").strip(),
        "phone": str(v.get("customer_phone") or "").strip(),
    }


def _wait_loading(timeout: float = 8.0) -> None:
    """有人在拉了就先等它 —— 否则并发请求会拿到空快照,
    而 /api/stores 会把这份空结果进缓存,导致「到店量 0」被冻住一个缓存周期。"""
    with _LOCK:
        if not _CACHE.get("loading"):
            return
    deadline = time.time() + timeout
    while time.time() < deadline:
        with _LOCK:
            if not _CACHE.get("loading"):
                return
        time.sleep(0.05)


def refresh(cfg: Dict[str, Any], force: bool = False) -> Dict[str, Any]:
    """真正打网络。任何异常都记在 cache['error'] 里,不往外抛。"""
    with _LOCK:
        if _CACHE.get("loading"):
            _busy = True
        else:
            _busy = False
            _CACHE["loading"] = True
    if _busy:
        _wait_loading()
        return dict(_CACHE)
    t0 = time.time()
    err = ""
    visits: List[Dict[str, Any]] = []
    stores: List[Dict[str, Any]] = []
    sources: List[Dict[str, Any]] = []
    meta: Dict[str, Any] = {}
    # 四个接口互不依赖 → 并发拉。「到店明细」是主体,另外三个只是门店名/
    # 来源字典/计数;串行时要 4 次往返(实测 4.3s),并发后 ≈ 最慢的那个。
    from concurrent.futures import ThreadPoolExecutor

    def _try(fn, default):
        try:
            return fn(cfg), ""
        except Exception as e:                   # 单个接口挂了不影响主体
            return default, str(e)[:200]

    try:
        with ThreadPoolExecutor(max_workers=4) as ex:
            f_visits = ex.submit(_try, fetch_visits, [])
            f_stores = ex.submit(_try, fetch_stores, [])
            f_sources = ex.submit(_try, fetch_sources, [])
            f_meta = ex.submit(_try, fetch_meta, {})
            raw, v_err = f_visits.result()
            stores, s_err = f_stores.result()
            sources, _ = f_sources.result()
            meta, _ = f_meta.result()
        visits = [_norm_visit(v) for v in (raw or [])]
        if v_err:
            raise TrafficError(v_err)
        err = s_err or ""
    except Exception as e:
        err = str(e)[:300]
    with _LOCK:
        _CACHE.update(ts=time.time(), visits=visits, stores=stores,
                      sources=sources, meta=meta, error=err,
                      loading=False, took_ms=int((time.time() - t0) * 1000))
        snap = dict(_CACHE)
    return snap


def _needs_refresh(cfg: Dict[str, Any]) -> bool:
    ttl = int(cfg.get("ttl") or CACHE_TTL)
    if not _CACHE.get("ts"):
        return True
    if time.time() - float(_CACHE["ts"]) > ttl:
        return True
    return False


def ensure(cfg: Dict[str, Any], force: bool = False,
           wait: bool = True) -> Dict[str, Any]:
    """取缓存;过期则刷新。

    wait=True  (冷启动/首次请求)→ 同步刷新,保证第一屏就有数
    wait=False (已有一份旧数据)→ 后台刷新,请求立即返回旧数据
    """
    if force:
        return refresh(cfg)
    if not _needs_refresh(cfg):
        return dict(_CACHE)
    if _CACHE.get("ts") and wait:
        # 有旧数据:先返回旧的,后台补
        threading.Thread(target=refresh, args=(cfg, False), daemon=True).start()
        return dict(_CACHE)
    return refresh(cfg)


def cache_state() -> Dict[str, Any]:
    with _LOCK:
        return {
            "age_sec": int(time.time() - _CACHE["ts"]) if _CACHE.get("ts") else None,
            "rows": len(_CACHE.get("visits") or []),
            "error": _CACHE.get("error") or "",
            "took_ms": _CACHE.get("took_ms") or 0,
            "loading": bool(_CACHE.get("loading")),
            "meta": _CACHE.get("meta") or {},
        }


def visits() -> List[Dict[str, Any]]:
    with _LOCK:
        return list(_CACHE.get("visits") or [])


def stores() -> List[Dict[str, Any]]:
    with _LOCK:
        return list(_CACHE.get("stores") or [])


def sources() -> List[Dict[str, Any]]:
    with _LOCK:
        return list(_CACHE.get("sources") or [])


# ==================== 门店映射 ====================

def _norm_name(s: Any) -> str:
    s = str(s or "").strip().lower()
    for ch in "  -—_·()()":
        s = s.replace(ch, "")
    return s


def suggest_map(traffic_stores: Iterable[Dict[str, Any]],
                local_stores: Iterable[Dict[str, Any]],
                existing: Optional[Dict[str, str]] = None
                ) -> Tuple[Dict[str, str], List[Dict[str, Any]]]:
    """客流门店 → 本系统门店 的建议映射。

    三级匹配,宁可漏配也不乱配:
      1) 名称完全相同(去空格/大小写后)
      2) 名称互相包含(「捷途山海」⊂「雅胜-山海」)
      3) 品牌唯一 —— **且**该品牌在本系统只剩一家没被占用的门店
    existing 里人工配过的一律原样保留。
    """
    local = [dict(s) for s in local_stores]
    lname = {s["id"]: _norm_name(s.get("name")) for s in local}
    lbrand = {s["id"]: _norm_name(s.get("brand")) for s in local}

    out: Dict[str, str] = dict(existing or {})
    detail: List[Dict[str, Any]] = []
    used = set(out.values())

    pending = [t for t in traffic_stores
               if str(t.get("id")) not in out or not out.get(str(t.get("id")))]

    # 1) 名称完全相同
    for t in pending:
        key = str(t.get("id"))
        n = _norm_name(t.get("name"))
        hit = [sid for sid, v in lname.items() if v and v == n]
        if len(hit) == 1 and hit[0] not in used:
            out[key] = hit[0]
            used.add(hit[0])

    # 2) 名称互相包含(取最长公共匹配,长度 ≥2 才算)
    for t in pending:
        key = str(t.get("id"))
        if out.get(key):
            continue
        n = _norm_name(t.get("name"))
        if len(n) < 2:
            continue
        best, best_len = None, 0
        for sid, v in lname.items():
            if not v or sid in used:
                continue
            common = 0
            for L in range(2, min(len(n), len(v)) + 1):
                if any(n[i:i + L] in v for i in range(len(n) - L + 1)):
                    common = L
            if common > best_len:
                best, best_len = sid, common
        if best and best_len >= 2:
            out[key] = best
            used.add(best)

    # 3) 品牌唯一
    for t in pending:
        key = str(t.get("id"))
        if out.get(key):
            continue
        b = _norm_name(t.get("brand_name"))
        if not b:
            continue
        cand = [sid for sid, v in lbrand.items() if v and v == b and sid not in used]
        if len(cand) == 1:
            out[key] = cand[0]
            used.add(cand[0])

    for t in traffic_stores:
        key = str(t.get("id"))
        sid = out.get(key) or ""
        detail.append({
            "cid": key,
            "code": t.get("code"),
            "name": t.get("name"),
            "brand": t.get("brand_name"),
            "store_id": sid,
            "store_name": next((s.get("name") for s in local if s["id"] == sid), ""),
        })
    return out, detail


# ==================== 聚合 ====================

def _in_window(v: Dict[str, Any], ts: Optional[datetime],
               te: Optional[datetime]) -> bool:
    dt = v.get("dt")
    if dt is None:
        return ts is None and te is None
    if ts is not None and dt < ts:
        return False
    if te is not None and dt > te:
        return False
    return True


def select(ts: Optional[datetime] = None, te: Optional[datetime] = None,
           store_ids: Optional[Iterable[str]] = None,
           keep_void: bool = False) -> List[Dict[str, Any]]:
    """按时间窗 + 门店集合挑出到店记录(store_ids=None 表示不限)。"""
    want = set(store_ids) if store_ids is not None else None
    out = []
    for v in visits():
        if not keep_void and str(v.get("status") or "") in SKIP_STATUS:
            continue
        if want is not None and v.get("sid") not in want:
            continue
        if not _in_window(v, ts, te):
            continue
        out.append(v)
    return out


def _apply_map(cfg: Dict[str, Any]) -> Dict[str, Any]:
    """把客流门店ID 换成看板门店ID(写进 v['sid']),并给出未映射清单。"""
    smap = cfg.get("stores") or {}
    unmapped: Dict[str, Dict[str, Any]] = {}
    counts: Dict[str, int] = {}
    rows = visits()
    for v in rows:
        cid = str(v.get("store_cid"))
        v["sid"] = smap.get(cid) or ""
        counts[v.get("store") or cid] = counts.get(v.get("store") or cid, 0) + 1
        if not v["sid"]:
            u = unmapped.setdefault(cid, {"cid": cid, "name": v.get("store") or "",
                                          "brand": v.get("brand") or "", "rows": 0})
            u["rows"] = u.get("rows", 0) + 1
    with _LOCK:
        _CACHE["mapped"] = True
    return {"unmapped": sorted(unmapped.values(), key=lambda x: -x["rows"]),
            "counts": counts}


def source_label(code: str) -> str:
    for s in sources():
        if str(s.get("code")) == code:
            return str(s.get("name") or code)
    return code or "未填"


def aggregate(ts: Optional[datetime] = None, te: Optional[datetime] = None,
              store_ids: Optional[Iterable[str]] = None,
              top: int = 8) -> Dict[str, Any]:
    """在已映射的前提下,按窗口/门店聚合成前端要的形状。"""
    rows = select(ts, te, store_ids)
    total = len(rows)
    by_store: Dict[str, int] = {}
    by_day: Dict[str, int] = {}
    by_source: Dict[str, int] = {}
    by_level: Dict[str, int] = {}
    by_advisor: Dict[Tuple[str, str], int] = {}
    by_purpose: Dict[str, int] = {}
    stays: List[float] = []
    first_cnt = repeat_cnt = 0
    test_cnt = 0
    test_by_store: Dict[str, int] = {}
    ord_cnt = 0
    ord_by_store: Dict[str, int] = {}
    wechat_cnt = 0
    status_cnt: Dict[str, int] = {}

    for v in rows:
        sid = v.get("sid") or ""
        if sid:
            by_store[sid] = by_store.get(sid, 0) + 1
        if v.get("date"):
            by_day[v["date"]] = by_day.get(v["date"], 0) + 1
        src = v.get("source") or ""
        lab = source_label(src)
        by_source[lab] = by_source.get(lab, 0) + 1
        lv = v.get("level") or "未分级"
        by_level[lv] = by_level.get(lv, 0) + 1
        eff = v.get("advisor") or "未指派"
        by_advisor[(eff, v.get("store") or "")] = by_advisor.get(
            (eff, v.get("store") or ""), 0) + 1
        pu = v.get("purpose") or "未填"
        by_purpose[pu] = by_purpose.get(pu, 0) + 1
        if isinstance(v.get("stay"), (int, float)) and v["stay"] > 0:
            stays.append(float(v["stay"]))
        st = str(v.get("status") or "")
        status_cnt[st] = status_cnt.get(st, 0) + 1
        rc = v.get("reception")
        if isinstance(rc, (int, float)) and rc > 1:
            repeat_cnt += 1
        else:
            first_cnt += 1
        if v.get("test_drive") in ("yes", "是", True):
            test_cnt += 1
            if sid:
                test_by_store[sid] = test_by_store.get(sid, 0) + 1
        if str(v.get("deal") or "") in ORDERED_INTENTS:
            ord_cnt += 1
            if sid:
                ord_by_store[sid] = ord_by_store.get(sid, 0) + 1
        if v.get("wechat"):
            wechat_cnt += 1

    adv = sorted(by_advisor.items(), key=lambda kv: -kv[1])[:top]
    return {
        "total": total,
        "by_store": by_store,
        "by_day": dict(sorted(by_day.items())),
        "by_source": [{"name": k, "count": v} for k, v in
                      sorted(by_source.items(), key=lambda kv: -kv[1])],
        "by_level": [{"level": k, "count": v} for k, v in
                     sorted(by_level.items(), key=lambda kv: -kv[1])],
        "by_purpose": [{"name": k, "count": v} for k, v in
                       sorted(by_purpose.items(), key=lambda kv: -kv[1])],
        "by_advisor": [{"name": k[0], "store": k[1], "count": v} for k, v in adv],
        "first_visit": first_cnt,
        "repeat_visit": repeat_cnt,
        "test_drive": test_cnt,
        "test_drive_by_store": test_by_store,
        "ordered": ord_cnt,
        "ordered_by_store": ord_by_store,
        "wechat_added": wechat_cnt,
        "avg_stay": round(sum(stays) / len(stays), 1) if stays else None,
        "status": status_cnt,
    }


def mask_phone(p: Any) -> str:
    """手机上屏一律脱敏:11 位号码留前 3 后 4;「未留电话#hash」原样显示前半段。"""
    s = str(p or "").strip()
    if not s:
        return "—"
    digits = "".join(ch for ch in s if ch.isdigit())
    if len(s) == 11 and len(digits) == 11:
        return s[:3] + "****" + s[-4:]
    if s.startswith("未留电话"):
        return "未留电话"
    return s[:2] + "****" if len(s) > 4 else "—"


def select_mapped(cfg: Dict[str, Any], ts: Optional[datetime] = None,
                  te: Optional[datetime] = None,
                  store_ids: Optional[Iterable[str]] = None,
                  keep_void: bool = False) -> List[Dict[str, Any]]:
    """先套门店映射再筛选(并发安全版)。

    为什么要单独一个函数:`ensure()` 在缓存过期时会**后台刷新**,
    如果先 `_apply_map()` 再 `select()`,中间那次刷新换进来的新列表还没映射过,
    sid 全是空 → 按门店筛出来就是 0。这里每次读都现套映射,绕开这个竞态。
    """
    smap = cfg.get("stores") or {}
    want = set(store_ids) if store_ids is not None else None
    out = []
    for v in visits():
        sid = smap.get(str(v.get("store_cid"))) or ""
        v["sid"] = sid
        if not keep_void and str(v.get("status") or "") in SKIP_STATUS:
            continue
        if want is not None and sid not in want:
            continue
        if not _in_window(v, ts, te):
            continue
        out.append(v)
    return out


def detail_rows(ts: Optional[datetime] = None, te: Optional[datetime] = None,
                store_ids: Optional[Iterable[str]] = None,
                limit: int = 500) -> List[Dict[str, Any]]:
    rows = select(ts, te, store_ids)
    rows.sort(key=lambda v: (v.get("dt") or datetime(1970, 1, 1)), reverse=True)
    out = []
    for v in rows[:limit]:
        out.append({
            "id": v.get("id"),
            "date": v.get("date"),
            "time": v.get("dt").strftime("%H:%M") if v.get("dt") else "",
            "store": v.get("store"),
            "brand": v.get("brand"),
            "advisor": v.get("advisor") or "—",
            "name": v.get("name") or "—",
            "phone": mask_phone(v.get("phone")),
            "level": v.get("level") or "—",
            "source": source_label(v.get("source") or ""),
            "stay": v.get("stay"),
            "status": v.get("status"),
            "intent": v.get("intent") or "—",
            "test_drive": v.get("test_drive"),
            "reception": v.get("reception"),
        })
    return out


def ensure_ready(cfg: Dict[str, Any]) -> Dict[str, Any]:
    """给请求路径用:确保缓存可用 + 门店映射已套用。"""
    st = ensure(cfg)
    _apply_map(cfg)
    return st