planner.py 22.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
"""补货算法(纯函数,无 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),和全国仓有没有货无关
单次补货:数量由人直接给,同样按起订量 / 包装数取整、受当日可订上限约束(超出按上限并说明)、关注仓全无货不订。
批量补货(grp=multi):每个零件的算法同单次补货;人要的数量记在 default_expected,系统按起订量 / 包装数 / 当日可订
算出的建议订货量记在 ext.agent_qty(也是 expected 的初始值),单据页上改过的数量记在 expected(modified = 和建议量不同),
可以取消勾选。单据页的数量只能在 qty_range 内按包装数加减(≥ 起订量的最小包装整数倍,≤ 当日可订和单个零件上限)。
复用定时补货页面的勾选 / 期望字段,确认、快照、改动记录都走同一套。
tag:normal / capped / oos / enough / in_transit_ok / unchecked / error
"""
from __future__ import annotations

import math
from dataclasses import asdict, dataclass, field, replace

TAG_LABEL = {"normal": "", "capped": "今天到上限了", "oos": "厂家缺货", "enough": "库存够用",
             "in_transit_ok": "在途够了", "unchecked": "没勾选,这次不订", "error": "没查到",
             "pending": "查询中", "not_found": "编码不存在"}
GROUP_LABEL = {"stock": "历史常备件", "other": "其他出库件", "single": "单次补货", "multi": "批量补货"}
SOURCE_LABEL = {"last": "上次", "recommend": "推荐", "manual": "已修改", "request": "群里要的"}
# 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 且勾选的行编号
    ext: dict = field(default_factory=dict)   # 批量补货:merged 合并了几条 / raw 原文写法 / reject DMS 点名拒绝的原因 /
                                              # agent_qty 系统建议的订货量(按起订量 / 包装数 / 当日可订取整后)

    @property
    def base_expected(self) -> int:
        """判断「人改过没有」的基准:批量补货 = 系统建议的订货量(ext.agent_qty),定时补货 = 默认期望。"""
        if self.grp == "multi" and (self.ext or {}).get("agent_qty") is not None:
            return int(self.ext["agent_qty"])
        return self.default_expected

    @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, "")

    @property
    def blocked(self) -> bool:
        """批量补货里订不了的零件(不管要几个都订不了):没查到 / 编码不存在 / 关注仓都没货 /
        当日可订凑不够一个起订量(含可订为 0)。单据页归到「不可以订的」组,不能勾选。"""
        if self.grp != "multi" or self.tag == "pending":
            return False
        if self.error:
            return True
        if self.wh and self.wh_total <= 0:
            return True
        return self.cap is not None and pack_down(self.cap, self.min_qty, self.pack_qty) <= 0

    @property
    def default_checked(self) -> bool:
        """系统默认勾选:历史常备件 / 单次补货勾,其他出库件不勾;批量补货订不了的不勾。"""
        if self.grp == "multi":
            return not self.blocked
        return self.grp != "other"

    @property
    def check_changed(self) -> bool:
        """勾选状态和系统默认不一样(常备件被取消、其他出库件被手动勾上)。"""
        return self.checked != self.default_checked

    @property
    def changed(self) -> bool:
        """用户改过:改了期望,或勾选和默认不一样。后台「改过」统计 / 筛选、确认消息都按这个口径。"""
        return self.modified or self.check_changed

    @property
    def change_text(self) -> str:
        """改了什么(一句话):「取消勾选(默认勾);期望 92→100」。"""
        parts = []
        if self.check_changed:
            parts.append("取消勾选(默认勾)" if not self.checked else "手动勾选(默认不勾)")
        if self.modified:
            what = "数量" if self.grp == "multi" else "期望"
            parts.append(f"{what} {self.base_expected}→{self.expected}")
        return ";".join(parts)

    def preview(self) -> tuple[int, str]:
        """勾选后会补多少(只给页面显示用):已勾选 = final_qty / note;未勾选 = 假设勾选重算一遍,本行不变、不会下单。"""
        if self.checked:
            return self.final_qty, self.note
        p = compute(replace(self, checked=True, wh=dict(self.wh or {})))
        return p.final_qty, p.note

    def to_dict(self) -> dict:
        d = asdict(self)
        d["preview_qty"], d["preview_note"] = self.preview()
        d.update(label=TAG_LABEL.get(self.tag, ""), orderable=self.orderable, recommend=self.recommend,
                 base_expected=self.base_expected,
                 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), default_checked=self.default_checked,
                 check_changed=self.check_changed, changed=self.changed, change_text=self.change_text,
                 blocked=self.blocked)
        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


