feat(shipping-notice): 增强发货通知候选管理功能,支持候选选择、重复检测与业务摘要修订
This commit is contained in:
1 parent
70f684b94a
commit
b595e157e9
83 files changed
+5857
-200
No files matched your search
+21
-2
@@ -47,7 +47,12 @@ SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
def _build_chat_adapter_hints(
|
||||
*,
|
||||
shipping_task_id: str | None = None,
|
||||
shipping_batch_no: str | None = None,
|
||||
shipping_intake_nos: list[str] | None = None,
|
||||
) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
@@ -56,12 +61,16 @@ def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_b
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
|
||||
if not task_id and not batch_no and not intake_nos:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1275,6 +1284,14 @@ def chat_completions():
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
raw_shipping_intakes = data.get('shipping_intake_nos')
|
||||
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
|
||||
raise ValidationError('shipping_intake_nos must be a list')
|
||||
shipping_intake_nos = sorted({
|
||||
str(item or '').strip().upper()
|
||||
for item in (raw_shipping_intakes or [])
|
||||
if str(item or '').strip()
|
||||
})
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
@@ -1404,6 +1421,7 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
@@ -1446,6 +1464,7 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -138,6 +138,25 @@ def tool_create_task():
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_order_extraction_context', methods=['POST'])
|
||||
def tool_get_order_extraction_context():
|
||||
"""
|
||||
返回当前会话待解析邮件及附件文本。
|
||||
【AI 触发时机】:仅当 agent_runtime_context.refs.capability=order_extraction 时,
|
||||
在完整订单抽取 LLM 节点之前调用一次。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_order_extraction_context(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_order_extraction', methods=['POST'])
|
||||
def tool_submit_order_extraction():
|
||||
"""
|
||||
提交 LLM 完整订单抽取结果并由 HXOPS 校验、判重和自动建单。
|
||||
【AI 触发时机】:订单抽取 LLM 与 JSON 标准化节点成功后调用;禁止绕过此 Tool 直接建单。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_order_extraction(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
|
||||
@@ -701,15 +701,79 @@ def workspace_refresh_shipping_notice_duplicate(intake_no: str):
|
||||
return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/candidates/<candidate_no>', methods=['PATCH'])
|
||||
def workspace_update_shipping_notice_candidate(candidate_no: str):
|
||||
"""更新订单候选的选择状态或人工修订业务摘要。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('请求体必须为对象')
|
||||
if 'selected' in body and not isinstance(body.get('selected'), bool):
|
||||
raise ValidationError('selected 必须为布尔值')
|
||||
if 'business_summary' in body and not isinstance(body.get('business_summary'), dict):
|
||||
raise ValidationError('business_summary 必须为对象')
|
||||
if 'selected' not in body and 'business_summary' not in body:
|
||||
raise ValidationError('selected 或 business_summary 至少提供一项')
|
||||
from app.services.shipping_notice.candidate_service import update_candidate
|
||||
|
||||
return _ok(
|
||||
update_candidate(
|
||||
user_id=user.id,
|
||||
candidate_no=candidate_no,
|
||||
selected=body.get('selected') if 'selected' in body else None,
|
||||
business_summary=body.get('business_summary') if 'business_summary' in body else None,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/candidates/<candidate_no>/duplicate-refresh',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_refresh_shipping_notice_candidate(candidate_no: str):
|
||||
"""刷新单个订单候选的重复检测。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.candidate_service import refresh_candidate_duplicate
|
||||
|
||||
return _ok(refresh_candidate_duplicate(user_id=user.id, candidate_no=candidate_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/candidates/<candidate_no>/duplicate-resolution',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_resolve_shipping_notice_candidate(candidate_no: str):
|
||||
"""保存单个订单候选的重复处理决策。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.candidate_service import resolve_candidate_duplicate
|
||||
|
||||
return _ok(
|
||||
resolve_candidate_duplicate(
|
||||
user_id=user.id,
|
||||
candidate_no=candidate_no,
|
||||
action=str(body.get('action') or ''),
|
||||
target_task_no=str(body.get('target_task_no') or '').strip() or None,
|
||||
reason=str(body.get('reason') or '').strip() or None,
|
||||
actor=user,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""从已解析接入记录确认建批。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('请求体必须为对象')
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError('intake_nos is required')
|
||||
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||
candidate_nos = body.get('candidate_nos')
|
||||
if candidate_nos is not None and not isinstance(candidate_nos, list):
|
||||
raise ValidationError('candidate_nos must be a list')
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
@@ -725,6 +789,7 @@ def workspace_create_shipping_batch_from_intakes():
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
candidate_nos=[str(item) for item in candidate_nos] if isinstance(candidate_nos, list) else None,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
@@ -6,7 +6,7 @@ backend/app/models/shipping.py
|
||||
逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等;
|
||||
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
|
||||
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
|
||||
Document/Candidate 承载阶段二「一邮件多订单」识别;ShippingTask.source_candidate_id 预留给建单;
|
||||
Document/Candidate 承载「一邮件多订单」识别;ShippingTask.source_candidate_id 记录正式建单来源;
|
||||
ShippingTask.supersedes_task_id 唯一约束保证修订链线性。
|
||||
"""
|
||||
|
||||
@@ -90,6 +90,7 @@ class ShippingTask(Base):
|
||||
Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
|
||||
Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'),
|
||||
Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'),
|
||||
Index('ix_shipping_tasks_user_content_fingerprint', 'user_id', 'content_fingerprint'),
|
||||
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
|
||||
UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'),
|
||||
Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'),
|
||||
@@ -122,6 +123,8 @@ class ShippingTask(Base):
|
||||
)
|
||||
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
supersedes_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
@@ -331,7 +334,7 @@ class ShippingTaskInventoryLink(Base):
|
||||
|
||||
|
||||
class ShippingNoticeIntake(Base):
|
||||
"""发货通知预解析接入记录(上传成功至正式建单前的异步解析阶段)。"""
|
||||
"""发货通知接入记录:分别跟踪文件预处理与订单抽取状态。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_intakes'
|
||||
__table_args__ = (
|
||||
@@ -358,6 +361,16 @@ class ShippingNoticeIntake(Base):
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False)
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True)
|
||||
order_extraction_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='not_started',
|
||||
server_default=text("'not_started'"),
|
||||
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)
|
||||
structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
@@ -428,6 +441,18 @@ class ShippingNoticeDocument(Base):
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False)
|
||||
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
order_extraction_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='not_started',
|
||||
server_default=text("'not_started'"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
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)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
@@ -436,17 +461,14 @@ class ShippingNoticeCandidate(Base):
|
||||
"""
|
||||
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
|
||||
|
||||
核心逻辑:通常 1 Document → 1 Candidate;重复检测与决策落在 Candidate 级,互不影响。
|
||||
核心逻辑:一个 Document 可抽取多个 Candidate;candidate_key 保证重提取幂等,
|
||||
重复检测、自动建单与待补字段状态均落在 Candidate 级。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_notice_candidates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
|
||||
UniqueConstraint(
|
||||
'intake_id',
|
||||
'primary_document_id',
|
||||
name='uq_shipping_notice_candidates_intake_primary_document',
|
||||
),
|
||||
UniqueConstraint('intake_id', 'candidate_key', name='uq_shipping_notice_candidates_intake_key'),
|
||||
# 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接
|
||||
ForeignKeyConstraint(
|
||||
['primary_document_id', 'intake_id'],
|
||||
@@ -470,6 +492,14 @@ class ShippingNoticeCandidate(Base):
|
||||
nullable=False,
|
||||
)
|
||||
primary_document_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
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)
|
||||
evidence_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
@@ -484,6 +514,8 @@ class ShippingNoticeCandidate(Base):
|
||||
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
content_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
content_fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
duplicate_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='unchecked',
|
||||
@@ -495,6 +527,8 @@ class ShippingNoticeCandidate(Base):
|
||||
duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
nullable=True,
|
||||
|
||||
@@ -31,6 +31,9 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
|
||||
"refs.batch_no",
|
||||
"refs.task_no",
|
||||
"refs.run_purpose",
|
||||
"refs.capability",
|
||||
"refs.contract_version",
|
||||
"refs.intake_nos",
|
||||
"refs.file_name",
|
||||
"refs.schedule_task_id",
|
||||
"refs.hxops_turn_id",
|
||||
|
||||
@@ -80,13 +80,29 @@ def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]])
|
||||
|
||||
核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。
|
||||
"""
|
||||
hashes = sorted(
|
||||
{
|
||||
str(item.get("source_content_hash") or "").strip().lower()
|
||||
for item in notice_items
|
||||
if isinstance(item, dict) and str(item.get("source_content_hash") or "").strip()
|
||||
}
|
||||
)
|
||||
hashes: list[str] = []
|
||||
for item in notice_items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
source_hash = str(item.get("source_content_hash") or "").strip().lower()
|
||||
if not source_hash:
|
||||
continue
|
||||
candidate_id = str(item.get("source_candidate_id") or "").strip()
|
||||
if candidate_id:
|
||||
hashes.append(
|
||||
"|".join(
|
||||
[
|
||||
candidate_id,
|
||||
source_hash,
|
||||
str(item.get("business_fingerprint") or "").strip().lower(),
|
||||
str(item.get("content_fingerprint") or "").strip().lower(),
|
||||
]
|
||||
)
|
||||
)
|
||||
else:
|
||||
# 旧单文件/直接上传路径保持纯文件哈希,兼容历史批次回放。
|
||||
hashes.append(source_hash)
|
||||
hashes = sorted(set(hashes))
|
||||
if not hashes:
|
||||
return ""
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
|
||||
@@ -22,7 +22,14 @@ from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import FileAsset, ShippingBatch, ShippingNoticeIntake, ShippingTask
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingBatch,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
build_existing_batch_tool_response,
|
||||
@@ -30,8 +37,13 @@ from app.services.shipping_notice.batch_create_idempotency import (
|
||||
normalize_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_notices import create_shipping_batch_from_notice_items
|
||||
from app.services.shipping_notice.duplicate_detection import detect_duplicates_for_intake
|
||||
from app.services.shipping_notice.intake_parse_workflow import intake_to_notice_item
|
||||
from app.services.shipping_notice.duplicate_detection import (
|
||||
apply_duplicate_result_to_candidate,
|
||||
detect_duplicates_for_candidate,
|
||||
detect_duplicates_for_intake,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
|
||||
from app.services.shipping_notice.intake_parse_workflow import candidate_to_notice_item, intake_to_notice_item
|
||||
from app.services.shipping_notice.intake_service import mark_intakes_consumed
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
@@ -414,11 +426,344 @@ def _attach_request_intake_summary(
|
||||
flag_modified(batch, 'process_summary_json')
|
||||
|
||||
|
||||
def _candidate_request_summary(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
"""读取 Intake 中保存的 Candidate 建批请求摘要。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
value = structured.get('candidate_batch_request')
|
||||
return value if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def _stamp_candidate_request(
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
*,
|
||||
candidate_nos: list[str],
|
||||
create_idempotency_key: str | None,
|
||||
) -> None:
|
||||
"""将 Candidate 集合与幂等键写入 Intake,支持纯 open_existing 与断点重放。"""
|
||||
now = datetime.utcnow()
|
||||
ordered = sorted(set(candidate_nos))
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
structured['candidate_batch_request'] = {
|
||||
'candidate_nos': ordered,
|
||||
'idempotency_key': normalize_create_idempotency_key(create_idempotency_key),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
intake.create_idempotency_key = normalize_create_idempotency_key(create_idempotency_key)
|
||||
intake.updated_at = now
|
||||
|
||||
|
||||
def _candidate_replay(
|
||||
*,
|
||||
user_id: int,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
candidates: list[ShippingNoticeCandidate],
|
||||
candidate_nos: list[str],
|
||||
create_idempotency_key: str | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""按 Candidate 集合重放已完成请求;集合或幂等键不一致时返回 None。"""
|
||||
key = normalize_create_idempotency_key(create_idempotency_key)
|
||||
if not key or not intakes:
|
||||
return None
|
||||
summary = _candidate_request_summary(intakes[0])
|
||||
stored = sorted(str(item).strip().upper() for item in summary.get('candidate_nos') or [])
|
||||
if summary.get('idempotency_key') != key or stored != sorted(set(candidate_nos)):
|
||||
return None
|
||||
if any(candidate.consumed_task_id is None for candidate in candidates):
|
||||
return None
|
||||
pairs = [
|
||||
(candidate, db.session.get(ShippingTask, int(candidate.consumed_task_id)))
|
||||
for candidate in candidates
|
||||
]
|
||||
pairs = [
|
||||
(candidate, task)
|
||||
for candidate, task in pairs
|
||||
if task is not None and int(task.user_id or 0) == int(user_id)
|
||||
]
|
||||
created_pairs = [
|
||||
(candidate, task)
|
||||
for candidate, task in pairs
|
||||
if str(candidate.duplicate_resolution or '').strip().lower() != 'open_existing'
|
||||
]
|
||||
opened_pairs = [
|
||||
(candidate, task)
|
||||
for candidate, task in pairs
|
||||
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing'
|
||||
]
|
||||
batch_ids = {int(task.batch_id) for _, task in created_pairs if task.batch_id is not None}
|
||||
if len(batch_ids) == 1:
|
||||
batch = db.session.get(ShippingBatch, next(iter(batch_ids)))
|
||||
if batch is not None:
|
||||
result = build_existing_batch_tool_response(batch, user_id=user_id)
|
||||
result['idempotent_replay'] = True
|
||||
if opened_pairs:
|
||||
result['opened_existing'] = [
|
||||
{'candidate_no': candidate.candidate_no, 'task_no': task.task_no, 'batch_no': None}
|
||||
for candidate, task in opened_pairs
|
||||
]
|
||||
return result
|
||||
opened = [
|
||||
{'candidate_no': candidate.candidate_no, 'task_no': task.task_no, 'batch_no': None}
|
||||
for candidate, task in opened_pairs
|
||||
]
|
||||
return {
|
||||
'status': 'ok',
|
||||
'batch_no': None,
|
||||
'idempotent_replay': True,
|
||||
'opened_existing': opened,
|
||||
'message': '已打开已有任务,未创建新批次',
|
||||
'data': {
|
||||
'opened_existing': opened,
|
||||
'focus_task': {'task_no': opened_pairs[0][1].task_no} if opened_pairs else None,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def create_shipping_batch_from_candidates(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str | None,
|
||||
intake_nos: list[str],
|
||||
candidate_nos: list[str],
|
||||
create_idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
从一封或多封 Intake 中选中的订单 Candidate 创建批次。
|
||||
|
||||
核心逻辑:锁定 Intake/Candidate → 逐候选验证与判重门禁 → open_existing 分流 →
|
||||
新候选一次建批 → 按 source_candidate_id 回填消费关系;同一 Intake 尚有待处理订单时保留为部分完成。
|
||||
"""
|
||||
intake_rows = (
|
||||
db.session.query(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(intake_nos),
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
intakes = [row[0] for row in intake_rows]
|
||||
assets = {int(row[0].id): row[1] for row in intake_rows}
|
||||
if {item.intake_no for item in intakes} != set(intake_nos):
|
||||
raise ValidationError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分接入记录不存在')
|
||||
candidates = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.candidate_no.in_(candidate_nos),
|
||||
ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]),
|
||||
)
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if {item.candidate_no for item in candidates} != set(candidate_nos):
|
||||
raise ValidationError(code='SHIPPING_NOTICE.CANDIDATE_NOT_FOUND', message='部分订单候选不存在')
|
||||
replay = _candidate_replay(
|
||||
user_id=user_id,
|
||||
intakes=intakes,
|
||||
candidates=candidates,
|
||||
candidate_nos=candidate_nos,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
selected_rows = (
|
||||
db.session.query(ShippingNoticeCandidate.candidate_no)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.intake_id.in_([int(item.id) for item in intakes]),
|
||||
ShippingNoticeCandidate.selected.is_(True),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
selected_nos = {str(row[0]).strip().upper() for row in selected_rows}
|
||||
if selected_nos != set(candidate_nos):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_SELECTION_CHANGED',
|
||||
message='订单候选选择状态已变化,请刷新后重试',
|
||||
details={'expected': sorted(selected_nos), 'actual': sorted(set(candidate_nos))},
|
||||
)
|
||||
intake_by_id = {int(item.id): item for item in intakes}
|
||||
opened: list[dict[str, Any]] = []
|
||||
create_items: list[dict[str, Any]] = []
|
||||
create_candidates: list[ShippingNoticeCandidate] = []
|
||||
now = datetime.utcnow()
|
||||
for candidate in candidates:
|
||||
intake = intake_by_id[int(candidate.intake_id)]
|
||||
if intake.parse_status != 'parsed' or intake.consumed_at is not None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS', message='接入状态不允许建单')
|
||||
structured_intake = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else None
|
||||
if is_attachment_parse_incomplete(structured_intake):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
|
||||
message='发货通知附件解析不完整,请重试解析或移除后重新上传',
|
||||
)
|
||||
if intake.expires_at and intake.expires_at < now:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期')
|
||||
if not candidate.selected:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中')
|
||||
if candidate.consumed_task_id is not None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='订单候选仍有字段冲突或未完成审核',
|
||||
details={'candidate_no': candidate.candidate_no, 'conflicts': list(candidate.conflicts_json or [])},
|
||||
)
|
||||
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
|
||||
if document is None or document.parse_status != 'parsed':
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DOCUMENT_INVALID', message='订单候选主附件不可用')
|
||||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||||
summary = normalize_candidate_business_summary(
|
||||
structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else None
|
||||
)
|
||||
if summary != structured.get('business_summary'):
|
||||
structured = dict(structured)
|
||||
structured['business_summary'] = summary
|
||||
candidate.structured_result_json = structured
|
||||
candidate.po_number = str(summary.get('po_number') or '').strip() or None
|
||||
child_asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else assets[int(intake.id)]
|
||||
fresh = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
asset=child_asset,
|
||||
document=document,
|
||||
business_summary=summary,
|
||||
)
|
||||
resolution = str(candidate.duplicate_resolution or '').strip().lower()
|
||||
apply_duplicate_result_to_candidate(candidate, fresh, clear_resolution=False)
|
||||
if fresh.get('blocking') and not resolution:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.DUPLICATE_RESOLUTION_REQUIRED',
|
||||
message='订单候选存在重复,请先选择处理方式',
|
||||
details={'candidate_no': candidate.candidate_no, 'duplicate': fresh},
|
||||
)
|
||||
if resolution and resolution not in set(fresh.get('allowed_actions') or []):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.DUPLICATE_ACTION_UNAVAILABLE',
|
||||
message='重复目标状态已变化,原处理方式不再可用',
|
||||
details={'candidate_no': candidate.candidate_no, 'duplicate': fresh},
|
||||
)
|
||||
target_no = str(candidate.duplicate_target_task_no or '').strip().upper()
|
||||
matches = list(fresh.get('matches') or [])
|
||||
if resolution and (
|
||||
not target_no or not any(str(item.get('task_no') or '').upper() == target_no for item in matches)
|
||||
):
|
||||
raise ConflictError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_CHANGED', message='重复目标已变化,请重新确认')
|
||||
if resolution == 'force_create':
|
||||
from app.models import User
|
||||
from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate
|
||||
|
||||
user = db.session.get(User, int(user_id))
|
||||
if not can_force_create_shipping_duplicate(user):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.DUPLICATE_OVERRIDE_FORBIDDEN',
|
||||
message='强制新建权限已变化,请重新确认',
|
||||
)
|
||||
if not str(candidate.duplicate_resolution_reason or '').strip():
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.DUPLICATE_REASON_REQUIRED',
|
||||
message='强制新建必须填写原因',
|
||||
)
|
||||
if resolution == 'open_existing':
|
||||
target = db.session.query(ShippingTask).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
||||
if target is None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在')
|
||||
candidate.consumed_task_id = int(target.id)
|
||||
candidate.updated_at = now
|
||||
opened.append({'candidate_no': candidate.candidate_no, 'task_no': target.task_no, 'batch_no': None})
|
||||
continue
|
||||
create_items.append(candidate_to_notice_item(candidate, intake, document))
|
||||
create_candidates.append(candidate)
|
||||
|
||||
_stamp_candidate_request(
|
||||
intakes,
|
||||
candidate_nos=candidate_nos,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
)
|
||||
result: dict[str, Any]
|
||||
batch_obj: ShippingBatch | None = None
|
||||
if create_items:
|
||||
result = create_shipping_batch_from_notice_items(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
notice_items=create_items,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
defer_commit=True,
|
||||
start_orchestrator=False,
|
||||
)
|
||||
batch_no = str(result.get('batch_no') or '').strip()
|
||||
batch_obj = db.session.query(ShippingBatch).filter_by(batch_no=batch_no, user_id=int(user_id)).first()
|
||||
if batch_obj is None:
|
||||
raise ConflictError(code='SHIPPING.BATCH_CREATE_INCOMPLETE', message='候选批次创建结果不完整')
|
||||
tasks = db.session.query(ShippingTask).filter_by(batch_id=int(batch_obj.id)).all()
|
||||
task_by_candidate = {int(task.source_candidate_id): task for task in tasks if task.source_candidate_id}
|
||||
for candidate in create_candidates:
|
||||
task = task_by_candidate.get(int(candidate.id))
|
||||
if task is None:
|
||||
raise ConflictError(code='SHIPPING.BATCH_CREATE_INCOMPLETE', message='候选任务关联不完整')
|
||||
candidate.consumed_task_id = int(task.id)
|
||||
candidate.updated_at = now
|
||||
_attach_request_intake_summary(
|
||||
batch_obj,
|
||||
request_intake_nos=intake_nos,
|
||||
open_existing_intake_nos=[],
|
||||
)
|
||||
batch_summary = dict(batch_obj.process_summary_json or {})
|
||||
batch_summary['request_candidate_nos'] = sorted(set(candidate_nos))
|
||||
batch_obj.process_summary_json = batch_summary
|
||||
flag_modified(batch_obj, 'process_summary_json')
|
||||
else:
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'batch_no': None,
|
||||
'idempotent_replay': False,
|
||||
'message': '已打开已有任务,未创建新批次',
|
||||
'data': {'opened_existing': opened},
|
||||
}
|
||||
|
||||
for intake in intakes:
|
||||
remaining_count = db.session.query(ShippingNoticeCandidate.id).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
).count()
|
||||
extraction_incomplete = intake.order_extraction_status == 'partially_completed'
|
||||
if remaining_count or extraction_incomplete:
|
||||
intake.parse_status = 'parsed'
|
||||
intake.consumed_at = None
|
||||
intake.order_extraction_status = 'partially_completed'
|
||||
else:
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = now
|
||||
intake.order_extraction_status = 'completed'
|
||||
if batch_obj is not None and intake.consumed_batch_id is None:
|
||||
intake.consumed_batch_id = int(batch_obj.id)
|
||||
intake.consumed_task_id = None
|
||||
intake.updated_at = now
|
||||
if not remaining_count:
|
||||
parent_asset = assets[int(intake.id)]
|
||||
from app.services.file_assets.service import mark_asset_referenced
|
||||
mark_asset_referenced(parent_asset)
|
||||
db.session.commit()
|
||||
|
||||
if batch_obj is not None:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
started = start_batch_orchestrator(batch_obj.batch_no)
|
||||
data = result.get('data') if isinstance(result.get('data'), dict) else {}
|
||||
data['orchestrator_started'] = started
|
||||
result['data'] = data
|
||||
if opened:
|
||||
result['opened_existing'] = opened
|
||||
return result
|
||||
|
||||
|
||||
def create_shipping_batch_from_intakes(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str | None,
|
||||
intake_nos: list[str],
|
||||
candidate_nos: list[str] | None = None,
|
||||
create_idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -434,6 +779,72 @@ def create_shipping_batch_from_intakes(
|
||||
normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
|
||||
if not normalized:
|
||||
raise ValidationError('intake_nos is required')
|
||||
normalized_candidates = [
|
||||
str(item or '').strip().upper() for item in (candidate_nos or []) if str(item or '').strip()
|
||||
]
|
||||
if candidate_nos is not None and not normalized_candidates:
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED',
|
||||
message='至少选择一个订单候选',
|
||||
)
|
||||
if normalized_candidates:
|
||||
return create_shipping_batch_from_candidates(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=normalized,
|
||||
candidate_nos=normalized_candidates,
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
)
|
||||
|
||||
all_candidate_rows = (
|
||||
db.session.query(ShippingNoticeCandidate.candidate_no)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeCandidate.intake_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
candidate_rows = (
|
||||
db.session.query(ShippingNoticeCandidate.candidate_no)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeCandidate.intake_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
ShippingNoticeCandidate.selected.is_(True),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
if candidate_rows:
|
||||
return create_shipping_batch_from_candidates(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=normalized,
|
||||
candidate_nos=[str(row[0]).strip().upper() for row in candidate_rows],
|
||||
create_idempotency_key=create_idempotency_key,
|
||||
)
|
||||
if all_candidate_rows:
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED',
|
||||
message='至少选择一个订单候选',
|
||||
)
|
||||
parser_versions = (
|
||||
db.session.query(ShippingNoticeIntake.parser_version)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if any(str(row[0] or '').strip().lower() == 'v6' for row in parser_versions):
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='未识别到可建单的订单候选,请检查附件内容或重新解析',
|
||||
)
|
||||
|
||||
# [STEP 1] 幂等重放优先
|
||||
replay = _try_idempotent_replay(
|
||||
|
||||
@@ -14,9 +14,10 @@ from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import normalize_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
FINGERPRINT_VERSION = 'shipping-v1'
|
||||
CONTENT_FINGERPRINT_VERSION = 'shipping-content-v2'
|
||||
|
||||
|
||||
def _norm_text(value: Any) -> str:
|
||||
@@ -38,7 +39,7 @@ def _line_digest(lines: list[dict[str, Any]]) -> str:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
sku = _norm_text(line.get('sku'))
|
||||
rid = normalize_reservation_id(str(line.get('reservation_id') or '')) or ''
|
||||
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:
|
||||
continue
|
||||
@@ -87,7 +88,7 @@ def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[
|
||||
po_number = normalize_po_number(str(summary.get('po_number') or '')) or ''
|
||||
reservation_ids = sorted(
|
||||
{
|
||||
normalize_reservation_id(str(item)) or ''
|
||||
validated_reservation_id(str(item)) or ''
|
||||
for item in (summary.get('reservation_ids') or [])
|
||||
if str(item or '').strip()
|
||||
}
|
||||
@@ -171,3 +172,71 @@ def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[
|
||||
'strength': strength,
|
||||
'components': components,
|
||||
}
|
||||
|
||||
|
||||
def build_content_fingerprint(business_summary: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
生成订单内容版本指纹,用于区分完全重复与同一订单修订。
|
||||
|
||||
核心逻辑:标准化并排序订单行,纳入 Reservation、SKU、数量、单位、交期及邮件分配字段;
|
||||
单头目的地和 PO 仅用于增强内容比较,不替代身份指纹。
|
||||
Args:
|
||||
business_summary: Candidate 融合后的业务摘要。
|
||||
Returns:
|
||||
包含 fingerprint、version 和 components 的字典;无有效订单行时 fingerprint 为空。
|
||||
"""
|
||||
summary = business_summary if isinstance(business_summary, dict) else {}
|
||||
parts: list[str] = []
|
||||
for line in summary.get('lines') or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
values = [
|
||||
_norm_text(line.get('line_no')),
|
||||
validated_reservation_id(line.get('reservation_id')) or '',
|
||||
_norm_text(line.get('sku')),
|
||||
_norm_qty(line.get('qty')),
|
||||
_norm_text(line.get('uom')),
|
||||
_norm_qty(line.get('unit_price')),
|
||||
_norm_qty(line.get('amount')),
|
||||
_norm_text(line.get('currency')),
|
||||
_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('hub_code')),
|
||||
]
|
||||
if any(values):
|
||||
parts.append('|'.join(values))
|
||||
if not parts:
|
||||
return {
|
||||
'fingerprint': None,
|
||||
'version': CONTENT_FINGERPRINT_VERSION,
|
||||
'components': {},
|
||||
}
|
||||
parts.sort()
|
||||
destination = summary.get('destination') if isinstance(summary.get('destination'), dict) else {}
|
||||
components = {
|
||||
'po_number': normalize_po_number(summary.get('po_number')) or None,
|
||||
'destination': '|'.join(
|
||||
_norm_text(destination.get(key)) for key in ('code', 'city', 'country')
|
||||
).strip('|') or None,
|
||||
'ship_to': _norm_text(summary.get('ship_to')) or None,
|
||||
'required_date': _norm_text(summary.get('required_date')) or None,
|
||||
'warehouse_hint': _norm_text(summary.get('warehouse_hint')) or None,
|
||||
'lines': parts,
|
||||
}
|
||||
digest = hashlib.sha256(
|
||||
json.dumps(
|
||||
{'version': CONTENT_FINGERPRINT_VERSION, 'components': components},
|
||||
ensure_ascii=False,
|
||||
sort_keys=True,
|
||||
separators=(',', ':'),
|
||||
).encode('utf-8')
|
||||
).hexdigest()
|
||||
return {
|
||||
'fingerprint': digest,
|
||||
'version': CONTENT_FINGERPRINT_VERSION,
|
||||
'components': components,
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/candidate_service.py
|
||||
|
||||
用途:提供订单候选的用户态查询、修订、选择与重复决策能力。
|
||||
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import FileAsset, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, User
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
|
||||
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
|
||||
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
|
||||
from app.services.shipping_notice.duplicate_detection import apply_duplicate_result_to_candidate, detect_duplicates_for_candidate
|
||||
from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate
|
||||
|
||||
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
||||
|
||||
|
||||
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
|
||||
"""按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。"""
|
||||
query = (
|
||||
db.session.query(ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeCandidate.intake_id)
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingNoticeCandidate.primary_document_id)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.candidate_no == str(candidate_no or '').strip().upper(),
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
)
|
||||
)
|
||||
if lock:
|
||||
query = query.with_for_update()
|
||||
row = query.first()
|
||||
if row is None:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.CANDIDATE_NOT_FOUND', message='订单候选不存在')
|
||||
return row
|
||||
|
||||
|
||||
def _refresh_candidate(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake, document: ShippingNoticeDocument) -> dict[str, Any]:
|
||||
"""重算 Candidate 双指纹和重复状态,不提交事务。"""
|
||||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||||
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
||||
identity = build_business_fingerprint(summary)
|
||||
content = build_content_fingerprint(summary)
|
||||
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
||||
result = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
asset=asset,
|
||||
document=document,
|
||||
business_summary=summary,
|
||||
fingerprint_result=identity,
|
||||
content_fingerprint_result=content,
|
||||
)
|
||||
candidate.business_fingerprint = identity.get('fingerprint')
|
||||
candidate.fingerprint_version = identity.get('version')
|
||||
candidate.fingerprint_strength = identity.get('strength')
|
||||
candidate.content_fingerprint = content.get('fingerprint')
|
||||
candidate.content_fingerprint_version = content.get('version')
|
||||
apply_duplicate_result_to_candidate(candidate, result)
|
||||
return result
|
||||
|
||||
|
||||
def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None = None, business_summary: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
更新候选选择状态或人工修订后的业务摘要。
|
||||
|
||||
核心逻辑:已消费候选禁止修改;摘要变化时清除冲突、置 ready 并重算双指纹与判重。
|
||||
"""
|
||||
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
||||
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
if selected is not None:
|
||||
if not isinstance(selected, bool):
|
||||
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值')
|
||||
candidate.selected = selected
|
||||
if business_summary is not None:
|
||||
if not isinstance(business_summary, dict):
|
||||
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象')
|
||||
normalized_summary = normalize_candidate_business_summary(business_summary)
|
||||
structured = dict(candidate.structured_result_json or {})
|
||||
structured['business_summary'] = normalized_summary
|
||||
structured['manual_edited'] = True
|
||||
candidate.structured_result_json = structured
|
||||
candidate.po_number = str(normalized_summary.get('po_number') or '').strip() or None
|
||||
candidate.conflicts_json = []
|
||||
candidate.validation_status = 'ready'
|
||||
_refresh_candidate(candidate, intake, document)
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _serialize_candidate_brief(candidate)
|
||||
|
||||
|
||||
def refresh_candidate_duplicate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
|
||||
"""刷新单个 Candidate 的重复检测结果并清除陈旧决策。"""
|
||||
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
||||
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
_refresh_candidate(candidate, intake, document)
|
||||
db.session.commit()
|
||||
return _serialize_candidate_brief(candidate)
|
||||
|
||||
|
||||
def resolve_candidate_duplicate(*, user_id: int, candidate_no: str, action: str, target_task_no: str | None = None, reason: str | None = None, actor: User | None = None) -> dict[str, Any]:
|
||||
"""保存单个 Candidate 的重复处理决策,并校验目标、权限及强制原因。"""
|
||||
action_norm = str(action or '').strip().lower()
|
||||
if action_norm not in _ACTIONS:
|
||||
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='无效的重复处理动作')
|
||||
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
||||
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
result = _refresh_candidate(candidate, intake, document)
|
||||
if action_norm not in set(result.get('allowed_actions') or []):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.DUPLICATE_ACTION_UNAVAILABLE',
|
||||
message='当前重复状态不允许该处理方式',
|
||||
)
|
||||
matches = list(result.get('matches') or [])
|
||||
target_no = str(target_task_no or '').strip().upper() or (
|
||||
str(matches[0].get('task_no') or '').strip().upper() if matches else ''
|
||||
)
|
||||
if not target_no or not any(str(item.get('task_no') or '').upper() == target_no for item in matches):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在或已变化')
|
||||
target = db.session.query(ShippingTask).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
||||
if target is None:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在')
|
||||
if action_norm == 'force_create':
|
||||
user = actor or db.session.get(User, int(user_id))
|
||||
if not can_force_create_shipping_duplicate(user):
|
||||
raise ForbiddenError(code='SHIPPING_NOTICE.DUPLICATE_OVERRIDE_FORBIDDEN', message='无权强制新建重复订单')
|
||||
if not str(reason or '').strip():
|
||||
raise ValidationError(code='SHIPPING_NOTICE.DUPLICATE_REASON_REQUIRED', message='强制新建必须填写原因')
|
||||
candidate.duplicate_resolution = action_norm
|
||||
candidate.duplicate_target_task_no = target_no
|
||||
candidate.duplicate_resolution_reason = str(reason or '').strip() or None
|
||||
candidate.duplicate_resolved_by_id = int(user_id)
|
||||
candidate.duplicate_resolved_at = datetime.utcnow()
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _serialize_candidate_brief(candidate)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/candidate_validation.py
|
||||
|
||||
用途:统一校验并标准化人工修订或建批前的订单 Candidate 业务摘要。
|
||||
依赖:notice_lines、po_number、reservation_id、core.errors。
|
||||
逻辑:Candidate API 与建批门禁共用,确保至少一条 SKU+Qty 有效订单行,避免空摘要绕过审核。
|
||||
"""
|
||||
|
||||
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.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
BUILD_REQUIRED_FIELDS = ('sku', 'qty')
|
||||
PROCESS_FIELDS = ('reservation_id', 'hub_code', 'source_type')
|
||||
|
||||
|
||||
def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
评估规则/LLM订单结果是否达到自动建单最低条件,同时保留不完整内容供自然对话修订。
|
||||
|
||||
核心逻辑:SKU + 正数 Qty 是建单硬条件;Reservation/Hub/Source Type 属于流程字段,
|
||||
缺失或格式异常时允许创建 Task,但必须进入后续字段补充门禁。
|
||||
|
||||
Args:
|
||||
summary: 单个订单的业务摘要。
|
||||
|
||||
Returns:
|
||||
包含 normalized_summary、can_create_task、missing_required_fields、
|
||||
missing_process_fields、invalid_lines 与 blocking_issues 的评估结果。
|
||||
"""
|
||||
raw = dict(summary) if isinstance(summary, dict) else {}
|
||||
raw_lines = raw.get('lines') if isinstance(raw.get('lines'), list) else []
|
||||
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)
|
||||
if normalized is None:
|
||||
invalid_lines.append({'line_index': index, 'reason': 'missing_sku_or_positive_qty'})
|
||||
continue
|
||||
raw_reservation = str(normalized.get('reservation_id') or '').strip()
|
||||
if raw_reservation and not validated_reservation_id(raw_reservation):
|
||||
invalid_lines.append({'line_index': index, 'reason': 'invalid_reservation_id'})
|
||||
continue
|
||||
normalized_lines.append(normalized)
|
||||
|
||||
normalized_summary = dict(raw)
|
||||
normalized_summary['lines'] = normalized_lines
|
||||
normalized_summary['po_number'] = normalize_po_number(raw.get('po_number')) or None
|
||||
normalized_summary['reservation_ids'] = sorted({
|
||||
normalized
|
||||
for line in normalized_lines
|
||||
if (normalized := validated_reservation_id(line.get('reservation_id')))
|
||||
})
|
||||
|
||||
missing_required: list[str] = []
|
||||
if not normalized_lines:
|
||||
missing_required.extend(BUILD_REQUIRED_FIELDS)
|
||||
missing_process = [
|
||||
field
|
||||
for field in PROCESS_FIELDS
|
||||
if not any(str(line.get(field) or '').strip() for line in normalized_lines)
|
||||
]
|
||||
blocking = [
|
||||
{'code': 'invalid_order_line', **item}
|
||||
for item in invalid_lines
|
||||
]
|
||||
return {
|
||||
'normalized_summary': normalized_summary,
|
||||
'can_create_task': bool(normalized_lines) and not invalid_lines,
|
||||
'can_auto_progress': bool(normalized_lines) and not invalid_lines and not missing_process,
|
||||
'missing_required_fields': sorted(set(missing_required)),
|
||||
'missing_process_fields': missing_process,
|
||||
'invalid_lines': invalid_lines,
|
||||
'process_issues': [],
|
||||
'blocking_issues': blocking,
|
||||
}
|
||||
|
||||
|
||||
def normalize_candidate_business_summary(summary: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
标准化并验证 Candidate 业务摘要。
|
||||
|
||||
核心逻辑:逐行严格校验 SKU 与正数 Qty;任何脏行都会阻断,不静默丢弃;
|
||||
同步标准 PO 与 Reservation 集合,同时保留未知单头字段供后续业务扩展。
|
||||
Args:
|
||||
summary: 前端人工修订或数据库中的 Candidate 业务摘要。
|
||||
Returns:
|
||||
可安全用于双指纹和建单的标准业务摘要副本。
|
||||
Raises:
|
||||
ValidationError: 摘要不是对象、没有订单行或任一订单行无效。
|
||||
"""
|
||||
if not isinstance(summary, dict):
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='订单候选摘要必须为对象',
|
||||
)
|
||||
assessment = assess_candidate_business_summary(summary)
|
||||
raw_lines = summary.get('lines')
|
||||
if not isinstance(raw_lines, list) or not raw_lines:
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='订单候选至少需要一条包含 SKU 与数量的订单行',
|
||||
)
|
||||
|
||||
if assessment['invalid_lines']:
|
||||
first = assessment['invalid_lines'][0]
|
||||
reason = str(first.get('reason') or '')
|
||||
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 或数量"
|
||||
)
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message=message,
|
||||
details={'line_index': first.get('line_index'), 'reason': reason},
|
||||
)
|
||||
return assessment['normalized_summary']
|
||||
@@ -169,6 +169,9 @@ class ShippingCreateBatchFromIntakesAction:
|
||||
or None
|
||||
)
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
candidate_nos = payload.get("candidate_nos")
|
||||
if candidate_nos is not None and not isinstance(candidate_nos, list):
|
||||
raise ValidationError("candidate_nos must be a list")
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_intakes", "label": "确认建单..."})
|
||||
|
||||
@@ -179,6 +182,7 @@ class ShippingCreateBatchFromIntakesAction:
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
candidate_nos=[str(item) for item in candidate_nos] if isinstance(candidate_nos, list) else None,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
opened = result.get("opened_existing") if isinstance(result.get("opened_existing"), list) else []
|
||||
@@ -209,7 +213,7 @@ class ShippingCreateBatchFromIntakesAction:
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
|
||||
file_count = len(intake_nos)
|
||||
file_count = len(candidate_nos) if isinstance(candidate_nos, list) and candidate_nos else len(intake_nos)
|
||||
content = format_batch_created_assistant_message(result, file_count=file_count)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
|
||||
@@ -28,7 +28,7 @@ def build_shipping_notice_context_adapter(
|
||||
"""
|
||||
构建发货通知 Dify Start inputs。
|
||||
|
||||
核心逻辑:从 adapter_hints.shipping_notice 读取 task_id/batch_no,委托 dify_inputs 组装 runtime_context。
|
||||
核心逻辑:从 adapter_hints.shipping_notice 读取 task/batch 或待抽取 Intake 集合,委托 dify_inputs 组装 runtime_context。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。
|
||||
@@ -50,4 +50,7 @@ def build_shipping_notice_context_adapter(
|
||||
trigger_source=trigger_source,
|
||||
request_id=request_id,
|
||||
locale=locale,
|
||||
intake_nos=shipping_hints.get('intake_nos'),
|
||||
capability=shipping_hints.get('capability'),
|
||||
contract_version=shipping_hints.get('contract_version'),
|
||||
)
|
||||
@@ -170,6 +170,26 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
and not match_completed(task)
|
||||
)
|
||||
):
|
||||
parse_validation = (
|
||||
(task.step_payload_json or {}).get("parse_validation")
|
||||
if isinstance(task.step_payload_json, dict)
|
||||
else None
|
||||
)
|
||||
blocking_issues = [
|
||||
item
|
||||
for item in (parse_validation.get("issues") if isinstance(parse_validation, dict) else []) or []
|
||||
if isinstance(item, dict) and item.get("severity") == "blocking"
|
||||
]
|
||||
if blocking_issues:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="解析结果仍包含不合法的关键字段,请修正后再确认。",
|
||||
data={**serialize_task_for_tool(task), "parse_validation": parse_validation},
|
||||
checkpoint=task.review_status or "parse_review",
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF
|
||||
# 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。
|
||||
if (
|
||||
|
||||
@@ -68,6 +68,9 @@ def build_dify_chat_inputs(
|
||||
trigger_source: str | None = None,
|
||||
request_id: str | None = None,
|
||||
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。
|
||||
@@ -108,7 +111,14 @@ def build_dify_chat_inputs(
|
||||
request_id=request_id,
|
||||
locale=locale,
|
||||
scope="task_run" if trigger_source == "backend_orchestrator" else "chat_turn",
|
||||
run_purpose="parse_notice" if trigger_source == "backend_orchestrator" else "chat_turn",
|
||||
run_purpose=(
|
||||
"parse_notice"
|
||||
if trigger_source == "backend_orchestrator"
|
||||
else ("order_extraction" if intake_nos else "chat_turn")
|
||||
),
|
||||
intake_nos=intake_nos,
|
||||
capability=capability,
|
||||
contract_version=contract_version,
|
||||
)
|
||||
if not runtime_context:
|
||||
return {}
|
||||
|
||||
@@ -29,10 +29,17 @@ from app.services.file_assets.service import (
|
||||
mark_asset_referenced,
|
||||
release_asset_reference,
|
||||
)
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
build_business_fingerprint,
|
||||
build_content_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.eml_parse import pop_attachment_payload, strip_attachment_payloads
|
||||
from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
from app.services.shipping_notice.order_candidate_builder import (
|
||||
build_email_order_index,
|
||||
merge_attachment_candidate,
|
||||
)
|
||||
|
||||
BODY_ATTACHMENT_KEY = 'body'
|
||||
|
||||
@@ -193,13 +200,25 @@ def _upsert_candidate(
|
||||
document: ShippingNoticeDocument,
|
||||
business_summary: dict[str, Any],
|
||||
fingerprint: dict[str, Any],
|
||||
content_fingerprint: dict[str, Any],
|
||||
duplicate_result: dict[str, Any],
|
||||
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,
|
||||
conflicts: list[dict[str, Any]] | None = None,
|
||||
validation_status: str = 'ready',
|
||||
evidence: dict[str, Any] | None = None,
|
||||
) -> ShippingNoticeCandidate:
|
||||
"""按 Intake + candidate_key 幂等写入一个订单草稿及其抽取审计。"""
|
||||
row = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.primary_document_id == int(document.id),
|
||||
ShippingNoticeCandidate.candidate_key == str(candidate_key),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
@@ -208,14 +227,25 @@ def _upsert_candidate(
|
||||
candidate_no=generate_candidate_no(),
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=int(document.id),
|
||||
candidate_key=str(candidate_key),
|
||||
selected=True,
|
||||
validation_status='pending',
|
||||
)
|
||||
db.session.add(row)
|
||||
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 [])
|
||||
row.evidence_json = list((evidence or {}).get('items') or []) if isinstance(evidence, dict) else []
|
||||
row.po_number = str(business_summary.get('po_number') or '').strip() or None
|
||||
row.structured_result_json = {
|
||||
'business_summary': business_summary,
|
||||
'fingerprint_components': fingerprint.get('components') or {},
|
||||
'content_fingerprint_components': content_fingerprint.get('components') or {},
|
||||
'evidence': evidence or {},
|
||||
}
|
||||
row.confidence = (
|
||||
float(business_summary['confidence'])
|
||||
@@ -225,6 +255,10 @@ def _upsert_candidate(
|
||||
row.business_fingerprint = fingerprint.get('fingerprint')
|
||||
row.fingerprint_version = fingerprint.get('version')
|
||||
row.fingerprint_strength = fingerprint.get('strength')
|
||||
row.content_fingerprint = content_fingerprint.get('fingerprint')
|
||||
row.content_fingerprint_version = content_fingerprint.get('version')
|
||||
row.validation_status = validation_status
|
||||
row.conflicts_json = list(conflicts or [])
|
||||
row.duplicate_status = str(duplicate_result.get('status') or 'none')
|
||||
row.duplicate_matches_json = list(duplicate_result.get('matches') or [])
|
||||
row.duplicate_checked_at = datetime.utcnow()
|
||||
@@ -232,6 +266,8 @@ def _upsert_candidate(
|
||||
row.duplicate_resolution = None
|
||||
row.duplicate_resolution_reason = None
|
||||
row.duplicate_target_task_no = None
|
||||
row.duplicate_resolved_by_id = None
|
||||
row.duplicate_resolved_at = None
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
return row
|
||||
@@ -259,6 +295,9 @@ def _serialize_document_brief(doc: ShippingNoticeDocument, *, include_text: bool
|
||||
|
||||
|
||||
def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
"""序列化 Candidate 审核摘要,并保持 duplicate 契约与 Intake 一致。"""
|
||||
from app.services.shipping_notice.duplicate_detection import _allowed_actions_for
|
||||
|
||||
matches = list(cand.duplicate_matches_json or [])
|
||||
status = str(cand.duplicate_status or 'unchecked')
|
||||
blocking = status in {
|
||||
@@ -266,6 +305,8 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
'same_active_task',
|
||||
'same_completed_task',
|
||||
'possible_duplicate',
|
||||
'same_business_content',
|
||||
'possible_revision',
|
||||
}
|
||||
strength = str(cand.fingerprint_strength or 'unavailable')
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
@@ -273,9 +314,11 @@ 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')
|
||||
document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id))
|
||||
return {
|
||||
'candidate_no': cand.candidate_no,
|
||||
'primary_document_id': cand.primary_document_id,
|
||||
'primary_document_filename': document.filename if document else None,
|
||||
'po_number': cand.po_number,
|
||||
'confidence': cand.confidence,
|
||||
'validation_status': cand.validation_status,
|
||||
@@ -283,12 +326,27 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
'business_fingerprint': cand.business_fingerprint,
|
||||
'fingerprint_strength': cand.fingerprint_strength,
|
||||
'fingerprint_version': cand.fingerprint_version,
|
||||
'content_fingerprint': cand.content_fingerprint,
|
||||
'content_fingerprint_version': cand.content_fingerprint_version,
|
||||
'conflicts': list(cand.conflicts_json or []),
|
||||
'duplicate': {
|
||||
'status': status,
|
||||
'blocking': blocking,
|
||||
'fingerprint_strength': strength,
|
||||
'matches': matches,
|
||||
'allowed_actions': _allowed_actions_for(
|
||||
status=status,
|
||||
fingerprint_strength=strength,
|
||||
matches=matches,
|
||||
),
|
||||
},
|
||||
'duplicate_resolution': cand.duplicate_resolution,
|
||||
'duplicate_resolution': {
|
||||
'action': cand.duplicate_resolution,
|
||||
'target_task_no': cand.duplicate_target_task_no,
|
||||
'reason': cand.duplicate_resolution_reason,
|
||||
} if cand.duplicate_resolution else None,
|
||||
'duplicate_resolved_by_id': cand.duplicate_resolved_by_id,
|
||||
'duplicate_resolved_at': cand.duplicate_resolved_at.isoformat() if cand.duplicate_resolved_at else None,
|
||||
'business_summary': summary,
|
||||
'consumed_task_id': cand.consumed_task_id,
|
||||
}
|
||||
@@ -335,15 +393,17 @@ def persist_documents_and_candidates(
|
||||
result: NoticeIntakeResult,
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
run_duplicate_detection: bool = True,
|
||||
create_candidates: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
从一次解析结果落派生资产 + Document + Candidate(仅 flush,由调用方统一 commit)。
|
||||
从一次解析结果落派生资产、Document,并可选生成规则 Candidate。
|
||||
|
||||
核心逻辑:
|
||||
1. 正文 Document(email_context,永不生成 Candidate);
|
||||
2. 附件 → 幂等派生 FileAsset → Document;仅真实订单信号生成 Candidate;
|
||||
3. 清理本轮无效 Document 与失效 Candidate;释放孤立派生资产引用;
|
||||
4. 剥离 `_payload_bytes`。
|
||||
create_candidates=False 用于上传预处理,只落 Document 并清理未消费旧 Candidate;
|
||||
run_duplicate_detection=False 时 Candidate 仅落基础行(duplicate=unchecked),
|
||||
供调用方在 SAVEPOINT 内再跑重复检测,避免检测 DB 异常连带回滚阶段二。
|
||||
|
||||
@@ -355,6 +415,7 @@ def persist_documents_and_candidates(
|
||||
meta = result.meta if isinstance(result.meta, dict) else {}
|
||||
email_meta = meta.get('email') if isinstance(meta.get('email'), dict) else {}
|
||||
body_text = str(email_meta.get('body_text') or '')
|
||||
body_order_rows = build_email_order_index(body_text)
|
||||
is_eml = str(meta.get('file_type') or '').lower() == 'eml' or bool(email_meta)
|
||||
|
||||
active_keys: set[str] = set()
|
||||
@@ -430,6 +491,12 @@ def persist_documents_and_candidates(
|
||||
document_type='attachment',
|
||||
),
|
||||
)
|
||||
fusion = merge_attachment_candidate(
|
||||
attachment_summary=att_summary,
|
||||
filename=str(item.get('filename') or ''),
|
||||
body_rows=body_order_rows,
|
||||
)
|
||||
att_summary = fusion['business_summary']
|
||||
classification = _classify_document(
|
||||
document_type='attachment',
|
||||
filename=str(item.get('filename') or ''),
|
||||
@@ -454,12 +521,13 @@ def persist_documents_and_candidates(
|
||||
active_keys.add(key)
|
||||
documents.append(doc)
|
||||
|
||||
if _should_create_candidate(
|
||||
if create_candidates and _should_create_candidate(
|
||||
document_type='attachment',
|
||||
classification=classification,
|
||||
parse_status=att_status,
|
||||
):
|
||||
fp = build_business_fingerprint(att_summary)
|
||||
content_fp = build_content_fingerprint(att_summary)
|
||||
if run_duplicate_detection:
|
||||
child_asset = db.session.get(FileAsset, int(asset_id)) if asset_id else parent_asset
|
||||
dup = detect_duplicates_for_candidate(
|
||||
@@ -476,7 +544,12 @@ def persist_documents_and_candidates(
|
||||
document=doc,
|
||||
business_summary=att_summary,
|
||||
fingerprint=fp,
|
||||
content_fingerprint=content_fp,
|
||||
duplicate_result=dup,
|
||||
candidate_key=f'document:{int(doc.id)}',
|
||||
conflicts=fusion['conflicts'],
|
||||
validation_status=str(fusion['validation_status']),
|
||||
evidence=fusion['evidence'],
|
||||
)
|
||||
candidates.append(cand)
|
||||
active_candidate_doc_ids.add(int(doc.id))
|
||||
@@ -508,12 +581,13 @@ def persist_documents_and_candidates(
|
||||
)
|
||||
active_keys.add('file')
|
||||
documents.append(file_doc)
|
||||
if _should_create_candidate(
|
||||
if create_candidates and _should_create_candidate(
|
||||
document_type='attachment',
|
||||
classification=file_class,
|
||||
parse_status='parsed',
|
||||
):
|
||||
fp = build_business_fingerprint(file_summary)
|
||||
content_fp = build_content_fingerprint(file_summary)
|
||||
if run_duplicate_detection:
|
||||
dup = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
@@ -529,7 +603,12 @@ def persist_documents_and_candidates(
|
||||
document=file_doc,
|
||||
business_summary=file_summary,
|
||||
fingerprint=fp,
|
||||
content_fingerprint=content_fp,
|
||||
duplicate_result=dup,
|
||||
candidate_key=f'document:{int(file_doc.id)}',
|
||||
conflicts=[],
|
||||
validation_status='ready',
|
||||
evidence={'attachment_filename': result.filename, 'matched_by': 'single_file'},
|
||||
)
|
||||
candidates.append(cand)
|
||||
active_candidate_doc_ids.add(int(file_doc.id))
|
||||
@@ -561,7 +640,7 @@ def persist_documents_and_candidates(
|
||||
stale_cand_q = stale_cand_q.filter(
|
||||
ShippingNoticeCandidate.primary_document_id.notin_(tuple(active_candidate_doc_ids)),
|
||||
)
|
||||
stale_cand_q.delete(synchronize_session=False)
|
||||
stale_cand_q.filter(ShippingNoticeCandidate.consumed_task_id.is_(None)).delete(synchronize_session=False)
|
||||
|
||||
# [STEP 6] 剥离 payload,防止后续 structured_result 泄漏
|
||||
strip_attachment_payloads(meta)
|
||||
@@ -577,6 +656,38 @@ def persist_documents_and_candidates(
|
||||
}
|
||||
|
||||
|
||||
def persist_intake_documents(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
parent_asset: FileAsset,
|
||||
result: NoticeIntakeResult,
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
上传后仅持久化邮件正文与附件 Document,不生成订单 Candidate。
|
||||
|
||||
核心逻辑:复用附件资产化与 Document 幂等逻辑,规则摘要只用于文档分类;
|
||||
用户点击发送并由 Chatflow 返回完整 orders[] 后,才允许另一条链路生成 Candidate。
|
||||
|
||||
Args:
|
||||
intake: 当前用户的发货通知接入记录。
|
||||
parent_asset: 原始 EML/附件 FileAsset。
|
||||
result: 已完成文本提取的预解析结果。
|
||||
uploaded_storage_keys: 本轮新写入对象存储的 key,供失败补偿。
|
||||
|
||||
Returns:
|
||||
Document 与派生资产数量摘要;candidate_count 恒为 0。
|
||||
"""
|
||||
return persist_documents_and_candidates(
|
||||
intake=intake,
|
||||
parent_asset=parent_asset,
|
||||
result=result,
|
||||
uploaded_storage_keys=uploaded_storage_keys,
|
||||
run_duplicate_detection=False,
|
||||
create_candidates=False,
|
||||
)
|
||||
|
||||
|
||||
def clear_intake_stage2_structured_projection(intake: ShippingNoticeIntake) -> None:
|
||||
"""
|
||||
清理 structured_result_json 中的阶段二投影(document/candidate 计数与附件资产标识)。
|
||||
|
||||
@@ -22,7 +22,12 @@ from app.models import (
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.business_fingerprint import FINGERPRINT_VERSION, build_business_fingerprint
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
CONTENT_FINGERPRINT_VERSION,
|
||||
FINGERPRINT_VERSION,
|
||||
build_business_fingerprint,
|
||||
build_content_fingerprint,
|
||||
)
|
||||
|
||||
# 与 state_machine 主路径对齐的活跃/完成/关闭态(禁止 needs_review/matching/export_ready 等非主状态)
|
||||
_ACTIVE_PROCESS_STATUSES = frozenset(
|
||||
@@ -72,6 +77,8 @@ def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[
|
||||
'matched_fields': list(matched_fields),
|
||||
'lifecycle': classify_task_lifecycle(task.process_status),
|
||||
'created_at': utc_iso(task.created_at),
|
||||
'content_fingerprint': task.content_fingerprint,
|
||||
'content_fingerprint_version': task.content_fingerprint_version,
|
||||
}
|
||||
|
||||
|
||||
@@ -99,6 +106,7 @@ def detect_duplicates_for_intake(
|
||||
asset: FileAsset | None = None,
|
||||
business_summary: dict[str, Any] | None = None,
|
||||
fingerprint_result: dict[str, Any] | None = None,
|
||||
content_fingerprint_result: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对已解析 intake 执行重复检测。
|
||||
@@ -122,6 +130,9 @@ def detect_duplicates_for_intake(
|
||||
fingerprint = fp.get('fingerprint')
|
||||
version = str(fp.get('version') or FINGERPRINT_VERSION)
|
||||
components = fp.get('components') if isinstance(fp.get('components'), dict) else {}
|
||||
content_fp = content_fingerprint_result or build_content_fingerprint(summary)
|
||||
content_fingerprint = content_fp.get('fingerprint')
|
||||
content_version = str(content_fp.get('version') or CONTENT_FINGERPRINT_VERSION)
|
||||
|
||||
if asset is None:
|
||||
asset = db.session.get(FileAsset, int(intake.asset_id))
|
||||
@@ -180,13 +191,24 @@ def detect_duplicates_for_intake(
|
||||
)
|
||||
)
|
||||
if matches and status == 'none':
|
||||
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
|
||||
if primary_life == 'active':
|
||||
status = 'same_active_task'
|
||||
elif primary_life == 'completed':
|
||||
status = 'same_completed_task'
|
||||
comparable = [
|
||||
task for task in fp_tasks
|
||||
if task.content_fingerprint and task.content_fingerprint_version == content_version
|
||||
]
|
||||
if content_fingerprint and comparable:
|
||||
status = (
|
||||
'same_business_content'
|
||||
if any(task.content_fingerprint == content_fingerprint for task in comparable)
|
||||
else 'possible_revision'
|
||||
)
|
||||
else:
|
||||
status = 'possible_duplicate'
|
||||
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
|
||||
if primary_life == 'active':
|
||||
status = 'same_active_task'
|
||||
elif primary_life == 'completed':
|
||||
status = 'same_completed_task'
|
||||
else:
|
||||
status = 'possible_duplicate'
|
||||
elif matches and status == 'exact_file':
|
||||
# 同文件命中优先;保留 status=exact_file
|
||||
pass
|
||||
@@ -315,10 +337,16 @@ def apply_duplicate_result_to_candidate(
|
||||
candidate.fingerprint_version = result.get('fingerprint_version')
|
||||
if result.get('fingerprint_strength') is not None:
|
||||
candidate.fingerprint_strength = result.get('fingerprint_strength')
|
||||
if result.get('content_fingerprint') is not None:
|
||||
candidate.content_fingerprint = result.get('content_fingerprint')
|
||||
if result.get('content_fingerprint_version') is not None:
|
||||
candidate.content_fingerprint_version = result.get('content_fingerprint_version')
|
||||
if clear_resolution:
|
||||
candidate.duplicate_resolution = None
|
||||
candidate.duplicate_resolution_reason = None
|
||||
candidate.duplicate_target_task_no = None
|
||||
candidate.duplicate_resolved_by_id = None
|
||||
candidate.duplicate_resolved_at = None
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
@@ -351,11 +379,13 @@ def refresh_candidates_and_aggregate_intake(
|
||||
)
|
||||
summary = summary if isinstance(summary, dict) else {}
|
||||
fingerprint = build_business_fingerprint(summary)
|
||||
content_fingerprint = build_content_fingerprint(summary)
|
||||
result = detect_duplicates_for_intake(
|
||||
intake=intake,
|
||||
asset=parent_asset,
|
||||
business_summary=summary,
|
||||
fingerprint_result=fingerprint,
|
||||
content_fingerprint_result=content_fingerprint,
|
||||
)
|
||||
apply_duplicate_result_to_intake(intake, result)
|
||||
return result
|
||||
@@ -408,6 +438,7 @@ def detect_duplicates_for_candidate(
|
||||
document: ShippingNoticeDocument | None = None,
|
||||
business_summary: dict[str, Any] | None = None,
|
||||
fingerprint_result: dict[str, Any] | None = None,
|
||||
content_fingerprint_result: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对单个订单候选执行重复检测(不写 Intake,不影响同信其它候选)。
|
||||
@@ -424,6 +455,9 @@ def detect_duplicates_for_candidate(
|
||||
fingerprint = fp.get('fingerprint')
|
||||
version = str(fp.get('version') or FINGERPRINT_VERSION)
|
||||
components = fp.get('components') if isinstance(fp.get('components'), dict) else {}
|
||||
content_fp = content_fingerprint_result or build_content_fingerprint(summary)
|
||||
content_fingerprint = content_fp.get('fingerprint')
|
||||
content_version = str(content_fp.get('version') or CONTENT_FINGERPRINT_VERSION)
|
||||
|
||||
content_hash = ''
|
||||
if document is not None and str(document.content_hash or '').strip():
|
||||
@@ -483,13 +517,24 @@ def detect_duplicates_for_candidate(
|
||||
)
|
||||
)
|
||||
if matches and status == 'none':
|
||||
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
|
||||
if primary_life == 'active':
|
||||
status = 'same_active_task'
|
||||
elif primary_life == 'completed':
|
||||
status = 'same_completed_task'
|
||||
comparable = [
|
||||
task for task in fp_tasks
|
||||
if task.content_fingerprint and task.content_fingerprint_version == content_version
|
||||
]
|
||||
if content_fingerprint and comparable:
|
||||
status = (
|
||||
'same_business_content'
|
||||
if any(task.content_fingerprint == content_fingerprint for task in comparable)
|
||||
else 'possible_revision'
|
||||
)
|
||||
else:
|
||||
status = 'possible_duplicate'
|
||||
primary_life = classify_task_lifecycle(matches[0].get('process_status'))
|
||||
if primary_life == 'active':
|
||||
status = 'same_active_task'
|
||||
elif primary_life == 'completed':
|
||||
status = 'same_completed_task'
|
||||
else:
|
||||
status = 'possible_duplicate'
|
||||
elif fingerprint and strength == 'weak' and status == 'none':
|
||||
fp_tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
@@ -519,6 +564,8 @@ def detect_duplicates_for_candidate(
|
||||
'same_active_task',
|
||||
'same_completed_task',
|
||||
'possible_duplicate',
|
||||
'same_business_content',
|
||||
'possible_revision',
|
||||
}
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
blocking = False
|
||||
@@ -530,6 +577,8 @@ def detect_duplicates_for_candidate(
|
||||
'fingerprint': fingerprint,
|
||||
'fingerprint_version': version,
|
||||
'components': components,
|
||||
'content_fingerprint': content_fingerprint,
|
||||
'content_fingerprint_version': content_version,
|
||||
'matches': matches,
|
||||
'allowed_actions': _allowed_actions_for(
|
||||
status=status,
|
||||
|
||||
@@ -17,6 +17,7 @@ from app.services.shipping_notice.notice_lines import (
|
||||
enrich_notice_with_document_currency,
|
||||
enrich_notice_with_document_required_date,
|
||||
enrich_notice_with_document_reservation,
|
||||
adjudicate_notice_lines,
|
||||
normalize_notice_lines,
|
||||
parse_notice_table_text,
|
||||
validate_notice_lines,
|
||||
@@ -38,6 +39,10 @@ def _finalize_notice_parse(
|
||||
if parse_source:
|
||||
parsed["parse_source"] = parse_source
|
||||
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
|
||||
lines, parse_issues, validation_status = adjudicate_notice_lines(lines, raw_text=raw_text)
|
||||
parsed["lines"] = lines
|
||||
parsed["parse_issues"] = parse_issues
|
||||
parsed["validation_status"] = validation_status
|
||||
warnings = validate_notice_lines(lines)
|
||||
from app.services.shipping_notice.notice_lines import notice_parse_completeness
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ from app.services.shipping_notice.query_service import (
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
|
||||
from app.services.shipping_notice.rpa import write_upload_trigger
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
max_rpa_upload_attempts,
|
||||
@@ -244,12 +244,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
order_missing = [
|
||||
{"sku": str(line.get("sku") or "").strip(), "reservation_id": str(line.get("reservation_id") or "").strip()}
|
||||
for line in (notice_lines if isinstance(notice_lines, list) else [])
|
||||
if not extract_reservation_id(line.get("reservation_id"))
|
||||
if not is_valid_reservation_id(line.get("reservation_id"))
|
||||
]
|
||||
inv_missing_count = sum(
|
||||
1
|
||||
for row in (inventory_lines or [])
|
||||
if not extract_reservation_id((row or {}).get("reservation_id"))
|
||||
if not is_valid_reservation_id((row or {}).get("reservation_id"))
|
||||
)
|
||||
if order_missing:
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
|
||||
@@ -66,6 +66,12 @@ def parse_intake_business_summary(
|
||||
'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,
|
||||
'customer_sku': str(line.get('customer_sku') or '').strip() or None,
|
||||
'vendor_part_number': str(line.get('vendor_part_number') or '').strip() or None,
|
||||
'hub_code': str(line.get('hub_code') or '').strip() or None,
|
||||
}
|
||||
for line in lines
|
||||
if isinstance(line, dict)
|
||||
|
||||
@@ -21,7 +21,13 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import FileAsset, ShippingNoticeIntake, ShippingTask
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
NoticeIntakeResult,
|
||||
@@ -596,7 +602,7 @@ def run_intake_parse(
|
||||
执行单条接入记录的预解析并更新 ORM 状态。
|
||||
|
||||
核心逻辑:抽取文本(无锁)→ FOR UPDATE Intake → 校验 parse_lease →
|
||||
同事务落阶段二基础行 + parsed;重复检测在 SAVEPOINT;失败出口持锁清理。
|
||||
同事务只落 Intake/Document 文件预处理结果;订单 Candidate、指纹和判重延后到用户点击发送后的 Chatflow 链。
|
||||
parse_lease 不匹配(超时后被新 Worker 接替)则 skipped,防止旧结果覆盖。
|
||||
|
||||
Returns:
|
||||
@@ -604,7 +610,7 @@ def run_intake_parse(
|
||||
"""
|
||||
from app.services.file_assets.service import compensate_uploaded_storage_keys
|
||||
from app.services.shipping_notice.document_candidate_persist import (
|
||||
persist_documents_and_candidates,
|
||||
persist_intake_documents,
|
||||
)
|
||||
from app.services.shipping_notice.eml_parse import strip_attachment_payloads
|
||||
|
||||
@@ -663,13 +669,12 @@ def run_intake_parse(
|
||||
persist_info: dict[str, Any] = {}
|
||||
uploaded_storage_keys: list[str] = []
|
||||
try:
|
||||
# [STEP 2] 阶段二基础落库(重复检测延后到 SAVEPOINT,避免检测异常回滚 Document/资产)
|
||||
persist_info = persist_documents_and_candidates(
|
||||
# [STEP 2] 上传阶段只完成文件预处理;禁止提前生成 Candidate 或业务判重。
|
||||
persist_info = persist_intake_documents(
|
||||
intake=locked,
|
||||
parent_asset=asset,
|
||||
result=result,
|
||||
uploaded_storage_keys=uploaded_storage_keys,
|
||||
run_duplicate_detection=False,
|
||||
)
|
||||
|
||||
tech_summary = intake_result_to_structured_summary(result)
|
||||
@@ -683,48 +688,46 @@ def run_intake_parse(
|
||||
locked.extracted_text = result.text
|
||||
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()
|
||||
|
||||
# SAVEPOINT:写业务摘要 + Candidate/Intake 重复检测;失败降级 unchecked
|
||||
from app.services.shipping_notice.duplicate_detection import (
|
||||
clear_duplicate_state_to_unchecked,
|
||||
refresh_candidates_and_aggregate_intake,
|
||||
)
|
||||
# [STEP 3] 规则结果仅作为 Chatflow 抽取提示,不代表完整订单或可建单结果。
|
||||
from app.services.shipping_notice.intake_business_parser import (
|
||||
parse_intake_business_summary,
|
||||
)
|
||||
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
business_summary = parse_intake_business_summary(
|
||||
extracted_text=str(result.text or ''),
|
||||
source_type=str(result.source_type or 'manual'),
|
||||
)
|
||||
structured = dict(locked.structured_result_json or {})
|
||||
structured['business_summary'] = business_summary
|
||||
structured['confidence'] = business_summary.get('confidence')
|
||||
structured['parse_source'] = business_summary.get('parse_source')
|
||||
locked.structured_result_json = structured
|
||||
dup = refresh_candidates_and_aggregate_intake(
|
||||
intake=locked,
|
||||
parent_asset=asset,
|
||||
)
|
||||
except Exception:
|
||||
clear_duplicate_state_to_unchecked(intake=locked)
|
||||
dup = {
|
||||
'status': 'unchecked',
|
||||
'fingerprint_strength': None,
|
||||
}
|
||||
rule_hints = parse_intake_business_summary(
|
||||
extracted_text=str(result.text or ''),
|
||||
source_type=str(result.source_type or 'manual'),
|
||||
)
|
||||
structured = dict(locked.structured_result_json or {})
|
||||
structured['rule_hints'] = rule_hints
|
||||
structured.pop('business_summary', None)
|
||||
structured.pop('confidence', None)
|
||||
structured.pop('parse_source', None)
|
||||
locked.structured_result_json = structured
|
||||
locked.business_fingerprint = None
|
||||
locked.fingerprint_version = None
|
||||
locked.fingerprint_strength = None
|
||||
locked.duplicate_status = 'unchecked'
|
||||
locked.duplicate_matches_json = []
|
||||
locked.duplicate_checked_at = None
|
||||
locked.duplicate_resolution = None
|
||||
locked.duplicate_resolution_reason = None
|
||||
locked.duplicate_target_task_no = None
|
||||
locked.duplicate_resolved_by_id = None
|
||||
locked.duplicate_resolved_at = None
|
||||
|
||||
strip_attachment_payloads(result.meta if isinstance(result.meta, dict) else {})
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'parsed',
|
||||
'intake_no': intake_no,
|
||||
'duplicate_status': dup.get('status'),
|
||||
'fingerprint_strength': dup.get('fingerprint_strength'),
|
||||
'order_extraction_status': 'not_started',
|
||||
'document_count': persist_info.get('document_count'),
|
||||
'candidate_count': persist_info.get('candidate_count'),
|
||||
'candidate_count': 0,
|
||||
}
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
@@ -821,3 +824,68 @@ def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dic
|
||||
item['duplicate_override_reason'] = intake.duplicate_resolution_reason
|
||||
item['duplicate_resolution_type'] = 'force_create'
|
||||
return item
|
||||
|
||||
|
||||
def candidate_to_notice_item(
|
||||
candidate: ShippingNoticeCandidate,
|
||||
intake: ShippingNoticeIntake,
|
||||
document: ShippingNoticeDocument,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将已审核 Candidate 转换为独立 notice_item。
|
||||
|
||||
核心逻辑:主附件资产/哈希作为 Task 来源;Candidate 双指纹和重复决策随任务落库。
|
||||
"""
|
||||
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
||||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||||
item = {
|
||||
'source_type': 'email_attachment',
|
||||
'source_file_name': document.filename,
|
||||
'source_file_type': asset.mime_type if asset else None,
|
||||
'source_content_hash': document.content_hash,
|
||||
'file_size': asset.file_size if asset else None,
|
||||
'raw_text': document.extracted_text or '',
|
||||
'warnings': list(document.parse_warnings_json or []),
|
||||
'source_asset_id': document.asset_id,
|
||||
'source_intake_id': intake.id,
|
||||
'source_candidate_id': candidate.id,
|
||||
'business_fingerprint': candidate.business_fingerprint,
|
||||
'fingerprint_version': candidate.fingerprint_version,
|
||||
'content_fingerprint': candidate.content_fingerprint,
|
||||
'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',
|
||||
'supersedes_task_id': None,
|
||||
'duplicate_source_task_id': None,
|
||||
'duplicate_override_reason': None,
|
||||
}
|
||||
resolution = str(candidate.duplicate_resolution or '').strip().lower()
|
||||
target_no = str(candidate.duplicate_target_task_no or '').strip().upper()
|
||||
if resolution == 'create_revision' and target_no:
|
||||
target = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter_by(task_no=target_no, user_id=int(intake.user_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if target is None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', message='修订目标任务不存在')
|
||||
if db.session.query(ShippingTask.id).filter_by(supersedes_task_id=int(target.id)).first():
|
||||
raise ConflictError(code='SHIPPING_NOTICE.REVISION_CONFLICT', message='目标任务已有修订版本')
|
||||
item['supersedes_task_id'] = int(target.id)
|
||||
item['document_version'] = int(target.document_version or 1) + 1
|
||||
item['duplicate_resolution_type'] = 'revision'
|
||||
elif resolution == 'force_create' and target_no:
|
||||
target = db.session.query(ShippingTask).filter_by(
|
||||
task_no=target_no,
|
||||
user_id=int(intake.user_id),
|
||||
).first()
|
||||
if target:
|
||||
item['duplicate_source_task_id'] = int(target.id)
|
||||
item['duplicate_override_reason'] = candidate.duplicate_resolution_reason
|
||||
item['duplicate_resolution_type'] = 'force_create'
|
||||
return item
|
||||
@@ -75,6 +75,8 @@ def _duplicate_payload_from_intake(intake: ShippingNoticeIntake) -> dict[str, An
|
||||
'same_completed_task',
|
||||
'possible_duplicate',
|
||||
'partial_duplicate',
|
||||
'same_business_content',
|
||||
'possible_revision',
|
||||
}
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
blocking = False
|
||||
@@ -183,6 +185,10 @@ def serialize_intake(
|
||||
'conversation_id': intake.conversation_id,
|
||||
'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,
|
||||
'business_summary': business_summary,
|
||||
'business_fingerprint': intake.business_fingerprint,
|
||||
|
||||
@@ -18,7 +18,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id, normalize_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import normalize_reservation_id, validated_reservation_id
|
||||
|
||||
|
||||
# 默认列映射:含 AWS DUB On Hand Inventory 模板(AWS Sku / Reservation ID / Qty)
|
||||
@@ -190,7 +190,7 @@ def _normalize_inventory_row(
|
||||
reservation_id = ""
|
||||
idx_res = columns.get("reservation_id")
|
||||
if idx_res is not None:
|
||||
reservation_id = extract_reservation_id(_cell(row, idx_res))
|
||||
reservation_id = validated_reservation_id(_cell(row, idx_res))
|
||||
|
||||
idx_avail = columns.get("available_qty")
|
||||
idx_qty = columns.get("qty")
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def _norm(value: Any) -> str:
|
||||
@@ -19,7 +19,7 @@ def _norm(value: Any) -> str:
|
||||
|
||||
|
||||
def _norm_reservation(value: Any) -> str:
|
||||
return extract_reservation_id(value)
|
||||
return validated_reservation_id(value)
|
||||
|
||||
|
||||
def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]:
|
||||
|
||||
@@ -20,6 +20,11 @@ NOTICE_LINE_FIELDS = (
|
||||
"vendor_part_number",
|
||||
"uom",
|
||||
"remark",
|
||||
"po_number",
|
||||
"allocation_id",
|
||||
"source_type",
|
||||
"customer_sku",
|
||||
"hub_code",
|
||||
)
|
||||
|
||||
# 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格)
|
||||
@@ -34,6 +39,8 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
"Material": "sku",
|
||||
"Material No": "sku",
|
||||
"产品编号": "sku",
|
||||
"Allocated APN": "sku",
|
||||
"Allocated HHPN": "customer_sku",
|
||||
# 项次 / Item
|
||||
"项次": "line_no",
|
||||
"line_no": "line_no",
|
||||
@@ -54,6 +61,7 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
"Order Qty": "qty",
|
||||
"Ship Qty": "qty",
|
||||
"发货数量": "qty",
|
||||
"Allocated QTY": "qty",
|
||||
# 单价
|
||||
"单价": "unit_price",
|
||||
"Unit Price": "unit_price",
|
||||
@@ -89,6 +97,10 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
"PR Number": "reservation_id",
|
||||
"PR No": "reservation_id",
|
||||
"PR#": "reservation_id",
|
||||
"Reservation N.r": "reservation_id",
|
||||
"Reservation Nr": "reservation_id",
|
||||
"External reservation ID": "reservation_id",
|
||||
"External Reservation ID": "reservation_id",
|
||||
# 交货日期
|
||||
"Required Date": "required_date",
|
||||
"Delivery Date": "required_date",
|
||||
@@ -107,6 +119,17 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
"Supplier Part Number": "vendor_part_number",
|
||||
"MPN": "vendor_part_number",
|
||||
"供应商料号": "vendor_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": "hub_code",
|
||||
"Hub": "hub_code",
|
||||
"HUB": "hub_code",
|
||||
"hub_code": "hub_code",
|
||||
# 单位
|
||||
"单位": "uom",
|
||||
"UOM": "uom",
|
||||
@@ -114,6 +137,17 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
"Unit": "uom",
|
||||
}
|
||||
|
||||
# 这些列可能与 Reservation ID 相邻,但业务语义不同,禁止作为 Reservation ID 来源。
|
||||
RESERVATION_ID_FORBIDDEN_HEADERS = frozenset(
|
||||
{
|
||||
"allocation id",
|
||||
"parent allocation id",
|
||||
"commodity group id",
|
||||
"supplier code",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
NOTICE_FIELD_LABELS = {
|
||||
"line_no": "项次 / Item / Line No",
|
||||
"sku": "SKU / 料号",
|
||||
@@ -124,6 +158,11 @@ NOTICE_FIELD_LABELS = {
|
||||
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
|
||||
"required_date": "要求交期 / 交货日期",
|
||||
"vendor_part_number": "供应商料号",
|
||||
"po_number": "PO Number",
|
||||
"allocation_id": "Allocation ID",
|
||||
"source_type": "库存来源提示",
|
||||
"customer_sku": "客户料号 / HHPN",
|
||||
"hub_code": "Hub Code / 枢纽代码",
|
||||
}
|
||||
|
||||
HEADER_SKIP_TOKENS = {
|
||||
|
||||
@@ -27,6 +27,15 @@ from app.services.shipping_notice.reservation_id import (
|
||||
)
|
||||
|
||||
|
||||
def _derive_hub_code(source_type: Any) -> str:
|
||||
"""避免循环依赖,在表格解析层从 VMI/DBS source type 提取 Hub Code。"""
|
||||
import re
|
||||
|
||||
text = re.sub(r"\s+", " ", str(source_type or "").strip().upper())
|
||||
match = re.fullmatch(r"(?:VMI|DBS)[\s_-]+([A-Z0-9]+)", text)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def parse_notice_row(
|
||||
row: list[Any] | tuple[Any, ...],
|
||||
columns: dict[str, int | None],
|
||||
@@ -75,6 +84,12 @@ def parse_notice_row(
|
||||
if idx_res is not None:
|
||||
reservation_id = extract_reservation_id(cell(row, idx_res))
|
||||
skip_indices.add(idx_res)
|
||||
if reservation_id:
|
||||
parsed["reservation_id_evidence"] = {
|
||||
"source_column": str(columns.get("_reservation_id_header") or "").strip(),
|
||||
"source_index": idx_res,
|
||||
"raw_value": str(cell(row, idx_res) or "").strip(),
|
||||
}
|
||||
else:
|
||||
reservation_id = infer_reservation_id_from_row(row, skip_indices=skip_indices)
|
||||
if reservation_id:
|
||||
@@ -123,6 +138,18 @@ def parse_notice_row(
|
||||
if vendor_part_number:
|
||||
parsed["vendor_part_number"] = vendor_part_number
|
||||
|
||||
for field in ("po_number", "allocation_id", "source_type", "customer_sku", "hub_code"):
|
||||
idx = columns.get(field)
|
||||
if idx is None:
|
||||
continue
|
||||
value = str(cell(row, idx) or "").strip()
|
||||
if value:
|
||||
parsed[field] = value
|
||||
if not parsed.get("hub_code"):
|
||||
hub_code = _derive_hub_code(parsed.get("source_type"))
|
||||
if hub_code:
|
||||
parsed["hub_code"] = hub_code
|
||||
|
||||
if "amount" not in parsed and "unit_price" in parsed:
|
||||
computed = round(parsed["unit_price"] * qty, 4)
|
||||
if computed > 0:
|
||||
@@ -170,6 +197,9 @@ def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> l
|
||||
核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取 SKU、数量、金额等字段。
|
||||
"""
|
||||
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
|
||||
if not has_header and headers:
|
||||
has_header = any(map_notice_header(h) for h in headers)
|
||||
|
||||
@@ -15,6 +15,7 @@ from app.services.shipping_notice.notice_line_constants import (
|
||||
HEADER_SKIP_TOKENS,
|
||||
NOTICE_COLUMN_MAP,
|
||||
NOTICE_LINE_FIELDS,
|
||||
RESERVATION_ID_FORBIDDEN_HEADERS,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
extract_reservation_id,
|
||||
@@ -107,6 +108,8 @@ def resolve_notice_columns(headers: list[str]) -> dict[str, int | None]:
|
||||
if columns.get("reservation_id") is None:
|
||||
for i, header in enumerate(headers):
|
||||
norm = norm_header(header)
|
||||
if norm in RESERVATION_ID_FORBIDDEN_HEADERS:
|
||||
continue
|
||||
if norm in {"com id", "reservation order", "reservation id", "reservation no", "resv id"}:
|
||||
columns["reservation_id"] = i
|
||||
break
|
||||
|
||||
@@ -8,6 +8,7 @@ services/shipping_notice/notice_lines.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.notice_line_constants import (
|
||||
@@ -33,6 +34,8 @@ from app.services.shipping_notice.reservation_id import (
|
||||
extract_reservation_id,
|
||||
find_reservation_id_in_document,
|
||||
looks_like_reservation_id,
|
||||
is_valid_reservation_id,
|
||||
validated_reservation_id,
|
||||
)
|
||||
|
||||
# 向后兼容:旧代码/tests 仍可从 notice_lines 引用私有别名
|
||||
@@ -43,6 +46,13 @@ _map_notice_header = map_notice_header
|
||||
_parse_number = parse_number
|
||||
|
||||
|
||||
def derive_hub_code(source_type: Any) -> str:
|
||||
"""从已知库存来源提示中派生 Hub Code,如 VMI-FRA01→FRA01、DBS DUB→DUB。"""
|
||||
text = re.sub(r"\s+", " ", str(source_type or "").strip().upper())
|
||||
match = re.fullmatch(r"(?:VMI|DBS)[\s_-]+([A-Z0-9]+)", text)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
标准化单条发货通知订单行。
|
||||
@@ -94,6 +104,9 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
)
|
||||
if reservation_id:
|
||||
line["reservation_id"] = reservation_id
|
||||
evidence = raw.get("reservation_id_evidence")
|
||||
if isinstance(evidence, dict):
|
||||
line["reservation_id_evidence"] = dict(evidence)
|
||||
|
||||
unit_price = parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price"))
|
||||
if unit_price is not None:
|
||||
@@ -137,6 +150,23 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
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", "Source Type"),
|
||||
"customer_sku": ("customer_sku", "customerSku", "allocated_hhpn", "Allocated HHPN"),
|
||||
"hub_code": ("hub_code", "hubCode", "Hub Code", "Hub", "HUB"),
|
||||
}
|
||||
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:
|
||||
line[field] = value
|
||||
|
||||
if not line.get("hub_code"):
|
||||
hub_code = derive_hub_code(line.get("source_type"))
|
||||
if hub_code:
|
||||
line["hub_code"] = hub_code
|
||||
|
||||
remark = str(raw.get("remark") or raw.get("note") or "").strip()
|
||||
if remark:
|
||||
line["remark"] = remark
|
||||
@@ -160,6 +190,110 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
|
||||
return normalized
|
||||
|
||||
|
||||
def adjudicate_notice_lines(
|
||||
lines: list[dict[str, Any]],
|
||||
*,
|
||||
raw_text: str = "",
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], str]:
|
||||
"""
|
||||
对 LLM 候选订单行执行后端真值裁决,并输出可审计问题清单。
|
||||
|
||||
核心逻辑:先从保留列边界的原文解析结构证据;非法候选仅在同 SKU 唯一命中合法表格值时纠正,
|
||||
否则清空并阻断。合法候选与明确表格证据冲突时保留候选但标记阻断,禁止静默覆盖。
|
||||
Args:
|
||||
lines: 已完成基础标准化的 LLM/启发式候选行。
|
||||
raw_text: 原始通知正文;仅 TSV/HTML 保留下来的明确列关系可作为自动纠错证据。
|
||||
|
||||
Returns:
|
||||
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]]] = {}
|
||||
for evidence_line in evidence_lines:
|
||||
sku = str(evidence_line.get("sku") 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)
|
||||
|
||||
adjudicated: list[dict[str, Any]] = []
|
||||
issues: list[dict[str, Any]] = []
|
||||
for index, source_line in enumerate(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
|
||||
)
|
||||
)
|
||||
]
|
||||
evidence_values = {
|
||||
validated_reservation_id(item.get("reservation_id"))
|
||||
for item in matches
|
||||
if validated_reservation_id(item.get("reservation_id"))
|
||||
}
|
||||
evidence_values.discard("")
|
||||
|
||||
if candidate and evidence_values and candidate not in evidence_values:
|
||||
issues.append(
|
||||
{
|
||||
"line_index": index,
|
||||
"sku": line.get("sku"),
|
||||
"field": "reservation_id",
|
||||
"reason": "source_conflict",
|
||||
"severity": "blocking",
|
||||
"raw_value": raw_candidate,
|
||||
"evidence_values": sorted(evidence_values),
|
||||
}
|
||||
)
|
||||
elif not candidate and len(evidence_values) == 1:
|
||||
resolved = next(iter(evidence_values))
|
||||
line["reservation_id"] = resolved
|
||||
evidence_line = matches[0]
|
||||
evidence = evidence_line.get("reservation_id_evidence") or {}
|
||||
issues.append(
|
||||
{
|
||||
"line_index": index,
|
||||
"sku": line.get("sku"),
|
||||
"field": "reservation_id",
|
||||
"reason": "value_corrected",
|
||||
"severity": "info",
|
||||
"raw_value": raw_candidate,
|
||||
"resolved_value": resolved,
|
||||
"resolution_basis": f"email_table.{evidence.get('source_column') or 'Reservation ID'}",
|
||||
}
|
||||
)
|
||||
elif not candidate:
|
||||
line.pop("reservation_id", None)
|
||||
issues.append(
|
||||
{
|
||||
"line_index": index,
|
||||
"sku": line.get("sku"),
|
||||
"field": "reservation_id",
|
||||
"reason": "missing" if not raw_candidate else "invalid_format",
|
||||
"severity": "blocking",
|
||||
"raw_value": raw_candidate,
|
||||
}
|
||||
)
|
||||
else:
|
||||
line["reservation_id"] = candidate
|
||||
adjudicated.append(line)
|
||||
|
||||
status = "needs_review" if any(item.get("severity") == "blocking" for item in issues) else "ready"
|
||||
return adjudicated, issues, status
|
||||
|
||||
|
||||
def enrich_notice_with_document_reservation(
|
||||
parsed: dict[str, Any],
|
||||
*,
|
||||
@@ -179,8 +313,8 @@ def enrich_notice_with_document_reservation(
|
||||
"prNumber",
|
||||
"PR Number",
|
||||
):
|
||||
extracted = extract_reservation_id(parsed.get(key))
|
||||
if extracted and looks_like_reservation_id(extracted):
|
||||
extracted = validated_reservation_id(parsed.get(key))
|
||||
if extracted:
|
||||
doc_rid = extracted
|
||||
break
|
||||
|
||||
@@ -288,12 +422,11 @@ def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
|
||||
line["sku"]
|
||||
for line in lines
|
||||
if str(line.get("reservation_id") or "").strip()
|
||||
and not looks_like_reservation_id(line.get("reservation_id"))
|
||||
and not is_valid_reservation_id(line.get("reservation_id"))
|
||||
]
|
||||
if invalid_reservation:
|
||||
warnings.append(
|
||||
f"{len(invalid_reservation)} 行 Reservation ID 非典型纯数字格式(常见为 8~12 位,如 1000140351),"
|
||||
"请核对是否解析正确。"
|
||||
f"{len(invalid_reservation)} 行 Reservation ID 不满足业务格式契约,请核对来源列与原始值。"
|
||||
)
|
||||
|
||||
missing_price = sum(1 for line in lines if line.get("unit_price") is None and line.get("amount") is None)
|
||||
@@ -318,7 +451,7 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
|
||||
item += 0.35
|
||||
if line.get("qty"):
|
||||
item += 0.35
|
||||
if line.get("reservation_id"):
|
||||
if is_valid_reservation_id(line.get("reservation_id")):
|
||||
item += 0.15
|
||||
if line.get("unit_price") is not None or line.get("amount") is not None:
|
||||
item += 0.15
|
||||
@@ -333,6 +466,8 @@ __all__ = [
|
||||
"enrich_notice_with_document_currency",
|
||||
"enrich_notice_with_document_required_date",
|
||||
"enrich_notice_with_document_reservation",
|
||||
"derive_hub_code",
|
||||
"adjudicate_notice_lines",
|
||||
"normalize_notice_line",
|
||||
"normalize_notice_lines",
|
||||
"notice_parse_completeness",
|
||||
|
||||
@@ -74,6 +74,9 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
|
||||
task_id = _str_prop("发货任务编号(task id),如 SN-20260529-ABCD1234")
|
||||
batch_id = _str_prop("发货批次编号(batch id),如 SB-20260617-ABCD1234")
|
||||
runtime_context = _str_prop(
|
||||
"HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
)
|
||||
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
@@ -97,6 +100,99 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
"servers": [{"url": server}],
|
||||
"paths": {
|
||||
"/tools/get_order_extraction_context": _post_op(
|
||||
"get_order_extraction_context",
|
||||
"读取点击发送后完整订单抽取所需的邮件正文与附件文本",
|
||||
{"agent_runtime_context": runtime_context},
|
||||
required=["agent_runtime_context"],
|
||||
description=(
|
||||
"仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户,"
|
||||
"并返回 input_snapshot_hash、documents 与固定输出契约;禁止让 LLM 传 user_id。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_order_extraction": _post_op(
|
||||
"submit_order_extraction",
|
||||
"提交完整订单抽取结果,由 HXOPS 执行证据校验、订单级判重与自动建单",
|
||||
{
|
||||
"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 从一封或多封邮件中识别出的订单数组;一个附件可产生多个订单,非发货邮件可为空数组",
|
||||
"maxItems": 50,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"source_intake_no",
|
||||
"primary_document_id",
|
||||
"classification",
|
||||
"classification_confidence",
|
||||
"field_confidence",
|
||||
"lines",
|
||||
"evidence",
|
||||
],
|
||||
"properties": {
|
||||
"source_intake_no": _str_prop("来源 Intake 编号,必须来自上下文"),
|
||||
"primary_document_id": _int_prop("主来源 Document ID,必须来自上下文"),
|
||||
"candidate_key_hint": _str_prop("可选稳定订单标识,如 PO/订单号;不得使用随机值"),
|
||||
"classification": _str_prop("仅 shipping_request 可自动建单", enum=["shipping_request", "non_shipping_request", "uncertain"]),
|
||||
"classification_confidence": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
"field_confidence": {
|
||||
"type": "object",
|
||||
"required": ["sku", "qty"],
|
||||
"properties": {
|
||||
"sku": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
"qty": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
},
|
||||
},
|
||||
"po_number": _str_prop("可为空的 PO/订单号"),
|
||||
"lines": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["sku", "qty"],
|
||||
"properties": {
|
||||
"sku": _str_prop("SKU/料号"),
|
||||
"qty": {"type": "number", "exclusiveMinimum": 0},
|
||||
"reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
|
||||
"hub_code": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
|
||||
"source_type": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
|
||||
},
|
||||
"additionalProperties": True,
|
||||
},
|
||||
},
|
||||
"evidence": {
|
||||
"type": "array",
|
||||
"description": "至少分别提供 SKU 与 Qty 原文证据,元素含 field 与非空 quote",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["field", "quote"],
|
||||
"properties": {
|
||||
"field": _str_prop("证据字段,如 lines[0].sku 或 lines[0].qty"),
|
||||
"quote": _str_prop("原文片段,禁止改写"),
|
||||
"document_id": _int_prop("证据来源 Document ID"),
|
||||
},
|
||||
},
|
||||
},
|
||||
"conflicts": {
|
||||
"type": "array",
|
||||
"items": {"type": "object", "additionalProperties": True},
|
||||
},
|
||||
},
|
||||
"additionalProperties": True,
|
||||
},
|
||||
},
|
||||
},
|
||||
required=["agent_runtime_context", "input_snapshot_hash", "schema_version", "orders"],
|
||||
description=(
|
||||
"只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,"
|
||||
"且无阻断冲突/修订决策时自动建单;Reservation ID、Hub Code、Source Type 允许缺失。"
|
||||
),
|
||||
),
|
||||
"/tools/parse_notice": _post_op(
|
||||
"parse_notice",
|
||||
"解析发货通知文本",
|
||||
@@ -134,7 +230,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"line_index": _int_prop("行下标,从 0 开始"),
|
||||
"patch": {
|
||||
"type": "object",
|
||||
"description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom",
|
||||
"description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom/hub_code/source_type",
|
||||
"additionalProperties": True,
|
||||
},
|
||||
"comment": _str_prop("修改备注(可选)"),
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_candidate_builder.py
|
||||
|
||||
用途:将邮件正文订单索引与单个附件解析结果融合为可审核的订单候选。
|
||||
依赖:notice_line_table、po_number、reservation_id。
|
||||
逻辑:document_candidate_persist 先解析正文和附件,再由本模块按 PO/Reservation 关联、补字段并生成冲突。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.notice_line_table import parse_notice_table_text
|
||||
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", "hub_code")
|
||||
|
||||
|
||||
def _comparable_value(field: str, value: Any) -> str:
|
||||
"""按字段语义标准化正文与附件值,避免格式差异制造伪冲突。"""
|
||||
if field == "reservation_id":
|
||||
return validated_reservation_id(value) or ""
|
||||
if field == "qty":
|
||||
try:
|
||||
return format(Decimal(str(value)).normalize(), "f")
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
pass
|
||||
return str(value or "").strip().upper()
|
||||
|
||||
|
||||
def build_email_order_index(body_text: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从邮件正文表格提取订单索引行。
|
||||
|
||||
核心逻辑:复用统一订单表格解析器,并只保留具备 PO 或 Reservation 的有效订单行。
|
||||
Args:
|
||||
body_text: 邮件正文纯文本。
|
||||
Returns:
|
||||
正文订单索引列表。
|
||||
"""
|
||||
rows = parse_notice_table_text(str(body_text or ""))
|
||||
return [
|
||||
row for row in rows
|
||||
if normalize_po_number(row.get("po_number"))
|
||||
or validated_reservation_id(row.get("reservation_id"))
|
||||
]
|
||||
|
||||
|
||||
def _summary_po(summary: dict[str, Any], filename: str | None) -> str:
|
||||
"""读取附件摘要 PO;正文未抽到时从附件文件名中的纯数字单号兜底。"""
|
||||
po = normalize_po_number(summary.get("po_number"))
|
||||
if po:
|
||||
return po
|
||||
match = _PO_IN_FILENAME.search(str(filename or ""))
|
||||
return normalize_po_number(match.group(1)) if match else ""
|
||||
|
||||
|
||||
def _summary_reservations(summary: dict[str, Any]) -> set[str]:
|
||||
"""汇总附件摘要中的 Reservation ID,供无 PO 时安全关联。"""
|
||||
values = set()
|
||||
for value in summary.get("reservation_ids") or []:
|
||||
normalized = validated_reservation_id(value)
|
||||
if normalized:
|
||||
values.add(normalized)
|
||||
for line in summary.get("lines") or []:
|
||||
if isinstance(line, dict):
|
||||
normalized = validated_reservation_id(line.get("reservation_id"))
|
||||
if normalized:
|
||||
values.add(normalized)
|
||||
return values
|
||||
|
||||
|
||||
def _find_body_row(
|
||||
body_rows: list[dict[str, Any]],
|
||||
*,
|
||||
po_number: str,
|
||||
reservations: set[str],
|
||||
) -> tuple[dict[str, Any] | None, str | None]:
|
||||
"""按 PO 优先、唯一 Reservation 次优选择正文订单行;歧义时不自动关联。"""
|
||||
if po_number:
|
||||
hits = [row for row in body_rows if normalize_po_number(row.get("po_number")) == po_number]
|
||||
if len(hits) == 1:
|
||||
return hits[0], "po_number"
|
||||
if reservations:
|
||||
hits = [
|
||||
row for row in body_rows
|
||||
if validated_reservation_id(row.get("reservation_id")) in reservations
|
||||
]
|
||||
if len(hits) == 1:
|
||||
return hits[0], "reservation_id"
|
||||
return None, None
|
||||
|
||||
|
||||
def _find_attachment_line(
|
||||
lines: list[dict[str, Any]],
|
||||
body_row: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""按唯一 Reservation、唯一 SKU、单行顺序选择正文字段应融合的附件行。"""
|
||||
body_reservation = validated_reservation_id(body_row.get("reservation_id"))
|
||||
if body_reservation:
|
||||
hits = [
|
||||
line for line in lines
|
||||
if validated_reservation_id(line.get("reservation_id")) == body_reservation
|
||||
]
|
||||
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]
|
||||
if len(hits) == 1:
|
||||
return hits[0]
|
||||
return lines[0] if len(lines) == 1 else None
|
||||
|
||||
|
||||
def merge_attachment_candidate(
|
||||
*,
|
||||
attachment_summary: dict[str, Any],
|
||||
filename: str | None,
|
||||
body_rows: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将一个主附件与邮件正文对应订单行融合。
|
||||
|
||||
核心逻辑:附件为主证据,正文仅补缺失字段;关键字段不一致时保留附件值并生成阻断冲突。
|
||||
Args:
|
||||
attachment_summary: 单个附件业务摘要。
|
||||
filename: 附件原始文件名。
|
||||
body_rows: 邮件正文订单索引。
|
||||
Returns:
|
||||
包含 business_summary、conflicts、validation_status、evidence 的融合结果。
|
||||
"""
|
||||
summary = dict(attachment_summary or {})
|
||||
lines = [dict(item) for item in (summary.get("lines") or []) if isinstance(item, dict)]
|
||||
po_number = _summary_po(summary, filename)
|
||||
body_row, matched_by = _find_body_row(
|
||||
body_rows,
|
||||
po_number=po_number,
|
||||
reservations=_summary_reservations(summary),
|
||||
)
|
||||
conflicts: list[dict[str, Any]] = []
|
||||
|
||||
if body_row:
|
||||
if not lines:
|
||||
lines = [dict(body_row)]
|
||||
else:
|
||||
target = _find_attachment_line(lines, body_row)
|
||||
if target is None:
|
||||
conflicts.append({
|
||||
"field": "line_association",
|
||||
"attachment_value": [
|
||||
{
|
||||
"reservation_id": line.get("reservation_id"),
|
||||
"sku": line.get("sku"),
|
||||
}
|
||||
for line in lines
|
||||
],
|
||||
"email_value": body_row,
|
||||
"severity": "blocking",
|
||||
})
|
||||
else:
|
||||
for field, body_value in body_row.items():
|
||||
if body_value in (None, ""):
|
||||
continue
|
||||
attachment_value = target.get(field)
|
||||
if field in _KEY_FIELDS and attachment_value not in (None, ""):
|
||||
left = _comparable_value(field, attachment_value)
|
||||
right = _comparable_value(field, body_value)
|
||||
if left != right:
|
||||
conflicts.append({
|
||||
"field": field,
|
||||
"attachment_value": attachment_value,
|
||||
"email_value": body_value,
|
||||
"severity": "blocking",
|
||||
})
|
||||
continue
|
||||
if attachment_value in (None, ""):
|
||||
target[field] = body_value
|
||||
if not po_number:
|
||||
po_number = normalize_po_number(body_row.get("po_number"))
|
||||
|
||||
summary["po_number"] = po_number or summary.get("po_number")
|
||||
summary["lines"] = lines
|
||||
summary["reservation_ids"] = sorted({
|
||||
validated_reservation_id(item.get("reservation_id"))
|
||||
for item in lines
|
||||
if validated_reservation_id(item.get("reservation_id"))
|
||||
})
|
||||
return {
|
||||
"business_summary": summary,
|
||||
"conflicts": conflicts,
|
||||
"validation_status": "needs_review" if conflicts else "ready",
|
||||
"evidence": {
|
||||
"attachment_filename": filename,
|
||||
"email_row": body_row,
|
||||
"matched_by": matched_by,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,575 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction.py
|
||||
|
||||
用途:为现有货代 Chatflow 提供建单前订单抽取上下文,并接收 LLM orders[] 完成校验、判重与自动建单。
|
||||
依赖:agent_runtime_context、ChatSession、ShippingNoticeIntake/Document/Candidate、batch_from_intakes。
|
||||
逻辑:点击发送后 Dify 先读取不可变输入快照,再提交结构化订单;HXOPS 以会话用户为权限边界,
|
||||
逐订单落 Candidate,高置信度 SKU/Qty 订单自动消费建 Task,其余保留供自然对话修订。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
)
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
build_business_fingerprint,
|
||||
build_content_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.duplicate_detection import (
|
||||
aggregate_intake_duplicate_from_candidates,
|
||||
apply_duplicate_result_to_candidate,
|
||||
apply_duplicate_result_to_intake,
|
||||
detect_duplicates_for_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
|
||||
|
||||
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',
|
||||
]
|
||||
|
||||
|
||||
def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, list[str], str]:
|
||||
"""从统一运行态上下文解析会话用户、Intake集合与请求号。"""
|
||||
parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS)
|
||||
values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {}
|
||||
if str(values.get('agent_code') or '') != 'shipping_notice':
|
||||
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()
|
||||
session = ChatSession.query.filter_by(session_id=session_id).first()
|
||||
if session is None:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='聊天会话不存在')
|
||||
try:
|
||||
raw_nos = json.loads(str(values.get('refs.intake_nos') or '[]'))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='Intake 上下文格式无效') from exc
|
||||
if not isinstance(raw_nos, list):
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='Intake 上下文必须为数组')
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in raw_nos if str(item or '').strip()})
|
||||
if not intake_nos:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='未提供待解析 Intake')
|
||||
return session, intake_nos, str(values.get('platform.request_id') or '').strip()
|
||||
|
||||
|
||||
def _load_intakes(
|
||||
*,
|
||||
session: ChatSession,
|
||||
intake_nos: list[str],
|
||||
lock: bool,
|
||||
allow_consumed: bool = False,
|
||||
) -> list[ShippingNoticeIntake]:
|
||||
"""按会话用户加载并可选锁定 Intake;提交重放可读取已消费记录。"""
|
||||
query = db.session.query(ShippingNoticeIntake).filter(
|
||||
ShippingNoticeIntake.user_id == int(session.user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(intake_nos),
|
||||
)
|
||||
if lock:
|
||||
query = query.with_for_update()
|
||||
rows = query.order_by(ShippingNoticeIntake.id.asc()).all()
|
||||
if {row.intake_no for row in rows} != set(intake_nos):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在')
|
||||
for row in rows:
|
||||
if row.conversation_id and row.conversation_id != session.session_id:
|
||||
raise ForbiddenError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='发货通知已绑定其他会话')
|
||||
ready = row.parse_status == 'parsed' and row.consumed_at is None
|
||||
replayable = allow_consumed and row.parse_status == 'consumed'
|
||||
if not ready and not replayable:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理')
|
||||
if row.conversation_id is None:
|
||||
row.conversation_id = session.session_id
|
||||
row.updated_at = datetime.utcnow()
|
||||
return rows
|
||||
|
||||
|
||||
def _load_documents(intakes: list[ShippingNoticeIntake], *, lock: bool) -> list[ShippingNoticeDocument]:
|
||||
"""加载本轮 Intake 的全部 Document,保持稳定排序供快照和 LLM输入复用。"""
|
||||
query = db.session.query(ShippingNoticeDocument).filter(
|
||||
ShippingNoticeDocument.intake_id.in_([int(row.id) for row in intakes])
|
||||
)
|
||||
if lock:
|
||||
query = query.with_for_update()
|
||||
return query.order_by(ShippingNoticeDocument.intake_id.asc(), ShippingNoticeDocument.id.asc()).all()
|
||||
|
||||
|
||||
def _snapshot_hash(intakes: list[ShippingNoticeIntake], documents: list[ShippingNoticeDocument]) -> str:
|
||||
"""对输入集合及正文内容生成稳定 SHA-256,拒绝旧 LLM 结果覆盖新附件。"""
|
||||
payload = {
|
||||
'intakes': [
|
||||
{
|
||||
'id': row.id,
|
||||
'no': row.intake_no,
|
||||
'asset_id': row.asset_id,
|
||||
}
|
||||
for row in intakes
|
||||
],
|
||||
'documents': [
|
||||
{
|
||||
'id': row.id,
|
||||
'intake_id': row.intake_id,
|
||||
'content_hash': row.content_hash,
|
||||
'parse_status': row.parse_status,
|
||||
'text_hash': hashlib.sha256(str(row.extracted_text or '').encode('utf-8')).hexdigest(),
|
||||
}
|
||||
for row in documents
|
||||
],
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
返回现有 Chatflow 完整理解邮件所需的 Intake/Document 上下文。
|
||||
|
||||
【AI 触发时机】:当 agent_runtime_context.refs.capability=order_extraction 时,
|
||||
在订单抽取 LLM 节点之前调用一次;禁止用于已创建 Task 的普通续办。
|
||||
|
||||
Args:
|
||||
payload: 必须包含 agent_runtime_context。
|
||||
|
||||
Returns:
|
||||
邮件正文、附件文本、规则提示、输入快照 hash 与输出契约。
|
||||
"""
|
||||
session, intake_nos, request_id = _runtime_identity(payload.get('agent_runtime_context'))
|
||||
intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True)
|
||||
documents = _load_documents(intakes, lock=False)
|
||||
if not documents:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', message='未找到可供订单抽取的邮件正文或附件')
|
||||
|
||||
max_total = int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_CONTEXT_CHARS') or 500000)
|
||||
used = 0
|
||||
document_rows: list[dict[str, Any]] = []
|
||||
intake_by_id = {int(row.id): row for row in intakes}
|
||||
for document in documents:
|
||||
text = str(document.extracted_text or '')
|
||||
remaining = max(max_total - used, 0)
|
||||
clipped = text[:remaining]
|
||||
used += len(clipped)
|
||||
document_rows.append({
|
||||
'document_id': int(document.id),
|
||||
'source_intake_no': intake_by_id[int(document.intake_id)].intake_no,
|
||||
'document_type': document.document_type,
|
||||
'filename': document.filename,
|
||||
'mime_type': (
|
||||
db.session.get(FileAsset, int(document.asset_id)).mime_type
|
||||
if document.asset_id and db.session.get(FileAsset, int(document.asset_id)) is not None
|
||||
else None
|
||||
),
|
||||
'classification_hint': document.classification,
|
||||
'parse_status': document.parse_status,
|
||||
'text': clipped,
|
||||
'text_truncated': len(clipped) < len(text),
|
||||
'warnings': list(document.parse_warnings_json or []),
|
||||
})
|
||||
snapshot = _snapshot_hash(intakes, documents)
|
||||
now = datetime.utcnow()
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
structured['order_extraction_snapshot'] = {
|
||||
'hash': snapshot,
|
||||
'request_id': request_id,
|
||||
'session_id': session.session_id,
|
||||
'created_at': now.isoformat(),
|
||||
}
|
||||
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
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'ok',
|
||||
'request_id': request_id,
|
||||
'input_snapshot_hash': snapshot,
|
||||
'intake_nos': intake_nos,
|
||||
'documents': document_rows,
|
||||
'rule_hints': {
|
||||
row.intake_no: dict(row.structured_result_json or {}).get('rule_hints') or {}
|
||||
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'],
|
||||
'allowed_missing_process_fields': ['reservation_id', 'hub_code', 'source_type'],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _float(value: Any, default: float = 0.0) -> float:
|
||||
"""将 LLM 置信度规范为 0..1 浮点数。"""
|
||||
try:
|
||||
return max(0.0, min(float(value), 1.0))
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def _candidate_key(intake_no: str, order: dict[str, Any], summary: dict[str, Any], index: int) -> str:
|
||||
"""生成同一 Intake 内稳定订单键;只有缺少业务身份时才使用顺序兜底。"""
|
||||
hint = str(order.get('candidate_key_hint') or '').strip()
|
||||
po_number = str(summary.get('po_number') or '').strip()
|
||||
reservation_ids = list(summary.get('reservation_ids') or [])
|
||||
identity = {
|
||||
'hint': hint,
|
||||
'primary_document_id': order.get('primary_document_id'),
|
||||
'po_number': po_number or None,
|
||||
'reservation_ids': reservation_ids,
|
||||
'lines': [
|
||||
{'sku': line.get('sku'), 'reservation_id': line.get('reservation_id')}
|
||||
for line in summary.get('lines') or []
|
||||
],
|
||||
}
|
||||
if not hint and not po_number and not reservation_ids:
|
||||
identity['fallback_index'] = index
|
||||
raw = json.dumps(identity, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
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 提供了原文证据;防止只靠自报高置信度自动建单。"""
|
||||
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)
|
||||
|
||||
|
||||
def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
提交 Chatflow 的 orders[],执行后端强校验、订单级判重与自动建单。
|
||||
|
||||
【AI 触发时机】:订单抽取 LLM + JSON 标准化节点成功后调用;每轮只调用一次。
|
||||
低置信度、缺 SKU/Qty、证据不足或可能修订的订单会保留为待处理 Candidate,
|
||||
不得由画布自行绕过后端门禁。
|
||||
|
||||
Args:
|
||||
payload: agent_runtime_context、input_snapshot_hash、schema_version、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 必须为数组')
|
||||
max_orders = int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_ORDERS') or 50)
|
||||
if len(orders) > max_orders:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT', message='订单数量超过限制')
|
||||
|
||||
intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True, allow_consumed=True)
|
||||
documents = _load_documents(intakes, lock=True)
|
||||
current_snapshot = _snapshot_hash(intakes, documents)
|
||||
supplied_snapshot = str(payload.get('input_snapshot_hash') or '').strip().lower()
|
||||
if not supplied_snapshot or supplied_snapshot != current_snapshot:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED', message='邮件或附件内容已变化,请重新解析')
|
||||
replay_results = []
|
||||
for intake in intakes:
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
submission = structured.get('order_extraction_submission')
|
||||
if not isinstance(submission, dict) or submission.get('input_snapshot_hash') != current_snapshot:
|
||||
replay_results = []
|
||||
break
|
||||
stored_result = submission.get('result')
|
||||
if isinstance(stored_result, dict):
|
||||
replay_results.append(stored_result)
|
||||
if len(replay_results) == len(intakes):
|
||||
replay = dict(replay_results[0])
|
||||
replay['idempotent_replay'] = True
|
||||
return replay
|
||||
if any(row.parse_status == 'consumed' for row in intakes):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
message='已消费的 Intake 仅允许回放原订单抽取结果',
|
||||
)
|
||||
intake_by_no = {row.intake_no: row for row in intakes}
|
||||
document_by_id = {int(row.id): row for row in documents}
|
||||
documents_by_intake: dict[int, list[ShippingNoticeDocument]] = {}
|
||||
for document in documents:
|
||||
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]] = []
|
||||
duplicate_results_by_intake: dict[int, list[dict[str, Any]]] = {}
|
||||
active_keys_by_intake: dict[int, set[str]] = {int(row.id): set() for row in intakes}
|
||||
pending_by_intake: dict[int, list[dict[str, Any]]] = {int(row.id): [] for row in intakes}
|
||||
document_candidate_keys: dict[int, list[str]] = {int(row.id): [] for row in documents}
|
||||
document_has_pending: dict[int, bool] = {int(row.id): False for row in documents}
|
||||
|
||||
# [STEP 1] 本轮选择状态完全由最新 LLM 结果决定,避免旧的 selected Candidate 混入自动建批集合。
|
||||
db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id.in_([int(row.id) for row in intakes]),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
).update({'selected': False}, synchronize_session=False)
|
||||
|
||||
for index, raw_order in enumerate(orders):
|
||||
if not isinstance(raw_order, dict):
|
||||
pending.append({'order_index': index, 'reasons': ['order_must_be_object']})
|
||||
continue
|
||||
intake_no = str(raw_order.get('source_intake_no') or '').strip().upper()
|
||||
if not intake_no and len(intakes) == 1:
|
||||
intake_no = intakes[0].intake_no
|
||||
intake = intake_by_no.get(intake_no)
|
||||
if intake is None:
|
||||
pending.append({'order_index': index, 'reasons': ['source_intake_not_found']})
|
||||
continue
|
||||
document_id = raw_order.get('primary_document_id')
|
||||
document = document_by_id.get(int(document_id)) if str(document_id or '').isdigit() else None
|
||||
owned_docs = documents_by_intake.get(int(intake.id), [])
|
||||
if document is None and len(owned_docs) == 1:
|
||||
document = owned_docs[0]
|
||||
if document is None or int(document.intake_id) != int(intake.id):
|
||||
pending_item = {'order_index': index, 'source_intake_no': intake_no, 'reasons': ['primary_document_not_found']}
|
||||
pending.append(pending_item)
|
||||
pending_by_intake[int(intake.id)].append(pending_item)
|
||||
continue
|
||||
|
||||
summary = dict(raw_order)
|
||||
summary.pop('evidence', None)
|
||||
summary.pop('field_confidence', None)
|
||||
summary.pop('classification_confidence', None)
|
||||
summary.pop('candidate_key_hint', None)
|
||||
summary.pop('classification', None)
|
||||
summary.pop('source_intake_no', None)
|
||||
summary.pop('primary_document_id', None)
|
||||
assessment = assess_candidate_business_summary(summary)
|
||||
normalized = assessment['normalized_summary']
|
||||
classification_confidence = _float(raw_order.get('classification_confidence'))
|
||||
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'))
|
||||
classification = str(raw_order.get('classification') or '').strip().lower()
|
||||
conflicts = [item for item in (raw_order.get('conflicts') or []) if isinstance(item, dict)]
|
||||
blocking_conflicts = [item for item in conflicts if str(item.get('severity') or 'blocking') == 'blocking']
|
||||
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')
|
||||
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 blocking_conflicts:
|
||||
reasons.append('blocking_conflict')
|
||||
|
||||
candidate_key = _candidate_key(intake_no, raw_order, normalized, index)
|
||||
active_keys_by_intake[int(intake.id)].add(candidate_key)
|
||||
candidate = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter_by(intake_id=int(intake.id), candidate_key=candidate_key)
|
||||
.first()
|
||||
)
|
||||
if candidate is not None and candidate.consumed_task_id is not None:
|
||||
document_candidate_keys[int(document.id)].append(candidate_key)
|
||||
continue
|
||||
if candidate is None:
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no=generate_candidate_no(),
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=int(document.id),
|
||||
candidate_key=candidate_key,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
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'])
|
||||
candidate.evidence_json = [item for item in (raw_order.get('evidence') or []) if isinstance(item, dict)]
|
||||
candidate.po_number = str(normalized.get('po_number') or '').strip() or None
|
||||
candidate.confidence = classification_confidence
|
||||
candidate.conflicts_json = blocking_conflicts
|
||||
candidate.validation_status = 'ready' if not reasons else 'needs_review'
|
||||
candidate.selected = not reasons
|
||||
identity = build_business_fingerprint(normalized)
|
||||
content = build_content_fingerprint(normalized)
|
||||
candidate.business_fingerprint = identity.get('fingerprint')
|
||||
candidate.fingerprint_version = identity.get('version')
|
||||
candidate.fingerprint_strength = identity.get('strength')
|
||||
candidate.content_fingerprint = content.get('fingerprint')
|
||||
candidate.content_fingerprint_version = content.get('version')
|
||||
candidate.structured_result_json = {
|
||||
'business_summary': normalized,
|
||||
'fingerprint_components': identity.get('components') or {},
|
||||
'content_fingerprint_components': content.get('components') or {},
|
||||
'extraction': {
|
||||
'request_id': request_id,
|
||||
'classification': classification,
|
||||
'classification_confidence': classification_confidence,
|
||||
'field_confidence': field_confidence,
|
||||
'missing_required_fields': assessment['missing_required_fields'],
|
||||
'missing_process_fields': assessment['missing_process_fields'],
|
||||
'process_issues': assessment['process_issues'],
|
||||
'auto_create_reasons': reasons,
|
||||
},
|
||||
}
|
||||
duplicate = detect_duplicates_for_candidate(
|
||||
intake=intake,
|
||||
asset=db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None,
|
||||
document=document,
|
||||
business_summary=normalized,
|
||||
fingerprint_result=identity,
|
||||
content_fingerprint_result=content,
|
||||
)
|
||||
apply_duplicate_result_to_candidate(candidate, duplicate)
|
||||
duplicate_results_by_intake.setdefault(int(intake.id), []).append(duplicate)
|
||||
if duplicate.get('status') in {'exact_file', 'same_active_task', 'same_completed_task', 'same_business_content'}:
|
||||
matches = list(duplicate.get('matches') or [])
|
||||
if matches:
|
||||
candidate.duplicate_resolution = 'open_existing'
|
||||
candidate.duplicate_target_task_no = str(matches[0].get('task_no') or '').strip().upper() or None
|
||||
candidate.selected = True
|
||||
candidate.validation_status = 'ready' if not reasons else 'needs_review'
|
||||
elif duplicate.get('blocking'):
|
||||
reasons.append('duplicate_decision_required')
|
||||
candidate.selected = False
|
||||
candidate.validation_status = 'needs_review'
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
document_candidate_keys[int(document.id)].append(candidate_key)
|
||||
document_has_pending[int(document.id)] = document_has_pending[int(document.id)] or bool(reasons)
|
||||
if candidate.selected and candidate.validation_status == 'ready':
|
||||
auto_candidates.append(candidate)
|
||||
else:
|
||||
pending_item = {
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'order_index': index,
|
||||
'source_intake_no': intake_no,
|
||||
'po_number': candidate.po_number,
|
||||
'reasons': sorted(set(reasons)),
|
||||
'missing_fields': list(candidate.missing_fields_json or []),
|
||||
'duplicate_status': candidate.duplicate_status,
|
||||
}
|
||||
pending.append(pending_item)
|
||||
pending_by_intake[int(intake.id)].append(pending_item)
|
||||
|
||||
# [STEP 2] 聚合 Document 结果,避免同一附件多订单时后一个 Candidate 覆盖前一个审计记录。
|
||||
for document in documents:
|
||||
keys = document_candidate_keys[int(document.id)]
|
||||
document.order_extraction_status = 'partially_completed' if document_has_pending[int(document.id)] 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}
|
||||
document.order_extraction_error_code = None
|
||||
document.order_extraction_error_message = None
|
||||
|
||||
# [STEP 3] 清理同一抽取版本中消失、且尚未消费的旧 Candidate。
|
||||
has_unassigned_pending = any(not item.get('source_intake_no') for item in pending)
|
||||
for intake in intakes:
|
||||
active_keys = active_keys_by_intake[int(intake.id)]
|
||||
stale = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
ShippingNoticeCandidate.extraction_source == 'dify_chatflow',
|
||||
)
|
||||
if active_keys:
|
||||
stale = stale.filter(ShippingNoticeCandidate.candidate_key.notin_(tuple(active_keys)))
|
||||
stale.delete(synchronize_session=False)
|
||||
aggregate = aggregate_intake_duplicate_from_candidates(
|
||||
intake,
|
||||
duplicate_results_by_intake.get(int(intake.id), []),
|
||||
)
|
||||
apply_duplicate_result_to_intake(intake, aggregate)
|
||||
intake.order_extraction_status = (
|
||||
'partially_completed'
|
||||
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()
|
||||
db.session.flush()
|
||||
|
||||
auto_candidate_nos = [row.candidate_no for row in auto_candidates]
|
||||
create_result: dict[str, Any] | None = None
|
||||
if auto_candidate_nos:
|
||||
idem = f"extract:{current_snapshot[:48]}"
|
||||
create_result = create_shipping_batch_from_candidates(
|
||||
user_id=int(session.user_id),
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=intake_nos,
|
||||
candidate_nos=auto_candidate_nos,
|
||||
create_idempotency_key=idem,
|
||||
)
|
||||
else:
|
||||
# [STEP 4] 没有待处理订单且 LLM 明确返回 0 单时,本次 Intake 已完成但不会产生 Batch/Task。
|
||||
if not pending:
|
||||
now = datetime.utcnow()
|
||||
for intake in intakes:
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = now
|
||||
intake.order_extraction_status = 'completed'
|
||||
intake.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
create_data = (create_result or {}).get('data')
|
||||
create_data = create_data if isinstance(create_data, dict) else {}
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': request_id,
|
||||
'batch_no': create_result.get('batch_no') if create_result else None,
|
||||
'created': list(create_data.get('tasks') or []),
|
||||
'opened_existing': list(
|
||||
(create_result or {}).get('opened_existing')
|
||||
or create_data.get('opened_existing')
|
||||
or []
|
||||
),
|
||||
'pending_orders': pending,
|
||||
'auto_created_count': len(auto_candidate_nos),
|
||||
'pending_count': len(pending),
|
||||
'message': (
|
||||
f"已自动处理 {len(auto_candidate_nos)} 份发货订单,另有 {len(pending)} 份需要补充或确认。"
|
||||
),
|
||||
}
|
||||
# [STEP 5] 保存 Tool 级幂等回放结果,防止 Dify 网络重试重复建单。
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
structured['order_extraction_submission'] = {
|
||||
'input_snapshot_hash': current_snapshot,
|
||||
'schema_version': EXTRACTION_CONTRACT_VERSION,
|
||||
'result': result,
|
||||
'submitted_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
db.session.commit()
|
||||
return result
|
||||
@@ -19,7 +19,9 @@ from app.services.shipping_notice.constants import (
|
||||
CP_UPLOAD_REQ,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_RSV_REQ,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_RSV_REQ,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
@@ -71,6 +73,18 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
except (TypeError, ValueError):
|
||||
confidence = None
|
||||
|
||||
if task.review_status == RS_RSV_REQ or task.pending_human_reason == PH_RSV_REQ:
|
||||
ui = resolve_task_ui_state(task)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="订单仍缺少后续处理必需字段,请先补充后再继续。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF:
|
||||
ui = resolve_task_ui_state(task)
|
||||
return tool_response(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/reservation_id.py
|
||||
|
||||
用途:提取、标准化并识别发货通知与库存中的 Reservation ID。
|
||||
用途:提取、标准化并校验发货通知与库存中的 Reservation ID。
|
||||
依赖:正则表达式与标准 `typing` 工具。
|
||||
逻辑:由 notice_lines、inventory_snapshot、match、extract 等多个解析/匹配模块复用本文件完成 Reservation ID 归一化。
|
||||
"""
|
||||
@@ -13,6 +13,14 @@ from typing import Any
|
||||
|
||||
# 常见 Reservation ID:纯数字,如 1000140351(通常 8~12 位)
|
||||
RESERVATION_ID_NUMERIC_RE = re.compile(r"^\d{8,12}$")
|
||||
# 部分库存源使用带字母/连字符的业务单号,如 AWS-311、ORD-3002、R-1。
|
||||
RESERVATION_ID_BUSINESS_RE = re.compile(r"^[A-Z0-9][A-Z0-9._/-]{1,63}$", re.IGNORECASE)
|
||||
# 数据库主键、哈希或 UUID 不属于业务 Reservation ID。
|
||||
INTERNAL_HEX_ID_RE = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE)
|
||||
INTERNAL_UUID_RE = re.compile(
|
||||
r"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351
|
||||
RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{8,12})\b")
|
||||
PR_NUMBER_LINE_RE = re.compile(
|
||||
@@ -51,7 +59,7 @@ def normalize_reservation_id(value: Any) -> str:
|
||||
|
||||
|
||||
def extract_reservation_id(value: Any) -> str:
|
||||
"""从纯数字、Excel 浮点或 PR Number(xxx@1000140351)中提取 Reservation ID。"""
|
||||
"""从原值提取 Reservation ID 候选;合法性必须另由 `is_valid_reservation_id` 判断。"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
@@ -96,3 +104,35 @@ def looks_like_reservation_id(value: Any) -> bool:
|
||||
"""判断标准化后的值是否符合 8~12 位纯数字 Reservation ID 格式。"""
|
||||
text = normalize_reservation_id(value)
|
||||
return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text))
|
||||
|
||||
|
||||
def is_valid_reservation_id(value: Any, *, numeric_only: bool = False) -> bool:
|
||||
"""
|
||||
判断候选值是否可作为业务 Reservation ID。
|
||||
|
||||
核心逻辑:默认兼容数字型与现有字母型业务单号,但明确拒绝 32 位 hex、UUID、纯字母等内部或弱语义值。
|
||||
Args:
|
||||
value: 待校验的原始值。
|
||||
numeric_only: 为 True 时仅接受 8~12 位纯数字,用于明确的 External Reservation 模板。
|
||||
|
||||
Returns:
|
||||
bool: 值是否满足当前 Reservation ID 契约。
|
||||
"""
|
||||
text = extract_reservation_id(value)
|
||||
if not text or INTERNAL_HEX_ID_RE.fullmatch(text) or INTERNAL_UUID_RE.fullmatch(text):
|
||||
return False
|
||||
if RESERVATION_ID_NUMERIC_RE.fullmatch(text):
|
||||
return True
|
||||
if numeric_only:
|
||||
return False
|
||||
return bool(
|
||||
RESERVATION_ID_BUSINESS_RE.fullmatch(text)
|
||||
and re.search(r"[A-Z]", text, re.IGNORECASE)
|
||||
and re.search(r"\d", text)
|
||||
)
|
||||
|
||||
|
||||
def validated_reservation_id(value: Any, *, numeric_only: bool = False) -> str:
|
||||
"""提取并返回合法 Reservation ID;候选不满足契约时返回空字符串。"""
|
||||
candidate = extract_reservation_id(value)
|
||||
return candidate if is_valid_reservation_id(candidate, numeric_only=numeric_only) else ""
|
||||
@@ -9,6 +9,7 @@ backend/app/services/shipping_notice/runtime_context.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
@@ -74,6 +75,9 @@ def _build_refs(
|
||||
task: ShippingTask | None,
|
||||
batch: ShippingBatch | None,
|
||||
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。
|
||||
@@ -84,6 +88,9 @@ def _build_refs(
|
||||
task: 当前任务。
|
||||
batch: 当前批次。
|
||||
run_purpose: 本次 Dify run 的目的。
|
||||
intake_nos: 点击发送时锁定的 Intake 编号集合。
|
||||
capability: 当前固定画布能力,如 order_extraction。
|
||||
contract_version: 能力输入输出契约版本。
|
||||
|
||||
Returns:
|
||||
非空业务锚点字典。
|
||||
@@ -101,6 +108,13 @@ def _build_refs(
|
||||
refs["run_purpose"] = normalized_run_purpose
|
||||
if file_name:
|
||||
refs["file_name"] = file_name
|
||||
normalized_intakes = sorted({str(item or '').strip().upper() for item in (intake_nos or []) if str(item or '').strip()})
|
||||
if normalized_intakes:
|
||||
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
|
||||
|
||||
|
||||
@@ -196,6 +210,9 @@ def build_shipping_runtime_context(
|
||||
locale: str | None = None,
|
||||
scope: str = "task_run",
|
||||
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。
|
||||
@@ -212,6 +229,9 @@ def build_shipping_runtime_context(
|
||||
locale: 用户语言。
|
||||
scope: 上下文作用域。
|
||||
run_purpose: 本次 Dify run 的目的,如 parse_notice。
|
||||
intake_nos: 尚未建 Task 时的 Intake 编号集合。
|
||||
capability: 当前固定画布能力。
|
||||
contract_version: 能力契约版本。
|
||||
|
||||
Returns:
|
||||
agent_runtime_context 字典;session_id 为空时返回空 dict。
|
||||
@@ -233,7 +253,14 @@ def build_shipping_runtime_context(
|
||||
request_id=request_id,
|
||||
trigger_source=trigger_source,
|
||||
locale=locale,
|
||||
refs=_build_refs(task=task, batch=batch, run_purpose=run_purpose),
|
||||
refs=_build_refs(
|
||||
task=task,
|
||||
batch=batch,
|
||||
run_purpose=run_purpose,
|
||||
intake_nos=intake_nos,
|
||||
capability=capability,
|
||||
contract_version=contract_version,
|
||||
),
|
||||
domain=domain,
|
||||
reference_context=reference_context,
|
||||
)
|
||||
@@ -23,6 +23,7 @@ from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_OK,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_TASK_EXISTS,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
@@ -49,7 +50,7 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task as qs_serialize_task,
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||||
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
|
||||
@@ -75,7 +76,16 @@ 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", "reservation_id", "qty", "quantity", "required_date", "uom"})
|
||||
EDITABLE_NOTICE_LINE_FIELDS = frozenset({
|
||||
"sku",
|
||||
"reservation_id",
|
||||
"qty",
|
||||
"quantity",
|
||||
"required_date",
|
||||
"uom",
|
||||
"hub_code",
|
||||
"source_type",
|
||||
})
|
||||
|
||||
|
||||
def _capture_destination_context(task: ShippingTask, parsed: dict[str, Any], lines: list[Any]) -> None:
|
||||
@@ -145,7 +155,7 @@ def _missing_reservation_lines(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
for index, line in enumerate(lines):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if extract_reservation_id(line.get("reservation_id")):
|
||||
if is_valid_reservation_id(line.get("reservation_id")):
|
||||
continue
|
||||
missing.append(
|
||||
{
|
||||
@@ -157,6 +167,55 @@ def _missing_reservation_lines(lines: list[Any]) -> list[dict[str, Any]]:
|
||||
return missing
|
||||
|
||||
|
||||
def _missing_process_field_issues(
|
||||
lines: list[Any],
|
||||
*,
|
||||
require_order_extraction_routing: bool,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
检查 Task 进入库存链前必须补齐的订单行流程字段。
|
||||
|
||||
核心逻辑:所有入口继续检查 Reservation ID;仅本期完整订单抽取契约额外检查 Source Type 与 Hub Code,
|
||||
避免把新协议强行扩散到历史手工 parse_notice 调用。
|
||||
|
||||
Args:
|
||||
lines: 已标准化的订单行。
|
||||
require_order_extraction_routing: 是否启用 v1 订单抽取的 Source Type/Hub Code 门禁。
|
||||
Returns:
|
||||
每个缺失字段对应的结构化 issue,包含行号、SKU、field 与原因。
|
||||
"""
|
||||
issues: list[dict[str, Any]] = []
|
||||
for index, line in enumerate(lines):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
sku = str(line.get('sku') or '').strip()
|
||||
raw_reservation = str(line.get('reservation_id') or '').strip()
|
||||
field_values = {
|
||||
'reservation_id': raw_reservation if is_valid_reservation_id(raw_reservation) else None,
|
||||
}
|
||||
if require_order_extraction_routing:
|
||||
field_values.update({
|
||||
'source_type': str(line.get('source_type') or '').strip() or None,
|
||||
'hub_code': str(line.get('hub_code') or '').strip() or None,
|
||||
})
|
||||
for field, value in field_values.items():
|
||||
if value:
|
||||
continue
|
||||
issues.append({
|
||||
'line_index': index,
|
||||
'sku': sku,
|
||||
'field': field,
|
||||
'reason': (
|
||||
'invalid_format'
|
||||
if field == 'reservation_id' and raw_reservation
|
||||
else 'missing'
|
||||
),
|
||||
'severity': 'blocking',
|
||||
'raw_value': str(line.get(field) or '').strip(),
|
||||
})
|
||||
return issues
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
|
||||
@@ -368,8 +427,11 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
source_content_hash=content_hash,
|
||||
source_asset_id=item.get("source_asset_id"),
|
||||
source_intake_id=item.get("source_intake_id"),
|
||||
source_candidate_id=item.get("source_candidate_id"),
|
||||
business_fingerprint=str(item.get("business_fingerprint") or "").strip() or None,
|
||||
fingerprint_version=str(item.get("fingerprint_version") or "").strip() or None,
|
||||
content_fingerprint=str(item.get("content_fingerprint") or "").strip() or None,
|
||||
content_fingerprint_version=str(item.get("content_fingerprint_version") or "").strip() or None,
|
||||
document_version=int(item.get("document_version") or 1),
|
||||
supersedes_task_id=item.get("supersedes_task_id"),
|
||||
duplicate_source_task_id=item.get("duplicate_source_task_id"),
|
||||
@@ -645,6 +707,13 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.required_date = required_date or None
|
||||
task.lines_json = lines
|
||||
task.parse_confidence = confidence
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
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)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -669,29 +738,58 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
# [STEP 3] Reservation ID 是后续匹配的硬前置;解析阶段缺失时直接阻断,禁止进入普通确认。
|
||||
missing_reservation = _missing_reservation_lines(lines)
|
||||
if missing_reservation:
|
||||
# [STEP 3] 流程字段是后续库存匹配硬前置;允许 Task 创建,但缺失时停在字段补充门禁。
|
||||
require_order_extraction_routing = (
|
||||
isinstance(structured, dict)
|
||||
and structured.get('_order_extraction_contract') == 'shipping-order-extraction-v1'
|
||||
)
|
||||
process_field_issues = _missing_process_field_issues(
|
||||
lines,
|
||||
require_order_extraction_routing=require_order_extraction_routing,
|
||||
)
|
||||
if process_field_issues:
|
||||
missing_reservation = [item for item in process_field_issues if item.get('field') == 'reservation_id']
|
||||
missing_fields = sorted({str(item.get('field') or '') for item in process_field_issues if item.get('field')})
|
||||
only_reservation_missing = missing_fields == ['reservation_id']
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
task.error_message = "解析失败:未识别到 Reservation ID / COM ID(预定单号)"
|
||||
task.error_message = (
|
||||
"解析失败:未识别到 Reservation ID / COM ID(预定单号)"
|
||||
if only_reservation_missing
|
||||
else f"订单已创建,但缺少后续处理必需字段:{', '.join(missing_fields)}"
|
||||
)
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['process_field_gate'] = {
|
||||
'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(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="failed",
|
||||
message="解析失败:未识别到预定单号",
|
||||
message="订单流程字段待补充",
|
||||
progress_percent=100,
|
||||
current=len(lines) - len(missing_reservation),
|
||||
current=max(0, len(lines) - len({int(item['line_index']) for item in process_field_issues})),
|
||||
total=len(lines),
|
||||
detail="请重新上传包含 Reservation ID / COM ID 的发货通知,或重新解析后补充预定单号。",
|
||||
extra={"warnings": warnings, "missing_reservation": missing_reservation[:5]},
|
||||
detail="可直接通过自然对话补充 Reservation ID、Source Type 或 Hub Code;补齐前不会进入库存流程。",
|
||||
extra={
|
||||
"warnings": warnings,
|
||||
"missing_reservation": missing_reservation[:5],
|
||||
"missing_process_fields": missing_fields,
|
||||
"process_field_issues": process_field_issues[:15],
|
||||
},
|
||||
)
|
||||
detail = {
|
||||
"missing_count": len(missing_reservation),
|
||||
"missing_preview": missing_reservation[:5],
|
||||
"missing_process_fields": missing_fields,
|
||||
"process_field_issues": process_field_issues[:15],
|
||||
"warnings": warnings,
|
||||
}
|
||||
log_task_event(task, "notice_reservation_id_missing", detail)
|
||||
log_task_event(task, "notice_process_fields_missing", detail)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -699,6 +797,8 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message=(
|
||||
"解析失败:未识别到 Reservation ID / COM ID(预定单号),"
|
||||
"当前任务无法继续匹配库存。请重新上传包含该字段的通知,或重新解析后补充预定单号。"
|
||||
if only_reservation_missing
|
||||
else f"订单任务已创建,但缺少 {', '.join(missing_fields)};请通过自然对话补齐后继续。"
|
||||
),
|
||||
data={**serialize_task_for_tool(task), "missing_reservation": detail},
|
||||
checkpoint=CP_RSV_REQ,
|
||||
@@ -707,7 +807,43 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 4] 无可审核内容时优先返回 notice_text_extraction_failed,不进入库存源裁决。
|
||||
# [STEP 4] 格式合法但与原文证据冲突等问题同样属于硬阻断,禁止被 LLM 高置信度绕过。
|
||||
parse_issues = parsed.get("parse_issues") if isinstance(parsed.get("parse_issues"), list) else []
|
||||
blocking_parse_issues = [
|
||||
item for item in parse_issues
|
||||
if isinstance(item, dict) and item.get("severity") == "blocking"
|
||||
]
|
||||
if blocking_parse_issues:
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
task.error_message = "解析结果与原文证据存在冲突,请人工核对关键字段。"
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
step_title="确认解析",
|
||||
status="needs_human",
|
||||
message="解析关键字段需要人工核对",
|
||||
progress_percent=100,
|
||||
current=len(lines),
|
||||
total=len(lines),
|
||||
detail="Reservation ID、SKU 或数量存在来源冲突,确认前不会进入库存匹配。",
|
||||
extra={"warnings": warnings, "parse_issues": blocking_parse_issues[:10]},
|
||||
)
|
||||
log_task_event(task, "notice_parse_validation_blocked", {"parse_issues": blocking_parse_issues[:10]})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="解析结果与原文证据存在冲突,请核对后再确认。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"parse_validation": (task.step_payload_json or {}).get("parse_validation"),
|
||||
},
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 5] 无可审核内容时优先返回 notice_text_extraction_failed,不进入库存源裁决。
|
||||
if not _has_parse_review_content(task, lines):
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings})
|
||||
@@ -724,7 +860,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
)
|
||||
|
||||
# [STEP 5] 先裁决库存源线索(写入 destination / 候选),但低置信度必须先走解析复核。
|
||||
# [STEP 6] 先裁决库存源线索(写入 destination / 候选),但低置信度必须先走解析复核。
|
||||
# 业务顺序:确认解析正确 → 再人工确认库存源 → 才允许库存/RPA。
|
||||
low_confidence = confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7)
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
@@ -767,7 +903,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
|
||||
)
|
||||
|
||||
# [STEP 6] 解析已自动接受(高置信度);库存源未稳定时才进入库存源人工确认。
|
||||
# [STEP 7] 解析已自动接受(高置信度);库存源未稳定时才进入库存源人工确认。
|
||||
if not source_stable:
|
||||
from app.services.shipping_notice.inventory_source_gate import transition_task_to_inventory_source_review
|
||||
|
||||
@@ -1020,7 +1156,44 @@ def _commit_notice_edit(
|
||||
before_lines: list[dict[str, Any]] | None = None,
|
||||
after_lines: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
existing_gate = step_payload.get('process_field_gate')
|
||||
require_order_extraction_routing = (
|
||||
isinstance(existing_gate, dict)
|
||||
and existing_gate.get('contract_version') == 'shipping-order-extraction-v1'
|
||||
)
|
||||
validation_issues = _missing_process_field_issues(
|
||||
list(task.lines_json or []),
|
||||
require_order_extraction_routing=require_order_extraction_routing,
|
||||
)
|
||||
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:
|
||||
missing_fields = sorted({str(item.get('field') or '') for item in validation_issues if item.get('field')})
|
||||
step_payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': missing_fields,
|
||||
'issues': validation_issues,
|
||||
'contract_version': (
|
||||
'shipping-order-extraction-v1'
|
||||
if require_order_extraction_routing
|
||||
else 'shipping-line-v1'
|
||||
),
|
||||
}
|
||||
else:
|
||||
step_payload.pop('process_field_gate', None)
|
||||
task.step_payload_json = step_payload
|
||||
|
||||
# [STEP 2] 解析编辑后重置下游结果并进入重新确认,避免旧匹配真相继续生效。
|
||||
apply_task_transition(
|
||||
task,
|
||||
TaskTransition.RSV_REQUIRED if validation_issues else TaskTransition.PARSE_NEEDS_REVIEW,
|
||||
)
|
||||
_reset_notice_edit_downstream(task)
|
||||
log_task_event(
|
||||
task,
|
||||
@@ -1038,7 +1211,11 @@ def _commit_notice_edit(
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="已更新解析结果,请重新确认。",
|
||||
message=(
|
||||
"已更新订单字段,但仍有后续处理必需字段待补充。"
|
||||
if validation_issues
|
||||
else "已更新解析结果,请重新确认。"
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
|
||||
@@ -2,13 +2,50 @@
|
||||
services/shipping_notice/tools.py
|
||||
|
||||
用途:发货通知 Agent Tool 统一门面(API 唯一业务入口,无编排实现)。
|
||||
依赖:task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow。
|
||||
依赖:task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow;order_extraction 延迟导入以避免建批循环依赖。
|
||||
逻辑:shipping_notice_tools / workspace_shipping_notice 仅 import 本模块公开符号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice import fulfillment_workflow, inventory_rpa_workflow, inventory_workflow, task_workflow
|
||||
from app.services.shipping_notice import (
|
||||
fulfillment_workflow,
|
||||
inventory_rpa_workflow,
|
||||
inventory_workflow,
|
||||
task_workflow,
|
||||
)
|
||||
|
||||
|
||||
def get_order_extraction_context(payload: dict):
|
||||
"""
|
||||
返回点击发送后的完整订单抽取上下文。
|
||||
【AI 触发时机】:仅在 Dify 订单抽取固定分支的 LLM 节点之前调用。
|
||||
|
||||
核心逻辑:延迟导入实现,避免 batch_from_intakes 与 Tool 门面形成模块初始化环。
|
||||
Args:
|
||||
payload: 必须包含完整 agent_runtime_context。
|
||||
Returns:
|
||||
邮件/附件文本、输入快照与抽取契约。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import get_order_extraction_context as _get
|
||||
|
||||
return _get(payload)
|
||||
|
||||
|
||||
def submit_order_extraction(payload: dict):
|
||||
"""
|
||||
提交 LLM 完整订单结果并执行自动建单。
|
||||
【AI 触发时机】:订单抽取 LLM 与 JSON 标准化节点成功后调用。
|
||||
|
||||
核心逻辑:延迟导入实现,保留 Tool 门面为唯一 API 业务入口且不引入建批循环依赖。
|
||||
Args:
|
||||
payload: 完整运行态上下文、输入快照、契约版本与 orders[]。
|
||||
Returns:
|
||||
自动建单、打开已有任务和待处理订单摘要。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction as _submit
|
||||
|
||||
return _submit(payload)
|
||||
|
||||
# 任务 / 批次 / 解析 / 决策
|
||||
create_batch = task_workflow.create_batch
|
||||
|
||||
@@ -209,6 +209,23 @@ def _append_unique_issue(issues: list[str], raw: Any) -> None:
|
||||
issues.append(text)
|
||||
|
||||
|
||||
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 "-"
|
||||
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}。"
|
||||
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 '-'} 冲突。"
|
||||
if reason == "invalid_format":
|
||||
return f"第 {line_no} 行 SKU {sku}:Reservation ID {raw_value or '空值'} 格式不合法。"
|
||||
return f"第 {line_no} 行 SKU {sku}:缺少合法的 Reservation ID。"
|
||||
|
||||
|
||||
def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> list[str]:
|
||||
"""
|
||||
汇总文件解析阶段(步骤 2)全部待处理问题,供工作台一次列出。
|
||||
@@ -253,6 +270,13 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l
|
||||
for item in warnings:
|
||||
_append_unique_issue(issues, item)
|
||||
|
||||
parse_validation = payload.get("parse_validation") if isinstance(payload, dict) else None
|
||||
structured_issues = parse_validation.get("issues") if isinstance(parse_validation, dict) else None
|
||||
if isinstance(structured_issues, list):
|
||||
for item in structured_issues:
|
||||
if isinstance(item, dict):
|
||||
_append_unique_issue(issues, _parse_validation_issue_text(item))
|
||||
|
||||
# 存量兼容:旧顺序「先库存源后解析」延后的低置信度提示。
|
||||
if payload.get("pending_parse_review_after_source") or (
|
||||
checkpoint_value == CP_INVENTORY_SOURCE_REVIEW and task.review_status == RS_PARSE_REVIEW
|
||||
|
||||
Reference in new issue
Block a user