Compare commits

...
6 changed files with 350 additions and 23 deletions

No files matched your search

@@ -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; - 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预测交期、可用库存、主导因素; - 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; - 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 when finished-product available inventory covers demand, or when the readable AR836 shortage list contains no `20.30.*` reducer constraint after AR836's 95% yield, five-unit rounding and BOM calculation;
- an LF candidate with insufficient finished-product inventory plus a `20.30.*` shortage, or with an unreadable shortage list, is absent from the report, fastest comparison, candidate counts and `不可用候选`;
- an original LF inquiry remains visible, but when finished-product inventory is insufficient and AR836 returns a `20.30.*` shortage, its API lead time is suppressed and original-model analysis says `来福减速器后续需求需AR516核实,交期以人工答复为准`;
## Sample 1B | API Workdays And Final Delivery Date ## Sample 1B | API Workdays And Final Delivery Date
@@ -0,0 +1,38 @@
# 来福减速器存量清仓候选门禁(AR836 当前接口版)
## 背景
来福减速器后续不再采购。使用来福减速器的生成候选,必须有整机可用库存或 AR836 根据本次排产需求核算后确认减速器不构成供应约束,不能只凭型号相似和预测交期推荐。
## 当前使用的 AR836 字段
AM516 仅依赖现有接口已返回的:
- `data.库存信息.可用库存(扣除了待产数量)`:候选整机的当前可用库存口径。
- `data.采购信息.缺料明细[]` 及其 `缺料物料`:物料编码以 `20.30.` 开头的记录视为减速器供应约束。
AR836 已在内部按下列口径把订单数量换算为排产和 BOM 需求:
```text
成品缺口 = max(订单需求 - 净可用成品库存, 0)
本次排产量 = ceil(成品缺口 / 95% / 5) × 5
```
AR836 根据该排产量、BOM 用量、存量需求和当前供应判定减速器是否进入缺料明细。AM516 不重复实现 95% 合格率和 5 台取整。
## 推荐门禁
```text
若 整机可用库存 >= 本次需求数量 -> 保留
否则,若 缺料明细缺失或不可读 -> 保守剔除
否则,若 缺料明细中存在 20.30.* 物料 -> 剔除
否则 -> AR836 未发现减速器供应约束,保留
```
被剔除的生成 LF 候选不出现在关节模组交期预估报告、不可用候选、最快交期比较、现货候选或候选统计中。
原始询单型号本身为 LF 时也使用同一判断口径:整机库存已覆盖需求时正常答复交期;整机库存不足且 AR836 识别到 `20.30.*` 减速器缺料时,原型号仍展示,但不答复算法交期,并在原型号分析中写明“来福减速器后续需求需AR516核实,交期以人工答复为准”。
## 当前接口的边界
减速器未进入缺料明细时,当前接口不返回匹配减速器编码和确切库存。本版也不具备销售订单待锁库/待预留的二次扣减、逾期 30 天订单提醒能力;这些需要 AR836 后续增加数据后才能严格实现。
@@ -215,3 +215,24 @@ AI 生成推荐型号时,应按以下顺序判断:
| 2 | 被剔除型号 | 不推荐 | 剔除项 | 违反强约束或出现中约束降级 | 不进入候选交期计算 | | 2 | 被剔除型号 | 不推荐 | 剔除项 | 违反强约束或出现中约束降级 | 不进入候选交期计算 |
AI 输出中不得使用“已替代”“已承诺”“可直接交付”等确定性表述;应使用“候选型号”“推荐理由”“需确认差异”“需 AR516 复核”等内部候选表述。 AI 输出中不得使用“已替代”“已承诺”“可直接交付”等确定性表述;应使用“候选型号”“推荐理由”“需确认差异”“需 AR516 复核”等内部候选表述。
---
## 15. 来福减速器存量清仓门禁(2026-11-27补充)
来福减速器后续不再采购,因此 `(Vx)` 来福候选不能只凭型号配置相似和预测交期进入报告。
对每个来福候选读取 AR836 当前返回的:
```text
data.库存信息.可用库存(扣除了待产数量)
data.采购信息.缺料明细[].缺料物料
```
- 整机可用库存覆盖需求:保留候选。
- 整机库存不足,且缺料明细中出现 `20.30.*` 减速器物料:剔除候选。
- 整机库存不足,但 AR836 按 95% 合格率、5 台取整及 BOM 用量核算后未返回减速器供应约束:保留候选。
- 缺料明细缺失或不可读:保守剔除。
- 被剔除型号不进入交期报告、最快交期比较或不可用候选清单。
- 原始询单型号为 LF 时,整机库存覆盖需求则正常答复;整机库存不足且识别到 `20.30.*` 减速器缺料时,不答复该原型号的算法交期,原型号分析固定提示“来福减速器后续需求需AR516核实,交期以人工答复为准”。
- 当前接口无法在减速器不缺料时单独展示匹配编码和确切库存,也无法实现销售订单待锁库/待预留二次扣减及逾期 30 天提醒。
@@ -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`. - 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. - 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. - 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. - 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. - 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. - 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,20 @@ 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. final batch explicitly states that all rule candidates have been queried.
- Missing or unsupported models count as queried positions and remain summarized - Missing or unsupported models count as queried positions and remain summarized
under `不可用候选`; do not silently skip them to pull later candidates forward. 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 `data.库存信息.可用库存(扣除了待产数量)` and `data.采购信息.缺料明细` from the current AR836 response.
- AR836 owns the 95% yield, five-unit rounding and BOM-demand calculation. AM516 must not reproduce a different quantity formula.
- If finished-product available inventory covers the original demand, retain the candidate.
- Otherwise reject when the shortage list is missing/unreadable or contains any material code beginning `20.30.`; retain when the readable list contains no such reducer constraint.
- Rejected LF candidates are omitted from the report, fastest comparison, candidate counts and `不可用候选`.
- Do not claim that the current response proves the matched reducer code or exact reducer stock when no reducer shortage record is returned.
- Apply the same evidence rule when the original input model is LF. If finished-product stock covers demand, reply normally. If stock is insufficient and AR836 returns a `20.30.*` reducer shortage, keep the original model visible but suppress its API lead time and show exactly `来福减速器后续需求需AR516核实,交期以人工答复为准` under original-model analysis.
## Unavailable Result Reasons ## Unavailable Result Reasons
@@ -195,7 +209,7 @@ Use this field order for a successful Feishu report:
1. {model}({candidate type and reducer brand}) 1. {model}({candidate type and reducer brand})
- 需求数量:{input quantity}台 - 需求数量:{input quantity}台
- AM516预测交期:{API workdays}个工作日,最终交货日期:{API final delivery date} - AM516预测交期:{API workdays}个工作日,最终交货日期:{API final delivery date}
- 可用库存/覆盖情况:{summary-level inventory and coverage only} - 可用库存/覆盖情况:整机可用库存{AR836 available inventory}台({coverage statement})
- 主导因素:{main factor} - 主导因素:{main factor}
- 推荐理由:{rule-based recommendation reason} - 推荐理由:{rule-based recommendation reason}
- 差异项:{field changes formatted as `字段 原值→新值`; join multiple changes with `;`, for example `编码器 HS→HM;品牌 DZ→LF`} - 差异项:{field changes formatted as `字段 原值→新值`; join multiple changes with `;`, for example `编码器 HS→HM;品牌 DZ→LF`}
+87 -12
View File
@@ -180,6 +180,44 @@ class CandidateUnavailableError(RuntimeError):
pass pass
LF_MANUAL_REVIEW_MESSAGE = "来福减速器后续需求需AR516核实,交期以人工答复为准"
def is_lf_model(model: str) -> bool:
match = MODEL_PATTERN.fullmatch(model)
return bool(match and match.group("bracket") == "(")
def lf_reducer_shortage_detected(model: str, details: dict[str, Any]) -> bool:
"""Return whether an LF model still needs production and AR836 reports reducer shortage."""
if not is_lf_model(model):
return False
available_inventory = details.get("available_inventory")
requested_quantity = details.get("requested_quantity")
if available_inventory is None or requested_quantity is None:
return False
return available_inventory < requested_quantity and bool(details.get("reducer_shortages"))
def lf_stock_gate_reason(model: str, details: dict[str, Any]) -> str | None:
"""Use the current AR836 response to gate generated LF candidates."""
if not is_lf_model(model):
return None
available_inventory = details.get("available_inventory")
requested_quantity = details.get("requested_quantity")
if available_inventory is None or requested_quantity is None:
return "接口未返回可核验的整机可用库存"
if available_inventory >= requested_quantity:
return None
if details.get("shortage_data_available") is not True:
return "接口未返回可核验的缺料明细"
if lf_reducer_shortage_detected(model, details):
return "整机库存未覆盖需求且AR836返回减速器供应约束"
return None
def validate_demand_quantity(quantity: int) -> None: def validate_demand_quantity(quantity: int) -> None:
"""Reject invalid demand before calling the controlled API.""" """Reject invalid demand before calling the controlled API."""
if isinstance(quantity, bool) or not isinstance(quantity, int) or quantity <= 0: if isinstance(quantity, bool) or not isinstance(quantity, int) or quantity <= 0:
@@ -755,16 +793,21 @@ def lead_time_details(
) )
purchase_info = data.get("采购信息") purchase_info = data.get("采购信息")
shortages = purchase_info.get("缺料明细") if isinstance(purchase_info, dict) else None shortages = purchase_info.get("缺料明细") if isinstance(purchase_info, dict) else None
if has_bom is False: shortage_data_available = has_bom is not False and isinstance(shortages, list)
evidence_lines = ["- 缺料/BOM摘要:API未返回有效BOM,需补充数据源。"] reducer_shortages = (
elif isinstance(shortages, list) and shortages: [
reducer_shortages = [
item item
for item in shortages for item in shortages
if isinstance(item, dict) if isinstance(item, dict)
and isinstance(item.get("缺料物料"), str) and isinstance(item.get("缺料物料"), str)
and item["缺料物料"].startswith("20.30.") and item["缺料物料"].startswith("20.30.")
] ]
if isinstance(shortages, list)
else []
)
if has_bom is False:
evidence_lines = ["- 缺料/BOM摘要:API未返回有效BOM,需补充数据源。"]
elif isinstance(shortages, list) and shortages:
evidence_lines = [shortage_material_names_line(shortages)] evidence_lines = [shortage_material_names_line(shortages)]
real_shortage_key = ( real_shortage_key = (
"真实缺料数量(每套需求×订单数量 + 存量需求数量 − 库存数量 − 待检数量 − 在途数量)" "真实缺料数量(每套需求×订单数量 + 存量需求数量 − 库存数量 − 待检数量 − 在途数量)"
@@ -804,6 +847,9 @@ def lead_time_details(
"available_inventory": ( "available_inventory": (
available_inventory if isinstance(available_inventory, (int, float)) else None available_inventory if isinstance(available_inventory, (int, float)) else None
), ),
"requested_quantity": requested_quantity,
"shortage_data_available": shortage_data_available,
"reducer_shortages": reducer_shortages,
"full_coverage": full_coverage, "full_coverage": full_coverage,
"evidence_lines": evidence_lines, "evidence_lines": evidence_lines,
"timestamp": timestamp, "timestamp": timestamp,
@@ -813,7 +859,12 @@ def lead_time_details(
def overall_judgment_lines(candidates: list[dict[str, Any]]) -> list[str]: def overall_judgment_lines(candidates: list[dict[str, Any]]) -> list[str]:
available = [candidate for candidate in candidates if candidate["details"]["has_lead_time"]] available = [
candidate
for candidate in candidates
if candidate["details"]["has_lead_time"]
and not candidate.get("manual_lf_review")
]
if not available: if not available:
return [ return [
"- 现货候选:无法判断", "- 现货候选:无法判断",
@@ -848,10 +899,15 @@ def overall_judgment_lines(candidates: list[dict[str, Any]]) -> list[str]:
def candidate_report_lines(candidate: dict[str, Any], quantity: int) -> list[str]: def candidate_report_lines(candidate: dict[str, Any], quantity: int) -> list[str]:
details = candidate["details"] details = candidate["details"]
lead_time_lines = (
[f"- 原型号分析:{LF_MANUAL_REVIEW_MESSAGE}"]
if candidate.get("manual_lf_review")
else [f"- {details['prediction']}"]
)
return [ return [
f"{candidate['index']}. {candidate['model']}({candidate['type']})", f"{candidate['index']}. {candidate['model']}({candidate['type']})",
f"- 需求数量:{quantity}台", f"- 需求数量:{quantity}台",
f"- {details['prediction']}", *lead_time_lines,
f"- 可用库存/覆盖情况:{details['inventory']}", f"- 可用库存/覆盖情况:{details['inventory']}",
f"- 主导因素:{details['main_factor']}", f"- 主导因素:{details['main_factor']}",
f"- 推荐理由:{candidate['reason']}", f"- 推荐理由:{candidate['reason']}",
@@ -952,7 +1008,14 @@ def render_record(
details = candidate["details"] details = candidate["details"]
inventory = details.get("available_inventory") inventory = details.get("available_inventory")
inventory_text = f"{inventory:g}台" if isinstance(inventory, (int, float)) else "—" inventory_text = f"{inventory:g}台" if isinstance(inventory, (int, float)) else "—"
api_status = "✅ 现货" if details.get("full_coverage") is True else "✅ 返回" manual_lf_review = candidate.get("manual_lf_review") is True
api_status = (
"⚠️ 人工复核"
if manual_lf_review
else "✅ 现货"
if details.get("full_coverage") is True
else "✅ 返回"
)
row = [ row = [
record_order, record_order,
record_time, record_time,
@@ -960,7 +1023,7 @@ def render_record(
candidate["type"], candidate["type"],
candidate["difference"], candidate["difference"],
api_status, api_status,
details.get("prediction_value") or "—", "人工答复" if manual_lf_review else details.get("prediction_value") or "—",
inventory_text, inventory_text,
details.get("main_factor") or "—", details.get("main_factor") or "—",
] ]
@@ -1035,6 +1098,7 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
f"原因:{baseline['unavailable_reason']}\n" f"原因:{baseline['unavailable_reason']}\n"
"处理建议:请按上述提示核对;如确认信息无误,请联系维护人员核查。" "处理建议:请按上述提示核对;如确认信息无误,请联系维护人员核查。"
) )
manual_lf_review = lf_reducer_shortage_detected(request.model, baseline)
candidates.append( candidates.append(
{ {
"index": 1, "index": 1,
@@ -1042,6 +1106,7 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
"model": request.model, "model": request.model,
"type": "原型号,DZ" if "[" in request.model else "原型号,LF", "type": "原型号,DZ" if "[" in request.model else "原型号,LF",
"details": baseline, "details": baseline,
"manual_lf_review": manual_lf_review,
"reason": "原始需求基准,用于交期测算与候选比较。", "reason": "原始需求基准,用于交期测算与候选比较。",
"difference": "无", "difference": "无",
"confirmation": "无型号差异;需确认正式交付节点和承诺边界。", "confirmation": "无型号差异;需确认正式交付节点和承诺边界。",
@@ -1049,6 +1114,7 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
) )
unavailable: list[dict[str, 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]: def query_candidate(spec: dict[str, str]) -> tuple[dict[str, str], dict[str, Any] | None]:
try: try:
@@ -1060,6 +1126,10 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
**spec, **spec,
"unavailable_reason": details["unavailable_reason"], "unavailable_reason": details["unavailable_reason"],
}, None }, 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 return spec, details
if candidate_specs: if candidate_specs:
@@ -1072,7 +1142,10 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
for future in concurrent.futures.as_completed(future_map): for future in concurrent.futures.as_completed(future_map):
spec, details = future.result() spec, details = future.result()
if details is None: if details is None:
unavailable.append(spec) if "stock_gate_reason" in spec:
stock_gate_excluded.append(spec)
else:
unavailable.append(spec)
continue continue
candidates.append({**spec, "details": details}) candidates.append({**spec, "details": details})
@@ -1084,6 +1157,7 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
candidates[candidate_start:], key=lambda item: candidate_order[item["model"]] candidates[candidate_start:], key=lambda item: candidate_order[item["model"]]
) )
unavailable.sort(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:]: for candidate in candidates[candidate_start:]:
candidate["record_order"] = candidate_order[candidate["model"]] + 2 candidate["record_order"] = candidate_order[candidate["model"]] + 2
candidate["index"] = candidate["record_order"] candidate["index"] = candidate["record_order"]
@@ -1107,13 +1181,14 @@ def build_report(request: RequestInput, candidate_offset: int = 0) -> str:
queried_end = candidate_offset + len(candidate_specs) queried_end = candidate_offset + len(candidate_specs)
remaining_count = len(all_candidate_specs) - queried_end remaining_count = len(all_candidate_specs) - queried_end
if is_initial_batch: if is_initial_batch:
visible_candidate_count = len(candidates) - 1
batch_scope = ( batch_scope = (
f"本次先推荐{len(candidate_specs)}个候选型号(原型号另作基准)" f"本次展示{visible_candidate_count}个符合门槛的候选型号(原型号另作基准)"
if remaining_count if remaining_count
else f"本次已推荐全部{len(candidate_specs)}个候选型号(原型号另作基准)" else f"本次已展示全部{visible_candidate_count}个符合门槛的候选型号(原型号另作基准)"
) )
else: else:
batch_scope = f"本次继续推荐第{candidate_offset + 1}-{queried_end}个候选型号" batch_scope = f"本次继续展示{len(candidates)}个符合门槛的候选型号"
if remaining_count: if remaining_count:
batch_scope += f";尚有{remaining_count}个规则候选未查询" batch_scope += f";尚有{remaining_count}个规则候选未查询"
else: else:
+184 -8
View File
@@ -38,13 +38,20 @@ def successful_payload() -> dict[str, object]:
"AM516最终交货日期": "2026-09-01", "AM516最终交货日期": "2026-09-01",
"AM516主导因素": "现货", "AM516主导因素": "现货",
}, },
"库存信息": {"可用库存(扣除了待产数量)": 100}, "库存信息": {
"可用库存(扣除了待产数量)": 100,
},
"BOM信息": {"是否有BOM(False则需提醒无BOM)": True}, "BOM信息": {"是否有BOM(False则需提醒无BOM)": True},
"采购信息": {"缺料明细": []}, "采购信息": {"缺料明细": []},
} }
} }
def set_stock(payload: dict[str, object], stock: object, demand: int) -> None:
inventory = payload["data"]["库存信息"]
inventory["可用库存(扣除了待产数量)"] = stock
def message_event(message_id: str, chat_id: str, open_id: str) -> SimpleNamespace: def message_event(message_id: str, chat_id: str, open_id: str) -> SimpleNamespace:
return SimpleNamespace( return SimpleNamespace(
event=SimpleNamespace( event=SimpleNamespace(
@@ -420,7 +427,7 @@ class OriginalDemandQueryTests(unittest.TestCase):
def test_partial_full_and_zero_stock_do_not_change_api_quantity(self) -> None: 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)): for demand, stock in ((12, 10), (8, 5), (24, 6), (24, 0), (24, 24), (24, 30), (24, -2), (5, 1)):
payload = successful_payload() payload = successful_payload()
payload['data']['库存信息']['可用库存(扣除了待产数量)'] = stock set_stock(payload, stock, demand)
request = bridge.RequestInput('eRob70F50I-FHM-18ET[V4]', demand) request = bridge.RequestInput('eRob70F50I-FHM-18ET[V4]', demand)
with ( with (
self.subTest(demand=demand, stock=stock), self.subTest(demand=demand, stock=stock),
@@ -434,7 +441,7 @@ class OriginalDemandQueryTests(unittest.TestCase):
def test_screenshot_regression_passes_twelve_to_controlled_script(self) -> None: def test_screenshot_regression_passes_twelve_to_controlled_script(self) -> None:
request = bridge.RequestInput('eRob70F50I-FHM-18ET[V4]', 12) request = bridge.RequestInput('eRob70F50I-FHM-18ET[V4]', 12)
payload = successful_payload() payload = successful_payload()
payload['data']['库存信息']['可用库存(扣除了待产数量)'] = 10 set_stock(payload, 10, 12)
payload['data']['交期汇总'].update(AM516工作日交期=8, AM516最终交货日期='2026-10-27', AM516主导因素='生产') payload['data']['交期汇总'].update(AM516工作日交期=8, AM516最终交货日期='2026-10-27', AM516主导因素='生产')
completed = SimpleNamespace(stdout=bridge.json.dumps(payload), stderr='', returncode=0) completed = SimpleNamespace(stdout=bridge.json.dumps(payload), stderr='', returncode=0)
with ( with (
@@ -474,7 +481,7 @@ class OriginalDemandQueryTests(unittest.TestCase):
stocks = dict(zip(models, [6, 0, 24, 20, 30])) stocks = dict(zip(models, [6, 0, 24, 20, 30]))
def query(r): def query(r):
payload = successful_payload() payload = successful_payload()
payload['data']['库存信息']['可用库存(扣除了待产数量)'] = stocks[r.model] set_stock(payload, stocks[r.model], 24)
return payload return payload
with ( with (
mock.patch.object(bridge, 'run_controlled_query', side_effect=query) as run, mock.patch.object(bridge, 'run_controlled_query', side_effect=query) as run,
@@ -490,7 +497,7 @@ class OriginalDemandQueryTests(unittest.TestCase):
def test_missing_or_invalid_stock_is_unknown_without_overriding_api_forecast(self) -> None: 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')): for stock in (None, True, '6', 1.5, float('nan'), float('inf')):
payload = successful_payload() payload = successful_payload()
payload['data']['库存信息']['可用库存(扣除了待产数量)'] = stock set_stock(payload, stock, 24)
with ( with (
self.subTest(stock=stock), self.subTest(stock=stock),
mock.patch.object(bridge, 'run_controlled_query', return_value=payload) as query, mock.patch.object(bridge, 'run_controlled_query', return_value=payload) as query,
@@ -504,7 +511,7 @@ class OriginalDemandQueryTests(unittest.TestCase):
def test_forecast_preserves_api_date_and_materials(self) -> None: def test_forecast_preserves_api_date_and_materials(self) -> None:
payload = successful_payload() payload = successful_payload()
payload['data']['库存信息']['可用库存(扣除了待产数量)'] = 10 set_stock(payload, 10, 12)
payload['data']['交期汇总'].update(AM516工作日交期=8, AM516最终交货日期='2026-10-27') payload['data']['交期汇总'].update(AM516工作日交期=8, AM516最终交货日期='2026-10-27')
payload['data']['采购信息']['缺料明细'] = [{'物料名称': '测算物料'}] payload['data']['采购信息']['缺料明细'] = [{'物料名称': '测算物料'}]
with mock.patch.object(bridge, 'run_controlled_query', return_value=payload) as query: with mock.patch.object(bridge, 'run_controlled_query', return_value=payload) as query:
@@ -526,6 +533,175 @@ class OriginalDemandQueryTests(unittest.TestCase):
record.assert_not_called() record.assert_not_called()
class LfStockGateTests(unittest.TestCase):
LF_MODEL = "eRob70F50I-FHM-18ET(V4)"
def details(
self,
demand: int,
stock: int,
shortages: list[dict[str, object]] | None,
) -> dict[str, object]:
payload = successful_payload()
set_stock(payload, stock, demand)
if shortages is None:
del payload["data"]["采购信息"]["缺料明细"]
else:
payload["data"]["采购信息"]["缺料明细"] = shortages
return bridge.lead_time_details(payload, demand)
def test_full_finished_goods_stock_passes_even_with_reducer_shortage(self) -> None:
details = self.details(
demand=10,
stock=10,
shortages=[{"缺料物料": "20.30.00999"}],
)
self.assertEqual(details["available_inventory"], 10)
self.assertIsNone(bridge.lf_stock_gate_reason(self.LF_MODEL, details))
def test_partial_stock_passes_when_ar836_returns_no_reducer_constraint(self) -> None:
details = self.details(demand=10, stock=3, shortages=[])
self.assertIsNone(bridge.lf_stock_gate_reason(self.LF_MODEL, details))
def test_partial_stock_and_reducer_shortage_is_excluded(self) -> None:
details = self.details(
demand=10,
stock=3,
shortages=[{"缺料物料": "20.30.00999"}],
)
self.assertIn(
"AR836返回减速器供应约束",
bridge.lf_stock_gate_reason(self.LF_MODEL, details),
)
def test_zero_stock_passes_when_ar836_returns_no_reducer_constraint(self) -> None:
details = self.details(demand=10, stock=0, shortages=[])
self.assertIsNone(bridge.lf_stock_gate_reason(self.LF_MODEL, details))
def test_missing_shortage_details_is_excluded_when_stock_is_partial(self) -> None:
details = self.details(demand=10, stock=3, shortages=None)
self.assertIn(
"未返回可核验的缺料明细",
bridge.lf_stock_gate_reason(self.LF_MODEL, details),
)
def test_explicit_missing_bom_is_excluded_when_stock_is_partial(self) -> None:
payload = successful_payload()
set_stock(payload, 3, 10)
payload["data"]["BOM信息"]["是否有BOM(False则需提醒无BOM)"] = False
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"]["采购信息"]["缺料明细"] = [
{"缺料物料": "20.30.00999", "物料名称": "来福减速器"}
]
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_eligible_lf_candidate_uses_current_inventory_wording(self) -> None:
details = self.details(demand=10, stock=3, shortages=[])
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.assertNotIn("减速器实际可用量", report)
def test_original_lf_with_reducer_shortage_uses_manual_reply(self) -> None:
request = bridge.RequestInput(self.LF_MODEL, 10)
def query(query_request: bridge.RequestInput) -> dict[str, object]:
payload = successful_payload()
if query_request.model == request.model:
set_stock(payload, 3, query_request.quantity)
payload["data"]["采购信息"]["缺料明细"] = [
{"缺料物料": "20.30.00999", "物料名称": "来福减速器"}
]
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)
original_section = report.split(f"1. {request.model}", 1)[1].split("\n\n", 1)[0]
self.assertIn(
"原型号分析:来福减速器后续需求需AR516核实,交期以人工答复为准",
original_section,
)
self.assertNotIn("AM516预测交期", original_section)
recorded_candidates = record.call_args.args[1]
self.assertTrue(recorded_candidates[0]["manual_lf_review"])
def test_original_lf_with_full_stock_keeps_api_lead_time(self) -> None:
payload = successful_payload()
set_stock(payload, 10, 10)
payload["data"]["采购信息"]["缺料明细"] = [
{"缺料物料": "20.30.00999", "物料名称": "来福减速器"}
]
details = bridge.lead_time_details(payload, 10)
candidate = {
"index": 1,
"model": self.LF_MODEL,
"type": "原型号,LF",
"details": details,
"manual_lf_review": bridge.lf_reducer_shortage_detected(self.LF_MODEL, details),
"reason": "原始需求基准",
"difference": "无",
"confirmation": "无",
}
report = "\n".join(bridge.candidate_report_lines(candidate, 10))
self.assertIn("AM516预测交期", report)
self.assertNotIn(bridge.LF_MANUAL_REVIEW_MESSAGE, report)
class CandidateBatchTests(unittest.TestCase): class CandidateBatchTests(unittest.TestCase):
def setUp(self) -> None: def setUp(self) -> None:
self.request = bridge.RequestInput(model="eRob70H50I-FS-18CN[V5]", quantity=10) self.request = bridge.RequestInput(model="eRob70H50I-FS-18CN[V5]", quantity=10)
@@ -550,7 +726,7 @@ class CandidateBatchTests(unittest.TestCase):
queried_models[1:], queried_models[1:],
[spec["model"] for spec in self.specs[: bridge.CANDIDATE_BATCH_SIZE]], [spec["model"] for spec in self.specs[: bridge.CANDIDATE_BATCH_SIZE]],
) )
self.assertIn("本次先推荐4个候选型号(原型号另作基准)", report) self.assertIn("本次展示4个符合门槛的候选型号(原型号另作基准)", report)
self.assertIn("可说“还有吗”“再推荐几个”“继续”等类似表达", report) self.assertIn("可说“还有吗”“再推荐几个”“继续”等类似表达", report)
self.assertNotIn(self.specs[bridge.CANDIDATE_BATCH_SIZE]["model"], report) self.assertNotIn(self.specs[bridge.CANDIDATE_BATCH_SIZE]["model"], report)
@@ -578,7 +754,7 @@ class CandidateBatchTests(unittest.TestCase):
self.assertEqual(len(queried_models), bridge.CANDIDATE_BATCH_SIZE) self.assertEqual(len(queried_models), bridge.CANDIDATE_BATCH_SIZE)
self.assertNotIn(self.request.model, queried_models) self.assertNotIn(self.request.model, queried_models)
self.assertCountEqual(queried_models, expected_models) self.assertCountEqual(queried_models, expected_models)
self.assertIn("本次继续推荐第5-8个候选型号", report) self.assertIn("本次继续展示4个符合门槛的候选型号", report)
for model in expected_models: for model in expected_models:
self.assertIn(model, report) self.assertIn(model, report)
for model in [spec["model"] for spec in self.specs[:4]]: for model in [spec["model"] for spec in self.specs[:4]]:
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.