def qty_range(ln: Line, max_qty: int | None = None) -> tuple[int, int, int]:
    """批量补货单据页数量的可选范围 (最小, 最大, 步长):最小 = ≥ 起订量的最小包装整数倍,最大 = 当日可订和单个零件
    上限以内最大的包装整数倍,步长 = 包装数。最大 < 最小 表示一个都订不了。"""
    pk = max(int(ln.pack_qty or 1), 1)
    lo = pack_up(1, ln.min_qty, pk)
    tops = [pack_down(ln.cap, ln.min_qty, pk)] if ln.cap is not None else []
    if max_qty:
        tops.append(pack_down(max_qty, ln.min_qty, pk))
    hi = min(tops) if tops else 10 ** 9
    return lo, hi, pk


def qty_problem(ln: Line, max_qty: int | None = None) -> str:
    """批量补货确认时校验数量(已勾选、可订的行):不在范围内 / 不是包装数整数倍 → 返回原因;没问题返回空串。"""
    lo, hi, pk = qty_range(ln, max_qty)
    q = int(ln.expected or 0)
    if hi < lo:
        return f"{ln.part_no} 今天订不了(凑不够{_pack_text(ln)})"
    if q < lo:
        return f"{ln.part_no} × {q} 少于起订量,最少 {lo} 个({_pack_text(ln)})"
    if q % pk:
        return f"{ln.part_no} × {q} 不是包装数 {pk} 的整数倍"
    if q > hi:
        why = " DMS 当日可订" if ln.cap is not None and pack_down(ln.cap, ln.min_qty, pk) == hi else "单个零件的数量上限"
        return f"{ln.part_no} × {q} 超过{why},最多 {hi} 个"
    return ""


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:
    """按当前的期望、勾选、库存 / 在途 / 上限 / 关注仓算补货数(定时补货;批量补货转给 compute_multi)。"""
    if ln.grp == "multi":
        return compute_multi(ln)
    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:
            lo = pack_up(1, ln.min_qty, ln.pack_qty)
            ln.note = (f"DMS 今天最多还能订 {ln.cap} 个,不够起订 {lo} 个"
                       + (f"(包装 {ln.pack_qty})" if ln.pack_qty > 1 else "") + ",今天订不了")
        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 not in ("single", "multi"):
        notes.append("没查全国仓(刷新后会查)")
    ln.note = ";".join(notes)
    return ln


