diff --git a/capabilities/am516-delivery-prediction/docs/acceptance_samples.md b/capabilities/am516-delivery-prediction/docs/acceptance_samples.md index 7422cc5..d53218f 100644 --- a/capabilities/am516-delivery-prediction/docs/acceptance_samples.md +++ b/capabilities/am516-delivery-prediction/docs/acceptance_samples.md @@ -48,6 +48,9 @@ Expected: - each future appended candidate row records the same query-completion time in `YYYY-MM-DD HH:mm:ss +0800` form (with the actual local UTC offset), without rewriting or backfilling historical records; - record-table columns follow this order: 序号、记录时间、型号、推荐类型、差异项、API状态、AM516预测交期、可用库存、主导因素; - unavailable candidates remain in their original rule order and are recorded as `❌ 不可用` with unavailable result fields shown as `—`; lack of a result does not itself establish that the model does not exist; +- generated LF candidates pass only when `现货数` and matching LF reducer actual availability cover the original demand; an LF candidate with insufficient combined coverage, missing stock fields, no matched reducer or an inconsistent `需排产数` is absent from the report, fastest comparison, candidate counts and `不可用候选`; +- retained results display `现货数` and `需排产数`; retained LF candidates needing production also display the matched reducer code and reducer actual available quantity; +- overdue unreserved sales orders returned by the API display the sales-order code and a human-review reminder without automatically releasing inventory; ## Sample 1B | API Workdays And Final Delivery Date diff --git a/capabilities/am516-delivery-prediction/docs/lf_reducer_stock_gate.md b/capabilities/am516-delivery-prediction/docs/lf_reducer_stock_gate.md new file mode 100644 index 0000000..146058c --- /dev/null +++ b/capabilities/am516-delivery-prediction/docs/lf_reducer_stock_gate.md @@ -0,0 +1,59 @@ +# 来福减速器存量清仓候选门禁 + +## 背景 + +来福减速器后续不再采购。使用来福减速器的候选整机只能依据当前整机现货和对应来福减速器实际可用库存推荐,不能用采购在途、待检、固定提前期或未来补货能力补足数量。 + +## AR836 接口字段 + +AM516 从 `data.库存信息` 读取以下精简字段: + +- `现货数`:候选整机实际可用量。它不是 ERP 库存量,也不是未补扣销售订单占用的可用量。 +- `需排产数`:`max(需求数量 - 现货数, 0)`。 +- `对应来福减速器编码`:候选型号匹配的来福减速器物料编码。 +- `减速器实际可用量`:ERP 即时库存口径下可用于本次生产的数量。 +- `逾期待复核销售订单`:可选列表;订单超过要货日期 30 天但仍有待锁库/待预留数量时,包含销售订单编码、要货日期和逾期天数。 + +`现货数`由 AR836/ERP 侧计算: + +```text +整机实际可用量 += max( + ERP可用量(主单位) + - 有效销售订单待锁库/待预留数量(换算为主单位), 0 + ) +``` + +AM516 不要求接口返回、也不在报告展示以下中间字段: + +- `ERP可用量(主单位)` +- `待锁库待预留数量(主单位)` +- `实际可用量` +- `每台减速器用量` +- `合计可覆盖整机数量` +- `本次需求数量` +- `是否满足推荐门槛` + +## 推荐门禁 + +当前业务按每台关节模组使用一件对应减速器判断: + +```text +现货数 = 整机实际可用量 +需排产数 = max(需求数量 - 现货数, 0) + +需排产数 = 0 + -> 整机现货已覆盖,可保留 LF 候选 + +需排产数 > 0 且 减速器实际可用量 >= 需排产数 + -> 整机现货与减速器库存合计覆盖,可保留 LF 候选 + +其他情况 + -> 剔除 LF 候选 +``` + +以下情况同样剔除:字段缺失或不可读、`需排产数`与公式不一致、需要排产但无对应减速器编码。 + +被剔除的 LF 型号不出现在关节模组交期预估报告、不可用候选、最快交期比较、现货候选或候选统计中。原始输入型号仍作为基准展示,不按“生成候选”处理。 + +逾期销售订单只触发人工复核提醒,不自动释放库存;在 ERP 完成释放前,其待锁库/待预留数量仍由 AR836 扣除在`现货数`之外。 diff --git a/capabilities/am516-delivery-prediction/rules/eRob关节模组相似型号推荐规则_v3.1.md b/capabilities/am516-delivery-prediction/rules/eRob关节模组相似型号推荐规则_v3.1.md index 3b7d796..daf1fcc 100644 --- a/capabilities/am516-delivery-prediction/rules/eRob关节模组相似型号推荐规则_v3.1.md +++ b/capabilities/am516-delivery-prediction/rules/eRob关节模组相似型号推荐规则_v3.1.md @@ -215,3 +215,23 @@ AI 生成推荐型号时,应按以下顺序判断: | 2 | 被剔除型号 | 不推荐 | 剔除项 | 违反强约束或出现中约束降级 | 不进入候选交期计算 | AI 输出中不得使用“已替代”“已承诺”“可直接交付”等确定性表述;应使用“候选型号”“推荐理由”“需确认差异”“需 AR516 复核”等内部候选表述。 + +--- + +## 15. 来福减速器存量清仓门禁(2026-11-27补充) + +来福减速器后续不再采购,因此 `(Vx)` 来福候选不能只凭型号配置相似和预测交期进入报告。 + +对每个来福候选读取 AR836 返回的: + +```text +现货数 = 候选整机实际可用量 +需排产数 = max(本次需求数量 - 现货数, 0) +``` + +- `需排产数 = 0`:整机现货覆盖本次需求,可保留候选。 +- `需排产数 > 0`:对应来福减速器实际可用量必须大于等于需排产数,才可保留候选。 +- 整机现货与减速器库存合计不足,或库存字段缺失、无匹配减速器、数量口径矛盾:剔除候选。 +- 被剔除型号不进入交期报告、最快交期比较或不可用候选清单。 +- 采购在途、待检、固定提前期和未来采购不得作为放行依据。 +- 超过要货日期30天且仍有待锁库/待预留数量的销售订单只提示人工复核,不自动释放现货。 diff --git a/capabilities/am516-delivery-prediction/skills/joint-module-leadtime-report/SKILL.md b/capabilities/am516-delivery-prediction/skills/joint-module-leadtime-report/SKILL.md index f750d73..92d278d 100644 --- a/capabilities/am516-delivery-prediction/skills/joint-module-leadtime-report/SKILL.md +++ b/capabilities/am516-delivery-prediction/skills/joint-module-leadtime-report/SKILL.md @@ -44,8 +44,8 @@ Stop if: - AR51 confirmed on 2026-10-15 that the upstream API already accounts for available inventory and explicitly cancelled local inventory deduction, 95% yield adjustment and rounding to five. Follow `docs/production_quantity.md`. - Treat the user's positive integer quantity as original demand `D`. Query each model exactly once through the controlled script with `quantity=D`, unchanged. Preserve `D` in continuation context and pass it unchanged for every newly queried candidate. -- Inventory accounting and delivery calculation belong to the upstream API. Do not calculate a local production quantity, send a reduced or inflated quantity, or issue a second production query. -- Display each model's own returned inventory coverage against original demand. A displayed inventory gap is informational and must not become a new API quantity. Missing or invalid stock means unknown coverage, never zero; do not discard valid API workdays/date solely because inventory display is unavailable. +- Inventory accounting and delivery calculation belong to the upstream API. Do not change the API query quantity or issue a second production query. The sole local quantity check is the LF stock gate below, which validates the upstream compact stock fields without recalculating AR836 delivery dates. +- Display each model's own returned inventory coverage against original demand. A displayed inventory gap is informational and must not become a new API quantity. Missing or invalid stock means unknown coverage, never zero; do not discard valid API workdays/date solely because inventory display is unavailable, except that a generated LF candidate must be removed when its mandatory stock-gate fields cannot be verified. - Remove the obsolete partial-stock/production-quantity shortcut rejection. API failures and missing or invalid workdays/date retain existing error handling. - Replies show original demand per model. Hide the technical explanation lines `数量传递规则`, `库存覆盖口径` and `API查询数量` in both initial and continuation replies, along with the obsolete local net-demand or production-quantity fields. New internal records preserve the actual API quantities and quantity rules for traceability; leave historical records unchanged. @@ -126,6 +126,22 @@ Do not use temporary curl, WebFetch, or any API method outside the controlled sc final batch explicitly states that all rule candidates have been queried. - Missing or unsupported models count as queried positions and remain summarized under `不可用候选`; do not silently skip them to pull later candidates forward. +- LF candidates rejected by the stock gate are not API-unavailable candidates. Omit + them entirely from the report, fastest comparison, candidate counts and + `不可用候选`, without pulling later rule positions into the current batch. + +## LF Reducer Stock Gate + +- Apply this gate only to generated LF candidates, identified by `(Vx)`. +- Read `现货数`、`需排产数`、`对应来福减速器编码`、`减速器实际可用量` from `data.库存信息`. +- `现货数` means the finished product's actual available quantity after AR836 has deducted valid sales-order quantities waiting for locking/reservation. +- Require `需排产数 = max(原始需求数量 - 现货数, 0)`. +- If `需排产数 = 0`, the finished-product stock covers demand and the candidate passes without reducer replenishment. +- Otherwise require a matched LF reducer code and `减速器实际可用量 >= 需排产数`. +- Missing, invalid, inconsistent or insufficient fields reject the LF candidate. Purchasing in transit, inspection stock, fixed lead time and future replenishment must not rescue it. +- Show `现货数` and `需排产数` for retained results. Show the matched LF reducer code and actual available quantity for retained LF candidates that need production. +- If `逾期待复核销售订单` is returned, show its sales-order code and request human review. Never release stock automatically. +- The original input model remains the baseline; this generated-candidate gate does not hide the user's original model. ## Unavailable Result Reasons @@ -195,7 +211,7 @@ Use this field order for a successful Feishu report: 1. {model}({candidate type and reducer brand}) - 需求数量:{input quantity}台 - AM516预测交期:{API workdays}个工作日,最终交货日期:{API final delivery date} -- 可用库存/覆盖情况:{summary-level inventory and coverage only} +- 现货/排产情况:现货数{actual available finished goods}台;需排产数{remaining production quantity}台 - 主导因素:{main factor} - 推荐理由:{rule-based recommendation reason} - 差异项:{field changes formatted as `字段 原值→新值`; join multiple changes with `;`, for example `编码器 HS→HM;品牌 DZ→LF`} diff --git a/shared/runtime/feishu_bot_bridge.py b/shared/runtime/feishu_bot_bridge.py index 235a768..5a354ae 100644 --- a/shared/runtime/feishu_bot_bridge.py +++ b/shared/runtime/feishu_bot_bridge.py @@ -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: diff --git a/tests/test_feishu_bot_bridge.py b/tests/test_feishu_bot_bridge.py index a5fa32c..4af2b23 100644 --- a/tests/test_feishu_bot_bridge.py +++ b/tests/test_feishu_bot_bridge.py @@ -38,13 +38,30 @@ def successful_payload() -> dict[str, object]: "AM516最终交货日期": "2026-09-01", "AM516主导因素": "现货", }, - "库存信息": {"可用库存(扣除了待产数量)": 100}, + "库存信息": { + "可用库存(扣除了待产数量)": 100, + "现货数": 100, + "需排产数": 0, + "对应来福减速器编码": "20.30.00999", + "减速器实际可用量": 100, + "逾期待复核销售订单": [], + }, "BOM信息": {"是否有BOM(False则需提醒无BOM)": True}, "采购信息": {"缺料明细": []}, } } +def set_stock(payload: dict[str, object], stock: object, demand: int) -> None: + inventory = payload["data"]["库存信息"] + inventory["可用库存(扣除了待产数量)"] = stock + inventory["现货数"] = stock + if isinstance(stock, (int, float)) and not isinstance(stock, bool): + inventory["需排产数"] = max(demand - stock, 0) + else: + inventory["需排产数"] = None + + def message_event(message_id: str, chat_id: str, open_id: str) -> SimpleNamespace: return SimpleNamespace( event=SimpleNamespace( @@ -420,7 +437,7 @@ class OriginalDemandQueryTests(unittest.TestCase): def test_partial_full_and_zero_stock_do_not_change_api_quantity(self) -> None: for demand, stock in ((12, 10), (8, 5), (24, 6), (24, 0), (24, 24), (24, 30), (24, -2), (5, 1)): payload = successful_payload() - payload['data']['库存信息']['可用库存(扣除了待产数量)'] = stock + set_stock(payload, stock, demand) request = bridge.RequestInput('eRob70F50I-FHM-18ET[V4]', demand) with ( self.subTest(demand=demand, stock=stock), @@ -434,7 +451,7 @@ class OriginalDemandQueryTests(unittest.TestCase): def test_screenshot_regression_passes_twelve_to_controlled_script(self) -> None: request = bridge.RequestInput('eRob70F50I-FHM-18ET[V4]', 12) payload = successful_payload() - payload['data']['库存信息']['可用库存(扣除了待产数量)'] = 10 + set_stock(payload, 10, 12) payload['data']['交期汇总'].update(AM516工作日交期=8, AM516最终交货日期='2026-10-27', AM516主导因素='生产') completed = SimpleNamespace(stdout=bridge.json.dumps(payload), stderr='', returncode=0) with ( @@ -446,7 +463,7 @@ class OriginalDemandQueryTests(unittest.TestCase): for call in run.call_args_list: command = call.args[0] self.assertEqual(command[command.index('--quantity') + 1], '12') - self.assertIn('整机可用库存10台(部分覆盖,仍需补齐2台)', report) + self.assertIn('现货数10台;需排产数2台', report) self.assertIn('8个工作日,最终交货日期:2026-10-27', report) self.assertNotIn('误走现货分支', report) self.assertNotIn('排产测算数量', report) @@ -474,7 +491,7 @@ class OriginalDemandQueryTests(unittest.TestCase): stocks = dict(zip(models, [6, 0, 24, 20, 30])) def query(r): payload = successful_payload() - payload['data']['库存信息']['可用库存(扣除了待产数量)'] = stocks[r.model] + set_stock(payload, stocks[r.model], 24) return payload with ( mock.patch.object(bridge, 'run_controlled_query', side_effect=query) as run, @@ -490,7 +507,7 @@ class OriginalDemandQueryTests(unittest.TestCase): def test_missing_or_invalid_stock_is_unknown_without_overriding_api_forecast(self) -> None: for stock in (None, True, '6', 1.5, float('nan'), float('inf')): payload = successful_payload() - payload['data']['库存信息']['可用库存(扣除了待产数量)'] = stock + set_stock(payload, stock, 24) with ( self.subTest(stock=stock), mock.patch.object(bridge, 'run_controlled_query', return_value=payload) as query, @@ -504,7 +521,7 @@ class OriginalDemandQueryTests(unittest.TestCase): def test_forecast_preserves_api_date_and_materials(self) -> None: payload = successful_payload() - payload['data']['库存信息']['可用库存(扣除了待产数量)'] = 10 + set_stock(payload, 10, 12) payload['data']['交期汇总'].update(AM516工作日交期=8, AM516最终交货日期='2026-10-27') payload['data']['采购信息']['缺料明细'] = [{'物料名称': '测算物料'}] with mock.patch.object(bridge, 'run_controlled_query', return_value=payload) as query: @@ -526,6 +543,123 @@ class OriginalDemandQueryTests(unittest.TestCase): record.assert_not_called() +class LfStockGateTests(unittest.TestCase): + LF_MODEL = "eRob70F50I-FHM-18ET(V4)" + + def details(self, demand: int, stock: int, reducer_stock: int | None) -> dict[str, object]: + payload = successful_payload() + set_stock(payload, stock, demand) + inventory = payload["data"]["库存信息"] + inventory["对应来福减速器编码"] = "20.30.00999" + inventory["减速器实际可用量"] = reducer_stock + return bridge.lead_time_details(payload, demand) + + def test_full_finished_goods_stock_passes_without_reducer_stock(self) -> None: + details = self.details(demand=10, stock=10, reducer_stock=None) + + self.assertEqual(details["stock_on_hand"], 10) + self.assertEqual(details["production_required"], 0) + self.assertIsNone(bridge.lf_stock_gate_reason(self.LF_MODEL, details)) + + def test_partial_finished_goods_and_reducer_stock_must_cover_all_demand(self) -> None: + covered = self.details(demand=10, stock=3, reducer_stock=7) + insufficient = self.details(demand=10, stock=3, reducer_stock=6) + + self.assertIsNone(bridge.lf_stock_gate_reason(self.LF_MODEL, covered)) + self.assertIn( + "合计不足", + bridge.lf_stock_gate_reason(self.LF_MODEL, insufficient), + ) + + def test_zero_finished_goods_and_zero_reducer_stock_is_excluded(self) -> None: + details = self.details(demand=10, stock=0, reducer_stock=0) + + self.assertIsNotNone(bridge.lf_stock_gate_reason(self.LF_MODEL, details)) + + def test_inconsistent_production_required_is_excluded(self) -> None: + payload = successful_payload() + set_stock(payload, 3, 10) + payload["data"]["库存信息"]["需排产数"] = 6 + details = bridge.lead_time_details(payload, 10) + + self.assertIn( + "不一致", + bridge.lf_stock_gate_reason(self.LF_MODEL, details), + ) + + def test_missing_compact_stock_fields_is_excluded(self) -> None: + payload = successful_payload() + del payload["data"]["库存信息"]["现货数"] + del payload["data"]["库存信息"]["需排产数"] + details = bridge.lead_time_details(payload, 10) + + self.assertIn( + "未返回可核验", + bridge.lf_stock_gate_reason(self.LF_MODEL, details), + ) + + def test_insufficient_lf_candidate_is_absent_from_report(self) -> None: + request = bridge.RequestInput("eRob70F50I-FHM-18ET[V4]", 10) + lf_model = next( + spec["model"] + for spec in bridge.generate_candidate_specs(request.model)[:4] + if bridge.is_lf_model(spec["model"]) + ) + + def query(query_request: bridge.RequestInput) -> dict[str, object]: + payload = successful_payload() + if query_request.model == lf_model: + set_stock(payload, 3, query_request.quantity) + payload["data"]["库存信息"]["减速器实际可用量"] = 6 + return payload + + with ( + mock.patch.object(bridge, "run_controlled_query", side_effect=query), + mock.patch.object(bridge, "write_record") as record, + ): + report = bridge.build_report(request) + + self.assertNotIn(lf_model, report) + self.assertNotIn( + lf_model, + [item["model"] for item in record.call_args.args[1]], + ) + self.assertNotIn( + lf_model, + [item["model"] for item in record.call_args.args[2]], + ) + + def test_covered_lf_candidate_shows_stock_basis_and_overdue_order(self) -> None: + payload = successful_payload() + set_stock(payload, 3, 10) + inventory = payload["data"]["库存信息"] + inventory["减速器实际可用量"] = 7 + inventory["逾期待复核销售订单"] = [ + { + "销售订单编码": "SAL-OVERDUE-001", + "要货日期": "2026-09-01", + "逾期天数": 35, + } + ] + details = bridge.lead_time_details(payload, 10) + candidate = { + "index": 2, + "model": self.LF_MODEL, + "type": "品牌替代候选,LF", + "details": details, + "reason": "强约束保持一致", + "difference": "品牌 DZ→LF", + "confirmation": "需人工确认", + } + + report = "\n".join(bridge.candidate_report_lines(candidate, 10)) + + self.assertIn("现货数3台;需排产数7台", report) + self.assertIn("实际可用量7件", report) + self.assertIn("SAL-OVERDUE-001", report) + self.assertIn("是否释放现货", report) + + class CandidateBatchTests(unittest.TestCase): def setUp(self) -> None: self.request = bridge.RequestInput(model="eRob70H50I-FS-18CN[V5]", quantity=10) @@ -550,7 +684,7 @@ class CandidateBatchTests(unittest.TestCase): queried_models[1:], [spec["model"] for spec in self.specs[: bridge.CANDIDATE_BATCH_SIZE]], ) - self.assertIn("本次先推荐4个候选型号(原型号另作基准)", report) + self.assertIn("本次展示4个符合门槛的候选型号(原型号另作基准)", report) self.assertIn("可说“还有吗”“再推荐几个”“继续”等类似表达", report) self.assertNotIn(self.specs[bridge.CANDIDATE_BATCH_SIZE]["model"], report) @@ -578,7 +712,7 @@ class CandidateBatchTests(unittest.TestCase): self.assertEqual(len(queried_models), bridge.CANDIDATE_BATCH_SIZE) self.assertNotIn(self.request.model, queried_models) self.assertCountEqual(queried_models, expected_models) - self.assertIn("本次继续推荐第5-8个候选型号", report) + self.assertIn("本次继续展示4个符合门槛的候选型号", report) for model in expected_models: self.assertIn(model, report) for model in [spec["model"] for spec in self.specs[:4]]: