代码管理

facts_pull.py

← 返回编辑
# -*- coding: utf-8 -*-
"""四域数据拉取(云端版,2026-11-18)。

原来是本机命令行脚本(gr-runner/facts_sync.py),改成模块后由看板服务
自己的后台线程定时调用 —— **不再依赖任何本机进程**。

时间线:线索 createTime → 订单 createTime/planMonth → 交付 recordDate → 库存 时点

落库不在这里做:调用方通过 `set_sink(fn)` 注入一个写库函数
(app.py 的 `_facts_ingest_core`),避免模块反向依赖 app 造成循环导入。

只读红线:所有请求都是 count / page 查询,无任何写入平台的操作。
"""
from __future__ import annotations

import calendar
import json
import re
import time
import urllib.error
import urllib.request
from datetime import datetime
from concurrent.futures import ThreadPoolExecutor

import db                       # noqa: E402
import api_facts as fx          # noqa: E402
import crypto_store as cs       # noqa: E402
import api_connectors as apix   # noqa: E402


import db                       # noqa: E402
import api_facts as fx          # noqa: E402
import crypto_store as cs       # noqa: E402
import api_connectors as apix   # noqa: E402

OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))

ODIN_ORDER_HOST = {
    "aodin": "https://icarodin.mychery.com",
    "yldodin": "https://icarodin.mychery.com",
    "qaodin": "https://odin.mychery.com",
    "hodin": "https://odin.mychery.com",
    "hlodin": "https://odin.mychery.com",
    "codin": "https://odin.mychery.com",
    "qodin": "https://odin.mychery.com",
    "jtodin": "https://odin.jetourauto.com",
    "lsodin": "https://odin.jetourauto.com",
    "ysodin": "https://odin.jetourauto.com",
    "znzodin": "https://odin.jetourauto.com",
    "lgzodin": "https://odin.jetourauto.com",
}


# ---------------------------------------------------------------- 云端配置
def load_cfg():
    conn = db.get_conn()
    try:
        r = conn.execute("SELECT config FROM dashboard_config WHERE id=?",
                         (apix.CFG_ID,)).fetchone()
        key = conn.execute("SELECT config FROM dashboard_config WHERE id='facts_cfg'").fetchone()
    finally:
        conn.close()
    raw = json.loads(r["config"]) if r and r["config"] else {}
    fk = ""
    if key and key["config"]:
        try:
            fk = json.loads(key["config"]).get("key") or ""
        except Exception:
            fk = ""
    return apix.norm_cfg(raw), fk


def save_cfg(cfg):
    """把续期后的 token 写回云端(奥丁 refresh 会轮换 refresh_token)。"""
    conn = db.get_conn()
    try:
        conn.execute(
            "INSERT OR REPLACE INTO dashboard_config(id, config, updated_at) VALUES(?,?,?)",
            (apix.CFG_ID, json.dumps(cfg, ensure_ascii=False), datetime.now().isoformat(" ", "seconds")))
        conn.commit()
    finally:
        conn.close()


def cred_of(it):
    t = str(it.get("token") or "").strip()
    if cs.is_encrypted(t):
        t = cs.decrypt(t)
    t = t.strip()
    if t.startswith("{"):
        try:
            return json.loads(t)
        except Exception:
            pass
    return {"token": t, "x_token": t, "sc_token": t}


def _unwrap(v):
    if isinstance(v, str):
        v = v.strip()
        if len(v) >= 2 and v[0] == '"' and v[-1] == '"':
            try:
                return json.loads(v)
            except Exception:
                return v[1:-1]
    return v


