feat(shipping-notice): 添加订单文档 Profile 盲测集和样本管理功能,支持创建、执行和批准盲测,增强订单冻结和库存核验功能
This commit is contained in:
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()))
|
||||
@@ -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):
|
||||
|
||||
@@ -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))
|
||||
)
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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')
|
||||
@@ -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"
|
||||
|
||||
+202
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
@@ -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'
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -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'
|
||||
Reference in new issue
Block a user