feat: add LF reducer stock coverage gate
This commit is contained in:
1 parent
a017c4b48c
commit
f1099c84dd
6 files changed
+391
-19
No files matched your search
@@ -4,6 +4,7 @@ import concurrent.futures
|
||||
import itertools
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
@@ -180,6 +181,51 @@ class CandidateUnavailableError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def nonnegative_quantity(value: Any) -> int | float | None:
|
||||
"""Return a finite nonnegative ERP quantity, excluding booleans."""
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
return None
|
||||
if not math.isfinite(value) or value < 0:
|
||||
return None
|
||||
if isinstance(value, float) and not value.is_integer():
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def quantity_text(value: int | float) -> str:
|
||||
return f"{value:g}"
|
||||
|
||||
|
||||
def is_lf_model(model: str) -> bool:
|
||||
match = MODEL_PATTERN.fullmatch(model)
|
||||
return bool(match and match.group("bracket") == "(")
|
||||
|
||||
|
||||
def lf_stock_gate_reason(model: str, details: dict[str, Any]) -> str | None:
|
||||
"""Return an internal exclusion reason for an LF candidate, or None when eligible."""
|
||||
if not is_lf_model(model):
|
||||
return None
|
||||
|
||||
stock_on_hand = details.get("stock_on_hand")
|
||||
production_required = details.get("production_required")
|
||||
if stock_on_hand is None or production_required is None:
|
||||
return "接口未返回可核验的现货数和需排产数"
|
||||
if details.get("stock_quantity_consistent") is not True:
|
||||
return "接口返回的需排产数与需求数量、现货数不一致"
|
||||
if production_required == 0:
|
||||
return None
|
||||
|
||||
reducer_code = details.get("lf_reducer_code")
|
||||
reducer_available = details.get("lf_reducer_available")
|
||||
if not isinstance(reducer_code, str) or not reducer_code.strip():
|
||||
return "接口未返回与候选型号匹配的来福减速器编码"
|
||||
if reducer_available is None:
|
||||
return "接口未返回对应来福减速器实际可用量"
|
||||
if reducer_available < production_required:
|
||||
return "整机现货与对应来福减速器实际可用量合计不足"
|
||||
return None
|
||||
|
||||
|
||||
def validate_demand_quantity(quantity: int) -> None:
|
||||
"""Reject invalid demand before calling the controlled API."""
|
||||
if isinstance(quantity, bool) or not isinstance(quantity, int) or quantity <= 0:
|
||||
@@ -661,6 +707,42 @@ def shortage_material_names_line(shortages: list[Any]) -> str:
|
||||
return f"- 缺料物料明细:{text}"
|
||||
|
||||
|
||||
def stock_contract_value(data: dict[str, Any], field: str) -> Any:
|
||||
"""Read the compact stock contract, preferring data.库存信息."""
|
||||
inventory_info = data.get("库存信息")
|
||||
if isinstance(inventory_info, dict) and field in inventory_info:
|
||||
return inventory_info[field]
|
||||
# Temporary compatibility for AR836 rollout samples that place the same
|
||||
# compact fields directly under data.
|
||||
return data.get(field)
|
||||
|
||||
|
||||
def overdue_sales_order_lines(data: dict[str, Any]) -> list[str]:
|
||||
orders = stock_contract_value(data, "逾期待复核销售订单")
|
||||
if not isinstance(orders, list):
|
||||
return []
|
||||
lines: list[str] = []
|
||||
for order in orders:
|
||||
if not isinstance(order, dict):
|
||||
continue
|
||||
order_code = order.get("销售订单编码")
|
||||
if not isinstance(order_code, str) or not order_code.strip():
|
||||
continue
|
||||
parts = [f"销售订单编码{order_code.strip()}"]
|
||||
required_date = order.get("要货日期")
|
||||
if isinstance(required_date, str) and required_date.strip():
|
||||
parts.append(f"要货日期{required_date.strip()}")
|
||||
overdue_days = whole_day_count(order.get("逾期天数"))
|
||||
if overdue_days is not None:
|
||||
parts.append(f"逾期{overdue_days}天")
|
||||
lines.append(
|
||||
"- 库存复核提醒:"
|
||||
+ ";".join(parts)
|
||||
+ ";请人工确认是否为客户逾期未提货订单及是否释放现货。"
|
||||
)
|
||||
return lines
|
||||
|
||||
|
||||
def lead_time_details(
|
||||
payload: dict[str, Any],
|
||||
requested_quantity: int,
|
||||
@@ -720,11 +802,33 @@ def lead_time_details(
|
||||
prediction_value = None
|
||||
|
||||
inventory_info = data.get("库存信息")
|
||||
available_inventory = (
|
||||
stock_on_hand = nonnegative_quantity(stock_contract_value(data, "现货数"))
|
||||
production_required = nonnegative_quantity(stock_contract_value(data, "需排产数"))
|
||||
expected_production_required = (
|
||||
max(requested_quantity - stock_on_hand, 0)
|
||||
if stock_on_hand is not None
|
||||
else None
|
||||
)
|
||||
stock_quantity_consistent = (
|
||||
production_required is not None
|
||||
and expected_production_required is not None
|
||||
and math.isclose(production_required, expected_production_required, abs_tol=1e-9)
|
||||
)
|
||||
lf_reducer_code = stock_contract_value(data, "对应来福减速器编码")
|
||||
if not isinstance(lf_reducer_code, str) or not lf_reducer_code.strip():
|
||||
lf_reducer_code = None
|
||||
else:
|
||||
lf_reducer_code = lf_reducer_code.strip()
|
||||
lf_reducer_available = nonnegative_quantity(
|
||||
stock_contract_value(data, "减速器实际可用量")
|
||||
)
|
||||
|
||||
legacy_available_inventory = (
|
||||
inventory_info.get("可用库存(扣除了待产数量)")
|
||||
if isinstance(inventory_info, dict)
|
||||
else None
|
||||
)
|
||||
available_inventory = stock_on_hand if stock_on_hand is not None else legacy_available_inventory
|
||||
# Inventory is display-only; invalid values do not invalidate API dates.
|
||||
if (
|
||||
isinstance(available_inventory, bool)
|
||||
@@ -732,7 +836,13 @@ def lead_time_details(
|
||||
or (isinstance(available_inventory, float) and not available_inventory.is_integer())
|
||||
):
|
||||
available_inventory = None
|
||||
if available_inventory is not None:
|
||||
if stock_on_hand is not None and production_required is not None:
|
||||
inventory_text = (
|
||||
f"现货数{quantity_text(stock_on_hand)}台;"
|
||||
f"需排产数{quantity_text(production_required)}台"
|
||||
)
|
||||
full_coverage = production_required == 0
|
||||
elif available_inventory is not None:
|
||||
if available_inventory >= requested_quantity:
|
||||
inventory_text = f"整机可用库存{available_inventory:g}台(完全覆盖)"
|
||||
full_coverage: bool | None = True
|
||||
@@ -792,6 +902,7 @@ def lead_time_details(
|
||||
else:
|
||||
evidence_lines = ["- 缺料/BOM摘要:接口未返回可识别缺料汇总,需人工复核。"]
|
||||
|
||||
stock_review_lines = overdue_sales_order_lines(data)
|
||||
timestamp = data.get("时间戳") if isinstance(data.get("时间戳"), str) else None
|
||||
return {
|
||||
"prediction": prediction,
|
||||
@@ -804,6 +915,12 @@ def lead_time_details(
|
||||
"available_inventory": (
|
||||
available_inventory if isinstance(available_inventory, (int, float)) else None
|
||||
),
|
||||
"stock_on_hand": stock_on_hand,
|
||||
"production_required": production_required,
|
||||
"stock_quantity_consistent": stock_quantity_consistent,
|
||||
"lf_reducer_code": lf_reducer_code,
|
||||
"lf_reducer_available": lf_reducer_available,
|
||||
"stock_review_lines": stock_review_lines,
|
||||
"full_coverage": full_coverage,
|
||||
"evidence_lines": evidence_lines,
|
||||
"timestamp": timestamp,
|
||||
@@ -848,11 +965,24 @@ def overall_judgment_lines(candidates: list[dict[str, Any]]) -> list[str]:
|
||||
|
||||
def candidate_report_lines(candidate: dict[str, Any], quantity: int) -> list[str]:
|
||||
details = candidate["details"]
|
||||
lf_inventory_lines: list[str] = []
|
||||
if is_lf_model(candidate["model"]):
|
||||
reducer_code = details.get("lf_reducer_code")
|
||||
reducer_available = details.get("lf_reducer_available")
|
||||
if isinstance(reducer_code, str) and reducer_available is not None:
|
||||
lf_inventory_lines.append(
|
||||
"- 来福减速器库存依据:"
|
||||
f"物料编码{reducer_code};实际可用量{quantity_text(reducer_available)}件。"
|
||||
)
|
||||
elif details.get("production_required") == 0:
|
||||
lf_inventory_lines.append("- 来福库存门禁:整机现货已覆盖需求,无需减速器库存补充。")
|
||||
return [
|
||||
f"{candidate['index']}. {candidate['model']}({candidate['type']})",
|
||||
f"- 需求数量:{quantity}台",
|
||||
f"- {details['prediction']}",
|
||||
f"- 可用库存/覆盖情况:{details['inventory']}",
|
||||
f"- 现货/排产情况:{details['inventory']}",
|
||||
*lf_inventory_lines,
|
||||
*details.get("stock_review_lines", []),
|
||||
f"- 主导因素:{details['main_factor']}",
|
||||
f"- 推荐理由:{candidate['reason']}",
|
||||
f"- 差异项:{candidate['difference']}",
|
||||
@@ -1049,6 +1179,7 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
|
||||
)
|
||||
|
||||
unavailable: list[dict[str, str]] = []
|
||||
stock_gate_excluded: list[dict[str, str]] = []
|
||||
|
||||
def query_candidate(spec: dict[str, str]) -> tuple[dict[str, str], dict[str, Any] | None]:
|
||||
try:
|
||||
@@ -1060,6 +1191,10 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
|
||||
**spec,
|
||||
"unavailable_reason": details["unavailable_reason"],
|
||||
}, None
|
||||
stock_gate_reason = lf_stock_gate_reason(spec["model"], details)
|
||||
if stock_gate_reason is not None:
|
||||
logging.info("LF candidate excluded by stock gate: %s", spec["model"])
|
||||
return {**spec, "stock_gate_reason": stock_gate_reason}, None
|
||||
return spec, details
|
||||
|
||||
if candidate_specs:
|
||||
@@ -1072,7 +1207,10 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
|
||||
for future in concurrent.futures.as_completed(future_map):
|
||||
spec, details = future.result()
|
||||
if details is None:
|
||||
unavailable.append(spec)
|
||||
if "stock_gate_reason" in spec:
|
||||
stock_gate_excluded.append(spec)
|
||||
else:
|
||||
unavailable.append(spec)
|
||||
continue
|
||||
candidates.append({**spec, "details": details})
|
||||
|
||||
@@ -1084,6 +1222,7 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
|
||||
candidates[candidate_start:], key=lambda item: candidate_order[item["model"]]
|
||||
)
|
||||
unavailable.sort(key=lambda item: candidate_order[item["model"]])
|
||||
stock_gate_excluded.sort(key=lambda item: candidate_order[item["model"]])
|
||||
for candidate in candidates[candidate_start:]:
|
||||
candidate["record_order"] = candidate_order[candidate["model"]] + 2
|
||||
candidate["index"] = candidate["record_order"]
|
||||
@@ -1107,13 +1246,14 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
|
||||
queried_end = candidate_offset + len(candidate_specs)
|
||||
remaining_count = len(all_candidate_specs) - queried_end
|
||||
if is_initial_batch:
|
||||
visible_candidate_count = len(candidates) - 1
|
||||
batch_scope = (
|
||||
f"本次先推荐{len(candidate_specs)}个候选型号(原型号另作基准)"
|
||||
f"本次展示{visible_candidate_count}个符合门槛的候选型号(原型号另作基准)"
|
||||
if remaining_count
|
||||
else f"本次已推荐全部{len(candidate_specs)}个候选型号(原型号另作基准)"
|
||||
else f"本次已展示全部{visible_candidate_count}个符合门槛的候选型号(原型号另作基准)"
|
||||
)
|
||||
else:
|
||||
batch_scope = f"本次继续推荐第{candidate_offset + 1}-{queried_end}个候选型号"
|
||||
batch_scope = f"本次继续展示{len(candidates)}个符合门槛的候选型号"
|
||||
if remaining_count:
|
||||
batch_scope += f";尚有{remaining_count}个规则候选未查询"
|
||||
else:
|
||||
|
||||