planner.py 12.5 KB
"""补货算法(纯函数,无 IO)。口径来自 10-28 门店交流会需求(库存补货-需求标注版):

定时补货(出库驱动):
  候选 = 窗口(前一天 15:00 ~ 当天 15:00)内厂家分类为「纯牌」、净出库量 > 0 的零件
  分组 = 历史常备件 stock(在库分类表属常备分类,或近 N 个月 SO 单里补过)默认勾选;其余 other 默认不勾
  推荐期望 = 库存 + 净出库(「把用掉的补回来」)
  默认期望 = 有上次人工修改的值就用上次(标「上次」),否则用推荐(标「推荐」);人可以改
  补货数 = 期望 −(库存 + 在途),≤0 不订;在途按配置 in_transit_field 取(两个原始值都保存)
  关注仓(默认 GTMC广州 + 华南GTMC,给人看时叫「广州仓 / 华南仓」)查过且全部无货 → 厂家缺货,不订
  订购数按 DMS 起订量(minPurchaseQty)/ 包装数(packagesQty)向上取整——DMS 只收「≥ 起订量且是包装数整数倍」的数量,
  不取整的话取数端建单前校验会把整张单拒掉
  超出当日剩余可订(dailySurplusPurQty,DMS 为空表示不限)→ 按上限订(向下取到包装数整数倍),并标出来;
  可订 0 多半是库存已超 DMS 库存上限(dailyStorageLimit),和全国仓有没有货无关
单次补货:数量由人直接给,同样按起订量 / 包装数取整、受当日可订上限约束(超出按上限并说明)、关注仓全无货不订。
tag:normal / capped / oos / enough / in_transit_ok / unchecked / error
"""
from __future__ import annotations

import math
from dataclasses import asdict, dataclass, field

TAG_LABEL = {"normal": "", "capped": "今天到上限了", "oos": "厂家缺货", "enough": "库存够用",
             "in_transit_ok": "在途够了", "unchecked": "没勾选,这次不订", "error": "没查到"}
GROUP_LABEL = {"stock": "历史常备件", "other": "其他出库件", "single": "单次补货"}
SOURCE_LABEL = {"last": "上次", "recommend": "推荐", "manual": "已修改"}
# DMS 全国仓库名 → 给人看的叫法(配置 / 接口匹配仍用 DMS 原名)
WH_LABEL = {"GTMC广州": "广州仓", "华南GTMC": "华南仓"}


def wh_label(name: str) -> str:
    """「GTMC广州」→「广州仓」、「华南GTMC」→「华南仓」;表里没有的:含广州 / 华南的按同样叫法,其余原样。"""
    name = str(name or "")
    if name in WH_LABEL:
        return WH_LABEL[name]
    for key in ("广州", "华南"):
        if key in name:
            return key + "仓"
    return name


def wh_cn(wh: dict | None) -> dict:
    """{DMS 仓库名: 数量} → {广州仓: 数量, …}(保持顺序)。"""
    return {wh_label(k): v for k, v in (wh or {}).items()}


@dataclass
class Line:
    part_no: str
    name: str
    grp: str = "stock"
    category: str = ""
    so_hit: dict | None = None
    outbound_qty: float = 0
    outbound_rows: int = 0
    stock: float = 0
    trans_shipped: float = 0
    unreceived: float = 0
    in_transit: float = 0
    mad: float | None = None
    cap: int | None = None
    min_qty: int = 1                 # DMS 起订量
    pack_qty: int = 1                # DMS 包装数(订购数必须是它的整数倍)
    storage_limit: int | None = None  # DMS 库存上限(只用来解释可订为什么是 0)
    purchased_today: int | None = None  # DMS 今日已订
    unit_price: float = 0
    wh: dict = field(default_factory=dict)
    national_queried: bool = False
    checked: bool = True
    default_expected: int = 0
    default_source: str = "recommend"
    last_expected: int | None = None
    last_at: str | None = None
    last_by: str = ""
    expected: int = 0
    modified: bool = False
    suggested: int = 0
    final_qty: int = 0
    tag: str = "normal"
    note: str = ""
    error: str = ""
    seq: int | None = None          # 只给 suggested>0 且勾选的行编号

    @property
    def orderable(self) -> bool:
        return self.final_qty > 0 and self.tag in ("normal", "capped")

    @property
    def have(self) -> float:
        return (self.stock or 0) + (self.in_transit or 0)

    @property
    def recommend(self) -> int:
        """推荐期望 = 库存 + 净出库(把用掉的补回来)。"""
        return max(int(math.ceil((self.stock or 0) + max(self.outbound_qty or 0, 0))), 0)

    @property
    def wh_total(self) -> float:
        return sum(float(q or 0) for q in (self.wh or {}).values())

    @property
    def wh_short(self) -> bool:
        need = int(self.final_qty or self.suggested or 0)
        return bool(self.wh) and need > 0 and 0 < self.wh_total < need

    @property
    def source_label(self) -> str:
        return SOURCE_LABEL["manual"] if self.modified else SOURCE_LABEL.get(self.default_source, "")

    def to_dict(self) -> dict:
        d = asdict(self)
        d.update(label=TAG_LABEL.get(self.tag, ""), orderable=self.orderable, recommend=self.recommend,
                 amount=round(self.final_qty * (self.unit_price or 0), 2), wh_total=self.wh_total,
                 wh_short=self.wh_short, group_label=GROUP_LABEL.get(self.grp, self.grp),
                 source_label=self.source_label, wh_cn=wh_cn(self.wh))
        return d


