代码管理

vehicle_ledger.py

← 返回编辑
"""车辆台账口径引擎(钉钉「进销存」表)。

## 为什么不能用通用指标识别
`column_matcher` 是按"数字列求和"设计的,但车辆台账的关键信息在
**文本列「车辆状态(信息员手动更新)」** 里 —— 每行一台车,状态决定它算
库存还是算销量。所以必须按状态分组计数,而不是对某列求和。

## 口径(实测校验过全量 265 台)
库存 = 车辆状态 ∈ {经销商仓库, 经销商在途}
销量 = 车辆状态 = 实销完成
(经销商调拨是内部调拨,不算零售成交,单列出来不计入销量)

## ⚠️ 视图名会骗人
iCAR 的「在库车辆」视图返回的状态**全是"实销完成"** —— 该视图根本没配筛选条件,
返回了全部记录。**绝不能按视图名判断口径,必须按字段值算。**

而且同一张表的多个视图返回的是**不同子集**(QQ 三视图并集 119 台,
两两交集小到 0),必须按车架号合并去重才能拿到全量。
"""
from typing import Any, Dict, List, Optional

ST_COL = "车辆状态(信息员手动更新)"
LOC_COL = "存放地点(信息员手动更新)"
MODEL_COL = "车型名称"
VIN_COL = "车架号"
SALES_COL = "销售顾问(开票通知单)"
DEAL_TIME_COL = "销售时间(开票通知单)"

# 🔑 时间列优先级:**成交时间必须用「销售时间(开票通知单)」**
# 实测(iCAR 139 台已售):
#   销售时间(开票通知单)138/139 有值← 唯一真正的成交时间
#   厂家扣款时间         139/139 有值  ← 财务流程时间,比销售晚,不可用于销量
#   传档时间(财务信息)  137/139
#   入公司库时间         113/139      ← 进库时间,不是销售时间
# find_time_column 通用识别会选中「厂家扣款时间」(非空率更高),
# 直接拿它当销量时间会让月度分布错位,所以这里显式指定优先级。
TIME_COL_PRIORITY = (
    DEAL_TIME_COL,           # 销售时间(开票通知单)← 成交口径
    "销售日期",
    "销售时间",
    "开票时间",
    "传档时间(财务信息)",
    "厂家扣款时间",
    "入公司库时间(信息员手动更新)",
)

# 状态分类
STOCK_STATES = {"经销商仓库", "经销商在途"}
SOLD_STATES = {"实销完成"}
TRANSFER_STATES = {"经销商调拨"}


def _norm(v: Any) -> str:
    return str(v or "").strip()


def excel_date(v: Any) -> str:
    """把「销售时间」转成日期字符串。

    ⚠️ 钉钉 aitable 的日期字段读出来是 **Excel 序列号**(如 46179.6316
    对应 2026-06-06 15:09),不是 ISO 字符串,也不是毫秒时间戳。
    1900 历法:1899-12-30 + n 天。
    """
    s = _norm(v)
    if not s:
        return ""
    # 已经是 ISO / 普通日期串
    if not s.replace(".", "", 1).isdigit():
        return s[:10]
    try:
        n = float(s)
    except ValueError:
        return s[:10]
    # 毫秒时间戳兜底(若某天改用13 位)
    if n > 1e11:
        from datetime import datetime as _dt, timezone as _tz
        return _dt.fromtimestamp(n / 1000, _tz.utc).strftime("%Y-%m-%d")
    if n < 1000:
        return s
    from datetime import datetime as _dt, timedelta as _td
    return (_dt(1899, 12, 30) + _td(days=n)).strftime("%Y-%m-%d")


def find_col(cols: List[Any], name: str) -> Optional[int]:
    """按列名精确匹配(去空白),找不到返回 None。"""
    idx = {str(c).strip(): i for i, c in enumerate(cols)}
    return idx.get(name)


def is_ledger(cols: List[Any]) -> bool:
    """判断是否车辆台账:有车架号 + 车辆状态。"""
    return find_col(cols, VIN_COL) is not None and find_col(cols, ST_COL) is not None


# 车型明细要用的列(不同门店台账列名略有差异,给几个别名兜底)
SPEC_COLS = ("型号", "车辆型号", "型号名称", "配置")
EXT_COLOR_COLS = ("外观颜色", "车身颜色", "外饰颜色", "外观色")
INT_COLOR_COLS = ("内饰颜色", "内饰色", "内色", "内饰")
LOC_ALIASES = ("存放地点(信息员手动更新)", "存放地点", "库位", "存放位置")
# 成交价列(不同门店台账叫法不同)。**找不到就留空,绝不拿毛利倒推一个价格出来**:
# 源表里没有的价格是"没采集到",编一个数比显示「—」危险得多。
PRICE_COLS = ("开票金额", "销售价格", "成交价", "销售价", "开票价",
              "含税金额", "车辆售价", "订单金额", "实际售价")


