代码管理

stock_engine.py

← 返回编辑
"""库存口径引擎(金山 / 钉钉库存表 → 车型层级明细)。

## 为什么单独一个模块
现有 `vehicle_ledger` 是**钉钉进销存**专用:它靠「车辆状态(信息员手动更新)」
这个文本列判断在库/已售。而门店自己维护的**金山库存表**长这样:

    序号 | 销售车型名称 | 配置 | 市场价 | 颜色 | 内饰 | 物料描述 | VIN |
    定购日期 | 入库日期 | 库龄 | 车辆摆放地 | 备注 | 资金类型 | 返利 | ... | 是否在库

没有「车辆状态」,但有「是否在库」「库龄」「入库日期」。两张表的列名、在库判据、
库龄来源都不一样,硬套台账引擎只会得到 0 台。所以这里做一套**配置驱动**的解析:
列名写在配置里(默认按别名自动识别),换一张表只改配置、不改代码。

## 两个必须处理的坑
1) **合并单元格**:金山导出的「销售车型名称 / 配置」只在第一行有值,后续行是空串。
   不向下填充,按车型汇总就只剩 1 台;填充过头又会把「真的没填」的行归错。
   这里的做法:只对显式配置的 `fill_down` 列向下填充,且遇到 VIN 为空的行不传播。
2) **库龄的两个来源**:「库龄」列是导出当时的快照天数,会随时间过期;
   「入库日期」是绝对时间,永远正确。默认优先用**入库日期算库龄**,
   只有在没有入库日期 / 解析失败时才退回落库龄列 —— 这样即使表是上周导出的,
   今天看到的库龄也不会少算一周。
"""
from __future__ import annotations

import re
from datetime import date, datetime, timedelta
from typing import Any, Dict, Iterable, List, Optional, Tuple

# ---------- 字段别名(第一个命中的列名生效) ----------
FIELD_ALIASES: Dict[str, Tuple[str, ...]] = {
    # 顺序有讲究:「车型」必须排在「车型名称」前面 ——
    # 蓝胜库存表里「车型」是商品车名(瑞虎9X),「车型名称」是物料描述长串,
    # 反过来的话车型会被拆成几十个只占 1 台的碎片。
    "model": ("销售车型名称", "车型", "车型名称", "车系"),
    "spec": ("配置", "型号", "型号名称", "版本"),
    "color": ("颜色", "车身颜色", "外观颜色", "外饰颜色", "外观色"),
    "inner": ("内饰", "内饰颜色", "内饰色", "内色"),
    "location": ("车辆摆放地", "存放地点(信息员手动更新)", "存放地点",
                 "存放位置", "库位"),
    "vin": ("VIN", "车架号", "vin"),
    "in_date": ("入库日期", "入公司库时间(信息员手动更新)", "车辆到店日期",
                "到店日期", "入库时间", "到店时间"),
    "age": ("库龄", "库龄(天)", "库龄天数", "库存天数"),
    "in_stock": ("是否在库", "在库状态", "车辆状态(信息员手动更新)"),
    "price": ("市场价", "指导价", "厂家指导价", "参考市场价"),
}

FIELD_LABELS = {
    "model": "车型", "spec": "配置", "color": "外观颜色", "inner": "内饰颜色",
    "location": "存放地点", "vin": "车架号", "in_date": "入库日期",
    "age": "库龄", "in_stock": "在库状态", "price": "市场价",
}

# 默认向下填充的列:金山导出把同一车型/配置的相邻行合并了
DEFAULT_FILL_DOWN = ("model", "spec", "color", "inner")

# 「是否在库」列的视为在库取值(不同门店写法不一)
IN_STOCK_TRUE = {"是", "在库", "Y", "y", "yes", "1", "TRUE", "true",
                 "经销商仓库", "经销商在途", "在店", "展厅", "在库车辆"}

