feat(shipping-notice): 添加订单文档 Profile 盲测集和样本管理功能,支持创建、执行和批准盲测,增强订单冻结和库存核验功能

This commit is contained in:
hugo committed 2026-07-23 00:15:34 +08:00
1 parent c35223d49d
commit abd8fc1e16
98 files changed
+4629 -528

No files matched your search

@@ -46,6 +46,23 @@ def list_order_document_profile_samples():
return _ok(service.list_sample_documents(limit=limit))
@admin_bp.route('/shipping-notice/order-document-profile-samples', methods=['POST'])
@require_admin
def create_order_document_profile_sample():
"""将管理员已上传的 PDF/EML 投递为隔离模板样本,不创建发货业务数据。"""
data = request.get_json(silent=True) or {}
return _ok(service.create_sample_intake(
asset_no=str(data.get('asset_no') or ''), actor_id=_actor_id(),
), status=202)
@admin_bp.route('/shipping-notice/order-document-profile-samples/intakes/<string:intake_no>', methods=['GET'])
@require_admin
def get_order_document_profile_sample_status(intake_no: str):
"""读取当前管理员模板样本的异步解析状态。"""
return _ok(service.get_sample_intake_status(intake_no, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/order-document-profile-samples/<int:document_id>/tables', methods=['GET'])
@require_admin
def get_order_document_profile_sample_tables(document_id: int):
@@ -119,3 +136,39 @@ def delete_order_document_profile(profile_id: int):
"""删除错误草稿。"""
service.delete_draft(profile_id)
return '', 204
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/test-suites', methods=['POST'])
@require_admin
def create_order_document_profile_test_suite(profile_id: int):
"""为发布模板创建独立盲测集。"""
from app.services.shipping_notice import document_profile_quality_service as quality
return _ok(quality.create_suite(profile_id=profile_id, actor_id=_actor_id()), status=201)
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/samples', methods=['POST'])
@require_admin
def add_order_document_profile_test_sample(suite_id: int):
"""写入管理员确认的盲测样本真值。"""
from app.services.shipping_notice import document_profile_quality_service as quality
data = request.get_json(silent=True) or {}
return _ok(quality.add_sample(
suite_id=suite_id, document_id=data.get('document_id'), table_id=str(data.get('table_id') or ''),
expected_rows=data.get('expected_rows'), actor_id=_actor_id(),
), status=201)
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/execute', methods=['POST'])
@require_admin
def execute_order_document_profile_test_suite(suite_id: int):
"""运行盲测并记录不可变结果。"""
from app.services.shipping_notice import document_profile_quality_service as quality
return _ok(quality.execute_suite(suite_id=suite_id, actor_id=_actor_id()))
@admin_bp.route('/shipping-notice/order-document-profile-test-suites/<int:suite_id>/approve', methods=['POST'])
@require_admin
def approve_order_document_profile_test_suite(suite_id: int):
"""批准最新合格盲测,使该模板可参与确定性自动建单。"""
from app.services.shipping_notice import document_profile_quality_service as quality
return _ok(quality.approve_suite(suite_id=suite_id, actor_id=_actor_id()))
+78 -6
View File
@@ -51,6 +51,7 @@ from app.services.shipping_notice.customer_identity_gate import (
list_customer_options,
)
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
@@ -295,6 +296,7 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
customer_id=customer_id,
site_id=site_id,
actor_id=user.id,
reason=str(data.get('reason') or ''),
)
return _ok(result)
@@ -616,7 +618,10 @@ def workspace_update_shipping_notice_fields(task_no: str):
if not isinstance(fields, dict) or not fields:
raise ValidationError('fields is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'fields': fields}
payload = {'task_id': task.task_no, 'fields': fields, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
@@ -627,6 +632,33 @@ def workspace_update_shipping_notice_fields(task_no: str):
payload['idempotency_key'] = idem
return jsonify(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freeze-order', methods=['POST'])
def workspace_freeze_shipping_order(task_no: str):
"""冻结已复核订单为不可编辑的强类型履约快照。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
expected_version = int(data.get('expected_order_data_version'))
except (TypeError, ValueError) as exc:
raise ValidationError('expected_order_data_version is required') from exc
snapshot = freeze_order_snapshot(
task,
actor_id=int(user.id),
expected_order_data_version=expected_version,
rule_versions=data.get('rule_versions') if isinstance(data.get('rule_versions'), dict) else None,
)
db.session.commit()
return _ok({
'task_no': task.task_no,
'snapshot_id': snapshot.id,
'order_data_version': snapshot.order_data_version,
'frozen_at': snapshot.frozen_at.isoformat(),
})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
def workspace_update_shipping_notice_line(task_no: str):
"""更新发货通知中的指定订单行。"""
@@ -643,7 +675,10 @@ def workspace_update_shipping_notice_line(task_no: str):
if not isinstance(patch, dict) or not patch:
raise ValidationError('patch is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch}
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
@@ -707,6 +742,7 @@ def workspace_resolve_shipping_field_conflict(task_no: str, conflict_id: int):
expected_conflict_version=_optional_int('expected_conflict_version'),
expected_order_data_version=_optional_int('expected_order_data_version'),
resolved_by_id=int(user.id),
evidence_ref=str(data.get('evidence_ref') or '').strip() or None,
reason=str(data.get('reason') or '').strip() or None,
idempotency_key=str(data.get('idempotency_key') or '').strip() or None,
)
@@ -724,10 +760,18 @@ def workspace_add_shipping_notice_line(task_no: str):
if not isinstance(line, dict) or not line:
raise ValidationError('line is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line': line}
payload = {'task_id': task.task_no, 'line': line, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
@@ -743,10 +787,18 @@ def workspace_remove_shipping_notice_line(task_no: str):
except (TypeError, ValueError):
raise ValidationError('line_index is required')
from app.services.shipping_notice import tools as shipping_tools
payload = {'task_id': task.task_no, 'line_index': line_index}
payload = {'task_id': task.task_no, 'line_index': line_index, 'event_source': 'workspace_api'}
payload['reviewed_by_id'] = int(user.id)
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
payload['reason'] = str(data.get('reason') or '').strip()
comment = str(data.get('comment') or '').strip()
if comment:
payload['comment'] = comment
if data.get('expected_order_data_version') is not None:
payload['expected_order_data_version'] = data.get('expected_order_data_version')
idem = str(data.get('idempotency_key') or '').strip()
if idem:
payload['idempotency_key'] = idem
return jsonify(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
@@ -799,15 +851,35 @@ def workspace_match_shipping_inventory(task_no: str):
matched['action_buttons'] = buttons
return jsonify(matched)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
def workspace_upload_shipping_inventory(task_no: str):
"""为当前任务上传正式库存文件;工作台直连既有确定性库存解析链路。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
upload = request.files.get('file')
if upload is None:
raise ValidationError('file is required')
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
def workspace_mark_manual_uploaded(task_no: str):
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
"""登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
data = request.get_json(silent=True) or {}
payload = {
'task_id': task.task_no, 'mode': 'manual_confirm', 'operator_id': user.id,
'evidence_asset_no': data.get('evidence_asset_no'), 'freight_ref_no': data.get('freight_ref_no'),
'artifact_id': data.get('artifact_id'),
}
return jsonify(shipping_tools.upload_to_freight(payload))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
def workspace_retry_shipping_upload(task_no: str):
+2
View File
@@ -497,6 +497,8 @@ class Config:
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
# 单次批量上传通知文件上限;与 EML 内附件上限独立,防止请求级资源耗尽。
SHIPPING_NOTICE_BATCH_MAX_FILES = int(os.getenv('SHIPPING_NOTICE_BATCH_MAX_FILES', '20'))
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
)
+28
View File
@@ -32,6 +32,13 @@ from app.models.shipping import (
from app.models.shipping_task_line import ShippingTaskFieldConflict
from app.models.shipping_context_provider import ShippingContextProvider, ShippingContextProviderOption
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
from app.models.shipping_fulfillment import (
ShippingExportArtifactLine,
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingReservation,
ShippingUploadAttempt,
)
from app.models.shipping_order_schema import (
ShippingOrderExtraction,
ShippingOrderSchemaAuditEvent,
@@ -44,6 +51,11 @@ from app.models.shipping_order_schema import (
ShippingOrderSchemaVersion,
)
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
from app.models.shipping_order_snapshot import (
ShippingOrderReviewEvent,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
)
from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionDiagnosticAudit,
ShippingOrderExtractionProgressEvent,
@@ -53,6 +65,11 @@ from app.models.shipping_order_extraction_run import (
ShippingOrderExtractionUnit,
)
from app.models.shipping_order_document_profile import ShippingOrderDocumentProfile
from app.models.shipping_document_profile_quality import (
ShippingDocumentProfileTestRun,
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
)
from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
from app.models.shipping_inventory_config import (
ShippingInventoryField,
@@ -144,6 +161,9 @@ __all__ = [
'ShippingOrderFieldDecision',
'ShippingOrderFieldValue',
'ShippingOrderCustomerMatch',
'ShippingOrderSnapshot',
'ShippingOrderSnapshotLine',
'ShippingOrderReviewEvent',
'ShippingOrderExtractionRun',
'ShippingOrderExtractionRunIntake',
'ShippingOrderExtractionPlan',
@@ -153,6 +173,9 @@ __all__ = [
'ShippingOrderExtractionQualityBatch',
'ShippingOrderExtractionQualityLabel',
'ShippingOrderDocumentProfile',
'ShippingDocumentProfileTestSuite',
'ShippingDocumentProfileTestSample',
'ShippingDocumentProfileTestRun',
'ShippingDocumentLayoutVersion',
'ShippingCustomer',
'ShippingCustomerIdentifier',
@@ -190,6 +213,11 @@ __all__ = [
'ShippingTemporaryInventorySession',
'ShippingExcelTemplate',
'ShippingExportArtifact',
'ShippingReservation',
'ShippingInventoryVerification',
'ShippingInventoryVerificationLine',
'ShippingExportArtifactLine',
'ShippingUploadAttempt',
'ShippingNoticeIntake',
'ShippingNoticeDocument',
'ShippingNoticeCandidate',
+18 -1
View File
@@ -8,7 +8,8 @@ backend/app/models/shipping.py
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
Document/Candidate 承载「一邮件多订单」识别;ShippingTask.source_candidate_id 记录正式建单来源;
ShippingTask.supersedes_task_id 唯一约束保证修订链线性;
order_data_version 为动态订单 FieldValue 编辑的乐观锁版本;订单事实仅保存于 Extraction。
order_data_version 为冻结前 Candidate/Extraction 纠错的乐观锁版本;
current_order_extraction_id 追溯解析事实,order_snapshot_id 指向不可变履约事实。
"""
from __future__ import annotations
@@ -18,6 +19,7 @@ from typing import List, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
Float,
ForeignKey,
@@ -180,6 +182,17 @@ class ShippingTask(Base):
nullable=True,
index=True,
)
# 阶段 1:库存、导出和上传必须通过此指针读取冻结订单快照。
order_snapshot_id: Mapped[Optional[int]] = mapped_column(
ForeignKey(
'shipping_order_snapshots.id',
name='fk_shipping_tasks_order_snapshot_id',
use_alter=True,
),
nullable=True,
unique=True,
index=True,
)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -409,6 +422,10 @@ class ShippingNoticeIntake(Base):
__tablename__ = 'shipping_notice_intakes'
__table_args__ = (
CheckConstraint(
"purpose IN ('shipping_notice', 'order_document_profile_sample')",
name='ck_shipping_notice_intakes_purpose',
),
UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'),
UniqueConstraint(
'asset_id',
@@ -0,0 +1,85 @@
"""
backend/app/models/shipping_document_profile_quality.py
用途:保存订单文档 Profile 的独立盲测集、样本期望值和不可变执行结果。
依赖:订单 Profile、订单文档、用户和 SQLAlchemy Base。
逻辑:每个 Profile 版本以冻结 checksum 绑定至少三个盲测样本;全部通过并经管理员批准后,才可用于确定性自动建单。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingDocumentProfileTestSuite(Base):
"""一个发布 Profile 版本的盲测集;批准状态是确定性自动建单的发布凭证。"""
__tablename__ = 'shipping_document_profile_test_suites'
__table_args__ = (
UniqueConstraint('profile_id', name='uq_shipping_document_profile_test_suites_profile'),
CheckConstraint("status IN ('draft', 'approved', 'superseded')", name='ck_shipping_document_profile_test_suites_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=False, index=True)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
samples: Mapped[list['ShippingDocumentProfileTestSample']] = relationship(
back_populates='suite', cascade='all, delete-orphan', order_by='ShippingDocumentProfileTestSample.id',
)
runs: Mapped[list['ShippingDocumentProfileTestRun']] = relationship(
back_populates='suite', cascade='all, delete-orphan', order_by='ShippingDocumentProfileTestRun.id',
)
class ShippingDocumentProfileTestSample(Base):
"""盲测样本文档及管理员确认的字段期望值;不与建 Profile 的样本自动复用。"""
__tablename__ = 'shipping_document_profile_test_samples'
__table_args__ = (
UniqueConstraint('suite_id', 'document_id', 'table_id', name='uq_shipping_document_profile_test_samples_source'),
)
id: Mapped[int] = mapped_column(primary_key=True)
suite_id: Mapped[int] = mapped_column(ForeignKey('shipping_document_profile_test_suites.id', ondelete='CASCADE'), nullable=False)
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
table_id: Mapped[str] = mapped_column(String(128), nullable=False)
expected_rows_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
created_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
suite: Mapped['ShippingDocumentProfileTestSuite'] = relationship(back_populates='samples')
class ShippingDocumentProfileTestRun(Base):
"""一次可审计盲测执行;只存计数和失败码,避免把订单正文复制到测试日志。"""
__tablename__ = 'shipping_document_profile_test_runs'
__table_args__ = (
CheckConstraint("status IN ('passed', 'failed')", name='ck_shipping_document_profile_test_runs_status'),
Index('ix_shipping_document_profile_test_runs_suite_created', 'suite_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
suite_id: Mapped[int] = mapped_column(ForeignKey('shipping_document_profile_test_suites.id', ondelete='CASCADE'), nullable=False)
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
passed_sample_count: Mapped[int] = mapped_column(Integer, nullable=False)
failure_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
executed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
suite: Mapped['ShippingDocumentProfileTestSuite'] = relationship(back_populates='runs')
+130
View File
@@ -0,0 +1,130 @@
"""
backend/app/models/shipping_fulfillment.py
用途:保存预约单全局注册、每轮库存核验和 Excel 对预约单的不可重叠归属。
依赖:冻结订单 Snapshot、库存文件、导出 Artifact 与 SQLAlchemy Base。
逻辑:Snapshot 行可保留历史预约号;全局 Reservation 决定当前有效行和履约状态,核验与 Artifact 行均追加保存。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingReservation(Base):
"""预约单当前履约注册表;同一预约号与内部料号在当前版本只能有一条事实。"""
__tablename__ = 'shipping_reservations'
__table_args__ = (
UniqueConstraint('reservation_id', 'part_number', name='uq_shipping_reservations_reservation_part'),
CheckConstraint(
"status IN ('pending', 'available', 'artifact_reserved', 'uploaded', 'external_change_required')",
name='ck_shipping_reservations_status',
),
Index('ix_shipping_reservations_task_status', 'task_id', 'status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
snapshot_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshot_lines.id'), nullable=False)
reservation_id: Mapped[str] = mapped_column(String(64), nullable=False)
part_number: Mapped[str] = mapped_column(String(255), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
current_artifact_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_export_artifacts.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
class ShippingInventoryVerification(Base):
"""一次任务库存核验的不可变轮次,绑定当时有效库存快照。"""
__tablename__ = 'shipping_inventory_verifications'
__table_args__ = (
CheckConstraint("status IN ('completed', 'expired', 'superseded')", name='ck_shipping_inventory_verifications_status'),
Index('ix_shipping_inventory_verifications_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed')
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingInventoryVerificationLine']] = relationship(
back_populates='verification', cascade='all, delete-orphan', order_by='ShippingInventoryVerificationLine.id',
)
class ShippingInventoryVerificationLine(Base):
"""一个预约单在一轮库存中的需求、可用数量和确定性结果。"""
__tablename__ = 'shipping_inventory_verification_lines'
__table_args__ = (
UniqueConstraint('verification_id', 'reservation_id', name='uq_shipping_inventory_verification_lines_reservation'),
CheckConstraint("status IN ('available', 'shortage', 'invalid')", name='ck_shipping_inventory_verification_lines_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
verification_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_verifications.id', ondelete='CASCADE'), nullable=False)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_reservations.id'), nullable=False)
required_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
available_qty: Mapped[Decimal] = mapped_column(Numeric(24, 8), nullable=False)
status: Mapped[str] = mapped_column(String(16), nullable=False)
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
verification: Mapped['ShippingInventoryVerification'] = relationship(back_populates='lines')
class ShippingExportArtifactLine(Base):
"""将本轮 Excel 与预约单一对一绑定,防止同一预约单进入两个有效 Artifact。"""
__tablename__ = 'shipping_export_artifact_lines'
__table_args__ = (
UniqueConstraint('artifact_id', 'reservation_id', name='uq_shipping_export_artifact_lines_artifact_reservation'),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_id: Mapped[int] = mapped_column(ForeignKey('shipping_export_artifacts.id', ondelete='CASCADE'), nullable=False)
reservation_id: Mapped[int] = mapped_column(ForeignKey('shipping_reservations.id'), nullable=False)
verification_line_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_verification_lines.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class ShippingUploadAttempt(Base):
"""一次 Artifact 上传尝试;回调幂等键和人工回执均在此处归档。"""
__tablename__ = 'shipping_upload_attempts'
__table_args__ = (
UniqueConstraint('artifact_id', 'attempt_no', name='uq_shipping_upload_attempts_artifact_attempt'),
UniqueConstraint('idempotency_key', name='uq_shipping_upload_attempts_idempotency'),
UniqueConstraint('callback_id', name='uq_shipping_upload_attempts_callback'),
CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_upload_attempts_mode'),
CheckConstraint("status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out')", name='ck_shipping_upload_attempts_status'),
Index('ix_shipping_upload_attempts_artifact_created', 'artifact_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
artifact_id: Mapped[int] = mapped_column(ForeignKey('shipping_export_artifacts.id'), nullable=False)
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
mode: Mapped[str] = mapped_column(String(16), nullable=False)
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
callback_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending')
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -3,7 +3,7 @@ backend/app/models/shipping_order_customer_match.py
用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。
依赖:ShippingOrderExtraction、ShippingCustomer、users。
逻辑:动态订单字段保留原文客户名称;本表按角色保存候选、确认客户及名称/简称快照,供复核和导出读取。
逻辑:动态订单字段保留原文客户名称;本表按角色保存规则版本化身份指纹、候选、确认客户及名称/简称快照,供冻结和导出读取。
"""
from __future__ import annotations
@@ -40,6 +40,9 @@ class ShippingOrderCustomerMatch(Base):
normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
identity_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
identity_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
identity_components_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched')
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True)
@@ -47,6 +50,7 @@ class ShippingOrderCustomerMatch(Base):
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
confirmation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
@@ -0,0 +1,121 @@
"""
backend/app/models/shipping_order_snapshot.py
用途:保存从订单解析候选冻结而来的不可变履约订单快照及人工复核审计。
依赖:shipping_order_schema 的 Extraction、shipping_tasks、shipping_customers 与 users。
逻辑:order_freeze_service 将已接受 Extraction 的字段按稳定 field_id 冻结为 Snapshot;库存、导出和上传阶段只消费本模块的快照。
"""
from __future__ import annotations
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from sqlalchemy import CheckConstraint, Date, DateTime, ForeignKey, Index, Integer, JSON, Numeric, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.models.base import Base
class ShippingOrderSnapshot(Base):
"""不可变的订单单头履约事实;一个已接受 Extraction 最多冻结一次。"""
__tablename__ = 'shipping_order_snapshots'
__table_args__ = (
UniqueConstraint('extraction_id', name='uq_shipping_order_snapshots_extraction'),
Index('ix_shipping_order_snapshots_customer_created', 'customer_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False, index=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False)
rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
# 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
po_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
bill_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
bill_to_address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
ship_to_customer: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
ship_to_address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
destination: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
currency: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
incoterm: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
required_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
order_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
payment_term: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
frozen_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
frozen_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
lines: Mapped[list['ShippingOrderSnapshotLine']] = relationship(
back_populates='snapshot', cascade='all, delete-orphan', order_by='ShippingOrderSnapshotLine.position',
)
review_events: Mapped[list['ShippingOrderReviewEvent']] = relationship(
back_populates='snapshot', cascade='all, delete-orphan', order_by='ShippingOrderReviewEvent.created_at',
)
schema_version = relationship('ShippingOrderSchemaVersion')
class ShippingOrderSnapshotLine(Base):
"""不可变订单单身履约事实;料号和预约单始终保存为字符串以保留前导零。"""
__tablename__ = 'shipping_order_snapshot_lines'
__table_args__ = (
UniqueConstraint('snapshot_id', 'position', name='uq_shipping_order_snapshot_lines_position'),
CheckConstraint('qty IS NULL OR qty > 0', name='ck_shipping_order_snapshot_lines_positive_qty'),
)
id: Mapped[int] = mapped_column(primary_key=True)
snapshot_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False)
line_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
customer_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
aws_part_number: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
qty: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
uom: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
unit_price: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
amount: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
warehouse: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
inventory_source_hint: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 与 Header 同理:以 field_id 为键,避免后续字段重命名改变已冻结履约事实。
field_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
snapshot: Mapped['ShippingOrderSnapshot'] = relationship(back_populates='lines')
class ShippingOrderReviewEvent(Base):
"""冻结前人工纠错的追加式审计;每项变更必须保留原值、新值、证据和原因。"""
__tablename__ = 'shipping_order_review_events'
__table_args__ = (
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_review_events_scope'),
Index('ix_shipping_order_review_events_task_created', 'task_id', 'created_at'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_snapshots.id', ondelete='CASCADE'), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False)
line_position: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
old_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
new_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
evidence_ref: Mapped[str] = mapped_column(String(512), nullable=False)
reason: Mapped[str] = mapped_column(Text, nullable=False)
reviewed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
snapshot: Mapped[Optional['ShippingOrderSnapshot']] = relationship(back_populates='review_events')
@@ -10,6 +10,7 @@ from __future__ import annotations
from typing import Any
from flask import current_app
from sqlalchemy.exc import IntegrityError
from app.services.shipping_notice import tools as shipping_tools
@@ -185,6 +186,15 @@ def intake_notice_uploads_for_batch(
Returns:
(notice_items, file_summary)
"""
max_files = max(int(current_app.config.get('SHIPPING_NOTICE_BATCH_MAX_FILES', 20) or 20), 1)
if len(uploads) > max_files:
from app.core.errors import ValidationError
raise ValidationError(
'批量上传文件数超过限制',
code='SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED',
details={'max_files': max_files, 'received_files': len(uploads)},
)
from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads
accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads)
@@ -260,6 +260,42 @@ class ShippingGenerateExcelAction:
yield TurnEvent(event="step.completed", data={"step_id": "generate_excel"})
class ShippingFreezeOrderAction:
"""冻结已复核订单,使后续履约只读取不可变 Snapshot。
AI 触发时机:订单字段和订购客户已在对话中确认、界面显示“冻结订单”时调用。
必须携带用户看到订单时的 expected_order_data_version;版本变化由乐观锁拒绝,要求刷新后重试。
"""
action_type = "shipping.freeze_order"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
try:
expected_version = int(payload.get("expected_order_data_version"))
except (TypeError, ValueError) as exc:
raise ValidationError("expected_order_data_version is required") from exc
yield TurnEvent(event="step.started", data={"step_id": "freeze_order", "label": "冻结订单..."})
from app import db
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
snapshot = freeze_order_snapshot(
task,
actor_id=int(ctx.user_id),
expected_order_data_version=expected_version,
)
db.session.commit()
refreshed = get_task_by_ref(task.task_no) or task
yield _shipping_ui_state_event(refreshed)
yield from _stream_text_events(
f"订单已冻结为履约快照 #{snapshot.id}。接下来可以继续库存处理。\n\n任务编号:{task.task_no}",
message_type="text",
payload={"task_no": task.task_no, "snapshot_id": snapshot.id},
)
yield TurnEvent(event="step.completed", data={"step_id": "freeze_order"})
class ShippingRetryUploadAction:
action_type = "shipping.retry_upload"
@@ -334,15 +370,29 @@ class ShippingConfirmInventorySourceAction:
class ShippingMarkManualUploadedAction:
"""以 Chat 中上传的截图或回执确认人工货代上传。
AI 触发时机:用户明确已在货代系统上传并已通过 Chat 选择回执文件时调用。
payload 必须含 evidence_asset_no;操作者只从当前 Chat 用户上下文取得,不能由客户端伪造。
"""
action_type = "shipping.mark_manual_uploaded"
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
evidence_asset_no = str(payload.get("evidence_asset_no") or "").strip()
if not evidence_asset_no:
raise ValidationError("evidence_asset_no is required", code="SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED")
yield TurnEvent(event="step.started", data={"step_id": "mark_manual_uploaded", "label": "确认手工上传..."})
result = shipping_tools.upload_to_freight({
"task_id": task.task_no,
"mode": "manual_confirm",
"event_source": "chat_turn",
"operator_id": int(ctx.user_id),
"evidence_asset_no": evidence_asset_no,
"artifact_id": payload.get("artifact_id"),
"freight_ref_no": str(payload.get("freight_ref_no") or "").strip(),
})
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "mark_manual_uploaded failed")
@@ -364,6 +414,7 @@ _HANDLERS = (
ShippingCreateBatchFromNoticesAction(),
ShippingCreateBatchFromIntakesAction(),
ShippingSubmitDecisionAction(),
ShippingFreezeOrderAction(),
ShippingGenerateExcelAction(),
ShippingRetryUploadAction(),
ShippingMatchInventoryAction(),
@@ -28,6 +28,7 @@ CP_READY_EXPORT = "ready_to_export"
CP_EXPORT_READY = "export_ready"
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
CP_ORDER_FREEZE = "order_freeze"
CP_EXPORT_GENERATED = "export_generated"
CP_UPLOADED = "uploaded"
CP_COMPLETED = "completed"
@@ -0,0 +1,202 @@
"""
从 PDF 原生字符坐标重建被 HTML 网格错误拆分的订单表格候选。
依赖:布局 bbox 契约和 PositionedCharacter。调用方必须先提供已人工确认的列锚点;本模块
只按几何、有限内容形态和相邻行连续性生成可审计的 needs_review 候选,绝不自动接受。
"""
from __future__ import annotations
import re
from statistics import median
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
_LINE_NUMBER_PATTERN = re.compile(r'^0{2,}\d+$')
_DELETED_PATTERN = re.compile(r'^\*+\s*item\s+deleted\s*\*+$', re.IGNORECASE)
class CoordinateReconstructionModel(BaseModel):
"""为坐标重建的中间证据启用严格契约,禁止调用方注入未定义字段。"""
model_config = ConfigDict(extra='forbid')
class CoordinateColumnAnchor(CoordinateReconstructionModel):
"""人工确认表头后冻结的列几何区间;不从错误的 HTML 表头自行猜测。"""
column_index: int = Field(ge=0)
bbox: LayoutBBox
class ReconstructedCell(CoordinateReconstructionModel):
"""一段按 x 归属的原生文本及其证据 glyph 索引。"""
column_index: int = Field(ge=0)
text: str = Field(min_length=1)
bbox: LayoutBBox
glyph_indices: list[int] = Field(min_length=1)
class ReconstructedRow(CoordinateReconstructionModel):
"""一个 y-band 形成的视觉行;删除标记只能附着在前一强锚定行。"""
row_index: int = Field(ge=0)
role: Literal['data', 'continuation', 'deleted', 'needs_review']
cells: list[ReconstructedCell] = Field(min_length=1)
@model_validator(mode='after')
def validate_columns(self) -> 'ReconstructedRow':
"""确保同一视觉行中的列按几何顺序且无重复,方便人工复核。"""
columns = [cell.column_index for cell in self.cells]
if columns != sorted(columns) or len(columns) != len(set(columns)):
raise ValueError('reconstructed row columns must be unique and ascending')
return self
class CoordinateTableReconstruction(CoordinateReconstructionModel):
"""坐标重建输出,固定为 needs_review 并给出不含文档原文的诊断码。"""
status: Literal['needs_review'] = 'needs_review'
rows: list[ReconstructedRow] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
def reconstruct_table_from_positioned_text(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox,
column_anchors: list[CoordinateColumnAnchor | dict[str, Any]],
) -> CoordinateTableReconstruction:
"""
以 x 列锚点、y 视觉行和内容/邻接辅助规则重建保守候选。
AI/调用方触发时机:仅当 MinerU 网格已确认行列关系错误、且 PDF 原生 glyph 坐标和
人工确认列锚点均存在时调用。没有锚点、越界 glyph、列归属并列或删除行无前序明细时,
必须保留 needs_review,不能用本函数替代人工确认。
Args:
characters: 表格范围内外的 PDF 原生字符及 source_index。
table_bbox: 当前表格的真实页面范围。
column_anchors: 从可信表头得到的列区间,至少两列且不可重叠。
Returns:
带 glyph 索引的视觉行候选;status 始终为 needs_review。
"""
anchors = _validated_anchors(column_anchors)
glyphs = _table_glyphs(characters, table_bbox)
if not glyphs:
return CoordinateTableReconstruction(issues=['coordinate_reconstruction_text_missing'])
issues: set[str] = set()
rows: list[ReconstructedRow] = []
previous_has_line_number = False
for row_index, band in enumerate(_group_visual_rows(glyphs)):
cells: dict[int, list[tuple[int, PositionedCharacter]]] = {}
for glyph_index, glyph in band:
column = _assign_column(glyph.bbox, anchors)
if column is None:
issues.add('coordinate_reconstruction_column_ambiguous')
continue
cells.setdefault(column, []).append((glyph_index, glyph))
if not cells:
continue
rebuilt = [
_cell_from_glyphs(column, value)
for column, value in sorted(cells.items())
]
text = ' '.join(cell.text for cell in rebuilt)
has_line_number = any(_LINE_NUMBER_PATTERN.fullmatch(cell.text.replace(' ', '')) for cell in rebuilt)
if _DELETED_PATTERN.fullmatch(text.strip()):
role: Literal['data', 'continuation', 'deleted', 'needs_review'] = (
'deleted' if previous_has_line_number else 'needs_review'
)
if role == 'needs_review':
issues.add('coordinate_reconstruction_deleted_row_unattached')
elif has_line_number:
role = 'data'
else:
role = 'continuation' if previous_has_line_number else 'needs_review'
if role == 'needs_review':
issues.add('coordinate_reconstruction_row_unanchored')
rows.append(ReconstructedRow(row_index=row_index, role=role, cells=rebuilt))
previous_has_line_number = has_line_number or (role == 'continuation' and previous_has_line_number)
if not rows:
issues.add('coordinate_reconstruction_rows_missing')
return CoordinateTableReconstruction(rows=rows, issues=sorted(issues))
def _validated_anchors(raw: list[CoordinateColumnAnchor | dict[str, Any]]) -> list[CoordinateColumnAnchor]:
"""校验列锚点数量、排序与不重叠,防止错误表头诱导列归属。"""
anchors = sorted(
[item if isinstance(item, CoordinateColumnAnchor) else CoordinateColumnAnchor.model_validate(item) for item in raw],
key=lambda item: item.column_index,
)
if len(anchors) < 2 or [item.column_index for item in anchors] != list(range(len(anchors))):
raise ValueError('coordinate reconstruction requires contiguous column anchors')
if any(right.bbox.x0 < left.bbox.x1 for left, right in zip(anchors, anchors[1:])):
raise ValueError('coordinate reconstruction column anchors must not overlap')
return anchors
def _table_glyphs(
raw: list[PositionedCharacter | dict[str, Any]], table_bbox: LayoutBBox,
) -> list[tuple[int, PositionedCharacter]]:
"""只保留中心落在表格内的有效 glyph,并以 y/x/source 顺序稳定排序。"""
glyphs: list[tuple[int, PositionedCharacter]] = []
for index, item in enumerate(raw):
glyph = item if isinstance(item, PositionedCharacter) else PositionedCharacter.model_validate(item)
center_x = (glyph.bbox.x0 + glyph.bbox.x1) / 2
center_y = (glyph.bbox.y0 + glyph.bbox.y1) / 2
if table_bbox.x0 <= center_x <= table_bbox.x1 and table_bbox.y0 <= center_y <= table_bbox.y1:
glyphs.append((glyph.source_index if glyph.source_index is not None else index, glyph))
return sorted(glyphs, key=lambda item: ((item[1].bbox.y0 + item[1].bbox.y1) / 2, item[1].bbox.x0, item[0]))
def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[list[tuple[int, PositionedCharacter]]]:
"""按自适应 y 阈值形成视觉行,阈值来自字体高度而不是固定页面像素。"""
heights = [glyph.bbox.y1 - glyph.bbox.y0 for _, glyph in glyphs]
tolerance = max(2.0, median(heights) * 0.75)
bands: list[list[tuple[int, PositionedCharacter]]] = []
centers: list[float] = []
for item in glyphs:
center = (item[1].bbox.y0 + item[1].bbox.y1) / 2
if bands and abs(center - centers[-1]) <= tolerance:
bands[-1].append(item)
centers[-1] = sum((glyph.bbox.y0 + glyph.bbox.y1) / 2 for _, glyph in bands[-1]) / len(bands[-1])
else:
bands.append([item])
centers.append(center)
return bands
def _assign_column(bbox: LayoutBBox, anchors: list[CoordinateColumnAnchor]) -> int | None:
"""优先最大 x-overlap,只有唯一最佳候选才允许归属;中心距离仅作无重叠时的后备。"""
overlaps = [max(0.0, min(bbox.x1, item.bbox.x1) - max(bbox.x0, item.bbox.x0)) for item in anchors]
best_overlap = max(overlaps)
if best_overlap > 0 and overlaps.count(best_overlap) == 1:
return anchors[overlaps.index(best_overlap)].column_index
center = (bbox.x0 + bbox.x1) / 2
distances = [abs(center - (item.bbox.x0 + item.bbox.x1) / 2) for item in anchors]
nearest = min(distances)
return anchors[distances.index(nearest)].column_index if distances.count(nearest) == 1 else None
def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell:
"""合并同一视觉行、同一列的 glyph,保留按页面位置排序的证据索引。"""
ordered = sorted(glyphs, key=lambda item: item[1].bbox.x0)
boxes = [item.bbox for _, item in ordered]
return ReconstructedCell(
column_index=column_index,
text=''.join(item.text for _, item in ordered).strip(),
bbox=LayoutBBox(
x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes),
x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes),
),
glyph_indices=[index for index, _ in ordered],
)
@@ -32,6 +32,10 @@ from app.services.shipping_notice.order_schema.table_contract import (
ORDER_PROFILE_VERSION = 'shipping_order_document_profile.v1'
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts'})
HEADER_LINE_ITEM_VALUE_PATTERN = re.compile(
r'\b(?:item|line)\s*(?:no\.?|number|#)?\s*[:#-]?\s*0{2,}\d+\b',
re.IGNORECASE,
)
class OrderProfileModel(BaseModel):
@@ -112,6 +116,27 @@ class OrderProfileParseResult(OrderProfileModel):
issues: list[str] = Field(default_factory=list)
def diagnose_order_profile_header(grid: HtmlGrid, *, header_row_index: int) -> list[str]:
"""
诊断管理员所选表头是否已经混入明显的订单明细值。
只有在表头 cell 同时出现 Item/Line 标签和零填充行号时才判定污染;普通的
``Item No`` 表头不会触发。该诊断是建 Profile 前的硬门禁,避免把错误网格固化。
Args:
grid: 已展开的 MinerU HTML 网格。
header_row_index: 管理员选择的最后一行表头索引。
Returns:
稳定、无原文的诊断码列表,供预览和服务端阻断共用。
"""
if header_row_index < 0 or header_row_index >= grid.row_count:
raise ValueError('order profile header row index is invalid')
header_slots = (slot for row in grid.rows[:header_row_index + 1] for slot in row if slot)
if any(HEADER_LINE_ITEM_VALUE_PATTERN.search(slot.text or '') for slot in header_slots):
return ['order_profile_header_contaminated_by_data']
return []
def order_profile_structure_fingerprint(
grid: HtmlGrid, *, header_row_index: int,
) -> str:
@@ -0,0 +1,172 @@
"""
services/shipping_notice/document_profile_quality_service.py
用途:治理订单文档 Profile 的盲测样本、执行结果和确定性自动建单资格。
依赖:Profile 服务、MinerU 当前布局快照、Profile 纯解析器与质量 ORM 模型。
逻辑:管理员先固化独立样本的期望行,服务按冻结 Profile 执行比对;至少三份样本全部通过并批准后才放行自动建单。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingDocumentProfileTestRun,
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
ShippingNoticeDocument,
ShippingOrderDocumentProfile,
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
from app.services.shipping_notice.document_layout.order_profile import parse_html_table_with_order_profile
from app.services.shipping_notice.order_document_profile_service import _definition_contract
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
MINIMUM_BLIND_SAMPLES = 3
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
"""读取已发布 Profile;草稿和退役版本不能获得自动建单质量凭证。"""
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
if profile.status != 'published' or not profile.checksum:
raise ConflictError('Only published order document profile can be tested', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
return profile
def _table_html(document_id: int, table_id: str) -> str:
"""读取 ready 布局中指定表格,不接受浏览器传入 HTML 或可变正文。"""
document = db.session.get(ShippingNoticeDocument, int(document_id))
if document is None:
raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
layout = current_layout_snapshot(document) or {}
for table in layout.get('tables') or []:
if isinstance(table, dict) and str(table.get('table_id') or '') == str(table_id):
html = str(table.get('html') or '')
if html.strip():
return html
raise ValidationError('Test sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
def _expected_rows(raw: Any) -> list[dict[str, Any]]:
"""校验人工录入的盲测真值,只接受行字段字典且不允许空集合。"""
if not isinstance(raw, list) or not raw or any(not isinstance(item, dict) or not item for item in raw):
raise ValidationError('expected_rows must be a non-empty list of field maps', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
return [dict(item) for item in raw]
def create_suite(*, profile_id: int, actor_id: int) -> dict[str, Any]:
"""为一个发布 Profile 建立唯一盲测集;旧批准凭证不会被覆盖。"""
profile = _profile(profile_id)
existing = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first()
if existing is not None:
return serialize_suite(existing)
suite = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=profile.checksum, created_by_id=actor_id,
)
db.session.add(suite)
db.session.commit()
return serialize_suite(suite)
def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows: Any, actor_id: int) -> dict[str, Any]:
"""增加独立盲测样本;批准后禁止继续更改真值。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None:
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
if suite.status != 'draft':
raise ConflictError('Approved test suite is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE')
_table_html(document_id, table_id)
sample = ShippingDocumentProfileTestSample(
suite_id=suite.id, document_id=int(document_id), table_id=str(table_id),
expected_rows_json=_expected_rows(expected_rows), created_by_id=actor_id,
)
db.session.add(sample)
try:
db.session.commit()
except Exception as exc:
db.session.rollback()
raise ConflictError('Test sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_CONFLICT') from exc
return serialize_suite(suite)
def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
"""在当前已发布 Profile 上执行全部盲测;任何差异都不得放行自动建单。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None:
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
profile = _profile(suite.profile_id)
if suite.profile_checksum != profile.checksum:
raise ConflictError('Profile changed after test suite creation', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_STALE')
contract = compile_table_header_contract(profile.schema_version.definition_json or {})
parser = _definition_contract(profile)
failures: list[str] = []
passed = 0
for sample in suite.samples:
parsed = parse_html_table_with_order_profile(
_table_html(sample.document_id, sample.table_id), table_id=sample.table_id,
profile=parser, contract=contract,
)
actual = [dict(row.fields) for row in parsed.rows if row.status == 'parsed']
if parsed.matched and not parsed.issues and actual == list(sample.expected_rows_json or []):
passed += 1
else:
failures.append(f'sample:{sample.id}:mismatch')
sample_count = len(suite.samples)
run = ShippingDocumentProfileTestRun(
suite_id=suite.id, profile_checksum=profile.checksum,
status='passed' if sample_count >= MINIMUM_BLIND_SAMPLES and passed == sample_count else 'failed',
sample_count=sample_count, passed_sample_count=passed, failure_codes_json=failures,
executed_by_id=actor_id,
)
db.session.add(run)
db.session.commit()
return serialize_suite(suite)
def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
"""批准最近一次合格盲测,形成绑定 Profile checksum 的不可变自动建单凭证。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None:
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
profile = _profile(suite.profile_id)
last_run = suite.runs[-1] if suite.runs else None
if (
suite.status != 'draft' or suite.profile_checksum != profile.checksum or last_run is None
or last_run.status != 'passed' or last_run.profile_checksum != profile.checksum
):
raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY')
suite.status = 'approved'
suite.approved_by_id = actor_id
suite.approved_at = datetime.utcnow()
db.session.commit()
return serialize_suite(suite)
def profile_is_auto_create_approved(*, profile_id: int, checksum: str) -> bool:
"""为 Run 冻结快照判断模板是否有当前 checksum 的已批准盲测凭证。"""
suite = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=int(profile_id), profile_checksum=str(checksum), status='approved',
).first()
return suite is not None
def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
"""返回不含订单正文的盲测治理摘要,供管理端确认发布状态。"""
latest = suite.runs[-1] if suite.runs else None
return {
'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum,
'status': suite.status, 'sample_count': len(suite.samples),
'approved_at': suite.approved_at.isoformat() if suite.approved_at else None,
'latest_run': None if latest is None else {
'status': latest.status, 'sample_count': latest.sample_count,
'passed_sample_count': latest.passed_sample_count,
'failure_codes': list(latest.failure_codes_json or []),
},
}
@@ -269,17 +269,19 @@ def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]:
definition = item.definition_json if isinstance(item.definition_json, dict) else {}
mappings = definition.get('mappings')
filename_pattern = str(definition.get('filename_pattern') or '').strip()
if not isinstance(mappings, list) or not mappings or not filename_pattern:
raise ValidationError('Template mappings and filename_pattern are required', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
try:
rendered_name = filename_pattern.format(
task_no='TASK', business_no='BUSINESS', source_code='SOURCE', ts='20260101000000', date='20260101',
customer_short_code='CUSTOMER', business_date='260602', sequence='01',
)
except (KeyError, ValueError) as exc:
raise ValidationError('Template filename_pattern is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc
if not rendered_name.strip():
raise ValidationError('Template filename_pattern is empty', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
if not isinstance(mappings, list) or not mappings:
raise ValidationError('Template mappings are required', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
# An empty published rule deliberately delegates naming to the controlled environment fallback.
if filename_pattern:
try:
rendered_name = filename_pattern.format(
task_no='TASK', business_no='BUSINESS', source_code='SOURCE', ts='20260101000000', date='20260101',
customer_short_code='CUSTOMER', business_date='260602', sequence='01',
)
except (KeyError, ValueError) as exc:
raise ValidationError('Template filename_pattern is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc
if not rendered_name.strip():
raise ValidationError('Template filename_pattern is empty', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
raw = file_asset_storage.get_bytes(item.storage_key)
if hashlib.sha256(raw).hexdigest() != item.file_checksum:
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
+46 -60
View File
@@ -2,8 +2,8 @@
services/shipping_notice/export.py
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、动态订单 FieldValue、库存快照与 openpyxl。
逻辑:锁定 Source、模板、订单 Schema/Extraction、库存解析 Profile 和库存快照,按白名单映射写入模板。
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板。
"""
from __future__ import annotations
@@ -19,16 +19,13 @@ from zoneinfo import ZoneInfo
from flask import current_app
from openpyxl import load_workbook
from sqlalchemy import update
from app import db
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderExtraction,
ShippingOrderFieldValue,
ShippingOrderSnapshot,
ShippingTask,
)
from app.path_utils import resolve_backend_relative_path
@@ -43,40 +40,18 @@ def _storage_root() -> Path:
return Path(current_app.instance_path) / 'shipping_notice'
def _typed_value(item: ShippingOrderFieldValue) -> Any:
"""从类型化投影读取唯一业务值,禁止回退旧任务固定列。"""
for value in (
item.value_text, item.value_decimal, item.value_integer,
item.value_date, item.value_boolean, item.value_json,
):
if value is not None:
return value
return None
def _order_values(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""将稳定 field_id 投影为 Header 字典及按订单行 position 排序的字典列表。"""
header: dict[str, Any] = {}
line_positions = {line.id: line.position for line in extraction.lines}
lines: dict[int, dict[str, Any]] = {position: {} for position in line_positions.values()}
for item in extraction.values:
value = _typed_value(item)
if item.line_id is None:
header[item.field_id] = value
elif item.line_id in line_positions:
lines[line_positions[item.line_id]][item.field_id] = value
return header, [lines[position] for position in sorted(lines)]
def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""读取任务当前已接受订单解析,并按稳定字段 ID 返回 Header 与明细值。"""
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
)
if extraction is None or extraction.status != 'accepted':
raise ValueError('任务没有可用于库存匹配的订单解析版本')
return _order_values(extraction)
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于库存匹配的冻结订单快照')
fields = (snapshot.schema_version.definition_json or {}).get('fields') or []
header = dict(snapshot.header_values_json or {})
lines = [
dict(line.field_values_json or {})
for line in snapshot.lines
]
return header, lines
def _system_fact(task: ShippingTask, key: str) -> Any:
@@ -241,9 +216,13 @@ def _safe_filename(name: str) -> str:
def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str:
"""按发布规则生成下载名,业务单变量始终取已锁定的客户与编号快照。"""
pattern = str((template.definition_json or {}).get('filename_pattern') or '')
now = datetime.utcnow().strftime('%Y%m%d%H%M%S')
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
if not pattern:
pattern = str(current_app.config.get('SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN') or '').strip()
if not pattern:
raise ValueError('发货 Excel 文件名规则未配置')
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
shipping_case = task.shipping_case
values = {
'task_no': task.task_no,
@@ -263,13 +242,13 @@ def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str:
def _input_checksum(
task: ShippingTask, source: ShippingInventorySource, template: ShippingExcelTemplate,
extraction: ShippingOrderExtraction, header: dict[str, Any], lines: list[dict[str, Any]],
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
) -> str:
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
payload = {
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': extraction.schema_version_id, 'extraction_id': extraction.id,
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [],
}
@@ -301,13 +280,25 @@ def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExpor
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
if source.parsing_profile is None or source.parsing_profile.status != 'published':
raise ValueError('库存源未绑定已发布的库存解析模板')
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
active_artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
).first()
if active_artifact is not None:
raise ValueError('当前任务存在待上传的发货 Excel,必须先完成或授权作废该 Artifact')
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
reserve_available_for_artifact,
)
if extraction is None or extraction.status != 'accepted':
raise ValueError('任务没有可用于导出的订单解析版本')
header_values, line_values = _order_values(extraction)
verification, available_line_ids = current_available_snapshot_line_ids(task)
line_values = [
values for line, values in zip(snapshot.lines, all_line_values, strict=True)
if line.id in available_line_ids
]
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
definition = template.definition_json or {}
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
@@ -358,24 +349,19 @@ def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExpor
wb.close()
content = path.read_bytes()
db.session.execute(
update(ShippingExportArtifact)
.where(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status == 'ready',
)
.values(status='superseded')
)
# 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是
# 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=task.id, batch_id=task.batch_id, template_id=template.id,
order_schema_version_id=extraction.schema_version_id, order_extraction_id=extraction.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
input_checksum=_input_checksum(task, source, template, extraction, header_values, line_values),
input_checksum=_input_checksum(task, source, template, snapshot, header_values, line_values),
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
)
db.session.add(artifact)
db.session.flush()
reserve_available_for_artifact(task, artifact=artifact, verification=verification)
return str(path), filename, artifact
except Exception:
if path.is_file():
@@ -3,7 +3,7 @@ services/shipping_notice/export_archive.py
用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。
逻辑:只选每票最新 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。
逻辑:选择每票全部 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。
"""
from __future__ import annotations
@@ -53,16 +53,15 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N
return tasks, archive_key
def _latest_ready_artifacts(tasks: list[ShippingTask]) -> dict[int, ShippingExportArtifact]:
"""批量查询每票最新 ready Artifact,避免 N+1。"""
def _ready_artifacts(tasks: list[ShippingTask]) -> dict[int, list[ShippingExportArtifact]]:
"""批量查询每票全部可下载 Artifact,滚动履约不得遗漏前一轮 Excel。"""
task_ids = [int(task.id) for task in tasks if task.id is not None]
rows = ShippingExportArtifact.query.join(ShippingTask, ShippingTask.id == ShippingExportArtifact.task_id).filter(
ShippingExportArtifact.task_id.in_(task_ids), ShippingExportArtifact.status == 'ready',
ShippingTask.export_file_path == ShippingExportArtifact.file_path,
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).all()
result: dict[int, ShippingExportArtifact] = {}
).order_by(ShippingExportArtifact.created_at, ShippingExportArtifact.id).all()
result: dict[int, list[ShippingExportArtifact]] = {}
for item in rows:
result.setdefault(int(item.task_id), item)
result.setdefault(int(item.task_id), []).append(item)
return result
@@ -93,7 +92,7 @@ def build_export_archive(
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
"""
tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos)
artifacts = _latest_ready_artifacts(tasks)
artifacts = _ready_artifacts(tasks)
# 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。
stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b')
used_names: set[str] = {'manifest.json'}
@@ -101,9 +100,11 @@ def build_export_archive(
included = 0
with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive:
for task in tasks:
artifact = artifacts.get(int(task.id)) if task.id is not None else None
entry = {'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None}
if artifact is not None:
task_artifacts = artifacts.get(int(task.id), []) if task.id is not None else []
if not task_artifacts:
entries.append({'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
for artifact in task_artifacts:
entry = {'task_no': task.task_no, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
entry['artifact_no'] = artifact.artifact_no
path = Path(artifact.file_path)
if not path.is_file():
@@ -117,11 +118,11 @@ def build_export_archive(
archive.writestr(name, content)
entry.update({'status': 'included', 'file_name': name, 'file_checksum': artifact.file_checksum})
included += 1
entries.append(entry)
entries.append(entry)
manifest = {
'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []},
'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks),
'included_count': included, 'excluded_count': len(tasks) - included, 'entries': entries,
'included_count': included, 'excluded_count': len(entries) - included, 'entries': entries,
}
archive.writestr('manifest.json', json.dumps(manifest, ensure_ascii=False, indent=2).encode('utf-8'))
stream.seek(0)
@@ -17,6 +17,7 @@ from typing import Any
from flask import current_app
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
@@ -36,6 +37,12 @@ from app.services.shipping_notice.order_field_purposes import task_line_purpose_
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
from app.services.shipping_notice.rpa import write_upload_trigger
from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
current_upload_artifact,
record_manual_upload,
start_rpa_attempt,
)
from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts,
upload_rpa_attempts,
@@ -155,11 +162,11 @@ def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] |
def match_completed(task: ShippingTask) -> bool:
"""判断任务是否已完成可履约的库存匹配(fulfillable 且 line_results 非空)。"""
"""滚动履约只要求至少一个预约单完整满足,partial 也可进入本轮制单。"""
return bool(
task.match_status == "fulfillable"
task.match_status in {"fulfillable", "partial"}
and isinstance(task.line_results_json, list)
and len(task.line_results_json) > 0
and any(str(item.get('line_status') or '') == 'ok' for item in task.line_results_json if isinstance(item, dict))
)
@@ -358,8 +365,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
stop_agent_turn=True,
)
# [STEP 3] 执行匹配并按结果分流。
# fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。
# [STEP 3] 执行匹配并按结果分流;partial 有完整满足预约单时也可滚动制单。
def _on_match_progress(processed: int, total: int) -> None:
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
set_task_step_progress(
@@ -402,18 +408,23 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task.match_status = match_status
task.line_results_json = line_results
task.shortage_json = shortage
from app.services.shipping_notice.reservation_service import record_inventory_verification
verification = record_inventory_verification(
task, inventory_snapshot_id=task.inventory_snapshot_id,
source_config_version=task.inventory_source_config_version, line_results=line_results,
)
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="needs_human" if match_status != "fulfillable" else "completed",
status="needs_human" if match_status == "unfulfillable" else "completed",
message=t("workflow.fulfillment.match_completed", lang=lang),
progress_percent=100,
current=len(line_results),
total=len(line_results),
detail=(
t("workflow.fulfillment.match_completed_ok_detail", lang=lang).format(count=len(line_results))
if match_status == "fulfillable"
if match_status in {"fulfillable", "partial"}
else t("workflow.fulfillment.match_completed_shortage_detail", lang=lang).format(count=len(line_results))
),
)
@@ -424,9 +435,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
lang=lang,
)
if match_status == "fulfillable":
if match_status in {"fulfillable", "partial"} and match_completed(task):
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
log_task_event(task, "matched_fulfillable", {"match_status": match_status})
log_task_event(task, "matched_rolling_available", {"match_status": match_status, "verification_id": verification.id})
db.session.commit()
match_result = tool_response(
status="ok",
@@ -464,7 +475,7 @@ def _commit_generated_export(path: str) -> None:
def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
"""
基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。
【AI 触发时机】:match_inventory 返回 fulfillable 且用户需下载/上传 Excel 时调用;未匹配前禁止调用。
【AI 触发时机】:本轮至少一个预约单完整满足且用户确认制单时调用;未匹配前禁止调用。
核心逻辑:已有导出文件时直接返回成功;否则走 excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。
@@ -514,17 +525,24 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
forbidden_next_tools=["upload_to_freight"],
)
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
# [STEP 1] 已有旧 Artifact 不等于本轮没有可导出预约单;库存刷新后
# 仍须允许缺货项生成下一轮 Excel。仅当最新核验没有未占用的可用预约单时复用下载结果。
if task.export_file_path and not task_export_error_message(task):
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.fulfillment.excel_exists", lang=lang).format(
file=task.export_file_name or task.export_file_path
),
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
)
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
try:
_verification, available_line_ids = current_available_snapshot_line_ids(task)
except ConflictError:
available_line_ids = set()
if not available_line_ids:
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.fulfillment.excel_exists", lang=lang).format(
file=task.export_file_name or task.export_file_path
),
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
)
# [STEP 2] 先校验是否满足导出门禁。
# 只有库存匹配完成后才允许生成货代 Excel;但 waiting_upload/uploaded 仍应视为“已完成匹配”。
@@ -552,7 +570,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
# 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。
try:
path, filename, artifact = generate_shipment_excel(task)
except ValueError as exc:
except (ConflictError, ValueError) as exc:
return tool_response(
status="failed",
task=task,
@@ -627,47 +645,31 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
# [STEP 1] 先确保上传所需的 Excel 已经存在。
# 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。
# [STEP 1] 先确保至少有一份 Artifact;后续上传始终由 Artifact 而非 Task 文件指针驱动。
if not task.export_file_path:
gen = generate_excel({"task_id": task.task_no})
if gen.get("status") != "ok":
return gen
# [STEP 2] 区分人工确认与 RPA 上传两种路径。
# manual_confirm 直接收口任务;auto/retry_upload 则走 RPA 触发、轮询和失败兜底。
artifact_id = payload.get('artifact_id')
try:
artifact_id = int(artifact_id) if artifact_id is not None else None
except (TypeError, ValueError):
return tool_response(status='failed', task=task, message='artifact_id 无效', data=serialize_task_for_tool(task))
# manual_confirm 需要私有回执;auto/retry_upload 走 Artifact 尝试和回调。
mode = str(payload.get("mode") or "auto").strip().lower()
if mode == "manual_confirm":
if task.process_status == "uploaded":
return tool_response(
status="ok",
task=task,
task_id=task.task_no,
message=t("workflow.fulfillment.manual_already_done", lang=lang).format(task_no=task.task_no),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
operator_id = payload.get('operator_id')
try:
attempt = record_manual_upload(
task, artifact_id=artifact_id, evidence_asset_no=str(payload.get('evidence_asset_no') or ''),
operator_id=int(operator_id), freight_ref_no=str(payload.get('freight_ref_no') or ''),
)
apply_task_transition(task, TaskTransition.UPLOADED)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="completed",
message=t("workflow.fulfillment.manual_confirmed", lang=lang),
progress_percent=100,
detail=t("workflow.fulfillment.task_completed", lang=lang),
)
# [STEP 2.1] 手工上传确认属于任务终态写路径,需要同步刷新批次汇总,
# 否则聊天顶部批次卡片仍会读取旧的 process_summary_json,显示成未完成。
from app.services.shipping_notice.task_workflow import sync_batch_after_task_change
sync_batch_after_task_change(task)
ref = str(payload.get("freight_ref_no") or "").strip()
if ref:
task.freight_ref_no = ref
log_task_event(task, "upload_manual_confirmed", {"freight_ref_no": ref or None})
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
log_task_event(task, 'upload_manual_confirmed', {'artifact_id': attempt.artifact_id, 'attempt_id': attempt.id})
db.session.commit()
return tool_response(
status="ok",
@@ -675,8 +677,8 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
task_id=task.task_no,
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
human_options=[] if task.process_status == 'uploaded' else None,
)
# [STEP 3] 处理 RPA 上传状态机。
@@ -742,10 +744,17 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
data=serialize_task_for_tool(task),
)
queued, trigger = write_upload_trigger(task.task_no, task.export_file_path or "")
try:
attempt = start_rpa_attempt(task, artifact_id=artifact_id, idempotency_key=payload.get('idempotency_key'))
artifact = current_upload_artifact(task, attempt.artifact_id)
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
queued, trigger = write_upload_trigger(task.task_no, artifact.file_path, payload={
'artifact_id': artifact.id, 'attempt_id': attempt.id, 'callback_id': f'rpa:{attempt.id}',
})
if queued and trigger:
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
attempt_no = attempts + 1
attempt_no = attempt.attempt_no
task.upload_started_at = datetime.utcnow()
set_task_step_progress(
task,
@@ -767,6 +776,8 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
"queue_file": queued,
"trigger": trigger,
"attempt": attempt_no,
'attempt_id': attempt.id,
'artifact_id': artifact.id,
"timeout_seconds": timeout_seconds,
"max_attempts": max_attempts,
},
@@ -828,11 +839,33 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
disposition_gate = _task_disposition_gate_response(task)
if disposition_gate is not None:
return disposition_gate
customer_gate = customer_gate_tool_response(task, operation='rpa_report_upload')
if customer_gate is not None:
return customer_gate
try:
attempt_id = int(payload.get('attempt_id'))
except (TypeError, ValueError):
return tool_response(status='failed', task=task, message='attempt_id is required', data=serialize_task_for_tool(task))
from app.models import ShippingUploadAttempt
attempt = db.session.get(ShippingUploadAttempt, attempt_id)
if attempt is None:
return tool_response(status='failed', task=task, message='Upload attempt not found', data=serialize_task_for_tool(task))
from app.models import ShippingExportArtifact
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
if artifact is None or artifact.task_id != task.id:
return tool_response(status='failed', task=task, message='Upload attempt does not belong to this task', data=serialize_task_for_tool(task))
success = bool(payload.get("success", True))
try:
completed = complete_attempt(
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
freight_ref_no=str(payload.get('freight_ref_no') or ''), error_message=str(payload.get('error_message') or ''),
)
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
if success:
apply_task_transition(task, TaskTransition.UPLOADED)
task.upload_finished_at = datetime.utcnow()
if task.process_status == 'uploaded':
apply_task_transition(task, TaskTransition.UPLOADED)
set_task_step_progress(
task,
step_key="step7_upload_freight",
@@ -842,8 +875,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
progress_percent=100,
detail=t("workflow.fulfillment.task_completed", lang=lang),
)
task.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None
log_task_event(task, "upload_rpa_success", {"freight_ref_no": task.freight_ref_no})
log_task_event(task, "upload_rpa_success", {"artifact_id": completed.artifact_id, "attempt_id": completed.id})
db.session.commit()
return tool_response(
status="ok",
@@ -851,11 +883,11 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
task_id=task.task_no,
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
checkpoint=CP_UPLOADED if task.process_status == 'uploaded' else None,
human_options=[] if task.process_status == 'uploaded' else None,
)
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
@@ -866,8 +898,8 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
progress_percent=100,
detail=t("workflow.fulfillment.upload_failed_detail", lang=lang),
)
task.error_message = str(payload.get("error_message") or "RPA upload failed")[:500]
log_task_event(task, "upload_rpa_failed", {"error": task.error_message})
task.error_message = completed.error_message or 'RPA upload failed'
log_task_event(task, "upload_rpa_failed", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": task.error_message})
db.session.flush()
attempts = upload_rpa_attempts(task)
max_attempts = max_rpa_upload_attempts()
@@ -670,10 +670,13 @@ def run_intake_parse(
persist_info: dict[str, Any] = {}
uploaded_storage_keys: list[str] = []
try:
from app.models import ShippingOrderSchemaVersion
is_profile_sample = str(locked.purpose or '') == 'order_document_profile_sample'
schema_definition: dict[str, Any] = {'fields': []}
if not is_profile_sample:
from app.models import ShippingOrderSchemaVersion
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
schema_definition = dict(schema_version.definition_json or {}) if schema_version is not None else {'fields': []}
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
schema_definition = dict(schema_version.definition_json or {}) if schema_version is not None else {'fields': []}
# [STEP 2] 上传阶段只完成文件预处理;禁止提前生成 Candidate 或业务判重。
persist_info = persist_intake_documents(
intake=locked,
@@ -699,7 +702,28 @@ def run_intake_parse(
locked.order_extraction_error_message = None
locked.updated_at = datetime.utcnow()
# [STEP 3] 规则结果仅作为 Chatflow 抽取提示,不代表完整订单或可建单结果。
# [STEP 3] 模板样本不得生成业务摘要;业务 Intake 的规则结果仅作 Chatflow 抽取提示。
if is_profile_sample:
locked.structured_result_json = tech_summary
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, 'sample_only': True,
'document_count': persist_info.get('document_count'), 'candidate_count': 0,
}
# 规则结果仅作为 Chatflow 抽取提示,不代表完整订单或可建单结果。
from app.services.shipping_notice.intake_business_parser import (
parse_intake_business_summary,
)
@@ -44,6 +44,7 @@ ACTIVE_INTAKE_STATUSES = frozenset(
)
_DUPLICATE_RESOLUTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE = 'order_document_profile_sample'
def _parser_version() -> str:
@@ -284,6 +285,29 @@ def create_shipping_notice_intake(
3. parsed/consumed/queued/parsing 直接返回;cancelled/expired(含过期时间到期)冲突拒绝;
4. 仅 created/parse_failed 持锁重投:enqueue(commit=False) 并绑定 parse_job_id。
"""
return _create_intake_for_asset(
user_id=user_id, asset_no=asset_no, purpose='shipping_notice',
conversation_id=conversation_id,
)
def create_order_document_profile_sample_intake(*, user_id: int, asset_no: str) -> dict[str, Any]:
"""
为订单文档模板页创建隔离的 PDF/EML 样本解析 Intake。
AI/调用方触发时机:仅管理员在模板页上传用于配置/复核的文件后调用。该 Intake
不绑定会话,后续预解析只生成 Document 和布局候选,禁止进入候选、建单或 Dify 链路。
"""
return _create_intake_for_asset(
user_id=user_id, asset_no=asset_no, purpose=ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE,
conversation_id=None,
)
def _create_intake_for_asset(
*, user_id: int, asset_no: str, purpose: str, conversation_id: str | None,
) -> dict[str, Any]:
"""按受控 purpose 创建幂等 Intake;模板样本与业务发货通知共享基础设施但隔离用途。"""
asset = get_asset_for_user(asset_no, user_id)
if str(asset.upload_status or '') != 'ready':
raise ValidationError(code='FILE_ASSET.INVALID_STATUS', message='文件尚未上传完成')
@@ -291,8 +315,14 @@ def create_shipping_notice_intake(
raise ValidationError(code='FILE_ASSET.EXPIRED', message='文件资产已过期')
parser_version = _parser_version()
purpose = 'shipping_notice'
conv = str(conversation_id or '').strip() or None
if purpose == ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE:
extension = str(asset.extension or '').strip().lower()
if extension not in {'pdf', 'eml'}:
raise ValidationError(
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID',
message='Only PDF and EML files can be order profile samples',
)
# [STEP 1] 持锁定位或创建 Intake
intake = _lock_intake_for_asset_purpose_parser(
@@ -373,7 +403,7 @@ def create_shipping_notice_intake(
domain=SHIPPING_NOTICE_JOB_DOMAIN,
business_ref=intake.intake_no,
created_by_id=user_id,
message='等待预解析发货通知',
message=('等待解析订单模板样本' if purpose == ORDER_DOCUMENT_PROFILE_SAMPLE_PURPOSE else '等待预解析发货通知'),
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', 3) or 3),
dedupe_active=True,
dedupe_statuses=QUEUED_ONLY_STATUSES,
@@ -2,7 +2,7 @@
services/shipping_notice/inventory_routing_engine.py
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
依赖:库存路由模型、动态订单 FieldValue、routing_operators。
依赖:库存路由模型、冻结订单 Snapshot、routing_operators。
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
"""
@@ -12,7 +12,7 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Any
from app.models import ShippingInventoryRoutingRule, ShippingOrderFieldValue, ShippingOrderLine
from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot
from app.services.shipping_notice.routing_operators import matches_operator
@@ -30,23 +30,20 @@ class InventoryRoutingResult:
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any:
"""只读取 Task 当前 Extraction 的动态订单 FieldValue。"""
"""只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。"""
if condition.source_kind != 'order_field':
return None
extraction_id = getattr(task, 'current_order_extraction_id', None)
if not extraction_id:
snapshot_id = getattr(task, 'order_snapshot_id', None)
if not snapshot_id:
return None
snapshot = ShippingOrderSnapshot.query.get(int(snapshot_id))
if snapshot is None:
return None
query = ShippingOrderFieldValue.query.filter_by(
extraction_id=int(extraction_id), field_id=condition.order_field_id,
)
if line is None:
value = query.filter(ShippingOrderFieldValue.line_id.is_(None)).first()
else:
position = int(line.get('_position', 0))
value = query.join(ShippingOrderLine, ShippingOrderLine.id == ShippingOrderFieldValue.line_id).filter(
ShippingOrderLine.position == position,
).first()
return value.value_json if value is not None else None
return (snapshot.header_values_json or {}).get(str(condition.order_field_id))
position = int(line.get('_position', 0))
target = next((item for item in snapshot.lines if item.position == position), None)
return (target.field_values_json or {}).get(str(condition.order_field_id)) if target is not None else None
def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[str, Any] | None) -> bool:
@@ -706,6 +706,16 @@ def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
stop_agent_turn=True,
)
# 客户身份是所有库存与履约副作用的首要门禁;不能被后续 Snapshot/预约单
# 校验掩盖,否则 RPA 回调会在未确认客户时返回错误的人工节点。
try:
assert_customer_identity_gate(task, operation='rpa_inventory_callback')
except AppError as exc:
return tool_response(
status='failed', task=task, message=str(exc.message or '客户身份未确认,拒绝处理 RPA 回调'),
data=serialize_task_for_tool(task),
)
conflict_gate = field_conflict_gate_response(task, lang="zh")
if conflict_gate is not None:
return conflict_gate
@@ -731,7 +741,6 @@ def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
)
try:
assert_customer_identity_gate(task, operation='rpa_inventory_callback')
assert_inventory_source_gate(task, operation="rpa_inventory_callback")
except AppError as exc:
return tool_response(
@@ -98,6 +98,16 @@ def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang:
customer_gate = customer_gate_tool_response(task, operation=operation)
if customer_gate is not None:
return customer_gate
if not task.order_snapshot_id:
return tool_response(
status='needs_human',
task=task,
message='订单解析已确认后必须先冻结订单快照,才能进入库存链路。',
data={**serialize_task_for_tool(task), 'error_code': 'SHIPPING.ORDER_SNAPSHOT_REQUIRED'},
checkpoint='order_freeze',
stop_agent_turn=True,
forbidden_next_tools=['ensure_inventory', 'parse_inventory', 'match_inventory', 'generate_shipment_excel'],
)
conflict_gate = field_conflict_gate_response(task, lang=lang)
if conflict_gate is not None:
return conflict_gate
@@ -8,6 +8,8 @@ backend/app/services/shipping_notice/order_customer_matching.py
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
@@ -28,6 +30,7 @@ ROLE_FIELDS = {
'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'},
'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'},
}
IDENTITY_RULE_VERSION = 'order-customer-fingerprint.v1'
def _normalized_code(value: Any) -> str:
@@ -35,6 +38,21 @@ def _normalized_code(value: Any) -> str:
return str(value or '').strip().upper()
def _identity_fingerprint(*, role: str, raw_name: str, external_code: str, source_system: str) -> tuple[str, dict[str, str]]:
"""用订单原文标准化值和固定规则版本生成稳定身份指纹,不写回或替换原始字段。"""
components = {
'role': role,
'normalized_name': normalize_customer_name(raw_name) if raw_name else '',
'external_code': _normalized_code(external_code),
'source_system': _normalized_code(source_system),
}
encoded = json.dumps(
{'rule_version': IDENTITY_RULE_VERSION, 'components': components},
ensure_ascii=True, sort_keys=True, separators=(',', ':'),
).encode('utf-8')
return hashlib.sha256(encoded).hexdigest(), components
def _customer_candidates(raw_name: str) -> list[dict[str, Any]]:
"""按标准名称和 approved 名称别名返回稳定去重的启用客户候选。"""
normalized = normalize_customer_name(raw_name)
@@ -150,6 +168,9 @@ def refresh_order_customer_matches(
raw_name = str(header.get(fields['name']) or '').strip()
external_code = _normalized_code(header.get(fields['code']))
source_system = _normalized_code(header.get(fields['source']))
fingerprint, components = _identity_fingerprint(
role=role, raw_name=raw_name, external_code=external_code, source_system=source_system,
)
candidates = (
_bill_to_candidates(raw_name, external_code, source_system)
if role == 'bill_to'
@@ -165,6 +186,9 @@ def refresh_order_customer_matches(
row.normalized_name = normalize_customer_name(raw_name) if raw_name else None
row.source_system = source_system or None
row.external_code = external_code or None
row.identity_fingerprint = fingerprint
row.identity_rule_version = IDENTITY_RULE_VERSION
row.identity_components_json = components
row.candidates_json = candidates
if len(candidates) == 1:
candidate = candidates[0]
@@ -183,6 +207,7 @@ def refresh_order_customer_matches(
row.resolution_method = None
row.confirmed_by_id = None
row.confirmed_at = None
row.confirmation_reason = None
row.updated_at = datetime.utcnow()
db.session.flush()
results.append(serialize_order_customer_match(row))
@@ -196,8 +221,9 @@ def confirm_order_customer_match(
customer_id: int,
site_id: int | None = None,
actor_id: int | None,
reason: str,
) -> dict[str, Any]:
"""人工确认某个订单客户角色;Ship-to 必须同时选择所属客户的启用站点。"""
"""人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。"""
if role not in ROLE_FIELDS:
raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID')
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
@@ -205,6 +231,9 @@ def confirm_order_customer_match(
).one_or_none()
if row is None:
raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_NOT_FOUND')
reason_value = str(reason or '').strip()
if not reason_value:
raise ValidationError('Customer confirmation reason is required', code='SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
@@ -221,6 +250,7 @@ def confirm_order_customer_match(
row.customer_name_snapshot = customer.standard_name
row.customer_short_code_snapshot = customer.short_code
row.resolution_method = 'manual'
row.confirmation_reason = reason_value
row.confirmed_by_id = actor_id
row.confirmed_at = datetime.utcnow()
db.session.commit()
@@ -239,8 +269,11 @@ def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str,
'site_id': row.site_id,
'source_system': row.source_system,
'external_code': row.external_code,
'identity_fingerprint': row.identity_fingerprint,
'identity_rule_version': row.identity_rule_version,
'standard_name': row.customer_name_snapshot,
'short_code': row.customer_short_code_snapshot,
'candidates': list(row.candidates_json or []),
'resolution_method': row.resolution_method,
'confirmation_reason': row.confirmation_reason,
}
@@ -20,6 +20,7 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocumentProfile,
ShippingOrderSchemaVersion,
)
@@ -27,6 +28,7 @@ from app.services.shipping_notice.document_layout.html_table import parse_html_g
from app.services.shipping_notice.document_layout.order_profile import (
OrderDocumentProfile,
OrderProfileColumnRule,
diagnose_order_profile_header,
order_profile_structure_fingerprint,
)
@@ -195,8 +197,11 @@ def _document_layout(document: ShippingNoticeDocument) -> dict[str, Any]:
def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
"""列出最近含 ready MinerU 表格的订单附件;不返回正文、HTML 或原始布局。"""
safe_limit = max(1, min(int(limit), 100))
rows = ShippingNoticeDocument.query.filter(
ShippingNoticeDocument.document_type == 'attachment',
rows = ShippingNoticeDocument.query.join(
ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id,
).filter(
ShippingNoticeDocument.document_type.in_({'attachment', 'email_body'}),
ShippingNoticeIntake.purpose.in_({'shipping_notice', 'order_document_profile_sample'}),
ShippingNoticeDocument.current_layout_version_id.is_not(None),
).order_by(ShippingNoticeDocument.created_at.desc()).limit(safe_limit * 4).all()
result: list[dict[str, Any]] = []
@@ -210,7 +215,7 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
result.append({
'document_id': document.id,
'intake_id': document.intake_id,
'filename': document.filename,
'filename': document.filename,
'content_hash': document.content_hash,
'provider': layout.get('provider'),
'provider_version': layout.get('provider_version'),
@@ -222,6 +227,42 @@ def list_sample_documents(*, limit: int = 50) -> list[dict[str, Any]]:
return result
def create_sample_intake(*, asset_no: str, actor_id: int | None) -> dict[str, Any]:
"""从模板页已上传的私有 PDF/EML 创建隔离样本 Intake,不生成履约业务数据。"""
if actor_id is None:
raise ValidationError(
'Profile sample requires an administrator identity',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
)
from app.services.shipping_notice.intake_service import create_order_document_profile_sample_intake
intake = create_order_document_profile_sample_intake(user_id=int(actor_id), asset_no=str(asset_no or ''))
return {
'intake_no': intake['intake_no'],
'parse_status': intake['parse_status'],
'document_count': 0,
'error_code': None,
}
def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[str, Any]:
"""返回模板样本的最小处理状态;拒绝读取业务 Intake 或解析正文。"""
if actor_id is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
intake = ShippingNoticeIntake.query.filter_by(
intake_no=str(intake_no or '').strip().upper(), user_id=int(actor_id),
purpose='order_document_profile_sample',
).first()
if intake is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
return {
'intake_no': intake.intake_no,
'parse_status': intake.parse_status,
'document_count': ShippingNoticeDocument.query.filter_by(intake_id=intake.id).count(),
'error_code': intake.error_code,
}
def get_sample_tables(document_id: int) -> dict[str, Any]:
"""返回样本文档的表格网格预览;预览只含 cell 文本,不返回 bbox、正文或原始 HTML。"""
document = db.session.get(ShippingNoticeDocument, int(document_id))
@@ -237,6 +278,7 @@ def get_sample_tables(document_id: int) -> dict[str, Any]:
continue
table_id = str(raw.get('table_id') or '')
grid = parse_html_grid(str(raw['html']), table_id=table_id)
issues = diagnose_order_profile_header(grid, header_row_index=0)
tables.append({
'table_id': table_id,
'page_no': int(raw.get('page_no') or 1),
@@ -246,6 +288,8 @@ def get_sample_tables(document_id: int) -> dict[str, Any]:
[slot.text if slot is not None else '' for slot in row]
for row in grid.rows
],
'issues': issues,
'profile_creation_allowed': not issues,
})
return {
'document': {
@@ -305,6 +349,13 @@ def create_draft_from_sample(
'Sample row selection is out of range',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
)
structure_issues = diagnose_order_profile_header(grid, header_row_index=header_row_index)
if structure_issues:
raise ValidationError(
'Sample table header contains order line data and must be structurally rebuilt',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED',
details={'issues': structure_issues},
)
definition = {
'structure_fingerprint': order_profile_structure_fingerprint(
grid, header_row_index=header_row_index,
@@ -514,6 +565,8 @@ def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any
rows = ShippingOrderDocumentProfile.query.filter_by(
schema_version_id=int(schema_version_id), status='published',
).order_by(ShippingOrderDocumentProfile.profile_code.asc()).all()
from app.services.shipping_notice.document_profile_quality_service import profile_is_auto_create_approved
return [{
'profile_id': item.id,
'profile_code': item.profile_code,
@@ -522,4 +575,7 @@ def published_snapshots_for_schema(schema_version_id: int) -> list[dict[str, Any
'schema_version_id': item.schema_version_id,
'structure_fingerprint': item.structure_fingerprint,
'definition': dict(item.definition_json or {}),
'auto_create_approved': profile_is_auto_create_approved(
profile_id=item.id, checksum=str(item.checksum or ''),
),
} for item in rows]
@@ -355,6 +355,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
'profile_checksum': str(raw_profile.get('checksum') or ''),
'table_id': table_id,
'page_no': int(raw_table.get('page_no') or 1),
'auto_create_approved': bool(raw_profile.get('auto_create_approved')),
'rows': compact_rows,
})
return {
@@ -422,10 +423,19 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[
return raw
def validate_unit_orders(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""强制单元来源边界及 accepted 字段锁,阻止跨附件引用或覆盖确定性值。"""
def validate_unit_orders(
run: Any, *, unit: Any, orders: list[dict[str, Any]], strict_provider_evidence: bool = False,
) -> list[dict[str, Any]]:
"""强制单元、字段白名单和证据边界;Dify 输出另须逐字证据可验证。"""
intake, document = _unit_snapshot(run, unit)
intake_no = str(intake.get('intake_no') or '').strip().upper()
schema_snapshot = run.input_snapshot_json.get('schema') if isinstance(run.input_snapshot_json, dict) else {}
contract = schema_snapshot.get('extraction_contract') if isinstance(schema_snapshot, dict) else {}
allowed_fields = {
str(item.get('field_id') or '')
for item in contract.get('fields') or [] if isinstance(item, dict) and item.get('field_id')
}
evidence_text = frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '')
for order in orders:
if str(order.get('source_intake_no') or '').strip().upper() != intake_no:
raise ValidationError(
@@ -445,12 +455,24 @@ def validate_unit_orders(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -
)
for fields in field_groups:
for field in fields if isinstance(fields, list) else []:
if not isinstance(field, dict) or str(field.get('field_id') or '') not in allowed_fields:
raise ValidationError(
'Unit order contains a field outside the frozen extraction contract',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
for observation in field.get('observations') or [] if isinstance(field, dict) else []:
if int(observation.get('document_id') or 0) != int(unit.document_id):
if not isinstance(observation, dict) or int(observation.get('document_id') or 0) != int(unit.document_id):
raise ValidationError(
'Unit observation references another document',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
if strict_provider_evidence:
quote = str(observation.get('quote') or '').strip()
if not quote or quote not in evidence_text:
raise ValidationError(
'Workflow observation evidence is not verifiable in the frozen unit input',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
_validate_locked_layout_fields(document, orders=orders)
return orders
@@ -503,7 +525,7 @@ def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dic
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
"""仅 accepted layout 完整表可零 Provider;其他结构或纯文本一律交给模型补充。"""
"""仅由盲测批准的唯一 Profile 实测行生成零 Provider 订单;其余交给模型补充。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
schema = (
@@ -512,38 +534,40 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
else {}
)
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
intake, document = _unit_snapshot(run, unit)
layout_order = _build_accepted_layout_order(
unit=unit, intake=intake, document=document, schema=schema, definition=definition,
intake, _document = _unit_snapshot(run, unit)
profile_result = _profile_table_candidates(run, unit=unit)
if profile_result.get('blocking'):
return None
approved_tables = [
item for item in profile_result.get('tables') or []
if bool(item.get('auto_create_approved'))
]
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也回退 Dify/人工。
if len(profile_result.get('tables') or []) != 1 or len(approved_tables) != 1:
return None
order = _build_approved_profile_order(
unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0],
)
if layout_order is not None:
return [layout_order]
return None
return [order] if order is not None else None
def _build_accepted_layout_order(
*, unit: Any, intake: dict[str, Any], document: dict[str, Any],
schema: dict[str, Any], definition: dict[str, Any],
def _build_approved_profile_order(
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
table: dict[str, Any],
) -> dict[str, Any] | None:
"""
把唯一且完整的 accepted L4 表格转换为零 Provider 订单。
把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。
Args:
unit: 当前抽取单元,用于固定 document_id。
intake: 当前冻结 Intake,用于固定 source_intake_no。
document: 含 layout_schema_candidates 的冻结 Document。
schema: Dify 抽取契约元信息。
definition: Run 冻结 Schema 完整定义,用于 required/scope 门禁。
table: `_profile_table_candidates` 产生且已批准的单个表解析结果。
Returns:
完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。
"""
candidates = [
item for item in document.get('layout_schema_candidates') or []
if isinstance(item, dict) and item.get('mapping_status') == 'accepted'
]
if len(candidates) != 1 or candidates[0].get('issues'):
return None
fields = [
item for item in definition.get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
@@ -552,9 +576,12 @@ def _build_accepted_layout_order(
by_id = {str(item.get('field_id') or ''): item for item in fields}
line_groups: list[dict[str, Any]] = []
header_values: dict[str, list[dict[str, Any]]] = {}
for row in candidates[0].get('rows') or []:
if not isinstance(row, dict) or row.get('role') in {'deleted', 'empty', 'summary', 'repeated_header'}:
for row in table.get('rows') or []:
# Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。
if not isinstance(row, dict) or row.get('status') == 'deleted':
continue
if row.get('status') != 'parsed' or row.get('issues'):
return None
line_fields: list[dict[str, Any]] = []
for raw in row.get('fields') or []:
if not isinstance(raw, dict):
@@ -622,7 +649,7 @@ def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, tim
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
) from exc
orders = validate_unit_orders(
run, unit=unit, orders=parse_order_extraction_workflow_result(result),
run, unit=unit, orders=parse_order_extraction_workflow_result(result), strict_provider_evidence=True,
)
metadata = {
'workflow_run_id': result.get('workflow_run_id'),
@@ -1,7 +1,7 @@
"""
services/shipping_notice/order_field_purposes.py
用途:将当前已接受订单解析的 FieldValue 按已发布 Schema 业务用途投影给履约链。
用途:将冻结订单 Snapshot 按冻结 Schema 业务用途投影给履约链。
依赖:order_schema.service、export.order_field_id_values、ShippingTask。
逻辑:路由、门禁、匹配和展示只通过发布快照中的 business_purpose 定位稳定 field_id,禁止读取任务行固定业务列。
"""
@@ -11,21 +11,18 @@ from __future__ import annotations
from typing import Any
from app import db
from app.models import ShippingOrderExtraction, ShippingTask
from app.models import ShippingOrderSnapshot, ShippingTask
from app.services.shipping_notice.export import order_field_id_values
def task_line_purpose_field_ids(task: ShippingTask, *, required: set[str] | None = None) -> dict[str, str]:
"""读取任务锁定 Schema 快照的行级用途与字段 ID,防止后续发布版本重解释历史任务。"""
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
)
if extraction is None or extraction.status != 'accepted':
raise ValueError('任务没有可用于履约的已接受订单解析版本')
"""读取冻结快照的行级用途与字段 ID,防止后续发布版本重解释履约任务。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于履约的冻结订单快照')
purposes = {
str(config.get('business_purpose')): str(config.get('field_id'))
for config in (extraction.schema_version.definition_json or {}).get('fields') or []
for config in (snapshot.schema_version.definition_json or {}).get('fields') or []
if config.get('scope') == 'line' and config.get('business_purpose') not in (None, '', 'general')
}
missing = sorted((required or set()) - set(purposes))
@@ -35,7 +32,7 @@ def task_line_purpose_field_ids(task: ShippingTask, *, required: set[str] | None
def task_line_purpose_values(task: ShippingTask, *, required: set[str] | None = None) -> list[dict[str, Any]]:
"""按订单行位置返回用途键值,值只来自任务当前 accepted Extraction 的 FieldValue。"""
"""按订单行位置返回用途键值,值只来自冻结 Snapshot。"""
purpose_ids = task_line_purpose_field_ids(task, required=required)
_header, lines = order_field_id_values(task)
return [
@@ -0,0 +1,267 @@
"""
services/shipping_notice/order_freeze_service.py
用途:将已复核的动态订单解析冻结为强类型履约快照。
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingTask 与统一 AppError。
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot,库存、导出和上传的后续阶段只读取该快照。
"""
from __future__ import annotations
from datetime import date
from decimal import Decimal, InvalidOperation
from typing import Any
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderCustomerMatch,
ShippingOrderReviewEvent,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingTask,
)
HEADER_FIELDS = (
'po_number', 'customer_code', 'customer_name', 'bill_to_customer', 'bill_to_address',
'ship_to_customer', 'ship_to_address', 'destination', 'currency', 'incoterm', 'required_date',
'order_date', 'payment_term',
)
LINE_FIELDS = (
'line_no', 'part_number', 'customer_part_number', 'aws_part_number', 'reservation_id', 'qty', 'uom',
'unit_price', 'amount', 'warehouse', 'inventory_source_hint', 'remark',
)
CRITICAL_FIELDS = frozenset({'part_number', 'reservation_id', 'qty', 'po_number'})
DECIMAL_FIELDS = frozenset({'qty', 'unit_price', 'amount'})
DATE_FIELDS = frozenset({'required_date', 'order_date'})
def freeze_order_snapshot(
task: ShippingTask,
*,
actor_id: int,
expected_order_data_version: int,
rule_versions: dict[str, Any] | None = None,
) -> ShippingOrderSnapshot:
"""
冻结指定任务的已接受解析为不可变履约订单。
核心逻辑:校验乐观锁、已接受 Extraction、预置核心字段和未确认 LLM 证据;随后在同一事务写入单头/单身快照并回填 Task 指针。
Args:
task: 必须是当前用户有权操作且尚未冻结的任务。
actor_id: 执行冻结的用户 ID,不能为空。
expected_order_data_version: 用户界面读取到的版本;不匹配时拒绝覆盖。
rule_versions: 已冻结的订单/客户规则版本审计数据。
Returns:
ShippingOrderSnapshot: 已落库的不可变快照。
Raises:
ConflictError: 快照已存在、版本冲突或存在未确认 LLM 关键字段。
ValidationError: 当前 Extraction 不完整或核心字段契约不匹配。
"""
if task.order_snapshot_id:
raise ConflictError('Order snapshot is already frozen', code='SHIPPING.ORDER_SNAPSHOT_FROZEN')
if not actor_id:
raise ValidationError('Snapshot freeze requires an operator', code='SHIPPING.ORDER_FREEZE_BLOCKED')
actual_version = int(task.order_data_version or 1)
if actual_version != int(expected_order_data_version):
raise ConflictError(
'Order data version has changed',
code='SHIPPING.ORDER_DATA_VERSION_MISMATCH',
details={'expected': expected_order_data_version, 'actual': actual_version},
)
extraction = _accepted_extraction(task)
configs = _fixed_configs(extraction)
_assert_llm_review_gate(extraction, configs)
header_values, line_values = _extraction_values(extraction, configs)
customer_match = _confirmed_ordering_customer(extraction)
# [STEP 1] 所有已发布字段均按 field_id 冻结;核心字段同步为强类型列,供既有履约能力兼容读取。
snapshot = ShippingOrderSnapshot(
task_id=task.id,
extraction_id=extraction.id,
schema_version_id=extraction.schema_version_id,
customer_id=customer_match.customer_id,
customer_short_code_snapshot=customer_match.customer_short_code_snapshot,
order_data_version=actual_version,
rule_versions_json={
**dict(rule_versions or {}),
'ordering_customer': {
'match_id': customer_match.id,
'identity_fingerprint': customer_match.identity_fingerprint,
'identity_rule_version': customer_match.identity_rule_version,
'resolution_method': customer_match.resolution_method,
'confirmed_by_id': customer_match.confirmed_by_id,
'confirmed_at': customer_match.confirmed_at.isoformat() if customer_match.confirmed_at else None,
},
},
frozen_by_id=actor_id,
header_values_json=_field_id_values(header_values, configs),
**{field: _coerce_value(header_values.get(field), field) for field in HEADER_FIELDS},
)
db.session.add(snapshot)
db.session.flush()
for position, source in enumerate(line_values):
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id,
position=position,
field_values_json=_field_id_values(source, configs),
**{field: _coerce_value(source.get(field), field) for field in LINE_FIELDS},
))
task.order_snapshot_id = snapshot.id
ShippingOrderReviewEvent.query.filter_by(
task_id=task.id,
extraction_id=extraction.id,
snapshot_id=None,
).update({'snapshot_id': snapshot.id}, synchronize_session=False)
db.session.flush()
return snapshot
def assert_task_order_is_editable(task: ShippingTask) -> None:
"""拒绝冻结后对 Candidate/Extraction 的任何直接编辑,防止快照与解析事实漂移。"""
if task.order_snapshot_id:
raise ConflictError('Frozen order snapshot cannot be edited', code='SHIPPING.ORDER_SNAPSHOT_FROZEN')
def _accepted_extraction(task: ShippingTask) -> ShippingOrderExtraction:
"""读取当前已接受 Extraction;冻结绝不回读旧版本或 Task JSON 投影。"""
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) if task.current_order_extraction_id else None
if extraction is None or extraction.status != 'accepted':
raise ValidationError('Task has no accepted order extraction', code='SHIPPING.ORDER_FREEZE_BLOCKED')
return extraction
def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> ShippingOrderCustomerMatch:
"""只接受已人工确认的 Bill-to 订购客户,禁止由冻结请求自由指定 customer_id。"""
row = ShippingOrderCustomerMatch.query.filter_by(extraction_id=extraction.id, role='bill_to').one_or_none()
if (
row is None or row.status != 'confirmed' or row.customer_id is None
or not row.customer_short_code_snapshot or not row.identity_fingerprint or not row.identity_rule_version
):
raise ValidationError(
'Ordering customer must be confirmed before freezing',
code='SHIPPING.ORDER_CUSTOMER_CONFIRMATION_REQUIRED',
)
return row
def _fixed_configs(extraction: ShippingOrderExtraction) -> dict[str, dict[str, Any]]:
"""验证预置核心字段存在且类型正确;扩展字段由已发布业务配置决定是否参与履约。"""
configs = {
str(item.get('field_code')): item
for item in (extraction.schema_version.definition_json or {}).get('fields') or []
if item.get('enabled', True)
}
expected = set(HEADER_FIELDS) | set(LINE_FIELDS)
missing = expected - set(configs)
if missing:
raise ValidationError(
'Frozen order schema is missing required core fields',
code='SHIPPING.ORDER_CONTRACT_INVALID',
details={'missing': sorted(missing)},
)
wrong_scope = [
code for code, config in configs.items() if code in expected
if str(config.get('scope')) != ('header' if code in HEADER_FIELDS else 'line')
]
if wrong_scope:
raise ValidationError('Frozen order schema has invalid field scope', code='SHIPPING.ORDER_CONTRACT_INVALID', details={'fields': wrong_scope})
wrong_type = [
code for code, config in configs.items() if code in expected
if str(config.get('value_type')) != (
'date' if code in DATE_FIELDS else 'decimal' if code in DECIMAL_FIELDS else 'string'
)
]
if wrong_type:
raise ValidationError('Frozen order schema has invalid core field type', code='SHIPPING.ORDER_CONTRACT_INVALID', details={'fields': wrong_type})
return configs
def _assert_llm_review_gate(extraction: ShippingOrderExtraction, configs: dict[str, dict[str, Any]]) -> None:
"""关键字段若由未经证据确认的 LLM fallback 参与裁决,则强制人工复核。"""
decisions = {
int(item.id): item
for item in ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).all()
}
observations = {
int(item.id): item
for item in ShippingOrderFieldObservation.query.filter_by(extraction_id=extraction.id).all()
}
field_codes = {str(config['field_id']): code for code, config in configs.items()}
blocked: list[dict[str, Any]] = []
for decision in decisions.values():
code = field_codes.get(str(decision.field_id))
if code not in CRITICAL_FIELDS:
continue
observation_ids = [decision.selected_observation_id, *(decision.supporting_observation_ids_json or [])]
for observation_id in observation_ids:
observation = observations.get(int(observation_id)) if observation_id else None
if observation and _is_unverified_llm(observation):
blocked.append({'field_code': code, 'line_id': decision.line_id, 'observation_id': observation.id})
if blocked:
raise ConflictError(
'LLM fallback values require human evidence review before freezing',
code='SHIPPING.ORDER_LLM_REVIEW_REQUIRED',
details={'fields': blocked},
)
def _is_unverified_llm(observation: ShippingOrderFieldObservation) -> bool:
"""识别 LLM fallback Observation;确定性证据和已人工确认 Observation 不受此门禁影响。"""
source = f'{observation.source_type}:{observation.extractor}'.lower()
return not observation.evidence_verified and ('llm' in source or 'dify' in source or 'fallback' in source)
def _extraction_values(
extraction: ShippingOrderExtraction,
configs: dict[str, dict[str, Any]],
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""按 Schema 稳定 field_id 汇集 FieldValue,保留原始字符串以避免料号和预约单丢失前导零。"""
code_by_id = {str(item['field_id']): code for code, item in configs.items()}
values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all()
headers = {code_by_id[str(item.field_id)]: item.value_json for item in values if item.line_id is None and str(item.field_id) in code_by_id}
line_maps: dict[int, dict[str, Any]] = {}
for item in values:
if item.line_id is not None and str(item.field_id) in code_by_id:
line_maps.setdefault(int(item.line_id), {})[code_by_id[str(item.field_id)]] = item.value_json
lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all()
if not lines:
raise ValidationError('Frozen order requires at least one order line', code='SHIPPING.ORDER_FREEZE_BLOCKED')
return headers, [line_maps.get(int(line.id), {}) for line in lines]
def _field_id_values(values: dict[str, Any], configs: dict[str, dict[str, Any]]) -> dict[str, Any]:
"""将当前作用域字段按稳定 field_id 写入快照,供业务配置安全消费扩展字段。"""
return {
str(config['field_id']): values.get(code)
for code, config in configs.items()
if config.get('field_id') and values.get(code) is not None
}
def _coerce_value(value: Any, field_code: str) -> Any:
"""将动态 JSON 值安全写入强类型快照;数量为 Decimal,日期为 date,标识符为字符串。"""
if value in (None, ''):
return None
if field_code in DECIMAL_FIELDS:
try:
return Decimal(str(value))
except (InvalidOperation, ValueError, TypeError) as exc:
raise ValidationError('Numeric order value is invalid', code='SHIPPING.ORDER_FREEZE_BLOCKED', details={'field': field_code}) from exc
if field_code in DATE_FIELDS:
if isinstance(value, date):
return value
try:
return date.fromisoformat(str(value))
except ValueError as exc:
raise ValidationError('Date order value is invalid', code='SHIPPING.ORDER_FREEZE_BLOCKED', details={'field': field_code}) from exc
return str(value)
@@ -66,6 +66,36 @@ DIFY_EXPOSURE_POLICY_ORDER = ('never', 'redacted', 'confirmed_readonly')
DIFY_EXPOSURE_POLICIES = frozenset(DIFY_EXPOSURE_POLICY_ORDER)
SENSITIVITY_LEVELS = frozenset({'low', 'personal', 'confidential'})
# 阶段 1:这 26 个字段是预置强类型履约核心。扩展字段也可由已发布业务配置纳入履约,
# 并在 Snapshot 中按稳定 field_id 冻结,避免字段重命名影响历史履约事实。
FIXED_CORE_FIELD_SPECS: dict[str, tuple[str, str]] = {
'po_number': ('header', 'string'),
'customer_code': ('header', 'string'),
'customer_name': ('header', 'string'),
'bill_to_customer': ('header', 'string'),
'bill_to_address': ('header', 'string'),
'ship_to_customer': ('header', 'string'),
'ship_to_address': ('header', 'string'),
'destination': ('header', 'string'),
'currency': ('header', 'string'),
'incoterm': ('header', 'string'),
'required_date': ('header', 'date'),
'order_date': ('header', 'date'),
'payment_term': ('header', 'string'),
'line_no': ('line', 'string'),
'part_number': ('line', 'string'),
'customer_part_number': ('line', 'string'),
'aws_part_number': ('line', 'string'),
'reservation_id': ('line', 'string'),
'qty': ('line', 'decimal'),
'uom': ('line', 'string'),
'unit_price': ('line', 'decimal'),
'amount': ('line', 'decimal'),
'warehouse': ('line', 'string'),
'inventory_source_hint': ('line', 'string'),
'remark': ('line', 'string'),
}
def _iso(value: datetime | None) -> str | None:
"""将可空时间转换为 API 使用的 ISO 字符串。"""
@@ -620,7 +650,7 @@ def get_extraction_audit(extraction_id: int) -> dict[str, Any]:
def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""初始化全局唯一订单 Schema;重复初始化明确拒绝。"""
"""初始化全局唯一订单 Schema 并预置 26 个履约核心字段;仍允许新增扩展字段。"""
if ShippingOrderSchema.query.count():
raise ConflictError('Only one shipping order schema is allowed', code='SHIPPING.ORDER_SCHEMA_EXISTS')
display_name = str(data.get('display_name') or '').strip()
@@ -634,6 +664,18 @@ def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str
updated_by_id=actor_id,
)
db.session.add(schema)
db.session.flush()
for sequence, (field_code, (scope, value_type)) in enumerate(FIXED_CORE_FIELD_SPECS.items(), start=1):
db.session.add(ShippingOrderField(
schema_id=schema.id,
field_code=field_code,
scope=scope,
value_type=value_type,
field_category='order_header' if scope == 'header' else 'order_line',
collection_mode='llm_extraction',
display_sequence=sequence,
created_by_id=actor_id,
))
db.session.commit()
return get_state()
@@ -642,7 +684,7 @@ def save_field(
data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None,
request_id: str | None = None,
) -> dict[str, Any]:
"""创建或更新稳定字段;首次发布后锁定作用域、类型、字段分类和采集模式。"""
"""创建或更新字段;核心 26 字段身份不可变,扩展字段仍可按既有治理规则维护。"""
schema = _require_schema()
field = db.session.get(ShippingOrderField, field_id) if field_id else None
if field_id and (field is None or field.schema_id != schema.id):
@@ -654,6 +696,18 @@ def save_field(
collection_mode = str(data.get('collection_mode') or 'llm_extraction').strip()
if not FIELD_CODE_RE.fullmatch(code):
raise ValidationError('field_code must use lower snake_case', code='SHIPPING.ORDER_FIELD_INVALID')
fixed_shape = FIXED_CORE_FIELD_SPECS.get(code)
# 预置核心字段在 Schema 初始化时已存在。历史调用方重复声明相同契约时
# 只返回既有字段,绝不能再插入一条同名记录;形状不一致仍是硬错误。
if field is None and fixed_shape is not None:
existing_core = ShippingOrderField.query.filter_by(schema_id=schema.id, field_code=code).one_or_none()
if existing_core is not None:
if (scope, value_type) != fixed_shape:
raise ConflictError('Core order field identity is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
return _field_payload(existing_core)
if field is not None and field.field_code in FIXED_CORE_FIELD_SPECS:
if field.field_code != code or (scope, value_type) != fixed_shape:
raise ConflictError('Core order field identity is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
if scope not in FIELD_SCOPES or value_type not in FIELD_TYPES:
raise ValidationError('scope or value_type is invalid', code='SHIPPING.ORDER_FIELD_INVALID')
if field_category not in FIELD_CATEGORIES or collection_mode not in COLLECTION_MODES:
@@ -23,9 +23,13 @@ from app import db
from app.models import (
ShippingBatch,
ShippingCase,
ShippingExportArtifact,
ShippingExportArtifactLine,
ShippingInventoryVerification,
ShippingNoticeCandidate,
ShippingNoticeIntake,
ShippingTask,
ShippingUploadAttempt,
)
from app.services.shipping_notice.task_order_field_editor import (
current_header_field_values_or_empty,
@@ -55,6 +59,50 @@ class BatchProjection(str, Enum):
TOOL = "tool"
def _fulfillment_timeline(task: ShippingTask) -> dict[str, list[dict[str, Any]]]:
"""为工作台投影库存核验、滚动 Artifact 与上传 Attempt,所有事实只读且按时间排序。"""
verifications = ShippingInventoryVerification.query.filter_by(task_id=task.id).order_by(
ShippingInventoryVerification.created_at, ShippingInventoryVerification.id,
).all()
artifacts = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by(
ShippingExportArtifact.created_at, ShippingExportArtifact.id,
).all()
artifact_ids = [item.id for item in artifacts]
artifact_lines = ShippingExportArtifactLine.query.filter(
ShippingExportArtifactLine.artifact_id.in_(artifact_ids),
).all() if artifact_ids else []
reservations_by_artifact: dict[int, list[int]] = {}
for line in artifact_lines:
reservations_by_artifact.setdefault(int(line.artifact_id), []).append(int(line.reservation_id))
attempts = ShippingUploadAttempt.query.filter(
ShippingUploadAttempt.artifact_id.in_(artifact_ids),
).order_by(ShippingUploadAttempt.created_at, ShippingUploadAttempt.id).all() if artifact_ids else []
return {
'inventory_verifications': [{
'id': item.id, 'status': item.status, 'inventory_snapshot_id': item.inventory_snapshot_id,
'source_config_version': item.source_config_version, 'created_at': item.created_at.isoformat() if item.created_at else None,
'lines': [{
'reservation_id': line.reservation_id, 'required_qty': str(line.required_qty),
'available_qty': str(line.available_qty), 'status': line.status,
} for line in item.lines],
} for item in verifications],
'export_artifacts': [{
'id': item.id, 'artifact_no': item.artifact_no, 'status': item.status, 'file_name': item.file_name,
'file_size': item.file_size, 'created_at': item.created_at.isoformat() if item.created_at else None,
'reservation_ids': reservations_by_artifact.get(int(item.id), []),
} for item in artifacts],
'upload_attempts': [{
'id': item.id, 'artifact_id': item.artifact_id, 'attempt_no': item.attempt_no, 'mode': item.mode,
'status': item.status, 'callback_id': item.callback_id, 'freight_ref_no': item.freight_ref_no,
'error_code': item.error_code, 'error_message': item.error_message,
'evidence_asset_id': item.evidence_asset_id, 'operator_id': item.operator_id,
'started_at': item.started_at.isoformat() if item.started_at else None,
'finished_at': item.finished_at.isoformat() if item.finished_at else None,
'created_at': item.created_at.isoformat() if item.created_at else None,
} for item in attempts],
}
def _task_batch_no(task: ShippingTask) -> str | None:
if task.batch is not None and task.batch.batch_no:
return task.batch.batch_no
@@ -607,8 +655,11 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
"parse_validation": _dict_or_none(step_payload.get("parse_validation")),
"process_field_gate": _dict_or_none(step_payload.get("process_field_gate")),
"source_candidate": _serialize_source_candidate_projection(task),
# 工作台据此隐藏冻结按钮;是否可冻结仍由写路径重算,不能信任前端状态。
"order_snapshot_id": task.order_snapshot_id,
"order_data_version": int(task.order_data_version or 1),
"field_conflicts": _serialize_open_field_conflicts(task),
**_fulfillment_timeline(task),
"events": [
{
"event_type": e.event_type,
@@ -0,0 +1,143 @@
"""
services/shipping_notice/reservation_service.py
用途:管理冻结订单预约单的注册、库存核验轮次和滚动制单占用。
依赖:ShippingOrderSnapshot、履约 ORM、统一 AppError。
逻辑:每轮核验追加记录;只有本轮全部满足的预约单可被同一事务选择并绑定到一个新 Artifact。
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingExportArtifact,
ShippingExportArtifactLine,
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingOrderSnapshot,
ShippingReservation,
ShippingTask,
)
def _decimal(value: Any) -> Decimal:
"""将库存与需求数量转为 Decimal;零或负数均不是可履约数量。"""
try:
result = Decimal(str(value))
except (InvalidOperation, TypeError, ValueError) as exc:
raise ValidationError('Reservation quantity is invalid', code='SHIPPING.RESERVATION_INVALID') from exc
if result <= 0:
raise ValidationError('Reservation quantity must be positive', code='SHIPPING.RESERVATION_INVALID')
return result
def ensure_task_reservations(task: ShippingTask) -> list[ShippingReservation]:
"""由冻结 Snapshot 注册预约单;历史上传或占用记录不允许被新快照静默覆盖。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
if snapshot is None:
raise ValidationError('Frozen order snapshot is required', code='SHIPPING.ORDER_SNAPSHOT_REQUIRED')
registered: list[ShippingReservation] = []
for line in snapshot.lines:
reservation_id = str(line.reservation_id or '').strip()
part_number = str(line.part_number or '').strip()
if not reservation_id or not part_number or line.qty is None:
raise ValidationError('Reservation id, part number and quantity are required', code='SHIPPING.RESERVATION_INVALID')
row = ShippingReservation.query.filter_by(reservation_id=reservation_id, part_number=part_number).one_or_none()
if row is None:
row = ShippingReservation(
task_id=task.id, snapshot_line_id=line.id, reservation_id=reservation_id,
part_number=part_number, required_qty=_decimal(line.qty), status='pending',
)
db.session.add(row)
elif row.task_id != task.id or row.snapshot_line_id != line.id:
raise ConflictError(
'Reservation is already registered by another order version',
code='SHIPPING.RESERVATION_ALREADY_REGISTERED',
)
registered.append(row)
db.session.flush()
return registered
def record_inventory_verification(
task: ShippingTask, *, inventory_snapshot_id: int | None, source_config_version: str | None,
line_results: list[dict[str, Any]],
) -> ShippingInventoryVerification:
"""把一轮库存匹配追加为核验事实,并仅将完整满足的 pending 预约单标记 available。"""
reservations = ensure_task_reservations(task)
by_key = {(row.reservation_id, row.part_number): row for row in reservations}
verification = ShippingInventoryVerification(
task_id=task.id, inventory_snapshot_id=inventory_snapshot_id,
source_config_version=source_config_version, status='completed', result_json={'line_count': len(line_results)},
)
db.session.add(verification)
db.session.flush()
available_count = 0
for item in line_results:
reservation_id = str(item.get('reservation_id') or '').strip()
part_number = str(item.get('part_number') or '').strip()
reservation = by_key.get((reservation_id, part_number))
if reservation is None:
raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
required = _decimal(item.get('required_qty'))
available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0')
status = 'available' if available >= required else 'shortage'
db.session.add(ShippingInventoryVerificationLine(
verification_id=verification.id, reservation_id=reservation.id, required_qty=required,
available_qty=available, status=status, detail_json={'line_status': item.get('line_status')},
))
if reservation.status == 'pending' and status == 'available':
reservation.status = 'available'
available_count += 1
elif reservation.status == 'available' and status == 'shortage':
reservation.status = 'pending'
verification.result_json = {'line_count': len(line_results), 'available_count': available_count}
db.session.flush()
return verification
def reserve_available_for_artifact(task: ShippingTask, *, artifact: ShippingExportArtifact, verification: ShippingInventoryVerification) -> list[ShippingReservation]:
"""锁定本轮全部 available 预约单并写入 Artifact 行;并发第二次制单必须失败。"""
rows = (
ShippingReservation.query.filter_by(task_id=task.id, status='available')
.with_for_update().all()
)
if not rows:
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
verification_lines = {item.reservation_id: item for item in verification.lines if item.status == 'available'}
selected = [item for item in rows if item.id in verification_lines]
if not selected:
raise ConflictError('Current verification has no available reservations', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
for reservation in selected:
reservation.status = 'artifact_reserved'
reservation.current_artifact_id = artifact.id
db.session.add(ShippingExportArtifactLine(
artifact_id=artifact.id, reservation_id=reservation.id,
verification_line_id=verification_lines[reservation.id].id,
))
db.session.flush()
return selected
def current_available_snapshot_line_ids(task: ShippingTask) -> tuple[ShippingInventoryVerification, set[int]]:
"""取得最新核验中仍可用预约单的快照行;导出只能写入这个完整满足集合。"""
verification = (
ShippingInventoryVerification.query.filter_by(task_id=task.id, status='completed')
.order_by(ShippingInventoryVerification.id.desc()).first()
)
if verification is None:
raise ConflictError('No inventory verification is available', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
reservation_ids = {line.reservation_id for line in verification.lines if line.status == 'available'}
reservations = ShippingReservation.query.filter(
ShippingReservation.task_id == task.id,
ShippingReservation.id.in_(reservation_ids),
ShippingReservation.status == 'available',
).all() if reservation_ids else []
line_ids = {item.snapshot_line_id for item in reservations}
if not line_ids:
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
return verification, line_ids
@@ -18,13 +18,14 @@ from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
from app import db
from app.models import ShippingOrderExtraction, ShippingOrderLine, ShippingTask
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
CP_CUSTOMER_REVIEW,
CP_PARSE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
@@ -56,11 +57,14 @@ from app.services.shipping_notice.constants import (
def _task_has_dynamic_order_lines(task: ShippingTask) -> bool:
"""仅在当前已接受 Extraction 含行 FieldValue 时开放库存匹配检查点。"""
try:
return bool(task_line_purpose_values(task))
except ValueError:
"""判断当前已接受 Extraction 是否有订单行,用于在冻结前显示唯一的冻结入口。"""
extraction_id = task.current_order_extraction_id
if not extraction_id:
return False
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
if extraction is None or extraction.status != "accepted":
return False
return ShippingOrderLine.query.filter_by(extraction_id=extraction.id).first() is not None
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
@@ -94,6 +98,11 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
"message": "匹配库存",
"variant": "primary",
},
"freeze_order": {
"label": "冻结订单",
"message": "冻结已复核订单",
"variant": "primary",
},
}
# checkpoint id → default human option ids (HTTP / Dify before task reload)
@@ -106,6 +115,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
"confirm_inventory_source",
"retry_resolve_inventory_source",
),
CP_ORDER_FREEZE: ("freeze_order",),
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
RS_SHORTAGE_REVIEW: ("retry_rpa", "rematch", "reject"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
@@ -275,7 +285,14 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
human_options=list(CHECKPOINT_REGISTRY[CP_CUSTOMER_REVIEW]),
)
# [STEP 3] 客户确认后,才进入库存和履约节点。
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结动作始终在 Chat Turn 执行。
if not task.order_snapshot_id and _task_has_dynamic_order_lines(task):
return TaskUiState(
checkpoint=CP_ORDER_FREEZE,
human_options=list(CHECKPOINT_REGISTRY[CP_ORDER_FREEZE]),
)
# [STEP 4] 客户确认并冻结订单后,才进入库存和履约节点。
if reason == PH_RPA_EXHAUSTED:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
@@ -13,7 +13,7 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingTask, ShippingTaskFieldConflict
from app.models import ShippingOrderReviewEvent, ShippingTask, ShippingTaskFieldConflict
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
@@ -121,6 +121,7 @@ def resolve_field_conflict(
expected_conflict_version: int | None = None,
expected_order_data_version: int | None = None,
resolved_by_id: int | None = None,
evidence_ref: str | None = None,
reason: str | None = None,
idempotency_key: str | None = None,
) -> dict[str, Any]:
@@ -133,7 +134,11 @@ def resolve_field_conflict(
Args:
resolution: keep_existing | take_incoming | custom
expected_conflict_version / expected_order_data_version: 乐观锁;不匹配抛 409。
resolved_by_id / evidence_ref / reason: 人工纠错审计必填,禁止无证据回写。
"""
from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable
assert_task_order_is_editable(task)
conflict = (
ShippingTaskFieldConflict.query.filter_by(id=int(conflict_id), task_id=int(task.id))
.first()
@@ -201,13 +206,30 @@ def resolve_field_conflict(
task=task, position=int(conflict.position), field_code=conflict.field_name, value=value,
)
clean_evidence_ref = str(evidence_ref or '').strip()
clean_reason = str(reason or '').strip()
if not resolved_by_id or not clean_evidence_ref or not clean_reason:
raise ValidationError('Field conflict resolution requires operator, evidence and reason', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
conflict.status = 'resolved'
conflict.resolved_value = value
conflict.resolved_by_id = resolved_by_id
conflict.resolved_at = datetime.utcnow()
conflict.resolution_reason = str(reason or '').strip() or None
conflict.resolution_reason = clean_reason
conflict.conflict_version = int(conflict.conflict_version or 1) + 1
conflict.updated_at = datetime.utcnow()
db.session.add(ShippingOrderReviewEvent(
task_id=task.id,
extraction_id=task.current_order_extraction_id,
scope='line' if conflict.position is not None else 'header',
line_position=conflict.position,
field_code=conflict.field_name,
old_value_json=conflict.existing_value,
new_value_json=value,
evidence_ref=clean_evidence_ref,
reason=clean_reason,
reviewed_by_id=int(resolved_by_id),
))
remaining = list_open_field_conflicts(task)
issues = task_reservation_gate_issues(task)
@@ -263,6 +285,7 @@ def resolve_field_conflict(
'before_value': conflict.existing_value,
'after_value': value,
'reason': conflict.resolution_reason,
'evidence_ref': clean_evidence_ref,
'resolved_by_id': resolved_by_id,
},
)
@@ -20,6 +20,7 @@ from app.models import (
ShippingOrderLine,
ShippingTask,
)
from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable
def current_line_field_values(task: ShippingTask) -> list[dict[str, Any]]:
@@ -126,6 +127,7 @@ def bump_order_data_version(task: ShippingTask) -> None:
def retire_current_order_extraction(task: ShippingTask) -> None:
"""废弃当前订单真相版本并解除任务指针,供整单重新解析或重新上传使用。"""
assert_task_order_is_editable(task)
extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
if task.current_order_extraction_id is not None else None
@@ -186,6 +188,7 @@ def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
def replace_current_line_field_value(*, task: ShippingTask, position: int, field_code: str, value: Any) -> None:
"""将人工确认值写入当前 accepted Extraction 的稳定字段,缺少值投影时补建 FieldValue。"""
assert_task_order_is_editable(task)
extraction = _current_extraction(task)
config = next(
(
@@ -229,6 +232,7 @@ def replace_current_line_field_value(*, task: ShippingTask, position: int, field
def replace_current_header_field_value(*, task: ShippingTask, field_code: str, value: Any) -> None:
"""将人工确认值写入当前 accepted Extraction 的单头 FieldValue。"""
assert_task_order_is_editable(task)
extraction = _current_extraction(task)
config = next(
(
@@ -265,6 +269,7 @@ def replace_current_header_field_value(*, task: ShippingTask, field_code: str, v
def replace_current_line_fields(*, task: ShippingTask, lines: list[dict[str, Any]]) -> None:
"""以人工确认的完整行集创建新的已接受 Extraction,供新增或删除订单行使用。"""
assert_task_order_is_editable(task)
extraction = _current_extraction(task)
configs = [
item for item in (extraction.schema_version.definition_json or {}).get('fields') or []
@@ -63,6 +63,8 @@ from app.services.shipping_notice.tool_common import (
log_task_event,
set_task_step_progress,
)
from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable
from app.models import ShippingOrderReviewEvent
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
EDITABLE_NOTICE_LINE_FIELDS = frozenset({
@@ -663,8 +665,21 @@ def _commit_notice_edit(
after_header: dict[str, Any] | None = None,
before_lines: list[dict[str, Any]] | None = None,
after_lines: list[dict[str, Any]] | None = None,
review_context: dict[str, Any] | None = None,
idempotency_key: str | None = None,
) -> dict[str, Any]:
"""提交冻结前的人工复核,记录证据审计并使旧库存/导出派生结果失效。"""
assert_task_order_is_editable(task)
reviewed_by_id = None
evidence_ref = ''
reason = ''
# 调用方已在入口校验该三项;此处集中写事件,以免各编辑路径漏审计。
if isinstance(review_context, dict):
reviewed_by_id = review_context.get('reviewed_by_id')
evidence_ref = str(review_context.get('evidence_ref') or '')
reason = str(review_context.get('reason') or '')
if not reviewed_by_id or not evidence_ref or not reason:
raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
step_payload = dict(task.step_payload_json or {})
validation_issues = task_reservation_gate_issues(task)
@@ -709,6 +724,32 @@ def _commit_notice_edit(
"order_data_version": task.order_data_version,
},
)
changes: list[tuple[str, str, int | None, Any, Any]] = []
for field, before in (before_header or {}).items():
after = (after_header or {}).get(field)
if before != after:
changes.append(('header', field, None, before, after))
before_line_rows = before_lines or []
after_line_rows = after_lines or []
for position in range(max(len(before_line_rows), len(after_line_rows))):
before = before_line_rows[position] if position < len(before_line_rows) else {}
after = after_line_rows[position] if position < len(after_line_rows) else {}
for field in sorted(set(before) | set(after)):
if before.get(field) != after.get(field):
changes.append(('line', field, position, before.get(field), after.get(field)))
for scope, field_code, position, old_value, new_value in changes:
db.session.add(ShippingOrderReviewEvent(
task_id=task.id,
extraction_id=task.current_order_extraction_id,
scope=scope,
line_position=position,
field_code=field_code,
old_value_json=old_value,
new_value_json=new_value,
evidence_ref=evidence_ref,
reason=reason,
reviewed_by_id=int(reviewed_by_id),
))
sync_batch_after_task_change(task)
db.session.commit()
return tool_response(
@@ -719,6 +760,25 @@ def _commit_notice_edit(
)
def _prepare_review_context(task: ShippingTask, payload: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
"""校验冻结前纠错的操作者、证据和原因,禁止 Dify 或无证据路径直接改订单。"""
assert_task_order_is_editable(task)
if str(payload.get('event_source') or '').strip() != 'workspace_api':
return None, tool_response(
status='failed', task=task, message='订单纠错只能由工作台人工复核提交',
data={'error_code': 'SHIPPING.ORDER_REVIEW_WORKSPACE_REQUIRED'},
)
try:
actor_id = int(payload.get('reviewed_by_id'))
except (TypeError, ValueError):
return None, tool_response(status='failed', task=task, message='缺少复核人员', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
evidence_ref = str(payload.get('evidence_ref') or '').strip()
reason = str(payload.get('reason') or payload.get('comment') or '').strip()
if not evidence_ref or not reason:
return None, tool_response(status='failed', task=task, message='人工纠错必须提供证据和原因', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
return {'reviewed_by_id': actor_id, 'evidence_ref': evidence_ref, 'reason': reason}, None
def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
"""
更新发货通知单头字段,并将任务重新打回解析确认阶段。
@@ -738,6 +798,9 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
review_context, review_error = _prepare_review_context(task, payload)
if review_error is not None:
return review_error
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
@@ -773,6 +836,7 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
comment=str(payload.get("comment") or "").strip(),
before_header=before_header,
after_header=_notice_header_snapshot(task),
review_context=review_context,
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -796,6 +860,9 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
review_context, review_error = _prepare_review_context(task, payload)
if review_error is not None:
return review_error
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
@@ -847,6 +914,7 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=after_lines,
review_context=review_context,
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -870,6 +938,9 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
review_context, review_error = _prepare_review_context(task, payload)
if review_error is not None:
return review_error
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
@@ -887,6 +958,7 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=after_lines,
review_context=review_context,
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -910,6 +982,9 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
replay = _notice_edit_idempotency_replay(task, payload)
if replay is not None:
return replay
review_context, review_error = _prepare_review_context(task, payload)
if review_error is not None:
return review_error
version_error = _assert_order_data_version(task, payload)
if version_error is not None:
return version_error
@@ -933,6 +1008,7 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=after_lines,
review_context=review_context,
idempotency_key=str(payload.get("idempotency_key") or "").strip() or None,
)
@@ -17,6 +17,7 @@ from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
@@ -82,6 +83,7 @@ _BLOCKED_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
RS_SHORTAGE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_REQ,
@@ -177,6 +179,7 @@ _PARSE_STAGE_CHECKPOINTS = {
CP_PARSE_REVIEW,
CP_RSV_REQ,
CP_INVENTORY_SOURCE_REVIEW,
CP_ORDER_FREEZE,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
}
@@ -280,6 +283,7 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
CP_ORDER_FREEZE: "订单已复核,冻结订单后才能进入库存履约。",
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
CP_READY_MATCH: "库存已就绪,可以继续执行匹配。",
CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。",
@@ -0,0 +1,167 @@
"""
services/shipping_notice/upload_attempt_service.py
用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工回执证据。
依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、FileAsset、任务状态机。
逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,Task 字段仅保留聚合投影。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingExportArtifact,
ShippingExportArtifactLine,
ShippingReservation,
ShippingTask,
ShippingUploadAttempt,
)
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
def current_upload_artifact(task: ShippingTask, artifact_id: int | None = None) -> ShippingExportArtifact:
"""返回本次上传目标 Artifact;调用方不能借 Task 旧文件指针绕过分轮履约。"""
query = ShippingExportArtifact.query.filter_by(task_id=task.id)
if artifact_id is not None:
artifact = query.filter_by(id=artifact_id).one_or_none()
else:
artifact = query.filter(ShippingExportArtifact.status.in_({'ready', 'uploading'})).order_by(
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
).first()
if artifact is None:
raise ValidationError('No uploadable export artifact', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED')
if artifact.status == 'uploaded':
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
if artifact.status not in {'ready', 'uploading'}:
raise ConflictError('Artifact is not uploadable', code='SHIPPING.UPLOAD_ARTIFACT_INVALID')
return artifact
def start_rpa_attempt(task: ShippingTask, *, artifact_id: int | None = None, idempotency_key: str | None = None) -> ShippingUploadAttempt:
"""为一个未完成 Artifact 创建 RPA Attempt;重复 idempotency key 返回同一未完成尝试。"""
artifact = current_upload_artifact(task, artifact_id)
key = str(idempotency_key or '').strip() or f'rpa:{artifact.id}:{uuid.uuid4().hex}'
existing = ShippingUploadAttempt.query.filter_by(idempotency_key=key).one_or_none()
if existing is not None:
if existing.artifact_id != artifact.id:
raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT')
return existing
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1)
attempt = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key,
status='running', started_at=datetime.utcnow(),
)
artifact.status = 'uploading'
db.session.add(attempt)
db.session.flush()
return attempt
def _aggregate_task_upload_status(task: ShippingTask) -> None:
"""从预约单真相刷新兼容 Task 投影,不能由单个旧回调直接覆盖。"""
reservations = ShippingReservation.query.filter_by(task_id=task.id).all()
if reservations and all(item.status == 'uploaded' for item in reservations):
task.upload_status = 'uploaded'
task.upload_finished_at = datetime.utcnow()
task.process_status = 'uploaded'
elif any(item.status == 'uploaded' for item in reservations):
task.upload_status = 'partial'
task.process_status = 'waiting_upload'
else:
task.upload_status = 'pending'
def complete_attempt(
attempt: ShippingUploadAttempt, *, success: bool, callback_id: str,
freight_ref_no: str | None = None, error_message: str | None = None,
) -> ShippingUploadAttempt:
"""幂等落库 RPA 回调;失败或过期 Attempt 绝不能覆盖已经成功的 Artifact。"""
callback = str(callback_id or '').strip()
if not callback:
raise ValidationError('callback_id is required', code='SHIPPING.UPLOAD_CALLBACK_REQUIRED')
existing = ShippingUploadAttempt.query.filter_by(callback_id=callback).one_or_none()
if existing is not None:
if existing.id != attempt.id:
raise ConflictError('Callback id belongs to another attempt', code='SHIPPING.UPLOAD_CALLBACK_CONFLICT')
return existing
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
if artifact is None:
raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED')
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
attempt.callback_id = callback
attempt.finished_at = datetime.utcnow()
task = db.session.get(ShippingTask, artifact.task_id)
if success:
attempt.status = 'succeeded'
attempt.freight_ref_no = str(freight_ref_no or '').strip() or None
artifact.status = 'uploaded'
reservation_ids = [row.reservation_id for row in ShippingExportArtifactLine.query.filter_by(artifact_id=artifact.id).all()]
ShippingReservation.query.filter(ShippingReservation.id.in_(reservation_ids)).update(
{'status': 'uploaded'}, synchronize_session=False,
)
# 批量更新绕开 ORM identity map;立即失效以确保同一事务的 Task 聚合读取最新预约单状态。
db.session.expire_all()
if task is not None:
task.freight_ref_no = attempt.freight_ref_no
_aggregate_task_upload_status(task)
else:
attempt.status = 'failed'
message = str(error_message or 'RPA upload failed')[:500]
attempt.error_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED'
attempt.error_message = message
artifact.status = 'ready'
if task is not None:
task.upload_status = 'failed'
db.session.flush()
return attempt
def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt:
"""登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。"""
asset_no = str(evidence_asset_no or '').strip()
if not asset_no:
raise ValidationError('Manual upload evidence is required', code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED')
artifact = current_upload_artifact(task, artifact_id)
asset = get_asset_for_user(asset_no, operator_id)
if asset.upload_status != 'ready' or asset.deleted_at is not None:
raise ValidationError('Manual upload evidence is unavailable', code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED')
attempt = ShippingUploadAttempt(
artifact_id=artifact.id,
attempt_no=ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() + 1,
mode='manual', idempotency_key=f'manual:{artifact.id}:{uuid.uuid4().hex}',
status='running', started_at=datetime.utcnow(), evidence_asset_id=asset.id, operator_id=operator_id,
)
db.session.add(attempt)
db.session.flush()
mark_asset_referenced(asset)
return complete_attempt(
attempt, success=True, callback_id=f'manual:{attempt.id}', freight_ref_no=freight_ref_no,
)
def void_rejected_artifact(task: ShippingTask, *, artifact_id: int, operator_id: int, reason: str) -> ShippingExportArtifact:
"""仅在货代明确拒绝且有操作者授权时作废 Artifact,并释放其未上传预约单以便后续核验。"""
if not operator_id or not str(reason or '').strip():
raise ValidationError('Operator and rejection reason are required', code='SHIPPING.ARTIFACT_VOID_AUTH_REQUIRED')
artifact = current_upload_artifact(task, artifact_id)
attempts = ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).all()
if not any(item.status == 'failed' and item.error_code == 'FREIGHT_REJECTED' for item in attempts):
raise ConflictError('Artifact may only be voided after explicit freight rejection', code='SHIPPING.ARTIFACT_VOID_NOT_ALLOWED')
artifact.status = 'superseded'
reservation_ids = [row.reservation_id for row in ShippingExportArtifactLine.query.filter_by(artifact_id=artifact.id).all()]
ShippingReservation.query.filter(
ShippingReservation.id.in_(reservation_ids), ShippingReservation.status == 'artifact_reserved',
).update({'status': 'pending', 'current_artifact_id': None}, synchronize_session=False)
db.session.expire_all()
db.session.flush()
return artifact
@@ -0,0 +1,172 @@
"""add frozen shipping order snapshots
Revision ID: 019fa1b2c3d4
Revises: a77f8091a2c3
Create Date: 2026-07-22 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
import uuid
revision = '019fa1b2c3d4'
down_revision = 'a77f8091a2c3'
branch_labels = None
depends_on = None
def upgrade():
_converge_order_field_catalog()
op.create_table(
'shipping_order_snapshots',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.Column('extraction_id', sa.Integer(), nullable=False),
sa.Column('schema_version_id', sa.Integer(), nullable=False),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.Column('customer_short_code_snapshot', sa.String(length=32), nullable=True),
sa.Column('order_data_version', sa.Integer(), nullable=False),
sa.Column('rule_versions_json', sa.JSON(), nullable=False),
sa.Column('header_values_json', sa.JSON(), nullable=False),
sa.Column('po_number', sa.String(length=255), nullable=True),
sa.Column('customer_code', sa.String(length=255), nullable=True),
sa.Column('customer_name', sa.Text(), nullable=True),
sa.Column('bill_to_customer', sa.Text(), nullable=True),
sa.Column('bill_to_address', sa.Text(), nullable=True),
sa.Column('ship_to_customer', sa.Text(), nullable=True),
sa.Column('ship_to_address', sa.Text(), nullable=True),
sa.Column('destination', sa.Text(), nullable=True),
sa.Column('currency', sa.String(length=16), nullable=True),
sa.Column('incoterm', sa.String(length=64), nullable=True),
sa.Column('required_date', sa.Date(), nullable=True),
sa.Column('order_date', sa.Date(), nullable=True),
sa.Column('payment_term', sa.String(length=255), nullable=True),
sa.Column('frozen_by_id', sa.Integer(), nullable=True),
sa.Column('frozen_at', sa.DateTime(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['customer_id'], ['shipping_customers.id']),
sa.ForeignKeyConstraint(['extraction_id'], ['shipping_order_extractions.id']),
sa.ForeignKeyConstraint(['frozen_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['schema_version_id'], ['shipping_order_schema_versions.id']),
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('extraction_id', name='uq_shipping_order_snapshots_extraction'),
)
op.create_index('ix_shipping_order_snapshots_customer_created', 'shipping_order_snapshots', ['customer_id', 'created_at'])
op.create_index('ix_shipping_order_snapshots_task_id', 'shipping_order_snapshots', ['task_id'])
op.create_table(
'shipping_order_snapshot_lines',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('snapshot_id', sa.Integer(), nullable=False),
sa.Column('position', sa.Integer(), nullable=False),
sa.Column('line_no', sa.String(length=64), nullable=True),
sa.Column('part_number', sa.String(length=255), nullable=True),
sa.Column('customer_part_number', sa.String(length=255), nullable=True),
sa.Column('aws_part_number', sa.String(length=255), nullable=True),
sa.Column('reservation_id', sa.String(length=64), nullable=True),
sa.Column('qty', sa.Numeric(precision=24, scale=8), nullable=True),
sa.Column('uom', sa.String(length=64), nullable=True),
sa.Column('unit_price', sa.Numeric(precision=24, scale=8), nullable=True),
sa.Column('amount', sa.Numeric(precision=24, scale=8), nullable=True),
sa.Column('warehouse', sa.String(length=255), nullable=True),
sa.Column('inventory_source_hint', sa.String(length=255), nullable=True),
sa.Column('remark', sa.Text(), nullable=True),
sa.Column('field_values_json', sa.JSON(), nullable=False),
sa.CheckConstraint('qty IS NULL OR qty > 0', name='ck_shipping_order_snapshot_lines_positive_qty'),
sa.ForeignKeyConstraint(['snapshot_id'], ['shipping_order_snapshots.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('snapshot_id', 'position', name='uq_shipping_order_snapshot_lines_position'),
)
op.create_table(
'shipping_order_review_events',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('task_id', sa.Integer(), nullable=False),
sa.Column('extraction_id', sa.Integer(), nullable=False),
sa.Column('snapshot_id', sa.Integer(), nullable=True),
sa.Column('scope', sa.String(length=16), nullable=False),
sa.Column('line_position', sa.Integer(), nullable=True),
sa.Column('field_code', sa.String(length=64), nullable=False),
sa.Column('old_value_json', sa.JSON(), nullable=True),
sa.Column('new_value_json', sa.JSON(), nullable=True),
sa.Column('evidence_ref', sa.String(length=512), nullable=False),
sa.Column('reason', sa.Text(), nullable=False),
sa.Column('reviewed_by_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_review_events_scope'),
sa.ForeignKeyConstraint(['extraction_id'], ['shipping_order_extractions.id']),
sa.ForeignKeyConstraint(['reviewed_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['snapshot_id'], ['shipping_order_snapshots.id'], ondelete='CASCADE'),
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_shipping_order_review_events_task_created', 'shipping_order_review_events', ['task_id', 'created_at'])
# batch_alter_table keeps the migration executable in the SQLite migration tests.
with op.batch_alter_table('shipping_tasks') as batch:
batch.add_column(sa.Column('order_snapshot_id', sa.Integer(), nullable=True))
batch.create_foreign_key('fk_shipping_tasks_order_snapshot_id', 'shipping_order_snapshots', ['order_snapshot_id'], ['id'])
batch.create_index('ix_shipping_tasks_order_snapshot_id', ['order_snapshot_id'], unique=True)
def _converge_order_field_catalog() -> None:
"""补齐预置核心字段;保留历史和新增扩展字段。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
if 'shipping_order_schemas' not in inspector.get_table_names():
return
schema = bind.execute(sa.text("SELECT id FROM shipping_order_schemas WHERE schema_code = 'SHIPPING_ORDER'")).mappings().first()
if not schema:
return
header = (
'po_number', 'customer_code', 'customer_name', 'bill_to_customer', 'bill_to_address',
'ship_to_customer', 'ship_to_address', 'destination', 'currency', 'incoterm', 'required_date',
'order_date', 'payment_term',
)
line = (
'line_no', 'part_number', 'customer_part_number', 'aws_part_number', 'reservation_id', 'qty', 'uom',
'unit_price', 'amount', 'warehouse', 'inventory_source_hint', 'remark',
)
specs = {
**{code: ('header', 'date' if code in {'required_date', 'order_date'} else 'string') for code in header},
**{code: ('line', 'decimal' if code in {'qty', 'unit_price', 'amount'} else 'string') for code in line},
}
rows = bind.execute(
sa.text("SELECT id, field_code FROM shipping_order_fields WHERE schema_id = :schema_id"),
{'schema_id': schema['id']},
).mappings().all()
existing = {str(row['field_code']): str(row['id']) for row in rows}
for code, (scope, value_type) in specs.items():
if code in existing:
bind.execute(sa.text("""
UPDATE shipping_order_fields
SET scope = :scope, value_type = :value_type,
field_category = :field_category, collection_mode = 'llm_extraction', status = 'active'
WHERE id = :id
"""), {
'id': existing[code], 'scope': scope, 'value_type': value_type,
'field_category': 'order_header' if scope == 'header' else 'order_line',
})
continue
bind.execute(sa.text("""
INSERT INTO shipping_order_fields
(id, schema_id, field_code, scope, value_type, field_category, collection_mode, display_sequence, status, published_once, created_at, updated_at)
VALUES
(:id, :schema_id, :field_code, :scope, :value_type, :field_category, 'llm_extraction', :sequence, 'active', false, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
"""), {
'id': str(uuid.uuid4()), 'schema_id': schema['id'], 'field_code': code, 'scope': scope,
'value_type': value_type, 'field_category': 'order_header' if scope == 'header' else 'order_line',
'sequence': list(specs).index(code) + 1,
})
def downgrade():
with op.batch_alter_table('shipping_tasks') as batch:
batch.drop_index('ix_shipping_tasks_order_snapshot_id')
batch.drop_constraint('fk_shipping_tasks_order_snapshot_id', type_='foreignkey')
batch.drop_column('order_snapshot_id')
op.drop_index('ix_shipping_order_review_events_task_created', table_name='shipping_order_review_events')
op.drop_table('shipping_order_review_events')
op.drop_table('shipping_order_snapshot_lines')
op.drop_index('ix_shipping_order_snapshots_task_id', table_name='shipping_order_snapshots')
op.drop_index('ix_shipping_order_snapshots_customer_created', table_name='shipping_order_snapshots')
op.drop_table('shipping_order_snapshots')
@@ -0,0 +1,82 @@
"""add shipping document profile blind-test quality gates
Revision ID: 020a1b2c3d4e
Revises: 019fa1b2c3d4
Create Date: 2026-07-22 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '020a1b2c3d4e'
down_revision = '019fa1b2c3d4'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""建立模板盲测集、真值样本和不可变执行结果,作为自动建单资格凭证。"""
op.create_table(
'shipping_document_profile_test_suites',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('profile_id', sa.Integer(), nullable=False),
sa.Column('profile_checksum', sa.String(length=64), nullable=False),
sa.Column('status', sa.String(length=16), nullable=False, server_default='draft'),
sa.Column('approved_by_id', sa.Integer(), nullable=True),
sa.Column('approved_at', sa.DateTime(), nullable=True),
sa.Column('created_by_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("status IN ('draft', 'approved', 'superseded')", name='ck_shipping_document_profile_test_suites_status'),
sa.ForeignKeyConstraint(['approved_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['created_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id']),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('profile_id', name='uq_shipping_document_profile_test_suites_profile'),
)
op.create_index('ix_shipping_document_profile_test_suites_profile_id', 'shipping_document_profile_test_suites', ['profile_id'])
op.create_table(
'shipping_document_profile_test_samples',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('suite_id', sa.Integer(), nullable=False),
sa.Column('document_id', sa.Integer(), nullable=False),
sa.Column('table_id', sa.String(length=128), nullable=False),
sa.Column('expected_rows_json', sa.JSON(), nullable=False),
sa.Column('created_by_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['created_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id']),
sa.ForeignKeyConstraint(['suite_id'], ['shipping_document_profile_test_suites.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('suite_id', 'document_id', 'table_id', name='uq_shipping_document_profile_test_samples_source'),
)
op.create_table(
'shipping_document_profile_test_runs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('suite_id', sa.Integer(), nullable=False),
sa.Column('profile_checksum', sa.String(length=64), nullable=False),
sa.Column('status', sa.String(length=16), nullable=False),
sa.Column('sample_count', sa.Integer(), nullable=False),
sa.Column('passed_sample_count', sa.Integer(), nullable=False),
sa.Column('failure_codes_json', sa.JSON(), nullable=False),
sa.Column('executed_by_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("status IN ('passed', 'failed')", name='ck_shipping_document_profile_test_runs_status'),
sa.ForeignKeyConstraint(['executed_by_id'], ['users.id']),
sa.ForeignKeyConstraint(['suite_id'], ['shipping_document_profile_test_suites.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'),
)
op.create_index(
'ix_shipping_document_profile_test_runs_suite_created',
'shipping_document_profile_test_runs', ['suite_id', 'created_at'],
)
def downgrade() -> None:
"""按依赖逆序移除盲测资格表。"""
op.drop_index('ix_shipping_document_profile_test_runs_suite_created', table_name='shipping_document_profile_test_runs')
op.drop_table('shipping_document_profile_test_runs')
op.drop_table('shipping_document_profile_test_samples')
op.drop_index('ix_shipping_document_profile_test_suites_profile_id', table_name='shipping_document_profile_test_suites')
op.drop_table('shipping_document_profile_test_suites')
@@ -0,0 +1,35 @@
"""add order customer match fingerprint audit
Revision ID: 021a2b3c4d5e
Revises: 020a1b2c3d4e
Create Date: 2026-07-22 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '021a2b3c4d5e'
down_revision = '020a1b2c3d4e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""为订单客户匹配增加版本化指纹与人工确认理由,保留既有原文和候选快照。"""
with op.batch_alter_table('shipping_order_customer_matches') as batch:
batch.add_column(sa.Column('identity_fingerprint', sa.String(length=64), nullable=True))
batch.add_column(sa.Column('identity_rule_version', sa.String(length=32), nullable=True))
batch.add_column(sa.Column('identity_components_json', sa.JSON(), nullable=False, server_default=sa.text("'{}'")))
batch.add_column(sa.Column('confirmation_reason', sa.Text(), nullable=True))
batch.create_index('ix_shipping_order_customer_matches_identity_fingerprint', ['identity_fingerprint'])
def downgrade() -> None:
"""移除阶段 3 的订单客户指纹审计列。"""
with op.batch_alter_table('shipping_order_customer_matches') as batch:
batch.drop_index('ix_shipping_order_customer_matches_identity_fingerprint')
batch.drop_column('confirmation_reason')
batch.drop_column('identity_components_json')
batch.drop_column('identity_rule_version')
batch.drop_column('identity_fingerprint')
@@ -0,0 +1,65 @@
"""add rolling shipment fulfillment facts
Revision ID: 022a3b4c5d6e
Revises: 021a2b3c4d5e
Create Date: 2026-07-22 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '022a3b4c5d6e'
down_revision = '021a2b3c4d5e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""建立预约单注册、库存核验轮次和 Artifact 归属,支持滚动制单。"""
op.create_table(
'shipping_reservations',
sa.Column('id', sa.Integer(), nullable=False), sa.Column('task_id', sa.Integer(), nullable=False),
sa.Column('snapshot_line_id', sa.Integer(), nullable=False), sa.Column('reservation_id', sa.String(64), nullable=False),
sa.Column('part_number', sa.String(255), nullable=False), sa.Column('required_qty', sa.Numeric(24, 8), nullable=False),
sa.Column('status', sa.String(32), nullable=False, server_default='pending'), sa.Column('current_artifact_id', sa.Integer(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("status IN ('pending', 'available', 'artifact_reserved', 'uploaded', 'external_change_required')", name='ck_shipping_reservations_status'),
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']), sa.ForeignKeyConstraint(['snapshot_line_id'], ['shipping_order_snapshot_lines.id']),
sa.ForeignKeyConstraint(['current_artifact_id'], ['shipping_export_artifacts.id']), sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('reservation_id', 'part_number', name='uq_shipping_reservations_reservation_part'),
)
op.create_index('ix_shipping_reservations_task_status', 'shipping_reservations', ['task_id', 'status'])
op.create_table(
'shipping_inventory_verifications',
sa.Column('id', sa.Integer(), nullable=False), sa.Column('task_id', sa.Integer(), nullable=False),
sa.Column('inventory_snapshot_id', sa.Integer(), nullable=True), sa.Column('source_config_version', sa.String(64), nullable=True),
sa.Column('status', sa.String(16), nullable=False, server_default='completed'), sa.Column('result_json', sa.JSON(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("status IN ('completed', 'expired', 'superseded')", name='ck_shipping_inventory_verifications_status'),
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']), sa.ForeignKeyConstraint(['inventory_snapshot_id'], ['shipping_inventory_files.id']), sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_shipping_inventory_verifications_task_created', 'shipping_inventory_verifications', ['task_id', 'created_at'])
op.create_table(
'shipping_inventory_verification_lines',
sa.Column('id', sa.Integer(), nullable=False), sa.Column('verification_id', sa.Integer(), nullable=False), sa.Column('reservation_id', sa.Integer(), nullable=False),
sa.Column('required_qty', sa.Numeric(24, 8), nullable=False), sa.Column('available_qty', sa.Numeric(24, 8), nullable=False), sa.Column('status', sa.String(16), nullable=False), sa.Column('detail_json', sa.JSON(), nullable=False),
sa.CheckConstraint("status IN ('available', 'shortage', 'invalid')", name='ck_shipping_inventory_verification_lines_status'),
sa.ForeignKeyConstraint(['verification_id'], ['shipping_inventory_verifications.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['reservation_id'], ['shipping_reservations.id']), sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('verification_id', 'reservation_id', name='uq_shipping_inventory_verification_lines_reservation'),
)
op.create_table(
'shipping_export_artifact_lines',
sa.Column('id', sa.Integer(), nullable=False), sa.Column('artifact_id', sa.Integer(), nullable=False), sa.Column('reservation_id', sa.Integer(), nullable=False), sa.Column('verification_line_id', sa.Integer(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['artifact_id'], ['shipping_export_artifacts.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['reservation_id'], ['shipping_reservations.id']), sa.ForeignKeyConstraint(['verification_line_id'], ['shipping_inventory_verification_lines.id']), sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('artifact_id', 'reservation_id', name='uq_shipping_export_artifact_lines_artifact_reservation'),
)
def downgrade() -> None:
"""按履约依赖逆序移除滚动制单事实表。"""
op.drop_table('shipping_export_artifact_lines')
op.drop_table('shipping_inventory_verification_lines')
op.drop_index('ix_shipping_inventory_verifications_task_created', table_name='shipping_inventory_verifications')
op.drop_table('shipping_inventory_verifications')
op.drop_index('ix_shipping_reservations_task_status', table_name='shipping_reservations')
op.drop_table('shipping_reservations')
@@ -0,0 +1,48 @@
"""add shipment upload attempts
Revision ID: 023a4b5c6d7e
Revises: 022a3b4c5d6e
Create Date: 2026-07-22 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '023a4b5c6d7e'
down_revision = '022a3b4c5d6e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""建立按 Artifact 归属的上传尝试、幂等回调和人工回执引用。"""
op.create_table(
'shipping_upload_attempts',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('artifact_id', sa.Integer(), nullable=False),
sa.Column('attempt_no', sa.Integer(), nullable=False),
sa.Column('mode', sa.String(16), nullable=False),
sa.Column('idempotency_key', sa.String(128), nullable=False),
sa.Column('callback_id', sa.String(128), nullable=True),
sa.Column('status', sa.String(16), nullable=False, server_default='pending'),
sa.Column('started_at', sa.DateTime(), nullable=True), sa.Column('finished_at', sa.DateTime(), nullable=True),
sa.Column('error_code', sa.String(64), nullable=True), sa.Column('error_message', sa.String(500), nullable=True),
sa.Column('evidence_asset_id', sa.Integer(), nullable=True), sa.Column('operator_id', sa.Integer(), nullable=True),
sa.Column('freight_ref_no', sa.String(128), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False),
sa.CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_upload_attempts_mode'),
sa.CheckConstraint("status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out')", name='ck_shipping_upload_attempts_status'),
sa.ForeignKeyConstraint(['artifact_id'], ['shipping_export_artifacts.id']),
sa.ForeignKeyConstraint(['evidence_asset_id'], ['file_assets.id']),
sa.ForeignKeyConstraint(['operator_id'], ['users.id']), sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('artifact_id', 'attempt_no', name='uq_shipping_upload_attempts_artifact_attempt'),
sa.UniqueConstraint('idempotency_key', name='uq_shipping_upload_attempts_idempotency'),
sa.UniqueConstraint('callback_id', name='uq_shipping_upload_attempts_callback'),
)
op.create_index('ix_shipping_upload_attempts_artifact_created', 'shipping_upload_attempts', ['artifact_id', 'created_at'])
def downgrade() -> None:
"""移除上传 Attempt 事实表。"""
op.drop_index('ix_shipping_upload_attempts_artifact_created', table_name='shipping_upload_attempts')
op.drop_table('shipping_upload_attempts')
@@ -0,0 +1,30 @@
"""add order document profile sample intake purpose
Revision ID: 024a5b6c7d8e
Revises: 023a4b5c6d7e
Create Date: 2026-07-23 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = '024a5b6c7d8e'
down_revision = '023a4b5c6d7e'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""限制 Intake purpose,隔离模板样本与业务发货通知解析。"""
with op.batch_alter_table('shipping_notice_intakes') as batch:
batch.create_check_constraint(
'ck_shipping_notice_intakes_purpose',
"purpose IN ('shipping_notice', 'order_document_profile_sample')",
)
def downgrade() -> None:
"""移除 purpose 约束,回到历史兼容结构。"""
with op.batch_alter_table('shipping_notice_intakes') as batch:
batch.drop_constraint('ck_shipping_notice_intakes_purpose', type_='check')
+5
View File
@@ -211,9 +211,14 @@ def _ensure_test_task_dynamic_order(task: "ShippingTask") -> None:
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
order_schema_service.initialize_schema({'display_name': 'RPA 测试动态订单'}, actor_id=None)
existing_fields = {
item['field_code']: item
for item in order_schema_service.get_state()['fields']
}
fields = {
code: order_schema_service.save_field(
{'field_code': code, 'scope': 'line', 'value_type': value_type}, actor_id=None,
field_id=existing_fields.get(code, {}).get('id'),
)
for code, value_type in (('part_number', 'string'), ('reservation_id', 'string'), ('qty', 'decimal'))
}
@@ -0,0 +1,200 @@
"""
backend/tests/services/shipping_notice/test_shipping_order_snapshot.py
用途:验证订单解析事实冻结为强类型履约快照的阶段 1 门禁。
依赖:Flask 测试 app、ShippingOrder* ORM 与 order_freeze_service。
逻辑:构造预置核心字段和扩展字段的 accepted Extraction;验证 Snapshot 类型、LLM 阻断、乐观锁及冻结后不可编辑。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
import pytest
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderCustomerMatch,
ShippingCustomer,
ShippingTask,
User,
)
from app.services.shipping_notice.order_freeze_service import (
HEADER_FIELDS,
LINE_FIELDS,
assert_task_order_is_editable,
freeze_order_snapshot,
)
def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False):
"""创建一份含预置核心字段的已接受解析;可加入扩展字段验证配置化履约。"""
user = User(username='snapshot-user', email='snapshot-user@example.test', password_hash='x')
task = ShippingTask(task_no='SN-SNAPSHOT-001', source_type='test', order_data_version=7)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order')
db.session.add_all([user, task, schema])
db.session.flush()
definitions = []
fields: dict[str, ShippingOrderField] = {}
field_codes = [*HEADER_FIELDS, *LINE_FIELDS]
if with_extension:
field_codes.append('packing_reference')
for position, code in enumerate(field_codes, start=1):
scope = 'header' if code in HEADER_FIELDS else 'line'
value_type = 'decimal' if code in {'qty', 'unit_price', 'amount'} else ('date' if code in {'required_date', 'order_date'} else 'string')
field = ShippingOrderField(
schema_id=schema.id, field_code=code, scope=scope, value_type=value_type,
field_category='order_header' if scope == 'header' else 'order_line',
collection_mode='llm_extraction', display_sequence=position,
)
db.session.add(field)
db.session.flush()
fields[code] = field
definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': value_type, 'enabled': True})
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='snapshot-test')
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
db.session.add(line)
db.session.flush()
values = {
'po_number': 'PO-0001', 'customer_code': 'C-001', 'customer_name': 'Customer',
'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'),
'unit_price': Decimal('2.30'), 'amount': Decimal('28.75'), 'uom': 'PCS',
'packing_reference': 'PK-0007',
}
for code, field in fields.items():
value = values.get(code)
decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=None if code in HEADER_FIELDS else line.id,
field_id=field.id, decision_status='accepted', resolved_value_json=str(value) if isinstance(value, Decimal) else value,
supporting_observation_ids_json=[],
)
db.session.add(decision)
db.session.flush()
if value is not None:
db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=None if code in HEADER_FIELDS else line.id,
field_id=field.id, decision_id=decision.id, value_json=str(value) if isinstance(value, Decimal) else value,
value_text=str(value) if isinstance(value, str) else None,
value_decimal=value if isinstance(value, Decimal) else None,
))
if with_unverified_llm and code == 'qty':
observation = ShippingOrderFieldObservation(
extraction_id=extraction.id, line_id=line.id, field_id=field.id, source_type='llm_fallback',
extractor='dify', raw_value_json='12.50', normalized_value_json='12.50', evidence_verified=False,
)
db.session.add(observation)
db.session.flush()
decision.selected_observation_id = observation.id
task.current_order_extraction_id = extraction.id
customer = ShippingCustomer(standard_name='Snapshot Customer', short_code='CUS')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingOrderCustomerMatch(
extraction_id=extraction.id, role='bill_to', raw_name='Snapshot Customer',
normalized_name='SNAPSHOT CUSTOMER', status='confirmed', customer_id=customer.id,
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
identity_fingerprint='f' * 64, identity_rule_version='order-customer-fingerprint.v1',
identity_components_json={'role': 'bill_to'}, resolution_method='manual',
confirmation_reason='测试确认', confirmed_by_id=user.id, confirmed_at=datetime.utcnow(),
))
db.session.commit()
return task, user
def test_freeze_creates_strong_snapshot_and_preserves_identifiers(app):
"""关键断言:Decimal 保持精度,料号和预约单保留前导零,Task 只关联一个冻结快照。"""
with app.app_context():
task, user = _build_accepted_order()
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
db.session.commit()
assert task.order_snapshot_id == snapshot.id
assert snapshot.customer_short_code_snapshot == 'CUS'
assert snapshot.customer_id is not None
assert snapshot.rule_versions_json['ordering_customer']['identity_rule_version'] == 'order-customer-fingerprint.v1'
assert snapshot.lines[0].part_number == '000123'
assert snapshot.lines[0].reservation_id == '0012345678'
assert snapshot.lines[0].qty == Decimal('12.50000000')
def test_freeze_rejects_unverified_llm_critical_field(app):
"""关键断言:关键字段含未确认 LLM fallback 时冻结必须返回专用阻断码。"""
with app.app_context():
task, user = _build_accepted_order(with_unverified_llm=True)
with pytest.raises(ConflictError, match='LLM') as error:
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
assert error.value.code == 'SHIPPING.ORDER_LLM_REVIEW_REQUIRED'
def test_freeze_rejects_stale_version_and_any_followup_edit(app):
"""关键断言:并发旧版本不能冻结,冻结成功后所有解析纠错入口必须被统一拒绝。"""
with app.app_context():
task, user = _build_accepted_order()
with pytest.raises(ConflictError) as stale:
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=6)
assert stale.value.code == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
with pytest.raises(ConflictError) as frozen:
assert_task_order_is_editable(task)
assert frozen.value.code == 'SHIPPING.ORDER_SNAPSHOT_FROZEN'
def test_freeze_preserves_configured_extension_field_by_stable_id(app):
"""关键断言:扩展字段可由业务模板/路由/RPA 配置按 field_id 从 Snapshot 消费。"""
with app.app_context():
task, user = _build_accepted_order(with_extension=True)
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
extension_id = next(
item['field_id'] for item in extraction.schema_version.definition_json['fields']
if item['field_code'] == 'packing_reference'
)
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
db.session.commit()
assert snapshot.lines[0].field_values_json[extension_id] == 'PK-0007'
from app.services.shipping_notice.export import order_field_id_values
_header, lines = order_field_id_values(task)
assert lines[0][extension_id] == 'PK-0007'
def test_freeze_rejects_core_field_type_drift(app):
"""关键断言:预置核心字段仍需保持既定强类型,扩展字段不受此固定契约限制。"""
with app.app_context():
task, user = _build_accepted_order()
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
definition = extraction.schema_version.definition_json
next(item for item in definition['fields'] if item['field_code'] == 'qty')['value_type'] = 'string'
with pytest.raises(ValidationError) as error:
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
assert error.value.code == 'SHIPPING.ORDER_CONTRACT_INVALID'
def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app):
"""冻结只能采纳已确认订购客户,调用者传 customer_id 不能绕过该链路。"""
with app.app_context():
task, user = _build_accepted_order()
match = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=task.current_order_extraction_id, role='bill_to',
).one()
match.status = 'unique_candidate'
with pytest.raises(ValidationError) as error:
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
assert error.value.code == 'SHIPPING.ORDER_CUSTOMER_CONFIRMATION_REQUIRED'
+31 -3
View File
@@ -703,8 +703,8 @@ def test_unique_manifest_accepted_layout_fields_cannot_be_overridden(app):
assert caught.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
def test_accepted_complete_layout_builds_order_without_provider(app):
"""唯一 accepted 表格覆盖全部必填字段时必须直接生成订单,保持零 Provider 调用。"""
def test_accepted_layout_without_approved_profile_uses_provider(app):
"""仅 L4 accepted 表格不是模板盲测凭证,未批准 Profile 仍必须走受控兜底。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='LAYOUT-ZERO-PROVIDER')
run, _ = create_order_extraction_run(
@@ -724,8 +724,36 @@ def test_accepted_complete_layout_builds_order_without_provider(app):
orders = build_deterministic_unit_orders(run, unit=unit)
assert orders is None
def test_approved_profile_builds_order_from_its_own_parsed_rows(app):
"""关键断言:零 Provider 订单只能取已批准 Profile 的实际解析行,不能借用 L4 候选。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='APPROVED-PROFILE')
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
unit = run.extraction_plan.units[0]
with patch(
'app.services.shipping_notice.order_extraction_workflow._profile_table_candidates',
return_value={
'matched': True, 'blocking': False, 'issues': [],
'tables': [{
'table_id': 'profile-table', 'auto_create_approved': True,
'rows': [{
'row_index': 1, 'status': 'parsed', 'issues': [],
'fields': [{'field_id': 'qty-id', 'field_code': 'qty', 'value': 30, 'quote': 'Qty 30'}],
}],
}],
},
):
from app.services.shipping_notice.order_extraction_workflow import build_deterministic_unit_orders
orders = build_deterministic_unit_orders(run, unit=unit)
assert orders is not None
assert orders[0]['lines'][0]['fields'][0]['field_id'] == 'qty-id'
assert orders[0]['lines'][0]['fields'][0]['observations'][0]['value'] == 30
@@ -6,13 +6,18 @@ backend/tests/test_shipping_chat_action_handlers.py
from __future__ import annotations
import pytest
from app import db
from app.core.errors import ValidationError
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 (
ShippingCreateBatchFromIntakesAction,
ShippingFreezeOrderAction,
ShippingGenerateExcelAction,
ShippingMarkManualUploadedAction,
)
@@ -138,3 +143,95 @@ def test_create_batch_from_intakes_handler_forwards_candidate_nos(app, monkeypat
assert captured["candidate_nos"] == ["SNC-1", "SNC-2"]
assert captured["conversation_id"] == "sess-candidate"
assert any(event.event == "message.completed" for event in events)
def test_freeze_order_handler_requires_the_chat_version_and_emits_snapshot(app):
"""关键断言:Chat 冻结传递展示版本,成功后只以 Snapshot 继续履约。"""
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
with app.app_context():
task, user = _build_accepted_order()
task.user_id = user.id
agent = Agent(
name="冻结订单 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
agent_code="shipping_notice_freeze", runtime_provider="hybrid", conversation_mode="task_chat",
)
db.session.add(agent)
db.session.commit()
ctx = TurnContext(
turn_id="turn-freeze", run_id="turn-freeze", session_id="sess-freeze", request_id="req-freeze",
user=user, agent=agent,
input=TurnInput(
type="action", display_text="冻结订单", action_type="shipping.freeze_order",
payload={"task_no": task.task_no, "expected_order_data_version": 7},
),
refs={"task_no": task.task_no},
)
events = list(ShippingFreezeOrderAction().stream(ctx))
db.session.refresh(task)
assert task.order_snapshot_id is not None
assert "ui_state.updated" in [event.event for event in events]
assert "message.completed" in [event.event for event in events]
def test_manual_upload_handler_forwards_private_evidence_and_actor(app, monkeypatch):
"""关键断言:Chat 人工上传只能使用当前用户的回执资产,不接受无证据提交。"""
user = User(username="manual-handler", email="manual-handler@example.com", role="user", status="active")
user.set_password("password")
db.session.add(user)
db.session.commit()
task_no = _create_task(user.id)
agent = Agent(
name="手工上传 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
agent_code="shipping_notice_manual", runtime_provider="hybrid", conversation_mode="task_chat",
)
db.session.add(agent)
db.session.commit()
captured: dict = {}
monkeypatch.setattr(
"app.services.shipping_notice.chat_action_handlers.shipping_tools.upload_to_freight",
lambda payload: captured.update(payload) or {"status": "ok", "message": "已登记"},
)
ctx = TurnContext(
turn_id="turn-manual", run_id="turn-manual", session_id="sess-manual", request_id="req-manual",
user=user, agent=agent,
input=TurnInput(
type="action", display_text="已上传", action_type="shipping.mark_manual_uploaded",
payload={"task_no": task_no, "evidence_asset_no": "FA-RECEIPT-001"},
),
refs={"task_no": task_no},
)
events = list(ShippingMarkManualUploadedAction().stream(ctx))
assert captured["operator_id"] == user.id
assert captured["evidence_asset_no"] == "FA-RECEIPT-001"
assert any(event.event == "message.completed" for event in events)
def test_manual_upload_handler_rejects_chat_turn_without_evidence(app):
"""关键断言:不能借助 Chat action 绕过人工上传截图/回执门禁。"""
user = User(username="manual-handler-no-evidence", email="manual-handler-no-evidence@example.com", role="user", status="active")
user.set_password("password")
db.session.add(user)
db.session.commit()
task_no = _create_task(user.id)
agent = Agent(
name="手工上传无证据 Agent", description="t", dify_api_key="k", api_base_url="http://example.com",
agent_code="shipping_notice_manual_missing", runtime_provider="hybrid", conversation_mode="task_chat",
)
db.session.add(agent)
db.session.commit()
ctx = TurnContext(
turn_id="turn-manual-missing", run_id="turn-manual-missing", session_id="sess-manual-missing", request_id="req-manual-missing",
user=user, agent=agent,
input=TurnInput(type="action", display_text="已上传", action_type="shipping.mark_manual_uploaded", payload={"task_no": task_no}),
refs={"task_no": task_no},
)
with pytest.raises(ValidationError) as error:
list(ShippingMarkManualUploadedAction().stream(ctx))
assert error.value.code == "SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED"
@@ -0,0 +1,64 @@
"""
验证坐标重建仅在可信列锚点下生成可审计的 needs_review 订单行候选。
依赖:coordinate_table_reconstruction、LayoutBBox。逻辑:覆盖 x 列归属、y 新行、续行与
删除标记;没有强行号锚点的行不能被伪装成独立订单明细。
"""
from __future__ import annotations
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
reconstruct_table_from_positioned_text,
)
def _glyphs(*rows: list[tuple[str, float]]) -> list[dict]:
"""为每个视觉行构造逐字坐标;x 值表示该文本的首字横坐标。"""
result = []
for row_index, cells in enumerate(rows):
for text, start_x in cells:
for offset, char in enumerate(text):
result.append({'text': char, 'bbox': {
'x0': start_x + offset * 4, 'y0': 20 + row_index * 14,
'x1': start_x + offset * 4 + 3, 'y1': 30 + row_index * 14,
}})
return result
def _reconstruct(characters: list[dict]):
"""使用三列已确认表头区间,模拟 MinerU 网格失真后的 PDF 原生证据。"""
return reconstruct_table_from_positioned_text(
characters=characters,
table_bbox=LayoutBBox(x0=0, y0=0, x1=200, y1=100),
column_anchors=[
{'column_index': 0, 'bbox': {'x0': 10, 'y0': 2, 'x1': 35, 'y1': 15}},
{'column_index': 1, 'bbox': {'x0': 60, 'y0': 2, 'x1': 135, 'y1': 15}},
{'column_index': 2, 'bbox': {'x0': 150, 'y0': 2, 'x1': 190, 'y1': 15}},
],
)
def test_coordinate_reconstruction_uses_x_y_and_continuation_rules():
"""行号、料号、数量按 x/y 重建;无行号的下一视觉行只能是续行。"""
result = _reconstruct(_glyphs(
[('00010', 12), ('6Y70ABC', 62), ('36', 144)],
[('B3-AR1000270A', 62), ('Ship by sea', 142)],
))
# 关键断言:首个强行号行和相邻续行分开,且料号不会落到数量列。
assert result.status == 'needs_review'
assert [row.role for row in result.rows] == ['data', 'continuation']
assert [cell.text for cell in result.rows[0].cells] == ['00010', '6Y70ABC', '36']
assert result.rows[1].cells[0].column_index == 1
assert result.rows[1].cells[0].glyph_indices == list(range(14, 27))
def test_coordinate_reconstruction_only_attaches_deleted_marker_to_prior_line():
"""删除标记必须关联前一强行号行;没有前序行号时保留 needs_review。"""
attached = _reconstruct(_glyphs([('00010', 12), ('PART-A', 62)], [('** Item deleted **', 62)]))
unattached = _reconstruct(_glyphs([('** Item deleted **', 62)]))
assert attached.rows[1].role == 'deleted'
assert unattached.rows[0].role == 'needs_review'
assert unattached.issues == ['coordinate_reconstruction_deleted_row_unattached']
@@ -0,0 +1,153 @@
"""
backend/tests/test_shipping_document_profile_quality.py
用途:验证订单文档模板的独立盲测、批准资格和冻结 checksum 门禁。
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
逻辑:管理员固化三份独立样本真值;全部通过且批准后才可放行确定性自动建单。
"""
from __future__ import annotations
from datetime import datetime
import pytest
from app import db
from app.models import (
FileAsset,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocumentProfile,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
User,
)
from app.services.shipping_notice import document_profile_quality_service as quality
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.shipping_notice.document_layout.order_profile import order_profile_structure_fingerprint
def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, User, list[ShippingNoticeDocument]]:
"""创建一份已发布 Profile 及三份不同文档盲测样本,真值不复用建模输入。"""
user = User(username='profile-quality-admin', email='profile-quality-admin@example.com', role='admin')
# 产品模型只允许唯一的 SHIPPING_ORDER Schema,测试仅创建其隔离版本。
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Quality order')
db.session.add_all([user, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', checksum='a' * 64,
published_at=datetime.utcnow(), definition_json={'fields': [
{
'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
'value_type': 'string', 'enabled': True, 'required': True,
'normalizer_key': 'trim', 'validator_keys': [],
},
{
'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line',
'value_type': 'decimal', 'enabled': True, 'required': True,
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
},
]},
)
db.session.add(version)
db.session.flush()
html = '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr></table>'
fingerprint = order_profile_structure_fingerprint(parse_html_grid(html, table_id='table-1'), header_row_index=0)
profile = ShippingOrderDocumentProfile(
profile_code='QUALITY_TEMPLATE', display_name='Quality template', version=1, status='published',
schema_version_id=version.id, structure_fingerprint=fingerprint, checksum='b' * 64,
published_at=datetime.utcnow(), definition_json={
'contract_version': 'shipping_order_document_profile.v1', 'structure_fingerprint': fingerprint,
'header_row_index': 0, 'data_start_row_index': 1, 'row_structure': 'preserved',
'drop_zero_qty': True, 'column_rules': [
{'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['part_number'],
'target_fields': [{'field_id': 'part-id', 'field_code': 'part_number'}]},
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['qty'],
'target_fields': [{'field_id': 'qty-id', 'field_code': 'qty'}]},
],
},
)
db.session.add(profile)
db.session.flush()
documents = []
for index in range(3):
asset = FileAsset(
asset_no=f'FA-QUALITY-{index}', owner_user_id=user.id, original_filename=f'q{index}.pdf',
storage_provider='test', storage_bucket='test', storage_key=f'q{index}.pdf',
content_hash=f'{index:x}' * 64, file_size=1, mime_type='application/pdf',
upload_status='ready', lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no=f'SNI-QUALITY-{index}', asset_id=asset.id, user_id=user.id,
purpose='shipping_notice', parse_status='parsed', parser_version='test',
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key=asset.storage_key,
filename=asset.original_filename, content_hash=asset.content_hash, classification='order_notice',
parse_status='parsed', extracted_text='PN-1 3',
)
db.session.add(document)
db.session.flush()
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1', 'provider': 'mineru',
'backend': 'test', 'status': 'ready', 'issues': [],
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': html}],
})
documents.append(document)
db.session.commit()
return profile, user, documents
def test_profile_auto_create_requires_three_passing_blind_samples_and_approval(app):
"""关键断言:三样本全通过和管理员批准缺一不可,批准后样本不可篡改。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
for document in documents[:2]:
quality.add_sample(
suite_id=suite['id'], document_id=document.id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
)
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
assert executed['latest_run']['status'] == 'failed'
with pytest.raises(Exception) as caught:
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY'
quality.add_sample(
suite_id=suite['id'], document_id=documents[2].id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
)
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
assert approved['status'] == 'approved'
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
with pytest.raises(Exception) as immutable:
quality.add_sample(
suite_id=suite['id'], document_id=documents[0].id, table_id='other',
expected_rows=[{'part_number': 'PN-1'}], actor_id=user.id,
)
assert getattr(immutable.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
with app.app_context():
profile, user, documents = _published_profile_with_samples()
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
for document in documents:
quality.add_sample(
suite_id=suite['id'], document_id=document.id, table_id='table-1',
expected_rows=[{'part_number': 'PN-1', 'qty': 3}], actor_id=user.id,
)
quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
profile.checksum = 'c' * 64
db.session.commit()
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
@@ -0,0 +1,50 @@
"""
backend/tests/test_shipping_document_profile_quality_migration.py
用途:验证模板盲测资格迁移可以独立升级和回滚。
依赖:Alembic Operations、SQLite 内存数据库。
逻辑:以最小外键前置表执行迁移,确认三张质量表及关键唯一约束存在。
"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_document_profile_quality_migration_upgrade_and_downgrade(monkeypatch):
"""盲测迁移必须完整创建三张表,并可无残留回滚。"""
migration = importlib.import_module(
'migrations.versions.020a1b2c3d4e_add_shipping_document_profile_quality',
)
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_order_document_profiles', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_notice_documents', metadata, sa.Column('id', sa.Integer(), primary_key=True))
metadata.create_all(engine)
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
monkeypatch.setattr(migration, 'op', operations)
migration.upgrade()
tables = set(sa.inspect(connection).get_table_names())
assert {
'shipping_document_profile_test_suites',
'shipping_document_profile_test_samples',
'shipping_document_profile_test_runs',
} <= tables
suite_constraints = sa.inspect(connection).get_unique_constraints(
'shipping_document_profile_test_suites',
)
assert any(item['name'] == 'uq_shipping_document_profile_test_suites_profile' for item in suite_constraints)
migration.downgrade()
tables = set(sa.inspect(connection).get_table_names())
assert 'shipping_document_profile_test_suites' not in tables
assert 'shipping_document_profile_test_samples' not in tables
assert 'shipping_document_profile_test_runs' not in tables
+81 -1
View File
@@ -7,6 +7,7 @@
from __future__ import annotations
from datetime import date
from decimal import Decimal
from io import BytesIO
from unittest.mock import patch
@@ -18,11 +19,13 @@ from app import db
from app.models import (
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingTask,
ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingTask,
)
from app.services.shipping_notice import excel_template
from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
from app.services.shipping_notice.reservation_service import record_inventory_verification
from app.core.errors import ConflictError, ValidationError
@@ -31,6 +34,36 @@ def _inventory_field_id(field_code: str) -> str:
return str(ShippingInventoryField.query.filter_by(field_code=field_code).one().id)
def _freeze_export_snapshot(
task: ShippingTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
) -> None:
"""为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
order_data_version=1, rule_versions_json={},
header_values_json={str(key): value for key, value in (header or {}).items()},
)
db.session.add(snapshot)
db.session.flush()
for position, field_id, part_number, qty, reservation_id in lines or []:
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=position, part_number=part_number,
reservation_id=reservation_id, qty=Decimal(str(qty)),
field_values_json={str(field_id): part_number},
))
db.session.flush()
task.order_snapshot_id = snapshot.id
record_inventory_verification(
task, inventory_snapshot_id=task.inventory_snapshot_id, source_config_version='test-v1',
line_results=[{
'reservation_id': line.reservation_id, 'part_number': line.part_number,
'required_qty': line.qty, 'available_qty': line.qty, 'line_status': 'ok',
} for line in snapshot.lines],
)
db.session.flush()
@pytest.fixture(autouse=True)
def _template_object_storage(monkeypatch):
"""使用内存私有对象存储替身,验证模板不依赖本机文件系统。"""
@@ -82,6 +115,37 @@ def test_filename_pattern_supports_business_number_and_split_business_variables(
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx'
def test_filename_pattern_falls_back_to_controlled_environment_configuration(app):
"""模板未提供规则时可使用受控环境变量,调用方仍不能提交任意文件名。"""
with app.app_context():
app.config['SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN'] = 'default_{task_no}.xlsx'
task = ShippingTask(task_no='TASK-FILENAME-DEFAULT')
template = ShippingExcelTemplate(template_code='DEFAULT', display_name='Default', definition_json={})
assert _filename(task, template) == 'default_TASK-FILENAME-DEFAULT.xlsx'
def test_publish_allows_empty_template_filename_pattern_for_environment_fallback(app, tmp_path):
"""空模板规则代表显式采用环境变量回退,发布时仍须完整校验 Excel 映射。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
draft = excel_template.create_draft(_workbook_upload(), {
'template_code': 'ENV_FALLBACK',
'display_name': 'Environment fallback',
'definition': {
'filename_pattern': '',
'mappings': [{
'sheet': 'Header', 'row_mode': 'header', 'start_row': 1, 'target_column': 1,
'source_kind': 'constant', 'source_key': 'fallback', 'formatter': 'text',
}],
},
}, actor_id=None)
published = excel_template.publish(draft['id'], actor_id=None)
assert published['status'] == 'published'
assert published['definition']['filename_pattern'] == ''
def test_published_template_generates_dynamic_artifact(app, tmp_path):
"""发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
@@ -158,6 +222,11 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
)
db.session.add(task)
db.session.flush()
_freeze_export_snapshot(
task, extraction, version,
header={customer.id: 'acme', po_number.id: '16754796'},
lines=[(1, part.id, 'PN-1', 1, 'RES-EXPORT-1')],
)
path, filename, artifact = generate_shipment_excel(task)
db.session.commit()
@@ -337,6 +406,13 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
],
)
db.session.add(task); db.session.flush()
_freeze_export_snapshot(
task, extraction, version,
lines=[
(1, part.id, 'PN-A', 1, 'RES-KEYED-A'),
(2, part.id, 'PN-B', 1, 'RES-KEYED-B'),
],
)
path, _filename, _artifact = generate_shipment_excel(task)
workbook = load_workbook(path, read_only=True)
@@ -501,6 +577,10 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app,
],
)
db.session.add(task); db.session.flush()
_freeze_export_snapshot(
task, extraction, version,
lines=[(1, part.id, 'PN-A', 1, 'RES-AMBIGUOUS-A')],
)
with pytest.raises(ValueError, match='值不一致'):
generate_shipment_excel(task)
+11 -6
View File
@@ -1,5 +1,5 @@
"""
用途:验证发货 Excel 批次 ZIP 的权限、最新 Artifact、重名、校验和与 manifest 契约。
用途:验证发货 Excel 批次 ZIP 的权限、全部有效 Artifact、重名、校验和与 manifest 契约。
依赖:export_archive、ShippingBatch/Task/ExportArtifact、zipfile。
逻辑:构造同批次有效、缺失及损坏产物,断言 ZIP 仅包含可信文件并完整列出排除原因。
"""
@@ -59,7 +59,7 @@ def _artifact(task, path, dependencies, *, no: str, checksum: str | None = None)
def test_batch_archive_manifest_and_duplicate_names(app, tmp_path):
"""有效同名文件均进入 ZIP,缺失/损坏任务只进入 manifest 并带明确状态。"""
"""同一任务多轮有效 Excel 都进入 ZIP,缺失/损坏 Artifact 保留明确审计状态。"""
with app.app_context():
user = User(username='zip-owner', email='zip@example.com', role='user', status='approved')
batch = ShippingBatch(batch_no='SB-ZIP', user_id=None, file_count=4)
@@ -67,10 +67,12 @@ def test_batch_archive_manifest_and_duplicate_names(app, tmp_path):
tasks = [ShippingTask(task_no=f'TASK-{index}', user_id=user.id, batch_id=batch.id, batch_index=index, batch_total=4) for index in range(1, 5)]
db.session.add_all(tasks); db.session.flush()
first = tmp_path / 'first.xlsx'; first.write_bytes(b'first')
first_second_round = tmp_path / 'first-second-round.xlsx'; first_second_round.write_bytes(b'first-second-round')
second = tmp_path / 'second.xlsx'; second.write_bytes(b'second')
corrupt = tmp_path / 'corrupt.xlsx'; corrupt.write_bytes(b'changed')
dependencies = _seed_artifact_dependencies()
_artifact(tasks[0], first, dependencies, no='EXP-1')
_artifact(tasks[0], first_second_round, dependencies, no='EXP-1-SECOND')
_artifact(tasks[1], second, dependencies, no='EXP-2')
_artifact(tasks[2], tmp_path / 'missing.xlsx', dependencies, no='EXP-3')
_artifact(tasks[3], corrupt, dependencies, no='EXP-4', checksum='0' * 64)
@@ -81,11 +83,12 @@ def test_batch_archive_manifest_and_duplicate_names(app, tmp_path):
names = archive.namelist()
assert 'shipment.xlsx' in names
assert 'shipment_TASK-2.xlsx' in names # 同名按任务号消歧,避免覆盖。
assert 'shipment_TASK-1.xlsx' in names # 同一任务第二轮滚动 Artifact 不得遗漏。
archived_manifest = json.loads(archive.read('manifest.json'))
assert filename.startswith('shipping_exports_SB-ZIP_')
assert archived_manifest['included_count'] == 2
assert archived_manifest['included_count'] == 3
assert [entry['status'] for entry in manifest['entries']] == [
'included', 'included', 'missing_file', 'checksum_mismatch',
'included', 'included', 'included', 'missing_file', 'checksum_mismatch',
]
@@ -104,8 +107,8 @@ def test_archive_rejects_foreign_task_and_invalid_selection(app):
build_export_archive(user_id=owner.id, batch_no='SB', task_nos=[task.task_no])
def test_archive_excludes_artifact_after_task_export_is_invalidated(app, tmp_path):
"""任务纠错清空当前导出引用后,旧 ready Artifact 不得继续进入下载包。"""
def test_archive_excludes_superseded_artifact_after_task_export_is_invalidated(app, tmp_path):
"""任务纠错必须显式作废旧 Artifact;仅清空旧 Task 指针不能影响滚动履约历史。"""
with app.app_context():
user = User(username='archive-reset', email='archive-reset@example.com', role='user', status='approved')
batch = ShippingBatch(batch_no='SB-RESET', user_id=None, file_count=1)
@@ -114,6 +117,8 @@ def test_archive_excludes_artifact_after_task_export_is_invalidated(app, tmp_pat
db.session.add(task); db.session.flush()
path = tmp_path / 'old.xlsx'; path.write_bytes(b'old')
_artifact(task, path, _seed_artifact_dependencies(), no='EXP-OLD')
artifact = ShippingExportArtifact.query.filter_by(artifact_no='EXP-OLD').one()
artifact.status = 'superseded'
task.export_file_path = None
task.export_file_name = None
db.session.commit()
@@ -0,0 +1,50 @@
"""
用途:验证人工上传必须引用用户私有回执资产。
依赖:上传 Attempt 服务、FileAsset 服务、滚动履约测试夹具。
逻辑:无回执请求被拒;有已上传资产时创建 manual Attempt 并锁定预约单。
"""
from __future__ import annotations
from io import BytesIO
import pytest
from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import ValidationError
from app.models import ShippingUploadAttempt, User
from app.services.file_assets.service import upload_file_asset
from app.services.shipping_notice.upload_attempt_service import record_manual_upload
from tests.test_shipping_upload_attempt import _ready_artifact
def test_manual_upload_requires_receipt_asset(app):
"""人工确认不可仅凭文本或参考号,缺少回执文件必须返回专用业务错误。"""
with app.app_context():
task, artifact, _reservation = _ready_artifact()
user = User(username='manual-evidence', email='manual-evidence@example.test', password_hash='x')
db.session.add(user); db.session.flush()
with pytest.raises(ValidationError) as exc_info:
record_manual_upload(task, artifact_id=artifact.id, evidence_asset_no='', operator_id=user.id)
assert exc_info.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED'
def test_manual_upload_records_receipt_asset(app):
"""已上传的私有截图资产会成为 manual Attempt 的不可变证据。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
user = User(username='manual-evidence-ok', email='manual-evidence-ok@example.test', password_hash='x')
db.session.add(user); db.session.commit()
payload = upload_file_asset(
user_id=user.id,
upload=FileStorage(stream=BytesIO(b'receipt'), filename='receipt.png', content_type='image/png'),
)
attempt = record_manual_upload(
task, artifact_id=artifact.id, evidence_asset_no=payload['asset_no'], operator_id=user.id,
)
assert attempt.mode == 'manual'
assert attempt.status == 'succeeded'
assert attempt.evidence_asset_id is not None
assert db.session.get(type(reservation), reservation.id).status == 'uploaded'
assert ShippingUploadAttempt.query.count() == 1
+75 -12
View File
@@ -30,6 +30,7 @@ from app.models import (
ShippingOrderExtraction,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSnapshot,
ShippingTask,
ShippingTaskEvent,
ShippingTemporaryInventorySession,
@@ -418,6 +419,59 @@ def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
assert len(task.lines_json or []) == 0
def test_workspace_create_batch_rejects_configured_file_limit_before_intake(app, client, tmp_path):
"""超过请求级文件数限制必须明确失败,且不创建批次、任务或临时上传目录。"""
headers = _workspace_headers(app)
app.config['SHIPPING_NOTICE_BATCH_MAX_FILES'] = 1
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path)
with app.app_context():
batch_count_before = ShippingBatch.query.count()
task_count_before = ShippingTask.query.count()
response = client.post(
'/api/workspace/shipping-batches/create-from-notices',
headers=headers,
data={
'files': [
(BytesIO(b'first'), 'notice-a.txt'),
(BytesIO(b'second'), 'notice-b.txt'),
],
},
content_type='multipart/form-data',
)
assert response.status_code == 400
payload = response.get_json()
# 关键断言:请求在抽取前被阻断,避免超限文件占用临时目录或部分建单。
assert payload['error']['code'] == 'SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED'
assert payload['error']['details'] == {'max_files': 1, 'received_files': 2}
with app.app_context():
assert ShippingBatch.query.count() == batch_count_before
assert ShippingTask.query.count() == task_count_before
assert not (tmp_path / 'notice_uploads' / '_tmp').exists()
def test_workspace_inventory_upload_requires_authenticated_task_and_file(app, client):
"""独立工作台库存上传端点必须保持任务归属校验,并拒绝缺少 multipart 文件的调用。"""
headers = _workspace_headers(app)
response = client.post('/api/workspace/shipping-tasks/SN-NOT-OWNED/upload-inventory', headers=headers)
assert response.status_code == 404
with app.app_context():
user = User.query.filter_by(username='shipping_workspace_user').order_by(User.id.desc()).first()
assert user is not None
task = ShippingTask(task_no='SN-WORKSPACE-INVENTORY-UPLOAD', user_id=user.id)
db.session.add(task)
db.session.commit()
response = client.post(
'/api/workspace/shipping-tasks/SN-WORKSPACE-INVENTORY-UPLOAD/upload-inventory', headers=headers,
data={}, content_type='multipart/form-data',
)
assert response.status_code == 400
assert response.get_json()['error']['message'] == 'file is required'
def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(app, client, monkeypatch):
"""开启编排器时,工作台上传接口应返回 orchestrator_started。"""
headers = _workspace_headers(app)
@@ -627,8 +681,8 @@ def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app,
assert task.export_file_name is None
def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
"""库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。"""
def test_auto_progress_requires_order_freeze_before_inventory_trigger(app, tmp_path):
"""关键断言:库存自动推进前必须先阻断到订单冻结,不能消费动态订单投影。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
@@ -664,16 +718,13 @@ def test_auto_progress_inventory_trigger_failure_marks_step3(app, tmp_path):
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert task.process_status == "waiting_inventory"
assert task.pending_human_reason == "inv_unavail"
assert task.current_step == "step3_inventory_prepare"
assert task.step_payload_json["current_step_progress"]["status"] == "needs_human"
assert result["checkpoint"] == "order_freeze"
assert task.process_status == "parsed"
from app.services.shipping_notice.ui_state import build_task_ui_state
ui_state = build_task_ui_state(task)
inventory_step = next(step for step in ui_state["steps"] if step["code"] == "inventory_prepare")
assert inventory_step["status"] == "blocked"
assert ui_state["checkpoint"] == "order_freeze"
assert ui_state["current_step"]["code"] == "parse_confirm"
def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, client, tmp_path):
@@ -736,8 +787,8 @@ def test_workspace_task_detail_is_read_only_for_timed_out_inventory_rpa(app, cli
assert not list((tmp_path / "inventory_triggers").glob("inventory_export_*.json"))
def test_auto_progress_resolves_dub_source_without_implicitly_triggering_rpa(app, tmp_path):
"""自动推进可解析 Dublin 库存源,但正式 RPA 刷新必须由用户明确触发。"""
def test_auto_progress_requires_order_freeze_before_inventory_source_resolution(app, tmp_path):
"""关键断言:库存源解析也不得绕过冻结 Snapshot 门禁。"""
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(tmp_path / "empty_inventory_drop")
@@ -769,7 +820,8 @@ def test_auto_progress_resolves_dub_source_without_implicitly_triggering_rpa(app
db.session.refresh(task)
assert result["status"] == "needs_human"
assert result["checkpoint"] == "upload_req"
assert result["checkpoint"] == "order_freeze"
# 预置的历史 Source 提示可以保留,但不可据此触发库存/RPA。
assert task.inventory_source_code == "DSV360_AWSDU"
trigger_path = tmp_path / "inventory_triggers" / f"inventory_export_{task.task_no}.json"
assert not trigger_path.exists()
@@ -845,6 +897,17 @@ def test_inventory_source_rules_resolve_configured_dublin_source(app):
value_json='DUB',
))
task.current_order_extraction_id = extraction.id
snapshot = ShippingOrderSnapshot(
task_id=task.id,
extraction_id=extraction.id,
schema_version_id=published['id'],
order_data_version=1,
header_values_json={str(destination_field['id']): 'DUB'},
rule_versions_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
db.session.add(ShippingInventoryRoutingRule(
rule_code='BATCH_TEST_DUB',
rule_name='批次测试 Dublin 路由',
@@ -17,6 +17,7 @@ from app.models import (
ShippingCase, ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingTask,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion,
ShippingOrderSnapshot, ShippingOrderSnapshotLine,
ShippingTaskEvent, ShippingTaskInventoryLink,
)
from app.services.shipping_notice.match import match_notice_lines
@@ -77,6 +78,23 @@ def _attach_dynamic_order(task: ShippingTask, *, part_number: str, reservation_i
value_json=value,
))
task.current_order_extraction_id = extraction.id
# RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时
# 建立最小履约真相,避免旧测试绕过阶段 1 门禁。
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'],
order_data_version=task.order_data_version or 1, rule_versions_json={}, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, part_number=part_number, reservation_id=reservation_id,
qty=quantity, field_values_json={
str(fields['part_number']['id']): part_number,
str(fields['reservation_id']['id']): reservation_id,
str(fields['qty']['id']): quantity,
},
))
task.order_snapshot_id = snapshot.id
db.session.flush()
@@ -0,0 +1,34 @@
"""
backend/tests/test_shipping_order_customer_match_fingerprint_migration.py
用途:验证订单客户指纹审计迁移可升级和回滚。
依赖:Alembic Operations、SQLite 内存数据库。
逻辑:以最小匹配表执行迁移,检查规则指纹与人工理由列的完整生命周期。
"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_order_customer_match_fingerprint_migration_upgrade_and_downgrade(monkeypatch):
"""客户指纹迁移必须增加审计列和索引,并可不留残余回滚。"""
migration = importlib.import_module('migrations.versions.021a2b3c4d5e_add_order_customer_match_fingerprint')
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table('shipping_order_customer_matches', metadata, sa.Column('id', sa.Integer(), primary_key=True))
metadata.create_all(engine)
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
monkeypatch.setattr(migration, 'op', operations)
migration.upgrade()
columns = {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_customer_matches')}
assert {'identity_fingerprint', 'identity_rule_version', 'identity_components_json', 'confirmation_reason'} <= columns
migration.downgrade()
columns = {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_customer_matches')}
assert 'identity_fingerprint' not in columns
@@ -99,11 +99,32 @@ def test_order_customer_matching_keeps_ambiguous_and_manual_confirmation(app):
assert len(bill_to['candidates']) == 2
confirmed = confirm_order_customer_match(
extraction.id, role='bill_to', customer_id=second.id, actor_id=None,
extraction.id, role='bill_to', customer_id=second.id, actor_id=None, reason='业务复核确认订购客户',
)
assert confirmed['status'] == 'confirmed'
assert confirmed['standard_name'] == 'Customer Two'
assert confirmed['short_code'] == 'TWO'
assert confirmed['confirmation_reason'] == '业务复核确认订购客户'
assert len(confirmed['identity_fingerprint']) == 64
assert confirmed['identity_rule_version'] == 'order-customer-fingerprint.v1'
def test_order_customer_fingerprint_is_stable_and_confirmation_requires_reason(app):
"""相同原文及规则必须得到稳定指纹,人工绑定不能缺失可审计理由。"""
with app.app_context():
customer = ShippingCustomer(standard_name='Fingerprint Customer', short_code='FPC')
db.session.add(customer)
extraction = _extraction()
first = refresh_order_customer_matches(extraction, {'bill_to_customer': ' Fingerprint Customer '})
fingerprint = next(item for item in first if item['role'] == 'bill_to')['identity_fingerprint']
second = refresh_order_customer_matches(extraction, {'bill_to_customer': 'Fingerprint Customer'})
assert next(item for item in second if item['role'] == 'bill_to')['identity_fingerprint'] == fingerprint
try:
confirm_order_customer_match(extraction.id, role='bill_to', customer_id=customer.id, actor_id=None, reason='')
except Exception as error:
assert getattr(error, 'code', None) == 'SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED'
else:
raise AssertionError('confirmation without reason must be blocked')
def test_order_customer_matching_prefers_external_customer_and_site_codes(app):
@@ -15,6 +15,7 @@ from app.services.shipping_notice.document_layout.html_table import parse_html_g
from app.services.shipping_notice.document_layout.order_profile import (
OrderDocumentProfile,
OrderProfileColumnRule,
diagnose_order_profile_header,
order_profile_structure_fingerprint,
parse_html_table_with_order_profile,
)
@@ -163,6 +164,18 @@ def test_template_profile_routes_lost_row_structure_without_column_mapping():
assert result.issues == ['order_profile_row_structure_unsupported']
def test_profile_header_diagnosis_blocks_merged_item_number_data():
"""合并到表头的 `ITEM NO 00010` 必须在映射前被识别为明细污染。"""
html = (
'<table><tr><th>ITEM NO 00010</th><th>Part Number</th><th>Qty</th></tr>'
'<tr><td>00020</td><td>PART-2</td><td>36</td></tr></table>'
)
assert diagnose_order_profile_header(parse_html_grid(html, table_id='contaminated'), header_row_index=0) == [
'order_profile_header_contaminated_by_data',
]
def test_template_profile_rejects_freeform_or_invalid_extractor_targets():
"""Profile 只能引用注册 parser key 和固定输出字段,禁止自由代码/正则。"""
with pytest.raises(ValidationError):
@@ -23,6 +23,7 @@ from app.models import (
User,
)
from app.services.shipping_notice import order_document_profile_service as service
from app.services.shipping_notice.intake_service import create_order_document_profile_sample_intake
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from tests.conftest import parse_api_data, parse_api_error
@@ -314,3 +315,100 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
assert updated['display_name'] == 'Sample template v2'
assert updated['change_note'] == 'Reconfirmed against MinerU sample'
assert updated['lock_version'] == clone['lock_version'] + 1
def test_profile_sample_api_blocks_header_contaminated_by_first_line_data(app):
"""错误网格预览要给出稳定诊断,且不能被管理员固化为可发布 Profile。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
schema = _schema_version()
user = User(username='contaminated-admin', email='contaminated@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-PROFILE-CONTAMINATED', owner_user_id=user.id, original_filename='bad.pdf',
storage_provider='minio', storage_bucket='test', storage_key='bad.pdf',
content_hash='d' * 64, 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-PROFILE-CONTAMINATED', 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='bad.pdf', filename='bad.pdf', content_hash='d' * 64,
classification='order_notice', parse_status='parsed', extracted_text='sample',
)
db.session.add(document)
db.session.flush()
record_inline_layout_snapshot(document, {
'snapshot_version': 'shipping_document_table_snapshot.v1',
'provider': 'mineru', 'provider_version': '3.1.14', 'status': 'ready',
'tables': [{'table_id': 'table-bad', 'page_no': 1, 'html': (
'<table><tr><th>ITEM NO 00010</th><th>Part Number</th><th>Qty</th></tr>'
'<tr><td>00020</td><td>INTERNAL-2</td><td>36</td></tr></table>'
)}],
})
db.session.commit()
document_id = document.id
schema_id = schema.id
client = app.test_client()
headers = {'X-Username': 'contaminated-admin', 'X-Role': 'admin'}
preview = parse_api_data(client.get(
f'/api/admin/shipping-notice/order-document-profile-samples/{document_id}/tables',
headers=headers,
).get_json())
assert preview['tables'][0]['issues'] == ['order_profile_header_contaminated_by_data']
assert preview['tables'][0]['profile_creation_allowed'] is False
response = client.post('/api/admin/shipping-notice/order-document-profiles/from-sample', json={
'profile_code': 'CONTAMINATED_TEMPLATE', 'display_name': 'Bad template',
'schema_version_id': schema_id, 'document_id': document_id, 'table_id': 'table-bad',
'header_row_index': 0, 'data_start_row_index': 1,
'column_rules': [
{'column_index': 0, 'extractor_key': 'direct', 'target_field_codes': ['customer_part_number']},
{'column_index': 1, 'extractor_key': 'direct', 'target_field_codes': ['part_number']},
{'column_index': 2, 'extractor_key': 'direct', 'target_field_codes': ['qty']},
],
}, headers=headers)
assert response.status_code == 400
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED'
def test_profile_sample_intake_is_isolated_from_shipping_business_flow(app):
"""模板页 PDF/EML 样本只能建立专用 Intake,不能复用业务目的或被错误文件类型绕过。"""
with app.app_context():
user = User(username='profile-sample-admin', email='profile-sample@example.com', role='admin', status='active')
db.session.add(user)
db.session.flush()
pdf = FileAsset(
asset_no='FA-PROFILE-UPLOAD', owner_user_id=user.id, original_filename='template.pdf',
storage_provider='minio', storage_bucket='test', storage_key='template.pdf',
content_hash='e' * 64, file_size=100, mime_type='application/pdf', extension='pdf',
upload_status='ready', lifecycle_status='temporary',
)
invalid = FileAsset(
asset_no='FA-PROFILE-INVALID', owner_user_id=user.id, original_filename='template.docx',
storage_provider='minio', storage_bucket='test', storage_key='template.docx',
content_hash='f' * 64, file_size=100,
mime_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', extension='docx',
upload_status='ready', lifecycle_status='temporary',
)
db.session.add_all([pdf, invalid])
db.session.commit()
created = create_order_document_profile_sample_intake(user_id=user.id, asset_no=pdf.asset_no)
intake = ShippingNoticeIntake.query.filter_by(intake_no=created['intake_no']).one()
assert intake.purpose == 'order_document_profile_sample'
assert intake.conversation_id is None
assert intake.order_extraction_status == 'not_started'
with pytest.raises(Exception) as caught:
create_order_document_profile_sample_intake(user_id=user.id, asset_no=invalid.asset_no)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID'
+48 -21
View File
@@ -83,6 +83,31 @@ def _publish_draft(version_id: int) -> dict:
return service.publish(version_id, actor_id=None, expected_lock_version=version.lock_version)
def test_order_schema_initializes_fixed_core_and_allows_extension_fields(app):
"""关键断言:25 个预置业务核心不可变;扩展字段仍允许按业务治理新增。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
core_codes = set(service.FIXED_CORE_FIELD_SPECS)
fields = ShippingOrderField.query.order_by(ShippingOrderField.display_sequence).all()
assert len(core_codes) == 25
assert {field.field_code for field in fields} == core_codes
assert service.FIXED_CORE_FIELD_SPECS['bill_to_address'] == ('header', 'string')
assert 'bill_to_customer_code' not in core_codes
bill_to_address = next(field for field in fields if field.field_code == 'bill_to_address')
with pytest.raises(Exception) as error:
service.save_field({
'field_code': 'bill_to_address', 'scope': 'line', 'value_type': 'string',
}, actor_id=None, field_id=bill_to_address.id)
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_FIELD_IMMUTABLE'
extension = service.save_field({
'field_code': 'business_extension', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
assert extension['field_code'] == 'business_extension'
def test_order_schema_publish_keeps_history_when_field_code_changes(app):
"""发布后可重命名系统标识,但旧契约快照保持原名称且位置/类型仍锁定。"""
with app.app_context():
@@ -114,25 +139,27 @@ def test_order_schema_publish_keeps_history_when_field_code_changes(app):
def test_order_schema_business_purposes_bind_stable_line_field_ids(app):
"""业务用途只存在于不可变版本快照,字段改名后仍由原 field_id 供下游定位。"""
"""业务用途绑定固定核心 field_id,发布后仍由该稳定标识供下游定位。"""
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
reservation = service.save_field({
'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
source_hint = service.save_field({
'field_code': 'inventory_source_hint', 'scope': 'line', 'value_type': 'string',
}, actor_id=None)
fields_by_code = {
field.field_code: field
for field in ShippingOrderField.query.filter_by(status='active').all()
}
reservation = fields_by_code['reservation_id']
source_hint = fields_by_code['inventory_source_hint']
draft = service.create_draft({}, actor_id=None)
reservation_config = _field_config(reservation['id'], name='预定单号')
reservation_config = _field_config(reservation.id, name='预定单号')
reservation_config.update({
'normalizer_key': 'uppercase_trim', 'validator_keys': ['reservation_id'],
'comparator_key': 'normalized_text', 'business_purpose': 'reservation_id',
'aliases': ['Reservation ID'],
})
source_hint_config = _field_config(source_hint['id'], name='库存源线索')
source_hint_config = _field_config(source_hint.id, name='库存源线索')
source_hint_config.update({
'normalizer_key': 'uppercase_trim', 'validator_keys': [],
'comparator_key': 'normalized_text', 'business_purpose': 'inventory_source_hint',
'aliases': ['Inventory Source Hint'],
})
_save_draft(draft['id'], [reservation_config, source_hint_config])
@@ -142,15 +169,12 @@ def test_order_schema_business_purposes_bind_stable_line_field_ids(app):
for item in service.get_published_contract()['fields']
}
assert purposes == {
'reservation_id': reservation['id'],
'inventory_source_hint': source_hint['id'],
'reservation_id': reservation.id,
'inventory_source_hint': source_hint.id,
}
service.save_field({
'field_code': 'reservation_number', 'scope': 'line', 'value_type': 'string',
}, actor_id=None, field_id=reservation['id'])
assert next(
item for item in published['definition']['fields'] if item['field_id'] == reservation['id']
item for item in published['definition']['fields'] if item['field_id'] == reservation.id
)['business_purpose'] == 'reservation_id'
@@ -330,7 +354,7 @@ def test_delete_unused_order_field_removes_draft_config_and_catalog_row(app):
assert result == {'field_id': field['id'], 'action': 'deleted'}
assert db.session.get(ShippingOrderField, field['id']) is None
assert service.get_state()['fields'] == []
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.FIXED_CORE_FIELD_SPECS)
assert service.get_state()['versions'][0]['field_count'] == 0
@@ -339,7 +363,7 @@ def test_delete_historical_order_field_archives_and_hides_current_catalog(app):
with app.app_context():
service.initialize_schema({'display_name': '发货订单字段'}, actor_id=None)
field = service.save_field({
'field_code': 'po_number', 'scope': 'header', 'value_type': 'string',
'field_code': 'historical_note', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
draft = service.create_draft({}, actor_id=None)
config = _field_config(field['id'], name='订单号')
@@ -352,7 +376,7 @@ def test_delete_historical_order_field_archives_and_hides_current_catalog(app):
assert result == {'field_id': field['id'], 'action': 'archived'}
assert db.session.get(ShippingOrderField, field['id']).status == 'retired'
assert service.get_state()['fields'] == []
assert {item['field_code'] for item in service.get_state()['fields']} == set(service.FIXED_CORE_FIELD_SPECS)
assert service.get_state()['versions'][0]['id'] == next_draft['id']
assert service.get_state()['versions'][0]['field_count'] == 0
@@ -508,11 +532,14 @@ def test_order_field_global_order_persists_without_schema_draft(app):
'field_code': 'second_header', 'scope': 'header', 'value_type': 'string',
}, actor_id=None)
service.reorder_fields({'field_ids': [second['id'], first['id']]}, actor_id=None)
core_ids = [field.id for field in ShippingOrderField.query.filter_by(status='active').order_by(
ShippingOrderField.display_sequence
) if field.id not in {first['id'], second['id']}]
service.reorder_fields({'field_ids': [*core_ids, second['id'], first['id']]}, actor_id=None)
refreshed = service.get_state()
assert [item['id'] for item in refreshed['fields']] == [second['id'], first['id']]
assert [item['display_sequence'] for item in refreshed['fields']] == [1, 2]
assert [item['id'] for item in refreshed['fields']][-2:] == [second['id'], first['id']]
assert [item['display_sequence'] for item in refreshed['fields']][-2:] == [26, 27]
assert not any(item['status'] == 'draft' for item in refreshed['versions'])
@@ -0,0 +1,46 @@
"""
backend/tests/test_shipping_order_snapshot_migration.py
用途:验证冻结订单快照迁移可在隔离 SQLite 数据库升级和降级。
依赖:Alembic migration module、临时 SQLite 连接。
逻辑:迁移创建 Snapshot、行和复核审计表以及 Task 引用;降级完整移除新增结构。
"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_shipping_order_snapshot_migration_upgrade_and_downgrade(monkeypatch):
"""关键断言:升级后快照可保存 field_id 值,降级后不残留新增表和 Task 引用。"""
migration = importlib.import_module('migrations.versions.019fa1b2c3d4_add_shipping_order_snapshots')
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_customers', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_order_extractions', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_order_schema_versions', metadata, sa.Column('id', sa.Integer(), primary_key=True))
sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer(), primary_key=True))
metadata.create_all(engine)
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
monkeypatch.setattr(migration, 'op', operations)
migration.upgrade()
inspector = sa.inspect(connection)
assert {'shipping_order_snapshots', 'shipping_order_snapshot_lines', 'shipping_order_review_events'} <= set(inspector.get_table_names())
assert 'order_snapshot_id' in {item['name'] for item in inspector.get_columns('shipping_tasks')}
assert 'header_values_json' in {item['name'] for item in inspector.get_columns('shipping_order_snapshots')}
assert 'field_values_json' in {item['name'] for item in inspector.get_columns('shipping_order_snapshot_lines')}
migration.downgrade()
inspector = sa.inspect(connection)
assert 'shipping_order_snapshots' not in inspector.get_table_names()
assert 'shipping_order_snapshot_lines' not in inspector.get_table_names()
assert 'shipping_order_review_events' not in inspector.get_table_names()
assert 'order_snapshot_id' not in {item['name'] for item in inspector.get_columns('shipping_tasks')}
@@ -0,0 +1,81 @@
"""
backend/tests/test_shipping_rolling_fulfillment.py
用途:验证 SHIP_AVAILABLE_ROLLING 的预约单注册和多轮库存核验。
依赖:冻结订单快照、reservation_service、Flask 测试库。
逻辑:本轮仅完整满足的预约单可进入 available;缺货项保留 pending 并可在下一轮变为 available。
"""
from __future__ import annotations
from decimal import Decimal
from app import db
from app.models import ShippingOrderSnapshotLine, ShippingReservation
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
record_inventory_verification,
)
from tests.services.shipping_notice.test_shipping_order_snapshot import _build_accepted_order
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
def test_rolling_verification_keeps_shortage_pending_and_later_releases_it(app):
"""关键断言:部分满足时不生成半量预约单,后续补货轮次才将其转为 available。"""
with app.app_context():
task, user = _build_accepted_order()
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
db.session.commit()
line = snapshot.lines[0]
first = record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[{
'reservation_id': line.reservation_id, 'part_number': line.part_number,
'required_qty': Decimal('12.5'), 'available_qty': Decimal('8'), 'line_status': 'partial',
}])
db.session.commit()
assert first.lines[0].status == 'shortage'
assert first.result_json['available_count'] == 0
second = record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[{
'reservation_id': line.reservation_id, 'part_number': line.part_number,
'required_qty': Decimal('12.5'), 'available_qty': Decimal('12.5'), 'line_status': 'ok',
}])
db.session.commit()
assert second.lines[0].status == 'available'
assert second.result_json['available_count'] == 1
def test_rolling_reservation_only_selects_unoccupied_lines_in_later_round(app):
"""A/B 首轮占用后,C 补货只能进入第二轮;首轮 Artifact 不得被覆盖或重复占用。"""
with app.app_context():
task, user = _build_accepted_order()
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
first_line = snapshot.lines[0]
second_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=1, part_number='000124', reservation_id='0012345679',
qty=Decimal('4'), field_values_json={},
)
third_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=2, part_number='000125', reservation_id='0012345680',
qty=Decimal('3'), field_values_json={},
)
snapshot.lines.extend([second_line, third_line])
db.session.flush()
first = record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v1', line_results=[
{'reservation_id': first_line.reservation_id, 'part_number': first_line.part_number, 'required_qty': '12.5', 'available_qty': '12.5', 'line_status': 'ok'},
{'reservation_id': second_line.reservation_id, 'part_number': second_line.part_number, 'required_qty': '4', 'available_qty': '4', 'line_status': 'ok'},
{'reservation_id': third_line.reservation_id, 'part_number': third_line.part_number, 'required_qty': '3', 'available_qty': '1', 'line_status': 'partial'},
])
_verification, first_available = current_available_snapshot_line_ids(task)
assert first_available == {first_line.id, second_line.id} # A/B 首轮完整满足。
ShippingReservation.query.filter(
ShippingReservation.snapshot_line_id.in_(first_available),
).update({'status': 'artifact_reserved'}, synchronize_session=False)
second = record_inventory_verification(task, inventory_snapshot_id=None, source_config_version='v2', line_results=[
{'reservation_id': first_line.reservation_id, 'part_number': first_line.part_number, 'required_qty': '12.5', 'available_qty': '12.5', 'line_status': 'ok'},
{'reservation_id': second_line.reservation_id, 'part_number': second_line.part_number, 'required_qty': '4', 'available_qty': '4', 'line_status': 'ok'},
{'reservation_id': third_line.reservation_id, 'part_number': third_line.part_number, 'required_qty': '3', 'available_qty': '3', 'line_status': 'ok'},
])
_verification, second_available = current_available_snapshot_line_ids(task)
assert second.id > first.id
assert second_available == {third_line.id} # C 后续补货,只能进入第二轮。
@@ -0,0 +1,39 @@
"""
backend/tests/test_shipping_rolling_fulfillment_migration.py
用途:验证滚动履约事实表迁移可升级、可回滚。
依赖:Alembic Operations、SQLite 最小前置表。
逻辑:覆盖预约单注册、库存核验与 Artifact 行归属三类结构。
"""
from __future__ import annotations
import importlib
import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
def test_rolling_fulfillment_migration_upgrade_and_downgrade(monkeypatch):
"""迁移必须建立所有滚动制单事实表,回滚后不保留业务表。"""
migration = importlib.import_module('migrations.versions.022a3b4c5d6e_add_shipping_rolling_fulfillment')
engine = sa.create_engine('sqlite:///:memory:')
metadata = sa.MetaData()
for table in ('shipping_tasks', 'shipping_order_snapshot_lines', 'shipping_export_artifacts', 'shipping_inventory_files'):
sa.Table(table, metadata, sa.Column('id', sa.Integer(), primary_key=True))
metadata.create_all(engine)
with engine.begin() as connection:
context = MigrationContext.configure(connection)
operations = Operations(context)
monkeypatch.setattr(migration, 'op', operations)
migration.upgrade()
tables = set(sa.inspect(connection).get_table_names())
assert {
'shipping_reservations', 'shipping_inventory_verifications',
'shipping_inventory_verification_lines', 'shipping_export_artifact_lines',
} <= tables
migration.downgrade()
tables = set(sa.inspect(connection).get_table_names())
assert 'shipping_reservations' not in tables
assert 'shipping_export_artifact_lines' not in tables
@@ -13,7 +13,7 @@ from types import SimpleNamespace
from app import db
from app.models import (
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
ShippingTask, ShippingTaskFieldConflict,
ShippingOrderReviewEvent, ShippingTask, ShippingTaskFieldConflict,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice.task_candidate_reconciliation import (
@@ -26,6 +26,16 @@ from app.services.shipping_notice.task_field_gate import field_conflict_gate_res
from app.services.shipping_notice.task_workflow import add_notice_line, update_notice_line
def _review_payload() -> dict[str, str | int]:
"""提供工作台人工纠错的最小审计上下文,避免测试绕过生产门禁。"""
return {
'event_source': 'workspace_api',
'reviewed_by_id': 1,
'evidence_ref': 'asset://review/order.png',
'reason': '原始订单附件已复核',
}
def _task(**kwargs) -> ShippingTask:
task = ShippingTask(
task_no=kwargs.pop('task_no', 'SN-RECON-001'),
@@ -55,9 +65,14 @@ def _candidate(summary_lines: list[dict], *, po_number: str = 'PO-100') -> Simpl
def _attach_dynamic_extraction(task: ShippingTask, rows: list[dict]) -> dict[str, str]:
"""建立候选对账所需的动态 FieldValue,测试不得依赖固定订单行投影。"""
order_schema_service.initialize_schema({'display_name': '对账字段'}, actor_id=None)
existing_fields = {
item['field_code']: item
for item in order_schema_service.get_state()['fields']
}
fields = {
code: order_schema_service.save_field(
{'field_code': code, 'scope': scope, 'value_type': value_type}, actor_id=None,
field_id=existing_fields.get(code, {}).get('id'),
)
for code, scope, value_type in (
('po_number', 'header', 'string'),
@@ -192,6 +207,8 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app):
expected_conflict_version=conflict.conflict_version,
expected_order_data_version=task.order_data_version,
resolved_by_id=1,
evidence_ref='asset://review/conflict-1.png',
reason='原始订单附件已复核',
idempotency_key='resolve-1',
)
assert first['idempotent_replay'] is False
@@ -201,11 +218,16 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app):
).one()
assert value.value_json == '3000092917'
assert ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').count() == 0
event = ShippingOrderReviewEvent.query.filter_by(task_id=task.id, field_code='reservation_id').one()
assert event.evidence_ref == 'asset://review/conflict-1.png'
assert event.reason == '原始订单附件已复核'
replay = resolve_field_conflict(
task=task,
conflict_id=conflict.id,
resolution='take_incoming',
evidence_ref='asset://review/conflict-1.png',
reason='原始订单附件已复核',
idempotency_key='resolve-1',
)
assert replay['idempotent_replay'] is True
@@ -225,6 +247,7 @@ def test_update_notice_line_version_mismatch(app):
'line_index': 0,
'patch': {'inventory_source_hint': 'H9'},
'expected_order_data_version': 1,
**_review_payload(),
})
# replace 已 bump version,再带 1 应失败;先读当前版本再测过期。
task = db.session.get(ShippingTask, task.id)
@@ -234,6 +257,7 @@ def test_update_notice_line_version_mismatch(app):
'line_index': 0,
'patch': {'inventory_source_hint': 'H8'},
'expected_order_data_version': stale,
**_review_payload(),
})
assert resp['status'] == 'failed'
assert resp['data']['error_code'] == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
@@ -259,6 +283,7 @@ def test_add_notice_line_creates_new_extraction_and_preserves_header_values(app)
result = add_notice_line({
'task_id': task.task_no,
'line': {'reservation_id': '3000000002'},
**_review_payload(),
})
assert result['status'] == 'ok'
current = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
@@ -18,7 +18,15 @@ from app.models import (
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingExportArtifactLine,
ShippingInventoryParsingProfile,
ShippingInventoryVerification,
ShippingInventoryVerificationLine,
ShippingReservation,
ShippingTask,
ShippingUploadAttempt,
User,
)
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
@@ -126,6 +134,78 @@ def test_serialize_task_detail_projects_parse_gates_and_source_candidate(app):
assert detail['source_candidate']['candidate_no'] == 'SNC-PARSED-PROJECTION-001'
assert detail['source_candidate']['missing_fields'] == ['inventory_source_hint']
assert detail['source_candidate']['evidence'][0]['reservation_id'] == '1000140351'
assert detail['order_snapshot_id'] is None
def test_serialize_task_detail_projects_fulfillment_timeline(app):
"""DETAIL 必须按履约事实投影核验轮次、Artifact 与上传 Attempt,不回读 Task 冗余字段。"""
with app.app_context():
task = ShippingTask(task_no='SN-FULFILLMENT-TIMELINE-001')
template = ShippingExcelTemplate(
template_code='TIMELINE', display_name='Timeline', version=1, status='published', storage_bucket='test',
storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='TIMELINE', display_name='Timeline', version=1, status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Timeline')
db.session.add_all([task, template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='EXP-FULFILLMENT-TIMELINE-001', task_id=task.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, file_path='test.xlsx',
file_name='test.xlsx', file_checksum='d' * 64, file_size=12, status='ready',
)
reservation = ShippingReservation(
task_id=task.id, snapshot_line_id=1, reservation_id='RES-TIMELINE-001', part_number='PN-TIMELINE',
required_qty=2, status='artifact_reserved', current_artifact_id=None,
)
db.session.add_all([artifact, reservation])
db.session.flush()
verification = ShippingInventoryVerification(task_id=task.id, status='completed', result_json={})
db.session.add(verification)
db.session.flush()
verification_line = ShippingInventoryVerificationLine(
verification_id=verification.id, reservation_id=reservation.id, required_qty=2, available_qty=3, status='available', detail_json={},
)
db.session.add(verification_line)
db.session.flush()
db.session.add(ShippingExportArtifactLine(
artifact_id=artifact.id, reservation_id=reservation.id, verification_line_id=verification_line.id,
))
db.session.add(ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=1, mode='rpa', idempotency_key='timeline-rpa-key',
callback_id='timeline-callback', status='succeeded', freight_ref_no='FREIGHT-001',
))
db.session.commit()
detail = serialize_task_detail(task)
assert detail['inventory_verifications'][0]['lines'] == [{
'reservation_id': reservation.id, 'required_qty': '2.00000000', 'available_qty': '3.00000000', 'status': 'available',
}]
assert detail['export_artifacts'][0]['artifact_no'] == artifact.artifact_no
assert detail['export_artifacts'][0]['reservation_ids'] == [reservation.id]
assert detail['upload_attempts'][0]['callback_id'] == 'timeline-callback'
assert detail['upload_attempts'][0]['freight_ref_no'] == 'FREIGHT-001'
def test_serialize_task_detail_projects_frozen_snapshot_marker(app):
"""关键断言:工作台必须知道订单已冻结,避免错误展示再次冻结入口。"""
with app.app_context():
task = ShippingTask(task_no='SN-FROZEN-MARKER-001', order_snapshot_id=42)
db.session.add(task)
db.session.commit()
detail = serialize_task_detail(task)
assert detail['order_snapshot_id'] == 42
def test_serialize_candidate_brief_exposes_evidence_and_missing_fields(app):
@@ -0,0 +1,88 @@
"""
用途:验证 Artifact 级 RPA 上传 Attempt、回调幂等与预约单终态锁定。
依赖:上传 Attempt 服务、滚动履约模型、Flask 测试库。
逻辑:构造包含一个预约单的 ready Artifact,重复回调仅生效一次,失败不完成预约单。
"""
from __future__ import annotations
from decimal import Decimal
import pytest
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingExportArtifact, ShippingExportArtifactLine, ShippingExcelTemplate, ShippingInventoryParsingProfile,
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingReservation, ShippingTask,
ShippingUploadAttempt,
)
from app.services.shipping_notice.upload_attempt_service import complete_attempt, start_rpa_attempt, void_rejected_artifact
def _ready_artifact() -> tuple[ShippingTask, ShippingExportArtifact, ShippingReservation]:
"""建立 Attempt 服务需要的最小 ready Artifact 与已占用预约单。"""
task = ShippingTask(task_no='TASK-UPLOAD-ATTEMPT')
template = ShippingExcelTemplate(
template_code='ATTEMPT', display_name='Attempt', version=1, status='published', storage_bucket='test',
storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(profile_code='ATTEMPT', display_name='Attempt', version=1, status='published', file_format='xlsx', definition_json={})
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add_all([task, template, profile, schema]); db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version); db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted')
db.session.add(extraction); db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='EXP-UPLOAD-ATTEMPT', task_id=task.id, template_id=template.id, order_schema_version_id=version.id,
order_extraction_id=extraction.id, inventory_parsing_profile_id=profile.id, input_checksum='b' * 64,
file_path='test.xlsx', file_name='test.xlsx', file_checksum='c' * 64, file_size=1, status='ready',
)
db.session.add(artifact); db.session.flush()
reservation = ShippingReservation(
task_id=task.id, snapshot_line_id=1, reservation_id='RES-UPLOAD-1', part_number='PN-1',
required_qty=Decimal('1'), status='artifact_reserved', current_artifact_id=artifact.id,
)
db.session.add(reservation); db.session.flush()
db.session.add(ShippingExportArtifactLine(artifact_id=artifact.id, reservation_id=reservation.id, verification_line_id=1))
db.session.flush()
return task, artifact, reservation
def test_upload_callback_is_idempotent_and_locks_reservation(app):
"""相同回调重复十次只接受一次,Artifact 成功后预约单永久进入 uploaded。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key='rpa-key')
complete_attempt(attempt, success=True, callback_id='callback-1', freight_ref_no='F-1')
for _ in range(10):
assert complete_attempt(attempt, success=True, callback_id='callback-1').id == attempt.id
assert ShippingUploadAttempt.query.count() == 1
assert db.session.get(ShippingReservation, reservation.id).status == 'uploaded'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploaded'
with pytest.raises(ConflictError):
start_rpa_attempt(task, artifact_id=artifact.id)
def test_failed_attempt_does_not_complete_reservation(app):
"""RPA 失败仅释放 Artifact 重试状态,不能把预约单错误标记为上传完成。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
complete_attempt(attempt, success=False, callback_id='callback-failed', error_message='network')
assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved'
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'ready'
def test_only_explicit_rejection_can_void_and_release_artifact(app):
"""网络失败不能释放预约单;货代明确拒绝且有授权后才可重新进入库存核验。"""
with app.app_context():
task, artifact, reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
complete_attempt(attempt, success=False, callback_id='callback-rejected', error_message='freight_rejected: invalid document')
with pytest.raises(ValidationError):
void_rejected_artifact(task, artifact_id=artifact.id, operator_id=0, reason='')
void_rejected_artifact(task, artifact_id=artifact.id, operator_id=1, reason='货代明确拒绝')
assert db.session.get(ShippingExportArtifact, artifact.id).status == 'superseded'
assert db.session.get(ShippingReservation, reservation.id).status == 'pending'
+21 -2
View File
@@ -156,7 +156,7 @@
- 管理员可维护字段稳定 ID、`field_code`、名称、Header/Line 作用域、类型、别名、规范化、校验、证据和跨文档关联策略。
- 字段首次发布后,稳定 ID、作用域和类型不可原地修改;`field_code` 可重命名并只影响后续草稿,历史发布快照保留旧值;识别规则变更须创建新的不可变 Schema 版本。
- 订单 Schema 必须覆盖库存源路由、库存匹配和发货 Excel 所需的订单字段;下游配置引用稳定字段 ID,不引用显示名称。
- 已接受订单的唯一真相为 `ShippingOrderExtraction` 及其 `Decision/FieldValue`;Task 只通过 `current_order_extraction_id` 锁定版本。不得保存或读取固定订单头/行列、JSON 行快照或兼容投影。
- 已接受订单的解析真相为 `ShippingOrderExtraction` 及其 `Decision/FieldValue`;Task 以 `current_order_extraction_id` 追溯解析版本。完成复核、客户绑定和冻结后,`ShippingOrderSnapshot/Line` 是库存、导出、上传的唯一业务真相;不得以 JSON 行快照或兼容投影替代 Snapshot。
- 管理端必须使用后端字段目录和白名单提供结构化选择器,不要求业务管理员直接编辑 Profile/模板 JSON;发布新 Schema 版本时,若移除仍被路由、库存解析 Profile 或 Excel 模板引用的字段,必须阻断并要求先迁移下游配置。
- 发货 Excel 模板必须独立版本化管理并由库存源绑定 published 版本;多个同结构库存源共享同一模板,不得在库存源中复制映射。模板发布后文件和映射不可变。
- 库存站点允许先以禁用状态保存基础信息,逐步通过测试导出确认库存文件解析方案并绑定 published 发货模板;首次保存不要求手工选择解析方案。正式启用是独立门禁动作,必须完成连接、测试导出与解析验证、解析方案、发货模板和仓库映射;一旦启用,各项绑定必须齐全且有效。固定仓须维护该货代仓的精确映射或库存源默认映射;动态仓还须从测试文件识别仓库栏位并覆盖测试样例中的每个仓库。系统绝不根据名称相似度自动创建外部仓库映射。
@@ -184,13 +184,29 @@
- Reservation ID 统一为 5 位或 10 位纯数字;字母型编号、其他长度数字、32 位十六进制内部主键和 UUID 均不得进入订单关联或库存匹配。
- 自动纠错必须具备表头列关系和唯一 SKU/APN/MPN 关联证据;拍平文本或多义匹配不得猜测,必须进入人工复核。
- 后端必须保留原始候选、修正值、原因与证据;任何 blocking 问题不得被 LLM 高置信度或人工“确认”动作绕过。
- 订单持久化:Task 通过 `current_order_extraction_id` 锁定 `ShippingOrderExtraction/Line/Decision/FieldValue` 唯一真相;不保留固定订单表、JSON 快照或兼容回滚。Candidate→既有 Task 仅允许空 FieldValue 安全补齐,双方非空且不同时落字段冲突并阻断库存/匹配/导出;人工改单须带 `expected_order_data_version`。
- 订单持久化:Task 通过 `current_order_extraction_id` 追溯 `ShippingOrderExtraction/Line/Decision/FieldValue` 解析真相,并通过 `order_snapshot_id` 关联冻结业务真相。Candidate 纠错只发生于冻结前;冻结后不得编辑 Snapshot,客户修订必须创建新 Candidate/新 Snapshot。人工纠错须携带乐观锁版本、原值/新值、证据和原因。
- **同请求去重**:上传接入阶段按源文件 SHA-256 去重,相同内容只抽取、建任务一次。
- **建单幂等**:`ShippingBatch.create_idempotency_key` 防止双击、重试与并发重复建批;数据库唯一约束 `(user_id, create_idempotency_key)` 提供最终保护。
- **内容指纹**:`ShippingTask.source_content_hash` 记录完整文件哈希,支持跨请求精确重复检测。
- **语义分离**:货代上传幂等仍使用 `ShippingTask.idempotency_key`,不与建单幂等键混用。
### 2.x 发货通知滚动履约领域契约(阶段 0,2026-07-22)
本节是发货通知后续阶段的冻结业务契约;与本文件此前关于订单真相、制单条件或单份 Excel 的描述不一致时,以本节为准。
- 履约策略固定为 `SHIP_AVAILABLE_ROLLING`:每轮有效库存核验中,只要至少一个预约单满足,即可由用户确认生成本轮 Excel;系统必须将该任务中全部“满足且未被有效 Excel 占用”的预约单一并写入该 Excel,缺货项继续等待下一轮库存。
- **试点容量与恢复(阶段 7)**:批量通知文件数、单文件大小、EML 附件数量/单附件大小/总大小均须由环境变量限制,超限在解析和建单前返回明确业务错误;试点先以 3–5 个高频模板逐个完成独立盲测,再根据管理员健康接口记录的 P50/P95、失败率、积压与 RPA 耗时确定正式 SLA。Worker 重启恢复、同文件幂等重试和备份恢复演练均须留存环境、时间、操作者、结果与问题记录;演练失败不得启用自动建单或自动上传。
- 一个附件可形成一个业务任务,但一个任务可形成多份按时间顺序的 Excel Artifact。全部缺货时不得产生空 Excel;已成功上传的预约单永久不得再次制单;仅当任务全部当前有效预约单均上传成功时才完成。
- `FieldValue` 仅是解析阶段的 Observation/Decision 投影;人工复核和客户绑定完成后冻结 `OrderSnapshot` 及其行作为库存、制单、上传的正式业务真相。冻结快照不可编辑,后续客户修订必须形成新快照版本。
- 预置核心字段同步保存为强类型列;管理员可新增扩展字段,已发布库存路由、Excel 模板或 RPA 配置需要使用时,Snapshot 按稳定 `field_id` 一并冻结并只由该快照提供值。扩展字段是否参与履约由业务配置决定,不得回读可变 `FieldValue`。
- **字段计数校正**:预置业务核心为 13 个 Header 和 12 个 Line(共 25 个)。历史蓝图中的“26 个”包含已废弃的 `bill_to_customer_code`;该字段已按业务决定替换为 `bill_to_address`,不会重新引入。`position` 是明细行内部排序键,不是可抽取或可配置的业务字段。管理员仍可按治理规则新增扩展字段。
- 预约单以全局注册表管理,而非以历史订单行文本去重。唯一预约单在任一时刻只能处于 `pending`、`available`、`artifact_reserved`、`uploaded` 或 `external_change_required` 之一,并只允许归属一个有效 Artifact。
- Excel 文件名允许由已发布 Excel 模板的版本化命名规则定义;没有模板规则时可使用受控环境变量默认规则。后端必须校验规则、生成最终文件名并在 Artifact 冻结规则来源/版本、文件名和流水;前端、Dify 或普通用户不得提交任意文件名。
- Dify 仅生成候选 Observation,不能创建 Task、冻结 Snapshot、选择库存、生成 Excel 或触发上传。任何关键字段含未人工确认的 LLM fallback Observation 时,必须转人工复核并阻断自动冻结。
- 人工上传是 RPA 的受控降级,必须上传截图或回执文件;没有外部成功证据不得将预约单标记为已上传。
- 上传以 Excel Artifact 为边界:每次 RPA 或人工操作均创建独立 Attempt,trigger 和回调必须携带 `artifact_id`、`attempt_id` 与幂等 `callback_id`。相同回调只生效一次;网络失败只能重试原 Artifact,只有货代明确拒绝并经授权才可作废 Artifact、释放未上传预约单;Task 上传字段仅为 Artifact/Attempt 的聚合投影。
### 3.1 本期范围
- 查询员工本人假期余额
@@ -562,3 +578,6 @@
- L6 要求所有 accepted Observation 具有稳定证据引用;无 cell 的纯文本表格只能形成复核原因,不能作为已验证后端表格证据。跨文档关联必须使用同 Document 强身份,禁止以 Qty 等常见值串接订单行。
- 自动建单配置位于“货代配置 → 订单字段模板”:管理员只维护一个自动建单总开关;每个字段独立标记为建单关键字段并设置自身最低置信度。每个 Run 冻结开关与字段快照;阈值不能绕过必填、证据、冲突、重复和 Reservation 等硬门禁。
- 终态且未消费的订单抽取 Run 支持“按当前规则重新识别”:创建新的可审计 Run,重新冻结当前 Schema、执行绑定、文档 Profile 与 ready 布局;旧候选在新版执行期间不可建单,新版失败后恢复旧版。失败 Run 的基础设施重试仍复用原冻结 Run,不得与重新识别混用。
- **模板自动建单资格**:Profile 发布仅表示可作为受控解析候选,不等于可跳过 Dify。每个已发布 Profile 版本必须建立独立盲测集,至少 3 个独立样本全部按管理员确认真值通过,并由管理员批准;资格与 Profile checksum 绑定,checksum 变化立即失效。唯一命中的已批准 Profile 才可确定性建单,未知、多模板、行解析异常或未批准时一律回退 Dify/人工复核。
- **Dify 证据边界**:Dify 输出只能使用冻结 `extraction_contract` 中的 field_id,所有 Observation 必须引用当前 Unit 文档且 quote 可在冻结输入中逐字验证;不得回传确定性上下文字段或覆盖已锁定值。Dify 画布由管理员在最终验收时手工配置,HXOPS 不修改画布。
- **客户绑定与冻结**:订单原文、按 `order-customer-fingerprint.v1` 标准化生成的身份指纹、正式 `customer_id` 三层分离保存。Bill-to 是订购客户;只有已人工确认并写明理由的 Bill-to 匹配可以冻结为 Snapshot。调用方不能在冻结请求中自由传入客户或简码;Snapshot 固化客户简码和匹配规则版本,客户后续改名、合并或规则变化不回写历史。
+25 -19
View File
@@ -74,8 +74,8 @@
- 先上传或粘贴**发货通知**,确认解析结果
- 库存由已配置站点自动准备;仅在系统提示时刷新库存
- 匹配结果若有缺口,**默认无法发货**;须补库存或返回修订后重匹配
- 全部行满足后,下载/确认**发货 Excel**,并完成货代上传
- 匹配结果有缺口时,缺货预约单继续等待补货;本轮已满足预约单仍可进入滚动制单
- 至少一个预约单满足时,生成包含全部当前可用预约单的**本轮发货 Excel**,并完成该文件的货代上传
**系统如何工作(便于理解)**:
@@ -301,12 +301,12 @@ WYC26071501
- 必须先确认**发货通知和标准客户**,再处理**库存**。
- 库存文件必须通过库存站点已发布解析方案的结构校验,才能执行**库存匹配**。
- 只有**全部订单行满足**后,才能生成 Excel 并上传货代;存在缺口时系统会阻断后续步骤。
- 使用 `SHIP_AVAILABLE_ROLLING`:只要本轮库存中至少一个预约单满足,业务人员即可生成本轮 Excel。系统自动纳入该任务全部“已满足且未被有效 Excel 占用”的预约单;缺货项继续等待补货,不能进入本轮 Excel。
**一句话 SOP**
```text
发货通知 → 确认解析 → 确认客户并生成业务编号 → 获取或上传库存 → 系统校验并解析 → 匹配库存 → (有缺口则阻断)→ 生成 Excel → 上传货代
发货通知 → 确认解析 → 确认客户并生成业务编号 → 获取或上传库存 → 系统校验并解析 → 匹配库存 → (有满足项则生成本轮 Excel;缺货项继续等待)→ 上传货代
```
---
@@ -358,6 +358,8 @@ WYC26071501
系统会根据发货通知中的客户名称、发件人等已审核线索推荐标准客户。您需要确认推荐客户是否正确;若未匹配或存在多个候选,请选择已有客户或提交新客户申请。
确认订购客户时需填写简短确认理由。系统保留订单原文和本次匹配指纹,不会用客户主数据名称替换订单原文;冻结后客户改名或合并也不会改变历史发货文件使用的客户简码。
客户确认后,系统生成类似 `WYC26071501` 的业务编号。客户未确认前不会进入库存处理;Agent 不会自行创建客户简码。
---
@@ -421,16 +423,16 @@ WYC26071501
### 阶段 ⑦ — 库存不足时的处理
若存在缺口,系统会**暂停并阻断发货**,展示缺口明细,并引导您补库存或返回修订(详见 [§8](#8-库存不足时的处理))。**不可**按可发数量部分发货。
若存在缺口,系统会展示缺口明细;缺货预约单暂停等待补货,已完整满足的预约单可进入本轮发货。**不可**按同一预约单的可发数量拆分发货。
---
### 阶段 ⑧⑨ — 生成 Excel 与上传货代
**全部行满足**后:
**至少一个预约单满足**后:
1. 系统生成发货 Excel(可在任务详情或助手提示中下载);
2. 尝试自动上传货代;若自动化未完成,会提示您手工上传并在系统中登记货代单号。
1. 业务人员确认后,系统生成包含全部当前满足且未被占用预约单的本轮发货 Excel(可在任务详情或助手提示中下载);
2. 系统尝试自动上传该 Excel;若自动化未完成,会提示您手工上传并上传截图或回执文件。
---
@@ -459,19 +461,19 @@ WYC26071501
## 8. 库存不足时的处理
存在任一行缺口时,**默认禁止发货**,不可进入生成 Excel 与上传货代环节。系统会展示缺口明细(内部料号、需求数量、可用数量、缺口数量),您可选择:
存在缺口时,系统会展示缺口明细(内部料号、需求数量、可用数量、缺口数量)。已完整满足的预约单可先生成本轮 Excel;缺货预约单可选择:
| 您的选择 | 含义 | 后续 |
|----------|------|------|
| **重新上传库存** | 仓库/货代已更新库存文件 | 系统先解除当前库存关联并清理旧匹配结果,再按发布方案校验新文件并匹配 |
| **联系管理员修订解析方案** | 正式库存文件结构确实发生变化 | 管理员用样本创建新版本、测试并发布后重新上传 |
| **重新匹配** | 订单或库存数据已修订,需重新比对 | 在同一份已确认数据上再次执行匹配 |
| **驳回** | 本单暂无法处理 | 终止任务,不生成发货文件 |
| **驳回** | 本单暂无法处理 | 仅在尚无有效 Artifact 且符合任务处置规则时终止任务 |
**重要说明**:
- 本期**不支持**「确认部分发货」或按可发数量继续出单;须**全部订单行满足**后方可继续。
- 补库存后请重新上传 Excel;系统会按发布方案重新校验和匹配,直至结果变为「完全满足」。
- 本期支持按预约单滚动履约,但不支持按同一预约单的可发数量拆分。仅完整满足的预约单可出单,缺货预约单须等待补货后再次核验。
- 补库存后请重新获取或上传库存文件;系统会按发布方案创建新的核验轮次,并仅将新满足且未占用的预约单放入下一份 Excel。
若任务已被驳回,助手可能建议「重新创建发货任务」;此时应**新开对话**处理新单据,勿在已驳回任务上继续点「确认对齐」类按钮。
@@ -481,8 +483,8 @@ WYC26071501
### 9.1 发货 Excel
- 在**全部订单行满足**后自动生成;
- 内容基于已确认的订单行与匹配结果,含全部应发行;
- 在至少一个预约单本轮满足、且业务人员确认生成后创建;
- 内容基于冻结订单快照和本轮匹配结果,含全部当前可用且未被有效 Artifact 占用的预约单;
- 具体列布局取决于公司配置的货代模板(需业务与 IT 共同确认)。
### 9.2 上传货代
@@ -507,9 +509,10 @@ WYC26071501
| 解析已确认 | 发货通知无误,待提供库存 |
| 待库存 / 库存处理中 | 已收到或正在处理库存文件 |
| 库存结构异常 | 文件与库存站点发布解析方案不一致,须换文件或联系管理员修订方案 |
| 已匹配 | 库存比对完成且全部行满足 |
| 库存不足,无法发货 | 存在缺口,须补库存或返回修订后重匹配 |
| 已生成 Excel | 发货文件已就绪 |
| 已匹配 | 本轮库存比对完成,可能同时存在满足项和缺货项 |
| 待补货 | 当前没有可制单预约单,或剩余预约单均有缺口 |
| 可生成本轮 Excel | 至少一个预约单满足,等待生成包含全部可用项的 Artifact |
| 已生成 Excel | 至少一份发货文件已就绪,剩余缺货预约单仍可等待下一轮 |
| 上传中 / 已上传 | 货代侧处理中或已完成 |
| 已驳回 | 本任务终止 |
@@ -605,11 +608,14 @@ WYC26071501
## 13. 常见问题
**Q:库存不够时能否先发有货的部分?**
A:不可以。存在任一行缺口时,系统**默认禁止发货**,须补库存或返回修订后重新匹配,直至**全部订单行满足**后方可生成 Excel 并上传货代。
A:可以。只要至少一个预约单本轮库存满足,就可以生成 Excel;系统会自动包含所有当前满足且未被占用的预约单,不能手工挑选排除已满足项。缺货预约单保留在任务中,补货并重新核验后生成下一份 Excel。
**Q:为什么要先确认发货通知,再传库存?**
A:避免任务编号不一致、订单行未定型就占用库存比对,导致结果不可追溯。
**Q:模板已经发布,为什么仍可能需要人工复核或调用 Dify?**
A:发布只表示模板可受控使用。只有该模板完成至少 3 份独立样本盲测、全部通过并经管理员批准后,才具备确定性自动建单资格;模板版本或校验和变化、多模板同时命中、字段不完整或行异常都会回退复核。Dify 配置不由业务人员在此处修改,最终由管理员按技术手册统一验收。
**Q:库存 Excel 很大,可以粘贴到聊天吗?**
A:不可以。请使用「选择库存文件」上传;整表粘贴易失败且无法保证列映射准确。
@@ -659,4 +665,4 @@ A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理;
| 业务文档 | `docs/features/shipping-notice/business.md`(本文件) |
| 技术文档 | `docs/features/shipping-notice/technical.md` |
| 同步维护 | 流程、字段、确认节点变更时 **两份文档一并更新** |
| 最近更新 | 2026-06-17:缺口策略收敛为「存在缺口默认禁止发货」,移除部分发货 |
| 最近更新 | 2026-07-22:履约策略更新为 `SHIP_AVAILABLE_ROLLING`;允许完整满足的预约单分轮制单,仍禁止按同一预约单拆分可发数量 |
+38 -9
View File
@@ -118,16 +118,16 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
### L7 影子与正式切换准备(2026-07-22)
- 已删除 Worker 的 Profile/纯文本确定性零 Provider 路径。现在只有完整 `mapping_status=accepted` layout 表格可以跳过 Provider;纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。
- 纯文本表格即使字段齐全也必须进入模型补充和后端 needs_review 门禁。Profile 发布本身只提供紧凑候选;只有唯一命中的 Profile 已完成独立盲测资格(至少 3 样本全通过、管理员批准且 checksum 未漂移)时,才可由该 Profile 的实际解析行零 Provider 建单。
- Profile 仍可生成不含 HTML/bbox/token 的紧凑候选供模型参考,并继续执行零 Qty 删除等候选清洗,但未获得 accepted cell 前不能直接生成订单。
- 自动建单只能在质量门禁满足时由 Schema 策略开启;它不依赖 Dify 输入格式开关。
- L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、Runtime Binding、质量门禁与迁移共 `247 passed`;前端生产构建通过,Alembic 唯一 head 为 `a72f8091a2b8`,`git diff --check` 通过。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。
- L7 最终工程 Review 覆盖 L0-L7 布局、Intake、Schema、订单抽取、Runtime Binding、质量门禁与迁移共 `247 passed`;前端生产构建通过。该记录的历史基线 head 为 `a72f8091a2b8`;当前货代履约链部署必须以 `023a4b5c6d7e` 为唯一 Alembic head,`git diff --check` 通过。静态检查确认 `build_deterministic_unit_orders` 不再调用纯文本表格解析器。
**L7 当前验收结论:未通过,不得开启自动建单。** 缺少人工单元格真值、真实字段准确率/召回率、解析性能指标、100 个影子 Run、20 个测试环境真实 Run、业务/技术负责人批准及 Dify 实际配置验收。当前完成的是安全切换准备,不是 L7 完成。
人工真值已明确延期后,工程侧新增不可绕过的 L7 质量批次门禁:批次锁定 Owner、当前发布 Schema 与阈值版本;同一真实 Run 必须由两名不同管理员提交完全一致的匿名计数才进入指标,至少 100 个一致样本且 precision>=99.5%、recall>=98%、错误合并/拆分各<=0.5%、错误自动建单为 0,之后还需不同账号分别完成业务与技术批准。首次批准后标签及对应角色批准均不可变。Run 创建时冻结质量门禁事实,Worker 执行前再次核验 Owner、Schema、阈值和指标。当前无人工真值即不会产生可选批准批次,管理端自动建单保持禁用。
**L7 Dify 手工配置顺序**:先完成本文要求的人工真值与影子指标;再按 Dify 手册完成唯一画布并发布;随后保持自动建单关闭,完成不少于 20 个测试环境真实 Run;书面批准后才允许开启自动建单。任一步失败立即关闭自动建单并修复画布或规则。
**L7 Dify 手工配置顺序**:先完成本文要求的人工真值与影子指标;再按 Dify 手册完成唯一画布并发布;随后保持自动建单关闭,完成不少于 20 个测试环境真实 Run;书面批准后才允许开启自动建单。Profile 盲测资格不能替代 L7 的全局质量批次和业务/技术批准。任一步失败立即关闭自动建单并修复画布或规则。
**阶段 7 影子验收与启用步骤(管理员执行)**:
@@ -138,7 +138,23 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
**阶段 7 Dify 手工配置**:确认 Start 只含 String 类型 `execution_manifest`,所有 Code/LLM/End 节点只接受本手册定义的唯一 Manifest;删除任何按文档集合遍历、整封邮件拼接、输入格式判断、跨附件合并和画布内自动建单逻辑。End 只输出当前 Unit 的 `orders`。
**L7 第 4 阶段工程补充验收(2026-07-22)**:人工编辑 Candidate 的业务摘要时,系统在 `structured_result_json.manual_review_history` 追加编辑前摘要、冲突、校验状态、编辑人和编辑时间,避免“修订后清空冲突”丢失审计。自动建单 Binding 和每次 Run 均冻结 `quality_batch_id`;创建 Run 与 Worker 开始执行时都重新校验该批次的 Owner、Schema、阈值和双人批准状态。`auto_create_enabled=true` 的生产 Run 禁止作为影子质量标签样本,防止用生产结果反向证明质量。迁移 head 为 `a77f8091a2c3`;阶段回归为 `129 passed`,迁移往返和 `git diff --check` 通过。
**阶段 7 试点、容量与恢复验收(HXOPS 运维执行)**:
1. 保持 `auto_create_enabled=false` 和 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,选择 3–5 个高频模板逐个建立独立盲测集;每个模板至少 3 个独立样本全通过并经管理员批准后,才可进入下一模板试点。不得用一个模板的结果覆盖其他模板。
2. 请求级文件数由 `SHIPPING_NOTICE_BATCH_MAX_FILES`(默认 `20`)控制;单文件由 `FILE_ASSET_MAX_SIZE_MB` 控制;EML 展开由 `SHIPPING_NOTICE_EML_MAX_ATTACHMENTS`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES` 和 `SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` 控制。任一限制超出必须在解析或建单前明确拒绝,不创建 Batch/Task,也不保留临时文件。
3. 每日试点记录管理员 `GET /api/admin/shipping-notice/order-extraction-runs/health` 的队列、Provider、HXOPS 落库与总时延 P50/P95、失败率、重试与积压;库存 RPA 从配置测试运行记录读取耗时,上传 RPA 从 `ShippingUploadAttempt.started_at/finished_at` 统计。试点累计数据形成正式容量 SLA 前,不提高并发或放开自动建单。
4. 恢复演练在测试环境完成:人为中断 Worker 后重启,确认 stale Job 被恢复、已有 Provider 结果只续做 HXOPS 落库、相同文件重试不重复建单;再从经批准的数据库备份与 RPA 共享目录备份恢复到隔离环境,核对 Artifact、Attempt、Reservation 和审计记录。演练记录必须包含环境、备份时间、操作者、耗时、校验结果及遗留问题;失败时保持自动建单和自动上传关闭。
**阶段 7 Dify 手工配置补充**:上述容量、健康、恢复和备份均由 HXOPS/运维执行,Dify 不增加限流、重试、循环、恢复或自动建单节点。完成真实影子与试点验收后,仍需按本节既有唯一 Manifest 检查清单手工检查画布并留存截图/运行记录。
### 阶段 3 客户指纹绑定与冻结(2026-07-22)
- `ShippingOrderCustomerMatch` 为 Bill-to/Ship-to 分别保存订单原文、标准化组件、`order-customer-fingerprint.v1`、候选快照及确认审计;客户主数据不覆盖订单原文。
- Bill-to 作为正式订购客户。人工确认必须指定启用客户并填写理由;Ship-to 仍可独立匹配站点,但不替代订购客户。影子识别仅用于质量评测,不能直接冻结。
- `freeze_order_snapshot` 不再接受请求任意传入的客户 ID/简码,只读取当前 Extraction 已确认 Bill-to;Snapshot 同时保存客户 ID、简码和匹配规则快照。客户后续变更不回写已冻结 Snapshot。
- 阶段 3 Dify 手工配置:无需修改画布。客户指纹、候选排序、确认理由与 Snapshot 冻结均由 HXOPS 执行;Dify 不返回 customer_id、客户简码或匹配结论。
**L7 第 4 阶段工程补充验收(2026-07-22)**:人工编辑 Candidate 的业务摘要时,系统在 `structured_result_json.manual_review_history` 追加编辑前摘要、冲突、校验状态、编辑人和编辑时间,避免“修订后清空冲突”丢失审计。自动建单 Binding 和每次 Run 均冻结 `quality_batch_id`;创建 Run 与 Worker 开始执行时都重新校验该批次的 Owner、Schema、阈值和双人批准状态。`auto_create_enabled=true` 的生产 Run 禁止作为影子质量标签样本,防止用生产结果反向证明质量。该子阶段历史 head 为 `a77f8091a2c3`;当前部署还必须继续执行 Snapshot、质量、客户指纹、滚动履约和 Attempt 迁移至 `023a4b5c6d7e`。阶段回归为 `129 passed`,迁移往返和 `git diff --check` 通过。
**L7 状态不变**:以上仅完成工程硬门禁。人工真值、100 个影子 Run、Dify 实配验收、20 个测试环境真实 Run 及业务/技术双人书面批准完成前,必须保持 `auto_create_enabled=false`。
@@ -174,7 +190,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
| L6 裁决与诊断 | 通过 | 真实质量未通过 | Observation 证据引用、纯文本伪证据阻断、跨 Document 强身份关联、冲突保留、管理员脱敏诊断和迁移测试通过 | 真实 accepted 追溯率、错误自动建单统计尚无质量批次 | 可进入 L7 工程门禁;自动建单继续关闭 |
| L7 影子与启用 | 通过 | 未通过 | 质量批次、双人一致标签、首次批准冻结、当前 Schema、双角色批准、Run 冻结、Worker 二次校验、管理 API 脱敏和 UI 门禁通过 | 人工真值、100 个影子 Run、20 个测试环境真实 Run、性能指标、Dify 实配、业务/技术批准均缺失 | 不得开启自动建单,`auto_create_enabled=false` |
最终工程证据分两组执行:主链路 L0-L7 回归 `247 passed`;L0 契约/评测/覆盖/OpenCV/XFA 等补充审计 `102 passed, 1 skipped`,唯一 skip 为缺少 XFA PDF fixture。前端生产构建通过,Alembic 唯一 head 为 `a72f8091a2b8`,`git diff --check` 通过。上述结果只证明工程实现与安全降级,不证明真实订单准确率达到 95%。
最终工程证据分两组执行:主链路 L0-L7 回归 `247 passed`;L0 契约/评测/覆盖/OpenCV/XFA 等补充审计 `102 passed, 1 skipped`,唯一 skip 为缺少 XFA PDF fixture。前端生产构建通过;上述 L0-L7 历史记录对应 `a72f8091a2b8`,当前完整货代履约链唯一 head 为 `023a4b5c6d7e`,`git diff --check` 通过。上述结果只证明工程实现与安全降级,不证明真实订单准确率达到 95%。
### L0 版面契约
@@ -321,6 +337,8 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏
**Profile 可视化治理 Review(2026-07-22)**:管理端 `/admin/shipping-order-document-profiles` 只展示 ready MinerU 样本文档及展开后的 cell 文本,不返回 HTML、bbox、全文或结构指纹。管理员选择表格、表头行、数据起始行、行结构和 Schema 明细字段;页面只允许 `direct` 与已注册 `temp_internal_parts` 解析器,阻止同一目标字段跨列重复映射。结构指纹始终由后端从持久化 HTML 计算,浏览器提交值无效。草稿支持乐观锁更新、发布、删除;不可变版本支持复制为下一草稿和退役。复制后的草稿必须选择样本重新确认映射才能更新,不允许直接编辑 JSON、HTML、正则、脚本或结构指纹。
**表头污染与坐标重建 Review(2026-07-22)**:若样本表头混入明显订单行值(例如 `ITEM NO 00010`),预览返回稳定诊断 `order_profile_header_contaminated_by_data` 并标记不可建 Profile;服务端也拒绝从该表创建草稿,避免浏览器绕过。Profile 页面不是手工修复原始网格的入口。对有 PDF 原生 glyph 坐标且已人工确认列锚点的文档,`coordinate_table_reconstruction` 仅输出 `needs_review` 候选:以 x-overlap/唯一中心距离归属列,以字体高度自适应 y-band 判断新视觉行,内容形态与相邻行连续性只作辅助;无强行号的行只能是续行或复核,`** Item deleted **` 只能附着前一强锚定明细。候选保留 glyph 索引,坐标不足、列归属并列或删除行无前序明细时一律复核,绝不自动接受、发布 Profile 或进入履约。
MinerU 生产捕获固定使用 `pipeline`,通过 `/tasks` 异步提交、状态轮询和 `/result` 取回结果,不使用同步 `/file_parse` 长连接。Intake 不再内联调用 MinerU:它在持久化 Document/派生 FileAsset 后,同事务创建独立布局版本和 `shipping_document_layout` Job;布局 Worker 再读取对象存储并调用 Provider。`SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=false` 时不创建布局 Job;启用后只保存 `shipping_document_table_snapshot.v1` 的页/整表 bbox、HTML 表格与能力摘要,不保存 task 原响应、model output、content list 或非表格文本块。默认每个 Intake 最多 4 个支持文档;超量建立 `unsupported` 审计版本。所有 HTML/bbox 在 Dify Manifest 编译前剥离,仅 Profile 映射后的 `field_id/value/quote` 紧凑候选可进入 Dify。
### L1 布局版本与独立任务生命周期
@@ -946,7 +964,7 @@ GET /api/admin/shipping-order-schema/published-contract
- 新 Schema 版本发布前反向检查 draft/published 路由规则、解析 Profile 与 Excel 模板;任何仍被引用字段都不能通过“取消勾选”绕过退役门禁。
- Task 级规则只能选择 Header 字段,Line 级规则只能选择 Line 字段;字段退役、作用域不匹配或不存在时禁止保存规则。
- 路由条件只允许已发布订单 Schema 的 `order_field_id`;不支持 `system_fact_key` 或任意模型属性路径。
- 运行时按 `ShippingTask.current_order_extraction_id -> ShippingOrderFieldValue` 读取 accepted/corroborated 类型化值;行规则按 `ShippingOrderLine.position` 定位。
- 冻结前的候选/客户识别阶段可按 `ShippingTask.current_order_extraction_id -> ShippingOrderFieldValue` 读取 accepted/corroborated 类型化值;一旦形成 `order_snapshot_id`,库存路由、匹配、导出和 RPA 只能按 Snapshot 中冻结的稳定 `field_id` 取值。行规则均使用冻结行的 `position` 定位。
- 规则发布快照保存稳定字段 ID,字段显示名修改不会改变路由语义;字段被新 Schema 版本移除后,既有已发布规则仍可审计,但新草稿必须重新选择 active 字段。
### 可复用库存解析 Profile(阶段四)
@@ -991,6 +1009,7 @@ GET /api/admin/shipping-order-schema/published-contract
- 模板在“货代配置 → 发货模板”独立维护,状态为 `draft / published / retired`;库存站点只能绑定 published 版本。
- 定义契约为 `filename_pattern + mappings[]`。每条 mapping 包含 `sheet`、`row_mode(header|line)`、`start_row`、`target_column`、`source_kind`、`source_key`、`formatter`。管理端上传模板时读取工作表与首行表头,管理员从实际工作表和目标列中选择,不要求记忆列序号。
- `filename_pattern` 是已发布模板可选的版本化规则;规则为空才使用 `SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN`。两种规则均只允许后端支持的变量和格式,Artifact 必须冻结实际来源、模板/环境规则版本、最终名称和不可复用流水,禁止客户端或 Dify 自定义名称。
- 文件名规则默认推荐 `{business_no}.xlsx`(例如 `WYC26060201.xlsx`)。可用变量必须在界面显式展示:`{business_no}`、`{customer_short_code}`、`{business_date}`(六位)、`{sequence}`(两位)、`{task_no}`、`{source_code}`、`{date}`(八位)、`{ts}`。业务单相关变量只读取 `ShippingCase` 已锁定的客户简称、业务日期和流水快照,保证重新导出与历史审计一致。
- 管理端使用结构化映射行;`source_kind`、订单字段、库存标准字段、系统事实、row mode 与 formatter 均来自后端受控目录,只有常量值和模板坐标允许自由输入。
- `source_kind=order_field` 时 `source_key` 必须为当前已发布订单模板中的稳定 `order_field_id`。订单头区域只能引用订单信息字段;货品明细区域可引用货品明细字段,也可把订单信息字段重复写入每条明细。另允许标准 `inventory_field`、白名单 `system_fact` 和常量。
@@ -1038,6 +1057,8 @@ GET /api/admin/shipping-order-schema/published-contract
# 真实货代上传 RPA 尚未完成,默认 false;仅 mock 或已接入正式上传 Driver 后再开启。
# SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
# 当已发布 Excel 模板未定义 filename_pattern 时使用;模板规则优先。
# 后端冻结每个 Artifact 实际规则来源、规则版本、流水和最终文件名;客户端不得提交文件名。
# SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# 订单抽取固定由 Intake Run + 显式绑定的内部 Dify Workflow 执行;不再提供 Chatflow/同步解析切换开关
@@ -1791,7 +1812,7 @@ docker compose --env-file .env.prod stop hxops-kb-worker hxops-backend
- 聊天界面仍是**主上传入口**,通知附件、库存附件与对话续办都优先在 Chat 完成
- 聊天页右侧**轻量批次工作台**允许执行当前任务动作,但业务按钮必须直接消费后端 `ui_state.action_buttons`,禁止前端按 `process_status / pending_human_reason` 本地二次推导
- 独立工作台入口 **货代发货** 仍以只读查看、筛选排查与跳转聊天界面为主,不单独维护第二套业务动作口径
- 独立工作台入口 **货代发货** 仅提供任务筛选、只读履约审计和“在 Chat 中继续”入口;候选审核、订单冻结、库存、Excel、RPA、人工回执、客户确认、归档等所有用户操作统一在对话界面执行,避免维护两套动作口径。
- **在 Chat 中继续** → `/chat/{agentId}?task_id=SN-...`
### 1.7 端到端验证
@@ -1829,11 +1850,19 @@ pytest tests/test_shipping_notice_tools.py tests/test_shipping_notice_query_serv
- **发货通知人工修订**:已支持改单头、改订单行、增行、删行。
- **库存匹配与缺口阻断主规则**:存在 shortage 时会停留在人工节点,前端 Stepper 也会展示阻断状态。
- **Excel 生成与上传闭环**:已具备后端匹配、自动推进、生成 Excel、人工上传确认等主流程接口。
- **滚动 Artifact 上传闭环**:每份 Excel 独立创建 `ShippingUploadAttempt`;RPA trigger 与回调传递 `artifact_id`、`attempt_id`、`callback_id`,重复回调幂等。人工确认必须提供当前用户的私有截图/回执 `evidence_asset_no`,无证据返回 `SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED`。网络失败不释放预约单;仅 `freight_rejected:` 明确拒绝并经授权才可作废 Artifact。此链路不需要修改 Dify 画布、Tool 或 Prompt。
- **Chat 人工上传交互**:用户点击“已手工上传”后,Chat 必须先选择图片或 PDF 回执;前端上传为当前用户私有 `FileAsset`,再把 `evidence_asset_no` 与任务号提交 `shipping.mark_manual_uploaded` Chat Turn。服务端仅从 Chat 用户上下文填充 `operator_id`,拒绝缺失或不属于当前用户的回执;取消选择不提交上传完成动作。
### 3.2 部分实现,和原型仍有差距
- **三层进度展示**:当前已具备批次层摘要、任务层七步 Stepper,以及统一的 `step_payload_json.current_step_progress` 步骤内进度协议;但“第 `i/n` 个文件解析中”“匹配严格逐行 `x/y`”这类更细运行态仍未完全达到原型描述粒度。
- **工作台职责收敛**:正式口径应收敛为“**对话主路径 + 轻量批次工作台**”;聊天页右侧轻量工作台允许执行动作,但只负责渲染后端 `ui_state.action_buttons` 与查看类辅助入口,不能本地二次推导“继续处理 / 重试 RPA / 查看详情”等业务按钮;独立详情页仍主要承担只读排查与管理视角。
- **工作台职责收敛**:聊天页右侧轻量工作台允许执行动作,但只负责渲染后端 `ui_state.action_buttons` 与查看类辅助入口,不能本地二次推导“继续处理 / 重试 RPA / 查看详情”等业务按钮;独立详情页严格只读,不渲染任何写操作按钮。服务端状态机、审计和乐观锁仍是 Chat 操作的唯一裁决。
#### 阶段 6 工作台 Review(2026-07-22)
- 业务用户在对话界面完成候选审核到上传闭环;独立工作台用于筛选、查看任务真相与审计,并可跳转至对应 Chat 继续操作。候选修订、重复决策、建批与订单冻结均经 Chat 调用既有 API,后端继续执行乐观锁和审计。
- 字段证据目前可展示字段、Document 编号和逐字 quote;现有用户态 API 没有受控的原文件页图/坐标预览读模型,因此**不宣称**已实现页图高亮。后续如需该能力,须先设计按用户与 Document 权限校验的预览资产接口,返回最小化页图 URL 与 `evidence_ref/page/bbox`,不得直接暴露原始 MinIO 路径或全文。
- Dify 手工配置:本阶段不需要新增或改动 Dify 节点、Tool、变量或 Prompt。保持既有 Workflow 的单 Document `execution_manifest` 契约;工作台仅调用 HXOPS 用户态 API。
- **任务列表筛选口径**:工作台已覆盖全部可展示流程状态;`shortage_review` 由后端按 `review_status / pending_human_reason` 复合过滤,其余选项按真实 `process_status` 过滤。状态目录由 `shippingTaskStatuses.spec.ts` 锁定。
- **解析复核状态命名**:前端使用当前 `parse_review / rsv_required / shortage_review` 口径,已移除任务级库存映射旧状态。
@@ -2034,7 +2063,7 @@ API 层
> 详细方案见 [`inventory_source_plan.md`](./inventory_source_plan.md)。
1. **动态 FieldValue 路由裁决**:订单抽取 accepted 后,后端从任务锁定的 `current_order_extraction_id` 读取用途为 `inventory_source_hint` 的字段值;命中库存源线索规则时优先裁决,只有线索未命中时才使用 5 位或 10 位预定单号兜底规则。
1. **冻结 Snapshot 路由裁决**:订单抽取 accepted 且订单冻结后,后端从 Snapshot 读取用途为 `inventory_source_hint` 的字段值;命中库存源线索规则时优先裁决,只有线索未命中时才使用 5 位或 10 位预定单号兜底规则。冻结前只允许显示“冻结订单”检查点,不能触发库存路由或 RPA。
- 线索规则优先级为 300:AWSSG、AWSBI-FRA、AWSBI-CMH、AWSDU、AWSSL、AWSCV、AWSAMS、Crane 共 8 组;Crane 线索为 `DBS TZR02 / TZR02 / VMI-RBD02 / RBD2 / LUK`。
- 5 位纯数字预定单号优先级为 200,仅作为 Crane 兜底;10 位且首位为 1–4 的规则优先级为 100。当前共 13 条草稿规则,发布前必须由业务管理员复核候选 Source。
2. **先解析复核,再定库存源**:低置信度先 `checkpoint=parse_review`(含重新解析);解析通过(人工确认或高置信度自动过)后,若源未稳定再进 `inventory_source_review`。RPA 等后续步骤仍要求 `inventory_source_status ∈ {resolved, user_confirmed}`。
+4 -1
View File
@@ -109,7 +109,7 @@
| 订单识别断流与重复执行保护 | 已实现 | 同一 Intake 仅允许一个未释放 Run;Provider 结果先独立提交,HXOPS 持久化重试不重复调用 Dify;浏览器断流或切会话不取消后台作业 |
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 使用 `shipping-v1` 身份指纹与 `shipping-content-v4` 内容指纹;高置信 `part_number`+Qty 订单可自动建 Task;缺失/非法 Reservation、未解决字段冲突继续阻断下游,库存源线索统一为 `inventory_source_hint` |
| 订单解析结果持久只读展示 | 已实现 | Task Detail 顶层投影 `order_header` / `order_header_fields` / `order_line_fields` / `lines` / `parse_validation` / `process_field_gate` / `source_candidate`;右侧工作台按任务锁定 Schema 的显示名称和 `sequence` 展示订单信息与动态明细列,避免前端写死字段顺序;Candidate 审核非编辑态同步展示关键行 |
| 动态订单唯一真相 | 已实现 | Task 通过 `current_order_extraction_id` 锁定 `ShippingOrderExtraction/Line/Decision/FieldValue`;订单读写、人工编辑、Candidate 对账、路由、库存、RPA、匹配和展示均只读取该版本。旧 `shipping_task_lines`、`lines_json`、固定订单头列和双写/影子脚本已物理删除。 |
| 动态订单解析真相 | 已实现 | Task 通过 `current_order_extraction_id` 追溯 `ShippingOrderExtraction/Line/Decision/FieldValue`;它们只承载解析结果。订单冻结后由 `order_snapshot_id` 供库存、RPA、匹配和导出读取,旧 `shipping_task_lines`、`lines_json` 和兼容投影不恢复。 |
| 订单字段对账与冲突复核 | 已实现 | Candidate→Task 字段级自动补空/冲突落库;未解决冲突阻断库存/匹配/导出;workspace 冲突查询与解决 API;改单支持 `expected_order_data_version` 与幂等键;工作台解析卡可解决冲突 |
| 库存源/RPA Profile 数据库主数据 | 已实现 | 以 Inventory Source 为业务主键;Source 持久化 DBS 报表路径与查询参数;订单到站点的选择统一由路由规则维护;RPA Profile 仅保存登录、密文凭据与连接级登录配置;YAML 不再作为运行时真相源 |
| 货代配置工作台 | 在建(导航补齐) | 管理端“货代配置”将提供“库存配置”和“客户识别规则”二级入口;订单解析、库存文件解析方案、发货模板、库存站点和路由规则仍集中在库存配置页。两页复用货代配置权限,客户主数据仍位于货代工作台。 |
@@ -166,6 +166,7 @@
| 受控自动客户识别 | 已实现 | 自动确认消费字段驱动的冻结规则快照,交叉校验历史订单 Schema、Extraction、Decision、FieldValue、审核授权证据、active 客户、唯一命中、公共域名与质量阈值;任务事件保存完整追溯主键,任一快照漂移或链路不一致均转人工复核。 |
| 客户治理闭环 | 已实现 | 客户与识别证据关键变更记录快照时间线;简码、状态、自动匹配授权必须填写原因。自动确认在总开关外再受有效人工标注样本量(默认 20)与准确率(默认 98%)门禁约束,未达标保持 `customer_review`;客户主数据页展示时间线和降级原因 |
| 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) |
| 滚动履约领域契约(阶段 0) | 实施中 | 冻结 `SHIP_AVAILABLE_ROLLING`、预置核心字段与可配置扩展字段、Snapshot 正式真相、预约单全局注册、Artifact/Attempt 拆分、LLM 人工复核门禁;扩展字段是否进入库存/Excel/RPA 由已发布业务配置决定;Excel 命名由已发布模板规则优先、环境变量受控回退,最终规则在 Artifact 审计冻结。 |
### 排程平台任务契约中心(schedule)
@@ -632,3 +633,5 @@
| 订单抽取紧凑结构化候选 | 已实现 / 质量验收延期 | 唯一 Manifest、Run 冻结、无 HTML/bbox/token 泄漏、accepted 字段锁与完整表零 Provider;人工真值及 95% 指标暂缓。 |
| 订单抽取 L6 证据裁决与诊断 | 已实现 / 质量验收延期 | Observation 证据引用、纯文本无 cell 转复核、同 Document 强身份关联、冲突阻断、Candidate/UI 原因码和脱敏管理员追溯率诊断。 |
| 订单抽取 L7 启用准备 | 工程完成 / 阶段未验收 | 删除 Profile/纯文本零 Provider;自动建单要求当前 Schema 的已批准质量批次,并冻结到 Run、Worker 再核验。人工真值延期时无批准批次可选,自动建单保持关闭;影子 Run 和实际 Dify 验收尚缺。 |
| 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布 Profile 与自动建单资格分离;至少 3 份独立样本全通过、管理员批准且 checksum 未漂移时,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 |
| 订单客户指纹与 Snapshot 绑定 | 已实现 | Bill-to/Ship-to 原文与正式客户分层保存;Bill-to 人工确认须有理由并生成规则版本化指纹,冻结只采纳该确认结果并固化客户简码。 |
+17 -1
View File
@@ -57,6 +57,19 @@
- **模型**:识别定义只描述目标对象、稳定 `context_field_id`、业务名称、权重和自动化上限;字段采集、格式、校验与证据来源全部继承已发布订单 Schema。客户/站点证据值关联定义;规则集独立草稿/发布/退役、乐观锁、checksum 与追加式审计。详见 [customer_identity_rules_plan.md](features/shipping-notice/customer_identity_rules_plan.md)。
- **唯一取值路径**:运行时只读取 Candidate 所属 Extraction 中 `ShippingOrderFieldDecision=accepted|corroborated` 对应的 Header `ShippingOrderFieldValue`。禁止重读 EML `From`、生成模板指纹、读取原始 LLM JSON 或按定义编码分支取值。
### 1.x 发货通知滚动履约冻结架构(阶段 0,2026-07-22)
本节取代此前“动态 `FieldValue` 是履约唯一真相”“全部订单行满足才可导出”及“单 Task/单 Excel”语义;后续数据库、API 和前端必须以此为实现边界。
- 当前预置核心清单为 13 个 Header 加 12 个 Line(共 25 个):Header 为 `po_number`、`customer_code`、`customer_name`、`bill_to_customer`、`bill_to_address`、`ship_to_customer`、`ship_to_address`、`destination`、`currency`、`incoterm`、`required_date`、`order_date`、`payment_term`;Line 为 `line_no`、`part_number`、`customer_part_number`、`aws_part_number`、`reservation_id`、`qty`、`uom`、`unit_price`、`amount`、`warehouse`、`inventory_source_hint`、`remark`。历史“26 个”计数中的 `bill_to_customer_code` 已按业务决定替换为 `bill_to_address`;`position` 仅为行排序键,二者均不新增为核心字段。料号和预约单为字符串,数量/金额为 `Decimal/Numeric`,不得使用浮点数;管理员可按业务增加扩展字段。
- `ShippingOrderSnapshot` / `ShippingOrderSnapshotLine` 同步保存预置核心的强类型列、正式 `customer_id`、客户简码和规则版本,并以稳定 `field_id` JSON 冻结所有已发布扩展字段;库存、导出、RPA 是否消费扩展字段由已发布业务配置决定。库存、导出、RPA 与其测试不得读取 `ShippingOrderFieldValue` 作为业务真相;`ShippingOrderReviewEvent` 保存人工纠错的原值、新值、证据、原因、人员和时间。
- `ShippingReservation` 是预约单全局注册表,唯一键为 `reservation_id`,保存当前有效快照行和状态;`ShippingInventoryVerification` / Line 保存每轮库存快照和逐预约单结论;`ShippingExportArtifactLine` 建立预约单到 Excel 的唯一有效归属;`ShippingUploadAttempt` 记录每一次上传和幂等回调。
- `ShippingUploadAttempt` 以 `(artifact_id, attempt_no)`、`idempotency_key` 与 `callback_id` 约束一次上传事实,记录模式、起止时间、错误、操作人、货代参考号及人工回执 `FileAsset`。成功回调原子锁定本 Artifact 所有预约单为 `uploaded`;失败保持预约单占用,明确货代拒绝后才允许授权作废并释放。单 Task 同时最多一份 `ready/uploading` Artifact,防止旧文件与新轮次并行上传。
- 状态机为 `pending -> available -> artifact_reserved -> uploaded`,`pending|available|artifact_reserved -> external_change_required`;Artifact 作废仅在外部明确拒绝且授权后释放对应预约单。`SHIP_AVAILABLE_ROLLING` 仅在至少一个 `available` 时进入 `READY_TO_EXPORT`,生成操作以行锁/唯一约束一次性领取所有当前可用行。
- Excel 命名规则由已发布模板的 `filename_pattern` 定义;未定义时读取环境变量 `SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN`。两者均由后端编译、校验并在 Artifact 保存规则来源、版本、最终文件名和独立流水。客户端请求不得携带命名模式或文件名;流水即使 Artifact 作废亦不得复用。
- LLM Observation 必须有真实 `evidence_ref`,并以 `evidence_verified=false` 落库;任意关键字段存在该类 Observation 时,冻结门禁返回 `SHIPPING.ORDER_LLM_REVIEW_REQUIRED`。Dify 故障只能转人工复核,不能使确定性模板路径降级为猜测。
- JSON API 按统一 envelope 返回。关键错误码至少包括 `SHIPPING.ORDER_SNAPSHOT_FROZEN`、`SHIPPING.ORDER_LLM_REVIEW_REQUIRED`、`SHIPPING.RESERVATION_CONFLICT`、`SHIPPING.INVENTORY_STALE`、`SHIPPING.EXPORT_NOT_READY`、`SHIPPING.UPLOAD_EVIDENCE_REQUIRED`;权限矩阵禁止 Dify/普通用户调用冻结、制单、上传回调和作废接口。
- **引用与快照**:规则保存 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。
- **裁决边界**:客户主体和送货站点独立候选;编码确定性匹配优先;多命中、冲突、未命中均进入人工复核。业务弱证据(地址、联系人、名称)默认不得单独自动确认;公共邮箱域名永久禁止。
- **Dify**:不新增 Tool 或修改画布。Dify 继续按已发布动态 Schema 契约提交 Header Observation;HXOPS 完成证据校验、字段裁决、规则匹配、质量门禁和最终确认。
@@ -68,6 +81,7 @@
- **原子编号服务**:业务编号格式固定为 `{customer_short_code}{YYMMDD}{sequence_2}`,例如 `WYC26071501`;日期使用 `Asia/Shanghai`。PostgreSQL 按 `(business_type, customer_id, business_date)` 原子递增两位流水,并由 `business_no` 唯一约束兜底;不得使用“查询最大值 + 1”。
- **格式约束**:客户简码为全局唯一的 `2-6` 位大写英文字母(`^[A-Z]{2,6}$`);完整业务编号正则为 `^[A-Z]{2,6}\d{8}$`。
- **容量与幂等**:单客户单日允许 `01-99`;第 100 票抛出明确业务错误。同一业务单重复确认直接返回原编号,不重复消耗流水。
- **试点保护与恢复**:`SHIPPING_NOTICE_BATCH_MAX_FILES`(默认 `20`)限制单次通知批量文件数;`FILE_ASSET_MAX_SIZE_MB`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENTS`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES`、`SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` 分别限制文件和 EML 展开规模。超限在接入/抽取前失败,不生成批次或任务。订单抽取管理员健康接口提供队列、Provider、HXOPS 落库和总时延 P50/P95、失败率、重试与积压;RPA 耗时由配置测试和 Artifact Attempt 审计追溯。通用 Job stale recovery 在 Worker 重新领取前恢复超时任务;数据库与 RPA 共享目录备份恢复演练须在非生产环境按运维记录执行,禁止以演练替代真实试点指标。
- **编号后纠错**:管理员必须填写原因;尚未上传货代时保留原业务号并标记作废,创建 `replaces_case_id` 指向原单的替代业务单并申请正确客户的新流水。旧号查询跟随替代链,已上传货代的任务须先完成外部作废流程。
- **期初数据导入**:使用客户导入批次和导入行暂存表保存原文件哈希、原始值、标准化值、校验结果、处理决定和发布结果;正式发布前完成简码冲突、疑似重复、公共域名和标识歧义检查。
- **渐进发布**:按 `off → shadow → manual_gate → auto_gate` 开启客户识别;影子阶段只记录候选不阻断生产,强规则质量达标后先启用人工 Gate,再开放有限自动确认。
@@ -133,7 +147,7 @@
- 库存 Excel 上传后保存为 `shipping_inventory_files` 批次库存快照,并通过 `shipping_task_inventory_links` 关联到本批任务。
- 字段映射与完整库存解析在库存快照层完成一次;每票仍使用自己的发货需求行独立执行库存匹配、Excel 生成与上传。
- `ShippingTask.inventory_lines_json` 仅作为任务侧投影缓存,批次库存真相源为 `shipping_inventory_files.inventory_lines_json`。
- **订单唯一真相**:`shipping_order_extractions`、`shipping_order_lines`、`ShippingOrderFieldDecision/Value` 是订单唯一持久化事实;`ShippingTask.current_order_extraction_id` 锁定任务版本。`shipping_task_lines`、`ShippingTask.lines_json` 和固定订单单头列已物理删除。字段冲突按动态订单行 `position` 审计,`order_data_version` 支撑并发安全编辑。
- **订单真相分层**:`shipping_order_extractions`、`shipping_order_lines`、`ShippingOrderFieldDecision/Value` 是可追溯的解析事实;`ShippingOrderSnapshot/Line` 是冻结后的履约业务事实。`ShippingTask.current_order_extraction_id` 追溯解析版本,`order_snapshot_id` 锁定履约版本。`shipping_task_lines`、`ShippingTask.lines_json` 和兼容固定单头列不得作为业务真相;冻结前的 Candidate 编辑及 Snapshot 冻结均使用乐观锁。
- **库存源与库存文件分层**:`source_code` 是业务库存主键;通用、版本化的路由规则先产生 Source 候选,正常任务再按 Source 匹配最新 `ready`、未过期库存文件,禁止因文件缺失自动触发 RPA。RPA Profile 仅保存登录 URL、加密凭据和连接级登录配置;每个 Source 保存 DBS 的报表路径和查询参数,不允许在业务配置中保存 selector、下载策略或第二套路由别名。排程按 Profile 分组优化登录但每个结果独立归档到 Source。`connector_type` 只允许 `dbs` / `crane`,不再使用 `site_id`。固定 Source 使用配置 Warehouse;Crane 等动态 Source 按 `reservation_id + part_number` 从库存行解析 Warehouse。详见 [inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)。
- **建单防重复(第一阶段)**:`ShippingBatch.create_idempotency_key` + `(user_id, create_idempotency_key)` 唯一约束提供并发保护;`ShippingTask.source_content_hash` 记录源文件 SHA-256;Chat Turn 与 Workspace API 共用 `batch_from_notices` 幂等逻辑;与货代上传 `ShippingTask.idempotency_key` 语义分离。
@@ -1236,3 +1250,5 @@ Dify
- L6 Observation 通过 `evidence_ref + evidence_metadata_json` 保存文本、邮件头或 layout cell 证据身份。旧纯文本表格解析器只做候选检测,不再进入 verified Observation;accepted layout 仅按同 Document 强身份关联。
- L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。
- L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。
- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。Profile 仅在至少 3 份样本全通过、管理员批准且当前 checksum 一致时获得 `auto_create_approved`;Run 创建冻结该事实。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。
- **订单客户指纹与冻结门禁**:`ShippingOrderCustomerMatch` 保留 Bill-to/Ship-to 原文、标准化组件、`order-customer-fingerprint.v1` 指纹、候选快照和确认理由。只有 `bill_to.status=confirmed` 且存在客户/简码/指纹/规则版本时 `order_freeze_service` 才冻结 Snapshot;冻结服务不接受外部 `customer_id` 或 `customer_short_code`。Snapshot 的 `rule_versions_json.ordering_customer` 保存匹配 ID、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。
+8 -2
View File
@@ -56,7 +56,9 @@
| **发货通知** | **文档版面结构化 L4 冻结 Schema 证据映射** | layout.v1 Table 直接按 Run 冻结 Schema 映射,字段证据必须引用真实 cell/token;跨页只接受显式 continuation。 | `test_shipping_document_layout_schema_mapping.py`、`test_shipping_document_layout_html_table.py`、`test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py` | 后置表头、重复目标列、Qty=0、真实 cell/token/evidence_ref、显式/缺失 continuation、Run 后 Schema 漂移、Manifest 泄漏 | 映射复用既有安全规则;重复列全 ambiguous;零 Qty 删除;Run v3冻结候选不漂移;needs_review 只标 candidate且不进 Dify/确定性执行。人工真值延期时不判真实字段映射准确率,但错误自动接受数必须为 0。 |
| **发货通知** | **订单文档模板 Profile 纯契约** | 以表头网格精确结构指纹选择固定列规则,允许模板级字段语义覆盖全局 Schema;只运行注册解析器。 | `test_shipping_order_document_profile.py` | `Part Number -> customer_part_number`、`Vendor Item# -> part_number`、复合料号 cell、零 Qty、结构漂移、MinerU 行关系丢失、自由解析器注入 | 精确命中时模板映射原样生效;零 Qty 行删除;结构变化不做相似匹配;行关系丢失显式阻断;未知解析器或非法目标字段拒绝保存。 |
| **发货通知** | **订单文档 Profile 发布与运行锁定** | Profile 绑定不可变 Schema/稳定 field_id,版本化发布;Run 冻结完整 Profile 与 MinerU 紧凑布局,Worker 只执行唯一精确匹配。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_migration.py`、`test_shipping_document_layout_runtime.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py` | 并发草稿覆盖、新版发布、字段退役、Provider 失败、多附件预算、多表/多 Profile、零 Qty、Decimal JSON、布局 HTML 泄漏 Dify、Run 后配置变化 | 乐观锁与单 published 唯一索引生效;字段引用阻断退役;Run 快照不漂移;Provider 失败安全回退;唯一完整表跳过 Dify;多表不自动合并;HTML/bbox/field_code 不进入 Dify;零 Qty 删除。 |
| **发货通知** | **订单文档 Profile 可视化治理** | 管理员只从 ready MinerU 样本选择表格、行和受控字段/解析器,完成草稿、新版本、发布与退役;浏览器不持有可伪造运行契约。 | `test_shipping_order_document_profile_service.py`、`orderProfileForm.utils.spec.ts`、`shippingConfigNavigation.spec.ts`、前端生产构建 | 普通用户访问、伪造结构指纹、HTML/bbox 泄漏、越界行、重复目标字段、复合解析器冲突、过期 lock、新版本重配、unsupported 行结构 | 普通用户拒绝;预览仅 cell 文本;指纹后端计算;越界/过期锁/重复字段阻断;只允许注册解析器;复制草稿须用样本重新确认;无需编辑 JSON/HTML/脚本。 |
| **发货通知** | **订单文档 Profile 可视化治理** | 管理员只从 ready MinerU 样本选择表格、行和受控字段/解析器,完成草稿、新版本、发布与退役;浏览器不持有可伪造运行契约。 | `test_shipping_order_document_profile_service.py`、`orderProfileForm.utils.spec.ts`、`shippingConfigNavigation.spec.ts`、前端生产构建 | 普通用户访问、伪造结构指纹、HTML/bbox 泄漏、越界行、重复目标字段、复合解析器冲突、过期 lock、新版本重配、unsupported 行结构、`ITEM NO 00010` 混入表头 | 普通用户拒绝;预览仅 cell 文本;指纹后端计算;表头污染返回稳定诊断并拒绝建草稿;越界/过期锁/重复字段阻断;只允许注册解析器;复制草稿须用样本重新确认;无需编辑 JSON/HTML/脚本。 |
| **发货通知** | **文档版面坐标重建候选** | 仅在可信 PDF glyph 坐标与人工确认列锚点同时存在时,按 x 列归属、y 视觉行、内容适配度及相邻连续性重建错误 MinerU 网格的复核候选。 | `test_shipping_coordinate_table_reconstruction.py` | `00010/00020` 行号、料号/数量列、跨视觉行续行、`** Item deleted **`、无锚点行、列归属并列 | 候选固定 `needs_review` 并保留 glyph 索引;续行不伪装为新明细;删除标记仅关联前一强行号;无坐标/歧义绝不自动接受、发布 Profile 或进入履约。 |
| **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py`、`test_agent_runtime_bindings.py` | 少于 3 样本、真值不匹配、批准后编辑、checksum 漂移、未知/多模板、Dify 不可用 | 至少 3 个独立样本全通过且管理员批准才放行;批准样本不可改;checksum 变化立即失效;唯一已批准 Profile 直接生成确定性订单,其他情形回退 Dify/人工。 |
| **发货通知** | **Workflow 结果缓存与重试** | Dify 成功后先独立保存结构化 orders;即使无 workflow_run_id,HXOPS 落库失败重试也不得再次调用 Dify。 | `test_agent_runtime_bindings.py::test_worker_caches_provider_output_and_does_not_call_dify_twice` | 首次 Provider 成功、后续 DB 暂时失败 | Dify 调用 1 次、持久化尝试 2 次,Run 最终 completed。 |
| **发货通知** | **Provider 变更与密钥轮换** | App ID/Base URL 漂移阻断旧 Run;API Key 轮换允许旧 Run 使用新密钥继续。 | `test_agent_runtime_bindings.py` Provider drift / key rotation 用例 | 排队后修改 App ID、Base URL 或 API Key | 前两者 Run/Job failed 且不调用 Dify;密钥轮换成功完成。 |
| **发货通知** | **Run 安全视图与事务原子性** | 用户 API 不返回正文、Provider 快照/原始结果/配置;Agent 与 binding 保存同事务。 | `test_shipping_order_extraction_runs.py`、`tests/services/admin/test_agent_service.py` | 查询 Run;创建/更新时绑定校验失败 | 响应无敏感快照;失败后 Agent 字段和 binding 均不留下半成品。 |
@@ -85,7 +87,11 @@
| **发货通知** | **MinerU pipeline-only Provider 边界** | 当前阶段只使用 MinerU pipeline;未评测 Provider 不得形成隐藏 fallback、自动切换或兼容分支。 | MinerU 适配器测试、技术路线 Review、依赖/代码搜索 | pipeline 成功/失败、VLM/hybrid 配置、MonkeyOCR 未部署 | 生产候选只来自 pipeline;VLM/hybrid/MonkeyOCR 不参与运行;Provider 变化必须建立独立评测阶段后再接入。 |
| **发货通知** | **跨文档 Reservation 关系门禁** | 邮件中的 Reservation 只能按明确 PO/内部料号关系补充订单行;同 Intake 或同邮件不是广播依据。 | 关系契约测试、跨文档合并测试、Dify 手工配置验收 | 多 PO 单 Reservation、多 PO 多 Reservation、明确 PO-Reservation 对、明确 Part-Reservation 对、唯一一对一 | 仅明确或唯一关系补充;多义关系保持 needs_review;每条最终行仍需 Reservation 才可库存匹配和生成发货 Excel。 |
| **发货通知** | **Candidate 迁移往返** | 内容指纹、订单抽取状态与多 Candidate 唯一键迁移须可独立 upgrade/downgrade。 | `test_shipping_notice_candidate_migration.py` | 前一版本最小 schema;同 Document 多 Candidate | 新列/约束存在;安全场景完整降级;多 Candidate 场景明确拒绝降级。 |
| **发货通知** | **动态订单唯一真相** | 订单头/行仅保存在任务锁定的 `ShippingOrderExtraction/FieldValue`;固定投影表和 JSON 快照不得存在。 | `test_shipping_task_field_reconciliation.py`、`test_shipping_notice_order_extraction.py`、迁移结构检查 | 人工改单、open_existing 回填、重解析、旧表/列结构检查 | 业务读取只见动态 FieldValue;旧表/列不存在;冲突按动态行 `position` 保留。 |
| **发货通知** | **冻结订单真相与预置核心字段契约(阶段 1)** | `FieldValue` 仅用于解析;25 个预置 Header/Line 业务核心字段同步冻结为强类型列,所有已发布扩展字段按稳定 `field_id` 冻结至 Snapshot,库存/导出/上传只读 Snapshot。 | `test_shipping_order_schema.py::test_order_schema_initializes_fixed_core_and_allows_extension_fields`、`test_shipping_order_snapshot.py`、`test_shipping_task_field_reconciliation.py` | 扩展字段履约映射、未冻结入库存、冻结后编辑、并发复核、前导零、Decimal 数量、无证据修改 | 13 Header + 12 Line;历史第 26 项 `bill_to_customer_code` 已替换为 `bill_to_address`,`position` 仅为排序键;管理员可新增扩展字段,其是否被库存/Excel/RPA 消费由已发布业务配置决定;冻结后更新被拒;每次纠错保留前后值/证据/原因/人员/时间;下游不读 FieldValue。 |
| **发货通知** | **阶段 0 领域契约一致性 Review** | 六份权威文档必须一致描述 Snapshot、`SHIP_AVAILABLE_ROLLING`、模板优先/环境变量回退命名、LLM 人工复核和人工上传证据。 | 文档静态扫描 + 业务示例 Review 记录 | A/B 有货、C 缺货;关键字段含 LLM fallback;模板规则存在/缺失;人工上传无/有回执 | 不残留“全部满足才可制单”或“FieldValue 为履约真相”;A/B 进入 Excel 01,C 补货后进入 Excel 02;LLM 未确认阻断冻结;命名来源可追溯;无回执上传被拒。 |
| **发货通知** | **滚动库存、Artifact 与并发制单(阶段 4)** | 每轮库存新建 Verification,至少一个 `available` 才可制单;一次领取全部当前可用预约单。 | `test_shipping_reservation_registry.py`、`test_shipping_inventory_verification_rounds.py`、`test_shipping_rolling_export.py`、`test_shipping_export_concurrency.py` | A/B 满足、C 缺货;全缺;补货;过期库存;料号不一致;两个并发请求 | Excel 01 仅含 A/B,C 补货后 Excel 02 仅含 C;不生成空文件;一个预约单不进入两个有效 Artifact;并发仅一个成功;已上传预约单永不重制。 |
| **发货通知** | **上传 Attempt 与人工证据(阶段 5)** | 上传从 Task 拆至 Artifact Attempt;回调幂等,人工降级必须保留外部证据。 | `test_shipping_upload_attempt.py`、`test_shipping_upload_callback_idempotency.py`、`test_shipping_manual_upload_evidence.py` | 同回调 10 次、旧/新 Attempt 乱序、RPA 失败、人工无/有截图 | 同回调仅一次状态变化;失败/旧回调不得覆盖成功;无证据人工完成返回业务错误;成功 Artifact 的预约单永久锁定。 |
| **发货通知** | **试点容量、恢复与逐模板发布(阶段 7)** | 请求级/文件级/EML 级限制必须配置化;试点逐模板盲测、记录性能并验证 Worker 与备份恢复。 | `test_shipping_notice_batches.py::test_workspace_create_batch_rejects_configured_file_limit_before_intake`、既有 EML 限制/Job recovery/Profile blind-test 回归、运维演练记录 | 超过批量数、超过文件/附件限制、Worker 重启、同文件重试、3–5 个模板、数据库/RPA 共享目录恢复 | 超限无临时文件、无 Batch/Task;重启可恢复且不重复建单;每模板独立盲测通过;健康指标与 RPA 耗时形成试点记录;备份恢复核对 Artifact/Attempt/Reservation/审计,失败时自动建单/上传保持关闭。 |
| **发货通知** | **字段对账与冲突门禁** | Candidate 空字段可补齐;双方非空不同落冲突;未解决冲突阻断库存/RPA/匹配/导出;改单带版本。 | `test_shipping_task_field_reconciliation.py` | open_existing 补 Reservation;多行同字段冲突;行重建后冲突存活 | applied/conflicted 可区分;下游入口无副作用;resolve 后重算 Gate。 |
| **发货通知** | **唯一订单 Schema 发布门禁与版本治理** | 全局单 Schema;完整 JSON 定义是草稿/发布唯一真相;保存/发布使用乐观锁;发布事件追加审计。 | `test_shipping_order_schema.py`、`test_shipping_order_schema_version_governance_migration.py` | 动态字段、草稿、过期锁、连续发布、审计快照、迁移清理草稿、Profile/模板跨域字段引用、下游引用字段被新版本移除 | 契约 checksum 稳定;仅一个 published Schema 版本;过期锁返回 409;审计事件保留前后快照;字段退役和 Schema 发布均不可留下下游悬空引用。 |
| **发货通知** | **通用上下文字段来源与运行门禁** | 通用字段仅允许 Header 确定性采集;数据库目录必须命中代码注册表;Run/Extraction 冻结邮件上下文并写入统一值链。 | `test_context_fields_service.py`、`test_shipping_context_field_catalog_migration.py`、`test_shipping_order_schema_runtime.py`、`test_shipping_order_extraction_runs.py::test_run_submission_rejects_changed_frozen_mail_context`、`test_agent_runtime_bindings.py::test_workflow_inputs_use_frozen_extraction_contract_only` | From 邮箱/域名、非 ASCII 显示名、公共域名、缺失/非法/多地址、Reply-To/正文伪线索、重入、多 Intake、审计详情、Run 后元数据漂移、Dify 隔离、迁移往返 | 仅返回受控来源;任意 selector 无法保存;每个 Extraction 独立产生 Observation→Decision→FieldValue;missing 重入不重复;公共域名保留;漂移阻断;审计可重建;Workflow 不收到或回传通用确定性字段。 |
@@ -10,6 +10,7 @@ import { getAuthHeaders } from '@/shared/utils/auth';
import type {
CreateOrderProfileFromSampleInput,
OrderProfileSampleDocument,
OrderProfileSampleIntake,
OrderProfileSamplePreview,
ShippingOrderDocumentProfile,
} from '../types/shipping-order-document-profile.types';
@@ -25,6 +26,19 @@ export const listOrderDocumentProfiles = () =>
export const listOrderProfileSamples = () =>
requestJson<OrderProfileSampleDocument[]>('/api/admin/shipping-notice/order-document-profile-samples', auth());
/** 将已上传 PDF/EML 创建为隔离模板样本,不创建发货任务。 */
export const createOrderProfileSample = (assetNo: string) =>
requestJson<OrderProfileSampleIntake>('/api/admin/shipping-notice/order-document-profile-samples', {
method: 'POST', body: JSON.stringify({ asset_no: assetNo }), ...jsonAuth(),
});
/** 轮询模板样本解析状态;响应不含正文、HTML 或坐标。 */
export const getOrderProfileSampleStatus = (intakeNo: string) =>
requestJson<OrderProfileSampleIntake>(
`/api/admin/shipping-notice/order-document-profile-samples/intakes/${encodeURIComponent(intakeNo)}`,
auth(),
);
/** 读取一个样本文档的网格预览,不返回 HTML 或 bbox。 */
export const getOrderProfileSampleTables = (documentId: number) =>
requestJson<OrderProfileSamplePreview>(
@@ -303,7 +303,7 @@
<div class="filename-pattern-field full">
<span>{{ t('admin.shippingInventory.filenamePattern') }}</span>
<div class="filename-input-wrap">
<input ref="filenamePatternInput" v-model="excelTemplate.filename_pattern" :disabled="templateReadOnly" required @input="updateFilenameVariableMenu" @keydown="handleFilenamePatternKeydown" @blur="closeFilenameVariableMenu">
<input ref="filenamePatternInput" v-model="excelTemplate.filename_pattern" :disabled="templateReadOnly" @input="updateFilenameVariableMenu" @keydown="handleFilenamePatternKeydown" @blur="closeFilenameVariableMenu">
<div v-if="filenameVariableMenuOpen" class="filename-variable-menu" role="listbox" :aria-label="t('admin.shippingInventory.filenameVariablesTitle')">
<button v-for="(variable, index) in filenameVariableCandidates" :key="variable.key" type="button" :class="{ active: index === filenameVariableActiveIndex }" role="option" :aria-selected="index === filenameVariableActiveIndex" @mousedown.prevent @click="insertFilenameVariable(variable)">
<code>{{ variable.key }}</code><span>{{ t(variable.labelKey) }}</span>
@@ -11,15 +11,18 @@ import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
import {
cloneOrderDocumentProfile,
createOrderProfileSample,
createOrderProfileFromSample,
deleteOrderDocumentProfile,
getOrderProfileSampleTables,
getOrderProfileSampleStatus,
listOrderDocumentProfiles,
listOrderProfileSamples,
publishOrderDocumentProfile,
retireOrderDocumentProfile,
updateOrderProfileFromSample,
} from '@/features/admin/api/shipping-order-document-profile.api';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
import type {
OrderProfileSampleDocument,
@@ -40,6 +43,8 @@ const { t } = useI18n();
const message = useMessage();
const loading = ref(false);
const saving = ref(false);
const sampleUploading = ref(false);
const sampleInput = ref<HTMLInputElement | null>(null);
const editingProfileId = ref<number | null>(null);
const editingLockVersion = ref<number | null>(null);
const profiles = ref<ShippingOrderDocumentProfile[]>([]);
@@ -75,6 +80,7 @@ const duplicateTargets = computed(() => {
const canSave = computed(() => Boolean(
form.profile_code.trim() && form.display_name.trim() && form.schema_version_id
&& form.document_id && form.table_id && selectedTable.value
&& selectedTable.value.profile_creation_allowed
&& form.data_start_row_index > form.header_row_index
&& form.header_row_index >= 0
&& form.data_start_row_index < (selectedTable.value?.row_count || 0)
@@ -119,6 +125,35 @@ const loadPreview = async () => {
}
};
/** 上传管理员专用 PDF/EML 样本并轮询预解析;此入口不创建发货任务或调用 Dify。 */
const uploadSample = async (event: Event) => {
const file = (event.target as HTMLInputElement).files?.[0];
if (!file) return;
const extension = file.name.split('.').pop()?.toLowerCase();
if (extension !== 'pdf' && extension !== 'eml') {
message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid'));
return;
}
sampleUploading.value = true;
try {
const asset = await uploadFileAsset(file);
const intake = await createOrderProfileSample(asset.asset_no);
for (let attempt = 0; attempt < 30; attempt += 1) {
const state = await getOrderProfileSampleStatus(intake.intake_no);
if (state.parse_status === 'parsed') break;
if (state.parse_status === 'parse_failed') throw new Error(state.error_code || 'sample parse failed');
await new Promise((resolve) => window.setTimeout(resolve, 1000));
}
await load();
message.success(t('admin.shippingOrderProfiles.sampleUploaded'));
} catch (error) {
showError(error);
} finally {
sampleUploading.value = false;
if (sampleInput.value) sampleInput.value.value = '';
}
};
/** 表格变化时按真实列数初始化受控列映射。 */
const resetColumns = () => {
const count = selectedTable.value?.column_count || 0;
@@ -271,6 +306,13 @@ onMounted(load);
</option>
</select>
</label>
<div class="rounded-lg border border-dashed border-slate-300 p-3">
<p class="text-sm text-slate-600">{{ t('admin.shippingOrderProfiles.uploadSampleHint') }}</p>
<input ref="sampleInput" class="sr-only" type="file" accept=".pdf,.eml,application/pdf,message/rfc822" @change="uploadSample" />
<button type="button" :disabled="sampleUploading" class="mt-2 rounded border border-blue-300 px-3 py-1.5 text-sm text-blue-700 disabled:opacity-50" @click="sampleInput?.click()">
{{ sampleUploading ? t('common.loading') : t('admin.shippingOrderProfiles.uploadSample') }}
</button>
</div>
<label class="block text-sm">
<span class="mb-1 block text-slate-600">{{ t('admin.shippingOrderProfiles.table') }}</span>
<select v-model="form.table_id" class="w-full rounded-lg border border-slate-300 px-3 py-2" :disabled="!preview">
@@ -309,6 +351,9 @@ onMounted(load);
<p v-if="duplicateTargets.length" class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700">
{{ t('admin.shippingOrderProfiles.duplicateTargets', { fields: duplicateTargets.join(', ') }) }}
</p>
<p v-if="selectedTable && !selectedTable.profile_creation_allowed" class="rounded-lg bg-amber-50 px-3 py-2 text-sm text-amber-800">
{{ t('admin.shippingOrderProfiles.structureBlocked') }}
</p>
<button type="submit" :disabled="!canSave || saving" class="w-full rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white disabled:opacity-50">
{{ saving ? t('admin.shippingOrderProfiles.saving') : t(editingProfileId ? 'admin.shippingOrderProfiles.updateDraft' : 'admin.shippingOrderProfiles.createDraft') }}
</button>
@@ -58,6 +58,8 @@ export interface OrderProfileSampleTable {
row_count: number;
column_count: number;
rows: string[][];
issues: string[];
profile_creation_allowed: boolean;
}
export interface OrderProfileSamplePreview {
@@ -65,6 +67,13 @@ export interface OrderProfileSamplePreview {
tables: OrderProfileSampleTable[];
}
export interface OrderProfileSampleIntake {
intake_no: string;
parse_status: string;
document_count: number;
error_code?: string | null;
}
export interface CreateOrderProfileFromSampleInput {
profile_code: string;
display_name: string;
+40 -2
View File
@@ -449,6 +449,24 @@ export async function updateWorkspaceShippingNoticeFields(
return assertShippingOk(body);
}
/**
* 冻结已复核的订单数据为后续库存、Excel 与上传唯一读取的履约快照。
* @param taskNo - 当前任务编号
* @param expectedOrderDataVersion - 用户看到的订单版本,用于拒绝并发覆盖
*/
export async function freezeWorkspaceShippingOrder(
taskNo: string,
expectedOrderDataVersion: number,
) {
const body = await requestJson<ShippingApiStatusPayload & {
data?: { task_no: string; snapshot_id: number; order_data_version: number; frozen_at: string };
}>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/freeze-order`,
jsonPost({ expected_order_data_version: expectedOrderDataVersion }),
);
return assertShippingOk(body);
}
/**
* 更新指定订单行。
* @param taskNo - 发货任务编号
@@ -580,6 +598,22 @@ export async function matchWorkspaceShippingInventory(taskNo: string) {
return assertShippingOk(body);
}
/**
* 上传当前任务使用的正式库存文件。
* @param taskNo - 发货任务编号
* @param file - 已按库存源发布方案导出的 xls/xlsx/csv 文件
* @returns 库存解析与后续匹配结果
*/
export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) {
const form = new FormData();
form.append('file', file);
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/upload-inventory`,
{ method: 'POST', body: form },
);
return assertShippingOk(body);
}
/**
* 以用户态触发自动推进,作为聊天前端兜底入口。
* @param taskNo - 发货任务编号
@@ -597,12 +631,16 @@ export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: s
/**
* 标记货代系统已人工上传完成。
* @param taskNo - 发货任务编号
* @param payload - 当前 Artifact、人工回执 FileAsset 编号及可选货代参考号;回执编号必填。
* @returns 上传确认结果
*/
export async function markWorkspaceShippingManualUploaded(taskNo: string) {
export async function markWorkspaceShippingManualUploaded(
taskNo: string,
payload: { evidence_asset_no: string; artifact_id?: number; freight_ref_no?: string },
) {
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
jsonPost(),
jsonPost(payload),
);
return assertShippingOk(body);
}
@@ -3,7 +3,7 @@
* 用途:验证建批 Chat Turn payload 包含幂等键与会话映射。
*/
import { describe, expect, it } from 'vitest';
import { buildShippingCreateBatchFromIntakesTurn, buildShippingCreateBatchTurn } from './shippingTurnActions';
import { buildShippingCreateBatchFromIntakesTurn, buildShippingCreateBatchTurn, resolveShippingChatTurn } from './shippingTurnActions';
describe('shippingTurnActions', () => {
it('buildShippingCreateBatchTurn includes idempotency_key in payload', () => {
@@ -32,4 +32,12 @@ describe('shippingTurnActions', () => {
expect(turn.payload.intake_nos).toEqual(['SNI-001']);
expect(turn.payload.candidate_nos).toEqual(['SNC-001', 'SNC-003']);
});
it('maps freeze_order only with the version shown to the user', () => {
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001')).toBeNull();
expect(resolveShippingChatTurn('freeze_order', 'sn-freeze-001', { expectedOrderDataVersion: 7 })).toEqual({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-001', expected_order_data_version: 7 },
});
});
});
@@ -21,7 +21,7 @@ export interface ShippingChatTurnSpec {
export function resolveShippingChatTurn(
actionId: string,
taskNo: string,
extra?: { sourceCode?: string },
extra?: { sourceCode?: string; expectedOrderDataVersion?: number },
): ShippingChatTurnSpec | null {
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!normalizedTaskNo) return null;
@@ -36,6 +36,16 @@ export function resolveShippingChatTurn(
}
switch (id) {
case 'freeze_order':
const expectedOrderDataVersion = extra?.expectedOrderDataVersion;
if (!Number.isInteger(expectedOrderDataVersion) || !expectedOrderDataVersion || expectedOrderDataVersion < 1) return null;
return {
actionType: 'shipping.freeze_order',
payload: {
task_no: normalizedTaskNo,
expected_order_data_version: expectedOrderDataVersion,
},
};
case 'generate_excel':
return { actionType: 'shipping.generate_excel', payload: { task_no: normalizedTaskNo } };
case 'retry_upload':
@@ -6,6 +6,7 @@
*/
import { buildShippingSubmitDecisionTurn, buildShippingTurnRefs } from './shippingTurnActions';
import { reportShippingDebugEvent } from './shippingDebugReporter';
import { uploadFileAsset } from '@/shared/api/file-assets.api';
import type { StartChatTurnOptions } from '../types/chat-turn.types';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
@@ -57,6 +58,30 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
void ctx.refreshShippingActions();
};
/**
* 在 Chat 操作中选择并上传人工货代回执,返回当前用户私有的 FileAsset 编号。
* 取消选择不会提交“已手工上传”动作,确保后端的证据门禁没有绕过路径。
*/
const selectManualUploadEvidence = () => new Promise<File | null>((resolve) => {
const picker = document.createElement('input');
picker.type = 'file';
picker.accept = 'image/*,.pdf';
picker.style.display = 'none';
document.body.appendChild(picker);
let settled = false;
const finish = (file: File | null) => {
if (settled) return;
settled = true;
picker.remove();
resolve(file);
};
picker.addEventListener('change', () => finish(picker.files?.[0] || null), { once: true });
picker.addEventListener('cancel', () => finish(null), { once: true });
// 部分浏览器不会触发 cancel;窗口重新获得焦点后仍未选择文件即视为取消。
window.addEventListener('focus', () => setTimeout(() => finish(picker.files?.[0] || null), 0), { once: true });
picker.click();
});
/**
* 提交发货人工决策,经 Chat Turn 统一 SSE 返回。
*/
@@ -108,12 +133,18 @@ export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
manualUploadInFlightTaskIds.add(normalizedTaskId);
const userText = (displayText || '我已在货代系统完成上传').trim();
try {
const evidenceFile = await selectManualUploadEvidence();
if (!evidenceFile) {
ctx.msg.warning('请先选择货代上传截图或回执文件');
return false;
}
const evidence = await uploadFileAsset(evidenceFile);
const ok = await ctx.startChatTurn({
agentId: ctx.currentAgentId.value,
inputType: 'action',
displayText: userText,
actionType: 'shipping.mark_manual_uploaded',
payload: { task_no: normalizedTaskId },
payload: { task_no: normalizedTaskId, evidence_asset_no: evidence.asset_no },
refs: buildShippingTurnRefs(normalizedTaskId, ctx.getActiveShippingBatchNo()),
hooks: {
onAssistantMessageFinished: async (assistantMsg) => {
@@ -101,6 +101,23 @@ describe('useChatShippingMenuHandler', () => {
);
});
it('reads the displayed order version before freezing through Chat Turn', async () => {
getWorkspaceShippingTask.mockResolvedValue({ order_data_version: 9 });
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
await handleShippingMenuAction(
{ id: 'freeze_order', label: '冻结订单', message: '冻结已复核订单' },
undefined,
{ taskId: 'sn-freeze-901' },
);
expect(ctx.startChatTurn).toHaveBeenCalledWith(expect.objectContaining({
actionType: 'shipping.freeze_order',
payload: { task_no: 'SN-FREEZE-901', expected_order_data_version: 9 },
}));
});
it('passes explicit taskId into inventory picker actions', async () => {
const ctx = createContext();
const { handleShippingMenuAction } = createShippingMenuHandlers(ctx);
@@ -90,7 +90,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const runShippingActionTurn = async (
action: ShippingActionButton | { id?: string; message: string; label?: string },
taskId: string,
extra?: { sourceCode?: string },
extra?: { sourceCode?: string; expectedOrderDataVersion?: number },
) => {
const actionId = String(action.id || '').trim();
const turnSpec = resolveShippingChatTurn(actionId, taskId, extra);
@@ -153,6 +153,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
const chatTurnActionIds = new Set([
'freeze_order',
'generate_excel',
'retry_upload',
'match_inventory',
@@ -171,6 +172,17 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
}
try {
let sourceCode = '';
let expectedOrderDataVersion: number | undefined;
if (action.id === 'freeze_order') {
const detail = await getWorkspaceShippingTask(taskId);
const version = Number(detail.order_data_version);
if (!Number.isInteger(version) || version < 1) {
ctx.msg.warning(ctx.t('chat.shippingNoticeRefreshRequired'));
if (chatMsg) chatMsg.shipping_actions_used = false;
return;
}
expectedOrderDataVersion = version;
}
if (action.id === 'confirm_inventory_source') {
sourceCode = String((action as { source_code?: unknown }).source_code || '').trim().toUpperCase();
if (!sourceCode) {
@@ -193,7 +205,7 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
await runShippingActionTurn(
{ ...action, message: displayMessage },
taskId,
sourceCode ? { sourceCode } : undefined,
sourceCode ? { sourceCode } : { expectedOrderDataVersion },
);
} catch (e: unknown) {
ctx.msg.warning(e instanceof Error ? e.message : '操作失败');
@@ -357,8 +357,13 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
parse_validation?: ShippingParseValidation | null;
process_field_gate?: ShippingProcessFieldGate | null;
source_candidate?: ShippingSourceCandidateProjection | null;
/** 非空表示订单已冻结,后续履约链只读取该 Snapshot。 */
order_snapshot_id?: number | null;
order_data_version?: number | null;
field_conflicts?: ShippingFieldConflict[] | null;
inventory_verifications?: ShippingInventoryVerification[];
export_artifacts?: ShippingExportArtifact[];
upload_attempts?: ShippingUploadAttempt[];
events: ShippingTaskEvent[];
ui_state?: ShippingTaskUiState;
}
@@ -551,6 +556,49 @@ export interface ShippingNoticeIntakeResponse {
candidate_count?: number;
}
export interface ShippingInventoryVerificationLine {
reservation_id: number;
required_qty: string;
available_qty: string;
status: 'available' | 'shortage' | 'invalid' | string;
}
export interface ShippingInventoryVerification {
id: number;
status: string;
inventory_snapshot_id?: number | null;
source_config_version?: string | null;
created_at?: string | null;
lines: ShippingInventoryVerificationLine[];
}
export interface ShippingExportArtifact {
id: number;
artifact_no: string;
status: string;
file_name: string;
file_size: number;
created_at?: string | null;
reservation_ids: number[];
}
export interface ShippingUploadAttempt {
id: number;
artifact_id: number;
attempt_no: number;
mode: 'rpa' | 'manual' | string;
status: string;
callback_id?: string | null;
freight_ref_no?: string | null;
error_code?: string | null;
error_message?: string | null;
evidence_asset_id?: number | null;
operator_id?: number | null;
started_at?: string | null;
finished_at?: string | null;
created_at?: string | null;
}
export type ShippingOrderExtractionRunStatus =
| 'queued'
| 'running'
@@ -1,42 +1,29 @@
<script setup lang="ts">
/**
* features/workspace/views/ShippingNoticeView.vue
* 用途:货代发货任务只读工作台,提供任务筛选、详情查看与跳转 Chat 继续处理入口。
* 用途:货代发货任务工作台,提供任务筛选、履约审计与跳转对话入口。
* 依赖:ShippingWorkflowStepper、ShippingMatchResultCard、ShippingTaskParsedResultCard、shipping.api。
* 逻辑:先拉取任务列表与详情,再以只读方式展示步骤、匹配结果、解析行和事件记录;所有写操作回到 Chat 主路径完成。
* 逻辑:先拉取任务列表与详情,再展示步骤、匹配结果、解析行和事件记录;所有用户写操作仅由对话界面执行。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/features/auth';
import { Archive, ArrowLeft, Download, ExternalLink, RefreshCw, RotateCcw, Trash2 } from 'lucide-vue-next';
import { ArrowLeft, ExternalLink, RefreshCw } from 'lucide-vue-next';
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
import ShippingTaskParsedResultCard from '@/features/chat/components/ShippingTaskParsedResultCard.vue';
import { formatLocalDateTime } from '@/shared/utils/dateTime';
import { useMessage } from '@/shared/composables/useMessage';
import {
getWorkspaceShippingTask,
archiveWorkspaceShippingTasks,
deleteWorkspaceShippingTasks,
downloadWorkspaceShippingExportArchive,
listShippingChatAgents,
listWorkspaceShippingTasks,
purgeWorkspaceShippingTasks,
restoreWorkspaceShippingTasks,
SHIPPING_NOTICE_AGENT_CODE,
workspaceShippingExportUrl,
type ShippingCurrentStepProgress,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import { getAuthHeaders } from '@/shared/utils/auth';
import { resolveShippingWorkflowSteps } from '@/features/chat/shipping';
import { sanitizeShippingRuntimeStatusText } from '@/features/chat/shipping/shippingText';
import {
selectVisibleShippingExports,
updateShippingExportSelection,
} from '@/features/shipping-notice/utils/exportSelection';
import { SHIPPING_TASK_STATUS_FILTERS } from '../shippingTaskStatuses';
const props = defineProps<{
@@ -45,17 +32,10 @@ const props = defineProps<{
const router = useRouter();
const { t, te } = useI18n();
const msg = useMessage();
const authStore = useAuthStore();
const isAdmin = computed(() => authStore.isAdmin);
const loading = ref(false);
const detailLoading = ref(false);
const tasks = ref<ShippingTaskSummary[]>([]);
const selectedTaskNo = ref<string | null>(null);
const selectedTaskNos = ref<string[]>([]);
const archiveDownloading = ref(false);
const dispositionSubmitting = ref(false);
const detail = ref<ShippingTaskDetail | null>(null);
const statusFilter = ref('all');
const lifecycleFilter = ref('active');
@@ -222,7 +202,6 @@ const loadCases = async (resetPage = false) => {
}
tasks.value = result.items;
totalTasks.value = result.total;
selectedTaskNos.value = [];
selectedTaskNo.value = null;
} catch {
tasks.value = [];
@@ -232,7 +211,7 @@ const loadCases = async (resetPage = false) => {
}
};
/** 切换分页时清空仅当前页有效的下载选择,防止跨页误下载。 */
/** 切换页码并重新读取只读任务列表。 */
const changePage = async (page: number) => {
const normalized = Math.max(1, Math.min(page, totalPages.value));
if (normalized === currentPage.value || loading.value) return;
@@ -271,93 +250,6 @@ const openInChat = (taskNo: string, conversationId?: string | null, batchNo?: st
router.push({ path: `/chat/${chatAgentId.value}`, query });
};
const downloadExport = async (taskNo: string) => {
const url = workspaceShippingExportUrl(taskNo);
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) return;
const blob = await res.blob();
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = detail.value?.export_file_name || `${taskNo}.xlsx`;
a.click();
URL.revokeObjectURL(a.href);
};
/** 下载当前任务所属批次的所有有效 Artifact;缺失票据记录在 ZIP manifest。 */
const downloadBatchExports = async (batchNo: string) => {
await downloadExportArchive({ batch_no: batchNo });
};
/** 下载批次或显式任务集合,并确保临时对象 URL 在点击后释放。 */
const downloadExportArchive = async (payload: { batch_no?: string; task_nos?: string[] }) => {
archiveDownloading.value = true;
try {
const { blob, filename } = await downloadWorkspaceShippingExportArchive(payload);
const a = document.createElement('a');
a.href = URL.createObjectURL(blob); a.download = filename; a.click(); URL.revokeObjectURL(a.href);
} catch {
msg.error(t('workspace.shippingNotice.archiveDownloadFailed'));
} finally {
archiveDownloading.value = false;
}
};
/** 更新单票勾选;数量门禁与后端 100 票限制一致。 */
const toggleTask = (taskNo: string, checked: boolean) => {
selectedTaskNos.value = updateShippingExportSelection(selectedTaskNos.value, taskNo, checked);
};
/** 全选或清空当前页结果,切页后不保留选择。 */
const toggleAllVisibleTasks = (checked: boolean) => {
selectedTaskNos.value = checked
? selectVisibleShippingExports(tasks.value.map((item) => item.task_no))
: [];
};
const allVisibleTasksSelected = computed(() => (
tasks.value.length > 0 && tasks.value.every((item) => selectedTaskNos.value.includes(item.task_no))
));
/** 按用户显式选择下载,后端仍逐票执行权限与 Artifact 当前性校验。 */
const downloadSelectedExports = async () => {
if (!selectedTaskNos.value.length) return;
await downloadExportArchive({ task_nos: selectedTaskNos.value });
};
/** 批量执行回收站、归档或恢复;删除必须显式录入原因,服务端仍逐票重算资格。 */
const applyTaskDisposition = async (action: 'delete' | 'archive' | 'restore' | 'purge') => {
if (!selectedTaskNos.value.length || dispositionSubmitting.value) return;
let reason = '';
if (action === 'delete' || action === 'purge') {
const promptKey = action === 'purge'
? 'workspace.shippingNotice.disposition.purgeReasonPrompt'
: 'workspace.shippingNotice.disposition.reasonPrompt';
reason = window.prompt(t(promptKey))?.trim() || '';
if (!reason) return;
}
if (!window.confirm(t('workspace.shippingNotice.disposition.confirm', {
action: t(`workspace.shippingNotice.disposition.actions.${action}`), count: selectedTaskNos.value.length,
}))) return;
dispositionSubmitting.value = true;
try {
const result = action === 'delete'
? await deleteWorkspaceShippingTasks(selectedTaskNos.value, reason)
: action === 'archive'
? await archiveWorkspaceShippingTasks(selectedTaskNos.value)
: action === 'restore'
? await restoreWorkspaceShippingTasks(selectedTaskNos.value)
: await purgeWorkspaceShippingTasks(selectedTaskNos.value, reason);
const blocked = result.results.filter((item) => item.status === 'blocked').length;
if (blocked) msg.error(t('workspace.shippingNotice.disposition.partial', { success: result.results.length - blocked, blocked }));
else msg.success(t('workspace.shippingNotice.disposition.success', { count: result.results.length }));
await loadCases();
} catch {
msg.error(t('workspace.shippingNotice.disposition.failed'));
} finally {
dispositionSubmitting.value = false;
}
};
const shortageLines = computed(() => detail.value?.shortage?.lines || []);
const hasMatchCard = computed(() =>
!!detail.value && (
@@ -393,14 +285,16 @@ onMounted(async () => {
<p class="text-sm text-muted">{{ $t('workspace.shippingNotice.subtitle') }}</p>
</div>
</div>
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="loadCases(true)"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.refresh') }}
</button>
<div class="flex gap-2">
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="loadCases(true)"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.refresh') }}
</button>
</div>
</div>
<div class="flex flex-wrap items-end gap-3 rounded-2xl border border-default/80 bg-surface/70 px-4 py-3 shadow-sm">
@@ -423,67 +317,6 @@ onMounted(async () => {
>
{{ $t('workspace.shippingNotice.search') }}
</button>
<label class="ml-auto inline-flex items-center gap-2 text-sm text-secondary">
<input
type="checkbox"
:checked="allVisibleTasksSelected"
:disabled="tasks.length === 0"
@change="toggleAllVisibleTasks(($event.target as HTMLInputElement).checked)"
>
{{ $t('workspace.shippingNotice.selectAllVisible') }}
</label>
<span class="text-sm text-muted">
{{ $t('workspace.shippingNotice.selectedCount', { count: selectedTaskNos.length }) }}
</span>
<button
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
:disabled="selectedTaskNos.length === 0 || archiveDownloading"
@click="downloadSelectedExports"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.downloadSelected') }}
</button>
<button
v-if="lifecycleFilter === 'active'"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
:disabled="selectedTaskNos.length === 0 || dispositionSubmitting"
@click="applyTaskDisposition('archive')"
>
<Archive class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.disposition.actions.archive') }}
</button>
<button
v-if="lifecycleFilter === 'active'"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-rose-300 px-3 py-2 text-sm font-medium text-rose-700 hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="selectedTaskNos.length === 0 || dispositionSubmitting"
@click="applyTaskDisposition('delete')"
>
<Trash2 class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.disposition.actions.delete') }}
</button>
<button
v-if="lifecycleFilter === 'deleted'"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
:disabled="selectedTaskNos.length === 0 || dispositionSubmitting"
@click="applyTaskDisposition('restore')"
>
<RotateCcw class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.disposition.actions.restore') }}
</button>
<button
v-if="lifecycleFilter === 'deleted' && isAdmin"
type="button"
class="inline-flex items-center gap-1.5 rounded-xl border border-rose-300 px-3 py-2 text-sm font-medium text-rose-700 hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="selectedTaskNos.length === 0 || dispositionSubmitting"
@click="applyTaskDisposition('purge')"
>
<Trash2 class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.disposition.actions.purge') }}
</button>
</div>
<div class="grid gap-5 lg:grid-cols-5">
@@ -500,13 +333,6 @@ onMounted(async () => {
class="flex w-full items-start gap-3 rounded-2xl border px-4 py-3 transition-colors"
:class="selectedTaskNo === item.task_no ? 'border-brand-400 bg-brand-50/60' : 'border-default hover:bg-surface-soft/70'"
>
<input
type="checkbox"
class="mt-1"
:aria-label="$t('workspace.shippingNotice.selectForDownload', { taskNo: item.task_no })"
:checked="selectedTaskNos.includes(item.task_no)"
@change="toggleTask(item.task_no, ($event.target as HTMLInputElement).checked)"
>
<button type="button" class="min-w-0 flex-1 text-left" @click="selectedTaskNo = item.task_no">
<div class="flex items-center justify-between gap-2">
<span class="font-mono text-sm font-semibold text-primary">{{ item.task_no }}</span>
@@ -585,25 +411,6 @@ onMounted(async () => {
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.openChat') }}
</button>
<button
v-if="detail.export_file_name"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
@click="downloadExport(detail.task_no)"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.download') }}
</button>
<button
v-if="detail.batch_no"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
:disabled="archiveDownloading"
@click="downloadBatchExports(detail.batch_no)"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.downloadBatch') }}
</button>
</div>
</div>
@@ -743,6 +550,59 @@ onMounted(async () => {
:action-busy="false"
/>
<section
v-if="detail.inventory_verifications?.length"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm"
>
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.fulfillmentTimeline.inventoryTitle') }}</h3>
<div v-for="verification in detail.inventory_verifications" :key="verification.id" class="border-t border-default/70 py-2 first:border-t-0 first:pt-0">
<div class="flex flex-wrap gap-x-3 gap-y-1 text-xs">
<span class="font-medium text-secondary">#{{ verification.id }} · {{ verification.status }}</span>
<span>{{ formatLocalDateTime(verification.created_at) }}</span>
</div>
<div class="mt-1 text-xs text-muted">
<span v-for="line in verification.lines" :key="line.reservation_id" class="mr-3 inline-block">
{{ $t('workspace.shippingNotice.fulfillmentTimeline.verificationLine', { reservationId: line.reservation_id, availableQty: line.available_qty, requiredQty: line.required_qty, status: line.status }) }}
</span>
</div>
</div>
</section>
<section
v-if="detail.export_artifacts?.length"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm"
>
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.fulfillmentTimeline.artifactTitle') }}</h3>
<div v-for="artifact in detail.export_artifacts" :key="artifact.id" class="border-t border-default/70 py-2 first:border-t-0 first:pt-0">
<div class="flex flex-wrap gap-x-3 gap-y-1 text-xs">
<span class="font-mono font-medium text-secondary">{{ artifact.artifact_no }}</span>
<span>{{ artifact.status }}</span>
<span>{{ artifact.file_name }}</span>
<span>{{ formatLocalDateTime(artifact.created_at) }}</span>
</div>
<p class="mt-1 text-xs text-muted">{{ $t('workspace.shippingNotice.fulfillmentTimeline.reservationIds', { reservationIds: artifact.reservation_ids.join(', ') || '—' }) }}</p>
</div>
</section>
<section
v-if="detail.upload_attempts?.length"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3 text-sm"
>
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.fulfillmentTimeline.uploadTitle') }}</h3>
<div v-for="attempt in detail.upload_attempts" :key="attempt.id" class="border-t border-default/70 py-2 first:border-t-0 first:pt-0">
<div class="flex flex-wrap gap-x-3 gap-y-1 text-xs">
<span class="font-medium text-secondary">{{ $t('workspace.shippingNotice.fulfillmentTimeline.uploadAttempt', { artifactId: attempt.artifact_id, attemptNo: attempt.attempt_no }) }}</span>
<span>{{ attempt.mode }}</span><span>{{ attempt.status }}</span>
<span>{{ formatLocalDateTime(attempt.finished_at || attempt.created_at) }}</span>
</div>
<p v-if="attempt.freight_ref_no || attempt.error_message || attempt.evidence_asset_id" class="mt-1 text-xs text-muted">
{{ attempt.freight_ref_no ? $t('workspace.shippingNotice.fulfillmentTimeline.freightRef', { freightRefNo: attempt.freight_ref_no }) : '' }}
{{ attempt.error_message ? ` ${attempt.error_message}` : '' }}
{{ attempt.evidence_asset_id ? ` ${$t('workspace.shippingNotice.fulfillmentTimeline.evidenceAsset', { assetId: attempt.evidence_asset_id })}` : '' }}
</p>
</div>
</section>
<ShippingTaskParsedResultCard
v-if="detail.lines?.length || detail.process_field_gate || detail.parse_validation || detail.source_candidate || detail.field_conflicts?.length"
class="mt-3"
+5
View File
@@ -2468,6 +2468,11 @@
"shippingOrderProfiles": {
"title": "Order Document Profiles",
"subtitle": "Configure exact column mappings from MinerU table samples without editing JSON or fingerprints.",
"structureBlocked": "This table has a structural error and cannot create a profile. Wait for coordinate-evidence reconstruction and review it; do not repair the raw grid with field mappings.",
"uploadSample": "Upload Template Sample",
"uploadSampleHint": "PDF or EML only. It is used only for profile configuration and structural review; no shipping task is created.",
"sampleFileTypeInvalid": "Only PDF or EML files are supported as profile samples.",
"sampleUploaded": "The template sample is parsed. Select its document from the sample list to continue.",
"createTitle": "Create Draft from Sample",
"editTitle": "Update Draft from Sample",
"sample": "Sample document",
+3
View File
@@ -1,6 +1,7 @@
{
"generic": "Request failed.",
"codes": {
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "The number of uploaded files exceeds the system limit. Split the batch and try again.",
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "An application and an internal executor cannot be converted into each other.",
"AGENT.ADMIN_SCOPE_INVALID": "The application management tab parameter is invalid.",
"AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN": "Internal executors cannot be displayed, assigned, or accessed through user-facing APIs.",
@@ -23,6 +24,8 @@
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "The order document parsing profile is invalid.",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "The profile must bind to a published or retired order schema version.",
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "The profile references an unavailable order line field.",
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "The sample header contains order line data. Rebuild the table structure before creating a profile.",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "Only PDF or EML files are supported as profile samples.",
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "A published order document parsing profile cannot be modified.",
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "The profile lock version is missing. Refresh and try again.",
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "Another administrator changed the profile. Refresh and try again.",
+29 -1
View File
@@ -113,6 +113,7 @@
"schedule": {
"title": "Schedule Runs",
"refresh": "Refresh",
"uploadNotices": "Upload shipping notices",
"search": "Search",
"reset": "Reset",
"loading": "Loading...",
@@ -158,8 +159,9 @@
},
"shippingNotice": {
"title": "Shipping Notice Tasks",
"subtitle": "Read-only view. Continue processing in Chat.",
"subtitle": "Review and perform controlled fulfillment actions independently.",
"refresh": "Refresh",
"uploadNotices": "Upload shipping notices",
"search": "Search",
"loading": "Loading...",
"empty": "No shipping tasks yet",
@@ -173,6 +175,22 @@
"downloadSelected": "Download selected ZIP",
"selectForDownload": "Select task {taskNo} for batch download",
"archiveDownloadFailed": "Batch download failed. Refresh the tasks and try again.",
"actions": {
"title": "Available actions",
"freezeOrder": "Freeze order",
"freezeConfirm": "Freeze the reviewed order? The frozen order becomes the fulfillment fact for inventory, Excel, and upload.",
"freezeFailed": "Order freezing failed or its version changed. Refresh and review it again.",
"inventorySourcePrompt": "Enter the published inventory source code:",
"customerPrompt": "Enter a customer short code or name to search:",
"customerNotFound": "No enabled customer is available to confirm.",
"customerConfirm": "Bind this task to customer {name} ({code})?",
"failed": "Action failed. Refresh the task and try again."
},
"candidateReview": {
"title": "Candidates awaiting batch creation",
"hint": "Select, revise, and resolve duplicates here. Only selected candidates that pass backend gates can create a batch.",
"createBatch": "Create batch from selected"
},
"lifecycle": {
"active": "Active",
"deleted": "Recycle bin",
@@ -246,6 +264,16 @@
"fileNo": "Snapshot ID",
"expired": "Snapshot expired; system will re-trigger RPA or wait for manual upload"
},
"fulfillmentTimeline": {
"inventoryTitle": "Inventory verification history",
"verificationLine": "Reservation {reservationId}: {availableQty}/{requiredQty} ({status})",
"artifactTitle": "Excel artifact timeline",
"reservationIds": "Reservation IDs: {reservationIds}",
"uploadTitle": "Upload attempt timeline",
"uploadAttempt": "Artifact #{artifactId} / Attempt {attemptNo}",
"freightRef": "Freight reference: {freightRefNo}",
"evidenceAsset": "Receipt asset: {assetId}"
},
"status": {
"all": "All",
"created": "Created",
+5
View File
@@ -2336,6 +2336,11 @@
"shippingOrderProfiles": {
"title": "โปรไฟล์เอกสารคำสั่งซื้อ",
"subtitle": "ตั้งค่าการแมปคอลัมน์จากตัวอย่างตาราง MinerU โดยไม่ต้องแก้ไข JSON หรือลายนิ้วมือโครงสร้าง",
"structureBlocked": "ตารางนี้มีข้อผิดพลาดด้านโครงสร้างและไม่สามารถสร้างโปรไฟล์ได้ โปรดรอการสร้างใหม่จากหลักฐานพิกัดแล้วตรวจทาน ห้ามแก้กริดต้นฉบับด้วยการแมปฟิลด์",
"uploadSample": "อัปโหลดตัวอย่างเทมเพลต",
"uploadSampleHint": "รองรับเฉพาะ PDF หรือ EML ใช้สำหรับตั้งค่าโปรไฟล์และตรวจทานโครงสร้างเท่านั้น และไม่สร้างงานจัดส่ง",
"sampleFileTypeInvalid": "ตัวอย่างโปรไฟล์รองรับเฉพาะไฟล์ PDF หรือ EML",
"sampleUploaded": "แยกวิเคราะห์ตัวอย่างเทมเพลตแล้ว โปรดเลือกเอกสารจากรายการตัวอย่างเพื่อดำเนินการต่อ",
"createTitle": "สร้างฉบับร่างจากตัวอย่าง",
"editTitle": "อัปเดตฉบับร่างจากตัวอย่าง",
"sample": "เอกสารตัวอย่าง",
+3
View File
@@ -1,6 +1,7 @@
{
"generic": "คำขอล้มเหลว",
"codes": {
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "จำนวนไฟล์ที่อัปโหลดเกินขีดจำกัดของระบบ โปรดแบ่งชุดแล้วลองใหม่",
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "ไม่สามารถแปลงแอปพลิเคชันเป็นตัวดำเนินการภายในหรือกลับกันได้",
"AGENT.ADMIN_SCOPE_INVALID": "พารามิเตอร์แท็บการจัดการแอปพลิเคชันไม่ถูกต้อง",
"AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN": "ไม่สามารถแสดง มอบสิทธิ์ หรือเข้าถึงตัวดำเนินการภายในผ่าน API สำหรับผู้ใช้ได้",
@@ -23,6 +24,8 @@
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "การตั้งค่าโปรไฟล์การแยกข้อมูลเอกสารคำสั่งซื้อไม่ถูกต้อง",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "โปรไฟล์ต้องผูกกับเวอร์ชันสคีมาคำสั่งซื้อที่เผยแพร่หรือเลิกใช้งานแล้ว",
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "โปรไฟล์อ้างอิงฟิลด์รายการคำสั่งซื้อที่ไม่พร้อมใช้งาน",
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "ส่วนหัวของตัวอย่างมีข้อมูลรายการคำสั่งซื้อ ต้องสร้างโครงสร้างตารางใหม่ก่อนจึงจะสร้างโปรไฟล์ได้",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "ตัวอย่างโปรไฟล์รองรับเฉพาะไฟล์ PDF หรือ EML",
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "ไม่สามารถแก้ไขโปรไฟล์เอกสารคำสั่งซื้อที่เผยแพร่แล้ว",
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "ไม่มีเวอร์ชันล็อกของโปรไฟล์ โปรดรีเฟรชแล้วลองใหม่",
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "ผู้ดูแลระบบรายอื่นแก้ไขโปรไฟล์แล้ว โปรดรีเฟรชแล้วลองใหม่",
+28 -1
View File
@@ -100,8 +100,9 @@
},
"shippingNotice": {
"title": "ใบแจ้งส่งสินค้า",
"subtitle": "พื้นที่ทำงานแบบอ่านอย่างเดียว โปรดดำเนินการต่อใน Chat",
"subtitle": "ตรวจสอบและดำเนินการตามขั้นตอนการจัดส่งที่ควบคุมได้อย่างอิสระ",
"refresh": "รีเฟรช",
"uploadNotices": "อัปโหลดใบแจ้งการจัดส่ง",
"search": "ค้นหา",
"loading": "กำลังโหลด...",
"empty": "ยังไม่มีงานส่งสินค้า",
@@ -115,6 +116,22 @@
"downloadSelected": "ดาวน์โหลด ZIP ที่เลือก",
"selectForDownload": "เลือกงาน {taskNo} สำหรับดาวน์โหลดแบบกลุ่ม",
"archiveDownloadFailed": "ดาวน์โหลดแบบกลุ่มไม่สำเร็จ โปรดรีเฟรชงานแล้วลองอีกครั้ง",
"actions": {
"title": "การดำเนินการที่ทำได้",
"freezeOrder": "ตรึงคำสั่งซื้อ",
"freezeConfirm": "ยืนยันการตรึงคำสั่งซื้อที่ตรวจทานแล้วหรือไม่ หลังตรึงแล้วจะเป็นข้อเท็จจริงสำหรับสต็อก Excel และการอัปโหลด",
"freezeFailed": "ตรึงคำสั่งซื้อไม่สำเร็จหรือเวอร์ชันเปลี่ยนแล้ว โปรดรีเฟรชและตรวจทานอีกครั้ง",
"inventorySourcePrompt": "ป้อนรหัสแหล่งสต็อกที่เผยแพร่แล้ว:",
"customerPrompt": "ป้อนรหัสย่อลูกค้าหรือชื่อเพื่อค้นหา:",
"customerNotFound": "ไม่พบลูกค้าที่เปิดใช้งานสำหรับการยืนยัน",
"customerConfirm": "ผูกงานนี้กับลูกค้า {name} ({code}) หรือไม่?",
"failed": "การดำเนินการล้มเหลว โปรดรีเฟรชงานแล้วลองใหม่"
},
"candidateReview": {
"title": "ผู้สมัครที่รอสร้างแบตช์",
"hint": "เลือก แก้ไข และจัดการรายการซ้ำที่นี่ เฉพาะผู้สมัครที่เลือกและผ่านเงื่อนไขฝั่งเซิร์ฟเวอร์จึงสร้างแบตช์ได้",
"createBatch": "สร้างแบตช์จากรายการที่เลือก"
},
"lifecycle": {
"active": "กำลังดำเนินการ",
"deleted": "ถังรีไซเคิล",
@@ -188,6 +205,16 @@
"fileNo": "รหัสสแนปช็อต",
"expired": "สแนปช็อตหมดอายุ ระบบจะเรียก RPA ใหม่หรือรอการอัปโหลดด้วยตนเอง"
},
"fulfillmentTimeline": {
"inventoryTitle": "ประวัติการตรวจสอบสต็อก",
"verificationLine": "ใบจอง {reservationId}: {availableQty}/{requiredQty} ({status})",
"artifactTitle": "ไทม์ไลน์ Excel Artifact",
"reservationIds": "รหัสใบจอง: {reservationIds}",
"uploadTitle": "ไทม์ไลน์ความพยายามอัปโหลด",
"uploadAttempt": "Artifact #{artifactId} / Attempt {attemptNo}",
"freightRef": "หมายเลขอ้างอิงผู้ขนส่ง: {freightRefNo}",
"evidenceAsset": "ไฟล์หลักฐาน: {assetId}"
},
"status": {
"all": "ทั้งหมด",
"created": "สร้างแล้ว",
+5
View File
@@ -2446,6 +2446,11 @@
"shippingOrderProfiles": {
"title": "订单文档模板",
"subtitle": "从 MinerU 表格样本可视化配置精确列映射;无需编辑 JSON 或结构指纹。",
"structureBlocked": "该表格结构异常,不能创建模板。请等待坐标证据重建后再复核,勿通过字段映射修复原始网格。",
"uploadSample": "上传模板样本",
"uploadSampleHint": "仅支持 PDF 或 EML,仅用于模板配置和结构复核,不创建发货任务。",
"sampleFileTypeInvalid": "模板样本仅支持 PDF 或 EML 文件。",
"sampleUploaded": "模板样本已解析,请从样本列表选择文档继续配置。",
"createTitle": "从样本创建草稿",
"editTitle": "用样本更新草稿",
"sample": "样本文档",
+3
View File
@@ -1,6 +1,7 @@
{
"generic": "请求失败。",
"codes": {
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "本次上传文件数超过系统限制,请拆分后重试。",
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "应用与内部执行器不可互相转换。",
"AGENT.ADMIN_SCOPE_INVALID": "应用管理页签参数无效。",
"AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN": "内部执行器不能展示、授权或通过普通用户接口访问。",
@@ -23,6 +24,8 @@
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "订单文档解析模板配置无效。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "订单文档解析模板必须绑定已发布或已退役的订单字段版本。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "订单文档解析模板引用了不可用的订单明细字段。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "样本表头混入订单明细,必须先重建表格结构,不能创建模板。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "模板样本仅支持 PDF 或 EML 文件。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "已发布的订单文档解析模板不可修改。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "订单文档解析模板缺少版本锁,请刷新后重试。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "订单文档解析模板已被其他管理员修改,请刷新后重试。",
+29 -1
View File
@@ -114,6 +114,7 @@
"schedule": {
"title": "排程记录",
"refresh": "刷新",
"uploadNotices": "上传发货通知",
"search": "查询",
"reset": "重置",
"loading": "正在加载...",
@@ -159,8 +160,9 @@
},
"shippingNotice": {
"title": "货代发货通知",
"subtitle": "只读工作台,请在 Chat 中继续处理。",
"subtitle": "可独立查看、复核与执行受控履约操作。",
"refresh": "刷新",
"uploadNotices": "上传发货通知",
"search": "查询",
"loading": "正在加载...",
"empty": "暂无发货任务",
@@ -174,6 +176,22 @@
"downloadSelected": "下载所选 ZIP",
"selectForDownload": "选择任务 {taskNo} 用于批量下载",
"archiveDownloadFailed": "批量下载失败,请刷新任务后重试。",
"actions": {
"title": "当前可执行操作",
"freezeOrder": "冻结订单",
"freezeConfirm": "确认冻结当前已复核订单吗?冻结后将作为库存、Excel 和上传的履约事实。",
"freezeFailed": "订单冻结失败或版本已变化,请刷新后复核。",
"inventorySourcePrompt": "请输入已发布的库存源编码:",
"customerPrompt": "请输入客户简码或名称以搜索:",
"customerNotFound": "未找到可确认的启用客户。",
"customerConfirm": "确认将当前任务绑定到客户 {name}({code})吗?",
"failed": "操作失败,请刷新任务后重试。"
},
"candidateReview": {
"title": "待建单候选复核",
"hint": "在此完成候选选择、人工修订和重复处理;仅已选择且通过后端门禁的候选可以建批。",
"createBatch": "按已选候选建批"
},
"lifecycle": {
"active": "进行中/活动",
"deleted": "回收站",
@@ -247,6 +265,16 @@
"fileNo": "快照编号",
"expired": "快照已过期,系统将重新触发 RPA 或等待人工上传"
},
"fulfillmentTimeline": {
"inventoryTitle": "库存核验历史",
"verificationLine": "预约 {reservationId}:{availableQty}/{requiredQty}({status})",
"artifactTitle": "Excel Artifact 时间线",
"reservationIds": "包含预约单 ID:{reservationIds}",
"uploadTitle": "上传 Attempt 时间线",
"uploadAttempt": "Artifact #{artifactId} / Attempt {attemptNo}",
"freightRef": "货代参考号:{freightRefNo}",
"evidenceAsset": "回执资产:{assetId}"
},
"status": {
"all": "全部",
"created": "已创建",
+5
View File
@@ -2336,6 +2336,11 @@
"shippingOrderProfiles": {
"title": "訂單文件範本",
"subtitle": "從 MinerU 表格樣本視覺化設定精確欄位對應;無需編輯 JSON 或結構指紋。",
"structureBlocked": "此表格結構異常,不能建立範本。請等待座標證據重建後再複核,勿以欄位對應修復原始網格。",
"uploadSample": "上傳範本樣本",
"uploadSampleHint": "僅支援 PDF 或 EML,僅用於範本設定與結構複核,不會建立發貨任務。",
"sampleFileTypeInvalid": "範本樣本僅支援 PDF 或 EML 檔案。",
"sampleUploaded": "範本樣本已解析,請從樣本清單選擇文件繼續設定。",
"createTitle": "從樣本建立草稿",
"editTitle": "使用樣本更新草稿",
"sample": "樣本文件",
+3
View File
@@ -1,6 +1,7 @@
{
"generic": "請求失敗。",
"codes": {
"SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED": "本次上傳檔案數超過系統限制,請拆分後重試。",
"AGENT.EXPOSURE_ROLE_IMMUTABLE": "應用與內部執行器不可互相轉換。",
"AGENT.ADMIN_SCOPE_INVALID": "應用管理頁籤參數無效。",
"AGENT.INTERNAL_EXECUTOR_USER_ACCESS_FORBIDDEN": "內部執行器不能顯示、授權或透過一般使用者介面存取。",
@@ -23,6 +24,8 @@
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "訂單文件解析範本設定無效。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "訂單文件解析範本必須綁定已發布或已退役的訂單欄位版本。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "訂單文件解析範本引用了不可用的訂單明細欄位。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_HEADER_CONTAMINATED": "樣本表頭混入訂單明細,必須先重建表格結構,不能建立範本。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_SAMPLE_FILE_TYPE_INVALID": "範本樣本僅支援 PDF 或 EML 檔案。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_IMMUTABLE": "已發布的訂單文件解析範本不可修改。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED": "訂單文件解析範本缺少版本鎖,請重新整理後再試。",
"SHIPPING_ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT": "訂單文件解析範本已被其他管理員修改,請重新整理後再試。",
+29 -1
View File
@@ -114,6 +114,7 @@
"schedule": {
"title": "排程記錄",
"refresh": "刷新",
"uploadNotices": "上傳發貨通知",
"search": "查詢",
"reset": "重置",
"loading": "正在載入...",
@@ -159,8 +160,9 @@
},
"shippingNotice": {
"title": "貨代發貨通知",
"subtitle": "只讀工作台,請在 Chat 中繼續處理。",
"subtitle": "可獨立檢視、覆核並執行受控履約操作。",
"refresh": "刷新",
"uploadNotices": "上傳發貨通知",
"search": "查詢",
"loading": "正在載入...",
"empty": "暫無發貨任務",
@@ -174,6 +176,22 @@
"downloadSelected": "下載所選 ZIP",
"selectForDownload": "選擇任務 {taskNo} 用於批次下載",
"archiveDownloadFailed": "批次下載失敗,請重新整理任務後再試。",
"actions": {
"title": "目前可執行操作",
"freezeOrder": "凍結訂單",
"freezeConfirm": "確認凍結目前已覆核訂單嗎?凍結後將作為庫存、Excel 與上傳的履約事實。",
"freezeFailed": "訂單凍結失敗或版本已變更,請重新整理後覆核。",
"inventorySourcePrompt": "請輸入已發布的庫存源編碼:",
"customerPrompt": "請輸入客戶簡碼或名稱以搜尋:",
"customerNotFound": "找不到可確認的啟用客戶。",
"customerConfirm": "確認將目前任務綁定至客戶 {name}({code})嗎?",
"failed": "操作失敗,請重新整理任務後再試。"
},
"candidateReview": {
"title": "待建單候選覆核",
"hint": "在此完成候選選擇、人工修訂與重複處理;只有已選擇且通過後端門檻的候選可以建批。",
"createBatch": "依已選候選建批"
},
"lifecycle": {
"active": "進行中/活動",
"deleted": "回收站",
@@ -247,6 +265,16 @@
"fileNo": "快照編號",
"expired": "快照已過期,系統將重新觸發 RPA 或等待人工上傳"
},
"fulfillmentTimeline": {
"inventoryTitle": "庫存核驗歷史",
"verificationLine": "預約 {reservationId}:{availableQty}/{requiredQty}({status})",
"artifactTitle": "Excel Artifact 時間線",
"reservationIds": "包含預約單 ID:{reservationIds}",
"uploadTitle": "上傳 Attempt 時間線",
"uploadAttempt": "Artifact #{artifactId} / Attempt {attemptNo}",
"freightRef": "貨代參考號:{freightRefNo}",
"evidenceAsset": "回執資產:{assetId}"
},
"status": {
"all": "全部",
"created": "已建立",
+6
View File
@@ -1170,6 +1170,8 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
task_no = str(body.get("task_no") or "").strip()
file_path = str(body.get("file_path") or "").strip()
attempt_id = body.get("attempt_id")
callback_id = str(body.get("callback_id") or "").strip()
failed_dir = trigger_path.parent / "failed"
if not task_no:
trigger_path.unlink(missing_ok=True)
@@ -1184,6 +1186,8 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
try:
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"success": False,
"error_message": f"queue file missing: {file_path}",
})
@@ -1196,6 +1200,8 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
try:
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"success": True,
"freight_ref_no": ref,
})