def _find_like(cols: List[Any], cands) -> Optional[int]:
    """先精确匹配,再退化到"包含"匹配(台账列名常带括号后缀)。"""
    for name in cands:
        i = find_col(cols, name)
        if i is not None:
            return i
    for name in cands:
        for i, c in enumerate(cols):
            if name in str(c or ""):
                return i
    return None


def stock_detail(cols: List[Any], rows: List[List],
                 model: Optional[str] = None) -> List[Dict[str, Any]]:
    """在库车辆的逐台明细:型号 / 外观颜色 / 内饰颜色 / 存放地点 / 车架号。

    model 传了就只看该车型(与饼图里的车型名一致,即「车型名称」列)。
    口径与 summarize 保持一致:只有 车辆状态 ∈ {经销商仓库, 经销商在途} 才算在库。
    """
    i_st = find_col(cols, ST_COL)
    if i_st is None:
        return []
    i_model = find_col(cols, MODEL_COL)
    i_spec = _find_like(cols, SPEC_COLS)
    i_ext = _find_like(cols, EXT_COLOR_COLS)
    i_int = _find_like(cols, INT_COLOR_COLS)
    i_loc = _find_like(cols, LOC_ALIASES)
    i_vin = find_col(cols, VIN_COL)

    def cell(r, i):
        return _norm(r[i]) if (i is not None and i < len(r)) else ""

    want = _norm(model)
    out: List[Dict[str, Any]] = []
    for r in rows:
        st = cell(r, i_st)
        if st not in STOCK_STATES:
            continue
        m = cell(r, i_model)
        if want and m != want:
            continue
        out.append({
            "vin": cell(r, i_vin),
            "model": m,
            "spec": cell(r, i_spec),
            "ext_color": cell(r, i_ext),
            "int_color": cell(r, i_int),
            "location": cell(r, i_loc),
            "state": st,
        })
    # 排序:按型号 → 外观色 → 内饰色 → 地点,同配置的车聚在一起好核对
    out.sort(key=lambda x: (x["spec"], x["ext_color"], x["int_color"], x["location"], x["vin"]))
    return out


def stock_spec_summary(cols: List[Any], rows: List[List],
                       model: Optional[str] = None) -> List[Dict[str, Any]]:
    """按「型号 + 外观色 + 内饰色 + 存放地点」聚合台数(明细表的汇总行)。"""
    detail = stock_detail(cols, rows, model)
    agg: Dict[tuple, int] = {}
    for x in detail:
        k = (x["spec"], x["ext_color"], x["int_color"], x["location"])
        agg[k] = agg.get(k, 0) + 1
    out = [{"spec": k[0], "ext_color": k[1], "int_color": k[2],
            "location": k[3], "count": v} for k, v in agg.items()]
    out.sort(key=lambda x: (-x["count"], x["spec"], x["ext_color"]))
    return out


