代码管理

traffic_sync.py

← 返回编辑
"""SCRM / 奥丁 → 集团客流登记系统 · 数据下发

两类数据、两个落点,**不混放**:

| 来源 | 内容 | 目标区域(客流系统) |
|---|---|---|
| SCRM 客户档案(线索池) | 姓名 / 手机 / 省市 / 线索级别 / 状态 / 渠道 | `customer` 客户档案 |
| 奥丁实销 | VIN / 车型 / 成交价 / 交车日 / 顾问 / 门店 | `deal_record` 成交记录 |

为什么这样分
------------
- 客户身份(手机号)**只有 SCRM 给得到**。但两类账号返回的口径不一样:
  奇瑞 C/H 网 4 家店的列表接口直接给全号;iCAR 两家**列表恒脱敏**
  (187****9948),必须照前端「查看明文」的行为逐条调
  `POST /scrm-clue/sensitive/plain/query` 换真号(见 facts_pull.fill_plain_phones)。
  捷途 5 家 token 过期(401)→ 报错留痕,不阻塞其它门店。
  所以"客户档案"一律以 SCRM 为准 —— 用奥丁那点脱敏姓名(**朋)去建档等于往主档里灌垃圾。
- 奥丁实销是**成交事实**(VIN、车型、日期、价格、顾问),没有客户身份。所以它只进
  "成交记录",靠脱敏号在客流系统**内部**匹配已有档案(唯一命中才落,多个候选一律拒绝)。
- 奥丁"订单"(vehicleOrder)是**经销商向厂家订车**,不是客户订单,混进成交会把台数虚增,
  因此不采。

同步原则
--------
1. **只增不改**:客户档案走 upsert,已存在的非空字段不覆盖;成交按 (客户, VIN) 幂等,
   只在"未交车 → 已交车"前进时更新。
2. **拒绝猜测**:手机号脱敏、跨店、多候选,一律不写,只在报告里计数并给出原因。
3. **可演练**:`dry_run=True` 时只统计与校验,不落库;正式写入前必须先看演练结果。
4. **留痕**:每次调用由客流系统写 audit_log(谁/何时/新增多少),逐字段变更写
   customer_change_log;本模块把最近一次结果存进 dashboard_config,重启不丢。
"""
from __future__ import annotations

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

import requests

import facts_pull as fp

CFG_ID = "traffic_sync"
BASE_DEFAULT = "https://traffic-system.app.workbuddy.host/api/v1/open/inbound"
CLIENT_ID_DEFAULT = "wb_guangrui_sync"
# 与客流系统 app/routers/inbound.py 的 INBOUND_CLIENT_SECRET_DEFAULT 保持一致
SECRET_DEFAULT = "sk_grsync_2026_odin_scrm_push_9f3c7a1e5b"
SHARECODE_DEFAULT = "ONDEZN7NKO"          # 平台访问门(不带它一律 403)
BATCH = 100                                # 单批条数,服务端上限 500
TIMEOUT = 30

MOBILE_RE = re.compile(r"^1[3-9]\d{9}$")
MASK_RE = re.compile(r"^\d{3}\*+\d{4}$")
EMPTY_NAMES = {"", "未命名", "匿名", "客户"}

_TS = threading.local()


def _sess() -> requests.Session:
    s = getattr(_TS, "s", None)
    if s is None:
        s = requests.Session()
        s.trust_env = False                 # 本机代理会劫持 requests,实测必踩
        _TS.s = s
    return s


# ================================================================ 配置
def norm_cfg(raw: Optional[Dict[str, Any]]) -> Dict[str, Any]:
    r = raw or {}
    return {
        "base": (r.get("base") or BASE_DEFAULT).rstrip("/"),
        "client_id": r.get("client_id") or CLIENT_ID_DEFAULT,
        "secret": r.get("secret") or "",           # 密文;空 = 用内置默认
        "sharecode": r.get("sharecode") or SHARECODE_DEFAULT,
        "stores": r.get("stores") or {},            # {本系统store_id: 客流store_id}
        "months": int(r.get("months") or 3),
        "sources": {"scrm": True, "odin": True, "orders": True,
                    **(r.get("sources") or {})},
        "allow_masked_match": bool(r.get("allow_masked_match")),
        "create_missing": r.get("create_missing", True) is not False,
        # 明文补全:列表接口恒脱敏的账号(iCAR 两家)需要逐条换真号
        "plain_phone": r.get("plain_phone", True) is not False,
        "last_run": r.get("last_run") or None,
        "last_dry": r.get("last_dry") or None,
        "history": r.get("history") or [],
        "updated_at": r.get("updated_at") or "",
    }