# 长库龄分档(需求:3 个月 / 6 个月 / 10 个月 / 1 年以上)
AGE_BUCKETS = [
    {"key": "d90", "label": "3 个月以上", "min": 90, "max": None},
    {"key": "d180", "label": "6 个月以上", "min": 180, "max": None},
    {"key": "d300", "label": "10 个月以上", "min": 300, "max": None},
    {"key": "d365", "label": "1 年以上", "min": 365, "max": None},
]
AGE_BUCKET_KEYS = tuple(b["key"] for b in AGE_BUCKETS)


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


def _clean(v: Any) -> str:
    """压平单元格里的换行与多余空格。

    金山导出会把一格里的两行文本原样带出来(实测「销售车型名称」里出现过
    `艾瑞泽8\\n征服版`),不清洗会让同一个车型被拆成两个名字,
    看板上的车型饼图就多出一个只占 1 台的分支。
    """
    s = _norm(v).replace("\r", "\n").replace("\u3000", " ")
    return re.sub(r"[ \t]+", " ", s.replace("\n", " ")).strip()


def _model_name(v: Any) -> str:
    """车型名:一格多行时取第一行(车型在前、配置在后)。"""
    s = _norm(v).replace("\r", "\n")
    first = s.split("\n")[0]
    return _clean(first)


def to_date(v: Any) -> Optional[date]:
    """把单元格转成日期。

    金山 / 钉钉导出的日期几乎都是 **Excel 序列号**(46251 = 2026-08-11),
    也有少量是 2026-08-11 / 2026/8/11 / 2026年8月11日 这几种文本。
    认不出来一律返回 None —— 宁可不显示库龄,也不要编一个日期。
    """
    s = _norm(v)
    if not s:
        return None
    # 文本日期
    m = re.match(r"^(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})", s)
    if m:
        try:
            return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
        except ValueError:
            return None
    # 纯数字:Excel 序列号(1900 历法,1899-12-30 起算)
    if re.match(r"^\d+(\.\d+)?$", s):
        try:
            n = float(s)
        except ValueError:
            return None
        if 20000 <= n <= 80000:            # 1954 ~ 2119,合理区间
            return date(1899, 12, 30) + timedelta(days=int(n))
        if n > 1e12:                        # 毫秒时间戳
            return datetime.fromtimestamp(n / 1000).date()
        if n > 1e9:                         # 秒时间戳
            return datetime.fromtimestamp(n).date()
    return None


def pick_cols(cols: List[Any], fields: Optional[Dict[str, str]] = None) -> Dict[str, Optional[int]]:
    """按配置 → 别名 的顺序,把逻辑字段映射到列下标。"""
    fields = fields or {}
    exact = {_norm(c): i for i, c in enumerate(cols)}
    out: Dict[str, Optional[int]] = {}
    for key, aliases in FIELD_ALIASES.items():
        want = _norm(fields.get(key))
        if want and want in exact:
            out[key] = exact[want]
            continue
        if want:                            # 配置了但表里没有 → 退回别名,不硬用错列
            pass
        hit = None
        for a in aliases:
            if a in exact:
                hit = exact[a]
                break
        if hit is None:
            for a in aliases:               # 再退一步:包含匹配("库龄(天)")
                for i, c in enumerate(cols):
                    if a in _norm(c):
                        hit = i
                        break
                if hit is not None:
                    break
        out[key] = hit
    return out


def detect_fields(cols: List[Any]) -> Dict[str, str]:
    """给设置页用的自动识别结果:{逻辑字段: 列名}。"""
    idx = pick_cols(cols)
    return {k: (_norm(cols[i]) if i is not None and i < len(cols) else "")
            for k, i in idx.items()}