def sold_detail(cols: List[Any], rows: List[List],
                start=None, end=None,
                sales_col_name: Optional[str] = None) -> List[Dict[str, Any]]:
    """已售车辆的逐台明细:销售时间 / 车型 / 型号 / 车架号 / 销售顾问 / 价格。

    ## 为什么单独做
    卡片上"本月销量 12 台"是**计数**,用户点开要看的是**哪 12 台、哪天卖的、多少钱**。
    明细必须和卡片同源:状态仍按 `车辆状态 = 实销完成`,时间仍按
    `pick_time_col`(销售时间(开票通知单)优先),否则会出现
    "卡片 12、明细 15 行"这类对不上账的情况。

    ⚠️ 价格列在部分门店台账里根本没有(PRICE_COLS 全不命中)→ price 返回 None,
       前端显示「—」。**不拿毛利或均值倒推价格**。
    ⚠️ 缺销售时间的已售车仍要出现在明细里(date 为空),派单/补录时要用到;
       只在统计「某时间窗」时才把无日期的行排除。
    """
    i_st = find_col(cols, ST_COL)
    if i_st is None:
        return []
    i_model = find_col(cols, MODEL_COL)
    i_spec = _find_like(cols, SPEC_COLS)
    i_ext = _find_like(cols, EXT_COLOR_COLS)
    i_int = _find_like(cols, INT_COLOR_COLS)
    i_loc = _find_like(cols, LOC_ALIASES)
    i_vin = find_col(cols, VIN_COL)
    i_sales = find_col(cols, sales_col_name or SALES_COL)
    i_price = _find_like(cols, PRICE_COLS)
    i_tm = pick_time_col(cols, rows)

    s, e = _dt(start), _dt(end)

    def cell(r, i):
        return _norm(r[i]) if (i is not None and i < len(r)) else ""

    out: List[Dict[str, Any]] = []
    for r in rows:
        st = cell(r, i_st)
        if st not in SOLD_STATES:
            continue
        t = _dt(r[i_tm]) if (i_tm is not None and i_tm < len(r)) else None
        if (s or e) and t is not None:
            if s and t < s:
                continue
            if e and t > e:
                continue
        price = None
        raw_price = cell(r, i_price)
        if raw_price:
            from field_engine import to_number as _tn
            price = _tn(raw_price)
        out.append({
            "vin": cell(r, i_vin),
            "model": cell(r, i_model),
            "spec": cell(r, i_spec),
            "ext_color": cell(r, i_ext),
            "int_color": cell(r, i_int),
            "location": cell(r, i_loc),
            "sales": cell(r, i_sales),
            "date": t.strftime("%Y-%m-%d") if t else "",
            "price": price,
            "state": st,
            "has_price_col": i_price is not None,
        })
    # 最近成交排前面;没有日期的排最后(它们需要人工补录,放最显眼反而挡住正常数据)
    out.sort(key=lambda x: (x["date"] or "0000-00-00"), reverse=True)
    return out


def summarize(cols: List[Any], rows: List[List]) -> Dict[str, Any]:
    """整体口径汇总。

    返回 {total, stock, onway, sold, transfer, states, models, locations, period}
    """
    i_st = find_col(cols, ST_COL)
    i_loc = find_col(cols, LOC_COL)
    i_model = find_col(cols, MODEL_COL)
    i_deal = find_col(cols, DEAL_TIME_COL)

    out = {
        "total": len(rows),
        "stock": 0, "onway": 0, "sold": 0, "transfer": 0,
        "states": {}, "models": {}, "locations": {},
        "period": None,
    }
    if i_st is None:
        return out

    st_cnt: Dict[str, int] = {}
    md_cnt: Dict[str, int] = {}
    lc_cnt: Dict[str, int] = {}
    dates = []

    for r in rows:
        st = _norm(r[i_st]) if i_st < len(r) else ""
        st_cnt[st] = st_cnt.get(st, 0) + 1
        if st in STOCK_STATES:
            out["stock"] += 1
            if st == "经销商在途":
                out["onway"] += 1
            if i_model is not None and i_model < len(r):
                m = _norm(r[i_model])
                if m:
                    md_cnt[m] = md_cnt.get(m, 0) + 1
            if i_loc is not None and i_loc < len(r):
                lc = _norm(r[i_loc])
                if lc:
                    lc_cnt[lc] = lc_cnt.get(lc, 0) + 1
        elif st in SOLD_STATES:
            out["sold"] += 1
        elif st in TRANSFER_STATES:
            out["transfer"] += 1

        if i_deal is not None and i_deal < len(r):
            d = excel_date(r[i_deal]) if i_deal < len(r) else ""
            if d and len(d) >= 10:
                dates.append(d[:10])

    out["states"] = dict(sorted(st_cnt.items(), key=lambda kv: -kv[1]))
    out["models"] = dict(sorted(md_cnt.items(), key=lambda kv: -kv[1]))
    out["locations"] = dict(sorted(lc_cnt.items(), key=lambda kv: -kv[1]))
    if dates:
        out["period"] = f"{min(dates)} ~ {max(dates)}"
    # 在库里在途是子集,stock 字段已含它;另给"纯在库"
    out["instock_only"] = out["stock"] - out["onway"]
    return out


def pick_time_col(cols: List[Any], rows: Optional[List[List]] = None) -> Optional[int]:
    """挑「成交时间」列:按 TIME_COL_PRIORITY 顺序,取第一个存在且有值的。

    ⚠️ 不复用 field_engine.find_time_column —— 它按"非空率最高"选,
    在进销存里会选中「厂家扣款时间」(175/175),那是**财务流程时间**,
    比销售时间晚且不代表成交。用它算月度销量会让分布整体后移。
    """
    for name in TIME_COL_PRIORITY:
        i = find_col(cols, name)
        if i is None:
            continue
        if rows:
            non_empty = sum(1 for r in rows
                            if i < len(r) and str(r[i]).strip())
            if non_empty == 0:
                continue
        return i
    return None


