173 lines
7.5 KiB
Python
173 lines
7.5 KiB
Python
"""
|
|
backend/app/services/shipping_notice/candidate_validation.py
|
|
|
|
用途:统一校验并标准化人工修订或建批前的订单 Candidate 业务摘要。
|
|
依赖:notice_lines、po_number、reservation_id、field_rules、core.errors。
|
|
逻辑:Candidate API 与建批门禁共用,确保至少一条 SKU+Qty 有效订单行,避免空摘要绕过审核;
|
|
流程门禁使用有效 Reservation(行 ?? 头),库存源候选由资格服务另行裁决。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from app.core.errors import ValidationError
|
|
from app.services.shipping_notice.notice_lines import non_atomic_part_number_field, normalize_notice_line
|
|
from app.services.shipping_notice.notice_line_values import parse_number
|
|
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
|
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
|
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
|
|
|
BUILD_REQUIRED_FIELDS = ('part_number', 'qty')
|
|
PROCESS_FIELDS = ('reservation_id',)
|
|
|
|
|
|
def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[str, Any]:
|
|
"""
|
|
评估规则/LLM订单结果是否达到自动建单最低条件,同时保留不完整内容供自然对话修订。
|
|
|
|
核心逻辑:原子 part_number + 正数 Qty 是建单硬条件;有效 Reservation(行优先回退头)
|
|
是流程门禁字段。inventory_source_hint 仅保留为可选路由线索,缺失时不阻断本评估。
|
|
|
|
Args:
|
|
summary: 单个订单的业务摘要。
|
|
|
|
Returns:
|
|
包含 normalized_summary、can_create_task、missing_required_fields、
|
|
missing_process_fields、invalid_lines 与 blocking_issues 的评估结果。
|
|
"""
|
|
raw = dict(summary) if isinstance(summary, dict) else {}
|
|
header_reservation = raw.get('reservation_id')
|
|
raw_lines = raw.get('lines') if isinstance(raw.get('lines'), list) else []
|
|
normalized_lines: list[dict[str, Any]] = []
|
|
invalid_lines: list[dict[str, Any]] = []
|
|
missing_required: set[str] = set()
|
|
for index, item in enumerate(raw_lines):
|
|
raw_line = item if isinstance(item, dict) else None
|
|
non_atomic_field = non_atomic_part_number_field(raw_line)
|
|
if non_atomic_field:
|
|
invalid_lines.append({
|
|
'line_index': index,
|
|
'reason': 'non_atomic_part_number',
|
|
'field': non_atomic_field,
|
|
})
|
|
continue
|
|
normalized = normalize_notice_line(raw_line)
|
|
if normalized is None:
|
|
raw_part_number = str((raw_line or {}).get('part_number') or '').strip()
|
|
raw_qty = parse_number(
|
|
(raw_line or {}).get('qty')
|
|
if (raw_line or {}).get('qty') is not None
|
|
else (raw_line or {}).get('quantity')
|
|
)
|
|
line_missing = []
|
|
if not raw_part_number:
|
|
line_missing.append('part_number')
|
|
if raw_qty is None or raw_qty <= 0:
|
|
line_missing.append('qty')
|
|
missing_required.update(line_missing)
|
|
invalid_lines.append({
|
|
'line_index': index,
|
|
'reason': 'missing_part_number_or_positive_qty',
|
|
'fields': line_missing,
|
|
})
|
|
continue
|
|
raw_reservation = str(normalized.get('reservation_id') or '').strip()
|
|
if raw_reservation and not validated_reservation_id(raw_reservation):
|
|
invalid_lines.append({'line_index': index, 'reason': 'invalid_reservation_id'})
|
|
continue
|
|
effective = compute_effective_reservation_id(
|
|
line_reservation_id=normalized.get('reservation_id'),
|
|
header_reservation_id=header_reservation,
|
|
)
|
|
if effective:
|
|
normalized['reservation_id'] = effective
|
|
normalized['effective_reservation_id'] = effective
|
|
normalized_lines.append(normalized)
|
|
|
|
normalized_summary = dict(raw)
|
|
normalized_summary['lines'] = normalized_lines
|
|
# customer_po_number 是动态 Schema 的正式字段;po_number 保留为 Candidate/履约链路的兼容投影。
|
|
normalized_summary['po_number'] = normalize_atomic_po_number(
|
|
raw.get('customer_po_number') or raw.get('po_number')
|
|
) or None
|
|
normalized_summary['reservation_ids'] = sorted({
|
|
normalized
|
|
for line in normalized_lines
|
|
if (normalized := validated_reservation_id(
|
|
line.get('effective_reservation_id') or line.get('reservation_id')
|
|
))
|
|
})
|
|
|
|
if not normalized_lines and not invalid_lines:
|
|
missing_required.update(BUILD_REQUIRED_FIELDS)
|
|
# 有效 Reservation 是逐行匹配键;头级可回填行级缺失。
|
|
missing_process = [
|
|
field
|
|
for field in PROCESS_FIELDS
|
|
if any(
|
|
not validated_reservation_id(
|
|
line.get('effective_reservation_id') or line.get(field)
|
|
)
|
|
for line in normalized_lines
|
|
)
|
|
]
|
|
blocking = [
|
|
{'code': 'invalid_order_line', **item}
|
|
for item in invalid_lines
|
|
]
|
|
return {
|
|
'normalized_summary': normalized_summary,
|
|
'can_create_task': bool(normalized_lines) and not invalid_lines,
|
|
'can_auto_progress': bool(normalized_lines) and not invalid_lines and not missing_process,
|
|
'missing_required_fields': sorted(missing_required),
|
|
'missing_process_fields': missing_process,
|
|
'invalid_lines': invalid_lines,
|
|
'process_issues': [],
|
|
'blocking_issues': blocking,
|
|
}
|
|
|
|
|
|
def normalize_candidate_business_summary(summary: dict[str, Any] | None) -> dict[str, Any]:
|
|
"""
|
|
标准化并验证 Candidate 业务摘要。
|
|
|
|
核心逻辑:逐行严格校验 SKU 与正数 Qty;任何脏行都会阻断,不静默丢弃;
|
|
同步标准 PO 与 Reservation 集合,同时保留未知单头字段供后续业务扩展。
|
|
Args:
|
|
summary: 前端人工修订或数据库中的 Candidate 业务摘要。
|
|
Returns:
|
|
可安全用于双指纹和建单的标准业务摘要副本。
|
|
Raises:
|
|
ValidationError: 摘要不是对象、没有订单行或任一订单行无效。
|
|
"""
|
|
if not isinstance(summary, dict):
|
|
raise ValidationError(
|
|
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
|
message='订单候选摘要必须为对象',
|
|
)
|
|
assessment = assess_candidate_business_summary(summary)
|
|
raw_lines = summary.get('lines')
|
|
if not isinstance(raw_lines, list) or not raw_lines:
|
|
raise ValidationError(
|
|
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
|
message='订单候选至少需要一条包含 SKU 与数量的订单行',
|
|
)
|
|
|
|
if assessment['invalid_lines']:
|
|
first = assessment['invalid_lines'][0]
|
|
reason = str(first.get('reason') or '')
|
|
line_number = int(first.get('line_index') or 0) + 1
|
|
if reason == 'invalid_reservation_id':
|
|
message = f"第 {line_number} 条订单行 Reservation ID 不满足业务格式契约"
|
|
elif reason == 'non_atomic_part_number':
|
|
message = f"第 {line_number} 条订单行 {first.get('field')} 必须是不可包含 / 的原子料号"
|
|
else:
|
|
message = f"第 {line_number} 条订单行缺少有效内部料号或数量"
|
|
raise ValidationError(
|
|
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
|
message=message,
|
|
details={'line_index': first.get('line_index'), 'reason': reason},
|
|
)
|
|
return assessment['normalized_summary']
|