def _f(v) -> float:
    try:
        return float(v or 0)
    except (TypeError, ValueError):
        return 0.0


def _i(v) -> int | None:
    try:
        return None if v is None or str(v).strip() == "" else int(float(v))
    except (TypeError, ValueError):
        return None


def pack_up(want: int, min_qty: int = 1, pack_qty: int = 1) -> int:
    """DMS 能收的最小订购数:≥ want、≥ 起订量、是包装数的整数倍。want <= 0 → 0。"""
    if want <= 0:
        return 0
    pk = max(int(pack_qty or 1), 1)
    return int(math.ceil(max(want, int(min_qty or 1)) / pk)) * pk


def pack_down(cap: int, min_qty: int = 1, pack_qty: int = 1) -> int:
    """上限 cap 以内 DMS 能收的最大订购数(包装数整数倍且 ≥ 起订量),凑不够一个起订量 → 0。"""
    pk = max(int(pack_qty or 1), 1)
    q = max(int(cap), 0) // pk * pk
    return q if q >= max(int(min_qty or 1), 1) else 0


IN_TRANSIT_LABEL = {"trans_shipped": "在途数量", "unreceived": "未收货", "max": "在途数量/未收货取大"}


def pick_in_transit(trans_shipped: float, unreceived: float, field: str) -> float:
    if field == "unreceived":
        return unreceived
    if field == "max":
        return max(trans_shipped, unreceived)
    return trans_shipped


def fill_facts(ln: Line, it: dict, in_transit_field: str = "trans_shipped") -> Line:
    """把取数端 quote 返回的一项(库存 / 在途 / 月均 / 可订 / 单价 / 关注仓)填进行里。"""
    ln.name = ln.name or it.get("name") or it.get("name_dms") or ""
    ln.stock, ln.trans_shipped, ln.unreceived = _f(it.get("stock")), _f(it.get("trans_shipped")), _f(it.get("unreceived"))
    ln.in_transit = pick_in_transit(ln.trans_shipped, ln.unreceived, in_transit_field)
    ln.mad = None if it.get("mad") is None else _f(it.get("mad"))
    ln.cap = _i(it.get("daily_surplus"))
    ln.min_qty = max(_i(it.get("min_qty")) or 1, 1)
    ln.pack_qty = max(_i(it.get("pack_qty")) or 1, 1)
    ln.storage_limit = _i(it.get("storage_limit"))
    ln.purchased_today = _i(it.get("purchased_today"))
    ln.unit_price = _f(it.get("unit_price"))
    ln.wh = dict(it.get("warehouses") or {})
    ln.national_queried = bool(it.get("national_queried"))
    ln.error = it.get("error") or ""
    return ln


def apply_defaults(ln: Line) -> Line:
    """默认期望:有上次人工修改的值用上次,否则用推荐(库存 + 出库)。人工修改过的保留本次的值。"""
    if ln.last_expected is not None:
        ln.default_expected, ln.default_source = int(ln.last_expected), "last"
    else:
        ln.default_expected, ln.default_source = ln.recommend, "recommend"
    if not ln.modified:
        ln.expected = ln.default_expected
    return ln


def compute(ln: Line) -> Line:
    """按当前的期望、勾选、库存 / 在途 / 上限 / 关注仓算补货数(定时补货)。"""
    ln.final_qty, ln.note = 0, ""
    if ln.error:
        ln.tag, ln.suggested, ln.note = "error", 0, "没查到,这次算不进去"
        return ln
    ln.suggested = max(int(math.ceil((ln.expected or 0) - ln.have)), 0)
    if not ln.checked:
        ln.tag, ln.note = "unchecked", TAG_LABEL["unchecked"]
        return ln
    if ln.suggested <= 0:
        ln.tag = "in_transit_ok" if (ln.in_transit > 0 and ln.stock < (ln.expected or 0)) else "enough"
        ln.note = TAG_LABEL[ln.tag]
        return ln
    return _cap(ln, ln.suggested)


