feat(shipping-notice): 库存缺口料号兜底自动放行并新增料号可用量列

- 匹配器按料号二次汇总 part_available_qty 随行级匹配事实持久化(新列,迁移 0a575f3a)
- 缺口行料号总库存满足需求时系统自动放行,复用人工放行同一落库/审计/门禁链路,证据按预约优先→料号兜底自动带出
- 前端库存匹配表原「可用数量」列改为「预约数量」,其后新增「可用数量」(料号总库存)列
- DSV 连接器防误点「忘记密码」链接并参数化料号报表取数,库存 worker 按料号查询配套
- 收料就绪与来源状态联动调整;casdoor 未识别认证错误日志保留原始异常堆栈
- 同步门禁/投影/持久化测试、调拨卡片文案四语言与文档
This commit is contained in:
hugo committed 2026-10-11 17:42:55 +08:00
1 parent 4e97553f42
commit 386f93108c
62 files changed
+4000 -219

No files matched your search

@@ -793,6 +793,32 @@ def retry_source_rpa_api(source_code: str):
}, status=202)
@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"])
@require_transfer_permission
def retry_sources_rpa_batch_api():
"""批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
"""
payload = request.get_json(silent=True) or {}
source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()]
if not source_codes:
raise ValidationError("source_codes is required")
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch
outcome = trigger_receipt_rpa_batch(
source_codes=source_codes,
business_date=str(business_date_now()),
reason="transfer_retry_receipt",
)
return _ok(outcome)
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
@require_transfer_permission
def backlog_api():
@@ -104,6 +104,9 @@ class ShippingNoticeLineInventoryMatch(Base):
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
+6 -1
View File
@@ -97,7 +97,12 @@ def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
)
if 'invalid or expired casdoor state' in lowered_raw:
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
# [STEP 2] 未识别错误必须保留原始异常堆栈,否则本地换票后的崩溃会被吞成一行 payload={}。
current_app.logger.warning(
'[casdoor] unmapped auth error context=%s payload=%s source=%r',
context, data, source,
exc_info=source if isinstance(source, BaseException) else None,
)
raise AppError(
code='CASDOOR_AUTH_FAILED',
message='Authentication failed, please try again',
@@ -10,7 +10,7 @@ from __future__ import annotations
from dataclasses import dataclass
from datetime import date, datetime
from decimal import Decimal
from decimal import Decimal, InvalidOperation
from typing import Any, Iterable, Mapping
from app.core.errors import AppError
@@ -59,16 +59,26 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
rows.append({"row_no": row_no, "reason": reason})
def _is_unreceived_row(date_value: Any) -> bool:
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool:
"""判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实:
① 未收料在途 ASN(Date Received 空、Qty Received 0);
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与匹配;
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章);
③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。
收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程
抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。
"""
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()):
return True
try:
# 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。
return Decimal(str(quantity_raw)) == 0
except (InvalidOperation, ValueError, TypeError):
# 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由
# validate_receipt_quantity 按非法数量阻断,不在此吞掉。
return not str(quantity_raw or "").strip()
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
@@ -174,7 +184,7 @@ def _parse_rows(
if row_source and row_source.upper() != str(source_code).upper():
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
continue
if _is_unreceived_row(receipt_date_value):
if _is_unusable_receipt_row(receipt_date_value, quantity_raw):
continue
try:
receipt_date = parse_date(receipt_date_value)
@@ -202,5 +212,8 @@ def _parse_rows(
unit=str(row.get("unit") or "").strip(),
))
if errors:
raise ReceiptFileSchemaError(rows=errors)
# 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message
# 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。
summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3])
raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors)
return parsed
@@ -1,6 +1,6 @@
"""在途调拨真实收料 RPA 触发服务。
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
@@ -8,11 +8,14 @@
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Callable
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
@@ -151,3 +154,117 @@ def trigger_receipt_rpa(
unit.trigger_snapshot_json = unit_payload
db.session.commit()
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
def trigger_receipt_rpa_batch(
*,
source_codes: list[str],
business_date: str,
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
Args:
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
business_date: 业务日期。
reason: 触发原因(写入 trigger payload)。
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
Returns:
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
ok=本次请求产生了主效果(写盘成功,或无需写盘且全部来源经本地重解析恢复);
triggered=是否写了 batch trigger;results 逐来源携带真实结果
(触发:{source_code, ok: true};重解析:{..., reparsed: true, file_status};
跳过:{source_code, ok: false, error_code, error_message})。
"""
from app import db
from app.models import ShippingReceiptRpaUnitRun
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
results: list[dict[str, Any]] = []
units: list[ShippingReceiptRpaUnitRun] = []
unit_payloads: list[dict[str, Any]] = []
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
for code in codes:
status = resolve_source_file_status(source_code=code)
if status.get('file_status') == 'parse_failed' and status.get('file_sha256'):
sync_and_commit_for_callback(
source_code=code, business_date=business_date, now=datetime.utcnow(),
)
status = resolve_source_file_status(source_code=code)
results.append({
'source_code': code,
'ok': status.get('file_status') == 'ready',
'reparsed': True,
'file_status': status.get('file_status'),
})
continue
try:
unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason))
except RuntimeError as exc:
results.append({
'source_code': code, 'ok': False,
'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc),
})
if not unit_payloads:
# 无可触发来源:全部经重解析恢复 → 请求已达成目的;否则如实报无可用来源。
reparse_recovered = any(item.get('reparsed') and item.get('ok') for item in results)
db.session.commit()
if reparse_recovered:
return {"ok": True, "triggered": False, "results": results}
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results}
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
for payload in unit_payloads:
unit = ShippingReceiptRpaUnitRun(
inventory_source_id=payload['inventory_source_id'],
source_code=payload['source_code'],
connector_type=payload['connector_type'],
warehouse_id=payload.get('warehouse_id'),
callback_id=payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(payload['config_snapshot']),
)
db.session.add(unit)
units.append(unit)
db.session.flush()
for unit, payload in zip(units, unit_payloads):
payload['unit_run_id'] = unit.id
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, unit_payloads, payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'business_date': business_date,
'reason': reason,
'source_codes': [payload['source_code'] for payload in unit_payloads],
})
if not path:
for unit in units:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
db.session.commit()
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results}
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
for unit, payload in zip(units, unit_payloads):
unit.trigger_snapshot_json = payload
results.append({'source_code': unit.source_code, 'ok': True})
db.session.commit()
return {"ok": True, "triggered": True, "trigger_path": path, "results": results}
@@ -26,7 +26,10 @@ from app.services.in_transit_transfer.receipt_file_gate import (
)
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障,
# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
NO_DATA_UNIT_STATUSES = ('empty',)
def resolve_source_file_status(*, source_code: str) -> dict:
@@ -37,7 +40,7 @@ def resolve_source_file_status(*, source_code: str) -> dict:
Returns:
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'};
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
仍带 file_no/file_sha256 便于诊断与前端提示。
"""
@@ -84,6 +87,9 @@ def resolve_source_file_status(*, source_code: str) -> dict:
.order_by(ShippingReceiptRpaUnitRun.id.desc())
.first()
)
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
# 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
@@ -1277,6 +1277,14 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
)
# 行级匹配只持久化当前 LineMatch;OT 不再保存库存匹配聚合列或行结果缓存。
_merge_line_inventory_resolutions(task, match_payload, snapshot_line_id=int(snapshot.lines[orig_idx].id) if snapshot is not None and orig_idx < len(snapshot.lines) else None)
# [BE-料号兜底自动放行] 行事实落库后、聚合重算【前】执行(与 match_inventory 同款钩子):
# 料号总量满足需求的缺口行由系统自动放行,使下方聚合重算把放行行计入满足、
# 行级重匹配可直接落 MATCHED_FULFILLABLE;重入安全性说明见 match_inventory 钩子注释。
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
auto_release_part_fallback_shortages,
)
auto_release_part_fallback_shortages(task)
line_results = list(match_payload.get('line_results') or [])
from app.services.shipping_notice.reservation_service import record_inventory_verification
@@ -1778,6 +1786,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None,
matching_rule_version='stp_line_v2',
)
# [BE-料号兜底自动放行] 行事实落库后、聚合与 match_completed 判定【前】执行:
# 料号总量满足需求的缺口行由系统自动放行(满足即放行,非仅可放行),使随后的
# 聚合重算与满足性判定把放行行计入满足、任务可直接落 MATCHED_FULFILLABLE。
# 重入安全:匹配跑在 AutoProgress Gate 执行器事务内时,submit_auto_progress 按
# 「任务唯一活动 Job + 活动 Attempt 复用」幂等,不会重复入队或自触发;auto fulfill
# Job 重复入队由协调器 eligible+幂等键吸收(与既有匹配路径的多入队行为一致)。
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
auto_release_part_fallback_shortages,
)
auto_release_part_fallback_shortages(task)
# 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
# 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
match_status, shortages = _recompute_task_match_aggregate(task)
@@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_persistence.py
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
供后续投影层与自动放行服务读取。
"""
from __future__ import annotations
@@ -277,6 +279,12 @@ def persist_line_inventory_match_facts(
required_qty=str(required) if required is not None else None,
available_qty=str(available) if available is not None else None,
shortage_qty=str(shortage) if shortage is not None else None,
# 料号兜底总量(Task 1 匹配器下发):字符串化落列;无键/None → NULL,
# BE-5 / not_found 分支不篡改,直接取匹配器原值。
part_available_qty=(
str(result['part_available_qty'])
if result.get('part_available_qty') is not None else None
),
reservation_id=rsv,
part_number=pn,
unit=unit_value,
@@ -342,6 +350,11 @@ def persist_line_inventory_match_facts(
existing.required_qty = str(required) if required is not None else None
existing.available_qty = str(available) if available is not None else None
existing.shortage_qty = str(shortage) if shortage is not None else None
# 更新分支同样以最新匹配结果刷新兜底总量;键缺失 → NULL,不残留旧值。
existing.part_available_qty = (
str(result['part_available_qty'])
if result.get('part_available_qty') is not None else None
)
existing.reservation_id = rsv
existing.part_number = pn
existing.unit = unit_value
@@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_projection.py
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
ready+not_found→available=0;result_missing 不得转 0;
part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None,
不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算);
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
@@ -562,6 +564,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'required_qty': row.required_qty,
'available_qty': row.available_qty,
'shortage_qty': row.shortage_qty,
'part_available_qty': getattr(row, 'part_available_qty', None),
'reservation_id': row.reservation_id,
'part_number': row.part_number,
'unit': row.unit,
@@ -661,6 +664,7 @@ def project_line_inventory_view(
'inventory_status': None,
'match_result': None,
'available_qty': None,
'part_available_qty': None,
'shortage_qty': None,
'is_shortage': False,
'display_available': 'pending',
@@ -699,6 +703,12 @@ def project_line_inventory_view(
required_qty=required_qty if required_qty is not None else fact.get('required_qty'),
available_qty=fact.get('available_qty'),
)
# [STEP] 料号兜底口径:仅库存就绪时透出料号总可用量(与 available_qty 同门控);
# 「是否可兜底放行」的判定由自动放行服务基于行事实现算,投影层不下发派生布尔。
part_total = _parse_qty(fact.get('part_available_qty'))
part_available_value = (
str(part_total) if inventory_status == STATUS_READY and part_total is not None else None
)
user_status = project_user_line_status(
inventory_status=inventory_status,
match_result=match_result,
@@ -770,6 +780,7 @@ def project_line_inventory_view(
'inventory_status': inventory_status,
'match_result': match_result,
'available_qty': qty['available_qty'],
'part_available_qty': part_available_value,
'shortage_qty': qty['shortage_qty'],
'is_shortage': bool(qty['is_shortage']),
'display_available': qty['display_available'],
@@ -30,6 +30,9 @@ from app.models import (
ShippingOrderTask,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.line_inventory_match_persistence import (
resolve_review_case_for_task,
)
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
@@ -317,8 +320,14 @@ def _shortage_release_required_fields(
line_index: int | None,
inventory_snapshot_id: int | None,
inventory_source_code: str | None,
) -> list[dict[str, str]]:
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。"""
) -> tuple[list[dict[str, Any]], str]:
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。
Returns:
(fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读,
其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'},
'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。
"""
if line_index is None:
raise ConflictError(
'Current line inventory evidence is unavailable',
@@ -371,7 +380,8 @@ def _shortage_release_required_fields(
and str(item.get('source_key') or '').strip().isdigit()
}
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels)
# 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot'
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
expected = [
@@ -395,6 +405,24 @@ def _shortage_release_required_fields(
dict(row) for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
]
evidence_scope = 'inventory_snapshot'
if not candidates:
# [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行,
# 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键;
# 匹配方案不含料号键则维持空候选(全人工补录,fail-closed)。
part_field_ids = {
int(field_id) for field_id, _value in expected
if str(field_id).strip().isdigit()
and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number'
}
if part_field_ids:
candidates = [
dict(row) for row in inventory_lines
if all(_match_text(row.get(str(field_id))) == value
for field_id, value in expected if int(field_id) in part_field_ids)
]
if candidates:
evidence_scope = 'part_fallback'
field_ids = {
int(str(item.get('source_key') or '').strip())
for item in mappings
@@ -411,7 +439,7 @@ def _shortage_release_required_fields(
mappings=mappings,
candidates=candidates,
field_labels=labels,
)
), evidence_scope
def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[str, str]]:
@@ -429,7 +457,7 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
def _sync_confirmed_task_fulfillment_gates(
*,
case: ShippingOrderReviewCase,
actor_id: int,
actor_id: int | None,
trigger: str = 'inventory_shortage_released',
) -> None:
"""
@@ -924,7 +952,8 @@ def project_review_case_line_decisions(
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
if release_line_index is None:
release_line_index = draft_line.get('_line_index')
release_template_fields = _shortage_release_required_fields(
# scope 仅在 decide 落库时写入审计快照;投影契约本期不新增字段。
release_template_fields, _evidence_scope = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=release_snapshot_id,
@@ -1076,6 +1105,185 @@ def build_inventory_issue_fallback(
}
def _apply_shortage_line_release(
task: ShippingNotice,
line_index: int,
release_field_values: dict[str, Any],
*,
evidence_scope: str | None = None,
actor_type: str = 'user',
actor_id: int | None = None,
auto_release: bool = False,
case: ShippingOrderReviewCase | None = None,
reason: str | None = None,
) -> ShippingOrderReviewLineDecision:
"""
人工 decide 与缺口自动放行共用的短缺放行执行体:解析证据字段、校验补录、
版本化落库、同步正式 OT 门禁并写审计。
核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。
证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中
按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 +
人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并
同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过,
本执行体不重复校验放行资格。
Args:
task: 正式 OT 聚合根(含 order_snapshot_id;自动放行来自匹配钩子,
人工 decide 来自 case.confirmed_task_id)。
line_index: 目标行号(0-based,与行匹配事实 line_index 同口径)。
release_field_values: 人工补录值(decide)或自动带出全量值(自动放行);
校验后与模板字段合并为全量值字典落库。
evidence_scope: 调用方已解析的证据范围;None 时按行事实重新解析
(人工 decide 路径,由本执行体统一解析避免双重查询语义分叉)。
actor_type: 决定来源('user' 人工 / 'system' 自动放行),写入 decision_source。
actor_id: 操作人(人工为操作用户;自动为触发匹配的用户,可为 None)。
auto_release: True 时在决定与审计快照标记 auto_release(系统自动放行溯源)。
case: 可选;人工 decide 已加载的可写 Case。缺省时按 confirmed_task_id 反查。
reason: 可选人工放行原因;自动放行为 None。
Returns:
新建的 ShippingOrderReviewLineDecision(已 flush、含主键)。
Raises:
ConflictError: Case/草稿行缺失、证据不可解析或人工必填字段缺失。
"""
release_case = case if case is not None else resolve_review_case_for_task(task)
if release_case is None or getattr(release_case, 'id', None) is None:
raise ConflictError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
draft_line_by_index = {
int(row.get('_line_index')): (key, row)
for key, row in _draft_line_map(release_case).items()
if row.get('_line_index') is not None
}
pair = draft_line_by_index.get(int(line_index))
if pair is None:
raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
key, draft_line = pair
from app.models import ShippingNoticeLineInventoryMatch
fact = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True)
.first()
if getattr(task, 'id', None) is not None else None
)
release_line_index = getattr(fact, 'line_index', None) if fact is not None else int(line_index)
release_template_fields, resolved_scope = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
)
release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot')
release_required_fields = _manual_required_release_fields(release_template_fields)
release_values = _validate_inventory_shortage_release_fields(
required_fields=release_required_fields,
supplied_values=release_field_values or {},
)
# [STEP] 落库为「自动带出 + 人工补录」全量模板字段值字典:人工提交值覆盖自动带出值
# (校验白名单仅用于必填校验,不再裁剪落库字典)。export.release_overrides_by_source_line
# 只读本字典——若仍落仅人工项,料号兜底/预约命中自动带出的字段在 Excel 证据列将为空。
manual_field_ids = {str(field.get('field_id') or '') for field in release_required_fields}
release_values = {
str(field.get('field_id') or ''): (
release_values[str(field.get('field_id') or '')]
if str(field.get('field_id') or '') in manual_field_ids
else (None if field.get('value') is None else str(field.get('value')))
)
for field in release_template_fields
}
projections = _line_projection_map(release_case)
proj = projections.get(key) or {}
from app.services.shipping_notice.order_review_workbench_projection import (
schema_fields_from_case,
)
schema_fields = schema_fields_from_case(release_case)
req_qty = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
avail_qty = _parse_qty(proj.get('available_qty'))
current = _active_decision(release_case, key)
# [STEP 1] 停用旧活动决定(放行资格与终态校验由调用方完成)。
if current is not None:
current.is_active = False
current.updated_at = datetime.utcnow()
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
row = ShippingOrderReviewLineDecision(
review_case_id=int(release_case.id),
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(release_case, key),
decision_code=DECISION_RELEASE_SHORTAGE,
decision_source=actor_type,
line_status=status,
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=str(req_qty) if req_qty is not None else None,
available_qty=str(avail_qty) if avail_qty is not None else (
str(proj.get('available_qty') or '').strip() or None
),
reservation_id=_line_reservation_id(draft_line, proj),
part_number=_line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
actor_user_id=int(actor_id) if actor_id is not None else None,
snapshot_json={
'decision_code': DECISION_RELEASE_SHORTAGE,
'decision_source': actor_type,
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'draft_line_id': key,
'release_field_values': release_values,
'release_required_fields': release_required_fields,
# 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。
'release_evidence_scope': release_evidence_scope,
**({'auto_release': True} if auto_release else {}),
},
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
# [BE-结案-豁免] 放行是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=release_case,
actor_id=actor_id,
trigger='inventory_shortage_released',
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='review_line_fulfillment_decided',
aggregate_type='order_review_case',
aggregate_id=str(release_case.case_no),
action=DECISION_RELEASE_SHORTAGE,
actor_type=actor_type,
actor_id=int(actor_id) if actor_id is not None else None,
review_case_no=str(release_case.case_no),
run_no=str(release_case.run.run_no) if release_case.run is not None else None,
metadata={
'draft_line_id': key,
'decision_code': DECISION_RELEASE_SHORTAGE,
'decision_version': int(row.decision_version),
'line_status': status,
'release_field_count': len(release_values),
**({'auto_release': True} if auto_release else {}),
},
before=_serialize_decision(current) if current is not None else None,
after=_serialize_decision(row),
source='order_review_fulfillment_decision',
)
return row
def decide_review_line_fulfillment(
*,
user_id: int,
@@ -1100,7 +1308,9 @@ def decide_review_line_fulfillment(
draft_line_id: 草稿行键。
decision_code: 决定码。
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照
release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源),
release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。
expected_draft_version: 可选草稿乐观锁。
actor_is_admin: 是否管理员(重开授权)。
@@ -1200,93 +1410,94 @@ def decide_review_line_fulfillment(
details={'draft_line_id': key},
)
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
release_template_fields = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
) if task is not None else []
release_required_fields = _manual_required_release_fields(release_template_fields)
release_values = _validate_inventory_shortage_release_fields(
required_fields=release_required_fields,
supplied_values=release_field_values or {},
)
else:
release_required_fields = []
release_values = {}
# [STEP 1] 停用旧活动决定
if current is not None:
current.is_active = False
current.updated_at = datetime.utcnow()
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(case, key),
decision_code=code,
decision_source='user',
line_status=status,
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=str(req_qty) if req_qty is not None else None,
available_qty=str(avail_qty) if avail_qty is not None else (
str(proj.get('available_qty') or '').strip() or None
),
reservation_id=_line_reservation_id(draft_line, proj),
part_number=_line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
actor_user_id=int(user_id),
snapshot_json={
'decision_code': code,
'decision_source': 'user',
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'draft_line_id': key,
'release_field_values': release_values,
'release_required_fields': release_required_fields,
},
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=case,
# [STEP] 短缺放行统一走共享执行体:证据字段解析、全量字段落库、停用旧决定、
# 门禁同步与审计均在 _apply_shortage_line_release 内完成(人工与系统自动放行
# 同一条链路,行为不变)。无 task 时上方放行资格校验已拒绝(无事实且无 RPA
# 终态失败豁免),不会到达此处。
row = _apply_shortage_line_release(
task,
release_line_index,
release_field_values or {},
actor_type='user',
actor_id=int(user_id),
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
case=case,
reason=reason,
)
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
else:
# [STEP 1] 停用旧活动决定
if current is not None:
current.is_active = False
current.updated_at = datetime.utcnow()
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(case, key),
decision_code=code,
decision_source='user',
line_status=status,
is_active=True,
reason=str(reason or '').strip()[:2000] or None,
required_qty=str(req_qty) if req_qty is not None else None,
available_qty=str(avail_qty) if avail_qty is not None else (
str(proj.get('available_qty') or '').strip() or None
),
reservation_id=_line_reservation_id(draft_line, proj),
part_number=_line_part_number(
draft_line,
proj,
schema_fields=schema_fields,
),
actor_user_id=int(user_id),
snapshot_json={
'decision_code': code,
'decision_source': 'user',
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'draft_line_id': key,
'release_field_values': {},
'release_required_fields': [],
'release_evidence_scope': None,
},
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
db.session.add(row)
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
db.session.flush()
if code == DECISION_CLOSE:
# [BE-结案-豁免] 结案是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
_sync_confirmed_task_fulfillment_gates(
case=case,
actor_id=int(user_id),
trigger='line_fulfillment_closed',
)
record_fulfillment_audit(
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action=code,
actor_type='user',
actor_id=int(user_id),
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
metadata={
'draft_line_id': key,
'decision_code': code,
'decision_version': int(row.decision_version),
'line_status': status,
'release_field_count': len(release_values),
},
before=_serialize_decision(current) if current is not None else None,
after=_serialize_decision(row),
source='order_review_fulfillment_decision',
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action=code,
actor_type='user',
actor_id=int(user_id),
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
metadata={
'draft_line_id': key,
'decision_code': code,
'decision_version': int(row.decision_version),
'line_status': status,
'release_field_count': 0,
},
before=_serialize_decision(current) if current is not None else None,
after=_serialize_decision(row),
source='order_review_fulfillment_decision',
)
from app.services.shipping_notice.order_review_resume_service import (
attach_resume_outcome,
@@ -1311,6 +1522,113 @@ def decide_review_line_fulfillment(
return attach_resume_outcome(payload, resume)
def _active_decision_line_indexes(task: ShippingNotice) -> set[int]:
"""读取当前任务全部活动行决定的 line_index(含 release/close/fulfill 等一切决定)。
核心逻辑:自动放行只处理「无任何活动决定」的行——已放行、已结案、已入波次或
已有其他人工决定的行一律跳过,保证幂等且绝不自动撤销既有决定(与
``_released_snapshot_line_ids_for_task`` 同款 Case 反查口径)。
"""
from app.models import ShippingOrderReviewCase
if getattr(task, 'id', None) is None:
return set()
rows = (
ShippingOrderReviewLineDecision.query
.join(
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.line_index.isnot(None),
)
.all()
)
return {int(row.line_index) for row in rows}
def auto_release_part_fallback_shortages(
task: ShippingNotice,
*,
actor_id: int | None = None,
) -> list[int]:
"""
匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。
核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可
自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工
路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动
履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不自动撤销
既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 fact['line_index']。
Args:
task: 正式任务聚合根(OT 或正式 Notice,须含 id 与 order_snapshot_id)。
actor_id: 触发匹配的用户(审计归属);自动决定本身 actor_type='system'。
Returns:
自动放行的 line_index 列表(按行号升序)。
"""
from app.services.shipping_notice.line_inventory_match_projection import (
load_current_match_facts_by_task,
)
task_id = getattr(task, 'id', None)
if task_id is None:
return []
facts = load_current_match_facts_by_task(int(task_id))
if not facts:
return []
decided_indexes = _active_decision_line_indexes(task)
ordered_facts = sorted(
(fact for fact in facts.values() if fact.get('line_index') is not None),
key=lambda fact: int(fact['line_index']),
)
released: list[int] = []
for fact in ordered_facts:
line_index = int(fact['line_index'])
try:
if line_index in decided_indexes:
continue
if not _is_shortage_match_fact(fact):
continue
required = _parse_qty(fact.get('required_qty'))
part_total = _parse_qty(fact.get('part_available_qty'))
if required is None or part_total is None or part_total < required:
# 料号兜底量缺失或不足 → 维持人工待处置(不得任取部分数量放行)。
continue
fields, evidence_scope = _shortage_release_required_fields(
task=task,
line_index=line_index,
inventory_snapshot_id=fact.get('inventory_snapshot_id'),
inventory_source_code=fact.get('inventory_source_code'),
)
if any(bool(field.get('requires_manual')) for field in fields):
# 证据字段无法唯一取值(requires_manual 残留)→ 降级人工放行,补录要求保留。
continue
auto_values = {
str(field.get('field_id') or ''): (
None if field.get('value') is None else str(field.get('value'))
)
for field in fields
}
_apply_shortage_line_release(
task,
line_index,
auto_values,
evidence_scope=evidence_scope,
actor_type='system',
actor_id=actor_id,
auto_release=True,
)
released.append(line_index)
except ConflictError:
# 证据不可解析(无源/模板未发布/无快照/草稿行缺失)→ 维持人工路径,不中断其余行。
continue
return released
def close_remaining_fulfillment(
*,
user_id: int,
@@ -352,6 +352,13 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
continue
current = gate
break
facts_before = (
execution.last_passed_gate_code,
execution.current_gate_code,
execution.primary_next_action_code,
execution.responsible_party,
execution.status,
)
execution.last_passed_gate_code = last_passed
if current is None:
execution.current_gate_code = None
@@ -359,7 +366,16 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
execution.responsible_party = None
if execution.status not in {'cancelled', 'failed'}:
execution.status = 'completed'
_sync_order_task_stage_after_gate_refresh(execution)
_sync_order_task_stage_after_gate_refresh(
execution,
facts_changed=facts_before != (
execution.last_passed_gate_code,
execution.current_gate_code,
execution.primary_next_action_code,
execution.responsible_party,
execution.status,
),
)
return
execution.current_gate_code = current.gate_code
execution.primary_next_action_code = current.next_action_code
@@ -376,10 +392,23 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
# [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读
# 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。
# 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。
_sync_order_task_stage_after_gate_refresh(execution)
_sync_order_task_stage_after_gate_refresh(
execution,
facts_changed=facts_before != (
execution.last_passed_gate_code,
execution.current_gate_code,
execution.primary_next_action_code,
execution.responsible_party,
execution.status,
),
)
def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecution) -> None:
def _sync_order_task_stage_after_gate_refresh(
execution: ShippingProcessExecution,
*,
facts_changed: bool = False,
) -> None:
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
if getattr(execution, 'task_id', None) is None:
return
@@ -397,10 +426,38 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio
if task is not None else None
)
if notice is not None:
version_before = int(getattr(task, 'progress_version', 0) or 0)
sync_order_task_stage_for_notice(notice, order_task=task)
# 库存缺口/文件就绪等 Gate 事实变化但映射后 stage/status 未变时,仍须推进
# progress_version:工作台以该版本变化触发 [REFRESH_ON_CHANGE] 重拉任务详情,
# 版本冻结会让行级可用数量/缺口停留在上一次快照。
if (
facts_changed
and task is not None
and int(getattr(task, 'progress_version', 0) or 0) == version_before
):
_bump_order_task_progress_version(task)
elif task is not None:
# Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。
task.stage = task.stage or 'notification_preparation'
# 无 Notice 绑定(通知准备/库存匹配常态)时上方 Notice 映射不存在,Gate 每次真实
# 推进都必须经中央写入口递增 progress_version,否则统一投影版本冻结,
# 前端轮询只更新右卡门禁、任务详情表格永不刷新。
if facts_changed:
_bump_order_task_progress_version(task)
def _bump_order_task_progress_version(task: ShippingOrderTask) -> None:
"""Gate 事实已变化但 stage/status 无值可变时,经中央写入口强制递增进度版本。"""
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
sync_order_task_processing_state(
task,
bump_progress=True,
force_progress_bump=True,
reason_code='gate_facts_advanced',
source='process_gate_service',
)
def ensure_execution_for_workflow_version(
@@ -812,6 +812,11 @@ def apply_user_projection_fields(
return 'waiting_human'
if unverified_upload_terminal:
return 'waiting_human'
if gate_status in {'queued', 'running', 'waiting_external'}:
# Gate/Execution 在途 = 系统处理中:Notice 生成前 OT.status 会停留在建单前
# 的 waiting_review,不得据此把 RPA 自动推进误报成待人工——前端把
# waiting_human 视为终态并停止投影轮询,回调完成将永远无法被感知。
return 'running'
# 1) 终态短路:old_status completed/cancelled/failed
if old_status == 'completed':
return 'completed'
@@ -8,6 +8,7 @@ services/shipping_notice/stp_line_inventory_match.py
__source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结
resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后
forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
行结果另含料号兜底总量 part_available_qty(允许源内、忽略预约号与单位的二次汇总)。
"""
from __future__ import annotations
@@ -77,6 +78,37 @@ def _inventory_row_qty(row: dict[str, Any]) -> Decimal:
return Decimal('0')
def _part_total_available_qty(
buckets: dict[tuple[str, str, str, str], dict[str, Any]],
*,
part: str,
allowed_source_codes: list[str],
has_candidate_scope: bool,
) -> Decimal | None:
"""
按料号(忽略预约号、不限单位)在该行允许源范围内汇总库存总可用量(料号兜底口径)。
Args:
buckets: (reservation, part, unit, source) 聚合桶;unit 维度不参与过滤。
part: 归一化料号;空串返回 None。
allowed_source_codes: 该行冻结的候选源;仅 has_candidate_scope 时约束。
has_candidate_scope: 行是否携带候选源范围事实。
Returns:
料号总可用量(Decimal);缺料号返回 None。跨源不合并(multi_file_conflict 语义)。
"""
if not part:
return None
total = Decimal('0')
for key, bucket in buckets.items():
if key[1] != part:
continue
if has_candidate_scope and bucket['source_code'] and bucket['source_code'] not in allowed_source_codes:
continue
total += bucket['available_qty']
return total
def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> str | None:
"""
从冻结 Snapshot 读取 Header 级 reservation_id。
@@ -275,6 +307,9 @@ def match_order_lines_across_candidates(
核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定,
库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。
料号兜底:仅 not_found(预约不匹配)/ok/shortage 行额外下发
``part_available_qty``(行允许源内、忽略预约号、不限单位的料号总可用量);
缺料号、invalid(超出候选范围)、multi_file_conflict、缺预约行不写该键,由下游按缺失→None 处理。
Args:
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
@@ -348,6 +383,13 @@ def match_order_lines_across_candidates(
else True
)
]
# [STEP] 料号兜底总量:行允许源内、忽略预约号、不限单位,供预约不匹配/缺口行自动放行判断。
part_total = _part_total_available_qty(
buckets,
part=part,
allowed_source_codes=allowed_source_codes,
has_candidate_scope=has_candidate_scope,
)
if not effective or not part:
disposition = 'not_found'
@@ -408,6 +450,7 @@ def match_order_lines_across_candidates(
'required_qty': float(required),
'available_qty': 0.0,
'shortage_qty': float(required),
'part_available_qty': float(part_total) if part_total is not None else None,
'line_status': 'shortage',
'disposition': disposition,
'resolved_inventory_source_code': None,
@@ -431,6 +474,7 @@ def match_order_lines_across_candidates(
'required_qty': float(required),
'available_qty': float(available),
'shortage_qty': 0.0,
'part_available_qty': float(part_total) if part_total is not None else None,
'line_status': 'ok',
'disposition': disposition,
'resolved_inventory_source_code': resolved_source,
@@ -453,6 +497,7 @@ def match_order_lines_across_candidates(
'required_qty': float(required),
'available_qty': float(available),
'shortage_qty': float(max(required - available, Decimal('0'))),
'part_available_qty': float(part_total) if part_total is not None else None,
'line_status': 'partial' if available > 0 else 'shortage',
'disposition': disposition,
'resolved_inventory_source_code': resolved_source,
@@ -16,6 +16,7 @@ services/shipping_notice/ui_state.py
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
prep 行直透投影 part_available_qty(料号兜底总量,仅库存就绪时非空)供前端「可用数量」列;
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
@@ -950,7 +951,8 @@ def _build_stage_context(
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
if release_line_index is None and getattr(snapshot_line, 'position', None) is not None:
release_line_index = int(snapshot_line.position)
release_template_fields = _shortage_release_required_fields(
# scope 仅在 decide 落库时写入审计快照;prep 行投影契约本期不新增字段。
release_template_fields, _evidence_scope = _shortage_release_required_fields(
task=order_task,
line_index=release_line_index,
inventory_snapshot_id=release_snapshot_id,
@@ -976,6 +978,7 @@ def _build_stage_context(
'required_qty': required_qty,
'available_qty': inv_view.get('available_qty'),
'shortage_qty': inv_view.get('shortage_qty'),
'part_available_qty': inv_view.get('part_available_qty'),
'source_code': source_code,
'selected_source_code': selected_source_code,
'status': inv_view.get('user_line_status'),