refactor(shipping-notice): 统一料号字段,移除过时的 SKU 相关字段,更新相关逻辑以支持新字段命名
This commit is contained in:
1 parent
dde25344ca
commit
46eb63f5bb
111 files changed
+3116
-1250
No files matched your search
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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)} |",
|
||||
]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
+42
@@ -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():
|
||||
|
||||
@@ -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"
|
||||
@@ -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,
|
||||
|
||||
@@ -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'
|
||||
+9
-4
@@ -50,7 +50,7 @@
|
||||
### 3.x 货代发货通知库存源补充需求
|
||||
|
||||
- **核心目标**:在订单解析阶段即确定库存查询来源(`source_code`),避免 RPA 抓错库存池;用户仅需确认来源编码,站点与仓库由系统配置生成。
|
||||
- **字段隔离**:订单行 `source_type` 仅作为可选路由线索;库存连接器字段统一为 `connector_type`,任务 API 使用 `inventory_connector_type`,不得复用 `ShippingTask.source_type` 通知来源。
|
||||
- **字段隔离**:订单行仅使用 `inventory_source_hint` 保存可选路由线索;库存连接器字段统一为 `connector_type`,任务 API 使用 `inventory_connector_type`,不得复用 `ShippingTask.source_type` 通知来源。
|
||||
- **自动匹配**:根据发货通知目的地/港口/仓库线索与 `shipping_inventory_sources.yaml` 规则自动 adjudicate;唯一命中则 `resolved` 并继续流程。
|
||||
- **人工确认**:无法唯一命中时进入 `inventory_source_review` 检查点,用户在聊天区选择或输入线索确认 `source_code`。
|
||||
- **硬阻断**:库存源未稳定(`resolved` / `user_confirmed`)时,RPA、库存匹配、Excel 生成、货代上传均不得执行。
|
||||
@@ -76,9 +76,9 @@
|
||||
|
||||
- 保持“一封 EML = 一个 Intake”;上传阶段只预处理正文和附件为 Document,用户点击发送后才由现有货代 Chatflow 完整解析业务订单并生成 Candidate。
|
||||
- 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。
|
||||
- 正文与附件由 LLM 结合语义关联;附件优先作为主证据,SKU/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。
|
||||
- 正文与附件由 LLM 结合语义关联;后端规则解析与 Dify LLM 均只产出不可变字段 Observation,由 HXOPS 按字段证据统一裁决;`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。
|
||||
- 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。
|
||||
- 高置信发货需求只要包含可信 SKU + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;订单行 Source Type 是可选路由线索,不作为必填门禁。
|
||||
- 高置信发货需求只要包含可信内部料号 `part_number` + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。
|
||||
- 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。
|
||||
- 本期复用现有货代 Chatflow,不新增独立 Dify Workflow,不新增 `agent_runtime_bindings`。
|
||||
- 用户点击发送后,聊天区必须立即显示订单识别进行态;该阶段无法获得可信完成比例,因此使用不确定进度,不展示伪造百分比。
|
||||
@@ -87,7 +87,12 @@
|
||||
|
||||
### 3.x 发货通知关键字段真值校验
|
||||
|
||||
- LLM 只负责从不同客户、不同版式的通知中抽取候选值;HXOPS 后端负责 `reservation_id / sku / qty` 的归一化、来源校验、冲突裁决与最终落库。
|
||||
- 规范订单行采用通用三料号领域模型:`part_number` 是内部料号且为订单必填字段;`customer_part_number` 是客户料号、`aws_part_number` 是货代/AWS 系统料号,二者可选且不单独触发流程门禁;旧 `sku / vendor_part_number / customer_sku` 不再作为当前字段模型字段。
|
||||
- LLM 与后端规则解析器只负责从不同文档和版式产生字段 Observation;HXOPS 后端负责 `part_number / customer_part_number / aws_part_number / reservation_id / qty` 的归一化、证据验证、字段级评分、冲突裁决与规范投影落库,禁止任何一方整体覆盖另一方。
|
||||
- 料号必须是原子值;三个料号字段均禁止包含 `/`。复合文本须先拆为候选 token,再依据表头、前缀、相邻字段和跨文档证据判定角色;角色不明时落冲突,不得把复合文本直接落为料号。
|
||||
- 跨来源裁决遵循:仅一方有可信值则采用;双方一致则标记 consensus;双方均可信但不同或分差不足则落字段冲突。LLM 自报置信度仅作弱参考,最终置信度由后端按证据质量统一计算。
|
||||
- 库存主匹配键固定为 `(part_number, reservation_id)`;库存 `Supplier Sku` 映射为 `part_number`,`AWS Sku` 仅映射为可选 `aws_part_number`,不得作为默认主匹配料号。
|
||||
- 本次为无生产数据的破坏性字段升级,不保留旧字段兼容层:规范订单行使用 `shipping-task-line-v2`,内容指纹使用 `shipping-content-v4`;后端、Dify 画布、静态 OpenAPI 与前端必须同批切换。
|
||||
- Reservation ID 不绑定单一邮件模板:允许 `Reservation ID / COM ID / Reservation Order / PR Number / External reservation ID` 等业务来源;禁止把 `Allocation ID / Parent allocation ID / Commodity group ID` 当作 Reservation ID。
|
||||
- 32 位十六进制内部主键和 UUID 不得进入库存匹配;数字型及 `AWS-311 / ORD-3002 / R-1` 等字母型业务编号按通用契约兼容,后续可按客户或来源 profile 收紧。
|
||||
- 自动纠错必须具备表头列关系和唯一 SKU/APN/MPN 关联证据;拍平文本或多义匹配不得猜测,必须进入人工复核。
|
||||
|
||||
@@ -137,15 +137,14 @@ agent_code
|
||||
platform.session_id
|
||||
platform.request_id
|
||||
refs.capability
|
||||
refs.contract_version
|
||||
refs.intake_nos
|
||||
```
|
||||
|
||||
当 `refs.capability=order_extraction` 且 `refs.contract_version=shipping-order-extraction-v1` 时,必须在任务续办/库存/自由 Agent 之前执行:
|
||||
当 `refs.capability=order_extraction` 时,必须在任务续办/库存/自由 Agent 之前执行:
|
||||
|
||||
```text
|
||||
get_order_extraction_context
|
||||
-> LLM 输出 {schema_version, orders[]}
|
||||
-> LLM 输出 {orders[]}
|
||||
-> Code 校验 JSON
|
||||
-> submit_order_extraction
|
||||
-> 模板回复
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# 货代发货通知 — 业务培训手册 / 操作 SOP
|
||||
|
||||
> **面向对象**:货代、跟单、仓储等业务人员。
|
||||
> **面向对象**:货代、跟单、仓储等业务人员。
|
||||
> **配套技术文档**:[`technical.md`](./technical.md)(部署、系统配置,供 IT / 开发维护)。
|
||||
> **维护约定**:发货流程、字段规则、人工确认节点等发生变更时,**须同时更新本文件与 `technical.md`**,避免业务说明与系统行为不一致。
|
||||
|
||||
@@ -53,10 +53,10 @@
|
||||
|
||||
**货代发货通知助手**帮助业务人员把客户发来的发货指令(邮件、微信文字、PDF、Word 等)转成可执行的发货动作,主要能力包括:
|
||||
|
||||
1. **解析发货通知**:上传后系统先读取邮件正文和附件;您点击“发送”后,AI 才会完整识别客户、收货信息,以及每一行的 SKU、数量、单价、金额、Reservation ID 等。
|
||||
1. **解析发货通知**:上传后系统先读取邮件正文和附件;您点击“发送”后,AI 与后端解析器会分别提取候选,再由系统逐字段核验证据,识别客户、收货信息,以及每一行的内部料号、客户料号、AWS 料号、数量、金额、Reservation ID 等。
|
||||
一封 EML 中可以包含多个订单,也可能一个附件里包含多个订单;系统仍保留为一个接入记录,并按实际业务订单拆分处理。
|
||||
2. **载入库存**:上传库存 Excel,或由系统自动从货代/仓库系统导出库存(若已配置自动化)。
|
||||
3. **核对库存**:按 SKU + Reservation ID + 需求数量,与库存表比对是否可满足。
|
||||
3. **核对库存**:按内部料号 + Reservation ID + 需求数量,与库存表比对是否可满足。
|
||||
4. **生成发货文件**:生成符合货代要求的发货 Excel。
|
||||
5. **上传货代系统**:自动或手工确认上传至货代平台。
|
||||
|
||||
@@ -71,8 +71,8 @@
|
||||
|
||||
**系统如何工作(便于理解)**:
|
||||
|
||||
- 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后由 AI 完整识别订单。只要明确属于发货需求且 SKU、数量可信,系统会自动创建任务,无需再次人工确认建单。
|
||||
- Reservation ID 暂时缺失时,任务仍会创建,但会停在“待补充字段”,不会继续查库存;订单行 Source Type 是可选路由线索,可在候选编辑中补充,不作为必填门禁。
|
||||
- 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后由 AI 完整识别订单。只要明确属于发货需求且内部料号、数量可信,系统会自动创建任务,无需再次人工确认建单。
|
||||
- Reservation ID 暂时缺失时,任务仍会创建,但会停在“待补充字段”,不会继续查库存;订单行 `inventory_source_hint` 是可选路由线索,可在候选编辑中补充,不作为必填门禁。
|
||||
- 上传 **库存 Excel** 后,系统会**自动识别表头**(如 `Reservation Order`、`COM ID`)并给出列映射建议;**不确定的列**可在对齐界面用下拉框修改后再确认。
|
||||
- 匹配与生成 Excel 由系统规则执行;您主要在解析结果、字段对齐、库存不足时做确认或补货修订。
|
||||
|
||||
@@ -122,7 +122,7 @@ WYC26071501
|
||||
|
||||
| 顺序 | 资料 | 格式 | 用途 |
|
||||
|------|------|------|------|
|
||||
| 1 | **发货通知 / 订单** | PDF、Word,或邮件/微信正文 | 解析客户、SKU、数量、Reservation ID、单价、金额等 |
|
||||
| 1 | **发货通知 / 订单** | PDF、Word,或邮件/微信正文 | 解析客户、内部料号、客户料号、AWS 料号、数量、Reservation ID、单价、金额等 |
|
||||
| 2 | **库存快照** | Excel(.xlsx / .csv) | 与订单行核对可用库存;大表请直接上传文件,不要整表粘贴到聊天框 |
|
||||
| 3 | (可选)**货代发货模板** | 由 IT 配置 | 生成最终上传货代用的 Excel |
|
||||
|
||||
@@ -132,7 +132,7 @@ WYC26071501
|
||||
|
||||
| 检查项 | 通过标准 |
|
||||
|--------|----------|
|
||||
| 发货通知原件 | 能看到 SKU、数量,最好能看到 Reservation ID / COM ID / PR Number |
|
||||
| 发货通知原件 | 能看到内部料号、数量,最好能看到 Reservation ID / COM ID / PR Number |
|
||||
| 库存文件 | 使用 Excel 文件上传,不把整张大表粘贴进聊天 |
|
||||
| 当前任务 | 已拿到任务编号 `SN-...`,且本次库存属于这一个任务 |
|
||||
| 操作顺序 | 先确认解析,再传库存,再确认字段对齐 |
|
||||
@@ -149,21 +149,23 @@ WYC26071501
|
||||
|------|----------|-------------------|
|
||||
| **PO Number** | 采购订单号(文档级) | PO Number、Purchase Order No、P.O. No、采购订单号;Wistron 原文若带 `ZNB` 前缀(如 ZNB16754796),系统输出为 `16754796` |
|
||||
| **项次 / Item** | 订单行序号 | 项次、Line No、Item、Item No |
|
||||
| **SKU / 料号** | 物料编码 | AWS Sku、Material、料号、Part Number |
|
||||
| **内部料号(Part Number)** | 公司内部管理和库存匹配使用的主料号 | MPN、Vendor Part Number、Supplier Part Number、内部料号 |
|
||||
| **客户料号(Customer Part Number)** | 客户侧物料编码,可为空 | Customer PN、Customer Part Number、Allocated HHPN |
|
||||
| **AWS 料号(AWS Part Number)** | 货代/AWS 系统物料编码,可为空 | AWS Sku、AWS SKU |
|
||||
| **需求数量** | 本次应发数量 | Qty、Order Qty、数量、发货数量 |
|
||||
| **单价** | 单行单价 | Unit Price、单价、Price |
|
||||
| **金额** | 单行金额 | Amount、Line Amount、金额、小计 |
|
||||
| **币种** | 单价/金额的货币单位 | Currency、Curr、CCY、币种;也可从 `100.50 USD` 等形式识别 |
|
||||
| **Reservation ID** | 预留/订单占用编号,用于与库存精确对应 | Reservation ID、COM ID、Reservation Order、External reservation ID;Wistron 等 PO 可能在 **PR Number / PR_Number** 字段:`ADU_S-xxx@1000140351`,系统取 `@` 后业务编号 |
|
||||
| **Source Type** | 可选库存路由线索,不代表通知来源或已确认的库存连接器类型 | Source Type、库存来源类型 |
|
||||
| **库存源线索(Inventory Source Hint)** | 可选库存路由线索,不代表通知来源或已确认的库存连接器类型 | Source Type、Hub Code、仓库/站点别名 |
|
||||
| **要求交期** | 该行物料的交货/发货日期 | Required Date、Delivery Date、ETA、交期、交货日期 |
|
||||
| **供应商料号** | 客户侧记录的供应商物料编码 | Vendor Part Number、Vendor PN、Supplier Part No、供应商料号 |
|
||||
|
||||
**说明**:
|
||||
|
||||
- **PO Number** 为文档级字段;**PR Number**(含 `@1000140351`)通常对应 **Reservation ID**,不要与 PO Number 混淆。
|
||||
- **SKU、需求数量、Reservation ID** 是库存核对的核心字段。
|
||||
- **Source Type** 仅辅助库存路由,可展示和修订;缺失时不会单独触发字段门禁。
|
||||
- **内部料号、需求数量、Reservation ID** 是库存核对的核心字段。
|
||||
- `inventory_source_hint` 仅辅助库存源路由,可展示和修订;缺失时不会单独触发字段门禁。
|
||||
- 三种料号都必须是单一原子值,不得包含 `/`。例如 `TEMP-S000218929/D4-A08AR12000002` 应拆成候选后,依据表头和跨文档证据分别归类;无法可靠归类时必须人工复核。
|
||||
- 邮件模板可以不同;系统按字段语义和表格列关系识别,不依赖固定列顺序。`Allocation ID`、`Parent allocation ID`、`Commodity group ID` 不属于 Reservation ID。
|
||||
- AI 解析结果只是候选,后端会再次校验。若候选像 32 位内部主键、与原文列证据冲突或无法可靠对齐,系统会阻断并要求人工复核,不会把猜测值送入库存匹配。
|
||||
- 建单后工作台会持久展示订单解析结果;若新订单与旧任务同 PO 但字段冲突,系统会标出冲突并停住后续库存步骤,需您选择保留旧值、采用新值或手工修正后再继续。
|
||||
@@ -173,10 +175,10 @@ WYC26071501
|
||||
|
||||
**订单行示例**(便于理解系统解析目标):
|
||||
|
||||
| 项次 | SKU | Reservation ID | 需求数量 | 要求交期 | 供应商料号 | 单价 | 金额 | 币种 |
|
||||
|------|-----|----------------|----------|----------|------------|------|------|------|
|
||||
| 10 | 10-40594-001 | 1000140351 | 2 | 2026-06-15 | VND-PN-001 | 15.50 | 31.00 | USD |
|
||||
| 20 | 10-40594-002 | 1000140352 | 1 | 2026-06-18 | VND-PN-002 | 20.00 | 20.00 | USD |
|
||||
| 项次 | 内部料号 | 客户料号 | AWS 料号 | Reservation ID | 需求数量 | 要求交期 |
|
||||
|------|--------------|----------|----------|----------------|----------|----------|
|
||||
| 10 | D4-A08AR12000002 | TEMP-S000218929 | B0XXXXXXXX | 1000140351 | 2 | 2026-06-15 |
|
||||
| 20 | D4-A08AR12000003 | - | - | 1000140352 | 1 | 2026-06-18 |
|
||||
|
||||
### 4.2 库存表(来自仓库/货代导出)
|
||||
|
||||
@@ -184,15 +186,17 @@ WYC26071501
|
||||
|
||||
| 字段 | 业务含义 | 常见列名示例 |
|
||||
|------|----------|--------------|
|
||||
| **SKU / 料号** | 与订单 SKU 一致 | AWS Sku、料号 |
|
||||
| **内部料号** | 与订单 `part_number` 一致 | Supplier Sku、Supplier SKU |
|
||||
| **AWS 料号** | 可选追溯字段,不作为默认主匹配键 | AWS Sku、AWS SKU |
|
||||
| **Reservation ID** | 与订单 Reservation ID 一致 | COM ID、**Reservation Order**、Reservation ID |
|
||||
| **可用数量** | 当前可发数量 | Qty Available、可用数量、Qty |
|
||||
|
||||
**AWS 库存模板**(当前系统默认支持)示例:
|
||||
|
||||
- `AWS Sku` → SKU
|
||||
- `COM ID` / `Reservation Order` → Reservation ID
|
||||
- `Qty Available` → 可用数量
|
||||
- `Supplier Sku` → 内部料号 `part_number`
|
||||
- `AWS Sku` → 可选 AWS 料号 `aws_part_number`
|
||||
- `COM ID` / `Reservation Order` → Reservation ID
|
||||
- `Qty Available` → 可用数量
|
||||
|
||||
若您的库存表带标题行(如「AWS DUB On Hand Inventory by Location」),系统会尝试跳过标题行,自动识别真正的表头。
|
||||
|
||||
@@ -203,7 +207,7 @@ WYC26071501
|
||||
```text
|
||||
① 提交发货通知
|
||||
↓
|
||||
② 确认解析结果(客户、SKU、数量、Reservation ID 等)
|
||||
② 确认解析结果(客户、内部料号、客户料号、AWS 料号、数量、Reservation ID 等)
|
||||
↓
|
||||
③ 确认标准客户并生成业务编号
|
||||
↓
|
||||
@@ -240,17 +244,17 @@ WYC26071501
|
||||
|
||||
**您可以做:**
|
||||
|
||||
- 在聊天中上传 PDF / Word 发货通知;或
|
||||
- 在聊天中上传 PDF / Word 发货通知;或
|
||||
- 直接粘贴邮件、微信中的发货文字。
|
||||
|
||||
**系统会做:**
|
||||
|
||||
- **自动**创建任务并分配 **SN-…** 编号;
|
||||
- **自动**创建任务并分配 **SN-…** 编号;
|
||||
- **自动**解析客户名称、收货信息、订单明细行(PDF 上传或正文粘贴后由系统后台完成,无需您输入「创建任务」)。
|
||||
|
||||
**您会看到:**
|
||||
|
||||
- 助手展示 **固定格式解析表格**(PO、SKU、Reservation ID、数量、单价、金额、交期、收货方等);
|
||||
- 助手展示 **固定格式解析表格**(PO、内部料号、客户料号、AWS 料号、Reservation ID、数量、单价、金额、交期、收货方等);
|
||||
- 若置信度较低,表格下方会额外提示核对后再继续。
|
||||
|
||||
---
|
||||
@@ -261,8 +265,8 @@ WYC26071501
|
||||
|
||||
**您需要核对:**
|
||||
|
||||
- 客户、交期、收货地址是否正确;
|
||||
- 每一行 **SKU、需求数量、Reservation ID** 是否与原件一致;
|
||||
- 客户、交期、收货地址是否正确;
|
||||
- 每一行 **内部料号、需求数量、Reservation ID** 是否与原件一致;
|
||||
- 单价、金额是否合理(如有)。
|
||||
|
||||
**可选操作:**
|
||||
@@ -289,36 +293,37 @@ WYC26071501
|
||||
|
||||
**推荐方式(大表):**
|
||||
|
||||
- 在聊天中点击 **「选择库存文件」** 上传 Excel;或
|
||||
- 在聊天中点击 **「选择库存文件」** 上传 Excel;或
|
||||
- 使用助手提示的 **数字选项**(如「1 = 上传库存」),再选文件。
|
||||
|
||||
**其他方式:**
|
||||
|
||||
- **自动导出**:若已对接 RPA,助手可触发从货代/仓库系统自动拉取库存(需等待完成);
|
||||
- **自动导出**:若已对接 RPA,助手可触发从货代/仓库系统自动拉取库存(需等待完成);
|
||||
- **小表粘贴**:仅几行库存时,可直接粘贴到聊天(大 Excel 请勿粘贴,易失败)。
|
||||
|
||||
**注意:**
|
||||
|
||||
- 库存文件须关联**当前任务的 SN-… 编号**;
|
||||
- 库存文件须关联**当前任务的 SN-… 编号**;
|
||||
- 发货通知用 PDF/Word,库存用 Excel,**不要混用**(不要把库存 Excel 当发货通知上传)。
|
||||
|
||||
---
|
||||
|
||||
### 阶段 ⑤ — 确认字段对齐
|
||||
|
||||
上传库存后,系统会**先自动推断** Excel 列与订单字段的对应关系(例如 `AWS Sku`→SKU、`Reservation Order`→Reservation ID、`Qty Available`→可用数量),并展示**字段对齐表**供您核对。
|
||||
上传库存后,系统会**先自动推断** Excel 列与订单字段的对应关系(例如 `Supplier Sku`→内部料号、`AWS Sku`→AWS 料号、`Reservation Order`→Reservation ID、`Qty Available`→可用数量),并展示**字段对齐表**供您核对。
|
||||
|
||||
对齐表说明:
|
||||
|
||||
- 库存 Excel 哪一列对应 SKU、Reservation ID、可用数量;
|
||||
- 这些列如何与订单里的字段比对;
|
||||
- 库存 Excel 哪一列对应内部料号、AWS 料号、Reservation ID、可用数量;
|
||||
- 这些列如何与订单里的字段比对;
|
||||
- 订单与库存各取几行样例供您目视检查。
|
||||
|
||||
**示例(概念示意):**
|
||||
|
||||
| 比对项 | 库存 Excel 列 | 订单字段 |
|
||||
|--------|---------------|----------|
|
||||
| 料号 | AWS Sku(或系统推断的列名) | SKU |
|
||||
| 内部料号 | Supplier Sku(或系统推断的列名) | part_number |
|
||||
| AWS 料号 | AWS Sku(可选追溯列) | `aws_part_number` |
|
||||
| 预留号 | COM ID / **Reservation Order**(可在下拉框中改选) | Reservation ID |
|
||||
| 数量 | Qty Available(可在下拉框中改选) | 需求数量 |
|
||||
|
||||
@@ -346,10 +351,10 @@ WYC26071501
|
||||
| 结果 | 含义 |
|
||||
|------|------|
|
||||
| **完全满足** | 所有订单行库存均够 |
|
||||
| **部分满足** | 部分 SKU 有货、部分不足或只能发一部分 |
|
||||
| **部分满足** | 部分内部料号有货、部分不足或只能发一部分 |
|
||||
| **无法满足** | 全部或关键行无可用库存 |
|
||||
|
||||
助手会以表格形式展示:SKU、Reservation ID、需求数量、可用数量、缺口等。
|
||||
助手会以表格形式展示:内部料号、Reservation ID、需求数量、可用数量、缺口等。
|
||||
|
||||
---
|
||||
|
||||
@@ -363,7 +368,7 @@ WYC26071501
|
||||
|
||||
**全部行满足**后:
|
||||
|
||||
1. 系统生成发货 Excel(可在任务详情或助手提示中下载);
|
||||
1. 系统生成发货 Excel(可在任务详情或助手提示中下载);
|
||||
2. 尝试自动上传货代;若自动化未完成,会提示您手工上传并在系统中登记货代单号。
|
||||
|
||||
---
|
||||
@@ -372,11 +377,11 @@ WYC26071501
|
||||
|
||||
系统对**每一行订单**执行如下逻辑(业务口径):
|
||||
|
||||
1. 取订单行的 **SKU** 与 **Reservation ID**。当前规则要求**订单侧必须提供 Reservation ID**;若订单未解析到 Reservation ID,系统会先阻断匹配并要求回到解析阶段修正。
|
||||
2. 在库存表中,将 **相同 SKU + 相同 Reservation ID** 的多行**可用数量相加**。
|
||||
3. 将汇总后的可用数量与订单 **需求数量** 比较:
|
||||
- 可用 ≥ 需求 → 该行 **满足**;
|
||||
- 0 < 可用 < 需求 → 该行 **部分满足**(有缺口);
|
||||
1. 取订单行的 **内部料号 `part_number`** 与 **Reservation ID**。当前规则要求**订单侧必须提供有效 Reservation ID**;若订单未解析到 Reservation ID,系统会先阻断匹配并要求回到解析阶段修正。
|
||||
2. 在库存表中,将 **相同 `part_number` + 相同 Reservation ID** 的多行**可用数量相加**;AWS 料号只作追溯,不作为默认主匹配键。
|
||||
3. 将汇总后的可用数量与订单 **需求数量** 比较:
|
||||
- 可用 ≥ 需求 → 该行 **满足**;
|
||||
- 0 < 可用 < 需求 → 该行 **部分满足**(有缺口);
|
||||
- 可用 = 0 → 该行 **缺货**。
|
||||
|
||||
**Reservation ID 格式说明:**
|
||||
@@ -393,7 +398,7 @@ WYC26071501
|
||||
|
||||
## 8. 库存不足时的处理
|
||||
|
||||
存在任一行缺口时,**默认禁止发货**,不可进入生成 Excel 与上传货代环节。系统会展示缺口明细(SKU、需求数量、可用数量、缺口数量),您可选择:
|
||||
存在任一行缺口时,**默认禁止发货**,不可进入生成 Excel 与上传货代环节。系统会展示缺口明细(内部料号、需求数量、可用数量、缺口数量),您可选择:
|
||||
|
||||
| 您的选择 | 含义 | 后续 |
|
||||
|----------|------|------|
|
||||
@@ -466,7 +471,7 @@ WYC26071501
|
||||
|
||||
**关于聊天中的数字 1 / 2 / 3:**
|
||||
|
||||
- 含义以**助手上一轮文字菜单**为准(例如 1=上传库存、2=粘贴、3=重试导出);
|
||||
- 含义以**助手上一轮文字菜单**为准(例如 1=上传库存、2=粘贴、3=重试导出);
|
||||
- 不会固定写死,请先看清助手给出的选项再输入数字。
|
||||
|
||||
---
|
||||
@@ -484,7 +489,7 @@ WYC26071501
|
||||
| 原则 | 说明 |
|
||||
|------|------|
|
||||
| 保留任务编号 | 截图里尽量带上 `SN-...`,便于定位同一任务 |
|
||||
| 保留关键字段 | 至少能看到 SKU、Reservation ID、数量、状态或按钮 |
|
||||
| 保留关键字段 | 至少能看到内部料号、Reservation ID、数量、状态或按钮 |
|
||||
| 一屏一主题 | 一张图只说明一个阶段,避免把多个动作混在一起 |
|
||||
| 注意脱敏 | 对客户名称、价格、地址等敏感信息按公司要求处理 |
|
||||
|
||||
@@ -499,7 +504,7 @@ WYC26071501
|
||||
|
||||
| 截图位 | 应包含内容 | 用途 |
|
||||
|--------|------------|------|
|
||||
| 发货通知上传后结果页 | 任务编号、采购单号、SKU、Reservation ID、数量、确认/重新解析/驳回按钮 | 培训业务如何核对解析结果 |
|
||||
| 发货通知上传后结果页 | 任务编号、采购单号、内部料号、客户料号、AWS 料号、Reservation ID、数量、确认/重新解析/驳回按钮 | 培训业务如何核对解析结果 |
|
||||
| 低置信度提示页 | 解析结果下方的风险提示或需人工核对提示 | 培训业务识别“需要更认真核对”的场景 |
|
||||
|
||||
### 12.3 库存上传与字段对齐阶段截图
|
||||
@@ -508,13 +513,13 @@ WYC26071501
|
||||
|--------|------------|------|
|
||||
| 上传库存入口 | 选择库存文件按钮或上传动作 | 培训业务如何上传库存 Excel |
|
||||
| 字段对齐页 | 库存列、订单字段、样例数据、确认/更正映射/重新上传按钮 | 培训业务如何确认列映射 |
|
||||
| 列映射下拉框 | Reservation ID、SKU、可用数量的下拉选择 | 培训业务如何修正错误映射 |
|
||||
| 列映射下拉框 | 内部料号、AWS 料号、Reservation ID、可用数量的下拉选择 | 培训业务如何修正错误映射 |
|
||||
|
||||
### 12.4 匹配与缺口阻断阶段截图
|
||||
|
||||
| 截图位 | 应包含内容 | 用途 |
|
||||
|--------|------------|------|
|
||||
| 匹配结果页 | SKU、Reservation ID、需求数量、可用数量、缺口、状态 | 培训业务如何判断是否可发 |
|
||||
| 匹配结果页 | 内部料号、Reservation ID、需求数量、可用数量、缺口、状态 | 培训业务如何判断是否可发 |
|
||||
| 缺口阻断页 | 不可发货提示、重新上传库存 / 返回字段对齐 / 重新匹配 / 驳回按钮 | 培训业务如何处理库存不足 |
|
||||
|
||||
### 12.5 发货 Excel 与上传阶段截图
|
||||
@@ -529,8 +534,8 @@ WYC26071501
|
||||
|
||||
业务反馈问题给 IT / 开发时,建议至少提供以下 3 类截图:
|
||||
|
||||
1. **当前页面全图**:能看到任务编号、当前状态、主要按钮
|
||||
2. **异常位置局部图**:报错提示、空字段、错误映射、缺口结果等
|
||||
1. **当前页面全图**:能看到任务编号、当前状态、主要按钮
|
||||
2. **异常位置局部图**:报错提示、空字段、错误映射、缺口结果等
|
||||
3. **原始资料图**:原 PDF / 邮件 / 库存 Excel 中对应字段的位置
|
||||
|
||||
若能同时提供任务编号 `SN-...`、操作时间、当时做了什么,排查会更快。
|
||||
@@ -539,35 +544,35 @@ WYC26071501
|
||||
|
||||
## 13. 常见问题
|
||||
|
||||
**Q:库存不够时能否先发有货的部分?**
|
||||
**Q:库存不够时能否先发有货的部分?**
|
||||
A:不可以。存在任一行缺口时,系统**默认禁止发货**,须补库存或返回修订后重新匹配,直至**全部订单行满足**后方可生成 Excel 并上传货代。
|
||||
|
||||
**Q:为什么要先确认发货通知,再传库存?**
|
||||
**Q:为什么要先确认发货通知,再传库存?**
|
||||
A:避免任务编号不一致、订单行未定型就占用库存比对,导致结果不可追溯。
|
||||
|
||||
**Q:库存 Excel 很大,可以粘贴到聊天吗?**
|
||||
**Q:库存 Excel 很大,可以粘贴到聊天吗?**
|
||||
A:不可以。请使用「选择库存文件」上传;整表粘贴易失败且无法保证列映射准确。
|
||||
|
||||
**Q:订单有 Reservation ID,库存表里是 COM ID,能匹配吗?**
|
||||
**Q:订单有 Reservation ID,库存表里是 COM ID,能匹配吗?**
|
||||
A:可以。字段对齐环节会把 COM ID 与订单 Reservation ID 对应;确认映射无误即可。
|
||||
|
||||
**Q:发货通知解析结果里没有 Reservation ID(或一直为空)怎么办?**
|
||||
**Q:发货通知解析结果里没有 Reservation ID(或一直为空)怎么办?**
|
||||
A:Reservation ID(也可能叫 COM ID / Reservation Order / PR Number)是库存精确匹配的关键字段。请按以下顺序处理:
|
||||
|
||||
1. 先在原 PDF/邮件中确认是否真的存在该字段(常见写法:`Reservation ID: 1000140351`、`COM ID: 1000140351`、`Reservation Order: 1000140351`、`PR Number: xxx@1000140351`、`PR_Number: xxx@1000140351`)。
|
||||
2. 若原件里存在但系统没抽出来:请把**原文件/截图、任务编号 SN-...、错误现象**一起反馈给 IT/开发排查。
|
||||
3. 若原件里不存在:请向客户/上游确认 Reservation ID 的提供规则,否则系统只能按 SKU 汇总匹配,可能导致同 SKU 多预留号的场景误匹配。
|
||||
1. 先在原 PDF/邮件中确认是否真的存在该字段(常见写法:`Reservation ID: 1000140351`、`COM ID: 1000140351`、`Reservation Order: 1000140351`、`PR Number: xxx@1000140351`、`PR_Number: xxx@1000140351`)。
|
||||
2. 若原件里存在但系统没抽出来:请把**原文件/截图、任务编号 SN-...、错误现象**一起反馈给 IT/开发排查。
|
||||
3. 若原件里不存在:请向客户/上游确认 Reservation ID 的提供规则,在补齐并通过门禁前,系统不会执行库存匹配,避免同一内部料号对应多个预留号时误匹配。
|
||||
|
||||
**Q:Reservation ID 必须是数字吗?**
|
||||
**Q:Reservation ID 必须是数字吗?**
|
||||
A:不一定。很多来源使用 8~12 位纯数字(如 `1000140351`),也有来源使用 `AWS-311`、`ORD-3002` 等字母型业务编号。系统兼容多模板,但会拒绝 32 位十六进制内部主键、UUID 等明显不是业务预留号的值。
|
||||
|
||||
**Q:单价、金额错了会影响能不能发货吗?**
|
||||
A:不会。库存匹配只看 SKU、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。
|
||||
**Q:单价、金额错了会影响能不能发货吗?**
|
||||
A:不会。库存匹配只看内部料号、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。
|
||||
|
||||
**Q:助手文字建议和下方按钮不一致怎么办?**
|
||||
**Q:助手文字建议和下方按钮不一致怎么办?**
|
||||
A:以**系统按钮和任务当前状态**为准。助手正文只负责说明状态,不应重复列出一套操作清单;若正文和按钮不一致,请以按钮为准并保留截图反馈。
|
||||
|
||||
**Q:同一对话里能否处理两票货?**
|
||||
**Q:同一对话里能否处理两票货?**
|
||||
A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理;同一会话下可以包含多个批次和多票任务。操作前请看清顶部显示的当前批次 `SB-...` 和当前任务 `SN-...`,确认、驳回、重试等动作只作用于当前聚焦范围。
|
||||
|
||||
---
|
||||
@@ -579,8 +584,8 @@ A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理;
|
||||
| 项 | 说明 |
|
||||
|----|------|
|
||||
| 货代库存导出 SOP | 从哪个系统导出、路径、频率、文件名规范 |
|
||||
| 库存 Excel 样例 | 含真实列名的脱敏样表(尤其 SKU、COM ID、Qty Available) |
|
||||
| 发货通知样例 | PDF/邮件样例,含 Reservation ID 与 SKU 的典型排版 |
|
||||
| 库存 Excel 样例 | 含真实列名的脱敏样表(尤其 Supplier Sku、AWS Sku、COM ID、Qty Available) |
|
||||
| 发货通知样例 | PDF/邮件样例,含 Reservation ID 与内部料号的典型排版 |
|
||||
| 货代上传 SOP | 登录步骤、上传入口、必填字段 |
|
||||
| 正式发货 Excel 模板 | 列顺序、必填项、与货代系统的字段对应关系 |
|
||||
| Reservation ID 业务规则 | 是否恒为 10 位数字、是否与 COM ID 一一对应等 |
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
## 设计原则
|
||||
|
||||
- Dify LLM 负责从非结构化发货通知和用户对话中抽取候选字段(目的地、港口、仓库线索等),**不负责**最终 RPA URL / source_code 决策。
|
||||
- 订单行 `source_type` 仅保留为可选路由线索;库存连接器使用独立 `connector_type`,两者不得混用。
|
||||
- 订单行仅保留 `inventory_source_hint` 作为可选路由线索;库存连接器使用独立 `connector_type`,两者不得混用。
|
||||
- HXOPS 在 `parse_notice` 阶段根据 YAML 配置做标准化、规则匹配、唯一性判断;唯一命中写入任务独立字段。
|
||||
- 用户人工确认时**只确认 `source_code`**;`site_id`、`warehouse_id` 由配置自动生成,禁止前端或 LLM 直写。
|
||||
- RPA、库存准备、匹配、Excel 生成、上传等后续步骤均通过 **inventory source gate** 硬阻断,未稳定(`resolved` / `user_confirmed`)不得继续。
|
||||
|
||||
@@ -19,8 +19,8 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
|
||||
-> 现有货代 Chatflow 的 order_extraction 固定分支
|
||||
-> LLM 一次完整识别 orders[]
|
||||
-> HXOPS 逐订单校验、Candidate 落库、订单级判重
|
||||
-> 高置信且有 SKU/Qty 原文证据的订单自动建 Batch/Task
|
||||
-> 缺 Reservation ID 的 Task 停在字段补充门禁;订单行 Source Type 仅作可选路由线索
|
||||
-> 高置信且有 part_number/Qty 原文证据的订单自动建 Batch/Task
|
||||
-> 缺 Reservation ID 的 Task 停在字段补充门禁;订单行 `inventory_source_hint` 仅作可选路由线索
|
||||
-> 用户通过自然对话调用既有字段修改 Tool 补齐
|
||||
```
|
||||
|
||||
@@ -29,8 +29,8 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
|
||||
- **上传阶段不调用 LLM、不生成 Candidate、不判订单重复**:规则解析只作为 `rule_hints`,Candidate 只在 `submit_order_extraction` 后生成。
|
||||
- **一封 EML 仍是一个 Intake**;一个 Document 可以产生多个 Candidate;跨附件同一订单由 LLM 合并并以一个主 Document、多个 evidence 记录来源。
|
||||
- **判重粒度是订单 Candidate,不是整封邮件或单个附件**:附件 hash 是证据之一,最终通过身份指纹 + 内容指纹区分完全重复与可能修订。
|
||||
- **自动建单硬条件**:`classification=shipping_request`、至少一条合法 SKU + 正数 Qty、分类与 SKU/Qty 置信度达阈值、SKU/Qty 均有非空原文证据、无阻断冲突、无必须人工决策的修订。
|
||||
- **流程字段允许缺失**:Reservation ID 缺失不阻止 Task 创建,但会阻止库存、匹配、Excel 与上传;自然对话补齐后重新进入解析确认。订单行 Source Type 可选,不单独触发门禁。
|
||||
- **自动建单硬条件**:`classification=shipping_request`、至少一条合法 `part_number` + 正数 Qty、分类与 `part_number`/Qty 置信度达阈值、两者均有非空原文证据、无阻断冲突、无必须人工决策的修订。
|
||||
- **流程字段允许缺失**:Reservation ID 缺失不阻止 Task 创建,但会阻止库存、匹配、Excel 与上传;自然对话补齐后重新进入解析确认。订单行 `inventory_source_hint` 可选,不单独触发门禁。
|
||||
|
||||
## 2026-07-15 客户身份与业务编号实施基线
|
||||
|
||||
@@ -121,7 +121,7 @@ EML FileAsset -> ShippingNoticeIntake
|
||||
| --- | --- |
|
||||
| 正文与附件融合 | Chatflow 同时读取正文和全部附件文本;附件优先作为订单主证据,正文用于订单通知语义、PO/Reservation 关联和补缺;不确定字段必须输出 `null` |
|
||||
| 建单粒度 | 一个 EML 对应一个 Intake;每个 LLM 识别出的业务订单对应 Candidate;一个 Document 可对应多个 Candidate;高置信订单提交后自动创建 Batch/Task |
|
||||
| 判重粒度 | Candidate 主附件 `content_hash` 做文件级精确判重;`shipping-v1` 业务身份指纹识别同一订单;`shipping-content-v3` 内容指纹覆盖 PO、收货地、交期、Reservation、SKU、Qty、价格币种、Allocation、Source Type 等,区分 `same_business_content` 与 `possible_revision` |
|
||||
| 判重粒度 | Candidate 主附件 `content_hash` 做文件级精确判重;`shipping-v1` 业务身份指纹识别同一订单;`shipping-content-v4` 内容指纹覆盖 PO、收货地、交期、Reservation、三料号字段、Qty、价格币种、Allocation、inventory_source_hint 等,区分 `same_business_content` 与 `possible_revision` |
|
||||
| 审核 API | `PATCH /api/workspace/shipping-notice/candidates/{candidate_no}`;`POST .../duplicate-refresh`;`POST .../duplicate-resolution`;所有操作按 Intake owner 隔离,已消费 Candidate 禁止修改 |
|
||||
| 建批 API | `POST /api/workspace/shipping-batches/create-from-intakes` 可传 `candidate_nos`;Candidate 集合参与建批幂等,Task 回填 `source_candidate_id` 与独立附件 hash |
|
||||
| 消费关系 | Candidate 一对一回填 `consumed_task_id`;同 Intake 尚有低置信/冲突 Candidate 时保持 `parse_status=parsed` + `order_extraction_status=partially_completed`,全部处理后才 `consumed` |
|
||||
@@ -998,7 +998,7 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv
|
||||
|
||||
本方案不是“用户一句话,Dify 自由发挥到流程结束”,而是“每轮先读状态,再按确定性分支或人工节点收口”。推荐把每轮都视为以下固定编排:
|
||||
|
||||
1. **先做能力路由**:`parse_agent_runtime_context` 读取 `refs.capability / refs.contract_version / refs.intake_nos`;命中 `order_extraction + shipping-order-extraction-v1` 时,必须先走固定订单抽取分支并在该分支结束本轮。
|
||||
1. **先做能力路由**:`parse_agent_runtime_context` 读取 `refs.capability / refs.intake_nos`;命中 `order_extraction` 时,必须先走固定订单抽取分支并在该分支结束本轮。
|
||||
2. **识别普通回合上下文**:未命中订单抽取时,再从用户消息、`agent_runtime_context.refs` 与 `reference_context` 识别 `task_id / batch_no / intent_hint`;模糊指代必须使用解析后的 `reference_context`。
|
||||
3. **读取真相源**:凡属“继续处理 / 切换任务 / 询问当前状态 / 确认或驳回当前步骤”,优先调用 `get_task_status`;只有库存文件上传链走 `inventory_path`。
|
||||
4. **优先直连确定性动作**:`confirm / reject / reparse / retry_rpa / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory / rematch` 必须先走直连 Tool,不先进入 Agent 自由推理。
|
||||
@@ -1087,12 +1087,12 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv
|
||||
|
||||
| 阶段 | 输入 | 输出 | 真相源 / 约束 |
|
||||
| --- | --- | --- | --- |
|
||||
| 顶层能力识别 | `agent_runtime_context` | `capability`、`contract_version`、`intake_nos_json` | 只读取 `parse_agent_runtime_context` 结果,不分析用户文案 |
|
||||
| 顶层能力识别 | `agent_runtime_context` | `capability`、`intake_nos_json` | 只读取 `parse_agent_runtime_context` 结果,不分析用户文案 |
|
||||
| 抽取上下文读取 | 原样 `agent_runtime_context` | Tool `text` | HXOPS 校验会话、用户、Intake 归属并生成不可变快照 |
|
||||
| 抽取上下文标准化 | Tool `text` | `context_ok`、`input_snapshot_hash`、`context_json`、`error_message` | Code 只解析 JSON 和检查必要字段,不修改业务内容 |
|
||||
| LLM 完整理解 | `context_json` | LLM `text` | LLM 只识别 `orders[]`,不判重、不建单、不推进任务 |
|
||||
| LLM JSON 标准化 | LLM `text` | `parse_ok`、`schema_version`、`orders`、`orders_json`、`error_message` | Code 只做契约形状校验;业务门禁仍由 HXOPS 执行 |
|
||||
| 抽取结果提交 | 运行态上下文、快照、契约版本、`orders` | Tool `text` | HXOPS 做证据校验、Candidate 判重、自动建单及幂等回放 |
|
||||
| LLM JSON 标准化 | LLM `text` | `parse_ok`、`orders`、`orders_json`、`error_message` | Code 只做 JSON 形状校验;业务门禁仍由 HXOPS 执行 |
|
||||
| 抽取结果提交 | 运行态上下文、快照、`orders` | Tool `text` | HXOPS 做证据校验、Candidate 判重、自动建单及幂等回放 |
|
||||
| 提交结果标准化 | Tool `text` | `submit_ok`、`message`、`batch_no`、计数与结果 JSON | 回复只消费 HXOPS Tool 返回,不使用 LLM 猜测建单结果 |
|
||||
|
||||
##### `agent_runtime_context` 订单抽取输入示例
|
||||
@@ -1112,7 +1112,6 @@ HXOPS 点击发送时应在现有 Chatflow 的 `inputs.agent_runtime_context`
|
||||
},
|
||||
"refs": {
|
||||
"capability": "order_extraction",
|
||||
"contract_version": "shipping-order-extraction-v1",
|
||||
"intake_nos": ["SNI-20260715-ABCDEFGH"],
|
||||
"run_purpose": "chat_turn"
|
||||
}
|
||||
@@ -1435,8 +1434,8 @@ flowchart TD
|
||||
| ------- | --------------- | ---------------- | ---------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------- |
|
||||
| 开始 | `开始` | Start | 接收消息、附件、会话号与平台上下文 | `sys.query`、`sys.files`、`sys.conversation_id`、`agent_runtime_context` | 无 |
|
||||
| Tool 解析运行态上下文 | `Tool 解析运行态上下文` | Tool | 调 `parse_agent_runtime_context` 读取 shipping 画布需要的字段 | `agent_runtime_context` | Tool `text` |
|
||||
| 运行态上下文标准化 | `运行态上下文标准化` | Code | 将 parse 结果转为后续节点可直接使用的 shipping 领域变量 | `Tool 解析运行态上下文.text` | `capability`、`contract_version`、`intake_nos_json`、`task_no`、`batch_no`、`trigger_source`、`focus_task_no`、`last_action`、`candidate_count` |
|
||||
| 顶层能力路由 | `顶层能力路由` | If-Else | 最高优先级识别点击发送订单抽取回合,并与普通聊天链隔离 | `capability`、`contract_version` | `order_extraction_path / normal_path` |
|
||||
| 运行态上下文标准化 | `运行态上下文标准化` | Code | 将 parse 结果转为后续节点可直接使用的 shipping 领域变量 | `Tool 解析运行态上下文.text` | `capability`、`intake_nos_json`、`task_no`、`batch_no`、`trigger_source`、`focus_task_no`、`last_action`、`candidate_count` |
|
||||
| 顶层能力路由 | `顶层能力路由` | If-Else | 最高优先级识别点击发送订单抽取回合,并与普通聊天链隔离 | `capability` | `order_extraction_path / normal_path` |
|
||||
| 用户意图预处理 | `用户意图预处理` | Code | 结合用户消息与已标准化上下文识别任务锚点和短动作意图 | `sys.query`、`sys.conversation_id`、`运行态上下文标准化.*` | `task_no`、`batch_no`、`detected_task_no`、`detected_batch_no`、`intent_hint`、`trigger_source` |
|
||||
| 附件意图分类 | `附件意图分类` | Code | 区分通知附件、库存附件、任务续办 | `用户意图预处理.normalized_query`、`sys.files` | `route_key`、`reason` |
|
||||
| 分支调度 | `分支调度` | Code | 决定 direct / inventory / agent 三条路径 | `附件意图分类.route_key`、任务号 | `branch`、`final_reply`、`resolved_task_no` |
|
||||
@@ -1447,17 +1446,17 @@ flowchart TD
|
||||
| 节点名 | 节点标识 | 类型 | 主要职责 | 核心输入 | 核心输出 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| Tool 读取订单抽取上下文 | `Tool 读取订单抽取上下文` | Tool | 按运行态上下文读取邮件正文、附件文本、规则提示与不可变快照 | `agent_runtime_context` | Tool `text` |
|
||||
| 订单抽取上下文标准化 | `订单抽取上下文标准化` | Code | 解析 Tool JSON 并校验 `status / snapshot / documents / contract` | `Tool 读取订单抽取上下文.text` | `context_ok`、`input_snapshot_hash`、`context_json`、`documents_json`、`error_message` |
|
||||
| 订单抽取上下文标准化 | `订单抽取上下文标准化` | Code | 解析 Tool JSON 并校验 `status / snapshot / documents` | `Tool 读取订单抽取上下文.text` | `context_ok`、`input_snapshot_hash`、`context_json`、`documents_json`、`error_message` |
|
||||
| 订单抽取上下文是否有效 | `订单抽取上下文是否有效` | If-Else | 阻止无效上下文进入 LLM | `订单抽取上下文标准化.context_ok` | true / false |
|
||||
| 订单完整抽取 LLM | `订单完整抽取 LLM` | LLM | 从邮件正文与附件文本识别 0..N 个实际业务订单 | `订单抽取上下文标准化.context_json` | `text` |
|
||||
| 订单抽取 JSON 标准化 | `订单抽取 JSON 标准化` | Code | 校验 LLM JSON 契约并输出 Tool 可接收的 `orders` | `订单完整抽取 LLM.text` | `parse_ok`、`schema_version`、`orders`、`orders_json`、`order_count`、`error_message` |
|
||||
| 抽取 JSON 是否有效 | `抽取 JSON 是否有效` | If-Else | 仅允许合法契约结果进入提交 Tool | `订单抽取 JSON 标准化.parse_ok` | true / false |
|
||||
| Tool 提交订单抽取 | `Tool 提交订单抽取` | Tool | 提交同一快照的 `orders[]`,由 HXOPS 校验、判重并自动建单 | 运行态上下文、快照、契约版本、`orders` | Tool `text` |
|
||||
| 订单抽取 JSON 标准化 | `订单抽取 JSON 标准化` | Code | 校验 LLM JSON 形状并输出 Tool 可接收的 `orders` | `订单完整抽取 LLM.text` | `parse_ok`、`orders`、`orders_json`、`order_count`、`error_message` |
|
||||
| 抽取 JSON 是否有效 | `抽取 JSON 是否有效` | If-Else | 仅允许合法结构化结果进入提交 Tool | `订单抽取 JSON 标准化.parse_ok` | true / false |
|
||||
| Tool 提交订单抽取 | `Tool 提交订单抽取` | Tool | 提交同一快照的 `orders[]`,由 HXOPS 校验、判重并自动建单 | 运行态上下文、快照、`orders` | Tool `text` |
|
||||
| 订单抽取提交结果标准化 | `订单抽取提交结果标准化` | Code | 解析唯一建单事实源,生成稳定回复字段 | `Tool 提交订单抽取.text` | `submit_ok`、`message`、`batch_no`、`created_count`、`opened_existing_count`、`pending_count`、`non_shipping_count`、`idempotent_replay`、结果 JSON |
|
||||
| 提交结果是否有效 | `提交结果是否有效` | If-Else | 区分 HXOPS 成功结果与非法/异常 Tool 结果 | `订单抽取提交结果标准化.submit_ok` | true / false |
|
||||
| 订单抽取结果回复 | `订单抽取结果回复` | Answer | 模板化展示 HXOPS 的处理结果 | `message`、`batch_line` | 最终回复 |
|
||||
| 订单抽取上下文失败回复 | `订单抽取上下文失败回复` | Answer | 上下文读取或契约失败时结束本轮 | `订单抽取上下文标准化.error_message` | 最终回复 |
|
||||
| 订单抽取 JSON 失败回复 | `订单抽取 JSON 失败回复` | Answer | LLM 输出不符合 JSON 契约时结束本轮 | `订单抽取 JSON 标准化.error_message` | 最终回复 |
|
||||
| 订单抽取上下文失败回复 | `订单抽取上下文失败回复` | Answer | 上下文读取或结构校验失败时结束本轮 | `订单抽取上下文标准化.error_message` | 最终回复 |
|
||||
| 订单抽取 JSON 失败回复 | `订单抽取 JSON 失败回复` | Answer | LLM 输出不符合 JSON 结构时结束本轮 | `订单抽取 JSON 标准化.error_message` | 最终回复 |
|
||||
| 订单抽取提交失败回复 | `订单抽取提交失败回复` | Answer | 提交 Tool 返回异常或非法结果时结束本轮 | `订单抽取提交结果标准化.error_message` | 最终回复 |
|
||||
|
||||
##### B. `inventory_path` 分支节点
|
||||
@@ -1667,7 +1666,6 @@ Tool 绑定:
|
||||
"platform.session_id",
|
||||
"platform.request_id",
|
||||
"refs.capability",
|
||||
"refs.contract_version",
|
||||
"refs.intake_nos",
|
||||
"refs.task_no",
|
||||
"refs.batch_no",
|
||||
@@ -1711,7 +1709,6 @@ Tool 绑定:
|
||||
| 字段 | 说明 |
|
||||
| --- | --- |
|
||||
| `capability` | 平台显式请求的能力;本期订单抽取固定为 `order_extraction` |
|
||||
| `contract_version` | 能力契约版本;本期固定为 `shipping-order-extraction-v1` |
|
||||
| `intake_nos_json` | 本轮 Intake 编号数组的 JSON 字符串;仅用于观察和排查,不作为 Tool 手写参数 |
|
||||
| `task_no` | shipping 当前任务号,来自 `refs.task_no` |
|
||||
| `batch_no` | shipping 当前批次号,来自 `refs.batch_no` |
|
||||
@@ -1765,7 +1762,6 @@ def main(text: str = ""):
|
||||
).upper()
|
||||
return {
|
||||
"capability": _value(parsed, "refs.capability"),
|
||||
"contract_version": _value(parsed, "refs.contract_version"),
|
||||
"intake_nos_json": json.dumps(intake_nos, ensure_ascii=False),
|
||||
"task_no": _value(parsed, "refs.task_no").upper(),
|
||||
"batch_no": _value(parsed, "refs.batch_no").upper(),
|
||||
@@ -1785,7 +1781,7 @@ def main(text: str = ""):
|
||||
说明:
|
||||
|
||||
- 本节点只把 parse Tool 的结果转成 Dify 后续节点方便引用的 shipping 领域变量。
|
||||
- `capability / contract_version` 只用于 `顶层能力路由`;不得根据 `sys.query` 覆盖。
|
||||
- `capability` 只用于 `顶层能力路由`;不得根据 `sys.query` 覆盖。
|
||||
- `intake_nos_json` 只用于调试或显示;订单抽取 Tool 仍必须接收完整 `agent_runtime_context` 并在 HXOPS 内部重新校验归属。
|
||||
- `task_no / batch_no` 允许为空;空值表示当前会话尚未有明确任务或批次锚点。
|
||||
- `candidate_count > 1` 时,Agent 必须追问用户选择具体任务,不得自行猜测。
|
||||
@@ -1801,20 +1797,14 @@ def main(text: str = ""):
|
||||
| Dify 变量 | 类型 | 必填 | 说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| `运行态上下文标准化.capability` | String | 是 | 平台显式能力标识;普通聊天为空 |
|
||||
| `运行态上下文标准化.contract_version` | String | 是 | 订单抽取契约版本;普通聊天为空 |
|
||||
|
||||
条件配置(使用 `AND` 同时满足):
|
||||
条件配置:
|
||||
|
||||
```text
|
||||
条件 1:运行态上下文标准化.capability
|
||||
运算符:is
|
||||
右值:order_extraction
|
||||
|
||||
AND
|
||||
|
||||
条件 2:运行态上下文标准化.contract_version
|
||||
运算符:is
|
||||
右值:shipping-order-extraction-v1
|
||||
```
|
||||
|
||||
分支去向:
|
||||
@@ -1828,7 +1818,6 @@ AND
|
||||
|
||||
- 本节点是主编排最高优先级路由;必须位于所有用户意图、附件意图、任务状态和 Agent 节点之前。
|
||||
- 不得添加 `run_purpose`、关键词、文件扩展名或 `sys.files` 作为订单抽取判断条件。
|
||||
- 契约版本不匹配时不得降级进入旧订单抽取逻辑;当前按 `normal_path` 处理,并由 HXOPS 联调监控发现协议漂移。
|
||||
|
||||
##### 节点:Tool 读取订单抽取上下文
|
||||
|
||||
@@ -1867,7 +1856,7 @@ Tool 绑定:
|
||||
| `intake_nos` | Array[String] | HXOPS 校验通过的 Intake 编号 |
|
||||
| `documents` | Array[Object] | 邮件正文与附件文本集合;元素见下表 |
|
||||
| `rule_hints` | Object | 上传预处理的规则提示,只可作为辅助信号 |
|
||||
| `contract` | Object | 固定输出契约与字段门禁说明 |
|
||||
| `contract` | Object | 订单字段与门禁说明 |
|
||||
|
||||
`documents[]` 字段:
|
||||
|
||||
@@ -1906,14 +1895,13 @@ Tool 绑定:
|
||||
|
||||
| 字段 | Dify 类型 | 说明 | 下游使用方 |
|
||||
| --- | --- | --- | --- |
|
||||
| `context_ok` | Boolean | Tool JSON 与必要契约是否有效 | `订单抽取上下文是否有效` |
|
||||
| `context_ok` | Boolean | Tool JSON 与必要字段是否有效 | `订单抽取上下文是否有效` |
|
||||
| `input_snapshot_hash` | String | 不可变输入快照 | `Tool 提交订单抽取` |
|
||||
| `context_json` | String | 保留完整 Tool JSON 的字符串 | `订单完整抽取 LLM` |
|
||||
| `documents_json` | String | `documents[]` JSON 字符串,便于调试 | 联调观察 |
|
||||
| `document_count` | Number | Document 数量 | 联调观察 |
|
||||
| `intake_nos_json` | String | Intake 编号数组 JSON 字符串 | 联调观察 |
|
||||
| `rule_hints_json` | String | 规则提示 JSON 字符串 | 联调观察 |
|
||||
| `contract_json` | String | Tool 契约 JSON 字符串 | 联调观察 |
|
||||
| `error_message` | String | 失败原因;成功为空 | 失败回复 |
|
||||
|
||||
代码:
|
||||
@@ -1934,17 +1922,13 @@ def main(text: str = ""):
|
||||
documents = data.get("documents") if isinstance(data.get("documents"), list) else []
|
||||
intake_nos = data.get("intake_nos") if isinstance(data.get("intake_nos"), list) else []
|
||||
rule_hints = data.get("rule_hints") if isinstance(data.get("rule_hints"), dict) else {}
|
||||
contract = data.get("contract") if isinstance(data.get("contract"), dict) else {}
|
||||
snapshot = str(data.get("input_snapshot_hash") or "").strip()
|
||||
schema_version = str(contract.get("schema_version") or "").strip()
|
||||
|
||||
error_message = ""
|
||||
if str(data.get("status") or "").strip() != "ok":
|
||||
error_message = str(data.get("message") or "订单抽取上下文读取失败,请重新发送。")
|
||||
elif not snapshot:
|
||||
error_message = "订单抽取上下文缺少 input_snapshot_hash,请重新发送。"
|
||||
elif schema_version != "shipping-order-extraction-v1":
|
||||
error_message = "订单抽取上下文契约版本不匹配,请联系管理员检查 Dify 配置。"
|
||||
elif not documents:
|
||||
error_message = "当前邮件没有可用于识别订单的正文或附件文本;本次未创建任务。"
|
||||
|
||||
@@ -1956,7 +1940,6 @@ def main(text: str = ""):
|
||||
"document_count": len(documents),
|
||||
"intake_nos_json": json.dumps(intake_nos, ensure_ascii=False),
|
||||
"rule_hints_json": json.dumps(rule_hints, ensure_ascii=False),
|
||||
"contract_json": json.dumps(contract, ensure_ascii=False),
|
||||
"error_message": error_message,
|
||||
}
|
||||
```
|
||||
@@ -2024,16 +2007,16 @@ System Prompt:
|
||||
```text
|
||||
你是货代发货订单结构化抽取器。你只负责理解 HXOPS 提供的邮件正文与附件文本,不负责建单、判重或推进业务状态。
|
||||
|
||||
[PROMPT_UPDATE] 2026-07-15:合并原订单需求解析 Prompt 的字段规则,并增加跨 Document 订单关联、Reservation ID 主动搜索及证据要求,避免因流程字段允许缺失而提前返回 null。
|
||||
[PROMPT_UPDATE] 2026-07-16:订单行切换为通用三料号领域模型,并增加后端/Dify Observation 交叉裁决、原子料号与跨 Document 证据要求。
|
||||
|
||||
一、输出与职责边界
|
||||
1. 只输出一个 JSON 对象,格式为 {"schema_version":"shipping-order-extraction-v1","orders":[]};禁止 Markdown、解释、代码围栏。
|
||||
1. 只输出一个 JSON 对象,格式为 {"orders":[]};禁止 Markdown、解释、代码围栏。
|
||||
2. 你只负责识别业务订单并输出候选结构;不得声称已建单、已判重、已推进任务,也不得根据 rule_hints 直接下最终结论。
|
||||
3. 非发货需求返回 orders=[]。不要为了产生任务而猜测订单。
|
||||
4. orders 最多 50 项;无法确定订单归属时使用 classification=uncertain,不得任意合并或拆分。
|
||||
5. 每个订单必须包含 source_intake_no、primary_document_id、classification、classification_confidence、field_confidence、lines、evidence、conflicts。
|
||||
6. classification 仅允许 shipping_request、non_shipping_request、uncertain。
|
||||
7. classification_confidence、field_confidence.sku、field_confidence.qty 必须是 0..1;field_confidence 取订单各行对应字段的最低可信度。
|
||||
7. classification_confidence、field_confidence.part_number、field_confidence.qty 必须是 0..1;field_confidence 取订单各行对应字段的最低可信度,且仅是 LLM 自报参考,不代表后端最终裁决分数。
|
||||
8. candidate_key_hint 只能使用稳定业务标识,如 PO、客户订单号或明确 Reservation ID;没有稳定标识则省略,禁止使用随机值或数组序号。
|
||||
|
||||
二、订单拆分与跨 Document 归并
|
||||
@@ -2041,10 +2024,10 @@ System Prompt:
|
||||
2. 同一订单的信息可能分散在邮件正文和多个附件中。应主动进行跨 Document 关联,而不是只使用 classification_hint=order_notice 的附件。
|
||||
3. 跨 Document 关联信号按可靠性从高到低使用:
|
||||
a. PO、客户订单号、Reservation ID 等稳定业务标识一致;
|
||||
b. 完整 SKU 一致;
|
||||
c. 一个 Document 的 MPN 是另一 Document 复合 SKU 的完整组成部分,且 Qty 一致;
|
||||
d. MPN/SKU、Qty、客户、目的地或日期等多个字段组合一致。
|
||||
4. 当邮件正文中的 MPN 是附件复合 SKU 的完整组成部分,且 Qty 一致时,应把邮件同一数据行中的 Reservation ID、Source Type 等字段合并到附件订单行;Source Type 仅作为可选库存路由线索。
|
||||
b. 完整 `part_number` 一致;
|
||||
c. 一个 Document 的 MPN 是另一 Document 复合料号文本的完整 token,且 Qty 一致;
|
||||
d. 料号 token、Qty、客户、目的地或日期等多个字段组合一致。
|
||||
4. 当邮件正文中的 MPN 是附件复合料号文本的完整 token,且 Qty 一致时,应把邮件同一数据行中的 Reservation ID、`inventory_source_hint` 等字段关联到同一订单行;不得将复合文本直接写入料号字段。
|
||||
5. 合并后选择最能代表订单主体的 Document 作为 primary_document_id;每个字段的 evidence.document_id 必须指向该字段真实来源,允许同一订单的 evidence 来自多个 Document。
|
||||
6. 只有单一弱信号、字段冲突或无法证明属于同一订单时不得强行合并;应保留 null,并在 conflicts 中记录原因。
|
||||
|
||||
@@ -2065,32 +2048,32 @@ System Prompt:
|
||||
7. reservation_id 非空时,evidence 必须包含对应原文证据,例如 {"field":"lines[0].reservation_id","quote":"3000092917","document_id":17}。
|
||||
8. 原文发现可能的 Reservation ID 但无法证明属于当前订单行时,reservation_id 返回 null,并在 conflicts 中记录 {"field":"lines[0].reservation_id","severity":"warning","reason":"reservation_id_found_but_order_link_uncertain","document_id":17}。
|
||||
|
||||
五、SKU、MPN 与 Qty 规则
|
||||
1. sku 优先取 Material、Part Number、Parts No.、Allocated APN、APN、AWS Sku、Customer PN、料号等业务料号字段。
|
||||
2. MPN、Vendor Part Number 是制造商料号;若原文同时存在 SKU/APN 与 MPN,应保留业务 SKU,并可额外输出 vendor_part_number。若附件明确使用复合 SKU,则可保留完整复合值,不得无依据拆改。
|
||||
3. qty 必须来自 Qty、Q'TY、Quantity、Allocated QTY、Allocated qty、数量等明确数量字段,并且必须是正数;无法确认时不得输出为有效 shipping_request 订单行。
|
||||
4. shipping_request 的每条有效订单行至少包含 sku 与正数 qty;reservation_id 只有在充分搜索且无法可靠识别或关联后才允许为 null;source_type 是可选库存路由线索,可为 null。
|
||||
5. SKU 和 Qty 必须分别提供非空原文 evidence;reservation_id、source_type 非空时也必须分别提供 evidence。
|
||||
五、料号与 Qty 规则
|
||||
1. `part_number` 是企业内部管理料号,优先来自 MPN、Vendor Part Number、Supplier Part Number、内部料号等明确语义字段。
|
||||
2. `customer_part_number` 是客户料号,优先来自 Customer PN、Customer Part Number、Allocated HHPN 等明确语义字段;`aws_part_number` 是货代/AWS 料号,只能来自 AWS Sku、AWS SKU 等明确字段。
|
||||
3. 三种料号都必须是原子值并禁止包含 `/`。遇到复合文本时先按 `/` 拆为非空 token,再结合表头、前缀、相邻字段和其他 Document 证据判断角色;角色不明时留空并记录 conflict,禁止把复合文本直接输出为任一料号。
|
||||
4. qty 必须来自 Qty、Q'TY、Quantity、Allocated QTY、Allocated qty、数量等明确数量字段,并且必须是正数;无法确认时不得输出为有效 shipping_request 订单行。
|
||||
5. shipping_request 的每条有效订单行至少包含 `part_number` 与正数 qty;reservation_id 只有在充分搜索且无法可靠识别或关联后才允许为 null;`customer_part_number`、`aws_part_number`、`inventory_source_hint` 均可为 null。
|
||||
6. `part_number` 和 Qty 必须分别提供非空原文 evidence;其他非空料号、reservation_id、inventory_source_hint 也必须分别提供 evidence。
|
||||
|
||||
六、冲突、证据与禁止臆造
|
||||
1. evidence 格式为 {"field":"lines[0].sku","quote":"原文片段","document_id":123};quote 必须逐字来自原文,不得改写或生成原文中不存在的文本。
|
||||
1. evidence 格式为 {"field":"lines[0].part_number","quote":"原文片段","document_id":123};quote 必须逐字来自原文,不得改写或生成原文中不存在的文本。
|
||||
2. source_intake_no、primary_document_id、evidence.document_id 和 conflict.document_id 必须来自输入上下文,不得创造不存在的编号。
|
||||
3. Reservation/SKU/Qty 来源冲突、订单归属冲突、正文与附件版本冲突或可能修订时写入 conflicts[];需要阻断自动建单的冲突 severity=blocking,仅表示不确定但不要求阻断时 severity=warning。
|
||||
4. 正文和附件冲突时不得静默覆盖。保留证据更强的值,同时在 conflicts 中记录另一来源、冲突字段和 document_id。
|
||||
5. 不确定字段返回 null 或省略,禁止编造 Reservation ID、PO、Source Type、SKU、Qty。
|
||||
3. Reservation/料号/Qty 来源冲突、订单归属冲突、正文与附件版本冲突或可能修订时写入 conflicts[];需要阻断自动建单的冲突 severity=blocking,仅表示不确定但不要求阻断时 severity=warning。
|
||||
4. 正文和附件冲突时不得静默覆盖。各自作为不可变 Observation 提交,由 HXOPS 后端按证据统一评分;双方高可信但不同或分差不足时必须进入字段冲突。
|
||||
5. 不确定字段返回 null 或省略,禁止编造 Reservation ID、PO、inventory_source_hint、料号或 Qty。
|
||||
```
|
||||
|
||||
输出:
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `text` | String | 仅包含 `shipping-order-extraction-v1` JSON 对象 |
|
||||
| `text` | String | 仅包含订单抽取 JSON 对象 |
|
||||
|
||||
期望输出示例:
|
||||
|
||||
```json
|
||||
{
|
||||
"schema_version": "shipping-order-extraction-v1",
|
||||
"orders": [
|
||||
{
|
||||
"source_intake_no": "SNI-20260715-4B36C3B7",
|
||||
@@ -2098,22 +2081,24 @@ System Prompt:
|
||||
"candidate_key_hint": "3400104730",
|
||||
"classification": "shipping_request",
|
||||
"classification_confidence": 0.98,
|
||||
"field_confidence": {"sku": 0.97, "qty": 0.96},
|
||||
"field_confidence": {"part_number": 0.97, "qty": 0.96},
|
||||
"po_number": "3400104730",
|
||||
"lines": [
|
||||
{
|
||||
"sku": "TEMP-S000218929/D4-A08AR12000002",
|
||||
"vendor_part_number": "D4-A08AR12000002",
|
||||
"part_number": "D4-A08AR12000002",
|
||||
"customer_part_number": "TEMP-S000218929",
|
||||
"aws_part_number": null,
|
||||
"qty": 10,
|
||||
"reservation_id": "3000092917",
|
||||
"source_type": null
|
||||
"inventory_source_hint": null
|
||||
}
|
||||
],
|
||||
"evidence": [
|
||||
{"field": "lines[0].sku", "quote": "TEMP-S000218929/D4-A08AR12000002/ Frame, AR1.2, 48.5U, Welltrust", "document_id": 18},
|
||||
{"field": "lines[0].part_number", "quote": "TEMP-S000218929/D4-A08AR12000002/ Frame, AR1.2, 48.5U, Welltrust", "document_id": 18},
|
||||
{"field": "lines[0].customer_part_number", "quote": "TEMP-S000218929/D4-A08AR12000002/ Frame, AR1.2, 48.5U, Welltrust", "document_id": 18},
|
||||
{"field": "lines[0].qty", "quote": "EA\n10\n2026/6/12", "document_id": 18},
|
||||
{"field": "lines[0].reservation_id", "quote": "3000092917", "document_id": 17},
|
||||
{"field": "lines[0].vendor_part_number", "quote": "D4-A08AR12000002", "document_id": 17}
|
||||
{"field": "lines[0].part_number", "quote": "D4-A08AR12000002", "document_id": 17}
|
||||
],
|
||||
"conflicts": []
|
||||
}
|
||||
@@ -2136,7 +2121,6 @@ System Prompt:
|
||||
| 字段 | Dify 类型 | 说明 | 下游使用方 |
|
||||
| --- | --- | --- | --- |
|
||||
| `parse_ok` | Boolean | JSON 契约形状是否有效 | `抽取 JSON 是否有效` |
|
||||
| `schema_version` | String | 固定契约版本 | `Tool 提交订单抽取` |
|
||||
| `orders` | Array[Object] | 结构化订单数组 | `Tool 提交订单抽取.orders` |
|
||||
| `orders_json` | String | 同一数组的 JSON 字符串 | 联调观察 |
|
||||
| `order_count` | Number | LLM 识别订单数;允许为 0 | 联调观察 |
|
||||
@@ -2152,7 +2136,6 @@ import re
|
||||
def _fail(message: str):
|
||||
return {
|
||||
"parse_ok": False,
|
||||
"schema_version": "",
|
||||
"orders": [],
|
||||
"orders_json": "[]",
|
||||
"order_count": 0,
|
||||
@@ -2170,10 +2153,7 @@ def main(llm_text: str = ""):
|
||||
if not isinstance(payload, dict):
|
||||
return _fail("订单抽取结果必须是 JSON 对象;本次未创建任务。")
|
||||
|
||||
schema_version = str(payload.get("schema_version") or "").strip()
|
||||
orders = payload.get("orders")
|
||||
if schema_version != "shipping-order-extraction-v1":
|
||||
return _fail("订单抽取结果契约版本不匹配;本次未创建任务。")
|
||||
if not isinstance(orders, list):
|
||||
return _fail("订单抽取结果中的 orders 必须是数组;本次未创建任务。")
|
||||
if len(orders) > 50:
|
||||
@@ -2204,7 +2184,6 @@ def main(llm_text: str = ""):
|
||||
|
||||
return {
|
||||
"parse_ok": True,
|
||||
"schema_version": schema_version,
|
||||
"orders": orders,
|
||||
"orders_json": json.dumps(orders, ensure_ascii=False),
|
||||
"order_count": len(orders),
|
||||
@@ -2264,7 +2243,6 @@ Tool 绑定:
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `agent_runtime_context` | `{{agent_runtime_context}}` | String | 是 | 与读取上下文时完全相同的 Start 输入,原样透传 |
|
||||
| `input_snapshot_hash` | `{{#订单抽取上下文标准化.input_snapshot_hash#}}` | String | 是 | 读取 Tool 返回的不可变快照 |
|
||||
| `schema_version` | `{{#订单抽取 JSON 标准化.schema_version#}}` | String | 是 | 固定为 `shipping-order-extraction-v1` |
|
||||
| `orders` | `{{#订单抽取 JSON 标准化.orders#}}` | Array[Object] | 是 | 直接选择 Code 节点声明的数组输出 |
|
||||
|
||||
输出:
|
||||
@@ -2297,7 +2275,7 @@ Tool 绑定:
|
||||
|
||||
- 本 Tool 返回是唯一建单事实源;Dify 不根据 LLM 置信度自行宣称“已建单”。
|
||||
- `pending_count=0` 只表示本次订单抽取无待处理订单,不表示库存、匹配、Excel 或上传已经完成。
|
||||
- 缺 Reservation ID 的高置信订单仍可能创建 Task,但 Task 会停在后端字段补充门禁;Source Type 缺失不单独阻断。
|
||||
- 缺 Reservation ID 的高置信订单仍可能创建 Task,但 Task 会停在后端字段补充门禁;`inventory_source_hint` 缺失不单独阻断。
|
||||
- 快照变化时 HXOPS 会拒绝旧结果;本分支失败后应提示用户重新发送,不得改用旧 LLM 输出重试提交。
|
||||
|
||||
##### 节点:订单抽取提交结果标准化
|
||||
@@ -2841,15 +2819,16 @@ System Prompt:
|
||||
你是库存 Excel 列映射助手。你的任务是根据表头和样例行,只输出合法 JSON,不要输出任何解释文字。
|
||||
|
||||
目标字段只允许包含:
|
||||
- part_number
|
||||
- reservation_id
|
||||
- sku
|
||||
- available_qty
|
||||
|
||||
规则:
|
||||
1. 返回 JSON object
|
||||
2. value 必须来自提供的真实表头,禁止臆造
|
||||
3. 如果无法判断 reservation_id,则返回空字符串
|
||||
4. 不要输出 markdown,不要输出代码块
|
||||
3. `part_number` 必须映射库存 Supplier Sku/内部料号列,禁止映射 AWS Sku
|
||||
4. `reservation_id` 与 `available_qty` 均为必填;任何必填列无法判断时返回空字符串,由下游进入人工修正
|
||||
5. 不要输出 markdown,不要输出代码块
|
||||
```
|
||||
|
||||
User Prompt:
|
||||
@@ -2867,7 +2846,7 @@ User Prompt:
|
||||
期望输出:
|
||||
|
||||
```json
|
||||
{"reservation_id":"Reservation Order","sku":"AWS Sku","available_qty":"Qty Available"}
|
||||
{"part_number":"Supplier Sku","reservation_id":"Reservation Order","available_qty":"Qty Available"}
|
||||
```
|
||||
|
||||
说明:
|
||||
@@ -2908,13 +2887,13 @@ def main(text: str = ""):
|
||||
"mapping_ok": False,
|
||||
"error_message": "库存列映射生成失败:LLM 未返回合法 JSON。请检查表头是否清晰,或人工更正列名后重试。",
|
||||
}
|
||||
allowed_keys = {"reservation_id", "sku", "available_qty"}
|
||||
allowed_keys = {"part_number", "reservation_id", "available_qty"}
|
||||
normalized = {k: str(v or "").strip() for k, v in mapping.items() if k in allowed_keys}
|
||||
if not normalized.get("reservation_id") or not normalized.get("sku"):
|
||||
if not all(normalized.get(key) for key in ("part_number", "reservation_id", "available_qty")):
|
||||
return {
|
||||
"map_json": json.dumps(normalized, ensure_ascii=False),
|
||||
"mapping_ok": False,
|
||||
"error_message": "库存列映射不完整:至少需要识别“预订单号”和“料号”两列。请人工确认后重试。",
|
||||
"error_message": "库存列映射不完整:必须识别内部料号、Reservation ID 和可用数量三列。请人工确认后重试。",
|
||||
}
|
||||
return {
|
||||
"map_json": json.dumps(normalized, ensure_ascii=False),
|
||||
@@ -3507,16 +3486,16 @@ System Prompt:
|
||||
4. 只允许输出一个可被下游 Code 节点直接解析的 JSON 对象。
|
||||
5. 若字段无法确定,可输出空字符串、空数组或 null,但仍必须返回合法 JSON。
|
||||
|
||||
[PROMPT_UPDATE] 2026-07-15:订单来源存在多种邮件/PDF 模板,禁止依赖固定列顺序;LLM 仅输出候选,HXOPS 后端负责最终裁决。
|
||||
[PROMPT_UPDATE] 2026-07-16:订单来源存在多种邮件/PDF 模板;LLM 仅输出新料号模型的 Observation 候选,HXOPS 后端负责最终字段级裁决。
|
||||
|
||||
关键字段规则:
|
||||
1. 按每份原文实际表头逐行抽取 reservation_id、sku、qty;不得假设所有客户共用同一模板。
|
||||
1. 按每份原文实际表头逐行抽取 reservation_id、part_number、customer_part_number、aws_part_number、qty;不得假设所有客户共用同一模板。
|
||||
2. reservation_id 的允许来源包括:Reservation ID、Reservation Id、COM ID、Reservation Order、Reservation No、Resv ID、PR Number、PR_Number、PR No、PR#、External reservation ID。
|
||||
3. 以下字段禁止映射为 reservation_id:Allocation ID、Parent allocation ID、Commodity group ID、Supplier code。
|
||||
4. Reservation ID 可以是 8~12 位数字,也可以是 AWS-311、ORD-3002、R-1 等字母型业务编号;32 位十六进制串和 UUID 通常是内部标识,不得作为 reservation_id。
|
||||
5. PR Number 出现 xxx@1000140351 时,取 @ 后的业务编号。
|
||||
6. 必须按 HTML/TSV 的列边界对齐值;空单元格仍占一列。无法证明列关系时 reservation_id 输出空字符串,禁止根据邻近数字猜测。
|
||||
7. sku 优先取 Material、Part Number、Allocated APN、AWS Sku、Customer PN、料号;MPN/Vendor Part Number 单独写入 vendor_part_number。复合 SKU 可保留原文。
|
||||
7. `part_number` 取 MPN/Vendor Part Number/Supplier Part Number;`customer_part_number` 取 Customer PN;`aws_part_number` 取 AWS Sku。三者均禁止 `/`,复合文本必须拆分并按证据归类,角色不明时留空并返回冲突。
|
||||
8. qty 必须为正数;无法确认时不要输出该订单行。
|
||||
9. 若正文和附件字段冲突,保留附件订单行候选,不得静默用正文覆盖;最终由后端标记冲突并进入人工复核。
|
||||
|
||||
@@ -3532,11 +3511,13 @@ System Prompt:
|
||||
"lines": [
|
||||
{
|
||||
"reservation_id": "",
|
||||
"sku": "",
|
||||
"part_number": "",
|
||||
"customer_part_number": "",
|
||||
"aws_part_number": "",
|
||||
"qty": 0,
|
||||
"uom": "",
|
||||
"required_date": "",
|
||||
"vendor_part_number": "",
|
||||
"inventory_source_hint": "",
|
||||
"evidence": {
|
||||
"reservation_id": {
|
||||
"source_column": "",
|
||||
@@ -3552,7 +3533,7 @@ System Prompt:
|
||||
1. 只输出合法 JSON object
|
||||
2. lines 必须是数组
|
||||
3. 若识别不到字段,返回空字符串或 0,不要臆造
|
||||
4. reservation_id、sku、qty 必须按原文行与列关系逐行抽取;无法可靠对应时留空,不得猜测
|
||||
4. reservation_id、part_number、qty 必须按原文行与列关系逐行抽取;无法可靠对应时留空,不得猜测
|
||||
5. 不要输出 markdown,不要输出代码块
|
||||
```
|
||||
|
||||
@@ -4059,9 +4040,9 @@ Agent 状态输入标准化 -> 货代续办 Agent
|
||||
|
||||
- [ ] Start 节点只配置 `agent_runtime_context`,未配置 `hxops_context`
|
||||
- [ ] `Tool 解析运行态上下文` 已绑定 `parse_agent_runtime_context`
|
||||
- [ ] `Tool 解析运行态上下文.paths` 已包含 `refs.capability / refs.contract_version / refs.intake_nos`
|
||||
- [ ] `运行态上下文标准化` 已输出 `capability / contract_version / intake_nos_json`
|
||||
- [ ] `顶层能力路由` 同时判断 `order_extraction` 与 `shipping-order-extraction-v1`
|
||||
- [ ] `Tool 解析运行态上下文.paths` 已包含 `refs.capability / refs.intake_nos`
|
||||
- [ ] `运行态上下文标准化` 已输出 `capability / intake_nos_json`
|
||||
- [ ] `顶层能力路由` 判断 `order_extraction`
|
||||
- [ ] `order_extraction_path` 位于用户意图、任务读取、库存和 Agent 节点之前
|
||||
- [ ] `Tool 读取订单抽取上下文` 只传原始 `agent_runtime_context`
|
||||
- [ ] `订单抽取上下文标准化` 正确解析 Tool `text`,并校验快照、documents 与 contract
|
||||
|
||||
+7
-4
@@ -62,16 +62,19 @@
|
||||
| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 |
|
||||
| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 |
|
||||
| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake,解析邮件正文/真实附件并派生 FileAsset/Document;上传阶段不调用 LLM、不生成 Candidate、不判订单重复;解析失败、超时、取消和资产引用补偿保持幂等 |
|
||||
| 点击发送完整订单抽取 | 已实现(Dify 画布待手工配置) | 前端通过普通 Chatflow 发送 `shipping_intake_nos`;`agent_runtime_context` 触发固定分支;两个 Tool 读取不可变快照、接收 orders[],支持一附件多订单、SKU/Qty 证据/置信度门禁与幂等重放 |
|
||||
| 点击发送完整订单抽取 | 已实现 | 前端通过普通 Chatflow 发送 `shipping_intake_nos`;`agent_runtime_context` 触发固定分支;Tool 使用统一的 `part_number`/Qty 字段,并在 Candidate 前执行字段级 Observation 裁决 |
|
||||
| 订单识别生命周期反馈 | 已实现 | Handler 在 Dify 首帧前推送 `shipping_order_extraction_state=extracting`,terminal 后推送真实计数与失败状态;终态合并到 `ChatLog.payload`,聊天历史可恢复,处理中不伪造百分比 |
|
||||
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation 的 Task 停在自然对话补字段门禁,订单行 Source Type 仅作可选路由线索 |
|
||||
| 订单解析结果持久只读展示 | 已实现 | Task Detail 顶层投影 `lines` / `parse_validation` / `process_field_gate` / `source_candidate`;右侧工作台与独立任务页共用解析卡,展示 Reservation/Source Type/Hub Code、门禁与证据;Candidate 审核非编辑态同步展示关键行 |
|
||||
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 使用 `shipping-v1` 身份指纹与 `shipping-content-v4` 内容指纹;高置信 `part_number`+Qty 订单可自动建 Task;缺失/非法 Reservation、未解决字段冲突继续阻断下游,库存源线索统一为 `inventory_source_hint` |
|
||||
| 订单解析结果持久只读展示 | 已实现 | Task Detail 顶层投影 `lines` / `parse_validation` / `process_field_gate` / `source_candidate`;右侧工作台与独立任务页共用解析卡,展示内部/客户/AWS 料号、Reservation、库存源线索、门禁与证据;Candidate 审核非编辑态同步展示关键行 |
|
||||
| 规范订单行双写与影子校验 | 已实现 | 默认 `WRITE_MODE=dual` + `READ_MODE=shadow`;解析/改单/回填/重解析经 `task_line_store` 同事务双写;历史回填与 `verify_shipping_task_lines` 支持干跑/续跑;shadow 对外仍读 JSON 并记 checksum;业务读路径统一走 store;观察窗口零差异后切 `READ_MODE=table`;`lines_json` 保留作回滚快照 |
|
||||
| 订单字段对账与冲突复核 | 已实现 | Candidate→Task 字段级自动补空/冲突落库;未解决冲突阻断库存/匹配/导出;workspace 冲突查询与解决 API;改单支持 `expected_order_data_version` 与幂等键;工作台解析卡可解决冲突 |
|
||||
| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML |
|
||||
| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;订单行 `source_type` 可选,连接器字段为 `connector_type` / `inventory_connector_type`;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` |
|
||||
| 订单解析阶段库存源判定 | 已实现(v2 单线索字段) | 订单行仅使用 `inventory_source_hint` 匹配库存源 `match_aliases`;正式路由结果独立写入任务库存源字段,连接器字段保持 `connector_type` / `inventory_connector_type` |
|
||||
| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings |
|
||||
| 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 |
|
||||
| 订单料号领域模型升级 | 已实现 | 主字段为内部料号 `part_number`;可选 `customer_part_number` / `aws_part_number`;三种料号必须原子化且禁止 `/`;当前字段模型不接受旧 `sku / vendor_part_number / customer_sku` |
|
||||
| 后端与 Dify 字段级交叉裁决 | 已实现 | 两侧输出不可变 Observation;后端统一验证 evidence、评分并生成规范投影;一致标记 consensus,高可信冲突或分差不足写 Candidate 阻断冲突;Observation 历史只追加不覆盖 |
|
||||
| 内部料号库存匹配 | 已实现 | 主匹配键为 `(part_number, reservation_id)`;库存 `Supplier Sku` 对应内部料号,`AWS Sku` 仅作为可选 `aws_part_number`,AWS-only 库存表不能形成有效主匹配行 |
|
||||
| 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 |
|
||||
| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 |
|
||||
| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 |
|
||||
|
||||
@@ -71,7 +71,6 @@
|
||||
"reference_context.recent_activity_summary",
|
||||
"refs.batch_no",
|
||||
"refs.capability",
|
||||
"refs.contract_version",
|
||||
"refs.file_name",
|
||||
"refs.hxops_turn_id",
|
||||
"refs.intake_nos",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
"url": "http://192.168.100.192:8890/api/shipping-notice"
|
||||
"url": "http://192.168.36.108:5052/api/shipping-notice"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
@@ -54,7 +54,7 @@
|
||||
"post": {
|
||||
"operationId": "submit_order_extraction",
|
||||
"summary": "提交完整订单抽取结果,由 HXOPS 执行证据校验、订单级判重与自动建单",
|
||||
"description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,订单行 Source Type / Hub Code 是可选路由线索并独立持久化。响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。",
|
||||
"description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、内部料号/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,订单行 inventory_source_hint 是可选路由线索并独立持久化。响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
@@ -71,13 +71,6 @@
|
||||
"type": "string",
|
||||
"description": "get_order_extraction_context 返回的不可变输入快照 SHA-256"
|
||||
},
|
||||
"schema_version": {
|
||||
"type": "string",
|
||||
"description": "固定为 shipping-order-extraction-v1",
|
||||
"enum": [
|
||||
"shipping-order-extraction-v1"
|
||||
]
|
||||
},
|
||||
"orders": {
|
||||
"type": "array",
|
||||
"description": "LLM 从一封或多封邮件中识别出的订单数组;一个附件可产生多个订单,非发货邮件可为空数组",
|
||||
@@ -123,11 +116,11 @@
|
||||
"field_confidence": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"sku",
|
||||
"part_number",
|
||||
"qty"
|
||||
],
|
||||
"properties": {
|
||||
"sku": {
|
||||
"part_number": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
@@ -148,13 +141,13 @@
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"sku",
|
||||
"part_number",
|
||||
"qty"
|
||||
],
|
||||
"properties": {
|
||||
"sku": {
|
||||
"part_number": {
|
||||
"type": "string",
|
||||
"description": "SKU/料号"
|
||||
"description": "内部料号/主匹配料号"
|
||||
},
|
||||
"qty": {
|
||||
"type": "number",
|
||||
@@ -164,21 +157,25 @@
|
||||
"type": "string",
|
||||
"description": "可为空,缺失时 Task 停在补字段门禁"
|
||||
},
|
||||
"source_type": {
|
||||
"inventory_source_hint": {
|
||||
"type": "string",
|
||||
"description": "可选订单路由线索(库存来源提示);仅在原文有可靠证据时填写,不代表任务通知来源或已确认的库存连接器类型"
|
||||
"description": "可选库存来源提示;仅在原文有可靠证据时填写,不代表任务通知来源或已确认的库存连接器类型"
|
||||
},
|
||||
"hub_code": {
|
||||
"customer_part_number": {
|
||||
"type": "string",
|
||||
"description": "可选 Hub/站点线索;与 source_type 独立落库,禁止折叠进 source_type"
|
||||
"description": "可选客户料号"
|
||||
},
|
||||
"aws_part_number": {
|
||||
"type": "string",
|
||||
"description": "可选 AWS 料号"
|
||||
}
|
||||
},
|
||||
"additionalProperties": true
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"evidence": {
|
||||
"type": "array",
|
||||
"description": "至少分别提供 SKU 与 Qty 原文证据,元素含 field 与非空 quote",
|
||||
"description": "至少分别提供内部料号与 Qty 原文证据,元素含 field 与非空 quote",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -188,7 +185,7 @@
|
||||
"properties": {
|
||||
"field": {
|
||||
"type": "string",
|
||||
"description": "证据字段,如 lines[0].sku 或 lines[0].qty"
|
||||
"description": "证据字段,如 lines[0].part_number 或 lines[0].qty"
|
||||
},
|
||||
"quote": {
|
||||
"type": "string",
|
||||
@@ -216,7 +213,6 @@
|
||||
"required": [
|
||||
"agent_runtime_context",
|
||||
"input_snapshot_hash",
|
||||
"schema_version",
|
||||
"orders"
|
||||
]
|
||||
}
|
||||
@@ -341,8 +337,8 @@
|
||||
"/tools/update_notice_line": {
|
||||
"post": {
|
||||
"operationId": "update_notice_line",
|
||||
"summary": "更新解析结果中的某一行,如 SKU、Reservation ID、数量、交期",
|
||||
"description": "更新解析结果中的某一行,如 SKU、Reservation ID、数量、交期",
|
||||
"summary": "更新解析结果中的某一行,如内部料号、Reservation ID、数量、交期",
|
||||
"description": "更新解析结果中的某一行,如内部料号、Reservation ID、数量、交期",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
@@ -361,7 +357,7 @@
|
||||
},
|
||||
"patch": {
|
||||
"type": "object",
|
||||
"description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom/source_type;source_type 仅作为可选订单路由线索",
|
||||
"description": "可更新字段:part_number/reservation_id/quantity/qty/required_date/uom/inventory_source_hint;inventory_source_hint 为可选订单路由线索",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"comment": {
|
||||
@@ -411,7 +407,7 @@
|
||||
},
|
||||
"line": {
|
||||
"type": "object",
|
||||
"description": "新增行,至少包含 sku 和 qty/quantity",
|
||||
"description": "新增行,至少包含 part_number 和 qty/quantity",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"comment": {
|
||||
@@ -547,7 +543,7 @@
|
||||
},
|
||||
"map_json": {
|
||||
"type": "string",
|
||||
"description": "Dify Tool 参数使用 JSON 字符串,内容含 sku/reservation_id/available_qty;可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。"
|
||||
"description": "Dify Tool 参数使用 JSON 字符串,内容含 part_number/reservation_id/available_qty,可选 aws_part_number;可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -802,4 +798,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -37,9 +37,9 @@
|
||||
### 2.x 多订单邮件 Candidate 架构
|
||||
|
||||
- 数据链路为 `FileAsset -> Intake -> Document[] --点击发送/Chatflow--> Candidate[] -> Batch -> Task[]`;上传阶段不调用 LLM、不生成 Candidate、不做订单级判重。
|
||||
- 普通聊天继续走 `/api/chat/completions`,前端传 `shipping_intake_nos`;后端通过 `agent_runtime_context.refs` 注入 `capability=order_extraction`、`contract_version=shipping-order-extraction-v1` 与 Intake JSON 字符串。
|
||||
- 普通聊天继续走 `/api/chat/completions`,前端传 `shipping_intake_nos`;后端通过 `agent_runtime_context.refs` 注入 `capability=order_extraction` 与 Intake JSON 字符串。
|
||||
- 现有 Chatflow 调用 `get_order_extraction_context` 获取不可变快照与全文,再调用 `submit_order_extraction` 提交 orders[];Tool 通过本地 ChatSession 反查用户,禁止信任 LLM 传入 user_id。
|
||||
- Candidate 使用身份指纹 `shipping-v1` 与内容指纹 `shipping-content-v3` 双层判重;内容版本覆盖单头、订单行、价格与分配字段,主附件 hash 独立落到 Task,避免以整封 EML 作为所有订单的判重依据。
|
||||
- Candidate 使用身份指纹 `shipping-v1` 与内容指纹 `shipping-content-v4` 双层判重;内容版本覆盖单头、V2 订单行、价格与分配字段,主附件 hash 独立落到 Task,避免以整封 EML 作为所有订单的判重依据。
|
||||
- Candidate 唯一键为 `(intake_id, candidate_key)`,支持一个 Document 产生多个 Candidate;Task 与 Candidate 一对一关联。
|
||||
- 自动建单后若仍有未消费/待处理 Candidate,Intake 保持 `parsed + partially_completed`;全部处理后才 `consumed`。后补订单可创建新的 Batch,并继续关联原 Intake/Candidate。
|
||||
- 本期不新增 Dify Workflow 或 `agent_runtime_bindings`;未来平台能力注册应由应用声明所需能力,管理端为能力配置 provider/API/key。
|
||||
@@ -51,8 +51,12 @@
|
||||
|
||||
- 解析链采用 `结构保真正文 -> LLM 候选 JSON -> 后端 adjudicate -> validated lines -> 匹配硬闸门`;LLM 不是业务真相源。
|
||||
- HTML 邮件按 `tr -> 换行`、`td/th -> 制表符` 转为 TSV,并保留空单元格;纯文本缺少列边界时只允许保守抽取。
|
||||
- 库存定位键为 `(sku, reservation_id)`,`qty` 是必须有效的数量约束;三者均为硬契约字段,非法或冲突时不得进入库存匹配。
|
||||
- 裁决结果写入 `ShippingTask.step_payload_json.parse_validation`,包含 `status / issues / contract_version`;第一阶段复用现有 JSON 字段,不新增数据库迁移。
|
||||
- 规范订单行采用通用三料号领域模型:`part_number` 为内部料号,`customer_part_number` 与 `aws_part_number` 为可选外部标识;库存定位键为 `(part_number, reservation_id)`,`qty` 是必须有效的数量约束。库存 `Supplier Sku` 映射 `part_number`,`AWS Sku` 映射 `aws_part_number`。
|
||||
- 解析架构采用 `Document -> backend/LLM Observations -> evidence verification -> field adjudication -> canonical ShippingTaskLine`。Observation 不可变,规范投影可随新增可信证据重新裁决;禁止后端解析结果与 Dify 结果相互覆盖原始记录。
|
||||
- 字段裁决按来源语义、表格边界、quote 逐字命中、格式合法性、跨文档一致性和业务上下文统一评分;LLM 自报 confidence 不直接作为最终分数。双方高可信冲突或分差不足时写入 `shipping_task_field_conflicts` 并阻断相关流程。
|
||||
- 三种料号均为原子值并禁止 `/`;复合文本先 token 化后按语义归类。无法证明角色时保留 Observation 并进入人工复核,不得将复合文本直接写入规范订单行。
|
||||
- 裁决结果写入规范订单行的 `field_sources_json / evidence_json`,流程摘要写入 `ShippingTask.step_payload_json.parse_validation`;字段模型调整必须配套 Alembic 迁移。
|
||||
- 规范订单行与内容指纹分别使用 `shipping-task-line-v2`、`shipping-content-v4`。生产尚无业务数据,因此不实现旧字段 alias、双版本读取或历史值猜测回填;dev/test 数据通过迁移或重建切换。
|
||||
- `parse_notice`、人工确认和 `match_inventory` 三层重复执行关键门禁,防止脏值通过任一旁路进入后续履约。
|
||||
|
||||
- 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。
|
||||
@@ -60,7 +64,7 @@
|
||||
- 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。
|
||||
- `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。
|
||||
- **订单行双写与切读**:业务读写经 `task_line_store`;`WRITE_MODE=dual` 同事务维护 `shipping_task_lines` 与 `lines_json`;`READ_MODE=shadow|table`(默认 shared 为 shadow);切 `table` 前须 `verify_shipping_task_lines` 全量零差异并完成观察窗口;回滚只改 `READ_MODE=json`,本期不删 `lines_json`。字段冲突表 `shipping_task_field_conflicts` 与 `order_data_version` 支撑并发安全编辑。
|
||||
- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;订单行 `source_type` 仅作为可选路由线索,库存连接器配置/API 分别使用 `connector_type` / `inventory_connector_type`,不得复用 `ShippingTask.source_type`;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。
|
||||
- **库存源判定前移至订单解析**:`parse_notice` 根据 `shipping_inventory_sources.yaml` 与目的地字段自动 adjudicate;订单行仅保留 `inventory_source_hint` 作为可选路由线索,库存连接器配置/API 分别使用 `connector_type` / `inventory_connector_type`,不得复用 `ShippingTask.source_type`;仅 `inventory_source_status` 为 `resolved` 或 `user_confirmed` 时允许 RPA 与后续步骤;`site_id` 与 `warehouse_id` 由配置生成,用户只确认 `source_code`。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。
|
||||
- **建单防重复(第一阶段)**:`ShippingBatch.create_idempotency_key` + `(user_id, create_idempotency_key)` 唯一约束提供并发保护;`ShippingTask.source_content_hash` 记录源文件 SHA-256;Chat Turn 与 Workspace API 共用 `batch_from_notices` 幂等逻辑;与货代上传 `ShippingTask.idempotency_key` 语义分离。
|
||||
|
||||
### 2.1 已有聊天路由能力
|
||||
|
||||
@@ -39,8 +39,8 @@
|
||||
| **发货通知** | **点击发送进入现有 Chatflow** | 已预处理 Intake 点击发送走普通 `/api/chat/completions`,携带 `shipping_intake_nos`,不调用本地建批 Action。 | `useChatShippingSendHandler.spec.ts` / chat runtime context 测试 | 空文本或自然语言 + parsed Intake | 使用默认/用户 query 调 `sendMessage`;上下文含 Intake;SSE 后仅清理 consumed 附件。 |
|
||||
| **发货通知** | **一附件多订单与部分成功** | 一个 Document 可形成多个 Candidate;高置信订单自动建 Task,低置信订单保留。 | `test_shipping_notice_order_extraction.py::test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay` | 同一附件 2 个订单,其中 1 个低置信 | 2 Candidate、1 Task、1 pending;Intake=`partially_completed`;重放不重复建单。 |
|
||||
| **发货通知** | **订单抽取快照与权限** | Tool 从 agent_runtime_context 会话反查用户;附件来源变化后拒绝旧 LLM 结果。 | `test_shipping_notice_order_extraction.py` | 合法上下文、修改 Document 文本后的旧 snapshot | 合法上下文可读取;漂移返回 `CANDIDATE_SOURCE_CHANGED`;不创建 Candidate。 |
|
||||
| **发货通知** | **自动建单与流程字段门禁** | 分类、SKU/Qty 置信度与原文证据达标即建 Task;缺 Reservation 仍建单但禁止库存链;订单行 Source Type 仅作可选路由线索。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 SKU+Qty,Reservation 为空、Source Type 可选 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel;Source Type 缺失不单独阻断。 |
|
||||
| **发货通知** | **库存连接器 API 命名** | 连接器候选使用 `connector_type`,任务 API 使用 `inventory_connector_type`;不得返回旧 `inventory_source_type`。 | `test_shipping_notice_openapi_contract.py` | 获取动态 OpenAPI 与静态 Dify 快照 | 订单行保留可选 `source_type` 且不暴露废弃路由字段;状态查询说明仅含 `inventory_connector_type`。 |
|
||||
| **发货通知** | **自动建单与流程字段门禁** | 分类、`part_number`/Qty 置信度与原文证据达标即建 Task;缺 Reservation 仍建单但禁止库存链;`inventory_source_hint` 仅作可选路由线索。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 `part_number`+Qty,Reservation 为空、库存源线索可选 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel;库存源线索缺失不单独阻断。 |
|
||||
| **发货通知** | **库存连接器 API 命名** | 连接器候选使用 `connector_type`,任务 API 使用 `inventory_connector_type`;不得返回旧 `inventory_source_type`。 | `test_shipping_notice_openapi_contract.py` | 获取动态 OpenAPI 与静态 Dify 快照 | 订单行仅保留可选 `inventory_source_hint` 且不暴露废弃路由字段;状态查询说明仅含 `inventory_connector_type`。 |
|
||||
| **发货通知** | **Candidate 双指纹判重** | 同身份同内容与同身份修订必须给出不同重复状态。 | `test_shipping_notice_business_dedup.py::test_candidate_content_fingerprint_distinguishes_same_content_and_revision` | 相同 PO/Reservation,不同或相同行数量 | 分别返回 `same_business_content`、`possible_revision`。 |
|
||||
| **发货通知** | **Candidate 审核 API** | owner 可选择/修订/刷新/决策;越权不可见;已消费不可修改。 | `test_shipping_notice_intakes.py::test_candidate_review_duplicate_api_and_access_guards` | owner/other 用户、已消费 Candidate | 成功路径 200,越权 404,已消费 409,修订后清空旧重复决策。 |
|
||||
| **发货通知** | **Candidate 安全门禁** | 空摘要、无效行、附件不完整、过期、选择漂移、无候选旧路径均不可建单。 | `test_shipping_notice_intakes.py` Candidate validation/gate 用例 | 非法摘要与异常 Intake | API 返回明确 400/409;不创建 Task;合法幂等重放不受影响。 |
|
||||
|
||||
@@ -79,6 +79,7 @@ const emit = defineEmits<{
|
||||
stop: [];
|
||||
'voice-click': [];
|
||||
'remove-attachment': [id: string];
|
||||
'retry-attachment': [id: string];
|
||||
'retry-shipping-notice-attachment': [id: string];
|
||||
'resolve-shipping-notice-duplicate': [id: string];
|
||||
'select-shipping-candidate': [candidateNo: string, selected: boolean];
|
||||
@@ -365,6 +366,22 @@ watch(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="a.kind === 'local' && a.uploadStatus === 'failed'"
|
||||
class="absolute bottom-1.5 right-2 flex items-center gap-1"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded p-1 text-red-500 hover:bg-red-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-400 disabled:cursor-not-allowed disabled:opacity-30 dark:hover:bg-red-950/30"
|
||||
:disabled="isUploadingAttachments"
|
||||
:title="t('chat.attachment.retry')"
|
||||
:aria-label="t('chat.attachment.retryNamed', { name: getAttachmentName(a) })"
|
||||
@click="emit('retry-attachment', a.id)"
|
||||
>
|
||||
<RefreshCw class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="a.kind === 'shipping_notice' && (canRetryShippingNoticeParse(a) || (!a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action))"
|
||||
class="absolute bottom-1.5 right-2 flex items-center gap-1"
|
||||
|
||||
@@ -287,6 +287,7 @@ watch(() => page.currentAgentId, () => {
|
||||
@stop="page.stopActiveGeneration()"
|
||||
@voice-click="page.handleVoiceFeatureClick"
|
||||
@remove-attachment="page.removeAttachment"
|
||||
@retry-attachment="page.retryAttachment"
|
||||
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
|
||||
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
|
||||
@select-shipping-candidate="page.setShippingCandidateSelected"
|
||||
|
||||
@@ -11,11 +11,12 @@ import type { ShippingDuplicateAction, ShippingNoticePendingAttachment } from '.
|
||||
|
||||
interface EditableCandidateLine {
|
||||
source: Record<string, unknown>;
|
||||
sku: string;
|
||||
part_number: string;
|
||||
customer_part_number: string;
|
||||
aws_part_number: string;
|
||||
qty: string;
|
||||
reservation_id: string;
|
||||
source_type: string;
|
||||
hub_code: string;
|
||||
inventory_source_hint: string;
|
||||
uom: string;
|
||||
}
|
||||
|
||||
@@ -47,7 +48,7 @@ watch(() => props.attachment.candidates, () => {
|
||||
|
||||
/**
|
||||
* 将 Candidate 摘要投影为可编辑的 PO 与订单行。
|
||||
* 核心逻辑:保留原始扩展字段,并显式映射 SKU、数量、Reservation ID、Source Type、Hub Code 与单位。
|
||||
* 核心逻辑:保留原始扩展字段,并显式映射三类料号、数量、Reservation ID、库存源线索与单位。
|
||||
* @param candidateNo - 待编辑的 Candidate 编号
|
||||
* @returns 无返回值;Candidate 不存在时保持当前编辑状态
|
||||
*/
|
||||
@@ -61,11 +62,12 @@ function startEdit(candidateNo: string): void {
|
||||
editPoNumber.value = String(candidate.businessSummary.po_number || candidate.poNumber || '');
|
||||
editLines.splice(0, editLines.length, ...sourceLines.map((line) => ({
|
||||
source: { ...line },
|
||||
sku: String(line.sku || ''),
|
||||
part_number: String(line.part_number || ''),
|
||||
customer_part_number: String(line.customer_part_number || ''),
|
||||
aws_part_number: String(line.aws_part_number || ''),
|
||||
qty: String(line.qty ?? ''),
|
||||
reservation_id: String(line.reservation_id || ''),
|
||||
source_type: String(line.source_type || ''),
|
||||
hub_code: String(line.hub_code || ''),
|
||||
inventory_source_hint: String(line.inventory_source_hint || ''),
|
||||
uom: String(line.uom || 'EA'),
|
||||
})));
|
||||
if (!editLines.length) addLine();
|
||||
@@ -74,16 +76,25 @@ function startEdit(candidateNo: string): void {
|
||||
|
||||
/**
|
||||
* 新增一条待修订订单行。
|
||||
* 核心逻辑:创建带可选 Source Type / Hub Code 路由线索的空白草稿。
|
||||
* 核心逻辑:创建带三类料号和可选库存源线索的空白草稿。
|
||||
* @returns 无返回值
|
||||
*/
|
||||
function addLine(): void {
|
||||
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', source_type: '', hub_code: '', uom: 'EA' });
|
||||
editLines.push({
|
||||
source: {},
|
||||
part_number: '',
|
||||
customer_part_number: '',
|
||||
aws_part_number: '',
|
||||
qty: '',
|
||||
reservation_id: '',
|
||||
inventory_source_hint: '',
|
||||
uom: 'EA',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并提交 Candidate 修订。
|
||||
* 核心逻辑:保留原始扩展字段;Source Type 与 Hub Code 分开提交,避免编辑时静默丢失 Hub Code。
|
||||
* 核心逻辑:保留原始扩展字段,并按 v2 契约提交三类料号与唯一库存源线索。
|
||||
* @returns 无返回值;校验失败时写入本地错误提示
|
||||
*/
|
||||
function saveEdit(): void {
|
||||
@@ -93,15 +104,16 @@ function saveEdit(): void {
|
||||
const source = { ...line.source };
|
||||
return {
|
||||
...source,
|
||||
sku: line.sku.trim(),
|
||||
part_number: line.part_number.trim(),
|
||||
customer_part_number: line.customer_part_number.trim() || undefined,
|
||||
aws_part_number: line.aws_part_number.trim() || undefined,
|
||||
qty: Number(line.qty),
|
||||
reservation_id: line.reservation_id.trim() || undefined,
|
||||
source_type: line.source_type.trim() || undefined,
|
||||
hub_code: line.hub_code.trim() || undefined,
|
||||
inventory_source_hint: line.inventory_source_hint.trim() || undefined,
|
||||
uom: line.uom.trim() || 'EA',
|
||||
};
|
||||
});
|
||||
if (normalizedLines.some((line) => !line.sku || !Number.isFinite(line.qty) || line.qty <= 0)) {
|
||||
if (normalizedLines.some((line) => !line.part_number || !Number.isFinite(line.qty) || line.qty <= 0)) {
|
||||
editError.value = t('chat.shippingCandidateInvalidLine');
|
||||
return;
|
||||
}
|
||||
@@ -198,6 +210,21 @@ function submitForceCreate(candidateNo: string): void {
|
||||
<div v-if="candidate.conflicts.length" class="mt-1 text-amber-700">
|
||||
{{ t('chat.shippingCandidateConflictCount', { count: candidate.conflicts.length }) }}
|
||||
</div>
|
||||
<div
|
||||
v-if="candidate.fieldAdjudication?.decisions?.length"
|
||||
class="mt-2 rounded-lg border border-sky-200 bg-sky-50/70 px-2 py-1.5"
|
||||
>
|
||||
<div class="font-semibold text-sky-900">{{ t('chat.shippingParsedResult.adjudicationTitle') }}</div>
|
||||
<div class="mt-1 flex flex-wrap gap-1">
|
||||
<span
|
||||
v-for="decision in candidate.fieldAdjudication.decisions"
|
||||
:key="`${decision.line_index}-${decision.field}`"
|
||||
class="rounded border border-sky-100 bg-white px-1.5 py-0.5 font-mono text-[10px] text-sky-900"
|
||||
>
|
||||
#{{ Number(decision.line_index) + 1 }} {{ decision.field }} · {{ decision.status }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="editingCandidateNo !== candidate.candidateNo && readonlyLines(candidate).length"
|
||||
class="mt-2 overflow-x-auto rounded-lg border border-default bg-surface"
|
||||
@@ -205,11 +232,12 @@ function submitForceCreate(candidateNo: string): void {
|
||||
<table class="min-w-full text-[11px]">
|
||||
<thead class="bg-surface-soft text-left text-muted">
|
||||
<tr>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateSku') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateQty') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateReservation') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateSourceType') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingCandidateHubCode') }}</th>
|
||||
<th class="px-2 py-1">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -218,11 +246,12 @@ function submitForceCreate(candidateNo: string): void {
|
||||
:key="`${candidate.candidateNo}-line-${index}`"
|
||||
class="border-t border-default/60"
|
||||
>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.sku) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.part_number) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.customer_part_number) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.aws_part_number) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.qty) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.reservation_id) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.source_type) }}</td>
|
||||
<td class="px-2 py-1 font-mono">{{ displayCell(line.hub_code) }}</td>
|
||||
<td class="px-2 py-1">{{ displayCell(line.inventory_source_hint) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -264,12 +293,13 @@ function submitForceCreate(candidateNo: string): void {
|
||||
<span class="text-muted">{{ t('chat.shippingCandidatePoNumber') }}</span>
|
||||
<input v-model="editPoNumber" class="mt-1 w-full rounded border border-default bg-surface px-2 py-1 text-primary" />
|
||||
</label>
|
||||
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-6">
|
||||
<input v-model="line.sku" :placeholder="t('chat.shippingCandidateSku')" class="rounded border border-default px-2 py-1" />
|
||||
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-4">
|
||||
<input v-model="line.part_number" :placeholder="t('chat.shippingNoticeUi.partNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.customer_part_number" :placeholder="t('chat.shippingNoticeUi.customerPartNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.aws_part_number" :placeholder="t('chat.shippingNoticeUi.awsPartNumber')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.qty" type="number" min="0.0001" step="any" :placeholder="t('chat.shippingCandidateQty')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.reservation_id" :placeholder="t('chat.shippingCandidateReservation')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.source_type" :placeholder="t('chat.shippingCandidateSourceType')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.hub_code" :placeholder="t('chat.shippingCandidateHubCode')" class="rounded border border-default px-2 py-1" />
|
||||
<input v-model="line.inventory_source_hint" :placeholder="t('chat.shippingNoticeUi.inventorySourceHint')" class="rounded border border-default px-2 py-1" />
|
||||
<div class="flex gap-1">
|
||||
<input v-model="line.uom" :placeholder="t('chat.shippingCandidateUom')" class="min-w-0 flex-1 rounded border border-default px-2 py-1" />
|
||||
<button v-if="editLines.length > 1" type="button" class="text-red-600" @click="editLines.splice(index, 1)">×</button>
|
||||
|
||||
@@ -65,6 +65,10 @@ const missingFields = computed(() => {
|
||||
return Array.from(new Set([...gateMissing, ...candidateMissing].map((item) => String(item)).filter(Boolean)));
|
||||
});
|
||||
|
||||
const adjudicationDecisions = computed(() => (
|
||||
props.sourceCandidate?.field_adjudication?.decisions || []
|
||||
).filter((item) => item && typeof item === 'object'));
|
||||
|
||||
const hasBlocking = computed(() =>
|
||||
gateIssues.value.some((issue) => String(issue.severity || '') === 'blocking')
|
||||
|| missingFields.value.includes('reservation_id')
|
||||
@@ -167,7 +171,9 @@ function issueReasonLabel(reason?: string | null): string {
|
||||
<span class="font-mono">{{ issue.field }}</span>
|
||||
<span class="ml-1">{{ issueReasonLabel(issue.reason) }}</span>
|
||||
</div>
|
||||
<div v-if="issue.sku" class="mt-0.5 text-[11px] opacity-80">SKU {{ issue.sku }}</div>
|
||||
<div v-if="issue.part_number" class="mt-0.5 text-[11px] opacity-80">
|
||||
{{ t('chat.shippingNoticeUi.partNumber') }} {{ issue.part_number }}
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
@@ -176,31 +182,49 @@ function issueReasonLabel(reason?: string | null): string {
|
||||
<thead class="bg-surface text-left text-[11px] text-muted">
|
||||
<tr>
|
||||
<th class="px-2.5 py-2">#</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.qty') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingParsedResult.sourceType') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingParsedResult.hubCode') }}</th>
|
||||
<th class="px-2.5 py-2">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="(line, index) in orderLines"
|
||||
:key="`${line.sku}-${index}`"
|
||||
:key="`${line.part_number}-${index}`"
|
||||
class="border-t border-default/60 text-xs"
|
||||
>
|
||||
<td class="px-2.5 py-2 text-muted">{{ index + 1 }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.sku) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.part_number) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.customer_part_number) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.aws_part_number) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.qty) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.reservation_id) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.source_type) }}</td>
|
||||
<td class="px-2.5 py-2 font-mono">{{ displayValue(line.hub_code) }}</td>
|
||||
<td class="px-2.5 py-2">{{ displayValue(line.inventory_source_hint) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-else class="text-muted">{{ t('chat.shippingParsedResult.noLines') }}</div>
|
||||
|
||||
<div v-if="adjudicationDecisions.length" class="rounded-xl border border-sky-200 bg-sky-50/70 p-2.5">
|
||||
<div class="font-semibold text-sky-900">{{ t('chat.shippingParsedResult.adjudicationTitle') }}</div>
|
||||
<div class="mt-2 grid gap-1.5 md:grid-cols-2">
|
||||
<div
|
||||
v-for="decision in adjudicationDecisions"
|
||||
:key="`${decision.line_index}-${decision.field}`"
|
||||
class="rounded border border-sky-100 bg-white/80 px-2 py-1.5 text-[11px]"
|
||||
>
|
||||
<span class="font-mono">#{{ Number(decision.line_index) + 1 }} {{ decision.field }}</span>
|
||||
<span class="ml-1 font-semibold text-sky-800">{{ decision.status }}</span>
|
||||
<span v-if="decision.score != null" class="ml-1 text-muted">{{ t('chat.shippingParsedResult.score', { score: decision.score }) }}</span>
|
||||
<div class="mt-0.5 truncate text-secondary">{{ displayValue(decision.value) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ShippingFieldEvidencePanel
|
||||
:evidence="sourceCandidate?.evidence || []"
|
||||
:compact="compact"
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* features/chat/components/messages/ChatMessageAttachmentList.vue
|
||||
* 用途:在用户消息中展示已发送附件快照。
|
||||
* 用途:在用户消息气泡内部展示已发送附件快照。
|
||||
* 依赖:lucide 文件图标、attachmentCard.utils 的大小格式化、chat.types 的消息附件契约。
|
||||
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;本组件只读展示,不提供删除、重试或上传状态操作。
|
||||
* 逻辑:ChatMessageBubble 将当前用户消息附件传入;卡片继承品牌气泡语境,只读展示且不提供删除或重试。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { FileAudio, FileImage, FileText, FileVideo, Link2 } from 'lucide-vue-next';
|
||||
@@ -35,16 +35,16 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
|
||||
<div
|
||||
v-if="attachments.length > 0"
|
||||
data-testid="chat-message-attachment-list"
|
||||
class="mb-2 flex w-full flex-wrap justify-end gap-2"
|
||||
class="flex w-full flex-wrap justify-end gap-2"
|
||||
>
|
||||
<article
|
||||
v-for="(attachment, attachmentIndex) in attachments"
|
||||
:key="attachment.id || `${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
|
||||
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900 sm:basis-[calc(50%-0.25rem)] sm:min-w-[220px] sm:max-w-[290px]"
|
||||
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-white/20 bg-white/10 px-3 py-2.5 shadow-sm backdrop-blur-sm sm:basis-[calc(50%-0.25rem)] sm:min-w-[220px] sm:max-w-[290px]"
|
||||
:title="attachment.name"
|
||||
>
|
||||
<div
|
||||
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-brand-50 text-brand-700 dark:bg-brand-900/30 dark:text-brand-300"
|
||||
class="flex h-10 w-9 shrink-0 flex-col items-center justify-center rounded-lg bg-white/15 text-white"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<component :is="attachmentIcon(attachment)" class="h-4 w-4" />
|
||||
@@ -53,8 +53,8 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
|
||||
</span>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="truncate text-sm font-semibold text-primary">{{ attachment.name }}</div>
|
||||
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-muted">
|
||||
<div class="truncate text-sm font-semibold text-white">{{ attachment.name }}</div>
|
||||
<div v-if="attachment.size !== undefined" class="mt-1 text-[11px] leading-none text-white/70">
|
||||
{{ formatAttachmentSize(attachment.size) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/chat/components/messages/ChatMessageBubble.vue
|
||||
* 用途:渲染单条聊天消息,统一承接用户气泡、助手 Markdown、内嵌文件下载、请假/出货子组件与操作栏。
|
||||
* 依赖:Vue computed、lucide 图标、消息附件/Leave/Shipping 子组件、chat.types 与页面级 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件显示在文字气泡上方,助手正文与特殊交互委托页面 handlers。
|
||||
* 逻辑:由 ChatMessageList 按消息逐条挂载;用户附件与文字共用同一气泡,助手正文与特殊交互委托页面 handlers。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from 'vue';
|
||||
@@ -125,6 +125,8 @@ const showSourceSection = computed(() => {
|
||||
});
|
||||
|
||||
const hasUserContent = computed(() => message.role === 'user' && String(message.content || '').trim().length > 0);
|
||||
const hasUserAttachments = computed(() => message.role === 'user' && !!message.attachments?.length);
|
||||
const hasUserPayload = computed(() => hasUserContent.value || hasUserAttachments.value);
|
||||
const showActions = computed(() => (
|
||||
message.type !== 'leave-form'
|
||||
&& (message.role !== 'user' || hasUserContent.value)
|
||||
@@ -655,18 +657,20 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
||||
class="flex flex-col"
|
||||
:class="message.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
|
||||
>
|
||||
<ChatMessageAttachmentList
|
||||
v-if="message.role === 'user' && message.attachments?.length"
|
||||
:attachments="message.attachments"
|
||||
/>
|
||||
<div
|
||||
v-if="message.role === 'assistant' || hasUserContent"
|
||||
v-if="message.role === 'assistant' || hasUserPayload"
|
||||
class="text-[15px] leading-relaxed"
|
||||
:class="message.role === 'user'
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
? 'rounded-2xl rounded-tr-sm bg-brand-600 p-2.5 text-white shadow-sm shadow-brand-500/15'
|
||||
: 'chat-msg-assistant'"
|
||||
>
|
||||
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
|
||||
<template v-if="message.role === 'user'">
|
||||
<ChatMessageAttachmentList
|
||||
v-if="message.attachments?.length"
|
||||
:attachments="message.attachments"
|
||||
/>
|
||||
<div v-if="hasUserContent" class="whitespace-pre-wrap px-2.5 py-1">{{ message.content }}</div>
|
||||
</template>
|
||||
<div v-else>
|
||||
<div
|
||||
v-if="shippingOrderExtractionState"
|
||||
|
||||
@@ -59,20 +59,20 @@ const { message, handlers } = defineProps<{
|
||||
<div class="space-y-2">
|
||||
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.orderDetails') }}</div>
|
||||
<div class="text-xs text-muted">
|
||||
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: handlers.getPayload(message)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderSkuPreview', { count: handlers.getPayload(message)!.order.skus.length, skus: handlers.getPayload(message)!.order.skus.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
|
||||
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: handlers.getPayload(message)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderPartNumberPreview', { count: handlers.getPayload(message)!.order.part_numbers.length, partNumbers: handlers.getPayload(message)!.order.part_numbers.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.skuColumnRequired') }}</span>
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.partNumberColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.sku"
|
||||
v-model="handlers.getPayload(message)!.form.part_number"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`sku-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`part-number-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
@@ -87,13 +87,13 @@ const { message, handlers } = defineProps<{
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5 md:col-span-2">
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnOptional') }}</span>
|
||||
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnRequired') }}</span>
|
||||
<select
|
||||
v-model="handlers.getPayload(message)!.form.reservation_id"
|
||||
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
|
||||
:disabled="handlers.getPayload(message)!.applying"
|
||||
>
|
||||
<option value="">{{ $t('chat.shippingNoticeMapping.reservationIdNotUsed') }}</option>
|
||||
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
|
||||
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`rid-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
@@ -76,7 +76,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
<tr>
|
||||
<th class="px-3 py-2">#</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.orderDemand') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.inventoryAvailable') }}</th>
|
||||
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.shortageQty') }}</th>
|
||||
@@ -91,7 +91,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
>
|
||||
<td class="px-3 py-2 text-secondary">{{ index + 1 }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-secondary">{{ line.sku || '-' }}</td>
|
||||
<td class="px-3 py-2 font-mono text-secondary">{{ line.part_number || '-' }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ formatQty(line.required_qty) }}</td>
|
||||
<td class="px-3 py-2 text-secondary">{{ formatQty(line.available_qty) }}</td>
|
||||
<td class="px-3 py-2" :class="Number(line.shortage_qty || 0) > 0 ? 'font-semibold text-rose-700' : 'text-secondary'">
|
||||
@@ -121,7 +121,7 @@ const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLi
|
||||
v-for="(line, index) in shortageLines"
|
||||
:key="`${taskId}-shortage-${index}`"
|
||||
>
|
||||
{{ t('chat.shippingNoticeUi.shortageRowDetail', { index: index + 1, reservationId: line.reservation_id || '-', sku: line.sku || '-', shortage: formatQty(line.shortage_qty) }) }}
|
||||
{{ t('chat.shippingNoticeUi.shortageRowDetail', { index: index + 1, reservationId: line.reservation_id || '-', partNumber: line.part_number || '-', shortage: formatQty(line.shortage_qty) }) }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -36,7 +36,10 @@ const headerForm = reactive<ShippingNoticeHeader>({
|
||||
});
|
||||
const lineForm = reactive<Partial<ShippingNoticeLine>>({
|
||||
reservation_id: '',
|
||||
sku: '',
|
||||
part_number: '',
|
||||
customer_part_number: '',
|
||||
aws_part_number: '',
|
||||
inventory_source_hint: '',
|
||||
qty: 0,
|
||||
required_date: '',
|
||||
uom: '',
|
||||
@@ -61,7 +64,10 @@ watch(
|
||||
const line = payload.value.lines[value];
|
||||
if (!line) return;
|
||||
lineForm.reservation_id = line.reservation_id ?? '';
|
||||
lineForm.sku = line.sku;
|
||||
lineForm.part_number = line.part_number;
|
||||
lineForm.customer_part_number = line.customer_part_number ?? '';
|
||||
lineForm.aws_part_number = line.aws_part_number ?? '';
|
||||
lineForm.inventory_source_hint = line.inventory_source_hint ?? '';
|
||||
lineForm.qty = line.qty;
|
||||
lineForm.required_date = line.required_date ?? '';
|
||||
lineForm.uom = line.uom ?? '';
|
||||
@@ -84,7 +90,10 @@ const saveLine = async () => {
|
||||
if (editingLineIndex.value == null) return;
|
||||
const ok = await handlers.updateLine(message, editingLineIndex.value, {
|
||||
reservation_id: lineForm.reservation_id,
|
||||
sku: lineForm.sku,
|
||||
part_number: lineForm.part_number,
|
||||
customer_part_number: lineForm.customer_part_number,
|
||||
aws_part_number: lineForm.aws_part_number,
|
||||
inventory_source_hint: lineForm.inventory_source_hint,
|
||||
qty: Number(lineForm.qty || 0),
|
||||
required_date: lineForm.required_date,
|
||||
uom: lineForm.uom,
|
||||
@@ -96,7 +105,10 @@ const startAddLine = () => {
|
||||
addingLine.value = true;
|
||||
editingLineIndex.value = null;
|
||||
lineForm.reservation_id = '';
|
||||
lineForm.sku = '';
|
||||
lineForm.part_number = '';
|
||||
lineForm.customer_part_number = '';
|
||||
lineForm.aws_part_number = '';
|
||||
lineForm.inventory_source_hint = '';
|
||||
lineForm.qty = 0;
|
||||
lineForm.required_date = '';
|
||||
lineForm.uom = '';
|
||||
@@ -105,7 +117,10 @@ const startAddLine = () => {
|
||||
const saveAddedLine = async () => {
|
||||
const ok = await handlers.addLine(message, {
|
||||
reservation_id: lineForm.reservation_id,
|
||||
sku: lineForm.sku,
|
||||
part_number: lineForm.part_number,
|
||||
customer_part_number: lineForm.customer_part_number,
|
||||
aws_part_number: lineForm.aws_part_number,
|
||||
inventory_source_hint: lineForm.inventory_source_hint,
|
||||
qty: Number(lineForm.qty || 0),
|
||||
required_date: lineForm.required_date,
|
||||
uom: lineForm.uom,
|
||||
@@ -207,7 +222,9 @@ const removeLine = async (lineIndex: number) => {
|
||||
<tr>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">#</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</th>
|
||||
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.actions') }}</th>
|
||||
@@ -217,7 +234,9 @@ const removeLine = async (lineIndex: number) => {
|
||||
<tr v-for="(line, lineIndex) in payload.lines" :key="`${payload.taskId}-${line.line_no || lineIndex}`">
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ lineIndex + 1 }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.sku }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.part_number }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.customer_part_number || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.aws_part_number || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.qty }}</td>
|
||||
<td class="border border-default px-3 py-2 text-secondary">{{ line.required_date || '-' }}</td>
|
||||
<td class="border border-default px-3 py-2">
|
||||
@@ -251,8 +270,20 @@ const removeLine = async (lineIndex: number) => {
|
||||
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
|
||||
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</span>
|
||||
<input v-model="lineForm.part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</span>
|
||||
<input v-model="lineForm.customer_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</span>
|
||||
<input v-model="lineForm.aws_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</span>
|
||||
<input v-model="lineForm.inventory_source_hint" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
|
||||
@@ -291,8 +322,20 @@ const removeLine = async (lineIndex: number) => {
|
||||
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
|
||||
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.partNumber') }}</span>
|
||||
<input v-model="lineForm.part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerPartNumber') }}</span>
|
||||
<input v-model="lineForm.customer_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.awsPartNumber') }}</span>
|
||||
<input v-model="lineForm.aws_part_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.inventorySourceHint') }}</span>
|
||||
<input v-model="lineForm.inventory_source_hint" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
|
||||
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
ShippingOrderExtractionStatus,
|
||||
} from '../types/chat.types';
|
||||
import type { ShippingBatchUiState, ShippingTaskUiState } from '../types/shipping.api.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import { createStartChatTurn } from './useChatTurn';
|
||||
|
||||
export interface SendMessageLifecycleHooks {
|
||||
@@ -533,7 +534,7 @@ export function useChat() {
|
||||
>,
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => {
|
||||
): Promise<ChatMessageSendResult> => {
|
||||
const displayQuery = String(
|
||||
context && Object.prototype.hasOwnProperty.call(context, 'display_query')
|
||||
? context.display_query ?? ''
|
||||
@@ -565,10 +566,12 @@ export function useChat() {
|
||||
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
||||
activeRunId.value = run.runId;
|
||||
|
||||
runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments));
|
||||
const userMessageIndex = runMessages.push(createUserChatMessage(displayQuery, hooks?.userAttachments)) - 1;
|
||||
let botMsgIndex: number | null = null;
|
||||
let hasAssistantContent = false;
|
||||
let hasTerminalEvent = false;
|
||||
let requestAccepted = false;
|
||||
let chatLogId: number | undefined;
|
||||
let ignoreFurtherStreamEvents = false;
|
||||
const ensureBotMessage = () => {
|
||||
if (botMsgIndex === null) {
|
||||
@@ -609,6 +612,7 @@ export function useChat() {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error((err as { error?: string }).error || `Request failed with status ${response.status}`);
|
||||
}
|
||||
requestAccepted = true;
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
@@ -655,6 +659,10 @@ export function useChat() {
|
||||
}
|
||||
|
||||
const eventName = String(data.event || '');
|
||||
const eventChatLogId = Number(data.chat_log_id || 0);
|
||||
if (Number.isInteger(eventChatLogId) && eventChatLogId > 0) {
|
||||
chatLogId = eventChatLogId;
|
||||
}
|
||||
if (ignoreFurtherStreamEvents && !isAllowedAfterStreamTerminal(eventName)) {
|
||||
continue;
|
||||
}
|
||||
@@ -791,11 +799,24 @@ export function useChat() {
|
||||
if (run.status === 'done' && botMsgIndex !== null) {
|
||||
const botMsg = runMessages[botMsgIndex];
|
||||
if (botMsg) {
|
||||
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||||
try {
|
||||
await hooks?.onAssistantMessageFinished?.(botMsg, runMessages);
|
||||
} catch (error) {
|
||||
// 助手完成后的领域刷新属于附加动作,失败不能反向改变已被服务端接受的消息结果。
|
||||
console.error('[chat] onAssistantMessageFinished failed', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!requestAccepted) {
|
||||
const removeCount = botMsgIndex === null ? 1 : Math.max(botMsgIndex - userMessageIndex + 1, 1);
|
||||
runMessages.splice(userMessageIndex, removeCount);
|
||||
}
|
||||
}
|
||||
return run.status === 'done';
|
||||
return {
|
||||
accepted: requestAccepted,
|
||||
completed: requestAccepted && run.status === 'done',
|
||||
...(chatLogId ? { chatLogId } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -20,6 +20,7 @@ const uploadChatFileMock = vi.mocked(uploadChatFile);
|
||||
function createAttachments() {
|
||||
return useChatAttachments({
|
||||
deps: {
|
||||
t: ((key: string, params?: Record<string, unknown>) => `${key}${params ? JSON.stringify(params) : ''}`),
|
||||
msg: { warning: vi.fn() },
|
||||
} as unknown as ChatDeps,
|
||||
currentAgentId: computed(() => 7),
|
||||
@@ -38,7 +39,7 @@ function createAttachments() {
|
||||
function selectLocalFile(api: ReturnType<typeof createAttachments>, name = 'order.pdf') {
|
||||
const file = new File(['content'], name, { type: 'application/pdf' });
|
||||
api.handleLocalFilesSelected({ target: { files: [file], value: 'selected' } } as unknown as Event);
|
||||
return api.attachments.value[0];
|
||||
return api.attachments.value.at(-1);
|
||||
}
|
||||
|
||||
describe('useChatAttachments upload states', () => {
|
||||
@@ -86,6 +87,41 @@ describe('useChatAttachments upload states', () => {
|
||||
expect(attachment && 'errorMessage' in attachment ? attachment.errorMessage : undefined).toBeUndefined();
|
||||
});
|
||||
|
||||
it('explicitly retries only the selected failed attachment', async () => {
|
||||
const api = createAttachments();
|
||||
const first = selectLocalFile(api, 'first.pdf');
|
||||
const second = selectLocalFile(api, 'second.pdf');
|
||||
if (first?.kind === 'local') first.uploadStatus = 'failed';
|
||||
if (second?.kind === 'local') {
|
||||
second.uploadStatus = 'uploaded';
|
||||
second.uploadFileId = 'upload-second';
|
||||
}
|
||||
uploadChatFileMock.mockResolvedValueOnce({ id: 'upload-first-retry' });
|
||||
|
||||
await expect(api.retryAttachment(first?.id || '')).resolves.toBe(true);
|
||||
|
||||
expect(uploadChatFileMock).toHaveBeenCalledOnce();
|
||||
expect(uploadChatFileMock).toHaveBeenCalledWith(7, first && 'file' in first ? first.file : undefined);
|
||||
expect(first).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-first-retry' });
|
||||
expect(second).toMatchObject({ uploadStatus: 'uploaded', uploadFileId: 'upload-second' });
|
||||
});
|
||||
|
||||
it('keeps explicit retry failures available for another retry', async () => {
|
||||
const api = createAttachments();
|
||||
const attachment = selectLocalFile(api);
|
||||
if (attachment?.kind === 'local') attachment.uploadStatus = 'failed';
|
||||
uploadChatFileMock.mockRejectedValueOnce(new Error('still unavailable'));
|
||||
|
||||
await expect(api.retryAttachment(attachment?.id || '')).resolves.toBe(false);
|
||||
|
||||
expect(attachment).toMatchObject({
|
||||
uploadStatus: 'failed',
|
||||
uploadProgress: 0,
|
||||
errorMessage: 'still unavailable',
|
||||
});
|
||||
expect(api.attachments.value).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('reuses earlier successful files when a later file failed', async () => {
|
||||
const api = createAttachments();
|
||||
selectLocalFile(api, 'first.pdf');
|
||||
|
||||
@@ -66,7 +66,7 @@ export interface UseChatAttachmentsOptions {
|
||||
|
||||
export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const { deps, currentAgentId, currentAgent } = options;
|
||||
const { msg } = deps;
|
||||
const { msg, t } = deps;
|
||||
|
||||
const attachments = ref<PendingAttachment[]>([]);
|
||||
const isUploadingAttachments = ref(false);
|
||||
@@ -265,12 +265,12 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
const files = Array.from(fileList);
|
||||
for (const f of files) {
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
msg.warning(t('chat.attachment.totalLimit', { limit: attachmentPolicy.value.totalLimit }));
|
||||
break;
|
||||
}
|
||||
const ext = extractExt(f.name || '');
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
msg.warning(t('chat.attachment.unsupportedFile', { name: f.name }));
|
||||
continue;
|
||||
}
|
||||
let type = inferFileTypeFromFile(f);
|
||||
@@ -278,23 +278,23 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning(`不支持的附件类型:${f.name}`);
|
||||
msg.warning(t('chat.attachment.unsupportedFile', { name: f.name }));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.local) {
|
||||
msg.warning(`当前应用不支持上传此类型附件:${type}`);
|
||||
msg.warning(t('chat.attachment.localTypeDisabled', { type }));
|
||||
continue;
|
||||
}
|
||||
const limit = attachmentPolicy.value.sizeLimitMb[type];
|
||||
if (limit && f.size > limit * 1024 * 1024) {
|
||||
msg.warning(`附件过大(上限 ${limit}MB):${f.name}`);
|
||||
msg.warning(t('chat.attachment.fileTooLarge', { limit, name: f.name }));
|
||||
continue;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
msg.warning(t('chat.attachment.typeLimit', { limit: caps.limit }));
|
||||
continue;
|
||||
}
|
||||
attachments.value.push({
|
||||
@@ -314,20 +314,20 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (!raw) return;
|
||||
const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
msg.warning('仅支持 http/https URL');
|
||||
msg.warning(t('chat.attachment.httpOnly'));
|
||||
return;
|
||||
}
|
||||
if (!attachmentPolicy.value.canRemote) {
|
||||
msg.warning('当前应用不支持 URL 附件');
|
||||
msg.warning(t('chat.attachment.remoteDisabled'));
|
||||
return;
|
||||
}
|
||||
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
|
||||
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
|
||||
msg.warning(t('chat.attachment.totalLimit', { limit: attachmentPolicy.value.totalLimit }));
|
||||
return;
|
||||
}
|
||||
const ext = extractExt(url);
|
||||
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
msg.warning(t('chat.attachment.unsupportedRemote'));
|
||||
return;
|
||||
}
|
||||
let type = inferFileTypeFromUrl(url);
|
||||
@@ -335,23 +335,70 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) {
|
||||
type = 'custom';
|
||||
} else {
|
||||
msg.warning('不支持的 URL 附件类型');
|
||||
msg.warning(t('chat.attachment.unsupportedRemote'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
const caps = attachmentPolicy.value.enabled[type];
|
||||
if (!caps?.remote) {
|
||||
msg.warning(`当前应用不支持该类型 URL 附件:${type}`);
|
||||
msg.warning(t('chat.attachment.remoteTypeDisabled', { type }));
|
||||
return;
|
||||
}
|
||||
const countSameType = attachments.value.filter((a) => a.type === type).length;
|
||||
if (caps.limit && countSameType >= caps.limit) {
|
||||
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
|
||||
msg.warning(t('chat.attachment.typeLimit', { limit: caps.limit }));
|
||||
return;
|
||||
}
|
||||
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
|
||||
};
|
||||
|
||||
/**
|
||||
* 上传单个普通本地附件;成功上传 ID 可被发送流程复用。
|
||||
* @param item - 必须是仍存在于输入区的本地附件
|
||||
* @returns Dify 本地文件参数
|
||||
*/
|
||||
const uploadLocalAttachment = async (
|
||||
item: Extract<PendingAttachment, { kind: 'local' }>,
|
||||
): Promise<ChatUploadFileSpec> => {
|
||||
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
|
||||
return { type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId };
|
||||
}
|
||||
item.uploadStatus = 'uploading';
|
||||
item.uploadProgress = 0;
|
||||
item.errorMessage = undefined;
|
||||
try {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) throw new Error(t('chat.attachment.missingUploadId'));
|
||||
item.uploadStatus = 'uploaded';
|
||||
item.uploadProgress = 100;
|
||||
item.uploadFileId = uploaded.id;
|
||||
return { type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id };
|
||||
} catch (error: unknown) {
|
||||
item.uploadStatus = 'failed';
|
||||
item.uploadProgress = 0;
|
||||
item.uploadFileId = undefined;
|
||||
item.errorMessage = error instanceof Error ? error.message : t('chat.attachment.uploadFailed');
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
/** 用户从失败卡片显式重试单个普通附件,不触发整条消息发送。 */
|
||||
const retryAttachment = async (id: string): Promise<boolean> => {
|
||||
const target = attachments.value.find(
|
||||
(item): item is Extract<PendingAttachment, { kind: 'local' }> => item.id === id && item.kind === 'local',
|
||||
);
|
||||
if (!target || target.uploadStatus !== 'failed' || isUploadingAttachments.value) return false;
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
await uploadLocalAttachment(target);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 将待发送附件转换为 Dify 文件参数,并逐个更新本地文件的真实上传状态。
|
||||
* 核心逻辑:复用已成功上传的 uploadFileId;失败附件保留并在下次发送时重试。
|
||||
@@ -370,30 +417,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
isUploadingAttachments.value = true;
|
||||
try {
|
||||
for (const item of locals) {
|
||||
if (item.uploadStatus === 'uploaded' && item.uploadFileId) {
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: item.uploadFileId });
|
||||
continue;
|
||||
}
|
||||
|
||||
item.uploadStatus = 'uploading';
|
||||
item.uploadProgress = 0;
|
||||
item.errorMessage = undefined;
|
||||
try {
|
||||
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
|
||||
if (!uploaded?.id) {
|
||||
throw new Error('Missing upload id');
|
||||
}
|
||||
item.uploadStatus = 'uploaded';
|
||||
item.uploadProgress = 100;
|
||||
item.uploadFileId = uploaded.id;
|
||||
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
|
||||
} catch (error: unknown) {
|
||||
item.uploadStatus = 'failed';
|
||||
item.uploadProgress = 0;
|
||||
item.uploadFileId = undefined;
|
||||
item.errorMessage = error instanceof Error ? error.message : 'File upload failed';
|
||||
throw error;
|
||||
}
|
||||
specs.push(await uploadLocalAttachment(item));
|
||||
}
|
||||
} finally {
|
||||
isUploadingAttachments.value = false;
|
||||
@@ -424,6 +448,7 @@ export function useChatAttachments(options: UseChatAttachmentsOptions) {
|
||||
isUploadingAttachments,
|
||||
attachmentPolicy,
|
||||
removeAttachment,
|
||||
retryAttachment,
|
||||
handleLocalFilesSelected,
|
||||
addRemoteUrlAttachment,
|
||||
buildFileSpecsForSend,
|
||||
|
||||
@@ -65,6 +65,7 @@ import {
|
||||
|
||||
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from './useChat';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||||
import type { ChatDeps } from './chat.deps';
|
||||
import { listChatMessages } from '../api/chat.api';
|
||||
@@ -98,7 +99,7 @@ export interface UseChatShippingOptions {
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||||
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
|
||||
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
|
||||
|
||||
@@ -35,7 +35,7 @@ function createContext(overrides: Partial<ChatPageSendContext> = {}): ChatPageSe
|
||||
]),
|
||||
createMessageAttachmentSnapshots: vi.fn(() => attachmentSnapshots.map((item) => ({ ...item }))),
|
||||
clearAttachments: vi.fn(),
|
||||
sendMessage: vi.fn(async () => true),
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: true })),
|
||||
refreshHistoryAfterSend: vi.fn(async () => undefined),
|
||||
refreshConversationAfterSend: vi.fn(async () => undefined),
|
||||
tryHandleShippingAttachmentAutoFlow: vi.fn(async () => false),
|
||||
@@ -62,25 +62,26 @@ describe('createChatPageSendApi attachment lifecycle', () => {
|
||||
expect(ctx.sendMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps uploaded attachments when message sending fails', async () => {
|
||||
it('keeps uploaded attachments and restores input when the request is not accepted', async () => {
|
||||
const ctx = createContext({
|
||||
sendMessage: vi.fn(async () => { throw new Error('stream failed'); }),
|
||||
});
|
||||
|
||||
await expect(createChatPageSendApi(ctx).handleSend()).rejects.toThrow('stream failed');
|
||||
|
||||
expect(ctx.clearAttachments).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps uploaded attachments when the real send result reports failure', async () => {
|
||||
const ctx = createContext({
|
||||
sendMessage: vi.fn(async () => false),
|
||||
sendMessage: vi.fn(async () => ({ accepted: false, completed: false })),
|
||||
});
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.clearAttachments).not.toHaveBeenCalled();
|
||||
expect(ctx.refreshHistoryAfterSend).not.toHaveBeenCalled();
|
||||
expect(ctx.input.value).toBe('请分析附件');
|
||||
});
|
||||
|
||||
it('clears attachments when the request is accepted even if the assistant stream fails', async () => {
|
||||
const ctx = createContext({
|
||||
sendMessage: vi.fn(async () => ({ accepted: true, completed: false, chatLogId: 42 })),
|
||||
});
|
||||
|
||||
await createChatPageSendApi(ctx).handleSend();
|
||||
|
||||
expect(ctx.clearAttachments).toHaveBeenCalledOnce();
|
||||
expect(ctx.refreshHistoryAfterSend).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('clears attachments only after message sending succeeds', async () => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { copyTextToClipboard } from '@/shared/utils/clipboard';
|
||||
import type { ChatMessage, ChatMessageAttachment } from '../types/chat.types';
|
||||
import type { SendMessageLifecycleHooks } from '../composables/useChat';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
const looksLikeCompletedAssistantReply = (content: string) => {
|
||||
@@ -55,7 +56,7 @@ export interface ChatPageSendContext {
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
|
||||
hooks?: SendMessageLifecycleHooks,
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
refreshHistoryAfterSend: () => Promise<void>;
|
||||
refreshConversationAfterSend?: () => Promise<void>;
|
||||
tryHandleShippingAttachmentAutoFlow: (
|
||||
@@ -133,7 +134,8 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof textOrEvent !== 'string') ctx.input.value = '';
|
||||
const shouldClearInput = typeof textOrEvent !== 'string';
|
||||
if (shouldClearInput) ctx.input.value = '';
|
||||
|
||||
const requestContent = trimmed || ctx.t('chat.attachment.defaultPrompt');
|
||||
const sendContext = {
|
||||
@@ -152,7 +154,10 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
|
||||
onAssistantMessageFinished: ctx.onAssistantMessageFinished,
|
||||
},
|
||||
);
|
||||
if (sent === false) return;
|
||||
if (!sent.accepted) {
|
||||
if (shouldClearInput) ctx.input.value = content;
|
||||
return;
|
||||
}
|
||||
ctx.clearAttachments();
|
||||
await ctx.refreshHistoryAfterSend();
|
||||
await ctx.refreshConversationAfterSend?.();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
*/
|
||||
import type { ChatSessionItem } from '../types/chat.types';
|
||||
import type { ChatUploadFileSpec } from '../types/shipping.types';
|
||||
import type { ChatMessageSendResult } from '../types/chat-turn.types';
|
||||
import type { ComputedRef, Ref } from 'vue';
|
||||
|
||||
export interface ShippingConversationContext {
|
||||
@@ -21,7 +22,7 @@ export interface ShippingConversationContext {
|
||||
kb: string,
|
||||
files: ChatUploadFileSpec[],
|
||||
context?: { task_id?: string; batch_no?: string; display_query?: string },
|
||||
) => Promise<boolean | void>;
|
||||
) => Promise<ChatMessageSendResult>;
|
||||
}
|
||||
|
||||
/** 发送菜单类消息后,若当前会话尚未出现在侧栏历史中则刷新列表 */
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingDecisionFormat.spec.ts
|
||||
* 用途:验证库存映射人工修正摘要使用 v2 系统字段名。
|
||||
* 依赖:vitest、shippingDecisionFormat。
|
||||
* 逻辑:锁死建议映射展示中的 part_number,防止旧 sku 契约回流。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatShippingDecisionAssistantMessage } from './shippingDecisionFormat';
|
||||
|
||||
describe('formatShippingDecisionAssistantMessage', () => {
|
||||
it('renders part_number for inventory mapping suggestions', () => {
|
||||
const text = formatShippingDecisionAssistantMessage(
|
||||
'correct_inventory_mapping',
|
||||
{
|
||||
message: '请修正映射',
|
||||
data: {
|
||||
schema_preview: {
|
||||
headers: ['Supplier Sku', 'COM ID', 'Qty Available'],
|
||||
suggested_mapping: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
'SN-MAP-001',
|
||||
'操作已完成',
|
||||
);
|
||||
|
||||
expect(text).toContain('- part_number → Supplier Sku');
|
||||
expect(text).not.toContain('- sku →');
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ export function formatShippingDecisionAssistantMessage(
|
||||
lines.push('', `当前表头:${headers.join(' | ')}`);
|
||||
}
|
||||
const mappingLines = [
|
||||
suggested.sku ? `- sku → ${suggested.sku}` : null,
|
||||
suggested.part_number ? `- part_number → ${suggested.part_number}` : null,
|
||||
suggested.reservation_id ? `- reservation_id → ${suggested.reservation_id}` : null,
|
||||
suggested.available_qty ? `- available_qty → ${suggested.available_qty}` : null,
|
||||
].filter((line): line is string => Boolean(line));
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* features/chat/shipping/shippingIntents.spec.ts
|
||||
* 用途:验证发货聊天自然语言库存映射遵循 v2 字段契约。
|
||||
* 依赖:vitest、shippingIntents。
|
||||
* 逻辑:覆盖完整三字段映射与缺 Reservation 拒绝分支。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseShippingColumnMappingFromText } from './shippingIntents';
|
||||
|
||||
describe('parseShippingColumnMappingFromText', () => {
|
||||
it('normalizes SKU wording to the v2 part_number key', () => {
|
||||
expect(parseShippingColumnMappingFromText([
|
||||
'SKU -> Supplier Sku',
|
||||
'Reservation ID -> COM ID',
|
||||
'Available Qty -> Qty Available',
|
||||
].join('\n'))).toEqual({
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects mappings that omit Reservation ID', () => {
|
||||
expect(parseShippingColumnMappingFromText([
|
||||
'part_number -> Supplier Sku',
|
||||
'available_qty -> Qty Available',
|
||||
].join('\n'))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -13,7 +13,7 @@ export interface ShippingTaskSwitchIntent {
|
||||
}
|
||||
|
||||
/**
|
||||
* 从自然语言文本解析库存列映射(sku / available_qty / reservation_id → Excel 列名)。
|
||||
* 从自然语言文本解析库存列映射(part_number / reservation_id / available_qty → Excel 列名)。
|
||||
*/
|
||||
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
|
||||
const raw = String(content || '').trim();
|
||||
@@ -31,7 +31,9 @@ export function parseShippingColumnMappingFromText(content: string): Record<stri
|
||||
const s = left.toLowerCase();
|
||||
if (s.includes('reservation') || left.includes('预留') || left.includes('预定')) return 'reservation_id';
|
||||
if (s.includes('qty') || s.includes('available') || left.includes('可用') || left.includes('数量')) return 'available_qty';
|
||||
if (s.includes('sku') || left.includes('料号') || left.includes('物料')) return 'sku';
|
||||
if (s.includes('part_number') || s.includes('part number') || s.includes('sku') || left.includes('料号') || left.includes('物料')) {
|
||||
return 'part_number';
|
||||
}
|
||||
return '';
|
||||
};
|
||||
for (const line of lines) {
|
||||
@@ -46,7 +48,7 @@ export function parseShippingColumnMappingFromText(content: string): Record<stri
|
||||
if (!col) continue;
|
||||
mapping[key] = col;
|
||||
}
|
||||
if (!mapping.sku || !mapping.available_qty) return null;
|
||||
if (!mapping.part_number || !mapping.reservation_id || !mapping.available_qty) return null;
|
||||
return mapping;
|
||||
}
|
||||
|
||||
|
||||
@@ -41,8 +41,8 @@ export function buildShippingFieldAlignmentText(payload: { data?: { field_alignm
|
||||
const invCols = (alignment as { inventory_columns?: { mapping?: Record<string, { source_column?: string }> } }).inventory_columns || {};
|
||||
const mapping = invCols.mapping || {};
|
||||
const rows: Array<[string, string]> = [
|
||||
['sku', normalizeShippingHeaderForDisplay(mapping?.sku?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别/可选)'],
|
||||
['part_number', normalizeShippingHeaderForDisplay(mapping?.part_number?.source_column) || '(未识别)'],
|
||||
['reservation_id', normalizeShippingHeaderForDisplay(mapping?.reservation_id?.source_column) || '(未识别)'],
|
||||
['available_qty', normalizeShippingHeaderForDisplay(mapping?.available_qty?.source_column) || '(未识别)'],
|
||||
];
|
||||
const lines: string[] = [];
|
||||
|
||||
@@ -50,7 +50,7 @@ export const formatShortageLine = (
|
||||
t: (key: string, params?: Record<string, unknown>) => string,
|
||||
) => t('chat.shippingNoticeUi.diagnosisShortageLine', {
|
||||
index: index + 1,
|
||||
sku: line.sku || '-',
|
||||
partNumber: line.part_number || '-',
|
||||
reservationId: line.reservation_id || '-',
|
||||
required: formatShippingQty(line.required_qty),
|
||||
available: formatShippingQty(line.available_qty),
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* features/chat/shipping/useChatShippingMappingForm.spec.ts
|
||||
* 用途:验证库存人工列映射严格使用 v2 料号与 Reservation 契约。
|
||||
* 依赖:vitest、Vue refs、shipping.api、useChatShippingMappingForm。
|
||||
* 逻辑:覆盖表单预填、完整映射提交和缺 Reservation 本地阻断。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createShippingMappingFormHandlers, type ShippingMappingFormContext } from './useChatShippingMappingForm';
|
||||
import type { ChatMessage } from '../types/chat.types';
|
||||
|
||||
const { getWorkspaceShippingTask } = vi.hoisted(() => ({
|
||||
getWorkspaceShippingTask: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/features/chat/api/shipping.api', () => ({
|
||||
getWorkspaceShippingTask,
|
||||
}));
|
||||
|
||||
const createContext = (
|
||||
overrides: Partial<ShippingMappingFormContext> = {},
|
||||
): ShippingMappingFormContext => ({
|
||||
messages: ref<ChatMessage[]>([]),
|
||||
chatScrollContainer: ref(null),
|
||||
shippingInventorySchemaPreviewCache: ref({
|
||||
'SN-MAP-001': {
|
||||
headers: ['Supplier Sku', 'COM ID', 'Qty Available'],
|
||||
suggested_mapping: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
}),
|
||||
shippingInventoryPickerRef: ref(null),
|
||||
pendingShippingUploadTaskId: ref(''),
|
||||
resolvedShippingTaskId: ref(''),
|
||||
newLocalMessageId: () => 'local-mapping-1',
|
||||
saveLocalMessageToBackend: vi.fn(async () => undefined),
|
||||
startChatTurn: vi.fn(async () => true),
|
||||
currentAgentId: computed(() => 42),
|
||||
refreshShippingActions: vi.fn(async () => undefined),
|
||||
msg: { warning: vi.fn() },
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('useChatShippingMappingForm', () => {
|
||||
beforeEach(() => {
|
||||
getWorkspaceShippingTask.mockReset();
|
||||
getWorkspaceShippingTask.mockResolvedValue({
|
||||
lines: [{ part_number: 'D4-A08AR12000002', reservation_id: '3000092917', qty: 10 }],
|
||||
});
|
||||
});
|
||||
|
||||
it('prefills and submits the v2 inventory mapping fields', async () => {
|
||||
const ctx = createContext();
|
||||
const handlers = createShippingMappingFormHandlers(ctx);
|
||||
|
||||
expect(await handlers.openShippingInventoryMappingFormForTask('sn-map-001')).toBe(true);
|
||||
const message = ctx.messages.value[0];
|
||||
expect(message.payload).toMatchObject({
|
||||
order: { line_count: 1, part_numbers: ['D4-A08AR12000002'] },
|
||||
form: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
});
|
||||
|
||||
await handlers.applyShippingInventoryMappingForm(message);
|
||||
|
||||
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
|
||||
actionType: 'shipping.apply_inventory_mapping',
|
||||
payload: {
|
||||
task_no: 'SN-MAP-001',
|
||||
map_json: {
|
||||
part_number: 'Supplier Sku',
|
||||
reservation_id: 'COM ID',
|
||||
available_qty: 'Qty Available',
|
||||
},
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
it('blocks submission when the Reservation ID mapping is missing', async () => {
|
||||
const ctx = createContext();
|
||||
const handlers = createShippingMappingFormHandlers(ctx);
|
||||
await handlers.openShippingInventoryMappingFormForTask('SN-MAP-001');
|
||||
const message = ctx.messages.value[0];
|
||||
const payload = message.payload as { form: { reservation_id: string } };
|
||||
payload.form.reservation_id = '';
|
||||
|
||||
await handlers.applyShippingInventoryMappingForm(message);
|
||||
|
||||
expect(ctx.startChatTurn).not.toHaveBeenCalled();
|
||||
expect(ctx.msg.warning).toHaveBeenCalledWith('请先选择内部料号列、Reservation ID 列与可用数量列');
|
||||
});
|
||||
});
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user