def number(lines: list[Line]) -> list[Line]:
    """排序(常备件在前,组内按出库量倒序)并给要订的行编号。"""
    order = {"stock": 0, "single": 0, "multi": 0, "other": 1}
    # 批量补货保持群里发的顺序(sort 是稳定的)
    lines.sort(key=lambda l: (order.get(l.grp, 2), -(l.outbound_qty or 0), "" if l.grp == "multi" else 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 pending_multi(part_no: str, qty: int, ext: dict | None = None) -> Line:
    """批量补货发起时的占位行(还没查):单据页先显示出来,查好一批填一批。"""
    q = max(int(qty), 0)
    return Line(part_no=part_no, name="", grp="multi", checked=True, default_expected=q, default_source="request",
                expected=q, suggested=q, tag="pending", note=TAG_LABEL["pending"], ext=dict(ext or {}))


def plan_multi(it: dict, qty: int, in_transit_field: str = "trans_shipped", ext: dict | None = None) -> Line:
    """批量补货的一项:人要的数量记在 default_expected(也是初始的 expected);能订的默认勾选,订不了的不勾。
    算法同单次补货。ext:合并条数 / 原文写法(单据页显示用)。"""
    ln = fill_facts(Line(part_no=it["part_no"], name=it.get("name") or "", grp="multi"), it, in_transit_field)
    q = max(int(qty), 0)
    ln.default_expected, ln.default_source, ln.expected, ln.modified = q, "request", q, False
    ln.ext = {k: v for k, v in (ext or {}).items() if k != "agent_qty"}
    ln.checked = ln.default_checked
    compute_multi(ln)
    # 建议订货量:按起订量 / 包装数 / 当日可订取整后的数,也是单据页数量的初始值(页面只能在 qty_range 内按包装数加减)
    if ln.orderable:
        ln.ext["agent_qty"] = ln.expected = ln.final_qty
        compute_multi(ln)
    return ln


def _not_found(error: str) -> bool:
    """查询错误是不是「DMS 里没有这个编码」(取数端:订货主数据查不到),不是网络之类的临时错误。"""
    return "查不到配件" in (error or "")


def compute_multi(ln: Line) -> Line:
    """批量补货:按当前数量(expected)和勾选重算(单据页改数量 / 取消勾选后确认时调)。
    订不了的零件(blocked)不管页面传来什么都按不勾选处理,原因照样写清。"""
    if ln.tag == "pending" and not ln.error:
        ln.final_qty = 0
        return ln
    ln.final_qty, ln.note = 0, ""
    if ln.error:
        ln.checked = False
        raw = (ln.ext or {}).get("raw") or ln.part_no
        if _not_found(ln.error):
            ln.tag, ln.suggested, ln.note = "not_found", 0, f"编码不存在(群里写的是「{raw}」,请核对是不是打错了)"
        else:
            ln.tag, ln.suggested, ln.note = "error", 0, "没查到:" + ln.error[:100] + "(可点「刷新库存」再查)"
        return ln
    ln.suggested = max(int(ln.expected or 0), 0)
    if ln.blocked:
        ln.checked = False
        _cap(ln, max(ln.suggested, 1))
        ln.final_qty = 0
        if ln.tag == "oos":
            ln.note = "%s都没货,这次订不了,可走 BO 单(需单独申请)" % " / ".join(wh_label(w) for w in ln.wh)
        return ln
    if not ln.checked:
        ln.tag, ln.note = "unchecked", TAG_LABEL["unchecked"]
        return ln
    if ln.suggested <= 0:
        ln.tag, ln.note = "enough", "数量为 0,不订"
        return ln
    _cap(ln, ln.suggested)
    # 数量已经是建议量(按上限取过整)时 _cap 看不出「到上限了」:按群里要的数量判断,还是标「按上限订」
    if ln.tag == "normal" and ln.cap is not None and ln.final_qty == pack_down(ln.cap, ln.min_qty, ln.pack_qty) \
            and pack_up(ln.default_expected, ln.min_qty, ln.pack_qty) > ln.cap:
        ln.tag = "capped"
    ln.note = _multi_note(ln) or ln.note
    return ln


def _multi_note(ln: Line) -> str:
    """批量补货:实际订的和群里要的不一样时,用「你要 X 个」开头把原因说清(起订量 / 包装数取整、当日可订上限)。
    人自己改成别的数量的不写(页面上有「已改」标记)。"""
    req, q = ln.default_expected, ln.final_qty
    if q <= 0 or q == req:
        return ""
    if ln.tag == "capped":
        return (f"你要 {req} 个,DMS 今天最多还能订 {ln.cap} 个,按 {q} 订"
                + (f"({_pack_text(ln)})" if q != ln.cap else "") + (f",差的 {req - q} 个明天再补" if req > q else ""))
    if q == pack_up(req, ln.min_qty, ln.pack_qty) and q > req:
        why = ([f"起订量 {ln.min_qty} 个"] if ln.min_qty > req else []) + (
            [f"包装 {ln.pack_qty} 个"] if ln.pack_qty > 1 else [])
        return f"你要 {req} 个,DMS {'、'.join(why)},按 {q} 订"
    return ""


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),
            "changed_count": sum(1 for l in lines if l.changed),
            "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)}