def parse_items(cols: List[Any], rows: List[List],
                rule: Optional[Dict[str, Any]] = None,
                today: Optional[date] = None) -> List[Dict[str, Any]]:
    """把一张库存表解析成逐台明细。

    返回每条:vin / model / spec / color / inner / location /
              in_date / age_days / month / price / in_stock
    """
    rule = rule or {}
    today = today or date.today()
    idx = pick_cols(cols, rule.get("fields") or {})
    fill_keys = [k for k in (rule.get("fill_down") or DEFAULT_FILL_DOWN)
                 if idx.get(k) is not None]
    # 在库判据:三条规则,顺序不能乱
    #   1) 用户显式配了取值 → 只用他配的(门店写法千奇百怪,尊重人工)
    #   2) 没配 + 该列**有值** → 按内置白名单(经销商仓库/在途/是/在库…)过滤
    #      ← 钉钉进销存台账靠这条,否则已售车会被当成在库,库存直接翻倍
    #   3) 没配 + 该列**整列为空** → 不过滤(金山库存表就是这样,它本身就是在库清单)
    _i_st = idx.get("in_stock")
    _has_state = False
    _state_hit = False
    if _i_st is not None:
        for _r in rows[:300]:
            if _i_st < len(_r):
                _v = _norm(_r[_i_st])
                if _v:
                    _has_state = True
                    if _v in IN_STOCK_TRUE:
                        _state_hit = True
                        break
    stock_vals = rule.get("in_stock_values")
    if stock_vals:
        stock_vals = {_norm(v) for v in stock_vals}
        stock_vals |= {v.lower() for v in stock_vals}
    elif _state_hit:
        # 列里有值**且确实出现**在库状态词 → 这是真正的状态列(钉钉台账)
        stock_vals = set(IN_STOCK_TRUE) | {v.lower() for v in IN_STOCK_TRUE}
    else:
        # 列有值但一个状态词都不命中(如蓝胜库存表的「车辆状态」写的是存放地"恒广")
        # → 当成普通列,不做在库过滤;否则整张表会被筛成 0 台
        stock_vals = None

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

    carry: Dict[str, str] = {k: "" for k in fill_keys}
    out: List[Dict[str, Any]] = []
    for r in rows:
        vin = cell(r, "vin")
        # 空行 / 只有序号没有任何车辆信息的占位行 → 跳过(也不参与向下填充)
        if not vin and not cell(r, "model") and not cell(r, "spec") \
                and not cell(r, "in_date"):
            continue
        # 🔑 模板占位行:车型列写着「车型」(表头漏进数据里)→ 不算库存
        #    (用户 2026-11-09:「库存表里的:车型=车型,不计算为库存数据」)
        #    放在 fill_down 之前,避免它把上面的值往下带。
        if (cell(r, "model") or "").strip() == "车型":
            continue
        for k in fill_keys:
            v = cell(r, k)
            if v:
                carry[k] = v
            elif vin:                       # 有车架号才算"沿用上一行",空行不传播
                pass
        vals = {k: (cell(r, k) or (carry.get(k, "") if k in carry else ""))
                for k in FIELD_ALIASES}
        vals["model"] = _model_name(vals["model"])
        for k in ("spec", "color", "inner", "location"):
            vals[k] = _clean(vals[k])
        # 在库判定
        if stock_vals is not None and idx.get("in_stock") is not None:
            if vals["in_stock"] not in stock_vals:
                continue
        in_date = to_date(cell(r, "in_date"))
        age_days = None
        if in_date:
            age_days = max(0, (today - in_date).days)
        else:
            raw_age = cell(r, "age")
            if raw_age:
                try:
                    age_days = max(0, int(float(raw_age)))
                except ValueError:
                    age_days = None
        price = cell(r, "price")
        try:
            price_num = float(price.replace(",", "")) if price else None
        except ValueError:
            price_num = None
        out.append({
            "vin": vin,
            "model": vals["model"] or "(未填车型)",
            "spec": vals["spec"],
            "color": vals["color"],
            "inner": vals["inner"],
            "location": vals["location"],
            "in_date": in_date.strftime("%Y-%m-%d") if in_date else "",
            "age_days": age_days,
            "month": in_date.strftime("%Y-%m") if in_date else "",
            "price": price_num,
            "in_stock": vals["in_stock"],
            "state": vals["in_stock"],
        })
    return out


