feat(shipping-notice): 增强订单文档 Profile 管理功能,新增复核与草稿管理
- 添加订单复核相关模型及 API,支持复核案例的创建、更新和确认 - 实现复核草稿的管理功能,允许用户对复核内容进行编辑和保存 - 引入复核事件审计,确保复核过程的可追溯性 - 更新数据库模型以支持复核和草稿的关系管理 - 完善相关服务逻辑,确保复核与草稿的状态管理和数据一致性 - 增强文档模板的管理能力,支持更复杂的业务场景
This commit is contained in:
1 parent
61ac6403c4
commit
b7307fc573
147 files changed
+15108
-1522
No files matched your search
@@ -12,10 +12,22 @@ import io
|
||||
|
||||
from flask import g, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice import order_document_profile_audit_service as audit_service
|
||||
from app.services.shipping_notice import order_document_profile_diff as diff_service
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from app.services.shipping_notice import order_document_profile_revision_service as revision_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
from app.services.shipping_notice import order_document_profile_usage_service as usage_service
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as publish_check_service
|
||||
from app.services.shipping_notice import order_document_profile_version_service as version_service
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
@@ -36,6 +48,53 @@ def _private_ok(data, *, status: int = 200):
|
||||
return response, response_status
|
||||
|
||||
|
||||
def _query_int(name: str, default: int, *, minimum: int | None = None, maximum: int | None = None) -> int:
|
||||
"""读取可选整数查询参数,并做受控范围校验。"""
|
||||
raw = request.args.get(name)
|
||||
if raw in (None, ''):
|
||||
value = int(default)
|
||||
else:
|
||||
try:
|
||||
value = int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise service.ValidationError(
|
||||
f'{name} is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
) from exc
|
||||
if minimum is not None and value < minimum:
|
||||
raise service.ValidationError(
|
||||
f'{name} is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
if maximum is not None and value > maximum:
|
||||
raise service.ValidationError(
|
||||
f'{name} is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def _write_context(data: dict) -> dict:
|
||||
"""读取草稿写入的租约与操作身份;令牌只透传服务层校验,绝不写入审计。"""
|
||||
return {
|
||||
'browser_session_id': data.get('browser_session_id'),
|
||||
'lease_token': data.get('lease_token'),
|
||||
'operation_id': str(data.get('operation_id') or getattr(g, 'request_id', '') or '').strip() or None,
|
||||
}
|
||||
|
||||
|
||||
def _log_profile_view_event(profile_id: int, *, event_type: str, detail: dict | None = None) -> None:
|
||||
"""为只读页面访问留痕;提交失败不影响页面读取。"""
|
||||
try:
|
||||
service._audit(
|
||||
profile_id=int(profile_id),
|
||||
event_type=event_type,
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
detail=detail or {},
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profiles():
|
||||
@@ -43,6 +102,29 @@ def list_order_document_profiles():
|
||||
return _ok(service.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-families', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_families():
|
||||
"""按模板编码聚合版本族摘要,供版本中心和默认选版使用。"""
|
||||
return _ok(version_service.list_profile_families())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-families/<string:profile_code>/versions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_family_versions(profile_code: str):
|
||||
"""列出同一模板族的版本摘要,不混入其他模板编码。"""
|
||||
return _ok(version_service.list_family_versions(profile_code))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-families/<string:profile_code>/versions/<int:version>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_family_version_detail(profile_code: str, version: int):
|
||||
"""按模板编码和版本号读取详情;版本不存在时明确返回 404。"""
|
||||
payload = version_service.get_profile_detail_by_family_version(profile_code, version)
|
||||
_log_profile_view_event(payload['id'], event_type='version_detail_viewed', detail={'source': 'family_version'})
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profile-samples', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_samples():
|
||||
@@ -126,24 +208,15 @@ def generate_order_document_profile_ocr_coordinate_evidence():
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/from-sample', methods=['POST'])
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/wizard-complete', methods=['POST'])
|
||||
@require_admin
|
||||
def create_order_document_profile_from_sample():
|
||||
"""由真实样本和结构化列选择生成后端计算指纹的 Profile 草稿。"""
|
||||
return _ok(service.create_draft_from_sample(
|
||||
def complete_order_document_profile_wizard():
|
||||
"""完成三步向导的唯一创建入口;草稿、样本、Revision、审计和 Lease 在同一事务提交。"""
|
||||
return _ok(creation_service.complete_wizard(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/from-sample', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_order_document_profile_from_sample(profile_id: int):
|
||||
"""用新样本和乐观锁整体更新 Profile 草稿,不允许浏览器提供结构指纹。"""
|
||||
return _ok(service.create_draft_from_sample(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_order_document_profile():
|
||||
@@ -157,8 +230,129 @@ def create_order_document_profile():
|
||||
@require_admin
|
||||
def update_order_document_profile(profile_id: int):
|
||||
"""按乐观锁整体更新模板 Profile 草稿。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(service.save_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
|
||||
data, actor_id=_actor_id(), profile_id=profile_id, **_write_context(data), enforce_lease=True,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/edit-lease', methods=['POST'])
|
||||
@require_admin
|
||||
def acquire_order_document_profile_edit_lease(profile_id: int):
|
||||
"""获取或确认接管草稿单写者租约;响应中的令牌只能由当前浏览器标签保存。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(lease_service.acquire_lease(
|
||||
profile_id, actor_id=_actor_id(), browser_session_id=data.get('browser_session_id'),
|
||||
operation_id=str(data.get('operation_id') or getattr(g, 'request_id', '') or ''),
|
||||
confirm_takeover=bool(data.get('confirm_takeover')),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/edit-lease/renew', methods=['POST'])
|
||||
@require_admin
|
||||
def renew_order_document_profile_edit_lease(profile_id: int):
|
||||
"""续租当前标签的编辑许可,身份或令牌失效统一返回租约冲突。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(lease_service.renew_lease(
|
||||
profile_id, actor_id=_actor_id(), browser_session_id=data.get('browser_session_id'),
|
||||
lease_token=data.get('lease_token'), operation_id=str(data.get('operation_id') or getattr(g, 'request_id', '') or ''),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/edit-lease/release', methods=['POST'])
|
||||
@require_admin
|
||||
def release_order_document_profile_edit_lease(profile_id: int):
|
||||
"""释放当前标签租约,避免离开编辑器后无谓阻塞其他管理员。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
lease_service.release_lease(
|
||||
profile_id, actor_id=_actor_id(), browser_session_id=data.get('browser_session_id'),
|
||||
lease_token=data.get('lease_token'), operation_id=str(data.get('operation_id') or getattr(g, 'request_id', '') or ''),
|
||||
)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/draft-revisions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_draft_revisions(profile_id: int):
|
||||
"""列出草稿 Revision 元数据;完整历史定义只能通过受控恢复操作使用。"""
|
||||
return _ok(revision_service.list_revisions(profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/draft-revisions/<int:revision_no>/restore', methods=['POST'])
|
||||
@require_admin
|
||||
def restore_order_document_profile_draft_revision(profile_id: int, revision_no: int):
|
||||
"""将历史 Revision 另存为当前草稿的新 Revision,绝不覆盖历史记录。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(revision_service.restore_revision(
|
||||
profile_id, revision_no, actor_id=_actor_id(), browser_session_id=str(data.get('browser_session_id') or ''),
|
||||
lease_token=str(data.get('lease_token') or ''), expected_lock_version=data.get('expected_lock_version'),
|
||||
operation_id=str(data.get('operation_id') or getattr(g, 'request_id', '') or ''),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile(profile_id: int):
|
||||
"""读取单个模板版本的安全详情,不返回 PDF、正文或盲测真值。"""
|
||||
payload = version_service.get_profile_detail(profile_id)
|
||||
_log_profile_view_event(payload['id'], event_type='version_detail_viewed', detail={'source': 'profile_id'})
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/diff', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_diff(profile_id: int):
|
||||
"""返回同模板版本的语义差异;未显式指定时默认对比上一版本。"""
|
||||
against_profile_id = request.args.get('against_profile_id')
|
||||
if against_profile_id in (None, ''):
|
||||
parsed_against_profile_id = None
|
||||
else:
|
||||
try:
|
||||
parsed_against_profile_id = int(against_profile_id)
|
||||
except ValueError as exc:
|
||||
raise service.ValidationError(
|
||||
'against_profile_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
) from exc
|
||||
payload = diff_service.get_profile_diff(profile_id, against_profile_id=parsed_against_profile_id)
|
||||
_log_profile_view_event(
|
||||
profile_id,
|
||||
event_type='version_diff_viewed',
|
||||
detail={
|
||||
'against_profile_id': parsed_against_profile_id,
|
||||
'comparison_mode': payload.get('comparison_mode'),
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/audit-events', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_audit_events(profile_id: int):
|
||||
"""按游标返回模板版本治理时间线,支持事件、操作者、日期和 request_id 过滤。"""
|
||||
return _ok(audit_service.list_profile_audit_events(
|
||||
profile_id=profile_id,
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
event_type=request.args.get('event_type'),
|
||||
actor_query=request.args.get('actor'),
|
||||
request_filter=request.args.get('request_id_filter'),
|
||||
created_from=request.args.get('created_from'),
|
||||
created_to=request.args.get('created_to'),
|
||||
before_id=request.args.get('before_id') and _query_int('before_id', 0, minimum=1),
|
||||
limit=_query_int('limit', 20, minimum=1, maximum=100),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/usages', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_usages(profile_id: int):
|
||||
"""按最新 RouteDecision 返回模板版本的实际使用记录,支持进入只读 Run 诊断。"""
|
||||
return _ok(usage_service.list_profile_usages(
|
||||
profile_id=profile_id,
|
||||
actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
before_id=request.args.get('before_id') and _query_int('before_id', 0, minimum=1),
|
||||
limit=_query_int('limit', 20, minimum=1, maximum=100),
|
||||
))
|
||||
|
||||
|
||||
@@ -193,14 +387,27 @@ def migrate_order_document_profile_schema(profile_id: int):
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish', methods=['POST'])
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish-checks', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_order_document_profile(profile_id: int):
|
||||
"""发布草稿并退役同模板旧版本。"""
|
||||
def create_order_document_profile_publish_check(profile_id: int):
|
||||
"""生成冻结草稿与验证运行的发布检查报告。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(service.publish(
|
||||
profile_id, actor_id=_actor_id(), expected_lock_version=data.get('expected_lock_version'),
|
||||
))
|
||||
return _ok(publish_check_service.create_report(profile_id, data=data, actor_id=_actor_id(), **_write_context(data)), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish-checks/<string:report_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_publish_check(profile_id: int, report_no: str):
|
||||
"""读取发布检查报告及失效、阻断和逐项警告确认状态。"""
|
||||
return _ok(publish_check_service.get_report(profile_id, report_no))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/publish-checks/<string:report_no>/confirm', methods=['POST'])
|
||||
@require_admin
|
||||
def confirm_order_document_profile_publish_check(profile_id: int, report_no: str):
|
||||
"""消费有效报告并原子发布,警告必须逐项确认。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(publish_check_service.consume_report(profile_id, report_no, data=data, actor_id=_actor_id(), **_write_context(data)))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/retire', methods=['POST'])
|
||||
@@ -297,6 +504,33 @@ def get_order_document_profile_preview_page(profile_id: int, page_no: int):
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/samples/<int:sample_binding_id>/preview-pages', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_frozen_sample_preview_pages(profile_id: int, sample_binding_id: int):
|
||||
"""按冻结样本绑定签发只读画布预览,不接受任意 document_id 读取。"""
|
||||
return _private_ok(preview_service.authorize_frozen_sample_preview_pages(
|
||||
profile_id, sample_binding_id=sample_binding_id, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/samples/<int:sample_binding_id>/preview-pages/<int:page_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_frozen_sample_preview_page(profile_id: int, sample_binding_id: int, page_no: int):
|
||||
"""消费冻结样本的一次性授权并返回单页 PNG。"""
|
||||
image = preview_service.render_frozen_sample_preview_page(
|
||||
profile_id=profile_id,
|
||||
sample_binding_id=sample_binding_id,
|
||||
token=str(request.args.get('preview_token') or ''),
|
||||
page_no=page_no,
|
||||
actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(image), mimetype='image/png', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/preview-pages/<int:page_no>/text-candidates', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_preview_page_text_candidates(profile_id: int, page_no: int):
|
||||
@@ -324,6 +558,44 @@ def suggest_order_document_profile_header(profile_id: int):
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/suggestion-decisions', methods=['POST'])
|
||||
@require_admin
|
||||
def decide_order_document_profile_suggestion(profile_id: int):
|
||||
"""冻结当前草稿对一个算法建议的接受、调整接受或拒绝决定。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(suggestion_service.decide(
|
||||
profile_id, data=data, actor_id=_actor_id(), operation_id=str(data.get('operation_id') or getattr(g, 'request_id', '') or ''),
|
||||
browser_session_id=data.get('browser_session_id'), lease_token=data.get('lease_token'),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/validation-runs', methods=['GET'])
|
||||
@require_admin
|
||||
def list_order_document_profile_validation_runs(profile_id: int):
|
||||
"""列出不可变验证运行摘要;旧 checksum 仅派生 stale 状态,不能修改历史记录。"""
|
||||
return _ok(validation_service.list_runs(profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/validation-runs/instant-check', methods=['POST'])
|
||||
@require_admin
|
||||
def run_order_document_profile_instant_check(profile_id: int):
|
||||
"""在持有租约的草稿上运行即时结构检查并冻结检查结果。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(validation_service.run_instant_check(
|
||||
profile_id, data=data, actor_id=_actor_id(), **_write_context(data),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/validation-runs/current-sample', methods=['POST'])
|
||||
@require_admin
|
||||
def run_order_document_profile_current_sample(profile_id: int):
|
||||
"""在标注/训练样本上试运行当前草稿;盲测样本不得通过本接口选择。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(validation_service.run_current_sample(
|
||||
profile_id, data=data, actor_id=_actor_id(), **_write_context(data),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/ocr-coordinate-evidence', methods=['POST'])
|
||||
@require_admin
|
||||
def generate_bound_order_document_profile_ocr_coordinate_evidence(profile_id: int):
|
||||
|
||||
@@ -8,6 +8,7 @@ backend/app/api/workspace/shipping_notice.py
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, g, jsonify, request, send_file
|
||||
|
||||
@@ -1038,6 +1039,237 @@ def workspace_list_shipping_order_extraction_documents(run_no: str):
|
||||
return _ok({'items': list_user_order_extraction_documents(user_id=user.id, run_no=run_no)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/review', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_run(run_no: str):
|
||||
"""读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_user_review_run
|
||||
|
||||
return _ok(serialize_review_run(get_user_review_run(user_id=user.id, run_no=run_no)))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_case(case_no: str):
|
||||
"""读取当前用户的一份 PDF 复核详情;Case 编号不能跨 owner 越权访问。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_service import get_user_review_case
|
||||
|
||||
return _ok(serialize_review_case(get_user_review_case(user_id=user.id, case_no=case_no)))
|
||||
|
||||
|
||||
def _review_draft_payload() -> dict:
|
||||
"""读取复核草稿 JSON 请求体;写接口统一要求对象,避免字段类型在路由层歧义。"""
|
||||
payload = request.get_json(silent=True)
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError('Review draft payload must be an object', code='VALIDATION.INVALID_PARAM')
|
||||
return payload
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/header-fields/<field_id>', methods=['PATCH'])
|
||||
def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: str):
|
||||
"""修改或恢复一个复核订单头字段;必须携带当前草稿版本。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
|
||||
payload = _review_draft_payload()
|
||||
result = patch_header_field(
|
||||
user_id=user.id, case_no=case_no, field_id=field_id, value=payload.get('value'),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
restore_machine=bool(payload.get('restore_machine')),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/fields/<field_id>', methods=['PATCH'])
|
||||
def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str, field_id: str):
|
||||
"""修改或恢复一个复核订单行字段;行只接受服务端返回的稳定 line_key。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_line_field
|
||||
|
||||
payload = _review_draft_payload()
|
||||
result = patch_line_field(
|
||||
user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'),
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
restore_machine=bool(payload.get('restore_machine')),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines', methods=['POST'])
|
||||
def workspace_add_shipping_order_review_line(case_no: str):
|
||||
"""新增一条空人工复核行;当前阶段仅保存草稿,不执行确认建单。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import add_line
|
||||
|
||||
result = add_line(user_id=user.id, case_no=case_no, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/copy', methods=['POST'])
|
||||
def workspace_copy_shipping_order_review_line(case_no: str, line_key: str):
|
||||
"""复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import copy_line
|
||||
|
||||
result = copy_line(user_id=user.id, case_no=case_no, line_key=line_key, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>', methods=['DELETE'])
|
||||
def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
|
||||
"""删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import delete_line
|
||||
|
||||
result = delete_line(user_id=user.id, case_no=case_no, line_key=line_key, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/validate', methods=['POST'])
|
||||
def workspace_validate_shipping_order_review_draft(case_no: str):
|
||||
"""显式重跑当前草稿校验,供自动保存后的用户可见状态刷新。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
|
||||
result = validate_draft(user_id=user.id, case_no=case_no, expected_draft_version=_review_draft_payload().get('expected_draft_version'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/confirm', methods=['POST'])
|
||||
def workspace_confirm_shipping_order_review_case(case_no: str):
|
||||
"""确认一份 PDF 草稿并独立建单;请求版本和幂等键不可省略。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
|
||||
payload = _review_draft_payload()
|
||||
result = confirm_review_case(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
idempotency_key=request.headers.get('Idempotency-Key') or payload.get('idempotency_key'),
|
||||
warning_acknowledgements=payload.get('warning_acknowledgements'),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/manual-draft', methods=['POST'])
|
||||
def workspace_create_shipping_order_review_manual_draft(case_no: str):
|
||||
"""启用无机器订单 PDF 的唯一人工草稿;不会创建第二个 Case、Candidate 或 Task。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_manual_draft
|
||||
|
||||
payload = _review_draft_payload()
|
||||
result = create_manual_draft(user_id=user.id, case_no=case_no, comment=payload.get('comment'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/disposition/non-order', methods=['POST'])
|
||||
def workspace_mark_shipping_order_review_non_order(case_no: str):
|
||||
"""把一份 PDF 独立标记为非订单;后端拒绝已确认和已替代的终态 Case。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_non_order
|
||||
|
||||
payload = _review_draft_payload()
|
||||
result = mark_non_order(user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/disposition/quality-issue', methods=['POST'])
|
||||
def workspace_mark_shipping_order_review_quality_issue(case_no: str):
|
||||
"""保留当前 PDF 和机器证据地标记质量异常,后续可单文件重识别或补件。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_quality_issue
|
||||
|
||||
payload = _review_draft_payload()
|
||||
result = mark_quality_issue(user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'))
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/reparse', methods=['POST'])
|
||||
def workspace_reparse_shipping_order_review_document(case_no: str):
|
||||
"""仅重识别当前 Case 的 PDF,永不借用整批 Run 重跑接口或覆盖原始文件。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_disposition_service import reparse_case_document
|
||||
|
||||
payload = _review_draft_payload()
|
||||
run, reused = reparse_case_document(
|
||||
user_id=user.id, case_no=case_no, reason=payload.get('reason'), comment=payload.get('comment'),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'run': serialize_order_extraction_run(run), 'reused': reused}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/replacement-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_order_review_replacement_intake(case_no: str):
|
||||
"""绑定已上传的新 PDF 为替代 Intake;原 PDF/Case 保留到替代识别成功后才被替代。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_upload_intake
|
||||
|
||||
payload = _review_draft_payload()
|
||||
intake = create_replacement_upload_intake(user_id=user.id, case_no=case_no, asset_no=payload.get('asset_no'))
|
||||
db.session.commit()
|
||||
return _ok(intake, status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/replacement-runs', methods=['POST'])
|
||||
def workspace_create_shipping_order_review_replacement_run(case_no: str):
|
||||
"""替代 Intake 解析完成后只为其唯一 PDF 创建新 Run;不覆盖旧文档证据。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_document_run
|
||||
|
||||
payload = _review_draft_payload()
|
||||
run, reused = create_replacement_document_run(
|
||||
user_id=user.id, case_no=case_no, intake_no=payload.get('intake_no'),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'run': serialize_order_extraction_run(run), 'reused': reused}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/evidence', methods=['GET'])
|
||||
def workspace_list_shipping_order_review_evidence(case_no: str):
|
||||
"""列出当前用户 PDF 的安全证据摘要;不泄露全文、对象存储位置或模型响应。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_evidence_service import list_case_evidence
|
||||
|
||||
return _ok(list_case_evidence(user_id=user.id, case_no=case_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/evidence/<evidence_id>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_evidence(case_no: str, evidence_id: str):
|
||||
"""读取当前用户的一条字段证据,用于问题导航;evidence_id 不可跨 Case 使用。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence
|
||||
|
||||
return _ok(get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/document-preview', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_document(case_no: str):
|
||||
"""应用代理当前用户的 PDF 预览流;禁止向浏览器下发 MinIO key 或直连地址。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_pdf_bytes
|
||||
|
||||
content, filename = get_case_pdf_bytes(user_id=user.id, case_no=case_no)
|
||||
return send_file(
|
||||
BytesIO(content), mimetype='application/pdf', as_attachment=False, download_name=filename,
|
||||
conditional=True,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
|
||||
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
|
||||
"""确认当前用户已加载终态订单识别卡片;仅用于会话待查看提醒,不改变业务结果。"""
|
||||
@@ -1225,25 +1457,24 @@ def workspace_refresh_shipping_notice_duplicate(intake_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/candidates/<candidate_no>', methods=['PATCH'])
|
||||
def workspace_update_shipping_notice_candidate(candidate_no: str):
|
||||
"""更新订单候选的选择状态或人工修订业务摘要。"""
|
||||
"""更新遗留批量建单候选的选择状态;人工编辑必须进入复核工作台。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('请求体必须为对象')
|
||||
if 'selected' in body and not isinstance(body.get('selected'), bool):
|
||||
raise ValidationError('selected 必须为布尔值')
|
||||
if 'business_summary' in body and not isinstance(body.get('business_summary'), dict):
|
||||
raise ValidationError('business_summary 必须为对象')
|
||||
if 'selected' not in body and 'business_summary' not in body:
|
||||
raise ValidationError('selected 或 business_summary 至少提供一项')
|
||||
if 'selected' not in body:
|
||||
raise ValidationError('selected 必须提供;订单字段请在人工复核工作台编辑')
|
||||
if set(body) != {'selected'}:
|
||||
raise ValidationError('订单候选不支持业务摘要覆盖,请在人工复核工作台编辑')
|
||||
from app.services.shipping_notice.candidate_service import update_candidate
|
||||
|
||||
return _ok(
|
||||
update_candidate(
|
||||
user_id=user.id,
|
||||
candidate_no=candidate_no,
|
||||
selected=body.get('selected') if 'selected' in body else None,
|
||||
business_summary=body.get('business_summary') if 'business_summary' in body else None,
|
||||
selected=body['selected'],
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -56,6 +56,9 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
finish_job(job.id, result={'status': 'stale', 'skipped': True}, owned_attempt=owned_attempt)
|
||||
return
|
||||
version, lease = claimed
|
||||
from app.services.shipping_notice.order_extraction_progress import record_layout_document_progress
|
||||
|
||||
record_layout_document_progress(document_id=int(version.document_id), event_code='layout_parsing_started')
|
||||
try:
|
||||
document = version.document
|
||||
asset = db.session.get(FileAsset, int(document.asset_id or 0))
|
||||
@@ -75,10 +78,14 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
'issues': ['shipping_document_layout_input_unsupported'],
|
||||
}
|
||||
if complete_layout_version(version.id, lease_token=lease, snapshot=snapshot):
|
||||
record_layout_document_progress(document_id=int(document.id), event_code='layout_parsing_completed')
|
||||
finish_job(
|
||||
job.id, result={'status': str(snapshot.get('status') or 'failed')},
|
||||
message='文档版面解析完成', owned_attempt=owned_attempt,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
|
||||
|
||||
resume_runs_waiting_for_layout(document_id=int(document.id))
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if ctx.logger is not None:
|
||||
@@ -87,4 +94,9 @@ def run_shipping_document_layout(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
fail_job(job.id, error=LAYOUT_JOB_ERROR, retryable=True, owned_attempt=owned_attempt)
|
||||
sync_layout_after_job_failure(job.id)
|
||||
# 仅当重试已耗尽时版本才会转 failed;此时需要唤醒等待中的 Run,
|
||||
# 让用户看到“附件解析失败”而不是永久停留在“正在解析”。
|
||||
from app.services.shipping_notice.order_extraction_run_service import resume_runs_waiting_for_layout
|
||||
|
||||
resume_runs_waiting_for_layout(document_id=int(version.document_id))
|
||||
raise
|
||||
@@ -33,7 +33,9 @@ from app.services.shipping_notice.order_extraction import submit_order_extractio
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
mark_order_extraction_persistence_started,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
materialize_order_extraction_run_inputs,
|
||||
schedule_order_extraction_layouts,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
@@ -506,13 +508,44 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
fail_job(job.id, error=f'run status is not executable: {run.status}', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'waiting_layout': True}, message='等待附件版面解析', owned_attempt=owned_attempt)
|
||||
return
|
||||
if layout_issues:
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='Order PDF layout prerequisites are incomplete',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'document_count': len(layout_issues)}, job_id=job.id, commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'layout_issues': layout_issues}, message='订单附件解析条件不完整', owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
# [STEP 3] 所有 PDF 布局就绪后重建快照,此时才冻结带坐标证据的执行计划。
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
if plan is None:
|
||||
raise RuntimeError('order extraction plan was not finalized')
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
selection = (run.input_snapshot_json or {}).get('attachment_selection') or {}
|
||||
max_runtime_seconds = max(0, int(selection.get('max_runtime_seconds') or 0))
|
||||
runtime_budget_stopped = False
|
||||
|
||||
@@ -56,6 +56,12 @@ from app.models.shipping_order_snapshot import (
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
)
|
||||
from app.models.shipping_order_review import (
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewDraft,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
)
|
||||
from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionDiagnosticAudit,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
@@ -69,6 +75,11 @@ from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_order_document_profile import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfileSuggestionDecision,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
ShippingOrderDocumentProfilePublishCheckReport,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.models.shipping_document_profile_quality import (
|
||||
@@ -171,6 +182,10 @@ __all__ = [
|
||||
'ShippingOrderSnapshot',
|
||||
'ShippingOrderSnapshotLine',
|
||||
'ShippingOrderReviewEvent',
|
||||
'ShippingOrderReviewCase',
|
||||
'ShippingOrderReviewDraft',
|
||||
'ShippingOrderReviewCaseEvent',
|
||||
'ShippingOrderReviewConfirmedRevision',
|
||||
'ShippingOrderExtractionRun',
|
||||
'ShippingOrderExtractionRunIntake',
|
||||
'ShippingOrderExtractionPlan',
|
||||
|
||||
@@ -81,6 +81,7 @@ class ShippingOrderDocumentProfileSample(Base):
|
||||
CheckConstraint("sample_role IN ('annotation', 'training', 'blind_test')", name='ck_shipping_order_document_profile_samples_role'),
|
||||
UniqueConstraint('profile_id', 'document_id', 'table_id', 'sample_role', name='uq_shipping_order_document_profile_samples_source_role'),
|
||||
Index('ix_shipping_order_document_profile_samples_document', 'document_id'),
|
||||
Index('ix_shipping_order_document_profile_samples_layout_version', 'layout_version_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -88,6 +89,19 @@ class ShippingOrderDocumentProfileSample(Base):
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
|
||||
table_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
sample_role: Mapped[str] = mapped_column(String(16), nullable=False, default='annotation', server_default='annotation')
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_document_layout_versions.id'), nullable=True,
|
||||
)
|
||||
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
layout_contract_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
parser_name: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
evidence_frozen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
source_filename_snapshot: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
page_count_snapshot: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
table_identity_snapshot: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
@@ -98,6 +112,8 @@ class ShippingOrderDocumentProfileAudit(Base):
|
||||
__tablename__ = 'shipping_order_document_profile_audits'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_order_document_profile_audits_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_audits_profile_request', 'profile_id', 'request_id', 'id'),
|
||||
Index('ix_shipping_order_document_profile_audits_operation', 'operation_id', 'id'),
|
||||
Index('ix_shipping_order_document_profile_audits_document', 'document_id'),
|
||||
)
|
||||
|
||||
@@ -106,5 +122,145 @@ class ShippingOrderDocumentProfileAudit(Base):
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_documents.id', ondelete='SET NULL'), nullable=True)
|
||||
event_type: Mapped[str] = mapped_column(String(48), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
browser_session_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
revision_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfileDraftRevision(Base):
|
||||
"""草稿每次有效保存的不可变定义快照;同 checksum 重试只能复用同一修订。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_draft_revisions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('profile_id', 'revision_no', name='uq_shipping_order_document_profile_draft_revisions_number'),
|
||||
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_draft_revisions_operation'),
|
||||
Index('ix_shipping_order_document_profile_draft_revisions_operation', 'operation_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
base_lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
result_lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
change_source: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
browser_session_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
definition_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfileEditLease(Base):
|
||||
"""Profile 单写者编辑租约;令牌仅保存 SHA-256 哈希,不能从数据库还原。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_edit_leases'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('profile_id', name='uq_shipping_order_document_profile_edit_leases_profile'),
|
||||
Index('ix_shipping_order_document_profile_edit_leases_expires', 'expires_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
lease_token_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
browser_session_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
last_renewed_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
|
||||
taken_over_from_actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfileSuggestionDecision(Base):
|
||||
"""冻结算法建议及管理员决定;建议永不直接覆盖已保存或人工画布配置。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_suggestion_decisions'
|
||||
__table_args__ = (
|
||||
CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_shipping_order_document_profile_suggestion_decisions_decision'),
|
||||
UniqueConstraint('profile_id', 'suggestion_id', name='uq_shipping_order_document_profile_suggestion_decisions_suggestion'),
|
||||
Index('ix_shipping_order_document_profile_suggestion_decisions_profile_revision', 'profile_id', 'revision_no'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_document_layout_versions.id'), nullable=True)
|
||||
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
algorithm_version: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
suggestion_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
suggestion_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
decision: Mapped[str] = mapped_column(String(24), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
detail_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfileValidationRun(Base):
|
||||
"""不可变验证运行;输出绑定精确草稿 checksum,草稿变化后只能标记 stale 而不重写历史。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_validation_runs'
|
||||
__table_args__ = (
|
||||
CheckConstraint("run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', 'schema_compatibility')", name='ck_shipping_order_document_profile_validation_runs_type'),
|
||||
CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_validation_runs_checksum', 'profile_id', 'definition_checksum'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
schema_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
sample_binding_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_samples.id', ondelete='SET NULL'), nullable=True)
|
||||
layout_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_document_layout_versions.id'), nullable=True)
|
||||
layout_payload_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
parser_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
run_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
result_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
|
||||
class ShippingOrderDocumentProfilePublishCheckReport(Base):
|
||||
"""不可变发布检查报告;只能由与冻结草稿完全一致的一次原子发布消费。"""
|
||||
|
||||
__tablename__ = 'shipping_order_document_profile_publish_check_reports'
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_shipping_order_document_profile_publish_check_reports_status'),
|
||||
UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_publish_check_reports_operation'),
|
||||
Index('ix_shipping_order_document_profile_publish_check_reports_profile_created', 'profile_id', 'created_at'),
|
||||
Index('ix_shipping_order_document_profile_publish_check_reports_report_no', 'report_no', unique=True),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
report_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='CASCADE'), nullable=False)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
definition_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
validation_run_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profile_validation_runs.id', ondelete='SET NULL'), nullable=True)
|
||||
base_published_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id', ondelete='SET NULL'), nullable=True)
|
||||
semantic_diff_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
blocking_items_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
warning_items_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
confirmed_warning_keys_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='valid')
|
||||
expires_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
@@ -127,6 +127,10 @@ class ShippingOrderExtractionRun(Base):
|
||||
route_decisions: Mapped[list['ShippingOrderExtractionRouteDecision']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRouteDecision.id',
|
||||
)
|
||||
review_cases: Mapped[list['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', back_populates='run', cascade='all, delete-orphan',
|
||||
order_by='ShippingOrderReviewCase.id',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRunIntake(Base):
|
||||
@@ -251,6 +255,9 @@ class ShippingOrderExtractionUnit(Base):
|
||||
route_decisions: Mapped[list['ShippingOrderExtractionRouteDecision']] = relationship(
|
||||
back_populates='unit', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRouteDecision.id',
|
||||
)
|
||||
review_case: Mapped[Optional['ShippingOrderReviewCase']] = relationship(
|
||||
'ShippingOrderReviewCase', back_populates='unit', uselist=False,
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRouteDecision(Base):
|
||||
@@ -269,6 +276,11 @@ class ShippingOrderExtractionRouteDecision(Base):
|
||||
),
|
||||
Index('ix_shipping_order_extraction_route_decisions_run_unit', 'run_id', 'unit_id', 'id'),
|
||||
Index('ix_shipping_order_extraction_route_decisions_unit_created', 'unit_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_route_decisions_profile_id', 'selected_profile_id', 'id'),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_route_decisions_profile_snapshot',
|
||||
'selected_profile_code', 'selected_profile_version', 'selected_profile_checksum', 'id',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""
|
||||
建单前订单人工复核领域模型。
|
||||
|
||||
依赖:订单抽取 Run/Unit、候选 Candidate、用户和后续 ShippingTask。
|
||||
逻辑:Case 以 PDF Unit 为唯一复核对象,Draft 保存独立人工版本;机器 Candidate
|
||||
始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task。
|
||||
"""
|
||||
|
||||
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 ShippingOrderReviewCase(Base):
|
||||
"""一份 PDF 的建单前复核生命周期;终态 Case 不允许后续草稿写入。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_cases'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('case_no', name='uq_shipping_order_review_cases_no'),
|
||||
UniqueConstraint('unit_id', name='uq_shipping_order_review_cases_unit'),
|
||||
UniqueConstraint('confirmed_task_id', name='uq_shipping_order_review_cases_confirmed_task'),
|
||||
CheckConstraint(
|
||||
"status IN ('unreviewed', 'draft', 'ready', 'confirming', 'confirmed', "
|
||||
"'non_order', 'quality_issue', 'reparse_pending', 'superseded')",
|
||||
name='ck_shipping_order_review_cases_status',
|
||||
),
|
||||
Index('ix_shipping_order_review_cases_run_status', 'run_id', 'status'),
|
||||
Index('ix_shipping_order_review_cases_owner_updated', 'owner_user_id', 'updated_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
case_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
unit_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=False)
|
||||
candidate_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_candidates.id'), nullable=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unreviewed', server_default='unreviewed')
|
||||
disposition: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
current_draft_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'),
|
||||
nullable=True,
|
||||
)
|
||||
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.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)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship('ShippingOrderExtractionRun', back_populates='review_cases')
|
||||
unit: Mapped['ShippingOrderExtractionUnit'] = relationship('ShippingOrderExtractionUnit', back_populates='review_case')
|
||||
current_draft: Mapped[Optional['ShippingOrderReviewDraft']] = relationship(
|
||||
'ShippingOrderReviewDraft', foreign_keys=[current_draft_id], post_update=True,
|
||||
)
|
||||
drafts: Mapped[list['ShippingOrderReviewDraft']] = relationship(
|
||||
'ShippingOrderReviewDraft', back_populates='case', foreign_keys='ShippingOrderReviewDraft.case_id',
|
||||
cascade='all, delete-orphan', order_by='ShippingOrderReviewDraft.draft_version',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderReviewDraft(Base):
|
||||
"""当前人工草稿;阶段 1 只初始化和投影,阶段 3 才允许写入。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_drafts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('case_id', 'draft_version', name='uq_shipping_order_review_drafts_case_version'),
|
||||
CheckConstraint('draft_version >= 1', name='ck_shipping_order_review_drafts_version'),
|
||||
Index('ix_shipping_order_review_drafts_case_updated', 'case_id', 'updated_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
case_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
draft_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
issue_summary_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
validation_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
change_reason_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.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)
|
||||
|
||||
case: Mapped['ShippingOrderReviewCase'] = relationship(
|
||||
'ShippingOrderReviewCase', back_populates='drafts', foreign_keys=[case_id],
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderReviewCaseEvent(Base):
|
||||
"""复核域追加审计事件;阶段 3 起记录每项草稿变更,阶段 1 记录初始化事实。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_case_events'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_order_review_case_events_case_occurred', 'case_id', 'occurred_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
case_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False)
|
||||
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
draft_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
actor_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
operation_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
occurred_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderReviewConfirmedRevision(Base):
|
||||
"""一次不可变建单确认快照;每个 PDF Case 最多确认一次。"""
|
||||
|
||||
__tablename__ = 'shipping_order_review_confirmed_revisions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('case_id', name='uq_shipping_order_review_confirmed_revisions_case'),
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_order_review_confirmed_revisions_idempotency'),
|
||||
Index('ix_shipping_order_review_confirmed_revisions_task', 'task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
case_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
draft_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
validation_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
warning_acknowledgements_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
confirmed_by_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
confirmed_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/candidate_service.py
|
||||
|
||||
用途:提供订单候选的用户态查询、修订、选择与重复决策能力。
|
||||
用途:提供订单候选的用户态查询、选择与重复决策能力。
|
||||
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态。
|
||||
"""
|
||||
@@ -15,7 +15,6 @@ from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import FileAsset, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, User
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
|
||||
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
|
||||
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
|
||||
from app.services.shipping_notice.duplicate_detection import apply_duplicate_result_to_candidate, detect_duplicates_for_candidate
|
||||
from app.services.shipping_notice.intake_service import can_force_create_shipping_duplicate
|
||||
@@ -86,62 +85,20 @@ def _refresh_candidate(candidate: ShippingNoticeCandidate, intake: ShippingNotic
|
||||
return result
|
||||
|
||||
|
||||
def _append_manual_review_history(
|
||||
structured: dict[str, Any], *, user_id: int, before_summary: dict[str, Any],
|
||||
before_conflicts: list[Any], before_status: str, after_summary: dict[str, Any],
|
||||
) -> None:
|
||||
"""追加不可变人工修订快照,保留规则/LLM 结果被人工更正前的审核依据。"""
|
||||
history = list(structured.get('manual_review_history') or [])
|
||||
history.append({
|
||||
'action': 'business_summary_edited',
|
||||
'actor_user_id': int(user_id),
|
||||
'edited_at': datetime.utcnow().isoformat(),
|
||||
'before_summary': before_summary,
|
||||
'before_conflicts': before_conflicts,
|
||||
'before_validation_status': before_status,
|
||||
'after_summary': after_summary,
|
||||
})
|
||||
structured['manual_review_history'] = history
|
||||
|
||||
|
||||
def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None = None, business_summary: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
def update_candidate(*, user_id: int, candidate_no: str, selected: bool) -> dict[str, Any]:
|
||||
"""
|
||||
更新候选选择状态或人工修订后的业务摘要。
|
||||
更新遗留批量建单流程的候选选择状态。
|
||||
|
||||
核心逻辑:已消费候选禁止修改;人工摘要通过统一校验后保留修订前快照,
|
||||
再清除已人工处理的冲突、置 ready 并重算双指纹与判重。
|
||||
订单抽取的建单前人工编辑只允许通过 Review Draft API 完成,不能覆盖
|
||||
机器 Candidate 的业务摘要;本接口仅保留给尚未迁移的历史批量流程。
|
||||
"""
|
||||
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
|
||||
if candidate.consumed_task_id is not None or intake.parse_status == 'consumed':
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
if selected is not None:
|
||||
if not isinstance(selected, bool):
|
||||
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值')
|
||||
# Selection is retained for legacy batch APIs but may not bypass acceptance.
|
||||
candidate.selected = selected if candidate.candidate_status == 'accepted' else False
|
||||
if business_summary is not None:
|
||||
if not isinstance(business_summary, dict):
|
||||
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象')
|
||||
normalized_summary = normalize_candidate_business_summary(business_summary)
|
||||
structured = dict(candidate.structured_result_json or {})
|
||||
before_summary = dict(structured.get('business_summary') or {})
|
||||
before_conflicts = list(candidate.conflicts_json or [])
|
||||
before_status = str(candidate.validation_status or '')
|
||||
_append_manual_review_history(
|
||||
structured,
|
||||
user_id=user_id,
|
||||
before_summary=before_summary,
|
||||
before_conflicts=before_conflicts,
|
||||
before_status=before_status,
|
||||
after_summary=normalized_summary,
|
||||
)
|
||||
structured['business_summary'] = normalized_summary
|
||||
structured['manual_edited'] = True
|
||||
candidate.structured_result_json = structured
|
||||
candidate.po_number = str(normalized_summary.get('po_number') or '').strip() or None
|
||||
candidate.conflicts_json = []
|
||||
candidate.validation_status = 'ready'
|
||||
_refresh_candidate(candidate, intake, document)
|
||||
if not isinstance(selected, bool):
|
||||
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值')
|
||||
# Selection is retained for legacy batch APIs but may not bypass acceptance.
|
||||
candidate.selected = selected if candidate.candidate_status == 'accepted' else False
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _serialize_candidate_brief(candidate)
|
||||
|
||||
@@ -775,11 +775,9 @@ def persist_documents_and_candidates(
|
||||
strip_attachment_payloads(meta)
|
||||
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
layout_versions = schedule_document_layouts(
|
||||
documents, created_by_id=int(intake.user_id) if intake.user_id else None,
|
||||
)
|
||||
# 完整版面解析由用户发送后统一编排。上传阶段只保存文档,避免未发送附件
|
||||
# 提前占用 MinerU,并确保订单 Run 能以同一时点的布局结果冻结输入。
|
||||
layout_versions = []
|
||||
return {
|
||||
'document_count': len(documents),
|
||||
'candidate_count': len(candidates),
|
||||
|
||||
@@ -576,6 +576,20 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
):
|
||||
raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY')
|
||||
suite.status = 'approved'
|
||||
# A coordinate-template approval is also its publish-quality credential.
|
||||
# Validate the remaining publish prerequisites before committing approval so
|
||||
# administrators never see an approved suite that publication must reject.
|
||||
if (
|
||||
profile.status == 'draft'
|
||||
and (profile.definition_json or {}).get('contract_version') == 'order_coordinate_profile.v2'
|
||||
):
|
||||
try:
|
||||
assert_profile_publishable(profile)
|
||||
except Exception:
|
||||
# The temporary approved state exists only for evaluating the same
|
||||
# publish gate; never leave a failed approval pending in this session.
|
||||
db.session.rollback()
|
||||
raise
|
||||
suite.approved_by_id = actor_id
|
||||
suite.approved_at = datetime.utcnow()
|
||||
qualification = ensure_manual_confirmation_qualification(profile)
|
||||
@@ -753,7 +767,7 @@ def suspend_auto_freeze_qualification(*, profile_id: int, actor_id: int, reason:
|
||||
|
||||
|
||||
def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""执行坐标模板发布门禁:训练样本、独立盲测、多明细与跨页覆盖均不可绕过。"""
|
||||
"""执行坐标模板发布门禁:训练样本、独立盲测与跨页声明覆盖均不可绕过。"""
|
||||
from app.models import ShippingOrderDocumentProfileSample
|
||||
|
||||
draft_checksum = _quality_checksum(profile)
|
||||
@@ -776,8 +790,6 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
|
||||
}
|
||||
if model_documents & {item.document_id for item in samples}:
|
||||
raise ConflictError('Blind test samples must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST')
|
||||
if not any(len(item.expected_rows_json or []) > 1 for item in samples):
|
||||
raise ConflictError('A multi-line blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_MULTILINE')
|
||||
if _requires_cross_page_sample(profile):
|
||||
has_cross_page = False
|
||||
for sample in samples:
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_audit_service.py
|
||||
|
||||
用途:提供订单模板版本中心的审计时间线查询与只读访问留痕。
|
||||
依赖:ShippingOrderDocumentProfile、ShippingOrderDocumentProfileAudit、User ORM 与 profile service 审计助手。
|
||||
逻辑:审计列表使用游标分页避免新增事件导致翻页重复;读接口返回安全摘要,不暴露 PDF、正文或盲测真值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, time
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import String, cast, or_
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileAudit, User
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取当前模板版本;不存在时复用版本中心统一 not-found 契约。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _parse_datetime(raw: str | None, *, is_end: bool) -> datetime | None:
|
||||
"""解析日期或 ISO 时间字符串;纯日期默认扩展到当天起止。"""
|
||||
value = str(raw or '').strip()
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
'audit datetime filter is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
) from exc
|
||||
if 'T' not in value and ' ' not in value:
|
||||
return datetime.combine(parsed.date(), time.max if is_end else time.min)
|
||||
return parsed
|
||||
|
||||
|
||||
def _actor_payload(row: ShippingOrderDocumentProfileAudit, actor: User | None) -> dict[str, Any]:
|
||||
"""返回操作者展示摘要;用户缺失时降级为 unknown actor。"""
|
||||
username = str(getattr(actor, 'username', '') or '').strip() or None
|
||||
return {
|
||||
'id': int(row.actor_id) if row.actor_id else None,
|
||||
'username': username,
|
||||
'display_name': username or 'unknown_actor',
|
||||
}
|
||||
|
||||
|
||||
def _event_payload(row: ShippingOrderDocumentProfileAudit, actor: User | None) -> dict[str, Any]:
|
||||
"""序列化单条审计事件;detail_json 已由写侧保证为非敏感摘要。"""
|
||||
return {
|
||||
'id': int(row.id),
|
||||
'event_type': row.event_type,
|
||||
'request_id': str(row.request_id or '') or None,
|
||||
'document_id': int(row.document_id) if row.document_id else None,
|
||||
'actor': _actor_payload(row, actor),
|
||||
'detail': dict(row.detail_json or {}),
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _write_view_audit_safely(
|
||||
*,
|
||||
profile_id: int,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
event_type: str,
|
||||
detail: dict[str, Any],
|
||||
) -> None:
|
||||
"""为只读页面访问追加留痕;提交失败不阻断读取接口。"""
|
||||
try:
|
||||
profile_service._audit(
|
||||
profile_id=int(profile_id),
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail=detail,
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('order document profile audit view logging failed profile_id=%s event_type=%s', profile_id, event_type)
|
||||
|
||||
|
||||
def list_profile_audit_events(
|
||||
*,
|
||||
profile_id: int,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
event_type: str | None = None,
|
||||
actor_query: str | None = None,
|
||||
request_filter: str | None = None,
|
||||
created_from: str | None = None,
|
||||
created_to: str | None = None,
|
||||
before_id: int | None = None,
|
||||
limit: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
返回模板版本治理时间线,支持事件类型、操作者、日期和 request_id 过滤。
|
||||
|
||||
Args:
|
||||
profile_id: 模板版本主键。
|
||||
actor_id: 当前管理员主键,仅用于记录访问留痕。
|
||||
request_id: 当前 HTTP request_id,仅写入 view audit。
|
||||
event_type: 可选事件类型精确过滤。
|
||||
actor_query: 可选操作者过滤,支持 username 模糊匹配或 actor_id 精确匹配。
|
||||
request_filter: 可选请求链路过滤。
|
||||
created_from: ISO 日期/时间起点。
|
||||
created_to: ISO 日期/时间终点。
|
||||
before_id: 向后翻页游标;仅返回更早事件。
|
||||
limit: 单次页大小,范围由路由层约束。
|
||||
Returns:
|
||||
profile 摘要、过滤条件、倒序事件列表与下一页游标。
|
||||
"""
|
||||
profile = _profile(profile_id)
|
||||
safe_event_type = str(event_type or '').strip() or None
|
||||
safe_actor_query = str(actor_query or '').strip() or None
|
||||
safe_request_filter = str(request_filter or '').strip() or None
|
||||
created_from_dt = _parse_datetime(created_from, is_end=False)
|
||||
created_to_dt = _parse_datetime(created_to, is_end=True)
|
||||
|
||||
query = (
|
||||
db.session.query(ShippingOrderDocumentProfileAudit, User)
|
||||
.outerjoin(User, User.id == ShippingOrderDocumentProfileAudit.actor_id)
|
||||
.filter(ShippingOrderDocumentProfileAudit.profile_id == int(profile.id))
|
||||
)
|
||||
if safe_event_type:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.event_type == safe_event_type)
|
||||
if safe_request_filter:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.request_id == safe_request_filter)
|
||||
if created_from_dt is not None:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.created_at >= created_from_dt)
|
||||
if created_to_dt is not None:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.created_at <= created_to_dt)
|
||||
if before_id is not None:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.id < int(before_id))
|
||||
if safe_actor_query:
|
||||
if safe_actor_query.isdigit():
|
||||
query = query.filter(
|
||||
or_(
|
||||
ShippingOrderDocumentProfileAudit.actor_id == int(safe_actor_query),
|
||||
User.username.ilike(f'%{safe_actor_query}%'),
|
||||
),
|
||||
)
|
||||
else:
|
||||
query = query.filter(
|
||||
or_(
|
||||
User.username.ilike(f'%{safe_actor_query}%'),
|
||||
cast(ShippingOrderDocumentProfileAudit.actor_id, String).ilike(f'%{safe_actor_query}%'),
|
||||
),
|
||||
)
|
||||
|
||||
rows = (
|
||||
query
|
||||
.order_by(ShippingOrderDocumentProfileAudit.id.desc())
|
||||
.limit(int(limit) + 1)
|
||||
.all()
|
||||
)
|
||||
has_more = len(rows) > int(limit)
|
||||
visible_rows = rows[:int(limit)]
|
||||
payload = {
|
||||
'profile': {
|
||||
'id': int(profile.id),
|
||||
'profile_code': profile.profile_code,
|
||||
'version': int(profile.version),
|
||||
'status': profile.status,
|
||||
},
|
||||
'filters': {
|
||||
'event_type': safe_event_type,
|
||||
'actor': safe_actor_query,
|
||||
'request_id': safe_request_filter,
|
||||
'created_from': created_from_dt.isoformat() if created_from_dt else None,
|
||||
'created_to': created_to_dt.isoformat() if created_to_dt else None,
|
||||
},
|
||||
'items': [_event_payload(audit, actor) for audit, actor in visible_rows],
|
||||
'page': {
|
||||
'limit': int(limit),
|
||||
'before_id': int(before_id) if before_id is not None else None,
|
||||
'next_before_id': int(visible_rows[-1][0].id) if has_more and visible_rows else None,
|
||||
'has_more': has_more,
|
||||
},
|
||||
}
|
||||
_write_view_audit_safely(
|
||||
profile_id=int(profile.id),
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
event_type='version_audit_viewed',
|
||||
detail={
|
||||
'filters': payload['filters'],
|
||||
'result_count': len(payload['items']),
|
||||
},
|
||||
)
|
||||
return payload
|
||||
@@ -0,0 +1,130 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_creation_service.py
|
||||
|
||||
用途:完成订单模板三步创建向导的最终原子提交。
|
||||
依赖:Profile 保存、样本布局、Revision、EditLease 与 Profile 审计模型。
|
||||
逻辑:前两步只在浏览器保存临时状态;本服务在最后一步一次创建草稿、样本绑定、Revision 审计和编辑租约,任一失败整体回滚。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingNoticeDocument, ShippingOrderDocumentProfileEditLease, ShippingOrderDocumentProfileSample
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
def _browser_session_id(value: Any) -> str:
|
||||
"""验证向导完成者的浏览器标签身份;完成后立即签发的 Lease 依赖该值。"""
|
||||
session_id = str(value or '').strip()
|
||||
if not session_id or len(session_id) > 128:
|
||||
raise ValidationError('browser_session_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
return session_id
|
||||
|
||||
|
||||
def _initial_definition(main_table_id: str) -> dict[str, Any]:
|
||||
"""生成未标注但合法的坐标草稿起点;编辑器后续才添加锚点、表头和行布局。"""
|
||||
region_suffix = re.sub(r'[^a-z0-9_]+', '_', main_table_id.lower()).strip('_') or 'table'
|
||||
return {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {
|
||||
'document_type': 'purchase_order', 'page_pattern': 'one_or_more',
|
||||
'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0,
|
||||
},
|
||||
'table_regions': [{
|
||||
'region_id': f'main_{region_suffix}', 'page_scope': 'first_page',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
# 空字段布局只占位已确认的主表格,避免向导阶段伪造字段绑定或识别规则。
|
||||
'header_layouts': [], 'line_layouts': [{
|
||||
'layout_id': f'main_{region_suffix}_row', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [], 'continuation_conditions': [],
|
||||
'required_fields': [], 'allowed_empty_fields': [],
|
||||
}],
|
||||
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'termination_rules': [], 'exclusion_regions': [],
|
||||
}],
|
||||
'order_field_layouts': [], 'draft_unbound_order_field_layouts': [],
|
||||
}
|
||||
|
||||
|
||||
def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
以单事务完成创建向导。
|
||||
|
||||
Args:
|
||||
data: 模板身份、已解析样本文档、主表格、Schema 和浏览器会话身份。
|
||||
actor_id: 当前管理员主键。
|
||||
|
||||
Returns:
|
||||
新草稿 DTO 与仅返回给当前标签的编辑租约令牌。
|
||||
"""
|
||||
try:
|
||||
document_id = int(data.get('document_id'))
|
||||
schema_version_id = int(data.get('schema_version_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('wizard identity is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') from exc
|
||||
table_id = str(data.get('main_table_id') or '').strip()
|
||||
if not table_id:
|
||||
raise ValidationError('main_table_id is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
session_id = _browser_session_id(data.get('browser_session_id'))
|
||||
operation_id = str(data.get('operation_id') or secrets.token_hex(16)).strip()
|
||||
document = db.session.get(ShippingNoticeDocument, document_id)
|
||||
if document is None:
|
||||
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
layout = profile_service._document_layout(document)
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
if not any(str(item.get('table_id') or '') == table_id for item in tables):
|
||||
raise ValidationError('Selected main table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
|
||||
try:
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
'schema_version_id': schema_version_id,
|
||||
'definition': _initial_definition(table_id),
|
||||
'change_note': 'Created from template wizard',
|
||||
},
|
||||
actor_id=actor_id, browser_session_id=session_id, operation_id=operation_id,
|
||||
change_source='wizard_created', commit=False,
|
||||
)
|
||||
profile_id = int(saved['id'])
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile_id, document_id=document.id, table_id=table_id,
|
||||
sample_role='annotation', created_by_id=actor_id,
|
||||
))
|
||||
revision_no = int(saved['draft_revision']['revision_no'])
|
||||
profile_service._audit(
|
||||
profile_id=profile_id, document_id=document.id, event_type='wizard_created', actor_id=actor_id,
|
||||
operation_id=operation_id, browser_session_id=session_id, revision_no=revision_no,
|
||||
detail={'main_table_id': table_id, 'schema_version_id': schema_version_id},
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
token = secrets.token_urlsafe(32)
|
||||
db.session.add(ShippingOrderDocumentProfileEditLease(
|
||||
profile_id=profile_id, lease_token_hash=hashlib.sha256(token.encode('utf-8')).hexdigest(),
|
||||
actor_id=actor_id, browser_session_id=session_id, expires_at=now + timedelta(seconds=300),
|
||||
last_renewed_at=now, lock_version=int(saved['lock_version']),
|
||||
))
|
||||
profile_service._audit(
|
||||
profile_id=profile_id, event_type='edit_lease_acquired', actor_id=actor_id,
|
||||
operation_id=operation_id, browser_session_id=session_id, revision_no=revision_no,
|
||||
detail={'lock_version': int(saved['lock_version']), 'source': 'wizard'},
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
saved['edit_lease'] = {
|
||||
'profile_id': profile_id, 'state': 'active', 'actor_id': actor_id,
|
||||
'browser_session_id': session_id, 'expires_at': (now + timedelta(seconds=300)).isoformat(),
|
||||
'last_renewed_at': now.isoformat(), 'lock_version': int(saved['lock_version']), 'lease_token': token,
|
||||
}
|
||||
return saved
|
||||
@@ -0,0 +1,766 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_diff.py
|
||||
|
||||
用途:计算订单模板版本之间的服务端语义差异,供版本中心详情页直接展示。
|
||||
依赖:ShippingOrderDocumentProfile、version_service 的安全详情 DTO。
|
||||
逻辑:先按 profile_code 约束比较范围,再用稳定身份配对 layout/field/sample,并对坐标使用统一容差避免浮点噪声。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice import order_document_profile_version_service as version_service
|
||||
|
||||
_REGION_KEYS = ('x0', 'y0', 'x1', 'y1')
|
||||
_REGION_TOLERANCE = 0.001
|
||||
_ENTITY_ORDER = {
|
||||
'profile_meta': 0,
|
||||
'document_match': 10,
|
||||
'table_region': 20,
|
||||
'header_layout': 30,
|
||||
'header_field_region': 40,
|
||||
'line_layout': 50,
|
||||
'line_field_region': 60,
|
||||
'termination_rule': 70,
|
||||
'exclusion_region': 80,
|
||||
'order_field_layout': 90,
|
||||
'sample_binding': 100,
|
||||
}
|
||||
|
||||
|
||||
def _copy_json(value: Any) -> Any:
|
||||
"""复制 JSON 兼容结构,避免后续修改污染 diff 快照。"""
|
||||
return json.loads(json.dumps(value, ensure_ascii=True))
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取模板版本实体,不存在时返回统一 404。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _profile_ref(detail: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""提取版本比较头部所需的最小安全摘要。"""
|
||||
if detail is None:
|
||||
return None
|
||||
return {
|
||||
'id': int(detail['id']),
|
||||
'profile_code': detail['profile_code'],
|
||||
'display_name': detail['display_name'],
|
||||
'version': int(detail['version']),
|
||||
'status': detail['status'],
|
||||
'schema_version_id': int(detail['schema_version_id']),
|
||||
'schema_version': detail.get('schema_version'),
|
||||
'schema_checksum': detail.get('schema_checksum'),
|
||||
'checksum': detail.get('checksum'),
|
||||
}
|
||||
|
||||
|
||||
def _safe_detail(profile: ShippingOrderDocumentProfile | None) -> dict[str, Any] | None:
|
||||
"""统一走版本中心详情 DTO,确保 diff 不绕开既有安全边界。"""
|
||||
if profile is None:
|
||||
return None
|
||||
return version_service.get_profile_detail(int(profile.id))
|
||||
|
||||
|
||||
def _change(key: str, kind: str, before: Any, after: Any, **extra: Any) -> dict[str, Any]:
|
||||
"""构造前端可直接消费的结构化变更项。"""
|
||||
payload = {
|
||||
'key': key,
|
||||
'kind': kind,
|
||||
'before': _copy_json(before) if before is not None else None,
|
||||
'after': _copy_json(after) if after is not None else None,
|
||||
}
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def _set_change(key: str, before: Any, after: Any) -> dict[str, Any] | None:
|
||||
"""比较无序集合并保留顺序变化信息。"""
|
||||
before_items = list(before or [])
|
||||
after_items = list(after or [])
|
||||
before_set = set(before_items)
|
||||
after_set = set(after_items)
|
||||
if before_set == after_set and before_items == after_items:
|
||||
return None
|
||||
return _change(
|
||||
key,
|
||||
'set',
|
||||
before_items,
|
||||
after_items,
|
||||
added=sorted(after_set - before_set),
|
||||
removed=sorted(before_set - after_set),
|
||||
order_changed=(before_set == after_set and before_items != after_items),
|
||||
)
|
||||
|
||||
|
||||
def _region_equal(before: Any, after: Any) -> bool:
|
||||
"""按统一浮点容差比较矩形区域。"""
|
||||
if before is None and after is None:
|
||||
return True
|
||||
if not isinstance(before, dict) or not isinstance(after, dict):
|
||||
return before == after
|
||||
for key in _REGION_KEYS:
|
||||
if abs(float(before.get(key, 0) or 0) - float(after.get(key, 0) or 0)) >= _REGION_TOLERANCE:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _region_change(key: str, before: Any, after: Any) -> dict[str, Any] | None:
|
||||
"""只在区域真实变化时返回差异,过滤浮点序列化噪声。"""
|
||||
if _region_equal(before, after):
|
||||
return None
|
||||
return _change(key, 'region', before, after, tolerance=_REGION_TOLERANCE)
|
||||
|
||||
|
||||
def _scalar_changes(before: dict[str, Any] | None, after: dict[str, Any] | None, keys: tuple[str, ...]) -> list[dict[str, Any]]:
|
||||
"""比较普通标量键。"""
|
||||
previous = before or {}
|
||||
current = after or {}
|
||||
return [
|
||||
_change(key, 'value', previous.get(key), current.get(key))
|
||||
for key in keys
|
||||
if previous.get(key) != current.get(key)
|
||||
]
|
||||
|
||||
|
||||
def _anchor_key(anchor: Any, index: int) -> str:
|
||||
"""为锚点列表生成稳定身份;历史快照缺少 anchor_id 时退回文本键。"""
|
||||
if isinstance(anchor, dict):
|
||||
if anchor.get('anchor_id'):
|
||||
return str(anchor['anchor_id'])
|
||||
text = str(anchor.get('text') or '').strip()
|
||||
if text:
|
||||
return f'text:{text.lower()}'
|
||||
return f'index:{index}'
|
||||
|
||||
|
||||
def _anchor_changes(prefix: str, before: Any, after: Any) -> list[dict[str, Any]]:
|
||||
"""展开单个锚点的语义变化。"""
|
||||
previous = before if isinstance(before, dict) else {}
|
||||
current = after if isinstance(after, dict) else {}
|
||||
changes = [
|
||||
_change(f'{prefix}.{key}', 'value', previous.get(key), current.get(key))
|
||||
for key in ('text', 'match_mode', 'minimum_evidence_level')
|
||||
if previous.get(key) != current.get(key)
|
||||
]
|
||||
aliases = _set_change(f'{prefix}.aliases', previous.get('aliases'), current.get('aliases'))
|
||||
if aliases:
|
||||
changes.append(aliases)
|
||||
region = _region_change(f'{prefix}.region', previous.get('region'), current.get('region'))
|
||||
if region:
|
||||
changes.append(region)
|
||||
return changes
|
||||
|
||||
|
||||
def _anchor_list_changes(prefix: str, before: Any, after: Any) -> list[dict[str, Any]]:
|
||||
"""按稳定 anchor_id 展开锚点数组差异,避免数组顺序误判为新增删除。"""
|
||||
before_items = list(before or [])
|
||||
after_items = list(after or [])
|
||||
before_map = {_anchor_key(item, index): item for index, item in enumerate(before_items) if isinstance(item, dict)}
|
||||
after_map = {_anchor_key(item, index): item for index, item in enumerate(after_items) if isinstance(item, dict)}
|
||||
changes: list[dict[str, Any]] = []
|
||||
for key in sorted(set(before_map) | set(after_map)):
|
||||
previous = before_map.get(key)
|
||||
current = after_map.get(key)
|
||||
if previous is None or current is None:
|
||||
changes.append(_change(f'{prefix}.{key}', 'json', previous, current))
|
||||
continue
|
||||
changes.extend(_anchor_changes(f'{prefix}.{key}', previous, current))
|
||||
return changes
|
||||
|
||||
|
||||
def _field_ref_key(value: Any, index: int) -> str:
|
||||
"""生成字段引用数组的稳定配对键。"""
|
||||
if isinstance(value, dict):
|
||||
if value.get('field_id'):
|
||||
return str(value['field_id'])
|
||||
if value.get('field_code'):
|
||||
return str(value['field_code'])
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
return f'index:{index}'
|
||||
|
||||
|
||||
def _field_ref_tokens(values: Any) -> list[str]:
|
||||
"""将字段引用数组压平成稳定 token。"""
|
||||
return [_field_ref_key(item, index) for index, item in enumerate(list(values or []))]
|
||||
|
||||
|
||||
def _region_signature(region: Any) -> str:
|
||||
"""将 exclusion region 规范化为容差级别的稳定签名。"""
|
||||
if not isinstance(region, dict):
|
||||
return str(region)
|
||||
normalized = [f'{round(float(region.get(key, 0) or 0) / _REGION_TOLERANCE):.0f}' for key in _REGION_KEYS]
|
||||
return ':'.join(normalized)
|
||||
|
||||
|
||||
def _sample_key(sample: Any, index: int) -> str:
|
||||
"""用冻结证据身份对样本绑定进行配对,避免仅按数据库主键比较。"""
|
||||
if not isinstance(sample, dict):
|
||||
return f'index:{index}'
|
||||
parts = [
|
||||
str(sample.get('sample_role') or ''),
|
||||
str(sample.get('source_content_hash') or ''),
|
||||
str(sample.get('layout_payload_checksum') or ''),
|
||||
str(sample.get('table_id') or ''),
|
||||
]
|
||||
key = '|'.join(parts).strip('|')
|
||||
return key or f'id:{sample.get("id", index)}'
|
||||
|
||||
|
||||
def _item(
|
||||
*,
|
||||
entity_type: str,
|
||||
entity_id: str,
|
||||
label: str,
|
||||
before: Any,
|
||||
after: Any,
|
||||
changes: list[dict[str, Any]],
|
||||
parent_id: str | None = None,
|
||||
sort_key: str = '',
|
||||
) -> dict[str, Any]:
|
||||
"""构造一条稳定排序的 diff item。"""
|
||||
if before is None and after is None:
|
||||
change_type = 'unchanged'
|
||||
elif before is None:
|
||||
change_type = 'added'
|
||||
elif after is None:
|
||||
change_type = 'removed'
|
||||
else:
|
||||
change_type = 'modified' if changes else 'unchanged'
|
||||
return {
|
||||
'entity_type': entity_type,
|
||||
'entity_id': entity_id,
|
||||
'parent_id': parent_id,
|
||||
'label': label,
|
||||
'change_type': change_type,
|
||||
'changes': changes,
|
||||
'before_snapshot': _copy_json(before) if before is not None else None,
|
||||
'after_snapshot': _copy_json(after) if after is not None else None,
|
||||
'sort_key': sort_key,
|
||||
}
|
||||
|
||||
|
||||
def _sort_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""按实体类别和稳定键排序,避免刷新抖动。"""
|
||||
ordered = sorted(
|
||||
items,
|
||||
key=lambda item: (
|
||||
_ENTITY_ORDER.get(str(item.get('entity_type') or ''), 999),
|
||||
str(item.get('parent_id') or ''),
|
||||
str(item.get('sort_key') or ''),
|
||||
str(item.get('entity_id') or ''),
|
||||
),
|
||||
)
|
||||
for item in ordered:
|
||||
item.pop('sort_key', None)
|
||||
return ordered
|
||||
|
||||
|
||||
def _compare_profile_meta(before_detail: dict[str, Any] | None, after_detail: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""比较模板级治理语义,包含 Schema、冻结证据与自动冻结资格摘要。"""
|
||||
previous = before_detail or {}
|
||||
current = after_detail or {}
|
||||
changes = []
|
||||
changes.extend(_scalar_changes(previous, current, ('status', 'template_mode', 'migration_status', 'checksum')))
|
||||
changes.extend(_scalar_changes(previous.get('schema_summary'), current.get('schema_summary'), ('id', 'version', 'checksum')))
|
||||
changes.extend(_scalar_changes(
|
||||
previous.get('frozen_evidence'),
|
||||
current.get('frozen_evidence'),
|
||||
('status', 'sample_count', 'frozen_sample_count', 'audit_ready'),
|
||||
))
|
||||
changes.extend(_scalar_changes(
|
||||
previous.get('auto_freeze_qualification'),
|
||||
current.get('auto_freeze_qualification'),
|
||||
('status', 'auto_freeze_enabled', 'qualification_id', 'requires_customer_confirmation'),
|
||||
))
|
||||
customer_ids = _set_change(
|
||||
'auto_freeze_qualification.customer_ids',
|
||||
(previous.get('auto_freeze_qualification') or {}).get('customer_ids'),
|
||||
(current.get('auto_freeze_qualification') or {}).get('customer_ids'),
|
||||
)
|
||||
if customer_ids:
|
||||
changes.append(customer_ids)
|
||||
scenarios = _set_change(
|
||||
'auto_freeze_qualification.business_scenarios',
|
||||
(previous.get('auto_freeze_qualification') or {}).get('business_scenarios'),
|
||||
(current.get('auto_freeze_qualification') or {}).get('business_scenarios'),
|
||||
)
|
||||
if scenarios:
|
||||
changes.append(scenarios)
|
||||
changes.extend(_scalar_changes(
|
||||
previous.get('test_summary'),
|
||||
current.get('test_summary'),
|
||||
('status', 'sample_count', 'approved_at'),
|
||||
))
|
||||
changes.extend(_scalar_changes(
|
||||
(previous.get('test_summary') or {}).get('latest_run'),
|
||||
(current.get('test_summary') or {}).get('latest_run'),
|
||||
('status', 'sample_count', 'passed_sample_count'),
|
||||
))
|
||||
failure_codes = _set_change(
|
||||
'test_summary.latest_run.failure_codes',
|
||||
((previous.get('test_summary') or {}).get('latest_run') or {}).get('failure_codes'),
|
||||
((current.get('test_summary') or {}).get('latest_run') or {}).get('failure_codes'),
|
||||
)
|
||||
if failure_codes:
|
||||
changes.append(failure_codes)
|
||||
return [
|
||||
_item(
|
||||
entity_type='profile_meta',
|
||||
entity_id='profile_meta',
|
||||
label='Profile metadata',
|
||||
before=before_detail,
|
||||
after=after_detail,
|
||||
changes=changes,
|
||||
sort_key='000',
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _compare_document_match(before_def: dict[str, Any] | None, after_def: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""比较文档识别入口规则。"""
|
||||
previous = (before_def or {}).get('document_match') or {}
|
||||
current = (after_def or {}).get('document_match') or {}
|
||||
changes = _scalar_changes(previous, current, ('document_type', 'page_pattern', 'minimum_score', 'minimum_margin'))
|
||||
changes.extend(_anchor_list_changes('required_anchors', previous.get('required_anchors'), current.get('required_anchors')))
|
||||
changes.extend(_anchor_list_changes('optional_anchors', previous.get('optional_anchors'), current.get('optional_anchors')))
|
||||
return [
|
||||
_item(
|
||||
entity_type='document_match',
|
||||
entity_id='document_match',
|
||||
label='Document match',
|
||||
before=previous if before_def is not None else None,
|
||||
after=current,
|
||||
changes=changes,
|
||||
sort_key='010',
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _compare_field_region(
|
||||
*,
|
||||
entity_type: str,
|
||||
parent_id: str,
|
||||
label_prefix: str,
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
sort_key: str,
|
||||
) -> dict[str, Any]:
|
||||
"""比较单个字段区域。"""
|
||||
previous = before or {}
|
||||
current = after or {}
|
||||
changes = _scalar_changes(previous, current, ('field_id', 'field_code', 'extractor_key', 'minimum_evidence_level'))
|
||||
allowed_sources = _set_change('allowed_sources', previous.get('allowed_sources'), current.get('allowed_sources'))
|
||||
if allowed_sources:
|
||||
changes.append(allowed_sources)
|
||||
targets = _set_change('target_fields', _field_ref_tokens(previous.get('target_fields')), _field_ref_tokens(current.get('target_fields')))
|
||||
if targets:
|
||||
changes.append(targets)
|
||||
region = _region_change('region', previous.get('region'), current.get('region'))
|
||||
if region:
|
||||
changes.append(region)
|
||||
field_code = current.get('field_code') or previous.get('field_code') or current.get('field_id') or previous.get('field_id')
|
||||
entity_id = str(current.get('field_id') or previous.get('field_id') or field_code)
|
||||
return _item(
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
parent_id=parent_id,
|
||||
label=f'{label_prefix} {field_code}',
|
||||
before=before,
|
||||
after=after,
|
||||
changes=changes,
|
||||
sort_key=sort_key,
|
||||
)
|
||||
|
||||
|
||||
def _append_keyed_items(
|
||||
items: list[dict[str, Any]],
|
||||
*,
|
||||
before_values: Any,
|
||||
after_values: Any,
|
||||
key_builder: Callable[[Any, int], str],
|
||||
comparator: Callable[[dict[str, Any] | None, dict[str, Any] | None, str], dict[str, Any]],
|
||||
) -> None:
|
||||
"""按稳定身份遍历键控数组并追加 diff item。"""
|
||||
previous_items = list(before_values or [])
|
||||
current_items = list(after_values or [])
|
||||
previous_map = {key_builder(value, index): value for index, value in enumerate(previous_items) if isinstance(value, dict)}
|
||||
current_map = {key_builder(value, index): value for index, value in enumerate(current_items) if isinstance(value, dict)}
|
||||
for key in sorted(set(previous_map) | set(current_map)):
|
||||
items.append(comparator(previous_map.get(key), current_map.get(key), key))
|
||||
|
||||
|
||||
def _compare_table_regions(before_def: dict[str, Any] | None, after_def: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""比较表格区域及其下游布局。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
previous_regions = list((before_def or {}).get('table_regions') or [])
|
||||
current_regions = list((after_def or {}).get('table_regions') or [])
|
||||
previous_map = {
|
||||
str(item.get('region_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(previous_regions)
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
current_map = {
|
||||
str(item.get('region_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(current_regions)
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
for region_id in sorted(set(previous_map) | set(current_map)):
|
||||
previous = previous_map.get(region_id)
|
||||
current = current_map.get(region_id)
|
||||
previous_body = previous or {}
|
||||
current_body = current or {}
|
||||
region_changes = _scalar_changes(previous_body, current_body, ('page_scope', 'page_no'))
|
||||
region = _region_change('region', previous_body.get('region'), current_body.get('region'))
|
||||
if region:
|
||||
region_changes.append(region)
|
||||
region_changes.extend(_scalar_changes(
|
||||
previous_body.get('continuation_rule'),
|
||||
current_body.get('continuation_rule'),
|
||||
('allow_cross_page',),
|
||||
))
|
||||
required_anchors = _set_change(
|
||||
'continuation_rule.required_anchor_ids',
|
||||
(previous_body.get('continuation_rule') or {}).get('required_anchor_ids'),
|
||||
(current_body.get('continuation_rule') or {}).get('required_anchor_ids'),
|
||||
)
|
||||
if required_anchors:
|
||||
region_changes.append(required_anchors)
|
||||
items.append(_item(
|
||||
entity_type='table_region',
|
||||
entity_id=region_id,
|
||||
label=f'Table region {region_id}',
|
||||
before=previous,
|
||||
after=current,
|
||||
changes=region_changes,
|
||||
sort_key=f'020:{region_id}',
|
||||
))
|
||||
|
||||
def header_layout_comparator(before_value: dict[str, Any] | None, after_value: dict[str, Any] | None, key: str) -> dict[str, Any]:
|
||||
previous_layout = before_value or {}
|
||||
current_layout = after_value or {}
|
||||
changes = []
|
||||
region_change = _region_change('region', previous_layout.get('region'), current_layout.get('region'))
|
||||
if region_change:
|
||||
changes.append(region_change)
|
||||
return _item(
|
||||
entity_type='header_layout',
|
||||
entity_id=key,
|
||||
parent_id=region_id,
|
||||
label=f'Header layout {key}',
|
||||
before=before_value,
|
||||
after=after_value,
|
||||
changes=changes,
|
||||
sort_key=f'030:{region_id}:{key}',
|
||||
)
|
||||
|
||||
_append_keyed_items(
|
||||
items,
|
||||
before_values=previous_body.get('header_layouts'),
|
||||
after_values=current_body.get('header_layouts'),
|
||||
key_builder=lambda value, index: str(value.get('layout_id') or f'index:{index}'),
|
||||
comparator=header_layout_comparator,
|
||||
)
|
||||
|
||||
previous_headers = {
|
||||
str(item.get('layout_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(list(previous_body.get('header_layouts') or []))
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
current_headers = {
|
||||
str(item.get('layout_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(list(current_body.get('header_layouts') or []))
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
for layout_id in sorted(set(previous_headers) | set(current_headers)):
|
||||
previous_layout = previous_headers.get(layout_id) or {}
|
||||
current_layout = current_headers.get(layout_id) or {}
|
||||
_append_keyed_items(
|
||||
items,
|
||||
before_values=previous_layout.get('field_regions'),
|
||||
after_values=current_layout.get('field_regions'),
|
||||
key_builder=lambda value, index: str(value.get('field_id') or value.get('field_code') or f'index:{index}'),
|
||||
comparator=lambda before_value, after_value, key: _compare_field_region(
|
||||
entity_type='header_field_region',
|
||||
parent_id=f'{region_id}:{layout_id}',
|
||||
label_prefix='Header field',
|
||||
before=before_value,
|
||||
after=after_value,
|
||||
sort_key=f'040:{region_id}:{layout_id}:{key}',
|
||||
),
|
||||
)
|
||||
|
||||
def line_layout_comparator(before_value: dict[str, Any] | None, after_value: dict[str, Any] | None, key: str) -> dict[str, Any]:
|
||||
previous_layout = before_value or {}
|
||||
current_layout = after_value or {}
|
||||
changes = _scalar_changes(previous_layout, current_layout, ('row_offset', 'role'))
|
||||
region_change = _region_change('region', previous_layout.get('region'), current_layout.get('region'))
|
||||
if region_change:
|
||||
changes.append(region_change)
|
||||
required_fields = _set_change('required_fields', previous_layout.get('required_fields'), current_layout.get('required_fields'))
|
||||
if required_fields:
|
||||
changes.append(required_fields)
|
||||
allowed_empty = _set_change(
|
||||
'allowed_empty_fields',
|
||||
previous_layout.get('allowed_empty_fields'),
|
||||
current_layout.get('allowed_empty_fields'),
|
||||
)
|
||||
if allowed_empty:
|
||||
changes.append(allowed_empty)
|
||||
changes.extend(_anchor_list_changes(
|
||||
'continuation_conditions',
|
||||
previous_layout.get('continuation_conditions'),
|
||||
current_layout.get('continuation_conditions'),
|
||||
))
|
||||
changes.extend(_anchor_changes('new_line_anchor', previous_layout.get('new_line_anchor'), current_layout.get('new_line_anchor')))
|
||||
return _item(
|
||||
entity_type='line_layout',
|
||||
entity_id=key,
|
||||
parent_id=region_id,
|
||||
label=f'Line layout {key}',
|
||||
before=before_value,
|
||||
after=after_value,
|
||||
changes=changes,
|
||||
sort_key=f'050:{region_id}:{key}',
|
||||
)
|
||||
|
||||
_append_keyed_items(
|
||||
items,
|
||||
before_values=previous_body.get('line_layouts'),
|
||||
after_values=current_body.get('line_layouts'),
|
||||
key_builder=lambda value, index: str(value.get('layout_id') or f'index:{index}'),
|
||||
comparator=line_layout_comparator,
|
||||
)
|
||||
|
||||
previous_lines = {
|
||||
str(item.get('layout_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(list(previous_body.get('line_layouts') or []))
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
current_lines = {
|
||||
str(item.get('layout_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(list(current_body.get('line_layouts') or []))
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
for layout_id in sorted(set(previous_lines) | set(current_lines)):
|
||||
previous_layout = previous_lines.get(layout_id) or {}
|
||||
current_layout = current_lines.get(layout_id) or {}
|
||||
_append_keyed_items(
|
||||
items,
|
||||
before_values=previous_layout.get('field_regions'),
|
||||
after_values=current_layout.get('field_regions'),
|
||||
key_builder=lambda value, index: str(value.get('field_id') or value.get('field_code') or f'index:{index}'),
|
||||
comparator=lambda before_value, after_value, key: _compare_field_region(
|
||||
entity_type='line_field_region',
|
||||
parent_id=f'{region_id}:{layout_id}',
|
||||
label_prefix='Line field',
|
||||
before=before_value,
|
||||
after=after_value,
|
||||
sort_key=f'060:{region_id}:{layout_id}:{key}',
|
||||
),
|
||||
)
|
||||
|
||||
_append_keyed_items(
|
||||
items,
|
||||
before_values=previous_body.get('termination_rules'),
|
||||
after_values=current_body.get('termination_rules'),
|
||||
key_builder=lambda value, index: str(value.get('rule_id') or f'index:{index}'),
|
||||
comparator=lambda before_value, after_value, key: _item(
|
||||
entity_type='termination_rule',
|
||||
entity_id=key,
|
||||
parent_id=region_id,
|
||||
label=f'Termination rule {key}',
|
||||
before=before_value,
|
||||
after=after_value,
|
||||
changes=_anchor_changes('anchor', (before_value or {}).get('anchor'), (after_value or {}).get('anchor')),
|
||||
sort_key=f'070:{region_id}:{key}',
|
||||
),
|
||||
)
|
||||
|
||||
previous_exclusions = {
|
||||
_region_signature(value): value
|
||||
for value in list(previous_body.get('exclusion_regions') or [])
|
||||
if isinstance(value, dict)
|
||||
}
|
||||
current_exclusions = {
|
||||
_region_signature(value): value
|
||||
for value in list(current_body.get('exclusion_regions') or [])
|
||||
if isinstance(value, dict)
|
||||
}
|
||||
for exclusion_key in sorted(set(previous_exclusions) | set(current_exclusions)):
|
||||
items.append(_item(
|
||||
entity_type='exclusion_region',
|
||||
entity_id=exclusion_key,
|
||||
parent_id=region_id,
|
||||
label=f'Exclusion region {exclusion_key}',
|
||||
before=previous_exclusions.get(exclusion_key),
|
||||
after=current_exclusions.get(exclusion_key),
|
||||
changes=[],
|
||||
sort_key=f'080:{region_id}:{exclusion_key}',
|
||||
))
|
||||
return items
|
||||
|
||||
|
||||
def _compare_order_field_layouts(before_def: dict[str, Any] | None, after_def: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""比较订单级字段布局。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
previous_items = list((before_def or {}).get('order_field_layouts') or [])
|
||||
current_items = list((after_def or {}).get('order_field_layouts') or [])
|
||||
previous_map = {
|
||||
str(item.get('layout_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(previous_items)
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
current_map = {
|
||||
str(item.get('layout_id') or f'index:{index}'): item
|
||||
for index, item in enumerate(current_items)
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
for layout_id in sorted(set(previous_map) | set(current_map)):
|
||||
previous = previous_map.get(layout_id)
|
||||
current = current_map.get(layout_id)
|
||||
previous_body = previous or {}
|
||||
current_body = current or {}
|
||||
changes = _scalar_changes(
|
||||
previous_body,
|
||||
current_body,
|
||||
('field_id', 'field_code', 'page_scope', 'page_no', 'value_mode', 'normalizer_key', 'required', 'minimum_evidence_level'),
|
||||
)
|
||||
value_region = _region_change('value_region', previous_body.get('value_region'), current_body.get('value_region'))
|
||||
if value_region:
|
||||
changes.append(value_region)
|
||||
fallback = _region_change(
|
||||
'fallback_value_region',
|
||||
previous_body.get('fallback_value_region'),
|
||||
current_body.get('fallback_value_region'),
|
||||
)
|
||||
if fallback:
|
||||
changes.append(fallback)
|
||||
changes.extend(_anchor_changes('anchor', previous_body.get('anchor'), current_body.get('anchor')))
|
||||
changes.extend(_anchor_list_changes('stop_anchors', previous_body.get('stop_anchors'), current_body.get('stop_anchors')))
|
||||
field_code = current_body.get('field_code') or previous_body.get('field_code') or layout_id
|
||||
items.append(_item(
|
||||
entity_type='order_field_layout',
|
||||
entity_id=layout_id,
|
||||
label=f'Order field {field_code}',
|
||||
before=previous,
|
||||
after=current,
|
||||
changes=changes,
|
||||
sort_key=f'090:{layout_id}',
|
||||
))
|
||||
return items
|
||||
|
||||
|
||||
def _compare_samples(before_detail: dict[str, Any] | None, after_detail: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""比较安全样本绑定与冻结证据身份变化。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
previous_items = list((before_detail or {}).get('sample_summary', {}).get('samples') or [])
|
||||
current_items = list((after_detail or {}).get('sample_summary', {}).get('samples') or [])
|
||||
previous_map = {_sample_key(item, index): item for index, item in enumerate(previous_items) if isinstance(item, dict)}
|
||||
current_map = {_sample_key(item, index): item for index, item in enumerate(current_items) if isinstance(item, dict)}
|
||||
for sample_key in sorted(set(previous_map) | set(current_map)):
|
||||
previous = previous_map.get(sample_key)
|
||||
current = current_map.get(sample_key)
|
||||
previous_body = previous or {}
|
||||
current_body = current or {}
|
||||
changes = _scalar_changes(
|
||||
previous_body,
|
||||
current_body,
|
||||
(
|
||||
'sample_role', 'table_id', 'frozen_evidence_ready', 'layout_version_id',
|
||||
'source_filename_snapshot', 'page_count_snapshot', 'parser_key',
|
||||
'parser_name', 'parser_version', 'evidence_frozen_at',
|
||||
),
|
||||
)
|
||||
table_identity = _change(
|
||||
'table_identity_snapshot',
|
||||
'json',
|
||||
previous_body.get('table_identity_snapshot'),
|
||||
current_body.get('table_identity_snapshot'),
|
||||
) if previous_body.get('table_identity_snapshot') != current_body.get('table_identity_snapshot') else None
|
||||
if table_identity:
|
||||
changes.append(table_identity)
|
||||
checksum = _scalar_changes(previous_body, current_body, ('source_content_hash', 'layout_payload_checksum', 'layout_contract_version'))
|
||||
changes.extend(checksum)
|
||||
label = current_body.get('source_filename_snapshot') or previous_body.get('source_filename_snapshot') or sample_key
|
||||
items.append(_item(
|
||||
entity_type='sample_binding',
|
||||
entity_id=sample_key,
|
||||
label=f'Sample {label}',
|
||||
before=previous,
|
||||
after=current,
|
||||
changes=changes,
|
||||
sort_key=f'100:{sample_key}',
|
||||
))
|
||||
return items
|
||||
|
||||
|
||||
def compare_profile_details(before_detail: dict[str, Any] | None, after_detail: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
比较两个安全详情 DTO,返回稳定排序的语义差异。
|
||||
|
||||
Args:
|
||||
before_detail: 作为基线的模板详情;为空时表示首版与空版本比较。
|
||||
after_detail: 当前查看的模板详情。
|
||||
Returns:
|
||||
适合前端直接展示的结构化 diff,包含 summary 与 item 列表。
|
||||
"""
|
||||
after_definition = dict(after_detail.get('definition') or {})
|
||||
before_definition = None if before_detail is None else dict(before_detail.get('definition') or {})
|
||||
items: list[dict[str, Any]] = []
|
||||
items.extend(_compare_profile_meta(before_detail, after_detail))
|
||||
items.extend(_compare_document_match(before_definition, after_definition))
|
||||
items.extend(_compare_table_regions(before_definition, after_definition))
|
||||
items.extend(_compare_order_field_layouts(before_definition, after_definition))
|
||||
items.extend(_compare_samples(before_detail, after_detail))
|
||||
ordered = _sort_items(items)
|
||||
summary = {'added': 0, 'removed': 0, 'modified': 0, 'unchanged': 0}
|
||||
for item in ordered:
|
||||
summary[item['change_type']] += 1
|
||||
return {'summary': summary, 'items': ordered}
|
||||
|
||||
|
||||
def _resolve_against_profile(profile: ShippingOrderDocumentProfile, against_profile_id: int | None) -> tuple[ShippingOrderDocumentProfile | None, str]:
|
||||
"""解析比较基线:显式指定则校验同族,否则默认上一版本。"""
|
||||
if against_profile_id is not None:
|
||||
against = _profile(against_profile_id)
|
||||
if against.profile_code != profile.profile_code:
|
||||
raise ValidationError(
|
||||
'Profiles from different families cannot be compared',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return against, 'explicit'
|
||||
against = (
|
||||
ShippingOrderDocumentProfile.query
|
||||
.filter(
|
||||
ShippingOrderDocumentProfile.profile_code == profile.profile_code,
|
||||
ShippingOrderDocumentProfile.version < profile.version,
|
||||
)
|
||||
.order_by(ShippingOrderDocumentProfile.version.desc())
|
||||
.first()
|
||||
)
|
||||
return against, 'previous' if against is not None else 'initial'
|
||||
|
||||
|
||||
def get_profile_diff(profile_id: int, *, against_profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""返回同模板版本的服务端语义差异,并在未指定时默认对比上一版本。"""
|
||||
profile = _profile(profile_id)
|
||||
against_profile, comparison_mode = _resolve_against_profile(profile, against_profile_id)
|
||||
current_detail = _safe_detail(profile)
|
||||
compare_detail = _safe_detail(against_profile)
|
||||
result = compare_profile_details(compare_detail, current_detail)
|
||||
return {
|
||||
'base_profile': _profile_ref(current_detail),
|
||||
'compare_profile': _profile_ref(compare_detail),
|
||||
'comparison_mode': comparison_mode,
|
||||
**result,
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_lease_service.py
|
||||
|
||||
用途:管理订单模板草稿的单写者编辑租约。
|
||||
依赖:Profile、EditLease ORM、Profile 审计服务与统一错误类型。
|
||||
逻辑:编辑器先获取租约,再带令牌保存;过期租约可确认接管,令牌仅以哈希形式持久化。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileEditLease
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
LEASE_TTL_SECONDS = 300
|
||||
|
||||
|
||||
def _token_hash(token: str) -> str:
|
||||
"""将浏览器租约令牌转换为固定长度哈希,数据库不得保存可重放令牌。"""
|
||||
return hashlib.sha256(token.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _browser_session_id(value: str | None) -> str:
|
||||
"""校验浏览器标签身份;该身份用于区分同一用户的多个写入者。"""
|
||||
session_id = str(value or '').strip()
|
||||
if not session_id or len(session_id) > 128:
|
||||
raise ConflictError('browser_session_id is required for an edit lease', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
return session_id
|
||||
|
||||
|
||||
def _profile_for_edit(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取可编辑草稿;发布或退役版本不能取得写租约。"""
|
||||
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 != 'draft':
|
||||
raise ConflictError('Profile is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE')
|
||||
return profile
|
||||
|
||||
|
||||
def _payload(lease: ShippingOrderDocumentProfileEditLease) -> dict[str, Any]:
|
||||
"""返回安全租约摘要;真实 token 仅由获取/续租调用方单独持有。"""
|
||||
now = datetime.utcnow()
|
||||
return {
|
||||
'profile_id': int(lease.profile_id),
|
||||
'state': 'active' if lease.expires_at > now else 'expired',
|
||||
'actor_id': int(lease.actor_id) if lease.actor_id else None,
|
||||
'browser_session_id': lease.browser_session_id,
|
||||
'expires_at': lease.expires_at.isoformat(),
|
||||
'last_renewed_at': lease.last_renewed_at.isoformat(),
|
||||
'lock_version': int(lease.lock_version),
|
||||
}
|
||||
|
||||
|
||||
def _write_audit(
|
||||
*, profile_id: int, event_type: str, actor_id: int | None, browser_session_id: str,
|
||||
operation_id: str, detail: dict[str, Any], revision_no: int | None = None,
|
||||
) -> None:
|
||||
"""追加不含令牌的租约语义审计,调用方事务失败时随之回滚。"""
|
||||
profile_service._audit(
|
||||
profile_id=profile_id,
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
browser_session_id=browser_session_id,
|
||||
operation_id=operation_id,
|
||||
revision_no=revision_no,
|
||||
detail=detail,
|
||||
)
|
||||
|
||||
|
||||
def acquire_lease(
|
||||
profile_id: int, *, actor_id: int | None, browser_session_id: str | None,
|
||||
operation_id: str, confirm_takeover: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为草稿取得五分钟单写者租约。
|
||||
|
||||
Args:
|
||||
profile_id: 草稿 Profile 主键。
|
||||
actor_id: 当前管理员身份。
|
||||
browser_session_id: 浏览器标签唯一身份,不能为空。
|
||||
operation_id: 本次业务操作链路身份。
|
||||
confirm_takeover: 为 True 时显式接管未过期的他人租约。
|
||||
|
||||
Returns:
|
||||
含一次性 lease_token 的安全租约 DTO。
|
||||
"""
|
||||
profile = _profile_for_edit(profile_id)
|
||||
session_id = _browser_session_id(browser_session_id)
|
||||
now = datetime.utcnow()
|
||||
lease = ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile.id).with_for_update().one_or_none()
|
||||
taken_over_from_actor_id = None
|
||||
event_type = 'edit_lease_acquired'
|
||||
expired_lease = lease is not None and lease.expires_at <= now
|
||||
if lease is not None and not expired_lease:
|
||||
same_holder = lease.actor_id == actor_id and lease.browser_session_id == session_id
|
||||
if same_holder:
|
||||
token = secrets.token_urlsafe(32)
|
||||
lease.lease_token_hash = _token_hash(token)
|
||||
lease.expires_at = now + timedelta(seconds=LEASE_TTL_SECONDS)
|
||||
lease.last_renewed_at = now
|
||||
lease.lock_version = profile.lock_version
|
||||
event_type = 'edit_lease_renewed'
|
||||
elif not confirm_takeover:
|
||||
raise ConflictError(
|
||||
'Profile draft already has an active edit lease',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT',
|
||||
details={'expires_at': lease.expires_at.isoformat(), 'lock_version': lease.lock_version},
|
||||
)
|
||||
else:
|
||||
taken_over_from_actor_id = lease.actor_id
|
||||
token = secrets.token_urlsafe(32)
|
||||
lease.lease_token_hash = _token_hash(token)
|
||||
lease.actor_id = actor_id
|
||||
lease.browser_session_id = session_id
|
||||
lease.expires_at = now + timedelta(seconds=LEASE_TTL_SECONDS)
|
||||
lease.last_renewed_at = now
|
||||
lease.taken_over_from_actor_id = taken_over_from_actor_id
|
||||
lease.lock_version = profile.lock_version
|
||||
event_type = 'edit_lease_taken_over'
|
||||
else:
|
||||
token = secrets.token_urlsafe(32)
|
||||
if lease is None:
|
||||
lease = ShippingOrderDocumentProfileEditLease(
|
||||
profile_id=profile.id,
|
||||
lease_token_hash=_token_hash(token),
|
||||
actor_id=actor_id,
|
||||
browser_session_id=session_id,
|
||||
expires_at=now + timedelta(seconds=LEASE_TTL_SECONDS),
|
||||
last_renewed_at=now,
|
||||
lock_version=profile.lock_version,
|
||||
)
|
||||
db.session.add(lease)
|
||||
else:
|
||||
lease.lease_token_hash = _token_hash(token)
|
||||
lease.actor_id = actor_id
|
||||
lease.browser_session_id = session_id
|
||||
lease.expires_at = now + timedelta(seconds=LEASE_TTL_SECONDS)
|
||||
lease.last_renewed_at = now
|
||||
lease.taken_over_from_actor_id = None
|
||||
lease.lock_version = profile.lock_version
|
||||
event_type = 'edit_lease_reacquired' if expired_lease else 'edit_lease_acquired'
|
||||
db.session.flush()
|
||||
_write_audit(
|
||||
profile_id=profile.id, event_type=event_type, actor_id=actor_id, browser_session_id=session_id,
|
||||
operation_id=operation_id, detail={'lock_version': profile.lock_version, 'taken_over': taken_over_from_actor_id is not None},
|
||||
)
|
||||
db.session.commit()
|
||||
result = _payload(lease)
|
||||
result['lease_token'] = token
|
||||
return result
|
||||
|
||||
|
||||
def renew_lease(
|
||||
profile_id: int, *, actor_id: int | None, browser_session_id: str | None,
|
||||
lease_token: str | None, operation_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""续租当前标签的有效租约;令牌、身份或过期不匹配时返回明确 409。"""
|
||||
session_id = _browser_session_id(browser_session_id)
|
||||
profile = _profile_for_edit(profile_id)
|
||||
lease = ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile.id).with_for_update().one_or_none()
|
||||
now = datetime.utcnow()
|
||||
if lease is None or lease.expires_at <= now or lease.actor_id != actor_id or lease.browser_session_id != session_id or lease.lease_token_hash != _token_hash(str(lease_token or '')):
|
||||
raise ConflictError('Edit lease is invalid or expired', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
lease.expires_at = now + timedelta(seconds=LEASE_TTL_SECONDS)
|
||||
lease.last_renewed_at = now
|
||||
lease.lock_version = profile.lock_version
|
||||
_write_audit(profile_id=profile.id, event_type='edit_lease_renewed', actor_id=actor_id, browser_session_id=session_id, operation_id=operation_id, detail={'lock_version': profile.lock_version})
|
||||
db.session.commit()
|
||||
result = _payload(lease)
|
||||
result['lease_token'] = str(lease_token)
|
||||
return result
|
||||
|
||||
|
||||
def release_lease(
|
||||
profile_id: int, *, actor_id: int | None, browser_session_id: str | None,
|
||||
lease_token: str | None, operation_id: str,
|
||||
) -> None:
|
||||
"""主动释放当前标签持有的租约;其他会话不能删除其写保护。"""
|
||||
session_id = _browser_session_id(browser_session_id)
|
||||
lease = ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=int(profile_id)).with_for_update().one_or_none()
|
||||
if lease is None or lease.actor_id != actor_id or lease.browser_session_id != session_id or lease.lease_token_hash != _token_hash(str(lease_token or '')):
|
||||
raise ConflictError('Edit lease is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
db.session.delete(lease)
|
||||
_write_audit(profile_id=int(profile_id), event_type='edit_lease_released', actor_id=actor_id, browser_session_id=session_id, operation_id=operation_id, detail={})
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def require_active_lease(
|
||||
profile_id: int, *, actor_id: int | None, browser_session_id: str | None, lease_token: str | None,
|
||||
) -> ShippingOrderDocumentProfileEditLease:
|
||||
"""供草稿保存前校验单写者身份;仅检查,不提交事务。"""
|
||||
session_id = _browser_session_id(browser_session_id)
|
||||
lease = ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=int(profile_id)).with_for_update().one_or_none()
|
||||
if lease is None or lease.expires_at <= datetime.utcnow() or lease.actor_id != actor_id or lease.browser_session_id != session_id or lease.lease_token_hash != _token_hash(str(lease_token or '')):
|
||||
raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
return lease
|
||||
@@ -0,0 +1,326 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_preview_service.py
|
||||
|
||||
用途:提供订单模板版本中心的冻结样本只读预览链路。
|
||||
依赖:Profile/Sample/Layout 模型、preview_grant_store、PDF 渲染能力。
|
||||
逻辑:预览必须绑定 profile sample,并校验冻结的 document/layout/hash/checksum 后才签发一次性 token。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import secrets
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import CURRENT_LAYOUT_STATUSES, canonical_layout_payload
|
||||
from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
|
||||
|
||||
PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-frozen-preview:'
|
||||
|
||||
|
||||
def _preview_grant_store() -> Any:
|
||||
"""返回冻结样本页预览的授权存储。"""
|
||||
return preview_grant_store()
|
||||
|
||||
|
||||
def _audit(
|
||||
*,
|
||||
profile_id: int,
|
||||
document_id: int,
|
||||
sample_binding_id: int,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""记录冻结样本只读画布的审计事件,不写入 PDF、token 或正文。"""
|
||||
db.session.add(ShippingOrderDocumentProfileAudit(
|
||||
profile_id=int(profile_id),
|
||||
document_id=int(document_id),
|
||||
event_type=str(event_type or '').strip()[:48] or 'preview_page_viewed',
|
||||
actor_id=actor_id,
|
||||
detail_json={
|
||||
'sample_binding_id': int(sample_binding_id),
|
||||
**dict(detail or {}),
|
||||
},
|
||||
))
|
||||
|
||||
|
||||
def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> bool:
|
||||
"""旧未冻结样本不得伪装成可审计只读画布。"""
|
||||
required = (
|
||||
sample.layout_version_id,
|
||||
sample.source_content_hash,
|
||||
sample.layout_payload_checksum,
|
||||
sample.layout_contract_version,
|
||||
sample.parser_key,
|
||||
sample.parser_name,
|
||||
sample.evidence_frozen_at,
|
||||
)
|
||||
return all(required)
|
||||
|
||||
|
||||
def _frozen_table_identity_ready(
|
||||
sample: ShippingOrderDocumentProfileSample,
|
||||
*,
|
||||
layout_payload: dict[str, Any],
|
||||
) -> None:
|
||||
"""冻结表格身份必须仍能在冻结 layout 中定位,禁止静默回退到最新布局。"""
|
||||
tables = layout_payload.get('tables') if isinstance(layout_payload.get('tables'), list) else []
|
||||
snapshot = dict(sample.table_identity_snapshot or {})
|
||||
expected_table_id = str(snapshot.get('table_id') or sample.table_id or '').strip()
|
||||
matched = next((
|
||||
item for item in tables
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '').strip() == expected_table_id
|
||||
), None)
|
||||
if matched is None:
|
||||
raise ValidationError(
|
||||
'Frozen table evidence is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
expected_page_no = snapshot.get('page_no')
|
||||
if expected_page_no is not None and int(matched.get('page_no') or 1) != int(expected_page_no):
|
||||
raise ValidationError(
|
||||
'Frozen table page no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
expected_row_count = snapshot.get('row_count')
|
||||
if expected_row_count is not None:
|
||||
rows = matched.get('rows') if isinstance(matched.get('rows'), list) else []
|
||||
if len(rows) != int(expected_row_count):
|
||||
raise ValidationError(
|
||||
'Frozen table rows no longer match the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
|
||||
|
||||
def _frozen_sample_context(
|
||||
*,
|
||||
profile_id: int,
|
||||
sample_binding_id: int,
|
||||
) -> tuple[
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingNoticeDocument,
|
||||
ShippingDocumentLayoutVersion,
|
||||
FileAsset,
|
||||
]:
|
||||
"""加载并校验冻结样本的 document/layout/asset 身份,任意漂移都直接阻断预览。"""
|
||||
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')
|
||||
sample = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
id=int(sample_binding_id), profile_id=int(profile_id),
|
||||
).one_or_none()
|
||||
if sample is None:
|
||||
raise NotFoundError(
|
||||
'Order profile sample not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
if not _sample_frozen_evidence_ready(sample):
|
||||
raise ValidationError(
|
||||
'Frozen evidence is unavailable for this sample',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
document = db.session.get(ShippingNoticeDocument, int(sample.document_id))
|
||||
if document is None or not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
raise ValidationError(
|
||||
'Frozen sample file is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
raise ValidationError(
|
||||
'Frozen sample file is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
layout_version = db.session.get(ShippingDocumentLayoutVersion, int(sample.layout_version_id))
|
||||
if (
|
||||
layout_version is None
|
||||
or int(layout_version.document_id) != int(document.id)
|
||||
or str(layout_version.status or '') not in CURRENT_LAYOUT_STATUSES
|
||||
or not isinstance(layout_version.payload_json, dict)
|
||||
):
|
||||
raise ValidationError(
|
||||
'Frozen layout evidence is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if str(document.content_hash or '').strip().lower() != str(sample.source_content_hash or '').strip().lower():
|
||||
raise ValidationError(
|
||||
'Frozen sample content hash no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if str(layout_version.source_content_hash or '').strip().lower() != str(sample.source_content_hash or '').strip().lower():
|
||||
raise ValidationError(
|
||||
'Frozen layout source hash no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
actual_checksum, _ = canonical_layout_payload(layout_version.payload_json)
|
||||
expected_checksum = str(sample.layout_payload_checksum or '').strip().lower()
|
||||
if (
|
||||
actual_checksum != expected_checksum
|
||||
or str(layout_version.payload_checksum or '').strip().lower() != expected_checksum
|
||||
):
|
||||
raise ValidationError(
|
||||
'Frozen layout checksum no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if str(layout_version.contract_version or '').strip() != str(sample.layout_contract_version or '').strip():
|
||||
raise ValidationError(
|
||||
'Frozen layout contract version no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if str(layout_version.parser_key or '').strip() != str(sample.parser_key or '').strip():
|
||||
raise ValidationError(
|
||||
'Frozen parser identity no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if str(layout_version.parser_name or '').strip() != str(sample.parser_name or '').strip():
|
||||
raise ValidationError(
|
||||
'Frozen parser identity no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
expected_parser_version = str(sample.parser_version or '').strip()
|
||||
if expected_parser_version and str(layout_version.parser_version or '').strip() != expected_parser_version:
|
||||
raise ValidationError(
|
||||
'Frozen parser version no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
_frozen_table_identity_ready(sample, layout_payload=layout_version.payload_json)
|
||||
return profile, sample, document, layout_version, asset
|
||||
|
||||
|
||||
def _render_pdf_pages(asset: FileAsset) -> list[Any]:
|
||||
"""渲染 PDF 页面像素;预览只输出 PNG,不暴露原文件地址。"""
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
|
||||
try:
|
||||
return list(extract_native_pdf_pages(read_asset_bytes(asset), render_scale=2.0))
|
||||
except Exception as exc:
|
||||
raise ValidationError(
|
||||
'PDF page preview is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
) from exc
|
||||
|
||||
|
||||
def authorize_frozen_sample_preview_pages(
|
||||
profile_id: int,
|
||||
*,
|
||||
sample_binding_id: int,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""按冻结样本绑定签发一次性页预览 token,禁止 document_id 枚举读取。"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError(
|
||||
'Order profile sample not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
_, sample, document, _layout_version, asset = _frozen_sample_context(
|
||||
profile_id=int(profile_id), sample_binding_id=int(sample_binding_id),
|
||||
)
|
||||
pages = _render_pdf_pages(asset)
|
||||
if sample.page_count_snapshot is not None and len(pages) != int(sample.page_count_snapshot):
|
||||
raise ValidationError(
|
||||
'Frozen page count no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
store = _preview_grant_store()
|
||||
preview_pages: list[dict[str, Any]] = []
|
||||
for page in pages:
|
||||
grant_token = secrets.token_urlsafe(24)
|
||||
store.setex(
|
||||
f'{PREVIEW_GRANT_KEY_PREFIX}{grant_token}',
|
||||
PREVIEW_GRANT_TTL_SECONDS,
|
||||
json.dumps({
|
||||
'profile_id': int(profile_id),
|
||||
'sample_binding_id': int(sample.id),
|
||||
'actor_id': int(actor_id),
|
||||
'page_no': int(page.page_no),
|
||||
}, separators=(',', ':')),
|
||||
)
|
||||
preview_pages.append({
|
||||
'page_no': int(page.page_no),
|
||||
'preview_token': grant_token,
|
||||
})
|
||||
_audit(
|
||||
profile_id=int(profile_id),
|
||||
document_id=int(document.id),
|
||||
sample_binding_id=int(sample.id),
|
||||
event_type='preview_pages_authorized',
|
||||
actor_id=actor_id,
|
||||
detail={'page_count': len(pages), 'ttl_seconds': PREVIEW_GRANT_TTL_SECONDS, 'mode': 'frozen_sample'},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'sample_binding_id': int(sample.id),
|
||||
'document_id': int(document.id),
|
||||
'page_count': len(pages),
|
||||
'pages': preview_pages,
|
||||
'expires_in_seconds': PREVIEW_GRANT_TTL_SECONDS,
|
||||
}
|
||||
|
||||
|
||||
def render_frozen_sample_preview_page(
|
||||
*,
|
||||
profile_id: int,
|
||||
sample_binding_id: int,
|
||||
token: str,
|
||||
page_no: int,
|
||||
actor_id: int | None,
|
||||
) -> bytes:
|
||||
"""消费一次性 token 输出冻结样本单页 PNG,跨人、跨样本或重放都直接失败。"""
|
||||
store = _preview_grant_store()
|
||||
raw_grant = store.getdel(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token or "")}')
|
||||
try:
|
||||
grant = json.loads(raw_grant) if raw_grant else None
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
grant = None
|
||||
if (
|
||||
not isinstance(grant, dict)
|
||||
or actor_id is None
|
||||
or grant.get('actor_id') != int(actor_id)
|
||||
or grant.get('page_no') != int(page_no)
|
||||
or grant.get('profile_id') != int(profile_id)
|
||||
or grant.get('sample_binding_id') != int(sample_binding_id)
|
||||
):
|
||||
raise NotFoundError(
|
||||
'Order profile preview not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND',
|
||||
)
|
||||
_, sample, document, _layout_version, asset = _frozen_sample_context(
|
||||
profile_id=int(profile_id), sample_binding_id=int(sample_binding_id),
|
||||
)
|
||||
page = next((item for item in _render_pdf_pages(asset) if int(item.page_no) == int(page_no)), None)
|
||||
if page is None:
|
||||
raise NotFoundError(
|
||||
'Order profile preview page not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND',
|
||||
)
|
||||
image = Image.fromarray(page.image)
|
||||
stream = io.BytesIO()
|
||||
image.save(stream, format='PNG', optimize=True)
|
||||
_audit(
|
||||
profile_id=int(profile_id),
|
||||
document_id=int(document.id),
|
||||
sample_binding_id=int(sample.id),
|
||||
event_type='preview_page_viewed',
|
||||
actor_id=actor_id,
|
||||
detail={'page_no': int(page_no), 'mode': 'frozen_sample'},
|
||||
)
|
||||
db.session.commit()
|
||||
return stream.getvalue()
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
services/shipping_notice/order_document_profile_publish_check_service.py
|
||||
|
||||
用途:生成、确认和消费订单模板不可变发布检查报告。
|
||||
依赖:草稿 Revision、验证运行、语义差异、发布服务和编辑租约服务。
|
||||
逻辑:报告冻结当前草稿身份;消费时在同一事务再次校验并发布,草稿变化只能令报告失效。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfilePublishCheckReport,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_diff as diff_service
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取唯一可创建或消费发布报告的草稿。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if row.status != 'draft':
|
||||
raise ConflictError('Only draft profiles support publish checks', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE')
|
||||
return row
|
||||
|
||||
|
||||
def _current_revision(profile: ShippingOrderDocumentProfile) -> ShippingOrderDocumentProfileDraftRevision:
|
||||
"""读取与当前草稿 checksum 完全一致的 Revision。"""
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id, definition_checksum=profile.structure_fingerprint,
|
||||
).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
|
||||
if revision is None:
|
||||
raise ValidationError('Draft revision is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_REVISION_NOT_FOUND')
|
||||
return revision
|
||||
|
||||
|
||||
def _payload(row: ShippingOrderDocumentProfilePublishCheckReport) -> dict[str, Any]:
|
||||
"""返回报告安全投影,不返回 PDF、盲测真值或原始审计详情。"""
|
||||
return {'id': row.id, 'report_no': row.report_no, 'profile_id': row.profile_id, 'revision_no': row.revision_no,
|
||||
'definition_checksum': row.definition_checksum, 'lock_version': row.lock_version, 'validation_run_id': row.validation_run_id,
|
||||
'status': row.status, 'expires_reason': row.expires_reason, 'semantic_diff': dict(row.semantic_diff_json or {}),
|
||||
'blocking_items': list(row.blocking_items_json or []), 'warning_items': list(row.warning_items_json or []),
|
||||
'confirmed_warning_keys': list(row.confirmed_warning_keys_json or []), 'operation_id': row.operation_id,
|
||||
'created_at': row.created_at.isoformat(), 'consumed_at': row.consumed_at.isoformat() if row.consumed_at else None}
|
||||
|
||||
|
||||
def _invalidate_if_changed(row: ShippingOrderDocumentProfilePublishCheckReport, profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""将草稿有效变化显式固化为报告失效,避免旧报告被误消费。"""
|
||||
if row.status == 'valid' and (row.definition_checksum != profile.structure_fingerprint or row.lock_version != profile.lock_version):
|
||||
row.status, row.expires_reason = 'invalidated', 'draft_changed'
|
||||
profile_service._audit(profile_id=profile.id, event_type='publish_check_invalidated', actor_id=None, operation_id=row.operation_id,
|
||||
revision_no=row.revision_no, detail={'report_id': row.id, 'reason': 'draft_changed'})
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None, browser_session_id: str | None, lease_token: str | None, operation_id: str) -> dict[str, Any]:
|
||||
"""生成冻结当前草稿和通过验证运行的发布检查报告;阻断项只可修复不能确认绕过。"""
|
||||
profile = _profile(profile_id)
|
||||
lease_service.require_active_lease(profile.id, actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token)
|
||||
op = str(operation_id or secrets.token_hex(16))
|
||||
existing = ShippingOrderDocumentProfilePublishCheckReport.query.filter_by(profile_id=profile.id, operation_id=op).one_or_none()
|
||||
if existing is not None:
|
||||
_invalidate_if_changed(existing, profile)
|
||||
db.session.commit()
|
||||
return _payload(existing)
|
||||
revision = _current_revision(profile)
|
||||
run_id = data.get('validation_run_id')
|
||||
validation = db.session.get(ShippingOrderDocumentProfileValidationRun, int(run_id)) if str(run_id or '').isdigit() else None
|
||||
blocking: list[dict[str, Any]] = []
|
||||
if validation is None or validation.profile_id != profile.id or validation.status != 'passed' or validation.definition_checksum != revision.definition_checksum:
|
||||
blocking.append({'key': 'current_validation_required', 'message': 'A passing validation run for the current draft is required.'})
|
||||
try:
|
||||
from app.services.shipping_notice.document_profile_quality_service import assert_profile_publishable
|
||||
assert_profile_publishable(profile)
|
||||
except Exception as exc:
|
||||
blocking.append({'key': getattr(exc, 'code', 'publish_prerequisite_failed'), 'message': 'Blind-test or profile publish prerequisites are not satisfied.'})
|
||||
previous = ShippingOrderDocumentProfile.query.filter_by(profile_code=profile.profile_code, status='published').first()
|
||||
semantic_diff = diff_service.get_profile_diff(profile.id, against_profile_id=previous.id if previous else None)
|
||||
warnings = [{'key': 'semantic_diff_review', 'message': 'Semantic changes must be reviewed before publication.'}] if semantic_diff.get('changes') else []
|
||||
row = ShippingOrderDocumentProfilePublishCheckReport(
|
||||
report_no=f'OPPC-{secrets.token_hex(8).upper()}', profile_id=profile.id, revision_no=revision.revision_no,
|
||||
definition_checksum=revision.definition_checksum, lock_version=profile.lock_version, validation_run_id=validation.id if validation else None,
|
||||
base_published_profile_id=previous.id if previous else None, semantic_diff_json=semantic_diff, blocking_items_json=blocking,
|
||||
warning_items_json=warnings, confirmed_warning_keys_json=[], status='valid', operation_id=op, actor_id=actor_id,
|
||||
)
|
||||
db.session.add(row)
|
||||
profile_service._audit(profile_id=profile.id, event_type='publish_check_created', actor_id=actor_id, operation_id=op, revision_no=revision.revision_no,
|
||||
detail={'report_no': row.report_no, 'validation_run_id': row.validation_run_id, 'blocking_count': len(blocking), 'warning_count': len(warnings)})
|
||||
db.session.commit()
|
||||
return _payload(row)
|
||||
|
||||
|
||||
def get_report(profile_id: int, report_no: str) -> dict[str, Any]:
|
||||
"""读取报告并在发现草稿变化时立刻持久化失效状态。"""
|
||||
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')
|
||||
row = ShippingOrderDocumentProfilePublishCheckReport.query.filter_by(profile_id=profile.id, report_no=str(report_no)).one_or_none()
|
||||
if row is None:
|
||||
raise NotFoundError('Publish check report not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
if profile.status == 'draft' and _invalidate_if_changed(row, profile):
|
||||
db.session.commit()
|
||||
return _payload(row)
|
||||
|
||||
|
||||
def consume_report(profile_id: int, report_no: str, *, data: dict[str, Any], actor_id: int | None, browser_session_id: str | None, lease_token: str | None, operation_id: str) -> dict[str, Any]:
|
||||
"""逐项确认警告后在同一事务消费报告并发布;重试已消费报告直接返回同一版本。"""
|
||||
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')
|
||||
row = ShippingOrderDocumentProfilePublishCheckReport.query.filter_by(profile_id=profile.id, report_no=str(report_no)).with_for_update().one_or_none()
|
||||
if row is None:
|
||||
raise NotFoundError('Publish check report not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
if row.status == 'consumed':
|
||||
return profile_service.payload(profile)
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Publish check report is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
lease_service.require_active_lease(profile.id, actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token)
|
||||
if _invalidate_if_changed(row, profile) or row.status != 'valid':
|
||||
db.session.commit()
|
||||
raise ConflictError('Publish check report is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
if row.blocking_items_json:
|
||||
raise ValidationError('Publish check has blocking items', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
confirmed = {str(item) for item in data.get('confirmed_warning_keys') or []}
|
||||
required = {str(item.get('key')) for item in row.warning_items_json or []}
|
||||
if confirmed != required:
|
||||
raise ValidationError('Each publish warning must be confirmed', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
try:
|
||||
published = profile_service.publish(profile.id, actor_id=actor_id, expected_lock_version=row.lock_version, commit=False)
|
||||
row.confirmed_warning_keys_json, row.status, row.consumed_at = sorted(confirmed), 'consumed', datetime.utcnow()
|
||||
profile_service._audit(profile_id=profile.id, event_type='publish_check_consumed', actor_id=actor_id,
|
||||
operation_id=str(operation_id or row.operation_id), revision_no=row.revision_no, detail={'report_no': row.report_no})
|
||||
lease = ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile.id).one_or_none()
|
||||
if lease is not None:
|
||||
db.session.delete(lease)
|
||||
db.session.commit()
|
||||
return published
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_revision_service.py
|
||||
|
||||
用途:提供订单模板草稿 Revision 的查询与恢复。
|
||||
依赖:Profile、DraftRevision、Profile 保存服务和编辑租约服务。
|
||||
逻辑:恢复只读取旧快照并作为新的有效保存写入,历史 Revision 绝不覆盖或删除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileDraftRevision
|
||||
|
||||
|
||||
def _payload(row: ShippingOrderDocumentProfileDraftRevision) -> dict[str, Any]:
|
||||
"""序列化不可变修订元数据;列表不返回完整定义快照。"""
|
||||
return {
|
||||
'revision_no': int(row.revision_no),
|
||||
'profile_id': int(row.profile_id),
|
||||
'base_lock_version': int(row.base_lock_version),
|
||||
'result_lock_version': int(row.result_lock_version),
|
||||
'definition_checksum': row.definition_checksum,
|
||||
'change_source': row.change_source,
|
||||
'actor_id': int(row.actor_id) if row.actor_id else None,
|
||||
'browser_session_id': row.browser_session_id,
|
||||
'operation_id': row.operation_id,
|
||||
'change_summary': dict(row.change_summary_json or {}),
|
||||
'created_at': row.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def list_revisions(profile_id: int) -> list[dict[str, Any]]:
|
||||
"""返回草稿的修订序列,按修订号倒序供历史面板加载。"""
|
||||
if db.session.get(ShippingOrderDocumentProfile, int(profile_id)) is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return [_payload(row) for row in ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=int(profile_id)).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).all()]
|
||||
|
||||
|
||||
def restore_revision(
|
||||
profile_id: int, revision_no: int, *, actor_id: int | None, browser_session_id: str,
|
||||
lease_token: str, expected_lock_version: int, operation_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""恢复旧 Revision 为新的草稿保存,确保恢复动作也形成新的不可变历史。"""
|
||||
row = ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=int(profile_id), revision_no=int(revision_no)).one_or_none()
|
||||
if row is None:
|
||||
raise NotFoundError('Draft revision not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_REVISION_NOT_FOUND')
|
||||
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')
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
return profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile.profile_code,
|
||||
'display_name': profile.display_name,
|
||||
'schema_version_id': profile.schema_version_id,
|
||||
'definition': dict(row.definition_snapshot_json or {}),
|
||||
'expected_lock_version': int(expected_lock_version),
|
||||
'change_note': f'Restored revision {int(revision_no)}',
|
||||
},
|
||||
actor_id=actor_id,
|
||||
profile_id=int(profile_id),
|
||||
browser_session_id=browser_session_id,
|
||||
lease_token=lease_token,
|
||||
operation_id=operation_id,
|
||||
change_source='restore',
|
||||
enforce_lease=True,
|
||||
)
|
||||
@@ -25,12 +25,14 @@ from app.core.errors import ServiceUnavailableError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingDocumentProfileTestSample,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
@@ -71,6 +73,65 @@ def _definition_hash(definition: dict[str, Any]) -> str:
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> bool:
|
||||
"""判断样本是否具备历史只读所需的冻结证据;旧空字段不得伪装成可审计版本。"""
|
||||
required = (
|
||||
sample.layout_version_id,
|
||||
sample.source_content_hash,
|
||||
sample.layout_payload_checksum,
|
||||
sample.layout_contract_version,
|
||||
sample.parser_key,
|
||||
sample.parser_name,
|
||||
sample.evidence_frozen_at,
|
||||
)
|
||||
return all(required)
|
||||
|
||||
|
||||
def _sample_payload(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]:
|
||||
"""返回不含正文的样本摘要,并显式暴露冻结证据状态。"""
|
||||
return {
|
||||
'id': sample.id,
|
||||
'document_id': sample.document_id,
|
||||
'table_id': sample.table_id,
|
||||
'sample_role': sample.sample_role,
|
||||
'created_at': sample.created_at.isoformat(),
|
||||
'frozen_evidence_ready': _sample_frozen_evidence_ready(sample),
|
||||
'layout_version_id': sample.layout_version_id,
|
||||
'source_content_hash': sample.source_content_hash,
|
||||
'layout_payload_checksum': sample.layout_payload_checksum,
|
||||
'layout_contract_version': sample.layout_contract_version,
|
||||
'parser_key': sample.parser_key,
|
||||
'parser_name': sample.parser_name,
|
||||
'parser_version': sample.parser_version,
|
||||
'source_filename_snapshot': sample.source_filename_snapshot,
|
||||
'page_count_snapshot': sample.page_count_snapshot,
|
||||
'table_identity_snapshot': dict(sample.table_identity_snapshot or {}) or None,
|
||||
'evidence_frozen_at': sample.evidence_frozen_at.isoformat() if sample.evidence_frozen_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _profile_frozen_evidence_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""汇总模板冻结证据完整度,供版本中心明确标出历史记录是否可审计。"""
|
||||
samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
|
||||
total_count = len(samples)
|
||||
ready_count = sum(1 for item in samples if _sample_frozen_evidence_ready(item))
|
||||
immutable = profile.status in {'published', 'retired'}
|
||||
if not immutable:
|
||||
status = 'pending'
|
||||
elif total_count == 0:
|
||||
status = 'missing'
|
||||
elif ready_count == total_count:
|
||||
status = 'ready'
|
||||
else:
|
||||
status = 'missing'
|
||||
return {
|
||||
'status': status,
|
||||
'sample_count': total_count,
|
||||
'frozen_sample_count': ready_count,
|
||||
'audit_ready': immutable and total_count > 0 and ready_count == total_count,
|
||||
}
|
||||
|
||||
|
||||
def _match_summary(definition: dict[str, Any]) -> dict[str, Any]:
|
||||
"""提取无文字锚点的匹配策略摘要,供查询索引和审计展示而不泄露文档内容。"""
|
||||
match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
|
||||
@@ -84,11 +145,25 @@ def _match_summary(definition: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _audit(*, profile_id: int | None, event_type: str, actor_id: int | None, document_id: int | None = None, detail: dict[str, Any] | None = None) -> None:
|
||||
def _audit(
|
||||
*,
|
||||
profile_id: int | None,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
document_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
browser_session_id: str | None = None,
|
||||
revision_no: int | None = None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""追加 Profile 操作审计;detail 只保存身份、数量、版本和 checksum 等非敏感摘要。"""
|
||||
db.session.add(ShippingOrderDocumentProfileAudit(
|
||||
profile_id=profile_id, document_id=document_id, event_type=event_type,
|
||||
actor_id=actor_id, detail_json=detail or {},
|
||||
actor_id=actor_id, request_id=str(request_id or '').strip() or None,
|
||||
operation_id=str(operation_id or '').strip() or None,
|
||||
browser_session_id=str(browser_session_id or '').strip() or None,
|
||||
revision_no=revision_no, detail_json=detail or {},
|
||||
))
|
||||
|
||||
|
||||
@@ -383,6 +458,7 @@ def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
'training_sample_count': profile.training_sample_count,
|
||||
'match_strategy_summary': dict(profile.match_strategy_summary_json or {}),
|
||||
'schema_compatibility': compatibility,
|
||||
'frozen_evidence': _profile_frozen_evidence_summary(profile),
|
||||
'migration_status': (
|
||||
'needs_revalidation'
|
||||
if (
|
||||
@@ -409,10 +485,7 @@ def list_profile_samples(profile_id: int) -> list[dict[str, Any]]:
|
||||
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')
|
||||
return [{
|
||||
'id': item.id, 'document_id': item.document_id, 'table_id': item.table_id,
|
||||
'sample_role': item.sample_role, 'created_at': item.created_at.isoformat(),
|
||||
} for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by(
|
||||
return [_sample_payload(item) for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileSample.id.asc(),
|
||||
).all()]
|
||||
|
||||
@@ -780,6 +853,116 @@ def _document_layout(document: ShippingNoticeDocument) -> dict[str, Any]:
|
||||
return layout
|
||||
|
||||
|
||||
def _current_ready_layout_version(document: ShippingNoticeDocument) -> ShippingDocumentLayoutVersion:
|
||||
"""读取发布时可冻结的 ready Layout 版本;历史详情必须依赖该实体而非最新解析结果。"""
|
||||
version = document.current_layout_version
|
||||
if (
|
||||
version is None
|
||||
or str(version.status or '') != 'ready'
|
||||
or not isinstance(version.payload_json, dict)
|
||||
):
|
||||
raise ConflictError(
|
||||
'Profile sample has no ready layout to freeze',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
return version
|
||||
|
||||
|
||||
def _layout_page_count(payload: dict[str, Any]) -> int | None:
|
||||
"""生成安全页数摘要;优先读取 payload 自带 pages,其次回退到表格页号统计。"""
|
||||
pages = payload.get('pages')
|
||||
if isinstance(pages, list) and pages:
|
||||
return len([item for item in pages if isinstance(item, dict)])
|
||||
evidence_pages = ((payload.get('coordinate_evidence') or {}).get('pages') or {})
|
||||
if isinstance(evidence_pages, dict) and evidence_pages:
|
||||
return len(evidence_pages)
|
||||
table_pages = {
|
||||
int(item.get('page_no'))
|
||||
for item in (payload.get('tables') or [])
|
||||
if isinstance(item, dict) and isinstance(item.get('page_no'), int)
|
||||
}
|
||||
return len(table_pages) or None
|
||||
|
||||
|
||||
def _layout_table_identity_snapshot(payload: dict[str, Any], table_id: str | None) -> dict[str, Any] | None:
|
||||
"""提取安全表格身份摘要,供历史版本详情恢复样本入口而不暴露正文。"""
|
||||
safe_table_id = str(table_id or '').strip()
|
||||
if not safe_table_id:
|
||||
return None
|
||||
raw_table = next(
|
||||
(
|
||||
item for item in (payload.get('tables') or [])
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == safe_table_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if raw_table is None:
|
||||
raise ConflictError(
|
||||
'Profile sample table is unavailable for evidence freeze',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
return {
|
||||
'table_id': safe_table_id,
|
||||
'page_no': raw_table.get('page_no'),
|
||||
'row_count': len(raw_table.get('rows') or []) if isinstance(raw_table.get('rows'), list) else None,
|
||||
}
|
||||
|
||||
|
||||
def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, frozen_at: datetime) -> int:
|
||||
"""在发布事务内冻结建模样本的 Layout/Schema/Parser 身份,避免历史画布读取漂移。"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload
|
||||
|
||||
samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileSample.id.asc(),
|
||||
).all()
|
||||
if not samples:
|
||||
raise ConflictError(
|
||||
'At least one profile sample is required before publishing',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
for sample in samples:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
if document is None:
|
||||
raise ConflictError(
|
||||
'Profile sample document is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
layout_version = _current_ready_layout_version(document)
|
||||
content_hash = str(document.content_hash or '').strip().lower()
|
||||
layout_hash = str(layout_version.source_content_hash or '').strip().lower()
|
||||
if len(content_hash) != 64 or len(layout_hash) != 64 or content_hash != layout_hash:
|
||||
raise ConflictError(
|
||||
'Profile sample content no longer matches the ready layout',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
payload_checksum = str(layout_version.payload_checksum or '').strip().lower()
|
||||
if len(payload_checksum) != 64:
|
||||
raise ConflictError(
|
||||
'Profile sample layout checksum is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
actual_checksum, _ = canonical_layout_payload(layout_version.payload_json)
|
||||
if actual_checksum != payload_checksum:
|
||||
raise ConflictError(
|
||||
'Profile sample layout checksum no longer matches the stored payload',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
sample.layout_version_id = layout_version.id
|
||||
sample.source_content_hash = layout_hash
|
||||
sample.layout_payload_checksum = payload_checksum
|
||||
sample.layout_contract_version = str(layout_version.contract_version or '').strip() or None
|
||||
sample.parser_key = str(layout_version.parser_key or '').strip() or None
|
||||
sample.parser_name = str(layout_version.parser_name or '').strip() or None
|
||||
sample.parser_version = str(layout_version.parser_version or '').strip() or None
|
||||
sample.evidence_frozen_at = frozen_at
|
||||
sample.source_filename_snapshot = str(document.filename or '').strip() or None
|
||||
sample.page_count_snapshot = _layout_page_count(layout_version.payload_json or {})
|
||||
sample.table_identity_snapshot = _layout_table_identity_snapshot(
|
||||
layout_version.payload_json or {}, sample.table_id,
|
||||
)
|
||||
return len(samples)
|
||||
|
||||
|
||||
def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[str, Any]]:
|
||||
"""读取当前布局冻结的整表原生字符;向浏览器只返回重建后的网格,不泄露坐标。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
@@ -1678,6 +1861,8 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
|
||||
|
||||
def create_draft_from_sample(
|
||||
data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None,
|
||||
browser_session_id: str | None = None, lease_token: str | None = None,
|
||||
operation_id: str | None = None, enforce_lease: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按管理员确认的 v2 坐标定义生成 Profile 草稿。
|
||||
@@ -1709,7 +1894,8 @@ def create_draft_from_sample(
|
||||
'definition': data['definition'],
|
||||
'change_note': data.get('change_note'),
|
||||
'expected_lock_version': data.get('expected_lock_version'),
|
||||
}, actor_id=actor_id, profile_id=profile_id)
|
||||
}, actor_id=actor_id, profile_id=profile_id, browser_session_id=browser_session_id,
|
||||
lease_token=lease_token, operation_id=operation_id, enforce_lease=enforce_lease)
|
||||
if ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=saved['id'], document_id=document.id, sample_role='annotation',
|
||||
).first() is None:
|
||||
@@ -1726,10 +1912,32 @@ def create_draft_from_sample(
|
||||
|
||||
def save_draft(
|
||||
data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None,
|
||||
browser_session_id: str | None = None, lease_token: str | None = None,
|
||||
operation_id: str | None = None, change_source: str = 'manual_save',
|
||||
enforce_lease: bool = False, commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""创建或整体替换草稿;更新要求乐观锁一致,发布版本不可修改。"""
|
||||
"""
|
||||
创建或整体替换草稿,并在有效写入后追加不可变 Revision。
|
||||
|
||||
Args:
|
||||
data: 经服务端规范化前的 Profile 草稿定义与乐观锁。
|
||||
actor_id: 当前操作者身份。
|
||||
profile_id: 更新目标;省略时创建新草稿。
|
||||
browser_session_id: 编辑器标签身份;启用租约检查时必填。
|
||||
lease_token: 编辑租约原始令牌;仅用于即时校验。
|
||||
operation_id: 串联审计与 Revision 的业务动作身份。
|
||||
change_source: 保存来源,恢复操作必须传入 restore。
|
||||
enforce_lease: 为 True 时更新必须持有当前单写者租约。
|
||||
commit: 为 False 时由外层业务事务统一提交,仅供创建向导等原子编排使用。
|
||||
|
||||
Returns:
|
||||
不含敏感定义外部证据的 Profile DTO,附带本次 Revision 摘要。
|
||||
"""
|
||||
operation = str(operation_id or secrets.token_hex(16)).strip()
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id) if profile_id else None
|
||||
previous_definition = dict(profile.definition_json or {}) if profile is not None else None
|
||||
previous_display_name = str(profile.display_name or '') if profile is not None else ''
|
||||
previous_change_note = str(profile.change_note or '') if profile is not None else ''
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile is not None and profile.status != 'draft':
|
||||
@@ -1755,6 +1963,11 @@ def save_draft(
|
||||
data.get('schema_version_id', profile.schema_version_id if profile else None),
|
||||
)
|
||||
if profile is not None:
|
||||
if enforce_lease:
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
lease_service.require_active_lease(
|
||||
profile.id, actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token,
|
||||
)
|
||||
expected = data.get('expected_lock_version')
|
||||
if not isinstance(expected, int):
|
||||
raise ValidationError(
|
||||
@@ -1773,6 +1986,18 @@ def save_draft(
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE',
|
||||
)
|
||||
definition = _normalize_definition(data.get('definition'), schema_version=schema_version)
|
||||
definition_checksum = _definition_hash(definition)
|
||||
next_display_name = str(data.get('display_name') or profile.display_name or code).strip()
|
||||
next_change_note = str(data.get('change_note') or '').strip()
|
||||
prior_operation_revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id if profile is not None else -1, operation_id=operation,
|
||||
).one_or_none()
|
||||
if prior_operation_revision is not None and prior_operation_revision.definition_checksum != definition_checksum:
|
||||
raise ConflictError(
|
||||
'Operation id was already used for a different draft definition',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
)
|
||||
base_lock_version = int(profile.lock_version) if profile is not None else 0
|
||||
if profile is None:
|
||||
version = int(db.session.query(func.max(ShippingOrderDocumentProfile.version)).filter_by(
|
||||
profile_code=code,
|
||||
@@ -1786,13 +2011,19 @@ def save_draft(
|
||||
)
|
||||
db.session.add(profile)
|
||||
else:
|
||||
profile.lock_version += 1
|
||||
profile.display_name = str(data.get('display_name') or profile.display_name or code).strip()
|
||||
profile.structure_fingerprint = _definition_hash(definition)
|
||||
# checksum 相同表示重试或无有效变化:不递增锁、不新增 Revision。
|
||||
if (
|
||||
profile.structure_fingerprint != definition_checksum
|
||||
or previous_display_name != next_display_name
|
||||
or previous_change_note != next_change_note
|
||||
):
|
||||
profile.lock_version += 1
|
||||
profile.display_name = next_display_name
|
||||
profile.structure_fingerprint = definition_checksum
|
||||
profile.definition_json = definition
|
||||
profile.template_mode = 'coordinate_v2'
|
||||
profile.match_strategy_summary_json = _match_summary(definition)
|
||||
profile.change_note = str(data.get('change_note') or '').strip() or None
|
||||
profile.change_note = next_change_note or None
|
||||
db.session.flush()
|
||||
_refresh_training_sample_count(profile)
|
||||
audit_summary = _definition_audit_summary(definition)
|
||||
@@ -1812,12 +2043,60 @@ def save_draft(
|
||||
_audit(profile_id=profile.id, event_type='field_bindings_changed', actor_id=actor_id, detail={
|
||||
'bound_field_count': audit_summary['bound_field_count'],
|
||||
})
|
||||
_audit(profile_id=profile.id, event_type='draft_saved', actor_id=actor_id, detail={
|
||||
retry_revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id, operation_id=operation,
|
||||
).one_or_none()
|
||||
latest_revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id, definition_checksum=profile.structure_fingerprint,
|
||||
).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
|
||||
revision = retry_revision
|
||||
# 从已发布版本复制出的草稿在治理迁移前没有历史 Revision;首次保存必须补建可恢复基线。
|
||||
has_effective_change = (
|
||||
previous_definition is None
|
||||
or previous_definition != definition
|
||||
or previous_display_name != next_display_name
|
||||
or previous_change_note != next_change_note
|
||||
or change_source == 'restore'
|
||||
or latest_revision is None
|
||||
)
|
||||
if revision is None and has_effective_change:
|
||||
next_revision_no = int(db.session.query(func.max(ShippingOrderDocumentProfileDraftRevision.revision_no)).filter_by(
|
||||
profile_id=profile.id,
|
||||
).scalar() or 0) + 1
|
||||
revision = ShippingOrderDocumentProfileDraftRevision(
|
||||
profile_id=profile.id,
|
||||
revision_no=next_revision_no,
|
||||
base_lock_version=base_lock_version,
|
||||
result_lock_version=profile.lock_version,
|
||||
definition_checksum=profile.structure_fingerprint,
|
||||
change_source=str(change_source or 'manual_save'),
|
||||
actor_id=actor_id,
|
||||
browser_session_id=str(browser_session_id or '').strip() or None,
|
||||
operation_id=operation,
|
||||
change_summary_json=audit_summary,
|
||||
definition_snapshot_json=dict(definition),
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.flush()
|
||||
elif revision is None:
|
||||
revision = latest_revision
|
||||
if revision is None:
|
||||
# 新草稿必有有效定义;此分支仅防御未来调用方绕过定义变更检测。
|
||||
raise ValidationError('Draft revision could not be created', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
_audit(profile_id=profile.id, event_type='draft_saved', actor_id=actor_id, operation_id=operation,
|
||||
browser_session_id=str(browser_session_id or '').strip() or None, revision_no=revision.revision_no, detail={
|
||||
'lock_version': profile.lock_version, 'definition_checksum': profile.structure_fingerprint,
|
||||
**audit_summary,
|
||||
})
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
result = payload(profile)
|
||||
result['draft_revision'] = {
|
||||
'revision_no': revision.revision_no,
|
||||
'definition_checksum': revision.definition_checksum,
|
||||
'operation_id': revision.operation_id,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
@@ -1854,11 +2133,31 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
)
|
||||
db.session.add(clone)
|
||||
db.session.flush()
|
||||
revision = ShippingOrderDocumentProfileDraftRevision(
|
||||
profile_id=clone.id,
|
||||
revision_no=1,
|
||||
base_lock_version=0,
|
||||
result_lock_version=clone.lock_version,
|
||||
definition_checksum=clone.structure_fingerprint,
|
||||
change_source='wizard_created',
|
||||
actor_id=actor_id,
|
||||
browser_session_id=None,
|
||||
operation_id=secrets.token_hex(16),
|
||||
change_summary_json=_definition_audit_summary(clone.definition_json),
|
||||
definition_snapshot_json=dict(clone.definition_json or {}),
|
||||
)
|
||||
db.session.add(revision)
|
||||
_audit(profile_id=clone.id, event_type='draft_cloned', actor_id=actor_id, detail={
|
||||
'source_profile_id': source.id, 'version': clone.version,
|
||||
'source_profile_id': source.id, 'version': clone.version, 'revision_no': revision.revision_no,
|
||||
})
|
||||
db.session.commit()
|
||||
return payload(clone)
|
||||
result = payload(clone)
|
||||
result['draft_revision'] = {
|
||||
'revision_no': revision.revision_no,
|
||||
'definition_checksum': revision.definition_checksum,
|
||||
'operation_id': revision.operation_id,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def create_schema_migration_draft(
|
||||
@@ -2048,78 +2347,95 @@ def create_schema_migration_draft(
|
||||
|
||||
|
||||
def publish(
|
||||
profile_id: int, *, actor_id: int | None, expected_lock_version: Any,
|
||||
profile_id: int, *, actor_id: int | None, expected_lock_version: Any, commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""发布草稿并原子退役同编码旧版本;checksum 包含 Schema 身份与完整定义。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError(
|
||||
'Only draft order document profile can be published',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
"""发布草稿并原子退役同编码旧版本;commit=False 时由发布报告消费事务统一提交。"""
|
||||
try:
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError(
|
||||
'Only draft order document profile can be published',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
if not isinstance(expected_lock_version, int):
|
||||
raise ValidationError(
|
||||
'expected_lock_version is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED',
|
||||
)
|
||||
if expected_lock_version != profile.lock_version:
|
||||
raise ConflictError(
|
||||
'Order document profile draft was changed by another user',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
)
|
||||
if any(
|
||||
item.get('requires_rebinding')
|
||||
for table in (profile.definition_json or {}).get('table_regions', [])
|
||||
if isinstance(table, dict)
|
||||
for item in (table.get('draft_unbound_field_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
):
|
||||
raise ValidationError(
|
||||
'All draft field regions must be bound before publish',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
if (profile.definition_json or {}).get('draft_unbound_order_field_layouts'):
|
||||
raise ValidationError(
|
||||
'All draft order field layouts must be bound before publish',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
# 发布必须先通过训练/盲测门禁;自动冻结资格仍在发布后从 manual_confirmation 起步。
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
assert_profile_publishable,
|
||||
ensure_manual_confirmation_qualification,
|
||||
promote_approved_suite_for_publish,
|
||||
)
|
||||
if not isinstance(expected_lock_version, int):
|
||||
raise ValidationError(
|
||||
'expected_lock_version is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_REQUIRED',
|
||||
)
|
||||
if expected_lock_version != profile.lock_version:
|
||||
raise ConflictError(
|
||||
'Order document profile draft was changed by another user',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
|
||||
)
|
||||
if any(
|
||||
item.get('requires_rebinding')
|
||||
for table in (profile.definition_json or {}).get('table_regions', [])
|
||||
if isinstance(table, dict)
|
||||
for item in (table.get('draft_unbound_field_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
):
|
||||
raise ValidationError(
|
||||
'All draft field regions must be bound before publish',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
if (profile.definition_json or {}).get('draft_unbound_order_field_layouts'):
|
||||
raise ValidationError(
|
||||
'All draft order field layouts must be bound before publish',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
# 发布只校验模板定义;自动冻结资格由独立的质量发布流程维护。
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
ensure_manual_confirmation_qualification,
|
||||
)
|
||||
|
||||
schema_version = _require_schema_version(profile.schema_version_id)
|
||||
normalized = _normalize_definition(profile.definition_json, schema_version=schema_version)
|
||||
profile.definition_json = normalized
|
||||
profile.structure_fingerprint = _definition_hash(normalized)
|
||||
_definition_contract(profile)
|
||||
encoded = json.dumps({
|
||||
'profile_code': profile.profile_code,
|
||||
'version': profile.version,
|
||||
'schema_version_id': schema_version.id,
|
||||
'schema_checksum': schema_version.checksum,
|
||||
'definition': normalized,
|
||||
}, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
now = datetime.utcnow()
|
||||
previous = ShippingOrderDocumentProfile.query.filter_by(
|
||||
profile_code=profile.profile_code, status='published',
|
||||
).first()
|
||||
if previous is not None:
|
||||
previous.status = 'retired'
|
||||
previous.retired_at = now
|
||||
db.session.flush()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
profile.status = 'published'
|
||||
profile.published_by_id = actor_id
|
||||
profile.published_at = now
|
||||
ensure_manual_confirmation_qualification(profile)
|
||||
_audit(profile_id=profile.id, event_type='published', actor_id=actor_id, detail={
|
||||
'checksum': profile.checksum, 'version': profile.version,
|
||||
})
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
schema_version = _require_schema_version(profile.schema_version_id)
|
||||
normalized = _normalize_definition(profile.definition_json, schema_version=schema_version)
|
||||
profile.definition_json = normalized
|
||||
profile.structure_fingerprint = _definition_hash(normalized)
|
||||
draft_checksum = str(profile.structure_fingerprint or '')
|
||||
_definition_contract(profile)
|
||||
assert_profile_publishable(profile)
|
||||
encoded = json.dumps({
|
||||
'profile_code': profile.profile_code,
|
||||
'version': profile.version,
|
||||
'schema_version_id': schema_version.id,
|
||||
'schema_checksum': schema_version.checksum,
|
||||
'definition': normalized,
|
||||
}, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
now = datetime.utcnow()
|
||||
frozen_sample_count = _freeze_profile_sample_evidence(profile, frozen_at=now)
|
||||
previous = ShippingOrderDocumentProfile.query.filter_by(
|
||||
profile_code=profile.profile_code, status='published',
|
||||
).first()
|
||||
if previous is not None:
|
||||
previous.status = 'retired'
|
||||
previous.retired_at = now
|
||||
db.session.flush()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
promote_approved_suite_for_publish(
|
||||
profile=profile,
|
||||
draft_checksum=draft_checksum,
|
||||
published_checksum=str(profile.checksum or ''),
|
||||
)
|
||||
profile.status = 'published'
|
||||
profile.published_by_id = actor_id
|
||||
profile.published_at = now
|
||||
ensure_manual_confirmation_qualification(profile)
|
||||
_audit(profile_id=profile.id, event_type='published', actor_id=actor_id, detail={
|
||||
'checksum': profile.checksum, 'version': profile.version,
|
||||
'frozen_sample_count': frozen_sample_count,
|
||||
})
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
except Exception:
|
||||
if commit:
|
||||
db.session.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]:
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_suggestion_service.py
|
||||
|
||||
用途:冻结订单模板算法建议的接受、调整接受或拒绝决定。
|
||||
依赖:Profile 草稿、Revision、编辑租约、SuggestionDecision ORM 与统一错误。
|
||||
逻辑:编辑器先呈现本地建议,再以建议摘要 checksum 写入不可变决定;服务端只记录决定事实,不替换 Profile 定义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocumentProfileSuggestionDecision,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
def suggestion_identity(summary: dict[str, Any]) -> dict[str, str]:
|
||||
"""根据无敏感建议摘要生成稳定身份;相同算法输出可幂等记录同一决定。"""
|
||||
encoded = json.dumps(summary, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
checksum = hashlib.sha256(encoded).hexdigest()
|
||||
return {'suggestion_id': checksum[:32], 'suggestion_checksum': checksum}
|
||||
|
||||
|
||||
def decide(
|
||||
profile_id: int, *, data: dict[str, Any], actor_id: int | None,
|
||||
browser_session_id: str | None, lease_token: str | None, operation_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
记录一个冻结建议决定。
|
||||
|
||||
Args:
|
||||
profile_id: 目标草稿 ID,发布版本不可决定。
|
||||
data: 必须含 suggestion_summary、suggestion_id、suggestion_checksum 和 decision;可含 adjustment_summary。
|
||||
actor_id: 当前管理员身份。
|
||||
browser_session_id: 当前编辑标签身份。
|
||||
lease_token: 当前编辑租约令牌。
|
||||
operation_id: 本次决定的审计链路身份。
|
||||
|
||||
Returns:
|
||||
不包含文档内容的不可变决定 DTO。
|
||||
"""
|
||||
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 != 'draft':
|
||||
raise ConflictError('Profile is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE')
|
||||
lease_service.require_active_lease(profile.id, actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token)
|
||||
summary = data.get('suggestion_summary')
|
||||
if not isinstance(summary, dict):
|
||||
raise ValidationError('suggestion_summary is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
identity = suggestion_identity(summary)
|
||||
if data.get('suggestion_id') != identity['suggestion_id'] or data.get('suggestion_checksum') != identity['suggestion_checksum']:
|
||||
raise ValidationError('Suggestion identity is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
decision = str(data.get('decision') or '')
|
||||
if decision not in {'accepted', 'accepted_adjusted', 'rejected'}:
|
||||
raise ValidationError('Suggestion decision is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if decision == 'accepted_adjusted' and not isinstance(data.get('adjustment_summary'), dict):
|
||||
raise ValidationError('adjustment_summary is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
prior = ShippingOrderDocumentProfileSuggestionDecision.query.filter_by(profile_id=profile.id, suggestion_id=identity['suggestion_id']).one_or_none()
|
||||
if prior is not None:
|
||||
if prior.decision != decision:
|
||||
raise ConflictError('Suggestion already has a different decision', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_CONFLICT')
|
||||
return _payload(prior)
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile.id).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
|
||||
if revision is None:
|
||||
raise ConflictError('Draft revision is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_REVISION_NOT_FOUND')
|
||||
sample = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id, sample_role='annotation').first()
|
||||
item = ShippingOrderDocumentProfileSuggestionDecision(
|
||||
profile_id=profile.id, revision_no=revision.revision_no, sample_binding_id=sample.id if sample else None,
|
||||
layout_version_id=sample.layout_version_id if sample else None, parser_key=sample.parser_key if sample else None,
|
||||
parser_version=sample.parser_version if sample else None, schema_version_id=profile.schema_version_id,
|
||||
algorithm_version=str(summary.get('algorithm_version') or 'coordinate-suggest-v1')[:64], suggestion_id=identity['suggestion_id'],
|
||||
suggestion_checksum=identity['suggestion_checksum'], decision=decision, actor_id=actor_id, operation_id=operation_id,
|
||||
detail_json={'kind': str(summary.get('kind') or 'region'), 'adjustment_summary': data.get('adjustment_summary') if decision == 'accepted_adjusted' else None},
|
||||
)
|
||||
db.session.add(item)
|
||||
profile_service._audit(profile_id=profile.id, event_type='suggestion_decided', actor_id=actor_id, browser_session_id=browser_session_id, operation_id=operation_id, revision_no=revision.revision_no, detail={'suggestion_id': identity['suggestion_id'], 'decision': decision, 'algorithm_version': item.algorithm_version})
|
||||
db.session.commit()
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def _payload(item: ShippingOrderDocumentProfileSuggestionDecision) -> dict[str, Any]:
|
||||
"""序列化安全决定 DTO,不返回建议正文、样本正文或坐标。"""
|
||||
return {'id': item.id, 'profile_id': item.profile_id, 'revision_no': item.revision_no, 'suggestion_id': item.suggestion_id, 'suggestion_checksum': item.suggestion_checksum, 'decision': item.decision, 'algorithm_version': item.algorithm_version, 'operation_id': item.operation_id, 'created_at': item.created_at.isoformat()}
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_usage_service.py
|
||||
|
||||
用途:投影订单模板版本的实际使用记录,供版本中心“实际使用”页签只读展示。
|
||||
依赖:Profile、Run/Unit/RouteDecision、Document ORM 与 profile audit 助手。
|
||||
逻辑:仅统计每个 Unit 的最新 RouteDecision;若外键缺失但 code/version/checksum 与当前版本一致,则标记为 snapshot_identity_match。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import and_, func, or_
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取模板版本实体,不存在时返回统一 not-found。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _mask_document_label(document: ShippingNoticeDocument | None, *, document_id: int | None) -> str:
|
||||
"""返回适合管理员列表展示的脱敏文档名称,避免把原始文件名完整暴露到列表。"""
|
||||
name = str(
|
||||
(getattr(document, 'filename', None) or getattr(document, 'attachment_key', None) or '').strip()
|
||||
)
|
||||
if not name:
|
||||
return f'document-{int(document_id or 0)}'
|
||||
path = Path(name)
|
||||
suffix = path.suffix
|
||||
stem = path.stem
|
||||
if len(stem) <= 4:
|
||||
return f'{stem[:1]}***{suffix}'
|
||||
return f'{stem[:2]}***{stem[-2:]}{suffix}'
|
||||
|
||||
|
||||
def _reason_codes(route: ShippingOrderExtractionRouteDecision, unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
"""合并分流与执行阶段的失败/降级原因,按首次出现顺序去重。"""
|
||||
values = [
|
||||
*(route.fallback_reason_codes_json or []),
|
||||
unit.reason_code,
|
||||
unit.technical_failure_reason_code,
|
||||
unit.error_code,
|
||||
route.match_status if route.match_status not in {'unique_match'} else None,
|
||||
]
|
||||
deduped: list[str] = []
|
||||
for value in values:
|
||||
code = str(value or '').strip()
|
||||
if code and code not in deduped:
|
||||
deduped.append(code)
|
||||
return deduped
|
||||
|
||||
|
||||
def _write_view_audit_safely(
|
||||
*,
|
||||
profile_id: int,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
result_count: int,
|
||||
) -> None:
|
||||
"""记录使用列表访问;写失败不阻断只读查询。"""
|
||||
try:
|
||||
profile_service._audit(
|
||||
profile_id=int(profile_id),
|
||||
event_type='version_usage_viewed',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail={'result_count': int(result_count)},
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('order document profile usage view logging failed profile_id=%s', profile_id)
|
||||
|
||||
|
||||
def list_profile_usages(
|
||||
*,
|
||||
profile_id: int,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
before_id: int | None = None,
|
||||
limit: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
返回模板版本的实际使用记录,只统计每个 Unit 的最新分流事实。
|
||||
|
||||
Args:
|
||||
profile_id: 模板版本主键。
|
||||
actor_id: 当前管理员主键,仅用于访问留痕。
|
||||
request_id: 当前 request_id,仅写入访问审计。
|
||||
before_id: 游标;仅返回更早的 route decision。
|
||||
limit: 页大小,范围由路由层约束。
|
||||
Returns:
|
||||
只读 usage 列表,包含 run_no、脱敏文档名、匹配/执行状态和进入管理员 run 审计的定位信息。
|
||||
"""
|
||||
profile = _profile(profile_id)
|
||||
latest_subquery = (
|
||||
db.session.query(
|
||||
ShippingOrderExtractionRouteDecision.unit_id.label('unit_id'),
|
||||
func.max(ShippingOrderExtractionRouteDecision.id).label('route_decision_id'),
|
||||
)
|
||||
.group_by(ShippingOrderExtractionRouteDecision.unit_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
snapshot_match = and_(
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_id.is_(None),
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_code == profile.profile_code,
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_version == profile.version,
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_checksum == profile.checksum,
|
||||
)
|
||||
direct_match = ShippingOrderExtractionRouteDecision.selected_profile_id == profile.id
|
||||
|
||||
query = (
|
||||
db.session.query(
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingNoticeDocument,
|
||||
)
|
||||
.join(
|
||||
latest_subquery,
|
||||
ShippingOrderExtractionRouteDecision.id == latest_subquery.c.route_decision_id,
|
||||
)
|
||||
.join(
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRun.id == ShippingOrderExtractionRouteDecision.run_id,
|
||||
)
|
||||
.join(
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderExtractionUnit.id == ShippingOrderExtractionRouteDecision.unit_id,
|
||||
)
|
||||
.outerjoin(
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeDocument.id == ShippingOrderExtractionUnit.document_id,
|
||||
)
|
||||
.filter(or_(direct_match, snapshot_match))
|
||||
)
|
||||
if before_id is not None:
|
||||
query = query.filter(ShippingOrderExtractionRouteDecision.id < int(before_id))
|
||||
|
||||
rows = (
|
||||
query
|
||||
.order_by(ShippingOrderExtractionRouteDecision.id.desc())
|
||||
.limit(int(limit) + 1)
|
||||
.all()
|
||||
)
|
||||
has_more = len(rows) > int(limit)
|
||||
visible_rows = rows[:int(limit)]
|
||||
items = []
|
||||
for route, run, unit, document in visible_rows:
|
||||
identity_match_mode = (
|
||||
'direct_profile_id'
|
||||
if route.selected_profile_id == profile.id
|
||||
else 'snapshot_identity_match'
|
||||
)
|
||||
items.append({
|
||||
'route_decision_id': int(route.id),
|
||||
'identity_match_mode': identity_match_mode,
|
||||
'run_no': str(run.run_no),
|
||||
'run_status': run.status,
|
||||
'unit_id': int(unit.id),
|
||||
'unit_position': int(unit.position),
|
||||
'document_id': int(unit.document_id),
|
||||
'document_label': _mask_document_label(document, document_id=unit.document_id),
|
||||
'match_status': route.match_status,
|
||||
'execution_status': unit.status,
|
||||
'auto_create_approved': route.auto_create_approved,
|
||||
'selected_profile_code': str(route.selected_profile_code or '') or None,
|
||||
'selected_profile_version': int(route.selected_profile_version) if route.selected_profile_version else None,
|
||||
'selected_profile_checksum': str(route.selected_profile_checksum or '') or None,
|
||||
'reason_codes': _reason_codes(route, unit),
|
||||
'created_at': route.created_at.isoformat() if route.created_at else None,
|
||||
'diagnostic_entry': {
|
||||
'route_name': 'AdminShippingOrderExtractionRuns',
|
||||
'run_no': str(run.run_no),
|
||||
},
|
||||
})
|
||||
payload = {
|
||||
'profile': {
|
||||
'id': int(profile.id),
|
||||
'profile_code': profile.profile_code,
|
||||
'version': int(profile.version),
|
||||
'status': profile.status,
|
||||
'checksum': profile.checksum,
|
||||
},
|
||||
'items': items,
|
||||
'page': {
|
||||
'limit': int(limit),
|
||||
'before_id': int(before_id) if before_id is not None else None,
|
||||
'next_before_id': int(items[-1]['route_decision_id']) if has_more and items else None,
|
||||
'has_more': has_more,
|
||||
},
|
||||
}
|
||||
_write_view_audit_safely(
|
||||
profile_id=int(profile.id),
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
result_count=len(items),
|
||||
)
|
||||
return payload
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
services/shipping_notice/order_document_profile_validation_service.py
|
||||
|
||||
用途:执行订单文档 Profile 草稿的不可变即时检查与当前样本试运行。
|
||||
依赖:Profile Revision、受控样本、Profile 保存服务及编辑租约服务。
|
||||
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;查询时根据当前 checksum 派生 stale,绝不改写历史运行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取可验证草稿;发布和退役版本不能被新的草稿验证记录替代。"""
|
||||
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 != 'draft':
|
||||
raise ConflictError('Only draft profiles can be validated', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE')
|
||||
return profile
|
||||
|
||||
|
||||
def _revision(profile: ShippingOrderDocumentProfile) -> ShippingOrderDocumentProfileDraftRevision:
|
||||
"""定位当前 checksum 对应的不可变 Revision,防止运行只绑定可变 Profile 行。"""
|
||||
row = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id, definition_checksum=profile.structure_fingerprint,
|
||||
).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
|
||||
if row is None:
|
||||
raise ValidationError('Draft revision is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_REVISION_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _sample(profile: ShippingOrderDocumentProfile, sample_binding_id: Any = None) -> ShippingOrderDocumentProfileSample:
|
||||
"""选择标注或训练样本;盲测样本永不进入当前样本试运行路径。"""
|
||||
query = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id)
|
||||
if sample_binding_id not in (None, ''):
|
||||
try:
|
||||
row = query.filter_by(id=int(sample_binding_id)).one_or_none()
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('sample_binding_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
|
||||
else:
|
||||
row = query.filter(ShippingOrderDocumentProfileSample.sample_role.in_(('annotation', 'training'))).order_by(
|
||||
ShippingOrderDocumentProfileSample.id.asc(),
|
||||
).first()
|
||||
if row is None or row.sample_role not in {'annotation', 'training'}:
|
||||
raise ValidationError('A bound annotation or training sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
return row
|
||||
|
||||
|
||||
def _run_payload(row: ShippingOrderDocumentProfileValidationRun, *, current_checksum: str) -> dict[str, Any]:
|
||||
"""序列化不含 PDF、对象地址、坐标或盲测真值的验证运行摘要。"""
|
||||
stale = row.definition_checksum != current_checksum
|
||||
return {
|
||||
'id': row.id,
|
||||
'profile_id': row.profile_id,
|
||||
'revision_no': row.revision_no,
|
||||
'definition_checksum': row.definition_checksum,
|
||||
'run_type': row.run_type,
|
||||
'status': 'stale' if stale else row.status,
|
||||
'stored_status': row.status,
|
||||
'summary': dict(row.summary_json or {}),
|
||||
'operation_id': row.operation_id,
|
||||
'created_at': row.created_at.isoformat(),
|
||||
'completed_at': row.completed_at.isoformat() if row.completed_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _new_run(
|
||||
*, profile: ShippingOrderDocumentProfile, revision: ShippingOrderDocumentProfileDraftRevision,
|
||||
run_type: str, sample: ShippingOrderDocumentProfileSample | None, actor_id: int | None, operation_id: str,
|
||||
) -> ShippingOrderDocumentProfileValidationRun:
|
||||
"""创建运行的冻结身份行;结果写入同一行但从不依赖其后的 Profile 当前状态。"""
|
||||
schema = profile.schema_version
|
||||
row = ShippingOrderDocumentProfileValidationRun(
|
||||
profile_id=profile.id, revision_no=revision.revision_no,
|
||||
definition_checksum=revision.definition_checksum, schema_version_id=profile.schema_version_id,
|
||||
schema_checksum=schema.checksum if schema is not None else None,
|
||||
sample_binding_id=sample.id if sample is not None else None,
|
||||
layout_version_id=sample.layout_version_id if sample is not None else None,
|
||||
layout_payload_checksum=sample.layout_payload_checksum if sample is not None else None,
|
||||
parser_key=sample.parser_key if sample is not None else None,
|
||||
parser_version=sample.parser_version if sample is not None else None,
|
||||
run_type=run_type, status='running', summary_json={}, result_snapshot_json={},
|
||||
operation_id=operation_id or secrets.token_hex(16), actor_id=actor_id,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def _instant_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""执行 v2 契约即时检查,覆盖区域、字段、页域、行关系和终止/跨页规则。"""
|
||||
definition = profile_service._normalize_definition(profile.definition_json, schema_version=profile.schema_version)
|
||||
contract = profile_service._definition_contract(profile)
|
||||
table_regions = definition.get('table_regions') or []
|
||||
field_codes: list[str] = []
|
||||
line_layout_count = 0
|
||||
for region in table_regions:
|
||||
for layout in (region.get('header_layouts') or []) + (region.get('line_layouts') or []):
|
||||
line_layout_count += int(layout in (region.get('line_layouts') or []))
|
||||
field_codes.extend(str(item.get('field_code') or '') for item in layout.get('field_regions') or [])
|
||||
duplicate_fields = sorted({code for code in field_codes if code and field_codes.count(code) > 1})
|
||||
# 同一字段在不同物理行可合法出现,因此只把 Schema/Pydantic 已检查的绑定规则作为通过依据。
|
||||
return {
|
||||
'check_categories': ['region_bounds', 'field_binding', 'page_scope', 'overlap', 'line_relation', 'cross_page', 'termination_rule', 'schema_validity'],
|
||||
'table_region_count': len(table_regions), 'line_layout_count': line_layout_count,
|
||||
'order_field_count': len(contract.order_field_layouts), 'diagnostic_duplicate_field_codes': duplicate_fields,
|
||||
}
|
||||
|
||||
|
||||
def run_instant_check(profile_id: int, *, data: dict[str, Any], actor_id: int | None, browser_session_id: str | None, lease_token: str | None, operation_id: str) -> dict[str, Any]:
|
||||
"""创建即时结构检查运行;必须持有草稿租约且失败结果同样持久化可查询。"""
|
||||
profile = _profile(profile_id)
|
||||
lease_service.require_active_lease(profile.id, actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token)
|
||||
revision = _revision(profile)
|
||||
row = _new_run(profile=profile, revision=revision, run_type='instant_check', sample=None, actor_id=actor_id, operation_id=operation_id)
|
||||
try:
|
||||
summary = _instant_summary(profile)
|
||||
row.status, row.summary_json, row.result_snapshot_json = 'passed', summary, {'check_count': len(summary['check_categories'])}
|
||||
except Exception as exc:
|
||||
row.status, row.summary_json, row.result_snapshot_json = 'failed', {'failure_code': getattr(exc, 'code', 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')}, {}
|
||||
row.completed_at = datetime.utcnow()
|
||||
profile_service._audit(profile_id=profile.id, event_type='validation_run_completed', actor_id=actor_id, operation_id=row.operation_id, revision_no=revision.revision_no, detail={'run_id': row.id, 'run_type': row.run_type, 'status': row.status})
|
||||
db.session.commit()
|
||||
return _run_payload(row, current_checksum=profile.structure_fingerprint)
|
||||
|
||||
|
||||
def run_current_sample(profile_id: int, *, data: dict[str, Any], actor_id: int | None, browser_session_id: str | None, lease_token: str | None, operation_id: str) -> dict[str, Any]:
|
||||
"""在绑定建模样本上运行当前草稿;仅保存行数和字段数,绝不保存正文或候选值。"""
|
||||
profile = _profile(profile_id)
|
||||
lease_service.require_active_lease(profile.id, actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token)
|
||||
revision, sample = _revision(profile), _sample(profile, data.get('sample_binding_id'))
|
||||
row = _new_run(profile=profile, revision=revision, run_type='current_sample', sample=sample, actor_id=actor_id, operation_id=operation_id)
|
||||
try:
|
||||
preview = profile_service.preview_profile_region(profile.id, data={
|
||||
'document_id': sample.document_id, 'table_id': sample.table_id,
|
||||
'definition': dict(profile.definition_json or {}),
|
||||
}, actor_id=actor_id)
|
||||
rows = preview.get('rows') if isinstance(preview, dict) else []
|
||||
fields = preview.get('field_codes') if isinstance(preview, dict) else []
|
||||
row.status, row.summary_json, row.result_snapshot_json = 'passed', {
|
||||
'sample_role': sample.sample_role, 'row_count': len(rows or []), 'field_count': len(fields or []),
|
||||
}, {'row_count': len(rows or []), 'field_count': len(fields or [])}
|
||||
except Exception as exc:
|
||||
row.status, row.summary_json, row.result_snapshot_json = 'failed', {
|
||||
'sample_role': sample.sample_role, 'failure_code': getattr(exc, 'code', 'SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
|
||||
}, {}
|
||||
row.completed_at = datetime.utcnow()
|
||||
profile_service._audit(profile_id=profile.id, event_type='validation_run_completed', actor_id=actor_id, operation_id=row.operation_id, revision_no=revision.revision_no, detail={'run_id': row.id, 'run_type': row.run_type, 'status': row.status, 'sample_role': sample.sample_role})
|
||||
db.session.commit()
|
||||
return _run_payload(row, current_checksum=profile.structure_fingerprint)
|
||||
|
||||
|
||||
def list_runs(profile_id: int) -> list[dict[str, Any]]:
|
||||
"""按时间倒序列出不可变运行;草稿 checksum 改变只令返回状态派生为 stale。"""
|
||||
profile = _profile(profile_id)
|
||||
rows = ShippingOrderDocumentProfileValidationRun.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileValidationRun.created_at.desc(), ShippingOrderDocumentProfileValidationRun.id.desc(),
|
||||
).all()
|
||||
return [_run_payload(row, current_checksum=profile.structure_fingerprint) for row in rows]
|
||||
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_version_service.py
|
||||
|
||||
用途:提供订单模板版本中心所需的模板族、版本摘要和安全详情 DTO。
|
||||
依赖:ShippingOrderDocumentProfile、盲测套件模型、order_document_profile_service 的既有安全 DTO。
|
||||
逻辑:按 profile_code 聚合版本;详情只返回结构化摘要,不返回 PDF、对象存储地址或盲测真值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentProfileTestSuite, ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
def _profile_event_time(profile: ShippingOrderDocumentProfile) -> datetime:
|
||||
"""返回版本中心排序使用的最近业务时间,优先发布/退役时间,其次更新时间。"""
|
||||
return profile.retired_at or profile.published_at or profile.updated_at or profile.created_at
|
||||
|
||||
|
||||
def _definition_scale_summary(definition: dict[str, Any]) -> dict[str, int]:
|
||||
"""提取配置规模统计,避免版本列表直接返回整份 definition。"""
|
||||
table_regions = [
|
||||
item for item in (definition.get('table_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
return {
|
||||
'table_region_count': len(table_regions),
|
||||
'header_layout_count': sum(len(item.get('header_layouts') or []) for item in table_regions),
|
||||
'line_layout_count': sum(len(item.get('line_layouts') or []) for item in table_regions),
|
||||
'order_field_layout_count': len(definition.get('order_field_layouts') or []),
|
||||
'draft_unbound_order_field_layout_count': len(definition.get('draft_unbound_order_field_layouts') or []),
|
||||
}
|
||||
|
||||
|
||||
def _version_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""返回模板族版本列表用的轻量摘要。"""
|
||||
safe = profile_service.payload(profile)
|
||||
return {
|
||||
'id': safe['id'],
|
||||
'profile_code': safe['profile_code'],
|
||||
'display_name': safe['display_name'],
|
||||
'version': safe['version'],
|
||||
'status': safe['status'],
|
||||
'schema_version_id': safe['schema_version_id'],
|
||||
'schema_version': safe.get('schema_version'),
|
||||
'schema_checksum': safe.get('schema_checksum'),
|
||||
'checksum': safe.get('checksum'),
|
||||
'change_note': safe.get('change_note'),
|
||||
'source_profile_id': safe.get('source_profile_id'),
|
||||
'published_at': safe.get('published_at'),
|
||||
'retired_at': safe.get('retired_at'),
|
||||
'template_mode': safe.get('template_mode'),
|
||||
'training_sample_count': safe.get('training_sample_count'),
|
||||
'match_strategy_summary': safe.get('match_strategy_summary'),
|
||||
'migration_status': safe.get('migration_status'),
|
||||
'auto_freeze_qualification': safe.get('auto_freeze_qualification'),
|
||||
'frozen_evidence': safe.get('frozen_evidence'),
|
||||
'definition_stats': _definition_scale_summary(dict(profile.definition_json or {})),
|
||||
'updated_at': _profile_event_time(profile).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def _test_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""返回版本详情页允许展示的盲测摘要,不泄露样本身份和真值。"""
|
||||
checksum = str(profile.checksum or profile.structure_fingerprint or '').strip()
|
||||
suite = (
|
||||
ShippingDocumentProfileTestSuite.query
|
||||
.filter_by(profile_id=profile.id, profile_checksum=checksum)
|
||||
.order_by(ShippingDocumentProfileTestSuite.created_at.desc())
|
||||
.first()
|
||||
)
|
||||
if suite is None:
|
||||
return {
|
||||
'status': 'missing',
|
||||
'sample_count': 0,
|
||||
'approved_at': None,
|
||||
'latest_run': None,
|
||||
}
|
||||
latest = suite.runs[-1] if suite.runs else None
|
||||
return {
|
||||
'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 []),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _sample_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""返回安全样本摘要;普通详情不回传 blind test 样本身份。"""
|
||||
samples = profile_service.list_profile_samples(profile.id)
|
||||
readable_samples = [item for item in samples if item['sample_role'] != 'blind_test']
|
||||
role_counts = {
|
||||
'annotation_count': sum(1 for item in samples if item['sample_role'] == 'annotation'),
|
||||
'training_count': sum(1 for item in samples if item['sample_role'] == 'training'),
|
||||
'blind_test_count': sum(1 for item in samples if item['sample_role'] == 'blind_test'),
|
||||
}
|
||||
return {
|
||||
**role_counts,
|
||||
'sample_count': len(samples),
|
||||
'samples': readable_samples,
|
||||
}
|
||||
|
||||
|
||||
def _source_version_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any] | None:
|
||||
"""返回来源版本摘要,供详情页展示“基于哪个版本复制/迁移”。"""
|
||||
source = profile.source_profile
|
||||
if source is None:
|
||||
return None
|
||||
return {
|
||||
'id': source.id,
|
||||
'profile_code': source.profile_code,
|
||||
'version': source.version,
|
||||
'status': source.status,
|
||||
'checksum': source.checksum,
|
||||
}
|
||||
|
||||
|
||||
def list_profile_families() -> list[dict[str, Any]]:
|
||||
"""按 profile_code 聚合模板族摘要,并返回默认选版信息。"""
|
||||
rows = ShippingOrderDocumentProfile.query.order_by(
|
||||
ShippingOrderDocumentProfile.profile_code.asc(),
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
).all()
|
||||
families: dict[str, list[ShippingOrderDocumentProfile]] = {}
|
||||
for row in rows:
|
||||
families.setdefault(row.profile_code, []).append(row)
|
||||
|
||||
result: list[dict[str, Any]] = []
|
||||
for profile_code, versions in families.items():
|
||||
draft = next((item for item in versions if item.status == 'draft'), None)
|
||||
published = next((item for item in versions if item.status == 'published'), None)
|
||||
retired = next((item for item in versions if item.status == 'retired'), None)
|
||||
default = published or draft or retired or versions[0]
|
||||
latest = versions[0]
|
||||
updated = max((_profile_event_time(item) for item in versions), default=latest.created_at)
|
||||
result.append({
|
||||
'profile_code': profile_code,
|
||||
'display_name': default.display_name,
|
||||
'draft_profile_id': draft.id if draft is not None else None,
|
||||
'draft_version': draft.version if draft is not None else None,
|
||||
'published_profile_id': published.id if published is not None else None,
|
||||
'published_version': published.version if published is not None else None,
|
||||
'latest_profile_id': latest.id,
|
||||
'latest_version': latest.version,
|
||||
'default_profile_id': default.id,
|
||||
'default_version': default.version,
|
||||
'version_count': len(versions),
|
||||
'updated_at': updated.isoformat(),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def list_family_versions(profile_code: str) -> list[dict[str, Any]]:
|
||||
"""列出同一模板族内的全部版本摘要,禁止混入其他 profile_code。"""
|
||||
safe_code = str(profile_code or '').strip()
|
||||
rows = ShippingOrderDocumentProfile.query.filter_by(profile_code=safe_code).order_by(
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
).all()
|
||||
if not rows:
|
||||
raise NotFoundError('Order document profile family not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return [_version_summary(item) for item in rows]
|
||||
|
||||
|
||||
def get_profile_detail(profile_id: int) -> dict[str, Any]:
|
||||
"""返回安全的结构化版本详情,不包含 PDF、正文或盲测真值。"""
|
||||
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')
|
||||
safe = profile_service.payload(profile)
|
||||
return {
|
||||
**safe,
|
||||
'schema_summary': {
|
||||
'id': safe['schema_version_id'],
|
||||
'version': safe.get('schema_version'),
|
||||
'checksum': safe.get('schema_checksum'),
|
||||
},
|
||||
'definition_stats': _definition_scale_summary(dict(profile.definition_json or {})),
|
||||
'sample_summary': _sample_summary(profile),
|
||||
'test_summary': _test_summary(profile),
|
||||
'source_version': _source_version_summary(profile),
|
||||
}
|
||||
|
||||
|
||||
def get_profile_detail_by_family_version(profile_code: str, version: int) -> dict[str, Any]:
|
||||
"""按模板族与版本号解析详情;不存在时返回明确 404。"""
|
||||
profile = ShippingOrderDocumentProfile.query.filter_by(
|
||||
profile_code=str(profile_code or '').strip(),
|
||||
version=int(version),
|
||||
).one_or_none()
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return get_profile_detail(profile.id)
|
||||
@@ -942,7 +942,11 @@ def submit_order_extraction_run_result(
|
||||
)
|
||||
run.auto_freeze_policy_json = evaluate_run_auto_freeze_policy(run=run, submission_result=result)
|
||||
flag_modified(run, 'auto_freeze_policy_json')
|
||||
# 旧自动冻结路径保留到阶段 6/7 切换;Review Case 同时初始化,供新只读入口使用。
|
||||
result = maybe_execute_run_auto_freeze(run=run, submission_result=result)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
|
||||
ensure_run_review_cases(run=run)
|
||||
_store_run_submission_result(
|
||||
intakes=current_intakes,
|
||||
snapshot_hash=str(run.input_snapshot_hash),
|
||||
|
||||
@@ -28,6 +28,8 @@ MAPPING_VERSION = 'shipping-order-progress-v2'
|
||||
EVENT_RETENTION_DAYS = 90
|
||||
EVENT_CODE_ORDER = {
|
||||
'plan_created': 5,
|
||||
'layout_parsing_started': 6,
|
||||
'layout_parsing_completed': 7,
|
||||
'initial_wave_started': 8,
|
||||
'expansion_wave_started': 9,
|
||||
'document_queued': 10,
|
||||
@@ -45,6 +47,8 @@ EVENT_CODE_ORDER = {
|
||||
}
|
||||
WORKSPACE_EVENT_CODES = {
|
||||
'plan_created',
|
||||
'layout_parsing_started',
|
||||
'layout_parsing_completed',
|
||||
'initial_wave_started',
|
||||
'expansion_wave_started',
|
||||
'document_queued',
|
||||
@@ -266,3 +270,37 @@ def record_run_progress(
|
||||
'occurred_at': datetime.utcnow(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def record_layout_document_progress(*, document_id: int, event_code: str, commit: bool = True) -> int:
|
||||
"""为等待版面解析的 Run 记录单 PDF 事实事件,供工作台显示真实文件进度。"""
|
||||
normalized_document_id = int(document_id or 0)
|
||||
if normalized_document_id <= 0 or event_code not in {'layout_parsing_started', 'layout_parsing_completed'}:
|
||||
return 0
|
||||
from app.models import ShippingOrderExtractionRun
|
||||
|
||||
rows = ShippingOrderExtractionRun.query.filter_by(status='queued', phase='waiting_layout').all()
|
||||
recorded = 0
|
||||
for run in rows:
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
document_ids = {
|
||||
int(document.get('document_id') or 0)
|
||||
for intake in snapshot.get('intakes') or [] if isinstance(intake, dict)
|
||||
for document in intake.get('documents') or [] if isinstance(document, dict)
|
||||
}
|
||||
if normalized_document_id not in document_ids:
|
||||
continue
|
||||
recorded += int(record_order_extraction_progress_event(
|
||||
run_no=str(run.run_no),
|
||||
commit=False,
|
||||
event={
|
||||
'document_id': normalized_document_id,
|
||||
'event_code': event_code,
|
||||
'status': 'completed',
|
||||
'visibility': 'workspace',
|
||||
'occurred_at': datetime.utcnow(),
|
||||
},
|
||||
))
|
||||
if commit and recorded:
|
||||
db.session.commit()
|
||||
return recorded
|
||||
@@ -14,6 +14,7 @@ import logging
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -459,13 +460,149 @@ def _build_snapshot(
|
||||
}
|
||||
|
||||
|
||||
def materialize_order_extraction_run_inputs(run: ShippingOrderExtractionRun) -> ShippingOrderExtractionPlan:
|
||||
def _run_snapshot_document_ids(run: ShippingOrderExtractionRun) -> set[int]:
|
||||
"""返回 Run 发送时已选附件的 Document ID,供版面任务与订单任务保持同一边界。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
return {
|
||||
int(document.get('document_id') or 0)
|
||||
for intake in snapshot.get('intakes') or [] if isinstance(intake, dict)
|
||||
for document in intake.get('documents') or [] if isinstance(document, dict)
|
||||
if int(document.get('document_id') or 0) > 0
|
||||
}
|
||||
|
||||
|
||||
def _run_layout_documents(run: ShippingOrderExtractionRun) -> list[ShippingNoticeDocument]:
|
||||
"""按 Run 冻结附件集合读取实际 Document,避免把同 Intake 后续上传的文件带入解析。"""
|
||||
document_ids = _run_snapshot_document_ids(run)
|
||||
if not document_ids:
|
||||
return []
|
||||
return ShippingNoticeDocument.query.filter(ShippingNoticeDocument.id.in_(document_ids)).all()
|
||||
|
||||
|
||||
def order_extraction_layout_prerequisite_issues(run: ShippingOrderExtractionRun) -> dict[int, str]:
|
||||
"""返回每份订单 PDF 在模板匹配前缺失的版面前置条件。
|
||||
|
||||
PDF 模板匹配只接受已完成的原生坐标快照:必须有当前 ready 版本、整页字符
|
||||
证据和 layout candidate。这里是订单主链唯一门禁,禁止用“没有订单表”掩盖
|
||||
调度、Provider 或证据构建失败。
|
||||
"""
|
||||
issues: dict[int, str] = {}
|
||||
for document in _run_layout_documents(run):
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
continue
|
||||
version = document.current_layout_version
|
||||
if version is None:
|
||||
# queued/running 版本不会写 current 指针;必须作为等待条件而不是缺失。
|
||||
version = next(
|
||||
(item for item in document.layout_versions if str(item.status or '') in {'queued', 'running'}),
|
||||
None,
|
||||
)
|
||||
if version is None:
|
||||
issues[int(document.id)] = 'layout_missing'
|
||||
continue
|
||||
if str(version.status or '') in {'queued', 'running'}:
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
continue
|
||||
if str(version.status or '') != 'ready':
|
||||
issues[int(document.id)] = 'layout_failed'
|
||||
continue
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
if not isinstance(payload.get('layout_candidate'), dict) or not isinstance(evidence.get('pages'), dict) or not isinstance(evidence.get('page_glyphs'), dict):
|
||||
issues[int(document.id)] = 'layout_evidence_incomplete'
|
||||
return issues
|
||||
|
||||
|
||||
def order_extraction_layouts_pending(run: ShippingOrderExtractionRun) -> bool:
|
||||
"""判断发送批次是否仍有运行中的布局任务;无布局能力的文档不阻塞订单流程。"""
|
||||
return 'layout_pending' in order_extraction_layout_prerequisite_issues(run).values()
|
||||
|
||||
|
||||
def order_extraction_layouts_failed(run: ShippingOrderExtractionRun) -> bool:
|
||||
"""判断发送批次是否存在最终失败的布局,失败必须单独反馈而非降级成“没有订单表”。"""
|
||||
from app.models import ShippingDocumentLayoutVersion
|
||||
|
||||
document_ids = [document.id for document in _run_layout_documents(run)]
|
||||
if not document_ids:
|
||||
return False
|
||||
return db.session.query(ShippingDocumentLayoutVersion.id).filter(
|
||||
ShippingDocumentLayoutVersion.document_id.in_(document_ids),
|
||||
ShippingDocumentLayoutVersion.status == 'failed',
|
||||
).first() is not None
|
||||
|
||||
|
||||
def schedule_order_extraction_layouts(
|
||||
run: ShippingOrderExtractionRun, *, created_by_id: int | None,
|
||||
) -> bool:
|
||||
"""发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
documents = _run_layout_documents(run)
|
||||
schedule_document_layouts(documents, created_by_id=created_by_id)
|
||||
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
|
||||
missing = [
|
||||
int(document.id) for document in documents
|
||||
if Path(str(document.filename or '')).suffix.lower() == '.pdf'
|
||||
# queued/running 版本尚不会成为 current,但它们已经满足“已创建布局 Job”。
|
||||
and not document.layout_versions
|
||||
]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'Order PDF layout job was not created',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED',
|
||||
details={'document_ids': missing},
|
||||
)
|
||||
return order_extraction_layouts_pending(run)
|
||||
|
||||
|
||||
def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
"""布局任务完成后唤醒所有已具备完整布局的 Run,确保订单任务不会早于版面快照执行。"""
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
resumed = 0
|
||||
runs = ShippingOrderExtractionRun.query.filter_by(status='queued', phase='waiting_layout').with_for_update().all()
|
||||
for run in runs:
|
||||
if int(document_id) not in _run_snapshot_document_ids(run) or order_extraction_layouts_pending(run):
|
||||
continue
|
||||
if order_extraction_layouts_failed(run):
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED',
|
||||
error_message='One or more order attachments could not be parsed',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
|
||||
created_by_id=run.user_id, max_attempts=3, message='附件解析完成,等待订单识别', commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
run.phase = 'queued'
|
||||
record_run_progress(run=run, event_code='layout_parsing_completed', commit=False)
|
||||
resumed += 1
|
||||
if resumed:
|
||||
db.session.commit()
|
||||
return resumed
|
||||
|
||||
|
||||
def materialize_order_extraction_run_inputs(
|
||||
run: ShippingOrderExtractionRun, *, finalize_plan: bool = True,
|
||||
) -> ShippingOrderExtractionPlan | None:
|
||||
"""
|
||||
在 Worker 中物化首轮附件并替换轻量输入快照为不可变 Document 快照。
|
||||
|
||||
AI 触发时机:仅订单抽取 Job 开始时调用;HTTP 发送路径严禁调用。
|
||||
核心逻辑:使用创建时冻结的 Schema/附件选择和 Intake 标识,先物化首轮,再生成计划;
|
||||
物化失败保持 Run 可重试,且不会把深度解析延迟转嫁给用户请求。
|
||||
核心逻辑:使用创建时冻结的 Schema/附件选择和 Intake 标识,先物化首轮;
|
||||
布局任务尚未完成时只刷新 Document 快照,待布局就绪后再冻结计划。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
@@ -516,9 +653,14 @@ def materialize_order_extraction_run_inputs(run: ShippingOrderExtractionRun) ->
|
||||
)
|
||||
materialized['auto_freeze_policy'] = dict(run.auto_freeze_policy_json or {})
|
||||
materialized['upload_batch_id'] = snapshot.get('upload_batch_id')
|
||||
if isinstance(snapshot.get('review_reparse'), dict):
|
||||
# 物化快照时保留 PDF 级重识别谱系,供新版终态准确收口原 Case。
|
||||
materialized['review_reparse'] = dict(snapshot['review_reparse'])
|
||||
run.input_snapshot_json = materialized
|
||||
run.input_snapshot_hash = _sha256(materialized)
|
||||
db.session.flush()
|
||||
if not finalize_plan:
|
||||
return None
|
||||
return ensure_order_extraction_plan(run)
|
||||
def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderExtractionRun | None:
|
||||
"""读取占用任一 Intake 的未释放 Run,供并发唯一约束冲突后返回明确业务结果。"""
|
||||
@@ -565,6 +707,8 @@ def create_order_extraction_run(
|
||||
reparse_of_run: ShippingOrderExtractionRun | None = None,
|
||||
reparse_reason: str | None = None,
|
||||
reparse_comment: str | None = None,
|
||||
selected_document_id: int | None = None,
|
||||
reparse_case_no: str | None = None,
|
||||
) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""
|
||||
创建订单抽取 Run;相同服务器快照幂等复用,不同输入抢占同一 Intake 时返回冲突。
|
||||
@@ -577,6 +721,8 @@ def create_order_extraction_run(
|
||||
upload_batch_id: 当前输入框上传批次,必须与每个 Intake 完全一致。
|
||||
reparse_of_run: 可选的终态来源 Run;提供时创建新的版本化识别 Run。
|
||||
reparse_reason/reparse_comment: 用户选择的重识别原因及可选备注,仅用于审计。
|
||||
selected_document_id: 指定时只冻结该附件;仅供 PDF 级重识别使用,禁止扩大为同邮件全量附件。
|
||||
reparse_case_no: 可选来源复核 Case 编号;仅作为 PDF 级版本谱系的冻结审计标识。
|
||||
Returns:
|
||||
`(run, reused)`;Run 与通用 Job 在同一事务创建。
|
||||
"""
|
||||
@@ -611,6 +757,38 @@ def create_order_extraction_run(
|
||||
)
|
||||
conversation_id = session.session_id
|
||||
attachment_selection = _build_attachment_selection_for_run(intakes=intakes)
|
||||
if selected_document_id is not None:
|
||||
# PDF 级重识别沿用原 Intake 的所有权边界,但选择计划只能包含当前 Case 的附件。
|
||||
target = db.session.get(ShippingNoticeDocument, int(selected_document_id))
|
||||
intake_by_id = {int(item.id): item for item in intakes}
|
||||
if target is None or int(target.intake_id) not in intake_by_id:
|
||||
raise NotFoundError('Shipping notice document not found', code='SHIPPING.REVIEW_DOCUMENT_NOT_FOUND')
|
||||
target_key = str(target.attachment_key or '').strip()
|
||||
target_intake_no = str(intake_by_id[int(target.intake_id)].intake_no or '').strip().upper()
|
||||
selected = False
|
||||
for item in attachment_selection.get('items') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
is_target = (
|
||||
str(item.get('intake_no') or '').strip().upper() == target_intake_no
|
||||
and str(item.get('attachment_key') or '').strip() == target_key
|
||||
)
|
||||
item['selected'] = is_target
|
||||
item['selection_batch'] = 1 if is_target else None
|
||||
item['planned_selection_batch'] = None
|
||||
if not is_target:
|
||||
item['skip_reason_codes'] = ['document_reparse_not_selected']
|
||||
selected = selected or is_target
|
||||
# 单文件上传没有 EML 附件目录;显式建立最小选择项,使物化阶段仍只处理目标 Document。
|
||||
if not selected:
|
||||
attachment_selection['items'] = [{
|
||||
'intake_no': target_intake_no, 'attachment_key': target_key,
|
||||
'filename': str(target.filename or ''), 'selected': True, 'selection_batch': 1,
|
||||
'planned_selection_batch': None, 'score_reasons': ['document_reparse_selected'],
|
||||
'skip_reason_codes': [],
|
||||
}]
|
||||
attachment_selection['total_attachment_count'] = 1
|
||||
attachment_selection['selected_attachment_count'] = 1
|
||||
if attachment_selection.get('input_budget_exceeded'):
|
||||
raise ConflictError(
|
||||
'Shipping notice input exceeds the extraction byte budget',
|
||||
@@ -631,6 +809,11 @@ def create_order_extraction_run(
|
||||
)
|
||||
snapshot['auto_freeze_policy'] = auto_freeze_policy
|
||||
snapshot['upload_batch_id'] = str(upload_batch_id or '').strip() or None
|
||||
if selected_document_id is not None:
|
||||
snapshot['review_reparse'] = {
|
||||
'document_id': int(selected_document_id),
|
||||
'source_case_no': str(reparse_case_no or '').strip().upper() or None,
|
||||
}
|
||||
snapshot_hash = _sha256(snapshot)
|
||||
idempotency_key = _sha256({
|
||||
'user_id': user.id,
|
||||
@@ -642,6 +825,8 @@ def create_order_extraction_run(
|
||||
'parser_policy_version': 'deterministic-order-policy.v1',
|
||||
'auto_freeze_policy': auto_freeze_policy,
|
||||
'reparse_of_run_id': reparse_of_run.id if reparse_of_run is not None else None,
|
||||
'selected_document_id': selected_document_id,
|
||||
'reparse_case_no': str(reparse_case_no or '').strip().upper() or None,
|
||||
})
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
if existing is not None:
|
||||
@@ -704,9 +889,12 @@ def create_order_extraction_run(
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
layouts_pending = schedule_order_extraction_layouts(run, created_by_id=user.id)
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
# 立即建立 Job 保持 Run 的可追踪性;Handler 发现 waiting_layout 后只安全收口,
|
||||
# 绝不开始订单提取。最后一份布局完成会创建真正可执行的后继 Job。
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no},
|
||||
@@ -714,10 +902,13 @@ def create_order_extraction_run(
|
||||
business_ref=run.run_no,
|
||||
created_by_id=user.id,
|
||||
max_attempts=3,
|
||||
message='订单抽取等待后台处理',
|
||||
message='等待附件版面解析' if layouts_pending else '订单抽取等待后台处理',
|
||||
commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
run.phase = 'waiting_layout' if layouts_pending else 'queued'
|
||||
if layouts_pending:
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
for intake in intakes:
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_error_code = None
|
||||
@@ -1651,6 +1842,13 @@ def transition_order_extraction_run(
|
||||
run.seen_at = None
|
||||
for member in run.intakes:
|
||||
member.released_at = now
|
||||
# PDF 级重识别只在新版实际终态后收口旧 Case;失败必须恢复旧草稿而非丢失它。
|
||||
from app.services.shipping_notice.order_review_disposition_service import finalize_document_reparse
|
||||
|
||||
finalize_document_reparse(
|
||||
run=run,
|
||||
succeeded=target_status in {'completed', 'partially_completed', 'review_required'},
|
||||
)
|
||||
_sync_order_extraction_chat_log(run)
|
||||
return run
|
||||
|
||||
|
||||
@@ -481,7 +481,9 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
]
|
||||
_intake, document = _unit_snapshot(run, unit)
|
||||
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
|
||||
if layout.get('status') != 'ready' or not profiles:
|
||||
if layout.get('status') != 'ready':
|
||||
return {'matched': False, 'blocking': True, 'tables': [], 'issues': ['order_layout_prerequisite_missing']}
|
||||
if not profiles:
|
||||
return {'matched': False, 'blocking': False, 'tables': [], 'issues': []}
|
||||
v2_profiles = [
|
||||
item for item in profiles
|
||||
@@ -489,6 +491,9 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
and item['definition'].get('contract_version') == 'order_coordinate_profile.v2'
|
||||
]
|
||||
if v2_profiles:
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
if not isinstance(layout.get('layout_candidate'), dict) or not isinstance(evidence.get('pages'), dict) or not isinstance(evidence.get('page_glyphs'), dict):
|
||||
return {'matched': False, 'blocking': True, 'tables': [], 'issues': ['order_layout_evidence_incomplete']}
|
||||
match = match_frozen_coordinate_profiles(profiles=v2_profiles, layout=layout)
|
||||
if match.status != 'unique_match':
|
||||
return {
|
||||
|
||||
@@ -49,6 +49,7 @@ def _snapshot_documents(run: ShippingOrderExtractionRun) -> dict[int, dict[str,
|
||||
'intake_id': intake_id,
|
||||
'file_name': _safe_file_name(document.get('filename')),
|
||||
'document_type': str(document.get('document_type') or ''),
|
||||
'content_hash': str(document.get('content_hash') or '').strip() or None,
|
||||
}
|
||||
return items
|
||||
|
||||
@@ -182,6 +183,21 @@ def _latest_progress_events(run: ShippingOrderExtractionRun) -> tuple[dict[tuple
|
||||
return events, current
|
||||
|
||||
|
||||
def _latest_layout_document_events(run: ShippingOrderExtractionRun) -> dict[tuple[int, str], ShippingOrderExtractionProgressEvent]:
|
||||
"""按 PDF 收集版面解析事件;该阶段早于 Unit 创建,不能复用 Unit 事件映射。"""
|
||||
events: dict[tuple[int, str], ShippingOrderExtractionProgressEvent] = {}
|
||||
rows = (
|
||||
ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id, visibility='workspace')
|
||||
.filter(ShippingOrderExtractionProgressEvent.document_id.isnot(None))
|
||||
.filter(ShippingOrderExtractionProgressEvent.event_code.in_({'layout_parsing_started', 'layout_parsing_completed'}))
|
||||
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.asc(), ShippingOrderExtractionProgressEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
for row in rows:
|
||||
events[(int(row.document_id), str(row.event_code))] = row
|
||||
return events
|
||||
|
||||
|
||||
def _current_activity_reason_codes(event: ShippingOrderExtractionProgressEvent | None) -> list[str]:
|
||||
"""归并当前事件的顶层 reason_code 与 summary.reason_codes,供聊天卡直接展示。"""
|
||||
if event is None:
|
||||
@@ -207,6 +223,25 @@ def _run_available_actions(run: ShippingOrderExtractionRun, units: list[Shipping
|
||||
return actions
|
||||
|
||||
|
||||
def _unresolved_review_document_count(run: ShippingOrderExtractionRun) -> int:
|
||||
"""统计用户仍需处理的 PDF 复核 Case,候选已生成但未确认也必须计入。"""
|
||||
resolved_statuses = {'confirmed', 'non_order', 'superseded'}
|
||||
return len({
|
||||
int(case.document_id)
|
||||
for case in getattr(run, 'review_cases', []) or []
|
||||
if str(case.status or '') not in resolved_statuses
|
||||
})
|
||||
|
||||
|
||||
def _planned_document_count(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> int:
|
||||
"""布局等待期尚无 Unit 时,使用冻结选择计划展示用户已选附件数量。"""
|
||||
if units:
|
||||
return len(units)
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
return max(0, int(selection.get('selected_attachment_count') or 0))
|
||||
|
||||
|
||||
def _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
"""按单元状态返回详情项可见操作。"""
|
||||
if unit.status == 'candidate_ready':
|
||||
@@ -216,6 +251,52 @@ def _document_available_actions(unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
return []
|
||||
|
||||
|
||||
def _planned_layout_documents(
|
||||
run: ShippingOrderExtractionRun,
|
||||
documents: dict[int, dict[str, Any]],
|
||||
event_map: dict[tuple[int, str], ShippingOrderExtractionProgressEvent],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""在 Unit 尚未物化时投影已选 PDF,避免版面解析期的详情列表显示为空。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
selected = [item for item in selection.get('items') or [] if isinstance(item, dict) and item.get('selected')]
|
||||
by_hash = {
|
||||
str(item.get('content_hash') or '').strip(): item
|
||||
for item in documents.values()
|
||||
if str(item.get('content_hash') or '').strip()
|
||||
}
|
||||
items: list[dict[str, Any]] = []
|
||||
for index, selected_item in enumerate(selected, start=1):
|
||||
document = by_hash.get(str(selected_item.get('content_hash') or '').strip(), {})
|
||||
document_id = int(document.get('document_id') or 0)
|
||||
started = event_map.get((document_id, 'layout_parsing_started'))
|
||||
completed = event_map.get((document_id, 'layout_parsing_completed'))
|
||||
items.append({
|
||||
# Unit 尚不存在时没有稳定 unit_id;使用负序号仅作 UI 列表 key,不可用于写接口。
|
||||
'unit_id': -index,
|
||||
'document_id': document_id,
|
||||
'file_name': _safe_file_name(selected_item.get('filename')) or document.get('file_name'),
|
||||
'status': 'pending',
|
||||
'selection_batch': int(selected_item.get('selection_batch') or 0) or None,
|
||||
'group_key': str(selected_item.get('group_key') or '').strip() or None,
|
||||
'retry_status': None,
|
||||
'technical_failure_reason_code': None,
|
||||
'budget_cost': None,
|
||||
'po_number': None,
|
||||
'line_count': 0,
|
||||
'profile': None,
|
||||
'email_supplement': {'status': 'none', 'relation_codes': [], 'conflict_count': 0},
|
||||
'reason_code': None,
|
||||
'review_details': [],
|
||||
'available_actions': [],
|
||||
'activity_event_code': 'layout_parsing_completed' if completed else 'layout_parsing_started' if started else None,
|
||||
'started_at': (started.occurred_at or started.received_at or started.created_at).isoformat() + 'Z' if started else None,
|
||||
'last_activity_at': None,
|
||||
'finished_at': (completed.occurred_at or completed.received_at or completed.created_at).isoformat() + 'Z' if completed else None,
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def _email_supplement_projection(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
event_map: dict[tuple[int, str], ShippingOrderExtractionProgressEvent],
|
||||
@@ -287,10 +368,12 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
"""
|
||||
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
documents = _snapshot_documents(run)
|
||||
event_map, _ = _latest_progress_events(run)
|
||||
if not units:
|
||||
return _planned_layout_documents(run, documents, _latest_layout_document_events(run))
|
||||
profiles_by_key = _snapshot_profiles(run)
|
||||
field_codes = _schema_field_codes(run)
|
||||
route_by_unit = _latest_route_decisions(run)
|
||||
event_map, _ = _latest_progress_events(run)
|
||||
items: list[dict[str, Any]] = []
|
||||
for unit in units:
|
||||
orders = _orders_from_unit(unit)
|
||||
@@ -312,6 +395,10 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
'reason_code': unit.reason_code or ('technical_failure' if unit.status == 'failed' else None),
|
||||
'review_details': list((unit.result_json or {}).get('review_details') or []),
|
||||
'available_actions': _document_available_actions(unit),
|
||||
'activity_event_code': None,
|
||||
'started_at': getattr(unit, 'started_at', None).isoformat() + 'Z' if getattr(unit, 'started_at', None) else None,
|
||||
'last_activity_at': getattr(unit, 'last_activity_at', None).isoformat() + 'Z' if getattr(unit, 'last_activity_at', None) else None,
|
||||
'finished_at': getattr(unit, 'finished_at', None).isoformat() + 'Z' if getattr(unit, 'finished_at', None) else None,
|
||||
})
|
||||
return items
|
||||
|
||||
@@ -328,7 +415,15 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
status_counter = Counter(str(unit.status or '') for unit in units)
|
||||
current_activity = None
|
||||
if run.status in {'queued', 'processing'}:
|
||||
if current_event is not None:
|
||||
if str(run.phase or '') == 'waiting_layout':
|
||||
current_activity = {
|
||||
'unit_id': None,
|
||||
'file_name': None,
|
||||
'event_code': 'layout_parsing_started',
|
||||
'selection_batch': None,
|
||||
'reason_codes': [],
|
||||
}
|
||||
elif current_event is not None:
|
||||
current_document = documents.get(int(current_event.document_id or 0), {}) if current_event.document_id is not None else {}
|
||||
current_activity = {
|
||||
'unit_id': int(current_event.unit_id) if current_event.unit_id is not None else None,
|
||||
@@ -349,13 +444,17 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
'selection_batch': int(pending_unit.selection_batch or 0) or None,
|
||||
'reason_codes': [],
|
||||
}
|
||||
review_document_count = max(
|
||||
status_counter.get('review_required', 0),
|
||||
_unresolved_review_document_count(run),
|
||||
)
|
||||
return {
|
||||
'summary': {
|
||||
'total_documents': len(units),
|
||||
'total_documents': _planned_document_count(run, units),
|
||||
'pending_documents': sum(status_counter.get(status, 0) for status in {'pending'}),
|
||||
'processing_documents': sum(status_counter.get(status, 0) for status in {'routing', 'matching_profile', 'extracting', 'merging_supplement'}),
|
||||
'completed_documents': status_counter.get('candidate_ready', 0),
|
||||
'review_required_documents': status_counter.get('review_required', 0),
|
||||
'review_required_documents': review_document_count,
|
||||
'failed_documents': status_counter.get('failed', 0),
|
||||
'candidate_count': sum(_candidate_count(unit) for unit in units),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task 与重复检测门禁。
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft(避免 joinedload+FOR UPDATE),
|
||||
冻结不可变 Revision,物化仅供履约的人工 Candidate 与 accepted Extraction;
|
||||
全程不改写机器 Candidate,也不创建 Batch。由 workspace shipping_notice API 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
ShippingOrderReviewDraft,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
acquire_notice_create_locks,
|
||||
assert_no_exact_duplicate_notices,
|
||||
normalize_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
|
||||
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
|
||||
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
|
||||
from app.services.shipping_notice.duplicate_detection import apply_duplicate_result_to_candidate, detect_duplicates_for_candidate
|
||||
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
|
||||
from app.services.shipping_notice.order_review_draft_service import build_confirmable_draft_summary
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import generate_task_no, log_task_event
|
||||
|
||||
|
||||
_CONFIRMABLE_STATUSES = frozenset({'draft', 'ready', 'unreviewed'})
|
||||
|
||||
|
||||
def _expected_version(value: Any) -> int:
|
||||
"""确认请求必须声明草稿版本,避免旧页面确认一个已变更的订单。"""
|
||||
if isinstance(value, bool):
|
||||
raise ValidationError('expected_draft_version is required', code='SHIPPING.REVIEW_DRAFT_VERSION_REQUIRED')
|
||||
try:
|
||||
version = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('expected_draft_version is required', code='SHIPPING.REVIEW_DRAFT_VERSION_REQUIRED') from exc
|
||||
if version < 1:
|
||||
raise ValidationError('expected_draft_version is invalid', code='SHIPPING.REVIEW_DRAFT_VERSION_REQUIRED')
|
||||
return version
|
||||
|
||||
|
||||
def _warning_acknowledgements(value: Any) -> list[dict[str, Any]]:
|
||||
"""仅保存结构化警告确认,不允许客户端夹带大段文档或任意执行参数。"""
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list) or any(not isinstance(item, dict) for item in value):
|
||||
raise ValidationError('warning_acknowledgements must be a list', code='SHIPPING.REVIEW_WARNING_ACK_INVALID')
|
||||
return [
|
||||
{
|
||||
'code': str(item.get('code') or '').strip()[:128],
|
||||
'comment': str(item.get('comment') or '').strip()[:500] or None,
|
||||
}
|
||||
for item in value
|
||||
if str(item.get('code') or '').strip()
|
||||
]
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
"""锁定 Case/Draft,确保双击或并发浏览器不会创建两张 Task。
|
||||
|
||||
核心逻辑:先单独 FOR UPDATE Case;再按 current_draft_id 二次锁定 Draft。
|
||||
PostgreSQL 不允许对外连接可空侧使用 FOR UPDATE,故禁止 joinedload + with_for_update。
|
||||
"""
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no or '').strip().upper(), owner_user_id=int(user_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if case is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
# [STEP 1] 幂等确认:已确认且已有 Task 时无需再锁 Draft
|
||||
if case.status == 'confirmed' and case.confirmed_task_id:
|
||||
return case
|
||||
# [STEP 2] 可确认态必须存在 Draft;按非空 FK 单独加锁,避免 LEFT JOIN FOR UPDATE
|
||||
if case.status not in _CONFIRMABLE_STATUSES or case.current_draft_id is None:
|
||||
raise ConflictError('Order review case cannot be confirmed', code='SHIPPING.REVIEW_CONFIRM_NOT_ALLOWED')
|
||||
draft = ShippingOrderReviewDraft.query.filter_by(id=int(case.current_draft_id)).with_for_update().first()
|
||||
if draft is None:
|
||||
raise ConflictError('Order review case cannot be confirmed', code='SHIPPING.REVIEW_CONFIRM_NOT_ALLOWED')
|
||||
case.current_draft = draft
|
||||
return case
|
||||
|
||||
|
||||
def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
|
||||
"""把冻结字段值写入类型化 FieldValue 投影,后续履约不会读取 Draft JSON。"""
|
||||
return {
|
||||
'value_text': str(value) if value is not None and value_type in {'string', 'enum'} else None,
|
||||
'value_decimal': value if value_type == 'decimal' else None,
|
||||
'value_integer': value if value_type == 'integer' else None,
|
||||
'value_date': value if value_type == 'date' else None,
|
||||
'value_boolean': value if value_type == 'boolean' else None,
|
||||
'value_json': _json_value(value),
|
||||
}
|
||||
|
||||
|
||||
def _json_value(value: Any) -> Any:
|
||||
"""将 Schema 规范化后的 Python 值转成 JSON 可持久化标量。"""
|
||||
if isinstance(value, Decimal):
|
||||
return format(value.normalize(), 'f')
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
return value
|
||||
|
||||
|
||||
def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, summary: dict[str, Any], actor_id: int) -> ShippingOrderExtraction:
|
||||
"""以人工确认草稿建立 accepted Extraction,不伪造机器观察或覆盖机器抽取。"""
|
||||
run = case.run
|
||||
definition = (
|
||||
(run.input_snapshot_json or {}).get('schema', {}).get('definition', {})
|
||||
if isinstance(run.input_snapshot_json, dict) else {}
|
||||
)
|
||||
configs = [item for item in definition.get('fields') or [] if isinstance(item, dict) and item.get('enabled', True)]
|
||||
extraction = ShippingOrderExtraction(
|
||||
run_id=int(run.id), intake_id=int(intake_id), schema_version_id=int(case.current_draft.schema_version_id),
|
||||
input_snapshot_hash=str(run.input_snapshot_hash or ''),
|
||||
input_snapshot_json={'source': 'review_confirmation', 'case_no': case.case_no, 'document_id': int(case.document_id)},
|
||||
status='accepted', raw_llm_output_json=None, normalized_result_json=copy.deepcopy(summary),
|
||||
validation_result_json={'blocked_fields': [], 'source': 'review_confirmation'}, created_by_id=int(actor_id),
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
header = summary.get('lines')
|
||||
header_values = {key: value for key, value in summary.items() if key != 'lines'}
|
||||
for scope, line_id, values in [('header', None, header_values)]:
|
||||
for config in configs:
|
||||
if str(config.get('scope') or '') != scope:
|
||||
continue
|
||||
field_id = str(config.get('field_id') or '')
|
||||
value = normalize_order_field_value(values.get(str(config.get('field_code') or '')), config)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=int(extraction.id), line_id=line_id, field_id=field_id,
|
||||
decision_status='accepted' if value is not None else 'missing', resolved_value_json=_json_value(value),
|
||||
supporting_observation_ids_json=[], reason_code='review_confirmed' if value is not None else 'missing',
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value is not None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=int(extraction.id), line_id=line_id, field_id=field_id, decision_id=int(decision.id),
|
||||
**_field_value_columns(value, str(config.get('value_type') or 'string')),
|
||||
))
|
||||
for position, values in enumerate(summary.get('lines') or []):
|
||||
line = ShippingOrderLine(extraction_id=int(extraction.id), position=position, line_key=f'review-{position + 1}')
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for config in configs:
|
||||
if str(config.get('scope') or '') != 'line':
|
||||
continue
|
||||
field_id = str(config.get('field_id') or '')
|
||||
value = normalize_order_field_value(values.get(str(config.get('field_code') or '')), config)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=int(extraction.id), line_id=int(line.id), field_id=field_id,
|
||||
decision_status='accepted' if value is not None else 'missing', resolved_value_json=_json_value(value),
|
||||
supporting_observation_ids_json=[], reason_code='review_confirmed' if value is not None else 'missing',
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value is not None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=int(extraction.id), line_id=int(line.id), field_id=field_id, decision_id=int(decision.id),
|
||||
**_field_value_columns(value, str(config.get('value_type') or 'string')),
|
||||
))
|
||||
return extraction
|
||||
|
||||
|
||||
def _create_review_candidate(*, case: ShippingOrderReviewCase, intake: ShippingNoticeIntake, document: ShippingNoticeDocument, summary: dict[str, Any], extraction: ShippingOrderExtraction, user_id: int) -> ShippingNoticeCandidate:
|
||||
"""物化独立人工 Candidate,复用既有重复、客户和下游 Task 关联契约。"""
|
||||
identity = build_business_fingerprint(summary)
|
||||
content = build_content_fingerprint(summary)
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no=generate_candidate_no(), intake_id=int(intake.id), primary_document_id=int(document.id),
|
||||
candidate_key=f'review-confirm-{int(case.id)}', source_order_index=0,
|
||||
order_extraction_id=int(extraction.id), order_extraction_run_id=int(case.run_id), is_current_version=True,
|
||||
extraction_source='manual', classification_confidence=1.0, field_confidence_json={}, missing_fields_json=[],
|
||||
evidence_json=[], po_number=str(summary.get('po_number') or '').strip() or None,
|
||||
structured_result_json={'business_summary': copy.deepcopy(summary), 'review_confirmation_case_no': case.case_no},
|
||||
confidence=1.0, validation_status='ready', conflicts_json=[], candidate_status='accepted',
|
||||
acceptance_mode='manual', accepted_at=datetime.utcnow(), accepted_by_id=int(user_id),
|
||||
acceptance_reason='review_case_confirmed', acceptance_policy_version='review-confirm-v1', selected=True,
|
||||
business_fingerprint=identity.get('fingerprint'), fingerprint_version=identity.get('version'),
|
||||
fingerprint_strength=identity.get('strength'), content_fingerprint=content.get('fingerprint'),
|
||||
content_fingerprint_version=content.get('version'),
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
||||
duplicate = detect_duplicates_for_candidate(
|
||||
intake=intake, asset=asset, document=document, business_summary=summary,
|
||||
fingerprint_result=identity, content_fingerprint_result=content,
|
||||
)
|
||||
apply_duplicate_result_to_candidate(candidate, duplicate)
|
||||
if duplicate.get('blocking'):
|
||||
raise ConflictError('Review order has a duplicate', code='SHIPPING.REVIEW_DUPLICATE_RESOLUTION_REQUIRED', details={'duplicate': duplicate})
|
||||
ensure_candidate_fulfillment_ready(candidate)
|
||||
return candidate
|
||||
|
||||
|
||||
def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None) -> dict[str, Any]:
|
||||
"""确认一个 PDF 草稿并建一张无 Batch 的 Task;任何门禁失败都由事务回滚。"""
|
||||
key = normalize_create_idempotency_key(idempotency_key)
|
||||
if not key:
|
||||
raise ValidationError('idempotency_key is required', code='SHIPPING.REVIEW_IDEMPOTENCY_KEY_REQUIRED')
|
||||
expected = _expected_version(expected_draft_version)
|
||||
acknowledgements = _warning_acknowledgements(warning_acknowledgements)
|
||||
replay = ShippingOrderReviewConfirmedRevision.query.filter_by(idempotency_key=key).first()
|
||||
if replay is not None:
|
||||
case = db.session.get(ShippingOrderReviewCase, int(replay.case_id))
|
||||
if case is None or int(case.owner_user_id) != int(user_id):
|
||||
raise ConflictError('Idempotency key is unavailable', code='SHIPPING.REVIEW_IDEMPOTENCY_KEY_CONFLICT')
|
||||
task = db.session.get(ShippingTask, int(replay.task_id))
|
||||
return {'task_no': task.task_no if task else None, 'idempotent_replay': True, 'case': serialize_review_case(case)}
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status == 'confirmed' and case.confirmed_task_id:
|
||||
task = db.session.get(ShippingTask, int(case.confirmed_task_id))
|
||||
return {'task_no': task.task_no if task else None, 'idempotent_replay': True, 'case': serialize_review_case(case)}
|
||||
if int(case.current_draft.draft_version) != expected:
|
||||
raise ConflictError('Review draft version changed', code='SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH')
|
||||
summary, validation = build_confirmable_draft_summary(case)
|
||||
if validation.get('status') != 'ready':
|
||||
raise ConflictError('Review draft is not ready', code='SHIPPING.REVIEW_CONFIRM_VALIDATION_FAILED', details={'issues': validation.get('issues') or []})
|
||||
document = db.session.get(ShippingNoticeDocument, int(case.document_id))
|
||||
if document is None:
|
||||
raise ConflictError('Review document is unavailable', code='SHIPPING.REVIEW_CONFIRM_DOCUMENT_INVALID')
|
||||
intake = db.session.get(ShippingNoticeIntake, int(document.intake_id))
|
||||
if intake is None or int(intake.user_id) != int(user_id) or str(document.parse_status or '') != 'parsed':
|
||||
raise ConflictError('Review document is unavailable', code='SHIPPING.REVIEW_CONFIRM_DOCUMENT_INVALID')
|
||||
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
||||
content_hash = str(document.content_hash or (asset.content_hash if asset else '')).strip()
|
||||
if content_hash:
|
||||
acquire_notice_create_locks(int(user_id), [content_hash])
|
||||
assert_no_exact_duplicate_notices(int(user_id), [{
|
||||
'source_content_hash': content_hash,
|
||||
'source_file_name': document.filename,
|
||||
'duplicate_resolution_type': 'normal',
|
||||
}])
|
||||
case.status = 'confirming'
|
||||
normalized = normalize_candidate_business_summary(summary)
|
||||
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=normalized, actor_id=int(user_id))
|
||||
candidate = _create_review_candidate(case=case, intake=intake, document=document, summary=normalized, extraction=extraction, user_id=int(user_id))
|
||||
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user_id))
|
||||
task = ShippingTask(
|
||||
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), batch_id=None, user_id=int(user_id),
|
||||
conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename,
|
||||
source_file_type=asset.mime_type if asset else None, source_content_hash=document.content_hash,
|
||||
source_asset_id=document.asset_id, source_intake_id=int(intake.id), source_candidate_id=int(candidate.id),
|
||||
business_fingerprint=candidate.business_fingerprint, fingerprint_version=candidate.fingerprint_version,
|
||||
content_fingerprint=candidate.content_fingerprint, content_fingerprint_version=candidate.content_fingerprint_version,
|
||||
document_version=1, duplicate_resolution_type='normal', raw_content=document.extracted_text,
|
||||
customer_resolution_status='pending', process_status='created', current_order_extraction_id=int(extraction.id),
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction.task_id = int(task.id)
|
||||
candidate.consumed_task_id = int(task.id)
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
# The review Case is the explicit human confirmation for this PDF. Do not
|
||||
# recreate a low-confidence parse checkpoint on the newly materialized Task.
|
||||
# Customer/inventory gates remain enforced by the standard task UI state.
|
||||
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
|
||||
revision = ShippingOrderReviewConfirmedRevision(
|
||||
case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version),
|
||||
schema_version_id=int(case.current_draft.schema_version_id), header_values_json=copy.deepcopy(case.current_draft.header_values_json or {}),
|
||||
lines_json=copy.deepcopy(case.current_draft.lines_json or []), validation_result_json=copy.deepcopy(validation),
|
||||
warning_acknowledgements_json=acknowledgements, idempotency_key=key, confirmed_by_id=int(user_id),
|
||||
)
|
||||
db.session.add(revision)
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = int(task.id)
|
||||
case.confirmed_at = datetime.utcnow()
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='case_confirmed', draft_version=int(case.current_draft.draft_version),
|
||||
actor_user_id=int(user_id), operation_json={'task_no': task.task_no, 'idempotency_key': key, 'warning_acknowledgements': acknowledgements},
|
||||
))
|
||||
log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None})
|
||||
db.session.flush()
|
||||
return {'task_no': task.task_no, 'idempotent_replay': False, 'case': serialize_review_case(case)}
|
||||
@@ -0,0 +1,279 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_review_disposition_service.py
|
||||
|
||||
用途:建单前订单复核的 PDF 处置与单文件重识别服务。
|
||||
依赖:Review Case/Draft/Event、冻结 Run/Document、抽取 Run 创建服务。
|
||||
逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft,
|
||||
禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果,
|
||||
成功后才由 Run 终态钩子替代旧 Case。由 workspace shipping_notice API 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewDraft,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
|
||||
_REPARSE_REASONS = frozenset({'document_quality', 'field_mapping_error', 'rule_updated', 'other'})
|
||||
_QUALITY_REASONS = frozenset({
|
||||
'blurred', 'incomplete_pages', 'password_protected', 'corrupted', 'wrong_orientation',
|
||||
'unsupported_layout', 'missing_order_table', 'other',
|
||||
})
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
"""锁定 owner 的 Case/Draft,所有处置都在同一事务内检查终态与版本边界。
|
||||
|
||||
核心逻辑:先 FOR UPDATE Case;若有 current_draft_id 再单独锁定 Draft。
|
||||
禁止 joinedload + with_for_update(PostgreSQL 不允许对外连接可空侧 FOR UPDATE)。
|
||||
"""
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no or '').strip().upper(), owner_user_id=int(user_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if case is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
if case.current_draft_id is not None:
|
||||
draft = ShippingOrderReviewDraft.query.filter_by(id=int(case.current_draft_id)).with_for_update().first()
|
||||
if draft is not None:
|
||||
case.current_draft = draft
|
||||
return case
|
||||
|
||||
|
||||
def _reason(value: Any, *, allowed: frozenset[str], code: str) -> str:
|
||||
"""校验受控原因码,避免自由文本成为状态机或审计查询的隐式分支。"""
|
||||
normalized = str(value or '').strip().lower()
|
||||
if normalized not in allowed:
|
||||
raise ValidationError('Review disposition reason is invalid', code=code)
|
||||
return normalized
|
||||
|
||||
|
||||
def _append_event(case: ShippingOrderReviewCase, *, actor_id: int, event_type: str, operation: dict[str, Any]) -> None:
|
||||
"""追加脱敏处置审计,不保存 PDF 正文、原始模型响应或对象存储定位。"""
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type=event_type,
|
||||
draft_version=int(case.current_draft.draft_version) if case.current_draft else None,
|
||||
actor_user_id=int(actor_id), operation_json=operation,
|
||||
))
|
||||
|
||||
|
||||
def create_manual_draft(*, user_id: int, case_no: str, comment: str | None = None) -> dict[str, Any]:
|
||||
"""启用无 Candidate PDF 的唯一现有 Draft;不会创建第二个订单或修改机器来源。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.candidate_id is not None:
|
||||
raise ConflictError('Machine order already exists', code='SHIPPING.REVIEW_MANUAL_DRAFT_ALREADY_HAS_CANDIDATE')
|
||||
if case.status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
|
||||
raise ConflictError('Order review case cannot create a manual draft', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE')
|
||||
if case.current_draft is None:
|
||||
raise ConflictError('Review draft is unavailable', code='SHIPPING.REVIEW_DRAFT_NOT_FOUND')
|
||||
previous = case.status
|
||||
case.status = 'draft'
|
||||
case.disposition = 'manual_order'
|
||||
_append_event(case, actor_id=user_id, event_type='manual_draft_created', operation={
|
||||
'previous_status': previous, 'comment': str(comment or '').strip()[:500] or None,
|
||||
})
|
||||
db.session.flush()
|
||||
return serialize_review_case(case)
|
||||
|
||||
|
||||
def mark_non_order(*, user_id: int, case_no: str, reason: str, comment: str | None = None) -> dict[str, Any]:
|
||||
"""把当前 PDF 标记为非订单;仅影响本 Case,且不产生 Task 或删除机器结果。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
|
||||
raise ConflictError('Order review case cannot be marked non-order', code='SHIPPING.REVIEW_DISPOSITION_NOT_ALLOWED')
|
||||
normalized = _reason(reason, allowed=frozenset({'non_order', 'duplicate_file', 'other'}), code='SHIPPING.REVIEW_NON_ORDER_REASON_INVALID')
|
||||
case.status = 'non_order'
|
||||
case.disposition = normalized
|
||||
if case.candidate_id is not None:
|
||||
candidate = db.session.get(ShippingNoticeCandidate, int(case.candidate_id))
|
||||
if candidate is not None and candidate.consumed_task_id is None and candidate.candidate_status == 'provisional':
|
||||
candidate.selected = False
|
||||
candidate.candidate_status = 'rejected'
|
||||
_append_event(case, actor_id=user_id, event_type='marked_non_order', operation={
|
||||
'reason': normalized, 'comment': str(comment or '').strip()[:500] or None,
|
||||
})
|
||||
db.session.flush()
|
||||
return serialize_review_case(case)
|
||||
|
||||
|
||||
def mark_quality_issue(*, user_id: int, case_no: str, reason: str, comment: str | None = None) -> dict[str, Any]:
|
||||
"""标记文件质量异常并保留 PDF、草稿和机器值,供补件或单文件重识别恢复。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
|
||||
raise ConflictError('Order review case cannot be marked quality issue', code='SHIPPING.REVIEW_DISPOSITION_NOT_ALLOWED')
|
||||
normalized = _reason(reason, allowed=_QUALITY_REASONS, code='SHIPPING.REVIEW_QUALITY_REASON_INVALID')
|
||||
case.status = 'quality_issue'
|
||||
case.disposition = normalized
|
||||
_append_event(case, actor_id=user_id, event_type='marked_quality_issue', operation={
|
||||
'reason': normalized, 'comment': str(comment or '').strip()[:500] or None,
|
||||
})
|
||||
db.session.flush()
|
||||
return serialize_review_case(case)
|
||||
|
||||
|
||||
def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: str | None = None) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""仅以当前 Case 的 Document 创建新版 Run;重复点击复用同一后继 Run。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status in {'confirmed', 'non_order', 'superseded'}:
|
||||
raise ConflictError('Order review case cannot be reparsed', code='SHIPPING.REVIEW_REPARSE_NOT_ALLOWED')
|
||||
normalized = _reason(reason, allowed=_REPARSE_REASONS, code='SHIPPING.REVIEW_REPARSE_REASON_INVALID')
|
||||
source = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
user = db.session.get(User, int(user_id))
|
||||
owner_agent = db.session.get(Agent, int(source.owner_agent_id)) if source is not None else None
|
||||
if source is None or user is None or owner_agent is None:
|
||||
raise ConflictError('Review reparse source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
# 同一个 Document 的处理中后继是幂等赢家;其他 PDF 的重识别不应互相影响。
|
||||
successors = ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=int(source.id)).order_by(
|
||||
ShippingOrderExtractionRun.created_at.desc(),
|
||||
).all()
|
||||
for successor in successors:
|
||||
marker = (successor.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict) and int(marker.get('document_id') or 0) == int(case.document_id):
|
||||
if successor.status in {'queued', 'processing'}:
|
||||
return successor, True
|
||||
if case.status == 'reparse_pending':
|
||||
raise ConflictError('Document reparse is pending', code='SHIPPING.REVIEW_REPARSE_PENDING')
|
||||
source_intake = next((item for item in source.intakes if int(item.intake_id) == int(case.unit.intake_id)), None)
|
||||
if source_intake is None:
|
||||
raise ConflictError('Review reparse input is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
from app.models import ShippingNoticeIntake
|
||||
intake = db.session.get(ShippingNoticeIntake, int(source_intake.intake_id))
|
||||
intake_no = str(intake.intake_no if intake is not None else '').strip()
|
||||
if not intake_no:
|
||||
raise ConflictError('Review reparse input is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=int(owner_agent.id), conversation_id=str(source.conversation_id), intake_nos=[intake_no],
|
||||
upload_batch_id=(source.input_snapshot_json or {}).get('upload_batch_id'), reparse_of_run=source,
|
||||
reparse_reason=normalized, reparse_comment=comment, selected_document_id=int(case.document_id), reparse_case_no=case.case_no,
|
||||
)
|
||||
if not reused:
|
||||
previous = case.status
|
||||
case.status = 'reparse_pending'
|
||||
_append_event(case, actor_id=user_id, event_type='document_reparse_started', operation={
|
||||
'previous_status': previous, 'reason': normalized, 'successor_run_no': run.run_no,
|
||||
})
|
||||
db.session.flush()
|
||||
return run, reused
|
||||
|
||||
|
||||
def create_replacement_upload_intake(*, user_id: int, case_no: str, asset_no: str) -> dict[str, Any]:
|
||||
"""为质量异常 PDF 建立新的私有 Intake;新文件永不覆盖原 Document 或旧 Case。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status not in {'quality_issue', 'draft', 'ready', 'unreviewed'}:
|
||||
raise ConflictError('Order review case cannot upload a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED')
|
||||
source = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
if source is None:
|
||||
raise ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
from app.services.file_assets.service import get_asset_for_user
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
asset = get_asset_for_user(str(asset_no or '').strip(), int(user_id))
|
||||
extension = str(asset.extension or '').strip().lower()
|
||||
if extension != 'pdf':
|
||||
raise ValidationError('Replacement file must be a PDF', code='SHIPPING.REVIEW_REPLACEMENT_FILE_INVALID')
|
||||
intake = create_shipping_notice_intake(
|
||||
user_id=int(user_id), asset_no=str(asset.asset_no), conversation_id=str(source.conversation_id),
|
||||
upload_batch_id=f'review-replacement-{case.case_no.lower()}',
|
||||
)
|
||||
_append_event(case, actor_id=user_id, event_type='replacement_upload_created', operation={
|
||||
'replacement_intake_no': intake['intake_no'],
|
||||
})
|
||||
db.session.flush()
|
||||
return intake
|
||||
|
||||
|
||||
def create_replacement_document_run(*, user_id: int, case_no: str, intake_no: str) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""在替代 Intake 已解析为唯一 PDF Document 后创建新 Run,并把旧 Case 置为等待替代结果。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status not in {'quality_issue', 'draft', 'ready', 'unreviewed'}:
|
||||
raise ConflictError('Order review case cannot use a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED')
|
||||
source = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
user = db.session.get(User, int(user_id))
|
||||
owner_agent = db.session.get(Agent, int(source.owner_agent_id)) if source is not None else None
|
||||
if source is None or user is None or owner_agent is None:
|
||||
raise ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID')
|
||||
from app.models import ShippingNoticeDocument, ShippingNoticeIntake
|
||||
|
||||
intake = ShippingNoticeIntake.query.filter_by(
|
||||
intake_no=str(intake_no or '').strip().upper(), user_id=int(user_id), purpose='shipping_notice',
|
||||
).with_for_update().first()
|
||||
if intake is None or str(intake.conversation_id or '') != str(source.conversation_id or ''):
|
||||
raise NotFoundError('Replacement intake not found', code='SHIPPING.REVIEW_REPLACEMENT_NOT_FOUND')
|
||||
if intake.parse_status != 'parsed':
|
||||
raise ConflictError('Replacement PDF is still parsing', code='SHIPPING.REVIEW_REPLACEMENT_PENDING')
|
||||
documents = ShippingNoticeDocument.query.filter_by(intake_id=int(intake.id)).filter(
|
||||
ShippingNoticeDocument.document_type != 'email_body',
|
||||
).all()
|
||||
pdfs = [item for item in documents if str(item.filename or '').lower().endswith('.pdf')]
|
||||
if len(pdfs) != 1:
|
||||
raise ConflictError('Replacement intake must contain exactly one PDF', code='SHIPPING.REVIEW_REPLACEMENT_DOCUMENT_INVALID')
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=int(owner_agent.id), conversation_id=str(source.conversation_id), intake_nos=[intake.intake_no],
|
||||
upload_batch_id=intake.upload_batch_id, reparse_of_run=source, reparse_reason='document_quality',
|
||||
reparse_comment=f'replacement for {case.case_no}', selected_document_id=int(pdfs[0].id), reparse_case_no=case.case_no,
|
||||
)
|
||||
if not reused:
|
||||
previous = case.status
|
||||
case.status = 'reparse_pending'
|
||||
_append_event(case, actor_id=user_id, event_type='replacement_reparse_started', operation={
|
||||
'previous_status': previous, 'replacement_intake_no': intake.intake_no,
|
||||
'replacement_document_id': int(pdfs[0].id), 'successor_run_no': run.run_no,
|
||||
})
|
||||
db.session.flush()
|
||||
return run, reused
|
||||
|
||||
|
||||
def finalize_document_reparse(*, run: ShippingOrderExtractionRun, succeeded: bool) -> None:
|
||||
"""在新版 Run 终态收口旧 Case:成功替代,失败恢复原草稿的原生命周期。"""
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
if not isinstance(marker, dict) or not run.reparse_of_run_id:
|
||||
return
|
||||
document_id = int(marker.get('document_id') or 0)
|
||||
if not document_id:
|
||||
return
|
||||
source_case_no = str(marker.get('source_case_no') or '').strip().upper()
|
||||
source_case = (
|
||||
ShippingOrderReviewCase.query.filter_by(
|
||||
case_no=source_case_no, run_id=int(run.reparse_of_run_id),
|
||||
).with_for_update().first()
|
||||
if source_case_no
|
||||
else ShippingOrderReviewCase.query.filter_by(
|
||||
run_id=int(run.reparse_of_run_id), document_id=document_id,
|
||||
).with_for_update().first()
|
||||
)
|
||||
if source_case is None or source_case.status != 'reparse_pending':
|
||||
return
|
||||
if succeeded:
|
||||
source_case.status = 'superseded'
|
||||
source_case.disposition = 'reparsed'
|
||||
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
|
||||
'successor_run_no': run.run_no,
|
||||
})
|
||||
return
|
||||
previous = 'quality_issue'
|
||||
event = ShippingOrderReviewCaseEvent.query.filter(
|
||||
ShippingOrderReviewCaseEvent.case_id == int(source_case.id),
|
||||
ShippingOrderReviewCaseEvent.event_type.in_({'document_reparse_started', 'replacement_reparse_started'}),
|
||||
).order_by(ShippingOrderReviewCaseEvent.id.desc()).first()
|
||||
if event is not None and isinstance(event.operation_json, dict):
|
||||
requested = str(event.operation_json.get('previous_status') or '')
|
||||
if requested in {'unreviewed', 'draft', 'ready', 'quality_issue'}:
|
||||
previous = requested
|
||||
source_case.status = previous
|
||||
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_failed', operation={
|
||||
'successor_run_no': run.run_no, 'restored_status': previous,
|
||||
})
|
||||
@@ -0,0 +1,280 @@
|
||||
"""
|
||||
建单前订单复核草稿的编辑、校验与审计服务。
|
||||
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则和 Candidate 履约硬门禁。
|
||||
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本并追加事件,
|
||||
绝不修改机器 Candidate。确认建单不属于本模块,留给阶段 6 的原子确认服务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import uuid
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewCaseEvent, ShippingOrderReviewDraft
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
|
||||
_EDITABLE_STATUSES = frozenset({'unreviewed', 'draft', 'ready'})
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
"""按 owner 分别锁定 Case 和当前 Draft,阻止旧浏览器窗口静默覆盖新草稿。"""
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no or '').strip().upper(), owner_user_id=int(user_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if case is None or case.current_draft_id is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
# PostgreSQL rejects FOR UPDATE on the nullable side of a joined eager load.
|
||||
# Lock the Draft by its non-null foreign key in a second statement instead.
|
||||
draft = ShippingOrderReviewDraft.query.filter_by(id=int(case.current_draft_id)).with_for_update().first()
|
||||
if draft is None:
|
||||
raise NotFoundError('Order review draft not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
case.current_draft = draft
|
||||
if case.status not in _EDITABLE_STATUSES:
|
||||
raise ConflictError('Order review case is not editable', code='SHIPPING.REVIEW_CASE_NOT_EDITABLE')
|
||||
return case
|
||||
|
||||
|
||||
def _expected_version(value: Any) -> int:
|
||||
"""写入接口必须明确带版本号,避免缺省值退化为最后写入者获胜。"""
|
||||
if isinstance(value, bool):
|
||||
raise ValidationError('expected_draft_version is required', code='SHIPPING.REVIEW_DRAFT_VERSION_REQUIRED')
|
||||
try:
|
||||
version = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('expected_draft_version is required', code='SHIPPING.REVIEW_DRAFT_VERSION_REQUIRED') from exc
|
||||
if version < 1:
|
||||
raise ValidationError('expected_draft_version is invalid', code='SHIPPING.REVIEW_DRAFT_VERSION_REQUIRED')
|
||||
return version
|
||||
|
||||
|
||||
def _assert_version(case: ShippingOrderReviewCase, expected: Any) -> None:
|
||||
"""在行锁内比较乐观锁版本;冲突由客户端重新加载完整 Case 后处理。"""
|
||||
if int(case.current_draft.draft_version) != _expected_version(expected):
|
||||
raise ConflictError('Review draft version changed', code='SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH')
|
||||
|
||||
|
||||
def _schema_fields(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
|
||||
"""只从本 Run 冻结 Schema 读取字段,禁止历史 Run 被当前发布版本污染。"""
|
||||
snapshot = case.run.input_snapshot_json if isinstance(case.run.input_snapshot_json, dict) else {}
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {}
|
||||
return {
|
||||
str(raw['field_id']): dict(raw)
|
||||
for raw in definition.get('fields') or []
|
||||
if isinstance(raw, dict) and raw.get('enabled', True) and raw.get('field_id')
|
||||
}
|
||||
|
||||
|
||||
def _require_field(case: ShippingOrderReviewCase, field_id: str, scope: str) -> dict[str, Any]:
|
||||
"""确认字段属于冻结 Schema 和目标作用域,前端不能伪造字段或跨 header/line 写入。"""
|
||||
field = _schema_fields(case).get(str(field_id or '').strip())
|
||||
if field is None or str(field.get('scope') or '') != scope:
|
||||
raise ValidationError('Review field is unavailable', code='SHIPPING.REVIEW_FIELD_INVALID')
|
||||
return field
|
||||
|
||||
|
||||
def _machine_value(machine_fields: list[Any], field_id: str) -> Any:
|
||||
"""从不可变机器快照找回字段初值;人工恢复只能恢复该 PDF 的机器事实。"""
|
||||
for raw in machine_fields:
|
||||
if not isinstance(raw, dict) or str(raw.get('field_id') or '') != field_id:
|
||||
continue
|
||||
observations = raw.get('observations') if isinstance(raw.get('observations'), list) else []
|
||||
if observations and isinstance(observations[0], dict):
|
||||
return copy.deepcopy(observations[0].get('value'))
|
||||
return None
|
||||
|
||||
|
||||
def _find_line(lines: list[dict[str, Any]], line_key: str) -> dict[str, Any]:
|
||||
"""按稳定 line_key 获取草稿行,禁止用可变化的数组下标定位编辑目标。"""
|
||||
for item in lines:
|
||||
if isinstance(item, dict) and str(item.get('line_key') or '') == str(line_key or ''):
|
||||
return item
|
||||
raise ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
|
||||
|
||||
def _current_value(container: dict[str, Any], field_id: str) -> Any:
|
||||
"""人工值优先,未修改字段继续投影机器值,确保机器原始记录永远不被覆盖。"""
|
||||
values = container.get('values') if isinstance(container.get('values'), dict) else {}
|
||||
entry = values.get(field_id)
|
||||
if isinstance(entry, dict) and 'value' in entry:
|
||||
return entry.get('value')
|
||||
return _machine_value(list(container.get('machine_fields') or []), field_id)
|
||||
|
||||
|
||||
def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *, restore_machine: bool) -> dict[str, Any]:
|
||||
"""写入单字段人工值或移除人工覆盖层;类型规范化始终按冻结字段规则执行。"""
|
||||
values = dict(container.get('values') or {})
|
||||
field_id = str(field['field_id'])
|
||||
if restore_machine:
|
||||
values.pop(field_id, None)
|
||||
container['values'] = values
|
||||
return {'source': 'machine_restored', 'value': _machine_value(list(container.get('machine_fields') or []), field_id)}
|
||||
normalized = normalize_order_field_value(value, field)
|
||||
# Draft is JSON-backed; persist typed values in deterministic JSON scalars.
|
||||
if isinstance(normalized, Decimal):
|
||||
normalized = format(normalized.normalize(), 'f')
|
||||
elif isinstance(normalized, date):
|
||||
normalized = normalized.isoformat()
|
||||
values[field_id] = {'value': normalized, 'source': 'manual'}
|
||||
container['values'] = values
|
||||
return {'source': 'manual', 'value': normalized}
|
||||
|
||||
|
||||
def _validation(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""全量校验草稿:动态 Schema 与 part/qty/Reservation 硬门禁同时生效,但不建单。"""
|
||||
draft = case.current_draft
|
||||
fields = _schema_fields(case)
|
||||
issues: list[dict[str, Any]] = []
|
||||
header: dict[str, Any] = {}
|
||||
header_container = dict(draft.header_values_json or {})
|
||||
for field_id, field in fields.items():
|
||||
if str(field.get('scope')) != 'header':
|
||||
continue
|
||||
value = _current_value(header_container, field_id)
|
||||
header[str(field.get('field_code') or field_id)] = value
|
||||
normalized = normalize_order_field_value(value, field)
|
||||
if field.get('required') and normalized in (None, ''):
|
||||
issues.append({'code': 'required_field_missing', 'field_id': field_id, 'scope': 'header', 'severity': 'blocking'})
|
||||
elif normalized is not None and not validate_order_field_value(normalized, field):
|
||||
issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'scope': 'header', 'severity': 'blocking'})
|
||||
lines: list[dict[str, Any]] = []
|
||||
for raw_line in draft.lines_json or []:
|
||||
if not isinstance(raw_line, dict):
|
||||
continue
|
||||
line = {}
|
||||
for field_id, field in fields.items():
|
||||
if str(field.get('scope')) != 'line':
|
||||
continue
|
||||
value = _current_value(raw_line, field_id)
|
||||
line[str(field.get('field_code') or field_id)] = value
|
||||
normalized = normalize_order_field_value(value, field)
|
||||
if field.get('required') and normalized in (None, ''):
|
||||
issues.append({'code': 'required_field_missing', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'})
|
||||
elif normalized is not None and not validate_order_field_value(normalized, field):
|
||||
issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'})
|
||||
lines.append(line)
|
||||
assessment = assess_candidate_business_summary({**header, 'lines': lines})
|
||||
for item in assessment['blocking_issues']:
|
||||
issues.append({'code': str(item.get('code') or 'invalid_order_line'), 'line_index': item.get('line_index'), 'severity': 'blocking'})
|
||||
for field_code in assessment['missing_process_fields']:
|
||||
issues.append({'code': 'process_field_missing', 'field_code': field_code, 'severity': 'blocking'})
|
||||
reservations = [str(item.get('reservation_id') or '').strip() for item in lines if item.get('reservation_id')]
|
||||
if len(reservations) != len(set(reservations)):
|
||||
issues.append({'code': 'reservation_duplicated_in_order', 'severity': 'blocking'})
|
||||
return {'status': 'ready' if not issues and assessment['can_auto_progress'] else 'needs_review', 'issues': issues}
|
||||
|
||||
|
||||
def build_confirmable_draft_summary(case: ShippingOrderReviewCase) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。"""
|
||||
fields = _schema_fields(case)
|
||||
header_container = dict(case.current_draft.header_values_json or {})
|
||||
header = {
|
||||
str(field.get('field_code') or field_id): _current_value(header_container, field_id)
|
||||
for field_id, field in fields.items()
|
||||
if str(field.get('scope') or '') == 'header'
|
||||
}
|
||||
lines = [
|
||||
{
|
||||
str(field.get('field_code') or field_id): _current_value(raw_line, field_id)
|
||||
for field_id, field in fields.items()
|
||||
if str(field.get('scope') or '') == 'line'
|
||||
}
|
||||
for raw_line in case.current_draft.lines_json or []
|
||||
if isinstance(raw_line, dict)
|
||||
]
|
||||
validation = _validation(case)
|
||||
return {**header, 'lines': lines}, validation
|
||||
|
||||
|
||||
def _record_change(case: ShippingOrderReviewCase, *, actor_id: int, event_type: str, operation: dict[str, Any]) -> dict[str, Any]:
|
||||
"""更新版本、状态和可重放的最小审计事件;不保存 PDF 正文或机器原始响应。"""
|
||||
draft = case.current_draft
|
||||
result = _validation(case)
|
||||
draft.validation_result_json = result
|
||||
draft.issue_summary_json = list(result['issues'])
|
||||
draft.updated_by_id = int(actor_id)
|
||||
draft.draft_version = int(draft.draft_version) + 1
|
||||
case.status = 'ready' if result['status'] == 'ready' else 'draft'
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type=event_type, draft_version=int(draft.draft_version), actor_user_id=int(actor_id),
|
||||
operation_json=operation,
|
||||
))
|
||||
db.session.flush()
|
||||
return serialize_review_case(case)
|
||||
|
||||
|
||||
def patch_header_field(*, user_id: int, case_no: str, field_id: str, value: Any, expected_draft_version: Any, restore_machine: bool = False) -> dict[str, Any]:
|
||||
"""编辑或恢复单个订单头字段;仅修改该字段,不会清理其他问题或人工值。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
field = _require_field(case, field_id, 'header')
|
||||
header = dict(case.current_draft.header_values_json or {})
|
||||
change = _set_value(header, field, value, restore_machine=restore_machine)
|
||||
case.current_draft.header_values_json = header
|
||||
return _record_change(case, actor_id=user_id, event_type='header_field_changed', operation={'field_id': field_id, **change})
|
||||
|
||||
|
||||
def patch_line_field(*, user_id: int, case_no: str, line_key: str, field_id: str, value: Any, expected_draft_version: Any, restore_machine: bool = False) -> dict[str, Any]:
|
||||
"""编辑或恢复一条明细字段;行由不可变 line_key 定位并受同一草稿版本锁保护。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
field = _require_field(case, field_id, 'line')
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
target = _find_line(lines, line_key)
|
||||
change = _set_value(target, field, value, restore_machine=restore_machine)
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(case, actor_id=user_id, event_type='line_field_changed', operation={'line_key': line_key, 'field_id': field_id, **change})
|
||||
|
||||
|
||||
def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""新增空人工明细行;空行立即进入校验问题,不能绕过后续建单门禁。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
line_key = f'manual-{uuid.uuid4().hex[:16]}'
|
||||
lines.append({'line_key': line_key, 'machine_fields': [], 'values': {}})
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(case, actor_id=user_id, event_type='line_added', operation={'line_key': line_key})
|
||||
|
||||
|
||||
def copy_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""复制明细为新 line_key;复制后的 Reservation 重复会由全量校验显式阻断。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
copied = copy.deepcopy(_find_line(lines, line_key))
|
||||
copied['line_key'] = f'manual-{uuid.uuid4().hex[:16]}'
|
||||
lines.append(copied)
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(case, actor_id=user_id, event_type='line_copied', operation={'source_line_key': line_key, 'line_key': copied['line_key']})
|
||||
|
||||
|
||||
def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""删除单条草稿行并写审计;删除最后有效行会保留为阻断校验结果。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
_find_line(lines, line_key)
|
||||
case.current_draft.lines_json = [item for item in lines if str(item.get('line_key') or '') != str(line_key)]
|
||||
return _record_change(case, actor_id=user_id, event_type='line_deleted', operation={'line_key': line_key})
|
||||
|
||||
|
||||
def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
"""显式执行全量草稿校验;只更新验证结果和事件,不创建 Candidate 或 ShippingTask。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
_assert_version(case, expected_draft_version)
|
||||
return _record_change(case, actor_id=user_id, event_type='draft_validated', operation={})
|
||||
@@ -0,0 +1,107 @@
|
||||
"""
|
||||
建单前订单复核的证据与受控 PDF 预览服务。
|
||||
|
||||
依赖:Review Case、Document/FileAsset、冻结 Unit 机器结果和文件资产读取服务。
|
||||
逻辑:证据仅从当前 PDF Unit 的机器 Observation 裁剪而来;预览通过 Case owner
|
||||
鉴权后由应用代理二进制,绝不向客户端公开对象存储地址或内部键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import FileAsset, ShippingNoticeDocument, ShippingOrderReviewCase
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.order_review_service import get_user_review_case
|
||||
|
||||
_MAX_QUOTE_LENGTH = 500
|
||||
|
||||
|
||||
def _safe_quote(value: Any) -> str | None:
|
||||
"""压缩引文长度与控制字符,防止预览 DTO 被异常正文或 HTML 片段污染。"""
|
||||
text = re.sub(r'\s+', ' ', str(value or '')).strip()
|
||||
return text[:_MAX_QUOTE_LENGTH] or None
|
||||
|
||||
|
||||
def _safe_bbox(value: Any) -> dict[str, float] | None:
|
||||
"""仅接受完整、有限的归一化 bbox;缺失或不可信时返回空而不是伪造高亮。"""
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
try:
|
||||
bbox = {key: float(value[key]) for key in ('x0', 'y0', 'x1', 'y1')}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if not (0 <= bbox['x0'] < bbox['x1'] <= 1 and 0 <= bbox['y0'] < bbox['y1'] <= 1):
|
||||
return None
|
||||
return bbox
|
||||
|
||||
|
||||
def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
"""展开本 Case Unit 的机器字段 Observation;不会查询其他 Run 或 Document 的结果。"""
|
||||
result = case.unit.result_json if isinstance(case.unit.result_json, dict) else {}
|
||||
orders = [item for item in result.get('orders') or [] if isinstance(item, dict)]
|
||||
if len(orders) != 1:
|
||||
return []
|
||||
fields = list(orders[0].get('header_fields') or [])
|
||||
for line_index, line in enumerate(orders[0].get('lines') or []):
|
||||
if isinstance(line, dict):
|
||||
fields.extend({**field, '_line_index': line_index} for field in line.get('fields') or [] if isinstance(field, dict))
|
||||
items: list[dict[str, Any]] = []
|
||||
for field in fields:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
for index, observation in enumerate(field.get('observations') or []):
|
||||
if not isinstance(observation, dict):
|
||||
continue
|
||||
page_no = observation.get('page_no')
|
||||
try:
|
||||
page = int(page_no) if page_no is not None else None
|
||||
except (TypeError, ValueError):
|
||||
page = None
|
||||
if page is not None and page < 1:
|
||||
page = None
|
||||
items.append({
|
||||
'evidence_id': f"{field.get('field_id') or 'field'}:{field.get('_line_index', 'header')}:{index}",
|
||||
'field_id': str(field.get('field_id') or ''),
|
||||
'line_index': field.get('_line_index'),
|
||||
'machine_value': observation.get('value'),
|
||||
'quote': _safe_quote(observation.get('quote') or observation.get('evidence_quote')),
|
||||
'page_no': page,
|
||||
'table_id': str(observation.get('table_id') or '')[:128] or None,
|
||||
'cell_id': str(observation.get('cell_id') or '')[:128] or None,
|
||||
'bbox': _safe_bbox(observation.get('normalized_bbox') or observation.get('bbox')),
|
||||
'source': str(observation.get('source') or 'machine_extraction')[:64],
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
def list_case_evidence(*, user_id: int, case_no: str) -> dict[str, Any]:
|
||||
"""返回 owner 可见的轻量证据列表,不返回正文、原始模型响应或存储信息。"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
return {'case_no': case.case_no, 'items': _observations(case)}
|
||||
|
||||
|
||||
def get_case_evidence(*, user_id: int, case_no: str, evidence_id: str) -> dict[str, Any]:
|
||||
"""按稳定 evidence_id 获取当前 Case 的一条证据,禁止跨 Case 枚举。"""
|
||||
for item in list_case_evidence(user_id=user_id, case_no=case_no)['items']:
|
||||
if item['evidence_id'] == str(evidence_id or ''):
|
||||
return item
|
||||
raise NotFoundError('Review evidence not found', code='SHIPPING.REVIEW_EVIDENCE_NOT_FOUND')
|
||||
|
||||
|
||||
def get_case_pdf_bytes(*, user_id: int, case_no: str) -> tuple[bytes, str]:
|
||||
"""读取 owner 的当前 PDF 文件;仅接受 PDF 附件且文件异常不影响草稿状态。"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
document = db.session.get(ShippingNoticeDocument, int(case.document_id))
|
||||
asset = db.session.get(FileAsset, int(document.asset_id)) if document and document.asset_id else None
|
||||
if document is None or asset is None:
|
||||
raise NotFoundError('Review document preview is unavailable', code='SHIPPING.REVIEW_PREVIEW_NOT_FOUND')
|
||||
if int(asset.owner_user_id or 0) != int(user_id):
|
||||
raise NotFoundError('Review document preview is unavailable', code='SHIPPING.REVIEW_PREVIEW_NOT_FOUND')
|
||||
mime_type = str(asset.mime_type or '').lower()
|
||||
if mime_type != 'application/pdf' and not str(document.filename or '').lower().endswith('.pdf'):
|
||||
raise ConflictError('Review document is not a PDF', code='SHIPPING.REVIEW_PREVIEW_INVALID')
|
||||
return read_asset_bytes(asset), str(document.filename or 'document.pdf').replace('\n', '').replace('\r', '')[:255]
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
建单前订单复核的用户态只读投影。
|
||||
|
||||
依赖:Review Case/Draft、冻结 Run Schema、冻结文档快照和机器 Candidate 摘要。
|
||||
逻辑:只返回工作台展示所需的字段定义、机器/人工草稿值、问题与动作;不返回
|
||||
全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingOrderReviewCase
|
||||
|
||||
|
||||
def _safe_filename(value: Any) -> str | None:
|
||||
"""从冻结文件名中移除路径片段,避免内部路径进入用户 DTO。"""
|
||||
name = str(value or '').replace('\\', '/').split('/')[-1].strip()
|
||||
return name[:255] or None
|
||||
|
||||
|
||||
def _schema_fields(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
|
||||
"""投影 Run 冻结 Schema,不读取当前 published Schema。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {}
|
||||
fields = []
|
||||
for item in definition.get('fields') or []:
|
||||
if not isinstance(item, dict) or not item.get('enabled', True):
|
||||
continue
|
||||
fields.append({
|
||||
'field_id': str(item.get('field_id') or ''),
|
||||
'field_code': str(item.get('field_code') or ''),
|
||||
'display_name': str(item.get('display_name') or item.get('field_code') or ''),
|
||||
'scope': str(item.get('scope') or ''),
|
||||
'value_type': str(item.get('value_type') or ''),
|
||||
'required': bool(item.get('required')),
|
||||
'options': list(item.get('options') or []) if isinstance(item.get('options'), list) else [],
|
||||
})
|
||||
return fields
|
||||
|
||||
|
||||
def _document_filename(run: ShippingOrderExtractionRun, document_id: int) -> str | None:
|
||||
"""仅从 Run 冻结快照获取文件展示名,避免回读可变资产。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
for intake in snapshot.get('intakes') or []:
|
||||
if not isinstance(intake, dict):
|
||||
continue
|
||||
for document in intake.get('documents') or []:
|
||||
if isinstance(document, dict) and int(document.get('document_id') or 0) == int(document_id):
|
||||
return _safe_filename(document.get('filename'))
|
||||
return None
|
||||
|
||||
|
||||
def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
|
||||
"""由后端 Case 状态决定可用动作,前端不可自行推导确认资格。"""
|
||||
if case.status in {'confirmed', 'non_order', 'superseded'}:
|
||||
return ['view']
|
||||
if case.status == 'reparse_pending':
|
||||
return ['view']
|
||||
if case.status == 'quality_issue':
|
||||
return ['view', 'mark_quality_issue', 'reparse']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'validate']
|
||||
if case.candidate_id is None and case.disposition != 'manual_order':
|
||||
actions.append('create_draft')
|
||||
else:
|
||||
actions.append('edit_draft')
|
||||
if case.current_draft is not None and str((case.current_draft.validation_result_json or {}).get('status') or '') == 'ready':
|
||||
actions.append('confirm')
|
||||
return actions
|
||||
|
||||
|
||||
def serialize_review_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""返回一个 Case 的安全详情,用于阶段 1 只读工作台与后续编辑基线。"""
|
||||
run = case.run
|
||||
draft = case.current_draft
|
||||
candidate = db.session.get(ShippingNoticeCandidate, case.candidate_id) if case.candidate_id else None
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'run_no': run.run_no,
|
||||
'document': {'id': int(case.document_id), 'file_name': _document_filename(run, int(case.document_id))},
|
||||
'status': case.status,
|
||||
'disposition': case.disposition,
|
||||
'confirmed_task_id': int(case.confirmed_task_id) if case.confirmed_task_id else None,
|
||||
'candidate': {
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'validation_status': candidate.validation_status,
|
||||
'po_number': candidate.po_number,
|
||||
} if candidate is not None else None,
|
||||
'schema': {'schema_version_id': int(run.schema_version_id), 'fields': _schema_fields(run)},
|
||||
'draft': {
|
||||
'draft_version': int(draft.draft_version),
|
||||
'header_values': dict(draft.header_values_json or {}),
|
||||
'lines': list(draft.lines_json or []),
|
||||
'issues': list(draft.issue_summary_json or []),
|
||||
'validation': dict(draft.validation_result_json or {}),
|
||||
} if draft is not None else None,
|
||||
'available_actions': _allowed_actions(case),
|
||||
}
|
||||
|
||||
|
||||
def serialize_review_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""返回 Run 的 Case 汇总和轻量列表,避免 N+1 查询及泄露机器原始结果。"""
|
||||
cases = list(run.review_cases or [])
|
||||
counts = {key: 0 for key in ('unreviewed', 'draft', 'ready', 'confirmed', 'non_order', 'quality_issue')}
|
||||
items = []
|
||||
for case in cases:
|
||||
counts[case.status] = counts.get(case.status, 0) + 1
|
||||
items.append({
|
||||
'case_no': case.case_no,
|
||||
'document_id': int(case.document_id),
|
||||
'file_name': _document_filename(run, int(case.document_id)),
|
||||
'status': case.status,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
|
||||
'available_actions': _allowed_actions(case),
|
||||
})
|
||||
return {'run_no': run.run_no, 'summary': counts, 'items': items}
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
建单前订单复核 Case 的初始化与只读加载服务。
|
||||
|
||||
依赖:冻结 Run/Unit、机器 Candidate、Review Case/Draft 模型和冻结 Schema 快照。
|
||||
逻辑:每个 PDF Unit 幂等创建一个 Case;只有该 PDF 恰有一个本 Run Candidate
|
||||
时才把它作为只读机器来源。Draft 从 Unit 的冻结结果初始化,绝不回写 Candidate。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewDraft,
|
||||
)
|
||||
|
||||
|
||||
def _is_pdf_unit(run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit) -> bool:
|
||||
"""仅为冻结快照中的 PDF 文档创建 Case,邮件关系单元不属于人工订单复核。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
for intake in snapshot.get('intakes') or []:
|
||||
if not isinstance(intake, dict):
|
||||
continue
|
||||
for document in intake.get('documents') or []:
|
||||
if not isinstance(document, dict) or int(document.get('document_id') or 0) != int(unit.document_id):
|
||||
continue
|
||||
return str(document.get('filename') or '').lower().endswith('.pdf')
|
||||
return False
|
||||
|
||||
|
||||
def _single_candidate_id(run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit) -> int | None:
|
||||
"""只关联唯一机器 Candidate;旧多 Candidate 结果必须留空并由后续清理处理。"""
|
||||
rows = ShippingNoticeCandidate.query.filter_by(
|
||||
order_extraction_run_id=int(run.id), primary_document_id=int(unit.document_id),
|
||||
).order_by(ShippingNoticeCandidate.id.asc()).all()
|
||||
return int(rows[0].id) if len(rows) == 1 else None
|
||||
|
||||
|
||||
def _initial_draft_payload(unit: ShippingOrderExtractionUnit) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""把唯一订单的冻结机器结果复制为草稿初值;无或多订单均保留空草稿与问题。"""
|
||||
result = unit.result_json if isinstance(unit.result_json, dict) else {}
|
||||
orders = [item for item in result.get('orders') or [] if isinstance(item, dict)]
|
||||
issues = [
|
||||
{'code': str(item.get('reason') or 'review_required'), 'severity': str(item.get('severity') or 'blocking')}
|
||||
for order in orders for item in order.get('conflicts') or []
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
if len(orders) != 1:
|
||||
issues.append({'code': 'machine_order_unavailable' if not orders else 'machine_multiple_orders_legacy', 'severity': 'blocking'})
|
||||
return {}, [], issues
|
||||
order = orders[0]
|
||||
header = {'machine_fields': list(order.get('header_fields') or [])}
|
||||
lines = [
|
||||
{'line_key': f'machine-{index + 1}', 'machine_fields': list(line.get('fields') or [])}
|
||||
for index, line in enumerate(order.get('lines') or []) if isinstance(line, dict)
|
||||
]
|
||||
return header, lines, issues
|
||||
|
||||
|
||||
def ensure_run_review_cases(*, run: ShippingOrderExtractionRun) -> list[ShippingOrderReviewCase]:
|
||||
"""为 Run 的每个 PDF Unit 幂等初始化唯一 Case 和 Draft,供 Worker 结果持久化后调用。"""
|
||||
plan = run.extraction_plan
|
||||
if plan is None:
|
||||
return []
|
||||
cases: list[ShippingOrderReviewCase] = []
|
||||
for unit in plan.units:
|
||||
if not _is_pdf_unit(run, unit):
|
||||
continue
|
||||
case = ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).first()
|
||||
if case is not None:
|
||||
cases.append(case)
|
||||
continue
|
||||
header, lines, issues = _initial_draft_payload(unit)
|
||||
candidate_id = _single_candidate_id(run, unit)
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no=f'SORC-{uuid.uuid4().hex[:16].upper()}',
|
||||
run_id=int(run.id), unit_id=int(unit.id), document_id=int(unit.document_id),
|
||||
candidate_id=candidate_id, owner_user_id=int(run.user_id),
|
||||
status='unreviewed',
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
draft = ShippingOrderReviewDraft(
|
||||
case_id=int(case.id), schema_version_id=int(run.schema_version_id),
|
||||
header_values_json=header, lines_json=lines, issue_summary_json=issues,
|
||||
validation_result_json={'status': 'not_validated'}, change_reason_json={'source': 'machine_initialization'},
|
||||
)
|
||||
db.session.add(draft)
|
||||
db.session.flush()
|
||||
case.current_draft_id = int(draft.id)
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='case_initialized', draft_version=1,
|
||||
actor_user_id=None, operation_json={'candidate_linked': candidate_id is not None, 'issue_count': len(issues)},
|
||||
))
|
||||
cases.append(case)
|
||||
db.session.flush()
|
||||
return cases
|
||||
|
||||
|
||||
def get_user_review_run(*, user_id: int, run_no: str) -> ShippingOrderExtractionRun:
|
||||
"""按 owner 获取 Run,禁止通过可猜测编号跨用户读取复核信息。"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=run_no, user_id=int(user_id)).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Order extraction run not found', code='SHIPPING.REVIEW_RUN_NOT_FOUND')
|
||||
return run
|
||||
|
||||
|
||||
def get_user_review_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
"""按 Case owner 获取复核对象,不信任客户端传入的 Run 或 Document 标识。"""
|
||||
case = ShippingOrderReviewCase.query.filter_by(case_no=case_no, owner_user_id=int(user_id)).first()
|
||||
if case is None:
|
||||
raise NotFoundError('Order review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
return case
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Repair review-confirmation tasks that were incorrectly reopened for parse review.
|
||||
|
||||
Revision ID: 0a1b2c3d4e5f
|
||||
Revises: ae0f1a2b3c4d
|
||||
Create Date: 2026-07-29
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = '0a1b2c3d4e5f'
|
||||
down_revision = 'ae0f1a2b3c4d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""Only repair tasks created by confirmed review Cases and left in the old erroneous state."""
|
||||
op.execute(
|
||||
"""
|
||||
UPDATE shipping_tasks
|
||||
SET process_status = 'parsed', review_status = NULL, pending_human_reason = NULL
|
||||
WHERE source_type = 'review_confirmation'
|
||||
AND process_status = 'pending_review'
|
||||
AND review_status = 'parse_review'
|
||||
AND pending_human_reason = 'low_confidence'
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""State repair is intentionally irreversible: the old state was invalid workflow data."""
|
||||
@@ -0,0 +1,65 @@
|
||||
"""freeze order profile sample evidence
|
||||
|
||||
Revision ID: 3e4f5a6b7c8d
|
||||
Revises: 2d3e4f5a6b7c
|
||||
Create Date: 2026-07-28 22:30:00.000000
|
||||
|
||||
用途:为订单模板样本绑定补齐发布时冻结的 Layout/Parser/摘要证据字段。
|
||||
依赖:现有 shipping_order_document_profile_samples、shipping_document_layout_versions 与 users 表。
|
||||
逻辑:仅追加冻结证据列与索引,不回填旧历史数据,旧记录保持空值等待受控重建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = '3e4f5a6b7c8d'
|
||||
down_revision = '2d3e4f5a6b7c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为模板样本绑定增加冻结 Layout 证据和安全展示摘要。"""
|
||||
with op.batch_alter_table('shipping_order_document_profile_samples', recreate='auto') as batch_op:
|
||||
batch_op.add_column(sa.Column('layout_version_id', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('source_content_hash', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(sa.Column('layout_payload_checksum', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(sa.Column('layout_contract_version', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(sa.Column('parser_key', sa.String(length=128), nullable=True))
|
||||
batch_op.add_column(sa.Column('parser_name', sa.String(length=32), nullable=True))
|
||||
batch_op.add_column(sa.Column('parser_version', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(sa.Column('evidence_frozen_at', sa.DateTime(), nullable=True))
|
||||
batch_op.add_column(sa.Column('source_filename_snapshot', sa.String(length=255), nullable=True))
|
||||
batch_op.add_column(sa.Column('page_count_snapshot', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('table_identity_snapshot', sa.JSON(), nullable=True))
|
||||
batch_op.create_foreign_key(
|
||||
'fk_ship_order_profile_sample_layout_version',
|
||||
'shipping_document_layout_versions',
|
||||
['layout_version_id'],
|
||||
['id'],
|
||||
)
|
||||
batch_op.create_index(
|
||||
'ix_shipping_order_document_profile_samples_layout_version',
|
||||
['layout_version_id'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除模板样本冻结证据列,回退到仅保留文档绑定的旧结构。"""
|
||||
with op.batch_alter_table('shipping_order_document_profile_samples', recreate='auto') as batch_op:
|
||||
batch_op.drop_index('ix_shipping_order_document_profile_samples_layout_version')
|
||||
batch_op.drop_constraint('fk_ship_order_profile_sample_layout_version', type_='foreignkey')
|
||||
batch_op.drop_column('table_identity_snapshot')
|
||||
batch_op.drop_column('page_count_snapshot')
|
||||
batch_op.drop_column('source_filename_snapshot')
|
||||
batch_op.drop_column('evidence_frozen_at')
|
||||
batch_op.drop_column('parser_version')
|
||||
batch_op.drop_column('parser_name')
|
||||
batch_op.drop_column('parser_key')
|
||||
batch_op.drop_column('layout_contract_version')
|
||||
batch_op.drop_column('layout_payload_checksum')
|
||||
batch_op.drop_column('source_content_hash')
|
||||
batch_op.drop_column('layout_version_id')
|
||||
@@ -0,0 +1,104 @@
|
||||
"""create shipping order review domain
|
||||
|
||||
Revision ID: 4f5a6b7c8d9e
|
||||
Revises: 3e4f5a6b7c8d
|
||||
Create Date: 2026-07-28 23:30:00.000000
|
||||
|
||||
用途:创建建单前订单人工复核的 Case、Draft 与追加式事件表。
|
||||
依赖:订单抽取 Run/Unit、Candidate、Schema、Task 和 users。
|
||||
逻辑:Unit 唯一约束保证一份 PDF 只能创建一个 Case;Case 与 Draft 分表,
|
||||
避免人工编辑覆盖机器 Candidate。确认 Task 关联保持唯一,供后续阶段原子确认使用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = '4f5a6b7c8d9e'
|
||||
down_revision = '3e4f5a6b7c8d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""建立 Review Case/Draft/Event 表以及 PDF Unit 和确认 Task 的唯一门禁。"""
|
||||
op.create_table(
|
||||
'shipping_order_review_cases',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('case_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), nullable=False),
|
||||
sa.Column('unit_id', sa.Integer(), nullable=False),
|
||||
sa.Column('document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('candidate_id', sa.Integer(), nullable=True),
|
||||
sa.Column('owner_user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='unreviewed'),
|
||||
sa.Column('disposition', sa.String(length=32), nullable=True),
|
||||
sa.Column('current_draft_id', sa.Integer(), nullable=True),
|
||||
sa.Column('confirmed_task_id', sa.Integer(), nullable=True),
|
||||
sa.Column('confirmed_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint("status IN ('unreviewed', 'draft', 'ready', 'confirming', 'confirmed', 'non_order', 'quality_issue', 'reparse_pending', 'superseded')", name='ck_shipping_order_review_cases_status'),
|
||||
sa.ForeignKeyConstraint(['run_id'], ['shipping_order_extraction_runs.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['unit_id'], ['shipping_order_extraction_units.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['candidate_id'], ['shipping_notice_candidates.id']),
|
||||
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['confirmed_task_id'], ['shipping_tasks.id']),
|
||||
sa.UniqueConstraint('case_no', name='uq_shipping_order_review_cases_no'),
|
||||
sa.UniqueConstraint('unit_id', name='uq_shipping_order_review_cases_unit'),
|
||||
sa.UniqueConstraint('confirmed_task_id', name='uq_shipping_order_review_cases_confirmed_task'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_review_cases_run_status', 'shipping_order_review_cases', ['run_id', 'status'])
|
||||
op.create_index('ix_shipping_order_review_cases_owner_updated', 'shipping_order_review_cases', ['owner_user_id', 'updated_at'])
|
||||
op.create_table(
|
||||
'shipping_order_review_drafts',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('case_id', sa.Integer(), nullable=False),
|
||||
sa.Column('draft_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('schema_version_id', sa.Integer(), nullable=False),
|
||||
sa.Column('header_values_json', sa.JSON(), nullable=False),
|
||||
sa.Column('lines_json', sa.JSON(), nullable=False),
|
||||
sa.Column('issue_summary_json', sa.JSON(), nullable=False),
|
||||
sa.Column('validation_result_json', sa.JSON(), nullable=False),
|
||||
sa.Column('change_reason_json', sa.JSON(), nullable=False),
|
||||
sa.Column('updated_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint('draft_version >= 1', name='ck_shipping_order_review_drafts_version'),
|
||||
sa.ForeignKeyConstraint(['case_id'], ['shipping_order_review_cases.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['schema_version_id'], ['shipping_order_schema_versions.id']),
|
||||
sa.ForeignKeyConstraint(['updated_by_id'], ['users.id']),
|
||||
sa.UniqueConstraint('case_id', 'draft_version', name='uq_shipping_order_review_drafts_case_version'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_review_drafts_case_updated', 'shipping_order_review_drafts', ['case_id', 'updated_at'])
|
||||
with op.batch_alter_table('shipping_order_review_cases', recreate='auto') as batch_op:
|
||||
batch_op.create_foreign_key('fk_shipping_order_review_cases_current_draft', 'shipping_order_review_drafts', ['current_draft_id'], ['id'])
|
||||
op.create_table(
|
||||
'shipping_order_review_case_events',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('case_id', sa.Integer(), nullable=False),
|
||||
sa.Column('event_type', sa.String(length=64), nullable=False),
|
||||
sa.Column('draft_version', sa.Integer(), nullable=True),
|
||||
sa.Column('actor_user_id', sa.Integer(), nullable=True),
|
||||
sa.Column('operation_json', sa.JSON(), nullable=False),
|
||||
sa.Column('occurred_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['case_id'], ['shipping_order_review_cases.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['actor_user_id'], ['users.id']),
|
||||
)
|
||||
op.create_index('ix_shipping_order_review_case_events_case_occurred', 'shipping_order_review_case_events', ['case_id', 'occurred_at'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按依赖逆序删除复核领域表,供隔离环境迁移往返验证。"""
|
||||
op.drop_index('ix_shipping_order_review_case_events_case_occurred', table_name='shipping_order_review_case_events')
|
||||
op.drop_table('shipping_order_review_case_events')
|
||||
with op.batch_alter_table('shipping_order_review_cases', recreate='auto') as batch_op:
|
||||
batch_op.drop_constraint('fk_shipping_order_review_cases_current_draft', type_='foreignkey')
|
||||
op.drop_index('ix_shipping_order_review_drafts_case_updated', table_name='shipping_order_review_drafts')
|
||||
op.drop_table('shipping_order_review_drafts')
|
||||
op.drop_index('ix_shipping_order_review_cases_owner_updated', table_name='shipping_order_review_cases')
|
||||
op.drop_index('ix_shipping_order_review_cases_run_status', table_name='shipping_order_review_cases')
|
||||
op.drop_table('shipping_order_review_cases')
|
||||
@@ -0,0 +1,54 @@
|
||||
"""add profile governance indexes
|
||||
|
||||
Revision ID: 5a6b7c8d9e0f
|
||||
Revises: 4f5a6b7c8d9e
|
||||
Create Date: 2026-07-28 22:55:00.000000
|
||||
|
||||
用途:为模板版本审计请求链路和实际使用查询补齐 request_id 列与受控索引。
|
||||
依赖:shipping_order_document_profile_audits、shipping_order_extraction_route_decisions 现有主表。
|
||||
逻辑:只追加列与索引,不回填历史 request_id;旧审计记录保持空值但仍可回放。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = '5a6b7c8d9e0f'
|
||||
down_revision = '4f5a6b7c8d9e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""增加 profile 审计 request_id 和版本使用查询索引。"""
|
||||
with op.batch_alter_table('shipping_order_document_profile_audits', recreate='auto') as batch_op:
|
||||
batch_op.add_column(sa.Column('request_id', sa.String(length=64), nullable=True))
|
||||
batch_op.create_index(
|
||||
'ix_shipping_order_document_profile_audits_profile_request',
|
||||
['profile_id', 'request_id', 'id'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
with op.batch_alter_table('shipping_order_extraction_route_decisions', recreate='auto') as batch_op:
|
||||
batch_op.create_index(
|
||||
'ix_shipping_order_extraction_route_decisions_profile_id',
|
||||
['selected_profile_id', 'id'],
|
||||
unique=False,
|
||||
)
|
||||
batch_op.create_index(
|
||||
'ix_shipping_order_extraction_route_decisions_profile_snapshot',
|
||||
['selected_profile_code', 'selected_profile_version', 'selected_profile_checksum', 'id'],
|
||||
unique=False,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除模板治理查询新增索引与 request_id 列。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_route_decisions', recreate='auto') as batch_op:
|
||||
batch_op.drop_index('ix_shipping_order_extraction_route_decisions_profile_snapshot')
|
||||
batch_op.drop_index('ix_shipping_order_extraction_route_decisions_profile_id')
|
||||
|
||||
with op.batch_alter_table('shipping_order_document_profile_audits', recreate='auto') as batch_op:
|
||||
batch_op.drop_index('ix_shipping_order_document_profile_audits_profile_request')
|
||||
batch_op.drop_column('request_id')
|
||||
@@ -0,0 +1,53 @@
|
||||
"""add shipping review confirmed revision
|
||||
|
||||
Revision ID: 6b7c8d9e0f1a
|
||||
Revises: 5a6b7c8d9e0f
|
||||
Create Date: 2026-07-29 09:30:00.000000
|
||||
|
||||
用途:持久化 PDF 复核草稿确认时的不可变版本。
|
||||
依赖:Review Case/Draft、订单 Schema、ShippingTask 和 users。
|
||||
逻辑:Case 与幂等键均唯一,保证重复确认只返回同一 Task,不能重放为另一张订单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = '6b7c8d9e0f1a'
|
||||
down_revision = '5a6b7c8d9e0f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建确认快照表及其 Case、幂等和 Task 查询约束。"""
|
||||
op.create_table(
|
||||
'shipping_order_review_confirmed_revisions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('case_id', sa.Integer(), nullable=False),
|
||||
sa.Column('task_id', sa.Integer(), nullable=False),
|
||||
sa.Column('draft_version', sa.Integer(), nullable=False),
|
||||
sa.Column('schema_version_id', sa.Integer(), nullable=False),
|
||||
sa.Column('header_values_json', sa.JSON(), nullable=False),
|
||||
sa.Column('lines_json', sa.JSON(), nullable=False),
|
||||
sa.Column('validation_result_json', sa.JSON(), nullable=False),
|
||||
sa.Column('warning_acknowledgements_json', sa.JSON(), nullable=False),
|
||||
sa.Column('idempotency_key', sa.String(length=128), nullable=False),
|
||||
sa.Column('confirmed_by_id', sa.Integer(), nullable=False),
|
||||
sa.Column('confirmed_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['case_id'], ['shipping_order_review_cases.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['task_id'], ['shipping_tasks.id']),
|
||||
sa.ForeignKeyConstraint(['schema_version_id'], ['shipping_order_schema_versions.id']),
|
||||
sa.ForeignKeyConstraint(['confirmed_by_id'], ['users.id']),
|
||||
sa.UniqueConstraint('case_id', name='uq_shipping_order_review_confirmed_revisions_case'),
|
||||
sa.UniqueConstraint('idempotency_key', name='uq_shipping_order_review_confirmed_revisions_idempotency'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_review_confirmed_revisions_task', 'shipping_order_review_confirmed_revisions', ['task_id'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除确认快照表,按创建顺序逆向回滚。"""
|
||||
op.drop_index('ix_shipping_order_review_confirmed_revisions_task', table_name='shipping_order_review_confirmed_revisions')
|
||||
op.drop_table('shipping_order_review_confirmed_revisions')
|
||||
@@ -0,0 +1,81 @@
|
||||
"""add order profile draft governance
|
||||
|
||||
Revision ID: 7c8d9e0f1a2b
|
||||
Revises: 6b7c8d9e0f1a
|
||||
Create Date: 2026-07-29 12:00:00.000000
|
||||
|
||||
用途:为订单模板草稿增加不可变修订、单写者租约和操作链路审计字段。
|
||||
依赖:订单模板 Profile 与现有 Profile 审计表。
|
||||
逻辑:新增表均以 Profile 外键级联清理;审计仅追加关联身份,不回填历史敏感详情。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = '7c8d9e0f1a2b'
|
||||
down_revision = '6b7c8d9e0f1a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 Revision/Lease 表并扩展审计操作身份。"""
|
||||
op.create_table(
|
||||
'shipping_order_document_profile_draft_revisions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=False),
|
||||
sa.Column('revision_no', sa.Integer(), nullable=False),
|
||||
sa.Column('base_lock_version', sa.Integer(), nullable=False),
|
||||
sa.Column('result_lock_version', sa.Integer(), nullable=False),
|
||||
sa.Column('definition_checksum', sa.String(length=64), nullable=False),
|
||||
sa.Column('change_source', sa.String(length=32), nullable=False),
|
||||
sa.Column('actor_id', sa.Integer(), nullable=True),
|
||||
sa.Column('browser_session_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('operation_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('change_summary_json', sa.JSON(), nullable=False),
|
||||
sa.Column('definition_snapshot_json', sa.JSON(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['actor_id'], ['users.id']),
|
||||
sa.UniqueConstraint('profile_id', 'revision_no', name='uq_shipping_order_document_profile_draft_revisions_number'),
|
||||
sa.UniqueConstraint('profile_id', 'operation_id', name='uq_shipping_order_document_profile_draft_revisions_operation'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_document_profile_draft_revisions_operation', 'shipping_order_document_profile_draft_revisions', ['operation_id'])
|
||||
op.create_table(
|
||||
'shipping_order_document_profile_edit_leases',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=False),
|
||||
sa.Column('lease_token_hash', sa.String(length=64), nullable=False),
|
||||
sa.Column('actor_id', sa.Integer(), nullable=True),
|
||||
sa.Column('browser_session_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('expires_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('last_renewed_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('taken_over_from_actor_id', sa.Integer(), nullable=True),
|
||||
sa.Column('lock_version', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['actor_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['taken_over_from_actor_id'], ['users.id']),
|
||||
sa.UniqueConstraint('profile_id', name='uq_shipping_order_document_profile_edit_leases_profile'),
|
||||
)
|
||||
op.create_index('ix_shipping_order_document_profile_edit_leases_expires', 'shipping_order_document_profile_edit_leases', ['expires_at'])
|
||||
with op.batch_alter_table('shipping_order_document_profile_audits', recreate='auto') as batch_op:
|
||||
batch_op.add_column(sa.Column('operation_id', sa.String(length=64), nullable=True))
|
||||
batch_op.add_column(sa.Column('browser_session_id', sa.String(length=128), nullable=True))
|
||||
batch_op.add_column(sa.Column('revision_no', sa.Integer(), nullable=True))
|
||||
batch_op.create_index('ix_shipping_order_document_profile_audits_operation', ['operation_id', 'id'], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""按依赖反序删除草稿治理扩展。"""
|
||||
with op.batch_alter_table('shipping_order_document_profile_audits', recreate='auto') as batch_op:
|
||||
batch_op.drop_index('ix_shipping_order_document_profile_audits_operation')
|
||||
batch_op.drop_column('revision_no')
|
||||
batch_op.drop_column('browser_session_id')
|
||||
batch_op.drop_column('operation_id')
|
||||
op.drop_index('ix_shipping_order_document_profile_edit_leases_expires', table_name='shipping_order_document_profile_edit_leases')
|
||||
op.drop_table('shipping_order_document_profile_edit_leases')
|
||||
op.drop_index('ix_shipping_order_document_profile_draft_revisions_operation', table_name='shipping_order_document_profile_draft_revisions')
|
||||
op.drop_table('shipping_order_document_profile_draft_revisions')
|
||||
@@ -0,0 +1,33 @@
|
||||
"""add order profile suggestion decisions
|
||||
|
||||
Revision ID: 8d9e0f1a2b3c
|
||||
Revises: 7c8d9e0f1a2b
|
||||
Create Date: 2026-07-29 13:00:00.000000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = '8d9e0f1a2b3c'
|
||||
down_revision = '7c8d9e0f1a2b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建建议决定表,保留算法身份和管理员决定但不复制文档正文。"""
|
||||
op.create_table('shipping_order_document_profile_suggestion_decisions',
|
||||
sa.Column('id', sa.Integer(), primary_key=True), sa.Column('profile_id', sa.Integer(), nullable=False),
|
||||
sa.Column('revision_no', sa.Integer(), nullable=False), sa.Column('sample_binding_id', sa.Integer()), sa.Column('layout_version_id', sa.Integer()),
|
||||
sa.Column('parser_key', sa.String(length=128)), sa.Column('parser_version', sa.String(length=64)), sa.Column('schema_version_id', sa.Integer(), nullable=False),
|
||||
sa.Column('algorithm_version', sa.String(length=64), nullable=False), sa.Column('suggestion_id', sa.String(length=64), nullable=False), sa.Column('suggestion_checksum', sa.String(length=64), nullable=False),
|
||||
sa.Column('decision', sa.String(length=24), nullable=False), sa.Column('actor_id', sa.Integer()), sa.Column('operation_id', sa.String(length=64), nullable=False), sa.Column('detail_json', sa.JSON(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint("decision IN ('accepted', 'accepted_adjusted', 'rejected')", name='ck_order_profile_suggestion_decision'),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['sample_binding_id'], ['shipping_order_document_profile_samples.id'], ondelete='SET NULL'), sa.ForeignKeyConstraint(['layout_version_id'], ['shipping_document_layout_versions.id']), sa.ForeignKeyConstraint(['schema_version_id'], ['shipping_order_schema_versions.id']), sa.ForeignKeyConstraint(['actor_id'], ['users.id']),
|
||||
sa.UniqueConstraint('profile_id', 'suggestion_id', name='uq_order_profile_suggestion'))
|
||||
op.create_index('ix_order_profile_suggestion_revision', 'shipping_order_document_profile_suggestion_decisions', ['profile_id', 'revision_no'])
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除建议决定事实表。"""
|
||||
op.drop_index('ix_order_profile_suggestion_revision', table_name='shipping_order_document_profile_suggestion_decisions')
|
||||
op.drop_table('shipping_order_document_profile_suggestion_decisions')
|
||||
@@ -0,0 +1,26 @@
|
||||
"""add order profile validation runs
|
||||
|
||||
Revision ID: 9e0f1a2b3c4d
|
||||
Revises: 8d9e0f1a2b3c
|
||||
Create Date: 2026-07-29 14:00:00.000000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
revision = '9e0f1a2b3c4d'
|
||||
down_revision = '8d9e0f1a2b3c'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
def upgrade() -> None:
|
||||
"""创建不可变验证运行,冻结草稿、Schema 和样本证据身份。"""
|
||||
op.create_table('shipping_order_document_profile_validation_runs',
|
||||
sa.Column('id', sa.Integer(), primary_key=True), sa.Column('profile_id', sa.Integer(), nullable=False), sa.Column('revision_no', sa.Integer(), nullable=False), sa.Column('definition_checksum', sa.String(length=64), nullable=False), sa.Column('schema_version_id', sa.Integer(), nullable=False), sa.Column('schema_checksum', sa.String(length=64)), sa.Column('sample_binding_id', sa.Integer()), sa.Column('layout_version_id', sa.Integer()), sa.Column('layout_payload_checksum', sa.String(length=64)), sa.Column('parser_key', sa.String(length=128)), sa.Column('parser_version', sa.String(length=64)), sa.Column('run_type', sa.String(length=32), nullable=False), sa.Column('status', sa.String(length=16), nullable=False), sa.Column('summary_json', sa.JSON(), nullable=False), sa.Column('result_snapshot_json', sa.JSON(), nullable=False), sa.Column('operation_id', sa.String(length=64), nullable=False), sa.Column('actor_id', sa.Integer()), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('completed_at', sa.DateTime()),
|
||||
sa.CheckConstraint("run_type IN ('instant_check', 'current_sample', 'blind_test', 'scenario_coverage', 'schema_compatibility')", name='ck_shipping_order_document_profile_validation_runs_type'), sa.CheckConstraint("status IN ('pending', 'running', 'passed', 'failed')", name='ck_shipping_order_document_profile_validation_runs_status'),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['schema_version_id'], ['shipping_order_schema_versions.id']), sa.ForeignKeyConstraint(['sample_binding_id'], ['shipping_order_document_profile_samples.id'], ondelete='SET NULL'), sa.ForeignKeyConstraint(['layout_version_id'], ['shipping_document_layout_versions.id']), sa.ForeignKeyConstraint(['actor_id'], ['users.id']))
|
||||
op.create_index('ix_order_profile_validation_created', 'shipping_order_document_profile_validation_runs', ['profile_id', 'created_at'])
|
||||
op.create_index('ix_order_profile_validation_checksum', 'shipping_order_document_profile_validation_runs', ['profile_id', 'definition_checksum'])
|
||||
def downgrade() -> None:
|
||||
"""移除验证运行。"""
|
||||
op.drop_index('ix_order_profile_validation_checksum', table_name='shipping_order_document_profile_validation_runs')
|
||||
op.drop_index('ix_order_profile_validation_created', table_name='shipping_order_document_profile_validation_runs')
|
||||
op.drop_table('shipping_order_document_profile_validation_runs')
|
||||
@@ -0,0 +1,55 @@
|
||||
"""add order profile publish check reports
|
||||
|
||||
Revision ID: ae0f1a2b3c4d
|
||||
Revises: 9e0f1a2b3c4d
|
||||
Create Date: 2026-07-29 15:00:00.000000
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = 'ae0f1a2b3c4d'
|
||||
down_revision = '9e0f1a2b3c4d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建发布检查报告表,冻结报告、草稿、验证运行及警告确认事实。"""
|
||||
op.create_table(
|
||||
'shipping_order_document_profile_publish_check_reports',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('report_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('profile_id', sa.Integer(), nullable=False),
|
||||
sa.Column('revision_no', sa.Integer(), nullable=False),
|
||||
sa.Column('definition_checksum', sa.String(length=64), nullable=False),
|
||||
sa.Column('lock_version', sa.Integer(), nullable=False),
|
||||
sa.Column('validation_run_id', sa.Integer()),
|
||||
sa.Column('base_published_profile_id', sa.Integer()),
|
||||
sa.Column('semantic_diff_json', sa.JSON(), nullable=False),
|
||||
sa.Column('blocking_items_json', sa.JSON(), nullable=False),
|
||||
sa.Column('warning_items_json', sa.JSON(), nullable=False),
|
||||
sa.Column('confirmed_warning_keys_json', sa.JSON(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=False),
|
||||
sa.Column('expires_reason', sa.String(length=64)),
|
||||
sa.Column('operation_id', sa.String(length=64), nullable=False),
|
||||
sa.Column('actor_id', sa.Integer()),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('consumed_at', sa.DateTime()),
|
||||
sa.CheckConstraint("status IN ('valid', 'invalidated', 'consumed')", name='ck_sodppcr_status'),
|
||||
sa.UniqueConstraint('profile_id', 'operation_id', name='uq_sodppcr_profile_operation'),
|
||||
sa.ForeignKeyConstraint(['profile_id'], ['shipping_order_document_profiles.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['validation_run_id'], ['shipping_order_document_profile_validation_runs.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['base_published_profile_id'], ['shipping_order_document_profiles.id'], ondelete='SET NULL'),
|
||||
sa.ForeignKeyConstraint(['actor_id'], ['users.id']),
|
||||
)
|
||||
op.create_index('ix_sodppcr_profile_created', 'shipping_order_document_profile_publish_check_reports', ['profile_id', 'created_at'])
|
||||
op.create_index('ix_sodppcr_report_no', 'shipping_order_document_profile_publish_check_reports', ['report_no'], unique=True)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""移除发布检查报告表。"""
|
||||
op.drop_index('ix_sodppcr_report_no', table_name='shipping_order_document_profile_publish_check_reports')
|
||||
op.drop_index('ix_sodppcr_profile_created', table_name='shipping_order_document_profile_publish_check_reports')
|
||||
op.drop_table('shipping_order_document_profile_publish_check_reports')
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
backend/tests/test_order_document_profile_creation_service.py
|
||||
|
||||
用途:验证订单模板三步向导最终提交的原子创建契约。
|
||||
依赖:创建服务、Profile/Revision/Lease/Audit ORM 与既有样本夹具。
|
||||
逻辑:前两步不调用该服务;覆盖无效主表格零写入,以及成功时草稿、样本、Revision、Lease、审计同事务落库。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as creation_service
|
||||
from tests.test_shipping_order_document_profile_service import _bind_ready_profile_sample, _schema_version
|
||||
|
||||
|
||||
def _wizard_payload(schema_id: int, document_id: int, *, table_id: str = 'sample-table') -> dict:
|
||||
"""构造已完成三步向导的最小请求,避免测试通过旧 from-sample 创建路径。"""
|
||||
return {
|
||||
'profile_code': 'WIZARD_PROFILE', 'display_name': 'Wizard profile',
|
||||
'schema_version_id': schema_id, 'document_id': document_id,
|
||||
'main_table_id': table_id, 'browser_session_id': 'wizard-tab-a', 'operation_id': 'wizard-create-op',
|
||||
}
|
||||
|
||||
|
||||
def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomically(app):
|
||||
"""关键断言:最后一步一次提交全部治理对象,并绑定用户已确认的主表格。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
# 只借用已解析文档夹具;其 Profile 绑定与向导目标无关。
|
||||
seed = ShippingOrderDocumentProfile(
|
||||
profile_code='SEED_PROFILE', display_name='Seed', version=1, status='draft',
|
||||
schema_version_id=schema.id, structure_fingerprint='a' * 64,
|
||||
definition_json={}, template_mode='coordinate_v2', lock_version=1,
|
||||
)
|
||||
db.session.add(seed)
|
||||
db.session.commit()
|
||||
sample = _bind_ready_profile_sample(seed.id)
|
||||
created = creation_service.complete_wizard(_wizard_payload(schema.id, sample.document_id), actor_id=None)
|
||||
profile_id = created['id']
|
||||
assert created['draft_revision']['revision_no'] == 1
|
||||
assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1
|
||||
assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1
|
||||
assert ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=profile_id, event_type='wizard_created', operation_id='wizard-create-op').count() == 1
|
||||
|
||||
|
||||
def test_wizard_completion_invalid_main_table_rolls_back_without_profile(app):
|
||||
"""关键断言:第三步主表格无效时不留下 Profile、Revision、Lease 或审计半成品。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
seed = ShippingOrderDocumentProfile(
|
||||
profile_code='SEED_BAD', display_name='Seed', version=1, status='draft',
|
||||
schema_version_id=schema.id, structure_fingerprint='b' * 64,
|
||||
definition_json={}, template_mode='coordinate_v2', lock_version=1,
|
||||
)
|
||||
db.session.add(seed)
|
||||
db.session.commit()
|
||||
sample = _bind_ready_profile_sample(seed.id)
|
||||
with pytest.raises(Exception) as caught:
|
||||
creation_service.complete_wizard(_wizard_payload(schema.id, sample.document_id, table_id='missing-table'), actor_id=None)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
assert ShippingOrderDocumentProfile.query.filter_by(profile_code='WIZARD_PROFILE').count() == 0
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.count() == 0
|
||||
assert ShippingOrderDocumentProfileEditLease.query.count() == 0
|
||||
@@ -0,0 +1,263 @@
|
||||
"""
|
||||
backend/tests/test_order_document_profile_diff.py
|
||||
|
||||
用途:验证订单模板版本语义 diff 的稳定配对、坐标容差与路由约束。
|
||||
依赖:order_document_profile_diff service、版本中心管理 API、JWT 管理员鉴权。
|
||||
逻辑:覆盖默认上一版、跨模板比较拦截、字段重命名不误判与 exclusion 重排不报变更。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderSchema, ShippingOrderSchemaVersion, User
|
||||
from app.services.shipping_notice import order_document_profile_diff as diff_service
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_jwt_headers(app):
|
||||
"""创建 Bearer JWT 管理员头,覆盖 require_admin 的当前鉴权方式。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='profile-diff-admin').first()
|
||||
if not user:
|
||||
user = User(
|
||||
username='profile-diff-admin',
|
||||
email='profile-diff-admin@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def _schema_version() -> ShippingOrderSchemaVersion:
|
||||
"""创建最小发布 Schema 版本,供模板详情摘要复用。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Profile Diff Schema')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
checksum='a' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.commit()
|
||||
return version
|
||||
|
||||
|
||||
def _anchor(anchor_id: str, text: str) -> dict:
|
||||
"""构造最小锚点结构,避免测试重复拼装。"""
|
||||
return {
|
||||
'anchor_id': anchor_id,
|
||||
'text': text,
|
||||
'aliases': [],
|
||||
'match_mode': 'contains',
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}
|
||||
|
||||
|
||||
def _definition() -> dict:
|
||||
"""构造具备表格、订单字段、终止与排除区的最小可比较定义。"""
|
||||
return {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {
|
||||
'document_type': 'purchase_order',
|
||||
'page_pattern': 'one_or_more',
|
||||
'required_anchors': [_anchor('po_title', 'PURCHASE ORDER')],
|
||||
'optional_anchors': [],
|
||||
'minimum_score': 1,
|
||||
'minimum_margin': 0,
|
||||
},
|
||||
'table_regions': [{
|
||||
'region_id': 'main_lines',
|
||||
'page_scope': 'first_page',
|
||||
'page_no': None,
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'header_layouts': [{
|
||||
'layout_id': 'header-1',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 0.1},
|
||||
'field_regions': [{
|
||||
'field_id': 'header-field',
|
||||
'field_code': 'customer_part_number',
|
||||
'region': {'x0': 0.1, 'y0': 0.01, 'x1': 0.4, 'y1': 0.08},
|
||||
'extractor_key': 'direct',
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
}],
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main-line',
|
||||
'row_offset': 0,
|
||||
'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0.1, 'x1': 1, 'y1': 0.8},
|
||||
'field_regions': [{
|
||||
'field_id': 'part-field',
|
||||
'field_code': 'part_number',
|
||||
'region': {'x0': 0, 'y0': 0.1, 'x1': 0.5, 'y1': 0.2},
|
||||
'extractor_key': 'direct',
|
||||
'allowed_sources': ['pdf_coordinate'],
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'continuation_conditions': [],
|
||||
'required_fields': ['part_number'],
|
||||
'allowed_empty_fields': [],
|
||||
}],
|
||||
'termination_rules': [{'rule_id': 'end-rule', 'anchor': _anchor('end-anchor', 'END')}],
|
||||
'exclusion_regions': [
|
||||
{'x0': 0.8, 'y0': 0.0, 'x1': 0.95, 'y1': 0.08},
|
||||
{'x0': 0.8, 'y0': 0.12, 'x1': 0.95, 'y1': 0.18},
|
||||
],
|
||||
}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'po-no',
|
||||
'field_id': 'po-field',
|
||||
'field_code': 'customer_po_number',
|
||||
'page_scope': 'first_page',
|
||||
'page_no': None,
|
||||
'anchor': _anchor('po-label', 'PO No'),
|
||||
'value_region': {'x0': 0.4, 'y0': 0.2, 'x1': 0.7, 'y1': 0.25},
|
||||
'fallback_value_region': None,
|
||||
'value_mode': 'right_of_anchor',
|
||||
'stop_anchors': [],
|
||||
'normalizer_key': 'trim',
|
||||
'required': True,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
}
|
||||
|
||||
|
||||
def _detail(*, profile_id: int, profile_code: str, version: int, definition: dict, sample_count: int = 0) -> dict:
|
||||
"""构造与版本中心详情结构一致的最小安全 DTO。"""
|
||||
return {
|
||||
'id': profile_id,
|
||||
'profile_code': profile_code,
|
||||
'display_name': profile_code,
|
||||
'version': version,
|
||||
'status': 'published',
|
||||
'schema_version_id': 1,
|
||||
'schema_version': 1,
|
||||
'schema_checksum': 'a' * 64,
|
||||
'definition': definition,
|
||||
'checksum': f'{version}' * 64,
|
||||
'migration_status': 'normal',
|
||||
'template_mode': 'coordinate_v2',
|
||||
'schema_summary': {'id': 1, 'version': 1, 'checksum': 'a' * 64},
|
||||
'frozen_evidence': {'status': 'ready', 'sample_count': sample_count, 'frozen_sample_count': sample_count, 'audit_ready': True},
|
||||
'auto_freeze_qualification': {
|
||||
'status': 'manual_confirmation',
|
||||
'auto_freeze_enabled': False,
|
||||
'qualification_id': None,
|
||||
'customer_ids': [],
|
||||
'business_scenarios': [],
|
||||
'requires_customer_confirmation': True,
|
||||
},
|
||||
'test_summary': {'status': 'missing', 'sample_count': 0, 'approved_at': None, 'latest_run': None},
|
||||
'sample_summary': {'annotation_count': 0, 'training_count': sample_count, 'blind_test_count': 0, 'sample_count': sample_count, 'samples': []},
|
||||
}
|
||||
|
||||
|
||||
def _profile(
|
||||
schema_version_id: int,
|
||||
*,
|
||||
profile_code: str,
|
||||
version: int,
|
||||
definition: dict,
|
||||
status: str = 'published',
|
||||
) -> ShippingOrderDocumentProfile:
|
||||
"""创建直接供 diff service 读取的最小模板版本。"""
|
||||
row = ShippingOrderDocumentProfile(
|
||||
profile_code=profile_code,
|
||||
display_name=profile_code,
|
||||
version=version,
|
||||
status=status,
|
||||
schema_version_id=schema_version_id,
|
||||
structure_fingerprint=(str(version) * 64)[:64],
|
||||
definition_json=definition,
|
||||
checksum=(str(version) * 64)[:64] if status in {'published', 'retired'} else None,
|
||||
template_mode='coordinate_v2',
|
||||
published_at=datetime.utcnow() if status == 'published' else None,
|
||||
retired_at=datetime.utcnow() if status == 'retired' else None,
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def test_compare_profile_details_uses_stable_ids_and_region_tolerance():
|
||||
"""同一 stable id 的字段改名应视为修改;微小坐标噪声不应被算作 region 变化。"""
|
||||
before_definition = _definition()
|
||||
after_definition = _definition()
|
||||
after_definition['table_regions'][0]['line_layouts'][0]['field_regions'][0]['field_code'] = 'internal_part_number'
|
||||
after_definition['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.5005
|
||||
|
||||
result = diff_service.compare_profile_details(
|
||||
_detail(profile_id=1, profile_code='TDIFF_TOL', version=1, definition=before_definition),
|
||||
_detail(profile_id=2, profile_code='TDIFF_TOL', version=2, definition=after_definition),
|
||||
)
|
||||
|
||||
field_item = next(item for item in result['items'] if item['entity_type'] == 'line_field_region')
|
||||
assert field_item['change_type'] == 'modified'
|
||||
assert any(change['key'] == 'field_code' for change in field_item['changes'])
|
||||
assert all(change['key'] != 'region' for change in field_item['changes'])
|
||||
|
||||
|
||||
def test_compare_profile_details_ignores_exclusion_region_reorder():
|
||||
"""排除区数组重排不应制造虚假的 added/removed。"""
|
||||
before_definition = _definition()
|
||||
after_definition = _definition()
|
||||
after_definition['table_regions'][0]['exclusion_regions'] = list(reversed(after_definition['table_regions'][0]['exclusion_regions']))
|
||||
|
||||
result = diff_service.compare_profile_details(
|
||||
_detail(profile_id=1, profile_code='TDIFF_EXC', version=1, definition=before_definition),
|
||||
_detail(profile_id=2, profile_code='TDIFF_EXC', version=2, definition=after_definition),
|
||||
)
|
||||
|
||||
exclusion_items = [item for item in result['items'] if item['entity_type'] == 'exclusion_region']
|
||||
assert exclusion_items
|
||||
assert all(item['change_type'] == 'unchanged' for item in exclusion_items)
|
||||
|
||||
|
||||
def test_profile_diff_route_defaults_to_previous_and_blocks_cross_family(app, admin_jwt_headers):
|
||||
"""路由默认对比上一版本,显式跨模板比较必须返回领域校验错误。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
first = _profile(schema.id, profile_code='TDIFF_ROUTE', version=1, definition=_definition(), status='retired')
|
||||
changed = _definition()
|
||||
changed['order_field_layouts'][0]['required'] = False
|
||||
second = _profile(schema.id, profile_code='TDIFF_ROUTE', version=2, definition=changed)
|
||||
other = _profile(schema.id, profile_code='TDIFF_OTHER', version=1, definition=_definition())
|
||||
db.session.commit()
|
||||
second_id = int(second.id)
|
||||
other_id = int(other.id)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{second_id}/diff',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload['base_profile']['version'] == 2
|
||||
assert payload['compare_profile']['version'] == 1
|
||||
assert payload['comparison_mode'] == 'previous'
|
||||
assert payload['summary']['modified'] >= 1
|
||||
|
||||
invalid = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{second_id}/diff?against_profile_id={other_id}',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
assert parse_api_error(invalid.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
backend/tests/test_order_document_profile_draft_governance.py
|
||||
|
||||
用途:验证订单模板草稿 Revision、编辑租约和 operation_id 审计链。
|
||||
依赖:Profile service、Lease service、Revision service 与既有 Profile 测试夹具。
|
||||
逻辑:覆盖有效保存、幂等重试、单写者冲突、确认接管和恢复历史快照,避免治理问题流入向导与自动保存阶段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfileAudit, ShippingOrderDocumentProfileDraftRevision
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_revision_service as revision_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from tests.test_shipping_order_document_profile_service import _data, _schema_version
|
||||
|
||||
|
||||
def _lease(profile_id: int, *, session_id: str, operation_id: str) -> dict:
|
||||
"""为测试草稿申请独立标签租约,确保写入经过与生产相同的单写者校验。"""
|
||||
return lease_service.acquire_lease(
|
||||
profile_id,
|
||||
actor_id=None,
|
||||
browser_session_id=session_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
|
||||
|
||||
def test_draft_save_creates_immutable_revision_and_same_operation_is_idempotent(app):
|
||||
"""关键断言:同一 operation 重试不重复 Revision,不同有效保存才追加快照。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='create-op')
|
||||
lease = _lease(draft['id'], session_id='tab-a', operation_id='lease-op')
|
||||
payload = _data(schema.id)
|
||||
payload['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.6
|
||||
payload.update({'expected_lock_version': draft['lock_version'], 'change_note': 'first edit'})
|
||||
first = profile_service.save_draft(
|
||||
payload,
|
||||
actor_id=None,
|
||||
profile_id=draft['id'],
|
||||
browser_session_id='tab-a',
|
||||
lease_token=lease['lease_token'],
|
||||
operation_id='same-save-op',
|
||||
enforce_lease=True,
|
||||
)
|
||||
retry = profile_service.save_draft(
|
||||
{**payload, 'expected_lock_version': first['lock_version']},
|
||||
actor_id=None,
|
||||
profile_id=draft['id'],
|
||||
browser_session_id='tab-a',
|
||||
lease_token=lease['lease_token'],
|
||||
operation_id='same-save-op',
|
||||
enforce_lease=True,
|
||||
)
|
||||
revisions = revision_service.list_revisions(draft['id'])
|
||||
assert first['draft_revision']['revision_no'] == retry['draft_revision']['revision_no']
|
||||
assert len(revisions) == 2
|
||||
assert revisions[0]['operation_id'] == 'same-save-op'
|
||||
|
||||
|
||||
def test_edit_lease_conflict_takeover_and_restore_append_new_revision(app):
|
||||
"""关键断言:他标签无法写入;确认接管后可恢复旧内容且历史 Revision 不被覆盖。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='create-restore-op')
|
||||
first_lease = _lease(draft['id'], session_id='tab-first', operation_id='first-lease-op')
|
||||
with pytest.raises(Exception) as conflict:
|
||||
_lease(draft['id'], session_id='tab-second', operation_id='second-lease-op')
|
||||
assert getattr(conflict.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT'
|
||||
|
||||
changed = _data(schema.id)
|
||||
changed['display_name'] = 'Changed profile name'
|
||||
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.7
|
||||
changed['expected_lock_version'] = draft['lock_version']
|
||||
saved = profile_service.save_draft(
|
||||
changed,
|
||||
actor_id=None,
|
||||
profile_id=draft['id'],
|
||||
browser_session_id='tab-first',
|
||||
lease_token=first_lease['lease_token'],
|
||||
operation_id='changed-save-op',
|
||||
enforce_lease=True,
|
||||
)
|
||||
second_lease = lease_service.acquire_lease(
|
||||
draft['id'], actor_id=None, browser_session_id='tab-second', operation_id='takeover-op', confirm_takeover=True,
|
||||
)
|
||||
restored = revision_service.restore_revision(
|
||||
draft['id'],
|
||||
1,
|
||||
actor_id=None,
|
||||
browser_session_id='tab-second',
|
||||
lease_token=second_lease['lease_token'],
|
||||
expected_lock_version=saved['lock_version'],
|
||||
operation_id='restore-op',
|
||||
)
|
||||
rows = ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=draft['id']).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no).all()
|
||||
events = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=draft['id'], operation_id='restore-op').all()
|
||||
assert [row.revision_no for row in rows] == [1, 2, 3]
|
||||
assert restored['draft_revision']['revision_no'] == 3
|
||||
assert rows[0].definition_snapshot_json == rows[2].definition_snapshot_json
|
||||
assert any(item.event_type == 'draft_saved' and item.revision_no == 3 for item in events)
|
||||
assert db.session.get(ShippingOrderDocumentProfileDraftRevision, rows[0].id).operation_id == 'create-restore-op'
|
||||
|
||||
|
||||
def test_edit_lease_can_renew_and_release_for_another_writer(app):
|
||||
"""关键断言:租约可续租并主动释放;释放后另一标签无需接管即可取得写权限。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='lease-lifecycle-create')
|
||||
first = _lease(draft['id'], session_id='tab-renew', operation_id='lease-lifecycle-acquire')
|
||||
renewed = lease_service.renew_lease(
|
||||
draft['id'], actor_id=None, browser_session_id='tab-renew', lease_token=first['lease_token'],
|
||||
operation_id='lease-lifecycle-renew',
|
||||
)
|
||||
assert renewed['state'] == 'active'
|
||||
lease_service.release_lease(
|
||||
draft['id'], actor_id=None, browser_session_id='tab-renew', lease_token=renewed['lease_token'],
|
||||
operation_id='lease-lifecycle-release',
|
||||
)
|
||||
second = _lease(draft['id'], session_id='tab-after-release', operation_id='lease-lifecycle-second')
|
||||
assert second['browser_session_id'] == 'tab-after-release'
|
||||
@@ -0,0 +1,35 @@
|
||||
"""验证订单模板草稿治理迁移的升级与回退合同。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_document_profile_draft_governance_migration_contract():
|
||||
"""Revision、Lease 和审计操作身份必须可升级回退,且不依赖无关业务表。"""
|
||||
migration = importlib.import_module('migrations.versions.7c8d9e0f1a2b_add_order_profile_draft_governance')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('users', 'shipping_order_document_profiles'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_order_document_profile_audits', metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert {
|
||||
'shipping_order_document_profile_draft_revisions',
|
||||
'shipping_order_document_profile_edit_leases',
|
||||
} <= set(inspector.get_table_names())
|
||||
audit_columns = {item['name'] for item in inspector.get_columns('shipping_order_document_profile_audits')}
|
||||
assert {'operation_id', 'browser_session_id', 'revision_no'} <= audit_columns
|
||||
migration.downgrade()
|
||||
assert 'shipping_order_document_profile_draft_revisions' not in set(sa.inspect(connection).get_table_names())
|
||||
@@ -0,0 +1,62 @@
|
||||
"""验证订单模板样本冻结证据迁移的升级与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_document_profile_evidence_migration_contract():
|
||||
"""样本冻结证据字段必须可升级回退,且不依赖业务表全量存在。"""
|
||||
migration = importlib.import_module('migrations.versions.3e4f5a6b7c8d_freeze_order_profile_sample_evidence')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('shipping_order_schema_versions', 'shipping_notice_documents', 'users', 'shipping_document_layout_versions'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_order_document_profiles',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_document_profile_samples',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('profile_id', sa.Integer, nullable=False),
|
||||
sa.Column('document_id', sa.Integer, nullable=False),
|
||||
sa.Column('table_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('sample_role', sa.String(length=16), nullable=False),
|
||||
sa.Column('created_by_id', sa.Integer, nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
columns = {
|
||||
item['name']
|
||||
for item in sa.inspect(connection).get_columns('shipping_order_document_profile_samples')
|
||||
}
|
||||
assert {
|
||||
'layout_version_id',
|
||||
'source_content_hash',
|
||||
'layout_payload_checksum',
|
||||
'layout_contract_version',
|
||||
'parser_key',
|
||||
'parser_name',
|
||||
'parser_version',
|
||||
'evidence_frozen_at',
|
||||
'source_filename_snapshot',
|
||||
'page_count_snapshot',
|
||||
'table_identity_snapshot',
|
||||
} <= columns
|
||||
migration.downgrade()
|
||||
downgraded = {
|
||||
item['name']
|
||||
for item in sa.inspect(connection).get_columns('shipping_order_document_profile_samples')
|
||||
}
|
||||
assert 'layout_version_id' not in downgraded
|
||||
assert 'table_identity_snapshot' not in downgraded
|
||||
@@ -0,0 +1,477 @@
|
||||
"""
|
||||
backend/tests/test_order_document_profile_governance_service.py
|
||||
|
||||
用途:验证订单模板版本中心的审计时间线与实际使用投影。
|
||||
依赖:Profile 审计/使用 service、管理员 JWT 路由、Run/Unit/RouteDecision 最小 ORM 夹具。
|
||||
逻辑:覆盖 request_id 过滤、游标分页、unknown actor 降级、最新 RouteDecision 去重与 snapshot_identity_match。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
Agent,
|
||||
FileAsset,
|
||||
Job,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_audit_service as audit_service
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_jwt_headers(app):
|
||||
"""创建 Bearer JWT 管理员头,覆盖 require_admin 的当前鉴权方式。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='profile-governance-admin').first()
|
||||
if not user:
|
||||
user = User(
|
||||
username='profile-governance-admin',
|
||||
email='profile-governance-admin@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def _schema_version() -> ShippingOrderSchemaVersion:
|
||||
"""创建最小已发布 Schema,供 Profile 与 Run 共享。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Governance Schema')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
checksum='a' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.commit()
|
||||
return version
|
||||
|
||||
|
||||
def _profile(schema_version_id: int, *, profile_code: str = 'GOV_PROFILE', version: int = 2) -> ShippingOrderDocumentProfile:
|
||||
"""创建可用于治理视图的最小已发布模板版本。"""
|
||||
row = ShippingOrderDocumentProfile(
|
||||
profile_code=profile_code,
|
||||
display_name=profile_code,
|
||||
version=version,
|
||||
status='published',
|
||||
schema_version_id=schema_version_id,
|
||||
structure_fingerprint='b' * 64,
|
||||
definition_json={
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'document_type': 'purchase_order', 'page_pattern': 'one_or_more', 'required_anchors': [], 'optional_anchors': [], 'minimum_score': 1, 'minimum_margin': 0},
|
||||
'table_regions': [],
|
||||
'order_field_layouts': [],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
},
|
||||
checksum='c' * 64,
|
||||
template_mode='coordinate_v2',
|
||||
published_at=datetime.utcnow(),
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def _document_and_intake(user_id: int, *, suffix: str) -> tuple[ShippingNoticeIntake, ShippingNoticeDocument]:
|
||||
"""创建 usage 投影需要的最小 Intake/Document。"""
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-GOV-{suffix}',
|
||||
owner_user_id=user_id,
|
||||
original_filename=f'usage-{suffix}.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'usage-{suffix}.pdf',
|
||||
content_hash=(suffix.lower() * 64)[:64],
|
||||
file_size=1,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=f'SNI-GOV-{suffix}',
|
||||
asset_id=asset.id,
|
||||
user_id=user_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key=f'usage-{suffix}.pdf',
|
||||
filename=f'usage-{suffix}.pdf',
|
||||
content_hash=(suffix.lower() * 64)[:64],
|
||||
classification='supporting',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
return intake, document
|
||||
|
||||
|
||||
def _run_context(
|
||||
schema_version_id: int,
|
||||
*,
|
||||
suffix: str,
|
||||
) -> tuple[User, Agent, ShippingOrderExtractionRun, ShippingOrderExtractionPlan]:
|
||||
"""创建 usage 投影需要的最小 Run。"""
|
||||
user = User(username=f'usage-user-{suffix}', email=f'usage-user-{suffix}@example.com', role='admin', status='active')
|
||||
agent = Agent(
|
||||
name=f'Usage Agent {suffix}',
|
||||
agent_code=f'usage-agent-{suffix}',
|
||||
runtime_provider='hybrid',
|
||||
dify_app_id=f'usage-agent-{suffix}',
|
||||
dify_api_key='test-key',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'RUN-{suffix}',
|
||||
user_id=user.id,
|
||||
owner_agent_id=agent.id,
|
||||
conversation_id=f'conversation-{suffix}',
|
||||
schema_version_id=schema_version_id,
|
||||
input_snapshot_hash=f'{suffix.lower():0<64}'[:64],
|
||||
input_snapshot_json={'documents': [suffix]},
|
||||
idempotency_key=f'usage-{suffix}',
|
||||
status='completed',
|
||||
phase='completed',
|
||||
current_stage_code='completed',
|
||||
progress_health='normal',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
plan = ShippingOrderExtractionPlan(
|
||||
run_id=run.id,
|
||||
plan_version='plan.v1',
|
||||
input_snapshot_hash=run.input_snapshot_hash,
|
||||
status='completed',
|
||||
unit_count=0,
|
||||
)
|
||||
db.session.add(plan)
|
||||
db.session.flush()
|
||||
return user, agent, run, plan
|
||||
|
||||
|
||||
def test_profile_audit_service_uses_cursor_pagination_and_unknown_actor(app):
|
||||
"""时间线必须稳定翻页,缺失操作者时降级为 unknown actor。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
profile = _profile(schema.id, profile_code='AUDIT_PROFILE')
|
||||
actor = User(username='audit-actor', email='audit-actor@example.com', role='admin', status='active')
|
||||
db.session.add(actor)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingOrderDocumentProfileAudit(
|
||||
profile_id=profile.id,
|
||||
event_type='draft_saved',
|
||||
actor_id=None,
|
||||
request_id='req-older',
|
||||
detail_json={'version': 1},
|
||||
),
|
||||
ShippingOrderDocumentProfileAudit(
|
||||
profile_id=profile.id,
|
||||
event_type='published',
|
||||
actor_id=actor.id,
|
||||
request_id='req-newer',
|
||||
detail_json={'version': 2},
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
first = audit_service.list_profile_audit_events(
|
||||
profile_id=profile.id,
|
||||
actor_id=actor.id,
|
||||
request_id='audit-list-1',
|
||||
limit=1,
|
||||
)
|
||||
assert [item['event_type'] for item in first['items']] == ['published']
|
||||
assert first['items'][0]['actor']['display_name'] == 'audit-actor'
|
||||
assert first['page']['has_more'] is True
|
||||
|
||||
second = audit_service.list_profile_audit_events(
|
||||
profile_id=profile.id,
|
||||
actor_id=actor.id,
|
||||
request_id='audit-list-2',
|
||||
before_id=first['page']['next_before_id'],
|
||||
limit=1,
|
||||
)
|
||||
assert [item['event_type'] for item in second['items']] == ['draft_saved']
|
||||
assert second['items'][0]['actor']['display_name'] == 'unknown_actor'
|
||||
assert second['page']['has_more'] is False
|
||||
|
||||
|
||||
def test_profile_audit_route_filters_request_id_and_logs_view_event(app, admin_jwt_headers):
|
||||
"""审计接口必须支持 request_id 过滤,且访问行为本身要留痕。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
profile = _profile(schema.id, profile_code='AUDIT_ROUTE_PROFILE')
|
||||
db.session.add_all([
|
||||
ShippingOrderDocumentProfileAudit(
|
||||
profile_id=profile.id,
|
||||
event_type='published',
|
||||
actor_id=None,
|
||||
request_id='req-match',
|
||||
detail_json={'version': 2},
|
||||
),
|
||||
ShippingOrderDocumentProfileAudit(
|
||||
profile_id=profile.id,
|
||||
event_type='draft_saved',
|
||||
actor_id=None,
|
||||
request_id='req-other',
|
||||
detail_json={'version': 1},
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
profile_id = int(profile.id)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/audit-events?request_id_filter=req-match&event_type=published&limit=20',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert [item['request_id'] for item in payload['items']] == ['req-match']
|
||||
assert [item['event_type'] for item in payload['items']] == ['published']
|
||||
|
||||
with app.app_context():
|
||||
view_event = (
|
||||
ShippingOrderDocumentProfileAudit.query
|
||||
.filter_by(profile_id=profile_id, event_type='version_audit_viewed')
|
||||
.order_by(ShippingOrderDocumentProfileAudit.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert view_event is not None
|
||||
assert view_event.detail_json['filters']['request_id'] == 'req-match'
|
||||
|
||||
|
||||
def test_profile_usage_route_returns_latest_direct_and_snapshot_matches(app, admin_jwt_headers):
|
||||
"""实际使用只统计每个 Unit 最新 RouteDecision,并保留 snapshot_identity_match。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
profile = _profile(schema.id, profile_code='USAGE_PROFILE', version=2)
|
||||
other_profile = _profile(schema.id, profile_code='OTHER_PROFILE', version=1)
|
||||
user, _agent, run, plan = _run_context(schema.id, suffix='USAGE')
|
||||
intake_one, document_one = _document_and_intake(user.id, suffix='ONE')
|
||||
intake_two, document_two = _document_and_intake(user.id, suffix='TWO')
|
||||
job_one = Job(domain='shipping_notice', job_type='shipping_order_extraction', status='completed', business_ref=run.run_no)
|
||||
job_two = Job(domain='shipping_notice', job_type='shipping_order_extraction', status='completed', business_ref=f'{run.run_no}-2')
|
||||
job_three = Job(domain='shipping_notice', job_type='shipping_order_extraction', status='completed', business_ref=f'{run.run_no}-3')
|
||||
db.session.add_all([job_one, job_two, job_three])
|
||||
db.session.flush()
|
||||
|
||||
unit_one = ShippingOrderExtractionUnit(
|
||||
plan_id=plan.id,
|
||||
intake_id=intake_one.id,
|
||||
document_id=document_one.id,
|
||||
position=0,
|
||||
unit_type='document_extraction',
|
||||
document_type='purchase_order',
|
||||
status='candidate_ready',
|
||||
attempt_count=2,
|
||||
)
|
||||
unit_two = ShippingOrderExtractionUnit(
|
||||
plan_id=plan.id,
|
||||
intake_id=intake_two.id,
|
||||
document_id=document_two.id,
|
||||
position=1,
|
||||
unit_type='document_extraction',
|
||||
document_type='purchase_order',
|
||||
status='review_required',
|
||||
attempt_count=1,
|
||||
reason_code='profile_ambiguous',
|
||||
)
|
||||
db.session.add_all([unit_one, unit_two])
|
||||
db.session.flush()
|
||||
plan.unit_count = 2
|
||||
|
||||
db.session.add_all([
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit_one.id,
|
||||
job_id=job_one.id,
|
||||
attempt_no=1,
|
||||
decision='deterministic',
|
||||
match_status='unique_match',
|
||||
selected_profile_id=other_profile.id,
|
||||
selected_profile_code=other_profile.profile_code,
|
||||
selected_profile_version=other_profile.version,
|
||||
selected_profile_checksum=other_profile.checksum,
|
||||
auto_create_approved=False,
|
||||
candidate_count=1,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=1,
|
||||
parsed_table_count=1,
|
||||
approved_table_count=0,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=[],
|
||||
),
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit_one.id,
|
||||
job_id=job_two.id,
|
||||
attempt_no=2,
|
||||
decision='deterministic',
|
||||
match_status='unique_match',
|
||||
selected_profile_id=profile.id,
|
||||
selected_profile_code=profile.profile_code,
|
||||
selected_profile_version=profile.version,
|
||||
selected_profile_checksum=profile.checksum,
|
||||
auto_create_approved=True,
|
||||
candidate_count=1,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=1,
|
||||
parsed_table_count=1,
|
||||
approved_table_count=1,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=[],
|
||||
),
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit_two.id,
|
||||
job_id=job_three.id,
|
||||
attempt_no=1,
|
||||
decision='review_required',
|
||||
match_status='ambiguous',
|
||||
selected_profile_id=None,
|
||||
selected_profile_code=profile.profile_code,
|
||||
selected_profile_version=profile.version,
|
||||
selected_profile_checksum=profile.checksum,
|
||||
auto_create_approved=False,
|
||||
candidate_count=2,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=0,
|
||||
parsed_table_count=0,
|
||||
approved_table_count=0,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=['profile_ambiguous'],
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
profile_id = int(profile.id)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/usages?limit=20',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert len(payload['items']) == 2
|
||||
assert payload['items'][0]['run_no'] == 'RUN-USAGE'
|
||||
assert payload['items'][0]['identity_match_mode'] in {'direct_profile_id', 'snapshot_identity_match'}
|
||||
assert {item['identity_match_mode'] for item in payload['items']} == {'direct_profile_id', 'snapshot_identity_match'}
|
||||
assert all(item['diagnostic_entry']['route_name'] == 'AdminShippingOrderExtractionRuns' for item in payload['items'])
|
||||
assert all(item['document_label'] != 'usage-ONE.pdf' for item in payload['items'])
|
||||
|
||||
with app.app_context():
|
||||
view_event = (
|
||||
ShippingOrderDocumentProfileAudit.query
|
||||
.filter_by(profile_id=profile_id, event_type='version_usage_viewed')
|
||||
.order_by(ShippingOrderDocumentProfileAudit.id.desc())
|
||||
.first()
|
||||
)
|
||||
assert view_event is not None
|
||||
assert view_event.detail_json['result_count'] == 2
|
||||
|
||||
|
||||
def test_retired_profile_usage_route_still_returns_historical_records(app, admin_jwt_headers):
|
||||
"""retired 版本仍需可查看历史使用记录,不能因状态变化丢失审计入口。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
profile = _profile(schema.id, profile_code='RETIRED_USAGE_PROFILE', version=3)
|
||||
profile.status = 'retired'
|
||||
profile.retired_at = datetime.utcnow()
|
||||
user, _agent, run, plan = _run_context(schema.id, suffix='RETIREDUSE')
|
||||
intake, document = _document_and_intake(user.id, suffix='RETIRED')
|
||||
job = Job(domain='shipping_notice', job_type='shipping_order_extraction', status='completed', business_ref=run.run_no)
|
||||
db.session.add(job)
|
||||
db.session.flush()
|
||||
|
||||
unit = ShippingOrderExtractionUnit(
|
||||
plan_id=plan.id,
|
||||
intake_id=intake.id,
|
||||
document_id=document.id,
|
||||
position=0,
|
||||
unit_type='document_extraction',
|
||||
document_type='purchase_order',
|
||||
status='candidate_ready',
|
||||
attempt_count=1,
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
plan.unit_count = 1
|
||||
db.session.add(
|
||||
ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id,
|
||||
unit_id=unit.id,
|
||||
job_id=job.id,
|
||||
attempt_no=1,
|
||||
decision='deterministic',
|
||||
match_status='unique_match',
|
||||
selected_profile_id=profile.id,
|
||||
selected_profile_code=profile.profile_code,
|
||||
selected_profile_version=profile.version,
|
||||
selected_profile_checksum=profile.checksum,
|
||||
auto_create_approved=False,
|
||||
candidate_count=1,
|
||||
table_count=1,
|
||||
document_table_count=1,
|
||||
business_table_count=1,
|
||||
matched_table_count=1,
|
||||
parsed_table_count=1,
|
||||
approved_table_count=0,
|
||||
candidate_summary_json=[],
|
||||
fallback_reason_codes_json=[],
|
||||
),
|
||||
)
|
||||
db.session.commit()
|
||||
profile_id = int(profile.id)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/usages?limit=20',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload['profile']['status'] == 'retired'
|
||||
assert len(payload['items']) == 1
|
||||
assert payload['items'][0]['run_no'] == 'RUN-RETIREDUSE'
|
||||
@@ -0,0 +1,222 @@
|
||||
"""
|
||||
backend/tests/test_order_document_profile_preview_service.py
|
||||
|
||||
用途:验证模板版本中心的冻结样本只读预览链路。
|
||||
依赖:Profile 发布流程、JWT 管理鉴权、冻结样本预览 service。
|
||||
逻辑:只读画布只能读取冻结样本绑定;token 必须一次性、隔离到管理员与样本,并忽略 document 当前最新 layout。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import ShippingOrderDocumentProfileSample, ShippingNoticeDocument, User
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality_service
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
from tests.test_shipping_order_document_profile_service import _bind_ready_profile_sample, _data, _schema_version
|
||||
|
||||
|
||||
class _PreviewStore:
|
||||
"""模拟一次性 GETDEL 语义,验证 token 不能重放也不能跨路径复用。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._items: dict[str, str] = {}
|
||||
|
||||
def setex(self, key, _ttl, value):
|
||||
self._items[str(key)] = str(value)
|
||||
|
||||
def getdel(self, key):
|
||||
return self._items.pop(str(key), None)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers_factory(app):
|
||||
"""为管理端路由生成 Bearer JWT,覆盖当前 require_admin 鉴权口径。"""
|
||||
|
||||
def _build(username: str):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if not user:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {'Authorization': f'Bearer {token}'}
|
||||
|
||||
return _build
|
||||
|
||||
|
||||
def _publish_profile_with_frozen_sample(app, monkeypatch) -> tuple[int, int, int]:
|
||||
"""创建已发布模板和冻结 annotation 样本,返回 profile/sample/document 身份。"""
|
||||
with app.app_context():
|
||||
# 这组阶段 4 用例只验证冻结样本只读预览,不重复搭建阶段 7 的盲测门禁数据。
|
||||
monkeypatch.setattr(quality_service, 'assert_profile_publishable', lambda _profile: None)
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None)
|
||||
_bind_ready_profile_sample(draft['id'], sample_role='annotation')
|
||||
published = profile_service.publish(
|
||||
draft['id'],
|
||||
actor_id=None,
|
||||
expected_lock_version=draft['lock_version'],
|
||||
)
|
||||
sample = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=published['id'],
|
||||
sample_role='annotation',
|
||||
).one()
|
||||
return int(published['id']), int(sample.id), int(sample.document_id)
|
||||
|
||||
|
||||
def test_frozen_sample_preview_authorizes_once_and_cannot_replay(app, monkeypatch, admin_headers_factory):
|
||||
"""冻结样本预览必须返回 no-store PNG,且 token 被消费一次后立即失效。"""
|
||||
profile_id, sample_id, _document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
|
||||
preview_store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store)
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-frozen-preview')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content, render_scale: [SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8))],
|
||||
)
|
||||
|
||||
client = app.test_client()
|
||||
headers = admin_headers_factory('frozen-preview-admin')
|
||||
authorized = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages',
|
||||
headers=headers,
|
||||
)
|
||||
assert authorized.status_code == 200
|
||||
assert authorized.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
payload = parse_api_data(authorized.get_json())
|
||||
assert payload['sample_binding_id'] == sample_id
|
||||
grant = payload['pages'][0]
|
||||
|
||||
image = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages/1',
|
||||
query_string={'preview_token': grant['preview_token']},
|
||||
headers=headers,
|
||||
)
|
||||
assert image.status_code == 200
|
||||
assert image.mimetype == 'image/png'
|
||||
assert image.headers['Cache-Control'] == 'private, no-store, max-age=0'
|
||||
|
||||
replay = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages/1',
|
||||
query_string={'preview_token': grant['preview_token']},
|
||||
headers=headers,
|
||||
)
|
||||
assert replay.status_code == 404
|
||||
assert parse_api_error(replay.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND'
|
||||
|
||||
|
||||
def test_frozen_sample_preview_rejects_unfrozen_sample_binding(app, monkeypatch, admin_headers_factory):
|
||||
"""未发布样本没有冻结证据时,详情页样本画布必须显式报错而不是降级读取当前文档。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None)
|
||||
sample = _bind_ready_profile_sample(draft['id'], sample_role='annotation')
|
||||
profile_id = int(draft['id'])
|
||||
sample_id = int(sample.id)
|
||||
|
||||
preview_store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store)
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-frozen-preview')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content, render_scale: [SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8))],
|
||||
)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages',
|
||||
headers=admin_headers_factory('frozen-preview-missing'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
error = parse_api_error(response.get_json())
|
||||
assert error['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE'
|
||||
assert 'Frozen evidence' in error['message']
|
||||
|
||||
|
||||
def test_frozen_sample_preview_uses_frozen_layout_instead_of_current_layout(app, monkeypatch, admin_headers_factory):
|
||||
"""文档后来出现新 current layout 时,历史版本只读画布仍必须绑定发布时冻结的 layout_version。"""
|
||||
profile_id, sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
|
||||
with app.app_context():
|
||||
document = db.session.get(ShippingNoticeDocument, document_id)
|
||||
assert document is not None
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'status': 'ready',
|
||||
'provider': 'mineru',
|
||||
'pages': [{'page_no': 1}],
|
||||
'tables': [{
|
||||
'table_id': 'new-current-layout',
|
||||
'page_no': 1,
|
||||
'rows': [{'cells': [{'text': 'changed'}]}],
|
||||
'html': '<table><tr><td>changed</td></tr></table>',
|
||||
}],
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
preview_store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store)
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-frozen-preview')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content, render_scale: [SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8))],
|
||||
)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages',
|
||||
headers=admin_headers_factory('frozen-preview-layout'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload['sample_binding_id'] == sample_id
|
||||
assert payload['page_count'] == 1
|
||||
|
||||
|
||||
def test_frozen_sample_preview_token_isolated_by_actor_and_sample(app, monkeypatch, admin_headers_factory):
|
||||
"""一次性 token 必须绑定管理员与样本,不能跨账号或跨样本路径复用。"""
|
||||
profile_id, sample_id, _document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
|
||||
preview_store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store)
|
||||
monkeypatch.setattr('app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-frozen-preview')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content, render_scale: [SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8))],
|
||||
)
|
||||
|
||||
owner_headers = admin_headers_factory('frozen-preview-owner')
|
||||
other_headers = admin_headers_factory('frozen-preview-other')
|
||||
client = app.test_client()
|
||||
authorized = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages',
|
||||
headers=owner_headers,
|
||||
)
|
||||
grant = parse_api_data(authorized.get_json())['pages'][0]
|
||||
|
||||
other_actor = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages/1',
|
||||
query_string={'preview_token': grant['preview_token']},
|
||||
headers=other_headers,
|
||||
)
|
||||
assert other_actor.status_code == 404
|
||||
|
||||
wrong_sample = client.get(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id + 1}/preview-pages/1',
|
||||
query_string={'preview_token': grant['preview_token']},
|
||||
headers=owner_headers,
|
||||
)
|
||||
assert wrong_sample.status_code == 404
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
tests/test_order_document_profile_publish_check_service.py
|
||||
|
||||
用途:验证订单模板发布检查报告的冻结、失效、逐项确认和原子消费。
|
||||
依赖:发布检查服务、Profile 草稿/租约/验证运行模型。
|
||||
逻辑:用最小受控草稿构造报告,覆盖报告不能绕过阻断项和消费幂等行为。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileValidationRun
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_publish_check_service as checks
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
from tests.test_shipping_order_document_profile_service import _data, _schema_version
|
||||
|
||||
|
||||
def _lease(profile_id: int) -> dict:
|
||||
"""取得与生产一致的编辑租约,以验证发布报告不能绕开单写者规则。"""
|
||||
return lease_service.acquire_lease(profile_id, actor_id=None, browser_session_id='publish-check-tab', operation_id='publish-check-lease')
|
||||
|
||||
|
||||
def _passing_run(profile: dict) -> ShippingOrderDocumentProfileValidationRun:
|
||||
"""构造当前 Revision 通过运行,隔离本测试对 PDF/盲测解析数据的依赖。"""
|
||||
row = ShippingOrderDocumentProfileValidationRun(
|
||||
profile_id=profile['id'], revision_no=profile['draft_revision']['revision_no'],
|
||||
definition_checksum=profile['draft_revision']['definition_checksum'], schema_version_id=profile['schema_version_id'],
|
||||
run_type='instant_check', status='passed', summary_json={}, result_snapshot_json={}, operation_id='passing-validation',
|
||||
)
|
||||
db.session.add(row); db.session.commit()
|
||||
return row
|
||||
|
||||
|
||||
def test_report_invalidates_when_draft_changes(app, monkeypatch):
|
||||
"""关键断言:报告冻结 lock/checksum,草稿任何有效保存后查询立即变 invalidated。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
|
||||
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-create')
|
||||
lease = _lease(draft['id']); run = _passing_run(draft)
|
||||
report = checks.create_report(draft['id'], data={'validation_run_id': run.id}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-report')
|
||||
changed = _data(schema.id); changed['expected_lock_version'] = draft['lock_version']; changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = .62
|
||||
profiles.save_draft(changed, actor_id=None, profile_id=draft['id'], browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-change', enforce_lease=True)
|
||||
assert checks.get_report(draft['id'], report['report_no'])['status'] == 'invalidated'
|
||||
|
||||
|
||||
def test_blocking_report_cannot_be_consumed(app):
|
||||
"""关键断言:无当前通过运行时报告可审阅但不能被任何确认请求绕过。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-block-create'); lease = _lease(draft['id'])
|
||||
report = checks.create_report(draft['id'], data={}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-block-report')
|
||||
with pytest.raises(Exception) as error:
|
||||
checks.consume_report(draft['id'], report['report_no'], data={'confirmed_warning_keys': []}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-block-consume')
|
||||
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID'
|
||||
|
||||
|
||||
def test_report_consumes_once_after_each_warning_confirmation(app, monkeypatch):
|
||||
"""关键断言:警告必须完整逐项确认,成功消费后重试只返回同一发布版本。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
|
||||
# 本测试聚焦报告消费原子性;样本证据冻结由既有发布服务测试单独覆盖。
|
||||
monkeypatch.setattr('app.services.shipping_notice.order_document_profile_service._freeze_profile_sample_evidence', lambda *_args, **_kwargs: 0)
|
||||
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-consume-create'); lease = _lease(draft['id']); run = _passing_run(draft)
|
||||
report = checks.create_report(draft['id'], data={'validation_run_id': run.id}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-consume-report')
|
||||
keys = [str(item['key']) for item in report['warning_items']]
|
||||
if keys:
|
||||
with pytest.raises(Exception):
|
||||
checks.consume_report(draft['id'], report['report_no'], data={'confirmed_warning_keys': []}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-consume-failed')
|
||||
published = checks.consume_report(draft['id'], report['report_no'], data={'confirmed_warning_keys': keys}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-consume')
|
||||
retried = checks.consume_report(draft['id'], report['report_no'], data={'confirmed_warning_keys': keys}, actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-consume')
|
||||
assert published['status'] == retried['status'] == 'published'
|
||||
assert db.session.get(ShippingOrderDocumentProfile, draft['id']).status == 'published'
|
||||
@@ -0,0 +1,27 @@
|
||||
"""验证订单模板建议决定迁移的表结构与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_document_profile_suggestion_decision_migration_contract():
|
||||
"""关键断言:决定表关联既有 Profile/样本/Schema,且可独立回退。"""
|
||||
migration = importlib.import_module('migrations.versions.8d9e0f1a2b3c_add_order_profile_suggestion_decisions')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('users', 'shipping_order_document_profiles', 'shipping_order_document_profile_samples', 'shipping_document_layout_versions', 'shipping_order_schema_versions'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
columns = {item['name'] for item in inspector.get_columns('shipping_order_document_profile_suggestion_decisions')}
|
||||
assert {'suggestion_id', 'suggestion_checksum', 'decision', 'revision_no', 'operation_id'} <= columns
|
||||
migration.downgrade()
|
||||
assert 'shipping_order_document_profile_suggestion_decisions' not in set(sa.inspect(connection).get_table_names())
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
backend/tests/test_order_document_profile_suggestion_service.py
|
||||
|
||||
用途:验证订单模板建议决定的冻结、幂等和租约边界。
|
||||
依赖:Suggestion service、Profile/Revision/Lease service 与既有建模夹具。
|
||||
逻辑:确保算法建议只能由当前写入者决定;同建议重试不重复落库,不同决定不能篡改历史事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingOrderDocumentProfileSuggestionDecision
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from tests.test_shipping_order_document_profile_service import _data, _schema_version
|
||||
|
||||
|
||||
def _input() -> dict:
|
||||
"""构造不含文档正文的冻结建议摘要,保持测试与生产隐私边界一致。"""
|
||||
summary = {'algorithm_version': 'coordinate-suggest-v1', 'kind': 'page_regions', 'page_no': 1, 'region_count': 3}
|
||||
identity = suggestion_service.suggestion_identity(summary)
|
||||
return {**identity, 'suggestion_summary': summary, 'decision': 'accepted'}
|
||||
|
||||
|
||||
def test_suggestion_decision_is_idempotent_and_immutable(app):
|
||||
"""关键断言:相同建议的重试只保留一个决定,不同决定返回冲突。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-create')
|
||||
lease = lease_service.acquire_lease(draft['id'], actor_id=None, browser_session_id='suggestion-tab', operation_id='suggestion-lease')
|
||||
payload = _input()
|
||||
first = suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-tab', lease_token=lease['lease_token'], operation_id='suggestion-decision')
|
||||
retry = suggestion_service.decide(draft['id'], data=payload, actor_id=None, browser_session_id='suggestion-tab', lease_token=lease['lease_token'], operation_id='suggestion-retry')
|
||||
assert first['suggestion_id'] == retry['suggestion_id']
|
||||
assert ShippingOrderDocumentProfileSuggestionDecision.query.filter_by(profile_id=draft['id']).count() == 1
|
||||
with pytest.raises(Exception) as conflict:
|
||||
suggestion_service.decide(draft['id'], data={**payload, 'decision': 'rejected'}, actor_id=None, browser_session_id='suggestion-tab', lease_token=lease['lease_token'], operation_id='suggestion-conflict')
|
||||
assert getattr(conflict.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_CONFLICT'
|
||||
|
||||
|
||||
def test_suggestion_decision_requires_active_lease(app):
|
||||
"""关键断言:建议决定和草稿保存一样必须经过当前标签单写者租约。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='suggestion-lease-create')
|
||||
with pytest.raises(Exception) as missing:
|
||||
suggestion_service.decide(draft['id'], data=_input(), actor_id=None, browser_session_id='missing-tab', lease_token='invalid', operation_id='suggestion-missing')
|
||||
assert getattr(missing.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED'
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
tests/test_order_document_profile_validation_service.py
|
||||
|
||||
用途:验证订单模板不可变验证运行的冻结、过期和样本隔离约束。
|
||||
依赖:Profile 验证服务、草稿保存服务与编辑租约服务。
|
||||
逻辑:先创建真实草稿 Revision,再验证运行不会随草稿修改而改写,并拒绝盲测样本进入当前样本路径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from tests.test_shipping_order_document_profile_service import _data, _schema_version
|
||||
|
||||
|
||||
def _lease(profile_id: int) -> dict:
|
||||
"""为验证测试取得真实草稿租约,确保验证接口不能绕开单写者保护。"""
|
||||
return lease_service.acquire_lease(profile_id, actor_id=None, browser_session_id='validation-test-tab', operation_id='validation-lease')
|
||||
|
||||
|
||||
def test_instant_run_freezes_revision_and_becomes_stale_without_history_mutation(app):
|
||||
"""关键断言:草稿改变后旧运行仅在查询 DTO 中变 stale,数据库原状态与 checksum 均保持不变。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='validation-create')
|
||||
lease = _lease(draft['id'])
|
||||
run = validation_service.run_instant_check(
|
||||
draft['id'], data={}, actor_id=None, browser_session_id='validation-test-tab',
|
||||
lease_token=lease['lease_token'], operation_id='instant-check',
|
||||
)
|
||||
stored = db.session.get(ShippingOrderDocumentProfileValidationRun, run['id'])
|
||||
frozen_checksum = stored.definition_checksum
|
||||
changed = _data(schema.id)
|
||||
changed['definition']['table_regions'][0]['line_layouts'][0]['field_regions'][0]['region']['x1'] = 0.61
|
||||
changed['expected_lock_version'] = draft['lock_version']
|
||||
profile_service.save_draft(
|
||||
changed, actor_id=None, profile_id=draft['id'], browser_session_id='validation-test-tab',
|
||||
lease_token=lease['lease_token'], operation_id='validation-change', enforce_lease=True,
|
||||
)
|
||||
listed = validation_service.list_runs(draft['id'])
|
||||
stored_after = db.session.get(ShippingOrderDocumentProfileValidationRun, run['id'])
|
||||
assert run['revision_no'] == 1
|
||||
assert listed[0]['status'] == 'stale'
|
||||
assert stored_after.definition_checksum == frozen_checksum
|
||||
assert stored_after.status == 'passed'
|
||||
|
||||
|
||||
def test_current_sample_rejects_blind_test_binding(app):
|
||||
"""关键断言:盲测绑定不能被指定为当前样本,避免真值与建模试运行混用。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='validation-blind-create')
|
||||
sample = ShippingOrderDocumentProfileSample(profile_id=draft['id'], document_id=9999, table_id='t1', sample_role='blind_test')
|
||||
db.session.add(sample)
|
||||
db.session.commit()
|
||||
with pytest.raises(Exception) as error:
|
||||
validation_service._sample(db.session.get(ShippingOrderDocumentProfile, draft['id']), sample.id)
|
||||
assert getattr(error.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
|
||||
|
||||
def test_failed_current_sample_run_remains_queryable(app):
|
||||
"""关键断言:运行时样本证据不可用也必须保存 failed 摘要,方便后续审计而非吞掉失败。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None, operation_id='validation-failed-create')
|
||||
sample = ShippingOrderDocumentProfileSample(profile_id=draft['id'], document_id=9998, table_id='missing', sample_role='annotation')
|
||||
db.session.add(sample)
|
||||
db.session.commit()
|
||||
lease = _lease(draft['id'])
|
||||
result = validation_service.run_current_sample(
|
||||
draft['id'], data={'sample_binding_id': sample.id}, actor_id=None,
|
||||
browser_session_id='validation-test-tab', lease_token=lease['lease_token'], operation_id='failed-sample-run',
|
||||
)
|
||||
assert result['status'] == 'failed'
|
||||
assert validation_service.list_runs(draft['id'])[0]['id'] == result['id']
|
||||
@@ -0,0 +1,339 @@
|
||||
"""订单模板版本中心读接口的服务层契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentProfileTestRun,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_version_service as version_service
|
||||
from tests.conftest import parse_api_data, parse_api_error
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_jwt_headers(app):
|
||||
"""创建 admin 用户并签发 Bearer JWT,覆盖 require_admin 的当前鉴权口径。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username='admin').first()
|
||||
if not user:
|
||||
user = User(username='admin', email='admin@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {
|
||||
'Authorization': f'Bearer {token}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
|
||||
def _schema_version() -> ShippingOrderSchemaVersion:
|
||||
"""创建最小发布 Schema,供版本详情 DTO 读取摘要使用。"""
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order Version Center')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
checksum='a' * 64,
|
||||
published_at=datetime.utcnow(),
|
||||
definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.commit()
|
||||
return version
|
||||
|
||||
|
||||
def _profile(
|
||||
schema_version_id: int,
|
||||
*,
|
||||
profile_code: str,
|
||||
version: int,
|
||||
status: str,
|
||||
display_name: str | None = None,
|
||||
) -> ShippingOrderDocumentProfile:
|
||||
"""创建最小模板版本记录,避免测试依赖阶段 3 画布结构。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code=profile_code,
|
||||
display_name=display_name or profile_code,
|
||||
version=version,
|
||||
status=status,
|
||||
schema_version_id=schema_version_id,
|
||||
structure_fingerprint=f'{version}' * 64,
|
||||
definition_json={
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {
|
||||
'document_type': 'purchase_order',
|
||||
'page_pattern': 'one_or_more',
|
||||
'required_anchors': [],
|
||||
'optional_anchors': [],
|
||||
'minimum_score': 1,
|
||||
'minimum_margin': 0,
|
||||
},
|
||||
'table_regions': [],
|
||||
'order_field_layouts': [],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
},
|
||||
checksum=(f'{version}' * 64)[:64] if status in {'published', 'retired'} else None,
|
||||
published_at=datetime.utcnow() if status == 'published' else None,
|
||||
retired_at=datetime.utcnow() if status == 'retired' else None,
|
||||
lock_version=1,
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
return profile
|
||||
|
||||
|
||||
def _document(owner: User, *, filename: str, content_hash: str) -> ShippingNoticeDocument:
|
||||
"""创建版本详情需要的安全样本文档实体。"""
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-{filename}',
|
||||
owner_user_id=owner.id,
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=filename,
|
||||
content_hash=content_hash,
|
||||
file_size=1,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=f'SNI-{filename}'.upper(),
|
||||
asset_id=asset.id,
|
||||
user_id=owner.id,
|
||||
purpose='order_document_profile_sample',
|
||||
parse_status='parsed',
|
||||
parser_version='v-test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key=filename,
|
||||
filename=filename,
|
||||
content_hash=content_hash,
|
||||
classification='supporting',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
return document
|
||||
|
||||
|
||||
def test_list_profile_families_prefers_published_then_draft_then_retired(app):
|
||||
"""模板族默认选版必须优先 published,其次 draft,最后最新 retired。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
_profile(schema.id, profile_code='T01', version=1, status='retired', display_name='Template 01')
|
||||
published = _profile(schema.id, profile_code='T01', version=2, status='published', display_name='Template 01')
|
||||
_profile(schema.id, profile_code='T01', version=3, status='draft', display_name='Template 01')
|
||||
retired_only = _profile(schema.id, profile_code='T02', version=4, status='retired', display_name='Template 02')
|
||||
db.session.commit()
|
||||
|
||||
families = version_service.list_profile_families()
|
||||
t01 = next(item for item in families if item['profile_code'] == 'T01')
|
||||
t02 = next(item for item in families if item['profile_code'] == 'T02')
|
||||
assert t01['published_version'] == 2
|
||||
assert t01['draft_version'] == 3
|
||||
assert t01['default_profile_id'] == published.id
|
||||
assert t01['default_version'] == 2
|
||||
assert t01['version_count'] == 3
|
||||
assert t02['published_version'] is None
|
||||
assert t02['draft_version'] is None
|
||||
assert t02['default_profile_id'] == retired_only.id
|
||||
assert t02['default_version'] == 4
|
||||
|
||||
|
||||
def test_list_family_versions_and_get_detail_by_family_version_are_scoped(app):
|
||||
"""版本列表与详情解析只能在同一 profile_code 内工作,不存在版本返回明确 404。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
_profile(schema.id, profile_code='T01', version=1, status='retired')
|
||||
target = _profile(schema.id, profile_code='T01', version=2, status='published')
|
||||
_profile(schema.id, profile_code='T02', version=1, status='published')
|
||||
db.session.commit()
|
||||
|
||||
versions = version_service.list_family_versions('T01')
|
||||
assert [item['version'] for item in versions] == [2, 1]
|
||||
assert {item['profile_code'] for item in versions} == {'T01'}
|
||||
detail = version_service.get_profile_detail_by_family_version('T01', 2)
|
||||
assert detail['id'] == target.id
|
||||
assert detail['profile_code'] == 'T01'
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
version_service.get_profile_detail_by_family_version('T01', 9)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND'
|
||||
|
||||
|
||||
def test_profile_detail_returns_safe_summaries_without_blind_truth(app):
|
||||
"""版本详情必须返回结构化摘要,但不能返回盲测真值、PDF 地址或对象存储信息。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
user = User(username='version-center-admin', email='version-center@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
profile = _profile(schema.id, profile_code='TSAFE', version=2, status='published', display_name='Safe template')
|
||||
document = _document(user, filename='safe.pdf', content_hash='b' * 64)
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id,
|
||||
document_id=document.id,
|
||||
table_id='table-1',
|
||||
sample_role='training',
|
||||
layout_version_id=11,
|
||||
source_content_hash='b' * 64,
|
||||
layout_payload_checksum='c' * 64,
|
||||
layout_contract_version='shipping_document_table_snapshot.v1',
|
||||
parser_key='mineru:test:v1',
|
||||
parser_name='mineru',
|
||||
parser_version='v1',
|
||||
evidence_frozen_at=datetime.utcnow(),
|
||||
source_filename_snapshot='safe.pdf',
|
||||
page_count_snapshot=2,
|
||||
table_identity_snapshot={'table_id': 'table-1', 'page_no': 1, 'row_count': 3},
|
||||
created_by_id=user.id,
|
||||
created_at=datetime.utcnow(),
|
||||
))
|
||||
blind_document = _document(user, filename='blind-secret.pdf', content_hash='d' * 64)
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id,
|
||||
document_id=blind_document.id,
|
||||
table_id='blind-table',
|
||||
sample_role='blind_test',
|
||||
layout_version_id=12,
|
||||
source_content_hash='d' * 64,
|
||||
layout_payload_checksum='e' * 64,
|
||||
layout_contract_version='shipping_document_table_snapshot.v1',
|
||||
parser_key='mineru:test:v1',
|
||||
parser_name='mineru',
|
||||
parser_version='v1',
|
||||
evidence_frozen_at=datetime.utcnow(),
|
||||
source_filename_snapshot='blind-secret.pdf',
|
||||
page_count_snapshot=1,
|
||||
table_identity_snapshot={'table_id': 'blind-table', 'page_no': 1, 'row_count': 1},
|
||||
created_by_id=user.id,
|
||||
created_at=datetime.utcnow(),
|
||||
))
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id,
|
||||
profile_checksum=profile.checksum or '2' * 64,
|
||||
status='approved',
|
||||
approved_by_id=user.id,
|
||||
approved_at=datetime.utcnow(),
|
||||
created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingDocumentProfileTestRun(
|
||||
suite_id=suite.id,
|
||||
profile_checksum=profile.checksum or '2' * 64,
|
||||
status='passed',
|
||||
sample_count=1,
|
||||
passed_sample_count=1,
|
||||
failure_codes_json=[],
|
||||
executed_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
detail = version_service.get_profile_detail(profile.id)
|
||||
assert detail['schema_summary']['version'] == 1
|
||||
assert detail['sample_summary']['training_count'] == 1
|
||||
assert detail['sample_summary']['blind_test_count'] == 1
|
||||
assert len(detail['sample_summary']['samples']) == 1
|
||||
assert detail['sample_summary']['samples'][0]['source_filename_snapshot'] == 'safe.pdf'
|
||||
assert detail['test_summary']['status'] == 'approved'
|
||||
assert detail['test_summary']['latest_run']['status'] == 'passed'
|
||||
encoded = json.dumps(detail, ensure_ascii=True, sort_keys=True)
|
||||
assert 'expected_rows_json' not in encoded
|
||||
assert 'expected_order_fields_json' not in encoded
|
||||
assert 'storage_key' not in encoded
|
||||
assert 'storage_bucket' not in encoded
|
||||
assert 'blind-secret.pdf' not in encoded
|
||||
|
||||
|
||||
def test_version_center_routes_return_family_summary_and_explicit_404(app, admin_jwt_headers):
|
||||
"""新版本中心路由必须能按族返回摘要,并在版本不存在时返回明确 404。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
target = _profile(schema.id, profile_code='TROUTE', version=2, status='published', display_name='Route template')
|
||||
_profile(schema.id, profile_code='TROUTE', version=1, status='retired', display_name='Route template')
|
||||
db.session.commit()
|
||||
target_id = int(target.id)
|
||||
|
||||
client = app.test_client()
|
||||
families = parse_api_data(client.get(
|
||||
'/api/admin/shipping-notice/order-document-profile-families',
|
||||
headers=admin_jwt_headers,
|
||||
).get_json())
|
||||
assert next(item for item in families if item['profile_code'] == 'TROUTE')['default_version'] == 2
|
||||
|
||||
detail_response = client.get(
|
||||
'/api/admin/shipping-notice/order-document-profile-families/TROUTE/versions/2',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert detail_response.status_code == 200
|
||||
detail = parse_api_data(detail_response.get_json())
|
||||
assert detail['id'] == target_id
|
||||
assert detail['profile_code'] == 'TROUTE'
|
||||
|
||||
missing_response = client.get(
|
||||
'/api/admin/shipping-notice/order-document-profile-families/TROUTE/versions/9',
|
||||
headers=admin_jwt_headers,
|
||||
)
|
||||
assert missing_response.status_code == 404
|
||||
assert parse_api_error(missing_response.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND'
|
||||
|
||||
|
||||
def test_retired_profile_detail_keeps_test_summary_by_frozen_checksum(app):
|
||||
"""退役版本仍需按冻结 checksum 回放盲测摘要,不能因状态变化丢失治理记录。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
user = User(username='retired-version-admin', email='retired-version@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
profile = _profile(schema.id, profile_code='TRETIRED', version=5, status='retired', display_name='Retired template')
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id,
|
||||
profile_checksum=profile.checksum or '5' * 64,
|
||||
status='approved',
|
||||
approved_by_id=user.id,
|
||||
approved_at=datetime.utcnow(),
|
||||
created_by_id=user.id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingDocumentProfileTestRun(
|
||||
suite_id=suite.id,
|
||||
profile_checksum=profile.checksum or '5' * 64,
|
||||
status='passed',
|
||||
sample_count=2,
|
||||
passed_sample_count=2,
|
||||
failure_codes_json=[],
|
||||
executed_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
detail = version_service.get_profile_detail(profile.id)
|
||||
assert detail['status'] == 'retired'
|
||||
assert detail['test_summary']['status'] == 'approved'
|
||||
assert detail['test_summary']['latest_run']['status'] == 'passed'
|
||||
@@ -608,6 +608,10 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
|
||||
lambda _run: ({}, None),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._latest_layout_document_events',
|
||||
lambda _run: {},
|
||||
)
|
||||
|
||||
items = serialize_workspace_run_documents(run)
|
||||
|
||||
@@ -638,4 +642,52 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch)
|
||||
'reason_code': 'technical_failure',
|
||||
'review_details': [],
|
||||
'available_actions': [],
|
||||
'activity_event_code': None,
|
||||
'started_at': None,
|
||||
'last_activity_at': None,
|
||||
'finished_at': None,
|
||||
}]
|
||||
|
||||
|
||||
def test_workspace_documents_show_selected_pdfs_while_layout_is_pending(monkeypatch):
|
||||
"""等待版面解析时仍返回已选 PDF,避免处理详情误报“暂无结果”。"""
|
||||
run = SimpleNamespace(
|
||||
id=1,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [{
|
||||
'selected': True,
|
||||
'filename': 'po-pending.pdf',
|
||||
'content_hash': 'pending-hash',
|
||||
'selection_batch': 1,
|
||||
'group_key': 'PO-PENDING',
|
||||
}],
|
||||
},
|
||||
'intakes': [{
|
||||
'intake_id': 11,
|
||||
'documents': [{
|
||||
'document_id': 101,
|
||||
'document_type': 'attachment',
|
||||
'filename': 'po-pending.pdf',
|
||||
'content_hash': 'pending-hash',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
extraction_plan=None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._latest_progress_events',
|
||||
lambda _run: ({}, None),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._latest_layout_document_events',
|
||||
lambda _run: {},
|
||||
)
|
||||
|
||||
items = serialize_workspace_run_documents(run)
|
||||
|
||||
# 关键断言:Unit 延后创建时,用户仍能看到正在等待版面解析的具体 PDF。
|
||||
assert items[0]['file_name'] == 'po-pending.pdf'
|
||||
assert items[0]['status'] == 'pending'
|
||||
assert items[0]['document_id'] == 101
|
||||
assert items[0]['activity_event_code'] is None
|
||||
@@ -114,6 +114,8 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
|
||||
|
||||
def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""将质量夹具改为最小 v2 草稿,使发布测试只覆盖阶段 4 边界。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
profile.status = 'draft'
|
||||
profile.checksum = None
|
||||
profile.published_at = None
|
||||
@@ -135,6 +137,11 @@ def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
}],
|
||||
}],
|
||||
}
|
||||
profile.definition_json = profiles._normalize_definition(
|
||||
profile.definition_json,
|
||||
schema_version=profile.schema_version,
|
||||
)
|
||||
profile.structure_fingerprint = profiles._definition_hash(profile.definition_json)
|
||||
|
||||
|
||||
def test_profile_blind_test_approval_enables_current_auto_freeze_qualification(app):
|
||||
@@ -297,13 +304,23 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
|
||||
|
||||
def test_profile_auto_freeze_qualification_can_be_suspended_independently(app):
|
||||
def test_profile_auto_freeze_qualification_can_be_suspended_independently(app, monkeypatch):
|
||||
"""关键断言:暂停资格不退役模板,且只影响当前版本。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
_publishable_v2_draft(profile)
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id,
|
||||
document_id=_documents[0].id,
|
||||
table_id='table-1',
|
||||
sample_role='training',
|
||||
created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
qualification = quality.suspend_auto_freeze_qualification(
|
||||
@@ -314,13 +331,23 @@ def test_profile_auto_freeze_qualification_can_be_suspended_independently(app):
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
|
||||
|
||||
def test_profile_auto_freeze_scope_can_be_configured_independently(app):
|
||||
def test_profile_auto_freeze_scope_can_be_configured_independently(app, monkeypatch):
|
||||
"""关键断言:客户/业务场景授权范围可独立配置,并写入模板审计摘要。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
_publishable_v2_draft(profile)
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id,
|
||||
document_id=_documents[0].id,
|
||||
table_id='table-1',
|
||||
sample_role='training',
|
||||
created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
customer = ShippingCustomer(standard_name='Scope Customer', short_code='SCOP')
|
||||
@@ -402,8 +429,8 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
|
||||
|
||||
|
||||
def test_draft_publish_is_independent_from_blind_test_and_starts_manual_confirmation(app):
|
||||
"""关键断言:模板可先发布供人工确认使用,缺样本绝不反向启用自动冻结。"""
|
||||
def test_draft_publish_requires_current_approved_blind_test(app):
|
||||
"""关键断言:阶段 7 起,缺少当前 approved blind test 的草稿不得发布。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
@@ -414,10 +441,9 @@ def test_draft_publish_is_independent_from_blind_test_and_starts_manual_confirma
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
published_without_suite = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert published_without_suite['status'] == 'published'
|
||||
assert published_without_suite['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
assert not published_without_suite['auto_freeze_qualification']['auto_freeze_enabled']
|
||||
with pytest.raises(Exception) as caught:
|
||||
profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
|
||||
|
||||
|
||||
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
@@ -448,6 +474,11 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
}],
|
||||
}],
|
||||
}
|
||||
profile.definition_json = profiles._normalize_definition(
|
||||
profile.definition_json,
|
||||
schema_version=profile.schema_version,
|
||||
)
|
||||
profile.structure_fingerprint = profiles._definition_hash(profile.definition_json)
|
||||
|
||||
def set_coordinate_rows(document: ShippingNoticeDocument, rows: list[tuple[str, str]]) -> None:
|
||||
"""冻结每个样本的字符坐标,让 v2 盲测不依赖 HTML 网格。"""
|
||||
@@ -467,7 +498,6 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
|
||||
for document in documents:
|
||||
set_coordinate_rows(document, [('PN-1', '3')])
|
||||
set_coordinate_rows(documents[1], [('PN-1', '3'), ('PN-2', '4')])
|
||||
extra = ShippingNoticeDocument(
|
||||
intake_id=documents[2].intake_id, asset_id=documents[2].asset_id, document_type='attachment',
|
||||
attachment_key='quality-v2-extra.pdf', filename='quality-v2-extra.pdf', content_hash='f' * 64,
|
||||
@@ -487,7 +517,7 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[0].id, table_id='table-1', expected_rows=[{'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
assert getattr(reused.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT'
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
|
||||
{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}, {'line_no': '00020', 'part_number': 'PN-2', 'qty': '4'},
|
||||
{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'},
|
||||
], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[2].id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-1', 'qty': '3'}], actor_id=user.id)
|
||||
quality.add_sample(suite_id=suite['id'], document_id=extra.id, table_id='table-1', expected_rows=[{'line_no': '00010', 'part_number': 'PN-3', 'qty': '5'}], actor_id=user.id)
|
||||
@@ -499,3 +529,6 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
assert published['status'] == 'published'
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=published['checksum'])
|
||||
frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id'])
|
||||
assert frozen_suite.profile_checksum == published['checksum']
|
||||
assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs)
|
||||
@@ -20,6 +20,7 @@ from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingDocumentProfileTestSample,
|
||||
@@ -105,6 +106,85 @@ def _coordinate_definition() -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _bind_ready_profile_sample(
|
||||
profile_id: int,
|
||||
*,
|
||||
sample_role: str = 'training',
|
||||
table_id: str = 'sample-table',
|
||||
content_hash: str = 's' * 64,
|
||||
filename: str = 'sample.pdf',
|
||||
) -> ShippingOrderDocumentProfileSample:
|
||||
"""为发布相关测试创建 ready Layout 样本,避免无样本草稿绕过发布证据冻结。"""
|
||||
suffix = f'{profile_id}-{str(sample_role).upper()}-{ShippingOrderDocumentProfileSample.query.count() + 1}'
|
||||
user = User(
|
||||
username=f'profile-sample-{suffix}',
|
||||
email=f'profile-sample-{suffix}@example.com',
|
||||
role='admin',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-PROFILE-SAMPLE-{suffix}',
|
||||
owner_user_id=user.id,
|
||||
original_filename=filename,
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=filename,
|
||||
content_hash=content_hash,
|
||||
file_size=1,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no=f'SNI-PROFILE-SAMPLE-{suffix}',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
purpose='order_document_profile_sample',
|
||||
parse_status='parsed',
|
||||
parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key=filename,
|
||||
filename=filename,
|
||||
content_hash=content_hash,
|
||||
classification='supporting',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'status': 'ready',
|
||||
'pages': [{'page_no': 1}],
|
||||
'tables': [{
|
||||
'table_id': table_id,
|
||||
'page_no': 1,
|
||||
'rows': [{'cells': [{'text': 'ok'}]}],
|
||||
'html': '<table><tr><td>ok</td></tr></table>',
|
||||
}],
|
||||
})
|
||||
db.session.commit()
|
||||
service.add_profile_sample(
|
||||
profile_id,
|
||||
document_id=document.id,
|
||||
table_id=table_id,
|
||||
sample_role=sample_role,
|
||||
actor_id=user.id,
|
||||
)
|
||||
return ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=profile_id, document_id=document.id, sample_role=sample_role,
|
||||
).one()
|
||||
|
||||
|
||||
def test_coordinate_profile_v2_requires_schema_source_authorization_and_freezes_field_id(app):
|
||||
"""关键断言:浏览器伪造 field_id 无效,Schema 未授权的坐标来源必须阻断 Profile 保存。"""
|
||||
with app.app_context():
|
||||
@@ -404,7 +484,7 @@ def test_coordinate_binding_allows_enabled_header_value_from_a_detail_physical_r
|
||||
assert bound['target_fields'] == [{'field_id': 'incoterm-field', 'field_code': 'incoterm'}]
|
||||
|
||||
|
||||
def test_profile_samples_are_governed_and_audited(app):
|
||||
def test_profile_samples_are_governed_and_audited(app, monkeypatch):
|
||||
"""训练/标注样本只能绑定草稿,计数与审计必须只保存非敏感结构摘要。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
@@ -458,11 +538,22 @@ def test_profile_samples_are_governed_and_audited(app):
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile.id).training_sample_count == 0
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).count() == 0
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.publish(profile.id, actor_id=None, expected_lock_version=profile.lock_version)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING'
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
rebound = _bind_ready_profile_sample(profile.id)
|
||||
published = service.publish(profile.id, actor_id=None, expected_lock_version=profile.lock_version)
|
||||
# 关键断言:样本不足不阻断模板人工确认发布,也绝不能开启自动冻结。
|
||||
# 关键断言:发布前必须冻结至少一份样本证据,且发布后只进入人工确认资格。
|
||||
assert published['status'] == 'published'
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
assert not published['auto_freeze_qualification']['auto_freeze_enabled']
|
||||
frozen = db.session.get(ShippingOrderDocumentProfileSample, rebound.id)
|
||||
assert frozen.layout_version_id is not None
|
||||
assert frozen.source_content_hash == 's' * 64
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.add_profile_sample(
|
||||
profile.id, document_id=document.id, table_id='sample-table', sample_role='blind_test', actor_id=None,
|
||||
@@ -471,7 +562,7 @@ def test_profile_samples_are_governed_and_audited(app):
|
||||
|
||||
|
||||
def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, monkeypatch):
|
||||
"""模板级语义必须冻结稳定字段 ID;新发布版本原子退役旧发布版本。"""
|
||||
"""模板级语义和样本证据必须一起冻结;新发布版本原子退役旧发布版本。"""
|
||||
with app.app_context():
|
||||
# This lifecycle test isolates version replacement; publish-gate coverage is below.
|
||||
monkeypatch.setattr(
|
||||
@@ -479,6 +570,7 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
)
|
||||
schema = _schema_version()
|
||||
first = service.save_draft(_data(schema.id), actor_id=None)
|
||||
first_sample = _bind_ready_profile_sample(first['id'])
|
||||
published = service.publish(
|
||||
first['id'], actor_id=None, expected_lock_version=first['lock_version'],
|
||||
)
|
||||
@@ -487,8 +579,20 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
assert field_region['field_id'] == 'part-field'
|
||||
assert field_region['field_code'] == 'part_number'
|
||||
assert len(published['checksum']) == 64
|
||||
frozen = db.session.get(ShippingOrderDocumentProfileSample, first_sample.id)
|
||||
layout_version = db.session.get(ShippingDocumentLayoutVersion, frozen.layout_version_id)
|
||||
assert frozen.evidence_frozen_at is not None
|
||||
assert frozen.source_content_hash == 's' * 64
|
||||
assert frozen.layout_payload_checksum == layout_version.payload_checksum
|
||||
assert frozen.layout_contract_version == layout_version.contract_version
|
||||
assert frozen.parser_key == layout_version.parser_key
|
||||
assert frozen.parser_name == layout_version.parser_name
|
||||
assert frozen.source_filename_snapshot == 'sample.pdf'
|
||||
assert frozen.page_count_snapshot == 1
|
||||
assert frozen.table_identity_snapshot == {'table_id': 'sample-table', 'page_no': 1, 'row_count': 1}
|
||||
|
||||
draft = service.clone_draft(published['id'], actor_id=None)
|
||||
_bind_ready_profile_sample(draft['id'], content_hash='c' * 64, filename='replacement.pdf')
|
||||
assert draft['migration_status'] == 'normal'
|
||||
update = _data(schema.id, fingerprint='c' * 64)
|
||||
update['expected_lock_version'] = draft['lock_version']
|
||||
@@ -504,6 +608,188 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
).one().id == replacement['id']
|
||||
|
||||
|
||||
def test_profile_publish_rolls_back_when_sample_layout_hash_drifts(app, monkeypatch):
|
||||
"""样本文件与 ready Layout hash 不一致时必须整体回滚,旧 published 不能被部分退役。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
schema = _schema_version()
|
||||
first = service.save_draft(_data(schema.id), actor_id=None)
|
||||
_bind_ready_profile_sample(first['id'])
|
||||
published = service.publish(first['id'], actor_id=None, expected_lock_version=first['lock_version'])
|
||||
|
||||
draft = service.clone_draft(published['id'], actor_id=None)
|
||||
sample = _bind_ready_profile_sample(draft['id'], content_hash='d' * 64, filename='drift.pdf')
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
document.content_hash = 'e' * 64
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
|
||||
assert db.session.get(ShippingOrderDocumentProfile, published['id']).status == 'published'
|
||||
failed_draft = db.session.get(ShippingOrderDocumentProfile, draft['id'])
|
||||
assert failed_draft.status == 'draft'
|
||||
frozen = db.session.get(ShippingOrderDocumentProfileSample, sample.id)
|
||||
assert frozen.layout_version_id is None
|
||||
assert frozen.evidence_frozen_at is None
|
||||
|
||||
|
||||
def test_profile_publish_rejects_corrupted_layout_checksum(app, monkeypatch):
|
||||
"""ready Layout payload 与持久化 checksum 不一致时,发布必须阻断。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
schema = _schema_version()
|
||||
draft = service.save_draft(_data(schema.id), actor_id=None)
|
||||
sample = _bind_ready_profile_sample(draft['id'])
|
||||
layout_version = db.session.get(
|
||||
ShippingDocumentLayoutVersion,
|
||||
db.session.get(ShippingOrderDocumentProfileSample, sample.id).layout_version_id or
|
||||
db.session.get(ShippingNoticeDocument, sample.document_id).current_layout_version_id,
|
||||
)
|
||||
assert layout_version is not None
|
||||
payload = dict(layout_version.payload_json or {})
|
||||
payload['tables'] = list(payload.get('tables') or []) + [{
|
||||
'table_id': 'tampered-table',
|
||||
'page_no': 1,
|
||||
'rows': [],
|
||||
}]
|
||||
layout_version.payload_json = payload
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
|
||||
|
||||
|
||||
def test_profile_frozen_sample_survives_new_layout_version(app, monkeypatch):
|
||||
"""文档重解析生成新 current layout 后,历史发布样本仍绑定原 layout_version_id。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
schema = _schema_version()
|
||||
draft = service.save_draft(_data(schema.id), actor_id=None)
|
||||
sample = _bind_ready_profile_sample(draft['id'])
|
||||
published = service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
|
||||
frozen_before = db.session.get(ShippingOrderDocumentProfileSample, sample.id)
|
||||
document = db.session.get(ShippingNoticeDocument, frozen_before.document_id)
|
||||
old_layout_version_id = frozen_before.layout_version_id
|
||||
old_checksum = frozen_before.layout_payload_checksum
|
||||
record_inline_layout_snapshot(document, {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1',
|
||||
'status': 'ready',
|
||||
'pages': [{'page_no': 1}, {'page_no': 2}],
|
||||
'tables': [{
|
||||
'table_id': 'sample-table',
|
||||
'page_no': 2,
|
||||
'rows': [{'cells': [{'text': 'new-layout'}]}],
|
||||
'html': '<table><tr><td>new-layout</td></tr></table>',
|
||||
}],
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
frozen_after = db.session.get(ShippingOrderDocumentProfileSample, sample.id)
|
||||
assert document.current_layout_version_id != old_layout_version_id
|
||||
assert frozen_after.layout_version_id == old_layout_version_id
|
||||
assert frozen_after.layout_payload_checksum == old_checksum
|
||||
listed = service.list_profile_samples(published['id'])
|
||||
assert listed[0]['layout_version_id'] == old_layout_version_id
|
||||
assert listed[0]['frozen_evidence_ready'] is True
|
||||
refreshed = service.payload(db.session.get(ShippingOrderDocumentProfile, published['id']))
|
||||
assert refreshed['frozen_evidence']['status'] == 'ready'
|
||||
assert refreshed['frozen_evidence']['audit_ready'] is True
|
||||
|
||||
|
||||
def test_immutable_profile_without_frozen_sample_is_marked_missing(app):
|
||||
"""历史旧发布记录若没有冻结证据,DTO 必须明确标记 missing,而不是伪装成可审计版本。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
user = User(username='legacy-profile-admin', email='legacy-profile@example.com', role='admin', status='active')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
asset = FileAsset(
|
||||
asset_no='FA-LEGACY-PROFILE',
|
||||
owner_user_id=user.id,
|
||||
original_filename='legacy.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key='legacy.pdf',
|
||||
content_hash='7' * 64,
|
||||
file_size=1,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-LEGACY-PROFILE',
|
||||
asset_id=asset.id,
|
||||
user_id=user.id,
|
||||
purpose='order_document_profile_sample',
|
||||
parse_status='parsed',
|
||||
parser_version='legacy',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=asset.id,
|
||||
document_type='attachment',
|
||||
attachment_key='legacy.pdf',
|
||||
filename='legacy.pdf',
|
||||
content_hash='7' * 64,
|
||||
classification='supporting',
|
||||
parse_status='parsed',
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='LEGACY_PROFILE', display_name='Legacy profile', version=1,
|
||||
status='published', schema_version_id=schema.id,
|
||||
structure_fingerprint='9' * 64, definition_json={}, checksum='8' * 64,
|
||||
published_at=datetime.utcnow(), lock_version=1,
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id,
|
||||
document_id=document.id,
|
||||
table_id='legacy-table',
|
||||
sample_role='training',
|
||||
created_by_id=user.id,
|
||||
created_at=datetime.utcnow(),
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
summary = service.payload(db.session.get(ShippingOrderDocumentProfile, profile.id))
|
||||
assert summary['frozen_evidence']['status'] == 'missing'
|
||||
assert summary['frozen_evidence']['audit_ready'] is False
|
||||
|
||||
|
||||
def test_published_profile_sample_intake_cannot_be_deleted(app, monkeypatch):
|
||||
"""已发布版本引用的样本 intake 不可删除,否则会连带删掉历史 Document/Layout。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
schema = _schema_version()
|
||||
draft = service.save_draft(_data(schema.id), actor_id=None)
|
||||
sample = _bind_ready_profile_sample(draft['id'])
|
||||
service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
intake = db.session.get(ShippingNoticeIntake, document.intake_id)
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.delete_sample_intake(intake.intake_no, actor_id=int(intake.user_id or 0))
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_DELETE_BLOCKED'
|
||||
|
||||
|
||||
def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_status(app, monkeypatch):
|
||||
"""迁移草稿只替换破坏性字段,且管理员修改备注后仍必须重新盲测。"""
|
||||
with app.app_context():
|
||||
@@ -513,6 +799,7 @@ def test_schema_migration_replaces_only_breaking_field_and_keeps_revalidation_st
|
||||
)
|
||||
source_schema = _schema_version()
|
||||
draft = service.save_draft(_data(source_schema.id), actor_id=None)
|
||||
_bind_ready_profile_sample(draft['id'])
|
||||
published = service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=draft['lock_version'],
|
||||
)
|
||||
@@ -582,6 +869,7 @@ def test_schema_migration_preserves_unbound_order_field_region_and_blocks_publis
|
||||
'profile_code': 'ORDER_FIELD_MIGRATION', 'display_name': 'Order field migration',
|
||||
'schema_version_id': source_schema.id, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
_bind_ready_profile_sample(draft['id'])
|
||||
published = service.publish(draft['id'], actor_id=None, expected_lock_version=draft['lock_version'])
|
||||
source_schema.status = 'retired'
|
||||
target_schema = ShippingOrderSchemaVersion(
|
||||
@@ -670,9 +958,23 @@ def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
payload = parse_api_data(created.get_json())
|
||||
assert payload['profile_code'] == 'PO_312207'
|
||||
|
||||
lease = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}/edit-lease",
|
||||
json={'browser_session_id': 'profile-admin-tab', 'operation_id': 'profile-admin-lease'},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert lease.status_code == 201
|
||||
lease_payload = parse_api_data(lease.get_json())
|
||||
|
||||
conflict = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={**_data(schema_id), 'expected_lock_version': payload['lock_version'] + 1},
|
||||
json={
|
||||
**_data(schema_id),
|
||||
'expected_lock_version': payload['lock_version'] + 1,
|
||||
'browser_session_id': 'profile-admin-tab',
|
||||
'lease_token': lease_payload['lease_token'],
|
||||
'operation_id': 'profile-admin-stale-save',
|
||||
},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert conflict.status_code == 409
|
||||
@@ -755,12 +1057,13 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
|
||||
assert 'bbox' not in preview['tables'][0]
|
||||
|
||||
sample_payload = {
|
||||
'profile_code': 'SAMPLE_TEMPLATE', 'display_name': 'Sample template',
|
||||
'schema_version_id': schema_id, 'document_id': document_id,
|
||||
'definition': _coordinate_definition(),
|
||||
'profile_code': 'SAMPLE_TEMPLATE', 'display_name': 'Sample template',
|
||||
'schema_version_id': schema_id, 'document_id': document_id,
|
||||
'main_table_id': 'table-1', 'browser_session_id': 'sample-owner-create-tab',
|
||||
'operation_id': 'sample-owner-create',
|
||||
}
|
||||
created = client.post(
|
||||
'/api/admin/shipping-notice/order-document-profiles/from-sample',
|
||||
'/api/admin/shipping-notice/order-document-profiles/wizard-complete',
|
||||
json=sample_payload, headers=admin_headers,
|
||||
)
|
||||
assert created.status_code == 201
|
||||
@@ -768,41 +1071,40 @@ def test_profile_sample_api_supports_secure_preview_create_and_version_update(ap
|
||||
assert draft['definition']['contract_version'] == 'order_coordinate_profile.v2'
|
||||
assert len(draft['structure_fingerprint']) == 64
|
||||
|
||||
published_response = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{draft['id']}/publish",
|
||||
json={'expected_lock_version': draft['lock_version']}, headers=admin_headers,
|
||||
)
|
||||
published = parse_api_data(published_response.get_json())
|
||||
clone_response = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{published['id']}/clone",
|
||||
headers=admin_headers,
|
||||
)
|
||||
clone = parse_api_data(clone_response.get_json())
|
||||
|
||||
stale = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{clone['id']}/from-sample",
|
||||
json={**sample_payload, 'expected_lock_version': clone['lock_version'] + 1},
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{draft['id']}",
|
||||
json={
|
||||
'profile_code': draft['profile_code'], 'display_name': draft['display_name'],
|
||||
'schema_version_id': draft['schema_version_id'], 'definition': draft['definition'],
|
||||
'expected_lock_version': draft['lock_version'] + 1,
|
||||
'browser_session_id': 'sample-owner-create-tab',
|
||||
'lease_token': draft['edit_lease']['lease_token'],
|
||||
'operation_id': 'sample-clone-stale-save',
|
||||
},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert stale.status_code == 409
|
||||
assert parse_api_error(stale.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
|
||||
updated_response = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{clone['id']}/from-sample",
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{draft['id']}",
|
||||
json={
|
||||
**sample_payload,
|
||||
'profile_code': draft['profile_code'], 'schema_version_id': draft['schema_version_id'], 'definition': draft['definition'],
|
||||
'display_name': 'Sample template v2',
|
||||
'change_note': 'Reconfirmed against MinerU sample',
|
||||
'expected_lock_version': clone['lock_version'],
|
||||
'expected_lock_version': draft['lock_version'],
|
||||
'browser_session_id': 'sample-owner-create-tab',
|
||||
'lease_token': draft['edit_lease']['lease_token'],
|
||||
'operation_id': 'sample-clone-valid-save',
|
||||
},
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert updated_response.status_code == 200
|
||||
updated = parse_api_data(updated_response.get_json())
|
||||
assert updated['id'] == clone['id']
|
||||
assert updated['id'] == draft['id']
|
||||
assert updated['display_name'] == 'Sample template v2'
|
||||
assert updated['change_note'] == 'Reconfirmed against MinerU sample'
|
||||
assert updated['lock_version'] == clone['lock_version'] + 1
|
||||
assert updated['lock_version'] == draft['lock_version'] + 1
|
||||
|
||||
|
||||
def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(app, monkeypatch):
|
||||
@@ -1246,10 +1548,10 @@ def test_profile_sample_api_reports_header_contamination_but_v2_can_use_independ
|
||||
assert preview['tables'][0]['issues'] == ['order_profile_header_contaminated_by_data']
|
||||
assert preview['tables'][0]['profile_creation_allowed'] is False
|
||||
|
||||
response = client.post('/api/admin/shipping-notice/order-document-profiles/from-sample', json={
|
||||
response = client.post('/api/admin/shipping-notice/order-document-profiles/wizard-complete', json={
|
||||
'profile_code': 'CONTAMINATED_TEMPLATE', 'display_name': 'Bad template',
|
||||
'schema_version_id': schema_id, 'document_id': document_id,
|
||||
'definition': _coordinate_definition(),
|
||||
'schema_version_id': schema_id, 'document_id': document_id, 'main_table_id': 'table-bad',
|
||||
'browser_session_id': 'contaminated-tab', 'operation_id': 'contaminated-create',
|
||||
}, headers=headers)
|
||||
assert response.status_code == 201
|
||||
|
||||
@@ -1483,6 +1785,7 @@ def test_workbench_auto_suggested_unbound_regions_do_not_block_publish(app, monk
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
_bind_ready_profile_sample(saved['id'])
|
||||
assert service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version'])['status'] == 'published'
|
||||
|
||||
|
||||
@@ -1503,6 +1806,7 @@ def test_schema_migration_unbound_regions_still_block_publish(app, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
_bind_ready_profile_sample(saved['id'])
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.publish(saved['id'], actor_id=None, expected_lock_version=saved['lock_version'])
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID'
|
||||
|
||||
@@ -48,6 +48,8 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
mark_order_extraction_run_seen,
|
||||
reparse_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
resume_runs_waiting_for_layout,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
serialize_order_extraction_message_state,
|
||||
serialize_order_extraction_run,
|
||||
transition_order_extraction_run,
|
||||
@@ -394,9 +396,10 @@ def test_create_run_scopes_to_selected_intakes_only(app):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('layout_status', ['queued', 'running'])
|
||||
def test_create_run_allows_active_document_layout_and_defers_runtime_fallback(app, layout_status):
|
||||
"""布局未 ready 时仍允许建 Run;冻结快照保持空 layout,执行期再补读当前 ready 版本。"""
|
||||
def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction(app, layout_status):
|
||||
"""发送后必须先完成版面解析;订单 Job 不得与布局 Job 并行抢跑。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, document = _seed_run_input(suffix=f'LAYOUT-{layout_status.upper()}')
|
||||
db.session.add(ShippingDocumentLayoutVersion(
|
||||
document_id=document.id,
|
||||
@@ -418,10 +421,57 @@ def test_create_run_allows_active_document_layout_and_defers_runtime_fallback(ap
|
||||
|
||||
assert reused is False
|
||||
assert run.status == 'queued'
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert db.session.get(Job, run.current_job_id) is not None
|
||||
assert run.input_snapshot_json['intakes'][0]['documents'][0]['layout_snapshot'] is None
|
||||
assert ShippingOrderExtractionRun.query.count() == 1
|
||||
|
||||
|
||||
def test_last_layout_completion_enqueues_waiting_run_once(app):
|
||||
"""最后一份附件布局完成才唤醒 Run,提前完成其中一份不能启动订单提取。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='WAIT-ALL')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=first.asset_id, document_type='attachment',
|
||||
attachment_key='orders-WAIT-ALL-2.pdf', filename='orders-WAIT-ALL-2.pdf',
|
||||
content_hash='b' * 64, classification='order_notice', parse_status='parsed', extracted_text='PO 2',
|
||||
)
|
||||
db.session.add(second)
|
||||
db.session.commit()
|
||||
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
layouts = ShippingDocumentLayoutVersion.query.filter(
|
||||
ShippingDocumentLayoutVersion.document_id.in_([first.id, second.id]),
|
||||
).all()
|
||||
assert len(layouts) == 2
|
||||
layouts[0].status = 'ready'
|
||||
db.session.commit()
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 0
|
||||
assert db.session.get(Job, run.current_job_id) is not None
|
||||
|
||||
layouts[1].status = 'ready'
|
||||
db.session.commit()
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[1].document_id) == 1
|
||||
db.session.refresh(run)
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
assert run.phase == 'queued'
|
||||
assert job is not None
|
||||
assert job.job_type == 'shipping_order_extraction'
|
||||
|
||||
|
||||
def test_pdf_without_ready_coordinate_layout_is_a_prerequisite_failure(app):
|
||||
"""PDF 未生成可用坐标快照时必须被门禁拦截,不能误报业务表不存在。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='LAYOUT-GATE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
assert order_extraction_layout_prerequisite_issues(run) == {document.id: 'layout_missing'}
|
||||
|
||||
|
||||
def test_deterministic_route_reports_no_layout_table_not_multiple_tables(app):
|
||||
"""没有可用 Layout 表格时必须给出准确回退原因,不能误报为多表。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -20,7 +20,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
|
||||
events: list[str] = []
|
||||
run = SimpleNamespace(
|
||||
id=1, run_no='SNER-WORKER-MATERIALIZE', status='queued', current_job_id=None,
|
||||
id=1, user_id=9, run_no='SNER-WORKER-MATERIALIZE', status='queued', current_job_id=None,
|
||||
attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
)
|
||||
job = SimpleNamespace(id=1, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
@@ -47,7 +47,13 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'transition_order_extraction_run', lambda target, **_kwargs: setattr(target, 'status', 'processing'))
|
||||
monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', lambda _run: events.append('materialize') or plan)
|
||||
def fake_materialize(_run, *, finalize_plan=True):
|
||||
events.append('finalize' if finalize_plan else 'materialize')
|
||||
return plan if finalize_plan else None
|
||||
|
||||
monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', fake_materialize)
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda _run, *, created_by_id: events.append('schedule') or False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or [])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: [])
|
||||
@@ -63,7 +69,44 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 1})
|
||||
|
||||
assert events.index('materialize') < events.index('units')
|
||||
assert events.index('materialize') < events.index('schedule') < events.index('finalize') < events.index('units')
|
||||
|
||||
|
||||
def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch):
|
||||
"""物化后新出现的 PDF 必须先排布局 Job;布局运行中禁止进入模板路由。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
run = SimpleNamespace(
|
||||
id=2, user_id=9, run_no='SNER-WORKER-WAIT-LAYOUT', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
)
|
||||
job = SimpleNamespace(id=2, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderExtractionRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: events.append('finalize' if finalize_plan else 'materialize'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, 'schedule_order_extraction_layouts',
|
||||
lambda _run, *, created_by_id: events.append('schedule') or True,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {357: 'layout_pending'})
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('waiting'))
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
monkeypatch.setattr(handler, 'route_deterministic_unit', lambda *_args, **_kwargs: events.append('routed'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 2})
|
||||
|
||||
assert events == ['materialize', 'schedule', 'waiting', 'finished']
|
||||
assert run.phase == 'waiting_layout'
|
||||
|
||||
|
||||
def _patch_unit_transitions(monkeypatch):
|
||||
|
||||
@@ -0,0 +1,552 @@
|
||||
"""
|
||||
建单前订单复核 Case/Draft 的阶段 1 服务测试。
|
||||
|
||||
依赖:订单抽取 Run 测试夹具、Review 初始化服务和只读投影。
|
||||
逻辑:验证 PDF Unit 的一对一 Case、机器 Candidate 隔离、owner 授权和冻结 Schema
|
||||
投影;关键断言覆盖后续编辑/确认阶段依赖的不可变初始化边界。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case, serialize_review_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
ensure_run_review_cases,
|
||||
get_user_review_case,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
add_line,
|
||||
delete_line,
|
||||
patch_header_field,
|
||||
patch_line_field,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence, list_case_evidence
|
||||
from app.services.shipping_notice.order_review_disposition_service import (
|
||||
create_manual_draft,
|
||||
finalize_document_reparse,
|
||||
mark_non_order,
|
||||
mark_quality_issue,
|
||||
reparse_case_document,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
|
||||
def _materialized_run(*, user, agent, session, intake):
|
||||
"""测试中显式物化延迟创建的 Plan/Unit,保持与 Worker 的生产时序一致。"""
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app):
|
||||
"""同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-ONE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-1'}]}],
|
||||
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'A001'}]}]}],
|
||||
'conflicts': [],
|
||||
}],
|
||||
}
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate_no='CAND-REVIEW-ONE', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='review-one', order_extraction_run_id=run.id, structured_result_json={'machine': 'unchanged'},
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.commit()
|
||||
|
||||
first = ensure_run_review_cases(run=run)
|
||||
second = ensure_run_review_cases(run=run)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:Unit 唯一约束和服务幂等防止 Worker 重入创建第二个复核对象。
|
||||
assert len(first) == len(second) == 1
|
||||
assert ShippingOrderReviewCase.query.filter_by(unit_id=unit.id).count() == 1
|
||||
case = first[0]
|
||||
assert case.candidate_id == candidate.id
|
||||
assert case.current_draft is not None
|
||||
assert case.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'PO-1'
|
||||
assert db.session.get(ShippingNoticeCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
|
||||
|
||||
|
||||
def test_review_case_without_or_with_multiple_candidates_never_picks_a_machine_source(app):
|
||||
"""无 Candidate 和旧多 Candidate 都必须创建 Case,但不得任意选择机器结果作为来源。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-MULTI')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
for index in (1, 2):
|
||||
db.session.add(ShippingNoticeCandidate(
|
||||
candidate_no=f'CAND-REVIEW-MULTI-{index}', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key=f'review-multi-{index}', order_extraction_run_id=run.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:旧多订单结果必须显式留给后续迁移,不得错误绑定任意 Candidate。
|
||||
assert case.candidate_id is None
|
||||
assert any(item['code'] == 'machine_order_unavailable' for item in case.current_draft.issue_summary_json)
|
||||
|
||||
|
||||
def test_run_summary_counts_unresolved_review_cases_for_ready_candidates(app):
|
||||
"""候选已生成但尚未人工确认时,聊天卡必须明确显示该 PDF 仍需复核。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-SUMMARY')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.status = 'candidate_ready'
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': []}]}
|
||||
run.status = 'partially_completed'
|
||||
ensure_run_review_cases(run=run)
|
||||
db.session.commit()
|
||||
|
||||
summary = serialize_workspace_run(run)['summary']
|
||||
|
||||
# 关键断言:Unit 成功不等于用户无需处理,未确认的 Review Case 应计入复核数。
|
||||
assert summary['completed_documents'] == 1
|
||||
assert summary['review_required_documents'] == 1
|
||||
|
||||
|
||||
def test_review_projection_uses_frozen_schema_and_enforces_case_owner(app):
|
||||
"""详情只返回冻结 Schema/安全文件名,其他用户无法通过 Case 编号读取。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-READ')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
other = User(username='review-other', email='review-other@example.com', password_hash='x', status='active')
|
||||
db.session.add(other)
|
||||
db.session.commit()
|
||||
|
||||
detail = serialize_review_case(case)
|
||||
listing = serialize_review_run(run)
|
||||
|
||||
# 关键断言:投影来自 Run 冻结 Schema,且安全 DTO 不携带原始文档正文或存储定位。
|
||||
assert detail['schema']['schema_version_id'] == run.schema_version_id
|
||||
assert detail['document']['file_name']
|
||||
assert 'extracted_text' not in str(detail)
|
||||
assert listing['items'][0]['case_no'] == case.case_no
|
||||
try:
|
||||
get_user_review_case(user_id=other.id, case_no=case.case_no)
|
||||
except NotFoundError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('another user must not read the review case')
|
||||
|
||||
|
||||
def test_review_read_api_returns_safe_owner_scoped_projection(app):
|
||||
"""两个阶段 1 只读 API 必须返回安全 DTO,且未知 owner 得到 404 而非数据泄露。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-API')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
|
||||
client = app.test_client()
|
||||
token = issue_local_access_token(user)
|
||||
headers = {'Authorization': f'Bearer {token}'}
|
||||
run_response = client.get(f'/api/workspace/shipping-notice/order-extraction-runs/{run.run_no}/review', headers=headers)
|
||||
case_response = client.get(f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}', headers=headers)
|
||||
|
||||
# 关键断言:列表和详情仅给 owner 返回 Case/Draft 安全投影,不输出原始文本或对象存储信息。
|
||||
assert run_response.status_code == 200
|
||||
assert case_response.status_code == 200
|
||||
assert case.case_no in str(run_response.get_json())
|
||||
body = case_response.get_json()
|
||||
assert 'extracted_text' not in str(body)
|
||||
assert 'storage_key' not in str(body)
|
||||
|
||||
|
||||
def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(app):
|
||||
"""单字段人工编辑不覆盖机器快照;旧版本写入被拒绝且每次变更都有独立审计。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-DRAFT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
schema = dict(snapshot['schema'])
|
||||
definition = dict(schema['definition'])
|
||||
definition['fields'] = [
|
||||
{'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': []},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
|
||||
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{
|
||||
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-MACHINE'}]}],
|
||||
'lines': [{'fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
|
||||
{'field_id': 'reservation-id', 'observations': [{'value': '3000092917'}]},
|
||||
]}],
|
||||
}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
first = patch_header_field(
|
||||
user_id=user.id, case_no=case.case_no, field_id='po-id', value='PO-MANUAL',
|
||||
expected_draft_version=1,
|
||||
)
|
||||
# 关键断言:仅当前字段人工覆盖,机器字段仍保存为不可变复原来源。
|
||||
assert first['draft']['draft_version'] == 2
|
||||
assert case.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'PO-MACHINE'
|
||||
assert case.current_draft.header_values_json['values']['po-id']['value'] == 'PO-MANUAL'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id, event_type='header_field_changed').count() == 1
|
||||
|
||||
try:
|
||||
patch_header_field(
|
||||
user_id=user.id, case_no=case.case_no, field_id='po-id', value='STALE',
|
||||
expected_draft_version=1,
|
||||
)
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH'
|
||||
else:
|
||||
raise AssertionError('stale version must not overwrite the newer draft')
|
||||
|
||||
updated = patch_line_field(
|
||||
user_id=user.id, case_no=case.case_no, line_key='machine-1', field_id='qty-id', value='3',
|
||||
expected_draft_version=2,
|
||||
)
|
||||
# 关键断言:单字段改动不会清除其他字段,校验结果仍保留到 Draft。
|
||||
assert updated['draft']['lines'][0]['values']['qty-id']['value'] == '3'
|
||||
assert updated['draft']['validation']['status'] == 'ready'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id).count() == 3
|
||||
|
||||
|
||||
def test_review_draft_empty_line_and_last_line_delete_remain_blocking(app):
|
||||
"""新增空行或删除最后一条有效行只能保存草稿,必须保留阻断问题而非伪装为可确认。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-DRAFT-LINE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
schema = dict(snapshot['schema'])
|
||||
definition = dict(schema['definition'])
|
||||
definition['fields'] = [
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
|
||||
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
|
||||
{'field_id': 'reservation-id', 'observations': [{'value': '3000092917'}]},
|
||||
]}]}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
added = add_line(user_id=user.id, case_no=case.case_no, expected_draft_version=1)
|
||||
assert added['draft']['validation']['status'] == 'needs_review'
|
||||
assert any(item['code'] == 'required_field_missing' for item in added['draft']['issues'])
|
||||
|
||||
deleted_empty = delete_line(
|
||||
user_id=user.id, case_no=case.case_no, line_key=added['draft']['lines'][-1]['line_key'],
|
||||
expected_draft_version=2,
|
||||
)
|
||||
deleted = delete_line(user_id=user.id, case_no=case.case_no, line_key='machine-1', expected_draft_version=3)
|
||||
assert deleted_empty['draft']['validation']['status'] == 'ready'
|
||||
assert deleted['draft']['validation']['status'] == 'needs_review'
|
||||
assert not deleted['draft']['lines']
|
||||
|
||||
|
||||
def test_review_evidence_is_case_scoped_and_omits_untrusted_bbox(app):
|
||||
"""证据仅来自当前 PDF Unit;不完整坐标必须降级为页码和引文,不能伪造高亮。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-EVIDENCE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [{
|
||||
'field_id': 'po', 'observations': [{
|
||||
'value': 'PO-1', 'page_no': 2, 'quote': '<b>PO-1</b>',
|
||||
'bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.3},
|
||||
}],
|
||||
}], 'lines': []}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
payload = list_case_evidence(user_id=user.id, case_no=case.case_no)
|
||||
item = get_case_evidence(user_id=user.id, case_no=case.case_no, evidence_id=payload['items'][0]['evidence_id'])
|
||||
# 关键断言:安全投影没有内部存储字段,坏 bbox 不会被前端当作可靠高亮。
|
||||
assert item['page_no'] == 2
|
||||
assert item['quote'] == '<b>PO-1</b>'
|
||||
assert item['bbox'] is None
|
||||
assert 'storage_key' not in str(payload)
|
||||
|
||||
|
||||
def test_manual_draft_and_dispositions_are_case_scoped_and_preserve_machine_facts(app):
|
||||
"""无 Candidate 仅能启用唯一草稿;非订单和质量异常不删除当前 PDF 的机器历史。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-DISPOSITION')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
manual = create_manual_draft(user_id=user.id, case_no=case.case_no)
|
||||
# 关键断言:手工创建复用每 PDF 唯一 Draft,不会额外创建订单对象。
|
||||
assert manual['status'] == 'draft'
|
||||
assert manual['disposition'] == 'manual_order'
|
||||
assert ShippingOrderReviewCase.query.filter_by(document_id=document.id).count() == 1
|
||||
assert create_manual_draft(user_id=user.id, case_no=case.case_no)['status'] == 'draft'
|
||||
|
||||
quality = mark_quality_issue(
|
||||
user_id=user.id, case_no=case.case_no, reason='blurred', comment='scan is blurred',
|
||||
)
|
||||
assert quality['status'] == 'quality_issue'
|
||||
assert quality['disposition'] == 'blurred'
|
||||
assert db.session.get(ShippingOrderReviewCase, case.id).current_draft is not None
|
||||
|
||||
# 独立 Case 的非订单处置不会改写相邻 PDF 或删除它的机器 Candidate。
|
||||
case.status = 'draft'
|
||||
non_order = mark_non_order(user_id=user.id, case_no=case.case_no, reason='non_order')
|
||||
assert non_order['status'] == 'non_order'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id, event_type='marked_non_order').count() == 1
|
||||
|
||||
|
||||
def test_document_reparse_uses_one_document_and_restores_old_draft_when_new_run_fails(app):
|
||||
"""PDF 重识别冻结目标 Document;失败只恢复旧 Case,不丢草稿也不替代其他 PDF。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-REPARSE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
replacement, reused = reparse_case_document(
|
||||
user_id=user.id, case_no=case.case_no, reason='document_quality', comment='recheck this pdf',
|
||||
)
|
||||
# 关键断言:后继快照只有当前 PDF,不能把同一 Intake 的其他附件一起带入。
|
||||
assert reused is False
|
||||
assert case.status == 'reparse_pending'
|
||||
marker = replacement.input_snapshot_json['review_reparse']
|
||||
assert marker == {'document_id': document.id, 'source_case_no': case.case_no}
|
||||
documents = [
|
||||
item for intake_snapshot in replacement.input_snapshot_json['intakes']
|
||||
for item in intake_snapshot['documents'] if item['document_type'] != 'email_body'
|
||||
]
|
||||
assert [item['document_id'] for item in documents] == [document.id]
|
||||
|
||||
duplicate, reused_duplicate = reparse_case_document(
|
||||
user_id=user.id, case_no=case.case_no, reason='document_quality',
|
||||
)
|
||||
assert reused_duplicate is True
|
||||
assert duplicate.id == replacement.id
|
||||
|
||||
finalize_document_reparse(run=replacement, succeeded=False)
|
||||
assert case.status == 'unreviewed'
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
# 已失败收口的 Run 不会在后续调用中错误替代旧 Case。
|
||||
assert case.status == 'unreviewed'
|
||||
assert case.current_draft is not None
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id, event_type='document_reparse_failed').count() == 1
|
||||
|
||||
|
||||
def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(app):
|
||||
"""成功后旧 Case 才只读替代;已确认/非订单 PDF 永远不能再次处置或重识别。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-REPARSE-SUCCESS')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
replacement, _ = reparse_case_document(user_id=user.id, case_no=case.case_no, reason='other')
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
assert case.status == 'superseded'
|
||||
assert case.disposition == 'reparsed'
|
||||
try:
|
||||
reparse_case_document(user_id=user.id, case_no=case.case_no, reason='other')
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_REPARSE_NOT_ALLOWED'
|
||||
else:
|
||||
raise AssertionError('superseded case must not be reparsed')
|
||||
|
||||
|
||||
def test_replacement_run_requires_new_pdf_and_preserves_old_case_until_success(app):
|
||||
"""替代上传必须来自新私有 PDF Intake;成功前保留旧草稿,成功后才把旧证据设为替代。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-REPLACEMENT')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake
|
||||
from app.services.shipping_notice.order_review_disposition_service import create_replacement_document_run
|
||||
|
||||
asset = FileAsset(
|
||||
asset_no='FAS-REVIEW-REPLACEMENT', owner_user_id=user.id, original_filename='replacement.pdf',
|
||||
extension='pdf', upload_status='ready', lifecycle_status='temporary', storage_provider='test',
|
||||
storage_bucket='test', storage_key='test/replacement.pdf', content_hash='replacement-asset-hash',
|
||||
file_size=1,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
replacement_intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-REVIEW-REPLACEMENT', asset_id=asset.id, user_id=user.id,
|
||||
conversation_id=session.session_id, upload_batch_id='review-replacement-test', purpose='shipping_notice',
|
||||
parse_status='parsed', parser_version=intake.parser_version,
|
||||
)
|
||||
db.session.add(replacement_intake)
|
||||
db.session.flush()
|
||||
replacement_document = ShippingNoticeDocument(
|
||||
intake_id=replacement_intake.id, asset_id=asset.id, attachment_key='file', document_type='attachment',
|
||||
filename='replacement.pdf', content_hash='replacement-hash', parse_status='parsed', extracted_text='replacement order',
|
||||
)
|
||||
db.session.add(replacement_document)
|
||||
db.session.commit()
|
||||
|
||||
# 布局调度由独立 Job 覆盖;此服务测试只验证替代文件的谱系与 Case 收口。
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts', return_value=True):
|
||||
replacement, reused = create_replacement_document_run(
|
||||
user_id=user.id, case_no=case.case_no, intake_no=replacement_intake.intake_no,
|
||||
)
|
||||
assert reused is False
|
||||
assert case.status == 'reparse_pending'
|
||||
assert replacement.input_snapshot_json['review_reparse'] == {
|
||||
'document_id': replacement_document.id, 'source_case_no': case.case_no,
|
||||
}
|
||||
finalize_document_reparse(run=replacement, succeeded=False)
|
||||
assert case.status == 'unreviewed'
|
||||
|
||||
|
||||
def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
|
||||
"""确认合格 PDF 只建一张无 Batch Task,且机器 Candidate 不能被人工确认覆盖。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-CONFIRM')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
schema = dict(snapshot['schema'])
|
||||
definition = dict(schema['definition'])
|
||||
definition['fields'] = [
|
||||
{'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', 'required': False, 'normalizer_key': 'trim', 'validator_keys': []},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
|
||||
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-CONFIRM'}]}], 'lines': [{'fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
|
||||
{'field_id': 'reservation-id', 'observations': [{'value': '3000092917'}]},
|
||||
]}]}]}
|
||||
machine = ShippingNoticeCandidate(
|
||||
candidate_no='CAND-REVIEW-CONFIRM', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='machine-confirm', order_extraction_run_id=run.id, structured_result_json={'machine': 'unchanged'},
|
||||
)
|
||||
db.session.add(machine)
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
validated = patch_header_field(
|
||||
user_id=user.id, case_no=case.case_no, field_id='po-id', value='PO-CONFIRMED', expected_draft_version=1,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
result = confirm_review_case(
|
||||
user_id=user.id, case_no=case.case_no, expected_draft_version=validated['draft']['draft_version'],
|
||||
idempotency_key='review-confirm-unique-1', warning_acknowledgements=[{'code': 'manual_checked'}],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
task = ShippingTask.query.filter_by(task_no=result['task_no']).one()
|
||||
revision = ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).one()
|
||||
# 关键断言:确认只生成当前 PDF 的一张 Task,无 Batch,并冻结草稿而不覆盖机器 Candidate。
|
||||
assert task.batch_id is None
|
||||
assert task.source_candidate_id is not None
|
||||
assert task.current_order_extraction_id is not None
|
||||
# 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。
|
||||
assert task.process_status == 'parsed'
|
||||
assert task.review_status is None
|
||||
assert task.pending_human_reason is None
|
||||
assert revision.task_id == task.id
|
||||
assert revision.header_values_json['values']['po-id']['value'] == 'PO-CONFIRMED'
|
||||
assert db.session.get(ShippingNoticeCandidate, machine.id).structured_result_json == {'machine': 'unchanged'}
|
||||
assert case.status == 'confirmed'
|
||||
|
||||
|
||||
def test_confirm_review_case_replays_same_task_and_rejects_stale_or_final_mutations(app):
|
||||
"""同键确认回放同一任务;旧版本确认、确认后编辑和处置均不能流入下游。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-CONFIRM-REPLAY')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
schema = dict(snapshot['schema'])
|
||||
definition = dict(schema['definition'])
|
||||
definition['fields'] = [
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
|
||||
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A002'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '3'}]},
|
||||
{'field_id': 'reservation-id', 'observations': [{'value': '3000092918'}]},
|
||||
]}]}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
try:
|
||||
confirm_review_case(user_id=user.id, case_no=case.case_no, expected_draft_version=99, idempotency_key='review-stale-1')
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_DRAFT_VERSION_MISMATCH'
|
||||
else:
|
||||
raise AssertionError('stale confirmation must be rejected')
|
||||
|
||||
first = confirm_review_case(user_id=user.id, case_no=case.case_no, expected_draft_version=1, idempotency_key='review-replay-1')
|
||||
db.session.commit()
|
||||
replay = confirm_review_case(user_id=user.id, case_no=case.case_no, expected_draft_version=1, idempotency_key='review-replay-1')
|
||||
# 关键断言:重复点击不创建第二 Task,终态 Case 也不能再修改或标记。
|
||||
assert replay['idempotent_replay'] is True
|
||||
assert replay['task_no'] == first['task_no']
|
||||
assert ShippingTask.query.filter_by(source_type='review_confirmation').count() == 1
|
||||
try:
|
||||
patch_line_field(user_id=user.id, case_no=case.case_no, line_key='machine-1', field_id='qty-id', value='4', expected_draft_version=1)
|
||||
except Exception as exc:
|
||||
assert getattr(exc, 'code', None) == 'SHIPPING.REVIEW_CASE_NOT_EDITABLE'
|
||||
else:
|
||||
raise AssertionError('confirmed case must be read-only')
|
||||
@@ -276,8 +276,8 @@ def test_normalize_notice_line_keeps_inventory_source_hint():
|
||||
assert summary['lines'][0]['inventory_source_hint'] == 'VMI-FRA01'
|
||||
|
||||
|
||||
def test_candidate_update_persists_inventory_source_hint_round_trip(app):
|
||||
"""Candidate 人工修订保存后,inventory_source_hint 必须仍在 business_summary 中。"""
|
||||
def test_candidate_selection_cannot_mutate_machine_business_summary(app):
|
||||
"""遗留选择接口只能更新 selected,机器业务摘要必须保持原样。"""
|
||||
from app.models import Agent, ChatSession, FileAsset, ShippingNoticeDocument, ShippingNoticeIntake, User
|
||||
from app.services.shipping_notice.candidate_service import update_candidate
|
||||
|
||||
@@ -356,24 +356,9 @@ def test_candidate_update_persists_inventory_source_hint_round_trip(app):
|
||||
updated = update_candidate(
|
||||
user_id=int(user.id),
|
||||
candidate_no='SNC-HUB-CODE-001',
|
||||
business_summary={
|
||||
'po_number': '4510038672',
|
||||
'lines': [{
|
||||
'part_number': 'P123456',
|
||||
'qty': 24,
|
||||
'reservation_id': '1000140351',
|
||||
'inventory_source_hint': 'DBS DUB',
|
||||
'uom': 'EA',
|
||||
}],
|
||||
},
|
||||
selected=True,
|
||||
)
|
||||
line = updated['business_summary']['lines'][0]
|
||||
assert line['inventory_source_hint'] == 'DBS DUB'
|
||||
assert updated['selected'] is False
|
||||
db.session.refresh(candidate)
|
||||
persisted = candidate.structured_result_json['business_summary']['lines'][0]
|
||||
assert persisted['inventory_source_hint'] == 'DBS DUB'
|
||||
history = candidate.structured_result_json['manual_review_history']
|
||||
assert history[-1]['action'] == 'business_summary_edited'
|
||||
assert history[-1]['actor_user_id'] == int(user.id)
|
||||
assert history[-1]['before_validation_status'] == 'needs_review'
|
||||
assert history[-1]['after_summary']['lines'][0]['reservation_id'] == '1000140351'
|
||||
assert persisted == {'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}
|
||||
+25
-2
@@ -111,18 +111,41 @@
|
||||
|
||||
### 3.x 货代发货通知建单防重复(第一阶段)
|
||||
|
||||
### 3.x 一封邮件多订单与 Candidate 级判重
|
||||
### 3.x 订单人工复核目标态(阶段 0,2026-07-28)
|
||||
|
||||
> 本节定义后续复核工作台的唯一目标契约,并优先于本节后保留的历史 Candidate 描述。历史“一份附件多订单、订单跨附件合并”仅是迁移前实现事实;阶段 7 必须移除其作为建单前入口的能力。
|
||||
|
||||
- 一个 PDF Unit 最多产生一个订单;一个订单只属于一份 PDF;订单可包含 0..N 条明细。系统不支持 PDF 多订单、订单跨 PDF、订单合并/拆分或明细跨订单移动。PDF 也可被处置为 `non_order` 或 `quality_issue`。
|
||||
- 机器 Candidate/Extraction 是不可变识别事实,绝不被人工编辑覆盖。每个 PDF Unit 恰有一个 `ShippingOrderReviewCase`,每个 Case 在可编辑生命周期内恰有一个当前 `ShippingOrderReviewDraft`;草稿保存人工 header、lines、字段来源、校验结果和递增 `draft_version`。
|
||||
- 确认时由服务端锁定 Case/Draft,校验 `expected_draft_version`、冻结 Schema、客户、重复订单、Reservation 和硬门禁;成功后同一事务生成不可变 Confirmed Revision、消费对应 Candidate 并创建唯一 Shipping Task。版本冲突返回 `409`,不得静默覆盖或建单。
|
||||
- Case 状态仅为 `unreviewed / draft / ready / confirming / confirmed / non_order / quality_issue / reparse_pending / superseded`;终态 `confirmed / non_order / superseded` 不可编辑。每个写动作都必须定义允许状态、目标状态和稳定错误码;Run 识别状态不因人工复核改写。
|
||||
- 用户 API 只能按当前用户拥有的 Run、Unit、Document 和 Case 授权读取;不得接受客户端任意 Schema、Document ID、证据引用或业务资格。用户 DTO 不返回全文、MinIO 对象键、模型原始响应、Prompt 或凭据。
|
||||
- Dify 不参与本目标态的识别、草稿、证据、确认或建单;相关画布由管理员手工维护,本任务结束时仅记录所需手工配置说明。
|
||||
|
||||
### 3.x 历史 Candidate 链路(待阶段 7 清理)
|
||||
|
||||
- 保持“一封 EML = 一个 Intake”;上传阶段只做快览:读取邮件头、正文白名单 HTML 表格快照和附件目录,不抽取附件全文、不创建附件 Document/派生资产、不调度 MinerU/OCR。订单抽取已切换为独立 Run:点击发送直接创建后台作业并轮询 Run 状态,不再把 `shipping_intake_nos` 发送给普通 Chatflow;普通无附件问答仍走聊天 SSE。
|
||||
- 一个附件可包含多个订单,一个订单也可跨正文/多个附件;按实际业务订单生成 Candidate,不按附件数量机械拆分。
|
||||
- 正文与附件由 HXOPS 的确定性关系规则关联并统一裁决;`part_number`/Qty 必须保留原文 evidence,不确定字段返回空值,关键字段冲突必须阻断自动建单。订单抽取主链不调用 Dify。
|
||||
- 判重以 Candidate 为业务粒度:附件 hash 判断相同文件,业务身份指纹判断同一订单,内容指纹区分完全重复与订单修订。
|
||||
- 高置信发货需求只要包含可信内部料号 `part_number` + 正数 Qty 且有原文证据即可自动创建 Batch/Task;Reservation ID 缺失时 Task 必须停在自然对话补字段门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。
|
||||
- 迁移前高置信 Candidate 可自动创建 Batch/Task;订单人工复核目标态切换后,任何 PDF 均必须由对应 Review Case 使用指定草稿版本确认,才可创建 Task。Reservation ID 缺失仍是硬门禁;`inventory_source_hint` 是可选库存源路由线索,不作为必填门禁。
|
||||
- 低置信、证据不足、阻断冲突或可能修订的 Candidate 保留待处理;同 Intake 已自动建单部分不得导致剩余 Candidate 丢失。
|
||||
- 订单抽取最终必须以持久化 `ShippingOrderExtractionRun` 为业务生命周期真相;发送时 Run 冻结用户、入口 Agent、会话、Intake、Schema 与附件选择计划的轻量请求快照,Worker 物化后另冻结 Document 正文执行快照。幂等键始终锚定请求快照,不依赖浏览器 request ID。
|
||||
- 订单附件结构化必须支持版本化订单坐标 Profile v2。模板真相为静态文档锚点、表区相对坐标、独立表头布局、明细物理行布局、字段区域到稳定 `field_id + field_code` 的绑定、注册解析器、跨页/终止规则;表头文字只能用于建议、校准和匹配,不能决定最终字段。已发布版本不可原地修改,同模板发布新版本时原子退役旧版本;Run 必须复制完整 published Profile,不能只保存当前 Profile ID。
|
||||
- 业务管理员必须通过受控样本页面维护订单坐标 Profile:可配置相对区域、静态锚点、独立表头/明细布局和注册解析器;不得编辑 HTML、原始 bbox、JSON、正则、脚本、Prompt 或结构指纹。草稿更新使用乐观锁;每个明细字段区域必须绑定 Schema 允许的 `pdf_coordinate`/`ocr_coordinate` 来源和最低证据等级;不可变版本可复制为新草稿或退役。
|
||||
- Profile 治理必须保存模板模式、训练样本计数和不含锚点正文的匹配策略摘要;训练/标注样本、盲测样本及其增删、草稿保存、区域/字段绑定变化、测试执行/批准、发布和退役均追加审计。样本文档被训练或盲测引用后不得删除;审计不得保存 PDF、HTML、对象存储地址、正文或凭据。
|
||||
- 订单文档模板后续统一按 `profile_code` 作为模板族管理版本;`version` 只在同一模板族内递增。每个模板族最多一个 `draft`、最多一个 `published`,可有多个 `retired`;默认选择顺序固定为 `published -> draft -> 最新 retired`,URL 显式指定版本时必须严格按该版本返回,找不到时返回明确 404,不得自动跳转到其他版本。
|
||||
- **订单模板录入 UX 重构(阶段 0–7)**:模板库、创建向导、草稿编辑、独立验证、发布检查和历史版本详情是职责分离的页面;页面路由固定为列表、`new`、草稿 `edit`、草稿 `validate`、草稿 `publish-check` 及只读 `versions/:version`。`profile_code` 是模板族身份且创建后不可改;Profile Version 是发布生命周期对象;Draft Revision 是同一草稿每次有效保存产生的不可变内容快照,三者不得混用。发布只能消费绑定当前 Revision/checksum/lock_version 与通过验证运行的不可变报告;草稿变化会使报告失效,阻断项不可绕过,警告必须逐项确认。
|
||||
- 创建新版本只从同族已发布版本建立下一草稿;复制为新模板必须使用新的 `profile_code`,两者不可复用同一动作。权限扩展不属于本期范围,但所有接口仍须记录实际 `actor_id`。
|
||||
- Dify 配置不属于本次代码实施范围;订单模板录入、验证和发布治理不新增 Dify Tool、节点、Prompt、变量或连线。管理员只需确认现有订单抽取主链仍为 HXOPS 本地确定性解析且未接入模板治理接口;任何 Dify 画布、工具或参数调整均由管理员手工完成。
|
||||
- 管理端必须从当前“版本操作抽屉”升级为“模板版本中心”:工作台保留草稿编辑,任意 `published`/`retired` 版本通过独立详情路由只读查看。详情页固定包含 `配置概览 / 样本画布 / 版本差异 / 审计记录 / 实际使用` 五个页签,并支持刷新恢复与链接分享;查看历史版本不得隐式创建草稿。
|
||||
- `审计记录` 页签必须支持按 `event_type`、操作者、日期范围和 `request_id` 过滤,并使用稳定游标分页避免新增事件导致翻页重复;访问详情、差异、审计和使用页签本身也要写入追加式审计,但只允许保存安全摘要,不得保存 PDF、正文、对象存储地址或盲测真值。操作者被删除时,历史记录仍需展示快照或 `unknown_actor`。
|
||||
- `实际使用` 页签必须回答“这个版本实际影响过哪些订单识别”:只统计每个 PDF Unit 最新的模板分流事实,优先使用 `selected_profile_id`,若历史 Run 未冻结外键但 `selected_profile_code + version + checksum` 一致,则以 `snapshot_identity_match` 展示,不得伪装成直接外键命中;列表需提供进入管理员只读 Run 审计页的定位信息,并在大量 Run 下依赖索引查询而非全表扫描。
|
||||
- 版本差异必须由服务端按同一 `profile_code` 内的稳定身份计算,并默认对比上一版本;前端只负责选择对比目标和展示结果,不得按显示名称、数组下标或当前页面状态自行猜测差异关系。
|
||||
- `published` 和 `retired` 版本严格只读,不提供原地编辑、覆盖发布或直接回滚。历史版本只能“复制为新草稿”;复制时只继承允许复用的配置与普通样本引用,不继承盲测批准状态、自动冻结资格或任何发布资格。
|
||||
- 历史版本画布必须读取发布时冻结的样本、Layout、Parser、Schema 与 checksum 证据,不得回读文档当前最新布局,也不得根据当前解析结果反推历史版本内容。现有未冻结证据的旧 Profile/Sample 记录不得伪装成可审计历史版本;如需纳入版本中心,必须按新规则重新建样本并重新发布。
|
||||
- 标注样本与训练样本可在版本详情中查看;普通版本详情中的样本列表不得返回 blind test 样本身份。盲测相关信息只允许以套件状态、样本数、批准时间、最近运行结果等摘要返回,不得返回 `expected_*` 真值、可推导答案的坐标信息、原始 PDF 身份、对象存储地址或其他可复原盲测答案的数据。
|
||||
- 发布门禁必须绑定“当前草稿定义 checksum + 当前 approved blind test”这一组事实:至少 1 份训练样本、至少 1 份与 annotation/training 完全独立的 blind test 样本、至少 1 份多明细真值;声明跨页时还必须覆盖带 `continuation_of` 的续页样本。任一条件不满足都必须阻断发布,不能以“先发布再补盲测”的方式绕过。
|
||||
- 模板工作台页面预览仅针对已绑定样本:PDF 以短时、单页、单用途 Redis 授权返回低分辨率 PNG,响应始终 `private, no-store`,不返回 MinIO URL、PDF、bbox、原始 HTML 或永久下载令牌。OCR 坐标只可由管理员对绑定 PDF 显式触发;页面文本和局部解析候选不包含坐标/token 身份。EML 仅使用既有白名单清洗的表格文本,禁止脚本、事件属性、表单、iframe、外链及远程图片/字体。
|
||||
- MinerU 按显式环境开关固定使用 `pipeline`,由发送后的 Worker 在 Document 物化后异步调用,不得阻塞上传快览。布局必须按 Document 独立版本化,保存 parser revision、状态、checksum、大小、质量问题和 Worker lease;只有成功版本可成为当前布局,失败/超限/旧 Worker 结果不得覆盖上一次成功版本。多附件受单 Run 文档预算限制;Provider 失败、超预算、结构不匹配或多表命中时进入人工复核,不得伪造确定性字段或回退 Dify。
|
||||
- 人工单元格真值当前允许延期,不阻塞布局版本/任务生命周期建设;但在真值评测完成前,不得宣称 95% 准确率、把 MinerU/OpenCV/文本对齐候选自动标记为 `accepted`,也不得据此开启错误自动建单风险。
|
||||
|
||||
@@ -53,8 +53,7 @@
|
||||
|
||||
**货代发货通知助手**帮助业务人员把客户发来的发货指令(邮件、微信文字、PDF、Word 等)转成可执行的发货动作,主要能力包括:
|
||||
|
||||
1. **解析发货通知**:上传后系统先读取邮件正文和附件;点击发送会提交可恢复的后台订单识别任务,再由系统逐字段核验证据,识别客户、收货信息,以及每一行的内部料号、客户料号、AWS 料号、数量、金额、Reservation ID 等。页面关闭、刷新或短时网络中断不会取消后台任务,重新进入会话会恢复任务状态。
|
||||
一封 EML 中可以包含多个订单,也可能一个附件里包含多个订单;系统仍保留为一个接入记录,并按实际业务订单拆分处理。
|
||||
1. **解析与复核发货通知**:上传后系统先读取邮件正文和附件;点击发送会提交可恢复的后台订单识别任务,再由系统逐字段核验证据。每一份 PDF 是一个独立复核对象,最多形成一张订单及其多行明细;页面关闭、刷新或短时网络中断不会取消后台任务,重新进入会话会恢复任务状态。不能识别为订单的 PDF 由业务人员标记为非订单或文件质量异常,而不是与其他 PDF 合并。
|
||||
2. **载入库存**:正式发货优先使用库存站点按排程或手动刷新导出的有效库存文件;对已有发货任务,可通过“选择库存文件”进行受控人工上传。系统按该任务库存站点已发布的解析方案校验工作表、表头和栏位,符合后直接进入匹配,不要求业务人员维护列映射。若用户在对话中临时上传 `.xls` / `.xlsx` / `.csv`,必须明确说明“这是库存文件”;系统只做隔离分析和待确认建议,绝不会直接进入正式库存匹配。
|
||||
|
||||
### 库存站点启用
|
||||
@@ -79,7 +78,7 @@
|
||||
|
||||
**系统如何工作(便于理解)**:
|
||||
|
||||
- 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后完整订单识别在后台执行,不依赖聊天连接持续在线。进行中显示不确定进度,不展示虚假百分比;失败附件会回到可重试入口。只要明确属于发货需求且内部料号、数量可信,系统会自动创建任务,无需再次人工确认建单。
|
||||
- 上传 **发货通知 EML/PDF/Word** 后,系统先自动读取正文和附件;点击发送后完整订单识别在后台执行,不依赖聊天连接持续在线。进行中显示不确定进度,不展示虚假百分比;失败附件会回到可重试入口。每份 PDF 均须在复核工作台确认对应草稿版本后独立创建任务;识别可信不替代人工确认。
|
||||
- 识别卡会按“等待执行、解析邮件及附件、识别订单、整理结果、生成任务”等通用阶段更新;可展开查看已收到的阶段时间线。阶段名称不会展示内部 Workflow、节点名称、模型思考或邮件/附件内容。
|
||||
- Reservation ID 暂时缺失时,任务仍会创建,但会停在“待补充字段”,不会继续查库存;订单行 `inventory_source_hint` 是可选路由线索,可在候选编辑中补充,不作为必填门禁。
|
||||
- 如果网络短时中断,进行卡会继续保留;系统会自动重试查询。切换到其他会话不会取消后台识别,返回原会话后可继续查看。只有后台 Run 明确失败时附件才恢复为可重试状态。
|
||||
@@ -226,6 +225,14 @@ WYC26071501
|
||||
|
||||
“纳入当前版本”只决定字段是否参与本次发布和订单解析,不控制名称编辑。未纳入字段仍可修改并保存系统标识与当前草稿显示名称;后续重新纳入时继续使用已保存配置。
|
||||
|
||||
订单文档模板接下来按“模板版本中心”治理,而不是继续停留在只会操作当前草稿的抽屉。`profile_code` 表示模板族,例如 `T01`;`version` 只在该模板族内递增。管理员默认先看到当前生效版本;没有生效版本时再落到草稿;只剩退役版本时显示最新退役版本。直接通过链接打开某个版本时,系统只展示该版本,不会偷偷跳到别的版本。
|
||||
|
||||
业务上,`当前草稿 / 当前生效 / 已退役` 都允许查看完整版本内容,但权限动作不同:草稿可继续编辑;当前生效和已退役只能查看,不能原地编辑、覆盖发布或直接回滚。历史版本唯一允许的后续动作是“复制为新草稿”,再在新草稿上修改和重新发布。
|
||||
|
||||
版本详情会是一个独立页面,支持刷新恢复和链接分享,固定包含 `配置概览 / 样本画布 / 版本差异 / 审计记录 / 实际使用` 五个页签。这里的“样本画布”必须展示当时发布版本实际审核过的冻结证据,而不是文档后来重新解析出的最新布局。
|
||||
|
||||
样本查看范围也要区分:标注样本和训练样本可以按正常版本详情查看;盲测样本在普通版本详情里只显示脱敏身份和结果摘要,不显示人工真值、可推导答案的坐标、原始 PDF 身份或其他可能泄露答案的数据。这样即使暂时沿用 `@require_admin`,普通版本详情也不会把盲测答案直接暴露出来。
|
||||
|
||||
| 配置项 | 含义 | 建议维护方式 |
|
||||
|---|---|---|
|
||||
| 字段位置 | 字段属于整张订单,还是每条货品明细 | PO/客户名填“订单信息”;料号、数量、Reservation ID 填“货品明细” |
|
||||
@@ -311,6 +318,8 @@ WYC26071501
|
||||
发货通知 → 确认解析 → 确认客户并生成业务编号 → 获取或上传库存 → 系统校验并解析 → 匹配库存 → (有满足项则生成本轮 Excel;缺货项继续等待)→ 上传货代
|
||||
```
|
||||
|
||||
**订单人工复核约束(目标态)**:在创建任务前,业务人员在独立复核工作台逐份处理 PDF。系统机器识别结果始终保留;业务人员编辑的是独立草稿,保存后可继续处理或刷新恢复。确认建单时系统只消费当前已保存的草稿版本;若另一个窗口已更新该草稿,系统提示版本冲突而不会覆盖对方结果。每个 PDF 可独立确认建单,其他 PDF 的处理状态不受影响。
|
||||
|
||||
---
|
||||
|
||||
## 6. 各阶段您需要做什么(分阶段 SOP)
|
||||
|
||||
@@ -339,6 +339,27 @@ MinerU 服务地址、无认证方式和 OpenAPI 已确认,并已取得脱敏
|
||||
**模板样本治理与版本识别 Review(2026-07-23)**:样本文档按上传时间倒序显示,并在选择器中标明文件名、时间、解析状态和表格数,可按文件名搜索;同一 `profile_code` 的 `published` 版本显示“当前生效”和发布时间。模板工作台样本下拉只查询页面专用上传样本 (`purpose=order_document_profile_sample`),普通 `shipping_notice` 业务附件不显示也不可从该入口维护。专用样本仅在已解析完成、未被独立盲测引用且其资产未被其他业务引用时允许删除;删除同时回收源文件和布局结果。Profile 当前未持久化“创建时样本”外键,因此不得声称可以按该不存在的关系阻止删除;如需这一级审计保护,须另行设计字段、迁移和历史数据策略。
|
||||
|
||||
**表头污染与坐标重建 Review(2026-07-22)**:若样本表头混入明显订单行值(例如 `ITEM NO 00010`),预览返回稳定诊断 `order_profile_header_contaminated_by_data` 并标记不可建 Profile;服务端也拒绝从该表创建草稿,避免浏览器绕过。Profile 页面不是手工修复原始网格的入口。对有 PDF 原生 glyph 坐标且已人工确认列锚点的文档,`coordinate_table_reconstruction` 仅输出 `needs_review` 候选:以 x-overlap/唯一中心距离归属列,以字体高度自适应 y-band 判断新视觉行,内容形态与相邻行连续性只作辅助;无强行号的行只能是续行或复核,`** Item deleted **` 只能附着前一强锚定明细。候选保留 glyph 索引,坐标不足、列归属并列或删除行无前序明细时一律复核,绝不自动接受、发布 Profile 或进入履约。
|
||||
**模板版本中心契约 Review(2026-07-28)**:订单模板管理入口升级为按 `profile_code` 聚合的版本中心。`draft / published / retired` 仍是唯一生命周期,但“查看版本”和“创建新版本”分离:查看任意 `published/retired` 版本只进入独立详情路由 `/admin/shipping-order-document-profiles/:profileCode/versions/:version`,不得隐式创建草稿。默认版本选择顺序固定为 `published -> draft -> 最新 retired`;URL 指定不存在版本时必须返回 404,不允许前端或后端自动改跳其他版本。版本详情固定包含 `配置概览 / 样本画布 / 版本差异 / 审计记录 / 实际使用` 五个页签,其中配置概览优先加载,PDF 画布、审计、使用情况按页签懒加载。
|
||||
|
||||
**历史画布与盲测隔离 Review(2026-07-28)**:历史样本画布必须显式区分 `edit` 与 `readonly` 两种模式,不能靠隐藏保存按钮伪装只读。`published/retired` 详情只允许切换样本、翻页、缩放、查看区域详情和复制为新草稿,禁止新建/拖拽/删除区域、重绑字段、撤销重做、自动建议写入、保存、OCR 重跑及样本解除绑定。画布读取只能使用发布时冻结的 Sample 绑定、Layout 版本、文件 hash、Layout checksum、Schema checksum 和 Parser 身份;缺任一证据时明确失败,不允许回读当前最新布局。普通版本详情 DTO 只返回盲测套件状态、样本数量、通过/失败数量、批准时间和最近运行摘要,不返回 `expected_rows_json`、`expected_order_fields_json`、人工真值、可推导答案的坐标或未执行盲测 PDF 的完整身份。
|
||||
|
||||
|
||||
**模板版本语义差异 Review(2026-07-28)**:版本中心 `diff` 页签已落地,统一通过 `GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/diff?against_profile_id={id}` 由服务端计算。未显式指定对比版本时默认上一版本;显式比较只允许同一 `profile_code`,跨模板立即阻断。差异引擎按 `region_id / layout_id / field_id / anchor_id` 等稳定身份配对,坐标矩形统一使用 `0.001` 容差过滤浮点噪声,避免字段改名、排除区重排或序列化精度造成“删除+新增”误判。前端仅展示结构化 summary、变更项和折叠的安全 JSON 快照,不直接比较整份 definition,更不暴露正文、对象存储地址或盲测真值。
|
||||
|
||||
**模板版本治理审计与实际使用 Review(2026-07-28)**:版本中心阶段 6 已落地 `audit` / `usage` 两个真实页签,分别对应 `GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/audit-events` 与 `GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/usages`。审计时间线支持 `event_type`、操作者、日期范围、`request_id_filter` 和 `before_id` 游标分页;访问详情、差异、审计、使用页签本身也会追加 `version_detail_viewed / version_diff_viewed / version_audit_viewed / version_usage_viewed` 审计,但只写过滤条件、结果计数等安全摘要。操作者缺失时统一降级为 `unknown_actor`,时间统一返回 ISO 8601。
|
||||
|
||||
`usage` 页签只统计每个 PDF Unit 最新一次 `RouteDecision`,先按 `selected_profile_id` 直接命中;如果历史 Run 没有外键但冻结的 `selected_profile_code + selected_profile_version + selected_profile_checksum` 与当前版本一致,则返回 `snapshot_identity_match`。两种命中方式必须显式区分,绝不能把快照匹配伪装成真实外键引用。列表只返回脱敏文档名、Run 编号、匹配/执行状态、原因码和进入管理员只读 Run 审计页所需的 `run_no`,不返回正文、对象存储地址、PDF 或模型原始输出。
|
||||
|
||||
为保证大量 Run 下的治理查询可用,`shipping_order_document_profile_audits` 新增 `(profile_id, request_id, id)` 索引,`shipping_order_extraction_route_decisions` 新增 `selected_profile_id` 与 `(selected_profile_code, selected_profile_version, selected_profile_checksum)` 查询索引。阶段 6 的产品边界到此为止,不提前揉入阶段 7 的盲测真值开放或发布治理增强。
|
||||
|
||||
**模板版本盲测隔离与发布治理 Review(2026-07-28)**:阶段 7 已收口到两个关键边界。第一,普通版本详情 DTO 的 `sample_summary.samples` 只返回 annotation/training 样本,blind test 仅保留 `blind_test_count` 与 `test_summary` 摘要;网络响应不再下发 blind test 文件名、文档身份、真值或可还原答案的坐标。第二,`publish()` 不再允许“先发布后补盲测”,而是先对归一化后的草稿定义重算 `structure_fingerprint`,然后执行 `assert_profile_publishable()`:至少 1 份训练样本、至少 1 份与 annotation/training 完全独立的 blind test 样本、至少 1 份多明细真值,声明跨页时还必须覆盖 `continuation_of` 续页样本。
|
||||
|
||||
发布成功后,同一事务内会冻结样本的 Layout/Parser/Schema/checksum 证据,随后把已批准 blind test suite 与 runs 的草稿 checksum 原子提升为正式 Profile checksum,保证历史版本详情仍能准确回放测试摘要。与此同时,发布后的自动冻结资格仍固定从 `manual_confirmation` 起步,不会因为草稿阶段已批准 blind test 就自动变成 `auto_freeze_approved`;scope 配置、客户确认和后续资格审批依然走既有独立治理路径。
|
||||
|
||||
**阶段 7 Dify 手工配置说明(模板版本中心)**:无需新增、修改或重新导入 Dify Tool/OpenAPI,也无需调整任何 Prompt、节点、变量或连线。模板版本中心、只读画布、语义 diff、审计、usage、盲测隔离和发布门禁全部由 HXOPS Admin API 与后端事务承担;管理员只需确认现有 Chatflow/Workflow 中不存在“读取模板版本详情后直接发布模板”“回传 blind test 真值”“依赖模板版本页签状态推进业务”的旧节点或输出字段。
|
||||
|
||||
**阶段 0 验收标准(模板版本中心契约)**:产品、前端、后端文档统一使用 `profile_code / version / draft / published / retired` 术语;明确历史版本只能查看和复制为新草稿,不能直接编辑、覆盖或回滚;明确版本详情固定五页签与独立路由;明确历史画布只读取冻结证据,不读取当前最新 Layout;明确普通版本详情不返回盲测真值、对象存储地址和 PDF 正文。阶段 0 未满足这些文档契约前,不进入后续模型、API 或前端实现阶段。
|
||||
|
||||
|
||||
**坐标逻辑明细闭环 Review(2026-07-23)**:坐标 Profile 不再依赖数据页自身的完整表头,而是按确认列数生成稳定虚拟表头并冻结列字段编码、新行起始列。字符先按 y-band 和横向间距组成文本片段,列归属仍以 x-overlap 为主,只在边界近似并列时使用字段格式(行号、数量/金额、单位、日期、料号)和同行从左到右顺序辅助。物理 `data/continuation/deleted/summary` 被保留到逻辑重建:续行按列并入最近明细,删除标记回写最近明细,合计/账单/条款起始行结束数据区;纯表头页因无逻辑明细不算 Profile 命中。管理页显示有效/删除状态和来源物理行,管理员确认后才可保存草稿,发布仍受盲测与自动建单质量门禁约束。
|
||||
|
||||
@@ -2175,9 +2196,9 @@ API 层
|
||||
|
||||
合并优先使用 `PO + MPN`;只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。
|
||||
|
||||
#### 阶段 3:PDF 模板解析、PO 拆分与严格拒识(2026-07-27)
|
||||
#### 阶段 3:PDF 模板解析、PO 拆分与严格拒识(2026-07-27,迁移前历史)
|
||||
|
||||
单 PDF 只有在同一个已批准模板表中、每条明细均带唯一且可验证的 PO 时,才按 PO 拆为独立订单/候选/后续任务;每个结果保留同一源 PDF 的字段证据。未证明第二个 PO 时不得臆造拆分;表级多 PO 而没有逐行归属、模板歧义、版式漂移、缺锚点或字段证据不足时,统一 `review_required`。
|
||||
该阶段的“单 PDF 按 PO 拆为多个订单/候选/后续任务”是迁移前行为,仅作为历史审计记录。订单人工复核目标态不再允许拆分:单 PDF 最多保留一张订单草稿;多 PO、模板歧义、版式漂移、缺锚点或字段证据不足均统一 `review_required`,由同一 Case 的人工处置路径处理。
|
||||
|
||||
Route Decision 现在分别记录 `document_table_count`、`business_table_count`、`matched_table_count` 和 `parsed_table_count`,不得再以成功匹配数冒充文档真实表数;这些仅为脱敏计数,不保存订单值、正文或坐标。
|
||||
|
||||
@@ -2189,12 +2210,53 @@ Route Decision 现在分别记录 `document_table_count`、`business_table_count
|
||||
|
||||
Run 自动冻结门禁真实消费资格表中的客户/业务场景范围:若 Bill-to 客户未确认、命中多个客户、客户不在白名单、业务场景未配置或不在白名单,都会写入稳定 `blocking_reason_codes` 并保持 **fail-closed**。只有资格、客户/场景范围及所有 Run/Task 冻结门禁均放行时,执行入口才消费当前 Run 的 accepted Candidate 并冻结新建 Task;盲测、质量批次或模板发布本身均不能直接打开自动冻结,也绝不触发库存、Excel 或上传。
|
||||
|
||||
**本阶段 Dify 配置**:无需修改。模板版本中心、历史只读详情、冻结证据读取、语义差异、审计记录和盲测隔离都由 HXOPS 自身 API 与管理端实现;Dify 画布仍由管理员手工维护,任务收尾时只补充配置说明,不由代码自动改写。
|
||||
|
||||
#### 阶段 5:人工复核与字段证据闭环(2026-07-28)
|
||||
|
||||
人工改单、增删行和字段冲突解决不再接受任意 `evidence_ref` 字符串。工作台请求必须同时带 `expected_order_data_version`、原因和结构化 `evidence`:`document_cell` 必须引用当前 Task 的当前 Extraction 中同一 Document 的 Observation,并包含页码、表格和单元格标识;`manual_input` 必须带人工确认原因。伪造、跨订单、跨 Extraction 或缺少原因的证据在写入 FieldValue 前被拒绝。
|
||||
|
||||
每项变更仍追加 `shipping_order_review_events`,保存前后值、字段/行、操作者、原因、结构化证据、当前 Extraction 和时间;编辑导致的 `order_data_version` 变化使并发旧请求失败。任务详情证据面板显示文档、页码、表格/单元格和原文 quote(存在时);未匹配模板不能通过人工整单录入绕过模板建设。
|
||||
|
||||
### 建单前订单人工复核目标态(阶段 0,2026-07-28)
|
||||
|
||||
本节定义新的建单前复核域,替代上文 Task 创建后的字段修订语义;Task 创建后的修订仍是履约阶段能力,不能作为建单前复核入口。数据流固定为:`不可变 Candidate/Extraction -> Review Case -> Review Draft(draft_version) -> Confirmed Revision -> Shipping Task`。Run 对每个 PDF Unit 创建一个且仅一个 Case,即使该 Unit 没有 Candidate;每个 Case 最多一张订单、订单只属于该 PDF,允许多行明细但禁止多订单、跨 PDF 合并/拆分和跨订单移动行。
|
||||
|
||||
Case 状态:`unreviewed`、`draft`、`ready`、`confirming`、`confirmed`、`non_order`、`quality_issue`、`reparse_pending`、`superseded`。Draft 仅以 `clean/dirty/saving/saved/save_failed/version_conflict` 表达客户端保存显示,不得替代服务端状态。所有 Case 写操作携带 `expected_draft_version`;服务端在锁定 Case/Draft 后校验版本和冻结 Schema,版本落后统一返回 `409`。`confirmed/non_order/superseded` 以及正在确认的 Case 不可编辑。
|
||||
|
||||
| 动作 | 允许 Case 状态 | 目标状态 | 失败码 |
|
||||
| --- | --- | --- | --- |
|
||||
| 初始化或创建唯一草稿 | `unreviewed`、`quality_issue` | `draft` | `SHIPPING.REVIEW_CASE_NOT_EDITABLE`、`SHIPPING.REVIEW_ORDER_ALREADY_EXISTS` |
|
||||
| 保存字段或明细、重置草稿 | `draft`、`ready` | `draft` 或 `ready` | `SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT`、`SHIPPING.REVIEW_SCHEMA_VALIDATION_FAILED` |
|
||||
| 校验草稿 | `draft`、`ready` | `draft` 或 `ready` | `SHIPPING.REVIEW_SCHEMA_VALIDATION_FAILED` |
|
||||
| 标记非订单 | `unreviewed`、`draft`、`ready` | `non_order` | `SHIPPING.REVIEW_DISPOSITION_BLOCKED` |
|
||||
| 标记质量异常/单 PDF 重新识别 | `unreviewed`、`draft`、`ready`、`quality_issue` | `quality_issue` 或 `reparse_pending` | `SHIPPING.REVIEW_DISPOSITION_BLOCKED` |
|
||||
| 确认并建单 | `ready` | `confirming -> confirmed` | `SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT`、`SHIPPING.REVIEW_CONFIRMATION_BLOCKED` |
|
||||
|
||||
`confirming` 只存在于持有数据库事务和行锁的短暂期间;事务提交后必定进入 `confirmed`,回滚后恢复原 `ready`,因此没有无法退出的中间状态。
|
||||
|
||||
#### 阶段 6:按 PDF 原子确认建单(2026-07-29)
|
||||
|
||||
确认接口为 `POST /api/workspace/shipping-notice/order-review-cases/{case_no}/confirm`。请求必须提供 `expected_draft_version` 和 `idempotency_key`;服务端在同一事务中锁定 Case/Draft、重跑冻结 Schema 全量校验、执行文件哈希与业务重复门禁、写入 `shipping_order_review_confirmed_revisions` 不可变快照,再创建**不归属 Batch 的单个 ShippingTask**。一份 PDF 只对应此一张 Task;同一 Run 的其他 PDF 不受影响。
|
||||
|
||||
确认过程为履约兼容性物化一条 `accepted` 的人工 Candidate 和 Accepted Extraction,但绝不改写机器 Candidate 的 `structured_result_json` 或机器 Extraction。Case 的 `confirmed_task_id`、确认事件和 Confirmed Revision 共同保存草稿版本、冻结 Schema、头/行 JSON、校验结果、警告确认、操作者和幂等键。相同幂等键或已确认 Case 重放时只返回原 Task;版本冲突、草稿校验失败、重复或任何创建异常均回滚,原 Draft 不丢失。
|
||||
|
||||
#### 阶段 7:聊天入口收敛(2026-07-29)
|
||||
|
||||
对话中的订单抽取卡只展示 Run 概览、处理详情和“进入人工复核”入口;处理详情抽屉只展示 PDF 结果概览与 Run 事实时间线。旧 `ShippingNoticeCandidateReview` 聊天编辑/采纳/驳回/重复决策组件已移除,Candidate 仅保留为后端不可变识别事实和审计来源。建单前编辑、处置、单 PDF 重识别、替代 PDF 与确认建单均只能在订单人工复核工作台完成。
|
||||
|
||||
运行中详情以 PDF 队列为主:即使 Unit 尚未物化,也会从冻结选择计划显示已选 PDF;版面解析 Worker 开始和完成时写入对应 PDF 的脱敏进度事件。详情抽屉打开期间按短轮询持续刷新 Run、PDF 结果和事件,避免长时间解析只在最终状态才出现变化;界面只展示有事实来源的阶段、文件和时间,不伪造百分比。
|
||||
|
||||
复核工作台不是独立聊天路由:入口在同一 `ChatView` 上写入 `mode=order-review&run_no={run_no}`,仅替换主内容区。左侧 Agent/历史、当前 `conversation_id`、消息内存和滚动位置始终由同一个 ChatView 实例持有;返回时仅移除这两个 query,不重新加载 Agent、历史或会话。历史 `/chat/{agentId}/shipping-order-review/{runNo}` 链接保留重定向兼容。工作台中心为单头网格与可横向滚动的单身表格,右侧默认 PDF/证据检查器;“对话上下文”按需替换右侧检查器显示最近相关消息和附件,避免常驻双窗口挤压复核空间。
|
||||
|
||||
工作台切换 PDF 时仅更新 `case` query,必须保留 `mode`、`run_no` 与原会话 query,防止主区误退回聊天欢迎页。
|
||||
|
||||
**本目标态 Dify 配置**:无需修改。订单抽取、Review Case、草稿、确认建单和聊天入口均由 HXOPS 本地实现;管理员不得为这些动作新增 Dify Tool、变量、Prompt 或自动确认分支。
|
||||
|
||||
阶段 1 的只读接口为 `GET /api/workspace/shipping-notice/order-extraction-runs/{run_no}/review` 和 `GET /api/workspace/shipping-notice/order-review-cases/{case_no}`。DTO 只包含按冻结 Schema 安全投影的字段、行、状态、问题、动作和证据摘要;它不返回 PDF 正文、MinIO 地址/对象键、原始模型响应、Prompt 或未授权 Document。后续写接口由 Case 和冻结 Schema 决定可编辑字段,不能由浏览器传入任意 Schema、Document 或 evidence identity。
|
||||
|
||||
**阶段 0 验收**:六份权威文档必须一致说明“一 PDF 至多一订单、订单可多行、机器事实与人工草稿分离、确认消费指定草稿版本”;状态机没有无法退出的中间状态;每项动作具有状态、错误码与权限边界。Dify 无需修改且不属于该数据流。
|
||||
|
||||
#### 阶段 6:统一冻结就绪门禁(2026-07-28)
|
||||
|
||||
`freeze_order_snapshot` 在同一事务以 `SELECT FOR UPDATE` 锁定 Task,并由 `freeze_readiness_service` 聚合检查当前已接受 Extraction、已确认 Bill-to、开放字段冲突、订单行、履约策略绑定的 `part_number` / `reservation_id` / 正数 `qty`,以及客户端给出的 `order_data_version`。任意失败均以 `SHIPPING.ORDER_FREEZE_BLOCKED`(或更具体的既有门禁码)拒绝,绝不写入半成品 Snapshot。
|
||||
|
||||
+4
-1
@@ -63,10 +63,13 @@
|
||||
| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 |
|
||||
| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake 快览:只解析邮件正文、白名单 HTML 表格快照和附件目录;上传阶段不抽取附件全文、不创建附件 FileAsset/Document、不生成 Candidate、不判订单重复;解析失败、超时、取消保持幂等 |
|
||||
| 上传与发送门禁状态一致性 | 已实现 | Intake 状态接口返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;聊天附件快览成功后显示“已就绪/已发现 N 个附件”并允许发送,不再因上传阶段版面任务阻塞;真正的订单识别进度在点击发送后单独展示 |
|
||||
| 点击发送完整订单抽取 | 已实现 | Run 冻结文档、Schema、模板 Profile 和确定性解析器版本;Worker 只执行本地模板解析,支持一附件多订单、证据门禁、幂等重放及人工复核,不依赖 Dify、Provider 或 Runtime Binding |
|
||||
| 点击发送完整订单抽取 | 已实现 | Run 冻结文档、Schema、模板 Profile 和确定性解析器版本;Worker 只执行本地模板解析、证据门禁和幂等重放,不依赖 Dify、Provider 或 Runtime Binding;旧的一附件多订单投影待订单复核目标态阶段 7 清理 |
|
||||
| 订单识别生命周期反馈 | 已实现 | Run 状态卡按真实确定性解析进度和终态计数更新并持久化到 `ChatLog.payload`;聊天历史可恢复,侧栏显示未查看终态提醒,处理中不伪造百分比 |
|
||||
| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,PDF 数量保持权威,歧义统一进入人工复核 |
|
||||
| PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 |
|
||||
| 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理 |
|
||||
| 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;阶段 7 已删除旧兼容工作台/创建路径和直接发布入口,并完成前后端构建、定向回归、迁移链及四语言校验。Dify 无需配置变更,仅由管理员核对本地确定性解析主链未接入模板治理接口。 |
|
||||
| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。对话仅保留识别概览/工作台入口,旧 Candidate 操作 UI 已移除 |
|
||||
| 模板发布与自动冻结资格分离(阶段 4) | 已实现 | Profile 的发布仅允许确定性解析;每个发布版本独立冻结人工确认资格,首版强制 `manual_confirmation` 且自动冻结关闭,盲测批准、旧版本资格或 checksum 变化均不能越过该门禁 |
|
||||
| Run 自动冻结门禁与执行 | 已实现 | Run 创建时冻结 `manual_confirmation` 初始策略;结果落库后按模板资格、已确认 Bill-to 客户、业务场景、技术失败、预算停止和待处理订单刷新 `auto_freeze_policy_json`。仅资格与全部门禁显式放行时,自动消费当前 Run 的 accepted Candidate 并冻结新建 Task;不触发库存、Excel 或上传履约副作用。 |
|
||||
| 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 |
|
||||
|
||||
+17
-2
@@ -22,13 +22,25 @@
|
||||
- 坐标版式建议先按自适应 y-band 分组物理行,再以左侧行号识别逻辑明细起点;相同 `row_offset` 的文本片段按相对 x 中心聚类,以相邻中心中点生成边界。接口只自动绑定确定性的 `line_no`,其他字段仍由管理员根据列示例确认,建议状态固定为 `needs_review`。
|
||||
- `shipping_order_document_profiles` 保存模板编码、版本、绑定 Schema、v2 定义校验值、完整定义、checksum 和乐观锁。同一模板只允许一个 published 版本;后续阶段的 Run 将冻结唯一匹配结果、Profile checksum、坐标证据和完整定义,发布/退役不会改变历史运行。
|
||||
- Schema 与 Profile 使用稳定 `field_id` 解耦版本:发布前评估 `compatible / review_required / breaking` 影响,published breaking 必须显式确认。非 breaking Profile 在运行快照中按目标 Schema 自动重映射 `field_code`;breaking 字段只能迁移到作用域、类型和坐标来源兼容的其他字段,或解除绑定并保留区域。迁移草稿不继承盲测批准且未绑定区域禁止发布,历史 Run 继续读取原冻结版本;该治理不改变 Dify 契约。
|
||||
- 管理端模板版本中心统一按 `profile_code` 聚合同族版本,`version` 仅在族内单调递增。版本路由使用 `/admin/shipping-order-document-profiles/:profileCode/versions/:version`;默认命中顺序固定为 `published -> draft -> 最新 retired`,URL 指定版本时服务端只返回该版本或 404,不做隐式跳转或“就近恢复”。
|
||||
- **模板录入治理契约(阶段 0 冻结)**:草稿有效保存必须以 `profile_id + revision_no + definition_checksum` 形成不可变 Revision;单写者 Lease 以 `profile_id + browser_session_id` 约束,失效、接管和旧 `lock_version` 写入均返回稳定 409。验证运行和发布检查报告都必须冻结 Revision、definition checksum、Schema/Sample/Layout/Parser 身份;草稿有效变化立即使旧验证和发布检查失效。所有关键写操作通过 `operation_id` 串联 `request_id`、actor、浏览器会话、Revision、验证和发布检查,审计仅保存安全语义摘要。
|
||||
- 阶段 0 只冻结前后端字段、枚举、错误码和 URL,不新增数据库表、保存逻辑、自动保存、验证或发布行为;旧工作台继续承担现有流量,直到对应阶段通过验收后替换。
|
||||
- 版本详情页的产品契约固定为五个懒加载页签:`配置概览 / 样本画布 / 版本差异 / 审计记录 / 实际使用`。`published/retired` 版本只能只读查看,不得原地编辑、覆盖发布或直接回滚;历史版本唯一写入口是“复制为新草稿”,且新草稿不继承盲测批准状态、自动冻结资格或任何旧版本发布资格。
|
||||
- 版本差异由后端接口 `GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/diff?against_profile_id={id}` 统一计算;未显式指定时默认对比上一版本。服务端只允许同一 `profile_code` 内比较,按 `layout_id / region_id / field_id / anchor_id` 等稳定身份配对,并对区域坐标使用 `0.001` 容差过滤浮点噪声。前端仅消费结构化 summary、变更条目和安全 JSON 快照,不自行推导 diff。
|
||||
- 历史样本画布必须绑定发布时冻结的 Sample 关系、`layout_version_id`、文件 hash、Layout checksum、Schema checksum 和 Parser 身份;读取失败时明确报错,不允许自动降级到文档当前最新 Layout 或最新解析结果。普通版本详情 DTO 只返回盲测摘要与脱敏样本身份,不返回 `expected_*` 真值、可推导答案的坐标、对象存储地址、PDF 正文或预览令牌。
|
||||
- 阶段 6 为版本中心补充两条治理查询:`GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/audit-events` 和 `GET /api/admin/shipping-notice/order-document-profiles/{profile_id}/usages`。前者支持 `event_type / actor / request_id_filter / created_from / created_to / before_id / limit`,使用 `before_id` 游标分页并在操作者缺失时降级 `unknown_actor`;后者只返回每个 Unit 最新 `RouteDecision` 的安全投影,包含进入管理员只读 Run 审计页所需的 `run_no`。
|
||||
- 审计表 `shipping_order_document_profile_audits` 新增可空 `request_id`,并建立 `(profile_id, request_id, id)` 索引;使用投影依赖 `shipping_order_extraction_route_decisions` 上的 `selected_profile_id` 与 `(selected_profile_code, selected_profile_version, selected_profile_checksum)` 索引。历史使用查询必须同时支持 direct FK 命中和 `snapshot_identity_match`,但返回值要显式区分两者,避免把快照匹配误写成真实外键引用。
|
||||
- 阶段 7 将普通版本详情进一步收敛为“训练/标注样本可读、blind test 身份不可读”:`sample_summary.samples` 只保留 annotation/training 的冻结样本摘要,blind test 只通过 `test_summary` 和 `blind_test_count` 暴露治理结果。这样前端无需再依赖隐藏逻辑拦截网络层 blind test 文件身份。
|
||||
- 发布事务必须先对当前归一化后的草稿定义重算 `structure_fingerprint`,再校验 `assert_profile_publishable()`;通过后在同一事务内冻结样本证据、生成正式 `checksum`,并把已批准 blind test suite / run 的草稿 checksum 原子提升为正式 Profile checksum。发布后的自动冻结资格仍从 `manual_confirmation` 起步,不因草稿阶段的 blind test 批准而直接变成 `auto_freeze_approved`。
|
||||
- **订单复核领域边界(阶段 0)**:建单前复核采用 `Run 1:N ReviewCase`、`PDF Unit 1:1 ReviewCase`、`ReviewCase 0:1 Candidate`、`ReviewCase 1:1 CurrentDraft`、`Confirmed ReviewCase 1:1 ShippingTask`。Candidate/Extraction 保存机器事实且不可变;Draft 保存人工编辑值与 `draft_version`;Confirmed Revision 保存被确认的不可变人工版本。一个 PDF Unit 最多一个订单、一个订单只属于一份 PDF;禁止订单合并/拆分和明细跨 PDF 移动。
|
||||
- **确认事务与 API 边界(阶段 0)**:确认 API 必须提供 `expected_draft_version` 和幂等键,在单一事务中锁定 Case/Draft、全量校验冻结 Schema 与业务门禁、写 Confirmed Revision、消费 Candidate、创建 Task 并标记 Case confirmed。旧版本返回 HTTP 409,任何失败不得留下半成品。读 API 由 Run/Case 所属用户授权,写 API 的字段、行、证据和动作均由后端基于冻结 Schema 和 Case 推导;禁止客户端提交任意 Schema 或跨 Case Document ID。
|
||||
- **货代字段与履约冻结(阶段 1)**:系统事实由代码/数据库固定;订单字段区分 57 个可按版本启用的标准目录与自定义字段,均以稳定 `field_id` 冻结。`SHIP_AVAILABLE_ROLLING_V1` 是当前唯一代码注册策略,只要求 Line `reservation_id:string`、`part_number:string`、`qty:decimal > 0` 和已确认订购客户;不要求全部 57 个字段,不新增 Header `inventory_source_hint_default` 或 `shipping_method`。`inventory_source_hint` 只可作为可选 Line 路由线索,库存路由只读取冻结 Snapshot。
|
||||
- **货代字段能力与策略(阶段 2)**:`ShippingFulfillmentPolicy` 独立版本化,字段能力只允许代码注册并按稳定 `field_id` 绑定;scope/value_type 不匹配、缺少最低能力或未发布策略均 fail closed。冻结 Snapshot 保存策略定义与 checksum,履约消费者不读取可变 Schema 的 `business_purpose`;自定义字段只要类型和作用域符合即可被策略受控绑定。
|
||||
- **Reservation 注册**:`shipping_reservations` 通过单列唯一 `reservation_id` 强制全局唯一,并持久化标准化 PO;PO 仅 trim + uppercase,保留前导零和中间字符。首次注册可缺 PO,但 Reservation 已注册后的重复记录缺 PO、不同 PO 或同快照重复均阻断;同 PO 内容变化返回可审计前后差异并等待人工确认;有效 Artifact 或上传后禁止直接修订。Dify 不参与这些判断,继续只返回字段 Observation。
|
||||
- Worker 仅对唯一表/唯一 Profile 精确命中执行确定性模板映射。Profile 可以合法覆盖裸表头的通用语义,如 `Part Number -> customer_part_number`、`Vendor Item# -> part_number`;显式零 Qty 删除。多 Profile 命中、多表命中、冻结 field_id 漂移、MinerU 行关系丢失或缺少 `part_number + qty` 时不自动合并,转 Dify/复核。Dify Manifest 会剥离布局 HTML、bbox 和内部 field_code,只携带稳定 field_id 的紧凑候选,避免 Token 膨胀。
|
||||
- Profile 管理端从 ready MinerU 布局生成最小网格预览;HTML、bbox、全文和结构指纹不下发浏览器。`from-sample` 创建/更新接口重新读取持久化 HTML 并计算指纹,更新草稿要求 `expected_lock_version`。页面仅允许注册解析器与 Schema line field 下拉,重复目标字段由前端提示、Pydantic 契约再次阻断;发布/复制/退役形成完整不可变版本生命周期。
|
||||
- Profile 管理端从 ready MinerU 布局生成最小网格预览;HTML、bbox、全文和结构指纹不下发浏览器。创建只能通过三步向导原子完成,草稿仅通过标准 `PUT /order-document-profiles/:id` 在租约和 `expected_lock_version` 保护下保存;历史 `from-sample` 创建/更新兼容路径已删除。页面仅允许注册解析器与 Schema line field 下拉,重复目标字段由前端提示、Pydantic 契约再次阻断;发布/复制/退役形成完整不可变版本生命周期。
|
||||
- Dify 是无状态模型执行层;HXOPS 是计划、并发/重试、Schema、跨文档合并、冲突、审计、成本、业务状态和持久化真相源。Reservation/Allocation 等安全语义由后端硬规则兜底,管理员配置不可覆盖。
|
||||
- 默认一附件一个抽取单元,单元可返回多个订单;邮件正文作为独立事实/关系单元。确定性表格和邮件头可以绕过 LLM,模型只接收无法确定解析的最小必要内容。
|
||||
- 迁移前默认一附件一个抽取单元,单元可返回多个订单;该结果形态只用于兼容清理,不能作为新建单前复核或新接口的契约。订单人工复核目标态固定为一 PDF Unit 最多一订单;邮件正文仍仅作为独立事实/关系单元。确定性表格和邮件头可以绕过 LLM,模型只接收无法确定解析的最小必要内容。
|
||||
- published Schema 在 Run 创建时冻结,并逐阶段收敛为表头别名、normalizer、validator、证据优先级和冲突策略的唯一业务配置真相;发布时必须拒绝标准化别名碰撞。
|
||||
- 阶段 1 已完成动态 Schema 表格契约收敛:确定性解析只消费 Run 锁定版本的 `field_code/display_name/aliases`,无契约不猜列;禁用/不支持字段不参与映射,重复列进入复核,Reservation 安全禁用表头由后端硬规则保护。默认 UOM、任意单元格 Reservation 推断、文档级 Reservation 广播及未启用字段派生均已从正式路径移除。
|
||||
- 阶段 2 已建立持久化抽取计划:Run 唯一 Plan,冻结 Document 唯一 Unit;正文关系单元与附件抽取单元隔离,复合外键保证 Document/Intake 一致。局部状态机和计划汇总支持 Worker 重启恢复、成功结果保留与失败单元后续重试;Provider 切分留在阶段 3/4。
|
||||
@@ -1264,6 +1276,9 @@ Dify
|
||||
- L7 清理后 Worker 的零 Provider 分支只认 accepted layout;Profile/纯文本必须进入唯一 Manifest 上下文。
|
||||
- L7 质量门禁独立保存匿名质量批次/双人标签,不保存订单字段值;Run 创建和 Worker 执行均复核当前 Schema、阈值、指标仍达标和双角色批准,避免配置后漂移或绕过。
|
||||
- **Profile 盲测资格门禁**:`shipping_document_profile_test_suites/samples/runs` 保存草稿/发布 Profile 的独立盲测集、管理员确认真值及不可变执行摘要,不复制订单正文。盲测集以 `profile_id + profile_checksum` 唯一绑定;模板保存改变草稿定义 hash 后,旧草稿集转为 `superseded`,新定义必须新建盲测集。发布事务校验至少 1 份训练样本、与 annotation/training 完全独立的 1 份盲测样本、至少 1 份多明细真值及跨页声明对应的 `continuation_of` 样本;全量通过并批准后,事务内将套件/执行记录的草稿 hash 原子提升为正式 Profile checksum。Run 创建只冻结正式 checksum 的 `auto_create_approved` 事实。`shipping_document_profile_auto_freeze_qualifications` 进一步独立保存客户白名单、业务场景白名单和 `requires_customer_confirmation` 开关;Run 结果落库后按已确认 Bill-to 客户与当前业务场景刷新 `auto_freeze_policy_json`。在自动冻结执行入口接入前,该策略仍 fail-closed。确定性订单直接由该 Profile 的当前解析行生成,绝不借用其他 accepted layout 候选。Dify 输出在进入持久化前还会校验冻结 field_id 白名单、Unit document_id 和 quote 的逐字可验证性。
|
||||
- **模板验证与两步发布**:`shipping_order_document_profile_validation_runs` 冻结 Revision、定义/Schema checksum 与 annotation/training 样本的 Layout/Parser 身份;查询时 checksum 不一致的历史运行派生为 `stale`,不改写原记录。`shipping_order_document_profile_publish_check_reports` 冻结 Revision、checksum、`lock_version`、通过的验证运行、基线发布版本与服务端语义差异;消费报告时在同一事务复核报告、逐项警告确认并调用发布/退役,报告被消费后重试只返回同一版本。模板编辑/验证/发布不调用 Dify;Dify 无需新增节点、Tool、变量或连线。
|
||||
- **坐标 Profile 治理审计**:`shipping_order_document_profiles` 增加 `template_mode`、`training_sample_count` 与无正文 `match_strategy_summary_json`;`shipping_order_document_profile_samples` 仅绑定 Document/Table/角色,`shipping_order_document_profile_audits` 只记录对象身份、事件和计数/checksum 摘要。样本、区域、字段绑定、盲测和版本事件使用同一追加式审计表,禁止保存锚点文本、坐标、PDF、HTML、MinIO URL 或凭据。
|
||||
- **受控坐标预览**:页面授权写入 Redis,key 为随机令牌且 TTL 120 秒;每个 token 固定管理员、Profile、Document、page_no,并通过 `GETDEL` 原子消费。Redis 不可用时预览 fail-closed。PDF 只在后端渲染低清单页 PNG;文本候选和局部预览按 Profile 样本关联再次鉴权,响应设置 `Cache-Control: private, no-store`。OCR 只能经绑定样本的显式管理员请求生成,EML 复用 HTML 白名单清洗结果且不渲染可执行 DOM。
|
||||
- **模板版本中心数据边界**:版本列表接口只返回族摘要和版本摘要,不返回 PDF、正文、大体积 Layout payload 或盲测真值。版本详情接口返回 Profile 元数据、Schema 摘要、定义摘要、配置规模、冻结证据摘要、样本摘要、测试摘要、自动冻结资格摘要、来源版本和 checksum;样本画布预览接口必须以冻结样本绑定身份鉴权,短时、单用途、管理员绑定且 `no-store`,不得接受任意 `document_id` 直接取页。
|
||||
- **模板版本中心审计与使用数据边界**:`audit-events` 只返回事件类型、操作者摘要、`request_id`、过滤条件命中的安全 `detail_json` 和 ISO 8601 时间,不返回 PDF、正文、对象存储地址、盲测真值或可复原答案的坐标。`usages` 只返回脱敏文档名、Run 编号、匹配/执行状态、原因码、模板身份命中方式和只读诊断入口;不得回传文档正文、文件地址或运行时原始模型输出。
|
||||
- **订单客户指纹与冻结门禁**:`ShippingOrderCustomerMatch` 保留 Bill-to/Ship-to 原文、标准化组件、`order-customer-fingerprint.v1` 指纹、候选快照和确认理由。只有 `bill_to.status=confirmed` 且存在客户/简码/指纹/规则版本时 `order_freeze_service` 才冻结 Snapshot;冻结服务不接受外部 `customer_id` 或 `customer_short_code`。Snapshot 的 `rule_versions_json.ordering_customer` 保存匹配 ID、指纹、规则版本、确认方法和人员时间,避免主数据变化改写历史履约事实。
|
||||
@@ -68,12 +68,23 @@
|
||||
| **发货通知** | **坐标修复模板闭环** | 结构污染 PDF 由管理员确认列边界后重建,确认结果随 Profile 与 Run 冻结。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 表头混入首条明细、无文本层 PDF、非法边界、未确认候选、盲测与 Run 证据缺失 | 浏览器只看到候选网格;边界必须从 0 到 1 严格递增;重建固定待审核且须显式确认;Profile/Run/盲测只用冻结坐标证据,任何缺失均阻断,不回退原始错误网格或 Dify。 |
|
||||
| **发货通知** | **订单模板页样本上传** | 管理员可从订单文档模板页直接上传 PDF/EML,建立隔离样本 Intake 并复用异步预解析和布局 Job。 | `test_shipping_order_document_profile_service.py`、前端生产构建、Alembic upgrade | PDF、EML 正文 HTML、多附件 EML、非 PDF/EML、样本解析中/失败、业务 Intake 混入 | 样本 Intake purpose 固定为 `order_document_profile_sample`,不绑定会话,不创建 Candidate/Task/指纹或 Dify 调用;仅解析完成的单 Document 表格可配置 Profile;文件类型前后端均拒绝;样本状态不泄露正文、HTML 或 bbox。 |
|
||||
| **发货通知** | **订单模板样本治理与版本识别** | 样本可按文件名搜索并展示时间/状态;当前发布版本可辨识;专用样本受控删除。 | `test_shipping_order_document_profile_service.py`、前端生产构建 | 同名样本、历史业务附件、解析中样本、盲测引用、资产共享、多个版本 | 选择器标明文件名/时间/状态/表格数;同编码 published 版本标记当前生效;仅 `order_document_profile_sample` 的已解析、未盲测引用且未共享资产样本可删除;删除同步回收源文件和布局,历史业务附件及盲测证据不可删除。 |
|
||||
| **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py` | 缺训练样本、复用 annotation/training 文档、少于 3 样本、无表头少于 5 样本、无多明细、缺跨页续页、真值不匹配、批准后编辑、checksum 漂移、未知/多模板 | 发布前至少 1 训练样本;盲测与建模样本完全独立,常规模板至少 3 个、无表头至少 5 个,含至少 1 个多明细及所需跨页续页样本;全通过且管理员批准后,草稿 hash 原子提升为正式 checksum 凭证;批准样本不可改;唯一已批准 Profile 直接生成确定性订单,其他情形进入人工复核。 |
|
||||
| **发货通知** | **订单文档 Profile 独立盲测资格** | 发布 Profile 与确定性自动建单资格分离;盲测真值、执行摘要和批准状态绑定 checksum。 | `test_shipping_document_profile_quality.py`、`test_shipping_document_profile_quality_migration.py` | 缺训练样本、复用 annotation/training 文档、缺独立 blind test、无多明细、缺跨页续页、真值不匹配、批准后编辑、checksum 漂移、未知/多模板 | 发布前至少 1 训练样本;blind test 与建模样本完全独立,最低 1 份独立样本且必须覆盖至少 1 份多明细真值,声明跨页时还必须覆盖续页样本;全通过且管理员批准后,草稿 hash 原子提升为正式 checksum 凭证;批准样本不可改;唯一已批准 Profile 直接生成确定性订单,其他情形进入人工复核。 |
|
||||
| **发货通知** | **订单模板版本中心与默认选版** | 模板版本中心按 `profile_code` 聚合;查看任意历史版本不创建草稿,默认选版顺序固定。 | `test_shipping_order_document_profile_service.py`、`frontend` 管理端构建、路由单测 | 多模板编码混合、同族多个 published/draft、只有 retired、URL 指向不存在版本、刷新恢复、返回工作台 | 版本列表只展示同族版本;默认顺序为 `published -> draft -> 最新 retired`;URL 指定不存在版本返回统一 404;查看版本不创建草稿;刷新后仍恢复到 URL 指定版本;返回工作台时保留模板族选择。 |
|
||||
| **发货通知** | **订单模板录入 UX 重构(阶段 0)** | 冻结模板库、向导、草稿编辑、验证、发布检查的 URL 和治理 DTO,不提前切换旧工作台。 | 路由单测、TypeScript 类型检查、四语言 JSON 解析 | 路由参数缺失、`profile_code`/Version/Revision 混用、直接发布契约、缺少稳定错误码、Dify 配置被代码修改 | 六个页面 URL 唯一且受管理员守卫;类型包含 Revision/Lease/Validation/Publish Check 与 `operation_id`/`browser_session_id`;本阶段不创建治理表或 Dify 配置。 |
|
||||
| **发货通知** | **订单模板草稿治理与单写者(阶段 1–4)** | 每次有效保存生成不可变 Revision;编辑租约、建议决定和自动保存不得覆盖他人或旧版本的内容。 | `test_order_document_profile_draft_governance.py`、`test_order_document_profile_suggestion_service.py`、前端生产构建 | 多标签并发、租约接管/过期、同 operation 重试、自动保存乱序、建议接受/调整/拒绝 | Revision 仅追加且同 operation 幂等;租约冲突明确返回;失租转只读并可恢复本地草稿;建议不直接覆盖人工画布。 |
|
||||
| **发货通知** | **订单模板不可变验证运行(阶段 5)** | 当前样本试运行和即时检查冻结草稿、Schema 与样本身份;旧运行不因草稿变更而改写。 | `test_order_document_profile_validation_service.py` | checksum 改变、盲测样本误用、样本证据失败、失败运行查询 | 查询将历史 checksum 不一致运行标记为 `stale`;annotation/training 与 blind test 严格隔离;失败摘要仍可审计且不返回 PDF、地址或真值。 |
|
||||
| **发货通知** | **订单模板两步发布(阶段 6)** | 发布检查报告冻结 Revision/checksum/lock_version/验证运行,逐项确认警告后单事务发布。 | `test_order_document_profile_publish_check_service.py`、前端生产构建 | 草稿变化、无当前通过验证、阻断项、漏确认警告、重复确认 | 报告失效不可消费;阻断项绝不可绕过;警告逐项确认;重复消费只返回同一 published 版本且释放编辑租约。 |
|
||||
| **发货通知** | **订单模板治理收口(阶段 7)** | 删除旧兼容创建/更新和直接发布路径,页面按库、向导、编辑、验证、发布检查、版本详情分责。 | 订单模板定向 pytest、Alembic 迁移测试、前端生产构建、四语言 JSON 解析、静态路径检索 | 旧 `/from-sample`、直接 `/publish`、遗留 Workbench、组件混编生命周期动作、迁移链断裂、Dify 配置被代码修改 | 旧兼容路径和直接发布入口均不存在;只有发布检查报告可消费发布;各页面职责独立;迁移链可升级;关键动作以 `operation_id` 审计;Dify 不新增 Tool、节点、变量、Prompt 或连线。 |
|
||||
| **发货通知** | **历史版本详情只读与盲测隔离** | `published/retired` 详情只读查看历史配置和冻结证据;普通详情不泄露 blind test 身份或真值。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_version_service.py`、后续版本详情前端单测、前端生产构建 | 历史画布回读最新 Layout、Token 越权、只读页面残留编辑动作、blind test 样本进入普通选择器、网络响应含 `expected_*` 真值/坐标/盲测文件名 | 历史样本画布只读且只能读取冻结 Sample/Layout/Schema/Parser 证据;缺失证据时明确报错且不降级;普通详情只返回盲测摘要与 blind test 数量,不返回 blind test 文件身份、真值、坐标、对象存储地址、PDF 正文或预览 Token;标注/训练样本仍可正常查看。 |
|
||||
| **发货通知** | **订单模板版本语义差异** | 服务端按稳定 `region_id/layout_id/field_id/anchor_id` 计算同模板版本差异,默认对比上一版本。 | `test_order_document_profile_diff.py`、`test_order_document_profile_version_service.py`、前端生产构建 | 字段改名、排除区重排、坐标浮点噪声、显式跨模板比较、首版无上一版本 | 同 stable id 的改名归类为 modified;排除区重排不误报新增/删除;`0.001` 内坐标噪声不产生 region 变化;跨模板比较被阻断;未指定对比版本时默认上一版本。 |
|
||||
| **发货通知** | **订单模板版本治理审计时间线** | 审计页签按 request_id、事件类型、操作者和日期范围回放治理事件,并对只读访问自身留痕。 | `test_order_document_profile_governance_service.py`、前端生产构建 | `request_id_filter`、`event_type`、游标翻页、已删除操作者、访问审计页本身 | `before_id` 翻页稳定且无重复漏项;缺失操作者显示 `unknown_actor`;返回时间为 ISO 8601;`version_audit_viewed` 追加审计只保存过滤条件和结果计数;响应不含 PDF、正文、对象存储地址或盲测真值。 |
|
||||
| **发货通知** | **订单模板版本实际使用投影** | 使用页签只统计每个 Unit 最新 RouteDecision,并支持 direct FK 与冻结快照两种模板命中方式。 | `test_order_document_profile_governance_service.py`、前端生产构建 | 同一 Unit 多次决策、`selected_profile_id` 为空但 code/version/checksum 一致、retired 版本、点击运行审计入口 | 仅最新 RouteDecision 计数;`direct_profile_id` 与 `snapshot_identity_match` 明确区分;文档名脱敏;可跳转管理员只读 Run 审计页;查询依赖 profile 相关索引,避免全表扫描。 |
|
||||
| **发货通知** | **本地结果持久化与重试** | 单元解析完成后先独立保存结构化结果;HXOPS 落库失败重试不得重复解析已完成单元。 | `test_shipping_order_extraction_runs.py` | 首次单元成功、后续 DB 暂时失败 | 单元解析 1 次、持久化尝试 2 次,Run 最终 completed。 |
|
||||
| **发货通知** | **本地结果持久化与重试** | 单元解析完成后先独立保存结构化结果;HXOPS 落库失败重试不得重复解析已完成单元。 | `test_shipping_order_extraction_runs.py` | 首次单元成功、后续 DB 暂时失败 | 单元解析 1 次、持久化尝试 2 次,Run 最终 completed。 |
|
||||
| **发货通知** | **本地解析版本冻结** | 解析器和策略版本漂移阻断旧 Run;无外部 App、URL 或密钥依赖。 | `test_order_extraction_deterministic_migration.py`、`test_shipping_order_extraction_runs.py` | 排队后修改解析器版本或策略 | Run/Job 使用冻结事实或安全失败;不调用远程服务。 |
|
||||
| **发货通知** | **Run 安全视图与事务原子性** | 用户 API 不返回正文、解析快照或内部配置;Run、计划和 Job 的创建保持原子性。 | `test_shipping_order_extraction_runs.py` | 查询 Run;创建计划或 Job 失败 | 响应无敏感快照;失败后不留下半成品 Run/计划/Job。 |
|
||||
| **发货通知** | **订单抽取断流与并发门禁** | 同一 Intake 只允许一个未释放 Run;已完成单元结果可在 HXOPS 重试中复用。 | `test_shipping_order_extraction_runs.py`、`useShippingOrderExtractionRuns.spec.ts` | 重复创建、单元成功后落库失败、浏览器轮询中断 | 返回同一 Run;重试复用单元结果;浏览器中断不取消后台 Run。 |
|
||||
| **发货通知** | **一附件多订单与部分成功** | 一个 Document 可形成多个 Candidate;高置信订单自动建 Task,低置信订单保留。 | `test_shipping_notice_order_extraction.py::test_persist_order_extraction_result_supports_multiple_orders_partial_success_and_replay` | 同一附件 2 个订单,其中 1 个低置信 | 2 Candidate、1 Task、1 pending;Intake=`partially_completed`;重放不重复建单。 |
|
||||
| **发货通知** | **一附件多订单与部分成功(迁移前回归)** | 一个 Document 可形成多个 Candidate 的旧行为只保留到阶段 7 清理完成,用于迁移回归;新建单前复核不得依赖它。 | `test_shipping_notice_order_extraction.py::test_persist_order_extraction_result_supports_multiple_orders_partial_success_and_replay` | 同一附件 2 个订单,其中 1 个低置信 | 迁移前行为在清理前可回归;新 Review Case 测试必须拒绝同 PDF 创建第二订单或第二 Case。 |
|
||||
| **发货通知** | **订单抽取快照与权限** | Run 冻结用户、会话、Schema、邮件上下文、Document 及解析版本;排队期间来源变化必须拒绝。 | `test_shipping_order_extraction_runs.py`、`test_shipping_order_schema_runtime.py` | 越权读取、解析版本漂移、正文或确定性上下文变化 | 用户态不泄密;执行版本漂移和来源变化返回稳定错误码;不创建 Candidate。 |
|
||||
| **发货通知** | **自动建单与流程字段门禁** | 分类、`part_number`/Qty 置信度与原文证据达标即建 Task;缺 Reservation 仍建单但禁止库存链;`inventory_source_hint` 仅作可选路由线索。 | `test_shipping_notice_order_extraction.py` / `test_shipping_notice_tools.py` | 高置信 `part_number`+Qty,Reservation 为空、库存源线索可选 | Task=`pending_review/rsv_req`;`auto_progress` 返回 needs_human 且禁止库存/匹配/Excel;库存源线索缺失不单独阻断。 |
|
||||
| **发货通知** | **字段分层、冻结与 Reservation 全局唯一(阶段 1)** | 57 个预置字段为版本化标准目录;固定滚动策略只校验当前最小履约字段与已确认客户,Reservation 按单列全局唯一绑定客户 PO。 | `test_shipping_order_snapshot.py`、`test_shipping_rolling_fulfillment.py`、`test_shipping_reservation_global_unique_migration.py`、`test_shipping_inventory_routing_engine.py` | 仅最小字段、缺任一字段、正/零/负 Decimal、未确认客户、同快照重复、跨 PO、同 PO 变更、有效 Artifact/上传、PO 大小写/空格、缺 PO | 不要求全部 57 字段;`customer_po_number` 用于 PO 判定;Snapshot 冻结策略和 field_id;路由只读 Snapshot;同 PO 变更返回前后差异并要求人工确认;不同 PO、重复 Reservation 和锁定修订阻断。 |
|
||||
@@ -125,6 +136,7 @@
|
||||
| **发货通知** | **订单 Schema 迁移往返** | 阶段一新增表和 Task 当前解析引用可独立 upgrade/downgrade。 | `test_shipping_order_schema_migration.py` | SQLite 最小上一版本基线 | 核心表和列完整新增并完整移除。 |
|
||||
| **发货通知** | **动态 Schema 订单解析** | published 契约驱动 EML/PDF 同字段 Observation 与后端裁决。 | `test_shipping_order_schema_runtime.py`、`test_shipping_notice_order_extraction.py` | 跨 Document 一致、冲突、缺证据、Schema checksum 漂移 | 一致值 corroborated;冲突/缺证据阻断;accepted 值生成类型化投影。 |
|
||||
| **发货通知** | **订单抽取 Run/Unit 事实进度与工作台投影** | 订单解析进度只来自后端持久化的 Run / PDF Unit / Progress Event 事实;工作台按 `summary/current_activity/documents/available_actions` 渲染,不再猜测 Workflow 阶段。 | `test_shipping_order_extraction_runs.py`、`test_shipping_order_extraction_progress.py`、`test_order_extraction_progress_facts_migration.py`、`useShippingOrderExtractionRuns.spec.ts`、`useChat.spec.ts`、`ShippingOrderExtractionCard.spec.ts` | 单 PDF 成功、多 PDF 部分成功、全部业务拒识、技术失败、跨用户读取、页面刷新恢复、历史消息恢复、网络失败、详情抽屉、键盘关闭、服务端动作按钮 | Run 计数与文档结果一致;`completed + processing + review_required + failed + pending = total`;当前活动与事件码来自数据库事实;聊天卡片和详情抽屉不出现 Workflow/LLM/Provider 文案;页面刷新、重新登录和 Worker 重启后可恢复同一事实视图。 |
|
||||
| **发货通知** | **订单人工复核目标态(阶段 0)** | 建单前复核固定为 PDF Unit → Review Case → 版本化 Draft → Confirmed Revision → Task;机器 Candidate 不可变。 | 文档契约 Review;阶段 1-7 服务、迁移、前端与 E2E 测试 | 同 PDF Worker 重入、无 Candidate、跨用户读取、过期 Draft、Case 终态、跨 PDF 文档引用、重复确认 | 每个 PDF 恰有一个 Case 且最多一张订单;草稿与机器事实分离;旧版本返回 409;终态不可编辑;确认只消费指定草稿版本;用户 API 不泄露正文、对象存储地址、Prompt 或凭据。 |
|
||||
| **发货通知** | **上传与订单版面准备状态一致性** | 文本预解析完成后继续汇总并轮询独立布局任务,活动布局不得过早创建订单识别 Run。 | `test_shipping_notice_intakes.py::test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallback`、`useShippingNoticeIntakes.spec.ts`、`attachmentCard.utils.spec.ts` | 无布局任务、queued/running、ready、failed/unsupported、刷新恢复、直接点击发送、四语言错误码 | `not_required` 与终态允许发送;`processing` 持续轮询并显示版面处理中;后端仍返回稳定门禁;失败布局可走文本/Dify 兜底且不永久卡住。 |
|
||||
| **发货通知** | **订单模板路由决策审计** | 每个 Unit 在后端确定性解析或人工复核前持久化脱敏路由事实;重试只追加不覆盖。 | `test_shipping_order_profile_matcher.py`、`test_shipping_order_extraction_stage0.py`、迁移 upgrade/downgrade 测试 | 缺失锚点、分差歧义、证据不足、未批准模板、多表、无有效行、Job 重试、Run 删除、管理员详情与普通用户访问 | 缺失项仅输出 `anchor_id`;稳定原因码完整;`unit_id + job_id + attempt_no` 唯一;审计先于结果写入;业务拒识为 `skipped/needs_review`;DTO/页面无正文、字段值、quote、坐标、Prompt 或凭据。 |
|
||||
| **发货通知** | **阶段 0 统一状态与追加式审计** | 路由结果统一为 `deterministic/review_required/skipped`;业务拒识不计技术失败;Run 状态变化与路由结果追加至统一审计账本。 | `test_shipping_audit_event.py`、`test_shipping_audit_event_migration.py`、路由/Run 状态测试 | 未命中模板、模板歧义、技术异常、状态变化、敏感元数据、ORM 更新/删除、迁移升级回退 | 业务拒识进入 `review_required` 或 `partially_completed`,不会伪装为技术失败;技术故障才进入 `failed`;审计含 actor/request/correlation/状态哈希,且拒绝正文、凭据、更新和删除。 |
|
||||
|
||||
Generated
+271
@@ -17,6 +17,7 @@
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-vue-next": "^0.575.0",
|
||||
"marked": "^17.0.3",
|
||||
"pdfjs-dist": "^5.6.205",
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.25",
|
||||
"vue-i18n": "^11.2.8",
|
||||
@@ -449,6 +450,256 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.100.tgz",
|
||||
"integrity": "sha512-xglYA6q3XO5P3BNJYxVZ1IV7DLVjp1Py6nwag88YntrS+3vKHyYcMqXVS4ZztJmwz2uGvz1FWhI/4LgbR5uQDA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"workspaces": [
|
||||
"e2e/*"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@napi-rs/canvas-android-arm64": "0.1.100",
|
||||
"@napi-rs/canvas-darwin-arm64": "0.1.100",
|
||||
"@napi-rs/canvas-darwin-x64": "0.1.100",
|
||||
"@napi-rs/canvas-linux-arm-gnueabihf": "0.1.100",
|
||||
"@napi-rs/canvas-linux-arm64-gnu": "0.1.100",
|
||||
"@napi-rs/canvas-linux-arm64-musl": "0.1.100",
|
||||
"@napi-rs/canvas-linux-riscv64-gnu": "0.1.100",
|
||||
"@napi-rs/canvas-linux-x64-gnu": "0.1.100",
|
||||
"@napi-rs/canvas-linux-x64-musl": "0.1.100",
|
||||
"@napi-rs/canvas-win32-arm64-msvc": "0.1.100",
|
||||
"@napi-rs/canvas-win32-x64-msvc": "0.1.100"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-android-arm64": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.100.tgz",
|
||||
"integrity": "sha512-hjhCKhntPv9+t4ckHymdx0phYNcVW+GKQR6Lzw2zE+pOVjOplSmtx9nNNknTjbEDLcuLZqA1y8ufKg1XfgftzQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-darwin-arm64": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.100.tgz",
|
||||
"integrity": "sha512-2PcswRaC7Ly645DGt88///zuFDhJxJYdKAs1uU3mfk1atYkXufgcgLfBpk6Tm12nCQBaNt1wpybuPZ4qOhTo8A==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-darwin-x64": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.100.tgz",
|
||||
"integrity": "sha512-ePNZtj7pNIva/siZMg+HmbeozkIjqUIYdoymH8HaA3qK7LfzFN4WMBM8G6HQ9ZC+H3+Dnn5pqtiXpgLykaPOhw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-arm-gnueabihf": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.100.tgz",
|
||||
"integrity": "sha512-d5cDB48oWFGU8/XPhUOFAlySgb/VAu7D+s8fi55K1Pcfg8aPplHWqMgibhVLU8ky7Pyg/fuiVLz4Nf3JrSTuUA==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-arm64-gnu": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.100.tgz",
|
||||
"integrity": "sha512-rDxgxRu69RvDlX/bh9o22DxLsGr8EqsNgotL9+RwQE1S0b0cqeatqsw6aW45mukm0B42DIAaAacKaYQ8cqS1nw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-arm64-musl": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.100.tgz",
|
||||
"integrity": "sha512-K3mDW66N+xT2/V439u1alFANiBUjdEx2gLiNYnCmUsva5jZMxWTjafBYwTzYK+EMFMHrUoabuU+T1BIP5CgbYQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-riscv64-gnu": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.100.tgz",
|
||||
"integrity": "sha512-mooqUBTIsccZpnoQC4NgrC1v6C1vof39etLNMnBwCY+p0gajWJvAHLGQ6g/gGyS5YrpDW+GefSN4+Cvcr08UWw==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-x64-gnu": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.100.tgz",
|
||||
"integrity": "sha512-1eCvkDCazm7FFhsT7DfGOdSaHgZVK3bt/dSBl5EWHOWmnz+I7j8tPseJqqD81NF+MH21jKUK4wQSDjN0mdhnTg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-linux-x64-musl": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.100.tgz",
|
||||
"integrity": "sha512-20arT6lnI19S68qNlii73TSEDbECNgzMz2EpldC1V3mZFuRkeujXkcebRk0LRJe9SEUAooYiLokfMViY8IX7yA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-win32-arm64-msvc": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-0.1.100.tgz",
|
||||
"integrity": "sha512-DZFFT1wIAg37LJw37yhMRFfjATd3vTQzjZ1Yki8u2vhO6Hi5VE6BVaGQ1aaDu7xb4iMErz+9EOwjpS7xcxFeBw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/canvas-win32-x64-msvc": {
|
||||
"version": "0.1.100",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.100.tgz",
|
||||
"integrity": "sha512-MyT1j3mHC2+Lu4pBi9mKyMJhtP6U7k7EldY7sj/uS5gJA65gTXt8MefJQXLJo5d/vZbuWmfxzkEUNc/urV3pHA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/wasm-runtime": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://mirrors.tencent.com/npm/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.1.tgz",
|
||||
@@ -2702,6 +2953,13 @@
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/node-readable-to-web-readable-stream": {
|
||||
"version": "0.4.2",
|
||||
"resolved": "https://registry.npmjs.org/node-readable-to-web-readable-stream/-/node-readable-to-web-readable-stream-0.4.2.tgz",
|
||||
"integrity": "sha512-/cMZNI34v//jUTrI+UIo4ieHAB5EZRY/+7OmXZgBxaWBMcW2tGdceIw06RFxWxrKZ5Jp3sI2i5TsRo+CBhtVLQ==",
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/node-releases": {
|
||||
"version": "2.0.27",
|
||||
"resolved": "https://mirrors.tencent.com/npm/node-releases/-/node-releases-2.0.27.tgz",
|
||||
@@ -2853,6 +3111,19 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pdfjs-dist": {
|
||||
"version": "5.6.205",
|
||||
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-5.6.205.tgz",
|
||||
"integrity": "sha512-tlUj+2IDa7G1SbvBNN74UHRLJybZDWYom+k6p5KIZl7huBvsA4APi6mKL+zCxd3tLjN5hOOEE9Tv7VdzO88pfg==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=20.19.0 || >=22.13.0 || >=24"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@napi-rs/canvas": "^0.1.96",
|
||||
"node-readable-to-web-readable-stream": "^0.4.2"
|
||||
}
|
||||
},
|
||||
"node_modules/perfect-debounce": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/perfect-debounce/-/perfect-debounce-1.0.0.tgz",
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"highlight.js": "^11.11.1",
|
||||
"lucide-vue-next": "^0.575.0",
|
||||
"marked": "^17.0.3",
|
||||
"pdfjs-dist": "^5.6.205",
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.25",
|
||||
"vue-i18n": "^11.2.8",
|
||||
|
||||
@@ -55,6 +55,16 @@ const ShippingOrderExtractionRunsPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-extraction-runs/ShippingOrderExtractionRunsPage.vue");
|
||||
const ShippingOrderDocumentProfilesPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue");
|
||||
const OrderProfileVersionDetailPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue");
|
||||
const OrderProfileCreateWizardPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue");
|
||||
const OrderProfileEditorRoutePage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/OrderProfileEditorRoutePage.vue");
|
||||
const OrderProfileValidationPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue");
|
||||
const OrderProfilePublishCheckPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue");
|
||||
|
||||
export const adminRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
@@ -177,6 +187,42 @@ export const adminRoutes: RouteRecordRaw[] = [
|
||||
component: ShippingOrderDocumentProfilesPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "订单文档模板" },
|
||||
},
|
||||
// 阶段 0 先固定 URL 身份;对应专属页面将在各自实施阶段替换,当前不切换旧工作台流量。
|
||||
{
|
||||
path: "shipping-order-document-profiles/new",
|
||||
name: "AdminShippingOrderDocumentProfileCreate",
|
||||
component: OrderProfileCreateWizardPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "创建订单文档模板" },
|
||||
},
|
||||
{
|
||||
path: "shipping-order-document-profiles/:profileCode/drafts/:profileId/edit",
|
||||
name: "AdminShippingOrderDocumentProfileEdit",
|
||||
component: OrderProfileEditorRoutePage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "编辑订单文档模板" },
|
||||
},
|
||||
{
|
||||
path: "shipping-order-document-profiles/:profileCode/drafts/:profileId/validate",
|
||||
name: "AdminShippingOrderDocumentProfileValidate",
|
||||
component: OrderProfileValidationPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "验证订单文档模板" },
|
||||
},
|
||||
{
|
||||
path: "shipping-order-document-profiles/:profileCode/drafts/:profileId/publish-check",
|
||||
name: "AdminShippingOrderDocumentProfilePublishCheck",
|
||||
component: OrderProfilePublishCheckPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_document_profiles', title: "订单文档模板发布检查" },
|
||||
},
|
||||
{
|
||||
path: "shipping-order-document-profiles/:profileCode/versions/:version",
|
||||
name: "AdminShippingOrderDocumentProfileVersionDetail",
|
||||
component: OrderProfileVersionDetailPage,
|
||||
meta: {
|
||||
requiresAdmin: true,
|
||||
adminModule: "shipping_inventory",
|
||||
adminSubModule: 'order_document_profiles',
|
||||
title: "模板版本详情",
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
path: "announcements",
|
||||
|
||||
@@ -10,4 +10,17 @@ export const chatRoutes: RouteRecordRaw[] = [
|
||||
name: 'Chat',
|
||||
component: () => import('@/features/chat/views/ChatView.vue'),
|
||||
},
|
||||
{
|
||||
path: '/chat/:agentId/shipping-order-review/:runNo',
|
||||
name: 'ShippingOrderReviewLegacy',
|
||||
redirect: (to) => ({
|
||||
name: 'Chat',
|
||||
params: { agentId: to.params.agentId },
|
||||
query: {
|
||||
...to.query,
|
||||
mode: 'order-review',
|
||||
run_no: String(to.params.runNo || ''),
|
||||
},
|
||||
}),
|
||||
},
|
||||
];
|
||||
@@ -8,8 +8,6 @@
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type {
|
||||
CreateOrderProfileFromSampleInput,
|
||||
LegacyCreateOrderProfileFromSampleInput,
|
||||
OrderProfileSampleDocument,
|
||||
CoordinateReconstructionPreview,
|
||||
CoordinateReconstructionSuggestion,
|
||||
@@ -24,6 +22,13 @@ import type {
|
||||
OrderProfileBlindTestInput,
|
||||
OrderProfileBlindTestAvailableSample,
|
||||
OrderProfileBlindTestCandidate,
|
||||
OrderProfileAuditEventPage,
|
||||
OrderProfileUsagePage,
|
||||
OrderProfileVersionDiff,
|
||||
OrderProfileVersionFamilySummary,
|
||||
OrderProfileVersionSummary,
|
||||
OrderProfileDraftRevision,
|
||||
OrderProfileEditLease,
|
||||
OrderProfileTestSuite,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '../types/shipping-order-document-profile.types';
|
||||
@@ -35,6 +40,131 @@ const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getA
|
||||
export const listOrderDocumentProfiles = () =>
|
||||
requestJson<ShippingOrderDocumentProfile[]>('/api/admin/shipping-notice/order-document-profiles', auth());
|
||||
|
||||
/** 列出模板族摘要,供版本中心和默认选版使用。 */
|
||||
export const listOrderDocumentProfileFamilies = () =>
|
||||
requestJson<OrderProfileVersionFamilySummary[]>('/api/admin/shipping-notice/order-document-profile-families', auth());
|
||||
|
||||
/** 列出单个模板族的全部版本摘要。 */
|
||||
export const listOrderDocumentProfileFamilyVersions = (profileCode: string) =>
|
||||
requestJson<OrderProfileVersionSummary[]>(
|
||||
`/api/admin/shipping-notice/order-document-profile-families/${encodeURIComponent(profileCode)}/versions`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 通过模板编码与版本号读取安全详情;版本不存在时由服务端返回明确 404。 */
|
||||
export const getOrderDocumentProfileByFamilyVersion = (profileCode: string, version: number) =>
|
||||
requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profile-families/${encodeURIComponent(profileCode)}/versions/${version}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取单个模板版本的结构化详情,不包含 PDF、正文或盲测真值。 */
|
||||
export const getOrderDocumentProfileDetail = (profileId: number) =>
|
||||
requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 以乐观锁、Revision 和当前标签租约保存草稿的完整 v2 定义。 */
|
||||
export const saveOrderDocumentProfileDraft = (profileId: number, payload: {
|
||||
profile_code: string; display_name: string; schema_version_id: number;
|
||||
definition: ShippingOrderDocumentProfile['definition']; change_note?: string;
|
||||
expected_lock_version: number; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
}) => requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}`,
|
||||
{ method: 'PUT', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 获取草稿单写者租约;令牌只应保存在当前浏览器标签的内存中。 */
|
||||
export const acquireOrderDocumentProfileEditLease = (
|
||||
profileId: number,
|
||||
input: { browser_session_id: string; operation_id: string; confirm_takeover?: boolean },
|
||||
) => requestJson<OrderProfileEditLease & { lease_token: string }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/edit-lease`,
|
||||
{ method: 'POST', body: JSON.stringify(input), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 续租当前标签的编辑许可,服务端会拒绝过期、冲突或错误令牌。 */
|
||||
export const renewOrderDocumentProfileEditLease = (
|
||||
profileId: number,
|
||||
input: { browser_session_id: string; lease_token: string; operation_id: string },
|
||||
) => requestJson<OrderProfileEditLease & { lease_token: string }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/edit-lease/renew`,
|
||||
{ method: 'POST', body: JSON.stringify(input), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 释放当前标签租约,不保存或展示其他会话的租约信息。 */
|
||||
export const releaseOrderDocumentProfileEditLease = (
|
||||
profileId: number,
|
||||
input: { browser_session_id: string; lease_token: string; operation_id: string },
|
||||
) => requestJson<void>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/edit-lease/release`,
|
||||
{ method: 'POST', body: JSON.stringify(input), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取草稿不可变 Revision 元数据,完整定义仅能通过受控恢复使用。 */
|
||||
export const listOrderDocumentProfileDraftRevisions = (profileId: number) =>
|
||||
requestJson<OrderProfileDraftRevision[]>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/draft-revisions`, auth(),
|
||||
);
|
||||
|
||||
/** 恢复旧 Revision 时由服务端另存为新 Revision,历史不会被覆盖。 */
|
||||
export const restoreOrderDocumentProfileDraftRevision = (
|
||||
profileId: number,
|
||||
revisionNo: number,
|
||||
input: { browser_session_id: string; lease_token: string; expected_lock_version: number; operation_id: string },
|
||||
) => requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/draft-revisions/${revisionNo}/restore`,
|
||||
{ method: 'POST', body: JSON.stringify(input), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取同模板版本的服务端语义 diff;未指定 against_profile_id 时默认对比上一版本。 */
|
||||
export const getOrderDocumentProfileDiff = (profileId: number, againstProfileId?: number | null) =>
|
||||
requestJson<OrderProfileVersionDiff>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/diff${againstProfileId ? `?against_profile_id=${againstProfileId}` : ''}`,
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取模板版本治理时间线,支持 request_id、事件类型、操作者与日期过滤。 */
|
||||
export const listOrderDocumentProfileAuditEvents = (
|
||||
profileId: number,
|
||||
params?: {
|
||||
eventType?: string;
|
||||
actor?: string;
|
||||
requestIdFilter?: string;
|
||||
createdFrom?: string;
|
||||
createdTo?: string;
|
||||
beforeId?: number | null;
|
||||
limit?: number;
|
||||
},
|
||||
) => {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.eventType) query.set('event_type', params.eventType);
|
||||
if (params?.actor) query.set('actor', params.actor);
|
||||
if (params?.requestIdFilter) query.set('request_id_filter', params.requestIdFilter);
|
||||
if (params?.createdFrom) query.set('created_from', params.createdFrom);
|
||||
if (params?.createdTo) query.set('created_to', params.createdTo);
|
||||
if (params?.beforeId) query.set('before_id', String(params.beforeId));
|
||||
if (params?.limit) query.set('limit', String(params.limit));
|
||||
const suffix = query.toString();
|
||||
return requestJson<OrderProfileAuditEventPage>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/audit-events${suffix ? `?${suffix}` : ''}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
/** 读取模板版本的实际使用记录,只返回每个 Unit 最新的 RouteDecision。 */
|
||||
export const listOrderDocumentProfileUsages = (profileId: number, params?: { beforeId?: number | null; limit?: number }) => {
|
||||
const query = new URLSearchParams();
|
||||
if (params?.beforeId) query.set('before_id', String(params.beforeId));
|
||||
if (params?.limit) query.set('limit', String(params.limit));
|
||||
const suffix = query.toString();
|
||||
return requestJson<OrderProfileUsagePage>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/usages${suffix ? `?${suffix}` : ''}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
/** 列出已具备 ready MinerU 表格的样本文档。 */
|
||||
export const listOrderProfileSamples = () =>
|
||||
requestJson<OrderProfileSampleDocument[]>('/api/admin/shipping-notice/order-document-profile-samples', auth());
|
||||
@@ -118,28 +248,81 @@ export const generateOrderProfileOcrCoordinateEvidence = (documentId: number, ta
|
||||
},
|
||||
);
|
||||
|
||||
/** 由真实样本和结构化列选择创建 Profile 草稿。 */
|
||||
export const createOrderProfileFromSample = (payload: CreateOrderProfileFromSampleInput | LegacyCreateOrderProfileFromSampleInput) =>
|
||||
requestJson<ShippingOrderDocumentProfile>('/api/admin/shipping-notice/order-document-profiles/from-sample', {
|
||||
method: 'POST', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
});
|
||||
|
||||
/** 用新样本和乐观锁更新已存在草稿。 */
|
||||
export const updateOrderProfileFromSample = (
|
||||
profileId: number, payload: (CreateOrderProfileFromSampleInput | LegacyCreateOrderProfileFromSampleInput) & { expected_lock_version: number },
|
||||
) => requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/from-sample`, {
|
||||
method: 'PUT', body: JSON.stringify(payload), ...jsonAuth(),
|
||||
},
|
||||
/** 三步向导的唯一落库动作:原子创建草稿、主样本、Revision 和编辑租约。 */
|
||||
export const completeOrderDocumentProfileWizard = (payload: {
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
main_table_id: string;
|
||||
browser_session_id: string;
|
||||
operation_id: string;
|
||||
}) => requestJson<ShippingOrderDocumentProfile & {
|
||||
edit_lease: { lease_token: string; browser_session_id: string; expires_at: string };
|
||||
}>(
|
||||
'/api/admin/shipping-notice/order-document-profiles/wizard-complete',
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 发布草稿并退役同编码旧版本。 */
|
||||
export const publishOrderDocumentProfile = (profileId: number, expectedLockVersion: number) =>
|
||||
requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/publish`,
|
||||
{ method: 'POST', body: JSON.stringify({ expected_lock_version: expectedLockVersion }), ...jsonAuth() },
|
||||
/** 冻结建议决定;接受后的实际区域修改仍由当前草稿保存接口统一写入 Revision。 */
|
||||
export const decideOrderDocumentProfileSuggestion = (profileId: number, payload: {
|
||||
suggestion_id: string;
|
||||
suggestion_checksum: string;
|
||||
suggestion_summary: Record<string, unknown>;
|
||||
decision: 'accepted' | 'accepted_adjusted' | 'rejected';
|
||||
adjustment_summary?: Record<string, unknown>;
|
||||
browser_session_id: string;
|
||||
lease_token: string;
|
||||
operation_id: string;
|
||||
}) => requestJson<{ suggestion_id: string; decision: string; revision_no: number }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/suggestion-decisions`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取不可变验证运行摘要;服务端会将与当前草稿不一致的历史运行标记为 stale。 */
|
||||
export const listOrderProfileValidationRuns = (profileId: number) =>
|
||||
requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfileValidationRun[]>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs`, auth(),
|
||||
);
|
||||
|
||||
/** 运行当前草稿的即时结构检查,必须携带编辑租约,禁止绕过单写者保护。 */
|
||||
export const runOrderProfileInstantCheck = (profileId: number, payload: {
|
||||
browser_session_id: string; lease_token: string; operation_id: string;
|
||||
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfileValidationRun>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/instant-check`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 在绑定 annotation/training 样本上试运行;接口不会接受或回显盲测真值。 */
|
||||
export const runOrderProfileCurrentSample = (profileId: number, payload: {
|
||||
sample_binding_id?: number; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfileValidationRun>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/validation-runs/current-sample`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 创建不可变发布检查报告;必须指定与当前草稿 checksum 一致的通过验证运行。 */
|
||||
export const createOrderProfilePublishCheck = (profileId: number, payload: {
|
||||
validation_run_id: number; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
}) => requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfilePublishCheckReport>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/publish-checks`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取已冻结报告;草稿若改变,服务端会将报告持久化标记为 invalidated。 */
|
||||
export const getOrderProfilePublishCheck = (profileId: number, reportNo: string) =>
|
||||
requestJson<import('@/features/admin/types/shipping-order-document-profile.types').OrderProfilePublishCheckReport>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/publish-checks/${encodeURIComponent(reportNo)}`, auth(),
|
||||
);
|
||||
|
||||
/** 对报告的每条警告逐项确认后,原子消费报告并发布草稿。 */
|
||||
export const confirmOrderProfilePublishCheck = (profileId: number, reportNo: string, payload: {
|
||||
confirmed_warning_keys: string[]; browser_session_id: string; lease_token: string; operation_id: string;
|
||||
}) => requestJson<ShippingOrderDocumentProfile>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/publish-checks/${encodeURIComponent(reportNo)}/confirm`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 从不可变版本复制下一草稿。 */
|
||||
export const cloneOrderDocumentProfile = (profileId: number) =>
|
||||
requestJson<ShippingOrderDocumentProfile>(
|
||||
@@ -181,6 +364,13 @@ export const authorizeOrderProfilePreviewPages = (profileId: number, documentId:
|
||||
},
|
||||
);
|
||||
|
||||
/** 为冻结样本绑定申请只读详情页逐页预览授权,禁止回退到当前 document layout。 */
|
||||
export const authorizeOrderProfileFrozenSamplePreviewPages = (profileId: number, sampleBindingId: number) =>
|
||||
requestJson<OrderProfilePreviewPages>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/samples/${sampleBindingId}/preview-pages`,
|
||||
{ method: 'POST', ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 列出当前 Profile 已绑定的标注/训练样本,用于恢复工作台上下文。 */
|
||||
export const listOrderProfileBoundSamples = (profileId: number) =>
|
||||
requestJson<OrderProfileBoundSample[]>(
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ref, onMounted, computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
|
||||
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/features/admin/api/admin.api';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
@@ -28,6 +29,8 @@ const form = ref({
|
||||
|
||||
const isUploading = ref(false);
|
||||
const uploadError = ref('');
|
||||
const deleteDialogOpen = ref(false);
|
||||
const pendingDeleteGuideId = ref<number | null>(null);
|
||||
|
||||
const fetchAgents = async () => {
|
||||
try {
|
||||
@@ -143,13 +146,20 @@ const submitForm = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const deleteGuide = async (id: number) => {
|
||||
if (!confirm('确定要删除该指南吗?删除后不可恢复。')) return;
|
||||
const deleteGuide = (id: number) => {
|
||||
pendingDeleteGuideId.value = id;
|
||||
deleteDialogOpen.value = true;
|
||||
};
|
||||
const confirmDeleteGuide = async () => {
|
||||
const id = pendingDeleteGuideId.value;
|
||||
if (!id) return;
|
||||
try {
|
||||
await deleteAdminAgentGuide(id);
|
||||
await fetchGuides();
|
||||
} catch (error) {
|
||||
console.error('Failed to delete guide:', error);
|
||||
} finally {
|
||||
pendingDeleteGuideId.value = null;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -348,5 +358,6 @@ const getIcon = (type: string) => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DeleteConfirmDialog v-model="deleteDialogOpen" title="删除指南" message="确定要删除该指南吗?删除后不可恢复。" confirm-tone="danger" @confirm="confirmDeleteGuide" />
|
||||
</div>
|
||||
</template>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileCreateWizardPage.vue
|
||||
用途:订单模板三步创建向导。
|
||||
依赖:Schema/样本/表格 API、三个步骤组件、Router。
|
||||
逻辑:身份、样本、主表格均在浏览器内暂存;仅第三步完成调用原子 wizard-complete 接口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { getShippingOrderSchemaState } from '@/features/admin/api/shipping-order-schema.api';
|
||||
import { completeOrderDocumentProfileWizard, getOrderProfileSampleTables, listOrderProfileSamples } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
|
||||
import OrderProfileIdentityStep from './components/OrderProfileIdentityStep.vue';
|
||||
import OrderProfileSampleStep from './components/OrderProfileSampleStep.vue';
|
||||
import OrderProfileModelStartStep from './components/OrderProfileModelStartStep.vue';
|
||||
|
||||
const { t } = useI18n(); const router = useRouter(); const message = useMessage();
|
||||
const step = ref(1); const saving = ref(false); const schemas = ref<ShippingOrderSchemaVersion[]>([]);
|
||||
const samples = ref<Array<{ document_id:number; intake_no:string; filename?:string|null; table_count:number }>>([]);
|
||||
const tables = ref<Array<{ table_id:string; page_no:number; row_count:number; column_count:number; rows:string[][] }>>([]);
|
||||
const identity = reactive({ displayName:'', profileCode:'', schemaId:0 }); const documentId = ref(0); const tableId = ref('');
|
||||
const browserSessionId = crypto.randomUUID();
|
||||
const canNext = computed(() => step.value === 1 ? Boolean(identity.displayName.trim() && identity.profileCode.trim() && identity.schemaId) : step.value === 2 ? Boolean(documentId.value) : Boolean(tableId.value));
|
||||
/** 加载可用 Schema 与已解析样本;失败不创建或缓存任何 Profile。 */
|
||||
async function loadContext(): Promise<void> { try { const [state, nextSamples] = await Promise.all([getShippingOrderSchemaState(), listOrderProfileSamples()]); schemas.value = state.versions || []; samples.value = nextSamples; } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.loadFailed')); } }
|
||||
/** 刷新上传后的样本库;样本解析未完成时只会留在样本库,不能产出半成品模板。 */
|
||||
async function refreshSamples(): Promise<void> { try { samples.value = await listOrderProfileSamples(); } catch { message.error(t('admin.shippingOrderProfiles.wizard.loadFailed')); } }
|
||||
watch(documentId, async (id) => { tableId.value=''; tables.value=[]; if (!id) return; try { const preview = await getOrderProfileSampleTables(id); tables.value = preview.tables; } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.tableLoadFailed')); } });
|
||||
/** 前进仅校验本地步骤状态;最后一步才拥有正式落库权限。 */
|
||||
function next(): void { if (!canNext.value) { message.error(t('admin.shippingOrderProfiles.wizard.incomplete')); return; } if (step.value < 3) step.value += 1; }
|
||||
/** 单事务完成后进入草稿编辑路由;创建草稿和创建并进入标注共享同一审计动作。 */
|
||||
async function finish(enterEditor: boolean): Promise<void> { if (!canNext.value) return; saving.value=true; try { const profile = await completeOrderDocumentProfileWizard({ profile_code:identity.profileCode, display_name:identity.displayName, schema_version_id:identity.schemaId, document_id:documentId.value, main_table_id:tableId.value, browser_session_id:browserSessionId, operation_id:crypto.randomUUID() }); message.success(t('admin.shippingOrderProfiles.created')); if (enterEditor) router.push({ name:'AdminShippingOrderDocumentProfileEdit', params:{ profileCode:profile.profile_code, profileId:profile.id }, query:{ editorSessionId:browserSessionId } }); else router.push({ name:'AdminShippingOrderDocumentProfiles' }); } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.createFailed')); } finally { saving.value=false; } }
|
||||
onMounted(loadContext);
|
||||
</script>
|
||||
<template><section class="wizard"><header><button type="button" @click="router.push({ name:'AdminShippingOrderDocumentProfiles' })">{{ t('admin.cancel') }}</button><h1>{{ t('admin.shippingOrderProfiles.wizard.title') }}</h1><p>{{ t('admin.shippingOrderProfiles.wizard.steps', { step }) }}</p></header><OrderProfileIdentityStep v-if="step===1" v-model="identity" :schemas="schemas"/><OrderProfileSampleStep v-else-if="step===2" v-model="documentId" :samples="samples" @uploaded="refreshSamples"/><OrderProfileModelStartStep v-else v-model="tableId" :tables="tables"/><footer><button v-if="step>1" type="button" @click="step-=1">{{ t('admin.shippingOrderProfiles.wizard.previous') }}</button><span/><button v-if="step<3" class="primary" type="button" :disabled="!canNext" @click="next">{{ t('admin.shippingOrderProfiles.wizard.next') }}</button><template v-else><button type="button" :disabled="saving||!canNext" @click="finish(false)">{{ t('admin.shippingOrderProfiles.wizard.createDraft') }}</button><button class="primary" type="button" :disabled="saving||!canNext" @click="finish(true)">{{ t('admin.shippingOrderProfiles.wizard.createAndEdit') }}</button></template></footer></section></template>
|
||||
<style scoped>.wizard{display:grid;gap:1.5rem;max-width:58rem;margin:0 auto;padding:1.5rem}.wizard header{display:grid;gap:.5rem}.wizard h1,.wizard p{margin:0}.wizard p{color:#64748b}.wizard footer{display:flex;gap:.75rem;align-items:center}.wizard footer span{flex:1}.wizard button{padding:.55rem .8rem;border:1px solid #cbd5e1;border-radius:.4rem;background:#fff}.wizard .primary{background:#2563eb;color:#fff;border-color:#2563eb}.wizard button:disabled{opacity:.5;cursor:not-allowed}</style>
|
||||
+309
-533
File diff suppressed because it is too large.
Load diff
+26
@@ -0,0 +1,26 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileEditorRoutePage.vue
|
||||
用途:承接草稿编辑深链并挂载独立编辑页。
|
||||
依赖:Vue Router、OrderProfileEditorPage。
|
||||
逻辑:将路径草稿身份传递给独立编辑页;query 仅传递标签会话,不得改变目标草稿。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import OrderProfileEditorPage from './OrderProfileEditorPage.vue';
|
||||
|
||||
const ready = ref(false);
|
||||
|
||||
/**
|
||||
* 路由参数由编辑页直接读取;本页只在挂载前准备渲染,避免旧 query 身份适配。
|
||||
* @returns 设置完成后显示编辑页。
|
||||
*/
|
||||
function prepareEditor(): void {
|
||||
ready.value = true;
|
||||
}
|
||||
|
||||
prepareEditor();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<OrderProfileEditorPage v-if="ready" />
|
||||
</template>
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileLibraryPage.vue
|
||||
用途:按 profile_code 聚合展示订单文档模板族,是创建和继续编辑的唯一首页。
|
||||
依赖:Profile family API、Vue Router、Vue I18n。
|
||||
逻辑:列表只选择下一步路由;草稿进入编辑页,已发布版本创建新草稿,历史版本进入只读版本中心。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { cloneOrderDocumentProfile, listOrderDocumentProfileFamilies } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileVersionFamilySummary } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const loading = ref(false);
|
||||
const query = ref('');
|
||||
const families = ref<OrderProfileVersionFamilySummary[]>([]);
|
||||
|
||||
const filteredFamilies = computed(() => {
|
||||
const keyword = query.value.trim().toLowerCase();
|
||||
if (!keyword) return families.value;
|
||||
return families.value.filter((item) => `${item.profile_code} ${item.display_name}`.toLowerCase().includes(keyword));
|
||||
});
|
||||
|
||||
/** 加载模板族摘要;列表只显示聚合结果,不能将每个版本扁平为独立模板。 */
|
||||
async function loadFamilies(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
families.value = await listOrderDocumentProfileFamilies();
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.library.loadFailed'));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开当前草稿编辑路由;草稿不存在时由其它操作创建,不在列表页隐式创建。 */
|
||||
function continueEditing(item: OrderProfileVersionFamilySummary): void {
|
||||
if (!item.draft_profile_id) return;
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: item.profile_code, profileId: item.draft_profile_id } });
|
||||
}
|
||||
|
||||
/** 从已发布版本建立同族下一草稿,然后进入后续编辑路由。 */
|
||||
async function createNewVersion(item: OrderProfileVersionFamilySummary): Promise<void> {
|
||||
if (!item.published_profile_id) return;
|
||||
try {
|
||||
const draft = await cloneOrderDocumentProfile(item.published_profile_id);
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: { profileCode: draft.profile_code, profileId: draft.id } });
|
||||
} catch (error) {
|
||||
message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.library.createFailed'));
|
||||
}
|
||||
}
|
||||
|
||||
/** 进入不可变历史详情,不允许在此页面把版本伪装成新草稿。 */
|
||||
function viewVersion(item: OrderProfileVersionFamilySummary): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: item.profile_code, version: item.default_version } });
|
||||
}
|
||||
|
||||
onMounted(loadFamilies);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="profile-library">
|
||||
<header class="profile-library__header">
|
||||
<div><h1>{{ t('admin.shippingOrderProfiles.library.title') }}</h1><p>{{ t('admin.shippingOrderProfiles.library.subtitle') }}</p></div>
|
||||
<button class="primary" type="button" @click="router.push({ name: 'AdminShippingOrderDocumentProfileCreate' })">{{ t('admin.shippingOrderProfiles.library.create') }}</button>
|
||||
</header>
|
||||
<input v-model="query" class="profile-library__search" :placeholder="t('admin.shippingOrderProfiles.library.search')" type="search">
|
||||
<p v-if="loading">{{ t('admin.shippingOrderProfiles.library.loading') }}</p>
|
||||
<p v-else-if="!filteredFamilies.length">{{ t('admin.shippingOrderProfiles.library.empty') }}</p>
|
||||
<table v-else><thead><tr><th>{{ t('admin.shippingOrderProfiles.name') }}</th><th>{{ t('admin.shippingOrderProfiles.code') }}</th><th>{{ t('admin.shippingOrderProfiles.library.status') }}</th><th>{{ t('admin.shippingOrderProfiles.library.actions') }}</th></tr></thead>
|
||||
<tbody><tr v-for="item in filteredFamilies" :key="item.profile_code"><td>{{ item.display_name }}</td><td><code>{{ item.profile_code }}</code></td><td>{{ item.draft_profile_id ? t('admin.shippingOrderProfiles.library.draft') : item.published_profile_id ? t('admin.shippingOrderProfiles.library.published', { version: item.published_version }) : t('admin.shippingOrderProfiles.library.retired') }}</td><td class="profile-library__actions"><button v-if="item.draft_profile_id" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button><button v-else-if="item.published_profile_id" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button><button type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button></td></tr></tbody>
|
||||
</table>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.profile-library { display:grid; gap:1rem; padding:1.5rem; } .profile-library__header { display:flex; justify-content:space-between; gap:1rem; align-items:start; } h1,p { margin:0; } p { color:#64748b; margin-top:.35rem; } .primary { background:#2563eb; color:#fff; border:0; border-radius:.45rem; padding:.6rem .9rem; } .profile-library__search { max-width:28rem; padding:.6rem; border:1px solid #cbd5e1; border-radius:.4rem; } table { border-collapse:collapse; width:100%; background:#fff; } th,td { padding:.75rem; border-bottom:1px solid #e2e8f0; text-align:left; } .profile-library__actions { display:flex; gap:.5rem; flex-wrap:wrap; } button { cursor:pointer; } @media (max-width:700px) { .profile-library__header { flex-direction:column; } table { font-size:.8rem; } }
|
||||
</style>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue
|
||||
用途:生成、审阅和消费订单模板的不可变发布检查报告。
|
||||
依赖:发布检查 API、验证运行 API、Vue Router 和统一消息提示。
|
||||
逻辑:用户选择当前通过验证运行生成报告;阻断项不可确认,警告逐项确认后才可原子发布。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease, confirmOrderProfilePublishCheck, createOrderProfilePublishCheck,
|
||||
listOrderProfileValidationRuns,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfilePublishCheckReport, OrderProfileValidationRun } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute(); const router = useRouter(); const message = useMessage();
|
||||
const { t } = useI18n();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const runs = ref<OrderProfileValidationRun[]>([]); const report = ref<OrderProfilePublishCheckReport | null>(null);
|
||||
const selectedRunId = ref<number | null>(null); const confirmed = ref<string[]>([]); const busy = ref(false);
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID(); const leaseToken = ref('');
|
||||
|
||||
/** 显示统一业务错误,避免发布页暴露服务端实现细节。 */
|
||||
function fail(error: unknown): void { message.error(error instanceof BusinessError ? error.code : t('admin.orderProfilePublishCheck.failed')); }
|
||||
/** 获取租约后才允许创建或消费报告,避免发布页绕过草稿写保护。 */
|
||||
async function ensureLease(): Promise<boolean> { if (leaseToken.value) return true; try { leaseToken.value = (await acquireOrderDocumentProfileEditLease(profileId, { browser_session_id: sessionId, operation_id: crypto.randomUUID() })).lease_token; return true; } catch (error) { fail(error); return false; } }
|
||||
/** 加载仅当前草稿仍有效的通过验证运行,历史 stale 运行不可用于发布。 */
|
||||
async function loadRuns(): Promise<void> { try { runs.value = await listOrderProfileValidationRuns(profileId); selectedRunId.value = runs.value.find(item => item.status === 'passed')?.id || null; } catch (error) { fail(error); } }
|
||||
/** 创建并冻结新报告;一次 operation 重试会在服务端返回同一报告。 */
|
||||
async function createReport(): Promise<void> { if (!selectedRunId.value || !(await ensureLease())) return; busy.value = true; try { report.value = await createOrderProfilePublishCheck(profileId, { validation_run_id: selectedRunId.value, browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() }); confirmed.value = []; } catch (error) { fail(error); } finally { busy.value = false; } }
|
||||
/** 逐项确认所有警告并消费报告,成功后跳转既有只读版本详情页。 */
|
||||
async function publish(): Promise<void> { if (!report.value || !(await ensureLease())) return; busy.value = true; try { const published = await confirmOrderProfilePublishCheck(profileId, report.value.report_no || '', { confirmed_warning_keys: confirmed.value, browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() }); await router.replace({ name: 'AdminShippingOrderDocumentProfileVersionDetail', params: { profileCode: published.profile_code, version: String(published.version) } }); } catch (error) { fail(error); } finally { busy.value = false; } }
|
||||
onMounted(loadRuns);
|
||||
</script>
|
||||
<template><section class="page"><header><div><p>{{ t('admin.orderProfilePublishCheck.eyebrow') }}</p><h1>{{ t('admin.orderProfilePublishCheck.title') }}</h1><small>{{ t('admin.orderProfilePublishCheck.description') }}</small></div><button type="button" @click="router.back()">{{ t('admin.orderProfilePublishCheck.back') }}</button></header><section v-if="!report" class="card"><h2>{{ t('admin.orderProfilePublishCheck.selectRun') }}</h2><label v-for="run in runs.filter(item => item.status === 'passed')" :key="run.id"><input v-model="selectedRunId" type="radio" :value="run.id">#{{ run.id }} · {{ run.run_type }} · {{ run.created_at }}</label><p v-if="!runs.some(item => item.status === 'passed')">{{ t('admin.orderProfilePublishCheck.noRun') }}</p><button :disabled="busy || !selectedRunId" type="button" @click="createReport">{{ t('admin.orderProfilePublishCheck.create') }}</button></section><section v-else class="card"><h2>{{ t('admin.orderProfilePublishCheck.report', { reportNo: report.report_no }) }}</h2><p>{{ t('admin.orderProfilePublishCheck.status', { status: report.status, revision: report.revision_no }) }}</p><h3>{{ t('admin.orderProfilePublishCheck.blocking') }}</h3><p v-if="!report.blocking_items.length">{{ t('admin.orderProfilePublishCheck.noBlocking') }}</p><ul><li v-for="item in report.blocking_items" :key="String(item.key)">{{ item.message }}</li></ul><h3>{{ t('admin.orderProfilePublishCheck.warnings') }}</h3><label v-for="item in report.warning_items" :key="String(item.key)"><input v-model="confirmed" type="checkbox" :value="String(item.key)">{{ item.message }}</label><button :disabled="busy || report.status !== 'valid' || report.blocking_items.length > 0 || confirmed.length !== report.warning_items.length" type="button" @click="publish">{{ t('admin.orderProfilePublishCheck.confirm') }}</button></section></section></template>
|
||||
<style scoped>.page{max-width:900px;margin:auto;padding:28px}.page header{display:flex;justify-content:space-between;gap:16px}.page header p{color:#2563eb;font-weight:700;margin:0}.page h1{margin:4px 0}.card{margin-top:24px;padding:20px;border:1px solid #cbd5e1;border-radius:8px}.card label{display:block;margin:10px 0}.card button,header button{margin-top:14px;padding:8px 13px;border:0;border-radius:5px;background:#2563eb;color:white}header button{background:#64748b}</style>
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileValidationPage.vue
|
||||
用途:展示草稿不可变验证运行,并发起即时检查和当前样本试运行。
|
||||
依赖:Profile API、Vue Router、统一消息提示。
|
||||
逻辑:从稳定路由获取草稿身份;所有写操作透传编辑器会话租约,页面仅展示安全摘要与运行编号。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import {
|
||||
acquireOrderDocumentProfileEditLease,
|
||||
listOrderProfileValidationRuns,
|
||||
runOrderProfileCurrentSample,
|
||||
runOrderProfileInstantCheck,
|
||||
} from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type { OrderProfileValidationRun } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
const message = useMessage();
|
||||
const profileId = Number(route.params.profileId);
|
||||
const runs = ref<OrderProfileValidationRun[]>([]);
|
||||
const loading = ref(false);
|
||||
const executing = ref(false);
|
||||
const leaseToken = ref('');
|
||||
const sessionId = String(route.query.editorSessionId || '').trim() || crypto.randomUUID();
|
||||
|
||||
/** 将后端业务错误转换为统一提示,避免验证页泄露服务端内部细节。 */
|
||||
function report(error: unknown): void {
|
||||
const code = error instanceof BusinessError ? error.code : '';
|
||||
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
|
||||
}
|
||||
|
||||
/** 读取运行历史;后端自行计算 stale,因此客户端不根据本地草稿猜测有效性。 */
|
||||
async function loadRuns(): Promise<void> {
|
||||
loading.value = true;
|
||||
try {
|
||||
runs.value = await listOrderProfileValidationRuns(profileId);
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 为本页获取单写者租约;冲突时明确提示并保留只读历史查询。 */
|
||||
async function ensureLease(): Promise<boolean> {
|
||||
if (leaseToken.value) return true;
|
||||
try {
|
||||
const lease = await acquireOrderDocumentProfileEditLease(profileId, {
|
||||
browser_session_id: sessionId, operation_id: crypto.randomUUID(),
|
||||
});
|
||||
leaseToken.value = lease.lease_token;
|
||||
return true;
|
||||
} catch (error) {
|
||||
report(error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 运行指定验证类型,完成后重新加载服务端冻结的运行摘要。 */
|
||||
async function execute(kind: 'instant' | 'sample'): Promise<void> {
|
||||
if (!(await ensureLease())) return;
|
||||
executing.value = true;
|
||||
try {
|
||||
const payload = { browser_session_id: sessionId, lease_token: leaseToken.value, operation_id: crypto.randomUUID() };
|
||||
if (kind === 'instant') await runOrderProfileInstantCheck(profileId, payload);
|
||||
else await runOrderProfileCurrentSample(profileId, payload);
|
||||
await loadRuns();
|
||||
message.success(t('admin.orderProfileValidation.completed'));
|
||||
} catch (error) {
|
||||
report(error);
|
||||
} finally {
|
||||
executing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 返回同一草稿的编辑路由,保留标签会话身份以复用仍有效的租约。 */
|
||||
function backToEditor(): void {
|
||||
router.push({ name: 'AdminShippingOrderDocumentProfileEdit', params: route.params, query: { editorSessionId: sessionId } });
|
||||
}
|
||||
|
||||
onMounted(loadRuns);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="validation-page">
|
||||
<header>
|
||||
<div>
|
||||
<p class="eyebrow">{{ t('admin.orderProfileValidation.eyebrow') }}</p>
|
||||
<h1>{{ t('admin.orderProfileValidation.title') }}</h1>
|
||||
<p>{{ t('admin.orderProfileValidation.description') }}</p>
|
||||
</div>
|
||||
<button class="secondary" type="button" @click="backToEditor">{{ t('admin.orderProfileValidation.backToEditor') }}</button>
|
||||
</header>
|
||||
<div class="actions">
|
||||
<button type="button" :disabled="executing" @click="execute('instant')">{{ t('admin.orderProfileValidation.instantCheck') }}</button>
|
||||
<button type="button" :disabled="executing" @click="execute('sample')">{{ t('admin.orderProfileValidation.currentSample') }}</button>
|
||||
</div>
|
||||
<p v-if="loading">{{ t('admin.orderProfileValidation.loading') }}</p>
|
||||
<table v-else>
|
||||
<thead><tr><th>{{ t('admin.orderProfileValidation.run') }}</th><th>{{ t('admin.orderProfileValidation.type') }}</th><th>{{ t('admin.orderProfileValidation.status') }}</th><th>{{ t('admin.orderProfileValidation.summary') }}</th><th>{{ t('admin.orderProfileValidation.time') }}</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="run in runs" :key="run.id">
|
||||
<td>#{{ run.id }}</td><td>{{ run.run_type }}</td><td><span :class="`status ${run.status}`">{{ run.status }}</span></td>
|
||||
<td>{{ JSON.stringify((run as OrderProfileValidationRun & { summary?: Record<string, unknown> }).summary || {}) }}</td><td>{{ run.created_at }}</td>
|
||||
</tr>
|
||||
<tr v-if="!runs.length"><td colspan="5">{{ t('admin.orderProfileValidation.empty') }}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.validation-page { max-width: 1180px; margin: 0 auto; padding: 28px; color: #1e293b; }
|
||||
header { display: flex; justify-content: space-between; gap: 24px; align-items: start; }
|
||||
h1 { margin: 4px 0; font-size: 24px; } .eyebrow { margin: 0; color: #2563eb; font-size: 12px; font-weight: 700; }
|
||||
header p:not(.eyebrow) { color: #64748b; margin: 0; }.actions { display: flex; gap: 12px; margin: 24px 0; }
|
||||
button { border: 0; border-radius: 6px; background: #2563eb; color: #fff; padding: 9px 14px; cursor: pointer; } button.secondary { background: #e2e8f0; color: #334155; } button:disabled { opacity: .6; cursor: wait; }
|
||||
table { width: 100%; border-collapse: collapse; background: #fff; } th, td { padding: 12px; border-bottom: 1px solid #e2e8f0; text-align: left; vertical-align: top; } td:nth-child(4) { max-width: 420px; overflow-wrap: anywhere; color: #475569; }
|
||||
.status { text-transform: uppercase; font-size: 12px; font-weight: 700; }.passed { color: #15803d; }.failed, .stale { color: #b91c1c; }
|
||||
@media (max-width: 767px) { .validation-page { padding: 16px; } header { display: block; } header button { margin-top: 16px; } table { font-size: 12px; } }
|
||||
</style>
|
||||
+338
@@ -0,0 +1,338 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfileVersionDetailPage.vue
|
||||
用途:订单模板版本中心详情页,支持刷新恢复与分享。
|
||||
依赖:版本详情 composable、配置概览组件、版本中心 API。
|
||||
逻辑:当前已接入配置概览、只读样本画布、服务端语义 diff、审计时间线与实际使用;后续仅剩盲测隔离与发布治理收口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import { useMessage } from "@/shared/composables/useMessage";
|
||||
import { cloneOrderDocumentProfile } from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import OrderProfileReadOnlyCanvas from "./components/OrderProfileReadOnlyCanvas.vue";
|
||||
import OrderProfileAuditTimeline from "./components/OrderProfileAuditTimeline.vue";
|
||||
import OrderProfileVersionDiff from "./components/OrderProfileVersionDiff.vue";
|
||||
import OrderProfileVersionOverview from "./components/OrderProfileVersionOverview.vue";
|
||||
import OrderProfileUsageTable from "./components/OrderProfileUsageTable.vue";
|
||||
import {
|
||||
useOrderProfileVersionDetail,
|
||||
type OrderProfileVersionDetailTab,
|
||||
} from "./composables/useOrderProfileVersionDetail";
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const message = useMessage();
|
||||
const cloning = ref(false);
|
||||
const {
|
||||
activeTab,
|
||||
detail,
|
||||
errorMessage,
|
||||
loading,
|
||||
profileCode,
|
||||
tabOptions,
|
||||
versions,
|
||||
} = useOrderProfileVersionDetail();
|
||||
|
||||
const pageTitle = computed(() => {
|
||||
if (!detail.value) {
|
||||
return `${profileCode.value} · v${route.params.version || ""}`;
|
||||
}
|
||||
const statusKey =
|
||||
detail.value.status === "draft"
|
||||
? "currentDraft"
|
||||
: detail.value.status === "published"
|
||||
? "currentPublished"
|
||||
: "retired";
|
||||
return `${detail.value.profile_code} · v${detail.value.version} · ${t(
|
||||
`admin.shippingOrderProfiles.versionCenter.status.${statusKey}`,
|
||||
)}`;
|
||||
});
|
||||
|
||||
const openTab = (tab: OrderProfileVersionDetailTab) => {
|
||||
void router.replace({
|
||||
query: {
|
||||
...route.query,
|
||||
tab,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const openVersion = (profileCodeParam: string, versionParam: number) => {
|
||||
void router.push({
|
||||
name: "AdminShippingOrderDocumentProfileVersionDetail",
|
||||
params: {
|
||||
profileCode: profileCodeParam,
|
||||
version: String(versionParam),
|
||||
},
|
||||
query: {
|
||||
tab: activeTab.value,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const goBackToWorkbench = () => {
|
||||
void router.push({
|
||||
name: "AdminShippingOrderDocumentProfiles",
|
||||
query: {
|
||||
profileCode: profileCode.value || undefined,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const continueEditing = () => {
|
||||
if (!detail.value) return;
|
||||
void router.push({
|
||||
name: "AdminShippingOrderDocumentProfiles",
|
||||
query: {
|
||||
profileCode: detail.value.profile_code,
|
||||
profileId: String(detail.value.id),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const createNewVersion = async () => {
|
||||
if (!detail.value || cloning.value) return;
|
||||
cloning.value = true;
|
||||
try {
|
||||
const draft = await cloneOrderDocumentProfile(detail.value.id);
|
||||
message.success(t("admin.shippingOrderProfiles.cloned"));
|
||||
void router.push({
|
||||
name: "AdminShippingOrderDocumentProfiles",
|
||||
query: {
|
||||
profileCode: draft.profile_code,
|
||||
profileId: String(draft.id),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
message.error(
|
||||
error instanceof BusinessError ? error.message : t("admin.shippingOrderProfiles.loadFailed"),
|
||||
);
|
||||
} finally {
|
||||
cloning.value = false;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="version-detail-page">
|
||||
<header class="page-header">
|
||||
<button type="button" class="ghost-button" @click="goBackToWorkbench">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.backToWorkbench") }}
|
||||
</button>
|
||||
<div class="header-main">
|
||||
<div>
|
||||
<p class="eyebrow">{{ t("admin.shippingOrderProfiles.versionCenter.eyebrow") }}</p>
|
||||
<h1>{{ pageTitle }}</h1>
|
||||
</div>
|
||||
<div class="header-actions" v-if="detail">
|
||||
<button
|
||||
v-if="detail.status === 'draft'"
|
||||
type="button"
|
||||
class="primary-button"
|
||||
@click="continueEditing"
|
||||
>
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.continueEditing") }}
|
||||
</button>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="primary-button"
|
||||
:disabled="cloning"
|
||||
@click="createNewVersion"
|
||||
>
|
||||
{{
|
||||
cloning
|
||||
? t("admin.shippingOrderProfiles.saving")
|
||||
: t("admin.shippingOrderProfiles.newVersion")
|
||||
}}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div v-if="loading" class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.loading") }}
|
||||
</div>
|
||||
<div v-else-if="errorMessage" class="state-card error-card">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
<template v-else-if="detail">
|
||||
<nav class="tab-nav" :aria-label="t('admin.shippingOrderProfiles.versionCenter.tabsLabel')">
|
||||
<button
|
||||
v-for="tab in tabOptions"
|
||||
:key="tab.key"
|
||||
type="button"
|
||||
class="tab-button"
|
||||
:class="{ active: activeTab === tab.key }"
|
||||
@click="openTab(tab.key)"
|
||||
>
|
||||
<span>{{ t(`admin.shippingOrderProfiles.versionCenter.tabs.${tab.key}`) }}</span>
|
||||
<small v-if="tab.count !== undefined && tab.count !== null">{{ tab.count }}</small>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<div class="content-layout">
|
||||
<aside class="version-rail">
|
||||
<header>
|
||||
<h2>{{ t("admin.shippingOrderProfiles.versionCenter.familyVersions") }}</h2>
|
||||
<p>{{ detail.profile_code }}</p>
|
||||
</header>
|
||||
<button
|
||||
v-for="item in versions"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
class="version-item"
|
||||
:class="{ active: item.id === detail.id }"
|
||||
@click="openVersion(item.profile_code, item.version)"
|
||||
>
|
||||
<strong>v{{ item.version }}</strong>
|
||||
<span>{{ t(`admin.shippingOrderProfiles.versionCenter.status.${item.status === 'draft' ? 'currentDraft' : item.status === 'published' ? 'currentPublished' : 'retired'}`) }}</span>
|
||||
</button>
|
||||
</aside>
|
||||
|
||||
<div class="detail-panel">
|
||||
<OrderProfileVersionOverview v-if="activeTab === 'overview'" :detail="detail" />
|
||||
<OrderProfileReadOnlyCanvas v-else-if="activeTab === 'canvas'" :detail="detail" />
|
||||
<OrderProfileVersionDiff v-else-if="activeTab === 'diff'" :detail="detail" :versions="versions" />
|
||||
<OrderProfileAuditTimeline v-else-if="activeTab === 'audit'" :detail="detail" />
|
||||
<OrderProfileUsageTable v-else-if="activeTab === 'usage'" :detail="detail" />
|
||||
<section v-else class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.loadFailed") }}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.version-detail-page {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.page-header,
|
||||
.state-card,
|
||||
.version-rail,
|
||||
.detail-panel {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 1rem;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.header-main {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 0.35rem;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.page-header h1,
|
||||
.version-rail h2 {
|
||||
margin: 0;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.ghost-button,
|
||||
.primary-button,
|
||||
.tab-button,
|
||||
.version-item {
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.7rem;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.ghost-button,
|
||||
.primary-button {
|
||||
padding: 0.5rem 0.85rem;
|
||||
}
|
||||
|
||||
.primary-button {
|
||||
background: #0f172a;
|
||||
border-color: #0f172a;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.tab-nav {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.tab-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.45rem;
|
||||
padding: 0.55rem 0.85rem;
|
||||
}
|
||||
|
||||
.tab-button.active {
|
||||
border-color: #2563eb;
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
}
|
||||
|
||||
.content-layout {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: minmax(180px, 220px) minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.version-rail {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.version-rail header p {
|
||||
margin: 0.35rem 0 0;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.version-item {
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
justify-items: start;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
.version-item.active {
|
||||
border-color: #2563eb;
|
||||
background: #eff6ff;
|
||||
}
|
||||
|
||||
.version-item span {
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.error-card {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.header-main,
|
||||
.content-layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+4
-4
@@ -1,13 +1,13 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue
|
||||
用途:订单坐标 Profile 管理路由入口。
|
||||
依赖:OrderProfileWorkbench。
|
||||
逻辑:页面编排保持极薄;受控页面预览、区域标注、版本抽屉和草稿保护全部由工作台组件协作完成。
|
||||
依赖:OrderProfileLibraryPage。
|
||||
逻辑:列表页只承担模板族管理与路由分发;旧工作台不再作为首页创建入口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import OrderProfileWorkbench from './OrderProfileWorkbench.vue';
|
||||
import OrderProfileLibraryPage from './OrderProfileLibraryPage.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<OrderProfileWorkbench />
|
||||
<OrderProfileLibraryPage />
|
||||
</template>
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileAuditTimeline.vue
|
||||
用途:展示订单模板版本中心的治理审计时间线。
|
||||
依赖:版本中心审计 API、版本详情 DTO、Vue I18n。
|
||||
逻辑:使用 before_id 游标分页避免新增事件导致翻页重复;只展示安全 detail 摘要,不展示 PDF、正文或盲测真值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import { listOrderDocumentProfileAuditEvents } from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import type {
|
||||
OrderProfileAuditEventPage,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
const props = defineProps<{ detail: ShippingOrderDocumentProfile }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref("");
|
||||
const page = ref<OrderProfileAuditEventPage | null>(null);
|
||||
const cursorStack = ref<Array<number | null>>([]);
|
||||
const activeBeforeId = ref<number | null>(null);
|
||||
const filters = reactive({
|
||||
eventType: "",
|
||||
actor: "",
|
||||
requestIdFilter: "",
|
||||
createdFrom: "",
|
||||
createdTo: "",
|
||||
});
|
||||
|
||||
const formatTime = (value?: string | null) => value ? new Date(value).toLocaleString() : "-";
|
||||
const formatJson = (value: unknown) => {
|
||||
try {
|
||||
return JSON.stringify(value ?? {}, null, 2);
|
||||
} catch {
|
||||
return String(value ?? "");
|
||||
}
|
||||
};
|
||||
|
||||
const hasPrevious = computed(() => cursorStack.value.length > 0);
|
||||
const hasNext = computed(() => Boolean(page.value?.page.has_more && page.value?.page.next_before_id));
|
||||
|
||||
const load = async () => {
|
||||
loading.value = true;
|
||||
errorMessage.value = "";
|
||||
try {
|
||||
page.value = await listOrderDocumentProfileAuditEvents(props.detail.id, {
|
||||
eventType: filters.eventType.trim() || undefined,
|
||||
actor: filters.actor.trim() || undefined,
|
||||
requestIdFilter: filters.requestIdFilter.trim() || undefined,
|
||||
createdFrom: filters.createdFrom || undefined,
|
||||
createdTo: filters.createdTo || undefined,
|
||||
beforeId: activeBeforeId.value,
|
||||
limit: 20,
|
||||
});
|
||||
} catch (error) {
|
||||
page.value = null;
|
||||
errorMessage.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t("admin.shippingOrderProfiles.versionCenter.audit.loadFailed");
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const applyFilters = async () => {
|
||||
activeBeforeId.value = null;
|
||||
cursorStack.value = [];
|
||||
await load();
|
||||
};
|
||||
|
||||
const resetFilters = async () => {
|
||||
filters.eventType = "";
|
||||
filters.actor = "";
|
||||
filters.requestIdFilter = "";
|
||||
filters.createdFrom = "";
|
||||
filters.createdTo = "";
|
||||
await applyFilters();
|
||||
};
|
||||
|
||||
const loadNext = async () => {
|
||||
if (!page.value?.page.next_before_id) return;
|
||||
cursorStack.value.push(activeBeforeId.value);
|
||||
activeBeforeId.value = page.value.page.next_before_id;
|
||||
await load();
|
||||
};
|
||||
|
||||
const loadPrevious = async () => {
|
||||
if (!cursorStack.value.length) return;
|
||||
activeBeforeId.value = cursorStack.value.pop() ?? null;
|
||||
await load();
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.detail.id,
|
||||
() => {
|
||||
activeBeforeId.value = null;
|
||||
cursorStack.value = [];
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="timeline-panel">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.audit.title") }}</h3>
|
||||
<p>{{ t("admin.shippingOrderProfiles.versionCenter.audit.subtitle") }}</p>
|
||||
</div>
|
||||
<div class="toolbar-actions">
|
||||
<button type="button" class="ghost-button" :disabled="loading" @click="resetFilters">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.audit.reset") }}
|
||||
</button>
|
||||
<button type="button" class="primary-button" :disabled="loading" @click="applyFilters">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.audit.apply") }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="filters">
|
||||
<label>
|
||||
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.eventType") }}</span>
|
||||
<input v-model="filters.eventType" type="text" />
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.actor") }}</span>
|
||||
<input v-model="filters.actor" type="text" />
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.requestId") }}</span>
|
||||
<input v-model="filters.requestIdFilter" type="text" />
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.createdFrom") }}</span>
|
||||
<input v-model="filters.createdFrom" type="date" />
|
||||
</label>
|
||||
<label>
|
||||
<span>{{ t("admin.shippingOrderProfiles.versionCenter.audit.createdTo") }}</span>
|
||||
<input v-model="filters.createdTo" type="date" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.audit.loading") }}
|
||||
</div>
|
||||
<div v-else-if="errorMessage" class="state-card error-card">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
<div v-else-if="!page?.items.length" class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.audit.empty") }}
|
||||
</div>
|
||||
<div v-else class="timeline-list">
|
||||
<article
|
||||
v-for="item in page.items"
|
||||
:key="item.id"
|
||||
class="timeline-item"
|
||||
>
|
||||
<header>
|
||||
<div>
|
||||
<p class="timeline-type">{{ item.event_type }}</p>
|
||||
<h4>{{ item.actor.display_name }}</h4>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<span>{{ formatTime(item.created_at) }}</span>
|
||||
<code v-if="item.request_id">{{ item.request_id }}</code>
|
||||
</div>
|
||||
</header>
|
||||
<pre>{{ formatJson(item.detail) }}</pre>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<button type="button" class="ghost-button" :disabled="loading || !hasPrevious" @click="loadPrevious">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.audit.previous") }}
|
||||
</button>
|
||||
<button type="button" class="ghost-button" :disabled="loading || !hasNext" @click="loadNext">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.audit.next") }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.timeline-panel,
|
||||
.toolbar,
|
||||
.filters,
|
||||
.timeline-item,
|
||||
.state-card {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 1rem;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.timeline-panel {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.toolbar,
|
||||
.filters,
|
||||
.state-card,
|
||||
.timeline-item {
|
||||
padding: 0.95rem 1rem;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.toolbar h3,
|
||||
.timeline-item h4 {
|
||||
margin: 0;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.toolbar p,
|
||||
.timeline-type {
|
||||
margin: 0.25rem 0 0;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.toolbar-actions,
|
||||
.pager {
|
||||
display: flex;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.filters {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.filters label {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
color: #475569;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.filters input,
|
||||
.ghost-button,
|
||||
.primary-button {
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.75rem;
|
||||
background: #fff;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.primary-button {
|
||||
background: #0f172a;
|
||||
border-color: #0f172a;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.timeline-list {
|
||||
display: grid;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.timeline-item header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: grid;
|
||||
justify-items: end;
|
||||
gap: 0.25rem;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.timeline-item pre {
|
||||
margin: 0.85rem 0 0;
|
||||
border-radius: 0.75rem;
|
||||
background: #0f172a;
|
||||
padding: 0.8rem;
|
||||
color: #e2e8f0;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.45;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.error-card {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
@media (max-width: 1100px) {
|
||||
.filters {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.toolbar,
|
||||
.timeline-item header {
|
||||
display: grid;
|
||||
}
|
||||
|
||||
.filters {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+160
-40
@@ -2,7 +2,7 @@
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileDocumentCanvas.vue
|
||||
用途:展示受控 PDF 单页预览,并以相对坐标框支持选择、拖动和缩放区域。
|
||||
依赖:浏览器 fetch、认证请求头、OrderProfileCanvasRegion。
|
||||
逻辑:父工作台签发单页令牌并提供分页/保存动作;本组件下载短时 PNG,以三段式工具栏和窄工具轨承载标注交互。
|
||||
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
@@ -14,6 +14,8 @@ import type { OrderProfileCanvasRegion, OrderProfilePreviewPageGrant } from '@/f
|
||||
const props = defineProps<{
|
||||
profileId: number | null;
|
||||
grant?: OrderProfilePreviewPageGrant | null;
|
||||
mode?: 'edit' | 'readonly';
|
||||
previewPagePath?: string | null;
|
||||
regions: OrderProfileCanvasRegion[];
|
||||
selectedRegionId?: string | null;
|
||||
creationKind?: OrderProfileCanvasRegion['kind'] | null;
|
||||
@@ -30,6 +32,7 @@ const props = defineProps<{
|
||||
saving?: boolean;
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const readonlyMode = computed(() => props.mode === 'readonly');
|
||||
const emit = defineEmits<{
|
||||
select: [regionId: string];
|
||||
start: [regionId: string];
|
||||
@@ -68,8 +71,10 @@ const loadPage = async () => {
|
||||
URL.revokeObjectURL(imageUrl.value);
|
||||
imageUrl.value = '';
|
||||
try {
|
||||
const previewPath = props.previewPagePath
|
||||
|| `/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages`;
|
||||
const response = await fetch(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${props.profileId}/preview-pages/${props.grant.page_no}?preview_token=${encodeURIComponent(props.grant.preview_token)}`,
|
||||
`${previewPath}/${props.grant.page_no}?preview_token=${encodeURIComponent(props.grant.preview_token)}`,
|
||||
{ headers: getAuthHeaders(), cache: 'no-store' },
|
||||
);
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
@@ -79,9 +84,9 @@ const loadPage = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
/** 将指针移动映射为相对坐标;八向手柄独立调整边或角,放大后仍以相对坐标精确落位。 */
|
||||
/** 将指针移动映射为相对坐标;readonly 模式只保留选中,不允许几何变化。 */
|
||||
const move = (event: PointerEvent) => {
|
||||
if (!activeDrag || !canvas.value) return;
|
||||
if (!activeDrag || !canvas.value || readonlyMode.value) return;
|
||||
const bounds = canvas.value.getBoundingClientRect();
|
||||
const dx = (event.clientX - activeDrag.startX) / bounds.width;
|
||||
const dy = (event.clientY - activeDrag.startY) / bounds.height;
|
||||
@@ -104,10 +109,11 @@ const move = (event: PointerEvent) => {
|
||||
emit('change', activeDrag.id, { x0, y0, x1: x0 + width, y1: y0 + height });
|
||||
};
|
||||
|
||||
/** 为单次鼠标手势建立一个撤销边界,避免每个像素移动污染历史。 */
|
||||
/** 为单次鼠标手势建立一个撤销边界;readonly 模式仅允许选中区域。 */
|
||||
const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode: DragMode) => {
|
||||
event.preventDefault();
|
||||
emit('select', region.id);
|
||||
if (readonlyMode.value) return;
|
||||
emit('start', region.id);
|
||||
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
|
||||
window.addEventListener('pointermove', move);
|
||||
@@ -122,7 +128,7 @@ const endMove = () => {
|
||||
};
|
||||
/** 未处于绘制模式时以左键拖动画布视口,避免依赖横纵滚动条定位放大页面。 */
|
||||
const beginPan = (event: PointerEvent) => {
|
||||
if (props.creationKind || !viewport.value || event.button !== 0) return;
|
||||
if ((props.creationKind && !readonlyMode.value) || !viewport.value || event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
activePan = { startX: event.clientX, startY: event.clientY, scrollLeft: viewport.value.scrollLeft, scrollTop: viewport.value.scrollTop };
|
||||
window.addEventListener('pointermove', pan);
|
||||
@@ -136,7 +142,7 @@ const pan = (event: PointerEvent) => {
|
||||
const endPan = () => { activePan = null; window.removeEventListener('pointermove', pan); };
|
||||
/** 在启用绘制模式时,把指针位置转换为受约束的相对区域并交由父级创建。 */
|
||||
const beginCreation = (event: PointerEvent) => {
|
||||
if (!props.creationKind || !canvas.value) { beginPan(event); return; }
|
||||
if (readonlyMode.value || !props.creationKind || !canvas.value) { beginPan(event); return; }
|
||||
const bounds = canvas.value.getBoundingClientRect();
|
||||
const x = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
|
||||
const y = Math.max(0, Math.min(1, (event.clientY - bounds.top) / bounds.height));
|
||||
@@ -180,49 +186,163 @@ onBeforeUnmount(() => { endMove(); endPan(); endCreation(); URL.revokeObjectURL(
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="canvas-shell" aria-label="Document annotation canvas">
|
||||
<section class="canvas-shell" :aria-label="readonlyMode ? 'Document readonly canvas' : 'Document annotation canvas'">
|
||||
<header v-if="imageUrl" class="canvas-toolbar">
|
||||
<div class="toolbar-actions"><button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button><button type="button" :disabled="redoDisabled" :title="t('admin.shippingOrderProfiles.workbench.redo')" @click="emit('redo')"><Redo2 /></button><span class="toolbar-divider" aria-hidden="true" /><button type="button" :disabled="duplicateDisabled" :title="t('admin.shippingOrderProfiles.workbench.duplicateRegionShortcut')" @click="emit('duplicate')"><Copy /></button><button type="button" class="delete-action" :disabled="deleteDisabled" :title="t('admin.shippingOrderProfiles.workbench.deleteRegionShortcut')" @click="emit('delete')"><Trash2 /></button><span class="toolbar-divider" aria-hidden="true" /><button type="button" class="save-action" :disabled="saveDisabled || saving" :title="t('admin.save')" @click="emit('save')"><Save /><span>{{ saving ? t('admin.shippingOrderProfiles.saving') : t('admin.save') }}</span></button></div>
|
||||
<div class="page-control"><button type="button" :disabled="pageNo <= 1" :title="t('admin.shippingOrderExtractionRuns.previous')" @click="emit('page', pageNo - 1)"><ArrowLeft /></button><label><input v-model.number="pageInput" type="number" min="1" :max="pageCount" :aria-label="t('admin.shippingOrderProfiles.workbench.pageNavigation')" @change="goToPage" @keydown.enter.prevent="goToPage" /><span>/ {{ pageCount }}</span></label><button type="button" :disabled="pageNo >= pageCount" :title="t('admin.shippingOrderExtractionRuns.next')" @click="emit('page', pageNo + 1)"><ArrowRight /></button></div>
|
||||
<div class="zoom-control"><button type="button" :disabled="zoom <= .5" :title="t('admin.shippingOrderProfiles.workbench.zoomOut')" @click="adjustZoom(-.25)"><Minus /></button><output>{{ zoomPercent }}%</output><button type="button" :disabled="zoom >= 4" :title="t('admin.shippingOrderProfiles.workbench.zoomIn')" @click="adjustZoom(.25)"><Plus /></button><button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button></div>
|
||||
<div class="toolbar-actions">
|
||||
<template v-if="!readonlyMode">
|
||||
<button type="button" :disabled="undoDisabled" :title="t('admin.shippingOrderProfiles.workbench.undo')" @click="emit('undo')"><RotateCcw /></button>
|
||||
<button type="button" :disabled="redoDisabled" :title="t('admin.shippingOrderProfiles.workbench.redo')" @click="emit('redo')"><Redo2 /></button>
|
||||
<span class="toolbar-divider" aria-hidden="true" />
|
||||
<button type="button" :disabled="duplicateDisabled" :title="t('admin.shippingOrderProfiles.workbench.duplicateRegionShortcut')" @click="emit('duplicate')"><Copy /></button>
|
||||
<button type="button" class="delete-action" :disabled="deleteDisabled" :title="t('admin.shippingOrderProfiles.workbench.deleteRegionShortcut')" @click="emit('delete')"><Trash2 /></button>
|
||||
<span class="toolbar-divider" aria-hidden="true" />
|
||||
<button type="button" class="save-action" :disabled="saveDisabled || saving" :title="t('admin.save')" @click="emit('save')"><Save /><span>{{ saving ? t('admin.shippingOrderProfiles.saving') : t('admin.save') }}</span></button>
|
||||
</template>
|
||||
<span v-else class="readonly-badge">{{ t('admin.shippingOrderProfiles.versionCenter.readonlyCanvasBadge') }}</span>
|
||||
</div>
|
||||
<div class="page-control">
|
||||
<button type="button" :disabled="pageNo <= 1" :title="t('admin.shippingOrderExtractionRuns.previous')" @click="emit('page', pageNo - 1)"><ArrowLeft /></button>
|
||||
<label><input v-model.number="pageInput" type="number" min="1" :max="pageCount" :aria-label="t('admin.shippingOrderProfiles.workbench.pageNavigation')" @change="goToPage" @keydown.enter.prevent="goToPage" /><span>/ {{ pageCount }}</span></label>
|
||||
<button type="button" :disabled="pageNo >= pageCount" :title="t('admin.shippingOrderExtractionRuns.next')" @click="emit('page', pageNo + 1)"><ArrowRight /></button>
|
||||
</div>
|
||||
<div class="zoom-control">
|
||||
<button type="button" :disabled="zoom <= .5" :title="t('admin.shippingOrderProfiles.workbench.zoomOut')" @click="adjustZoom(-.25)"><Minus /></button>
|
||||
<output>{{ zoomPercent }}%</output>
|
||||
<button type="button" :disabled="zoom >= 4" :title="t('admin.shippingOrderProfiles.workbench.zoomIn')" @click="adjustZoom(.25)"><Plus /></button>
|
||||
<button type="button" class="fit-action" @click="resetZoom">{{ t('admin.shippingOrderProfiles.workbench.fitPage') }}</button>
|
||||
</div>
|
||||
</header>
|
||||
<div v-if="loading" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.loadingPage') }}</div>
|
||||
<div v-else-if="!imageUrl" class="canvas-state">{{ t('admin.shippingOrderProfiles.workbench.selectBoundPdf') }}</div>
|
||||
<div v-else class="canvas-work-area"><aside class="annotation-tools" :class="{ collapsed: !toolsOpen }"><button type="button" class="tools-toggle" :aria-expanded="toolsOpen" :aria-label="toolsOpen ? t('admin.shippingOrderProfiles.workbench.hideAnnotationTools') : t('admin.shippingOrderProfiles.workbench.showAnnotationTools')" @click="toolsOpen = !toolsOpen"><BoxSelect /><span v-if="toolsOpen">{{ t('admin.shippingOrderProfiles.workbench.annotationTools') }}</span></button><template v-if="toolsOpen"><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchor')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderAnchorTool') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawOrderField')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderField') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawHeader')" :class="{ active: creationKind === 'header_field' }" @click="emit('draw', 'header_field')"><TableProperties /><span>{{ t('admin.shippingOrderProfiles.workbench.headerTool') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawLine')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><ScanLine /><span>{{ t('admin.shippingOrderProfiles.workbench.lineTool') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawField')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.fieldTool') }}</span></button><button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawExclusion')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /><span>{{ t('admin.shippingOrderProfiles.workbench.exclusionTool') }}</span></button><button type="button" class="suggest" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><Sparkles /><span>{{ suggesting ? t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') : t('admin.shippingOrderProfiles.workbench.autoSuggest') }}</span></button><p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p></template></aside><div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind }" @wheel.prevent="handleWheel"><div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
|
||||
<img :src="imageUrl" alt="Controlled document page preview" draggable="false" />
|
||||
<div
|
||||
v-for="region in regions"
|
||||
:key="region.id"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="region"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }]"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@keydown.enter="emit('select', region.id)"
|
||||
@keydown.space.prevent="emit('select', region.id)"
|
||||
><span class="region-label" @pointerdown.stop="beginDrag($event, region, 'move')">{{ region.label }}</span><template v-if="region.kind === 'line'"><span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" /></template><button v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" /></div>
|
||||
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
|
||||
</div></div></div>
|
||||
<div v-else class="canvas-work-area" :class="{ readonly: readonlyMode }">
|
||||
<aside v-if="!readonlyMode" class="annotation-tools" :class="{ collapsed: !toolsOpen }">
|
||||
<button type="button" class="tools-toggle" :aria-expanded="toolsOpen" :aria-label="toolsOpen ? t('admin.shippingOrderProfiles.workbench.hideAnnotationTools') : t('admin.shippingOrderProfiles.workbench.showAnnotationTools')" @click="toolsOpen = !toolsOpen"><BoxSelect /><span v-if="toolsOpen">{{ t('admin.shippingOrderProfiles.workbench.annotationTools') }}</span></button>
|
||||
<template v-if="toolsOpen">
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawOrderAnchor')" :class="{ active: creationKind === 'order_anchor' }" @click="emit('draw', 'order_anchor')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderAnchorTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawOrderField')" :class="{ active: creationKind === 'order_field' }" @click="emit('draw', 'order_field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.orderField') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawHeader')" :class="{ active: creationKind === 'header_field' }" @click="emit('draw', 'header_field')"><TableProperties /><span>{{ t('admin.shippingOrderProfiles.workbench.headerTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawLine')" :class="{ active: creationKind === 'line' }" @click="emit('draw', 'line')"><ScanLine /><span>{{ t('admin.shippingOrderProfiles.workbench.lineTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawField')" :class="{ active: creationKind === 'field' }" @click="emit('draw', 'field')"><BoxSelect /><span>{{ t('admin.shippingOrderProfiles.workbench.fieldTool') }}</span></button>
|
||||
<button type="button" :title="t('admin.shippingOrderProfiles.workbench.drawExclusion')" :class="{ active: creationKind === 'exclusion' }" @click="emit('draw', 'exclusion')"><Eraser /><span>{{ t('admin.shippingOrderProfiles.workbench.exclusionTool') }}</span></button>
|
||||
<button type="button" class="suggest" :disabled="autoSuggestDisabled || suggesting" @click="emit('suggest')"><Sparkles /><span>{{ suggesting ? t('admin.shippingOrderProfiles.workbench.autoSuggestRunning') : t('admin.shippingOrderProfiles.workbench.autoSuggest') }}</span></button>
|
||||
<p v-if="suggestionProgress" class="suggestion-progress" :class="{ failed: !suggesting }">{{ suggestionProgress }}</p>
|
||||
</template>
|
||||
</aside>
|
||||
<div ref="viewport" class="canvas-viewport" :class="{ panning: !creationKind || readonlyMode }" @wheel.prevent="handleWheel">
|
||||
<div ref="canvas" class="canvas-stage" :class="{ drawing: creationKind && !readonlyMode }" :style="{ '--canvas-zoom': zoom }" @pointerdown="beginCreation">
|
||||
<img :src="imageUrl" alt="Controlled document page preview" draggable="false" />
|
||||
<div
|
||||
v-for="region in regions"
|
||||
:key="region.id"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
class="region"
|
||||
:class="[`region-${region.kind}`, { selected: selected.has(region.id) }]"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@keydown.enter="emit('select', region.id)"
|
||||
@keydown.space.prevent="emit('select', region.id)"
|
||||
>
|
||||
<span class="region-label" @pointerdown.stop="beginDrag($event, region, 'move')">{{ region.label }}</span>
|
||||
<template v-if="region.kind === 'line' && !readonlyMode">
|
||||
<span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" />
|
||||
</template>
|
||||
<button v-if="!readonlyMode" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
|
||||
</div>
|
||||
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.canvas-shell { min-height: 36rem; background: #101827; padding: 0 1rem 1rem; overflow: hidden; }.canvas-toolbar { position: sticky; top: 0; z-index: 4; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: .75rem; margin: 0 -1rem 1rem; padding: .55rem 1rem; border-bottom: 1px solid #26354b; background: rgb(15 23 42 / .98); color: #cbd5e1; font-size: .75rem; }.canvas-toolbar>div { display: flex; align-items: center; gap: .35rem; }.canvas-toolbar button { display: inline-flex; min-width: 2rem; height: 2rem; align-items: center; justify-content: center; gap: .35rem; border: 1px solid #475569; border-radius: .35rem; background: #1e293b; padding: .3rem .5rem; color: #e2e8f0; font-size: .72rem; }.canvas-toolbar button:hover { border-color: #60a5fa; background: #26364f; }.canvas-toolbar button:disabled { cursor: not-allowed; opacity: .4; }.canvas-toolbar svg,.annotation-tools svg { width: .95rem; height: .95rem; }.toolbar-actions { justify-self: start; }.toolbar-divider { width: 1px; height: 1.25rem; margin: 0 .15rem; background: #475569; }.toolbar-actions .delete-action:not(:disabled) { color: #fecaca; }.toolbar-actions .delete-action:not(:disabled):hover { border-color: #f87171; background: #7f1d1d; color: #fff; }.toolbar-actions .save-action { border-color: #0284c7; background: #0284c7; padding-inline: .65rem; }.page-control { justify-self: center; }.page-control label { display: flex; height: 2rem; align-items: center; gap: .3rem; border: 1px solid #475569; border-radius: .35rem; background: #0f172a; padding: 0 .45rem; color: #94a3b8; }.page-control input { width: 3rem; border: 0; background: transparent; color: #f8fafc; font: 700 .76rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; text-align: right; outline: 0; }.zoom-control { justify-self: end; }.canvas-toolbar output { min-width: 3.4rem; color: #f8fafc; text-align: center; }.zoom-control .fit-action { padding-inline: .65rem; }
|
||||
.canvas-shell { min-height: 36rem; background: #101827; padding: 0 1rem 1rem; overflow: hidden; }
|
||||
.canvas-toolbar { position: sticky; top: 0; z-index: 4; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: .75rem; margin: 0 -1rem 1rem; padding: .55rem 1rem; border-bottom: 1px solid #26354b; background: rgb(15 23 42 / .98); color: #cbd5e1; font-size: .75rem; }
|
||||
.canvas-toolbar > div { display: flex; align-items: center; gap: .35rem; }
|
||||
.canvas-toolbar button { display: inline-flex; min-width: 2rem; height: 2rem; align-items: center; justify-content: center; gap: .35rem; border: 1px solid #475569; border-radius: .35rem; background: #1e293b; padding: .3rem .5rem; color: #e2e8f0; font-size: .72rem; }
|
||||
.canvas-toolbar button:hover { border-color: #60a5fa; background: #26364f; }
|
||||
.canvas-toolbar button:disabled { cursor: not-allowed; opacity: .4; }
|
||||
.canvas-toolbar svg, .annotation-tools svg { width: .95rem; height: .95rem; }
|
||||
.toolbar-actions { justify-self: start; }
|
||||
.toolbar-divider { width: 1px; height: 1.25rem; margin: 0 .15rem; background: #475569; }
|
||||
.toolbar-actions .delete-action:not(:disabled) { color: #fecaca; }
|
||||
.toolbar-actions .delete-action:not(:disabled):hover { border-color: #f87171; background: #7f1d1d; color: #fff; }
|
||||
.toolbar-actions .save-action { border-color: #0284c7; background: #0284c7; padding-inline: .65rem; }
|
||||
.readonly-badge { display: inline-flex; align-items: center; min-height: 2rem; border: 1px solid #475569; border-radius: .35rem; background: #0f172a; padding: 0 .65rem; color: #cbd5e1; }
|
||||
.page-control { justify-self: center; }
|
||||
.page-control label { display: flex; height: 2rem; align-items: center; gap: .3rem; border: 1px solid #475569; border-radius: .35rem; background: #0f172a; padding: 0 .45rem; color: #94a3b8; }
|
||||
.page-control input { width: 3rem; border: 0; background: transparent; color: #f8fafc; font: 700 .76rem/1 ui-monospace, SFMono-Regular, Menlo, monospace; text-align: right; outline: 0; }
|
||||
.zoom-control { justify-self: end; }
|
||||
.canvas-toolbar output { min-width: 3.4rem; color: #f8fafc; text-align: center; }
|
||||
.zoom-control .fit-action { padding-inline: .65rem; }
|
||||
.canvas-state { display: grid; min-height: 32rem; place-items: center; color: #94a3b8; font-size: .875rem; }
|
||||
.canvas-work-area { display: flex; max-height: 43rem; gap: .6rem; }.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }.canvas-viewport.panning { cursor: grab; }.canvas-viewport.panning:active { cursor: grabbing; }.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }.canvas-stage img { display: block; width: 100%; user-select: none; }.canvas-stage.drawing { cursor: crosshair; }.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 7rem; padding: .35rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }.annotation-tools.collapsed { flex-basis: 2.45rem; padding: .3rem; }.annotation-tools button { display: flex; min-height: 2rem; align-items: center; gap: .4rem; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem .45rem; color: #e2e8f0; font-size: .7rem; text-align: left; white-space: nowrap; }.annotation-tools button:hover,.annotation-tools button.active { border-color: #38bdf8; background: #0c4a6e; color: #f0f9ff; }.annotation-tools .tools-toggle { justify-content: center; }.annotation-tools.collapsed .tools-toggle { padding-inline: 0; }.annotation-tools .suggest { border-color: #0ea5e9; background: #0284c7; font-weight: 700; }.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }.suggestion-progress.failed { color: #fca5a5; }
|
||||
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
|
||||
.canvas-work-area { display: flex; max-height: 43rem; gap: .6rem; }
|
||||
.canvas-work-area.readonly { gap: 0; }
|
||||
.canvas-viewport { position: relative; min-width: 0; flex: 1; overflow: auto; }
|
||||
.canvas-viewport.panning { cursor: grab; }
|
||||
.canvas-viewport.panning:active { cursor: grabbing; }
|
||||
.canvas-stage { position: relative; margin: auto; width: calc(100% * var(--canvas-zoom)); min-width: 42rem; box-shadow: 0 16px 40px rgba(0,0,0,.35); }
|
||||
.canvas-stage img { display: block; width: 100%; user-select: none; }
|
||||
.canvas-stage.drawing { cursor: crosshair; }
|
||||
.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 7rem; padding: .35rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
|
||||
.annotation-tools.collapsed { flex-basis: 2.45rem; padding: .3rem; }
|
||||
.annotation-tools button { display: flex; min-height: 2rem; align-items: center; gap: .4rem; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem .45rem; color: #e2e8f0; font-size: .7rem; text-align: left; white-space: nowrap; }
|
||||
.annotation-tools button:hover, .annotation-tools button.active { border-color: #38bdf8; background: #0c4a6e; color: #f0f9ff; }
|
||||
.annotation-tools .tools-toggle { justify-content: center; }
|
||||
.annotation-tools.collapsed .tools-toggle { padding-inline: 0; }
|
||||
.annotation-tools .suggest { border-color: #0ea5e9; background: #0284c7; font-weight: 700; }
|
||||
.annotation-tools button:disabled { cursor: not-allowed; opacity: .45; }
|
||||
.suggestion-progress { margin: .1rem; color: #bae6fd; font-size: .66rem; line-height: 1.35; }
|
||||
.suggestion-progress.failed { color: #fca5a5; }
|
||||
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }
|
||||
.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region-label { position: absolute; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.resize-handle { position: absolute; z-index: 3; width: 10px; height: 10px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; }.handle-n,.handle-s { left: 50%; margin-left: -5px; cursor: ns-resize; }.handle-e,.handle-w { top: 50%; margin-top: -5px; cursor: ew-resize; }.handle-nw,.handle-se { cursor: nwse-resize; }.handle-ne,.handle-sw { cursor: nesw-resize; }.handle-n,.handle-nw,.handle-ne { top: -6px; }.handle-s,.handle-sw,.handle-se { bottom: -6px; }.handle-e,.handle-ne,.handle-se { right: -6px; }.handle-w,.handle-nw,.handle-sw { left: -6px; }
|
||||
.region-header_field { z-index: 2; border: 1.5px solid #f59e0b; background: rgb(245 158 11 / .08); }.region-header_field .region-label,.region-header_field .resize-handle { background: #b45309; }
|
||||
.region-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }.region-order_field .region-label,.region-order_field .resize-handle { background: #15803d; }
|
||||
.region-order_anchor { z-index: 2; border: 1.5px solid #a855f7; background: rgb(168 85 247 / .08); }.region-order_anchor .region-label,.region-order_anchor .resize-handle { background: #7e22ce; }
|
||||
.region-line { z-index: 0; border-color: #a78bfa; background: rgb(167 139 250 / .1); pointer-events: none; }.region-line .region-label,.region-line .line-hit-edge,.region-line.selected .resize-handle { pointer-events: auto; }.region-line .region-label,.region-line .resize-handle { background: #6d28d9; }
|
||||
.line-hit-edge { position: absolute; z-index: 2; display: block; }.line-hit-n,.line-hit-s { right: -6px; left: -6px; height: 12px; cursor: move; }.line-hit-e,.line-hit-w { top: 6px; bottom: 6px; width: 12px; cursor: move; }.line-hit-n { top: -6px; }.line-hit-e { right: -6px; }.line-hit-s { bottom: -6px; }.line-hit-w { left: -6px; }
|
||||
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }.region-exclusion .region-label,.region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region:not(.selected) .resize-handle { display: none; }.region.selected { outline: 3px solid white; outline-offset: 2px; }.region.selected:not(.region-line) { z-index: 4; }
|
||||
.resize-handle { position: absolute; z-index: 3; width: 10px; height: 10px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; }
|
||||
.handle-n, .handle-s { left: 50%; margin-left: -5px; cursor: ns-resize; }
|
||||
.handle-e, .handle-w { top: 50%; margin-top: -5px; cursor: ew-resize; }
|
||||
.handle-nw, .handle-se { cursor: nwse-resize; }
|
||||
.handle-ne, .handle-sw { cursor: nesw-resize; }
|
||||
.handle-n, .handle-nw, .handle-ne { top: -6px; }
|
||||
.handle-s, .handle-sw, .handle-se { bottom: -6px; }
|
||||
.handle-e, .handle-ne, .handle-se { right: -6px; }
|
||||
.handle-w, .handle-nw, .handle-sw { left: -6px; }
|
||||
.region-header_field { z-index: 2; border: 1.5px solid #f59e0b; background: rgb(245 158 11 / .08); }
|
||||
.region-header_field .region-label, .region-header_field .resize-handle { background: #b45309; }
|
||||
.region-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }
|
||||
.region-order_field .region-label, .region-order_field .resize-handle { background: #15803d; }
|
||||
.region-order_anchor { z-index: 2; border: 1.5px solid #a855f7; background: rgb(168 85 247 / .08); }
|
||||
.region-order_anchor .region-label, .region-order_anchor .resize-handle { background: #7e22ce; }
|
||||
.region-line { z-index: 0; border-color: #a78bfa; background: rgb(167 139 250 / .1); pointer-events: none; }
|
||||
.region-line .region-label, .region-line .line-hit-edge, .region-line.selected .resize-handle { pointer-events: auto; }
|
||||
.region-line .region-label, .region-line .resize-handle { background: #6d28d9; }
|
||||
.line-hit-edge { position: absolute; z-index: 2; display: block; }
|
||||
.line-hit-n, .line-hit-s { right: -6px; left: -6px; height: 12px; cursor: move; }
|
||||
.line-hit-e, .line-hit-w { top: 6px; bottom: 6px; width: 12px; cursor: move; }
|
||||
.line-hit-n { top: -6px; }
|
||||
.line-hit-e { right: -6px; }
|
||||
.line-hit-s { bottom: -6px; }
|
||||
.line-hit-w { left: -6px; }
|
||||
.region-exclusion { z-index: 3; border-style: dashed; border-color: #f87171; background: rgb(248 113 113 / .1); }
|
||||
.region-exclusion .region-label, .region-exclusion .resize-handle { background: #b91c1c; }
|
||||
.region:not(.selected) .resize-handle { display: none; }
|
||||
.region.selected { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region.selected:not(.region-line) { z-index: 4; }
|
||||
.canvas-stage.drawing .region { pointer-events: none; }
|
||||
@media (max-width: 900px) { .canvas-toolbar { grid-template-columns: 1fr auto; }.page-control { grid-column: 1 / -1; grid-row: 2; }.zoom-control { justify-self: end; }.canvas-stage { min-width: 32rem; }.canvas-viewport { max-height: 32rem; } } @media (max-width: 640px) { .canvas-shell { min-height: 24rem; padding-inline: .5rem; }.canvas-toolbar { margin-inline: -.5rem; padding-inline: .5rem; }.toolbar-actions .save-action span,.fit-action { display: none; }.annotation-tools { flex-basis: 2.45rem; }.annotation-tools button span,.suggestion-progress { display: none; } }
|
||||
@media (max-width: 900px) {
|
||||
.canvas-toolbar { grid-template-columns: 1fr auto; }
|
||||
.page-control { grid-column: 1 / -1; grid-row: 2; }
|
||||
.zoom-control { justify-self: end; }
|
||||
.canvas-stage { min-width: 32rem; }
|
||||
.canvas-viewport { max-height: 32rem; }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.canvas-shell { min-height: 24rem; padding-inline: .5rem; }
|
||||
.canvas-toolbar { margin-inline: -.5rem; padding-inline: .5rem; }
|
||||
.toolbar-actions .save-action span, .fit-action { display: none; }
|
||||
.annotation-tools { flex-basis: 2.45rem; }
|
||||
.annotation-tools button span, .suggestion-progress { display: none; }
|
||||
}
|
||||
.tools-toggle span { display: none; }
|
||||
</style>
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileFrozenEvidencePanel.vue
|
||||
用途:展示当前只读样本绑定的冻结证据信息。
|
||||
依赖:版本详情样本 DTO、i18n。
|
||||
逻辑:只渲染冻结身份与快照摘要,不泄露正文、对象存储地址或盲测真值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { OrderProfileBoundSample } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
|
||||
const props = defineProps<{
|
||||
sample: OrderProfileBoundSample | null;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const frozenStatus = computed(() => (
|
||||
props.sample?.frozen_evidence_ready
|
||||
? t('admin.shippingOrderProfiles.versionCenter.frozenEvidence.ready')
|
||||
: t('admin.shippingOrderProfiles.versionCenter.frozenEvidence.missing')
|
||||
));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="panel">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.versionCenter.frozenEvidencePanelTitle') }}</h3>
|
||||
<p v-if="!sample" class="empty">{{ t('admin.shippingOrderProfiles.versionCenter.selectSampleHint') }}</p>
|
||||
<dl v-else class="grid">
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.statusLabel') }}</dt>
|
||||
<dd>{{ frozenStatus }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.sampleFile') }}</dt>
|
||||
<dd>{{ sample.source_filename_snapshot || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.layoutVersionId') }}</dt>
|
||||
<dd>{{ sample.layout_version_id || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.evidenceFrozenAt') }}</dt>
|
||||
<dd>{{ sample.evidence_frozen_at || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.pageCountPlain') }}</dt>
|
||||
<dd>{{ sample.page_count_snapshot || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.parserIdentity') }}</dt>
|
||||
<dd>{{ sample.parser_name || sample.parser_key || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.parserVersionTitle') }}</dt>
|
||||
<dd>{{ sample.parser_version || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.frozenTableId') }}</dt>
|
||||
<dd>{{ sample.table_identity_snapshot?.table_id || sample.table_id || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.frozenPageNo') }}</dt>
|
||||
<dd>{{ sample.table_identity_snapshot?.page_no || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.frozenRowCount') }}</dt>
|
||||
<dd>{{ sample.table_identity_snapshot?.row_count || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.layoutChecksumTitle') }}</dt>
|
||||
<dd><code>{{ sample.layout_payload_checksum || '-' }}</code></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.contentHashTitle') }}</dt>
|
||||
<dd><code>{{ sample.source_content_hash || '-' }}</code></dd>
|
||||
</div>
|
||||
</dl>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.panel {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 1rem;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.panel h3 {
|
||||
margin: 0;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 0.85rem 0 0;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 0.85rem;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
margin: 0.9rem 0 0;
|
||||
}
|
||||
|
||||
.grid dt {
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.grid dd {
|
||||
margin: 0.3rem 0 0;
|
||||
color: #0f172a;
|
||||
word-break: break-word;
|
||||
}
|
||||
</style>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileIdentityStep.vue
|
||||
用途:收集创建向导第一步的模板身份与 Schema。
|
||||
依赖:Schema DTO、Vue I18n。
|
||||
逻辑:仅双向绑定浏览器状态,不调用创建 API,profile_code 在完成后由服务端永久冻结。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderSchemaVersion } from '@/features/admin/types/shipping-order-schema.types';
|
||||
const props = defineProps<{ modelValue: { displayName: string; profileCode: string; schemaId: number }; schemas: ShippingOrderSchemaVersion[] }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: { displayName: string; profileCode: string; schemaId: number }] }>();
|
||||
const { t } = useI18n();
|
||||
const publishedSchemas = computed(() => props.schemas.filter((item) => item.status === 'published'));
|
||||
/** 更新单个身份字段但不触发创建;向导刷新前没有正式 Profile。 */
|
||||
function update(key: 'displayName' | 'profileCode' | 'schemaId', value: string | number): void { emit('update:modelValue', { ...props.modelValue, [key]: value }); }
|
||||
</script>
|
||||
<template><div class="wizard-step"><label>{{ t('admin.shippingOrderProfiles.name') }}<input :value="modelValue.displayName" @input="update('displayName', ($event.target as HTMLInputElement).value)"></label><label>{{ t('admin.shippingOrderProfiles.code') }}<input :value="modelValue.profileCode" @input="update('profileCode', ($event.target as HTMLInputElement).value.toUpperCase())"></label><small>{{ t('admin.shippingOrderProfiles.wizard.codeHint') }}</small><label>{{ t('admin.shippingOrderProfiles.schema') }}<select :value="modelValue.schemaId" @change="update('schemaId', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.wizard.selectSchema') }}</option><option v-for="schema in publishedSchemas" :key="schema.id" :value="schema.id">v{{ schema.version }}</option></select></label></div></template>
|
||||
<style scoped>.wizard-step{display:grid;gap:1rem;max-width:36rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step input,.wizard-step select{padding:.6rem;border:1px solid #cbd5e1;border-radius:.4rem}small{color:#64748b}</style>
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileModelStartStep.vue
|
||||
用途:确认样本文档中作为建模起点的主表格。
|
||||
依赖:样本表格预览 DTO、Vue I18n。
|
||||
逻辑:只让用户选定服务端已发现的 table_id;缺少有效表格时禁止完成向导。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
const props = defineProps<{ tables: Array<{ table_id: string; page_no: number; row_count: number; column_count: number; rows: string[][] }>; modelValue: string }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: string] }>();
|
||||
const { t } = useI18n();
|
||||
</script>
|
||||
<template><div class="wizard-step"><label>{{ t('admin.shippingOrderProfiles.table') }}<select :value="modelValue" @change="emit('update:modelValue', ($event.target as HTMLSelectElement).value)"><option value="">{{ t('admin.shippingOrderProfiles.selectTable') }}</option><option v-for="table in tables" :key="table.table_id" :value="table.table_id">{{ t('admin.shippingOrderProfiles.wizard.tableOption', { page: table.page_no, rows: table.row_count, columns: table.column_count }) }}</option></select></label><p v-if="!tables.length">{{ t('admin.shippingOrderProfiles.wizard.noTable') }}</p><table v-else-if="modelValue"><tbody><tr v-for="row in tables.find((item) => item.table_id === modelValue)?.rows.slice(0, 4) || []" :key="row.join('|')"><td v-for="cell in row" :key="cell">{{ cell }}</td></tr></tbody></table></div></template>
|
||||
<style scoped>.wizard-step{display:grid;gap:1rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step select{padding:.6rem;border:1px solid #cbd5e1;border-radius:.4rem}table{border-collapse:collapse}td{padding:.35rem;border:1px solid #e2e8f0}p{color:#b45309}</style>
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileReadOnlyCanvas.vue
|
||||
用途:在版本详情页展示基于冻结样本绑定的只读画布。
|
||||
依赖:冻结样本预览 API、OrderProfileDocumentCanvas、冻结证据面板。
|
||||
逻辑:只允许 annotation/training 样本进入普通画布;blind_test 继续留在摘要层,不进入样本选择器。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { authorizeOrderProfileFrozenSamplePreviewPages } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
import type {
|
||||
OrderProfileBoundSample,
|
||||
OrderProfilePreviewPages,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import OrderProfileDocumentCanvas from './OrderProfileDocumentCanvas.vue';
|
||||
import OrderProfileFrozenEvidencePanel from './OrderProfileFrozenEvidencePanel.vue';
|
||||
import { buildOrderProfileReadonlyRegions } from '../orderProfileReadonlyCanvas.utils';
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref('');
|
||||
const selectedSampleId = ref<number | null>(null);
|
||||
const selectedRegionId = ref<string | null>(null);
|
||||
const previewPages = ref<OrderProfilePreviewPages | null>(null);
|
||||
const pageNo = ref(1);
|
||||
|
||||
const readonlySamples = computed(() =>
|
||||
(props.detail.sample_summary?.samples || []).filter((sample) => sample.sample_role !== 'blind_test'),
|
||||
);
|
||||
const selectedSample = computed<OrderProfileBoundSample | null>(() =>
|
||||
readonlySamples.value.find((sample) => sample.id === selectedSampleId.value) || null,
|
||||
);
|
||||
const readonlyRegions = computed(() => buildOrderProfileReadonlyRegions(props.detail));
|
||||
const pageRegions = computed(() => readonlyRegions.value.filter((region) => region.pageNo === pageNo.value));
|
||||
const selectedRegion = computed(() => pageRegions.value.find((region) => region.id === selectedRegionId.value) || null);
|
||||
const currentGrant = computed(() =>
|
||||
previewPages.value?.pages.find((item) => item.page_no === pageNo.value) || null,
|
||||
);
|
||||
const previewPagePath = computed(() => (
|
||||
props.detail.id && selectedSample.value
|
||||
? `/api/admin/shipping-notice/order-document-profiles/${props.detail.id}/samples/${selectedSample.value.id}/preview-pages`
|
||||
: null
|
||||
));
|
||||
const immutable = computed(() => props.detail.status !== 'draft');
|
||||
|
||||
const sampleLabel = (sample: OrderProfileBoundSample) => {
|
||||
const tableLabel = sample.table_identity_snapshot?.table_id || sample.table_id || '-';
|
||||
return `${sample.source_filename_snapshot || `#${sample.id}`} · ${tableLabel}`;
|
||||
};
|
||||
|
||||
const loadPreview = async (sampleId: number | null) => {
|
||||
if (!sampleId || !immutable.value) {
|
||||
previewPages.value = null;
|
||||
errorMessage.value = '';
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
errorMessage.value = '';
|
||||
selectedRegionId.value = null;
|
||||
try {
|
||||
const payload = await authorizeOrderProfileFrozenSamplePreviewPages(props.detail.id, sampleId);
|
||||
previewPages.value = payload;
|
||||
const preferredPage = selectedSample.value?.table_identity_snapshot?.page_no || 1;
|
||||
pageNo.value = Math.max(1, Math.min(payload.page_count || 1, preferredPage));
|
||||
} catch (error) {
|
||||
previewPages.value = null;
|
||||
errorMessage.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('admin.shippingOrderProfiles.versionCenter.canvasLoadFailed');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.detail.id,
|
||||
() => {
|
||||
const firstReady = readonlySamples.value.find((sample) => sample.frozen_evidence_ready) || readonlySamples.value[0] || null;
|
||||
selectedSampleId.value = firstReady?.id || null;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(selectedSampleId, (value) => {
|
||||
void loadPreview(value);
|
||||
}, { immediate: true });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="readonly-layout">
|
||||
<div v-if="!immutable" class="state-card">
|
||||
{{ t('admin.shippingOrderProfiles.versionCenter.draftCanvasHint') }}
|
||||
</div>
|
||||
<div v-else-if="!readonlySamples.length" class="state-card">
|
||||
{{ t('admin.shippingOrderProfiles.versionCenter.noReadableSamples') }}
|
||||
</div>
|
||||
<template v-else>
|
||||
<div class="toolbar">
|
||||
<label class="field">
|
||||
<span>{{ t('admin.shippingOrderProfiles.versionCenter.readonlySample') }}</span>
|
||||
<select v-model.number="selectedSampleId">
|
||||
<option v-for="sample in readonlySamples" :key="sample.id" :value="sample.id">
|
||||
{{ sampleLabel(sample) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<p v-if="selectedSample && !selectedSample.frozen_evidence_ready" class="warning-text">
|
||||
{{ t('admin.shippingOrderProfiles.versionCenter.sampleFrozenEvidenceMissing') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="errorMessage" class="state-card error-card">{{ errorMessage }}</div>
|
||||
<div v-else-if="loading" class="state-card">{{ t('admin.shippingOrderProfiles.versionCenter.loadingCanvas') }}</div>
|
||||
<div v-else-if="selectedSample && currentGrant" class="canvas-grid">
|
||||
<OrderProfileDocumentCanvas
|
||||
:profile-id="detail.id"
|
||||
:grant="currentGrant"
|
||||
:mode="'readonly'"
|
||||
:preview-page-path="previewPagePath"
|
||||
:regions="pageRegions"
|
||||
:selected-region-id="selectedRegionId"
|
||||
:page-no="pageNo"
|
||||
:page-count="previewPages?.page_count || 1"
|
||||
@select="selectedRegionId = $event"
|
||||
@page="pageNo = $event"
|
||||
/>
|
||||
<div class="side-panel">
|
||||
<OrderProfileFrozenEvidencePanel :sample="selectedSample" />
|
||||
<section class="panel">
|
||||
<h3>{{ t('admin.shippingOrderProfiles.versionCenter.regionSummaryTitle') }}</h3>
|
||||
<p v-if="!selectedRegion" class="empty">{{ t('admin.shippingOrderProfiles.versionCenter.selectRegionHint') }}</p>
|
||||
<dl v-else class="grid">
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionLabelTitle') }}</dt>
|
||||
<dd>{{ selectedRegion.label }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionKindTitle') }}</dt>
|
||||
<dd>{{ selectedRegion.kind }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionFieldCodeTitle') }}</dt>
|
||||
<dd>{{ selectedRegion.fieldCode || '-' }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t('admin.shippingOrderProfiles.versionCenter.regionPageTitle') }}</dt>
|
||||
<dd>{{ selectedRegion.pageNo }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.readonly-layout {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.toolbar,
|
||||
.state-card,
|
||||
.panel {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 1rem;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.field span {
|
||||
color: #475569;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.field select {
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.7rem;
|
||||
min-height: 2.5rem;
|
||||
padding: 0 0.75rem;
|
||||
}
|
||||
|
||||
.canvas-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: minmax(0, 1fr) 320px;
|
||||
}
|
||||
|
||||
.side-panel {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
margin: 0.85rem 0 0;
|
||||
}
|
||||
|
||||
.grid dt {
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.grid dd {
|
||||
margin: 0.25rem 0 0;
|
||||
color: #0f172a;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.warning-text {
|
||||
margin: 0;
|
||||
color: #b45309;
|
||||
}
|
||||
|
||||
.error-card {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.empty {
|
||||
margin: 0.75rem 0 0;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
@media (max-width: 1180px) {
|
||||
.canvas-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileSampleStep.vue
|
||||
用途:选择或上传模板样本,并显示其异步解析状态。
|
||||
依赖:模板样本 API、文件资产上传 API、Vue I18n。
|
||||
逻辑:上传只创建样本库 Intake;此步骤不创建 Profile,解析完成后才允许选择样本文档。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { uploadFileAsset } from '@/shared/api/file-assets.api';
|
||||
import { createOrderProfileSample } from '@/features/admin/api/shipping-order-document-profile.api';
|
||||
const props = defineProps<{ samples: Array<{ document_id: number; filename?: string | null; table_count: number; intake_no: string }>; modelValue: number }>();
|
||||
const emit = defineEmits<{ 'update:modelValue': [value: number]; uploaded: [] }>();
|
||||
const { t } = useI18n(); const message = useMessage(); const uploading = ref(false);
|
||||
/** 上传文件后仅投递样本解析;父级轮询并刷新可选样本列表。 */
|
||||
async function upload(event: Event): Promise<void> { const file = (event.target as HTMLInputElement).files?.[0]; if (!file) return; if (!/\.(pdf|eml)$/i.test(file.name)) { message.error(t('admin.shippingOrderProfiles.sampleFileTypeInvalid')); return; } uploading.value = true; try { const asset = await uploadFileAsset(file); await createOrderProfileSample(asset.asset_no); emit('uploaded'); } catch (error) { message.error(error instanceof BusinessError ? error.message : t('admin.shippingOrderProfiles.wizard.uploadFailed')); } finally { uploading.value = false; } }
|
||||
</script>
|
||||
<template><div class="wizard-step"><label>{{ t('admin.shippingOrderProfiles.uploadSample') }}<input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploading" @change="upload"></label><p>{{ t('admin.shippingOrderProfiles.wizard.sampleHint') }}</p><label>{{ t('admin.shippingOrderProfiles.selectSample') }}<select :value="modelValue" @change="emit('update:modelValue', Number(($event.target as HTMLSelectElement).value))"><option :value="0">{{ t('admin.shippingOrderProfiles.selectSample') }}</option><option v-for="sample in samples" :key="sample.document_id" :value="sample.document_id">{{ sample.filename || sample.intake_no }} · {{ sample.table_count }} {{ t('admin.shippingOrderProfiles.tablesUnit') }}</option></select></label></div></template>
|
||||
<style scoped>.wizard-step{display:grid;gap:1rem;max-width:36rem}.wizard-step label{display:grid;gap:.35rem;font-weight:600}.wizard-step select{padding:.6rem;border:1px solid #cbd5e1;border-radius:.4rem}p{margin:0;color:#64748b}</style>
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileUsageTable.vue
|
||||
用途:展示订单模板版本的实际使用记录,并提供进入只读 Run 审计的入口。
|
||||
依赖:版本中心 usage API、Vue Router。
|
||||
逻辑:只读取每个 Unit 最新 RouteDecision 的安全投影;点击行跳转到管理员 Run 诊断页,不在当前页改动任何业务状态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import { listOrderDocumentProfileUsages } from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import type {
|
||||
OrderProfileUsagePage,
|
||||
OrderProfileUsageRow,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
const props = defineProps<{ detail: ShippingOrderDocumentProfile }>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref("");
|
||||
const page = ref<OrderProfileUsagePage | null>(null);
|
||||
const cursorStack = ref<Array<number | null>>([]);
|
||||
const activeBeforeId = ref<number | null>(null);
|
||||
|
||||
const hasPrevious = computed(() => cursorStack.value.length > 0);
|
||||
const hasNext = computed(() => Boolean(page.value?.page.has_more && page.value?.page.next_before_id));
|
||||
|
||||
const formatTime = (value?: string | null) => value ? new Date(value).toLocaleString() : "-";
|
||||
|
||||
const translateUsageValue = (scope: "runStatuses" | "matchStatuses" | "executionStatuses" | "identityModes", value: string) =>
|
||||
t(`admin.shippingOrderProfiles.versionCenter.usage.${scope}.${value}`, value);
|
||||
|
||||
const load = async () => {
|
||||
loading.value = true;
|
||||
errorMessage.value = "";
|
||||
try {
|
||||
page.value = await listOrderDocumentProfileUsages(props.detail.id, {
|
||||
beforeId: activeBeforeId.value,
|
||||
limit: 20,
|
||||
});
|
||||
} catch (error) {
|
||||
page.value = null;
|
||||
errorMessage.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t("admin.shippingOrderProfiles.versionCenter.usage.loadFailed");
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadNext = async () => {
|
||||
if (!page.value?.page.next_before_id) return;
|
||||
cursorStack.value.push(activeBeforeId.value);
|
||||
activeBeforeId.value = page.value.page.next_before_id;
|
||||
await load();
|
||||
};
|
||||
|
||||
const loadPrevious = async () => {
|
||||
if (!cursorStack.value.length) return;
|
||||
activeBeforeId.value = cursorStack.value.pop() ?? null;
|
||||
await load();
|
||||
};
|
||||
|
||||
const openDiagnostic = (item: OrderProfileUsageRow) => {
|
||||
void router.push({
|
||||
name: item.diagnostic_entry.route_name,
|
||||
query: {
|
||||
runNo: item.diagnostic_entry.run_no,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.detail.id,
|
||||
() => {
|
||||
activeBeforeId.value = null;
|
||||
cursorStack.value = [];
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="usage-panel">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.usage.title") }}</h3>
|
||||
<p>{{ t("admin.shippingOrderProfiles.versionCenter.usage.subtitle") }}</p>
|
||||
</div>
|
||||
<button type="button" class="ghost-button" :disabled="loading" @click="load">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.usage.refresh") }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.usage.loading") }}
|
||||
</div>
|
||||
<div v-else-if="errorMessage" class="state-card error-card">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
<div v-else-if="!page?.items.length" class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.usage.empty") }}
|
||||
</div>
|
||||
<div v-else class="table-wrapper">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.runNo") }}</th>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.document") }}</th>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.matchStatus") }}</th>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.executionStatus") }}</th>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.identityMode") }}</th>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.autoCreateApproved") }}</th>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.createdAt") }}</th>
|
||||
<th>{{ t("admin.shippingOrderProfiles.versionCenter.usage.columns.reasonCodes") }}</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in page.items" :key="item.route_decision_id">
|
||||
<td>
|
||||
<div class="cell-title">{{ item.run_no }}</div>
|
||||
<small>{{ translateUsageValue("runStatuses", item.run_status) }}</small>
|
||||
</td>
|
||||
<td>
|
||||
<div class="cell-title">{{ item.document_label }}</div>
|
||||
<small>#{{ item.unit_position + 1 }}</small>
|
||||
</td>
|
||||
<td>{{ translateUsageValue("matchStatuses", item.match_status) }}</td>
|
||||
<td>{{ translateUsageValue("executionStatuses", item.execution_status) }}</td>
|
||||
<td>{{ translateUsageValue("identityModes", item.identity_match_mode) }}</td>
|
||||
<td>
|
||||
{{
|
||||
item.auto_create_approved == null
|
||||
? "-"
|
||||
: t(item.auto_create_approved
|
||||
? "admin.shippingOrderProfiles.versionCenter.usage.yes"
|
||||
: "admin.shippingOrderProfiles.versionCenter.usage.no")
|
||||
}}
|
||||
</td>
|
||||
<td>{{ formatTime(item.created_at) }}</td>
|
||||
<td>
|
||||
<span v-if="item.reason_codes.length">{{ item.reason_codes.join(", ") }}</span>
|
||||
<span v-else>-</span>
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" class="link-button" @click="openDiagnostic(item)">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.usage.openDiagnostic") }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div class="pager">
|
||||
<button type="button" class="ghost-button" :disabled="loading || !hasPrevious" @click="loadPrevious">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.usage.previous") }}
|
||||
</button>
|
||||
<button type="button" class="ghost-button" :disabled="loading || !hasNext" @click="loadNext">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.usage.next") }}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.usage-panel,
|
||||
.toolbar,
|
||||
.table-wrapper,
|
||||
.state-card {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 1rem;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.usage-panel {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.toolbar,
|
||||
.state-card,
|
||||
.table-wrapper {
|
||||
padding: 0.95rem 1rem;
|
||||
}
|
||||
|
||||
.toolbar,
|
||||
.pager {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.toolbar h3 {
|
||||
margin: 0;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.toolbar p {
|
||||
margin: 0.25rem 0 0;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.ghost-button,
|
||||
.link-button {
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.75rem;
|
||||
background: #fff;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.link-button {
|
||||
color: #2563eb;
|
||||
}
|
||||
|
||||
.table-wrapper {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 980px;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
thead {
|
||||
background: #f8fafc;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
padding: 0.75rem;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
|
||||
.cell-title {
|
||||
color: #0f172a;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
td small {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.error-card {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.toolbar,
|
||||
.pager {
|
||||
display: grid;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
+436
@@ -0,0 +1,436 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileVersionDiff.vue
|
||||
用途:展示订单模板版本中心的服务端语义 diff。
|
||||
依赖:版本中心 diff API、路由 query、版本摘要列表。
|
||||
逻辑:始终由服务端计算差异;前端只负责选择对比版本、呈现 summary 和折叠原始 JSON 快照。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import { getOrderDocumentProfileDiff } from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import type {
|
||||
OrderProfileVersionDiff,
|
||||
OrderProfileVersionDiffChange,
|
||||
OrderProfileVersionDiffItem,
|
||||
OrderProfileVersionSummary,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
versions: OrderProfileVersionSummary[];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const errorMessage = ref("");
|
||||
const diff = ref<OrderProfileVersionDiff | null>(null);
|
||||
|
||||
const explicitAgainstProfileId = computed<number | null>(() => {
|
||||
const raw = Number(route.query.againstProfileId || 0);
|
||||
return Number.isFinite(raw) && raw > 0 ? raw : null;
|
||||
});
|
||||
|
||||
const comparableVersions = computed(() =>
|
||||
props.versions.filter((item) => item.id !== props.detail.id),
|
||||
);
|
||||
|
||||
const changedItems = computed(() =>
|
||||
(diff.value?.items || []).filter((item) => item.change_type !== "unchanged"),
|
||||
);
|
||||
|
||||
const selectedAgainstProfileId = computed<number | null>(() =>
|
||||
explicitAgainstProfileId.value ?? diff.value?.compare_profile?.id ?? null,
|
||||
);
|
||||
|
||||
const comparisonTargetLabel = computed(() => {
|
||||
const target = comparableVersions.value.find((item) => item.id === selectedAgainstProfileId.value)
|
||||
|| diff.value?.compare_profile
|
||||
|| null;
|
||||
if (!target) {
|
||||
return t("admin.shippingOrderProfiles.versionCenter.diff.initialVersion");
|
||||
}
|
||||
return `v${target.version} · ${t(`admin.shippingOrderProfiles.versionCenter.status.${target.status === "draft" ? "currentDraft" : target.status === "published" ? "currentPublished" : "retired"}`)}`;
|
||||
});
|
||||
|
||||
const entityTypeLabel = (item: OrderProfileVersionDiffItem) =>
|
||||
t(`admin.shippingOrderProfiles.versionCenter.diff.entityType.${item.entity_type}`);
|
||||
|
||||
const changeTypeLabel = (value: OrderProfileVersionDiffItem["change_type"]) =>
|
||||
t(`admin.shippingOrderProfiles.versionCenter.diff.changeType.${value}`);
|
||||
|
||||
const changeLabel = (change: OrderProfileVersionDiffChange) => change.key;
|
||||
|
||||
const valueText = (value: unknown) => {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return t("admin.shippingOrderProfiles.versionCenter.diff.empty");
|
||||
}
|
||||
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
||||
return String(value);
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(value, null, 2);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
};
|
||||
|
||||
const syncAgainstProfileId = (againstProfileId: number | null) => {
|
||||
const query = { ...route.query };
|
||||
if (againstProfileId) {
|
||||
query.againstProfileId = String(againstProfileId);
|
||||
} else {
|
||||
delete query.againstProfileId;
|
||||
}
|
||||
void router.replace({ query });
|
||||
};
|
||||
|
||||
const handleAgainstChange = (event: Event) => {
|
||||
const value = Number((event.target as HTMLSelectElement).value || 0);
|
||||
syncAgainstProfileId(Number.isFinite(value) && value > 0 ? value : null);
|
||||
};
|
||||
|
||||
const load = async () => {
|
||||
loading.value = true;
|
||||
errorMessage.value = "";
|
||||
try {
|
||||
diff.value = await getOrderDocumentProfileDiff(props.detail.id, explicitAgainstProfileId.value);
|
||||
} catch (error) {
|
||||
diff.value = null;
|
||||
errorMessage.value =
|
||||
error instanceof BusinessError
|
||||
? error.message
|
||||
: t("admin.shippingOrderProfiles.versionCenter.diff.loadFailed");
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => [props.detail.id, explicitAgainstProfileId.value],
|
||||
() => {
|
||||
void load();
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="diff-panel">
|
||||
<div class="toolbar">
|
||||
<div>
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.diff.title") }}</h3>
|
||||
<p>{{ t("admin.shippingOrderProfiles.versionCenter.diff.subtitle") }}</p>
|
||||
</div>
|
||||
<label class="compare-select">
|
||||
<span>{{ t("admin.shippingOrderProfiles.versionCenter.diff.compareTarget") }}</span>
|
||||
<select
|
||||
:value="explicitAgainstProfileId || ''"
|
||||
@change="handleAgainstChange"
|
||||
>
|
||||
<option value="">{{ t("admin.shippingOrderProfiles.versionCenter.diff.defaultPrevious") }}</option>
|
||||
<option
|
||||
v-for="item in comparableVersions"
|
||||
:key="item.id"
|
||||
:value="item.id"
|
||||
>
|
||||
v{{ item.version }} · {{ t(`admin.shippingOrderProfiles.versionCenter.status.${item.status === "draft" ? "currentDraft" : item.status === "published" ? "currentPublished" : "retired"}`) }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.diff.loading") }}
|
||||
</div>
|
||||
<div v-else-if="errorMessage" class="state-card error-card">
|
||||
{{ errorMessage }}
|
||||
</div>
|
||||
<template v-else-if="diff">
|
||||
<div class="summary-bar">
|
||||
<span class="summary-target">{{ t("admin.shippingOrderProfiles.versionCenter.diff.comparedWith", { target: comparisonTargetLabel }) }}</span>
|
||||
<span class="summary-pill added">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.added", { count: diff.summary.added }) }}</span>
|
||||
<span class="summary-pill removed">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.removed", { count: diff.summary.removed }) }}</span>
|
||||
<span class="summary-pill modified">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.modified", { count: diff.summary.modified }) }}</span>
|
||||
<span class="summary-pill unchanged">{{ t("admin.shippingOrderProfiles.versionCenter.diff.summary.unchanged", { count: diff.summary.unchanged }) }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!changedItems.length" class="state-card">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.diff.noChanges") }}
|
||||
</div>
|
||||
|
||||
<article
|
||||
v-for="item in changedItems"
|
||||
:key="`${item.entity_type}:${item.entity_id}:${item.parent_id || ''}`"
|
||||
class="diff-item"
|
||||
:class="item.change_type"
|
||||
>
|
||||
<header>
|
||||
<div>
|
||||
<p>{{ entityTypeLabel(item) }}</p>
|
||||
<h4>{{ item.label }}</h4>
|
||||
</div>
|
||||
<span class="change-type">{{ changeTypeLabel(item.change_type) }}</span>
|
||||
</header>
|
||||
|
||||
<dl v-if="item.changes.length" class="change-list">
|
||||
<div
|
||||
v-for="change in item.changes"
|
||||
:key="change.key"
|
||||
>
|
||||
<dt><code>{{ changeLabel(change) }}</code></dt>
|
||||
<dd>
|
||||
<template v-if="change.kind === 'set'">
|
||||
<div class="change-pair"><del>{{ valueText(change.before) }}</del><ins>{{ valueText(change.after) }}</ins></div>
|
||||
<small v-if="change.added?.length">{{ t("admin.shippingOrderProfiles.versionCenter.diff.addedValues", { values: change.added.join(', ') }) }}</small>
|
||||
<small v-if="change.removed?.length">{{ t("admin.shippingOrderProfiles.versionCenter.diff.removedValues", { values: change.removed.join(', ') }) }}</small>
|
||||
<small v-if="change.order_changed">{{ t("admin.shippingOrderProfiles.versionCenter.diff.orderChanged") }}</small>
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="change-pair"><del>{{ valueText(change.before) }}</del><ins>{{ valueText(change.after) }}</ins></div>
|
||||
</template>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<details class="raw-json">
|
||||
<summary>{{ t("admin.shippingOrderProfiles.versionCenter.diff.rawJson") }}</summary>
|
||||
<div class="raw-json-grid">
|
||||
<section>
|
||||
<h5>{{ t("admin.shippingOrderProfiles.versionCenter.diff.beforeSnapshot") }}</h5>
|
||||
<pre>{{ valueText(item.before_snapshot) }}</pre>
|
||||
</section>
|
||||
<section>
|
||||
<h5>{{ t("admin.shippingOrderProfiles.versionCenter.diff.afterSnapshot") }}</h5>
|
||||
<pre>{{ valueText(item.after_snapshot) }}</pre>
|
||||
</section>
|
||||
</div>
|
||||
</details>
|
||||
</article>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.diff-panel,
|
||||
.toolbar,
|
||||
.summary-bar,
|
||||
.diff-item,
|
||||
.state-card {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 1rem;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.diff-panel {
|
||||
display: grid;
|
||||
gap: 0.9rem;
|
||||
}
|
||||
|
||||
.toolbar,
|
||||
.summary-bar,
|
||||
.state-card,
|
||||
.diff-item {
|
||||
padding: 0.95rem 1rem;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.toolbar h3,
|
||||
.diff-item h4,
|
||||
.raw-json h5 {
|
||||
margin: 0;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.toolbar p,
|
||||
.diff-item header p {
|
||||
margin: 0 0 0.3rem;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.compare-select {
|
||||
display: grid;
|
||||
gap: 0.35rem;
|
||||
color: #475569;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.compare-select select {
|
||||
min-width: 220px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 0.75rem;
|
||||
background: #fff;
|
||||
padding: 0.5rem 0.75rem;
|
||||
color: #0f172a;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.summary-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.summary-target {
|
||||
margin-right: 0.5rem;
|
||||
color: #334155;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.summary-pill,
|
||||
.change-type {
|
||||
border-radius: 999px;
|
||||
padding: 0.2rem 0.55rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.summary-pill.added,
|
||||
.diff-item.added .change-type {
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.summary-pill.removed,
|
||||
.diff-item.removed .change-type {
|
||||
background: #fee2e2;
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.summary-pill.modified,
|
||||
.diff-item.modified .change-type {
|
||||
background: #dbeafe;
|
||||
color: #1d4ed8;
|
||||
}
|
||||
|
||||
.summary-pill.unchanged,
|
||||
.diff-item.unchanged .change-type {
|
||||
background: #e2e8f0;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.diff-item {
|
||||
border-left-width: 4px;
|
||||
}
|
||||
|
||||
.diff-item.added { border-left-color: #22c55e; }
|
||||
.diff-item.removed { border-left-color: #ef4444; }
|
||||
.diff-item.modified { border-left-color: #3b82f6; }
|
||||
|
||||
.diff-item header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.change-list {
|
||||
display: grid;
|
||||
gap: 0.8rem;
|
||||
margin: 0.95rem 0 0;
|
||||
}
|
||||
|
||||
.change-list div {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(180px, 260px) minmax(0, 1fr);
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.change-list dt {
|
||||
color: #475569;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.change-list dd {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
margin: 0;
|
||||
color: #334155;
|
||||
font-size: 0.82rem;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.change-pair {
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
del {
|
||||
color: #b91c1c;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
ins {
|
||||
color: #15803d;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.change-list small {
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.raw-json {
|
||||
margin-top: 0.9rem;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
padding-top: 0.9rem;
|
||||
}
|
||||
|
||||
.raw-json summary {
|
||||
cursor: pointer;
|
||||
color: #334155;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.raw-json-grid {
|
||||
display: grid;
|
||||
gap: 0.85rem;
|
||||
margin-top: 0.75rem;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
|
||||
.raw-json pre {
|
||||
margin: 0.45rem 0 0;
|
||||
border-radius: 0.75rem;
|
||||
background: #0f172a;
|
||||
padding: 0.75rem;
|
||||
color: #e2e8f0;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.45;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.error-card {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.toolbar,
|
||||
.diff-item header,
|
||||
.change-list div,
|
||||
.raw-json-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.toolbar,
|
||||
.diff-item header {
|
||||
display: grid;
|
||||
}
|
||||
|
||||
.compare-select select {
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileVersionDrawer.vue
|
||||
用途:将模板历史收进可开合抽屉,避免版本列表占据标注工作面。
|
||||
依赖:ShippingOrderDocumentProfile DTO。
|
||||
逻辑:父页面负责版本动作和盲测流程;抽屉只发出用户意图。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { ShippingOrderDocumentProfile } from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
defineProps<{ open: boolean; profiles: ShippingOrderDocumentProfile[] }>();
|
||||
const { t } = useI18n();
|
||||
defineEmits<{ close: []; edit: [profile: ShippingOrderDocumentProfile]; publish: [profile: ShippingOrderDocumentProfile]; clone: [profile: ShippingOrderDocumentProfile]; migrate: [profile: ShippingOrderDocumentProfile]; retire: [profile: ShippingOrderDocumentProfile]; remove: [profile: ShippingOrderDocumentProfile]; test: [profile: ShippingOrderDocumentProfile] }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside v-if="open" class="drawer" :aria-label="t('admin.shippingOrderProfiles.versions')">
|
||||
<header><strong>{{ t('admin.shippingOrderProfiles.versions') }}</strong><button type="button" @click="$emit('close')">{{ t('common.close') }}</button></header>
|
||||
<article v-for="profile in profiles" :key="profile.id">
|
||||
<div><b>{{ profile.display_name }} · v{{ profile.version }}</b><small>{{ profile.profile_code }} · {{ profile.status }}</small><small v-if="profile.auto_freeze_qualification">{{ t(`admin.shippingOrderProfiles.autoFreezeQualification.${profile.auto_freeze_qualification.status}`) }}</small><small v-if="profile.migration_status === 'needs_revalidation'" class="migration-status">{{ t('admin.shippingOrderProfiles.migrationNeedsReview') }}</small></div>
|
||||
<div class="actions">
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('edit', profile)">{{ t('common.edit') }}</button>
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('test', profile)">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</button>
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('publish', profile)">{{ t('admin.shippingOrderProfiles.publish') }}</button>
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('remove', profile)">{{ t('common.delete') }}</button>
|
||||
<button v-if="profile.status !== 'draft'" type="button" @click="$emit('clone', profile)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button v-if="profile.status === 'published' && profile.schema_compatibility?.status === 'breaking'" type="button" @click="$emit('migrate', profile)">{{ t('admin.shippingOrderProfiles.migrateSchema') }}</button>
|
||||
<button v-if="profile.status === 'published'" type="button" @click="$emit('retire', profile)">{{ t('admin.shippingOrderProfiles.retire') }}</button>
|
||||
</div>
|
||||
</article>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.drawer { position: fixed; inset: 0 0 0 auto; z-index: 30; width: min(28rem, 92vw); overflow: auto; border-left: 1px solid #cbd5e1; background: white; box-shadow: -16px 0 36px rgb(15 23 42 / .16); }.drawer header { position: sticky; top: 0; display: flex; justify-content: space-between; border-bottom: 1px solid #e2e8f0; background: #fff; padding: 1rem; }.drawer article { display: grid; gap: .75rem; border-bottom: 1px solid #e2e8f0; padding: 1rem; }.drawer b,.drawer small { display: block; }.drawer small { margin-top: .25rem; color: #64748b; }.actions { display: flex; flex-wrap: wrap; gap: .4rem; }.actions button,.drawer header button { border: 1px solid #cbd5e1; border-radius: .4rem; background: white; padding: .35rem .55rem; font-size: .75rem; }.actions button:hover { background: #f1f5f9; }
|
||||
.drawer small.migration-status { color: #b45309; }
|
||||
</style>
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
<!--
|
||||
features/admin/modules/shipping-order-document-profiles/components/OrderProfileVersionOverview.vue
|
||||
用途:展示模板版本详情的配置概览页签。
|
||||
依赖:订单模板详情 DTO、i18n。
|
||||
逻辑:仅渲染结构化摘要与冻结证据状态,不请求 PDF、Layout payload 或盲测真值。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import type { ShippingOrderDocumentProfile } from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
const props = defineProps<{
|
||||
detail: ShippingOrderDocumentProfile;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const statusLabel = computed(() => {
|
||||
if (props.detail.status === "draft") {
|
||||
return t("admin.shippingOrderProfiles.versionCenter.status.currentDraft");
|
||||
}
|
||||
if (props.detail.status === "published") {
|
||||
return t("admin.shippingOrderProfiles.versionCenter.status.currentPublished");
|
||||
}
|
||||
return t("admin.shippingOrderProfiles.versionCenter.status.retired");
|
||||
});
|
||||
|
||||
const frozenEvidenceLabel = computed(() => {
|
||||
const status = props.detail.frozen_evidence?.status || "pending";
|
||||
return t(`admin.shippingOrderProfiles.versionCenter.frozenEvidence.${status}`);
|
||||
});
|
||||
|
||||
const testStatusLabel = computed(() => {
|
||||
const status = props.detail.test_summary?.status || "missing";
|
||||
return t(`admin.shippingOrderProfiles.versionCenter.testStatus.${status}`);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="overview">
|
||||
<div class="hero-card">
|
||||
<div class="hero-row">
|
||||
<div>
|
||||
<p class="eyebrow">{{ detail.profile_code }}</p>
|
||||
<h2>v{{ detail.version }} · {{ statusLabel }}</h2>
|
||||
</div>
|
||||
<div class="hero-meta">
|
||||
<span class="meta-chip">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.schemaVersion") }}
|
||||
{{ detail.schema_summary?.version ?? "-" }}
|
||||
</span>
|
||||
<span class="meta-chip">
|
||||
{{ t("admin.shippingOrderProfiles.versionCenter.sampleCount", { count: detail.sample_summary?.sample_count || 0 }) }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="hero-subtitle">{{ detail.display_name }}</p>
|
||||
<p v-if="detail.change_note" class="change-note">{{ detail.change_note }}</p>
|
||||
<dl class="hero-grid">
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.checksum") }}</dt>
|
||||
<dd><code>{{ detail.checksum || "-" }}</code></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.schemaChecksum") }}</dt>
|
||||
<dd><code>{{ detail.schema_summary?.checksum || "-" }}</code></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.publishedAt") }}</dt>
|
||||
<dd>{{ detail.published_at || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.retiredAt") }}</dt>
|
||||
<dd>{{ detail.retired_at || "-" }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<div class="summary-grid">
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.definitionStats") }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.tableRegions") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.table_region_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.headerLayouts") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.header_layout_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.lineLayouts") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.line_layout_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.orderFieldLayouts") }}</dt>
|
||||
<dd>{{ detail.definition_stats?.order_field_layout_count || 0 }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.frozenEvidenceTitle") }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.statusLabel") }}</dt>
|
||||
<dd>{{ frozenEvidenceLabel }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.sampleCountPlain") }}</dt>
|
||||
<dd>{{ detail.frozen_evidence?.sample_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.frozenSampleCount") }}</dt>
|
||||
<dd>{{ detail.frozen_evidence?.frozen_sample_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.auditReady") }}</dt>
|
||||
<dd>{{ detail.frozen_evidence?.audit_ready ? t("common.yes") : t("common.no") }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.sampleSummaryTitle") }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.annotationCount") }}</dt>
|
||||
<dd>{{ detail.sample_summary?.annotation_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.trainingCount") }}</dt>
|
||||
<dd>{{ detail.sample_summary?.training_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.blindTestCount") }}</dt>
|
||||
<dd>{{ detail.sample_summary?.blind_test_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.firstSample") }}</dt>
|
||||
<dd>{{ detail.sample_summary?.samples?.[0]?.source_filename_snapshot || "-" }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article class="summary-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.testSummaryTitle") }}</h3>
|
||||
<dl>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.statusLabel") }}</dt>
|
||||
<dd>{{ testStatusLabel }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.sampleCountPlain") }}</dt>
|
||||
<dd>{{ detail.test_summary?.sample_count || 0 }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.approvedAt") }}</dt>
|
||||
<dd>{{ detail.test_summary?.approved_at || "-" }}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{{ t("admin.shippingOrderProfiles.versionCenter.latestRun") }}</dt>
|
||||
<dd>{{ detail.test_summary?.latest_run?.status || "-" }}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<article class="summary-card source-card">
|
||||
<h3>{{ t("admin.shippingOrderProfiles.versionCenter.sourceVersionTitle") }}</h3>
|
||||
<p v-if="detail.source_version">
|
||||
{{ detail.source_version.profile_code }} · v{{ detail.source_version.version }} ·
|
||||
{{ detail.source_version.status }}
|
||||
</p>
|
||||
<p v-else>{{ t("admin.shippingOrderProfiles.versionCenter.noSourceVersion") }}</p>
|
||||
</article>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.overview {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.hero-card,
|
||||
.summary-card {
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 0.9rem;
|
||||
background: #fff;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.hero-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 0.35rem;
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.hero-card h2,
|
||||
.summary-card h3 {
|
||||
margin: 0;
|
||||
color: #0f172a;
|
||||
}
|
||||
|
||||
.hero-subtitle,
|
||||
.change-note {
|
||||
margin: 0.65rem 0 0;
|
||||
color: #475569;
|
||||
}
|
||||
|
||||
.change-note {
|
||||
border-left: 3px solid #cbd5e1;
|
||||
padding-left: 0.75rem;
|
||||
}
|
||||
|
||||
.hero-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.meta-chip {
|
||||
border-radius: 999px;
|
||||
background: #eff6ff;
|
||||
color: #1d4ed8;
|
||||
padding: 0.35rem 0.65rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.hero-grid,
|
||||
.summary-card dl {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||||
margin: 1rem 0 0;
|
||||
}
|
||||
|
||||
.hero-grid dt,
|
||||
.summary-card dt {
|
||||
color: #64748b;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.hero-grid dd,
|
||||
.summary-card dd {
|
||||
margin: 0.25rem 0 0;
|
||||
color: #0f172a;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.summary-grid {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
}
|
||||
|
||||
.source-card p {
|
||||
margin: 0.75rem 0 0;
|
||||
color: #334155;
|
||||
}
|
||||
</style>
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/composables/useOrderProfileVersionDetail.ts
|
||||
* 用途:按独立详情路由加载模板版本详情与同族版本导航数据。
|
||||
* 依赖:vue-router、订单模板版本中心 API。
|
||||
* 逻辑:只读取结构化详情与版本摘要,不触发 PDF 预览、画布或盲测真值请求。
|
||||
*/
|
||||
|
||||
import { computed, ref, watch } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
import { BusinessError } from "@/shared/api/client";
|
||||
import {
|
||||
getOrderDocumentProfileByFamilyVersion,
|
||||
listOrderDocumentProfileFamilyVersions,
|
||||
} from "@/features/admin/api/shipping-order-document-profile.api";
|
||||
import type {
|
||||
OrderProfileVersionSummary,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from "@/features/admin/types/shipping-order-document-profile.types";
|
||||
|
||||
export type OrderProfileVersionDetailTab =
|
||||
| "overview"
|
||||
| "canvas"
|
||||
| "diff"
|
||||
| "audit"
|
||||
| "usage";
|
||||
|
||||
export interface OrderProfileVersionDetailTabOption {
|
||||
key: OrderProfileVersionDetailTab;
|
||||
count?: number | null;
|
||||
}
|
||||
|
||||
const VALID_TABS: OrderProfileVersionDetailTab[] = [
|
||||
"overview",
|
||||
"canvas",
|
||||
"diff",
|
||||
"audit",
|
||||
"usage",
|
||||
];
|
||||
|
||||
/**
|
||||
* 按路由参数读取版本详情,只暴露阶段 3 需要的只读状态。
|
||||
*/
|
||||
export const useOrderProfileVersionDetail = () => {
|
||||
const route = useRoute();
|
||||
const loading = ref(false);
|
||||
const detail = ref<ShippingOrderDocumentProfile | null>(null);
|
||||
const versions = ref<OrderProfileVersionSummary[]>([]);
|
||||
const errorMessage = ref("");
|
||||
|
||||
const profileCode = computed(() =>
|
||||
String(route.params.profileCode || "").trim(),
|
||||
);
|
||||
const version = computed(() => Number(route.params.version || 0));
|
||||
const activeTab = computed<OrderProfileVersionDetailTab>(() => {
|
||||
const raw = String(route.query.tab || "overview").trim();
|
||||
return VALID_TABS.includes(raw as OrderProfileVersionDetailTab)
|
||||
? (raw as OrderProfileVersionDetailTab)
|
||||
: "overview";
|
||||
});
|
||||
const tabOptions = computed<OrderProfileVersionDetailTabOption[]>(() => [
|
||||
{ key: "overview" },
|
||||
{ key: "canvas", count: detail.value?.sample_summary?.sample_count || 0 },
|
||||
{ key: "diff" },
|
||||
{ key: "audit" },
|
||||
{ key: "usage" },
|
||||
]);
|
||||
|
||||
const load = async () => {
|
||||
if (!profileCode.value || !Number.isFinite(version.value) || version.value <= 0) {
|
||||
detail.value = null;
|
||||
versions.value = [];
|
||||
errorMessage.value = "";
|
||||
return;
|
||||
}
|
||||
loading.value = true;
|
||||
errorMessage.value = "";
|
||||
try {
|
||||
const [detailPayload, versionsPayload] = await Promise.all([
|
||||
getOrderDocumentProfileByFamilyVersion(profileCode.value, version.value),
|
||||
listOrderDocumentProfileFamilyVersions(profileCode.value),
|
||||
]);
|
||||
detail.value = detailPayload;
|
||||
versions.value = versionsPayload;
|
||||
} catch (error) {
|
||||
detail.value = null;
|
||||
versions.value = [];
|
||||
errorMessage.value =
|
||||
error instanceof BusinessError ? error.message : "Failed to load";
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
watch([profileCode, version], () => {
|
||||
void load();
|
||||
}, { immediate: true });
|
||||
|
||||
return {
|
||||
activeTab,
|
||||
detail,
|
||||
errorMessage,
|
||||
loading,
|
||||
profileCode,
|
||||
tabOptions,
|
||||
version,
|
||||
versions,
|
||||
};
|
||||
};
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileReadonlyCanvas.utils.ts
|
||||
* 用途:把模板定义恢复成版本详情只读画布可渲染的区域集合。
|
||||
* 依赖:订单模板类型、restoreOrderProfileRegionPageNo。
|
||||
* 逻辑:版本详情只读展示几何和绑定身份,不写回表单或草稿状态。
|
||||
*/
|
||||
|
||||
import type {
|
||||
OrderProfileCanvasRegion,
|
||||
ShippingOrderDocumentProfile,
|
||||
} from '@/features/admin/types/shipping-order-document-profile.types';
|
||||
import { restoreOrderProfileRegionPageNo } from './orderProfileForm.utils';
|
||||
|
||||
const mergeEquivalentOrderAnchors = (items: OrderProfileCanvasRegion[]) => {
|
||||
const canonicalByKey = new Map<string, string>();
|
||||
const anchorIds = new Map<string, string>();
|
||||
const retained: OrderProfileCanvasRegion[] = [];
|
||||
const anchorKey = (item: OrderProfileCanvasRegion) => [
|
||||
item.pageNo,
|
||||
item.label.trim().toLocaleLowerCase(),
|
||||
item.region.x0,
|
||||
item.region.y0,
|
||||
item.region.x1,
|
||||
item.region.y1,
|
||||
].join('|');
|
||||
for (const item of items) {
|
||||
if (item.kind !== 'order_anchor') {
|
||||
retained.push(item);
|
||||
continue;
|
||||
}
|
||||
const canonicalId = canonicalByKey.get(anchorKey(item));
|
||||
if (canonicalId) {
|
||||
anchorIds.set(item.id, canonicalId);
|
||||
if (item.orderFieldId) anchorIds.set(`layout:${item.orderFieldId}`, canonicalId);
|
||||
continue;
|
||||
}
|
||||
canonicalByKey.set(anchorKey(item), item.id);
|
||||
anchorIds.set(item.id, item.id);
|
||||
if (item.orderFieldId) anchorIds.set(`layout:${item.orderFieldId}`, item.id);
|
||||
retained.push(item);
|
||||
}
|
||||
return retained.map((item) => item.kind === 'order_field'
|
||||
? {
|
||||
...item,
|
||||
parentId: item.parentId
|
||||
? anchorIds.get(item.parentId) || item.parentId
|
||||
: item.orderFieldId
|
||||
? anchorIds.get(`layout:${item.orderFieldId}`) || null
|
||||
: null,
|
||||
}
|
||||
: item);
|
||||
};
|
||||
|
||||
const pageNoOf = (pageScope: 'first_page' | 'all_pages' | 'exact_page', pageNo?: number | null) =>
|
||||
pageScope === 'exact_page' ? (pageNo || 1) : 1;
|
||||
|
||||
/**
|
||||
* 从版本详情定义恢复只读画布区域;标签统一优先使用 field_code,避免引入可编辑态依赖。
|
||||
*/
|
||||
export const buildOrderProfileReadonlyRegions = (
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
): OrderProfileCanvasRegion[] => {
|
||||
const restored: OrderProfileCanvasRegion[] = [
|
||||
...(profile.definition.draft_unbound_order_field_layouts || []).flatMap<OrderProfileCanvasRegion>((item) => {
|
||||
const pageNo = pageNoOf(item.page_scope, item.page_no);
|
||||
if (!item.anchor?.region || !item.value_region) {
|
||||
return [{
|
||||
id: `unbound-${item.layout_id}`,
|
||||
kind: 'order_field',
|
||||
label: item.label,
|
||||
region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 },
|
||||
fieldCode: null,
|
||||
pageNo,
|
||||
}];
|
||||
}
|
||||
const anchor = item.anchor.region;
|
||||
const width = anchor.x1 - anchor.x0;
|
||||
const height = anchor.y1 - anchor.y0;
|
||||
return [{
|
||||
id: `unbound-${item.anchor.anchor_id}`,
|
||||
kind: 'order_anchor',
|
||||
label: item.anchor.text,
|
||||
region: anchor,
|
||||
orderFieldId: item.layout_id,
|
||||
pageNo,
|
||||
}, {
|
||||
id: `unbound-${item.layout_id}`,
|
||||
kind: 'order_field',
|
||||
label: item.label,
|
||||
region: {
|
||||
x0: anchor.x0 + item.value_region.x0 * width,
|
||||
y0: anchor.y0 + item.value_region.y0 * height,
|
||||
x1: anchor.x0 + item.value_region.x1 * width,
|
||||
y1: anchor.y0 + item.value_region.y1 * height,
|
||||
},
|
||||
fieldCode: null,
|
||||
orderFieldId: item.layout_id,
|
||||
pageNo,
|
||||
}];
|
||||
}),
|
||||
...(profile.definition.order_field_layouts || []).filter((item) => !item.anchor).map((item) => ({
|
||||
id: item.layout_id,
|
||||
kind: 'order_field' as const,
|
||||
label: item.field_code,
|
||||
region: item.fallback_value_region || { x0: .1, y0: .1, x1: .2, y1: .15 },
|
||||
fieldCode: item.field_code,
|
||||
pageNo: pageNoOf(item.page_scope, item.page_no),
|
||||
})),
|
||||
...(profile.definition.order_field_layouts || []).flatMap((item) => {
|
||||
if (!item.anchor?.region || !item.value_region) return [];
|
||||
const anchor = item.anchor.region;
|
||||
const width = anchor.x1 - anchor.x0;
|
||||
const height = anchor.y1 - anchor.y0;
|
||||
return [{
|
||||
id: item.anchor.anchor_id,
|
||||
kind: 'order_anchor' as const,
|
||||
label: item.anchor.text,
|
||||
region: anchor,
|
||||
orderFieldId: item.layout_id,
|
||||
pageNo: pageNoOf(item.page_scope, item.page_no),
|
||||
}, {
|
||||
id: item.layout_id,
|
||||
kind: 'order_field' as const,
|
||||
label: item.field_code,
|
||||
region: {
|
||||
x0: anchor.x0 + item.value_region.x0 * width,
|
||||
y0: anchor.y0 + item.value_region.y0 * height,
|
||||
x1: anchor.x0 + item.value_region.x1 * width,
|
||||
y1: anchor.y0 + item.value_region.y1 * height,
|
||||
},
|
||||
fieldCode: item.field_code,
|
||||
orderFieldId: item.layout_id,
|
||||
valueMode: item.value_mode,
|
||||
stopAnchorText: item.stop_anchors[0]?.text || null,
|
||||
pageNo: pageNoOf(item.page_scope, item.page_no),
|
||||
}];
|
||||
}),
|
||||
...profile.definition.table_regions.flatMap((table) => {
|
||||
const regionPageNo = restoreOrderProfileRegionPageNo(table);
|
||||
const headerLayoutIds = new Set(table.header_layouts.map((item) => item.layout_id));
|
||||
return [
|
||||
...table.header_layouts.flatMap((header) =>
|
||||
header.field_regions.map((item, index) => ({
|
||||
id: `${header.layout_id}-field-${index}`,
|
||||
kind: 'header_field' as const,
|
||||
label: item.field_code,
|
||||
fieldCode: item.field_code,
|
||||
region: item.region,
|
||||
parentId: header.layout_id,
|
||||
pageNo: regionPageNo,
|
||||
})),
|
||||
),
|
||||
...table.line_layouts.map((item) => ({
|
||||
id: item.layout_id,
|
||||
kind: 'line' as const,
|
||||
label: item.layout_id,
|
||||
region: item.region,
|
||||
pageNo: regionPageNo,
|
||||
})),
|
||||
...table.line_layouts.flatMap((line) =>
|
||||
line.field_regions.map((item, index) => ({
|
||||
id: `${line.layout_id}-field-${index}`,
|
||||
kind: 'field' as const,
|
||||
label: item.field_code,
|
||||
region: item.region,
|
||||
fieldCode: item.field_code,
|
||||
parentId: line.layout_id,
|
||||
pageNo: regionPageNo,
|
||||
})),
|
||||
),
|
||||
...(table.draft_unbound_field_regions || []).map((item) => ({
|
||||
id: item.region_id,
|
||||
kind: headerLayoutIds.has(item.parent_layout_id) ? ('header_field' as const) : ('field' as const),
|
||||
label: item.label,
|
||||
region: item.region,
|
||||
fieldCode: null,
|
||||
parentId: item.parent_layout_id,
|
||||
pageNo: regionPageNo,
|
||||
})),
|
||||
...table.exclusion_regions.map((region, index) => ({
|
||||
id: `exclusion-${regionPageNo}-${index}`,
|
||||
kind: 'exclusion' as const,
|
||||
label: `exclusion ${index + 1}`,
|
||||
region,
|
||||
pageNo: regionPageNo,
|
||||
})),
|
||||
];
|
||||
}),
|
||||
];
|
||||
return mergeEquivalentOrderAnchors(restored);
|
||||
};
|
||||
+35
-4
@@ -5,8 +5,9 @@
|
||||
逻辑:列表按状态筛选并按需加载单条详情;页面不提供重试、取消或任何业务数据修改入口。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import {
|
||||
getShippingOrderExtractionDiagnosticRun,
|
||||
listShippingOrderExtractionDiagnosticRuns,
|
||||
@@ -15,6 +16,8 @@ import {
|
||||
} from '@/features/admin/api/admin.api';
|
||||
|
||||
const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const detailLoading = ref(false);
|
||||
const page = ref(1);
|
||||
@@ -51,6 +54,9 @@ const openDetail = async (runNo: string) => {
|
||||
error.value = '';
|
||||
try {
|
||||
detail.value = await getShippingOrderExtractionDiagnosticRun(runNo);
|
||||
if (route.query.runNo !== runNo) {
|
||||
void router.replace({ query: { ...route.query, runNo } });
|
||||
}
|
||||
} catch {
|
||||
error.value = t('admin.shippingOrderExtractionRuns.detailFailed');
|
||||
} finally {
|
||||
@@ -58,12 +64,37 @@ const openDetail = async (runNo: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
const closeDetail = () => {
|
||||
detail.value = null;
|
||||
if (route.query.runNo) {
|
||||
const nextQuery = { ...route.query };
|
||||
delete nextQuery.runNo;
|
||||
void router.replace({ query: nextQuery });
|
||||
}
|
||||
};
|
||||
|
||||
const applyStatus = async () => {
|
||||
page.value = 1;
|
||||
await load();
|
||||
};
|
||||
|
||||
onMounted(() => { void load(); });
|
||||
onMounted(() => {
|
||||
void load();
|
||||
const runNo = String(route.query.runNo || '').trim();
|
||||
if (runNo) void openDetail(runNo);
|
||||
});
|
||||
|
||||
watch(
|
||||
() => String(route.query.runNo || '').trim(),
|
||||
(runNo) => {
|
||||
if (!runNo) {
|
||||
detail.value = null;
|
||||
return;
|
||||
}
|
||||
if (detail.value?.run.run_no === runNo || detailLoading.value) return;
|
||||
void openDetail(runNo);
|
||||
},
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -106,9 +137,9 @@ onMounted(() => { void load(); });
|
||||
</div>
|
||||
<div class="flex items-center justify-end gap-3 text-sm"><button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page <= 1 || loading" @click="page -= 1; load()">{{ t('admin.shippingOrderExtractionRuns.previous') }}</button><span>{{ page }}</span><button type="button" class="rounded border border-default px-3 py-1.5 disabled:opacity-50" :disabled="page * pageSize >= total || loading" @click="page += 1; load()">{{ t('admin.shippingOrderExtractionRuns.next') }}</button></div>
|
||||
|
||||
<div v-if="detail || detailLoading" class="fixed inset-0 z-50 flex justify-end bg-black/30" @click.self="detail = null">
|
||||
<div v-if="detail || detailLoading" class="fixed inset-0 z-50 flex justify-end bg-black/30" @click.self="closeDetail">
|
||||
<aside class="h-full w-full max-w-2xl overflow-y-auto bg-surface p-6 shadow-2xl">
|
||||
<div class="flex items-center justify-between"><h2 class="text-lg font-bold">{{ t('admin.shippingOrderExtractionRuns.detailTitle') }}</h2><button type="button" class="text-secondary" @click="detail = null">{{ t('admin.close') }}</button></div>
|
||||
<div class="flex items-center justify-between"><h2 class="text-lg font-bold">{{ t('admin.shippingOrderExtractionRuns.detailTitle') }}</h2><button type="button" class="text-secondary" @click="closeDetail">{{ t('admin.close') }}</button></div>
|
||||
<p v-if="detailLoading" class="mt-6 text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</p>
|
||||
<template v-else-if="detail"><dl class="mt-5 grid grid-cols-2 gap-3 text-sm"><dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.currentEvent') }}</dt><dd class="font-mono text-xs">{{ detail.run.current_event_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.candidateMaterializedAt') }}</dt><dd>{{ formatTime(detail.run.candidate_materialized_at) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd></dl>
|
||||
<section class="mt-6 rounded-lg border border-default p-4 text-sm">
|
||||
|
||||
@@ -66,4 +66,17 @@ describe('shipping configuration navigation contract', () => {
|
||||
expect.objectContaining({ requiresAdmin: true, adminModule: 'shipping_inventory', adminSubModule: 'order_document_profiles' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('routes a newly created draft to the dedicated editor deep link', () => {
|
||||
// 关键断言:创建向导完成后不能回落到模板库,必须有草稿身份明确的编辑入口。
|
||||
const editorRoute = adminRoutes[0].children?.find(
|
||||
(route) => route.name === 'AdminShippingOrderDocumentProfileEdit',
|
||||
);
|
||||
expect(editorRoute?.path).toBe('shipping-order-document-profiles/:profileCode/drafts/:profileId/edit');
|
||||
expect(editorRoute?.meta).toEqual(expect.objectContaining({
|
||||
requiresAdmin: true,
|
||||
adminModule: 'shipping_inventory',
|
||||
adminSubModule: 'order_document_profiles',
|
||||
}));
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,21 @@
|
||||
export type OrderProfileExtractorKey = 'direct' | 'temp_internal_parts' | 'quantity_uom' | 'amount_currency' | 'price_currency';
|
||||
export type OrderProfileEvidenceLevel = 'coordinate' | 'ocr_coordinate';
|
||||
export type OrderProfileAllowedSource = 'pdf_coordinate' | 'ocr_coordinate';
|
||||
export type OrderProfileChangeSource = 'wizard_created' | 'manual_save' | 'autosave' | 'restore' | 'sample_changed';
|
||||
export type OrderProfileLeaseState = 'active' | 'expired' | 'released' | 'taken_over';
|
||||
export type OrderProfileValidationRunType = 'instant_check' | 'current_sample' | 'blind_test' | 'scenario_coverage' | 'schema_compatibility';
|
||||
export type OrderProfileValidationRunStatus = 'pending' | 'running' | 'passed' | 'failed' | 'stale';
|
||||
export type OrderProfilePublishCheckStatus = 'valid' | 'invalidated' | 'consumed' | 'expired';
|
||||
|
||||
/** 阶段 0 冻结的 Profile 治理错误码;后端在相应阶段实现时必须使用这些稳定身份。 */
|
||||
export type OrderProfileGovernanceErrorCode =
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_LOCK_VERSION_CONFLICT'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_REVISION_NOT_FOUND'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_VALIDATION_STALE'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID'
|
||||
| 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_CONSUMED';
|
||||
|
||||
export interface OrderProfileRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
|
||||
export interface OrderProfileAnchorRelativeRegion { x0: number; y0: number; x1: number; y1: number; }
|
||||
@@ -72,12 +87,283 @@ export interface ShippingOrderDocumentProfile {
|
||||
requires_customer_confirmation?: boolean;
|
||||
scope_updated_at?: string | null;
|
||||
};
|
||||
frozen_evidence?: {
|
||||
status: 'pending' | 'ready' | 'missing';
|
||||
sample_count: number;
|
||||
frozen_sample_count: number;
|
||||
audit_ready: boolean;
|
||||
};
|
||||
schema_summary?: {
|
||||
id: number;
|
||||
version?: number | null;
|
||||
checksum?: string | null;
|
||||
};
|
||||
definition_stats?: {
|
||||
table_region_count: number;
|
||||
header_layout_count: number;
|
||||
line_layout_count: number;
|
||||
order_field_layout_count: number;
|
||||
draft_unbound_order_field_layout_count: number;
|
||||
};
|
||||
sample_summary?: {
|
||||
annotation_count: number;
|
||||
training_count: number;
|
||||
blind_test_count: number;
|
||||
sample_count: number;
|
||||
samples: OrderProfileBoundSample[];
|
||||
};
|
||||
test_summary?: {
|
||||
status: 'missing' | 'draft' | 'approved' | 'superseded';
|
||||
sample_count: number;
|
||||
approved_at?: string | null;
|
||||
latest_run?: {
|
||||
status: 'passed' | 'failed';
|
||||
sample_count: number;
|
||||
passed_sample_count: number;
|
||||
failure_codes: string[];
|
||||
} | null;
|
||||
};
|
||||
source_version?: {
|
||||
id: number;
|
||||
profile_code: string;
|
||||
version: number;
|
||||
status: 'draft' | 'published' | 'retired';
|
||||
checksum?: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** 不可变草稿快照;修改 Profile 时只追加新修订,禁止覆盖历史定义。 */
|
||||
export interface OrderProfileDraftRevision {
|
||||
revision_no: number;
|
||||
profile_id: number;
|
||||
base_lock_version: number;
|
||||
result_lock_version: number;
|
||||
definition_checksum: string;
|
||||
change_source: OrderProfileChangeSource;
|
||||
actor_id: number | null;
|
||||
browser_session_id: string;
|
||||
operation_id: string;
|
||||
change_summary: Record<string, unknown>;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** 当前浏览器标签持有的单写者租约;令牌仅用于写请求,不能记录或展示。 */
|
||||
export interface OrderProfileEditLease {
|
||||
profile_id: number;
|
||||
state: OrderProfileLeaseState;
|
||||
actor_id: number | null;
|
||||
browser_session_id: string;
|
||||
expires_at: string;
|
||||
last_renewed_at: string | null;
|
||||
lock_version: number;
|
||||
}
|
||||
|
||||
/** 绑定精确草稿 checksum 的不可变验证运行摘要。 */
|
||||
export interface OrderProfileValidationRun {
|
||||
id: number;
|
||||
profile_id: number;
|
||||
revision_no: number;
|
||||
definition_checksum: string;
|
||||
run_type: OrderProfileValidationRunType;
|
||||
status: OrderProfileValidationRunStatus;
|
||||
stored_status?: Exclude<OrderProfileValidationRunStatus, 'stale'>;
|
||||
summary?: Record<string, unknown>;
|
||||
operation_id: string;
|
||||
created_at: string;
|
||||
completed_at: string | null;
|
||||
}
|
||||
|
||||
/** 发布检查冻结草稿、验证运行与锁版本;只能被一次原子发布消费。 */
|
||||
export interface OrderProfilePublishCheckReport {
|
||||
id: number;
|
||||
report_no: string;
|
||||
profile_id: number;
|
||||
revision_no: number;
|
||||
definition_checksum: string;
|
||||
lock_version: number;
|
||||
validation_run_id: number | null;
|
||||
semantic_diff?: Record<string, unknown>;
|
||||
status: OrderProfilePublishCheckStatus;
|
||||
blocking_items: Array<Record<string, unknown>>;
|
||||
warning_items: Array<Record<string, unknown>>;
|
||||
operation_id: string;
|
||||
created_at: string;
|
||||
consumed_at: string | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileVersionFamilySummary {
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
draft_profile_id?: number | null;
|
||||
draft_version?: number | null;
|
||||
published_profile_id?: number | null;
|
||||
published_version?: number | null;
|
||||
latest_profile_id: number;
|
||||
latest_version: number;
|
||||
default_profile_id: number;
|
||||
default_version: number;
|
||||
version_count: number;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface OrderProfileVersionSummary {
|
||||
id: number;
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
version: number;
|
||||
status: 'draft' | 'published' | 'retired';
|
||||
schema_version_id: number;
|
||||
schema_version?: number | null;
|
||||
schema_checksum?: string | null;
|
||||
checksum?: string | null;
|
||||
change_note?: string | null;
|
||||
source_profile_id?: number | null;
|
||||
published_at?: string | null;
|
||||
retired_at?: string | null;
|
||||
template_mode?: string;
|
||||
training_sample_count?: number;
|
||||
match_strategy_summary?: Record<string, number | null>;
|
||||
migration_status?: 'normal' | 'needs_revalidation' | 'blocked';
|
||||
auto_freeze_qualification?: ShippingOrderDocumentProfile['auto_freeze_qualification'];
|
||||
frozen_evidence?: ShippingOrderDocumentProfile['frozen_evidence'];
|
||||
definition_stats?: ShippingOrderDocumentProfile['definition_stats'];
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface OrderProfileVersionDiffChange {
|
||||
key: string;
|
||||
kind: 'value' | 'set' | 'region' | 'json';
|
||||
before: unknown;
|
||||
after: unknown;
|
||||
added?: string[];
|
||||
removed?: string[];
|
||||
order_changed?: boolean;
|
||||
tolerance?: number;
|
||||
}
|
||||
|
||||
export interface OrderProfileVersionDiffItem {
|
||||
entity_type:
|
||||
| 'profile_meta'
|
||||
| 'document_match'
|
||||
| 'table_region'
|
||||
| 'header_layout'
|
||||
| 'header_field_region'
|
||||
| 'line_layout'
|
||||
| 'line_field_region'
|
||||
| 'termination_rule'
|
||||
| 'exclusion_region'
|
||||
| 'order_field_layout'
|
||||
| 'sample_binding';
|
||||
entity_id: string;
|
||||
parent_id?: string | null;
|
||||
label: string;
|
||||
change_type: 'added' | 'removed' | 'modified' | 'unchanged';
|
||||
changes: OrderProfileVersionDiffChange[];
|
||||
before_snapshot?: Record<string, unknown> | null;
|
||||
after_snapshot?: Record<string, unknown> | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileVersionDiff {
|
||||
base_profile: Pick<OrderProfileVersionSummary, 'id' | 'profile_code' | 'display_name' | 'version' | 'status' | 'schema_version_id' | 'schema_version' | 'schema_checksum' | 'checksum'>;
|
||||
compare_profile?: Pick<OrderProfileVersionSummary, 'id' | 'profile_code' | 'display_name' | 'version' | 'status' | 'schema_version_id' | 'schema_version' | 'schema_checksum' | 'checksum'> | null;
|
||||
comparison_mode: 'explicit' | 'previous' | 'initial';
|
||||
summary: {
|
||||
added: number;
|
||||
removed: number;
|
||||
modified: number;
|
||||
unchanged: number;
|
||||
};
|
||||
items: OrderProfileVersionDiffItem[];
|
||||
}
|
||||
|
||||
export interface OrderProfileAuditEvent {
|
||||
id: number;
|
||||
event_type: string;
|
||||
request_id?: string | null;
|
||||
document_id?: number | null;
|
||||
actor: {
|
||||
id?: number | null;
|
||||
username?: string | null;
|
||||
display_name: string;
|
||||
};
|
||||
detail: Record<string, unknown>;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface OrderProfileAuditEventPage {
|
||||
profile: Pick<OrderProfileVersionSummary, 'id' | 'profile_code' | 'version' | 'status'>;
|
||||
filters: {
|
||||
event_type?: string | null;
|
||||
actor?: string | null;
|
||||
request_id?: string | null;
|
||||
created_from?: string | null;
|
||||
created_to?: string | null;
|
||||
};
|
||||
items: OrderProfileAuditEvent[];
|
||||
page: {
|
||||
limit: number;
|
||||
before_id?: number | null;
|
||||
next_before_id?: number | null;
|
||||
has_more: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OrderProfileUsageRow {
|
||||
route_decision_id: number;
|
||||
identity_match_mode: 'direct_profile_id' | 'snapshot_identity_match';
|
||||
run_no: string;
|
||||
run_status: string;
|
||||
unit_id: number;
|
||||
unit_position: number;
|
||||
document_id: number;
|
||||
document_label: string;
|
||||
match_status: string;
|
||||
execution_status: string;
|
||||
auto_create_approved?: boolean | null;
|
||||
selected_profile_code?: string | null;
|
||||
selected_profile_version?: number | null;
|
||||
selected_profile_checksum?: string | null;
|
||||
reason_codes: string[];
|
||||
created_at?: string | null;
|
||||
diagnostic_entry: {
|
||||
route_name: 'AdminShippingOrderExtractionRuns';
|
||||
run_no: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface OrderProfileUsagePage {
|
||||
profile: Pick<OrderProfileVersionSummary, 'id' | 'profile_code' | 'version' | 'status' | 'checksum'>;
|
||||
items: OrderProfileUsageRow[];
|
||||
page: {
|
||||
limit: number;
|
||||
before_id?: number | null;
|
||||
next_before_id?: number | null;
|
||||
has_more: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
/** 受控预览授权只对单页生效,令牌不得持久化或复用。 */
|
||||
export interface OrderProfilePreviewPageGrant { page_no: number; preview_token: string; }
|
||||
export interface OrderProfileBoundSample { id: number; document_id: number; table_id?: string | null; sample_role: 'annotation' | 'training'; created_at: string; }
|
||||
export interface OrderProfilePreviewPages { document_id: number; page_count: number; pages: OrderProfilePreviewPageGrant[]; expires_in_seconds: number; }
|
||||
export interface OrderProfileBoundSample {
|
||||
id: number;
|
||||
document_id: number;
|
||||
table_id?: string | null;
|
||||
sample_role: 'annotation' | 'training' | 'blind_test';
|
||||
created_at: string;
|
||||
frozen_evidence_ready?: boolean;
|
||||
layout_version_id?: number | null;
|
||||
source_content_hash?: string | null;
|
||||
layout_payload_checksum?: string | null;
|
||||
layout_contract_version?: string | null;
|
||||
parser_key?: string | null;
|
||||
parser_name?: string | null;
|
||||
parser_version?: string | null;
|
||||
source_filename_snapshot?: string | null;
|
||||
page_count_snapshot?: number | null;
|
||||
table_identity_snapshot?: { table_id?: string | null; page_no?: number | null; row_count?: number | null } | null;
|
||||
evidence_frozen_at?: string | null;
|
||||
}
|
||||
export interface OrderProfilePreviewPages { sample_binding_id?: number; document_id: number; page_count: number; pages: OrderProfilePreviewPageGrant[]; expires_in_seconds: number; }
|
||||
export interface OrderProfilePageTextCandidates { document_id: number; page_no: number; tables: Array<{ table_id: string; row_count: number; column_count: number; rows: string[][] }>; status: 'needs_review'; }
|
||||
/** 发布门禁的脱敏盲测摘要;真值只在管理员添加样本时提交。 */
|
||||
export interface OrderProfileTestSuite {
|
||||
@@ -182,21 +468,6 @@ export interface CreateOrderProfileFromSampleInput {
|
||||
change_note?: string;
|
||||
}
|
||||
|
||||
/** 阶段 3 替换前的旧工作台本地表单形状;服务端会拒绝其提交。 */
|
||||
export interface LegacyCreateOrderProfileFromSampleInput {
|
||||
profile_code: string;
|
||||
display_name: string;
|
||||
schema_version_id: number;
|
||||
document_id: number;
|
||||
table_id: string;
|
||||
header_row_index: number;
|
||||
data_start_row_index: number;
|
||||
row_structure: 'preserved' | 'unsupported_row_structure';
|
||||
column_rules: OrderProfileColumnRule[];
|
||||
drop_zero_qty: boolean;
|
||||
coordinate_reconstruction?: CoordinateReconstructionSettings | null;
|
||||
change_note?: string;
|
||||
}
|
||||
export interface CoordinateReconstructionSettings {
|
||||
method: 'native_pdf_coordinates.v1' | 'ocr_pdf_coordinates.v1';
|
||||
column_boundaries: number[];
|
||||
|
||||
@@ -27,6 +27,11 @@ import type {
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRunCreateResponse,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewDraftWrite,
|
||||
ShippingOrderReviewEvidence,
|
||||
ShippingOrderReviewReparseResponse,
|
||||
ShippingOrderReviewRun,
|
||||
ShippingTaskUiState,
|
||||
} from '../types/shipping.api.types';
|
||||
|
||||
@@ -200,6 +205,127 @@ export const listWorkspaceShippingOrderExtractionDocuments = (runNo: string) =>
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/documents`,
|
||||
);
|
||||
|
||||
/** 获取 Run 下每份 PDF 的建单前复核摘要,服务端负责 owner 隔离。 */
|
||||
export const getWorkspaceShippingOrderReviewRun = (runNo: string) =>
|
||||
requestJson<ShippingOrderReviewRun>(
|
||||
`/api/workspace/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/review`,
|
||||
);
|
||||
|
||||
/** 获取一份 PDF 的冻结 Schema 与只读机器/草稿投影。 */
|
||||
export const getWorkspaceShippingOrderReviewCase = (caseNo: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}`,
|
||||
);
|
||||
|
||||
/** 保存一个复核订单头字段;后端以 expected_draft_version 拒绝过期窗口覆盖。 */
|
||||
export const patchWorkspaceShippingOrderReviewHeaderField = (
|
||||
caseNo: string, fieldId: string, payload: ShippingOrderReviewDraftWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/header-fields/${encodeURIComponent(fieldId)}`,
|
||||
{ method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/** 保存一个复核订单行字段;line_key 仅接受当前 Case DTO 返回的稳定标识。 */
|
||||
export const patchWorkspaceShippingOrderReviewLineField = (
|
||||
caseNo: string, lineKey: string, fieldId: string, payload: ShippingOrderReviewDraftWrite,
|
||||
) => requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/fields/${encodeURIComponent(fieldId)}`,
|
||||
{ method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
export const addWorkspaceShippingOrderReviewLine = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
export const copyWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}/copy`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
export const deleteWorkspaceShippingOrderReviewLine = (caseNo: string, lineKey: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/lines/${encodeURIComponent(lineKey)}`,
|
||||
{ method: 'DELETE', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
export const validateWorkspaceShippingOrderReviewDraft = (caseNo: string, expectedDraftVersion: number) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/draft/validate`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ expected_draft_version: expectedDraftVersion }) },
|
||||
);
|
||||
|
||||
/** 确认当前 PDF 的已校验草稿;服务端以版本和幂等键确保只创建一张 Task。 */
|
||||
export const confirmWorkspaceShippingOrderReviewCase = (
|
||||
caseNo: string,
|
||||
payload: { expected_draft_version: number; idempotency_key: string; warning_acknowledgements?: Array<{ code: string; comment?: string }> },
|
||||
) => requestJson<import('../types/shipping.api.types').ShippingOrderReviewConfirmResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/confirm`,
|
||||
{ method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': payload.idempotency_key }, body: JSON.stringify(payload) },
|
||||
);
|
||||
|
||||
/** 启用无机器订单 PDF 的唯一人工草稿;不创建第二个订单对象。 */
|
||||
export const createWorkspaceShippingOrderReviewManualDraft = (caseNo: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/manual-draft`,
|
||||
jsonPost({ comment }),
|
||||
);
|
||||
|
||||
/** 将当前 PDF 独立处置为非订单,服务端不会影响同一 Run 的其他 PDF。 */
|
||||
export const markWorkspaceShippingOrderReviewNonOrder = (caseNo: string, reason: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/disposition/non-order`,
|
||||
jsonPost({ reason, comment }),
|
||||
);
|
||||
|
||||
/** 标记质量异常但保留原始 PDF、机器结果和草稿,供补件或重识别。 */
|
||||
export const markWorkspaceShippingOrderReviewQualityIssue = (caseNo: string, reason: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewCase>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/disposition/quality-issue`,
|
||||
jsonPost({ reason, comment }),
|
||||
);
|
||||
|
||||
/** 仅创建当前 Case PDF 的后继识别 Run,重复点击幂等复用同一个处理中 Run。 */
|
||||
export const reparseWorkspaceShippingOrderReviewDocument = (caseNo: string, reason: string, comment?: string) =>
|
||||
requestJson<ShippingOrderReviewReparseResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/reparse`,
|
||||
jsonPost({ reason, comment }),
|
||||
);
|
||||
|
||||
/** 绑定已上传的替代 PDF;预解析成功后再单独创建替代识别 Run。 */
|
||||
export const createWorkspaceShippingOrderReviewReplacementIntake = (caseNo: string, assetNo: string) =>
|
||||
requestJson<ShippingNoticeIntakeResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-intakes`,
|
||||
jsonPost({ asset_no: assetNo }),
|
||||
);
|
||||
|
||||
/** 替代 Intake 解析成唯一 PDF 后创建新的单文档 Run。 */
|
||||
export const createWorkspaceShippingOrderReviewReplacementRun = (caseNo: string, intakeNo: string) =>
|
||||
requestJson<ShippingOrderReviewReparseResponse>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/replacement-runs`,
|
||||
jsonPost({ intake_no: intakeNo }),
|
||||
);
|
||||
|
||||
/** 获取复核字段的安全证据摘要;PDF 二进制继续由受控同源预览接口提供。 */
|
||||
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string) =>
|
||||
requestJson<{ case_no: string; items: ShippingOrderReviewEvidence[] }>(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence`,
|
||||
);
|
||||
|
||||
/** 以认证请求取得 PDF Blob,避免 iframe 无法携带 JWT 而退化为公开预览 URL。 */
|
||||
export async function getWorkspaceShippingOrderReviewPreview(caseNo: string): Promise<Blob> {
|
||||
const response = await fetch(
|
||||
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/document-preview`,
|
||||
{ headers: getAuthHeaders() },
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new BusinessError({ message: 'Review PDF preview failed', code: 'SHIPPING.REVIEW_PREVIEW_NOT_FOUND', status: response.status });
|
||||
}
|
||||
return response.blob();
|
||||
}
|
||||
|
||||
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
|
||||
export const listWorkspaceShippingOrderExtractionProgressEvents = (runNo: string) =>
|
||||
requestJson<{ items: ShippingOrderExtractionProgressEvent[] }>(
|
||||
@@ -762,7 +888,7 @@ export const refreshShippingNoticeDuplicate = (intakeNo: string) =>
|
||||
|
||||
export const updateShippingNoticeCandidate = (
|
||||
candidateNo: string,
|
||||
patch: { selected?: boolean; business_summary?: Record<string, unknown> },
|
||||
patch: { selected: boolean },
|
||||
) => requestJson<import('../types/shipping.api.types').ShippingNoticeCandidateResponse>(
|
||||
`/api/workspace/shipping-notice/candidates/${encodeURIComponent(candidateNo)}`,
|
||||
{
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* 逻辑:附件卡片位于文本框上方;订单审核结果随对应聊天消息展示,输入区只保留附件处理状态。
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import type { Ref } from 'vue';
|
||||
import {
|
||||
@@ -82,7 +82,6 @@ const emit = defineEmits<{
|
||||
'retry-shipping-notice-attachment': [id: string];
|
||||
'resolve-shipping-notice-duplicate': [id: string];
|
||||
'select-shipping-candidate': [candidateNo: string, selected: boolean];
|
||||
'update-shipping-candidate': [candidateNo: string, businessSummary: Record<string, unknown>, done: (success: boolean) => void];
|
||||
'resolve-shipping-candidate-duplicate': [candidateNo: string, action: import('../types/shipping.types').ShippingDuplicateAction, targetTaskNo: string | undefined, reason: string | undefined, done: (success: boolean) => void];
|
||||
'local-files-selected': [event: Event];
|
||||
'add-remote-url': [url: string];
|
||||
@@ -104,6 +103,16 @@ const showAttachmentUrlPanel = ref(false);
|
||||
const showKbDropdown = ref(false);
|
||||
const attachmentUrlInput = ref('');
|
||||
|
||||
/** 当前发货通知是否仍在上传或预解析,决定输入框下方的操作提示。 */
|
||||
const hasShippingNoticeInProgress = computed(() => props.attachments.some(
|
||||
(attachment) => attachment.kind === 'shipping_notice'
|
||||
&& (
|
||||
attachment.uploadStatus === 'waiting'
|
||||
|| attachment.uploadStatus === 'uploading'
|
||||
|| ['waiting', 'queued', 'parsing'].includes(attachment.parseStatus)
|
||||
),
|
||||
));
|
||||
|
||||
/**
|
||||
* 汇总 EML 附件解析进度,供输入栏徽标展示。
|
||||
* 核心逻辑:阶段 1 仅展示快览结果;优先说明发现了多少附件,技术失败/目录不完整再退化为问题提示。
|
||||
@@ -464,14 +473,7 @@ watch(
|
||||
v-if="isShippingNoticeAgent && attachments.length > 0"
|
||||
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-default bg-surface-soft px-3 py-1 font-medium text-secondary transition-colors hover:bg-surface-soft/70"
|
||||
@click="emit('use-shipping-suggested-prompt')"
|
||||
>
|
||||
{{ shippingSuggestedPrompt || '推荐问题' }}
|
||||
</button>
|
||||
<span>{{ t('chat.shippingNoticeConfirmBatchHint') }}</span>
|
||||
<span>{{ hasShippingNoticeInProgress ? t('chat.shippingNoticeWaitingForParse') : t('chat.shippingNoticeConfirmBatchHint') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-1.5 flex items-center justify-between px-1.5 pb-0.5">
|
||||
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user