refactor(shipping-notice): 统一料号字段,移除过时的 SKU 相关字段,更新相关逻辑以支持新字段命名

This commit is contained in:
hugo committed 2026-07-16 20:02:33 +08:00
1 parent dde25344ca
commit 46eb63f5bb
111 files changed
+3116 -1250

No files matched your search

-1
View File
@@ -160,7 +160,6 @@ def _build_chat_adapter_hints(
'batch_no': batch_no or None,
'intake_nos': intake_nos,
'capability': 'order_extraction' if intake_nos else None,
'contract_version': 'shipping-order-extraction-v1' if intake_nos else None,
}
}
-3
View File
@@ -408,7 +408,6 @@ class ShippingNoticeIntake(Base):
nullable=False,
index=True,
)
order_extraction_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_extraction_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
@@ -490,7 +489,6 @@ class ShippingNoticeDocument(Base):
)
order_extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
order_extraction_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
order_extraction_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_extraction_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -535,7 +533,6 @@ class ShippingNoticeCandidate(Base):
candidate_key: Mapped[str] = mapped_column(String(128), nullable=False)
source_order_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
extraction_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
missing_fields_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
+19 -8
View File
@@ -43,9 +43,21 @@ class ShippingTaskLine(Base):
__table_args__ = (
UniqueConstraint('task_id', 'position', name='uq_shipping_task_lines_task_position'),
CheckConstraint('qty > 0', name='ck_shipping_task_lines_qty_positive'),
CheckConstraint(
"part_number NOT LIKE '%/%'",
name='ck_shipping_task_lines_part_number_atomic',
),
CheckConstraint(
"customer_part_number IS NULL OR customer_part_number NOT LIKE '%/%'",
name='ck_shipping_task_lines_customer_part_number_atomic',
),
CheckConstraint(
"aws_part_number IS NULL OR aws_part_number NOT LIKE '%/%'",
name='ck_shipping_task_lines_aws_part_number_atomic',
),
Index('ix_shipping_task_lines_task_id', 'task_id'),
Index('ix_shipping_task_lines_reservation_id', 'reservation_id'),
Index('ix_shipping_task_lines_sku', 'sku'),
Index('ix_shipping_task_lines_part_number', 'part_number'),
)
id: Mapped[int] = mapped_column(primary_key=True)
@@ -54,16 +66,15 @@ class ShippingTaskLine(Base):
nullable=False,
)
position: Mapped[int] = mapped_column(Integer, nullable=False)
sku: Mapped[str] = mapped_column(String(128), nullable=False)
part_number: Mapped[str] = mapped_column(String(128), nullable=False)
qty: Mapped[Decimal] = mapped_column(Numeric(18, 6), nullable=False)
uom: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
source_type: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
hub_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
inventory_source_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
vendor_part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
customer_sku: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
customer_part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
aws_part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
allocation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
unit_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(18, 6), nullable=True)
@@ -76,8 +87,8 @@ class ShippingTaskLine(Base):
schema_version: Mapped[str] = mapped_column(
String(64),
nullable=False,
default='shipping-task-line-v1',
server_default=text("'shipping-task-line-v1'"),
default='shipping-task-line-v2',
server_default=text("'shipping-task-line-v2'"),
)
line_version: Mapped[int] = mapped_column(
Integer,
@@ -54,11 +54,10 @@ class ShippingNoticeHandler(AgentHandler):
@classmethod
def _order_extraction_intake_nos(cls, ctx: ChatStreamContext) -> list[str]:
"""仅在能力与契约均匹配时返回本轮 Intake 集合,避免普通续办误触抽取收口。"""
"""仅在订单抽取能力匹配时返回本轮 Intake 集合,避免普通续办误触抽取收口。"""
hints = cls._shipping_hints(ctx)
if (
str(hints.get('capability') or '') != 'order_extraction'
or str(hints.get('contract_version') or '') != 'shipping-order-extraction-v1'
or not isinstance(hints.get('intake_nos'), list)
):
return []
@@ -32,7 +32,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
"refs.task_no",
"refs.run_purpose",
"refs.capability",
"refs.contract_version",
"refs.intake_nos",
"refs.file_name",
"refs.schedule_task_id",
@@ -4,7 +4,7 @@ backend/app/services/shipping_notice/business_fingerprint.py
用途:基于业务摘要生成稳定业务指纹与强度判定(货代域,不含文件哈希)。
依赖:po_number / reservation_id 标准化函数。
逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;
身份算法版本 shipping-v1,内容算法版本 shipping-content-v3。
身份算法版本 shipping-v1,内容算法版本 shipping-content-v4。
"""
from __future__ import annotations
@@ -18,7 +18,7 @@ from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
FINGERPRINT_VERSION = 'shipping-v1'
CONTENT_FINGERPRINT_VERSION = 'shipping-content-v3'
CONTENT_FINGERPRINT_VERSION = 'shipping-content-v4'
def _norm_text(value: Any) -> str:
@@ -39,12 +39,12 @@ def _line_digest(lines: list[dict[str, Any]]) -> str:
for line in lines:
if not isinstance(line, dict):
continue
sku = _norm_text(line.get('sku'))
part_number = _norm_text(line.get('part_number'))
rid = validated_reservation_id(str(line.get('reservation_id') or '')) or ''
qty = _norm_qty(line.get('qty'))
if not sku and not rid and not qty:
if not part_number and not rid and not qty:
continue
parts.append(f'{sku}|{rid}|{qty}')
parts.append(f'{part_number}|{rid}|{qty}')
parts.sort()
return '\n'.join(parts)
@@ -194,7 +194,7 @@ def build_content_fingerprint(business_summary: dict[str, Any] | None) -> dict[s
values = [
_norm_text(line.get('line_no')),
validated_reservation_id(line.get('reservation_id')) or '',
_norm_text(line.get('sku')),
_norm_text(line.get('part_number')),
_norm_qty(line.get('qty')),
_norm_text(line.get('uom')),
_norm_qty(line.get('unit_price')),
@@ -203,9 +203,9 @@ def build_content_fingerprint(business_summary: dict[str, Any] | None) -> dict[s
_norm_text(line.get('required_date')),
normalize_po_number(line.get('po_number')) or '',
_norm_text(line.get('allocation_id')),
_norm_text(line.get('source_type')),
_norm_text(line.get('customer_sku')),
_norm_text(line.get('vendor_part_number')),
_norm_text(line.get('inventory_source_hint')),
_norm_text(line.get('customer_part_number')),
_norm_text(line.get('aws_part_number')),
]
if any(values):
parts.append('|'.join(values))
@@ -11,11 +11,11 @@ from __future__ import annotations
from typing import Any
from app.core.errors import ValidationError
from app.services.shipping_notice.notice_lines import normalize_notice_line
from app.services.shipping_notice.notice_lines import non_atomic_part_number_field, normalize_notice_line
from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
BUILD_REQUIRED_FIELDS = ('sku', 'qty')
BUILD_REQUIRED_FIELDS = ('part_number', 'qty')
PROCESS_FIELDS = ('reservation_id',)
@@ -23,8 +23,8 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
"""
评估规则/LLM订单结果是否达到自动建单最低条件,同时保留不完整内容供自然对话修订。
核心逻辑:SKU + 正数 Qty 是建单硬条件;Reservation ID 是唯一流程门禁字段。
行级 source_type 仅保留为可选库存源路由线索,缺失时不阻断建单或后续流程。
核心逻辑:原子 part_number + 正数 Qty 是建单硬条件;Reservation ID 是唯一流程门禁字段。
inventory_source_hint 仅保留为可选库存源路由线索,缺失时不阻断建单或后续流程。
Args:
summary: 单个订单的业务摘要。
@@ -38,9 +38,18 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
normalized_lines: list[dict[str, Any]] = []
invalid_lines: list[dict[str, Any]] = []
for index, item in enumerate(raw_lines):
normalized = normalize_notice_line(item if isinstance(item, dict) else None)
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:
invalid_lines.append({'line_index': index, 'reason': 'missing_sku_or_positive_qty'})
invalid_lines.append({'line_index': index, 'reason': 'missing_part_number_or_positive_qty'})
continue
raw_reservation = str(normalized.get('reservation_id') or '').strip()
if raw_reservation and not validated_reservation_id(raw_reservation):
@@ -114,11 +123,13 @@ def normalize_candidate_business_summary(summary: dict[str, Any] | None) -> dict
if assessment['invalid_lines']:
first = assessment['invalid_lines'][0]
reason = str(first.get('reason') or '')
message = (
f"第 {int(first.get('line_index') or 0) + 1} 条订单行 Reservation ID 不满足业务格式契约"
if reason == 'invalid_reservation_id'
else f"第 {int(first.get('line_index') or 0) + 1} 条订单行缺少有效 SKU 或数量"
)
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,
@@ -200,8 +200,8 @@ class ShippingApplyInventoryMappingAction:
if not isinstance(mapping_raw, dict) or not mapping_raw:
raise ValidationError(f"{MAP_JSON} is required")
mapping = {str(k): str(v) for k, v in mapping_raw.items() if str(v or "").strip()}
if not mapping.get("sku") or not mapping.get("available_qty"):
raise ValidationError("sku and available_qty mapping are required")
if not mapping.get("part_number") or not mapping.get("available_qty"):
raise ValidationError("part_number and available_qty mapping are required")
yield TurnEvent(event="step.started", data={"step_id": "apply_inventory_mapping", "label": "应用列映射..."})
result = shipping_tools.apply_inventory_mapping({
"task_id": task.task_no,
@@ -62,7 +62,8 @@ def _format_decision_message(decision: str, result: dict[str, Any], task_no: str
elif headers:
lines.extend(["", f"当前表头:{' | '.join(headers)}"])
mapping_lines = [
f"- sku → {suggested['sku']}" if suggested.get("sku") else None,
f"- part_number → {suggested['part_number']}" if suggested.get("part_number") else None,
f"- aws_part_number → {suggested['aws_part_number']}" if suggested.get("aws_part_number") else None,
f"- reservation_id → {suggested['reservation_id']}" if suggested.get("reservation_id") else None,
f"- available_qty → {suggested['available_qty']}" if suggested.get("available_qty") else None,
]
@@ -52,5 +52,4 @@ def build_shipping_notice_context_adapter(
locale=locale,
intake_nos=shipping_hints.get('intake_nos'),
capability=shipping_hints.get('capability'),
contract_version=shipping_hints.get('contract_version'),
)
@@ -70,7 +70,6 @@ def build_dify_chat_inputs(
locale: str | None = None,
intake_nos: list[str] | None = None,
capability: str | None = None,
contract_version: str | None = None,
) -> dict[str, Any]:
"""
构建发货通知 Dify Chatflow inputs。
@@ -118,7 +117,6 @@ def build_dify_chat_inputs(
),
intake_nos=intake_nos,
capability=capability,
contract_version=contract_version,
)
if not runtime_context:
return {}
@@ -206,7 +206,6 @@ def _upsert_candidate(
candidate_key: str,
source_order_index: int | None = None,
extraction_source: str = 'rule',
extraction_version: str | None = None,
classification_confidence: float | None = None,
field_confidence: dict[str, Any] | None = None,
missing_fields: list[str] | None = None,
@@ -236,7 +235,6 @@ def _upsert_candidate(
row.primary_document_id = int(document.id)
row.source_order_index = source_order_index
row.extraction_source = extraction_source
row.extraction_version = extraction_version
row.classification_confidence = classification_confidence
row.field_confidence_json = dict(field_confidence or {}) or None
row.missing_fields_json = list(missing_fields or [])
@@ -320,6 +318,13 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
summary = None
if isinstance(cand.structured_result_json, dict):
summary = cand.structured_result_json.get('business_summary')
structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {}
extraction = structured.get('extraction') if isinstance(structured.get('extraction'), dict) else {}
adjudication = (
extraction.get('field_adjudication')
if isinstance(extraction.get('field_adjudication'), dict)
else {}
)
document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id))
return {
'candidate_no': cand.candidate_no,
@@ -342,6 +347,13 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
else {}
),
'evidence': list(cand.evidence_json or []),
'field_adjudication': {
'schema_version': adjudication.get('schema_version'),
'decisions': list(adjudication.get('decisions') or []),
'observations': list(adjudication.get('observations') or []),
'observation_history': list(adjudication.get('observation_history') or []),
'conflicts': list(adjudication.get('conflicts') or []),
} if adjudication else None,
'duplicate': {
'status': status,
'blocking': blocking,
+16 -6
View File
@@ -90,6 +90,15 @@ def _delivery_date_for_task(task: ShippingTask) -> str:
def _resolve_odm_id(task: ShippingTask) -> str:
"""
按订单内部料号与 Reservation 定位当前库存投影中的 ODM ID。
核心逻辑:订单与库存统一按 part_number + reservation_id 配对。
Args:
task: 已关联库存快照的发货任务。
Returns:
首个匹配库存行的 ODM ID;未命中时回退库存中的首个非空值。
"""
notice_lines = read_task_order_lines(task)
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
if not inventory_lines:
@@ -98,14 +107,14 @@ def _resolve_odm_id(task: ShippingTask) -> str:
inv_by_key: dict[tuple[str, str], dict[str, Any]] = {}
for row in inventory_lines:
key = (
str(row.get("sku") or "").strip(),
str(row.get("part_number") or "").strip(),
str(row.get("reservation_id") or "").strip(),
)
inv_by_key[key] = row
for line in notice_lines:
key = (
str(line.get("sku") or "").strip(),
str(line.get("part_number") or "").strip(),
str(line.get("reservation_id") or "").strip(),
)
matched = inv_by_key.get(key)
@@ -155,8 +164,9 @@ def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str:
return ""
def _line_vendor_part_number(line: dict[str, Any]) -> str:
return str(line.get("vendor_part_number") or "").strip()
def _line_part_number(line: dict[str, Any]) -> str:
"""返回货代明细使用的内部料号。"""
return str(line.get("part_number") or "").strip()
def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
@@ -201,7 +211,7 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
detail_ws.cell(row_idx, 1).value = business_ref
detail_ws.cell(row_idx, 2).value = line_no
detail_ws.cell(row_idx, 4).value = _line_vendor_part_number(line)
detail_ws.cell(row_idx, 4).value = _line_part_number(line)
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
detail_ws.cell(row_idx, 7).value = _line_po_number(task, line)
detail_ws.cell(row_idx, 10).value = amount if amount is not None else ""
@@ -217,7 +227,7 @@ def _row_values(task: ShippingTask, line: dict | None) -> list:
task.customer_code or "",
task.ship_to or "",
task.required_date or "",
line.get("sku") or "",
line.get("part_number") or "",
line.get("qty") or "",
line.get("uom") or "EA",
line.get("remark") or "",
@@ -126,7 +126,7 @@ def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]
lines = []
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
lines.append({"sku": m.group(1), "qty": float(m.group(2)), "uom": "EA"})
lines.append({"part_number": m.group(1), "qty": float(m.group(2)), "uom": "EA"})
# 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2)
if not lines:
@@ -137,7 +137,7 @@ def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]
lines.append(
{
"reservation_id": m.group("resv"),
"sku": m.group(2),
"part_number": m.group(2),
"qty": float(m.group(3)),
"uom": "EA",
}
@@ -0,0 +1,442 @@
"""
backend/app/services/shipping_notice/field_adjudication.py
用途:把后端表格解析与 Dify LLM 输出转换为不可变字段 Observation,并生成规范订单行裁决结果。
依赖:ShippingNoticeDocument、notice_lines、标准库 hashlib/json/re。
逻辑:submit_order_extraction 在 Candidate 校验前调用;原始 Observation 只追加不互相覆盖,裁决结果另行投影。
"""
from __future__ import annotations
import hashlib
import json
import re
from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import ShippingNoticeDocument
from app.services.shipping_notice.notice_lines import normalize_notice_line, parse_notice_table_text
ADJUDICATION_SCHEMA_VERSION = "shipping-field-adjudication-v1"
ADJUDICATED_LINE_FIELDS = (
"part_number",
"customer_part_number",
"aws_part_number",
"reservation_id",
"qty",
)
_TRUSTED_SCORE = 70
_CREDIBLE_SCORE = 50
_DECISION_MARGIN = 20
def _json_value(value: Any) -> Any:
"""将 Observation 值转换为稳定、可 JSON 序列化的标量。"""
if isinstance(value, Decimal):
return float(value)
return value
def _normalized_value(field: str, value: Any) -> str:
"""按字段语义生成比较键;数量使用 Decimal 避免 10 与 10.0 被误判冲突。"""
if value in (None, ""):
return ""
if field == "qty":
try:
return format(Decimal(str(value).replace(",", "").strip()).normalize(), "f")
except (InvalidOperation, ValueError):
return ""
return str(value).strip().upper()
def _observation_id(payload: dict[str, Any]) -> str:
"""基于不可变 Observation 内容生成稳定标识。"""
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
def _quote_supports_value(field: str, value: Any, quote: str) -> bool:
"""确认 quote 不仅存在于原文,还实际包含被声明字段值。"""
normalized = _normalized_value(field, value)
if not normalized:
return False
if field != "qty":
return normalized in str(quote or "").upper()
numbers = re.findall(r"[-+]?\d[\d,]*(?:\.\d+)?", str(quote or ""))
return any(_normalized_value("qty", item) == normalized for item in numbers)
def _evidence_for_field(
*,
evidence_items: list[dict[str, Any]],
documents_by_id: dict[int, ShippingNoticeDocument],
line_index: int,
field: str,
value: Any,
) -> tuple[list[dict[str, Any]], bool]:
"""验证 Dify 字段证据的路径、Document 归属、逐字 quote 和值包含关系。"""
expected = f"lines[{line_index}].{field}".lower()
verified: list[dict[str, Any]] = []
for item in evidence_items:
if str(item.get("field") or "").strip().lower() != expected:
continue
document_id = item.get("document_id")
document = documents_by_id.get(int(document_id)) if str(document_id or "").isdigit() else None
quote = str(item.get("quote") or "").strip()
text = str(document.extracted_text or "") if document is not None else ""
if not quote or quote not in text or not _quote_supports_value(field, value, quote):
continue
verified.append({
"field": expected,
"quote": quote,
"document_id": int(document.id),
"verified": True,
})
return verified, bool(verified)
def _make_observation(
*,
source: str,
line_index: int,
field: str,
value: Any,
raw_value: Any = None,
document_id: int | None = None,
evidence: list[dict[str, Any]] | None = None,
evidence_verified: bool,
source_confidence: float,
score: int,
reasons: list[str],
) -> dict[str, Any]:
"""构造只包含事实与评分依据的不可变 Observation 字典。"""
payload = {
"source": source,
"line_index": line_index,
"field": field,
"value": _json_value(value),
"raw_value": _json_value(raw_value if raw_value is not None else value),
"normalized_value": _normalized_value(field, value),
"document_id": document_id,
"evidence": list(evidence or []),
"evidence_verified": evidence_verified,
"source_confidence": round(max(0.0, min(float(source_confidence), 1.0)), 4),
"score": max(0, min(int(score), 100)),
"score_reasons": list(reasons),
}
return {"observation_id": _observation_id(payload), **payload}
def _backend_rows(documents: list[ShippingNoticeDocument]) -> list[dict[str, Any]]:
"""从每个锁定 Document 的保留列边界文本生成后端表格 Observation 原料。"""
rows: list[dict[str, Any]] = []
for document in documents:
for row in parse_notice_table_text(str(document.extracted_text or "")):
if isinstance(row, dict):
rows.append({**row, "_document_id": int(document.id)})
return rows
def _line_matches_backend(raw_line: dict[str, Any], backend_row: dict[str, Any]) -> bool:
"""使用稳定标识优先、唯一数量兜底前的单行关联判断。"""
for field in ("reservation_id", "part_number", "customer_part_number", "aws_part_number"):
left = _normalized_value(field, raw_line.get(field))
right = _normalized_value(field, backend_row.get(field))
if left and right and left == right:
return True
return False
def _associated_backend_rows(
raw_line: dict[str, Any],
backend_rows: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""关联后端行;无稳定字段命中时,仅允许 Qty 唯一命中兜底。"""
matched = [row for row in backend_rows if _line_matches_backend(raw_line, row)]
if matched:
return matched
qty = _normalized_value("qty", raw_line.get("qty"))
qty_matches = [row for row in backend_rows if qty and _normalized_value("qty", row.get("qty")) == qty]
return qty_matches if len(qty_matches) == 1 else []
def _dify_observations(
*,
raw_line: dict[str, Any],
normalized_line: dict[str, Any],
line_index: int,
evidence_items: list[dict[str, Any]],
documents_by_id: dict[int, ShippingNoticeDocument],
field_confidence: dict[str, Any],
) -> list[dict[str, Any]]:
"""将 Dify 行转换为 Observation;自报 confidence 只贡献最多 10 分。"""
observations: list[dict[str, Any]] = []
for field in ADJUDICATED_LINE_FIELDS:
value = normalized_line.get(field)
if value in (None, ""):
continue
evidence, verified = _evidence_for_field(
evidence_items=evidence_items,
documents_by_id=documents_by_id,
line_index=line_index,
field=field,
value=value,
)
confidence = field_confidence.get(field)
if confidence is None and field in {"customer_part_number", "aws_part_number", "reservation_id"}:
confidence = field_confidence.get("part_number")
try:
confidence_value = max(0.0, min(float(confidence), 1.0))
except (TypeError, ValueError):
confidence_value = 0.0
score = 35 + (35 if verified else 0) + round(confidence_value * 10)
raw_value = raw_line.get(field)
if raw_value in (None, "") and field == "customer_part_number":
raw_value = raw_line.get("part_number")
observations.append(_make_observation(
source="dify_llm",
line_index=line_index,
field=field,
value=value,
raw_value=raw_value,
evidence=evidence,
evidence_verified=verified,
source_confidence=confidence_value,
score=score,
reasons=["dify_candidate", "verified_quote" if verified else "unverified_quote", "self_confidence_weak_weight"],
))
return observations
def _backend_observations(
*,
rows: list[dict[str, Any]],
line_index: int,
) -> list[dict[str, Any]]:
"""将列边界明确的后端表格值转换为高可信 Observation。"""
observations: list[dict[str, Any]] = []
for row in rows:
document_id = int(row.get("_document_id"))
for field in ADJUDICATED_LINE_FIELDS:
value = row.get(field)
if value in (None, ""):
continue
evidence = [{
"document_id": document_id,
"parser": "backend_table",
"column_boundary_verified": True,
}]
observations.append(_make_observation(
source="backend_table",
line_index=line_index,
field=field,
value=value,
document_id=document_id,
evidence=evidence,
evidence_verified=True,
source_confidence=0.9,
score=85,
reasons=["backend_parser", "column_boundary_verified", "format_valid"],
))
return observations
def _decide_field(
*,
field: str,
line_index: int,
observations: list[dict[str, Any]],
) -> tuple[dict[str, Any], dict[str, Any] | None]:
"""按可信阈值和分差选择字段值;双方高可信不同或分差不足时返回阻断冲突。"""
grouped: dict[str, list[dict[str, Any]]] = {}
for observation in observations:
normalized = str(observation.get("normalized_value") or "")
if normalized:
grouped.setdefault(normalized, []).append(observation)
ranked = sorted(
grouped.items(),
key=lambda item: (-max(int(obs["score"]) for obs in item[1]), item[0]),
)
if not ranked:
return {
"line_index": line_index,
"field": field,
"status": "unresolved",
"value": None,
"score": 0,
"observation_ids": [],
}, None
top_key, top_observations = ranked[0]
top_score = max(int(item["score"]) for item in top_observations)
top_value = max(top_observations, key=lambda item: int(item["score"]))["value"]
source_set = {str(item["source"]) for item in top_observations}
if len(ranked) == 1:
status = "consensus" if len(source_set) > 1 else "selected"
return {
"line_index": line_index,
"field": field,
"status": status,
"value": top_value,
"score": top_score,
"observation_ids": [item["observation_id"] for item in top_observations],
}, None
second_key, second_observations = ranked[1]
second_score = max(int(item["score"]) for item in second_observations)
trusted_values = [key for key, items in ranked if max(int(item["score"]) for item in items) >= _TRUSTED_SCORE]
insufficient_margin = top_score - second_score < _DECISION_MARGIN
if len(trusted_values) > 1 or (second_score >= _CREDIBLE_SCORE and insufficient_margin):
conflict = {
"field": field,
"line_index": line_index,
"severity": "blocking",
"reason": "cross_source_conflict" if len(trusted_values) > 1 else "insufficient_score_margin",
"values": [top_key, second_key],
"observation_ids": [
item["observation_id"]
for _, items in ranked
for item in items
],
}
return {
"line_index": line_index,
"field": field,
"status": "conflicted",
"value": top_value,
"score": top_score,
"observation_ids": conflict["observation_ids"],
}, conflict
return {
"line_index": line_index,
"field": field,
"status": "selected",
"value": top_value,
"score": top_score,
"observation_ids": [item["observation_id"] for item in top_observations],
}, None
def adjudicate_order_fields(
summary: dict[str, Any],
*,
raw_order: dict[str, Any],
documents: list[ShippingNoticeDocument],
field_confidence: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
对单个 Dify 订单和当前 Intake 的后端解析结果执行字段级交叉裁决。
核心逻辑:逐行生成两侧 Observation,按稳定字段/唯一 Qty 关联后端行,再按字段评分;
仅一侧可信时采用、双方一致时 consensus、双方可信不同或分差不足时生成 blocking conflict。
Args:
summary: 已去除抽取元数据的 Dify 业务摘要。
raw_order: Dify 原始订单对象,保留 evidence 与原始复合值。
documents: 当前 Intake 的锁定 Document 集合。
field_confidence: Dify 自报字段置信度,仅作弱权重。
Returns:
包含 canonical summary、不可变 observations、decisions 和 conflicts 的裁决结果。
"""
raw_lines = summary.get("lines") if isinstance(summary.get("lines"), list) else []
backend_rows = _backend_rows(documents)
documents_by_id = {int(item.id): item for item in documents}
evidence_items = [item for item in (raw_order.get("evidence") or []) if isinstance(item, dict)]
confidence = dict(field_confidence or {})
canonical_lines: list[dict[str, Any]] = []
observations: list[dict[str, Any]] = []
decisions: list[dict[str, Any]] = []
conflicts: list[dict[str, Any]] = []
line_count = len(raw_lines) if raw_lines else len(backend_rows)
for line_index in range(line_count):
raw_line = dict(raw_lines[line_index]) if line_index < len(raw_lines) and isinstance(raw_lines[line_index], dict) else {}
normalized_line = normalize_notice_line(raw_line) or {
key: value for key, value in raw_line.items() if value not in (None, "")
}
associated = _associated_backend_rows(raw_line, backend_rows)
if not raw_line and line_index < len(backend_rows):
associated = [backend_rows[line_index]]
line_observations = _dify_observations(
raw_line=raw_line,
normalized_line=normalized_line,
line_index=line_index,
evidence_items=evidence_items,
documents_by_id=documents_by_id,
field_confidence=confidence,
)
line_observations.extend(_backend_observations(rows=associated, line_index=line_index))
observations.extend(line_observations)
canonical = dict(normalized_line)
for field in ADJUDICATED_LINE_FIELDS:
field_observations = [item for item in line_observations if item["field"] == field]
decision, conflict = _decide_field(
field=field,
line_index=line_index,
observations=field_observations,
)
decisions.append(decision)
if decision.get("value") not in (None, ""):
canonical[field] = decision["value"]
if conflict:
conflicts.append(conflict)
normalized_canonical = normalize_notice_line(canonical)
canonical_lines.append(normalized_canonical or canonical)
canonical_summary = dict(summary)
canonical_summary["lines"] = canonical_lines
return {
"schema_version": ADJUDICATION_SCHEMA_VERSION,
"summary": canonical_summary,
"observations": observations,
"decisions": decisions,
"conflicts": conflicts,
}
def merge_observation_history(
previous: list[dict[str, Any]] | None,
current: list[dict[str, Any]] | None,
) -> list[dict[str, Any]]:
"""
按 Observation ID 追加不可变审计历史。
核心逻辑:已有 Observation 原样保留,新 Observation 仅在 ID 未出现时追加;禁止以当前值覆盖历史内容。
Args:
previous: Candidate 已持久化的历史 Observation。
current: 本次锁定快照生成的 Observation。
Returns:
保持首次出现顺序的累积 Observation 列表。
"""
merged: list[dict[str, Any]] = []
seen: set[str] = set()
for item in [*(previous or []), *(current or [])]:
if not isinstance(item, dict):
continue
observation_id = str(item.get("observation_id") or "").strip()
if not observation_id or observation_id in seen:
continue
seen.add(observation_id)
merged.append(dict(item))
return merged
def trusted_required_fields(adjudication: dict[str, Any]) -> bool:
"""确认每条规范行的 part_number 与 qty 都有可信且未冲突的裁决决定。"""
decisions = [item for item in (adjudication.get("decisions") or []) if isinstance(item, dict)]
lines = (adjudication.get("summary") or {}).get("lines") or []
for line_index, _line in enumerate(lines):
for field in ("part_number", "qty"):
decision = next(
(
item for item in decisions
if item.get("line_index") == line_index and item.get("field") == field
),
None,
)
if not decision or decision.get("status") in {"unresolved", "conflicted"}:
return False
if int(decision.get("score") or 0) < _TRUSTED_SCORE:
return False
return bool(lines)
@@ -78,7 +78,7 @@ def _format_sample_lines(field_alignment: dict[str, Any], *, lang: str) -> list[
if not isinstance(line, dict):
continue
parts.append(
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.qty', lang=lang)} {_fmt_qty(line.get('qty'))}"
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.part_number', lang=lang)} {_cell(line.get('part_number'))} | {t('field.qty', lang=lang)} {_fmt_qty(line.get('qty'))}"
)
if inventory_lines:
@@ -89,7 +89,7 @@ def _format_sample_lines(field_alignment: dict[str, Any], *, lang: str) -> list[
if not isinstance(line, dict):
continue
parts.append(
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.available_qty', lang=lang)} {_fmt_qty(line.get('available_qty'))}"
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.part_number', lang=lang)} {_cell(line.get('part_number'))} | {t('field.available_qty', lang=lang)} {_fmt_qty(line.get('available_qty'))}"
)
return parts
@@ -135,7 +135,8 @@ def format_field_alignment_summary(
f"| {t('align.table.sys_field', lang=resolved)} | {t('align.table.inv_col', lang=resolved)} | {t('align.table.notice_field', lang=resolved)} |",
"|---------|--------------|---------|",
f"| {t('field.reservation_id', lang=resolved)} | {_mapping_source_column(field_alignment, 'reservation_id')} | {t('field.reservation_id', lang=resolved)} |",
f"| {t('field.aws_sku', lang=resolved)} | {_mapping_source_column(field_alignment, 'sku')} | {t('field.sku', lang=resolved)} |",
f"| {t('field.part_number', lang=resolved)} | {_mapping_source_column(field_alignment, 'part_number')} | {t('field.part_number', lang=resolved)} |",
f"| {t('field.aws_sku', lang=resolved)} | {_mapping_source_column(field_alignment, 'aws_part_number')} | {t('field.aws_sku', lang=resolved)} |",
f"| {t('field.available_qty', lang=resolved)} | {_mapping_source_column(field_alignment, 'available_qty')} | {t('field.qty', lang=resolved)} |",
f"| — | — | {t('align.table.display_only', lang=resolved)} |",
]
+18 -12
View File
@@ -41,14 +41,16 @@ _MESSAGES: dict[str, dict[str, str]] = {
"table.field": "字段",
"table.value": "值",
"field.po": "采购单号",
"field.sku": "料号",
"field.sku": "库存内部料号",
"field.part_number": "内部料号",
"field.customer_part_number": "客户料号",
"field.aws_part_number": "AWS 料号",
"field.reservation_id": "预订单号",
"field.qty": "数量",
"field.unit_price": "单价",
"field.amount": "金额",
"field.required_date": "需求日期",
"field.ship_to": "收货方",
"field.vendor_part_number": "供应商料号",
"field.line_no": "项次",
"field.available_qty": "可用数量",
"field.aws_sku": "料号",
@@ -99,9 +101,9 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.parse_failed": "未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
"workflow.inventory.preview_read_failed": "读取库存表头失败: {error}",
"workflow.inventory.preview_ready": "已读取库存表头与样例行。请根据 schema_preview 推断列映射,调用 apply_inventory_mapping(map_json=...)。",
"workflow.inventory.preview_next": "根据 data.schema_preview.headers 与 sample_rows 推断 JSON:{\"sku\":\"<列名>\",\"reservation_id\":\"<列名>\",\"available_qty\":\"<列名>\"},再调用 apply_inventory_mapping",
"workflow.inventory.preview_next": "根据 data.schema_preview.headers 与 sample_rows 推断 JSON:{\"part_number\":\"<Supplier Sku列>\",\"aws_part_number\":\"<AWS Sku列,可选>\",\"reservation_id\":\"<列名>\",\"available_qty\":\"<列名>\"},再调用 apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "未找到已上传的库存文件。请先 upload_inventory_file。",
"workflow.inventory.mapping_invalid": "map_json 无效或不完整。需要提供 {\"sku\":\"列名\",\"reservation_id\":\"列名\",\"available_qty\":\"列名\"}。(库存的 Reservation ID 列允许为空值,但必须有该列标题)",
"workflow.inventory.mapping_invalid": "map_json 无效或不完整。需要提供 {\"part_number\":\"Supplier Sku列\",\"reservation_id\":\"列名\",\"available_qty\":\"列名\"};aws_part_number 可选。",
"workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。",
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
"workflow.inventory.file_missing": "未收到 file 字段",
@@ -177,14 +179,16 @@ _MESSAGES: dict[str, dict[str, str]] = {
"table.field": "Field",
"table.value": "Value",
"field.po": "PO",
"field.sku": "SKU",
"field.sku": "Inventory SKU",
"field.part_number": "Part Number",
"field.customer_part_number": "Customer Part Number",
"field.aws_part_number": "AWS Part Number",
"field.reservation_id": "Reservation ID",
"field.qty": "Qty",
"field.unit_price": "Unit Price",
"field.amount": "Amount",
"field.required_date": "Required date",
"field.ship_to": "Ship to",
"field.vendor_part_number": "Vendor PN",
"field.line_no": "Line",
"field.available_qty": "Available qty",
"field.aws_sku": "AWS Sku",
@@ -235,9 +239,9 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.parse_failed": "Inventory lines could not be parsed. For large Excel files, use upload_inventory_file; for small tables, paste the content; if inventory is unavailable, use RPA.",
"workflow.inventory.preview_read_failed": "Failed to read inventory headers: {error}",
"workflow.inventory.preview_ready": "Inventory headers and sample rows have been loaded. Please infer the column mapping from schema_preview and call apply_inventory_mapping(map_json=...).",
"workflow.inventory.preview_next": "Infer JSON from data.schema_preview.headers and sample_rows: {\"sku\":\"<column>\",\"reservation_id\":\"<column>\",\"available_qty\":\"<column>\"}, then call apply_inventory_mapping",
"workflow.inventory.preview_next": "Infer JSON from data.schema_preview.headers and sample_rows: {\"part_number\":\"<Supplier Sku column>\",\"aws_part_number\":\"<AWS Sku column, optional>\",\"reservation_id\":\"<column>\",\"available_qty\":\"<column>\"}, then call apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "No uploaded inventory file was found. Please call upload_inventory_file first.",
"workflow.inventory.mapping_invalid": "map_json is invalid or incomplete. You must provide {\"sku\":\"column\",\"reservation_id\":\"column\",\"available_qty\":\"column\"}. The Reservation ID column may contain empty values, but the column header itself must exist.",
"workflow.inventory.mapping_invalid": "map_json is invalid or incomplete. Provide part_number (Supplier Sku), reservation_id, and available_qty mappings; aws_part_number is optional.",
"workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.",
"workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}",
"workflow.inventory.file_missing": "The file field was not received.",
@@ -313,14 +317,16 @@ _MESSAGES: dict[str, dict[str, str]] = {
"table.field": "ฟิลด์",
"table.value": "ค่า",
"field.po": "PO",
"field.sku": "SKU",
"field.sku": "SKU สต็อก",
"field.part_number": "หมายเลขชิ้นส่วน",
"field.customer_part_number": "หมายเลขชิ้นส่วนลูกค้า",
"field.aws_part_number": "หมายเลขชิ้นส่วน AWS",
"field.reservation_id": "Reservation ID",
"field.qty": "จำนวน",
"field.unit_price": "ราคาต่อหน่วย",
"field.amount": "จำนวนเงิน",
"field.required_date": "วันที่ต้องการ",
"field.ship_to": "ผู้รับ",
"field.vendor_part_number": "หมายเลขชิ้นส่วนผู้ขาย",
"field.line_no": "รายการ",
"field.available_qty": "จำนวนคงเหลือ",
"field.aws_sku": "AWS Sku",
@@ -371,9 +377,9 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.inventory.parse_failed": "ไม่สามารถแยกรายการสต็อกได้ สำหรับไฟล์ Excel ขนาดใหญ่ให้ใช้ upload_inventory_file; สำหรับตารางเล็กสามารถวางข้อความได้; หากไม่มีสต็อกให้ใช้ RPA",
"workflow.inventory.preview_read_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
"workflow.inventory.preview_ready": "อ่านหัวตารางและแถวตัวอย่างของสต็อกแล้ว โปรดอนุมานการจับคู่คอลัมน์จาก schema_preview แล้วเรียก apply_inventory_mapping(map_json=...)",
"workflow.inventory.preview_next": "อนุมาน JSON จาก data.schema_preview.headers และ sample_rows: {\"sku\":\"<คอลัมน์>\",\"reservation_id\":\"<คอลัมน์>\",\"available_qty\":\"<คอลัมน์>\"} แล้วจึงเรียก apply_inventory_mapping",
"workflow.inventory.preview_next": "อนุมาน JSON จาก data.schema_preview.headers และ sample_rows โดยใช้ part_number จาก Supplier Sku, aws_part_number จาก AWS Sku (ไม่บังคับ), reservation_id และ available_qty แล้วเรียก apply_inventory_mapping",
"workflow.inventory.uploaded_file_missing_short": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดเรียก upload_inventory_file ก่อน",
"workflow.inventory.mapping_invalid": "map_json ไม่ถูกต้องหรือไม่ครบ ต้องระบุ {\"sku\":\"ชื่อคอลัมน์\",\"reservation_id\":\"ชื่อคอลัมน์\",\"available_qty\":\"ชื่อคอลัมน์\"} โดยคอลัมน์ Reservation ID สามารถมีค่าว่างได้ แต่ต้องมีหัวคอลัมน์นี้",
"workflow.inventory.mapping_invalid": "map_json ไม่ถูกต้องหรือไม่ครบ ต้องระบุ part_number (Supplier Sku), reservation_id และ available_qty; aws_part_number เป็นตัวเลือก",
"workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers",
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
"workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file",
@@ -62,16 +62,15 @@ def parse_intake_business_summary(
'required_date': str(parsed.get('required_date') or '').strip() or None,
'lines': [
{
'sku': str(line.get('sku') or '').strip() or None,
'part_number': str(line.get('part_number') or '').strip() or None,
'reservation_id': str(line.get('reservation_id') or '').strip() or None,
'qty': line.get('qty'),
'uom': str(line.get('uom') or '').strip() or None,
'po_number': str(line.get('po_number') or '').strip() or None,
'allocation_id': str(line.get('allocation_id') or '').strip() or None,
'source_type': str(line.get('source_type') or '').strip() or None,
'hub_code': str(line.get('hub_code') or '').strip() or None,
'customer_sku': str(line.get('customer_sku') or '').strip() or None,
'vendor_part_number': str(line.get('vendor_part_number') or '').strip() or None,
'inventory_source_hint': str(line.get('inventory_source_hint') or '').strip() or None,
'customer_part_number': str(line.get('customer_part_number') or '').strip() or None,
'aws_part_number': str(line.get('aws_part_number') or '').strip() or None,
}
for line in lines
if isinstance(line, dict)
@@ -689,7 +689,6 @@ def run_intake_parse(
locked.structured_result_json = tech_summary
locked.parse_warnings_json = warnings
locked.order_extraction_status = 'not_started'
locked.order_extraction_version = None
locked.order_extraction_error_code = None
locked.order_extraction_error_message = None
locked.updated_at = datetime.utcnow()
@@ -855,7 +854,6 @@ def candidate_to_notice_item(
'content_fingerprint_version': candidate.content_fingerprint_version,
'structured': {
**(structured.get('business_summary') or {}),
'_order_extraction_contract': candidate.extraction_version,
},
'document_version': 1,
'duplicate_resolution_type': 'normal',
@@ -210,7 +210,6 @@ def serialize_intake(
'parse_status': intake.parse_status,
'parser_version': intake.parser_version,
'order_extraction_status': intake.order_extraction_status,
'order_extraction_version': intake.order_extraction_version,
'order_extraction_error_code': intake.order_extraction_error_code,
'order_extraction_error_message': intake.order_extraction_error_message,
'parse_summary': parse_summary,
@@ -12,11 +12,12 @@ from typing import Any
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
SYSTEM_FIELDS = ("sku", "reservation_id", "available_qty")
SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty")
REQUIRED_SYSTEM_FIELDS = ("part_number", "reservation_id", "available_qty")
def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
"""将 map_json / JSON 字符串规范化为 sku+reservation_id+available_qty 三字段映射;不完整时返回 None。"""
"""将 map_json 规范为库存 v2 字段映射;缺内部料号、Reservation 或可用量时返回 None。"""
data: dict[str, Any] | None = None
if isinstance(raw, dict):
data = raw
@@ -44,7 +45,7 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
text = str(value).strip()
if text:
result[key] = text
return result if "sku" in result and "available_qty" in result and "reservation_id" in result else None
return result if all(field in result for field in REQUIRED_SYSTEM_FIELDS) else None
def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
@@ -69,9 +70,23 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
return None
mapping: dict[str, str] = {}
sku = pick("sku", "AWS Sku", "AWS SKU", "料号", "Part Number", "Material")
if sku:
mapping["sku"] = sku
part_number = pick(
"part_number",
"Supplier Sku",
"Supplier SKU",
"Supplier Part Number",
"Supplier Part No",
"Part Number",
"Part No",
"料号",
"SKU",
)
if part_number:
mapping["part_number"] = part_number
aws_part_number = pick("aws_part_number", "AWS Sku", "AWS SKU", "AWS SKU#", "AWS Sku#")
if aws_part_number:
mapping["aws_part_number"] = aws_part_number
reservation = pick(
"reservation_id",
@@ -94,8 +109,8 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
"""映射是否同时包含 sku、reservation_id、available_qty 三列。"""
return bool(field_mapping.get("sku") and field_mapping.get("available_qty") and field_mapping.get("reservation_id"))
"""映射是否同时包含内部料号、Reservation ID 与可用数量。"""
return all(bool(field_mapping.get(field)) for field in REQUIRED_SYSTEM_FIELDS)
def validate_field_mapping_against_headers(
@@ -107,14 +122,15 @@ def validate_field_mapping_against_headers(
lower_set = {h.lower() for h in norm_headers if h}
errors: list[str] = []
labels = {
"sku": "sku",
"part_number": "part_number",
"aws_part_number": "aws_part_number",
"reservation_id": "reservation_id",
"available_qty": "available_qty",
}
for key, label in labels.items():
name = str(field_mapping.get(key) or "").strip()
if not name:
if key in ("sku", "available_qty", "reservation_id"):
if key in REQUIRED_SYSTEM_FIELDS:
errors.append(f"缺少 {label} 列映射")
continue
if name not in norm_headers and name.lower() not in lower_set:
@@ -149,7 +165,8 @@ def resolve_columns_from_field_mapping(
# required mapping is provided explicitly by LLM or user.
columns = _resolve_inventory_columns(norm_headers, DEFAULT_COLUMN_MAP)
columns.update({
"sku": idx_for(field_mapping.get("sku")),
"part_number": idx_for(field_mapping.get("part_number")),
"aws_part_number": idx_for(field_mapping.get("aws_part_number")),
"reservation_id": idx_for(field_mapping.get("reservation_id")),
"available_qty": None,
})
@@ -187,10 +204,15 @@ def build_column_meta_from_mapping(
"mapping_source": mapping_source,
"field_mapping": dict(field_mapping),
"mapping": {
"sku": {
"system_field": "sku",
"label": "AWS Sku / 料号",
"source_column": source_column(columns.get("sku")),
"part_number": {
"system_field": "part_number",
"label": "Supplier Sku / 内部料号",
"source_column": source_column(columns.get("part_number")),
},
"aws_part_number": {
"system_field": "aws_part_number",
"label": "AWS Sku / AWS 料号",
"source_column": source_column(columns.get("aws_part_number")),
},
"reservation_id": {
"system_field": "reservation_id",
@@ -703,7 +703,36 @@ def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) ->
def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
"""校验客户与库存源门禁(skipped/failed/success 共用)。"""
"""
复核 RPA 触发后可能漂移的订单与路由门禁(skipped/failed/success 共用)。
核心逻辑:先阻断新增字段冲突和 Reservation 异常,再校验客户、库存源;
防止 RPA 执行期间人工改单后,旧回调继续把库存快照写入已失效任务。
"""
conflict_gate = field_conflict_gate_response(task, lang="zh")
if conflict_gate is not None:
return conflict_gate
reservation_issues = reservation_gate_issues(read_task_order_lines(task))
if reservation_issues:
return tool_response(
status="needs_human",
task=task,
message=(
f"当前订单有 {len(reservation_issues)} 项 Reservation 门禁问题,"
"已拒绝处理库存 RPA 回调。"
),
data={
**serialize_task_for_tool(task),
"reservation_id_required": {
"order_missing_count": len(reservation_issues),
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
stop_agent_turn=True,
)
try:
assert_customer_identity_gate(task, operation='rpa_inventory_callback')
assert_inventory_source_gate(task, operation="rpa_inventory_callback")
@@ -21,22 +21,28 @@ from openpyxl import load_workbook
from app.services.shipping_notice.reservation_id import normalize_reservation_id, validated_reservation_id
# 默认列映射:含 AWS DUB On Hand Inventory 模板(AWS Sku / Reservation ID / Qty)
# 默认列映射:Supplier Sku 是内部主匹配料号;AWS Sku 仅作可选追溯字段。
DEFAULT_COLUMN_MAP = {
# SKU
"料号": "sku",
"SKU": "sku",
"sku": "sku",
"AWS Sku": "sku",
"AWS SKU": "sku",
"Aws Sku": "sku",
"AWS SKU#": "sku",
"AWS Sku#": "sku",
"SKU#": "sku",
"Part No": "sku",
"Part No.": "sku",
"P/N": "sku",
"PN": "sku",
# 内部料号
"Supplier Sku": "part_number",
"Supplier SKU": "part_number",
"Supplier Part Number": "part_number",
"Supplier Part No": "part_number",
"料号": "part_number",
"SKU": "part_number",
"sku": "part_number",
"SKU#": "part_number",
"Part Number": "part_number",
"Part No": "part_number",
"Part No.": "part_number",
"P/N": "part_number",
"PN": "part_number",
# AWS 追溯料号
"AWS Sku": "aws_part_number",
"AWS SKU": "aws_part_number",
"Aws Sku": "aws_part_number",
"AWS SKU#": "aws_part_number",
"AWS Sku#": "aws_part_number",
# Reservation
"Reservation ID": "reservation_id",
"Reservation Id": "reservation_id",
@@ -115,11 +121,13 @@ def _map_header(header: str, col_map: dict[str, str]) -> str | None:
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
idx_sku = idx_reservation = idx_available = idx_qty = idx_odm = None
idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = None
for i, h in enumerate(headers):
mapped = _map_header(h, col_map)
if mapped == "sku" and idx_sku is None:
idx_sku = i
if mapped == "part_number" and idx_part_number is None:
idx_part_number = i
elif mapped == "aws_part_number" and idx_aws_part_number is None:
idx_aws_part_number = i
elif mapped == "reservation_id" and idx_reservation is None:
idx_reservation = i
elif mapped == "available_qty" and idx_available is None:
@@ -138,7 +146,8 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d
break
return {
"sku": idx_sku,
"part_number": idx_part_number,
"aws_part_number": idx_aws_part_number,
"reservation_id": idx_reservation,
"available_qty": idx_available,
"qty": idx_qty,
@@ -163,28 +172,29 @@ def _normalize_inventory_row(
row: list[Any] | tuple[Any, ...],
columns: dict[str, int | None],
*,
default_sku_index: int = 0,
default_part_number_index: int | None = None,
default_qty_index: int = 1,
) -> dict[str, Any] | None:
idx_sku = columns.get("sku")
if idx_sku is None:
idx_sku = default_sku_index
sku = str(_cell(row, idx_sku) or "").strip()
if not sku:
idx_part_number = columns.get("part_number")
if idx_part_number is None:
idx_part_number = default_part_number_index
if idx_part_number is None:
return None
part_number = str(_cell(row, idx_part_number) or "").strip()
if not part_number:
return None
skip_tokens = {
"sku",
"part_number",
"supplier sku",
"料号",
"aws sku",
"qty",
"qty available",
"可用数量",
"reservation id",
"com id",
}
if sku.lower() in skip_tokens:
if part_number.lower() in skip_tokens:
return None
reservation_id = ""
@@ -202,9 +212,14 @@ def _normalize_inventory_row(
available_qty = _parse_qty(_cell(row, default_qty_index))
parsed: dict[str, Any] = {
"sku": sku,
"part_number": part_number,
"available_qty": available_qty,
}
idx_aws = columns.get("aws_part_number")
if idx_aws is not None:
aws_part_number = str(_cell(row, idx_aws) or "").strip()
if aws_part_number:
parsed["aws_part_number"] = aws_part_number
if reservation_id:
parsed["reservation_id"] = reservation_id
idx_odm = columns.get("odm_id")
@@ -230,7 +245,7 @@ def _score_header_candidate(cells: list[Any]) -> int:
mapped_fields.add(mapped)
score = len(mapped_fields) * 10
if "sku" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields):
if "part_number" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields):
score += 30
return score
@@ -333,9 +348,12 @@ def describe_inventory_columns(
qty_note = "Qty"
inferred_mapping: dict[str, str] = {}
sku_src = source_column(columns.get("sku"))
if sku_src:
inferred_mapping["sku"] = sku_src
part_number_src = source_column(columns.get("part_number"))
if part_number_src:
inferred_mapping["part_number"] = part_number_src
aws_part_number_src = source_column(columns.get("aws_part_number"))
if aws_part_number_src:
inferred_mapping["aws_part_number"] = aws_part_number_src
rid_src = source_column(columns.get("reservation_id"))
if rid_src:
inferred_mapping["reservation_id"] = rid_src
@@ -351,10 +369,15 @@ def describe_inventory_columns(
return {
"headers": [str(h or "").strip() for h in headers],
"mapping": {
"sku": {
"system_field": "sku",
"label": "AWS Sku",
"source_column": sku_src,
"part_number": {
"system_field": "part_number",
"label": "Supplier Sku / 内部料号",
"source_column": part_number_src,
},
"aws_part_number": {
"system_field": "aws_part_number",
"label": "AWS Sku / AWS 料号",
"source_column": aws_part_number_src,
},
"reservation_id": {
"system_field": "reservation_id",
@@ -397,9 +420,9 @@ def build_field_alignment_preview(
if inventory_lines and not res_source:
warnings.append("库存表未识别到 Reservation ID 相关列(COM ID / Reservation Order 等)。")
sku_source = (inv_mapping.get("sku") or {}).get("source_column")
if notice_lines and inventory_lines and not sku_source:
warnings.append("库存表未识别到 AWS Sku 列,当前按第一列作为料号解析。")
part_number_source = (inv_mapping.get("part_number") or {}).get("source_column")
if notice_lines and inventory_lines and not part_number_source:
warnings.append("库存表未识别 Supplier Sku / 内部料号列,无法执行库存匹配。")
qty_source = (inv_mapping.get("available_qty") or {}).get("source_column")
if inventory_lines and not qty_source:
@@ -407,7 +430,9 @@ def build_field_alignment_preview(
notice_preview = [
{
"sku": str(line.get("sku") or "").strip(),
"part_number": str(line.get("part_number") or "").strip(),
"customer_part_number": str(line.get("customer_part_number") or "").strip(),
"aws_part_number": str(line.get("aws_part_number") or "").strip(),
"reservation_id": str(line.get("reservation_id") or "").strip(),
"qty": line.get("qty"),
"unit_price": line.get("unit_price"),
@@ -417,7 +442,8 @@ def build_field_alignment_preview(
]
sample_inventory = [
{
"sku": line.get("sku"),
"part_number": line.get("part_number"),
"aws_part_number": line.get("aws_part_number"),
"reservation_id": line.get("reservation_id", ""),
"available_qty": line.get("available_qty"),
}
@@ -427,7 +453,7 @@ def build_field_alignment_preview(
field_mapping_meta = mapping.get("field_mapping") if isinstance(mapping.get("field_mapping"), dict) else {}
fallback_mapping = {
k: str((inv_mapping.get(k) or {}).get("source_column") or "").strip()
for k in ("sku", "reservation_id", "available_qty")
for k in ("part_number", "aws_part_number", "reservation_id", "available_qty")
}
fallback_mapping = {k: v for k, v in fallback_mapping.items() if v}
if not fallback_mapping and field_mapping_meta:
@@ -442,7 +468,7 @@ def build_field_alignment_preview(
match_key=mapping.get("match_key") if isinstance(mapping.get("match_key"), list) else None,
)
if not match_rule:
match_rule, _, _ = resolve_match_rule(fallback_mapping or {"sku": "sku", "available_qty": "qty"})
match_rule, _, _ = resolve_match_rule(fallback_mapping or {"part_number": "Supplier Sku", "available_qty": "qty"})
return {
"match_rule": match_rule,
@@ -471,7 +497,7 @@ def parse_inventory_rows(
else:
col_map = _column_map()
columns = _resolve_inventory_columns(headers, col_map)
has_header = columns["sku"] is not None or columns["available_qty"] is not None or columns["qty"] is not None
has_header = columns["part_number"] is not None or columns["available_qty"] is not None or columns["qty"] is not None
if not has_header and headers and not field_mapping:
has_header = any(_map_header(h, _column_map()) for h in headers)
@@ -492,7 +518,7 @@ def parse_inventory_text(
) -> tuple[list[dict[str, Any]], list[str], dict[str, Any]]:
"""从聊天文本或文档提取器输出解析库存表格(TSV/CSV 形式)。"""
warnings: list[str] = []
empty_meta: dict[str, Any] = {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]}
empty_meta: dict[str, Any] = {"headers": [], "mapping": {}, "match_key": ["part_number", "reservation_id"]}
text = str(raw_text or "").strip()
if not text:
return [], ["empty inventory text"], empty_meta
@@ -514,7 +540,7 @@ def parse_inventory_text(
else:
col_map = _column_map()
columns = _resolve_inventory_columns(header, col_map)
has_header = columns["sku"] is not None or any(_map_header(h, col_map) for h in header)
has_header = columns["part_number"] is not None or any(_map_header(h, col_map) for h in header)
column_meta = describe_inventory_columns(header) if has_header else empty_meta
data_rows: list[list[Any]] = rows[1:] if has_header else rows
@@ -561,8 +587,9 @@ def read_inventory_schema_preview(
"suggested_mapping": suggested,
"header_row_index": header_idx + 1,
"mapping_targets": {
"sku": "料号 / AWS Sku",
"reservation_id": "Reservation ID / COM ID(可选)",
"part_number": "Supplier Sku / 内部料号",
"aws_part_number": "AWS Sku / AWS 料号(可选)",
"reservation_id": "Reservation ID / COM ID(必填)",
"available_qty": "可用数量 / Qty Available / Qty",
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 map_json.match_rule)",
},
@@ -586,7 +613,7 @@ def parse_inventory_excel_with_meta(
"""
rows, _total = _load_excel_rows(path)
if not rows:
return [], {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]}
return [], {"headers": [], "mapping": {}, "match_key": ["part_number", "reservation_id"]}
header_idx: int | None = None
if header_row_index is not None:
@@ -604,7 +631,7 @@ def parse_inventory_excel_with_meta(
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
suggested = suggest_field_mapping(headers)
if suggested.get("sku") and suggested.get("available_qty"):
if suggested.get("part_number") and suggested.get("available_qty"):
field_mapping = suggested
mapping_source = "rules"
@@ -105,9 +105,9 @@ def _extract_destination_object(candidates: list[str], value: Any) -> None:
def extract_destination_candidates(task: ShippingTask) -> list[str]:
"""
从任务解析结果提取目的地/港口/仓库候选。
【AI 触发时机】:订单解析后由裁决服务调用,Dify 行级 source_type 与目的地字段都作为候选证据。
【AI 触发时机】:订单解析后由裁决服务调用,行级 inventory_source_hint 与目的地字段都作为候选证据。
核心逻辑:只读取 orders[].lines[].source_type,禁止使用 Task.source_type;
核心逻辑:只读取 orders[].lines[].inventory_source_hint,禁止使用 Task.source_type;
Task.source_type 表示 PDF/manual 等接入来源,不是库存源路由证据。
Args:
task: 待裁决库存源的发货任务。
@@ -128,8 +128,7 @@ def extract_destination_candidates(task: ShippingTask) -> list[str]:
_extract_destination_object(candidates, line.get("destination"))
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to", "raw_text"):
_append_candidate(candidates, line.get(key))
_append_candidate(candidates, line.get("source_type"))
_append_candidate(candidates, line.get("hub_code"))
_append_candidate(candidates, line.get("inventory_source_hint"))
return candidates
@@ -116,7 +116,7 @@ def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
return {}
result: dict[str, str] = {}
for key in ("sku", "reservation_id", "available_qty"):
for key in ("part_number", "aws_part_number", "reservation_id", "available_qty"):
value = inner.get(key)
if value is None:
continue
+17 -16
View File
@@ -22,16 +22,17 @@ def _norm_reservation(value: Any) -> str:
return validated_reservation_id(value)
def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]:
return (_norm(sku), _norm_reservation(reservation_id))
def _line_key(part_number: str, reservation_id: str | None) -> tuple[str, str]:
"""构造内部料号与 Reservation 的库存定位键。"""
return (_norm(part_number), _norm_reservation(reservation_id))
def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]:
"""按 (sku, reservation_id) 汇总库存 available_qty。"""
"""按库存 part_number 与 reservation_id 汇总 available_qty。"""
totals: dict[tuple[str, str], float] = {}
for row in inventory_lines:
sku = _norm(row.get("sku"))
if not sku:
part_number = _norm(row.get("part_number"))
if not part_number:
continue
reservation_id = _norm_reservation(row.get("reservation_id"))
if not reservation_id:
@@ -40,21 +41,21 @@ def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[st
qty = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
qty = 0.0
key = _line_key(sku, reservation_id)
key = _line_key(part_number, reservation_id)
totals[key] = totals.get(key, 0.0) + qty
return totals
def _available_for_notice_line(
sku: str,
part_number: str,
reservation_id: str | None,
inv_totals: dict[tuple[str, str], float],
) -> float:
sku_n = _norm(sku)
part_number_normalized = _norm(part_number)
rid = _norm_reservation(reservation_id)
if not rid:
return 0.0
return inv_totals.get((sku_n, rid), 0.0)
return inv_totals.get((part_number_normalized, rid), 0.0)
def match_notice_lines(
@@ -64,14 +65,14 @@ def match_notice_lines(
progress_callback: Callable[[int, int], None] | None = None,
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
"""
将订单行与库存行按 (sku, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。
将订单行与库存行按 (part_number, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。
核心逻辑:聚合库存 → 逐行比对 required vs available → 汇总 match_status 与 shortages。
Returns:
tuple: (match_status, line_results, shortage_json)。
"""
# [STEP 1] 按 (sku, reservation_id) 聚合库存可用量。
# [STEP 1] 库存 Supplier Sku 已规范为 part_number,与订单内部料号直接配对。
inv_totals = _aggregate_inventory(inventory_lines)
line_results: list[dict[str, Any]] = []
@@ -82,14 +83,14 @@ def match_notice_lines(
# [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。
total_lines = len(notice_lines)
for index, line in enumerate(notice_lines, start=1):
sku = _norm(line.get("sku"))
part_number = _norm(line.get("part_number"))
reservation_id = _norm_reservation(line.get("reservation_id")) or None
try:
required = float(line.get("qty") or 0)
except (TypeError, ValueError):
required = 0.0
available = _available_for_notice_line(sku, reservation_id, inv_totals)
available = _available_for_notice_line(part_number, reservation_id, inv_totals)
if available >= required:
line_status = "ok"
shortage = 0.0
@@ -103,7 +104,7 @@ def match_notice_lines(
has_shortage = True
result = {
"sku": sku,
"part_number": part_number,
"reservation_id": reservation_id or "",
"required_qty": required,
"available_qty": available,
@@ -170,7 +171,7 @@ def format_match_summary(
lines.append(
"| # | "
f"{t('field.reservation_id', lang=resolved)} | "
f"{t('field.sku', lang=resolved)} | "
f"{t('field.part_number', lang=resolved)} | "
f"{t('match.col.order_qty', lang=resolved)} | "
f"{t('match.col.inv_qty', lang=resolved)} | "
f"{t('match.col.gap', lang=resolved)} | "
@@ -203,7 +204,7 @@ def format_match_summary(
"| "
f"{index} | "
f"{_md_cell(row.get('reservation_id'))} | "
f"{_md_cell(row.get('sku'))} | "
f"{_md_cell(row.get('part_number'))} | "
f"{_fmt_qty(required)} | "
f"{_fmt_qty(available)} | "
f"{gap_cell} | "
@@ -61,8 +61,8 @@ def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]:
def infer_match_key(field_mapping: dict[str, str]) -> list[str]:
"""根据 field_mapping 推断匹配键列表(默认 sku + reservation_id)。"""
keys = ["sku"]
"""根据库存列映射推断业务匹配键列表(默认 part_number + reservation_id)。"""
keys = ["part_number"]
if str(field_mapping.get("reservation_id") or "").strip():
keys.append("reservation_id")
return keys
@@ -74,18 +74,18 @@ def build_match_rule_fallback(
match_key: list[str] | None = None,
) -> str:
"""LLM 未提供 match_rule 时,根据列映射动态生成中文规则说明。"""
sku_col = str(field_mapping.get("sku") or "sku").strip() or "sku"
part_number_col = str(field_mapping.get("part_number") or "Supplier Sku").strip() or "Supplier Sku"
qty_col = str(field_mapping.get("available_qty") or "可用数量").strip() or "可用数量"
keys = match_key or infer_match_key(field_mapping)
if "reservation_id" in keys:
rid_col = str(field_mapping.get("reservation_id") or "Reservation ID").strip() or "Reservation ID"
return (
f"以库存列「{sku_col}」→ 订单 sku、「{rid_col}」→ 订单 reservation_id 为匹配键,"
f"以库存列「{part_number_col}」→ 订单 part_number、「{rid_col}」→ 订单 reservation_id 为匹配键,"
f"汇总「{qty_col}」可用量后与订单 qty 比对(库存缺 reservation_id 的行不参与)。"
)
return (
f"以库存列「{sku_col}」→ 订单 sku 为匹配键,"
f"以库存列「{part_number_col}」→ 订单 part_number 为匹配键,"
f"汇总「{qty_col}」可用量后与订单 qty 比对。"
)
@@ -10,37 +10,43 @@ from __future__ import annotations
NOTICE_LINE_FIELDS = (
"line_no",
"sku",
"part_number",
"qty",
"unit_price",
"amount",
"currency",
"reservation_id",
"required_date",
"vendor_part_number",
"customer_part_number",
"aws_part_number",
"uom",
"remark",
"po_number",
"allocation_id",
"source_type",
"hub_code",
"customer_sku",
"inventory_source_hint",
)
# 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格)
NOTICE_COLUMN_MAP: dict[str, str] = {
# SKU
"料号": "sku",
"SKU": "sku",
"sku": "sku",
"AWS Sku": "sku",
"AWS SKU": "sku",
"Part Number": "sku",
"Material": "sku",
"Material No": "sku",
"产品编号": "sku",
"Allocated APN": "sku",
"Allocated HHPN": "customer_sku",
# 内部料号
"料号": "part_number",
"Part Number": "part_number",
"产品编号": "part_number",
"MPN": "part_number",
"Vendor Part Number": "part_number",
"Vendor Part No": "part_number",
"Vendor PN": "part_number",
"Supplier Part No": "part_number",
"Supplier Part Number": "part_number",
# 外部料号
"Customer PN": "customer_part_number",
"Customer Part Number": "customer_part_number",
"Allocated HHPN": "customer_part_number",
"Allocated APN": "aws_part_number",
"Material": "aws_part_number",
"Material No": "aws_part_number",
"AWS Sku": "aws_part_number",
"AWS SKU": "aws_part_number",
# 项次 / Item
"项次": "line_no",
"line_no": "line_no",
@@ -110,28 +116,17 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"交货日期": "required_date",
"要求交期": "required_date",
"Required Delivery Date": "required_date",
# 供应商料号
"Vendor Part Number": "vendor_part_number",
"Vendor Part No": "vendor_part_number",
"Vendor PN": "vendor_part_number",
"vendor_part_number": "vendor_part_number",
"Supplier Part No": "vendor_part_number",
"Supplier Part Number": "vendor_part_number",
"MPN": "vendor_part_number",
"供应商料号": "vendor_part_number",
"供应商料号": "part_number",
# 邮件批量委托索引字段
"PO": "po_number",
"PO Number": "po_number",
"allocation_id": "allocation_id",
"Allocation ID": "allocation_id",
"source type": "source_type",
"Source Type": "source_type",
# Hub Code 与 Source Type 分列落库:前者是站点/Hub 线索,后者是库存来源提示。
"Hub Code": "hub_code",
"Hub": "hub_code",
"HUB": "hub_code",
"hub_code": "hub_code",
"hubCode": "hub_code",
"source type": "inventory_source_hint",
"Source Type": "inventory_source_hint",
"Hub Code": "inventory_source_hint",
"Hub": "inventory_source_hint",
"HUB": "inventory_source_hint",
# 单位
"单位": "uom",
"UOM": "uom",
@@ -152,19 +147,18 @@ RESERVATION_ID_FORBIDDEN_HEADERS = frozenset(
NOTICE_FIELD_LABELS = {
"line_no": "项次 / Item / Line No",
"sku": "SKU / 料号",
"part_number": "内部料号 / Part Number",
"qty": "需求数量",
"unit_price": "单价",
"amount": "金额",
"currency": "币种",
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
"required_date": "要求交期 / 交货日期",
"vendor_part_number": "供应商料号",
"customer_part_number": "客户料号 / Customer Part Number",
"aws_part_number": "AWS 料号 / AWS Part Number",
"po_number": "PO Number",
"allocation_id": "Allocation ID",
"source_type": "库存来源提示",
"hub_code": "Hub Code / 站点线索",
"customer_sku": "客户料号 / HHPN",
"inventory_source_hint": "库存来源提示 / Hub Code",
}
HEADER_SKIP_TOKENS = {
@@ -31,22 +31,25 @@ def parse_notice_row(
row: list[Any] | tuple[Any, ...],
columns: dict[str, int | None],
*,
default_sku_index: int = 0,
default_part_number_index: int | None = None,
default_qty_index: int = 1,
) -> dict[str, Any] | None:
"""
按列映射从单行表格数据提取一条订单行。
核心逻辑:校验 SKU 与 qty 必填;依次填充 reservation、价格、币种、交期等可选字段。
核心逻辑:校验原子 part_number 与 qty 必填;依次填充 reservation、价格、币种、交期等可选字段。
"""
idx_sku = columns.get("sku")
if idx_sku is None:
idx_sku = default_sku_index
idx_part_number = columns.get("part_number")
if idx_part_number is None:
idx_part_number = default_part_number_index
sku = str(cell(row, idx_sku) or "").strip()
if not sku:
if idx_part_number is None:
return None
if sku.lower() in HEADER_SKIP_TOKENS:
part_number = str(cell(row, idx_part_number) or "").strip()
if not part_number or "/" in part_number:
return None
if part_number.lower() in HEADER_SKIP_TOKENS:
return None
idx_qty = columns.get("qty")
@@ -57,9 +60,9 @@ def parse_notice_row(
if qty is None or qty <= 0:
return None
parsed: dict[str, Any] = {"sku": sku, "qty": qty, "uom": "EA"}
parsed: dict[str, Any] = {"part_number": part_number, "qty": qty, "uom": "EA"}
skip_indices: set[int] = {idx_sku}
skip_indices: set[int] = {idx_part_number}
if idx_qty is not None:
skip_indices.add(idx_qty)
@@ -123,13 +126,7 @@ def parse_notice_row(
if required_date:
parsed["required_date"] = required_date
idx_vendor_part = columns.get("vendor_part_number")
if idx_vendor_part is not None:
vendor_part_number = str(cell(row, idx_vendor_part) or "").strip()
if vendor_part_number:
parsed["vendor_part_number"] = vendor_part_number
for field in ("po_number", "allocation_id", "source_type", "hub_code", "customer_sku"):
for field in ("po_number", "allocation_id", "inventory_source_hint", "customer_part_number", "aws_part_number"):
idx = columns.get(field)
if idx is None:
continue
@@ -146,7 +143,7 @@ def parse_notice_row(
def score_notice_header_row(cells: list[Any]) -> int:
"""为候选表头行打分:映射字段越多、含 sku+qty 组合时分越高。"""
"""为候选表头行打分:映射字段越多、含 part_number+qty 组合时分越高。"""
headers = [str(c or "").strip() for c in cells]
if len([h for h in headers if h]) < 2:
return 0
@@ -156,7 +153,7 @@ def score_notice_header_row(cells: list[Any]) -> int:
if field:
mapped.add(field)
score = len(mapped) * 10
if "sku" in mapped and "qty" in mapped:
if "part_number" in mapped and "qty" in mapped:
score += 30
if "reservation_id" in mapped:
score += 10
@@ -181,13 +178,13 @@ def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> l
"""
按表头定义解析发货通知表格数据行。
核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取 SKU、数量、金额等字段。
核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取内部料号、数量、金额等字段。
"""
columns = resolve_notice_columns(headers)
idx_res = columns.get("reservation_id")
if idx_res is not None and idx_res < len(headers):
columns["_reservation_id_header"] = str(headers[idx_res] or "").strip()
has_header = columns.get("sku") is not None or columns.get("qty") is not None
has_header = columns.get("part_number") is not None or columns.get("qty") is not None
if not has_header and headers:
has_header = any(map_notice_header(h) for h in headers)
if not has_header:
@@ -45,11 +45,75 @@ _map_notice_header = map_notice_header
_parse_number = parse_number
def split_part_number_tokens(value: Any) -> list[str]:
"""
将复合料号文本拆成稳定的原子候选 token。
核心逻辑:仅把 `/` 视为业务确认的组合分隔符,去除空段和首尾空白;本函数不猜测 token 角色。
Args:
value: 原始表格单元格或 LLM 候选值。
Returns:
保持原顺序且去重的非空 token;无值时返回空数组。
"""
tokens: list[str] = []
for part in str(value or '').split('/'):
token = part.strip()
if token and token not in tokens:
tokens.append(token)
return tokens
def resolve_composite_part_numbers(value: Any) -> dict[str, str]:
"""
按已冻结 TEMP 业务规则解析二段复合料号。
核心逻辑:仅当恰有两个原子 token 且其中一个以 TEMP- 开头时,确定 TEMP 为客户料号、另一段为内部料号;
其余组合保持未解析,交由字段冲突流程处理。
Args:
value: 可能包含 `/` 的原始料号文本。
Returns:
可确定时返回 part_number/customer_part_number;否则返回空对象。
"""
tokens = split_part_number_tokens(value)
if len(tokens) != 2:
return {}
customer_tokens = [token for token in tokens if token.upper().startswith('TEMP-')]
if len(customer_tokens) != 1:
return {}
customer_part_number = customer_tokens[0]
part_number = next(token for token in tokens if token != customer_part_number)
return {
'part_number': part_number,
'customer_part_number': customer_part_number,
}
def non_atomic_part_number_field(raw: dict[str, Any] | None) -> str | None:
"""
检查订单行三类料号是否违反原子值契约。
核心逻辑:内部料号仅允许命中已冻结 TEMP 二段拆分规则;客户料号与 AWS 料号出现 `/` 时直接返回字段名。
Args:
raw: 待检查的原始订单行。
Returns:
首个非法字段名;全部合法时返回 None。
"""
if not isinstance(raw, dict):
return None
raw_part_number = str(raw.get("part_number") or "").strip()
if "/" in raw_part_number and not resolve_composite_part_numbers(raw_part_number):
return "part_number"
for field in ("customer_part_number", "aws_part_number"):
if "/" in str(raw.get(field) or "").strip():
return field
return None
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"""
标准化单条发货通知订单行。
核心逻辑:校验 SKU 与数量必填项,统一字段别名、币种、交期和 Reservation ID,并在缺少 amount 时按单价回填。
核心逻辑:校验原子 part_number 与数量必填项,统一币种、交期和 Reservation ID,并在缺少 amount 时按单价回填。
Args:
raw: 原始订单行字典,可包含多种字段别名。
@@ -58,9 +122,13 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"""
if not isinstance(raw, dict):
return None
if non_atomic_part_number_field(raw):
return None
sku = str(raw.get("sku") or raw.get("part_number") or raw.get("material") or "").strip()
if not sku:
raw_part_number = str(raw.get("part_number") or "").strip()
composite = resolve_composite_part_numbers(raw_part_number)
part_number = composite.get('part_number') or raw_part_number
if not part_number or "/" in part_number:
return None
qty = parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity"))
@@ -68,7 +136,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
return None
line: dict[str, Any] = {
"sku": sku,
"part_number": part_number,
"qty": qty,
"uom": str(raw.get("uom") or "EA").strip() or "EA",
}
@@ -131,34 +199,21 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
if required_date:
line["required_date"] = required_date
vendor_part_number = str(
raw.get("vendor_part_number")
or raw.get("vendorPartNumber")
or raw.get("vendor_pn")
or raw.get("supplier_part_number")
or raw.get("supplierPartNumber")
or ""
).strip()
if vendor_part_number:
line["vendor_part_number"] = vendor_part_number
optional_aliases = {
"po_number": ("po_number", "poNumber", "PO", "PO Number"),
"allocation_id": ("allocation_id", "allocationId", "Allocation ID"),
"source_type": (
"source_type",
"sourceType",
"inventory_source_hint": (
"inventory_source_hint",
"Source Type",
),
"hub_code": (
"hub_code",
"hubCode",
"Hub Code",
"Hub",
"HUB",
),
"customer_sku": ("customer_sku", "customerSku", "allocated_hhpn", "Allocated HHPN"),
"customer_part_number": ("customer_part_number", "Customer Part Number", "Customer PN", "Allocated HHPN"),
"aws_part_number": ("aws_part_number", "AWS Sku", "AWS SKU"),
}
if composite.get('customer_part_number'):
line['customer_part_number'] = composite['customer_part_number']
for field, aliases in optional_aliases.items():
value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "")
if value:
@@ -175,7 +230,7 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
"""
批量标准化订单行列表。
核心逻辑:逐行调用 `normalize_notice_line`,自动过滤掉无效、缺 SKU 或缺数量的脏数据。
核心逻辑:逐行调用 `normalize_notice_line`,自动过滤缺原子 part_number 或缺数量的脏数据。
"""
if not isinstance(lines, list):
return []
@@ -195,7 +250,7 @@ def adjudicate_notice_lines(
"""
对 LLM 候选订单行执行后端真值裁决,并输出可审计问题清单。
核心逻辑:先从保留列边界的原文解析结构证据;非法候选仅在同 SKU 唯一命中合法表格值时纠正,
核心逻辑:先从保留列边界的原文解析结构证据;非法候选仅在同 part_number 唯一命中合法表格值时纠正,
否则清空并阻断。合法候选与明确表格证据冲突时保留候选但标记阻断,禁止静默覆盖。
Args:
lines: 已完成基础标准化的 LLM/启发式候选行。
@@ -205,13 +260,13 @@ def adjudicate_notice_lines(
tuple: (裁决后的业务行、parse_issues、validation_status)。
"""
evidence_lines = parse_notice_table_text(raw_text) if "\t" in str(raw_text or "") else []
evidence_by_sku: dict[str, list[dict[str, Any]]] = {}
evidence_by_part_number: dict[str, list[dict[str, Any]]] = {}
for evidence_line in evidence_lines:
sku = str(evidence_line.get("sku") or "").strip()
part_number = str(evidence_line.get("part_number") or "").strip()
evidence = evidence_line.get("reservation_id_evidence")
source_column = norm_header(evidence.get("source_column")) if isinstance(evidence, dict) else ""
if sku and source_column and validated_reservation_id(evidence_line.get("reservation_id")):
evidence_by_sku.setdefault(sku, []).append(evidence_line)
if part_number and source_column and validated_reservation_id(evidence_line.get("reservation_id")):
evidence_by_part_number.setdefault(part_number, []).append(evidence_line)
adjudicated: list[dict[str, Any]] = []
issues: list[dict[str, Any]] = []
@@ -219,22 +274,8 @@ def adjudicate_notice_lines(
line = dict(source_line)
raw_candidate = str(line.get("reservation_id") or "").strip()
candidate = validated_reservation_id(raw_candidate)
line_sku = str(line.get("sku") or "").strip()
line_vendor_part = str(line.get("vendor_part_number") or "").strip()
matches = list(evidence_by_sku.get(line_sku, []))
if not matches:
matches = [
item
for candidates in evidence_by_sku.values()
for item in candidates
if (
str(item.get("vendor_part_number") or "").strip()
and (
str(item.get("vendor_part_number") or "").strip() == line_vendor_part
or str(item.get("vendor_part_number") or "").strip() in line_sku
)
)
]
line_part_number = str(line.get("part_number") or "").strip()
matches = list(evidence_by_part_number.get(line_part_number, []))
evidence_values = {
validated_reservation_id(item.get("reservation_id"))
for item in matches
@@ -246,7 +287,7 @@ def adjudicate_notice_lines(
issues.append(
{
"line_index": index,
"sku": line.get("sku"),
"part_number": line.get("part_number"),
"field": "reservation_id",
"reason": "source_conflict",
"severity": "blocking",
@@ -262,7 +303,7 @@ def adjudicate_notice_lines(
issues.append(
{
"line_index": index,
"sku": line.get("sku"),
"part_number": line.get("part_number"),
"field": "reservation_id",
"reason": "value_corrected",
"severity": "info",
@@ -276,7 +317,7 @@ def adjudicate_notice_lines(
issues.append(
{
"line_index": index,
"sku": line.get("sku"),
"part_number": line.get("part_number"),
"field": "reservation_id",
"reason": "missing" if not raw_candidate else "invalid_format",
"severity": "blocking",
@@ -400,10 +441,10 @@ def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
"""
warnings: list[str] = []
if not lines:
warnings.append("未解析到有效订单行(需至少包含 SKU 与需求数量)。")
warnings.append("未解析到有效订单行(需至少包含内部料号与需求数量)。")
return warnings
missing_reservation = [line["sku"] for line in lines if not str(line.get("reservation_id") or "").strip()]
missing_reservation = [line["part_number"] for line in lines if not str(line.get("reservation_id") or "").strip()]
if missing_reservation and len(missing_reservation) == len(lines):
warnings.append(
"订单行未解析到 Reservation ID;当前匹配规则会阻断后续库存匹配,"
@@ -416,7 +457,7 @@ def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
)
invalid_reservation = [
line["sku"]
line["part_number"]
for line in lines
if str(line.get("reservation_id") or "").strip()
and not is_valid_reservation_id(line.get("reservation_id"))
@@ -437,14 +478,14 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
"""
评估订单行解析完整度。
核心逻辑:按 SKU、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。
核心逻辑:按内部料号、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。
"""
if not lines:
return 0.0
scores: list[float] = []
for line in lines:
item = 0.0
if line.get("sku"):
if line.get("part_number"):
item += 0.35
if line.get("qty"):
item += 0.35
@@ -466,8 +507,11 @@ __all__ = [
"adjudicate_notice_lines",
"normalize_notice_line",
"normalize_notice_lines",
"non_atomic_part_number_field",
"notice_parse_completeness",
"parse_notice_table_rows",
"parse_notice_table_text",
"resolve_composite_part_numbers",
"split_part_number_tokens",
"validate_notice_lines",
]
@@ -116,10 +116,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
{
"agent_runtime_context": runtime_context,
"input_snapshot_hash": _str_prop("get_order_extraction_context 返回的不可变输入快照 SHA-256"),
"schema_version": _str_prop(
"固定为 shipping-order-extraction-v1",
enum=["shipping-order-extraction-v1"],
),
"orders": {
"type": "array",
"description": "LLM 从一封或多封邮件中识别出的订单数组;一个附件可产生多个订单,非发货邮件可为空数组",
@@ -143,9 +139,9 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"classification_confidence": {"type": "number", "minimum": 0, "maximum": 1},
"field_confidence": {
"type": "object",
"required": ["sku", "qty"],
"required": ["part_number", "qty"],
"properties": {
"sku": {"type": "number", "minimum": 0, "maximum": 1},
"part_number": {"type": "number", "minimum": 0, "maximum": 1},
"qty": {"type": "number", "minimum": 0, "maximum": 1},
},
},
@@ -154,30 +150,29 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"type": "array",
"items": {
"type": "object",
"required": ["sku", "qty"],
"required": ["part_number", "qty"],
"properties": {
"sku": _str_prop("SKU/料号"),
"part_number": _str_prop("内部料号/主匹配料号"),
"qty": {"type": "number", "exclusiveMinimum": 0},
"reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
"source_type": _str_prop(
"可选订单路由线索(库存来源提示);仅在原文有可靠证据时填写,"
"inventory_source_hint": _str_prop(
"可选库存来源提示;仅在原文有可靠证据时填写,"
"不代表任务通知来源或已确认的库存连接器类型"
),
"hub_code": _str_prop(
"可选 Hub/站点线索;与 source_type 独立落库,禁止折叠进 source_type"
),
"customer_part_number": _str_prop("可选客户料号"),
"aws_part_number": _str_prop("可选 AWS 料号"),
},
"additionalProperties": True,
"additionalProperties": False,
},
},
"evidence": {
"type": "array",
"description": "至少分别提供 SKU 与 Qty 原文证据,元素含 field 与非空 quote",
"description": "至少分别提供内部料号与 Qty 原文证据,元素含 field 与非空 quote",
"items": {
"type": "object",
"required": ["field", "quote"],
"properties": {
"field": _str_prop("证据字段,如 lines[0].sku 或 lines[0].qty"),
"field": _str_prop("证据字段,如 lines[0].part_number 或 lines[0].qty"),
"quote": _str_prop("原文片段,禁止改写"),
"document_id": _int_prop("证据来源 Document ID"),
},
@@ -192,11 +187,11 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
},
},
required=["agent_runtime_context", "input_snapshot_hash", "schema_version", "orders"],
required=["agent_runtime_context", "input_snapshot_hash", "orders"],
description=(
"只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,"
"只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、内部料号/Qty 置信度及原文证据均达标,"
"且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,"
"订单行 Source Type / Hub Code 是可选路由线索并独立持久化。"
"订单行 inventory_source_hint 是可选路由线索并独立持久化。"
"响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、"
"non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。"
),
@@ -232,15 +227,15 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
),
"/tools/update_notice_line": _post_op(
"update_notice_line",
"更新解析结果中的某一行,如 SKU、Reservation ID、数量、交期",
"更新解析结果中的某一行,如内部料号、Reservation ID、数量、交期",
{
"task_id": task_id,
"line_index": _int_prop("行下标,从 0 开始"),
"patch": {
"type": "object",
"description": (
"可更新字段:sku/reservation_id/quantity/qty/required_date/uom/source_type/hub_code;"
"source_type 与 hub_code 均为可选订单路由线索并独立落库"
"可更新字段:part_number/reservation_id/quantity/qty/required_date/uom/"
"inventory_source_hint;inventory_source_hint 为可选订单路由线索"
),
"additionalProperties": True,
},
@@ -255,7 +250,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"task_id": task_id,
"line": {
"type": "object",
"description": "新增行,至少包含 sku 和 qty/quantity",
"description": "新增行,至少包含 part_number 和 qty/quantity",
"additionalProperties": True,
},
"comment": _str_prop("修改备注(可选)"),
@@ -284,7 +279,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
{
"task_id": task_id,
MAP_JSON: _str_prop(
"Dify Tool 参数使用 JSON 字符串,内容含 sku/reservation_id/available_qty;"
"Dify Tool 参数使用 JSON 字符串,内容含 part_number/reservation_id/available_qty,"
"可选 aws_part_number;"
"可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。"
),
},
@@ -17,7 +17,7 @@ from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
_PO_IN_FILENAME = re.compile(r"(?<!\d)(\d{7,12})(?!\d)")
_KEY_FIELDS = ("reservation_id", "sku", "qty", "source_type")
_KEY_FIELDS = ("reservation_id", "part_number", "qty", "inventory_source_hint")
def _comparable_value(field: str, value: Any) -> str:
@@ -108,9 +108,13 @@ def _find_attachment_line(
]
if len(hits) == 1:
return hits[0]
body_sku = _comparable_value("sku", body_row.get("sku"))
if body_sku:
hits = [line for line in lines if _comparable_value("sku", line.get("sku")) == body_sku]
body_part_number = _comparable_value("part_number", body_row.get("part_number"))
if body_part_number:
hits = [
line
for line in lines
if _comparable_value("part_number", line.get("part_number")) == body_part_number
]
if len(hits) == 1:
return hits[0]
return lines[0] if len(lines) == 1 else None
@@ -154,7 +158,7 @@ def merge_attachment_candidate(
"attachment_value": [
{
"reservation_id": line.get("reservation_id"),
"sku": line.get("sku"),
"part_number": line.get("part_number"),
}
for line in lines
],
@@ -4,7 +4,7 @@ backend/app/services/shipping_notice/order_extraction.py
用途:为现有货代 Chatflow 提供建单前订单抽取上下文,并接收 LLM orders[] 完成校验、判重、自动建单与失败收口。
依赖:agent_runtime_context、ChatSession、ShippingNoticeIntake/Document/Candidate、batch_from_intakes。
逻辑:聊天请求进入 Dify 前先登记本轮抽取身份,Dify 再读取不可变输入快照并提交结构化订单;
HXOPS 逐订单落 Candidate,高置信度 SKU/Qty 订单自动消费建 Task,其余保留供自然对话修订;
HXOPS 逐订单落 Candidate,高置信度内部料号/Qty 订单自动消费建 Task,其余保留供自然对话修订;
Dify 终态或状态读取负责把未提交和超时请求收口为失败。
"""
@@ -46,15 +46,18 @@ from app.services.shipping_notice.order_extraction_evidence import (
adjudicate_order_reservations,
verify_reservation_evidence,
)
from app.services.shipping_notice.field_adjudication import (
adjudicate_order_fields,
merge_observation_history,
trusted_required_fields,
)
from app.services.shipping_notice.reservation_id import validated_reservation_id
EXTRACTION_CONTRACT_VERSION = 'shipping-order-extraction-v1'
_CONTEXT_PATHS = [
'agent_code',
'platform.session_id',
'platform.request_id',
'refs.capability',
'refs.contract_version',
'refs.intake_nos',
]
ORDER_EXTRACTION_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'
@@ -70,9 +73,6 @@ def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, l
raise ForbiddenError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='当前上下文不属于货代发货应用')
if str(values.get('refs.capability') or '') != 'order_extraction':
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='当前上下文不是订单抽取请求')
if str(values.get('refs.contract_version') or '') != EXTRACTION_CONTRACT_VERSION:
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单抽取契约版本不匹配')
session_id = str(values.get('platform.session_id') or '').strip()
request_id = str(values.get('platform.request_id') or '').strip()
if not session_id or not request_id:
@@ -222,7 +222,6 @@ def _set_documents_extraction_state(
for document in query.with_for_update().all():
document.order_extraction_status = status
document.order_extraction_source = 'dify_chatflow'
document.order_extraction_version = EXTRACTION_CONTRACT_VERSION
document.order_extraction_error_code = error_code
document.order_extraction_error_message = error_message
document.updated_at = now
@@ -301,7 +300,6 @@ def start_order_extraction(
intake.structured_result_json = structured
flag_modified(intake, 'structured_result_json')
intake.order_extraction_status = 'extracting'
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
intake.updated_at = now
@@ -376,7 +374,6 @@ def finalize_order_extraction_failure(
):
continue
intake.order_extraction_status = 'failed'
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
intake.order_extraction_error_code = code
intake.order_extraction_error_message = message
intake.updated_at = now
@@ -444,7 +441,6 @@ def expire_stale_order_extractions(
if started_at is None or current_time - started_at < timedelta(seconds=timeout):
continue
intake.order_extraction_status = 'failed'
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
intake.order_extraction_error_code = ORDER_EXTRACTION_FAILED_CODE
intake.order_extraction_error_message = ORDER_EXTRACTION_TIMEOUT_MESSAGE
intake.updated_at = current_time
@@ -668,7 +664,6 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
intake.structured_result_json = structured
flag_modified(intake, 'structured_result_json')
intake.order_extraction_status = 'extracting'
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
intake.updated_at = now
@@ -692,11 +687,10 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
for row in intakes
},
'contract': {
'schema_version': EXTRACTION_CONTRACT_VERSION,
'required_order_fields': ['source_intake_no', 'primary_document_id', 'classification', 'lines'],
'auto_create_required_line_fields': ['sku', 'qty'],
'auto_create_required_line_fields': ['part_number', 'qty'],
'required_process_line_fields': ['reservation_id'],
'optional_routing_line_fields': ['source_type', 'hub_code'],
'optional_routing_line_fields': ['inventory_source_hint'],
'allowed_missing_process_fields': ['reservation_id'],
},
}
@@ -721,7 +715,7 @@ def _candidate_key(intake_no: str, order: dict[str, Any], summary: dict[str, Any
'po_number': po_number or None,
'reservation_ids': reservation_ids,
'lines': [
{'sku': line.get('sku'), 'reservation_id': line.get('reservation_id')}
{'part_number': line.get('part_number'), 'reservation_id': line.get('reservation_id')}
for line in summary.get('lines') or []
],
}
@@ -731,14 +725,16 @@ def _candidate_key(intake_no: str, order: dict[str, Any], summary: dict[str, Any
return f"llm:{hashlib.sha256((intake_no + ':' + raw).encode('utf-8')).hexdigest()[:40]}"
def _evidence_has_sku_qty(order: dict[str, Any]) -> bool:
"""确认 LLM 为 SKU 与 Qty 提供了原文证据;防止只靠自报高置信度自动建单。"""
def _evidence_has_part_number_qty(order: dict[str, Any]) -> bool:
"""确认 LLM 为内部料号与 Qty 提供原文证据,防止只靠自报置信度自动建单。"""
fields = {
str(item.get('field') or '').lower()
for item in (order.get('evidence') or [])
if isinstance(item, dict) and str(item.get('quote') or '').strip()
}
return any('sku' in field for field in fields) and any('qty' in field or 'quantity' in field for field in fields)
return any('part_number' in field for field in fields) and any(
'qty' in field or 'quantity' in field for field in fields
)
def _build_submission_message(
@@ -779,18 +775,16 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
提交 Chatflow 的 orders[],执行后端强校验、订单级判重与自动建单。
【AI 触发时机】:订单抽取 LLM + JSON 标准化节点成功后调用;每轮只调用一次。
低置信度、缺 SKU/Qty、证据不足或可能修订的订单会保留为待处理 Candidate,
低置信度、缺内部料号/Qty、证据不足或可能修订的订单会保留为待处理 Candidate,
不得由画布自行绕过后端门禁。
Args:
payload: agent_runtime_context、input_snapshot_hash、schema_version、orders。
payload: agent_runtime_context、input_snapshot_hash、orders。
Returns:
自动创建/打开的任务、待处理订单及缺失流程字段摘要。
"""
session, intake_nos, request_id = _runtime_identity(payload.get('agent_runtime_context'))
if str(payload.get('schema_version') or '') != EXTRACTION_CONTRACT_VERSION:
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT', message='订单抽取结果契约版本无效')
orders = payload.get('orders')
if not isinstance(orders, list):
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT', message='orders 必须为数组')
@@ -846,7 +840,6 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
documents_by_intake.setdefault(int(document.intake_id), []).append(document)
class_threshold = float(current_app.config.get('SHIPPING_NOTICE_ORDER_CLASSIFICATION_CONFIDENCE') or 0.85)
field_threshold = float(current_app.config.get('SHIPPING_NOTICE_ORDER_FIELD_CONFIDENCE') or 0.90)
auto_candidates: list[ShippingNoticeCandidate] = []
pending: list[dict[str, Any]] = []
non_shipping: list[dict[str, Any]] = []
@@ -915,7 +908,16 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
summary.pop('classification', None)
summary.pop('source_intake_no', None)
summary.pop('primary_document_id', None)
assessment = assess_candidate_business_summary(summary)
field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {}
field_adjudication = adjudicate_order_fields(
summary,
raw_order=raw_order,
documents=owned_docs,
field_confidence=field_confidence,
)
normalized = field_adjudication['summary']
blocking_conflicts.extend(field_adjudication['conflicts'])
assessment = assess_candidate_business_summary(normalized)
normalized, backend_conflicts = adjudicate_order_reservations(
assessment['normalized_summary'],
documents=owned_docs,
@@ -944,20 +946,15 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
if str(item.get('line_index', '')).isdigit()
and validated_reservation_id(item.get('reservation_id'))
}
field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {}
sku_conf = _float(field_confidence.get('sku'))
qty_conf = _float(field_confidence.get('qty'))
reasons: list[str] = []
if classification != 'shipping_request':
reasons.append('not_shipping_request')
if not assessment['can_create_task']:
reasons.append('missing_or_invalid_sku_qty')
reasons.append('missing_or_invalid_part_number_qty')
if classification_confidence < class_threshold:
reasons.append('low_classification_confidence')
if sku_conf < field_threshold or qty_conf < field_threshold:
reasons.append('low_sku_qty_confidence')
if not _evidence_has_sku_qty(raw_order):
reasons.append('missing_sku_qty_evidence')
if not trusted_required_fields(field_adjudication):
reasons.append('untrusted_part_number_qty_adjudication')
if reservation_pairs - verified_reservation_pairs:
reasons.append('unverified_reservation_evidence')
if blocking_conflicts:
@@ -981,10 +978,28 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
candidate_key=candidate_key,
)
db.session.add(candidate)
previous_structured = (
candidate.structured_result_json
if isinstance(candidate.structured_result_json, dict)
else {}
)
previous_extraction = (
previous_structured.get('extraction')
if isinstance(previous_structured.get('extraction'), dict)
else {}
)
previous_adjudication = (
previous_extraction.get('field_adjudication')
if isinstance(previous_extraction.get('field_adjudication'), dict)
else {}
)
observation_history = merge_observation_history(
previous_adjudication.get('observation_history') or previous_adjudication.get('observations'),
field_adjudication['observations'],
)
candidate.primary_document_id = int(document.id)
candidate.source_order_index = index
candidate.extraction_source = 'dify_chatflow'
candidate.extraction_version = EXTRACTION_CONTRACT_VERSION
candidate.classification_confidence = classification_confidence
candidate.field_confidence_json = dict(field_confidence)
candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields'])
@@ -1010,6 +1025,13 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
'classification': classification,
'classification_confidence': classification_confidence,
'field_confidence': field_confidence,
'field_adjudication': {
'schema_version': field_adjudication['schema_version'],
'observations': field_adjudication['observations'],
'observation_history': observation_history,
'decisions': field_adjudication['decisions'],
'conflicts': field_adjudication['conflicts'],
},
'missing_required_fields': assessment['missing_required_fields'],
'missing_process_fields': assessment['missing_process_fields'],
'process_issues': assessment['process_issues'],
@@ -1068,7 +1090,6 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
else 'completed'
)
document.order_extraction_source = 'dify_chatflow'
document.order_extraction_version = EXTRACTION_CONTRACT_VERSION
document.order_extraction_result_json = {
'request_id': request_id,
'candidate_keys': keys,
@@ -1098,7 +1119,6 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
if pending_by_intake[int(intake.id)] or has_unassigned_pending
else 'completed'
)
intake.order_extraction_version = EXTRACTION_CONTRACT_VERSION
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
intake.updated_at = datetime.utcnow()
@@ -1187,7 +1207,6 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
structured = dict(intake.structured_result_json or {})
structured['order_extraction_submission'] = {
'input_snapshot_hash': current_snapshot,
'schema_version': EXTRACTION_CONTRACT_VERSION,
'request_id': request_id,
'result': result,
'submitted_at': datetime.utcnow().isoformat(),
@@ -66,14 +66,15 @@ def _format_line_block(
"|------|-----|",
]
_append_table_row(rows, t("field.reservation_id", lang=lang), line.get("reservation_id"))
_append_table_row(rows, t("field.sku", lang=lang), line.get("sku"))
_append_table_row(rows, t("field.part_number", lang=lang), line.get("part_number"))
_append_table_row(rows, t("field.qty", lang=lang), _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(rows, t("field.unit_price", lang=lang), _fmt_money(line.get("unit_price"), currency))
_append_table_row(rows, t("field.amount", lang=lang), _fmt_money(line.get("amount"), currency))
_append_table_row(rows, t("field.required_date", lang=lang), required_date)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(rows, t("field.vendor_part_number", lang=lang), vendor_pn)
for field_name in ("customer_part_number", "aws_part_number"):
value = str(line.get(field_name) or "").strip()
if value:
_append_table_row(rows, t(f"field.{field_name}", lang=lang), value)
line_no = str(line.get("line_no") or "").strip()
if line_no:
_append_table_row(rows, t("field.line_no", lang=lang), line_no)
@@ -118,7 +119,7 @@ def format_parse_summary(
parts.extend([f"| {t('table.field', lang=resolved)} | {t('table.value', lang=resolved)} |", "|------|-----|"])
_append_table_row(parts, t("field.po", lang=resolved), po_number)
_append_table_row(parts, t("field.reservation_id", lang=resolved), line.get("reservation_id"))
_append_table_row(parts, t("field.sku", lang=resolved), line.get("sku"))
_append_table_row(parts, t("field.part_number", lang=resolved), line.get("part_number"))
_append_table_row(parts, t("field.qty", lang=resolved), _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(parts, t("field.unit_price", lang=resolved), _fmt_money(line.get("unit_price"), line.get("currency")))
_append_table_row(parts, t("field.amount", lang=resolved), _fmt_money(line.get("amount"), line.get("currency")))
@@ -126,9 +127,10 @@ def format_parse_summary(
_append_table_row(parts, t("field.required_date", lang=resolved), line_date)
recipient = str(ship_to or customer_name or "").strip()
_append_table_row(parts, t("field.ship_to", lang=resolved), recipient)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(parts, t("field.vendor_part_number", lang=resolved), vendor_pn)
for field_name in ("customer_part_number", "aws_part_number"):
value = str(line.get(field_name) or "").strip()
if value:
_append_table_row(parts, t(f"field.{field_name}", lang=resolved), value)
else:
if po_number:
parts.append(f"{t('field.po', lang=resolved)}:{_cell(po_number)}")
@@ -451,7 +451,8 @@ def _serialize_source_candidate_projection(task: ShippingTask) -> dict[str, Any]
"""
投影建单来源 Candidate 的只读审计字段。
核心逻辑:按 source_candidate_id 取落库 evidence / missing_fields / field_confidence;
核心逻辑:按 source_candidate_id 取落库 evidence / missing_fields / field_confidence,
并投影当前字段裁决与不可变 Observation 历史;
Candidate 已清理或不存在时返回 None,不阻断 Task Detail。
"""
if not task.source_candidate_id:
@@ -460,12 +461,26 @@ def _serialize_source_candidate_projection(task: ShippingTask) -> dict[str, Any]
if candidate is None:
return None
field_confidence = candidate.field_confidence_json
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
extraction = structured.get("extraction") if isinstance(structured.get("extraction"), dict) else {}
adjudication = (
extraction.get("field_adjudication")
if isinstance(extraction.get("field_adjudication"), dict)
else {}
)
return {
"candidate_no": candidate.candidate_no,
"missing_fields": list(candidate.missing_fields_json or []),
"field_confidence": dict(field_confidence) if isinstance(field_confidence, dict) else {},
"evidence": list(candidate.evidence_json or []),
"conflicts": list(candidate.conflicts_json or []),
"field_adjudication": {
"schema_version": adjudication.get("schema_version"),
"decisions": list(adjudication.get("decisions") or []),
"observations": list(adjudication.get("observations") or []),
"observation_history": list(adjudication.get("observation_history") or []),
"conflicts": list(adjudication.get("conflicts") or []),
} if adjudication else None,
}
@@ -21,11 +21,33 @@ def reservation_gate_issues(lines: list[Any] | None) -> list[dict[str, Any]]:
lines: ShippingTask 订单行数组。
Returns:
含行号、SKU、原值和原因的 blocking issue;全部合法时返回空列表。
含行号、内部料号、原值和原因的 blocking issue;全部合法时返回空列表。
"""
if not lines:
return [
{
"line_index": None,
"part_number": "",
"field": "reservation_id",
"reason": "missing_order_lines",
"severity": "blocking",
"raw_value": "",
}
]
issues: list[dict[str, Any]] = []
for index, raw_line in enumerate(lines or []):
for index, raw_line in enumerate(lines):
if not isinstance(raw_line, dict):
issues.append(
{
"line_index": index,
"part_number": "",
"field": "reservation_id",
"reason": "invalid_order_line",
"severity": "blocking",
"raw_value": "",
}
)
continue
raw_value = str(raw_line.get("reservation_id") or "").strip()
if is_valid_reservation_id(raw_value):
@@ -33,7 +55,7 @@ def reservation_gate_issues(lines: list[Any] | None) -> list[dict[str, Any]]:
issues.append(
{
"line_index": index,
"sku": str(raw_line.get("sku") or "").strip(),
"part_number": str(raw_line.get("part_number") or "").strip(),
"field": "reservation_id",
"reason": "invalid_format" if raw_value else "missing",
"severity": "blocking",
@@ -77,7 +77,6 @@ def _build_refs(
run_purpose: str | None,
intake_nos: list[str] | None = None,
capability: str | None = None,
contract_version: str | None = None,
) -> dict[str, str]:
"""
构建新版 agent_runtime_context.refs。
@@ -90,7 +89,6 @@ def _build_refs(
run_purpose: 本次 Dify run 的目的。
intake_nos: 点击发送时锁定的 Intake 编号集合。
capability: 当前固定画布能力,如 order_extraction。
contract_version: 能力输入输出契约版本。
Returns:
非空业务锚点字典。
@@ -113,8 +111,6 @@ def _build_refs(
refs["intake_nos"] = json.dumps(normalized_intakes, ensure_ascii=False, separators=(",", ":"))
if _clean_text(capability):
refs["capability"] = _clean_text(capability)
if _clean_text(contract_version):
refs["contract_version"] = _clean_text(contract_version)
return refs
@@ -212,7 +208,6 @@ def build_shipping_runtime_context(
run_purpose: str | None = None,
intake_nos: list[str] | None = None,
capability: str | None = None,
contract_version: str | None = None,
) -> dict[str, Any]:
"""
构建货代发货通知 Agent 的 agent_runtime_context。
@@ -231,7 +226,6 @@ def build_shipping_runtime_context(
run_purpose: 本次 Dify run 的目的,如 parse_notice。
intake_nos: 尚未建 Task 时的 Intake 编号集合。
capability: 当前固定画布能力。
contract_version: 能力契约版本。
Returns:
agent_runtime_context 字典;session_id 为空时返回空 dict。
@@ -259,7 +253,6 @@ def build_shipping_runtime_context(
run_purpose=run_purpose,
intake_nos=intake_nos,
capability=capability,
contract_version=contract_version,
),
domain=domain,
reference_context=reference_context,
@@ -55,7 +55,7 @@ def format_shortage_details_message(task_data: dict[str, Any]) -> str:
parts = [f"任务 {task_no}({file_label})缺口明细:"]
for index, line in enumerate(lines, start=1):
parts.append(
f"{index}. SKU={line.get('sku') or '-'} "
f"{index}. Part Number={line.get('part_number') or '-'} "
f"Reservation={line.get('reservation_id') or '-'} "
f"需求={_format_qty(line.get('required_qty'))} "
f"可用={_format_qty(line.get('available_qty'))} "
@@ -28,15 +28,14 @@ from app.services.shipping_notice.task_field_conflict_service import (
)
from app.services.shipping_notice.task_line_store import read_task_order_lines, replace_task_order_lines
# 可自动对账字段;SKU/Qty 仅作行对齐键,禁止被 Candidate 覆盖。
# 可自动对账字段;part_number/Qty 仅作行对齐键,禁止被 Candidate 覆盖。
RECONCILE_FIELDS: tuple[str, ...] = (
'reservation_id',
'source_type',
'hub_code',
'inventory_source_hint',
'uom',
'required_date',
'vendor_part_number',
'customer_sku',
'customer_part_number',
'aws_part_number',
'allocation_id',
)
@@ -56,12 +55,12 @@ def _normalized_qty(value: Any) -> str:
def _line_match_key(line: dict[str, Any]) -> tuple[str, str] | None:
"""唯一业务键:(sku, qty)。"""
sku = str(line.get('sku') or '').strip().upper()
"""唯一业务键:(part_number, qty)。"""
part_number = str(line.get('part_number') or '').strip().upper()
qty = _normalized_qty(line.get('qty'))
if not sku or not qty:
if not part_number or not qty:
return None
return sku, qty
return part_number, qty
def _normalize_field_value(field_name: str, value: Any) -> str:
@@ -71,8 +70,8 @@ def _normalize_field_value(field_name: str, value: Any) -> str:
return ''
if field_name == 'reservation_id':
return validated_reservation_id(text) or ''
if field_name in {'sku', 'source_type', 'hub_code', 'uom'}:
return text.upper() if field_name == 'sku' else text
if field_name in {'part_number', 'inventory_source_hint', 'uom'}:
return text.upper() if field_name == 'part_number' else text
return text
@@ -309,7 +308,6 @@ def apply_candidate_reconciliation_plan(
step_payload['parse_validation'] = {
'status': 'needs_review',
'issues': issues,
'contract_version': 'shipping-line-v1',
'resolution_source': source,
}
step_payload['process_field_gate'] = {
@@ -325,7 +323,6 @@ def apply_candidate_reconciliation_plan(
}
for row in open_rows
],
'contract_version': 'shipping-order-extraction-v1',
}
step_payload['field_conflicts'] = {'open_count': len(open_rows)}
task.step_payload_json = step_payload
@@ -350,7 +347,6 @@ def apply_candidate_reconciliation_plan(
step_payload['parse_validation'] = {
'status': 'needs_review' if issues or open_rows else 'ready',
'issues': issues,
'contract_version': 'shipping-line-v1',
'resolution_source': source,
}
if open_rows:
@@ -367,7 +363,6 @@ def apply_candidate_reconciliation_plan(
}
for row in open_rows
],
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
elif issues:
@@ -375,7 +370,6 @@ def apply_candidate_reconciliation_plan(
'status': 'needs_enrichment',
'missing_fields': ['reservation_id'],
'issues': issues,
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
else:
@@ -251,7 +251,6 @@ def resolve_field_conflict(
}
for row in remaining
],
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
elif issues:
@@ -259,7 +258,6 @@ def resolve_field_conflict(
'status': 'needs_enrichment',
'missing_fields': ['reservation_id'],
'issues': issues,
'contract_version': 'shipping-order-extraction-v1',
}
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
else:
@@ -269,7 +267,6 @@ def resolve_field_conflict(
step_payload['parse_validation'] = {
'status': 'needs_review',
'issues': issues,
'contract_version': 'shipping-line-v1',
'resolution_source': 'field_conflict_resolve',
}
task.step_payload_json = step_payload
@@ -25,16 +25,15 @@ from app.services.shipping_notice.notice_lines import normalize_notice_lines
logger = logging.getLogger(__name__)
_STANDARD_FIELDS = (
'sku',
'part_number',
'qty',
'uom',
'reservation_id',
'source_type',
'hub_code',
'inventory_source_hint',
'line_no',
'required_date',
'vendor_part_number',
'customer_sku',
'customer_part_number',
'aws_part_number',
'po_number',
'allocation_id',
'unit_price',
@@ -91,7 +90,7 @@ def _json_safe(value: Any) -> Any:
def line_to_json(line: ShippingTaskLine) -> dict[str, Any]:
"""
将规范行投影为历史兼容的 lines_json 元素。
将规范行投影为 shipping-task-line-v2 的 lines_json 元素。
Args:
line: ShippingTaskLine 实例。
@@ -99,11 +98,11 @@ def line_to_json(line: ShippingTaskLine) -> dict[str, Any]:
含标准字段与 extra_json 展开项的字典。
"""
payload: dict[str, Any] = {
'sku': line.sku,
'part_number': line.part_number,
'qty': _json_safe(line.qty),
}
for field in _STANDARD_FIELDS:
if field in {'sku', 'qty'}:
if field in {'part_number', 'qty'}:
continue
value = getattr(line, field, None)
if value in (None, ''):
@@ -119,15 +118,14 @@ def line_to_json(line: ShippingTaskLine) -> dict[str, Any]:
# 影子对账时统一为字符串的标识类字段,避免 JSON number vs 规范表 str 假阳性。
_CHECKSUM_STRING_FIELDS = frozenset(
{
'sku',
'part_number',
'uom',
'reservation_id',
'source_type',
'hub_code',
'inventory_source_hint',
'line_no',
'required_date',
'vendor_part_number',
'customer_sku',
'customer_part_number',
'aws_part_number',
'po_number',
'allocation_id',
'currency',
@@ -175,7 +173,19 @@ def lines_checksum(lines: list[dict[str, Any]]) -> str:
def _build_line_row(*, task_id: int, position: int, raw: dict[str, Any]) -> ShippingTaskLine:
"""从标准化订单行字典构建 ShippingTaskLine(未知字段进 extra_json)。"""
"""
从 shipping-task-line-v2 字典构建规范行,未知扩展字段进入 extra_json。
核心逻辑:先验证内部料号是非空原子值,再验证正数数量;旧料号字段不作兼容转换。
Args:
task_id: 所属任务主键。
position: 订单行位置。
raw: 仅接受 v2 标准字段的订单行。
Returns:
可加入当前事务的 ShippingTaskLine。
Raises:
ValueError: part_number 缺失、包含 `/` 或 qty 非正数。
"""
extra = {
key: value
for key, value in raw.items()
@@ -184,19 +194,33 @@ def _build_line_row(*, task_id: int, position: int, raw: dict[str, Any]) -> Ship
qty = _to_decimal(raw.get('qty'))
if qty is None or qty <= 0:
raise ValueError(f'invalid qty at position={position}')
part_number = str(raw.get('part_number') or '').strip()
if not part_number:
raise ValueError(f'missing part_number at position={position}')
if '/' in part_number:
raise ValueError(f'non-atomic part_number at position={position}')
optional_part_numbers = {
field: str(raw.get(field) or '').strip() or None
for field in ('customer_part_number', 'aws_part_number')
}
invalid_optional = next(
(field for field, value in optional_part_numbers.items() if value and '/' in value),
None,
)
if invalid_optional:
raise ValueError(f'non-atomic {invalid_optional} at position={position}')
return ShippingTaskLine(
task_id=task_id,
position=position,
sku=str(raw.get('sku') or '').strip(),
part_number=part_number,
qty=qty,
uom=str(raw.get('uom') or '').strip() or None,
reservation_id=str(raw.get('reservation_id') or '').strip() or None,
source_type=str(raw.get('source_type') or '').strip() or None,
hub_code=str(raw.get('hub_code') or '').strip() or None,
inventory_source_hint=str(raw.get('inventory_source_hint') or '').strip() or None,
line_no=str(raw.get('line_no') or '').strip() or None,
required_date=str(raw.get('required_date') or '').strip() or None,
vendor_part_number=str(raw.get('vendor_part_number') or '').strip() or None,
customer_sku=str(raw.get('customer_sku') or '').strip() or None,
customer_part_number=optional_part_numbers['customer_part_number'],
aws_part_number=optional_part_numbers['aws_part_number'],
po_number=str(raw.get('po_number') or '').strip() or None,
allocation_id=str(raw.get('allocation_id') or '').strip() or None,
unit_price=_to_decimal(raw.get('unit_price')),
@@ -206,7 +230,7 @@ def _build_line_row(*, task_id: int, position: int, raw: dict[str, Any]) -> Ship
extra_json=extra or None,
field_sources_json=None,
evidence_json=None,
schema_version='shipping-task-line-v1',
schema_version='shipping-task-line-v2',
line_version=1,
)
@@ -324,7 +348,7 @@ def sync_task_order_lines_from_json(
'checksum': comparison['json_checksum'],
}
# [STEP 1] 先构造行对象以捕获非法 qty/sku,避免半写。
# [STEP 1] 先构造行对象以捕获非法 part_number/qty,避免半写。
built_rows: list[ShippingTaskLine] = []
try:
for position, item in enumerate(json_lines):
@@ -84,14 +84,13 @@ from app.services.shipping_notice.tool_common import (
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
EDITABLE_NOTICE_LINE_FIELDS = frozenset({
"sku",
"part_number",
"reservation_id",
"qty",
"quantity",
"required_date",
"uom",
"source_type",
"hub_code",
"inventory_source_hint",
})
@@ -167,7 +166,7 @@ def _missing_reservation_lines(lines: list[Any]) -> list[dict[str, Any]]:
missing.append(
{
"line_index": index,
"sku": str(line.get("sku") or "").strip(),
"part_number": str(line.get("part_number") or "").strip(),
"reservation_id": str(line.get("reservation_id") or "").strip(),
}
)
@@ -178,7 +177,7 @@ def _missing_process_field_issues(lines: list[Any]) -> list[dict[str, Any]]:
"""
检查 Task 进入库存链前必须补齐的订单行流程字段。
核心逻辑:所有入口只检查 Reservation ID;行级 Source Type / Hub Code 是可选库存源路由线索,
核心逻辑:所有入口只检查 Reservation ID;行级 inventory_source_hint 是可选库存源路由线索,
缺失时不阻断进入库存链,但必须独立持久化以便工作台展示与人工修订。
Args:
@@ -190,13 +189,13 @@ def _missing_process_field_issues(lines: list[Any]) -> list[dict[str, Any]]:
for index, line in enumerate(lines):
if not isinstance(line, dict):
continue
sku = str(line.get('sku') or '').strip()
part_number = str(line.get('part_number') or '').strip()
raw_reservation = str(line.get('reservation_id') or '').strip()
if is_valid_reservation_id(raw_reservation):
continue
issues.append({
'line_index': index,
'sku': sku,
'part_number': part_number,
'field': 'reservation_id',
'reason': 'invalid_format' if raw_reservation else 'missing',
'severity': 'blocking',
@@ -729,7 +728,6 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
step_payload["parse_validation"] = {
"status": str(parsed.get("validation_status") or "ready"),
"issues": parsed.get("parse_issues") if isinstance(parsed.get("parse_issues"), list) else [],
"contract_version": "shipping-line-v1",
}
task.step_payload_json = step_payload
_capture_destination_context(task, parsed, lines)
@@ -768,7 +766,6 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
'status': 'needs_enrichment',
'missing_fields': missing_fields,
'issues': process_field_issues,
'contract_version': 'shipping-order-extraction-v1',
}
task.step_payload_json = step_payload
set_task_step_progress(
@@ -1236,7 +1233,6 @@ def _commit_notice_edit(
step_payload["parse_validation"] = {
"status": "needs_review" if validation_issues else "ready",
"issues": validation_issues,
"contract_version": "shipping-line-v1",
"resolution_source": "human_edit",
}
if validation_issues:
@@ -1245,7 +1241,6 @@ def _commit_notice_edit(
'status': 'needs_enrichment',
'missing_fields': missing_fields,
'issues': validation_issues,
'contract_version': 'shipping-order-extraction-v1',
}
else:
step_payload.pop('process_field_gate', None)
@@ -1529,6 +1524,12 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
customer_gate = customer_gate_tool_response(task, operation='retry_task')
if customer_gate is not None:
return customer_gate
comment = str(payload.get("comment") or "").strip()
task.review_status = None
task.pending_human_reason = None
@@ -210,20 +210,20 @@ def _append_unique_issue(issues: list[str], raw: Any) -> None:
def _parse_validation_issue_text(issue: dict[str, Any]) -> str:
"""把结构化关键字段问题转换成工作台可读文案,同时保留行号、SKU 与原始值。"""
"""把关键字段问题转换成工作台文案,并保留行号、内部料号与原始值。"""
line_no = int(issue.get("line_index") or 0) + 1
sku = str(issue.get("sku") or "-").strip() or "-"
part_number = str(issue.get("part_number") or "-").strip() or "-"
raw_value = str(issue.get("raw_value") or "").strip()
resolved_value = str(issue.get("resolved_value") or "").strip()
reason = str(issue.get("reason") or "").strip()
if reason == "value_corrected":
return f"第 {line_no} 行 SKU {sku}:Reservation ID 已由 {raw_value or '空值'} 纠正为 {resolved_value}。"
return f"第 {line_no} 行料号 {part_number}:Reservation ID 已由 {raw_value or '空值'} 纠正为 {resolved_value}。"
if reason == "source_conflict":
values = ", ".join(str(item) for item in issue.get("evidence_values") or [])
return f"第 {line_no} 行 SKU {sku}:Reservation ID {raw_value or '空值'} 与原文列证据 {values or '-'} 冲突。"
return f"第 {line_no} 行料号 {part_number}:Reservation ID {raw_value or '空值'} 与原文列证据 {values or '-'} 冲突。"
if reason == "invalid_format":
return f"第 {line_no} 行 SKU {sku}:Reservation ID {raw_value or '空值'} 格式不合法。"
return f"第 {line_no} 行 SKU {sku}:缺少合法的 Reservation ID。"
return f"第 {line_no} 行料号 {part_number}:Reservation ID {raw_value or '空值'} 格式不合法。"
return f"第 {line_no} 行料号 {part_number}:缺少合法的 Reservation ID。"
def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> list[str]:
@@ -0,0 +1,108 @@
"""
backend/migrations/versions/0f7a8b9c0d1e_shipping_task_line_v2.py
用途:将规范订单行破坏性升级为公司内部视角的 shipping-task-line-v2 字段模型。
依赖:Alembic、SQLAlchemy;承接 e6f7a8b9c0d1。
逻辑:生产尚无业务数据,因此先清空旧规范行/冲突和旧 lines_json,再重命名或删除旧列,
新增 aws_part_number,并切换索引与 schema_version;不猜测旧料号角色。
Revision ID: 0f7a8b9c0d1e
Revises: e6f7a8b9c0d1
Create Date: 2026-07-16 20:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = '0f7a8b9c0d1e'
down_revision = 'e6f7a8b9c0d1'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""
清理无生产价值的旧订单行数据,并将规范表升级为 v2 字段。
核心逻辑:先删除依赖行并清空任务快照,再通过 batch alter 保证 PostgreSQL/SQLite 均可执行。
"""
op.execute(sa.text('DELETE FROM shipping_task_field_conflicts'))
op.execute(sa.text('DELETE FROM shipping_task_lines'))
op.execute(sa.text(
"UPDATE shipping_tasks SET lines_json = '[]', order_lines_migration_status = 'pending'"
))
op.drop_index('ix_shipping_task_lines_sku', table_name='shipping_task_lines')
with op.batch_alter_table('shipping_task_lines') as batch_op:
batch_op.alter_column('sku', new_column_name='part_number')
batch_op.alter_column('source_type', new_column_name='inventory_source_hint')
batch_op.drop_column('hub_code')
batch_op.drop_column('vendor_part_number')
batch_op.alter_column('customer_sku', new_column_name='customer_part_number')
batch_op.add_column(sa.Column('aws_part_number', sa.String(length=128), nullable=True))
batch_op.alter_column(
'schema_version',
existing_type=sa.String(length=64),
server_default=sa.text("'shipping-task-line-v2'"),
nullable=False,
)
batch_op.create_check_constraint(
'ck_shipping_task_lines_part_number_atomic',
"part_number NOT LIKE '%/%'",
)
batch_op.create_check_constraint(
'ck_shipping_task_lines_customer_part_number_atomic',
"customer_part_number IS NULL OR customer_part_number NOT LIKE '%/%'",
)
batch_op.create_check_constraint(
'ck_shipping_task_lines_aws_part_number_atomic',
"aws_part_number IS NULL OR aws_part_number NOT LIKE '%/%'",
)
op.create_index(
'ix_shipping_task_lines_part_number',
'shipping_task_lines',
['part_number'],
unique=False,
)
def downgrade() -> None:
"""
将空规范表结构退回 v1 字段;无法恢复升级时主动清理的旧业务数据。
核心逻辑:逆向恢复列名和默认值,新增回旧可空列,保持降级结构可运行。
"""
op.drop_index('ix_shipping_task_lines_part_number', table_name='shipping_task_lines')
with op.batch_alter_table('shipping_task_lines') as batch_op:
batch_op.drop_constraint(
'ck_shipping_task_lines_aws_part_number_atomic',
type_='check',
)
batch_op.drop_constraint(
'ck_shipping_task_lines_customer_part_number_atomic',
type_='check',
)
batch_op.drop_constraint(
'ck_shipping_task_lines_part_number_atomic',
type_='check',
)
batch_op.drop_column('aws_part_number')
batch_op.alter_column('customer_part_number', new_column_name='customer_sku')
batch_op.add_column(sa.Column('vendor_part_number', sa.String(length=128), nullable=True))
batch_op.add_column(sa.Column('hub_code', sa.String(length=64), nullable=True))
batch_op.alter_column('inventory_source_hint', new_column_name='source_type')
batch_op.alter_column('part_number', new_column_name='sku')
batch_op.alter_column(
'schema_version',
existing_type=sa.String(length=64),
server_default=sa.text("'shipping-task-line-v1'"),
nullable=False,
)
op.create_index(
'ix_shipping_task_lines_sku',
'shipping_task_lines',
['sku'],
unique=False,
)
@@ -0,0 +1,42 @@
"""
backend/migrations/versions/1a2b3c4d5e6f_remove_shipping_order_extraction_contract_version.py
用途:移除订单抽取已废弃的发布标记列。
依赖:Alembic、SQLAlchemy;承接 shipping-task-line-v2 迁移。
逻辑:系统仅维护一套画布、后端和字段模型,订单抽取不再传递或持久化发布标记;
保留状态、来源、快照、证据和幂等审计字段。
Revision ID: 1a2b3c4d5e6f
Revises: 0f7a8b9c0d1e
Create Date: 2026-07-16 21:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = '1a2b3c4d5e6f'
down_revision = '0f7a8b9c0d1e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""删除仅用于订单抽取发布标记的审计列。"""
with op.batch_alter_table('shipping_notice_intakes') as batch_op:
batch_op.drop_column('order_extraction_version')
with op.batch_alter_table('shipping_notice_documents') as batch_op:
batch_op.drop_column('order_extraction_version')
with op.batch_alter_table('shipping_notice_candidates') as batch_op:
batch_op.drop_column('extraction_version')
def downgrade() -> None:
"""恢复空审计列,供完整数据库回退使用。"""
with op.batch_alter_table('shipping_notice_candidates') as batch_op:
batch_op.add_column(sa.Column('extraction_version', sa.String(length=64), nullable=True))
with op.batch_alter_table('shipping_notice_documents') as batch_op:
batch_op.add_column(sa.Column('order_extraction_version', sa.String(length=64), nullable=True))
with op.batch_alter_table('shipping_notice_intakes') as batch_op:
batch_op.add_column(sa.Column('order_extraction_version', sa.String(length=64), nullable=True))
@@ -28,6 +28,7 @@ from app.services.shipping_notice.inventory_rpa_workflow import (
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory, parse_inventory, upload_inventory_file
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.task_workflow import retry_task
def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustomer, User]:
@@ -46,7 +47,8 @@ def _seed_task(*, with_case: bool = True) -> tuple[ShippingTask, ShippingCustome
task_no=f'SN-GATE-{user.id}', user_id=user.id,
shipping_case_id=case.id if case else None,
customer_resolution_status='pending' if case else None,
process_status='parsed', lines_json=[{'sku': 'A001', 'quantity': 1}],
process_status='parsed',
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
inventory_source_status='user_confirmed', inventory_source_code='DSV',
)
db.session.add(task)
@@ -92,6 +94,22 @@ def test_pending_customer_blocks_every_downstream_entry(app):
assert task.upload_status is None
def test_pending_customer_blocks_retry_before_clearing_review_state(app):
"""重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。"""
with app.app_context():
task, _customer, _user = _seed_task()
task.pending_human_reason = 'customer_unconfirmed'
task.error_message = '标准客户尚未确认'
db.session.commit()
result = retry_task({'task_id': task.task_no})
_assert_customer_gate_response(result)
db.session.refresh(task)
assert task.pending_human_reason == 'customer_unconfirmed'
assert task.error_message == '标准客户尚未确认'
def test_confirm_customer_syncs_revision_chain_and_assigns_number(app):
"""客户确认同步同业务单全部任务,并在同事务生成正式业务号。"""
with app.app_context():
@@ -649,7 +649,7 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
process_status="parsed",
parse_confidence=0.95,
raw_content="客户:ACME\nA001 x 10",
lines_json=[{"sku": "A001", "qty": 10}],
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
current_step="step2_parse_confirm",
step_payload_json={
"rpa_inventory_source": {
@@ -759,7 +759,7 @@ def test_auto_progress_resolves_dub_inventory_source_into_rpa_trigger(app, tmp_p
parse_confidence=0.95,
raw_content="Ship to Dublin DUB\nA001 x 10",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 10}],
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 10}],
step_payload_json={"destination": {"port_code": "DUB", "city": "Dublin"}},
)
db.session.add(task)
@@ -928,7 +928,7 @@ def test_parse_stage_ui_state_lists_all_issues(app):
"issues": [
{
"line_index": 0,
"sku": "A001",
"part_number": "A001",
"field": "reservation_id",
"reason": "invalid_format",
"severity": "blocking",
@@ -954,7 +954,7 @@ def test_parse_stage_ui_state_lists_all_issues(app):
assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
assert "第 1 行 SKU A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
assert "第 1 行料号 A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
assert len(issues) == 5
@@ -97,7 +97,7 @@ def test_business_fingerprint_ignores_internal_hex_reservation_id():
'reservation_ids': ['1f1a682dfdc446a393415dee93eb36ce'],
'lines': [
{
'sku': 'A001',
'part_number': 'A001',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
@@ -116,15 +116,15 @@ def test_fingerprint_stable_across_line_order():
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
'required_date': '2026-01-01',
'lines': [
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
{'part_number': 'B', 'qty': 2, 'reservation_id': '1000000001'},
{'part_number': 'A', 'qty': 1, 'reservation_id': '1000000002'},
],
}
swapped = {
**base,
'lines': [
{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'},
{'sku': 'B', 'qty': 2, 'reservation_id': '1000000001'},
{'part_number': 'A', 'qty': 1, 'reservation_id': '1000000002'},
{'part_number': 'B', 'qty': 2, 'reservation_id': '1000000001'},
],
}
a = build_business_fingerprint(base)
@@ -138,9 +138,9 @@ def test_fingerprint_changes_with_qty():
'customer_code': 'C1',
'destination': {'code': 'D', 'city': 'SH', 'country': 'CN'},
'required_date': '2026-01-01',
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '1000000002'}],
'lines': [{'part_number': 'A', 'qty': 1, 'reservation_id': '1000000002'}],
}
changed = {**base, 'lines': [{'sku': 'A', 'qty': 9, 'reservation_id': '1000000002'}]}
changed = {**base, 'lines': [{'part_number': 'A', 'qty': 9, 'reservation_id': '1000000002'}]}
assert build_business_fingerprint(base)['fingerprint'] != build_business_fingerprint(changed)['fingerprint']
@@ -264,7 +264,7 @@ def test_create_revision_sets_supersedes_and_version(app, dedup_user, monkeypatc
'customer_code': 'C1',
'po_number': 'PO-REV-1',
'reservation_ids': ['12345678'],
'lines': [{'sku': 'A', 'qty': 1, 'reservation_id': '12345678'}],
'lines': [{'part_number': 'A', 'qty': 1, 'reservation_id': '12345678'}],
}
fp = build_business_fingerprint(summary)
asset, intake = _seed_parsed_intake(
@@ -384,7 +384,7 @@ def test_fingerprint_strong_with_customer_name_po_reservation():
'customer_code': None,
'po_number': 'PO-20260714',
'reservation_ids': ['1000140351'],
'lines': [{'sku': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'SKU001', 'qty': 10, 'reservation_id': '1000140351'}],
}
fp = build_business_fingerprint(summary)
assert fp['strength'] == 'strong'
@@ -488,7 +488,7 @@ def test_serialize_intake_possible_duplicate_is_blocking(app, dedup_user):
dedup_user.id,
intake_no='SNI-POSSIBLE-1',
hash_value='hash-possible-1',
business_summary={'customer_name': 'X', 'lines': [{'sku': 'A', 'qty': 1}]},
business_summary={'customer_name': 'X', 'lines': [{'part_number': 'A', 'qty': 1}]},
fingerprint={'fingerprint': 'weakfp', 'version': 'shipping-v1', 'strength': 'weak'},
)
intake.duplicate_status = 'possible_duplicate'
@@ -786,7 +786,7 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
'lines': [
{
'reservation_id': '2000485916',
'sku': '504-006043-001',
'part_number': '504-006043-001',
'qty': 30,
'uom': 'EA',
}
@@ -855,11 +855,11 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
assert candidate.content_fingerprint == revision['content_fingerprint']
assert candidate.content_fingerprint != content['fingerprint']
source_type_changed = {
inventory_source_changed = {
**base,
'lines': [{**base['lines'][0], 'source_type': 'DBS DUB'}],
'lines': [{**base['lines'][0], 'inventory_source_hint': 'DBS DUB'}],
}
assert build_content_fingerprint(source_type_changed)['fingerprint'] != content['fingerprint']
assert build_content_fingerprint(inventory_source_changed)['fingerprint'] != content['fingerprint']
header_date_changed = {**base, 'required_date': '2026-07-20'}
assert build_content_fingerprint(header_date_changed)['fingerprint'] != content['fingerprint']
@@ -108,27 +108,34 @@ def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None:
def test_order_extraction_state_migration_upgrade_and_downgrade():
"""e0f1 迁移应增加抽取状态、多订单键并可在单候选场景完整降级。"""
"""订单状态迁移后应移除废弃发布标记,并可在单候选场景完整降级。"""
engine = sa.create_engine('sqlite:///:memory:')
_order_extraction_pre_migration_schema(engine)
migration = importlib.import_module(
state_migration = importlib.import_module(
'migrations.versions.e0f1a2b3c4d5_shipping_order_extraction_state'
)
removal_migration = importlib.import_module(
'migrations.versions.1a2b3c4d5e6f_remove_shipping_order_extraction_contract_version'
)
with engine.begin() as connection:
connection.execute(sa.text(
"INSERT INTO shipping_notice_candidates "
"(id, candidate_no, intake_id, primary_document_id) VALUES (1, 'SNC-1', 10, 20)"
))
operations = Operations(MigrationContext.configure(connection))
original_op = migration.op
migration.op = operations
original_state_op = state_migration.op
original_removal_op = removal_migration.op
state_migration.op = operations
removal_migration.op = operations
try:
migration.upgrade()
state_migration.upgrade()
removal_migration.upgrade()
inspector = sa.inspect(connection)
intake_columns = {column['name'] for column in inspector.get_columns('shipping_notice_intakes')}
document_columns = {column['name'] for column in inspector.get_columns('shipping_notice_documents')}
candidate_columns = {column['name'] for column in inspector.get_columns('shipping_notice_candidates')}
assert {'order_extraction_status', 'order_extraction_version'} <= intake_columns
assert 'order_extraction_status' in intake_columns
assert 'order_extraction_version' not in intake_columns
assert {'order_extraction_status', 'order_extraction_result_json'} <= document_columns
assert {'candidate_key', 'source_order_index', 'evidence_json'} <= candidate_columns
row = connection.execute(sa.text(
@@ -139,7 +146,8 @@ def test_order_extraction_state_migration_upgrade_and_downgrade():
item['name'] for item in inspector.get_unique_constraints('shipping_notice_candidates')
}
migration.downgrade()
removal_migration.downgrade()
state_migration.downgrade()
inspector = sa.inspect(connection)
assert 'order_extraction_status' not in {
column['name'] for column in inspector.get_columns('shipping_notice_intakes')
@@ -148,7 +156,8 @@ def test_order_extraction_state_migration_upgrade_and_downgrade():
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
}
finally:
migration.op = original_op
state_migration.op = original_state_op
removal_migration.op = original_removal_op
def test_order_extraction_state_migration_rejects_unsafe_multi_candidate_downgrade():
+90 -40
View File
@@ -1,6 +1,8 @@
from email.message import EmailMessage
from pathlib import Path
import pytest
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
from app.services.shipping_notice.order_candidate_builder import (
build_email_order_index,
@@ -123,6 +125,8 @@ def test_extract_notice_text_reads_xfa_pdf_datasets():
from app.services.shipping_notice.notice_upload import extract_notice_text
pdf_path = Path(__file__).resolve().parents[2] / "docs" / "prototype" / "4510038672.pdf"
if not pdf_path.exists():
pytest.skip("XFA PDF fixture docs/prototype/4510038672.pdf is not present")
text, meta = extract_notice_text(pdf_path)
assert meta["file_type"] == "pdf"
@@ -146,19 +150,18 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
assert len(rows) == 3
assert rows[0]['po_number'] == '4510039227'
assert rows[0]['reservation_id'] == '2000485916'
assert rows[0]['sku'] == '504-006043-001'
assert rows[0]['part_number'] == 'D4-A08AR12000001'
assert rows[0]['qty'] == 30
assert rows[0]['source_type'] == 'VMI-FRA01'
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
assert rows[0]['hub_code'] == 'FRA01'
assert rows[2]['hub_code'] == 'DUB'
assert rows[0]['inventory_source_hint'] == 'VMI-FRA01'
assert rows[0]['customer_part_number'] == 'TEMP-S000218922'
assert rows[0]['aws_part_number'] == '504-006043-001'
assert rows[2]['inventory_source_hint'] == 'DBS DUB'
fused = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30, 'uom': 'EA'}],
'lines': [{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', 'qty': 30, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
@@ -166,15 +169,15 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
line = fused['business_summary']['lines'][0]
assert fused['validation_status'] == 'ready'
assert not fused['conflicts']
assert line['source_type'] == 'VMI-FRA01'
assert line['customer_sku'] == 'TEMP-S000218922'
assert line['hub_code'] == 'FRA01'
assert line['inventory_source_hint'] == 'VMI-FRA01'
assert line['customer_part_number'] == 'TEMP-S000218922'
assert line['aws_part_number'] == '504-006043-001'
conflict = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 20, 'uom': 'EA'}],
'lines': [{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', 'qty': 20, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
@@ -187,16 +190,16 @@ S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD
'po_number': '4510039227',
'reservation_ids': ['OTHER', '2000485916'],
'lines': [
{'reservation_id': 'OTHER', 'sku': 'OTHER-SKU', 'qty': 5},
{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30},
{'reservation_id': 'OTHER', 'part_number': 'OTHER-SKU', 'qty': 5},
{'reservation_id': '2000485916', 'part_number': 'D4-A08AR12000001', 'qty': 30},
],
},
filename='4510039227.pdf',
body_rows=rows,
)
assert multi_line['validation_status'] == 'ready'
assert 'source_type' not in multi_line['business_summary']['lines'][0]
assert multi_line['business_summary']['lines'][1]['source_type'] == 'VMI-FRA01'
assert 'inventory_source_hint' not in multi_line['business_summary']['lines'][0]
assert multi_line['business_summary']['lines'][1]['inventory_source_hint'] == 'VMI-FRA01'
def test_extract_eml_with_three_pdf_attachments(tmp_path):
@@ -1236,8 +1239,8 @@ def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evid
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"vendor_part_number": "D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
@@ -1251,7 +1254,7 @@ def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evid
assert issues == [
{
"line_index": 0,
"sku": "TEMP-S000218929/D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"field": "reservation_id",
"reason": "value_corrected",
"severity": "info",
@@ -1270,7 +1273,7 @@ def test_flattened_text_does_not_guess_external_reservation_id():
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
@@ -1287,8 +1290,8 @@ def test_flattened_text_does_not_guess_external_reservation_id():
def test_adjudication_supports_non_numeric_reservation_templates():
"""不同来源模板可使用字母型 Reservation ID,后端只排除内部 ID,不绑定单一数字模板。"""
raw_text = "AWS Sku\tReservation Order\tQty\nA001\tAWS-311\t2"
lines = [{"sku": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
raw_text = "Part Number\tReservation Order\tQty\nA001\tAWS-311\t2"
lines = [{"part_number": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
@@ -1306,14 +1309,14 @@ Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tA
"""
lines = parse_notice_table_text(text)
assert len(lines) == 1
assert lines[0]["sku"] == "504-010213-001"
assert lines[0]["part_number"] == "B3-A08AR11000001"
assert lines[0]["line_no"] == "10"
assert lines[0]["qty"] == 9.0
assert lines[0]["unit_price"] == 1607.72
assert lines[0]["amount"] == 14469.48
assert lines[0]["reservation_id"] == "1000140351"
assert lines[0]["required_date"] == "2026-06-15"
assert lines[0]["vendor_part_number"] == "B3-A08AR11000001"
assert lines[0]["aws_part_number"] == "504-010213-001"
assert lines[0]["currency"] == "USD"
@@ -1325,7 +1328,7 @@ def test_normalize_reservation_id_from_excel_float():
def test_parse_notice_table_numeric_reservation_id():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
Part Number\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\t1000140351\t2\t15.5\t31.0
"""
lines = parse_notice_table_text(text)
@@ -1333,7 +1336,7 @@ AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
def test_infer_reservation_id_without_header():
headers = ["AWS Sku", "Ref", "Qty"]
headers = ["Part Number", "Ref", "Qty"]
rows = [["10-40594-001", 1000140351, 2]]
lines = parse_notice_table_rows(headers, rows)
assert lines[0]["reservation_id"] == "1000140351"
@@ -1341,13 +1344,13 @@ def test_infer_reservation_id_without_header():
def test_parse_notice_table_with_all_fields():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
Part Number\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\tAWS-311\t2\t15.5\t31.0
10-40594-002\tORD-3002\t1\t20\t20
"""
lines = parse_notice_table_text(text)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["part_number"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["qty"] == 2
assert lines[0]["unit_price"] == 15.5
@@ -1362,14 +1365,15 @@ def test_normalize_notice_line_aliases():
"com_id": "COM-99",
"price": "12.5",
"delivery_date": "2026/06/15",
"vendorPartNumber": "VND-001",
"customer_part_number": "CUST-001",
"aws_part_number": "AWS-001",
"currency": "USD",
"line_no": "10",
}
)
assert line == {
"line_no": "10",
"sku": "A-001",
"part_number": "A-001",
"qty": 3.0,
"uom": "EA",
"reservation_id": "COM-99",
@@ -1377,17 +1381,63 @@ def test_normalize_notice_line_aliases():
"amount": 37.5,
"currency": "USD",
"required_date": "2026-06-15",
"vendor_part_number": "VND-001",
"customer_part_number": "CUST-001",
"aws_part_number": "AWS-001",
}
def test_normalize_notice_line_splits_frozen_temp_composite():
"""TEMP 二段复合文本应拆为客户料号和内部料号,禁止把组合值持久化。"""
line = normalize_notice_line({
"part_number": "TEMP-S000218929/D4-A08AR12000002",
"qty": 10,
})
assert line is not None
assert line["part_number"] == "D4-A08AR12000002"
assert line["customer_part_number"] == "TEMP-S000218929"
@pytest.mark.parametrize(
"value",
["LEFT/RIGHT", "TEMP-A/D4-B/THIRD", "TEMP-A/TEMP-B"],
)
def test_normalize_notice_line_rejects_ambiguous_composite(value):
"""未命中冻结规则的复合料号不得猜测角色或生成有效订单行。"""
assert normalize_notice_line({"part_number": value, "qty": 1}) is None
def test_parse_notice_table_maps_three_part_number_roles():
"""MPN、Allocated HHPN 与 Allocated APN 必须分别进入内部、客户和 AWS 料号。"""
lines = parse_notice_table_rows(
["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"],
[["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]],
)
assert lines == [{
"part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929",
"aws_part_number": "504-006055-001",
"qty": 10.0,
"uom": "EA",
}]
def test_parse_notice_table_rejects_aws_only_as_internal_part_number():
"""只有 AWS Sku 的表格缺少内部料号,不能生成可建单订单行。"""
assert parse_notice_table_rows(
["AWS Sku", "Reservation ID", "Qty"],
[["504-006055-001", "3000092917", 10]],
) == []
def test_enrich_notice_with_document_currency():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_currency
parsed = enrich_notice_with_document_currency(
{
"currency": "USD",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "currency": "EUR", "uom": "EA"}],
"lines": [{"part_number": "A-001", "qty": 1, "uom": "EA"}, {"part_number": "B-002", "qty": 2, "currency": "EUR", "uom": "EA"}],
}
)
assert parsed["lines"][0]["currency"] == "USD"
@@ -1408,7 +1458,7 @@ def test_enrich_notice_with_document_required_date():
parsed = enrich_notice_with_document_required_date(
{
"required_date": "2026-06-20",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "required_date": "2026-06-18", "uom": "EA"}],
"lines": [{"part_number": "A-001", "qty": 1, "uom": "EA"}, {"part_number": "B-002", "qty": 2, "required_date": "2026-06-18", "uom": "EA"}],
}
)
assert parsed["lines"][0]["required_date"] == "2026-06-20"
@@ -1420,7 +1470,7 @@ def test_extract_notice_fields_structured():
"customer_name": "ACME",
"lines": [
{
"sku": "10-40594-001",
"part_number": "10-40594-001",
"qty": 2,
"reservation_id": "AWS-311",
"unit_price": 10,
@@ -1437,7 +1487,7 @@ def test_extract_notice_fields_structured():
def test_validate_notice_lines_missing_reservation():
warnings = validate_notice_lines([{"sku": "A001", "qty": 1, "uom": "EA"}])
warnings = validate_notice_lines([{"part_number": "A001", "qty": 1, "uom": "EA"}])
assert any("Reservation ID" in w for w in warnings)
assert any("阻断后续库存匹配" in w for w in warnings)
@@ -1447,12 +1497,12 @@ def test_heuristic_table_skips_title_row():
text = """
Shipping Notice
AWS Sku\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
10-40594-001\tORD-3002\t4\t5\t20
"""
parsed, confidence, _ = _heuristic_extract(text)
assert len(parsed["lines"]) == 1
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert parsed["lines"][0]["part_number"] == "10-40594-001"
assert parsed["lines"][0]["reservation_id"] == "ORD-3002"
assert parsed["lines"][0]["qty"] == 4
assert parsed["lines"][0]["unit_price"] == 5
@@ -1464,7 +1514,7 @@ def test_extract_notice_fields_structured_over_heuristic():
"""Dify 传入 structured 时应直接使用,不走启发式。"""
structured = {
"customer_name": "ACME",
"lines": [{"sku": "SKU-DIFY", "qty": 3, "uom": "EA"}],
"lines": [{"part_number": "SKU-DIFY", "qty": 3, "uom": "EA"}],
"confidence": 0.95,
}
parsed, confidence, warnings = extract_notice_fields(
@@ -1472,15 +1522,15 @@ def test_extract_notice_fields_structured_over_heuristic():
structured=structured,
)
assert parsed["parse_source"] == "dify"
assert parsed["lines"][0]["sku"] == "SKU-DIFY"
assert parsed["lines"][0]["part_number"] == "SKU-DIFY"
assert confidence > 0.8
assert "parse_fallback_heuristic" not in warnings
def test_extract_notice_fields_heuristic_fallback():
"""无 structured 时走后端启发式兜底。"""
text = "AWS Sku\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
parsed, _, warnings = extract_notice_fields(raw_text=text)
assert parsed["parse_source"] == "heuristic"
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert parsed["lines"][0]["part_number"] == "10-40594-001"
assert "parse_fallback_heuristic" in warnings
@@ -0,0 +1,168 @@
"""
tests/test_shipping_notice_field_adjudication.py
用途:锁定后端规则解析与 Dify LLM Observation 的字段级交叉裁决规则。
依赖:field_adjudication、ShippingNoticeDocument 测试替身。
逻辑:覆盖单侧采用、共识、可信冲突、分差决策及不可变 Observation 审计。
"""
from __future__ import annotations
from types import SimpleNamespace
from app.services.shipping_notice.field_adjudication import (
adjudicate_order_fields,
merge_observation_history,
trusted_required_fields,
)
def _document(document_id: int, text: str):
"""构造裁决服务所需的最小 Document 测试替身。"""
return SimpleNamespace(id=document_id, extracted_text=text)
def _raw_order(*, line: dict, document_id: int, evidence: bool = True) -> dict:
"""构造一条 Dify Observation 输入,可选择是否提供逐字可信证据。"""
items = []
if evidence:
items = [
{
"field": "lines[0].part_number",
"quote": str(line.get("part_number") or ""),
"document_id": document_id,
},
{
"field": "lines[0].qty",
"quote": f"Qty {line.get('qty')}",
"document_id": document_id,
},
]
return {
"lines": [line],
"evidence": items,
"field_confidence": {"part_number": 0.99, "qty": 0.99},
}
def test_adjudication_uses_verified_dify_when_backend_has_no_table():
"""只有 Dify 有可信字段时应采用,并保留 Dify Observation。"""
document = _document(1, "Email D4-A08AR12000002 Qty 10")
line = {"part_number": "D4-A08AR12000002", "qty": 10}
raw_order = _raw_order(line=line, document_id=1)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
assert trusted_required_fields(result) is True
assert {item["source"] for item in result["observations"]} == {"dify_llm"}
def test_adjudication_uses_backend_when_dify_field_is_missing():
"""Dify 缺内部料号但后端表格列关系明确时,应采用后端 Observation。"""
document = _document(1, "MPN\tQty\nD4-A08AR12000002\t10")
raw_order = {"lines": [{"qty": 10}], "evidence": [], "field_confidence": {}}
result = adjudicate_order_fields(
{"lines": [{"qty": 10}]},
raw_order=raw_order,
documents=[document],
)
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
assert trusted_required_fields(result) is True
assert any(item["source"] == "backend_table" for item in result["observations"])
def test_adjudication_marks_consensus_without_overwriting_observations():
"""双方一致时规范值标记 consensus,并同时保留两侧 Observation。"""
document = _document(1, "MPN\tQty\nD4-A08AR12000002\t10")
line = {"part_number": "D4-A08AR12000002", "qty": 10}
raw_order = _raw_order(line=line, document_id=1)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
decision = next(item for item in result["decisions"] if item["field"] == "part_number")
assert decision["status"] == "consensus"
assert {item["source"] for item in result["observations"] if item["field"] == "part_number"} == {
"backend_table",
"dify_llm",
}
def test_adjudication_blocks_two_trusted_different_values():
"""双方证据都可信但字段不同必须生成 blocking 冲突,禁止静默覆盖。"""
document = _document(
1,
"MPN\tQty\nD4-BACKEND\t10\nLLM evidence D4-DIFY Qty 10",
)
line = {"part_number": "D4-DIFY", "qty": 10}
raw_order = _raw_order(line=line, document_id=1)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
conflict = next(item for item in result["conflicts"] if item["field"] == "part_number")
assert conflict["severity"] == "blocking"
assert conflict["reason"] == "cross_source_conflict"
assert trusted_required_fields(result) is False
def test_adjudication_prefers_backend_when_dify_quote_is_unverified():
"""Dify 无可信 quote 且与后端不同,分差足够时应采用后端值而不产生冲突。"""
document = _document(1, "MPN\tQty\nD4-BACKEND\t10")
line = {"part_number": "D4-DIFY", "qty": 10}
raw_order = _raw_order(line=line, document_id=1, evidence=False)
result = adjudicate_order_fields(
{"lines": [line]},
raw_order=raw_order,
documents=[document],
field_confidence=raw_order["field_confidence"],
)
assert result["summary"]["lines"][0]["part_number"] == "D4-BACKEND"
assert not [item for item in result["conflicts"] if item["field"] == "part_number"]
assert len([item for item in result["observations"] if item["field"] == "part_number"]) == 2
def test_adjudication_builds_multiple_lines_from_backend_only():
"""Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。"""
document = _document(
1,
"MPN\tQty\tReservation ID\nD4-A\t10\tR-1\nD4-B\t20\tR-2",
)
result = adjudicate_order_fields(
{"lines": []},
raw_order={"lines": [], "evidence": []},
documents=[document],
)
assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"]
assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["R-1", "R-2"]
assert trusted_required_fields(result) is True
def test_observation_history_is_append_only_and_deduplicated():
"""重裁决必须保留旧 Observation,并按稳定 ID 去重当前重复项。"""
old = {"observation_id": "old", "value": "D4-OLD"}
current = {"observation_id": "current", "value": "D4-NEW"}
merged = merge_observation_history([old], [old, current])
assert merged == [old, current]
@@ -16,16 +16,17 @@ def test_format_field_alignment_summary_single_block():
"match_rule_source": "llm",
"inventory_columns": {
"mapping": {
"sku": {"source_column": "AWS Sku"},
"part_number": {"source_column": "Supplier Sku"},
"aws_part_number": {"source_column": "AWS Sku"},
"reservation_id": {"source_column": "Reservation Order"},
"available_qty": {"source_column": "Qty Available"},
}
},
"sample_notice_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "qty": 9},
{"part_number": "D4-A", "aws_part_number": "504-010213-001", "reservation_id": "1000140351", "qty": 9},
],
"sample_inventory_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "available_qty": 12},
{"part_number": "D4-A", "aws_part_number": "504-010213-001", "reservation_id": "1000140351", "available_qty": 12},
],
"inventory_row_count": 120,
"notice_line_count": 1,
@@ -40,14 +41,14 @@ def test_format_field_alignment_summary_single_block():
assert "【库存字段对齐确认" in text
assert "SN-20260602-AB12CD34" in text
assert "| 预订单号 | `Reservation Order` | 预订单号 |" in text
assert "| 料号 | `AWS Sku` | 料号 |" in text
assert "| 内部料号 | `Supplier Sku` | 内部料号 |" in text
rid_idx = text.index("| 预订单号 |")
sku_idx = text.index("| 料号 | `AWS Sku`")
sku_idx = text.index("| 内部料号 | `Supplier Sku`")
assert rid_idx < sku_idx
assert "(LLM 推断)" in text
assert "订单样例:" in text
assert "预订单号 1000140351" in text
assert "料号 504-010213-001" in text
assert "内部料号 D4-A" in text
assert "请核对字段对齐后使用下方按钮继续" in text
assert "回复「确认」进入匹配" not in text
@@ -109,7 +109,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
structured_result_json={
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 1}],
'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 1}],
},
},
validation_status='needs_review',
@@ -131,7 +131,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
'selected': False,
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 2}],
'lines': [{'reservation_id': 'R-1', 'part_number': 'SKU-1', 'qty': 2}],
},
},
headers=owner_headers,
@@ -186,7 +186,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
"""人工修订不得以空摘要或无效 SKU/Qty 绕过 Candidate 审核门禁。"""
"""人工修订不得以空摘要或无效 part_number/Qty 绕过 Candidate 审核门禁。"""
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
@@ -235,7 +235,7 @@ def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='test:SNC-CANDIDATE-VALIDATION',
structured_result_json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 1}]}},
structured_result_json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 1}]}},
validation_status='needs_review',
selected=True,
)
@@ -253,7 +253,7 @@ def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
invalid_qty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 0}]}},
json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 0}]}},
headers=headers,
)
assert invalid_qty.status_code == 400
@@ -264,7 +264,7 @@ def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
'business_summary': {
'lines': [
{
'sku': 'SKU-1',
'part_number': 'SKU-1',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
@@ -336,7 +336,7 @@ def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app
)
db.session.add(document)
db.session.flush()
summary = {'po_number': f'PO-{index}', 'lines': [{'sku': f'SKU-{index}', 'qty': index}]}
summary = {'po_number': f'PO-{index}', 'lines': [{'part_number': f'SKU-{index}', 'qty': index}]}
candidate = ShippingNoticeCandidate(
candidate_no=f'SNC-CANDIDATE-GATE-{index}',
intake_id=intake.id,
@@ -520,7 +520,7 @@ def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping
'lines': [
{
'reservation_id': f'20004859{index:02d}',
'sku': f'SKU-{index}',
'part_number': f'SKU-{index}',
'qty': index,
'uom': 'EA',
}
@@ -18,8 +18,8 @@ def _write_title_row_inventory_xlsx(path: Path) -> None:
ws = wb.active
ws.append(["AWS DUB On Hand Inventory by Location"])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available", "Qty"])
ws.append(["10-40594-001", "AWS-311", 2, 1])
ws.append(["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "Qty"])
ws.append(["D4-A08AR12000002", "10-40594-001", "AWS-311", 2, 1])
wb.save(str(path))
wb.close()
@@ -28,10 +28,10 @@ def _write_header_index_mismatch_xlsx(path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.append(["Inventory Report"])
ws.append(["AWS Sku", "Qty"])
ws.append(["Supplier Sku", "Qty"])
ws.append(["EARLY-001", 7])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["Supplier Sku", "COM ID", "Qty Available"])
ws.append(["LATE-001", "ORD-1", 5])
wb.save(str(path))
wb.close()
@@ -43,22 +43,26 @@ def test_read_inventory_schema_preview_skips_title_row(app, tmp_path):
with app.app_context():
preview = read_inventory_schema_preview(path)
assert preview["header_row_index"] == 3
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available", "Qty"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
assert preview["headers"] == ["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "Qty"]
assert preview["suggested_mapping"]["part_number"] == "Supplier Sku"
assert preview["suggested_mapping"]["aws_part_number"] == "AWS Sku"
assert preview["suggested_mapping"]["available_qty"] == "Qty Available"
assert preview["sample_rows"][0][0] == "10-40594-001"
assert preview["mapping_targets"]["reservation_id"] == "Reservation ID / COM ID(必填)"
assert preview["sample_rows"][0][0] == "D4-A08AR12000002"
assert preview["sample_rows"][0][1] == "10-40594-001"
def test_parse_aws_inventory_headers(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "Qty", "ODM ID"]
headers = ["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "Qty", "ODM ID"]
data = [
["10-40594-001", "AWS-311", 2, 1, "16754796"],
["10-40594-002", "ORD-3002", 0, 5, "16754797"],
["D4-A", "10-40594-001", "AWS-311", 2, 1, "16754796"],
["D4-B", "10-40594-002", "ORD-3002", 0, 5, "16754797"],
]
lines = parse_inventory_rows(headers, data)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["part_number"] == "D4-A"
assert lines[0]["aws_part_number"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["available_qty"] == 2.0
assert lines[0]["odm_id"] == "16754796"
@@ -71,22 +75,33 @@ def test_parse_inventory_drops_internal_hex_reservation_id(app):
"""库存快照可保留 SKU/数量,但内部 hex 不得写入 Reservation ID 字段。"""
with app.app_context():
lines = parse_inventory_rows(
["AWS Sku", "COM ID", "Qty Available"],
[["A001", "1f1a682dfdc446a393415dee93eb36ce", 2]],
["Supplier Sku", "AWS Sku", "COM ID", "Qty Available"],
[["A001", "AWS-A001", "1f1a682dfdc446a393415dee93eb36ce", 2]],
)
assert lines == [{"sku": "A001", "available_qty": 2.0}]
assert lines == [{"part_number": "A001", "aws_part_number": "AWS-A001", "available_qty": 2.0}]
def test_parse_inventory_rejects_aws_only_as_internal_part_number(app):
"""只有 AWS Sku 的库存表不能生成可匹配库存行。"""
with app.app_context():
lines = parse_inventory_rows(
["AWS Sku", "COM ID", "Qty Available"],
[["AWS-A001", "R-1", 2]],
)
assert lines == []
def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "ODM ID"]
data = [["10-40594-001", "AWS-311", 2, "16754796"]]
headers = ["Supplier Sku", "AWS Sku", "COM ID", "Qty Available", "ODM ID"]
data = [["D4-A", "10-40594-001", "AWS-311", 2, "16754796"]]
lines = parse_inventory_rows(
headers,
data,
field_mapping={
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"aws_part_number": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
@@ -94,11 +109,11 @@ def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
assert lines[0]["odm_id"] == "16754796"
def test_match_aggregates_same_sku_reservation():
notice = [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 3}]
def test_match_aggregates_same_part_number_reservation():
notice = [{"part_number": "D4-A", "reservation_id": "AWS-311", "qty": 3}]
inventory = [
{"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1},
{"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2},
{"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1},
{"part_number": "D4-A", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2},
]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
@@ -107,10 +122,11 @@ def test_match_aggregates_same_sku_reservation():
def test_parse_inventory_text_aws_table(app):
with app.app_context():
text = "AWS Sku\tReservation Order\tQty\n10-40594-001\tORD-3002\t4"
text = "Supplier Sku\tAWS Sku\tReservation Order\tQty\nD4-A\t10-40594-001\tORD-3002\t4"
lines, warnings, column_meta = parse_inventory_text(text)
assert not warnings or "no inventory" not in warnings[0]
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["part_number"] == "D4-A"
assert lines[0]["aws_part_number"] == "10-40594-001"
assert lines[0]["reservation_id"] == "ORD-3002"
assert lines[0]["available_qty"] == 4.0
assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order"
@@ -120,13 +136,13 @@ def test_read_inventory_schema_preview_suggests_misspelled_reservation_order(app
path = tmp_path / "aws_misspelled_reservation.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "Resevation Order", "Qty"])
ws.append(["10-40594-001", "ORD-3002", 4])
ws.append(["Supplier Sku", "AWS Sku", "Resevation Order", "Qty"])
ws.append(["D4-A", "10-40594-001", "ORD-3002", 4])
wb.save(str(path))
wb.close()
with app.app_context():
preview = read_inventory_schema_preview(path)
assert preview["headers"] == ["AWS Sku", "Resevation Order", "Qty"]
assert preview["headers"] == ["Supplier Sku", "AWS Sku", "Resevation Order", "Qty"]
assert preview["suggested_mapping"]["reservation_id"] == "Resevation Order"
@@ -134,7 +150,7 @@ def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
path = tmp_path / "header_mismatch.xlsx"
_write_header_index_mismatch_xlsx(path)
with app.app_context():
mapping = {"sku": "AWS Sku", "available_qty": "Qty"}
mapping = {"part_number": "Supplier Sku", "available_qty": "Qty"}
lines_auto, meta_auto = parse_inventory_excel_with_meta(path, field_mapping=mapping, mapping_source="manual")
lines_fixed, meta_fixed = parse_inventory_excel_with_meta(
path,
@@ -144,12 +160,12 @@ def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
)
assert meta_auto["header_row_index"] == 5
assert meta_fixed["header_row_index"] == 2
assert any(line["sku"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed)
assert any(line["part_number"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed)
def test_match_extracts_reservation_id_suffix():
notice = [{"sku": "A001", "reservation_id": "1000140351", "qty": 1}]
inventory = [{"sku": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}]
notice = [{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}]
inventory = [{"part_number": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 1.0
@@ -8,7 +8,10 @@
from datetime import datetime
from pathlib import Path
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
import pytest
from app import db
from app.models import ShippingCustomer, ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source
@@ -16,6 +19,34 @@ def _tool_headers():
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
@pytest.fixture(autouse=True)
def _confirmed_customer_for_rpa_flows(app, monkeypatch):
"""为本模块新建的业务单绑定测试客户,使用例聚焦客户门禁之后的 RPA 行为。"""
from app.services.shipping_notice import task_workflow
original = task_workflow.resolve_shipping_case_for_new_task
def _resolve_confirmed_case(**kwargs):
case = original(**kwargs)
if case.customer_id is not None:
return case
customer = db.session.query(ShippingCustomer).filter_by(short_code="RPA").one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name="RPA 流程测试客户",
short_code="RPA",
status="active",
)
db.session.add(customer)
db.session.flush()
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
return case
monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case)
def test_inventory_rpa_single_attempt_messages_hide_fraction():
"""单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。"""
from app.services.shipping_notice.inventory_rpa_workflow import (
@@ -69,7 +100,7 @@ def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path, monke
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -129,7 +160,7 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -196,6 +227,74 @@ def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_pat
assert task.inventory_snapshot_id == inv_file.id
def test_rpa_callback_gate_rechecks_order_drift_after_trigger(app, client):
"""RPA 触发后新增 Reservation 异常或字段冲突时,旧回调必须停止入库。"""
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
create_data = create_res.get_json()
assert create_res.status_code == 200 and create_data.get("task_id"), create_data
task_id = create_data["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [
{
"part_number": "D4-A08AR12000002",
"reservation_id": "R-1",
"qty": 1,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
with app.app_context():
from app.services.shipping_notice.inventory_rpa_workflow import _validate_rpa_callback_gate
from app.services.shipping_notice.task_field_conflict_service import upsert_open_field_conflict
from app.services.shipping_notice.task_line_store import replace_task_order_lines
task = ShippingTask.query.filter_by(task_no=task_id).one()
replace_task_order_lines(
task,
[{"part_number": "D4-A08AR12000002", "reservation_id": "", "qty": 1, "uom": "EA"}],
)
db.session.flush()
reservation_block = _validate_rpa_callback_gate(task)
assert reservation_block is not None
assert reservation_block["checkpoint"] == "rsv_req"
replace_task_order_lines(
task,
[{"part_number": "D4-A08AR12000002", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
)
upsert_open_field_conflict(
task=task,
position=0,
field_name="part_number",
existing_value="D4-A08AR12000002",
incoming_value="D4-A08AR12000003",
existing_source="backend",
incoming_source="dify",
)
db.session.flush()
conflict_block = _validate_rpa_callback_gate(task)
assert conflict_block is not None
assert conflict_block["checkpoint"] == "parse_review"
def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client, tmp_path):
"""无库存 skipped 回调应提示人工上传,且不计入 inventory_rpa_failed。"""
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(tmp_path / "drop")
@@ -211,13 +310,25 @@ def test_rpa_report_inventory_skipped_callback_needs_manual_upload(app, client,
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"destination": {"port_code": "DUB", "city": "Dublin"},
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
from app import db
from tests.conftest import seed_task_inventory_source
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
seed_rpa_inventory_trigger(task, run_no="RUN-SKIPPED")
@@ -428,7 +539,7 @@ def test_confirm_inventory_source_triggers_rpa_export(app, tmp_path, monkeypatch
],
}
},
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -473,7 +584,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -515,7 +626,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
from tests.conftest import seed_rpa_inventory_trigger
@@ -558,7 +669,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-FAIL-NO-IDENT")
@@ -637,7 +748,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT")
@@ -705,7 +816,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no=run_no)
@@ -820,14 +931,14 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
task_b = ShippingTask(
task_no="SN-BATCH-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "B001", "qty": 1}],
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
)
seed_task_inventory_source(task_a, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_b, source_code="DSV360_AWSDU")
@@ -883,14 +994,14 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
task_fail = ShippingTask(
task_no="SN-SHARED-FAIL",
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "B001", "qty": 1}],
lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}],
)
seed_task_inventory_source(task_ok, source_code="DSV360_AWSDU")
seed_task_inventory_source(task_fail, source_code="DSV360_AWSDU")
@@ -970,7 +1081,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-POST-COMMIT")
@@ -1014,7 +1125,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey
source_type="manual",
process_status="waiting_inventory",
pending_human_reason="rpa_pending",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-PROMOTE-FAIL")
@@ -1050,7 +1161,7 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path):
task_no="SN-REPAIR-ATTACH",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1209,7 +1320,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path):
task_no="SN-REPAIR-REJECT",
source_type="manual",
process_status="inventory_ready",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -61,7 +61,7 @@ def test_confirm_parse_blocked_when_inventory_source_unstable(app):
process_status="pending_review",
review_status="parse_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -89,7 +89,7 @@ def test_rpa_callback_rejected_when_inventory_source_unstable(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -121,7 +121,7 @@ def test_rpa_callback_rejects_mismatched_source_code(app, tmp_path):
task_no="SN-GATE-RPA-MISMATCH",
source_type="pdf",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
ship_to="Dublin",
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -148,7 +148,7 @@ def test_confirm_inventory_source_tool_route_exists(app, client):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -177,7 +177,7 @@ def test_crane_task_rpa_source_includes_dynamic_warehouse(app):
source_type="pdf",
process_status="parsed",
ship_to="TZR2",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="CRANE")
db.session.add(task)
@@ -209,7 +209,7 @@ def test_confirm_inventory_source_records_user_id(app, tmp_path, monkeypatch):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
@@ -243,7 +243,7 @@ def test_config_version_change_invalidates_stable_source(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.inventory_source_config_version = "stale-version"
@@ -264,7 +264,7 @@ def test_inventory_tools_blocked_without_stable_source(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -280,7 +280,7 @@ def test_inventory_tools_blocked_without_stable_source(app, tmp_path):
mapping_result = apply_inventory_mapping({
"task_id": task.task_no,
"map_json": {"sku": "SKU", "qty": "Qty"},
"map_json": {"part_number": "SKU", "qty": "Qty"},
})
assert mapping_result["status"] == "needs_human"
assert ShippingInventoryFile.query.count() == 0
@@ -296,7 +296,7 @@ def test_user_can_confirm_candidate_not_in_auto_top_match(app):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="UnknownCity",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
step_payload_json={
"inventory_source_resolution": {
"status": "unresolved",
@@ -321,7 +321,7 @@ def test_site_level_source_requires_explicit_warehouse_id(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
assert task.inventory_warehouse_id == "AWSDU"
@@ -344,7 +344,7 @@ def test_legacy_without_routing_fingerprint_is_not_stable(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
task.inventory_routing_fingerprint = None
@@ -363,7 +363,7 @@ def test_missing_warehouse_when_config_requires_it_is_not_stable(app):
source_type="pdf",
process_status="parsed",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSBI_BYAWSATL01")
task.inventory_warehouse_id = None
@@ -387,7 +387,7 @@ def test_rpa_callback_leaves_no_snapshot_when_identity_rejected(app, tmp_path):
task_no="SN-GATE-RPA-ORPHAN",
source_type="pdf",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
ship_to="Dublin",
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
@@ -419,7 +419,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
batch_index=1,
batch_total=2,
)
@@ -428,7 +428,7 @@ def test_batch_upload_skips_cross_inventory_source_tasks(app, tmp_path):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
lines_json=[{"part_number": "B001", "qty": 1, "reservation_id": "R-200"}],
batch_index=2,
batch_total=2,
)
@@ -455,7 +455,7 @@ def test_crane_auto_adjudication_resolves_warehouse_from_alias(app):
source_type="pdf",
process_status="parsed",
ship_to="TZR2 footprint",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -468,8 +468,8 @@ def test_crane_auto_adjudication_resolves_warehouse_from_alias(app):
@pytest.mark.inventory_source_gate
def test_line_source_type_matches_alias_without_using_task_source_type(app):
"""orders[].lines[].source_type 应命中 match_aliases,Task.source_type 接入来源不得参与裁决。"""
def test_line_inventory_source_hint_matches_alias_without_using_task_source_type(app):
"""订单行 inventory_source_hint 应命中别名,Task.source_type 接入来源不得参与裁决。"""
with app.app_context():
task = ShippingTask(
task_no="SN-GATE-LINE-SOURCE-TYPE",
@@ -477,10 +477,10 @@ def test_line_source_type_matches_alias_without_using_task_source_type(app):
process_status="parsed",
lines_json=[
{
"sku": "A001",
"part_number": "A001",
"qty": 1,
"reservation_id": "R-100",
"source_type": "DBS DUB",
"inventory_source_hint": "DBS DUB",
},
],
)
@@ -506,7 +506,7 @@ def test_crane_user_confirm_and_gate_stable(app):
process_status="pending_review",
pending_human_reason=PH_INVENTORY_SOURCE_UNRESOLVED,
ship_to="TZR3",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
db.session.add(task)
db.session.commit()
@@ -548,7 +548,7 @@ def test_low_confidence_unresolved_source_confirm_sequence(app, monkeypatch):
review_status="parse_review",
parse_confidence=0.4,
ship_to="UnknownCity",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
inventory_source_status="unresolved",
)
db.session.add(task)
@@ -603,7 +603,7 @@ def test_legacy_pending_parse_review_after_source_compat(app, monkeypatch):
review_status="parse_review",
parse_confidence=0.4,
ship_to="UnknownCity",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
step_payload_json={"pending_parse_review_after_source": True},
)
db.session.add(task)
@@ -651,7 +651,7 @@ def test_parse_notice_high_confidence_unresolved_source_goes_to_source_review(ap
"structured": {
"customer_name": "ACME",
"ship_to": "Mystery Port",
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -692,7 +692,7 @@ def test_parse_notice_low_confidence_unresolved_source_goes_to_parse_review(app,
"structured": {
"customer_name": "ACME",
"ship_to": "Mystery Port",
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.4,
},
},
@@ -730,7 +730,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
batch_index=1,
batch_total=2,
)
@@ -739,7 +739,7 @@ def test_upload_failure_leaves_no_db_or_files(app, tmp_path, monkeypatch):
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "B001", "qty": 1, "reservation_id": "R-200"}],
lines_json=[{"part_number": "B001", "qty": 1, "reservation_id": "R-200"}],
batch_index=2,
batch_total=2,
)
@@ -851,7 +851,7 @@ def test_rpa_callback_rejects_excel_warehouse_mismatch(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="TZR2 footprint",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="CRANE")
seed_rpa_inventory_trigger(task, run_no="RUN-EXCEL-WH")
@@ -877,7 +877,7 @@ def test_manual_upload_rejects_wrong_excel_warehouse(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -908,7 +908,7 @@ def test_rpa_callback_rejects_mismatched_warehouse_id(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-WH-MISMATCH")
@@ -939,7 +939,7 @@ def test_rpa_callback_rejects_stale_run_no(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT")
@@ -1000,7 +1000,7 @@ def test_manual_upload_csv_preserves_suffix_and_passes_identity(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1026,7 +1026,7 @@ def test_manual_upload_rejects_xls_extension(app, tmp_path):
task_no="SN-GATE-UPLOAD-XLS",
source_type="pdf",
process_status="waiting_inventory",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R-100"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R-100"}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1056,7 +1056,7 @@ def test_rpa_success_rejected_without_active_trigger(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.add(task)
@@ -1080,7 +1080,7 @@ def test_rpa_failed_rejected_stale_run_no(app, tmp_path):
source_type="pdf",
process_status="waiting_inventory",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}],
)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-CURRENT-FAIL")
@@ -7,7 +7,8 @@ from app.services.shipping_notice.match_rule_desc import (
def test_extract_mapping_payload_extras():
payload = {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"aws_part_number": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
"match_rule": "以 Reservation Order 对齐订单 reservation_id,汇总 Qty Available 与订单 qty 比对。",
@@ -19,25 +20,25 @@ def test_extract_mapping_payload_extras():
def test_resolve_match_rule_prefers_llm():
mapping = {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
llm_rule = "LLM 自定义匹配说明。"
rule, keys, source = resolve_match_rule(mapping, llm_match_rule=llm_rule)
assert rule == llm_rule
assert keys == ["sku", "reservation_id"]
assert keys == ["part_number", "reservation_id"]
assert source == "llm"
def test_build_match_rule_fallback_uses_column_names():
mapping = {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
rule = build_match_rule_fallback(mapping)
assert "AWS Sku" in rule
assert "Supplier Sku" in rule
assert "Reservation Order" in rule
assert "Qty Available" in rule
assert "按 SKU + Reservation ID" not in rule
@@ -6,7 +6,7 @@ def test_format_match_summary_fulfillable():
"fulfillable",
[
{
"sku": "10-40594-001",
"part_number": "D4-A08AR12000002",
"reservation_id": "AWS-311",
"required_qty": 2,
"available_qty": 5,
@@ -16,8 +16,8 @@ def test_format_match_summary_fulfillable():
],
)
assert "【库存匹配结果】" in msg or "匹配明细" in msg
assert "| # | 预订单号 | 料号 |" in msg
assert "| 1 | AWS-311 | 10-40594-001 | 2 | 5 | - |" in msg
assert "| # | 预订单号 | 内部料号 |" in msg
assert "| 1 | AWS-311 | D4-A08AR12000002 | 2 | 5 | - |" in msg
assert "✅ 充足" in msg
assert "可生成发货 Excel" in msg
@@ -27,7 +27,7 @@ def test_format_match_summary_shortage():
"partial",
[
{
"sku": "A001",
"part_number": "A001",
"reservation_id": "R-1",
"required_qty": 100,
"available_qty": 5,
@@ -1,7 +1,7 @@
"""
tests/test_shipping_notice_openapi_contract.py
用途:锁定发货通知订单行路由线索与库存连接器 OpenAPI 命名契约。
用途:锁定发货通知 v2 订单行、单一路由线索与库存连接器 OpenAPI 命名契约。
依赖:Flask 测试 client、静态 Dify OpenAPI JSON。
逻辑:分别校验动态 builder 输出与脚本生成的静态快照,防止两者发生漂移。
"""
@@ -17,8 +17,8 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
"""
校验订单行与库存连接器的字段边界。
核心逻辑:订单行保留可选 source_type 与独立 hub_code;任务状态说明使用
inventory_connector_type,并拒绝旧 inventory_source_type 命名。
核心逻辑:订单行只接受 part_number 与可选外部料号/inventory_source_hint;
任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。
Args:
spec: 动态接口或静态快照读取出的 OpenAPI 对象。
@@ -30,9 +30,23 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
"application/json"
]["schema"]["properties"]["orders"]["items"]
line_properties = order_schema["properties"]["lines"]["items"]["properties"]
assert set(line_properties) == {"sku", "qty", "reservation_id", "source_type", "hub_code"}
assert "可选订单路由线索" in line_properties["source_type"]["description"]
assert "Hub" in line_properties["hub_code"]["description"] or "hub" in line_properties["hub_code"]["description"].lower()
assert order_schema["properties"]["lines"]["items"]["additionalProperties"] is False
assert set(line_properties) == {
"part_number",
"customer_part_number",
"aws_part_number",
"qty",
"reservation_id",
"inventory_source_hint",
}
assert "库存来源提示" in line_properties["inventory_source_hint"]["description"]
assert not {"sku", "vendor_part_number", "source_type", "hub_code"} & set(line_properties)
request_schema = spec["paths"]["/tools/submit_order_extraction"]["post"]["requestBody"]["content"][
"application/json"
]["schema"]
assert "schema_version" not in request_schema["properties"]
assert request_schema["required"] == ["agent_runtime_context", "input_snapshot_hash", "orders"]
status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"]
assert "inventory_connector_type" in status_description
@@ -38,7 +38,6 @@ from app.services.chat.log_service import merge_chat_log_payload
from app.services.chat.stream_relay import iter_handler_preface_sse
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
from app.services.shipping_notice.order_extraction import (
EXTRACTION_CONTRACT_VERSION,
ORDER_EXTRACTION_FAILED_CODE,
ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
ORDER_EXTRACTION_TIMEOUT_MESSAGE,
@@ -63,8 +62,8 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
assessment = assess_candidate_business_summary({
'po_number': '4510038672',
'lines': [
{'sku': 'SKU-A', 'qty': 1, 'reservation_id': 'R-100'},
{'sku': 'SKU-B', 'qty': 2},
{'part_number': 'SKU-A', 'qty': 1, 'reservation_id': 'R-100'},
{'part_number': 'SKU-B', 'qty': 2},
],
})
@@ -72,6 +71,32 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
assert assessment['missing_process_fields'] == ['reservation_id']
@pytest.mark.parametrize('field', ['customer_part_number', 'aws_part_number'])
def test_candidate_validation_blocks_non_atomic_optional_part_numbers(field):
"""可选料号包含分隔符时必须在 Candidate 门禁阻断,不能延迟到规范表写入失败。"""
assessment = assess_candidate_business_summary({
'lines': [{'part_number': 'D4-A08AR12000002', field: 'LEFT/RIGHT', 'qty': 10}],
})
assert assessment['can_create_task'] is False
assert assessment['invalid_lines'] == [{
'line_index': 0,
'reason': 'non_atomic_part_number',
'field': field,
}]
def test_candidate_validation_accepts_frozen_temp_composite_rule():
"""已冻结 TEMP 二段规则应在门禁前拆成客户料号与内部料号。"""
assessment = assess_candidate_business_summary({
'lines': [{'part_number': 'TEMP-S000218929/D4-A08AR12000002', 'qty': 10}],
})
assert assessment['can_create_task'] is True
assert assessment['normalized_summary']['lines'][0]['part_number'] == 'D4-A08AR12000002'
assert assessment['normalized_summary']['lines'][0]['customer_part_number'] == 'TEMP-S000218929'
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, ShippingNoticeDocument, str]:
"""
创建一封已完成上传预处理的邮件、单个附件和对应统一运行态上下文。
@@ -132,7 +157,9 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
parse_status='parsed',
extracted_text=(
'PO 4510000001 SKU SKU-A QTY 10 RSV R-100 SOURCE AWS Dublin HUB DUB\n'
'PO 4510000002 SKU SKU-B QTY 20'
'PO 4510000002 SKU SKU-B QTY 20\n'
'SKU SKU-STATE SKU SKU-STALE SKU SKU-UI-STATE SKU SKU-OPEN-EXISTING\n'
'SKU P123456 SKU IGNORED-SKU QTY 1 QTY 2 QTY 3 QTY 5 QTY 24'
),
)
db.session.add(document)
@@ -143,7 +170,6 @@ def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, S
request_id='req-order-extraction-001',
refs={
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
'intake_nos': json.dumps([intake.intake_no], separators=(',', ':')),
'run_purpose': 'order_extraction',
},
@@ -156,17 +182,17 @@ def _order(
intake_no: str,
document_id: int,
po_number: str,
sku: str,
part_number: str,
qty: int,
confidence: float = 0.99,
include_process_fields: bool,
) -> dict:
"""构造符合 Chatflow v1 契约的单个订单结果。"""
line = {'sku': sku, 'qty': qty}
"""构造符合 Chatflow V2 契约的单个订单结果。"""
line = {'part_number': part_number, 'qty': qty}
if include_process_fields:
line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin'})
line.update({'reservation_id': 'R-100', 'inventory_source_hint': 'AWS Dublin'})
evidence = [
{'field': 'lines[0].sku', 'quote': f'SKU {sku}', 'document_id': document_id},
{'field': 'lines[0].part_number', 'quote': f'SKU {part_number}', 'document_id': document_id},
{'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id},
]
if include_process_fields:
@@ -181,7 +207,7 @@ def _order(
'candidate_key_hint': po_number,
'classification': 'shipping_request',
'classification_confidence': confidence,
'field_confidence': {'sku': confidence, 'qty': confidence},
'field_confidence': {'part_number': confidence, 'qty': confidence},
'po_number': po_number,
'lines': [line],
'evidence': evidence,
@@ -267,7 +293,6 @@ def _shipping_handler_context(
'shipping_notice': {
'intake_nos': [intake_no],
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -479,13 +504,12 @@ def test_order_extraction_state_is_request_fenced_and_reads_submission_facts(app
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000011',
sku='SKU-STATE',
part_number='SKU-STATE',
qty=2,
include_process_fields=False,
),
@@ -668,13 +692,12 @@ def test_superseded_order_extraction_request_cannot_read_or_submit(app):
submit_order_extraction({
'agent_runtime_context': old_runtime_context,
'input_snapshot_hash': old_context['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000999',
sku='SKU-STALE',
part_number='SKU-STALE',
qty=1,
include_process_fields=True,
),
@@ -702,13 +725,12 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re
payload = {
'agent_runtime_context': runtime_context,
'input_snapshot_hash': snapshot,
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=False,
),
@@ -716,7 +738,7 @@ def test_submit_order_extraction_supports_multiple_orders_partial_success_and_re
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000002',
sku='SKU-B',
part_number='SKU-B',
qty=20,
confidence=0.60,
include_process_fields=True,
@@ -794,7 +816,7 @@ def test_submit_order_extraction_consumes_empty_and_confident_non_shipping_resul
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='NOTICE-ONLY',
sku='IGNORED-SKU',
part_number='IGNORED-SKU',
qty=1,
include_process_fields=True,
)
@@ -803,7 +825,6 @@ def test_submit_order_extraction_consumes_empty_and_confident_non_shipping_resul
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [non_shipping_order],
})
@@ -858,7 +879,7 @@ def test_submit_order_extraction_reports_opened_existing_without_claiming_creati
'fingerprint_version': 'shipping-v1',
'components': {},
'content_fingerprint': 'existing-order-content',
'content_fingerprint_version': 'shipping-content-v3',
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{
'task_no': existing.task_no,
'process_status': existing.process_status,
@@ -879,12 +900,11 @@ def test_submit_order_extraction_reports_opened_existing_without_claiming_creati
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)],
@@ -911,7 +931,6 @@ def test_submit_order_extraction_empty_orders_reports_no_task_created(app):
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [],
})
@@ -934,12 +953,11 @@ def test_submit_order_extraction_pending_only_message_does_not_start_with_additi
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000002',
sku='SKU-B',
part_number='SKU-B',
qty=20,
confidence=0.60,
include_process_fields=True,
@@ -963,7 +981,6 @@ def test_submit_order_extraction_unassigned_pending_keeps_documents_partial(app)
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [None],
})
@@ -984,13 +1001,12 @@ def test_order_extraction_terminal_ui_state_resolves_only_the_current_intakes(ap
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000099',
sku='SKU-UI-STATE',
part_number='SKU-UI-STATE',
qty=3,
include_process_fields=False,
),
@@ -1037,7 +1053,6 @@ def test_order_extraction_terminal_ui_state_resolves_only_the_current_intakes(ap
'shipping_notice': {
'intake_nos': [intake.intake_no],
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -1131,7 +1146,7 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
'fingerprint_version': 'shipping-v1',
'components': {},
'content_fingerprint': 'existing-order-content',
'content_fingerprint_version': 'shipping-content-v3',
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{
'task_no': existing.task_no,
'process_status': existing.process_status,
@@ -1152,12 +1167,11 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000100',
sku='SKU-OPEN-EXISTING',
part_number='SKU-OPEN-EXISTING',
qty=5,
include_process_fields=True,
)],
@@ -1180,7 +1194,6 @@ def test_order_extraction_terminal_history_payload_persists_open_existing_anchor
'shipping_notice': {
'intake_nos': [intake.intake_no],
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -1240,13 +1253,12 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
review_status='rsv_req',
pending_human_reason='rsv_req',
error_message='解析失败:未识别到 Reservation ID',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
step_payload_json={
'process_field_gate': {
'status': 'needs_enrichment',
'missing_fields': ['reservation_id'],
'issues': [],
'contract_version': EXTRACTION_CONTRACT_VERSION,
},
},
)
@@ -1260,17 +1272,16 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
part_number='P123456',
qty=24,
include_process_fields=True,
)
order['lines'][0]['reservation_id'] = '1000140351'
order['lines'][0]['source_type'] = 'DBS DUB'
order['lines'][0]['inventory_source_hint'] = 'DBS DUB'
order['evidence'][-1]['quote'] = '1000140351'
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1280,13 +1291,13 @@ def test_exact_file_open_existing_backfills_unique_reservation_and_preserves_rev
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
candidate = ShippingNoticeCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
assert candidate_line['source_type'] == 'DBS DUB'
assert candidate_line['inventory_source_hint'] == 'DBS DUB'
# 通用字段对账会同时补空的 Source Type 等可选字段;Reservation 必须落库。
assert existing.lines_json[0]['sku'] == 'P123456'
assert existing.lines_json[0]['part_number'] == 'P123456'
assert existing.lines_json[0]['qty'] == 24
assert existing.lines_json[0]['uom'] == 'EA'
assert existing.lines_json[0]['reservation_id'] == '1000140351'
assert existing.lines_json[0].get('source_type') == 'DBS DUB'
assert existing.lines_json[0].get('inventory_source_hint') == 'DBS DUB'
assert existing.process_status == 'pending_review'
assert existing.pending_human_reason == 'low_confidence'
assert 'process_field_gate' not in (existing.step_payload_json or {})
@@ -1307,7 +1318,7 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)
@@ -1320,7 +1331,6 @@ def test_order_extraction_does_not_auto_create_with_unverified_reservation_evide
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1335,7 +1345,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
with app.app_context():
user, _session, intake, document, runtime_context = _seed_extraction_input()
document.extracted_text = (
"SKU\tReservation ID\tQty\n"
"Part Number\tReservation ID\tQty\n"
"SKU-A\tR-200\t10\n"
"LLM candidate quote R-100"
)
@@ -1345,7 +1355,7 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)
@@ -1353,7 +1363,6 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1361,7 +1370,13 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
assert result['pending_count'] == 1
assert 'blocking_conflict' in result['pending_orders'][0]['reasons']
candidate = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.conflicts_json[0]['reason'] == 'source_conflict'
assert candidate.conflicts_json[0]['reason'] == 'cross_source_conflict'
adjudication = candidate.structured_result_json['extraction']['field_adjudication']
reservation_observations = [
item for item in adjudication['observations']
if item['field'] == 'reservation_id'
]
assert {item['source'] for item in reservation_observations} == {'backend_table', 'dify_llm'}
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 0
@@ -1384,7 +1399,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
'process_status': 'pending_review',
'review_status': 'rsv_req',
'pending_human_reason': 'rsv_req',
'lines_json': [{'sku': 'P123456', 'qty': 24}],
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
}
task_values.update(task_overrides)
task = ShippingTask(**task_values)
@@ -1397,7 +1412,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
candidate=candidate,
candidate_summary={
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
},
duplicate_status='exact_file',
duplicate_matches=[{'task_no': task.task_no}],
@@ -1428,7 +1443,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
),
ShippingTask(
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
@@ -1438,8 +1453,8 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[
{'sku': 'P123456', 'qty': 24},
{'sku': 'P123456', 'qty': 24},
{'part_number': 'P123456', 'qty': 24},
{'part_number': 'P123456', 'qty': 24},
],
),
ShippingTask(
@@ -1449,7 +1464,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24}],
lines_json=[{'part_number': 'P123456', 'qty': 24}],
),
]
db.session.add_all(tasks)
@@ -1457,7 +1472,7 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS')
summary = {
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
}
results = [
@@ -1497,7 +1512,7 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
)
candidate = ShippingNoticeCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
db.session.add(task)
@@ -1508,7 +1523,7 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
candidate=candidate,
candidate_summary={
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
},
duplicate_status='exact_file',
duplicate_matches=[{'task_no': task.task_no}],
@@ -1543,7 +1558,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
source_content_hash=document.content_hash,
po_number='4510038672',
process_status='waiting_inventory',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.add(existing)
db.session.commit()
@@ -1555,7 +1570,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
part_number='P123456',
qty=24,
include_process_fields=True,
)
@@ -1565,7 +1580,6 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1574,7 +1588,7 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
assert result['opened_existing_count'] == 1
assert result['pending_count'] == 0
assert candidate.consumed_task_id == int(existing.id)
assert existing.lines_json == [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}]
assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}]
assert existing.process_status == 'waiting_inventory'
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
@@ -1588,7 +1602,7 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
part_number='SKU-A',
qty=10,
include_process_fields=True,
)
@@ -1611,7 +1625,6 @@ def test_order_extraction_requires_verified_pair_after_reservation_adjudication(
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1644,7 +1657,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
process_status='pending_review',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.add(existing)
db.session.commit()
@@ -1654,7 +1667,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510038672',
sku='P123456',
part_number='P123456',
qty=24,
include_process_fields=True,
)
@@ -1666,7 +1679,6 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
result = submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [order],
})
@@ -1693,7 +1705,6 @@ def test_submit_order_extraction_rejects_changed_document_snapshot(app):
submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [],
})
@@ -8,7 +8,7 @@ def test_format_parse_summary_single_line():
ship_to="Wistron Corporation, Czech Republic",
lines=[
{
"sku": "504-010213-001",
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "PCS",
@@ -22,11 +22,11 @@ def test_format_parse_summary_single_line():
assert "【发货通知解析确认】任务编号:SN-20260604-7249E4D7" in msg
assert "| 采购单号 | 16754796 |" in msg
assert "| 预订单号 | 1000140351 |" in msg
assert "| 料号 | 504-010213-001 |" in msg
assert "| 内部料号 | 504-010213-001 |" in msg
po_idx = msg.index("| 采购单号 |")
rid_idx = msg.index("| 预订单号 |")
sku_idx = msg.index("| 料号 |")
assert po_idx < rid_idx < sku_idx
part_idx = msg.index("| 内部料号 |")
assert po_idx < rid_idx < part_idx
assert "| 数量 | 9 PCS |" in msg
assert "| 单价 | $1,607.72 |" in msg
assert "| 金额 | $14,469.48 |" in msg
@@ -41,8 +41,8 @@ def test_format_parse_summary_multiple_lines():
task_no="SN-1",
po_number="PO-1",
lines=[
{"sku": "A", "qty": 1, "reservation_id": "R1"},
{"sku": "B", "qty": 2, "reservation_id": "R2"},
{"part_number": "A", "qty": 1, "reservation_id": "R1"},
{"part_number": "B", "qty": 2, "reservation_id": "R2"},
],
)
assert "【明细 1】" in msg
@@ -53,7 +53,7 @@ def test_format_parse_summary_multiple_lines():
def test_format_parse_summary_includes_warnings():
msg = format_parse_summary(
task_no="SN-1",
lines=[{"sku": "A", "qty": 1}],
lines=[{"part_number": "A", "qty": 1}],
warnings=["订单行未解析到 Reservation ID"],
low_confidence=True,
)
@@ -7,8 +7,8 @@ from app.services.shipping_notice.reservation_id import (
def test_match_numeric_reservation_id():
notice = [{"sku": "10-40594-001", "reservation_id": "1000140351", "qty": 2}]
inventory = [{"sku": "10-40594-001", "reservation_id": 1000140351.0, "available_qty": 3}]
notice = [{"part_number": "D4-A08AR12000002", "reservation_id": "1000140351", "qty": 2}]
inventory = [{"part_number": "D4-A08AR12000002", "reservation_id": 1000140351.0, "available_qty": 3}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["reservation_id"] == "1000140351"
@@ -27,3 +27,11 @@ def test_reservation_contract_rejects_internal_hex_but_keeps_business_ids():
assert is_valid_reservation_id("AWS-311")
assert is_valid_reservation_id("R-1")
assert not is_valid_reservation_id("AWS-311", numeric_only=True)
def test_reservation_gate_blocks_empty_and_malformed_order_lines():
"""空订单或畸形行都不能被视为 Reservation 门禁通过。"""
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
assert reservation_gate_issues([])[0]["reason"] == "missing_order_lines"
assert reservation_gate_issues(["invalid-line"])[0]["reason"] == "invalid_order_line"
+114 -74
View File
@@ -64,7 +64,7 @@ def _parse_notice_for_stable_inventory_source(client, headers, task_id: str) ->
"structured": {
"customer_name": "AWS",
"ship_to": "Dublin",
"lines": [{"sku": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -121,12 +121,12 @@ def test_match_notice_lines_reports_progress():
status, line_results, shortage = match_notice_lines(
[
{"sku": "A001", "reservation_id": "R-1", "qty": 1},
{"sku": "A002", "reservation_id": "R-2", "qty": 2},
{"part_number": "A001", "reservation_id": "R-1", "qty": 1},
{"part_number": "A002", "reservation_id": "R-2", "qty": 2},
],
[
{"sku": "A001", "reservation_id": "R-1", "available_qty": 1},
{"sku": "A002", "reservation_id": "R-2", "available_qty": 2},
{"part_number": "A001", "reservation_id": "R-1", "available_qty": 1},
{"part_number": "A002", "reservation_id": "R-2", "available_qty": 2},
],
progress_callback=lambda current, total: seen.append((current, total)),
)
@@ -158,11 +158,11 @@ def test_shipping_notice_tool_flow(app, client):
"structured": {
"customer_name": "ACME",
"lines": [{
"sku": "A001",
"part_number": "A001",
"reservation_id": "R-1",
"qty": 10,
"uom": "EA",
"source_type": "AWS Dublin",
"inventory_source_hint": "AWS Dublin",
}],
"confidence": 0.95,
},
@@ -172,14 +172,14 @@ def test_shipping_notice_tool_flow(app, client):
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human", "running"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| 料号 | A001 |" in parse_body["message"]
assert "| 内部料号 | A001 |" in parse_body["message"]
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
assert inv_res.status_code == 200
@@ -267,7 +267,7 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -275,7 +275,7 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -329,7 +329,7 @@ def test_submit_decision_rematch_reruns_match_and_returns_shortage(app, client,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -337,7 +337,7 @@ def test_submit_decision_rematch_reruns_match_and_returns_shortage(app, client,
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -394,7 +394,7 @@ def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 20, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 20, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -402,7 +402,7 @@ def test_contract_submit_decision_rematch_is_direct_recovery_entry(app, client,
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 1}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 1}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -481,7 +481,7 @@ def test_confirm_inventory_source_route_returns_json(app, client):
process_status="pending_review",
pending_human_reason="inventory_source_unresolved",
ship_to="Dublin",
lines_json=[{"sku": "A001", "qty": 1, "reservation_id": "R1"}],
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
)
db.session.add(task)
db.session.commit()
@@ -533,7 +533,7 @@ def test_parse_inventory_from_chat_text(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -592,7 +592,7 @@ def test_parse_inventory_empty_needs_human(app, client):
assert body.get("human_options") is not None or body.get("action_buttons")
def test_match_by_aws_sku_and_reservation_id(app, client):
def test_match_by_supplier_sku_and_reservation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
@@ -609,8 +609,8 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
"structured": {
"customer_name": "AWS",
"lines": [
{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"},
{"sku": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"},
{"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"},
{"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"},
],
"confidence": 0.95,
},
@@ -618,9 +618,9 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
)
inv_text = (
"AWS Sku\tCOM ID\tQty Available\n"
"10-40594-001\tAWS-311\t2\n"
"10-40594-001\tORD-3002\t0\n"
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
"D4-A08AR12000002\t10-40594-001\tAWS-311\t2\n"
"D4-A08AR12000002\t10-40594-001\tORD-3002\t0\n"
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
@@ -661,7 +661,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "D4-A08AR12000002", "aws_part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -671,7 +671,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
"raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n",
},
)
@@ -686,7 +686,8 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
assert blocked.get("stop_agent_turn") is True
assert "field_alignment" in blocked["data"]
mapping = blocked["data"]["field_alignment"]
assert mapping["inventory_columns"]["mapping"]["sku"]["source_column"] == "AWS Sku"
assert mapping["inventory_columns"]["mapping"]["part_number"]["source_column"] == "Supplier Sku"
assert mapping["inventory_columns"]["mapping"]["aws_part_number"]["source_column"] == "AWS Sku"
assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID"
@@ -706,7 +707,7 @@ def test_match_inventory_requires_reservation_id(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -714,7 +715,7 @@ def test_match_inventory_requires_reservation_id(app, client):
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"sku": "A001", "qty": 1, "uom": "EA"}]
task.lines_json = [{"part_number": "A001", "qty": 1, "uom": "EA"}]
db.session.commit()
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory as ensure_inventory_service,
@@ -726,7 +727,7 @@ def test_match_inventory_requires_reservation_id(app, client):
direct_data = ensure_inventory_service({
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
})
assert direct_data["status"] == "needs_human", direct_data
assert direct_data.get("checkpoint") == "rsv_req"
@@ -734,7 +735,7 @@ def test_match_inventory_requires_reservation_id(app, client):
parse_data = parse_inventory_service({
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
"inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}],
})
assert parse_data["status"] == "needs_human"
assert parse_data.get("checkpoint") == "rsv_req"
@@ -771,7 +772,15 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [
{
"part_number": "D4-A08AR12000002",
"aws_part_number": "10-40594-001",
"reservation_id": "AWS-311",
"qty": 1,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
@@ -781,7 +790,10 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
"raw_inventory_text": (
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
"D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n"
),
},
)
@@ -795,7 +807,12 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
assert data.get("checkpoint") == "map_infer"
assert data.get("stop_agent_turn") is True
assert "schema_preview" in data["data"]
assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert data["data"]["schema_preview"]["headers"] == [
"Supplier Sku",
"AWS Sku",
"COM ID",
"Qty Available",
]
def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
@@ -813,6 +830,25 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [
{
"part_number": "A001",
"reservation_id": "R-1",
"qty": 1,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
from app import db
from tests.conftest import seed_task_inventory_source
@@ -829,8 +865,8 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "料号", "可用数量"])
ws.append(["AWSDU", "A001", 20])
ws.append(["Warehouse ID", "Supplier Sku", "Reservation ID", "可用数量"])
ws.append(["AWSDU", "A001", "R-1", 20])
wb.save(inv_file)
wb.close()
@@ -842,8 +878,8 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
"task_no": task_id,
"success": True,
"file_path": str(inv_file),
"run_no": "RUN-TOOLS-CB",
"source_code": "DSV360_AWSDU",
"run_no": "RUN-TOOLS-CB",
"source_code": "DSV360_AWSDU",
"site_id": "AWSDU",
"warehouse_id": "AWSDU",
}
@@ -880,7 +916,7 @@ def test_rpa_upload_callback(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -888,7 +924,7 @@ def test_rpa_upload_callback(app, client, tmp_path):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]},
json={"task_id": task_id, "inventory_lines": [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
@@ -911,7 +947,7 @@ def test_rpa_upload_callback(app, client, tmp_path):
assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001"
def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
def test_generate_shipment_excel_writes_part_number_and_odm_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
@@ -931,8 +967,7 @@ def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
"po_number": "SN-20260608-7FCBFA4B",
"lines": [
{
"sku": "504-010213-001",
"vendor_part_number": "504-010213-001",
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "EA",
@@ -949,7 +984,7 @@ def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
"task_id": task_id,
"inventory_lines": [
{
"sku": "504-010213-001",
"part_number": "504-010213-001",
"reservation_id": "1000140351",
"available_qty": 9,
"odm_id": "16754796",
@@ -1004,7 +1039,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"lines": [{"part_number": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1017,8 +1052,8 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "10-40594-001", "AWS-311", 5])
ws.append(["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "D4-A08AR12000002", "10-40594-001", "AWS-311", 5])
wb.save(buf)
wb.close()
buf.seek(0)
@@ -1036,8 +1071,9 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
assert preview["headers"] == ["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["part_number"] == "Supplier Sku"
assert preview["suggested_mapping"]["aws_part_number"] == "AWS Sku"
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
@@ -1091,7 +1127,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
source_type="manual",
process_status="uploaded",
pending_human_reason=None,
lines_json=[{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
batch_index=1,
batch_total=2,
)
@@ -1100,7 +1136,7 @@ def test_batch_inventory_upload_does_not_reopen_completed_task(app, client, tmp_
batch=batch,
source_type="manual",
process_status="waiting_inventory",
lines_json=[{"sku": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}],
lines_json=[{"part_number": "A002", "reservation_id": "R-2", "qty": 1, "uom": "EA"}],
batch_index=2,
batch_total=2,
)
@@ -1156,8 +1192,8 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
wb = Workbook()
ws = wb.active
ws.append(["Warehouse ID", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "504-010213-001", "1000140351", 5])
ws.append(["Warehouse ID", "Supplier Sku", "AWS Sku", "COM ID", "Qty Available"])
ws.append(["AWSDU", "D4-A08AR12000002", "504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
buf.seek(0)
@@ -1174,7 +1210,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "AWS Sku",
"part_number": "Supplier Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
@@ -1182,7 +1218,7 @@ def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
)
apply_data = apply_res.get_json()
match_rule = apply_data["data"]["field_alignment"]["match_rule"]
assert "AWS Sku" in match_rule
assert "Supplier Sku" in match_rule
assert "COM ID" in match_rule
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "fallback"
@@ -1244,7 +1280,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "Part No",
"part_number": "Part No",
"reservation_id": "Resv",
"available_qty": "On Hand",
},
@@ -1254,7 +1290,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
assert apply_data["status"] == "needs_human"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0]
assert sample["sku"] == "SKU-99"
assert sample["part_number"] == "SKU-99"
assert sample["available_qty"] == 12
@@ -1276,7 +1312,7 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
"structured": {
"customer_name": "Wistron",
"ship_to": "Dublin",
"lines": [{"sku": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"lines": [{"part_number": "504-010213-001", "reservation_id": "R-1", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1333,7 +1369,7 @@ def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatc
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1380,7 +1416,8 @@ def test_parse_notice_blocks_invalid_nonempty_reservation_id(app, client, monkey
"structured": {
"lines": [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
"qty": 10,
"uom": "EA",
@@ -1421,7 +1458,7 @@ def test_human_edit_revalidates_reservation_and_blocks_stale_confirm(app, client
json={
"task_id": task_id,
"structured": {
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 2, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 2, "uom": "EA"}],
"confidence": 0.4,
},
},
@@ -1463,7 +1500,7 @@ def test_parse_notice_blocks_valid_reservation_when_column_evidence_conflicts(ap
headers=headers,
json={"source_type": "manual"},
).get_json()["task_id"]
raw_text = "AWS Sku\tReservation ID\tQty\nA001\t3000092917\t2"
raw_text = "Part Number\tReservation ID\tQty\nA001\t3000092917\t2"
result = client.post(
"/api/shipping-notice/tools/parse_notice",
@@ -1472,7 +1509,7 @@ def test_parse_notice_blocks_valid_reservation_when_column_evidence_conflicts(ap
"task_id": task_id,
"raw_text": raw_text,
"structured": {
"lines": [{"sku": "A001", "reservation_id": "3000092918", "qty": 2, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "3000092918", "qty": 2, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1510,7 +1547,7 @@ def test_parse_notice_low_confidence_does_not_write_parse_review_chat_card(app,
"conversation_id": "conv-no-parse-card",
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "1000140351", "qty": 10, "uom": "EA"}],
"confidence": 0.4,
},
},
@@ -1553,7 +1590,7 @@ def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client, m
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1598,7 +1635,7 @@ def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, cli
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1646,7 +1683,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{"part_number": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -1656,7 +1693,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task_db_id = task.id
task.inventory_lines_json = [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]
task.inventory_lines_json = [{"part_number": "A001", "reservation_id": "R-1", "available_qty": 10}]
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
@@ -1672,7 +1709,7 @@ def test_submit_decision_confirm_inventory_mapping_enqueues_worker(app, client,
"headers": ["Reservation ID", "SKU", "Qty Available"],
"field_mapping": {
"reservation_id": "Reservation ID",
"sku": "SKU",
"part_number": "SKU",
"available_qty": "Qty Available",
},
"mapping": {
@@ -1720,13 +1757,14 @@ def test_retry_rpa_force_refresh_clears_inventory_mapping_state(app, client, tmp
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "inventory_ready"
task.review_status = "align_review"
task.pending_human_reason = "align_review"
task.inventory_lines_json = [{"sku": "OLD", "reservation_id": "R-1", "available_qty": 3}]
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "R-1", "available_qty": 3}]
task.match_status = "fulfillable"
task.shortage_json = {"lines": []}
task.line_results_json = [{"sku": "OLD", "status": "ok"}]
task.line_results_json = [{"part_number": "OLD", "status": "ok"}]
task.export_file_path = str(tmp_path / "old.xlsx")
task.export_file_name = "old.xlsx"
task.upload_status = "failed"
@@ -1797,6 +1835,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
@@ -1860,6 +1899,7 @@ def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_pa
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_EXHAUSTED
task.step_payload_json = {
@@ -1939,6 +1979,7 @@ def test_batch_retry_marks_timed_out_rpa_pending_task_as_exhausted(app, client,
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
task.lines_json = [{"part_number": "A001", "reservation_id": "R-1", "qty": 1}]
task.process_status = "waiting_inventory"
task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = {
@@ -1993,7 +2034,7 @@ def test_submit_decision_by_conversation_id(app, client):
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "reservation_id": "1000140351", "qty": 9, "uom": "EA"}],
"lines": [{"part_number": "504-010213-001", "reservation_id": "1000140351", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -2028,7 +2069,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"sku": "A001", "reservation_id": "1000140351", "qty": 1}],
lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}],
)
second = ShippingTask(
task_no="SN-MULTI-CONV-002",
@@ -2037,7 +2078,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"sku": "A002", "reservation_id": "1000140352", "qty": 1}],
lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}],
)
with app.app_context():
db.session.add_all([first, second])
@@ -2147,4 +2188,3 @@ def test_chat_actions_empty_when_task_rejected(app):
ui_state = build_task_ui_state(task)
assert ui_state["checkpoint"] == "rejected"
assert ui_state["action_buttons"] == []
@@ -30,7 +30,7 @@ def _task(**kwargs) -> ShippingTask:
process_status=kwargs.pop('process_status', 'pending_review'),
pending_human_reason=kwargs.pop('pending_human_reason', 'rsv_req'),
po_number=kwargs.pop('po_number', 'PO-100'),
lines_json=kwargs.pop('lines_json', [{'sku': 'A001', 'qty': 10}]),
lines_json=kwargs.pop('lines_json', [{'part_number': 'A001', 'qty': 10}]),
order_data_version=1,
order_lines_migration_status='pending',
**kwargs,
@@ -52,15 +52,15 @@ def test_build_plan_fills_empty_and_conflicts_on_diff(app):
"""空字段自动进入 fills;双方非空不同进入 conflicts。"""
with app.app_context():
task = _task(lines_json=[
{'sku': 'A001', 'qty': 10, 'reservation_id': ''},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000001'},
{'part_number': 'A001', 'qty': 10, 'reservation_id': ''},
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000000001'},
])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary={
'lines': [
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917', 'hub_code': 'H1'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000099'},
{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917', 'inventory_source_hint': 'H1'},
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000000099'},
]
},
verified_reservation_evidence=[
@@ -76,9 +76,9 @@ def test_build_plan_fills_empty_and_conflicts_on_diff(app):
def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
"""冲突落库后库存门禁应阻断。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate.summary_json,
@@ -96,9 +96,9 @@ def test_apply_conflict_persists_field_conflict_and_blocks_gate(app):
def test_resolve_conflict_writes_line_and_is_idempotent(app):
"""解决冲突回写订单行;同幂等键可重放。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
plan = build_candidate_reconciliation_plan(
task=task,
candidate_summary=candidate.summary_json,
@@ -137,14 +137,14 @@ def test_update_notice_line_version_mismatch(app):
task = _task(
process_status='parsed',
pending_human_reason=None,
lines_json=[{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}],
)
replace_task_order_lines(task, task.lines_json, normalize=False)
db.session.commit()
resp = update_notice_line({
'task_id': task.task_no,
'line_index': 0,
'patch': {'hub_code': 'H9'},
'patch': {'inventory_source_hint': 'H9'},
'expected_order_data_version': 1,
})
# replace 已 bump version,再带 1 应失败;先读当前版本再测过期。
@@ -153,7 +153,7 @@ def test_update_notice_line_version_mismatch(app):
resp = update_notice_line({
'task_id': task.task_no,
'line_index': 0,
'patch': {'hub_code': 'H8'},
'patch': {'inventory_source_hint': 'H8'},
'expected_order_data_version': stale,
})
assert resp['status'] == 'failed'
@@ -165,13 +165,13 @@ def test_multiline_conflicts_persist_and_survive_line_replace(app):
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _task(lines_json=[
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000000001'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000000002'},
{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'},
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000000002'},
])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([
{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'},
{'sku': 'B002', 'qty': 5, 'reservation_id': '3000092918'},
{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'},
{'part_number': 'B002', 'qty': 5, 'reservation_id': '3000092918'},
])
plan = build_candidate_reconciliation_plan(
task=task,
@@ -200,9 +200,9 @@ def test_multiline_conflicts_persist_and_survive_line_replace(app):
def test_reconcile_exact_file_open_existing_auto_fill(app):
"""安全态 exact_file 可自动补空 Reservation。"""
with app.app_context():
task = _task(lines_json=[{'sku': 'A001', 'qty': 10}])
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10}])
replace_task_order_lines(task, task.lines_json, normalize=False)
candidate = _candidate([{'sku': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
candidate = _candidate([{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000092917'}])
result = reconcile_exact_file_open_existing(
task=task,
candidate=candidate,
+57 -31
View File
@@ -64,10 +64,12 @@ def test_dual_write_replace_persists_json_and_table(app):
task,
[
{
'sku': 'A001',
'part_number': 'A001',
'qty': 10,
'reservation_id': '3000092917',
'hub_code': 'H1',
'customer_part_number': 'C-A001',
'aws_part_number': 'AWS-A001',
'inventory_source_hint': 'H1',
'custom_note': 'keep-me',
}
],
@@ -75,17 +77,19 @@ def test_dual_write_replace_persists_json_and_table(app):
)
db.session.commit()
assert written[0]['sku'] == 'A001'
assert written[0]['part_number'] == 'A001'
assert task.lines_json[0]['custom_note'] == 'keep-me'
assert int(task.order_data_version) == version_before + 1
assert task.order_lines_migration_status == 'synced'
rows = ShippingTaskLine.query.filter_by(task_id=task.id).order_by(ShippingTaskLine.position).all()
assert len(rows) == 1
assert rows[0].sku == 'A001'
assert rows[0].part_number == 'A001'
assert rows[0].qty == Decimal('10')
assert rows[0].reservation_id == '3000092917'
assert rows[0].hub_code == 'H1'
assert rows[0].customer_part_number == 'C-A001'
assert rows[0].aws_part_number == 'AWS-A001'
assert rows[0].inventory_source_hint == 'H1'
assert rows[0].extra_json == {'custom_note': 'keep-me'}
assert compare_task_order_line_projections(task)['equal'] is True
@@ -94,19 +98,19 @@ def test_dual_write_failure_rolls_back_both_sides(app):
"""构造行失败时不得留下半写规范行或 JSON。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task(lines=[{'sku': 'OLD', 'qty': 1}])
task = _make_task(lines=[{'part_number': 'OLD', 'qty': 1}])
db.session.commit()
with pytest.raises(ValueError, match='invalid qty'):
replace_task_order_lines(
task,
[{'sku': 'BAD', 'qty': 0, 'reservation_id': 'R-1'}],
[{'part_number': 'BAD', 'qty': 0, 'reservation_id': 'R-1'}],
normalize=False,
)
db.session.rollback()
task = db.session.get(ShippingTask, task.id)
assert task.lines_json == [{'sku': 'OLD', 'qty': 1}]
assert task.lines_json == [{'part_number': 'OLD', 'qty': 1}]
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
@@ -115,7 +119,7 @@ def test_clear_and_shadow_read(app, caplog):
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task()
replace_task_order_lines(task, [{'sku': 'A001', 'qty': 2}], normalize=False)
replace_task_order_lines(task, [{'part_number': 'A001', 'qty': 2}], normalize=False)
db.session.commit()
clear_task_order_lines(task)
@@ -124,14 +128,14 @@ def test_clear_and_shadow_read(app, caplog):
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
# 人为制造影子差异:只改 JSON,不改表。
task.lines_json = [{'sku': 'SHADOW', 'qty': 9}]
task.lines_json = [{'part_number': 'SHADOW', 'qty': 9}]
task.order_lines_migration_status = 'pending'
db.session.commit()
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'shadow'
with caplog.at_level('WARNING'):
lines = read_task_order_lines(task)
assert lines == [{'sku': 'SHADOW', 'qty': 9}]
assert lines == [{'part_number': 'SHADOW', 'qty': 9}]
assert any('shadow mismatch' in message for message in caplog.messages)
@@ -142,9 +146,9 @@ def test_sync_from_json_backfill_idempotent_and_dry_run(app):
task_no='SN-LINE-BACKFILL-001',
lines=[
{
'sku': 'B002',
'part_number': 'B002',
'qty': '3.50',
'source_type': 'HUB',
'inventory_source_hint': 'HUB',
'legacy_flag': True,
}
],
@@ -176,7 +180,7 @@ def test_sync_rejects_invalid_historical_line(app):
with app.app_context():
task = _make_task(
task_no='SN-LINE-BAD-001',
lines=[{'sku': 'Z', 'qty': -1}],
lines=[{'part_number': 'Z', 'qty': -1}],
)
db.session.commit()
@@ -184,14 +188,14 @@ def test_sync_rejects_invalid_historical_line(app):
assert result['status'] == 'failed'
assert 'invalid qty' in str(result.get('reason') or '')
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
assert task.lines_json == [{'sku': 'Z', 'qty': -1}]
assert task.lines_json == [{'part_number': 'Z', 'qty': -1}]
def test_backfill_script_page_and_resume(app):
"""回填脚本支持 dry-run、apply、按 after_id 续跑,失败任务隔离。"""
with app.app_context():
good = _make_task(task_no='SN-BF-GOOD', lines=[{'sku': 'G1', 'qty': 1}])
bad = _make_task(task_no='SN-BF-BAD', lines=[{'sku': 'B1', 'qty': 0}])
good = _make_task(task_no='SN-BF-GOOD', lines=[{'part_number': 'G1', 'qty': 1}])
bad = _make_task(task_no='SN-BF-BAD', lines=[{'part_number': 'B1', 'qty': 0}])
db.session.commit()
dry_summary = backfill_shipping_task_lines(dry_run=True, after_id=0, limit=50)
@@ -218,9 +222,9 @@ def test_json_write_mode_skips_table(app):
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'json'
task = _make_task(task_no='SN-JSON-ONLY')
replace_task_order_lines(task, [{'sku': 'J1', 'qty': 4}], normalize=False)
replace_task_order_lines(task, [{'part_number': 'J1', 'qty': 4}], normalize=False)
db.session.commit()
assert task.lines_json[0]['sku'] == 'J1'
assert task.lines_json[0]['part_number'] == 'J1'
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
assert task.order_lines_migration_status == 'pending'
@@ -233,17 +237,17 @@ def test_table_read_mode_returns_canonical_projection(app):
task = _make_task(task_no='SN-TABLE-READ')
replace_task_order_lines(
task,
[{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}],
[{'part_number': 'T1', 'qty': 5, 'reservation_id': '3000092917'}],
normalize=False,
)
db.session.commit()
# 人为制造 JSON 漂移:table 读路径不得返回漂移值。
task.lines_json = [{'sku': 'DRIFT', 'qty': 99}]
task.lines_json = [{'part_number': 'DRIFT', 'qty': 99}]
db.session.commit()
lines = read_task_order_lines(task)
assert lines == [{'sku': 'T1', 'qty': 5, 'reservation_id': '3000092917'}]
assert lines == [{'part_number': 'T1', 'qty': 5, 'reservation_id': '3000092917'}]
comparison = compare_task_order_line_projections(task)
assert comparison['equal'] is False
assert comparison['table_count'] == 1
@@ -251,15 +255,15 @@ def test_table_read_mode_returns_canonical_projection(app):
def test_lines_checksum_stable_for_key_order(app):
"""checksum 对 dict key 顺序稳定,供影子对账。"""
left = [{'qty': 1, 'sku': 'A'}]
right = [{'sku': 'A', 'qty': 1}]
left = [{'qty': 1, 'part_number': 'A'}]
right = [{'part_number': 'A', 'qty': 1}]
assert lines_checksum(left) == lines_checksum(right)
def test_lines_checksum_normalizes_id_and_qty_types(app):
"""checksum 忽略 reservation_id int/str 与 qty 1/1.0 的类型差异。"""
left = [{'sku': 'A', 'qty': 1, 'reservation_id': 3000092917, 'hub_code': 12}]
right = [{'sku': 'A', 'qty': 1.0, 'reservation_id': '3000092917', 'hub_code': '12'}]
left = [{'part_number': 'A', 'qty': 1, 'reservation_id': 3000092917, 'inventory_source_hint': 12}]
right = [{'part_number': 'A', 'qty': 1.0, 'reservation_id': '3000092917', 'inventory_source_hint': '12'}]
assert lines_checksum(left) == lines_checksum(right)
@@ -271,9 +275,9 @@ def test_shadow_read_tolerates_unsaved_task(app):
task_no='SN-UNSAVED',
source_type='manual',
process_status='parsed',
lines_json=[{'sku': 'A001', 'qty': 1}],
lines_json=[{'part_number': 'A001', 'qty': 1}],
)
assert read_task_order_lines(task) == [{'sku': 'A001', 'qty': 1}]
assert read_task_order_lines(task) == [{'part_number': 'A001', 'qty': 1}]
app.config['SHIPPING_NOTICE_ORDER_LINES_READ_MODE'] = 'table'
assert read_task_order_lines(task) == []
@@ -282,16 +286,38 @@ def test_replace_rolls_back_when_commit_fails_after_dual_write(app):
"""提交阶段失败时,两侧变更应随事务回滚(故障注入)。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task(task_no='SN-FAULT-001', lines=[{'sku': 'OLD', 'qty': 1}])
task = _make_task(task_no='SN-FAULT-001', lines=[{'part_number': 'OLD', 'qty': 1}])
db.session.commit()
task_id = task.id
replace_task_order_lines(task, [{'sku': 'NEW', 'qty': 2}], normalize=False)
replace_task_order_lines(task, [{'part_number': 'NEW', 'qty': 2}], normalize=False)
with patch.object(db.session, 'commit', side_effect=RuntimeError('boom')):
with pytest.raises(RuntimeError, match='boom'):
db.session.commit()
db.session.rollback()
task = db.session.get(ShippingTask, task_id)
assert task.lines_json == [{'sku': 'OLD', 'qty': 1}]
assert task.lines_json == [{'part_number': 'OLD', 'qty': 1}]
assert ShippingTaskLine.query.filter_by(task_id=task_id).count() == 0
@pytest.mark.parametrize(
('line', 'error'),
[
({'qty': 1}, 'missing part_number'),
({'part_number': 'TEMP/D4', 'qty': 1}, 'non-atomic part_number'),
({'part_number': 'D4', 'customer_part_number': 'C/1', 'qty': 1}, 'non-atomic customer_part_number'),
({'part_number': 'D4', 'aws_part_number': 'AWS/1', 'qty': 1}, 'non-atomic aws_part_number'),
],
)
def test_v2_store_rejects_missing_or_composite_part_numbers(app, line, error):
"""v2 双写入口必须拒绝缺失或含 `/` 的任一料号,避免复合值进入规范投影。"""
with app.app_context():
app.config['SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE'] = 'dual'
task = _make_task(task_no=f"SN-V2-INVALID-{error[:8].upper()}")
with pytest.raises(ValueError, match=error):
replace_task_order_lines(task, [line], normalize=False)
db.session.rollback()
assert ShippingTaskLine.query.filter_by(task_id=task.id).count() == 0
@@ -135,7 +135,7 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
task_no='SN-LINE-ORM-001',
source_type='manual',
process_status='parsed',
lines_json=[{'sku': 'A001', 'qty': 1}],
lines_json=[{'part_number': 'A001', 'qty': 1}],
)
db.session.add(task)
db.session.flush()
@@ -143,11 +143,10 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
line = ShippingTaskLine(
task_id=int(task.id),
position=0,
sku='A001',
part_number='A001',
qty=Decimal('1'),
reservation_id='1000140351',
source_type='DBS DUB',
hub_code='DUB1',
inventory_source_hint='DUB1',
extra_json={'legacy_note': 'kept'},
)
db.session.add(line)
@@ -168,7 +167,7 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
db.session.add(ShippingTaskLine(
task_id=int(task.id),
position=0,
sku='B001',
part_number='B001',
qty=Decimal('2'),
))
db.session.flush()
@@ -179,3 +178,63 @@ def test_shipping_task_line_orm_constraints_and_cascade(app):
db.session.commit()
assert ShippingTaskLine.query.count() == 0
assert ShippingTaskFieldConflict.query.count() == 0
def test_shipping_task_line_v2_migration_is_destructive_and_reversible():
"""v2 迁移应清空旧数据、切换新列和约束,并可恢复空的 v1 表结构。"""
engine = sa.create_engine('sqlite:///:memory:')
_task_lines_pre_migration_schema(engine)
v1 = importlib.import_module(
'migrations.versions.d5e6f7a8b9c0_shipping_task_lines_and_conflicts'
)
v2 = importlib.import_module(
'migrations.versions.0f7a8b9c0d1e_shipping_task_line_v2'
)
with engine.begin() as connection:
operations = Operations(MigrationContext.configure(connection, opts={'render_as_batch': True}))
original_v1_op = v1.op
original_v2_op = v2.op
v1.op = operations
v2.op = operations
try:
v1.upgrade()
connection.execute(sa.text(
"INSERT INTO shipping_tasks "
"(id, task_no, source_type, process_status, lines_json, order_data_version, "
"order_lines_migration_status, created_at, updated_at) "
"VALUES (1, 'SN-V2-MIG', 'manual', 'parsed', :lines_json, 1, 'synced', "
"CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
), {'lines_json': '[{"sku":"OLD","qty":1}]'})
connection.execute(sa.text(
"INSERT INTO shipping_task_lines "
"(id, task_id, position, sku, qty, schema_version, line_version, created_at, updated_at) "
"VALUES (1, 1, 0, 'OLD', 1, 'shipping-task-line-v1', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
))
v2.upgrade()
columns = {column['name'] for column in sa.inspect(connection).get_columns('shipping_task_lines')}
assert {'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint'} <= columns
assert not {'sku', 'vendor_part_number', 'customer_sku', 'source_type', 'hub_code'} & columns
assert connection.execute(sa.text('SELECT COUNT(*) FROM shipping_task_lines')).scalar() == 0
task_row = connection.execute(sa.text(
'SELECT lines_json, order_lines_migration_status FROM shipping_tasks WHERE id = 1'
)).one()
assert str(task_row[0]) == '[]'
assert task_row[1] == 'pending'
with pytest.raises(IntegrityError):
with connection.begin_nested():
connection.execute(sa.text(
"INSERT INTO shipping_task_lines "
"(id, task_id, position, part_number, qty, schema_version, line_version, created_at, updated_at) "
"VALUES (2, 1, 0, 'TEMP/D4', 1, 'shipping-task-line-v2', 1, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"
))
v2.downgrade()
downgraded = {column['name'] for column in sa.inspect(connection).get_columns('shipping_task_lines')}
assert {'sku', 'vendor_part_number', 'customer_sku', 'source_type', 'hub_code'} <= downgraded
assert not {'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint'} & downgraded
finally:
v1.op = original_v1_op
v2.op = original_v2_op
@@ -22,8 +22,8 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
intake_id=1,
primary_document_id=1,
candidate_key='parsed-projection-1',
missing_fields_json=['hub_code'],
field_confidence_json={'sku': 0.95, 'qty': 0.9},
missing_fields_json=['inventory_source_hint'],
field_confidence_json={'part_number': 0.95, 'qty': 0.9},
evidence_json=[{
'field': 'lines[0].reservation_id',
'line_index': 0,
@@ -43,17 +43,15 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
po_number='4510038672',
source_candidate_id=int(candidate.id),
lines_json=[{
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'inventory_source_hint': 'DBS DUB',
}],
step_payload_json={
'parse_validation': {
'status': 'ready',
'issues': [],
'contract_version': 'shipping-line-v1',
},
'process_field_gate': {
'status': 'ready',
@@ -67,11 +65,11 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
detail = serialize_task_detail(task)
assert detail['lines'][0]['reservation_id'] == '1000140351'
assert detail['lines'][0]['hub_code'] == 'DUB1'
assert detail['lines'][0]['inventory_source_hint'] == 'DBS DUB'
assert detail['parse_validation']['status'] == 'ready'
assert detail['process_field_gate']['status'] == 'ready'
assert detail['source_candidate']['candidate_no'] == 'SNC-PARSED-PROJECTION-001'
assert detail['source_candidate']['missing_fields'] == ['hub_code']
assert detail['source_candidate']['missing_fields'] == ['inventory_source_hint']
assert detail['source_candidate']['evidence'][0]['reservation_id'] == '1000140351'
@@ -84,51 +82,66 @@ def test_serialize_candidate_brief_exposes_evidence_and_missing_fields(app):
primary_document_id=1,
candidate_key='brief-evidence-1',
missing_fields_json=['reservation_id'],
field_confidence_json={'sku': 0.88},
evidence_json=[{'field': 'lines[0].sku', 'quote': 'SKU-A', 'document_id': 1}],
field_confidence_json={'part_number': 0.88},
evidence_json=[{'field': 'lines[0].part_number', 'quote': 'SKU-A', 'document_id': 1}],
conflicts_json=[{'field': 'reservation_id', 'reason': 'source_conflict'}],
structured_result_json={'business_summary': {'po_number': 'PO-1', 'lines': []}},
structured_result_json={
'business_summary': {'po_number': 'PO-1', 'lines': []},
'extraction': {
'field_adjudication': {
'schema_version': 'shipping-field-adjudication-v1',
'decisions': [{'field': 'part_number', 'status': 'consensus'}],
'observations': [{'observation_id': 'obs-current'}],
'observation_history': [
{'observation_id': 'obs-old'},
{'observation_id': 'obs-current'},
],
'conflicts': [],
},
},
},
)
brief = _serialize_candidate_brief(candidate)
assert brief['missing_fields'] == ['reservation_id']
assert brief['field_confidence']['sku'] == 0.88
assert brief['field_confidence']['part_number'] == 0.88
assert brief['evidence'][0]['quote'] == 'SKU-A'
assert brief['conflicts'][0]['reason'] == 'source_conflict'
assert brief['field_adjudication']['decisions'][0]['status'] == 'consensus'
assert [
item['observation_id']
for item in brief['field_adjudication']['observation_history']
] == ['obs-old', 'obs-current']
def test_normalize_notice_line_keeps_hub_code_independent_of_source_type():
"""Hub Code 不得折叠进 source_type;两者应同时保留。"""
def test_normalize_notice_line_keeps_inventory_source_hint():
"""V2 订单行应保留唯一的 inventory_source_hint 路由线索。"""
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
from app.services.shipping_notice.notice_lines import normalize_notice_line
line = normalize_notice_line({
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'inventory_source_hint': 'DBS DUB',
'Hub Code': 'SHOULD_NOT_OVERRIDE_EXPLICIT',
})
assert line is not None
assert line['source_type'] == 'DBS DUB'
assert line['hub_code'] == 'DUB1'
assert line['inventory_source_hint'] == 'DBS DUB'
summary = normalize_candidate_business_summary({
'po_number': '4510038672',
'lines': [{
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'VMI-FRA01',
'hub_code': 'FRA01',
'inventory_source_hint': 'VMI-FRA01',
}],
})
assert summary['lines'][0]['source_type'] == 'VMI-FRA01'
assert summary['lines'][0]['hub_code'] == 'FRA01'
assert summary['lines'][0]['inventory_source_hint'] == 'VMI-FRA01'
def test_candidate_update_persists_hub_code_round_trip(app):
"""Candidate 人工修订保存后,hub_code 必须仍在 business_summary 中。"""
def test_candidate_update_persists_inventory_source_hint_round_trip(app):
"""Candidate 人工修订保存后,inventory_source_hint 必须仍在 business_summary 中。"""
from app.models import Agent, ChatSession, FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, User
from app.services.shipping_notice.candidate_service import update_candidate
@@ -197,7 +210,7 @@ def test_candidate_update_persists_hub_code_round_trip(app):
structured_result_json={
'business_summary': {
'po_number': '4510038672',
'lines': [{'sku': 'P123456', 'qty': 24, 'uom': 'EA'}],
'lines': [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
},
},
)
@@ -210,19 +223,16 @@ def test_candidate_update_persists_hub_code_round_trip(app):
business_summary={
'po_number': '4510038672',
'lines': [{
'sku': 'P123456',
'part_number': 'P123456',
'qty': 24,
'reservation_id': '1000140351',
'source_type': 'DBS DUB',
'hub_code': 'DUB1',
'inventory_source_hint': 'DBS DUB',
'uom': 'EA',
}],
},
)
line = updated['business_summary']['lines'][0]
assert line['source_type'] == 'DBS DUB'
assert line['hub_code'] == 'DUB1'
assert line['inventory_source_hint'] == 'DBS DUB'
db.session.refresh(candidate)
persisted = candidate.structured_result_json['business_summary']['lines'][0]
assert persisted['hub_code'] == 'DUB1'
assert persisted['source_type'] == 'DBS DUB'
assert persisted['inventory_source_hint'] == 'DBS DUB'