# ---------------------------------------------------------------- HTTP
def _as_list(v):
    """把接口返回的 data 兜成 list。

    这些厂商接口有个共同毛病:没数据时 data 直接给 0 或 null,
    而不是空数组。原写法 `j.get("data") or []` 对 0 有效(falsy),
    但对 int/字符串就漏了 —— out.extend(123) 直接
    TypeError: 'int' object is not iterable,整批门店/域全挂。
    11-20 那次"27 个门店/域失败、数据断流 48 小时"就是这么来的。
    """
    if isinstance(v, list):
        return v
    if isinstance(v, dict):
        for k in ("list", "records", "rows", "items", "recordsList", "data"):
            if isinstance(v.get(k), list):
                return v[k]
    return []


def _as_dict(v):
    """同理:期望 dict 的地方,拿到 int/None 一律当空 dict。"""
    return v if isinstance(v, dict) else {}


def post(url, body, headers, timeout=60):
    req = urllib.request.Request(url, data=json.dumps(body, ensure_ascii=False).encode(),
                                 headers=headers, method="POST")
    with OPENER.open(req, timeout=timeout) as r:
        return json.loads(r.read().decode())


_SINK = None
_ERRORS = []


def set_sink(fn):
    """注入落库函数:fn(domain, store_id, store_name, cols, rows, source, force) -> dict"""
    global _SINK
    _SINK = fn


def _ingest(domain, store, rows, cols, dry=False, source="", force=False):
    """force=True 只在「确认是口径切换」时用;空表仍然会被守卫拦下。"""
    if dry:
        return {"ok": True, "dry": True, "rows": len(rows)}
    if _SINK is None:
        raise RuntimeError("facts_pull 未注入 sink,无法落库")
    return _SINK(domain, store["store_id"], store.get("store_name") or "",
                 cols, rows, source, bool(force and rows))


# ---------------------------------------------------------------- 奥丁鉴权
def odin_refresh(base, c):
    rt, ba = c.get("refresh_token") or "", c.get("basic_auth") or ""
    if not (rt and ba):
        return None
    import urllib.parse
    qs = urllib.parse.urlencode({"refresh_token": rt, "grant_type": "refresh_token",
                                 "scope": "server"})
    req = urllib.request.Request(base + "/auth/oauth2/token?" + qs, data=b"", method="POST")
    req.add_header("Authorization", ba)
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    req.add_header("TENANT-ID", str(c.get("tenant_id") or ""))
    req.add_header("TENANT-CODE", str(c.get("tenant_code") or c.get("tenant_id") or ""))
    req.add_header("Cch", "Y2NocA==")
    try:
        with OPENER.open(req, timeout=30) as r:
            j = json.loads(r.read().decode())
    except Exception as e:
        print("    [refresh] 失败 %s" % str(e)[:100])
        return None
    if str(j.get("code")) not in ("0", "200"):
        print("    [refresh] 返回异常 %s" % str(j)[:120])
        return None
    d = _as_dict(j.get("data"))
    if not d.get("access_token"):
        return None
    exp = d.get("expires_in")
    return {"token": d["access_token"],
            "refresh_token": d.get("refresh_token") or rt,
            "tenant_id": c.get("tenant_id") or "",
            "tenant_code": c.get("tenant_code") or "",
            "basic_auth": ba,
            "expires_at": str(int(time.time()) + int(exp)) if exp else ""}


def odin_headers(c):
    return {"Content-Type": "application/json",
            "Accept": "application/json, text/plain, */*",
            "Authorization": "Bearer " + str(c.get("token") or ""),
            "TENANT-ID": str(c.get("tenant_id") or ""),
            "TENANT-CODE": str(c.get("tenant_code") or c.get("tenant_id") or ""),
            "Cch": str(c.get("basic_auth") or "Y2NocA=="),
            "time-zone": "Asia/Shanghai"}


def odin_post(it, c, url, body):
    """带自动续期的奥丁 POST。续期成功会把新凭据写回内存里的接口对象。"""
    try:
        return post(url, body, odin_headers(c))
    except urllib.error.HTTPError as e:
        if e.code not in (401, 424):
            raise
        base = (it.get("gateway") or "").rstrip("/")
        base = base if base.endswith("/api") else base + "/api"
        c2 = odin_refresh(base, c)
        if not c2:
            raise
        it["_cred_new"] = c2
        c.update(c2)
        return post(url, body, odin_headers(c2))


