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