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