# ---------------------------------------------------------------- 拉取
def pages_odin(it, c, url, body, size=100, cap=200):
    out, p = [], 1
    while p <= cap:
        b = dict(body, current=p, size=size)
        j = odin_post(it, c, url, b)
        d = _as_dict(j.get("data"))
        recs = _as_list(d.get("records"))
        out.extend(recs)
        total = int(d.get("total") or 0)
        if not recs or len(out) >= total:
            break
        p += 1
    return out


def pull_stock(it, c, months=None):
    base = (it.get("gateway") or "").rstrip("/")
    base = base if base.endswith("/api") else base + "/api"
    recs = pages_odin(it, c, base + "/dealerSvc/dealerVehicleStock/pageDealer",
                      {"activeTab": 1})
    return recs


def pull_orders(it, c, months):
    host = ODIN_ORDER_HOST.get(it.get("profile") or "", "")
    if not host:
        raise RuntimeError("未知奥丁网关:%s" % it.get("profile"))
    out = []
    for m in months:
        y, mm = int(m[:4]), int(m[5:7])
        out.extend(pages_odin(it, c, host + "/api/order/dealer/vehicleOrder/page",
                              {"planYear": y, "planMonths": [mm]}))
    return out


def pull_yike_orders(it, c):
    """亿客「订单管理」全量订单。

    接口在 scrm-customer-api 下(不是 clue-api),权限码 ShopSalesOrder ——
    这两个都是 2026-11-18 从页面真实请求里抓到的,猜路径是猜不出来的。
    pageIndex 在本接口有效(实测 951 条分 5 页无重复),pageSize 200 可用。
    """
    gw = (it.get("gateway") or "").rstrip("/")
    if "/scrm-clue-api" in gw:
        base = gw.split("/scrm-clue-api")[0]
    else:
        from urllib.parse import urlsplit
        u = urlsplit(gw)
        base = "%s://%s" % (u.scheme, u.netloc)
    url = base + "/scrm-customer-api/orderInfo/queryList"
    hdr = {"Content-Type": "application/json",
           "sc_token": c.get("sc_token") or c.get("token") or "",
           "scrm_permission": "ShopSalesOrder"}
    out, p = [], 1
    while p <= 80:
        j = post(url, {"orderStatusList": [], "odinStatusList": [],
                       "pageIndex": p, "pageSize": 200}, hdr, timeout=90)
        recs = _as_list(j.get("data"))
        out.extend(recs)
        tot = int((j.get("pageInfo") or {}).get("totalCount") or 0)
        if not recs or len(out) >= tot:
            break
        p += 1
    return out


def pull_chery_orders(it, c):
    """奇瑞订单 = 线索里「已下订(6) + 已交车(9)」两批。

    没有独立订单接口,也没有下定时间,所以订单日期只能取线索创建时间
    (近似口径,见 api_facts.normalize_chery_orders 的说明)。
    """
    gw = (it.get("gateway") or "").rstrip("/")
    base = gw if gw.endswith("scrm-clue") else gw + "/api/app/scrm-clue"
    hdr = {"Content-Type": "application/json",
           "X-Token": c.get("x_token") or c.get("token") or "",
           "pre-auth-code": c.get("pre_auth_code") or it.get("pre_auth_code") or "",
           "client-type": str(c.get("client_type") or "0"),
           "Origin": "https://scrm.mychery.com"}
    out = []
    for code in (6, 9):
        p = 1
        while p <= 30:
            j = post(base + "/crmClue/pc/list/query2",
                     {"pageNum": p, "pageSize": 1000,
                      "clueStatus": [code], "clueLevel": []}, hdr, timeout=90)
            if str(j.get("code")) not in ("0", "200"):
                raise RuntimeError("SCRM 返回 %s %s" % (j.get("code"), j.get("msg")))
            recs = _as_list(j.get("data"))
            out.extend(recs)
            if len(recs) < 1000:
                break
            p += 1
    return out


def _ms(d, end=False):
    t = time.strptime(d + (" 23:59:59" if end else " 00:00:00"), "%Y-%m-%d %H:%M:%S")
    return int(time.mktime(t) * 1000) - 8 * 3600 * 1000


def pull_sales(it, c, months):
    """实销:按月拉(区间太大时接口会限制返回条数,分月既快又能对齐时间线)。"""
    host = ODIN_ORDER_HOST.get(it.get("profile") or "", "")
    if not host:
        raise RuntimeError("未知奥丁网关:%s" % it.get("profile"))
    out = []
    for m in months:
        d1, d2 = fx.month_bounds(m)
        out.extend(pages_odin(it, c, host + "/api/order/actualSales/dealer/page",
                              {"startRecordDate": _ms(d1), "endRecordDate": _ms(d2, True)}))
    return out


def _pull_range(url, hdr, base_body, lo_ms, hi_ms, depth=0, log=None):
    """按「时间段按条数等分」把一个区间拉全。

    亿客这个接口有两个硬限制(都实测过,翻页相关的参数全试过):
      · 单次最多返回 **100 条**(pageSize 设 200/500/1000/2000 都一样)
      · `pageIndex` **不生效**,翻页永远返回第一页(100% 重叠);
        `nextToken` 放进 body 也不生效
    所以只能靠缩小时间窗来枚举:查到 total 后按 total/60 把区间**等分**,
    每个窗口一次拿全(≤100)。用等分而不是二分 —— 1722 条二分要 63 次请求,
    等分只要 30 次。
    """
    body = dict(base_body, createTimeStart=int(lo_ms), createTimeEnd=int(hi_ms))
    j = post(url, body, hdr)
    recs = _as_list(j.get("data"))
    total = int((j.get("pageInfo") or {}).get("totalCount") or 0)
    if total <= len(recs) or depth >= 6 or hi_ms - lo_ms < 1800 * 1000:
        if total > len(recs) and log:
            log("      ⚠️ %s 窗口仍有 %d/%d 条未取全"
                % (time.strftime("%Y-%m-%d %H", time.localtime(lo_ms / 1000)),
                   len(recs), total))
        return recs
    k = max(2, min(60, (total + 59) // 60))
    span = (hi_ms - lo_ms + 1) // k
    spans = [(lo_ms + i * span, (lo_ms + (i + 1) * span - 1) if i < k - 1 else hi_ms)
             for i in range(k)]
    out = []
    if k <= 6:
        for a, b in spans:
            out.extend(_pull_range(url, hdr, base_body, a, b, depth + 1, log))
        return out
    from concurrent.futures import ThreadPoolExecutor
    with ThreadPoolExecutor(max_workers=6) as ex:
        futs = [ex.submit(_pull_range, url, hdr, base_body, a, b, depth + 1, log)
                for a, b in spans]
        for f in futs:
            try:
                out.extend(f.result())
            except Exception as e:
                if log:
                    log("      ⚠️ 分段失败 %s" % str(e)[:60])
    return out


# ---------------------------------------------------------------- 明文补全
# iCAR 两家的列表接口**恒返回脱敏号**(187****9948),跟列表参数没关系 ——
# desensitized / showPlain / needPlain / decodePhone 这些开关全试过,一律无效。
# 但**账号本身是有「查看明文」权限的**:SCRM 前端那个「查看明文」按钮走的是
# 单条接口,一次换一个字段。所以要拿全程只能照 UI 的行为逐条换。
PLAIN_PATH = "/sensitive/plain/query"
PLAIN_TABLE = "crm_clue"
# ⚠️ 字段名必须是**下划线**的 mobile_phone;驼峰 mobilePhone 直接 500「操作失败」
PLAIN_FIELDS = ("mobile_phone", "mobilePhone")
PLAIN_WORKERS = 6                 # 6 并发 ≈ 50 条/秒;这个号还要日常用,不图快
_MOBILE_RE = re.compile(r"^1[3-9]\d{9}$")


def _plain_one(url, hdr, rid):
    """换一条明文手机号。任何异常都只返回 ''——一条失败不能拖垮整批。"""
    for fld in PLAIN_FIELDS:
        try:
            j = post(url, {"id": rid, "fieldName": fld,
                           "tableName": PLAIN_TABLE, "type": 1}, hdr, timeout=20)
        except Exception:                      # noqa: BLE001
            continue
        if str(j.get("code")) not in ("0", "200"):
            continue
        digits = "".join(ch for ch in str(_unwrap(j.get("data")) or "") if ch.isdigit())
        if _MOBILE_RE.match(digits[-11:] if len(digits) > 11 else digits):
            return digits[-11:]
    return ""


def fill_plain_phones(base, hdr, recs, log=None, workers=PLAIN_WORKERS):
    """把 recs 里脱敏的 mobilePhone 逐条换成明文(原地改写)。

    recs 中 mobilePhone 含 "*" 的才算需要补全。返回 {need, ok, fail}。
    需要补全却一条都没成功 → 打告警:多半是「查看明文」权限被收了,
    这种情况必须让人看见,不能静默变成「少三万条」。
    """
    idx = [i for i, r in enumerate(recs)
           if "*" in str(r.get("mobilePhone") or r.get("customerPhone") or "")]
    st = {"need": len(idx), "ok": 0, "fail": 0}
    if not idx:
        return st
    url = base + PLAIN_PATH
    pairs = [(i, str(recs[i].get("id") or "")) for i in idx]
    pairs = [(i, x) for i, x in pairs if x]
    st["fail"] += len(idx) - len(pairs)        # 连 id 都没有,查不了明文
    if not pairs:
        return st
    w = max(1, min(int(workers or 1), 16))
    pending = pairs
    done = 0
    for _round in range(2):                    # 失败的再补一轮,抛错/超时多为瞬时
        if not pending:
            break
        failed = []
        with ThreadPoolExecutor(max_workers=w) as ex:
            futs = [ex.submit(_plain_one, url, hdr, x) for _, x in pending]
            for (i, x), f in zip(pending, futs):
                try:
                    v = f.result()
                except Exception:              # noqa: BLE001
                    v = ""
                if v:
                    recs[i]["mobilePhone"] = v
                    recs[i]["_plain"] = True
                    st["ok"] += 1
                else:
                    failed.append((i, x))
                done += 1
                if log and done % 3000 == 0:
                    log("      明文补全进行中 %d/%d…" % (done, st["need"]))
        pending = failed
    st["fail"] = len(pending)
    if log and st["ok"] == 0:
        log("      ⚠️ 明文补全全部失败(%d 条):账号可能被收回「查看完整手机号」权限"
            % st["need"])
    return st


def _leads_yike_window(it, c, d1: str, d2: str, log=None):
    """亿客(捷途/纵横):一个日期窗口内的线索。窗口化是为了能按任意区间增量拉取。"""
    gw = (it.get("gateway") or "").rstrip("/")
    # ⚠️ 注册表里的 gateway 已经带了 /scrm-clue-api(https://digi.jetourauto.com/scrm-clue-api),
    #    再拼一次就是 .../scrm-clue-api/scrm-clue-api/... → 404(实测 5 个店全挂)
    base_j = gw if gw.endswith("scrm-clue-api") else gw + "/scrm-clue-api"
    url = base_j + "/shop/clue/pool/shop/default/queryShopCluePoolList"
    hdr = {"Content-Type": "application/json",
           "sc_token": c.get("sc_token") or c.get("token") or "",
           "scrm_permission": c.get("scrm_permission") or "ShopGeneralClueManage"}
    body = {"phone": "", "name": "", "meFlag": 0, "handleType": 1,
            "erpCode": it.get("erp") or "", "pageIndex": 1, "pageSize": 100}
    lo = int(time.mktime(time.strptime(d1, "%Y-%m-%d")) * 1000)
    hi = int(time.mktime(time.strptime(d2 + " 23:59:59", "%Y-%m-%d %H:%M:%S")) * 1000)
    got = _pull_range(url, hdr, body, lo, hi, log=log)
    # 等分窗口两端都含 → 边界记录可能重复,按 id 去重
    seen, fresh = set(), []
    for r in got:
        rid = r.get("id") or ""
        if rid and rid in seen:
            continue
        if rid:
            seen.add(rid)
        fresh.append(r)
    return fresh


def _chery_ctx(it, c):
    gw = (it.get("gateway") or "").rstrip("/")
    base = gw if gw.endswith("scrm-clue") else gw + "/api/app/scrm-clue"
    hdr = {"Content-Type": "application/json",
           "X-Token": c.get("x_token") or c.get("token") or "",
           "pre-auth-code": c.get("pre_auth_code") or it.get("pre_auth_code") or "",
           "client-type": str(c.get("client_type") or "0"),
           "Origin": "https://scrm.mychery.com"}
    return base, hdr


def _leads_chery_window(base, hdr, d1: str, d2: str, log=None):
    """奇瑞(C/H 网 + iCAR):一个日期窗口内的线索,query2 单页最多 1000。"""
    out = []
    p = 1
    while p <= 100:
        body = {"pageNum": p, "pageSize": 1000, "clueStatus": [], "clueLevel": [],
                "createTimeBegin": d1, "createTimeEnd": d2}
        j = post(base + "/crmClue/pc/list/query2", body, hdr)
        if str(j.get("code")) not in ("0", "200"):
            raise RuntimeError("SCRM 返回 %s %s" % (j.get("code"), j.get("msg")))
        recs = _as_list(j.get("data"))
        out.extend(recs)
        if len(recs) < 1000:
            break
        p += 1
    return out


def pull_leads(it, c, months, log=print, plain_phone=False):
    """plain_phone=True 时,把列表返回的脱敏号逐条换成明文(iCAR 必需)。

    默认关:只有「要把客户档案下发到客流系统」时才需要真号(traffic_sync),
    纯做指标统计的调用不该为此多打几万次接口。
    """
    fam = it.get("family") or ""
    out = []
    if fam == "jetour_yike":
        for m in months:
            d1, d2 = fx.month_bounds(m)
            fresh = _leads_yike_window(it, c, d1, d2, log=log)
            out.extend(fresh)
            log("      %s 亿客 %d 条" % (m, len(fresh)))
        return out
    base, hdr = _chery_ctx(it, c)
    for m in months:
        d1, d2 = fx.month_bounds(m)
        n0 = len(out)
        out.extend(_leads_chery_window(base, hdr, d1, d2, log=log))
        if log:
            log("      %s 奇瑞 %d 条" % (m, len(out) - n0))
    if plain_phone:
        st = fill_plain_phones(base, hdr, out, log=log)
        if st["need"] and log:
            log("      明文补全 %d/%d 条(失败 %d)"
                % (st["ok"], st["need"], st["fail"]))
    return out


def pull_leads_range(it, c, d1: str, d2: str, log=None, plain_phone=True):
    """按任意日期区间拉线索(YYYY-MM-DD,含头含尾)。

    给「客流系统主动来拉厂家客户档案」用:只要一段窗口,不要整月。
    脱敏号在窗口内逐条换明文(iCAR 必需),否则拉过去也建不了档。
    """
    fam = it.get("family") or ""
    if fam == "jetour_yike":
        out = _leads_yike_window(it, c, d1, d2, log=log)
    else:
        base, hdr = _chery_ctx(it, c)
        out = _leads_chery_window(base, hdr, d1, d2, log=log)
        if plain_phone:
            st = fill_plain_phones(base, hdr, out, log=log)
            if st["need"] and log:
                log("      明文补全 %d/%d 条(失败 %d)"
                    % (st["ok"], st["need"], st["fail"]))
    return out


# ---------------------------------------------------------------- 主流程

def do_store(store, domain, months, dry, log=print):
    ifaces = {i.get("kind"): i for i in (store.get("interfaces") or [])}
    leads_it = ifaces.get("线索")
    stock_it = ifaces.get("库存")
    if domain == "leads":
        it, source = leads_it, "SCRM 唯一线索"
        if not it or not it.get("token"):
            return None, "未接入线索接口"
        c = cred_of(it)
        recs = pull_leads(it, c, months, log=log)
        cols, rows = fx.normalize_leads(recs, it.get("family") or "")
        return _ingest(domain, store, rows, cols, dry, source), None
    # ---- 订单:亿客走自己的「订单管理」接口(用店端 sc_token),其余走奥丁 ----
    # ⚠️ 亿客的订单接口和线索是同一个账号同一个 token,跟奥丁库存无关,
    #    所以这一步必须放在「检查奥丁接口」之前,否则永远进不来。
    if domain == "order" and leads_it and (_li_fam := (leads_it.get("family") or "")) == "jetour_yike" \
            and leads_it.get("token"):
        recs = pull_yike_orders(leads_it, cred_of(leads_it))
        rows, stat = fx.normalize_yike_orders(recs)
        log("      亿客订单 拉取%d / 入库%d / 预付0排除%d / 战败%d"
            % (stat["total"], stat["kept"], stat["zero_pay"], stat["dead"]))
        # force:由「奥丁采购订单」换成「客户签单」属于口径切换,行数必然大降,
        # 但空表仍然会被塌陷守卫拦下(_ingest 里 force 只对非空生效)
        return _ingest(domain, store, rows, fx.COLUMNS["yike_order"],
                       dry, "亿客订单管理", force=True), None
    # ---- 订单:奇瑞从线索状态取(已下订 6 / 已交车 9)----
    if domain == "order" and leads_it and (leads_it.get("family") or "").startswith("chery") \
            and leads_it.get("token"):
        recs = pull_chery_orders(leads_it, cred_of(leads_it))
        rows = fx.normalize_chery_orders(recs)
        log("      SCRM 已下订+已交车 %d 条(订单日期=线索创建日期,近似)" % len(rows))
        return _ingest(domain, store, rows, fx.COLUMNS["yike_order"],
                       dry, "SCRM 线索状态", force=True), None
    if not stock_it or not stock_it.get("token"):
        return None, "未接入奥丁库存接口"
    it = stock_it
    c = cred_of(it)
    if domain == "stock":
        recs = pull_stock(it, c)
        rows = fx.normalize_stock(recs)
        return _ingest(domain, store, rows, fx.COLUMNS["stock"], dry, "奥丁在库"), None
    if domain == "order":
        recs = pull_orders(it, c, months)
        rows = fx.normalize_order(recs)
        return _ingest(domain, store, rows, fx.COLUMNS["order"], dry, "奥丁销售订单"), None
    if domain == "sales":
        recs = pull_sales(it, c, months)
        rows = fx.normalize_sales(recs)
        return _ingest(domain, store, rows, fx.COLUMNS["sales"], dry, "奥丁实销"), None
    return None, "未知域"


def run_all(domains=None, months=13, only_store="", dry=False, log=print):
    """按门店逐域拉取。返回 {"ok":n, "fail":n, "errors":[...], "domains":{...}}。

    单店单域失败不影响其它(亿客某家 token 过期时,其余 10 家照常更新)。
    """
    # ⚠️ months 允许两种写法:
    #    数字 N  = 最近 N 个月(调度配置里存的就是数字)
    #    列表    = ["2026-11", "2026-10", ...](调用方自己给具体月份)
    # 原来这里直接把数字透传给 pull_leads / pull_sales,
    # 而它们内部是 `for m in months: fx.month_bounds(m)` ——
    # 数字不能迭代,于是 leads/sales 全挂,报的就是
    # TypeError: 'int' object is not iterable [facts_pull.py:417/328]。
    # 11-18~11-20 所有门店的线索和实销都因此停更,首页显示"断流 48 小时"。
    if isinstance(months, int) or (isinstance(months, str) and months.isdigit()):
        n = max(1, min(24, int(months)))
        y, m = datetime.now().year, datetime.now().month
        lst = []
        for _ in range(n):
            lst.append("%04d-%02d" % (y, m))
            m -= 1
            if m == 0:
                y, m = y - 1, 12
        months = list(reversed(lst))

    cfg, _key = load_cfg()
    domains = domains or list(fx.DOMAINS)
    # error_items 比 errors 多了 store_id / domain:
    # 「最近成功时间」要按接口回写,只有一句中文错误串是定位不到接口的(2026-11-23)
    summary = {"ok": 0, "fail": 0, "errors": [], "error_items": [],
               "attempted": [], "domains": {}}
    stores = []
    for b in cfg.get("brands") or []:
        for s in b.get("stores") or []:
            if only_store and s.get("store_id") != only_store:
                continue
            stores.append(s)
        inv = b.get("inventory")
        if inv and not only_store:
            # 品牌级库存接口:挂到该品牌第一家门店上(与线下口径一致)
            if b.get("stores"):
                s0 = b["stores"][0]
                s0.setdefault("interfaces", [])
                if not any(i.get("kind") == "库存" for i in s0["interfaces"]):
                    s0["interfaces"].append(inv)
    for s in stores:
        name = s.get("store_name") or s.get("store_id")
        for d in domains:
            summary["attempted"].append([s.get("store_id"), d])
            try:
                log("  [%s] %s ..." % (name, d))
                res, err = do_store(s, d, months, dry, log=log)
                if err:
                    summary["fail"] += 1
                    summary["errors"].append("%s/%s: %s" % (name, d, err))
                    summary["error_items"].append(
                        {"store_id": s.get("store_id"), "domain": d, "error": str(err)[:200]})
                    continue
                summary["ok"] += 1
                summary["domains"].setdefault(d, 0)
                summary["domains"][d] += int((res or {}).get("rows") or 0)
            except urllib.error.HTTPError as e:
                summary["fail"] += 1
                body_txt = ""
                try:
                    body_txt = (e.read() or b"")[:120].decode("utf-8", "ignore")
                except Exception:
                    pass
                msg = ("%s/%s: HTTP %s %s" % (name, d, e.code, body_txt)).strip()
                summary["errors"].append(msg)
                summary["error_items"].append(
                    {"store_id": s.get("store_id"), "domain": d, "error": msg[:200]})
                log("    ✗ " + msg)
            except Exception as e:                            # noqa: BLE001
                summary["fail"] += 1
                # 带上出错的文件:行号 —— 只有 "TypeError: 'int' object is not
                # iterable" 这种消息根本定位不到位置(11-20 排查就卡在这儿)
                import traceback as _tb
                _loc = ""
                try:
                    _frames = _tb.extract_tb(e.__traceback__)
                    if _frames:
                        _f = _frames[-1]
                        _loc = " [%s:%d]" % (str(_f.filename).split("/")[-1], _f.lineno)
                except Exception:
                    pass
                msg = "%s/%s: %s: %s%s" % (name, d, type(e).__name__,
                                           str(e)[:140], _loc)
                summary["errors"].append(msg)
                summary["error_items"].append(
                    {"store_id": s.get("store_id"), "domain": d, "error": msg[:200]})
                log("    ✗ " + msg)
    # 奥丁续期后的新 token 立刻回写,否则下次又过期
    try:
        save_cfg(cfg)
    except Exception as e:                                    # noqa: BLE001
        log("  ⚠️ 回写配置失败:%s" % str(e)[:120])
    return summary