feat(shipping-notice): 增强发货通知候选管理功能,支持候选选择、重复检测与业务摘要修订

This commit is contained in:
hugo committed 2026-07-15 11:57:04 +08:00
1 parent 70f684b94a
commit b595e157e9
83 files changed
+5857 -200

No files matched your search

+21 -2
View File
@@ -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,
),
),
)
+19
View File
@@ -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)
+42 -8
View File
@@ -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),
)
+39 -2
View File
@@ -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
@@ -0,0 +1,61 @@
"""
backend/migrations/versions/d9e0f1a2b3c4_candidate_content_fingerprint.py
用途:为候选与任务增加订单内容指纹,并补齐候选重复决策审计字段。
依赖:Alembic revision c8d9e0f1a2b3。
逻辑:身份指纹继续判断同一订单,内容指纹用于区分完全重复与修订版本。
Revision ID: d9e0f1a2b3c4
Revises: c8d9e0f1a2b3
Create Date: 2026-07-14 22:00:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'd9e0f1a2b3c4'
down_revision = 'c8d9e0f1a2b3'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""增加内容指纹与 Candidate 决策审计字段。"""
with op.batch_alter_table('shipping_tasks') as batch_op:
batch_op.add_column(sa.Column('content_fingerprint', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('content_fingerprint_version', sa.String(length=32), nullable=True))
batch_op.create_index(
'ix_shipping_tasks_user_content_fingerprint',
['user_id', 'content_fingerprint'],
unique=False,
)
with op.batch_alter_table('shipping_notice_candidates') as batch_op:
batch_op.add_column(sa.Column('content_fingerprint', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('content_fingerprint_version', sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column('duplicate_resolved_by_id', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('duplicate_resolved_at', sa.DateTime(), nullable=True))
batch_op.create_foreign_key(
'fk_shipping_notice_candidates_duplicate_resolved_by_id',
'users',
['duplicate_resolved_by_id'],
['id'],
)
def downgrade() -> None:
"""移除内容指纹与 Candidate 决策审计字段。"""
with op.batch_alter_table('shipping_notice_candidates') as batch_op:
batch_op.drop_constraint(
'fk_shipping_notice_candidates_duplicate_resolved_by_id',
type_='foreignkey',
)
batch_op.drop_column('duplicate_resolved_at')
batch_op.drop_column('duplicate_resolved_by_id')
batch_op.drop_column('content_fingerprint_version')
batch_op.drop_column('content_fingerprint')
with op.batch_alter_table('shipping_tasks') as batch_op:
batch_op.drop_index('ix_shipping_tasks_user_content_fingerprint')
batch_op.drop_column('content_fingerprint_version')
batch_op.drop_column('content_fingerprint')
@@ -0,0 +1,129 @@
"""
backend/migrations/versions/e0f1a2b3c4d5_shipping_order_extraction_state.py
用途:拆分文件预处理与订单抽取状态,并支持一个 Document 产生多个订单 Candidate。
依赖:Alembic revision d9e0f1a2b3c4。
逻辑:补齐 Intake/Document 抽取状态与 Candidate 抽取审计字段;用 candidate_key 取代一附件一候选约束。
Revision ID: e0f1a2b3c4d5
Revises: d9e0f1a2b3c4
Create Date: 2026-07-15 10:30:00.000000
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'e0f1a2b3c4d5'
down_revision = 'd9e0f1a2b3c4'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""增加订单抽取状态、审计字段与多订单 Candidate 唯一键。"""
with op.batch_alter_table('shipping_notice_intakes') as batch_op:
batch_op.add_column(
sa.Column('order_extraction_status', sa.String(length=32), server_default='not_started', nullable=False)
)
batch_op.add_column(sa.Column('order_extraction_version', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('order_extraction_error_code', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('order_extraction_error_message', sa.Text(), nullable=True))
batch_op.create_index(
'ix_shipping_notice_intakes_order_extraction_status',
['order_extraction_status'],
unique=False,
)
with op.batch_alter_table('shipping_notice_documents') as batch_op:
batch_op.add_column(
sa.Column('order_extraction_status', sa.String(length=32), server_default='not_started', nullable=False)
)
batch_op.add_column(sa.Column('order_extraction_source', sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column('order_extraction_result_json', sa.JSON(), nullable=True))
batch_op.add_column(sa.Column('order_extraction_version', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('order_extraction_error_code', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('order_extraction_error_message', sa.Text(), nullable=True))
batch_op.create_index(
'ix_shipping_notice_documents_order_extraction_status',
['order_extraction_status'],
unique=False,
)
with op.batch_alter_table('shipping_notice_candidates') as batch_op:
batch_op.add_column(sa.Column('candidate_key', sa.String(length=128), nullable=True))
batch_op.add_column(sa.Column('source_order_index', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('extraction_source', sa.String(length=32), nullable=True))
batch_op.add_column(sa.Column('extraction_version', sa.String(length=64), nullable=True))
batch_op.add_column(sa.Column('classification_confidence', sa.Float(), nullable=True))
batch_op.add_column(sa.Column('field_confidence_json', sa.JSON(), nullable=True))
batch_op.add_column(sa.Column('missing_fields_json', sa.JSON(), nullable=True))
batch_op.add_column(sa.Column('evidence_json', sa.JSON(), nullable=True))
bind = op.get_bind()
bind.execute(
sa.text(
"""
UPDATE shipping_notice_candidates
SET candidate_key = 'legacy:' || CAST(id AS VARCHAR)
WHERE candidate_key IS NULL OR candidate_key = ''
"""
)
)
with op.batch_alter_table('shipping_notice_candidates') as batch_op:
batch_op.drop_constraint('uq_shipping_notice_candidates_intake_primary_document', type_='unique')
batch_op.alter_column('candidate_key', existing_type=sa.String(length=128), nullable=False)
batch_op.create_unique_constraint(
'uq_shipping_notice_candidates_intake_key',
['intake_id', 'candidate_key'],
)
def downgrade() -> None:
"""恢复一附件一 Candidate 约束并移除订单抽取字段。"""
bind = op.get_bind()
duplicate_documents = bind.execute(
sa.text(
"""
SELECT intake_id, primary_document_id
FROM shipping_notice_candidates
GROUP BY intake_id, primary_document_id
HAVING COUNT(*) > 1
"""
)
).fetchall()
if duplicate_documents:
raise RuntimeError('cannot downgrade: multiple candidates reference the same intake document')
with op.batch_alter_table('shipping_notice_candidates') as batch_op:
batch_op.drop_constraint('uq_shipping_notice_candidates_intake_key', type_='unique')
batch_op.create_unique_constraint(
'uq_shipping_notice_candidates_intake_primary_document',
['intake_id', 'primary_document_id'],
)
batch_op.drop_column('evidence_json')
batch_op.drop_column('missing_fields_json')
batch_op.drop_column('field_confidence_json')
batch_op.drop_column('classification_confidence')
batch_op.drop_column('extraction_version')
batch_op.drop_column('extraction_source')
batch_op.drop_column('source_order_index')
batch_op.drop_column('candidate_key')
with op.batch_alter_table('shipping_notice_documents') as batch_op:
batch_op.drop_index('ix_shipping_notice_documents_order_extraction_status')
batch_op.drop_column('order_extraction_error_message')
batch_op.drop_column('order_extraction_error_code')
batch_op.drop_column('order_extraction_version')
batch_op.drop_column('order_extraction_result_json')
batch_op.drop_column('order_extraction_source')
batch_op.drop_column('order_extraction_status')
with op.batch_alter_table('shipping_notice_intakes') as batch_op:
batch_op.drop_index('ix_shipping_notice_intakes_order_extraction_status')
batch_op.drop_column('order_extraction_error_message')
batch_op.drop_column('order_extraction_error_code')
batch_op.drop_column('order_extraction_version')
batch_op.drop_column('order_extraction_status')
@@ -10,7 +10,10 @@ from app import db
from app.models import Agent, User
from app.services.chat.action_schema import TurnInput
from app.services.chat.turn_context import TurnContext
from app.services.shipping_notice.chat_action_handlers import ShippingGenerateExcelAction
from app.services.shipping_notice.chat_action_handlers import (
ShippingCreateBatchFromIntakesAction,
ShippingGenerateExcelAction,
)
def _create_task(user_id: int) -> str:
@@ -76,3 +79,62 @@ def test_generate_excel_handler_yields_ui_state_and_message(app, monkeypatch):
assert "message.completed" in event_names
completed = next(item for item in events if item.event == "message.completed")
assert "Excel 已生成" in str(completed.data.get("content") or "")
def test_create_batch_from_intakes_handler_forwards_candidate_nos(app, monkeypatch):
"""Chat Turn Candidate 建批必须把选择集合透传后端,且不得引用未定义局部变量。"""
user = User(username="candidate_handler", email="candidate-handler@example.com", role="user", status="active")
user.set_password("password")
agent = Agent(
name="货代发货通知 Agent",
description="t",
dify_api_key="k",
api_base_url="http://example.com",
agent_code="shipping_notice",
runtime_provider="hybrid",
conversation_mode="task_chat",
)
db.session.add_all([user, agent])
db.session.commit()
captured: dict = {}
def _fake_create(**kwargs):
captured.update(kwargs)
return {
"status": "ok",
"batch_no": None,
"message": "已打开已有任务,未创建新批次",
"opened_existing": [{"candidate_no": "SNC-1", "task_no": "SN-EXISTING"}],
"data": {"focus_task": {"task_no": "SN-EXISTING"}},
}
monkeypatch.setattr(
"app.services.shipping_notice.batch_from_intakes.create_shipping_batch_from_intakes",
_fake_create,
)
ctx = TurnContext(
turn_id="turn-candidate",
run_id="turn-candidate",
session_id="sess-candidate",
request_id="req-candidate",
user=user,
agent=agent,
input=TurnInput(
type="action",
display_text="确认两个订单",
action_type="shipping.create_batch_from_intakes",
payload={
"intake_nos": ["SNI-1"],
"candidate_nos": ["SNC-1", "SNC-2"],
"idempotency_key": "idem-candidate-handler",
},
),
refs={},
)
events = list(ShippingCreateBatchFromIntakesAction().stream(ctx))
assert captured["intake_nos"] == ["SNI-1"]
assert captured["candidate_nos"] == ["SNC-1", "SNC-2"]
assert captured["conversation_id"] == "sess-candidate"
assert any(event.event == "message.completed" for event in events)
+15 -1
View File
@@ -909,6 +909,19 @@ def test_parse_stage_ui_state_lists_all_issues(app):
step_payload_json={
"pending_parse_review_after_source": True,
"inventory_source_resolution": {"status": "unresolved", "candidates": []},
"parse_validation": {
"status": "needs_review",
"issues": [
{
"line_index": 0,
"sku": "A001",
"field": "reservation_id",
"reason": "invalid_format",
"severity": "blocking",
"raw_value": "1f1a682dfdc446a393415dee93eb36ce",
}
],
},
"current_step_progress": {
"extra": {
"warnings": [
@@ -927,8 +940,9 @@ def test_parse_stage_ui_state_lists_all_issues(app):
assert issues[0] == "无法根据发货通知唯一确定库存查询来源"
assert "部分订单行缺少 Reservation ID,可能影响精确匹配。" in issues
assert "解析引擎回退到启发式规则,请人工核对字段。" in issues
assert "第 1 行 SKU A001:Reservation ID 1f1a682dfdc446a393415dee93eb36ce 格式不合法。" in issues
assert "解析置信度不足,确认库存源后仍需复核解析结果。" in issues
assert len(issues) == 4
assert len(issues) == 5
def test_workspace_shipping_ui_state_is_embedded_in_workspace_reads(app, client):
@@ -25,8 +25,12 @@ from app.models import (
User,
)
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
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.duplicate_detection import (
apply_duplicate_result_to_candidate,
detect_duplicates_for_candidate,
detect_duplicates_for_intake,
)
@@ -86,6 +90,26 @@ def _seed_parsed_intake(
return asset, intake
def test_business_fingerprint_ignores_internal_hex_reservation_id():
"""内部 32 位 hex 不得增强业务身份指纹,避免把数据库主键当成订单真值。"""
summary = {
'customer_name': 'ACME',
'reservation_ids': ['1f1a682dfdc446a393415dee93eb36ce'],
'lines': [
{
'sku': 'A001',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
],
}
fingerprint = build_business_fingerprint(summary)
assert fingerprint['strength'] == 'weak'
assert 'reservation_ids' not in fingerprint['components']
def test_fingerprint_stable_across_line_order():
base = {
'customer_code': 'C1',
@@ -616,6 +640,7 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
candidate_no=f'SNC-{po}',
intake_id=intake.id,
primary_document_id=doc.id,
candidate_key=f'test:SNC-{po}',
po_number=po,
structured_result_json={'business_summary': summary},
business_fingerprint=fp.get('fingerprint'),
@@ -725,6 +750,7 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
candidate_no='SNC-REFRESH-1',
intake_id=intake.id,
primary_document_id=doc.id,
candidate_key='test:SNC-REFRESH-1',
po_number='4510099999',
structured_result_json={'business_summary': summary},
business_fingerprint=fp.get('fingerprint'),
@@ -748,3 +774,98 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
cand2 = db.session.query(ShippingNoticeCandidate).filter_by(candidate_no='SNC-REFRESH-1').one()
assert cand2.duplicate_status != 'none'
assert list(cand2.duplicate_matches_json or [])
def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(app, dedup_user):
"""身份相同且内容相同应判重复内容;数量变化应判修订。"""
with app.app_context():
base = {
'customer_code': 'C1',
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [
{
'reservation_id': '2000485916',
'sku': '504-006043-001',
'qty': 30,
'uom': 'EA',
}
],
}
identity = build_business_fingerprint(base)
content = build_content_fingerprint(base)
existing = ShippingTask(
task_no='SN-CONTENT-EXISTING',
user_id=dedup_user.id,
source_type='manual',
process_status='pending_review',
business_fingerprint=identity['fingerprint'],
fingerprint_version=identity['version'],
content_fingerprint=content['fingerprint'],
content_fingerprint_version=content['version'],
)
db.session.add(existing)
parent, intake = _seed_parsed_intake(
dedup_user.id,
intake_no='SNI-CONTENT-CHECK',
hash_value='content-parent-hash',
business_summary=base,
fingerprint=identity,
)
doc = ShippingNoticeDocument(
intake_id=intake.id,
attachment_key='att-content',
document_type='attachment',
filename='4510039227.pdf',
content_hash='different-file-hash',
classification='order_notice',
parse_status='parsed',
)
db.session.add(doc)
db.session.commit()
same = detect_duplicates_for_candidate(
intake=intake,
document=doc,
business_summary=base,
fingerprint_result=identity,
content_fingerprint_result=content,
)
changed = {**base, 'lines': [{**base['lines'][0], 'qty': 25}]}
revision = detect_duplicates_for_candidate(
intake=intake,
document=doc,
business_summary=changed,
fingerprint_result=identity,
content_fingerprint_result=build_content_fingerprint(changed),
)
assert same['status'] == 'same_business_content'
assert revision['status'] == 'possible_revision'
candidate = ShippingNoticeCandidate(
candidate_no='SNC-CONTENT-WRITEBACK',
intake_id=intake.id,
primary_document_id=doc.id,
candidate_key='test:SNC-CONTENT-WRITEBACK',
structured_result_json={'business_summary': changed},
content_fingerprint=content['fingerprint'],
content_fingerprint_version=content['version'],
)
db.session.add(candidate)
apply_duplicate_result_to_candidate(candidate, revision)
assert candidate.content_fingerprint == revision['content_fingerprint']
assert candidate.content_fingerprint != content['fingerprint']
hub_changed = {
**base,
'lines': [{**base['lines'][0], 'hub_code': 'DUB'}],
}
assert build_content_fingerprint(hub_changed)['fingerprint'] != content['fingerprint']
header_date_changed = {**base, 'required_date': '2026-07-20'}
assert build_content_fingerprint(header_date_changed)['fingerprint'] != content['fingerprint']
allocation_changed = {
**base,
'lines': [{**base['lines'][0], 'allocation_id': 'ALLOC-2'}],
}
assert build_content_fingerprint(allocation_changed)['fingerprint'] != content['fingerprint']
@@ -0,0 +1,175 @@
"""
backend/tests/test_shipping_notice_candidate_migration.py
用途:独立验证 Candidate 内容指纹及订单抽取状态迁移可执行 upgrade/downgrade,不依赖历史全量迁移链。
依赖:Alembic MigrationContext、SQLAlchemy、d9e0f1a2b3c4/e0f1a2b3c4d5 迁移模块。
逻辑:构造前一版本最小 SQLite schema,执行迁移并检查字段/约束,再验证安全回滚与多订单降级保护。
"""
from __future__ import annotations
import importlib
import pytest
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_candidate_content_fingerprint_migration_upgrade_and_downgrade():
"""本次迁移应能独立增加并完整移除内容指纹与 Candidate 决策审计字段。"""
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table(
'shipping_tasks',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('user_id', sa.Integer(), nullable=True),
)
sa.Table(
'shipping_notice_candidates',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('candidate_no', sa.String(64), nullable=False),
)
metadata.create_all(engine)
migration = importlib.import_module(
'migrations.versions.d9e0f1a2b3c4_candidate_content_fingerprint'
)
with engine.begin() as connection:
operations = Operations(MigrationContext.configure(connection))
original_op = migration.op
migration.op = operations
try:
migration.upgrade()
inspector = sa.inspect(connection)
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
candidate_columns = {
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
}
assert {'content_fingerprint', 'content_fingerprint_version'} <= task_columns
assert {
'content_fingerprint',
'content_fingerprint_version',
'duplicate_resolved_by_id',
'duplicate_resolved_at',
} <= candidate_columns
assert 'ix_shipping_tasks_user_content_fingerprint' in {
index['name'] for index in inspector.get_indexes('shipping_tasks')
}
assert 'fk_shipping_notice_candidates_duplicate_resolved_by_id' in {
foreign_key['name']
for foreign_key in inspector.get_foreign_keys('shipping_notice_candidates')
}
migration.downgrade()
inspector = sa.inspect(connection)
task_columns = {column['name'] for column in inspector.get_columns('shipping_tasks')}
candidate_columns = {
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
}
assert 'content_fingerprint' not in task_columns
assert 'content_fingerprint_version' not in task_columns
assert 'content_fingerprint' not in candidate_columns
assert 'duplicate_resolved_by_id' not in candidate_columns
finally:
migration.op = original_op
def _order_extraction_pre_migration_schema(engine: sa.Engine) -> None:
"""创建 e0f1 迁移所需的 d9 版本最小表结构与旧唯一约束。"""
metadata = sa.MetaData()
sa.Table(
'shipping_notice_intakes',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
)
sa.Table(
'shipping_notice_documents',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
)
sa.Table(
'shipping_notice_candidates',
metadata,
sa.Column('id', sa.Integer(), primary_key=True),
sa.Column('candidate_no', sa.String(64), nullable=False),
sa.Column('intake_id', sa.Integer(), nullable=False),
sa.Column('primary_document_id', sa.Integer(), nullable=False),
sa.UniqueConstraint(
'intake_id',
'primary_document_id',
name='uq_shipping_notice_candidates_intake_primary_document',
),
)
metadata.create_all(engine)
def test_order_extraction_state_migration_upgrade_and_downgrade():
"""e0f1 迁移应增加抽取状态、多订单键并可在单候选场景完整降级。"""
engine = sa.create_engine('sqlite:///:memory:')
_order_extraction_pre_migration_schema(engine)
migration = importlib.import_module(
'migrations.versions.e0f1a2b3c4d5_shipping_order_extraction_state'
)
with engine.begin() as connection:
connection.execute(sa.text(
"INSERT INTO shipping_notice_candidates "
"(id, candidate_no, intake_id, primary_document_id) VALUES (1, 'SNC-1', 10, 20)"
))
operations = Operations(MigrationContext.configure(connection))
original_op = migration.op
migration.op = operations
try:
migration.upgrade()
inspector = sa.inspect(connection)
intake_columns = {column['name'] for column in inspector.get_columns('shipping_notice_intakes')}
document_columns = {column['name'] for column in inspector.get_columns('shipping_notice_documents')}
candidate_columns = {column['name'] for column in inspector.get_columns('shipping_notice_candidates')}
assert {'order_extraction_status', 'order_extraction_version'} <= intake_columns
assert {'order_extraction_status', 'order_extraction_result_json'} <= document_columns
assert {'candidate_key', 'source_order_index', 'evidence_json'} <= candidate_columns
row = connection.execute(sa.text(
"SELECT candidate_key FROM shipping_notice_candidates WHERE id = 1"
)).one()
assert row.candidate_key == 'legacy:1'
assert 'uq_shipping_notice_candidates_intake_key' in {
item['name'] for item in inspector.get_unique_constraints('shipping_notice_candidates')
}
migration.downgrade()
inspector = sa.inspect(connection)
assert 'order_extraction_status' not in {
column['name'] for column in inspector.get_columns('shipping_notice_intakes')
}
assert 'candidate_key' not in {
column['name'] for column in inspector.get_columns('shipping_notice_candidates')
}
finally:
migration.op = original_op
def test_order_extraction_state_migration_rejects_unsafe_multi_candidate_downgrade():
"""同一 Document 已产生多个 Candidate 时,降级必须明确失败而不是丢数据。"""
engine = sa.create_engine('sqlite:///:memory:')
_order_extraction_pre_migration_schema(engine)
migration = importlib.import_module(
'migrations.versions.e0f1a2b3c4d5_shipping_order_extraction_state'
)
with engine.begin() as connection:
operations = Operations(MigrationContext.configure(connection))
original_op = migration.op
migration.op = operations
try:
migration.upgrade()
connection.execute(sa.text(
"INSERT INTO shipping_notice_candidates "
"(candidate_no, intake_id, primary_document_id, candidate_key) VALUES "
"('SNC-A', 1, 2, 'a'), ('SNC-B', 1, 2, 'b')"
))
with pytest.raises(RuntimeError, match='multiple candidates'):
migration.downgrade()
finally:
migration.op = original_op
@@ -2,7 +2,12 @@ from email.message import EmailMessage
from pathlib import Path
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
from app.services.shipping_notice.order_candidate_builder import (
build_email_order_index,
merge_attachment_candidate,
)
from app.services.shipping_notice.notice_lines import (
adjudicate_notice_lines,
normalize_notice_line,
parse_notice_table_rows,
parse_notice_table_text,
@@ -129,6 +134,71 @@ def test_extract_notice_text_reads_xfa_pdf_datasets():
assert "EINDT=2026-06-23" in text
def test_email_body_order_index_and_attachment_fusion_by_po():
"""截图型邮件正文应解析三条订单,并按 PO 将正文分配字段融合到对应附件候选。"""
body = """
allocation_id\tReservation N.r\tsource type\tAllocated HHPN\tAllocated APN\tAllocated QTY\tMPN\tHub Code\tPO
S-ENC-FOBU260702-286\t2000485916\tVMI-FRA01\tTEMP-S000218922\t504-006043-001\t30\tD4-A08AR12000001\tFRA01\t4510039227
S-BRA-FOBU260702-187\t2000485915\tVMI-FRA01\tTEMP-S000196207\t504-006076-001\t60\tD4-AR1200115A1\tFRA01\t4510039228
S-ENCFOX260705BG977W\t1000148820\tDBS DUB\tTEMP-S000218922\t504-006043-001\t1\tD4-A08AR12000001\tDUB\t4510039229
"""
rows = build_email_order_index(body)
assert len(rows) == 3
assert rows[0]['po_number'] == '4510039227'
assert rows[0]['reservation_id'] == '2000485916'
assert rows[0]['sku'] == '504-006043-001'
assert rows[0]['qty'] == 30
assert rows[0]['source_type'] == 'VMI-FRA01'
assert rows[0]['customer_sku'] == 'TEMP-S000218922'
assert rows[0]['vendor_part_number'] == 'D4-A08AR12000001'
assert rows[0]['hub_code'] == 'FRA01'
assert rows[2]['hub_code'] == 'DUB'
fused = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
)
line = fused['business_summary']['lines'][0]
assert fused['validation_status'] == 'ready'
assert not fused['conflicts']
assert line['source_type'] == 'VMI-FRA01'
assert line['customer_sku'] == 'TEMP-S000218922'
assert line['hub_code'] == 'FRA01'
conflict = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['2000485916'],
'lines': [{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 20, 'uom': 'EA'}],
},
filename='4510039227.pdf',
body_rows=rows,
)
assert conflict['validation_status'] == 'needs_review'
assert conflict['conflicts'][0]['field'] == 'qty'
multi_line = merge_attachment_candidate(
attachment_summary={
'po_number': '4510039227',
'reservation_ids': ['OTHER', '2000485916'],
'lines': [
{'reservation_id': 'OTHER', 'sku': 'OTHER-SKU', 'qty': 5},
{'reservation_id': '2000485916', 'sku': '504-006043-001', 'qty': 30},
],
},
filename='4510039227.pdf',
body_rows=rows,
)
assert multi_line['validation_status'] == 'ready'
assert 'source_type' not in multi_line['business_summary']['lines'][0]
assert multi_line['business_summary']['lines'][1]['source_type'] == 'VMI-FRA01'
def test_extract_eml_with_three_pdf_attachments(tmp_path):
"""带 3 个 PDF 附件的 EML:attachment_count=3,且各附件独立抽到文本。"""
from app.services.shipping_notice.notice_upload import extract_notice_text
@@ -634,6 +704,29 @@ def test_extract_eml_html_table_keeps_row_boundaries(tmp_path):
assert "4510039227\t30" in body.replace(" ", "")
def test_extract_eml_html_table_preserves_empty_cells(tmp_path):
"""HTML 表格空单元格必须保留列占位,避免不同邮件模板的尾部业务字段整体错位。"""
from email.message import EmailMessage
from app.services.shipping_notice.notice_upload import extract_notice_text
html = (
"<table>"
"<tr><th>SKU</th><th>Parent allocation ID</th><th>External reservation ID</th></tr>"
"<tr><td>A001</td><td></td><td>AWS-311</td></tr>"
"</table>"
)
msg = EmailMessage()
msg.set_content(html, subtype="html")
path = tmp_path / "html-empty-cell.eml"
path.write_bytes(msg.as_bytes())
_, meta = extract_notice_text(path)
body = meta["email"]["body_text"].replace(" ", "")
assert "A001\t\tAWS-311" in body
def test_extract_eml_nested_eml_file_respects_depth(tmp_path):
"""嵌套 .eml 文件附件须共享深度/限额,不得重置 depth=0 无限展开。"""
from email.message import EmailMessage
@@ -1134,6 +1227,76 @@ def test_extract_reservation_id_from_pr_number():
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
def test_external_reservation_id_corrects_invalid_llm_candidate_with_column_evidence():
"""明确 TSV 列关系与唯一 MPN 关联时,应把 32 位内部 ID 纠正为 External Reservation ID。"""
raw_text = (
"Allocated APN\tMPN\tAllocated QTY\tCommodity group ID\tExternal reservation ID\n"
"504-006055-001\tD4-A08AR12000002\t10\t"
"1f1a682dfdc446a393415dee93eb36ce\t3000092917"
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"vendor_part_number": "D4-A08AR12000002",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
}
]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
assert status == "ready"
assert adjudicated[0]["reservation_id"] == "3000092917"
assert issues == [
{
"line_index": 0,
"sku": "TEMP-S000218929/D4-A08AR12000002",
"field": "reservation_id",
"reason": "value_corrected",
"severity": "info",
"raw_value": "1f1a682dfdc446a393415dee93eb36ce",
"resolved_value": "3000092917",
"resolution_basis": "email_table.External reservation ID",
}
]
def test_flattened_text_does_not_guess_external_reservation_id():
"""纯文本缺少列边界时不得因附近存在数字而自动修正 Reservation ID。"""
raw_text = (
"Commodity group ID External reservation ID "
"1f1a682dfdc446a393415dee93eb36ce 3000092917"
)
lines = [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"qty": 10,
"uom": "EA",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
}
]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
assert status == "needs_review"
assert "reservation_id" not in adjudicated[0]
assert issues[0]["reason"] == "invalid_format"
assert issues[0]["severity"] == "blocking"
def test_adjudication_supports_non_numeric_reservation_templates():
"""不同来源模板可使用字母型 Reservation ID,后端只排除内部 ID,不绑定单一数字模板。"""
raw_text = "AWS Sku\tReservation Order\tQty\nA001\tAWS-311\t2"
lines = [{"sku": "A001", "reservation_id": "", "qty": 2, "uom": "EA"}]
adjudicated, issues, status = adjudicate_notice_lines(lines, raw_text=raw_text)
assert status == "ready"
assert adjudicated[0]["reservation_id"] == "AWS-311"
assert issues[0]["reason"] == "value_corrected"
def test_wistron_po_table_with_pr_number_in_document():
text = """
Vendor: HOXIN
@@ -1,7 +1,16 @@
"""
tests/test_shipping_notice_field_alignment_summary.py
用途:验证库存字段对齐摘要的固定结构、多语言中文文案与警告合并行为。
依赖:shipping_notice.field_alignment_summary。
逻辑:构造字段映射预览并断言聊天区展示内容符合结构化按钮交互契约。
"""
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
def test_format_field_alignment_summary_single_block():
"""字段对齐摘要应展示映射证据,并提示用户使用结构化按钮继续。"""
field_alignment = {
"match_rule": "按 AWS Sku + Reservation Order 汇总 Qty Available 与订单 qty 比对。",
"match_rule_source": "llm",
@@ -39,10 +48,12 @@ def test_format_field_alignment_summary_single_block():
assert "订单样例:" in text
assert "预订单号 1000140351" in text
assert "料号 504-010213-001" in text
assert "回复「确认」进入匹配" in text
assert "请核对字段对齐后使用下方按钮继续" in text
assert "回复「确认」进入匹配" not in text
def test_format_field_alignment_summary_includes_warnings():
"""调用方警告与字段对齐警告都应合并展示。"""
text = format_field_alignment_summary(
task_no="SN-1",
field_alignment={
+548 -12
View File
@@ -29,6 +29,10 @@ from app.models import (
from app.services.file_assets.service import upload_file_asset
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
from app.services.shipping_notice.business_fingerprint import (
build_business_fingerprint,
build_content_fingerprint,
)
@pytest.fixture
@@ -44,6 +48,538 @@ def _make_upload(content: bytes = b'customer order line', filename: str = 'notic
return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain')
def test_candidate_review_duplicate_api_and_access_guards(app, client):
"""Candidate API 应支持修订、刷新和决策,并阻止越权或已消费候选修改。"""
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
owner = User(username='candidate-owner', email='candidate-owner@example.com', password_hash='x')
other = User(username='candidate-other', email='candidate-other@example.com', password_hash='x')
db.session.add_all([owner, other])
db.session.flush()
asset = FileAsset(
asset_no='FA-CANDIDATE-API-001',
owner_user_id=owner.id,
original_filename='order-7001.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{owner.id}/order-7001.pdf',
content_hash='candidate-api-content-hash',
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-CANDIDATE-API-001',
asset_id=asset.id,
user_id=owner.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key='attachment-1',
filename='order-7001.pdf',
content_hash=asset.content_hash,
classification='order_notice',
parse_status='parsed',
)
existing = ShippingTask(
task_no='SN-CANDIDATE-EXISTING-001',
user_id=owner.id,
source_content_hash=asset.content_hash,
process_status='created',
)
db.session.add_all([document, existing])
db.session.flush()
candidate = ShippingNoticeCandidate(
candidate_no='SNC-CANDIDATE-API-001',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='test:SNC-CANDIDATE-API-001',
po_number='7001',
structured_result_json={
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 1}],
},
},
validation_status='needs_review',
conflicts_json=[{'field': 'qty'}],
selected=True,
duplicate_resolution='open_existing',
duplicate_target_task_no=existing.task_no,
duplicate_resolved_by_id=owner.id,
duplicate_resolved_at=datetime.utcnow(),
)
db.session.add(candidate)
db.session.commit()
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
patch_response = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={
'selected': False,
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': 'R-1', 'sku': 'SKU-1', 'qty': 2}],
},
},
headers=owner_headers,
)
assert patch_response.status_code == 200
patched = patch_response.get_json()['data']
assert patched['selected'] is False
assert patched['validation_status'] == 'ready'
assert patched['conflicts'] == []
assert patched['content_fingerprint']
assert patched['duplicate_resolution'] is None
forbidden = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={'selected': True},
headers=other_headers,
)
assert forbidden.status_code == 404
refresh = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/duplicate-refresh',
headers=owner_headers,
)
assert refresh.status_code == 200
refreshed = refresh.get_json()['data']
assert refreshed['duplicate']['status'] == 'exact_file'
assert 'open_existing' in refreshed['duplicate']['allowed_actions']
resolution = client.post(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001/duplicate-resolution',
json={'action': 'open_existing', 'target_task_no': 'SN-CANDIDATE-EXISTING-001'},
headers=owner_headers,
)
assert resolution.status_code == 200
assert resolution.get_json()['data']['duplicate_resolution']['action'] == 'open_existing'
with app.app_context():
row = db.session.query(ShippingNoticeCandidate).filter_by(
candidate_no='SNC-CANDIDATE-API-001',
).one()
row.consumed_task_id = db.session.query(ShippingTask).filter_by(
task_no='SN-CANDIDATE-EXISTING-001',
).one().id
db.session.commit()
consumed = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={'selected': True},
headers=owner_headers,
)
assert consumed.status_code == 409
def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
"""人工修订不得以空摘要或无效 SKU/Qty 绕过 Candidate 审核门禁。"""
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
user = User(username='candidate-validation', email='candidate-validation@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-CANDIDATE-VALIDATION',
owner_user_id=user.id,
original_filename='invalid-order.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user.id}/invalid-order.pdf',
content_hash='candidate-validation-hash',
file_size=10,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-CANDIDATE-VALIDATION',
asset_id=asset.id,
user_id=user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key='invalid-order',
filename='invalid-order.pdf',
content_hash=asset.content_hash,
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
candidate = ShippingNoticeCandidate(
candidate_no='SNC-CANDIDATE-VALIDATION',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='test:SNC-CANDIDATE-VALIDATION',
structured_result_json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 1}]}},
validation_status='needs_review',
selected=True,
)
db.session.add(candidate)
db.session.commit()
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
empty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {}},
headers=headers,
)
assert empty.status_code == 400
assert empty.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
invalid_qty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {'lines': [{'sku': 'SKU-1', 'qty': 0}]}},
headers=headers,
)
assert invalid_qty.status_code == 400
invalid_reservation = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={
'business_summary': {
'lines': [
{
'sku': 'SKU-1',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
]
}
},
headers=headers,
)
assert invalid_reservation.status_code == 400
assert invalid_reservation.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
invalid_selected = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'selected': 'false'},
headers=headers,
)
assert invalid_selected.status_code == 400
null_summary = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': None},
headers=headers,
)
assert null_summary.status_code == 400
def test_candidate_batch_gate_rejects_incomplete_expired_and_selection_drift(app, shipping_user):
"""Candidate 建批必须继承附件完整性/过期门禁,并要求传入集合等于服务端已选集合。"""
with app.app_context():
parent = FileAsset(
asset_no='FA-CANDIDATE-GATE',
owner_user_id=shipping_user.id,
original_filename='gate.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/gate.eml',
content_hash='candidate-gate-parent',
file_size=100,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(parent)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-CANDIDATE-GATE',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
structured_result_json={
'attachment_count': 1,
'attachments': [{'parse_status': 'failed', 'filename': 'gate.pdf'}],
},
)
db.session.add(intake)
db.session.flush()
candidates = []
for index in (1, 2):
document = ShippingNoticeDocument(
intake_id=intake.id,
document_type='attachment',
attachment_key=f'gate-{index}',
filename=f'gate-{index}.pdf',
content_hash=f'candidate-gate-{index}',
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
summary = {'po_number': f'PO-{index}', 'lines': [{'sku': f'SKU-{index}', 'qty': index}]}
candidate = ShippingNoticeCandidate(
candidate_no=f'SNC-CANDIDATE-GATE-{index}',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key=f'test:SNC-CANDIDATE-GATE-{index}',
structured_result_json={'business_summary': summary},
validation_status='ready',
conflicts_json=[],
selected=True,
duplicate_status='none',
)
db.session.add(candidate)
candidates.append(candidate)
db.session.commit()
with pytest.raises(ConflictError) as incomplete:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-gate',
intake_nos=[intake.intake_no],
candidate_nos=[candidate.candidate_no for candidate in candidates],
)
assert incomplete.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
db.session.rollback()
intake.structured_result_json = {'attachment_count': 0, 'attachments': []}
intake.expires_at = datetime(2020, 1, 1)
db.session.commit()
with pytest.raises(ConflictError) as expired:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-gate',
intake_nos=[intake.intake_no],
candidate_nos=[candidate.candidate_no for candidate in candidates],
)
assert expired.value.code == 'SHIPPING_NOTICE.INTAKE_EXPIRED'
db.session.rollback()
intake.expires_at = None
db.session.commit()
with pytest.raises(ConflictError) as changed:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-gate',
intake_nos=[intake.intake_no],
candidate_nos=[candidates[0].candidate_no],
)
assert changed.value.code == 'SHIPPING_NOTICE.CANDIDATE_SELECTION_CHANGED'
for candidate in candidates:
candidate.selected = False
db.session.commit()
with pytest.raises(ValidationError) as none_selected:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-gate',
intake_nos=[intake.intake_no],
candidate_nos=None,
)
assert none_selected.value.code == 'SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED'
def test_candidate_era_intake_without_candidates_cannot_fallback_to_single_eml_task(app, shipping_user):
"""v6 Intake 无 Candidate 时必须阻断,不得退回整封 EML 建一个旧式 Task。"""
with app.app_context():
asset = FileAsset(
asset_no='FA-CANDIDATE-MISSING',
owner_user_id=shipping_user.id,
original_filename='missing-candidates.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/missing-candidates.eml',
content_hash='candidate-missing-hash',
file_size=100,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-CANDIDATE-MISSING',
asset_id=asset.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
structured_result_json={'attachment_count': 0, 'attachments': []},
)
db.session.add(intake)
db.session.commit()
with pytest.raises(ValidationError) as missing:
create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-missing-candidate',
intake_nos=[intake.intake_no],
)
assert missing.value.code == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
assert db.session.query(ShippingTask).filter_by(source_intake_id=intake.id).count() == 0
def test_one_eml_intake_candidates_create_one_batch_multiple_tasks(app, shipping_user, monkeypatch):
"""一封邮件的三个已审核 Candidate 应创建一个批次和三个独立 Task,并支持幂等重放。"""
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
with app.app_context():
parent = FileAsset(
asset_no='FA-CANDIDATE-BATCH',
owner_user_id=shipping_user.id,
original_filename='three-orders.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/three-orders.eml',
content_hash='eml-three-orders',
file_size=1000,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(parent)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-CANDIDATE-BATCH',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
extracted_text='three orders',
structured_result_json={
'attachment_count': 3,
'attachment_registered_count': 3,
'attachments': [
{'filename': f'{po}.pdf', 'parse_status': 'parsed'}
for po in ('4510039227', '4510039228', '4510039229')
],
},
)
db.session.add(intake)
db.session.flush()
candidate_nos = []
hashes = []
for index, po in enumerate(('4510039227', '4510039228', '4510039229'), start=1):
attachment = FileAsset(
asset_no=f'FA-CAND-{index}',
owner_user_id=shipping_user.id,
parent_asset_id=parent.id,
asset_role='derived_attachment',
source_attachment_key=f'att-{index}',
original_filename=f'{po}.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{shipping_user.id}/{po}.pdf',
content_hash=f'pdf-hash-{po}',
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='referenced',
)
db.session.add(attachment)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id,
asset_id=attachment.id,
attachment_key=f'att-{index}',
document_type='attachment',
filename=f'{po}.pdf',
content_hash=attachment.content_hash,
classification='order_notice',
parse_status='parsed',
extracted_text=f'PO Number: {po} SKU-{index} x {index}',
)
db.session.add(document)
db.session.flush()
summary = {
'customer_code': 'C1',
'po_number': po,
'reservation_ids': [f'20004859{index:02d}'],
'lines': [
{
'reservation_id': f'20004859{index:02d}',
'sku': f'SKU-{index}',
'qty': index,
'uom': 'EA',
}
],
}
identity = build_business_fingerprint(summary)
content = build_content_fingerprint(summary)
candidate = ShippingNoticeCandidate(
candidate_no=f'SNC-CAND-BATCH-{index}',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key=f'test:SNC-CAND-BATCH-{index}',
po_number=po,
structured_result_json={'business_summary': summary},
validation_status='ready',
conflicts_json=[],
selected=True,
business_fingerprint=identity['fingerprint'],
fingerprint_version=identity['version'],
fingerprint_strength=identity['strength'],
content_fingerprint=content['fingerprint'],
content_fingerprint_version=content['version'],
duplicate_status='none',
)
db.session.add(candidate)
candidate_nos.append(candidate.candidate_no)
hashes.append(attachment.content_hash)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.batch_orchestrator.start_batch_orchestrator',
lambda _batch_no: False,
)
first = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-candidate-batch',
intake_nos=[intake.intake_no],
candidate_nos=candidate_nos,
create_idempotency_key='candidate-batch-idem',
)
assert first['batch_no']
batch = db.session.query(ShippingBatch).filter_by(batch_no=first['batch_no']).one()
tasks = db.session.query(ShippingTask).filter_by(batch_id=batch.id).order_by(ShippingTask.id).all()
assert len(tasks) == 3
assert {task.source_content_hash for task in tasks} == set(hashes)
assert all(task.source_candidate_id for task in tasks)
assert len({task.source_candidate_id for task in tasks}) == 3
replay = create_shipping_batch_from_intakes(
user_id=shipping_user.id,
conversation_id='conv-candidate-batch',
intake_nos=[intake.intake_no],
candidate_nos=candidate_nos,
create_idempotency_key='candidate-batch-idem',
)
assert replay['idempotent_replay'] is True
assert replay['batch_no'] == first['batch_no']
def test_upload_file_asset_creates_ready_record(app, shipping_user):
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
@@ -2740,12 +3276,12 @@ def _minimal_pdf_bytes(marker: str) -> bytes:
return bytes(out)
def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
def test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candidates(
app, shipping_user, monkeypatch,
):
"""
阶段二验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document + 3 Candidate;
正文订单表不额外生成第 4 候选;各 PDF 独立 FileAsset;重试不膨胀。
上传预处理验收:3 个含真实 PO 的 PDF → 正文 Document(email_context) + 3 PDF Document;
点击发送前不生成 Candidate;各 PDF 独立 FileAsset;重试不膨胀。
"""
from email.message import EmailMessage
@@ -2845,14 +3381,13 @@ def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
assert len(pdf_docs) == 3
assert all(d.classification == 'order_notice' for d in pdf_docs)
assert all(d.asset_id for d in pdf_docs)
assert len(cands) == 3
assert all(c.primary_document_id != body_docs[0].id for c in cands)
assert len(cands) == 0
assert len(children) == 3
assert len({c.content_hash for c in children}) == 3
detail = serialize_intake(refreshed_intake, asset=parent, include_parse_texts=True)
assert detail['document_count'] == 4
assert detail['candidate_count'] == 3
assert detail['candidate_count'] == 0
intake2 = (
db.session.query(ShippingNoticeIntake)
@@ -2871,7 +3406,7 @@ def test_run_intake_parse_three_pdfs_creates_documents_candidates_and_assets(
.id
)
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=intake_id).count() == 4
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 3
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=intake_id).count() == 0
assert (
db.session.query(FileAsset)
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
@@ -3002,10 +3537,10 @@ def test_stage2_persist_failure_marks_parse_failed_and_allows_retry(
assert retried['parse_status'] == 'queued'
def test_candidate_dedup_savepoint_failure_keeps_stage2_and_unchecked(
def test_upload_preprocess_does_not_invoke_candidate_dedup(
app, shipping_user, monkeypatch,
):
"""Candidate 重复检测异常仅 SAVEPOINT 回滚:Document/Candidate 保留,去重为 unchecked。"""
"""上传预处理只落 Document;订单 Candidate 判重函数即使不可用也不影响预处理。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
@@ -3055,16 +3590,17 @@ def test_candidate_dedup_savepoint_failure_keeps_stage2_and_unchecked(
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parsed'
assert result.get('duplicate_status') == 'unchecked'
assert result.get('candidate_count') == 0
assert result.get('order_extraction_status') == 'not_started'
db.session.expire_all()
refreshed = db.session.query(ShippingNoticeIntake).filter_by(
intake_no='SNI-DEDUP-SAVEPOINT'
).one()
assert refreshed.parse_status == 'parsed'
assert refreshed.duplicate_status == 'unchecked'
assert refreshed.order_extraction_status == 'not_started'
assert refreshed.duplicate_matches_json in (None, [])
assert db.session.query(ShippingNoticeDocument).filter_by(intake_id=refreshed.id).count() >= 1
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=refreshed.id).count() >= 1
assert db.session.query(ShippingNoticeCandidate).filter_by(intake_id=refreshed.id).count() == 0
def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
@@ -67,6 +67,17 @@ def test_parse_aws_inventory_headers(app):
assert lines[1]["odm_id"] == "16754797"
def test_parse_inventory_drops_internal_hex_reservation_id(app):
"""库存快照可保留 SKU/数量,但内部 hex 不得写入 Reservation ID 字段。"""
with app.app_context():
lines = parse_inventory_rows(
["AWS Sku", "COM ID", "Qty Available"],
[["A001", "1f1a682dfdc446a393415dee93eb36ce", 2]],
)
assert lines == [{"sku": "A001", "available_qty": 2.0}]
def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "ODM ID"]
@@ -0,0 +1,259 @@
"""
backend/tests/test_shipping_notice_order_extraction.py
用途:验证点击发送后的 Dify 完整订单抽取、订单级 Candidate、自动建单和安全门禁。
依赖:agent_runtime_context builder、order_extraction、Shipping Notice 模型与 pytest Flask fixture。
逻辑:构造一封已预处理邮件及单个附件,模拟 Chatflow 读取快照并提交多个 orders[],断言部分成功、幂等与来源漂移。
"""
from __future__ import annotations
import json
import pytest
from app import db
from app.core.errors import ConflictError
from app.models import (
Agent,
ChatSession,
FileAsset,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingTask,
User,
)
from app.services.agent_runtime_context.builder import build_agent_runtime_context, serialize_for_dify
from app.services.shipping_notice.order_extraction import (
EXTRACTION_CONTRACT_VERSION,
get_order_extraction_context,
submit_order_extraction,
)
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.task_workflow import update_notice_line
def _seed_extraction_input() -> tuple[User, ChatSession, ShippingNoticeIntake, ShippingNoticeDocument, str]:
"""
创建一封已完成上传预处理的邮件、单个附件和对应统一运行态上下文。
Returns:
用户、会话、Intake、Document 与序列化 agent_runtime_context。
"""
user = User(username='order-extraction-user', email='order-extraction@example.com', password_hash='x')
agent = Agent(
name='Shipping Notice',
agent_code='shipping_notice',
dify_app_id='shipping-order-extraction-test',
dify_api_key='test-key',
)
db.session.add_all([user, agent])
db.session.flush()
session = ChatSession(
session_id='shipping-order-extraction-session',
user_id=int(user.id),
agent_id=int(agent.id),
title='Order extraction',
)
asset = FileAsset(
asset_no='FA-ORDER-EXTRACTION-001',
owner_user_id=int(user.id),
original_filename='orders.eml',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user.id}/orders.eml',
content_hash='order-extraction-parent-hash',
file_size=256,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add_all([session, asset])
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-ORDER-EXTRACTION-001',
asset_id=int(asset.id),
user_id=int(user.id),
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
order_extraction_status='not_started',
structured_result_json={'rule_hints': {'attachment_count': 1}},
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=int(intake.id),
asset_id=int(asset.id),
document_type='attachment',
attachment_key='orders.pdf',
filename='orders.pdf',
content_hash='order-extraction-document-hash',
classification='order_notice',
parse_status='parsed',
extracted_text=(
'PO 4510000001 SKU SKU-A QTY 10 RSV R-100 SOURCE AWS Dublin HUB DUB\n'
'PO 4510000002 SKU SKU-B QTY 20'
),
)
db.session.add(document)
db.session.commit()
context = build_agent_runtime_context(
agent_code='shipping_notice',
session_id=session.session_id,
request_id='req-order-extraction-001',
refs={
'capability': 'order_extraction',
'contract_version': EXTRACTION_CONTRACT_VERSION,
'intake_nos': json.dumps([intake.intake_no], separators=(',', ':')),
'run_purpose': 'order_extraction',
},
)
return user, session, intake, document, serialize_for_dify(context)
def _order(
*,
intake_no: str,
document_id: int,
po_number: str,
sku: str,
qty: int,
confidence: float = 0.99,
include_process_fields: bool,
) -> dict:
"""构造符合 Chatflow v1 契约的单个订单结果。"""
line = {'sku': sku, 'qty': qty}
if include_process_fields:
line.update({'reservation_id': 'R-100', 'source_type': 'AWS Dublin', 'hub_code': 'DUB'})
return {
'source_intake_no': intake_no,
'primary_document_id': document_id,
'candidate_key_hint': po_number,
'classification': 'shipping_request',
'classification_confidence': confidence,
'field_confidence': {'sku': confidence, 'qty': confidence},
'po_number': po_number,
'lines': [line],
'evidence': [
{'field': 'lines[0].sku', 'quote': f'SKU {sku}', 'document_id': document_id},
{'field': 'lines[0].qty', 'quote': f'QTY {qty}', 'document_id': document_id},
],
'conflicts': [],
}
def test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay(app):
"""一个附件可产生多 Candidate;高置信订单自动建单,低置信订单保留,重试只回放。"""
with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
# 断言读取 Tool 返回不可变快照,并把 Intake 绑定到当前会话。
assert context_result['status'] == 'ok'
assert context_result['intake_nos'] == [intake.intake_no]
assert context_result['documents'][0]['document_id'] == document.id
snapshot = context_result['input_snapshot_hash']
payload = {
'agent_runtime_context': runtime_context,
'input_snapshot_hash': snapshot,
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000001',
sku='SKU-A',
qty=10,
include_process_fields=False,
),
_order(
intake_no=intake.intake_no,
document_id=int(document.id),
po_number='4510000002',
sku='SKU-B',
qty=20,
confidence=0.60,
include_process_fields=True,
),
],
}
result = submit_order_extraction(payload)
# 断言一附件拆成两个 Candidate,仅高置信订单创建 Task,Intake 保留为部分完成。
assert result['auto_created_count'] == 1
assert result['pending_count'] == 1
assert result['batch_no']
candidates = ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).all()
assert len(candidates) == 2
assert len({item.candidate_key for item in candidates}) == 2
tasks = ShippingTask.query.filter_by(user_id=int(user.id)).all()
assert len(tasks) == 1
task = tasks[0]
assert task.process_status == 'pending_review'
assert task.pending_human_reason == 'rsv_req'
assert (task.step_payload_json or {})['process_field_gate']['missing_fields'] == [
'hub_code',
'reservation_id',
'source_type',
]
db.session.refresh(intake)
assert intake.parse_status == 'parsed'
assert intake.order_extraction_status == 'partially_completed'
db.session.refresh(document)
assert len((document.order_extraction_result_json or {})['candidate_keys']) == 2
# 断言后台或自然语言“继续”无法绕过字段门禁进入库存流程。
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
progress = auto_progress({'task_id': task.task_no})
assert progress['status'] == 'needs_human'
assert progress['checkpoint'] == 'rsv_req'
assert 'ensure_inventory' in progress['forbidden_next_tools']
replay = submit_order_extraction(payload)
assert replay['idempotent_replay'] is True
assert ShippingTask.query.filter_by(user_id=int(user.id)).count() == 1
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 2
edit_result = update_notice_line({
'task_id': task.task_no,
'line_index': 0,
'patch': {
'reservation_id': 'R-100',
'source_type': 'AWS Dublin',
'hub_code': 'DUB',
},
'comment': '用户通过自然对话补齐流程字段',
})
db.session.refresh(task)
# 断言既有行更新 Tool 可完成自然对话补字段,并清除旧流程字段门禁。
assert edit_result['status'] == 'ok'
assert task.pending_human_reason == 'low_confidence'
assert 'process_field_gate' not in (task.step_payload_json or {})
assert task.lines_json[0]['reservation_id'] == 'R-100'
assert task.lines_json[0]['source_type'] == 'AWS Dublin'
assert task.lines_json[0]['hub_code'] == 'DUB'
assert session.user_id == user.id
def test_submit_order_extraction_rejects_changed_document_snapshot(app):
"""读取上下文后附件文本变化时,旧 LLM 结果不得覆盖新来源。"""
with app.app_context():
_user, _session, intake, document, runtime_context = _seed_extraction_input()
context_result = get_order_extraction_context({'agent_runtime_context': runtime_context})
document.extracted_text = f'{document.extracted_text}\nCHANGED'
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
submit_order_extraction({
'agent_runtime_context': runtime_context,
'input_snapshot_hash': context_result['input_snapshot_hash'],
'schema_version': EXTRACTION_CONTRACT_VERSION,
'orders': [],
})
# 断言来源漂移使用稳定错误码,要求 Dify 重新读取上下文而不是重放旧结果。
assert exc_info.value.code == 'SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED'
assert ShippingNoticeCandidate.query.filter_by(intake_id=int(intake.id)).count() == 0
@@ -1,5 +1,9 @@
from app.services.shipping_notice.match import match_notice_lines
from app.services.shipping_notice.reservation_id import normalize_reservation_id
from app.services.shipping_notice.reservation_id import (
is_valid_reservation_id,
normalize_reservation_id,
validated_reservation_id,
)
def test_match_numeric_reservation_id():
@@ -13,3 +17,13 @@ def test_match_numeric_reservation_id():
def test_normalize_reservation_id_string():
assert normalize_reservation_id("1000140351") == "1000140351"
def test_reservation_contract_rejects_internal_hex_but_keeps_business_ids():
"""硬契约应拒绝内部 hex 主键,同时兼容已有字母型业务 Reservation ID。"""
assert not is_valid_reservation_id("1f1a682dfdc446a393415dee93eb36ce")
assert validated_reservation_id("1f1a682dfdc446a393415dee93eb36ce") == ""
assert is_valid_reservation_id("3000092917")
assert is_valid_reservation_id("AWS-311")
assert is_valid_reservation_id("R-1")
assert not is_valid_reservation_id("AWS-311", numeric_only=True)
+134 -1
View File
@@ -121,7 +121,14 @@ def test_shipping_notice_tool_flow(app, client):
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"lines": [{
"sku": "A001",
"reservation_id": "R-1",
"qty": 10,
"uom": "EA",
"source_type": "AWS Dublin",
"hub_code": "DUB",
}],
"confidence": 0.95,
},
},
@@ -1297,6 +1304,132 @@ def test_parse_notice_blocks_when_reservation_id_missing(app, client, monkeypatc
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_blocks_invalid_nonempty_reservation_id(app, client, monkeypatch):
"""非空内部 hex ID 仍应被后端硬闸门阻断,并在 step_payload 留存解析问题。"""
import app.services.shipping_notice.task_workflow as task_workflow
monkeypatch.setattr(task_workflow, "start_task_orchestrator", lambda task_no: True)
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"raw_text": "Commodity group ID External reservation ID 1f1a682dfdc446a393415dee93eb36ce 3000092917",
"structured": {
"lines": [
{
"sku": "TEMP-S000218929/D4-A08AR12000002",
"reservation_id": "1f1a682dfdc446a393415dee93eb36ce",
"qty": 10,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
data = parse_res.get_json()
assert data["status"] == "needs_human"
assert data["checkpoint"] == "rsv_req"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert "reservation_id" not in task.lines_json[0]
validation = (task.step_payload_json or {})["parse_validation"]
assert validation["status"] == "needs_review"
assert validation["issues"][0]["reason"] == "invalid_format"
@pytest.mark.auto_rpa
def test_human_edit_revalidates_reservation_and_blocks_stale_confirm(app, client, monkeypatch):
"""人工修订应重算硬契约;非法值不能确认,改成合法字母型业务 ID 后清除阻断。"""
import app.services.shipping_notice.decision_workflow as decision_workflow
monkeypatch.setattr(decision_workflow, "start_task_orchestrator", lambda task_no: True)
headers = _tool_headers(app)
task_id = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
).get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"lines": [{"sku": "A001", "reservation_id": "1000140351", "qty": 2, "uom": "EA"}],
"confidence": 0.4,
},
},
)
invalid_edit = client.post(
"/api/shipping-notice/tools/update_notice_line",
headers=headers,
json={"task_id": task_id, "line_index": 0, "patch": {"reservation_id": "f" * 32}},
)
assert invalid_edit.get_json()["status"] == "ok"
blocked = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_parse"},
).get_json()
assert blocked["status"] == "needs_human"
assert blocked["data"]["parse_validation"]["issues"][0]["reason"] == "invalid_format"
valid_edit = client.post(
"/api/shipping-notice/tools/update_notice_line",
headers=headers,
json={"task_id": task_id, "line_index": 0, "patch": {"reservation_id": "AWS-311"}},
)
assert valid_edit.get_json()["status"] == "ok"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
validation = (task.step_payload_json or {})["parse_validation"]
assert validation["status"] == "ready"
assert validation["issues"] == []
@pytest.mark.auto_rpa
def test_parse_notice_blocks_valid_reservation_when_column_evidence_conflicts(app, client):
"""两个值格式都合法时,原文列证据冲突仍必须进入 parse_review,不能靠高置信度自动通过。"""
headers = _tool_headers(app)
task_id = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
).get_json()["task_id"]
raw_text = "AWS Sku\tReservation ID\tQty\nA001\t3000092917\t2"
result = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"raw_text": raw_text,
"structured": {
"lines": [{"sku": "A001", "reservation_id": "3000092918", "qty": 2, "uom": "EA"}],
"confidence": 0.95,
},
},
).get_json()
assert result["status"] == "needs_human"
assert result["checkpoint"] == "parse_review"
assert result["data"]["parse_validation"]["issues"][0]["reason"] == "source_conflict"
@pytest.mark.auto_rpa
def test_parse_notice_low_confidence_does_not_write_parse_review_chat_card(app, client):
headers = _tool_headers(app)
+18
View File
@@ -58,6 +58,24 @@
### 3.x 货代发货通知建单防重复(第一阶段)
### 3.x 一封邮件多订单与 Candidate 级判重
- 保持“一封 EML = 一个 Intake”;上传阶段只预处理正文和附件为 Document,用户点击发送后才由现有货代 Chatflow 完整解析业务订单并生成 Candidate。
- 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。
- 正文与附件由 LLM 结合语义关联;附件优先作为主证据,SKU/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。
- 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。
- 高置信发货需求只要包含可信 SKU + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID、Source Type、Hub Code 允许缺失,但 Task 必须停在自然对话补字段门禁。
- 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。
- 本期复用现有货代 Chatflow,不新增独立 Dify Workflow,不新增 `agent_runtime_bindings`。
### 3.x 发货通知关键字段真值校验
- LLM 只负责从不同客户、不同版式的通知中抽取候选值;HXOPS 后端负责 `reservation_id / sku / qty` 的归一化、来源校验、冲突裁决与最终落库。
- Reservation ID 不绑定单一邮件模板:允许 `Reservation ID / COM ID / Reservation Order / PR Number / External reservation ID` 等业务来源;禁止把 `Allocation ID / Parent allocation ID / Commodity group ID` 当作 Reservation ID。
- 32 位十六进制内部主键和 UUID 不得进入库存匹配;数字型及 `AWS-311 / ORD-3002 / R-1` 等字母型业务编号按通用契约兼容,后续可按客户或来源 profile 收紧。
- 自动纠错必须具备表头列关系和唯一 SKU/APN/MPN 关联证据;拍平文本或多义匹配不得猜测,必须进入人工复核。
- 后端必须保留原始候选、修正值、原因与证据;任何 blocking 问题不得被 LLM 高置信度或人工“确认”动作绕过。
- **同请求去重**:上传接入阶段按源文件 SHA-256 去重,相同内容只抽取、建任务一次。
- **建单幂等**:`ShippingBatch.create_idempotency_key` 防止双击、重试与并发重复建批;数据库唯一约束 `(user_id, create_idempotency_key)` 提供最终保护。
- **内容指纹**:`ShippingTask.source_content_hash` 记录完整文件哈希,支持跨请求精确重复检测。
@@ -128,6 +128,32 @@
- 先读 `reference_context.last_failed_target.reason` + `id`
- 如果同时存在多个异常候选,再读 `reference_context.candidates`
## 6.1 货代 Chatflow 的订单抽取能力分支
货代应用不新增 Workflow;现有 Chatflow 读取以下路径:
```text
agent_code
platform.session_id
platform.request_id
refs.capability
refs.contract_version
refs.intake_nos
```
当 `refs.capability=order_extraction` 且 `refs.contract_version=shipping-order-extraction-v1` 时,必须在任务续办/库存/自由 Agent 之前执行:
```text
get_order_extraction_context
-> LLM 输出 {schema_version, orders[]}
-> Code 校验 JSON
-> submit_order_extraction
-> 模板回复
-> End
```
两个 Tool 均原样接收 Start 变量 `agent_runtime_context`。Dify 不传 `user_id`,不自行拆 `refs.intake_nos` 后调用旧建批接口,也不使用 `create_task/parse_notice` 替代 `submit_order_extraction`。完整 Prompt、Code 和参数映射见 [`technical.md §2.4.0`](../features/shipping-notice/technical.md#240-点击发送完整订单抽取固定分支本期必须手工新增)。
## 7. 验收场景
联调时至少覆盖以下场景:
+13 -6
View File
@@ -51,7 +51,8 @@
**货代发货通知助手**帮助业务人员把客户发来的发货指令(邮件、微信文字、PDF、Word 等)转成可执行的发货动作,主要能力包括:
1. **解析发货通知**:自动识别客户、收货信息,以及每一行的 SKU、数量、单价、金额、Reservation ID 等。
1. **解析发货通知**:上传后系统先读取邮件正文和附件;您点击“发送”后,AI 才会完整识别客户、收货信息,以及每一行的 SKU、数量、单价、金额、Reservation ID 等。
一封 EML 中可以包含多个订单,也可能一个附件里包含多个订单;系统仍保留为一个接入记录,并按实际业务订单拆分处理。
2. **载入库存**:上传库存 Excel,或由系统自动从货代/仓库系统导出库存(若已配置自动化)。
3. **核对库存**:按 SKU + Reservation ID + 需求数量,与库存表比对是否可满足。
4. **生成发货文件**:生成符合货代要求的发货 Excel。
@@ -68,7 +69,8 @@
**系统如何工作(便于理解)**:
- 上传 **发货通知 PDF/Word** 或**粘贴邮件/微信正文**后,系统会在后台**自动**创建任务编号并由 AI 解析订单行(无需您手动说「创建任务」)。
- 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后由 AI 完整识别订单。只要明确属于发货需求且 SKU、数量可信,系统会自动创建任务,无需再次人工确认建单。
- Reservation ID、Source Type、Hub Code 暂时缺失时,任务仍会创建,但会停在“待补充字段”,不会继续查库存;您可直接在对话中说明正确值。
- 上传 **库存 Excel** 后,系统会**自动识别表头**(如 `Reservation Order`、`COM ID`)并给出列映射建议;**不确定的列**可在对齐界面用下拉框修改后再确认。
- 匹配与生成 Excel 由系统规则执行;您主要在解析结果、字段对齐、库存不足时做确认或补货修订。
@@ -133,7 +135,7 @@ SN-20260529-A1B2C3D4
| **单价** | 单行单价 | Unit Price、单价、Price |
| **金额** | 单行金额 | Amount、Line Amount、金额、小计 |
| **币种** | 单价/金额的货币单位 | Currency、Curr、CCY、币种;也可从 `100.50 USD` 等形式识别 |
| **Reservation ID** | 预留/订单占用编号,用于与库存精确对应 | Reservation ID、COM ID;**常见为 8~12 位纯数字**(如 `1000140351`);Wistron 等 PO 可能在 **PR Number / PR_Number** 字段:`ADU_S-xxx@1000140351`,系统取 `@` 后数字 |
| **Reservation ID** | 预留/订单占用编号,用于与库存精确对应 | Reservation ID、COM ID、Reservation Order、External reservation ID;Wistron 等 PO 可能在 **PR Number / PR_Number** 字段:`ADU_S-xxx@1000140351`,系统取 `@` 后业务编号 |
| **要求交期** | 该行物料的交货/发货日期 | Required Date、Delivery Date、ETA、交期、交货日期 |
| **供应商料号** | 客户侧记录的供应商物料编码 | Vendor Part Number、Vendor PN、Supplier Part No、供应商料号 |
@@ -141,6 +143,8 @@ SN-20260529-A1B2C3D4
- **PO Number** 为文档级字段;**PR Number**(含 `@1000140351`)通常对应 **Reservation ID**,不要与 PO Number 混淆。
- **SKU、需求数量、Reservation ID** 是库存核对的核心字段。
- 邮件模板可以不同;系统按字段语义和表格列关系识别,不依赖固定列顺序。`Allocation ID`、`Parent allocation ID`、`Commodity group ID` 不属于 Reservation ID。
- AI 解析结果只是候选,后端会再次校验。若候选像 32 位内部主键、与原文列证据冲突或无法可靠对齐,系统会阻断并要求人工复核,不会把猜测值送入库存匹配。
- **要求交期、供应商料号、币种** 按**明细行**解析与导出;若 PDF 仅有一个文档级交期或币种,系统会回填到各行。
- **单价、金额、币种** 主要用于展示与导出,**不参与**「够不够货」的自动比对。
- 若订单含 Reservation ID 而库存表未正确对应,系统会在「字段对齐」环节给出警告。
@@ -229,6 +233,8 @@ SN-20260529-A1B2C3D4
### 阶段 ② — 确认发货通知解析
若邮件包含多个订单通知,页面会逐项显示订单候选。业务人员可取消不需要发货的候选、修订冲突字段,并分别处理重复订单。只有已选中、状态为“可建单”且已完成重复决策的候选才会进入本次建批;确认后系统创建一个批次,每个候选对应一个独立任务。
**您需要核对:**
- 客户、交期、收货地址是否正确;
@@ -343,8 +349,9 @@ SN-20260529-A1B2C3D4
**Reservation ID 格式说明:**
- 常见为 **8~12 位纯数字**,例如 `1000140351`。
- Excel 中可能被存成数字格式,系统会自动规范为同一字符串再比对,避免「1000140351」与「1000140351.0」对不上。
- 常见为 **8~12 位纯数字**,例如 `1000140351`,也可能是 `AWS-311` 等来源系统业务编号。
- Excel 中的数字型编号可能被存成浮点格式,系统会自动规范为同一字符串再比对,避免「1000140351」与「1000140351.0」对不上。
- 32 位十六进制内部主键和 UUID 会被拒绝,不参与订单关联、指纹或库存匹配。
**不参与匹配的字段:**
@@ -520,7 +527,7 @@ A:Reservation ID(也可能叫 COM ID / Reservation Order / PR Number)是
3. 若原件里不存在:请向客户/上游确认 Reservation ID 的提供规则,否则系统只能按 SKU 汇总匹配,可能导致同 SKU 多预留号的场景误匹配。
**Q:Reservation ID 必须是数字吗?**
A:业务上**一般为 8~12 位纯数字**(如 `1000140351`)。若格式异常,系统会提示核对是否解析正确。
A:不一定。很多来源使用 8~12 位纯数字(如 `1000140351`),也有来源使用 `AWS-311`、`ORD-3002` 等字母型业务编号。系统兼容多模板,但会拒绝 32 位十六进制内部主键、UUID 等明显不是业务预留号的值。
**Q:单价、金额错了会影响能不能发货吗?**
A:不会。库存匹配只看 SKU、Reservation ID、需求数量;但导出 Excel 前仍建议在解析确认阶段核对单价与金额。
+280 -13
View File
@@ -8,6 +8,30 @@
Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、OpenAPI、多文件批次解析、自动上传与 Agent 指令合集。
## 2026-07-15 当前实施基线(优先级最高)
> 本节覆盖本文档中仍残留的“上传即生成 Candidate / 人工确认后建单 / 通知附件只回引 Hxops”等旧描述;如有冲突,以本节为准。
```text
上传 EML/PDF/Word
-> HXOPS 自动预处理 Intake + Document[](正文、附件文本、派生资产)
-> 用户点击发送
-> 现有货代 Chatflow 的 order_extraction 固定分支
-> LLM 一次完整识别 orders[]
-> HXOPS 逐订单校验、Candidate 落库、订单级判重
-> 高置信且有 SKU/Qty 原文证据的订单自动建 Batch/Task
-> 缺 Reservation ID / Source Type / Hub Code 的 Task 停在字段补充门禁
-> 用户通过自然对话调用既有字段修改 Tool 补齐
```
- **不新增 Dify Workflow**:复用现有货代 Chatflow;订单抽取分支必须位于任务读取、自由 Agent 和库存链之前。
- **不新增 `agent_runtime_bindings`**:本期继续使用现有 Agent 注册与 Tool 集成密钥;能力提供方管理留待平台能力注册阶段统一实施。
- **上传阶段不调用 LLM、不生成 Candidate、不判订单重复**:规则解析只作为 `rule_hints`,Candidate 只在 `submit_order_extraction` 后生成。
- **一封 EML 仍是一个 Intake**;一个 Document 可以产生多个 Candidate;跨附件同一订单由 LLM 合并并以一个主 Document、多个 evidence 记录来源。
- **判重粒度是订单 Candidate,不是整封邮件或单个附件**:附件 hash 是证据之一,最终通过身份指纹 + 内容指纹区分完全重复与可能修订。
- **自动建单硬条件**:`classification=shipping_request`、至少一条合法 SKU + 正数 Qty、分类与 SKU/Qty 置信度达阈值、SKU/Qty 均有非空原文证据、无阻断冲突、无必须人工决策的修订。
- **流程字段允许缺失**:Reservation ID、Source Type、Hub Code 缺失不阻止 Task 创建,但阻止库存、匹配、Excel 与上传;自然对话补齐后重新进入解析确认。
### 第三阶段:业务去重与任务版本(实现摘要)
- **文件哈希去重**(FileAsset / notice `content_hash`)与 **业务指纹去重**(`shipping-v1`:客户码/PO/Reservation/行 digest)分层独立;建单幂等键、货代上传幂等键语义不变。
@@ -15,9 +39,31 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
- 阻断型重复须先 `POST .../intakes/{intake_no}/duplicate-resolution`(`open_existing` / `create_revision` / `force_create`),再确认建单;建单事务内重校检测结果。
- 修订创建新 `ShippingTask`:`supersedes_task_id` + `document_version+1`;已 `uploaded` 任务禁止原地覆盖;`force_create` 需 `admin` 或 `shipping_notice_force_create` 与原因,审计事件走 `ShippingTaskEvent`。
### 附件资产化与订单候选(阶段二)
### 附件资产化与订单候选(上传预处理 + 点击发送抽取)
> 本阶段在阶段一文本抽取之上,把附件升级为派生 FileAsset + Document,并识别订单 Candidate;**仍不**正式创建多个 Task。
> 一封 EML 保持一个 Intake。上传阶段只落 Document;点击发送后,现有 Chatflow 才生成多个订单 Candidate,并由 HXOPS 自动建单或保留待处理项。
### 多订单 EML、Candidate 审核与双指纹(阶段三至八)
```text
EML FileAsset -> ShippingNoticeIntake
-> email body / attachments -> ShippingNoticeDocument[]
-> 点击发送 -> Chatflow 完整理解 -> ShippingNoticeCandidate[]
-> HXOPS 校验 / 自动建单 / 重复与修订决策
-> ShippingBatch -> ShippingTask[]
```
| 主题 | 当前实现 |
| --- | --- |
| 正文与附件融合 | Chatflow 同时读取正文和全部附件文本;附件优先作为订单主证据,正文用于订单通知语义、PO/Reservation 关联和补缺;不确定字段必须输出 `null` |
| 建单粒度 | 一个 EML 对应一个 Intake;每个 LLM 识别出的业务订单对应 Candidate;一个 Document 可对应多个 Candidate;高置信订单提交后自动创建 Batch/Task |
| 判重粒度 | Candidate 主附件 `content_hash` 做文件级精确判重;`shipping-v1` 业务身份指纹识别同一订单;`shipping-content-v2` 内容指纹覆盖 PO、收货地、交期、Reservation、SKU、Qty、价格币种、Allocation、Source Type、Hub Code 等,区分 `same_business_content` 与 `possible_revision` |
| 审核 API | `PATCH /api/workspace/shipping-notice/candidates/{candidate_no}`;`POST .../duplicate-refresh`;`POST .../duplicate-resolution`;所有操作按 Intake owner 隔离,已消费 Candidate 禁止修改 |
| 建批 API | `POST /api/workspace/shipping-batches/create-from-intakes` 可传 `candidate_nos`;Candidate 集合参与建批幂等,Task 回填 `source_candidate_id` 与独立附件 hash |
| 消费关系 | Candidate 一对一回填 `consumed_task_id`;同 Intake 尚有低置信/冲突 Candidate 时保持 `parse_status=parsed` + `order_extraction_status=partially_completed`,全部处理后才 `consumed` |
| 前端 | 上传后显示文件预处理状态;点击发送通过 `/api/chat/completions` 携带 `shipping_intake_nos`;Chatflow 完成后只清理服务端已 `consumed` 的附件,部分完成继续保留 |
迁移 `d9e0f1a2b3c4_candidate_content_fingerprint` 增加内容指纹;迁移 `e0f1a2b3c4d5_shipping_order_extraction_state` 增加 Intake/Document 抽取状态、Candidate 抽取审计与 `(intake_id, candidate_key)` 多订单唯一约束。部署时须先执行 `flask db upgrade`,再发布后端与前端。
| 项 | 说明 |
| --- | --- |
@@ -25,7 +71,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
| 引用计数 | Document↔派生资产按关联边原子 `±1`;多 Document 共用同一子资产可正确归零回收;`cancel_intake` 行锁幂等清理并剥离摘要投影 |
| 锁顺序 | 解析成功/失败清理、重复刷新、重试入队均先 `FOR UPDATE` Intake,再碰 Document/资产,与 cancel 同序防死锁;阶段二+parsed+去重同事务 |
| 重试入队 | 仅复用 `queued` Job(不复用 `running`);`enqueue(commit=False)` 与 Intake.queued/`parse_job_id` 同事务提交 |
| 去重降级 | 阶段二先落 Document/Candidate 基础行;Candidate+Intake 重复检测在 SAVEPOINT;异常清空为 `unchecked`,不打挂阶段二 |
| 去重边界 | 上传预处理不做 Candidate 判重;`submit_order_extraction` 在 Candidate 落库后逐订单判重,单个订单异常不应把其他已验证订单伪装成成功 |
| 失败清空 | 阶段二失败清理复用 `clear_duplicate_state_to_unchecked`,去掉 matches/指纹/决策残留 |
| 资产缺失 | 领取后失败统一 `fail_intake_with_stage2_cleanup`;Job `retryable=False` 且不再抛出,外层仅 `running` 才 fail |
| 超时回收 | `FOR UPDATE SKIP LOCKED` + `status/attempts` 条件 UPDATE;同事务清空 `parse_lease` 并 `parsing→queued/parse_failed`;替代者须 `FOR UPDATE`:仅 `queued`,或 running 且 Intake 已持精确 `parse_job_id+parse_lease`,禁止向未接管的 running 伪造 lease |
@@ -38,16 +84,16 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
| 软删除唯一 | `(parent_asset_id, content_hash)` 为 **partial unique**(`deleted_at IS NULL`);清理后同哈希可复活/重建;迁移去重行转 `orphan_cleanup` 供 MinIO 回收 |
| 重复刷新 | `refresh_intake_duplicate_detection` 逐 Candidate 重检再聚合 Intake;避免仅更新概览导致候选状态陈旧 |
| Document | `ShippingNoticeDocument`:`body` + 各附件一行;详情/轮询经 Intake 序列化返回 |
| Candidate | 仅附件/单文件在抽到真实 PO/Reservation/行项目时生成;**正文永不生成 Candidate**(`email_context`) |
| Candidate | 上传阶段恒为 0;点击发送后由 Chatflow orders[] 生成。正文不单独生成 Candidate,但可以作为订单 evidence |
| 分类 | 无业务信号的 PDF 等为 `supporting` Document,禁止伪造 PO/SKU |
| 失败与重试 | 阶段二持久化失败 → `parse_failed`(可重试);与文本抽取成功解耦后不再静默 `parsed` |
| 并发 | Job 原子领取 `parsing`;派生资产部分唯一 + IntegrityError 回查;补偿删 MinIO 失败写 `orphan_cleanup` 行供定时回收 |
| 重复隔离 | 候选 A 重复只阻断 A;Intake 概览可为 `partial_duplicate` |
| 重试幂等 | `(parent, content_hash)` / `(intake, attachment_key)` / `(intake, primary_document_id)`;失效 Candidate 按本轮主文档集清理 |
| 解析器版本 | 默认 `SHIPPING_NOTICE_PARSER_VERSION=v6`(相对 v5:落库 Document/Candidate/派生资产) |
| 建单 | `ShippingTask.source_candidate_id` 预留;本阶段结束仍不按 Candidate 建 Task |
| 重试幂等 | Document 使用 `(parent, content_hash)` / `(intake, attachment_key)`;Candidate 使用 `(intake, candidate_key)`;Tool 使用输入 snapshot +建批幂等键回放 |
| 解析器版本 | 默认 `SHIPPING_NOTICE_PARSER_VERSION=v6`(上传阶段落库 Document/派生资产;Candidate 延后到 Chatflow 提交) |
| 建单 | `ShippingTask.source_candidate_id` 已启用;满足自动建单门禁的 Candidate 分别创建 Task,待处理 Candidate 保留在原 Intake |
实现入口:`document_candidate_persist.persist_documents_and_candidates` ← `intake_parse_workflow.run_intake_parse`;派生创建:`file_assets.service.create_derived_file_asset_from_bytes`。
实现入口:上传预处理 `persist_intake_documents` ← `run_intake_parse`;完整订单抽取 `order_extraction.get_order_extraction_context/submit_order_extraction`;派生创建 `file_assets.service.create_derived_file_asset_from_bytes`。
### EML 附件提取(阶段一)
@@ -928,12 +974,212 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv
### 2.4 画布配置
#### 2.4.0 点击发送完整订单抽取固定分支(本期必须手工新增)
本期**不新增 Dify Workflow**。在现有货代 Chatflow 中,把以下分支放在 `运行态上下文标准化` 之后、`用户意图预处理 / 附件意图分类 / 准备读取任务状态 / 货代续办 Agent` 之前:
```text
开始
-> Tool 解析运行态上下文
-> 运行态上下文标准化
-> 是否订单抽取请求
├─ 是 -> Tool 读取订单抽取上下文
│ -> 订单完整抽取 LLM
│ -> 订单抽取 JSON 标准化
│ -> 抽取 JSON 是否有效
│ ├─ 是 -> Tool 提交订单抽取
│ │ -> 订单抽取结果回复 -> 结束
│ └─ 否 -> 订单抽取失败回复 -> 结束
└─ 否 -> 进入现有“用户意图预处理”及后续链路
```
##### A. Tool 解析运行态上下文
原节点的 `paths` 增加并至少包含:
```json
[
"agent_code",
"platform.session_id",
"platform.request_id",
"refs.capability",
"refs.contract_version",
"refs.intake_nos",
"refs.task_no",
"refs.batch_no",
"refs.run_purpose"
]
```
`运行态上下文标准化` 增加输出:
| 输出 | 来源 |
| --- | --- |
| `capability` | `data["refs.capability"]`,缺省空字符串 |
| `contract_version` | `data["refs.contract_version"]`,缺省空字符串 |
| `intake_nos_json` | `data["refs.intake_nos"]`,保持 JSON 字符串,不拆成自由文本 |
##### B. 是否订单抽取请求
If-Else 条件必须同时满足:
```text
capability == "order_extraction"
AND contract_version == "shipping-order-extraction-v1"
```
不要只判断 `run_purpose`,也不要根据用户文案猜测是否需要抽取。
##### C. Tool 读取订单抽取上下文
绑定 `shipping_notice_tools.dify.json` 中的 `get_order_extraction_context`:
| Tool 参数 | 值 |
| --- | --- |
| `agent_runtime_context` | `{{agent_runtime_context}}` 原样透传 |
禁止新增 `user_id`、`conversation_id` 或手写 `intake_nos` 参数。HXOPS 会从运行态上下文的本地 ChatSession 反查用户并校验 Intake 归属。
主要输出:
- `input_snapshot_hash`
- `documents[]`:`document_id/source_intake_no/document_type/filename/text/text_truncated/warnings`
- `rule_hints`
- `contract`
##### D. 订单完整抽取 LLM
建议 Temperature `0.1`。模型输入为 `Tool 读取订单抽取上下文` 的完整 JSON;不要再使用 Dify `sys.files` 读取原文件。
系统 Prompt 可直接使用:
```text
你是货代发货订单结构化抽取器。你只负责理解 HXOPS 提供的邮件正文与附件文本,不负责建单、判重或推进业务状态。
必须遵守:
1. 只输出一个 JSON 对象,格式为 {"schema_version":"shipping-order-extraction-v1","orders":[]};禁止 Markdown、解释、代码围栏。
2. 一封邮件可能包含 0、1 或多个业务订单;一个附件也可能包含多个订单。按实际业务订单拆分 orders[],不要按附件数量机械拆分。
3. 同一订单信息可能分散在正文和多个附件中;可以合并,但必须选择一个 primary_document_id,并在 evidence 中记录真实来源 document_id。
4. 非发货需求返回 orders=[]。不要为了产生任务而猜测订单。
5. 不确定字段返回 null 或省略,禁止编造 Reservation ID、PO、Hub Code、Source Type、SKU、Qty。
6. 每个订单必须包含 source_intake_no、primary_document_id、classification、classification_confidence、field_confidence、lines、evidence、conflicts。
7. classification 仅允许 shipping_request、non_shipping_request、uncertain。
8. field_confidence.sku 与 field_confidence.qty 是 0..1 的订单级最低可信度;任一行不确定时取更低值。
9. 每条有效订单行至少包含 sku 与正数 qty;reservation_id、source_type、hub_code 可以为 null。
10. evidence 至少分别提供 SKU 和 Qty 原文证据,格式 {"field":"lines[0].sku","quote":"原文片段","document_id":123};quote 必须是原文,不得改写。
11. Reservation/SKU/Qty 来源冲突、订单归属冲突或可能修订时写入 conflicts[];需要阻断自动建单的冲突 severity=blocking。
12. candidate_key_hint 只能使用稳定业务标识(如 PO/客户订单号),没有则省略;禁止随机值或数组序号。
```
用户 Prompt:
```text
请根据以下 HXOPS 订单抽取上下文完整识别所有发货订单:
{{Tool 读取订单抽取上下文.text}}
```
期望输出示例:
```json
{
"schema_version": "shipping-order-extraction-v1",
"orders": [
{
"source_intake_no": "SNI-...",
"primary_document_id": 123,
"candidate_key_hint": "4510000001",
"classification": "shipping_request",
"classification_confidence": 0.98,
"field_confidence": {"sku": 0.97, "qty": 0.96},
"po_number": "4510000001",
"lines": [
{"sku": "SKU-A", "qty": 10, "reservation_id": null, "source_type": null, "hub_code": null}
],
"evidence": [
{"field": "lines[0].sku", "quote": "SKU SKU-A", "document_id": 123},
{"field": "lines[0].qty", "quote": "QTY 10", "document_id": 123}
],
"conflicts": []
}
]
}
```
##### E. 订单抽取 JSON 标准化
Code 节点输入 `llm_text` 绑定上一步 LLM 文本,使用 Python:
```python
import json
import re
def main(llm_text: str) -> dict:
text = str(llm_text or "").strip()
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.I | re.S).strip()
try:
payload = json.loads(text)
except Exception as exc:
return {"parse_ok": False, "schema_version": "", "orders": [], "error": f"invalid_json:{exc}"}
if not isinstance(payload, dict):
return {"parse_ok": False, "schema_version": "", "orders": [], "error": "result_must_be_object"}
schema_version = str(payload.get("schema_version") or "").strip()
orders = payload.get("orders")
if schema_version != "shipping-order-extraction-v1" or not isinstance(orders, list):
return {"parse_ok": False, "schema_version": schema_version, "orders": [], "error": "contract_mismatch"}
return {
"parse_ok": True,
"schema_version": schema_version,
"orders": orders,
"error": "",
}
```
输出类型:`parse_ok=Boolean`、`schema_version=String`、`orders=Array[Object]`、`error=String`。
##### F. Tool 提交订单抽取
仅当 `parse_ok=true` 时调用 `submit_order_extraction`:
| Tool 参数 | 值 |
| --- | --- |
| `agent_runtime_context` | `{{agent_runtime_context}}` 原样透传 |
| `input_snapshot_hash` | `{{Tool 读取订单抽取上下文.input_snapshot_hash}}` |
| `schema_version` | `{{订单抽取 JSON 标准化.schema_version}}` |
| `orders` | `{{订单抽取 JSON 标准化.orders}}` |
Tool 返回是唯一建单事实源:
- `batch_no/created/opened_existing`:已自动处理结果;
- `pending_orders`:低置信、证据不足、冲突、重复/修订待决策;
- `pending_count=0` 不代表后续库存链已完成,只代表本次订单抽取没有待处理订单;
- `idempotent_replay=true` 时直接解释原结果,禁止再次调用建单 Tool。
##### G. 回复节点
成功回复建议直接基于 Tool 字段模板化,不再经过自由 Agent:
```text
{{Tool 提交订单抽取.message}}
{{#if Tool 提交订单抽取.batch_no}}批次:{{Tool 提交订单抽取.batch_no}}{{#endif}}
```
`pending_count > 0` 时只说明“部分订单需要补充或确认”,具体 Candidate 由 HXOPS 前端/工作台展示;不要把 Candidate 称为用户必须先选择的“候选建单”。
JSON 失败回复:
```text
未能得到符合 shipping-order-extraction-v1 的结构化订单结果,请重新发送;本次未创建任务。
```
#### 2.4.1 完整画布总览
```text
开始
-> Tool 解析运行态上下文
-> 运行态上下文标准化
-> 是否订单抽取请求
-> (命中时走完整订单抽取固定分支并结束)
-> 用户意图预处理
-> 附件意图分类
-> 分支调度
@@ -1008,7 +1254,7 @@ agent_path:
说明:
- 当前保持 `enabled=true`,是为了让嵌入式聊天态把附件透传为 `sys.files`,供 `附件意图分类` 节点识别库存附件与通知附件。
- **通知附件即使进入 Dify,也不在 Dify 内直接建 task**;正式建批次、建任务、保存 `raw_text` 仍由 Hxops 负责,因此附件意图分类应走 `direct_answer` 回引提示。
- 通知原文件由 HXOPS 上传预处理,不依赖 Dify `sys.files`;用户点击发送后,HXOPS 通过 `agent_runtime_context.refs.intake_nos` 触发现有 Chatflow 的固定订单抽取分支,最终建单仍由 HXOPS Tool 完成。
- 若宿主前端已经完全接管附件上传,且不会向 Dify 透传 `sys.files`,则应关闭 Dify 原生 File Upload,并同步移除本文档中依赖 `sys.files` 的附件分流配置。
##### 其他 Features
@@ -2517,6 +2763,19 @@ System Prompt:
4. 只允许输出一个可被下游 Code 节点直接解析的 JSON 对象。
5. 若字段无法确定,可输出空字符串、空数组或 null,但仍必须返回合法 JSON。
[PROMPT_UPDATE] 2026-07-15:订单来源存在多种邮件/PDF 模板,禁止依赖固定列顺序;LLM 仅输出候选,HXOPS 后端负责最终裁决。
关键字段规则:
1. 按每份原文实际表头逐行抽取 reservation_id、sku、qty;不得假设所有客户共用同一模板。
2. reservation_id 的允许来源包括:Reservation ID、Reservation Id、COM ID、Reservation Order、Reservation No、Resv ID、PR Number、PR_Number、PR No、PR#、External reservation ID。
3. 以下字段禁止映射为 reservation_id:Allocation ID、Parent allocation ID、Commodity group ID、Supplier code。
4. Reservation ID 可以是 8~12 位数字,也可以是 AWS-311、ORD-3002、R-1 等字母型业务编号;32 位十六进制串和 UUID 通常是内部标识,不得作为 reservation_id。
5. PR Number 出现 xxx@1000140351 时,取 @ 后的业务编号。
6. 必须按 HTML/TSV 的列边界对齐值;空单元格仍占一列。无法证明列关系时 reservation_id 输出空字符串,禁止根据邻近数字猜测。
7. sku 优先取 Material、Part Number、Allocated APN、AWS Sku、Customer PN、料号;MPN/Vendor Part Number 单独写入 vendor_part_number。复合 SKU 可保留原文。
8. qty 必须为正数;无法确认时不要输出该订单行。
9. 若正文和附件字段冲突,保留附件订单行候选,不得静默用正文覆盖;最终由后端标记冲突并进入人工复核。
请把发货通知正文解析成结构化 JSON,只输出 JSON,不要输出解释。
输出字段要求:
@@ -2532,7 +2791,15 @@ System Prompt:
"sku": "",
"qty": 0,
"uom": "",
"required_date": ""
"required_date": "",
"vendor_part_number": "",
"evidence": {
"reservation_id": {
"source_column": "",
"raw_value": "",
"confidence": 0
}
}
}
]
}
@@ -2541,7 +2808,7 @@ System Prompt:
1. 只输出合法 JSON object
2. lines 必须是数组
3. 若识别不到字段,返回空字符串或 0,不要臆造
4. reservation_id、sku、qty 尽量逐行抽取
4. reservation_id、sku、qty 必须按原文行与列关系逐行抽取;无法可靠对应时留空,不得猜测
5. 不要输出 markdown,不要输出代码块
```
@@ -2555,7 +2822,8 @@ User Prompt:
说明:
- 本节点的职责是“立即把 `raw_text` 转成结构化对象”,不是与用户对话。
- 本节点的职责是“立即把 `raw_text` 转成候选结构化对象”,不是与用户对话,也不是最终真值裁决器。
- `evidence` 为推荐字段;后端即使未收到 evidence,也会根据保存的 `raw_text` 重新执行列证据校验。
- 若未来调整模型或字段抽取策略,只改 Prompt,不改下游 `parse_notice` 调用方式。
##### 节点:结构化结果标准化
@@ -3464,4 +3732,3 @@ API 层
5. **硬 Gate**:`inventory_rpa_workflow`、`inventory_workflow`、`fulfillment_workflow`、`progress_workflow` 入口均调用 `assert_inventory_source_gate`。
6. **快照复用键**:`find_latest_ready_snapshot(source_code, site_id, warehouse_id)`;link 时做 identity check。
7. **迁移**:`b4c5d6e7f8a9_add_shipping_inventory_source_gate_fields`。
+4 -1
View File
@@ -60,10 +60,13 @@
| 发货通知业务说明 | 已文档化 | 见 [docs/features/shipping-notice/business.md](features/shipping-notice/business.md) |
| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 |
| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 |
| 附件资产化与订单候选(阶段二) | 已实现 | EML 附件派生 FileAsset;Document 关联边引用计数;partial unique + 软删复活;cancel 释放 Document/Candidate;MinIO 补偿失败记 orphan_cleanup;候选去重在 SAVEPOINT;失败/资产缺失统一阶段二清理;预解析 Job 超时回收同步 Intake + parse_lease 代次隔离;入队原子绑定 parse_job_id;Intake 创建 FOR UPDATE/IntegrityError 幂等,cancelled/expired 禁止复活;enqueue 仅 SAVEPOINT 内插入;替代 Job FOR UPDATE,仅 queued 或已持精确 lease 的 running 可 supersede;parser v6;暂不按候选建 Task;见技术手册「附件资产化与订单候选」 |
| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake,解析邮件正文/真实附件并派生 FileAsset/Document;上传阶段不调用 LLM、不生成 Candidate、不判订单重复;解析失败、超时、取消和资产引用补偿保持幂等 |
| 点击发送完整订单抽取 | 已实现(Dify 画布待手工配置) | 前端通过普通 Chatflow 发送 `shipping_intake_nos`;`agent_runtime_context` 触发固定分支;两个 Tool 读取不可变快照、接收 orders[],支持一附件多订单、SKU/Qty 证据/置信度门禁与幂等重放 |
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 |
| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML |
| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` |
| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings |
| 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 |
| 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 |
| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 |
| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 |
@@ -44,9 +44,11 @@
"domain.state_hint.batch_no",
"domain.state_hint.current_step",
"domain.state_hint.focus_task_no",
"domain.state_hint.hxops_turn_id",
"domain.state_hint.match_status",
"domain.state_hint.pending_human_reason",
"domain.state_hint.review_status",
"domain.state_hint.schedule_task_id",
"domain.state_hint.status",
"domain.state_hint.upload_status",
"domain.summary",
@@ -68,7 +70,11 @@
"reference_context.last_failed_target.reason",
"reference_context.recent_activity_summary",
"refs.batch_no",
"refs.capability",
"refs.contract_version",
"refs.file_name",
"refs.hxops_turn_id",
"refs.intake_nos",
"refs.run_purpose",
"refs.schedule_task_id",
"refs.task_no",
+228 -2
View File
@@ -11,6 +11,232 @@
}
],
"paths": {
"/tools/get_order_extraction_context": {
"post": {
"operationId": "get_order_extraction_context",
"summary": "读取点击发送后完整订单抽取所需的邮件正文与附件文本",
"description": "仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户,并返回 input_snapshot_hash、documents 与固定输出契约;禁止让 LLM 传 user_id。",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"agent_runtime_context": {
"type": "string",
"description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
}
},
"required": [
"agent_runtime_context"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/submit_order_extraction": {
"post": {
"operationId": "submit_order_extraction",
"summary": "提交完整订单抽取结果,由 HXOPS 执行证据校验、订单级判重与自动建单",
"description": "只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、SKU/Qty 置信度及原文证据均达标,且无阻断冲突/修订决策时自动建单;Reservation ID、Hub Code、Source Type 允许缺失。",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"agent_runtime_context": {
"type": "string",
"description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
},
"input_snapshot_hash": {
"type": "string",
"description": "get_order_extraction_context 返回的不可变输入快照 SHA-256"
},
"schema_version": {
"type": "string",
"description": "固定为 shipping-order-extraction-v1",
"enum": [
"shipping-order-extraction-v1"
]
},
"orders": {
"type": "array",
"description": "LLM 从一封或多封邮件中识别出的订单数组;一个附件可产生多个订单,非发货邮件可为空数组",
"maxItems": 50,
"items": {
"type": "object",
"required": [
"source_intake_no",
"primary_document_id",
"classification",
"classification_confidence",
"field_confidence",
"lines",
"evidence"
],
"properties": {
"source_intake_no": {
"type": "string",
"description": "来源 Intake 编号,必须来自上下文"
},
"primary_document_id": {
"type": "integer",
"description": "主来源 Document ID,必须来自上下文"
},
"candidate_key_hint": {
"type": "string",
"description": "可选稳定订单标识,如 PO/订单号;不得使用随机值"
},
"classification": {
"type": "string",
"description": "仅 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": {
"type": "string",
"description": "可为空的 PO/订单号"
},
"lines": {
"type": "array",
"items": {
"type": "object",
"required": [
"sku",
"qty"
],
"properties": {
"sku": {
"type": "string",
"description": "SKU/料号"
},
"qty": {
"type": "number",
"exclusiveMinimum": 0
},
"reservation_id": {
"type": "string",
"description": "可为空,缺失时 Task 停在补字段门禁"
},
"hub_code": {
"type": "string",
"description": "可为空,缺失时 Task 停在补字段门禁"
},
"source_type": {
"type": "string",
"description": "可为空,缺失时 Task 停在补字段门禁"
}
},
"additionalProperties": true
}
},
"evidence": {
"type": "array",
"description": "至少分别提供 SKU 与 Qty 原文证据,元素含 field 与非空 quote",
"items": {
"type": "object",
"required": [
"field",
"quote"
],
"properties": {
"field": {
"type": "string",
"description": "证据字段,如 lines[0].sku 或 lines[0].qty"
},
"quote": {
"type": "string",
"description": "原文片段,禁止改写"
},
"document_id": {
"type": "integer",
"description": "证据来源 Document ID"
}
}
}
},
"conflicts": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": true
}
}
},
"additionalProperties": true
}
}
},
"required": [
"agent_runtime_context",
"input_snapshot_hash",
"schema_version",
"orders"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/parse_notice": {
"post": {
"operationId": "parse_notice",
@@ -135,7 +361,7 @@
},
"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": {
@@ -532,4 +758,4 @@
}
}
}
}
}
+18
View File
@@ -20,6 +20,24 @@
### 2.x 货代发货通知批次库存能力
### 2.x 多订单邮件 Candidate 架构
- 数据链路为 `FileAsset -> Intake -> Document[] --点击发送/Chatflow--> Candidate[] -> Batch -> Task[]`;上传阶段不调用 LLM、不生成 Candidate、不做订单级判重。
- 普通聊天继续走 `/api/chat/completions`,前端传 `shipping_intake_nos`;后端通过 `agent_runtime_context.refs` 注入 `capability=order_extraction`、`contract_version=shipping-order-extraction-v1` 与 Intake JSON 字符串。
- 现有 Chatflow 调用 `get_order_extraction_context` 获取不可变快照与全文,再调用 `submit_order_extraction` 提交 orders[];Tool 通过本地 ChatSession 反查用户,禁止信任 LLM 传入 user_id。
- Candidate 使用身份指纹 `shipping-v1` 与内容指纹 `shipping-content-v2` 双层判重;内容版本覆盖单头、订单行、价格、分配与 Hub 字段,主附件 hash 独立落到 Task,避免以整封 EML 作为所有订单的判重依据。
- Candidate 唯一键为 `(intake_id, candidate_key)`,支持一个 Document 产生多个 Candidate;Task 与 Candidate 一对一关联。
- 自动建单后若仍有未消费/待处理 Candidate,Intake 保持 `parsed + partially_completed`;全部处理后才 `consumed`。后补订单可创建新的 Batch,并继续关联原 Intake/Candidate。
- 本期不新增 Dify Workflow 或 `agent_runtime_bindings`;未来平台能力注册应由应用声明所需能力,管理端为能力配置 provider/API/key。
### 2.x 发货通知字段契约与后端裁决
- 解析链采用 `结构保真正文 -> LLM 候选 JSON -> 后端 adjudicate -> validated lines -> 匹配硬闸门`;LLM 不是业务真相源。
- HTML 邮件按 `tr -> 换行`、`td/th -> 制表符` 转为 TSV,并保留空单元格;纯文本缺少列边界时只允许保守抽取。
- 库存定位键为 `(sku, reservation_id)`,`qty` 是必须有效的数量约束;三者均为硬契约字段,非法或冲突时不得进入库存匹配。
- 裁决结果写入 `ShippingTask.step_payload_json.parse_validation`,包含 `status / issues / contract_version`;第一阶段复用现有 JSON 字段,不新增数据库迁移。
- `parse_notice`、人工确认和 `match_inventory` 三层重复执行关键门禁,防止脏值通过任一旁路进入后续履约。
- 单票与多票发货需求统一落入 `ShippingBatch`;单票使用 `file_count=1` 的批次容器。
- 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。
- 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。
+10 -1
View File
@@ -35,5 +35,14 @@
| **报表监控** | **数据导出** | 管理员导出用户、日志等数据为 Excel/CSV。 | 模拟 Admin GET `/api/admin/database/{table_name}`。 | URL Path: `/api/admin/database/chat_logs` | HTTP 200 OK; 返回完整数据列表。 |
| **发货通知** | **建单幂等** | 相同 `create_idempotency_key` 重复请求返回同一批次,不重复启动 orchestrator。 | `test_shipping_notice_batches.py`:Workspace API 双次 POST;断言 `idempotent_replay`、任务数、orchestrator 调用次数。 | Header `Idempotency-Key` + 相同 notice 文件 | 第二次 `batch_no` 相同;`idempotent_replay=true`;DB 仅 1 批次。 |
| **发货通知** | **同请求文件去重** | 同一次上传中内容相同文件只建 1 个任务。 | `test_notice_intake.py` / `test_shipping_notice_batches.py`:2 个同字节不同文件名。 | 2× 相同内容 PDF | `duplicate_count=1`;`tasks` 长度 1。 |
| **发货通知** | **双击/重试前端锁** | 建批提交中重复发送被消费,幂等键在重试间保持稳定。 | `useChatShippingUploadHandler.spec.ts` / `useChatShippingSendHandler.spec.ts` | 连续点击发送 | `startChatTurn` 仅 1 次;失败重试复用同一 `idempotency_key`。 |
| **发货通知** | **上传只预处理** | 上传 EML 后只落 Intake/Document/派生附件资产,不调用 LLM、不生成 Candidate。 | `test_shipping_notice_intakes.py::test_run_intake_parse_three_pdfs_creates_documents_and_assets_without_candidates` | 1 EML + 3 PDF | `document_count=4`、`candidate_count=0`、`order_extraction_status=not_started`;重试不膨胀。 |
| **发货通知** | **点击发送进入现有 Chatflow** | 已预处理 Intake 点击发送走普通 `/api/chat/completions`,携带 `shipping_intake_nos`,不调用本地建批 Action。 | `useChatShippingSendHandler.spec.ts` / chat runtime context 测试 | 空文本或自然语言 + parsed Intake | 使用默认/用户 query 调 `sendMessage`;上下文含 Intake;SSE 后仅清理 consumed 附件。 |
| **发货通知** | **一附件多订单与部分成功** | 一个 Document 可形成多个 Candidate;高置信订单自动建 Task,低置信订单保留。 | `test_shipping_notice_order_extraction.py::test_submit_order_extraction_supports_multiple_orders_partial_success_and_replay` | 同一附件 2 个订单,其中 1 个低置信 | 2 Candidate、1 Task、1 pending;Intake=`partially_completed`;重放不重复建单。 |
| **发货通知** | **订单抽取快照与权限** | Tool 从 agent_runtime_context 会话反查用户;附件来源变化后拒绝旧 LLM 结果。 | `test_shipping_notice_order_extraction.py` | 合法上下文、修改 Document 文本后的旧 snapshot | 合法上下文可读取;漂移返回 `CANDIDATE_SOURCE_CHANGED`;不创建 Candidate。 |
| **发货通知** | **自动建单与流程字段门禁** | 分类、SKU/Qty 置信度与原文证据达标即建 Task;缺 Reservation/Source Type/Hub Code 仍建单但禁止库存链。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 SKU+Qty,流程字段为空 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel。 |
| **发货通知** | **Candidate 双指纹判重** | 同身份同内容与同身份修订必须给出不同重复状态。 | `test_shipping_notice_business_dedup.py::test_candidate_content_fingerprint_distinguishes_same_content_and_revision` | 相同 PO/Reservation,不同或相同行数量 | 分别返回 `same_business_content`、`possible_revision`。 |
| **发货通知** | **Candidate 审核 API** | owner 可选择/修订/刷新/决策;越权不可见;已消费不可修改。 | `test_shipping_notice_intakes.py::test_candidate_review_duplicate_api_and_access_guards` | owner/other 用户、已消费 Candidate | 成功路径 200,越权 404,已消费 409,修订后清空旧重复决策。 |
| **发货通知** | **Candidate 安全门禁** | 空摘要、无效行、附件不完整、过期、选择漂移、无候选旧路径均不可建单。 | `test_shipping_notice_intakes.py` Candidate validation/gate 用例 | 非法摘要与异常 Intake | API 返回明确 400/409;不创建 Task;合法幂等重放不受影响。 |
| **发货通知** | **关键字段真值校验** | LLM 候选必须经后端格式、来源和列证据裁决;多模板字母/数字 ID 兼容,内部 hex/UUID 与来源冲突必须阻断。 | `test_shipping_notice_reservation_id.py`、`test_shipping_notice_extract.py`、`test_shipping_notice_tools.py` | External Reservation、COM ID、PR Number、AWS-311、32 位 hex、拍平文本、冲突 TSV | 有唯一列证据时纠正并留痕;无证据或冲突时进入 `rsv_req/parse_review`;确认与匹配旁路均不可绕过。 |
| **发货通知** | **Candidate 迁移往返** | 内容指纹、订单抽取状态与多 Candidate 唯一键迁移须可独立 upgrade/downgrade。 | `test_shipping_notice_candidate_migration.py` | 前一版本最小 schema;同 Document 多 Candidate | 新列/约束存在;安全场景完整降级;多 Candidate 场景明确拒绝降级。 |
@@ -540,10 +540,41 @@ export const refreshShippingNoticeDuplicate = (intakeNo: string) =>
{ method: 'POST' },
);
export const updateShippingNoticeCandidate = (
candidateNo: string,
patch: { selected?: boolean; business_summary?: Record<string, unknown> },
) => requestJson<import('../types/shipping.api.types').ShippingNoticeCandidateResponse>(
`/api/workspace/shipping-notice/candidates/${encodeURIComponent(candidateNo)}`,
{
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch),
},
);
export const resolveShippingNoticeCandidateDuplicate = (
candidateNo: string,
action: string,
targetTaskNo?: string | null,
reason?: string | null,
) => requestJson<import('../types/shipping.api.types').ShippingNoticeCandidateResponse>(
`/api/workspace/shipping-notice/candidates/${encodeURIComponent(candidateNo)}/duplicate-resolution`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action,
target_task_no: targetTaskNo || undefined,
reason: reason || undefined,
}),
},
);
export const createWorkspaceShippingBatchFromIntakes = (
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
candidateNos?: string[],
) =>
requestJson<ShippingCreateBatchFromIntakesResponse>('/api/workspace/shipping-batches/create-from-intakes', {
method: 'POST',
@@ -555,6 +586,7 @@ export const createWorkspaceShippingBatchFromIntakes = (
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
candidate_nos: candidateNos,
}),
});
@@ -21,6 +21,7 @@ import {
X,
} from 'lucide-vue-next';
import type { PendingAttachment, ShippingNoticePendingAttachment } from '../types/shipping.types';
import ShippingNoticeCandidateReview from './ShippingNoticeCandidateReview.vue';
import {
isBlockingWarning,
isShippingNoticeAttachmentParseIncomplete,
@@ -49,6 +50,7 @@ const props = defineProps<{
isShippingNoticeAgent: boolean;
isMaintenanceAgent?: boolean;
canManageMaintenance?: boolean;
canForceCreateShippingDuplicate?: boolean;
shippingSuggestedPrompt: string;
shippingFocusTaskNo?: string;
shippingFocusReason?: string;
@@ -65,6 +67,9 @@ const emit = defineEmits<{
'remove-attachment': [id: string];
'retry-shipping-notice-attachment': [id: string];
'resolve-shipping-notice-duplicate': [id: string];
'select-shipping-candidate': [candidateNo: string, selected: boolean];
'update-shipping-candidate': [candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void];
'resolve-shipping-candidate-duplicate': [candidateNo: string, action: import('../types/shipping.types').ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void];
'local-files-selected': [event: Event];
'add-remote-url': [url: string];
'shipping-inventory-selected': [event: Event];
@@ -276,6 +281,18 @@ watch(
<X class="h-3.5 w-3.5" />
</button>
</div>
<div v-if="isShippingNoticeAgent" class="space-y-2 px-3 pb-1">
<ShippingNoticeCandidateReview
v-for="a in attachments.filter((item): item is ShippingNoticePendingAttachment => item.kind === 'shipping_notice' && !!item.candidates?.length)"
:key="`candidate-${a.id}`"
:attachment="a"
:can-force-create="!!canForceCreateShippingDuplicate"
@select="(candidateNo, selected) => emit('select-shipping-candidate', candidateNo, selected)"
@update="(candidateNo, summary, done) => emit('update-shipping-candidate', candidateNo, summary, done)"
@resolve-duplicate="(candidateNo, action, targetTaskNo, reason, done) => emit('resolve-shipping-candidate-duplicate', candidateNo, action, targetTaskNo, reason, done)"
/>
</div>
<textarea
ref="textareaRef"
v-model="inputValue"
@@ -319,11 +336,11 @@ watch(
<span v-if="a.uploadStatus === 'uploading'" class="text-muted"> · {{ t('chat.shippingNoticeUploading') }}</span>
<span v-else-if="a.parseStatus === 'queued' || a.parseStatus === 'parsing'" class="text-muted"> · {{ t('chat.shippingNoticeParsing') }}</span>
<span
v-else-if="a.parseStatus === 'parsed' && a.duplicate?.status === 'possible_duplicate' && !a.duplicateResolution?.action"
v-else-if="a.parseStatus === 'parsed' && !a.candidates?.length && a.duplicate?.status === 'possible_duplicate' && !a.duplicateResolution?.action"
class="font-medium text-amber-700"
> · {{ t('chat.shippingNoticeDuplicatePossibleBadge') }}</span>
<span
v-else-if="a.parseStatus === 'parsed' && a.duplicate?.blocking && !a.duplicateResolution?.action"
v-else-if="a.parseStatus === 'parsed' && !a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
class="font-medium text-amber-700"
> · {{ t('chat.shippingNoticeDuplicateBlockingBadge') }}</span>
<span
@@ -355,7 +372,7 @@ watch(
</template>
</span>
<button
v-if="a.kind === 'shipping_notice' && a.duplicate?.blocking && !a.duplicateResolution?.action"
v-if="a.kind === 'shipping_notice' && !a.candidates?.length && a.duplicate?.blocking && !a.duplicateResolution?.action"
type="button"
class="text-amber-700 hover:text-amber-800"
:title="t('chat.shippingNoticeDuplicateHandle')"
@@ -276,6 +276,7 @@ watch(() => page.currentAgentId, () => {
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:is-maintenance-agent="isMaintenanceAgentPage"
:can-manage-maintenance="canManageMaintenance"
:can-force-create-shipping-duplicate="page.canForceCreateShippingDuplicate"
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
:shipping-focus-task-no="page.focusedShippingTaskNo"
:shipping-focus-reason="page.shippingFocusReason"
@@ -288,6 +289,9 @@ watch(() => page.currentAgentId, () => {
@remove-attachment="page.removeAttachment"
@retry-shipping-notice-attachment="page.retryShippingNoticeAttachment"
@resolve-shipping-notice-duplicate="page.openShippingDuplicateDialog"
@select-shipping-candidate="page.setShippingCandidateSelected"
@update-shipping-candidate="page.updateShippingCandidateSummary"
@resolve-shipping-candidate-duplicate="page.resolveShippingCandidateDuplicate"
@local-files-selected="page.handleLocalFilesSelected"
@add-remote-url="page.addRemoteUrlAttachment"
@shipping-inventory-selected="page.handleShippingInventorySelected"
@@ -0,0 +1,218 @@
<!--
features/chat/components/ShippingNoticeCandidateReview.vue
用途:展示一封 EML 下的订单候选,并提供选择、结构化修订与重复决策入口。
依赖:shipping.types、Vue I18n。
逻辑:组件维护 PO 与订单行编辑草稿,持久化操作通过事件交给 useShippingNoticeIntakes。
-->
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ShippingDuplicateAction, ShippingNoticePendingAttachment } from '../types/shipping.types';
interface EditableCandidateLine {
source: Record<string, unknown>;
sku: string;
qty: string;
reservation_id: string;
hub_code: string;
uom: string;
}
const props = defineProps<{
attachment: ShippingNoticePendingAttachment;
canForceCreate: boolean;
}>();
const emit = defineEmits<{
select: [candidateNo: string, selected: boolean];
update: [candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void];
resolveDuplicate: [candidateNo: string, action: ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void];
}>();
const { t } = useI18n();
const editingCandidateNo = ref('');
const editError = ref('');
const editPoNumber = ref('');
const editLines = reactive<EditableCandidateLine[]>([]);
const forceReasonCandidateNo = ref('');
const forceReason = ref('');
const submittingCandidateNo = ref('');
const candidates = computed(() => props.attachment.candidates || []);
watch(() => props.attachment.candidates, () => {
if (editingCandidateNo.value && !candidates.value.some((item) => item.candidateNo === editingCandidateNo.value)) {
editingCandidateNo.value = '';
}
});
/** 将 Candidate 摘要投影为业务用户可编辑的 PO、SKU、Qty、Reservation 与 Hub 字段。 */
function startEdit(candidateNo: string): void {
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
if (!candidate) return;
const sourceLines = Array.isArray(candidate.businessSummary.lines)
? candidate.businessSummary.lines.filter((item): item is Record<string, unknown> => !!item && typeof item === 'object')
: [];
editingCandidateNo.value = candidateNo;
editPoNumber.value = String(candidate.businessSummary.po_number || candidate.poNumber || '');
editLines.splice(0, editLines.length, ...sourceLines.map((line) => ({
source: { ...line },
sku: String(line.sku || ''),
qty: String(line.qty ?? ''),
reservation_id: String(line.reservation_id || ''),
hub_code: String(line.hub_code || ''),
uom: String(line.uom || 'EA'),
})));
if (!editLines.length) addLine();
editError.value = '';
}
/** 新增一条待修订订单行。 */
function addLine(): void {
editLines.push({ source: {}, sku: '', qty: '', reservation_id: '', hub_code: '', uom: 'EA' });
}
/** 校验所有订单行后提交,不允许空 SKU、非正数数量或空行静默通过。 */
function saveEdit(): void {
const candidate = candidates.value.find((item) => item.candidateNo === editingCandidateNo.value);
if (!candidate || !editLines.length) return;
const normalizedLines = editLines.map((line) => ({
...line.source,
sku: line.sku.trim(),
qty: Number(line.qty),
reservation_id: line.reservation_id.trim() || undefined,
hub_code: line.hub_code.trim() || undefined,
uom: line.uom.trim() || 'EA',
}));
if (normalizedLines.some((line) => !line.sku || !Number.isFinite(line.qty) || line.qty <= 0)) {
editError.value = t('chat.shippingCandidateInvalidLine');
return;
}
submittingCandidateNo.value = candidate.candidateNo;
emit('update', candidate.candidateNo, {
...candidate.businessSummary,
po_number: editPoNumber.value.trim() || null,
lines: normalizedLines,
}, (success) => {
submittingCandidateNo.value = '';
if (success) {
editingCandidateNo.value = '';
editError.value = '';
}
});
}
/** 对当前首个重复目标应用决策;强制新建时要求填写原因。 */
function resolveDuplicate(candidateNo: string, action: ShippingDuplicateAction): void {
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
const target = candidate?.duplicate?.matches?.[0]?.taskNo;
if (action === 'force_create') {
forceReasonCandidateNo.value = candidateNo;
forceReason.value = '';
return;
}
submittingCandidateNo.value = candidateNo;
emit('resolveDuplicate', candidateNo, action, target, undefined, () => {
submittingCandidateNo.value = '';
});
}
/** 提交内联强制新建原因,避免浏览器 prompt 丢失上下文或不可访问。 */
function submitForceCreate(candidateNo: string): void {
const candidate = candidates.value.find((item) => item.candidateNo === candidateNo);
const reason = forceReason.value.trim();
if (!candidate || !reason) return;
submittingCandidateNo.value = candidateNo;
emit(
'resolveDuplicate',
candidateNo,
'force_create',
candidate.duplicate?.matches?.[0]?.taskNo,
reason,
(success) => {
submittingCandidateNo.value = '';
if (success) forceReasonCandidateNo.value = '';
},
);
}
</script>
<template>
<div v-if="candidates.length" class="w-full space-y-2 rounded-xl border border-default bg-surface px-3 py-2">
<div class="flex items-center justify-between text-xs">
<span class="font-semibold text-primary">{{ t('chat.shippingCandidateTitle') }}</span>
<span class="text-muted">{{ t('chat.shippingCandidateCount', { count: candidates.length }) }}</span>
</div>
<div v-for="candidate in candidates" :key="candidate.candidateNo" class="rounded-lg border border-default bg-surface-soft p-2 text-xs">
<div class="flex flex-wrap items-center gap-2">
<input
type="checkbox"
:checked="candidate.selected"
:disabled="!!candidate.consumedTaskId"
@change="emit('select', candidate.candidateNo, ($event.target as HTMLInputElement).checked)"
/>
<span class="font-mono text-primary">{{ candidate.candidateNo }}</span>
<span class="font-medium text-secondary">PO {{ candidate.poNumber || '-' }}</span>
<span v-if="candidate.documentFilename" class="max-w-40 truncate text-muted">{{ candidate.documentFilename }}</span>
<span :class="candidate.validationStatus === 'ready' ? 'text-emerald-700' : 'text-amber-700'">
{{ candidate.validationStatus === 'ready' ? t('chat.shippingCandidateReady') : t('chat.shippingCandidateNeedsReview') }}
</span>
<button type="button" class="ml-auto text-brand-700 hover:underline" @click="startEdit(candidate.candidateNo)">
{{ t('chat.shippingCandidateEdit') }}
</button>
</div>
<div v-if="candidate.conflicts.length" class="mt-1 text-amber-700">
{{ t('chat.shippingCandidateConflictCount', { count: candidate.conflicts.length }) }}
</div>
<div v-if="candidate.duplicate?.blocking && !candidate.duplicateResolution" class="mt-2 flex flex-wrap items-center gap-2 text-amber-700">
<span>{{ t('chat.shippingCandidateDuplicate', { task: candidate.duplicate.matches[0]?.taskNo || '-' }) }}</span>
<button
v-if="candidate.duplicate.allowedActions.includes('open_existing')"
type="button"
class="rounded border border-default bg-surface px-2 py-0.5"
@click="resolveDuplicate(candidate.candidateNo, 'open_existing')"
>{{ t('chat.shippingNoticeDuplicateOpenExisting') }}</button>
<button
v-if="candidate.duplicate.allowedActions.includes('create_revision')"
type="button"
class="rounded border border-default bg-surface px-2 py-0.5"
@click="resolveDuplicate(candidate.candidateNo, 'create_revision')"
>{{ t('chat.shippingNoticeDuplicateCreateRevision') }}</button>
<button
v-if="canForceCreate && candidate.duplicate.allowedActions.includes('force_create')"
type="button"
class="rounded border border-amber-300 bg-surface px-2 py-0.5"
@click="resolveDuplicate(candidate.candidateNo, 'force_create')"
>{{ t('chat.shippingNoticeDuplicateForceCreate') }}</button>
</div>
<div v-if="forceReasonCandidateNo === candidate.candidateNo" class="mt-2 flex gap-2">
<input v-model="forceReason" :placeholder="t('chat.shippingCandidateForceReasonPrompt')" class="min-w-0 flex-1 rounded border border-default bg-surface px-2 py-1" />
<button type="button" class="rounded bg-amber-600 px-2 py-1 text-white disabled:opacity-50" :disabled="!forceReason.trim() || submittingCandidateNo === candidate.candidateNo" @click="submitForceCreate(candidate.candidateNo)">{{ t('chat.shippingNoticeDuplicateConfirm') }}</button>
<button type="button" class="text-muted" @click="forceReasonCandidateNo = ''">{{ t('common.cancel') }}</button>
</div>
<div v-else-if="candidate.duplicateResolution" class="mt-1 text-muted">
{{ t('chat.shippingCandidateDuplicateResolved', { action: candidate.duplicateResolution.action }) }}
</div>
<div v-if="editingCandidateNo === candidate.candidateNo" class="mt-2 space-y-2">
<label class="block">
<span class="text-muted">{{ t('chat.shippingCandidatePoNumber') }}</span>
<input v-model="editPoNumber" class="mt-1 w-full rounded border border-default bg-surface px-2 py-1 text-primary" />
</label>
<div v-for="(line, index) in editLines" :key="index" class="grid grid-cols-2 gap-2 rounded border border-default bg-surface p-2 md:grid-cols-5">
<input v-model="line.sku" :placeholder="t('chat.shippingCandidateSku')" class="rounded border border-default px-2 py-1" />
<input v-model="line.qty" type="number" min="0.0001" step="any" :placeholder="t('chat.shippingCandidateQty')" class="rounded border border-default px-2 py-1" />
<input v-model="line.reservation_id" :placeholder="t('chat.shippingCandidateReservation')" class="rounded border border-default px-2 py-1" />
<input v-model="line.hub_code" :placeholder="t('chat.shippingCandidateHubCode')" class="rounded border border-default px-2 py-1" />
<div class="flex gap-1">
<input v-model="line.uom" :placeholder="t('chat.shippingCandidateUom')" class="min-w-0 flex-1 rounded border border-default px-2 py-1" />
<button v-if="editLines.length > 1" type="button" class="text-red-600" @click="editLines.splice(index, 1)">×</button>
</div>
</div>
<button type="button" class="text-brand-700 hover:underline" @click="addLine">{{ t('chat.shippingCandidateAddLine') }}</button>
<div v-if="editError" class="text-red-600">{{ editError }}</div>
<div class="flex justify-end gap-2">
<button type="button" class="rounded px-2 py-1 text-secondary" @click="editingCandidateNo = ''">{{ t('common.cancel') }}</button>
<button type="button" class="rounded bg-brand-600 px-2 py-1 text-white disabled:opacity-50" :disabled="submittingCandidateNo === candidate.candidateNo" @click="saveEdit">{{ t('chat.shippingCandidateSave') }}</button>
</div>
</div>
</div>
</div>
</template>
@@ -433,7 +433,7 @@ export function useChat() {
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
context?: { task_id?: string; batch_no?: string; display_query?: string },
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: SendMessageLifecycleHooks,
) => {
const displayQuery = String(context?.display_query || query || '').trim();
@@ -495,6 +495,7 @@ export function useChat() {
files: files && files.length > 0 ? files : undefined,
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
shipping_intake_nos: context?.shipping_intake_nos?.length ? context.shipping_intake_nos : undefined,
display_query: context?.display_query || undefined,
}),
});
@@ -551,6 +551,9 @@ export function useChatPage() {
attachmentApi.removeAttachment(id);
},
retryShippingNoticeAttachment: shipping.retryShippingNoticeAttachment,
setShippingCandidateSelected: shipping.setShippingCandidateSelected,
updateShippingCandidateSummary: shipping.updateShippingCandidateSummary,
resolveShippingCandidateDuplicate: shipping.resolveShippingCandidateDuplicate,
showShippingDuplicateDialog: shipping.showShippingDuplicateDialog,
shippingDuplicateAttachment: shipping.shippingDuplicateAttachment,
canForceCreateShippingDuplicate: shipping.canForceCreateShippingDuplicate,
@@ -93,7 +93,7 @@ export interface UseChatShippingOptions {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
@@ -429,6 +429,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
const getCurrentShippingChatContext = () => ({
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
batch_no: getActiveShippingBatchNo(),
shipping_intake_nos: shippingIntakes.getParsedIntakeNos(),
});
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
@@ -561,6 +562,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
*/
const finalizeShippingAssistantMessage = async () => {
if (!isShippingNoticeAgent.value) return;
await shippingIntakes.refreshStatuses();
shippingIntakes.clearConsumedAttachments();
await refreshShippingActions();
};
@@ -730,6 +733,49 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingDuplicateAttachmentId.value = null;
};
/** 更新 Candidate 选择状态,并将 API 失败统一反馈给用户。 */
const setShippingCandidateSelected = async (candidateNo: string, selected: boolean) => {
try {
await shippingIntakes.setCandidateSelected(candidateNo, selected);
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
}
};
/** 保存 Candidate 结构化修订,并保留服务端校验错误。 */
const updateShippingCandidateSummary = async (
candidateNo: string,
businessSummary: Record<string, unknown>,
done?: (success: boolean) => void,
) => {
try {
await shippingIntakes.updateCandidateSummary(candidateNo, businessSummary);
msg.success(t('chat.shippingCandidateUpdateDone'));
done?.(true);
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
done?.(false);
}
};
/** 保存 Candidate 重复决策,并统一展示权限或目标漂移错误。 */
const resolveShippingCandidateDuplicate = async (
candidateNo: string,
action: import('../types/shipping.types').ShippingDuplicateAction,
targetTaskNo?: string,
reason?: string,
done?: (success: boolean) => void,
) => {
try {
await shippingIntakes.resolveCandidateDuplicate(candidateNo, action, targetTaskNo, reason);
msg.success(t('chat.shippingNoticeDuplicateResolved'));
done?.(true);
} catch (error: unknown) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingNoticeDuplicateResolveFailed'));
done?.(false);
}
};
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
@@ -763,6 +809,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
startChatTurn,
refreshShippingActions,
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
getSelectedCandidateNos: shippingIntakes.getSelectedCandidateNos,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
msg,
t,
@@ -819,8 +866,12 @@ export function useChatShipping(options: UseChatShippingOptions) {
hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
hasNoticeIntakeFailures: () => shippingIntakes.hasParseFailures.value,
hasBlockingNoticeDuplicates: () => shippingIntakes.hasBlockingDuplicates.value,
hasCandidateReviewIssues: () => shippingIntakes.hasCandidateReviewIssues.value,
hasSelectedNoticeCandidates: () => shippingIntakes.getSelectedCandidateNos().length > 0,
openShippingDuplicateDialog,
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
@@ -1132,6 +1183,10 @@ export function useChatShipping(options: UseChatShippingOptions) {
handleShippingLocalFilesSelected,
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
setShippingCandidateSelected,
updateShippingCandidateSummary,
resolveShippingCandidateDuplicate,
showShippingDuplicateDialog,
shippingDuplicateAttachment,
canForceCreateShippingDuplicate,
@@ -48,7 +48,7 @@ export interface ChatPageSendContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
refreshHistoryAfterSend: () => Promise<void>;
@@ -69,7 +69,7 @@ export interface ChatPageSendContext {
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
copiedIndex: Ref<number | null>;
getChatContext?: () => { task_id?: string; batch_no?: string; display_query?: string };
getChatContext?: () => { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string };
onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void>;
}
@@ -3,7 +3,7 @@
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingCreateBatchTurn } from './shippingTurnActions';
import { buildShippingCreateBatchFromIntakesTurn, buildShippingCreateBatchTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
@@ -19,4 +19,17 @@ describe('shippingTurnActions', () => {
expect(turn.payload.idempotency_key).toBe('idem-key-001');
expect(turn.files).toEqual(files);
});
it('buildShippingCreateBatchFromIntakesTurn includes selected candidate_nos', () => {
const turn = buildShippingCreateBatchFromIntakesTurn(
['SNI-001'],
'conv-001',
'idem-candidate-001',
['SNC-001', 'SNC-003'],
);
expect(turn.actionType).toBe('shipping.create_batch_from_intakes');
expect(turn.payload.intake_nos).toEqual(['SNI-001']);
expect(turn.payload.candidate_nos).toEqual(['SNC-001', 'SNC-003']);
});
});
@@ -103,6 +103,7 @@ export function buildShippingCreateBatchFromIntakesTurn(
intakeNos: string[],
conversationId?: string | null,
idempotencyKey?: string,
candidateNos?: string[],
): { actionType: string; displayText: string; payload: Record<string, unknown> } {
const count = intakeNos.length;
const displayText = count === 1
@@ -115,6 +116,7 @@ export function buildShippingCreateBatchFromIntakesTurn(
intake_nos: intakeNos,
conversation_id: conversationId || undefined,
idempotency_key: idempotencyKey,
candidate_nos: candidateNos,
},
};
}
@@ -1,6 +1,6 @@
/**
* features/chat/shipping/useChatShippingSendHandler.spec.ts
* 用途:验证建批提交中发送拦截不会回退到普通聊天发送。
* 用途:验证上传预处理与点击发送完整抽取链路,以及建批提交中的并发拦截。
*/
import { computed, ref } from 'vue';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -71,4 +71,80 @@ describe('useChatShippingSendHandler', () => {
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.msg.info).toHaveBeenCalledWith('chat.shippingNoticeBatchSubmitting');
});
it('sends parsed intakes to the existing Chatflow without requiring upload-time candidates', async () => {
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-1',
};
const ctx = createContext({
attachments: ref([attachment]),
hasCandidateReviewIssues: () => true,
hasSelectedNoticeCandidates: () => true,
getParsedIntakeNos: () => ['SNI-1'],
refreshNoticeIntakeStatuses: vi.fn(async () => undefined),
clearConsumedNoticeAttachments: vi.fn(),
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '', '');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultPrompt',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: 'chat.shippingOrderExtractionDefaultPrompt',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
);
});
it('uses the user query for full extraction even when no candidate exists before send', async () => {
const attachment = {
id: 'notice-1',
kind: 'shipping_notice' as const,
type: 'document' as const,
uploadStatus: 'uploaded' as const,
parseStatus: 'parsed' as const,
uploadProgress: 100,
originalFilename: 'orders.eml',
fileSize: 100,
intakeNo: 'SNI-1',
};
const ctx = createContext({
attachments: ref([attachment]),
hasCandidateReviewIssues: () => false,
hasSelectedNoticeCandidates: () => false,
getParsedIntakeNos: () => ['SNI-1'],
});
const { tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers(ctx);
const consumed = await tryHandleShippingAttachmentAutoFlow(undefined, '请解析这些附件', '请解析这些附件');
expect(consumed).toBe(true);
expect(ctx.handleShippingAutoUploadNoticeBatch).not.toHaveBeenCalled();
expect(ctx.sendMessage).toHaveBeenCalledWith(
'请解析这些附件',
1,
'',
[],
{
shipping_intake_nos: ['SNI-1'],
display_query: '请解析这些附件',
},
expect.objectContaining({ onAssistantMessageFinished: expect.any(Function) }),
);
});
});
@@ -1,8 +1,8 @@
/**
* features/chat/shipping/useChatShippingSendHandler.ts
* 用途:在聊天发送前拦截发货通知专属意图,如切票、决策文本、列映射和附件自动流程。
* 用途:在聊天发送前拦截发货通知专属意图,如订单抽取、切票、决策文本、列映射和附件自动流程。
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。
* 逻辑:业务动作经 Chat Turn / handleShippingMenuAction;纯 UI(下载/选文件/映射卡片)保留本地或客户端行为。
* 逻辑:已预处理 Intake 通过普通聊天接口进入现有 Dify Chatflow;其他业务动作经 Chat Turn / handleShippingMenuAction。
*/
import {
getWorkspaceShippingBatch,
@@ -50,6 +50,8 @@ export interface ShippingSendHandlerContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; shipping_intake_nos?: string[]; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadHistory: () => Promise<void>;
@@ -65,8 +67,12 @@ export interface ShippingSendHandlerContext {
hasBlockingNoticeIntake?: () => boolean;
hasNoticeIntakeFailures?: () => boolean;
hasBlockingNoticeDuplicates?: () => boolean;
hasCandidateReviewIssues?: () => boolean;
hasSelectedNoticeCandidates?: () => boolean;
openShippingDuplicateDialog?: (attachmentId?: string) => void;
getParsedIntakeNos?: () => string[];
refreshNoticeIntakeStatuses?: () => Promise<void>;
clearConsumedNoticeAttachments?: () => void;
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
isShippingShortageQueryIntent: (text: string) => boolean;
@@ -78,7 +84,7 @@ export interface ShippingSendHandlerContext {
/**
* 创建发货通知发送拦截器。
*
* 核心逻辑:识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图,并在命中时直接走本地前后端流程。
* 核心逻辑:已预处理邮件固定 Intake 上下文后调用普通聊天;其余识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图。
* @param ctx - 发送拦截上下文
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
*/
@@ -203,17 +209,30 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
ctx.msg.warning(ctx.t('chat.shippingNoticeParseFailedHint'));
return true;
}
if (ctx.hasBlockingNoticeDuplicates?.()) {
ctx.openShippingDuplicateDialog?.();
ctx.msg.warning(ctx.t('chat.shippingNoticeDuplicateNeedsResolution'));
return true;
}
const intakeNos = ctx.getParsedIntakeNos?.() || [];
if (intakeNos.length && (!trimmed || ctx.shippingAutoFlowRequested.value)) {
if (intakeNos.length) {
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultPrompt');
ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = '';
try {
await ctx.handleShippingAutoUploadNoticeBatch([]);
await ctx.sendMessage(
query,
ctx.currentAgentId.value,
ctx.selectedKb.value,
[],
{
shipping_intake_nos: intakeNos,
display_query: query,
},
{
onAssistantMessageFinished: async () => {
await ctx.refreshNoticeIntakeStatuses?.();
ctx.clearConsumedNoticeAttachments?.();
await ctx.refreshShippingActions();
},
},
);
await ctx.loadHistory();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
@@ -120,6 +120,7 @@ export interface ShippingUploadHandlerContext {
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
getParsedIntakeNos?: () => string[];
getSelectedCandidateNos?: () => string[];
clearConsumedNoticeAttachments?: () => void;
}
@@ -310,14 +311,14 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return ok;
};
const runNoticeBatchFromIntakes = async (intakeNos: string[]) => {
const runNoticeBatchFromIntakes = async (intakeNos: string[], candidateNos: string[]) => {
if (noticeBatchSubmitting) {
return true;
}
noticeBatchSubmitting = true;
try {
const conversationKey = normalizeConversationId(ctx.conversationId.value);
const intakeFingerprint = computeNoticeIntakeNosFingerprint(intakeNos);
const intakeFingerprint = computeNoticeIntakeNosFingerprint([...intakeNos, ...candidateNos]);
if (pendingNoticeBatchRetry) {
reconcilePendingNoticeBatchConversation(pendingNoticeBatchRetry, conversationKey);
}
@@ -337,7 +338,12 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
pendingNoticeBatchRetry.fileFingerprint = intakeFingerprint;
}
const idempotencyKey = pendingNoticeBatchRetry.idempotencyKey;
const turn = buildShippingCreateBatchFromIntakesTurn(intakeNos, ctx.conversationId.value, idempotencyKey);
const turn = buildShippingCreateBatchFromIntakesTurn(
intakeNos,
ctx.conversationId.value,
idempotencyKey,
candidateNos,
);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'upload_followup',
@@ -402,8 +408,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
const noticeFiles = files.filter(Boolean);
const intakeNos = ctx.getParsedIntakeNos?.() || [];
const candidateNos = ctx.getSelectedCandidateNos?.() || [];
if (!noticeFiles.length && intakeNos.length) {
await runNoticeBatchFromIntakes(intakeNos);
await runNoticeBatchFromIntakes(intakeNos, candidateNos);
return;
}
if (!noticeFiles.length) return;
@@ -13,15 +13,18 @@ import type {
ShippingDuplicateResult,
ShippingNoticeParseSummary,
ShippingNoticePendingAttachment,
ShippingNoticeCandidate,
} from '../types/shipping.types';
import type { ShippingNoticeIntakeResponse } from '../types/shipping.api.types';
import type { ShippingNoticeCandidateResponse, ShippingNoticeIntakeResponse } from '../types/shipping.api.types';
import {
cancelShippingNoticeIntake,
createShippingNoticeIntake,
getShippingNoticeIntakeStatuses,
listActiveShippingNoticeIntakes,
resolveShippingNoticeDuplicate,
resolveShippingNoticeCandidateDuplicate,
retryShippingNoticeIntake,
updateShippingNoticeCandidate,
} from '@/features/chat/api/shipping.api';
import { isShippingNoticeAttachmentParseIncomplete } from './shippingNoticeAttachmentIntegrity';
@@ -82,6 +85,44 @@ function listSafe(value: unknown): string[] {
return Array.isArray(value) ? value.map((item) => String(item)) : [];
}
/** 将 Candidate API 契约映射为输入区可审核状态。 */
function mapServerCandidate(remote: ShippingNoticeCandidateResponse): ShippingNoticeCandidate {
const duplicate = remote.duplicate
? {
status: remote.duplicate.status,
blocking: Boolean(remote.duplicate.blocking),
fingerprintStrength: remote.duplicate.fingerprint_strength,
matches: (remote.duplicate.matches || []).map((item) => ({
taskNo: item.task_no,
processStatus: item.process_status,
documentVersion: Number(item.document_version || 1),
matchType: item.match_type,
matchedFields: listSafe(item.matched_fields),
createdAt: item.created_at,
})),
allowedActions: (remote.duplicate.allowed_actions || []) as ShippingDuplicateAction[],
}
: undefined;
return {
candidateNo: remote.candidate_no,
poNumber: remote.po_number || undefined,
documentFilename: remote.primary_document_filename || undefined,
validationStatus: remote.validation_status,
selected: Boolean(remote.selected),
conflicts: remote.conflicts || [],
businessSummary: remote.business_summary || {},
duplicate,
duplicateResolution: remote.duplicate_resolution
? {
action: remote.duplicate_resolution.action,
targetTaskNo: remote.duplicate_resolution.target_task_no || undefined,
reason: remote.duplicate_resolution.reason || undefined,
}
: undefined,
consumedTaskId: remote.consumed_task_id || undefined,
};
}
function createPendingAttachment(file: File): ShippingNoticePendingAttachment {
return {
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
@@ -142,12 +183,28 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
const hasBlockingDuplicates = computed(() =>
noticeAttachments.value.some(
(item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
(item) => (item.candidates?.length
? item.candidates.some((candidate) =>
candidate.selected && candidate.duplicate?.blocking && !candidate.duplicateResolution?.action,
)
: item.duplicate?.blocking && !item.duplicateResolution?.action),
),
);
const hasCandidateReviewIssues = computed(() =>
noticeAttachments.value.some((item) =>
(item.candidates || []).some((candidate) =>
candidate.selected && candidate.validationStatus !== 'ready',
),
),
);
const allReadyForConfirmation = computed(() =>
allParsedReady.value && !hasBlockingDuplicates.value && !hasParseFailures.value,
allParsedReady.value
&& !hasBlockingDuplicates.value
&& !hasCandidateReviewIssues.value
&& !hasParseFailures.value
&& noticeAttachments.value.some((item) => (item.candidates || []).some((candidate) => candidate.selected)),
);
const stopPolling = () => {
@@ -198,12 +255,15 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
if (!local) continue;
patchAttachment(local.id, {
parseStatus: mapServerParseStatus(remote.parse_status),
orderExtractionStatus: remote.order_extraction_status || undefined,
orderExtractionVersion: remote.order_extraction_version || undefined,
parseSummary: (remote.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: remote.error_code || undefined,
errorMessage: remote.error_message || undefined,
errorCode: remote.order_extraction_error_code || remote.error_code || undefined,
errorMessage: remote.order_extraction_error_message || remote.error_message || undefined,
expiresAt: remote.expires_at || undefined,
assetNo: remote.asset_no || local.assetNo,
...mapServerDuplicate(remote),
candidates: (remote.candidates || []).map(mapServerCandidate),
});
}
};
@@ -226,10 +286,14 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
patchAttachment(attachment.id, {
intakeNo: intake.intake_no,
parseStatus: mapServerParseStatus(intake.parse_status),
orderExtractionStatus: intake.order_extraction_status || undefined,
orderExtractionVersion: intake.order_extraction_version || undefined,
parseSummary: (intake.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: intake.error_code || undefined,
errorMessage: intake.error_message || undefined,
errorCode: intake.order_extraction_error_code || intake.error_code || undefined,
errorMessage: intake.order_extraction_error_message || intake.error_message || undefined,
expiresAt: intake.expires_at || undefined,
...mapServerDuplicate(intake),
candidates: (intake.candidates || []).map(mapServerCandidate),
});
schedulePoll();
} catch (error) {
@@ -294,8 +358,10 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
.map((item) => String(item.intakeNo));
const clearConsumedAttachments = () => {
options.attachments.value = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
stopPolling();
options.attachments.value = options.attachments.value.filter(
(item) => item.kind !== 'shipping_notice' || item.parseStatus !== 'consumed',
);
if (!noticeAttachments.value.length) stopPolling();
};
const restoreForConversation = async (conversationId?: string | null) => {
@@ -311,14 +377,17 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
intakeNo: item.intake_no,
uploadStatus: 'uploaded' as const,
parseStatus: mapServerParseStatus(item.parse_status),
orderExtractionStatus: item.order_extraction_status || undefined,
orderExtractionVersion: item.order_extraction_version || undefined,
uploadProgress: 100,
originalFilename: item.original_filename || item.intake_no,
fileSize: Number(item.file_size || 0),
parseSummary: (item.parse_summary || undefined) as ShippingNoticeParseSummary | undefined,
errorCode: item.error_code || undefined,
errorMessage: item.error_message || undefined,
errorCode: item.order_extraction_error_code || item.error_code || undefined,
errorMessage: item.order_extraction_error_message || item.error_message || undefined,
expiresAt: item.expires_at || undefined,
...mapServerDuplicate(item),
...mapServerDuplicate(item),
candidates: (item.candidates || []).map(mapServerCandidate),
}));
const nonNotice = options.attachments.value.filter((item) => item.kind !== 'shipping_notice');
options.attachments.value = [...nonNotice, ...restored];
@@ -347,6 +416,56 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
});
};
/** 切换 Candidate 是否参与本次建批。 */
const setCandidateSelected = async (candidateNo: string, selected: boolean) => {
const remote = await updateShippingNoticeCandidate(candidateNo, { selected });
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, {
candidates: (attachment.candidates || []).map((item) =>
item.candidateNo === candidateNo ? mapServerCandidate(remote) : item,
),
});
}
};
/** 保存 Candidate 人工修订后的订单摘要。 */
const updateCandidateSummary = async (candidateNo: string, businessSummary: Record<string, unknown>) => {
const remote = await updateShippingNoticeCandidate(candidateNo, { business_summary: businessSummary });
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, {
candidates: (attachment.candidates || []).map((item) =>
item.candidateNo === candidateNo ? mapServerCandidate(remote) : item,
),
});
}
};
/** 保存单个 Candidate 的重复处理决策。 */
const resolveCandidateDuplicate = async (
candidateNo: string,
action: ShippingDuplicateAction,
targetTaskNo?: string,
reason?: string,
) => {
const remote = await resolveShippingNoticeCandidateDuplicate(candidateNo, action, targetTaskNo, reason);
for (const attachment of noticeAttachments.value) {
if (!(attachment.candidates || []).some((item) => item.candidateNo === candidateNo)) continue;
patchAttachment(attachment.id, {
candidates: (attachment.candidates || []).map((item) =>
item.candidateNo === candidateNo ? mapServerCandidate(remote) : item,
),
});
}
};
const getSelectedCandidateNos = () => noticeAttachments.value.flatMap((item) =>
(item.candidates || [])
.filter((candidate) => candidate.selected)
.map((candidate) => candidate.candidateNo),
);
onBeforeUnmount(() => {
stopPolling();
});
@@ -357,12 +476,18 @@ export function useShippingNoticeIntakes(options: UseShippingNoticeIntakesOption
hasParseFailures,
allParsedReady,
hasBlockingDuplicates,
hasCandidateReviewIssues,
allReadyForConfirmation,
enqueueNoticeFiles,
removeNoticeAttachment,
retryNoticeAttachment,
resolveDuplicateAttachment,
resolveCandidateDuplicate,
setCandidateSelected,
updateCandidateSummary,
getParsedIntakeNos,
getSelectedCandidateNos,
refreshStatuses,
clearConsumedAttachments,
restoreForConversation,
stopPolling,
@@ -81,6 +81,7 @@ export interface ShippingTaskSummary {
line_results?: ShippingMatchLineResult[];
step_payload?: Record<string, unknown> & {
current_step_progress?: ShippingCurrentStepProgress;
parse_validation?: ShippingParseValidation;
};
rpa_runtime?: ShippingRpaRuntime | null;
rpa_inventory_source?: Record<string, unknown> | null;
@@ -138,6 +139,25 @@ export interface ShippingCurrentStepProgress {
extra?: Record<string, unknown>;
}
export interface ShippingParseIssue {
line_index?: number;
sku?: string | null;
field: string;
reason: 'missing' | 'invalid_format' | 'source_conflict' | 'value_corrected' | string;
severity: 'blocking' | 'info' | string;
raw_value?: string | null;
resolved_value?: string | null;
resolution_basis?: string | null;
evidence_values?: string[];
}
export interface ShippingParseValidation {
status: 'ready' | 'needs_review' | string;
issues: ShippingParseIssue[];
contract_version?: string;
resolution_source?: string;
}
export interface ShippingNoticeHeader {
customer_name?: string | null;
customer_code?: string | null;
@@ -320,6 +340,10 @@ export interface ShippingNoticeIntakeResponse {
conversation_id?: string | null;
parse_status: string;
parser_version?: string;
order_extraction_status?: string | null;
order_extraction_version?: string | null;
order_extraction_error_code?: string | null;
order_extraction_error_message?: string | null;
parse_summary?: Record<string, unknown> | null;
business_summary?: Record<string, unknown> | null;
business_fingerprint?: string | null;
@@ -343,6 +367,37 @@ export interface ShippingNoticeIntakeResponse {
original_filename?: string;
file_size?: number;
content_hash?: string;
documents?: ShippingNoticeDocumentResponse[];
candidates?: ShippingNoticeCandidateResponse[];
document_count?: number;
candidate_count?: number;
}
export interface ShippingNoticeDocumentResponse {
id: number;
document_type: string;
filename?: string | null;
classification: string;
parse_status: string;
warnings?: string[];
}
export interface ShippingNoticeCandidateResponse {
candidate_no: string;
primary_document_id?: number;
primary_document_filename?: string | null;
po_number?: string | null;
validation_status: string;
selected: boolean;
conflicts?: Array<Record<string, unknown>>;
business_summary?: Record<string, unknown> | null;
duplicate?: ShippingDuplicateResult | null;
duplicate_resolution?: {
action: ShippingDuplicateAction;
target_task_no?: string | null;
reason?: string | null;
} | null;
consumed_task_id?: number | null;
}
export type ShippingDuplicateStatus =
@@ -351,7 +406,10 @@ export type ShippingDuplicateStatus =
| 'exact_file'
| 'same_active_task'
| 'same_completed_task'
| 'possible_duplicate';
| 'possible_duplicate'
| 'same_business_content'
| 'possible_revision'
| 'partial_duplicate';
export type ShippingDuplicateAction = 'open_existing' | 'create_revision' | 'force_create';
@@ -32,7 +32,10 @@ export type ShippingDuplicateStatus =
| 'exact_file'
| 'same_active_task'
| 'same_completed_task'
| 'possible_duplicate';
| 'possible_duplicate'
| 'same_business_content'
| 'possible_revision'
| 'partial_duplicate';
export interface ShippingDuplicateMatch {
taskNo: string;
@@ -57,6 +60,19 @@ export interface ShippingDuplicateResolution {
reason?: string;
}
export interface ShippingNoticeCandidate {
candidateNo: string;
poNumber?: string;
documentFilename?: string;
validationStatus: string;
selected: boolean;
conflicts: Array<Record<string, unknown>>;
businessSummary: Record<string, unknown>;
duplicate?: ShippingDuplicateResult;
duplicateResolution?: ShippingDuplicateResolution;
consumedTaskId?: number;
}
export interface ShippingNoticeParseAttachmentSummary {
attachment_key?: string;
filename?: string;
@@ -113,11 +129,14 @@ export type ShippingNoticePendingAttachment = {
originalFilename: string;
fileSize: number;
parseSummary?: ShippingNoticeParseSummary;
orderExtractionStatus?: string;
orderExtractionVersion?: string;
errorCode?: string;
errorMessage?: string;
expiresAt?: string;
duplicate?: ShippingDuplicateResult;
duplicateResolution?: ShippingDuplicateResolution;
candidates?: ShippingNoticeCandidate[];
};
/** 待发送附件(本地文件、远程 URL 或货代通知预解析) */
@@ -130,6 +130,13 @@ const detailStepDetail = computed(() =>
const detailErrorMessage = computed(() =>
sanitizeShippingRuntimeStatusText(String(detail.value?.error_message || '').trim()),
);
const detailIssues = computed(() => (
Array.isArray(detail.value?.ui_state?.summary?.issues)
? detail.value.ui_state.summary.issues
.map((item) => sanitizeShippingRuntimeStatusText(String(item || '').trim()))
.filter(Boolean)
: []
));
const inventorySnapshotLabel = (triggerType?: string | null) => {
const key = String(triggerType || 'on_demand');
@@ -489,6 +496,10 @@ onMounted(async () => {
{{ detailErrorMessage }}
</div>
<div v-if="detailIssues.length" class="rounded-xl border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
<div v-for="issue in detailIssues" :key="issue" class="py-0.5">{{ issue }}</div>
</div>
<ShippingMatchResultCard
v-if="hasMatchCard"
:task-id="detail.task_no"
+23
View File
@@ -68,6 +68,29 @@
"shippingNoticeDuplicateOpenChosen": "Will open existing task",
"shippingNoticeDuplicateResolved": "Duplicate resolution saved.",
"shippingNoticeDuplicateResolveFailed": "Failed to save duplicate resolution.",
"shippingCandidateTitle": "Order candidate review",
"shippingCandidateCount": "{count} orders",
"shippingCandidateReady": "Ready",
"shippingCandidateNeedsReview": "Needs review",
"shippingCandidateEdit": "Edit",
"shippingCandidateSave": "Save changes",
"shippingCandidateConflictCount": "{count} field conflicts must be corrected before task creation.",
"shippingCandidateDuplicate": "Matches existing task {task}",
"shippingCandidateDuplicateResolved": "Duplicate action selected: {action}",
"shippingCandidateForceReasonPrompt": "Enter the reason for force creation",
"shippingCandidateReviewRequired": "A selected order candidate still needs review. Correct its conflicting fields first.",
"shippingCandidateSelectRequired": "Select at least one order candidate before creating tasks.",
"shippingOrderExtractionDefaultPrompt": "Fully parse the shipping orders in the uploaded email and attachments, then create eligible tasks automatically.",
"shippingCandidateInvalidLine": "Every order line requires a SKU and a quantity greater than zero.",
"shippingCandidatePoNumber": "PO Number",
"shippingCandidateSku": "SKU",
"shippingCandidateQty": "Quantity",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateUom": "UOM",
"shippingCandidateAddLine": "Add order line",
"shippingCandidateUpdateDone": "Order candidate changes were saved.",
"shippingCandidateUpdateFailed": "Failed to save the order candidate.",
"shippingInventoryUploadFailed": "Inventory upload failed.",
"shippingNoticeRefreshDone": "Current task status refreshed.",
"shippingNoticeRetryUploadAction": "Retry freight upload",
+14 -1
View File
@@ -49,6 +49,8 @@
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "Shipping notice intake not found.",
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "Shipping notice is still parsing. Please wait before confirming the batch.",
"SHIPPING_NOTICE_INTAKE_PARSE_FAILED": "Shipping notice parse failed. Retry or remove and upload again.",
"SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "Shipping notice parsing timed out. Retry or remove and upload again.",
"SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "Saving preprocessed email or attachment documents failed. Retry parsing.",
"SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "Shipping notice attachments are incomplete. Retry parse or remove and upload again.",
"SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "Shipping notice intake has already been consumed.",
"SHIPPING_NOTICE_INTAKE_EXPIRED": "Shipping notice intake has expired.",
@@ -61,6 +63,17 @@
"SHIPPING_NOTICE_REVISION_TARGET_INVALID": "The revision target task is invalid.",
"SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "A later revision of this task already exists.",
"SHIPPING_NOTICE_REVISION_CONFLICT": "A revision of this task already exists. Open the existing revision or re-check.",
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "A reliable business fingerprint could not be generated; only file-hash dedupe applies."
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "A reliable business fingerprint could not be generated; only file-hash dedupe applies.",
"SHIPPING_NOTICE_CANDIDATE_NOT_FOUND": "The order candidate was not found.",
"SHIPPING_NOTICE_CANDIDATE_ALREADY_CONSUMED": "The order candidate has already created a task and cannot be changed.",
"SHIPPING_NOTICE_CANDIDATE_NOT_SELECTED": "The order candidate is not selected.",
"SHIPPING_NOTICE_CANDIDATE_REVIEW_REQUIRED": "The order candidate still requires manual review.",
"SHIPPING_NOTICE_CANDIDATE_DOCUMENT_INVALID": "The order candidate's primary attachment is invalid.",
"SHIPPING_NOTICE_CANDIDATE_SELECTION_CHANGED": "The order candidate selection changed. Refresh and try again.",
"SHIPPING_NOTICE_DUPLICATE_ACTION_UNAVAILABLE": "This duplicate action is not allowed for the current state.",
"SHIPPING_NOTICE_ORDER_EXTRACTION_CONTEXT_INVALID": "The order extraction context is invalid. Send the current email again.",
"SHIPPING_NOTICE_ORDER_EXTRACTION_PENDING": "Email preprocessing is incomplete or order extraction is still in progress.",
"SHIPPING_NOTICE_ORDER_EXTRACTION_INVALID_RESULT": "The extracted order result does not match the contract. Parse it again.",
"SHIPPING_NOTICE_CANDIDATE_SOURCE_CHANGED": "The email or attachment content changed. Send it again to re-extract orders."
}
}
+23
View File
@@ -68,6 +68,29 @@
"shippingNoticeDuplicateOpenChosen": "จะเปิดงานที่มีอยู่",
"shippingNoticeDuplicateResolved": "บันทึกวิธีจัดการรายการซ้ำแล้ว",
"shippingNoticeDuplicateResolveFailed": "บันทึกวิธีจัดการรายการซ้ำไม่สำเร็จ",
"shippingCandidateTitle": "ตรวจสอบรายการคำสั่งซื้อ",
"shippingCandidateCount": "คำสั่งซื้อ {count} รายการ",
"shippingCandidateReady": "พร้อมสร้างงาน",
"shippingCandidateNeedsReview": "ต้องตรวจสอบ",
"shippingCandidateEdit": "แก้ไข",
"shippingCandidateSave": "บันทึกการแก้ไข",
"shippingCandidateConflictCount": "มีข้อมูลขัดแย้ง {count} จุด โปรดแก้ไขก่อนสร้างงาน",
"shippingCandidateDuplicate": "ตรงกับงานเดิม {task}",
"shippingCandidateDuplicateResolved": "เลือกวิธีจัดการรายการซ้ำแล้ว: {action}",
"shippingCandidateForceReasonPrompt": "ระบุเหตุผลที่ต้องบังคับสร้างงานใหม่",
"shippingCandidateReviewRequired": "รายการคำสั่งซื้อที่เลือกยังต้องตรวจสอบ โปรดแก้ไขข้อมูลที่ขัดแย้งก่อน",
"shippingCandidateSelectRequired": "โปรดเลือกรายการคำสั่งซื้ออย่างน้อยหนึ่งรายการก่อนสร้างงาน",
"shippingOrderExtractionDefaultPrompt": "โปรดแยกวิเคราะห์คำสั่งซื้อจัดส่งจากอีเมลและไฟล์แนบที่อัปโหลดให้ครบถ้วน แล้วสร้างงานที่ผ่านเกณฑ์โดยอัตโนมัติ",
"shippingCandidateInvalidLine": "ทุกรายการต้องมี SKU และจำนวนมากกว่าศูนย์",
"shippingCandidatePoNumber": "PO Number",
"shippingCandidateSku": "SKU",
"shippingCandidateQty": "จำนวน",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateUom": "หน่วย",
"shippingCandidateAddLine": "เพิ่มรายการคำสั่งซื้อ",
"shippingCandidateUpdateDone": "บันทึกการแก้ไขรายการคำสั่งซื้อแล้ว",
"shippingCandidateUpdateFailed": "บันทึกรายการคำสั่งซื้อไม่สำเร็จ",
"shippingInventoryUploadFailed": "อัปโหลดไฟล์สต็อกล้มเหลว",
"shippingNoticeRefreshDone": "รีเฟรชสถานะงานปัจจุบันแล้ว",
"shippingNoticeRetryUploadAction": "ลองอัปโหลดไปยังระบบขนส่งอีกครั้ง",
+14 -1
View File
@@ -49,6 +49,8 @@
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "ไม่พบบันทึก intake ของใบแจ้งจัดส่ง",
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "ใบแจ้งจัดส่งยังกำลังแยกข้อความ โปรดรอก่อนยืนยันสร้างชุดงาน",
"SHIPPING_NOTICE_INTAKE_PARSE_FAILED": "แยกข้อความใบแจ้งจัดส่งล้มเหลว โปรดลองใหม่หรือลบแล้วอัปโหลดใหม่",
"SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "การแยกข้อความใบแจ้งจัดส่งหมดเวลา โปรดลองใหม่หรือลบแล้วอัปโหลดใหม่",
"SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "บันทึกอีเมลหรือไฟล์แนบที่ประมวลผลเบื้องต้นไม่สำเร็จ โปรดลองแยกข้อความใหม่",
"SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "ไฟล์แนบใบแจ้งจัดส่งแยกข้อความไม่ครบ โปรดลองแยกใหม่หรือลบแล้วอัปโหลดใหม่",
"SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "บันทึก intake ถูกใช้งานไปแล้ว",
"SHIPPING_NOTICE_INTAKE_EXPIRED": "บันทึก intake หมดอายุแล้ว",
@@ -61,6 +63,17 @@
"SHIPPING_NOTICE_REVISION_TARGET_INVALID": "งานเป้าหมายสำหรับการแก้ไขไม่ถูกต้อง",
"SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "งานนี้มีเวอร์ชันแก้ไขถัดไปอยู่แล้ว",
"SHIPPING_NOTICE_REVISION_CONFLICT": "งานเป้าหมายมีเวอร์ชันแก้ไขอยู่แล้ว กรุณาเปิดเวอร์ชันที่มีหรือตรวจสอบใหม่",
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "สร้างลายนิ้วมือทางธุรกิจที่เชื่อถือได้ไม่ได้ จะใช้การตัดรายการซ้ำด้วยแฮชไฟล์เท่านั้น"
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "สร้างลายนิ้วมือทางธุรกิจที่เชื่อถือได้ไม่ได้ จะใช้การตัดรายการซ้ำด้วยแฮชไฟล์เท่านั้น",
"SHIPPING_NOTICE_CANDIDATE_NOT_FOUND": "ไม่พบรายการคำสั่งซื้อ",
"SHIPPING_NOTICE_CANDIDATE_ALREADY_CONSUMED": "รายการคำสั่งซื้อนี้สร้างงานแล้วและไม่สามารถแก้ไขได้",
"SHIPPING_NOTICE_CANDIDATE_NOT_SELECTED": "ยังไม่ได้เลือกรายการคำสั่งซื้อ",
"SHIPPING_NOTICE_CANDIDATE_REVIEW_REQUIRED": "รายการคำสั่งซื้อยังต้องได้รับการตรวจสอบ",
"SHIPPING_NOTICE_CANDIDATE_DOCUMENT_INVALID": "ไฟล์แนบหลักของรายการคำสั่งซื้อไม่ถูกต้อง",
"SHIPPING_NOTICE_CANDIDATE_SELECTION_CHANGED": "สถานะการเลือกรายการคำสั่งซื้อเปลี่ยนแปลง โปรดรีเฟรชแล้วลองใหม่",
"SHIPPING_NOTICE_DUPLICATE_ACTION_UNAVAILABLE": "สถานะรายการซ้ำปัจจุบันไม่อนุญาตการดำเนินการนี้",
"SHIPPING_NOTICE_ORDER_EXTRACTION_CONTEXT_INVALID": "บริบทการแยกคำสั่งซื้อไม่ถูกต้อง โปรดส่งอีเมลปัจจุบันอีกครั้ง",
"SHIPPING_NOTICE_ORDER_EXTRACTION_PENDING": "การประมวลผลอีเมลเบื้องต้นยังไม่เสร็จ หรือกำลังแยกคำสั่งซื้ออยู่",
"SHIPPING_NOTICE_ORDER_EXTRACTION_INVALID_RESULT": "ผลการแยกคำสั่งซื้อไม่ตรงตามสัญญาข้อมูล โปรดลองแยกข้อความใหม่",
"SHIPPING_NOTICE_CANDIDATE_SOURCE_CHANGED": "เนื้อหาอีเมลหรือไฟล์แนบเปลี่ยนแปลง โปรดส่งอีกครั้งเพื่อแยกคำสั่งซื้อใหม่"
}
}
+23
View File
@@ -68,6 +68,29 @@
"shippingNoticeDuplicateOpenChosen": "将打开已有任务",
"shippingNoticeDuplicateResolved": "重复处理方式已保存。",
"shippingNoticeDuplicateResolveFailed": "保存重复处理方式失败。",
"shippingCandidateTitle": "订单候选审核",
"shippingCandidateCount": "共 {count} 个订单",
"shippingCandidateReady": "可建单",
"shippingCandidateNeedsReview": "需要审核",
"shippingCandidateEdit": "修订",
"shippingCandidateSave": "保存修订",
"shippingCandidateConflictCount": "存在 {count} 个字段冲突,请修订后再建单。",
"shippingCandidateDuplicate": "命中重复任务 {task}",
"shippingCandidateDuplicateResolved": "重复处理已选择:{action}",
"shippingCandidateForceReasonPrompt": "请输入强制新建原因",
"shippingCandidateReviewRequired": "仍有已选订单候选需要审核,请先修订冲突字段。",
"shippingCandidateSelectRequired": "请至少选择一个订单候选后再确认建单。",
"shippingOrderExtractionDefaultPrompt": "请完整解析已上传邮件及附件中的发货订单,并按规则自动建单。",
"shippingCandidateInvalidLine": "每条订单行都必须填写 SKU 和大于 0 的数量。",
"shippingCandidatePoNumber": "PO Number",
"shippingCandidateSku": "SKU",
"shippingCandidateQty": "数量",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateUom": "单位",
"shippingCandidateAddLine": "新增订单行",
"shippingCandidateUpdateDone": "订单候选修订已保存。",
"shippingCandidateUpdateFailed": "保存订单候选失败。",
"shippingInventoryUploadFailed": "库存文件上传失败。",
"shippingNoticeRefreshDone": "已刷新当前任务状态。",
"shippingNoticeRetryUploadAction": "重试上传货代",
+14 -1
View File
@@ -49,6 +49,8 @@
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "发货通知接入记录不存在。",
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "发货通知仍在解析中,请稍后再确认建单。",
"SHIPPING_NOTICE_INTAKE_PARSE_FAILED": "发货通知解析失败,请重试或移除后重新上传。",
"SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "发货通知解析超时,请重试或移除后重新上传。",
"SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "发货通知正文或附件预处理保存失败,请重试解析。",
"SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "发货通知附件解析不完整,请重试解析或移除后重新上传。",
"SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "发货通知接入记录已被消费。",
"SHIPPING_NOTICE_INTAKE_EXPIRED": "发货通知接入记录已过期。",
@@ -61,6 +63,17 @@
"SHIPPING_NOTICE_REVISION_TARGET_INVALID": "修订目标任务无效。",
"SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "该任务已有后续修订版本。",
"SHIPPING_NOTICE_REVISION_CONFLICT": "目标任务已有修订版本,请打开已有修订或重新检测。",
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "无法生成可靠业务指纹,将仅按文件去重。"
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "无法生成可靠业务指纹,将仅按文件去重。",
"SHIPPING_NOTICE_CANDIDATE_NOT_FOUND": "订单候选不存在。",
"SHIPPING_NOTICE_CANDIDATE_ALREADY_CONSUMED": "订单候选已被建单,无法修改。",
"SHIPPING_NOTICE_CANDIDATE_NOT_SELECTED": "订单候选未被选中。",
"SHIPPING_NOTICE_CANDIDATE_REVIEW_REQUIRED": "订单候选仍需人工审核。",
"SHIPPING_NOTICE_CANDIDATE_DOCUMENT_INVALID": "订单候选的主附件无效。",
"SHIPPING_NOTICE_CANDIDATE_SELECTION_CHANGED": "订单候选选择状态已变化,请刷新后重试。",
"SHIPPING_NOTICE_DUPLICATE_ACTION_UNAVAILABLE": "当前重复状态不允许该处理方式。",
"SHIPPING_NOTICE_ORDER_EXTRACTION_CONTEXT_INVALID": "订单识别上下文无效,请重新发送当前邮件。",
"SHIPPING_NOTICE_ORDER_EXTRACTION_PENDING": "邮件预处理尚未完成,或本次订单识别仍在处理中。",
"SHIPPING_NOTICE_ORDER_EXTRACTION_INVALID_RESULT": "订单识别结果不符合协议,请重新解析。",
"SHIPPING_NOTICE_CANDIDATE_SOURCE_CHANGED": "邮件或附件内容已变化,请重新发送并识别订单。"
}
}
+23
View File
@@ -68,6 +68,29 @@
"shippingNoticeDuplicateOpenChosen": "將開啟已有任務",
"shippingNoticeDuplicateResolved": "重複處理方式已儲存。",
"shippingNoticeDuplicateResolveFailed": "儲存重複處理方式失敗。",
"shippingCandidateTitle": "訂單候選審核",
"shippingCandidateCount": "共 {count} 個訂單",
"shippingCandidateReady": "可建單",
"shippingCandidateNeedsReview": "需要審核",
"shippingCandidateEdit": "修訂",
"shippingCandidateSave": "儲存修訂",
"shippingCandidateConflictCount": "存在 {count} 個欄位衝突,請修訂後再建單。",
"shippingCandidateDuplicate": "命中重複任務 {task}",
"shippingCandidateDuplicateResolved": "重複處理已選擇:{action}",
"shippingCandidateForceReasonPrompt": "請輸入強制新建原因",
"shippingCandidateReviewRequired": "仍有已選訂單候選需要審核,請先修訂衝突欄位。",
"shippingCandidateSelectRequired": "請至少選擇一個訂單候選後再確認建單。",
"shippingOrderExtractionDefaultPrompt": "請完整解析已上傳郵件及附件中的發貨訂單,並依規則自動建單。",
"shippingCandidateInvalidLine": "每條訂單行都必須填寫 SKU 和大於 0 的數量。",
"shippingCandidatePoNumber": "PO Number",
"shippingCandidateSku": "SKU",
"shippingCandidateQty": "數量",
"shippingCandidateReservation": "Reservation ID",
"shippingCandidateHubCode": "Hub Code",
"shippingCandidateUom": "單位",
"shippingCandidateAddLine": "新增訂單行",
"shippingCandidateUpdateDone": "訂單候選修訂已儲存。",
"shippingCandidateUpdateFailed": "儲存訂單候選失敗。",
"shippingInventoryUploadFailed": "庫存檔案上傳失敗。",
"shippingNoticeRefreshDone": "已重新整理目前任務狀態。",
"shippingNoticeRetryUploadAction": "重試上傳貨代",
+14 -1
View File
@@ -49,6 +49,8 @@
"SHIPPING_NOTICE_INTAKE_NOT_FOUND": "發貨通知接入記錄不存在。",
"SHIPPING_NOTICE_INTAKE_PARSE_PENDING": "發貨通知仍在解析中,請稍後再確認建單。",
"SHIPPING_NOTICE_INTAKE_PARSE_FAILED": "發貨通知解析失敗,請重試或移除後重新上傳。",
"SHIPPING_NOTICE_INTAKE_PARSE_TIMEOUT": "發貨通知解析逾時,請重試或移除後重新上傳。",
"SHIPPING_NOTICE_INTAKE_STAGE2_PERSIST_FAILED": "發貨通知正文或附件預處理儲存失敗,請重試解析。",
"SHIPPING_NOTICE_INTAKE_ATTACHMENTS_INCOMPLETE": "發貨通知附件解析不完整,請重試解析或移除後重新上傳。",
"SHIPPING_NOTICE_INTAKE_ALREADY_CONSUMED": "發貨通知接入記錄已被消費。",
"SHIPPING_NOTICE_INTAKE_EXPIRED": "發貨通知接入記錄已過期。",
@@ -61,6 +63,17 @@
"SHIPPING_NOTICE_REVISION_TARGET_INVALID": "修訂目標任務無效。",
"SHIPPING_NOTICE_REVISION_ALREADY_EXISTS": "該任務已有後續修訂版本。",
"SHIPPING_NOTICE_REVISION_CONFLICT": "目標任務已有修訂版本,請打開已有修訂或重新檢測。",
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "無法產生可靠業務指紋,將僅按檔案去重。"
"SHIPPING_NOTICE_FINGERPRINT_UNAVAILABLE": "無法產生可靠業務指紋,將僅按檔案去重。",
"SHIPPING_NOTICE_CANDIDATE_NOT_FOUND": "訂單候選不存在。",
"SHIPPING_NOTICE_CANDIDATE_ALREADY_CONSUMED": "訂單候選已被建單,無法修改。",
"SHIPPING_NOTICE_CANDIDATE_NOT_SELECTED": "訂單候選未被選中。",
"SHIPPING_NOTICE_CANDIDATE_REVIEW_REQUIRED": "訂單候選仍需人工審核。",
"SHIPPING_NOTICE_CANDIDATE_DOCUMENT_INVALID": "訂單候選的主附件無效。",
"SHIPPING_NOTICE_CANDIDATE_SELECTION_CHANGED": "訂單候選選擇狀態已變化,請重新整理後再試。",
"SHIPPING_NOTICE_DUPLICATE_ACTION_UNAVAILABLE": "目前重複狀態不允許此處理方式。",
"SHIPPING_NOTICE_ORDER_EXTRACTION_CONTEXT_INVALID": "訂單識別上下文無效,請重新傳送目前郵件。",
"SHIPPING_NOTICE_ORDER_EXTRACTION_PENDING": "郵件預處理尚未完成,或本次訂單識別仍在處理中。",
"SHIPPING_NOTICE_ORDER_EXTRACTION_INVALID_RESULT": "訂單識別結果不符合協議,請重新解析。",
"SHIPPING_NOTICE_CANDIDATE_SOURCE_CHANGED": "郵件或附件內容已變更,請重新傳送並識別訂單。"
}
}