def _pack_text(ln: Line) -> str:
    if ln.min_qty > 1 and ln.min_qty != ln.pack_qty:
        return f"起订 {ln.min_qty}、包装 {ln.pack_qty}"
    return f"包装 {ln.pack_qty}" if ln.pack_qty > 1 else f"起订 {ln.min_qty}"


def _zero_cap_note(ln: Line) -> str:
    """DMS 当日剩余可订为 0 的原因(全国仓有货也订不了:这是 DMS 按门店控的量,不是仓库库存)。"""
    if ln.storage_limit is not None and ln.have >= ln.storage_limit:
        return (f"DMS 当日可订为 0:库存{'+在途' if ln.in_transit else ''} {ln.have:g} 已超过 DMS 库存上限 "
                f"{ln.storage_limit},今天订不了")
    if ln.purchased_today:
        return f"DMS 当日可订为 0:今天已经订过 {ln.purchased_today} 个,可订量用完了"
    return "DMS 当日可订为 0,今天订不了"


def _cap(ln: Line, want: int) -> Line:
    if ln.wh and ln.wh_total <= 0:
        ln.tag, ln.note = "oos", "关注仓(%s)都没货,这次不订" % "/".join(wh_label(w) for w in ln.wh)
        return ln
    qty = pack_up(want, ln.min_qty, ln.pack_qty)
    if ln.cap is not None and qty > ln.cap:
        top = pack_down(ln.cap, ln.min_qty, ln.pack_qty)
        ln.tag, ln.final_qty = "capped", top
        if ln.cap <= 0:
            ln.note = _zero_cap_note(ln)
        elif top <= 0:
            ln.note = f"DMS 今天最多还能订 {ln.cap} 个,不够{_pack_text(ln)} 的量,今天订不了"
        else:
            ln.note = (f"DMS 今天最多还能订 {ln.cap} 个,按 {top} 订" + (f"({_pack_text(ln)})" if top != ln.cap else "")
                       + (f",差的 {want - top} 个明天再补" if want > top else ""))
        return ln
    ln.tag, ln.final_qty = "normal", qty
    notes = [f"差 {want} 个,按{_pack_text(ln)} 取整订 {qty}"] if qty != want else []
    if ln.national_queried is False and ln.grp != "single":
        notes.append("没查全国仓(刷新后会查)")
    ln.note = ";".join(notes)
    return ln


def number(lines: list[Line]) -> list[Line]:
    """排序(常备件在前,组内按出库量倒序)并给要订的行编号。"""
    order = {"stock": 0, "single": 0, "other": 1}
    lines.sort(key=lambda l: (order.get(l.grp, 2), -(l.outbound_qty or 0), l.part_no))
    n = 0
    for l in lines:
        l.seq = None
        if l.orderable:
            n += 1
            l.seq = n
    return lines


def plan_single(it: dict, qty: int, in_transit_field: str = "trans_shipped") -> Line:
    """单次补货:数量由人直接给(没有期望值环节),只受当日可订上限 / 关注仓约束。"""
    ln = fill_facts(Line(part_no=it["part_no"], name=it.get("name") or "", grp="single"), it, in_transit_field)
    ln.checked, ln.suggested, ln.expected = True, max(int(qty), 0), 0
    if ln.error:
        ln.tag, ln.note = "error", "没查到:" + ln.error[:100]
        return ln
    if ln.suggested <= 0:
        ln.tag, ln.note = "enough", "数量为 0,不订"
        return ln
    _cap(ln, ln.suggested)
    ln.seq = 1 if ln.orderable else None
    return ln


def summary(lines: list[Line]) -> dict:
    ok = [l for l in lines if l.orderable]
    return {"order_count": len(ok), "order_qty": sum(l.final_qty for l in ok),
            "amount": round(sum(l.final_qty * l.unit_price for l in ok), 2),
            "need_count": sum(1 for l in lines if l.checked and l.suggested > 0),
            "stock_count": sum(1 for l in lines if l.grp == "stock"),
            "other_count": sum(1 for l in lines if l.grp == "other"),
            "checked_count": sum(1 for l in lines if l.checked),
            "modified_count": sum(1 for l in lines if l.modified),
            "capped": [l.part_no for l in lines if l.tag == "capped"], "oos": [l.part_no for l in lines if l.tag == "oos"],
            "errors": [l.part_no for l in lines if l.tag == "error"],
            "wh_short": [l.part_no for l in lines if l.wh_short and l.tag != "oos"],
            "total": len(lines)}