def age_of(item: Dict[str, Any]) -> Optional[int]:
    return item.get("age_days")


def filter_items(items: Iterable[Dict[str, Any]],
                 age_key: str = "", month: str = "",
                 model: str = "") -> List[Dict[str, Any]]:
    """按库龄档 / 入库月份 / 车型过滤(三个条件同时生效)。"""
    age_min = None
    for b in AGE_BUCKETS:
        if b["key"] == age_key:
            age_min = b["min"]
            break
    out = []
    for it in items:
        if model and it.get("model") != model:
            continue
        if month and it.get("month") != month:
            continue
        if age_min is not None:
            a = age_of(it)
            if a is None or a < age_min:
                continue
        out.append(it)
    return out


def summarize(items: List[Dict[str, Any]]) -> Dict[str, Any]:
    """车型层级汇总 + 库龄分档 + 入库月份分布。"""
    total = len(items)
    by_model: Dict[str, Dict[str, Any]] = {}
    months: Dict[str, int] = {}
    bucket_cnt = {b["key"]: 0 for b in AGE_BUCKETS}
    ages = []
    for it in items:
        m = it.get("model") or "(未填车型)"
        g = by_model.setdefault(m, {
            "model": m, "count": 0, "age_sum": 0, "age_n": 0,
            "aged": 0, "specs": {}, "locations": {}, "months": {},
        })
        g["count"] += 1
        a = age_of(it)
        if a is not None:
            g["age_sum"] += a
            g["age_n"] += 1
            ages.append(a)
            if a >= 90:
                g["aged"] += 1
            for b in AGE_BUCKETS:
                if a >= b["min"]:
                    bucket_cnt[b["key"]] += 1
        if it.get("spec"):
            g["specs"][it["spec"]] = g["specs"].get(it["spec"], 0) + 1
        if it.get("location"):
            g["locations"][it["location"]] = g["locations"].get(it["location"], 0) + 1
        if it.get("month"):
            g["months"][it["month"]] = g["months"].get(it["month"], 0) + 1
            months[it["month"]] = months.get(it["month"], 0) + 1
    models = []
    for g in by_model.values():
        models.append({
            "model": g["model"], "count": g["count"],
            "avg_age": round(g["age_sum"] / g["age_n"], 1) if g["age_n"] else None,
            "aged": g["aged"],
            "share": round(g["count"] * 100.0 / total, 1) if total else 0,
            "spec_count": len(g["specs"]),
            "specs": sorted(g["specs"].items(), key=lambda x: -x[1])[:40],
            "locations": sorted(g["locations"].items(), key=lambda x: -x[1])[:20],
            "months": sorted(g["months"].items()),
        })
    models.sort(key=lambda x: (-x["count"], x["model"]))
    return {
        "total": total,
        "models": models,
        "months": sorted(months.items(), reverse=True),
        "age_buckets": [{"key": b["key"], "label": b["label"],
                         "min": b["min"], "count": bucket_cnt[b["key"]]}
                        for b in AGE_BUCKETS],
        "avg_age": round(sum(ages) / len(ages), 1) if ages else None,
        "aged_total": sum(1 for a in ages if a >= 90),
        "aged_180": sum(1 for a in ages if a >= 180),
    }


def age_bucket_label(days: Optional[int]) -> str:
    """单台车归属的库龄档(用于明细表打标签)。"""
    if days is None:
        return "—"
    if days >= 365:
        return "1 年以上"
    if days >= 300:
        return "10 个月以上"
    if days >= 180:
        return "6 个月以上"
    if days >= 90:
        return "3 个月以上"
    return "3 个月内"