def load_cfg(conn) -> Dict[str, Any]:
    try:
        row = conn.execute("SELECT config FROM dashboard_config WHERE id=?",
                           (CFG_ID,)).fetchone()
    except Exception:
        row = None
    if not row:
        return norm_cfg({})
    try:
        return norm_cfg(json.loads(row["config"] or "{}"))
    except Exception:
        return norm_cfg({})


def save_cfg(conn, cfg: Dict[str, Any]) -> Dict[str, Any]:
    c = norm_cfg(cfg)
    c["updated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    payload = json.dumps(c, ensure_ascii=False)
    conn.execute("INSERT OR REPLACE INTO dashboard_config(id, config) VALUES(?,?)",
                 (CFG_ID, payload))
    conn.commit()
    return c


def _secret(cfg: Dict[str, Any]) -> str:
    s = cfg.get("secret") or ""
    if not s:
        return SECRET_DEFAULT
    try:
        from crypto_store import decrypt_json, is_encrypted
        if is_encrypted(s):
            v = decrypt_json(s)
            return v if isinstance(v, str) else SECRET_DEFAULT
    except Exception:
        pass
    return s


# ================================================================ 客流接口
def _headers(cfg: Dict[str, Any]) -> Dict[str, str]:
    return {"X-Client-Id": cfg["client_id"], "X-Client-Secret": _secret(cfg),
            "Content-Type": "application/json"}


def _warm(cfg: Dict[str, Any]) -> None:
    """平台访问门:不带 sharecode 的会话一律 403(这不是登录,只是过网关)"""
    sc = cfg.get("sharecode")
    if not sc:
        return
    host = cfg["base"].split("/api/")[0]
    try:
        _sess().get(host + "/?sharecode=" + sc, timeout=TIMEOUT)
    except Exception:
        pass


def traffic_meta(cfg: Dict[str, Any]) -> Dict[str, Any]:
    _warm(cfg)
    r = _sess().get(cfg["base"] + "/meta", headers=_headers(cfg), timeout=TIMEOUT)
    if r.status_code == 401:
        raise RuntimeError("客流系统拒绝凭证(401):client_id/secret 不匹配或凭证被停用")
    if r.status_code == 403:
        raise RuntimeError("客流系统拒绝访问(403):凭证缺少 data:write,或平台访问门拦截")
    if not r.ok:
        raise RuntimeError("客流系统 /meta 返回 %d:%s" % (r.status_code, r.text[:120]))
    return r.json()


def _post(cfg: Dict[str, Any], path: str, body: Dict[str, Any]) -> Dict[str, Any]:
    last = None
    for attempt in range(3):
        try:
            r = _sess().post(cfg["base"] + path, headers=_headers(cfg),
                             json=body, timeout=TIMEOUT + 20)
            if r.status_code in (429, 500, 502, 503, 504):
                last = "HTTP %d" % r.status_code
                time.sleep(1.5 * (attempt + 1))
                continue
            if r.status_code == 401:
                raise RuntimeError("凭证失效(401),请检查 client_id / secret")
            if not r.ok:
                raise RuntimeError("%s 返回 %d:%s" % (path, r.status_code, r.text[:160]))
            return r.json()
        except RuntimeError:
            raise
        except Exception as e:                      # 网络抖动:退避重试
            last = "%s: %s" % (type(e).__name__, str(e)[:80])
            time.sleep(1.5 * (attempt + 1))
    raise RuntimeError("推送失败(%s):%s" % (path, last))


def _push_batched(cfg: Dict[str, Any], path: str, items: List[dict],
                  dry: bool, extra: Optional[dict] = None) -> Dict[str, Any]:
    """分批推送并汇总。单批失败不影响已成功的批次,最后一起回报。"""
    total = {"received": 0, "created": 0, "updated": 0, "unchanged": 0,
             "skipped": 0, "failed": 0, "masked_matched": 0}
    errors: List[dict] = []
    batches = 0
    for i in range(0, len(items), BATCH):
        chunk = items[i:i + BATCH]
        body = {"items": chunk, "dry_run": dry}
        if extra:
            body.update(extra)
        res = _post(cfg, path, body)
        batches += 1
        for k in total:
            total[k] += int((res.get("totals") or {}).get(k) or 0)
        for e in (res.get("errors") or []):
            if len(errors) < 80:
                errors.append(dict(e, batch=i // BATCH + 1))
    total["batches"] = batches
    return {"totals": total, "errors": errors}


# ================================================================ 来源数据
def _txt(v: Any, n: int = 0) -> str:
    s = "" if v is None else str(v).strip()
    if "*" in s:                      # 脱敏值(**朋 / 191****6080)一律当没有
        return ""
    return s[:n] if n else s


def _pick(*vals) -> str:
    for v in vals:
        s = _txt(v)
        if s:
            return s
    return ""


def _dt_of(*vals) -> str:
    """毫秒时间戳 / 日期串 → 'YYYY-MM-DD HH:MM:SS'(线索时间要精确到分钟)"""
    for v in vals:
        if v in (None, ""):
            continue
        s = str(v).strip()
        if s.isdigit() and len(s) >= 12:
            try:
                return datetime.fromtimestamp(int(s) / 1000).strftime("%Y-%m-%d %H:%M:%S")
            except Exception:
                continue
        m = re.match(r"^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}))?)?", s)
        if m:
            return "%04d-%02d-%02d %02d:%02d:%02d" % (
                int(m.group(1)), int(m.group(2)), int(m.group(3)),
                int(m.group(4) or 0), int(m.group(5) or 0), int(m.group(6) or 0))
    return ""


def _ms_date(*vals) -> str:
    """毫秒时间戳 / 日期串 → YYYY-MM-DD(奥丁的时间字段都是字符串毫秒)"""
    for v in vals:
        if v in (None, ""):
            continue
        s = str(v).strip()
        if s.isdigit() and len(s) >= 12:
            try:
                return datetime.fromtimestamp(int(s) / 1000).strftime("%Y-%m-%d")
            except Exception:
                continue
        m = re.match(r"^(\d{4})[-/](\d{1,2})[-/](\d{1,2})", s)
        if m:
            return "%04d-%02d-%02d" % (int(m.group(1)), int(m.group(2)), int(m.group(3)))
    return ""


def _short_vehicle(r: Dict[str, Any]) -> str:
    """奥丁 productName 是 "iCAR/V23/2025款/.../5座",成交表只放车系"""
    t = _txt(r.get("vehicleTypeName"), 64)
    if t:
        return t
    p = _txt(r.get("productName"))
    parts = [x for x in p.split("/") if x.strip()]
    return (parts[1] if len(parts) > 1 else p)[:64]


def _months_list(n: int) -> List[str]:
    n = max(1, min(24, int(n or 3)))
    y, m = datetime.now().year, datetime.now().month
    out = []
    for _ in range(n):
        out.append("%04d-%02d" % (y, m))
        m -= 1
        if m == 0:
            y, m = y - 1, 12
    return list(reversed(out))


def _interfaces(store: Dict[str, Any]) -> Tuple[Optional[dict], Optional[dict]]:
    lead = stock = None
    for i in (store.get("interfaces") or []):
        if i.get("kind") == "线索" and lead is None:
            lead = i
        if i.get("kind") == "库存" and stock is None:
            stock = i
    return lead, stock


def _store_names(conn) -> Dict[str, str]:
    out = {}
    try:
        for r in conn.execute("SELECT id, name FROM stores").fetchall():
            out[str(r["id"])] = (r["name"] or "").strip()
    except Exception:
        pass
    return out


def build_store_map(cfg: Dict[str, Any], meta: Dict[str, Any],
                    names: Dict[str, str]) -> Tuple[Dict[str, int], List[dict]]:
    """本系统门店 → 客流门店。

    只认**名称完全一致**(去空格、全角归一后)。像"旅胜-捷途"对应"长沙捷途"这种
    必须人工确认 —— 猜错店等于把客户记到别人账上。已确认过的映射写在 cfg["stores"]。
    """
    manual = {str(k): int(v) for k, v in (cfg.get("stores") or {}).items() if str(v).isdigit()}
    by_name = {}
    for s in (meta.get("stores") or []):
        by_name[_norm_name(s.get("name"))] = int(s["id"])
    # 人工确认过的映射优先(含本系统门店表里没有的 id,如测试库)
    mapping: Dict[str, int] = dict(manual)
    unmatched: List[dict] = []
    for sid, name in names.items():
        if sid in mapping:
            continue
        tid = by_name.get(_norm_name(name))
        if tid:
            mapping[sid] = tid
        else:
            unmatched.append({"store_id": sid, "name": name})
    return mapping, unmatched


def _norm_name(s: Any) -> str:
    x = str(s or "").strip().lower()
    for a, b in (("(", "("), (")", ")"), ("-", "-"), ("—", "-"), ("–", "-"), (" ", "")):
        x = x.replace(a, b)
    return x


def norm_scrm_row(r: dict, sid: str, mapping: Dict[str, int]) -> Optional[dict]:
    """一条 SCRM 线索 → 客流系统的客户档案条目。

    拿不到 11 位真号(脱敏 / 空号)一律返回 None —— 没有号码既不能建档也不能匹配。
    这里的字段是「客流系统主动来拉」时的契约,改字段要考虑对端兼容。
    """
    raw_phone = str(r.get("mobilePhone") or r.get("customerPhone") or
                    r.get("phone") or "").strip()
    if "*" in raw_phone:
        return None
    phone = re.sub(r"\D", "", raw_phone)[-11:]
    if not MOBILE_RE.match(phone):
        return None
    name = _txt(r.get("name") or r.get("customerName"), 64)
    if name in EMPTY_NAMES:
        name = ""
    channel = _txt(r.get("firstCustomerChannelName"), 24)
    level = _txt(r.get("clueLevelDesc"), 20)
    status = _txt(r.get("clueStatusName"), 20)
    # 线索归属人:奇瑞读 ownerName、亿客读 sales/firstTouchSales。
    # 两类字段不重叠,用「或」一次覆盖两套口径。
    owner = _txt(r.get("ownerName") or r.get("sales") or r.get("firstTouchSales"), 64)
    tags = [t for t in (level, status, channel) if t]
    _at = _dt_of(r.get("createTime"))
    _ext = _txt(r.get("id"), 32)
    item = {"phone": phone, "name": name, "src": "SCRM",
            "store_id": sid, "traffic_store_id": mapping.get(sid),
            "tags": tags, "remark": "SCRM线索#" + _ext,
            # 线索归属:查重时按品牌/门店做权限隔离靠这三个字段
            "lead_source": "SCRM", "lead_at": _at or "", "ext_id": _ext,
            # 线索归属人(奇瑞 ownerName / 亿客 sales → 归一化成 owner_name)
            "owner_name": owner or None,
            # 每条 SCRM 记录单独留痕:合并进同一档案后仍能追溯
            "refs": [{"s": "SCRM", "id": _ext, "at": _at,
                      "st": mapping.get(sid)}],
            # 厂家客户数据要单独展示的字段(客户名字 / 号码 / 日期 / 来源渠道)
            "channel": channel, "clue_level": level, "clue_status": status,
            "lead_on": (_at or "")[:10]}
    if mapping.get(sid):
        item["lead_store_id"] = mapping[sid]
    prov = _txt(r.get("province"), 32)
    city = _txt(r.get("city"), 32)
    if prov:
        item["region_province"] = prov
    if city:
        item["region_city"] = city
    return item


def collect_scrm(stores: List[dict], months: List[str], mapping: Dict[str, int],
                 log=print, plain_phone: bool = True) -> Tuple[List[dict], Dict[str, Any]]:
    """SCRM 客户档案 → 客户档案区。只有拿到 11 位真号的才入列。

    plain_phone=True 时,对列表返回脱敏号的账号逐条调「查看明文」换真号
    (iCAR 两家的列表接口永远不会给全号,只能这么拿)。
    """
    items: List[dict] = []
    stat = {"stores": 0, "rows": 0, "customers": 0, "masked": 0, "no_phone": 0,
            "plain_ok": 0, "error": 0, "errors": []}
    for s in stores:
        sid = str(s.get("store_id") or "")
        lead, _ = _interfaces(s)
        if not lead:
            continue
        stat["stores"] += 1
        # 只把「明文补全 / 窗口未取全 / 告警」这三类透出来:其余分月流水太啰嗦,
        # 但明文补全要跑好几分钟,全程静默会让人以为卡死了。
        def _plog(m, _sid=sid):
            t = str(m).strip()
            if "明文" in t or "⚠️" in t or "未取全" in t:
                log("[SCRM %s] %s" % (_sid, t))
        try:
            rows = fp.pull_leads(lead, fp.cred_of(lead), months, log=_plog,
                                 plain_phone=plain_phone)
        except Exception as e:                       # noqa: BLE001
            stat["error"] += 1
            stat["errors"].append({"store": sid, "where": "SCRM 拉取",
                                   "error": "%s: %s" % (type(e).__name__, str(e)[:90])})
            log("[SCRM] %s 拉取失败:%s" % (sid, str(e)[:80]))
            continue
        stat["rows"] += len(rows)
        _plain = sum(1 for r in rows if r.get("_plain"))
        stat["plain_ok"] += _plain
        for r in rows:
            raw_phone = str(r.get("mobilePhone") or r.get("customerPhone") or
                            r.get("phone") or "").strip()
            if "*" in raw_phone:
                stat["masked"] += 1
                continue
            item = norm_scrm_row(r, sid, mapping)
            if item is None:
                stat["no_phone"] += 1
                continue
            items.append(item)
        log("[SCRM] %s %d 条%s" % (sid, len(rows),
                                    "(明文补全 %d)" % _plain if _plain else ""))
    stat["customers"] = len(items)
    return items, stat


def collect_scrm_window(stores: List[dict], d1: str, d2: str,
                        mapping: Dict[str, int], log=print,
                        plain_phone: bool = True) -> Tuple[List[dict], Dict[str, Any]]:
    """按**任意日期窗口**拉厂家客户档案(客流系统主动来拉时用这条路)。

    和 collect_scrm 的区别:那个按月枚举、适合整批对账;这个只取一段窗口,
    增量拉取时不会为了 7 天的数据把整月几万条都翻一遍。
    """
    items: List[dict] = []
    stat = {"stores": 0, "rows": 0, "customers": 0, "masked": 0, "no_phone": 0,
            "plain_ok": 0, "error": 0, "errors": []}
    for s in stores:
        sid = str(s.get("store_id") or "")
        lead, _ = _interfaces(s)
        if not lead:
            continue
        stat["stores"] += 1
        try:
            rows = fp.pull_leads_range(lead, fp.cred_of(lead), d1, d2,
                                       log=None, plain_phone=plain_phone)
        except Exception as e:                       # noqa: BLE001
            stat["error"] += 1
            stat["errors"].append({"store": sid, "where": "SCRM 拉取",
                                   "error": "%s: %s" % (type(e).__name__, str(e)[:90])})
            continue
        stat["rows"] += len(rows)
        stat["plain_ok"] += sum(1 for r in rows if r.get("_plain"))
        for r in rows:
            raw_phone = str(r.get("mobilePhone") or r.get("customerPhone") or
                            r.get("phone") or "").strip()
            if "*" in raw_phone:
                stat["masked"] += 1
                continue
            item = norm_scrm_row(r, sid, mapping)
            if item is None:
                stat["no_phone"] += 1
                continue
            items.append(item)
    stat["customers"] = len(items)
    return items, stat


def collect_odin(stores: List[dict], months: List[str], mapping: Dict[str, int],
                 log=print) -> Tuple[List[dict], List[dict], Dict[str, Any]]:
    """奥丁实销 → 成交记录区(顺带把可用的客户字段带出去,但多数是脱敏的)"""
    deals: List[dict] = []
    custs: List[dict] = []
    stat = {"stores": 0, "rows": 0, "deals": 0, "with_full_phone": 0,
            "masked": 0, "no_phone": 0, "error": 0, "errors": []}
    for s in stores:
        sid = str(s.get("store_id") or "")
        _, stock = _interfaces(s)
        if not stock:
            continue
        tstore = mapping.get(sid)
        if not tstore:
            continue
        stat["stores"] += 1
        try:
            rows = fp.pull_sales(stock, fp.cred_of(stock), months)
        except Exception as e:                       # noqa: BLE001
            stat["error"] += 1
            stat["errors"].append({"store": sid, "where": "奥丁实销",
                                   "error": "%s: %s" % (type(e).__name__, str(e)[:90])})
            log("[奥丁] %s 拉取失败:%s" % (sid, str(e)[:80]))
            continue
        stat["rows"] += len(rows)
        for r in rows:
            raw_phone = str(r.get("mobileNumber") or r.get("contactPhone") or "").strip()
            phone = re.sub(r"\D", "", raw_phone)[-11:]
            item = {
                "store_id": tstore,
                "vehicle": _short_vehicle(r),
                "deal_date": _ms_date(r.get("salesDate"), r.get("recordDate"),
                                      r.get("invoiceDate"), r.get("deliveryDate")),
                "status": "delivered",           # 实销 = 已交车
                "advisor_name": _txt(r.get("salesConsultantName") or r.get("createName"), 64),
                "vin": _txt(r.get("vin"), 32),
                "order_no": _txt(r.get("scrmOrderCode") or r.get("id"), 40),
                "src": "奥丁",
            }
            if MOBILE_RE.match(phone):
                item["phone"] = phone
                stat["with_full_phone"] += 1
                # 有全号才可能补一份客户档案(奥丁字段比 SCRM 全)
                nm = _txt(r.get("customerName") or r.get("contactName"), 64)
                if nm:
                    custs.append({"phone": phone, "name": nm, "src": "奥丁",
                                  "gender": _txt(r.get("sex"), 8),
                                  "region_province": _txt(r.get("provinceName"), 32),
                                  "region_city": _txt(r.get("cityName"), 32),
                                  "tags": [t for t in (_txt(r.get("infoChannel"), 20),
                                                       _txt(r.get("customerType"), 20)) if t],
                                  "lead_source": "奥丁", "lead_store_id": tstore,
                                  "lead_at": _dt_of(r.get("salesDate"), r.get("recordDate")) or "",
                                  "remark": "奥丁客户#" + _txt(r.get("customerCode") or r.get("id"), 40)})
            elif MASK_RE.match(raw_phone):
                item["phone_masked"] = raw_phone    # 交给客流系统内部做唯一命中匹配
                stat["masked"] += 1
            else:
                stat["no_phone"] += 1
                continue            # 连脱敏号都没有 → 挂不到任何客户,不推送
            if not item["deal_date"]:
                continue           # 没有成交日期无法入账(宁可少算,不错算)
            deals.append(item)
        log("[奥丁] %s %d 条实销" % (sid, len(rows)))
    stat["deals"] = len(deals)
    return custs, deals, stat


def collect_orders(stores: List[dict], mapping: Dict[str, int],
                   log=print) -> Tuple[List[dict], Dict[str, Any]]:
    """下单/下定 → 成交记录区(status='ordered',与奥丁的 delivered 区分)。

    亿客 5 家走「订单管理」接口(真订单:VIN/车型/日期/顾问/客户),
    奇瑞 6 家走线索状态「已下订(6)+已交车(9)」(无 VIN、无成交价,近似口径)。
    字段对齐客流 /deals 契约:phone / store_id / vehicle / deal_date /
    status / advisor_name / vin / order_no。
    """
    orders: List[dict] = []
    stat = {"stores": 0, "rows": 0, "orders": 0, "masked": 0, "no_phone": 0,
            "error": 0, "errors": []}
    for s in stores:
        sid = str(s.get("store_id") or "")
        lead, _ = _interfaces(s)
        if not lead:
            continue
        tstore = mapping.get(sid)
        if not tstore:
            continue
        fam = (lead.get("family") or "")
        stat["stores"] += 1
        try:
            if fam.startswith("jetour"):
                recs = fp.pull_yike_orders(lead, fp.cred_of(lead))
                is_yike = True
            elif fam.startswith("chery"):
                recs = fp.pull_chery_orders(lead, fp.cred_of(lead))
                is_yike = False
            else:
                continue
        except Exception as e:                       # noqa: BLE001
            stat["error"] += 1
            stat["errors"].append({"store": sid, "where": "订单/下定",
                                   "error": "%s: %s" % (type(e).__name__, str(e)[:90])})
            log("[订单] %s 拉取失败:%s" % (sid, str(e)[:80]))
            continue
        stat["rows"] += len(recs)
        for r in recs:
            if is_yike:
                # 亿客订单:跳过战败单(废单)
                if _txt(r.get("orderStatusDesc")) == "已战败":
                    continue
                raw_phone = _txt(r.get("customerPhone"))
                phone = re.sub(r"\D", "", raw_phone)[-11:]
                vin = _txt(r.get("vin"), 32)
                vehicle = _txt(r.get("realSeriesName")) or _txt(r.get("modelCode"))
                day = _txt(r.get("createTime"))[:10]
                advisor = _txt(r.get("saleName"), 64)
                order_no = _txt(r.get("orderCode"), 64)
            else:
                # 奇瑞线索:已下订(6)+已交车(9),无 VIN/成交价
                raw_phone = _txt(r.get("mobilePhone"))
                phone = re.sub(r"\D", "", raw_phone)[-11:]
                vin = ""
                vehicle = (_txt(r.get("productCategoryCode"))
                           or _txt(r.get("productName")))
                day = _txt(r.get("createTime"))[:10]
                advisor = _txt(r.get("ownerName"), 64)
                order_no = _txt(r.get("clueId")) or _txt(r.get("id"), 64)
            if not day:
                continue
            if not vehicle:
                continue          # 没车型挂不进成交记录,宁可少算
            item = {
                "store_id": tstore,
                "vehicle": vehicle,
                "deal_date": day,
                "status": "ordered",           # 下定
                "advisor_name": advisor,
                "vin": vin,
                "order_no": order_no,
                "src": "亿客订单" if is_yike else "奇瑞线索",
            }
            if MOBILE_RE.match(phone):
                item["phone"] = phone
            elif MASK_RE.match(raw_phone):
                item["phone_masked"] = raw_phone
                stat["masked"] += 1
            else:
                stat["no_phone"] += 1
                continue
            orders.append(item)
        log("[订单] %s %d 条" % (sid, len(recs)))
    stat["orders"] = len(orders)
    return orders, stat


def merge_customers(*groups: Iterable[dict]) -> List[dict]:
    """按手机号合并:后到的只补空字段,标签取并集,**来源明细全部保留**

    SCRM 里同一个号码可能有多条记录(不同月份、不同门店各建过一次线索)。
    合并成一条档案时可以共用主档,但来源明细必须一条不少地留下来 ——
    否则「这个客户最早来自哪家店、哪个月」就查不清了。
    """
    out: Dict[str, dict] = {}
    for g in groups:
        for it in g:
            p = it.get("phone")
            if not p:
                continue
            cur = out.get(p)
            if cur is None:
                out[p] = dict(it, tags=list(dict.fromkeys(it.get("tags") or [])),
                              refs=list(it.get("refs") or []))
                continue
            for k, v in it.items():
                if k in ("tags", "phone", "refs", "lead_at"):
                    continue
                if v and not cur.get(k):
                    cur[k] = v
            merged = list(dict.fromkeys((cur.get("tags") or []) + (it.get("tags") or [])))
            cur["tags"] = merged
            refs = cur.get("refs") or []
            for x in (it.get("refs") or []):
                if x not in refs:
                    refs.append(x)
            cur["refs"] = refs[-20:]
            a1, a2 = (cur.get("lead_at") or ""), (it.get("lead_at") or "")
            if a2 and (not a1 or a2 < a1):
                cur["lead_at"] = a2          # 取最早的那次,作为来源时间
    # 收尾:把内部字段去掉,标签转字符串
    for it in out.values():
        it.pop("store_id", None)
        it.pop("traffic_store_id", None)
        it.pop("src", None)
        it.pop("ext_id", None)
        if isinstance(it.get("tags"), list):
            it["tags"] = ",".join([t for t in it["tags"] if t])[:255]
    return list(out.values())


# ================================================================ 任务
_JOB: Dict[str, Any] = {"running": False, "phase": "", "started_at": "", "trigger": "",
                        "log": [], "result": None, "error": ""}
_LOCK = threading.Lock()


def job_state() -> Dict[str, Any]:
    with _LOCK:
        return dict(_JOB, log=list(_JOB.get("log") or [])[-40:])


def _log(msg: str) -> None:
    line = "%s %s" % (datetime.now().strftime("%H:%M:%S"), msg)
    with _LOCK:
        _JOB["log"].append(line)
        _JOB["log"] = _JOB["log"][-200:]
    print("[traffic-sync]", msg, flush=True)


def run_once(conn, dry_run: bool = True, months: Optional[int] = None,
             store_ids: Optional[List[str]] = None,
             allow_masked: Optional[bool] = None) -> Dict[str, Any]:
    """同步一次。conn 由调用方给(后台线程里必须新开连接)。

    dry_run=True 只做统计与校验:客户/成交都走服务端的 dry_run,不落任何库。
    """
    t0 = time.time()
    cfg = load_cfg(conn)
    months_n = int(months or cfg["months"])
    mlist = _months_list(months_n)
    _log("开始%s:窗口 %s ~ %s" % ("演练" if dry_run else "正式下发", mlist[0], mlist[-1]))

    meta = traffic_meta(cfg)
    _log("客流系统可写,门店 %d 家" % len(meta.get("stores") or []))
    names = _store_names(conn)
    mapping, unmatched = build_store_map(cfg, meta, names)
    _log("门店映射:已对上 %d 家,待确认 %d 家" % (len(mapping), len(unmatched)))

    fcfg, _ = fp.load_cfg()
    stores = [s for b in (fcfg.get("brands") or []) for s in (b.get("stores") or [])
              if s.get("store_id")]
    if store_ids:
        keep = {str(x) for x in store_ids}
        stores = [s for s in stores if str(s.get("store_id")) in keep]
    unmapped = [str(s.get("store_id")) for s in stores
                if str(s.get("store_id")) not in mapping]
    if unmapped:
        stores = [s for s in stores if str(s.get("store_id")) in mapping]
        _log("跳过未映射门店 %d 家:%s" % (len(unmapped), ",".join(unmapped[:6])))

    report: Dict[str, Any] = {
        "ok": True, "dry_run": dry_run,
        "started_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "months": mlist, "mapping": mapping, "unmatched": unmatched,
        "scope_stores": [str(s.get("store_id")) for s in stores],
    }

    scrm_cust: List[dict] = []
    odin_cust: List[dict] = []
    deals: List[dict] = []
    s_stat: Dict[str, Any] = {}
    o_stat: Dict[str, Any] = {}

    if cfg["sources"].get("scrm", True):
        _log("拉取 SCRM 客户档案…")
        scrm_cust, s_stat = collect_scrm(stores, mlist, mapping, log=_log,
                                         plain_phone=cfg.get("plain_phone", True))
    if cfg["sources"].get("odin", True):
        _log("拉取奥丁实销…")
        odin_cust, deals, o_stat = collect_odin(stores, mlist, mapping, log=_log)

    # 下单/下定:亿客订单接口 + 奇瑞线索状态,status='ordered',与成交分开落
    order_items: List[dict] = []
    ord_stat: Dict[str, Any] = {}
    if cfg["sources"].get("orders", True):
        _log("拉取订单/下定…")
        order_items, ord_stat = collect_orders(stores, mapping, log=_log)

    customers = merge_customers(scrm_cust, odin_cust)
    report["sources"] = {"scrm": s_stat, "odin": o_stat, "orders": ord_stat}
    report["plan"] = {
        "customers": len(customers),
        "deals": len(deals),
        "orders": len(order_items),
        "customer_src": {"SCRM": len(scrm_cust), "奥丁": len(odin_cust),
                         "合并后": len(customers)},
    }
    _log("计划:客户档案 %d 条、成交 %d 条、下定 %d 条"
         % (len(customers), len(deals), len(order_items)))

    use_masked = cfg["allow_masked_match"] if allow_masked is None else bool(allow_masked)
    push: Dict[str, Any] = {}
    if customers:
        _log("推送客户档案(%s)…" % ("演练" if dry_run else "写入"))
        push["customers"] = _push_batched(cfg, "/customers", customers, dry_run,
                                           extra={"create_missing": cfg["create_missing"]})
    # 成交 + 下定合并推送 /deals:status 已区分 delivered / ordered
    all_deals = list(deals) + list(order_items)
    if all_deals:
        _log("推送成交/下定记录(%s)…" % ("演练" if dry_run else "写入"))
        push["deals"] = _push_batched(cfg, "/deals", all_deals, dry_run,
                                      extra={"allow_masked_match": use_masked})
    report["push"] = push
    report["allow_masked_match"] = use_masked
    report["elapsed"] = round(time.time() - t0, 1)

    # 结果台账:只留摘要,避免把上万条明细塞进配置。
    # 演练与正式分开记:演练若覆盖 last_run,面板会把"演练的 0"当成真实同步结果。
    report["summary"] = {
        "customers": (push.get("customers") or {}).get("totals"),
        "deals": (push.get("deals") or {}).get("totals"),
    }
    entry = {k: report[k] for k in
             ("ok", "dry_run", "started_at", "months", "plan",
              "summary", "elapsed", "allow_masked_match")}
    entry["unmatched"] = unmatched
    entry["sources"] = {"scrm": {k: v for k, v in (s_stat or {}).items()
                                 if k != "errors"},
                        "odin": {k: v for k, v in (o_stat or {}).items()
                                 if k != "errors"}}
    if dry_run:
        cfg["last_dry"] = entry
    else:
        cfg["last_run"] = entry
    # 最近 6 次记录:批量首发与后续增量都能回溯,不在面板上只剩最后一次
    hist = list(cfg.get("history") or [])
    hist.insert(0, {k: entry[k] for k in ("started_at", "dry_run", "plan", "summary", "elapsed")})
    cfg["history"] = hist[:6]
    try:
        save_cfg(conn, cfg)
    except Exception as e:                 # 台账写不进去不能把同步结果弄丢
        _log("结果台账写入失败(不影响本次结果):%s" % str(e)[:80])
    _log("完成,用时 %.1fs" % report["elapsed"])
    return report


def start_background(conn_factory, dry_run: bool = True, months: Optional[int] = None,
                     store_ids: Optional[List[str]] = None,
                     allow_masked: Optional[bool] = None,
                     trigger: str = "manual") -> Dict[str, Any]:
    """后台跑(HTTP 网关对单请求有 20 秒上限,拉数要几分钟,必须异步)"""
    with _LOCK:
        if _JOB["running"]:
            return {"ok": False, "busy": True, "message": "已有同步任务在跑,请等它结束"}
        _JOB.update(running=True, phase="prepare", error="", result=None,
                    started_at=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    trigger=trigger, log=[])

    def _run():
        conn = None
        try:
            conn = conn_factory()
            rep = run_once(conn, dry_run=dry_run, months=months,
                           store_ids=store_ids, allow_masked=allow_masked)
            with _LOCK:
                _JOB["result"] = rep
        except Exception as e:                        # noqa: BLE001
            _log("失败:%s: %s" % (type(e).__name__, str(e)[:160]))
            with _LOCK:
                _JOB["error"] = "%s: %s" % (type(e).__name__, str(e)[:200])
                _JOB["result"] = {"ok": False, "error": _JOB["error"],
                                  "dry_run": dry_run}
        finally:
            try:
                if conn is not None:
                    conn.close()
            except Exception:
                pass
            with _LOCK:
                _JOB["running"] = False

    threading.Thread(target=_run, daemon=True).start()
    return {"ok": True, "started": True, "mode": "dry_run" if dry_run else "apply"}