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]:
|
||||
|
||||
Reference in new issue
Block a user