def _dt(v):
    """把各种时间写法转 datetime;解析不了返回 None。"""
    from field_engine import parse_time
    t = parse_time(v)
    if t:
        return t
    s = _norm(v)
    if not s:
        return None
    from datetime import datetime as _dtm
    if s.replace(".", "", 1).isdigit():
        n = float(s)
        if 20000 < n < 60000:
            from datetime import timedelta as _td
            return _dtm(1899, 12, 30) + _td(days=n)
    return None


def sold_in_window(cols: List[Any], rows: List[List],
                   start=None, end=None) -> Dict[str, Any]:
    """统计「在指定时间窗内成交的车数」。

    ## 为什么单独做而不复用 summarize
    **库存和销量的时间语义完全不同**:
    - 库存是**时点值**:现在的在库车数,按销售时间筛毫无意义
    - 销量是**区间流量**:某段时间内成交了多少台,必须按销售时间筛

    ⚠️ 缺销售时间的已售车不计入(有明确计数,不静默丢)。
    """
    from datetime import datetime as _dtm, date as _date

    def _to_dt(v):
        if v is None or v == "":
            return None
        if isinstance(v, _dtm):
            return v
        if isinstance(v, _date):
            return _dtm(v.year, v.month, v.day)
        s = str(v).strip()
        if len(s) >= 10 and s[4] in "-/" and s[7] in "-/":
            try:
                return _dtm(int(s[0:4]), int(s[5:7]), int(s[8:10]))
            except ValueError:
                pass
        return _dt(v)

    i_st = find_col(cols, ST_COL)
    i_tm = pick_time_col(cols, rows)
    s, e = _to_dt(start), _to_dt(end)
    out = {"sold": 0, "sold_total": 0, "sold_no_time": 0,
           "time_column": cols[i_tm] if i_tm is not None else None,
           "from": None, "to": None, "applied": s is not None or e is not None,
           "reason": ""}
    if i_st is None:
        out["reason"] = f"找不到「{ST_COL}」列"
        return out
    if i_tm is None:
        out["reason"] = "找不到可用的时间列"
        return out

    months: Dict[str, int] = {}
    all_times = []
    for r in rows:
        st = _norm(r[i_st]) if i_st < len(r) else ""
        if st not in SOLD_STATES:
            continue
        out["sold_total"] += 1
        t = _dt(r[i_tm]) if i_tm < len(r) else None
        if t is None:
            out["sold_no_time"] += 1
            continue
        all_times.append(t)
        # ⚠️ 按**日期**比较,不能按 datetime 直接比:
        #    区间末端是「该月最后一天 00:00」(_month_bounds_of 给的),
        #    而销售时间常带时分(2026-06-30 15:30),直接比 `t > e` 会把
        #    月末当天的成交全丢掉 —— 实测 6 月少 6 台、8 月少 2 台,
        #    与走势图(months 全量分桶)对不上。
        td = t.date()
        if s and td < s.date():
            continue
        if e and td > e.date():
            continue
        out["sold"] += 1
        months[f"{t.year}-{t.month:02d}"] = months.get(
            f"{t.year}-{t.month:02d}", 0) + 1
    if all_times:
        out["from"] = min(all_times).strftime("%Y-%m-%d")
        out["to"] = max(all_times).strftime("%Y-%m-%d")
    out["months"] = dict(sorted(months.items()))
    if out["applied"] and out["sold"] == 0:
        out["reason"] = f"{out['time_column']} 在该区间内没有成交记录"
    return out


def by_sales(cols: List[Any], rows: List[List]) -> Dict[str, Dict[str, Any]]:
    """按销售顾问统计销量(已售的车有销售顾问与销售时间)。

    返回 {销售名: {sold, stock, models}}
    只有已售记录才带销售顾问(库存车没有归属销售)。
    """
    i_st = find_col(cols, ST_COL)
    i_sales = find_col(cols, SALES_COL)
    i_model = find_col(cols, MODEL_COL)
    if i_st is None or i_sales is None:
        return {}
    out: Dict[str, Dict[str, Any]] = {}
    for r in rows:
        st = _norm(r[i_st]) if i_st < len(r) else ""
        who = _norm(r[i_sales]) if i_sales < len(r) else ""
        if not who or who in ("--", "-", "null"):
            continue
        b = out.setdefault(who, {"sold": 0, "stock": 0, "models": {}})
        if st in SOLD_STATES:
            b["sold"] += 1
            if i_model is not None and i_model < len(r):
                m = _norm(r[i_model])
                if m:
                    b["models"][m] = b["models"].get(m, 0) + 1
        elif st in STOCK_STATES:
            b["stock"] += 1
    return out