feat(shipping-notice): 增强订单抽取与审计功能,支持取消与保留策略
- 在环境配置中新增进度细化、订单提取取消与审计导出相关的开关 - 实现订单抽取运行的取消功能,允许管理员在运行中进行操作 - 引入审计事件的保留策略,支持三年保留期的自动清理 - 更新相关模型与服务,确保新功能的完整性与可追溯性 - 增强文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
1 parent
c85997884b
commit
95cdfe66b0
158 files changed
+19005
-1201
No files matched your search
@@ -67,6 +67,11 @@ HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
# 进度细化灰度(阶段 5):新进度 UI / Run-Unit 取消 / 管理员审计导出;回滚只关开关,不删审计
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
|
||||
@@ -72,6 +72,12 @@ WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# 进度细化灰度(阶段 5;生产默认开启,回滚时按需关闭,禁止删除审计事实)
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
|
||||
@@ -156,6 +156,8 @@ SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow
|
||||
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
||||
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
|
||||
# 货代统一审计默认保留天数(三年);到期由 shipping-audit-retention Job 清理。
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
|
||||
# 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true)
|
||||
|
||||
@@ -77,6 +77,11 @@ WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
# 进度细化灰度(阶段 5):新进度 UI / Run-Unit 取消 / 管理员审计导出;回滚只关开关,不删审计
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED=true
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED=true
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
|
||||
@@ -220,10 +220,11 @@ def complete_order_document_profile_wizard():
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_order_document_profile():
|
||||
"""创建一个模板 Profile 草稿。"""
|
||||
return _ok(service.save_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
"""拒绝旧建模入口;新草稿必须经向导原子绑定样本、Revision 和编辑租约。"""
|
||||
raise service.ValidationError(
|
||||
'Create order document profiles through the sample wizard',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@@ -540,6 +541,15 @@ def get_order_document_profile_preview_page_text_candidates(profile_id: int, pag
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/preview-pages/<int:page_no>/region-text', methods=['POST'])
|
||||
@require_admin
|
||||
def read_order_document_profile_preview_page_region_text(profile_id: int, page_no: int):
|
||||
"""读取当前绑定样本中管理员框选区域的文字,用于创建文档匹配锚点。"""
|
||||
return _private_ok(service.read_preview_page_region_text(
|
||||
profile_id, data=request.get_json(silent=True) or {}, page_no=page_no, actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/preview-region', methods=['POST'])
|
||||
@require_admin
|
||||
def preview_order_document_profile_region(profile_id: int):
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_order_extraction.py
|
||||
|
||||
用途:提供订单抽取异步 Run 的管理员运维健康视图。
|
||||
依赖:admin Blueprint、require_admin、order_extraction_run_service。
|
||||
逻辑:路由校验监控窗口与阈值后返回安全聚合指标,不暴露文档、Provider 配置或错误正文。
|
||||
用途:提供订单抽取异步 Run 的管理员运维健康视图、任意 Run 取消与货代统一审计查询/导出。
|
||||
依赖:admin Blueprint、require_admin、order_extraction_run_service、order_extraction_cancel_service、audit_query_service。
|
||||
逻辑:健康/诊断只读;POST cancel 复用取消服务(代取消他人必须原因);审计接口只读查询/受控导出,访问留痕。
|
||||
"""
|
||||
|
||||
from flask import g, request
|
||||
from flask import Response, g, request
|
||||
|
||||
from app import db
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
@@ -46,17 +46,23 @@ def get_shipping_order_extraction_health():
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_extraction_diagnostic_runs():
|
||||
"""分页返回只读订单识别运行摘要;所有管理员默认可查看且访问留痕。"""
|
||||
"""分页返回只读订单识别运行摘要;支持状态、积压卡住、取消中筛选,访问留痕。"""
|
||||
page = _query_int('page', 1)
|
||||
page_size = _query_int('page_size', 25)
|
||||
if page < 1 or not 1 <= page_size <= 100:
|
||||
raise ValidationError('page must be positive and page_size must be between 1 and 100')
|
||||
stale_raw = str(request.args.get('stale_only') or '').strip().lower()
|
||||
cancel_raw = str(request.args.get('cancellation_in_flight') or '').strip().lower()
|
||||
payload = list_order_extraction_diagnostic_runs(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
status=request.args.get('status'),
|
||||
stale_only=stale_raw in {'1', 'true', 'yes'},
|
||||
cancellation_in_flight=cancel_raw in {'1', 'true', 'yes'},
|
||||
queued_stale_seconds=_query_int('queued_stale_seconds', 300),
|
||||
running_stale_seconds=_query_int('running_stale_seconds', 1800),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
@@ -64,7 +70,7 @@ def list_shipping_order_extraction_diagnostic_runs():
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_extraction_diagnostic_run_detail(run_no: str):
|
||||
"""读取单次 Run 的脱敏诊断详情;无重试、取消或其他状态变更操作。"""
|
||||
"""读取单次 Run 的脱敏诊断详情;访问留痕;取消走独立 POST。"""
|
||||
payload = get_order_extraction_diagnostic_run(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
@@ -73,6 +79,31 @@ def get_shipping_order_extraction_diagnostic_run_detail(run_no: str):
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs/<run_no>/cancel', methods=['POST'])
|
||||
@require_admin
|
||||
def admin_cancel_shipping_order_extraction_run(run_no: str):
|
||||
"""
|
||||
管理员取消任意活跃订单抽取 Run。
|
||||
|
||||
核心逻辑:复用 cancel_order_extraction_run;代取消他人必须提供 reason(服务层校验)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
|
||||
run = cancel_order_extraction_run(
|
||||
actor=g.current_user,
|
||||
run_no=run_no,
|
||||
reason=str(body.get('reason') or '') or None,
|
||||
reason_code=str(body.get('reason_code') or 'admin_cancelled') or 'admin_cancelled',
|
||||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'run': serialize_order_extraction_run(run)}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-quality-batches', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_extraction_quality_batches():
|
||||
@@ -153,3 +184,176 @@ def approve_shipping_order_extraction_quality_batch(batch_id: int):
|
||||
batch_id=batch_id, role=str(body.get('role') or ''), actor_id=g.current_user.id,
|
||||
)
|
||||
return ok(serialize_quality_batch(batch), request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
def _audit_filters_from_request() -> dict:
|
||||
"""从 query/json 收集审计筛选字段。"""
|
||||
source = request.args if request.method == 'GET' else (request.get_json(silent=True) or {})
|
||||
if not isinstance(source, dict):
|
||||
raise ValidationError('filters must be an object')
|
||||
keys = (
|
||||
'event_type', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id',
|
||||
'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'result',
|
||||
'conversation_id', 'session_item_id', 'review_case_no', 'owner_user_id',
|
||||
'created_from', 'created_to', 'q',
|
||||
)
|
||||
return {key: str(source.get(key) or '').strip() or None for key in keys}
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/session-work-items', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_session_work_items_supervision():
|
||||
"""
|
||||
管理员监管台:跨用户筛选会话 PDF 工作项。
|
||||
|
||||
核心逻辑:投影后写访问审计(查询者、筛选条件、结果数量),审计失败则阻断响应。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import project_admin_supervision_page
|
||||
|
||||
owner_raw = request.args.get('owner_user_id')
|
||||
owner_user_id = int(owner_raw) if owner_raw not in (None, '') else None
|
||||
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
q = str(request.args.get('q') or '').strip() or None
|
||||
page = _query_int('page', 1)
|
||||
page_size = _query_int('page_size', 20)
|
||||
payload = project_admin_supervision_page(
|
||||
lifecycle_status=lifecycle_status,
|
||||
owner_user_id=owner_user_id,
|
||||
conversation_id=conversation_id,
|
||||
q=q,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
record_access_audit(
|
||||
action='admin_list_session_work_items',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='supervision',
|
||||
actor_id=int(g.current_user.id),
|
||||
actor_type='admin',
|
||||
conversation_id=conversation_id,
|
||||
owner_user_id=owner_user_id,
|
||||
metadata={
|
||||
'lifecycle_status': lifecycle_status,
|
||||
'q': q,
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'result_count': len(payload.get('items') or []),
|
||||
'total': int(payload.get('total') or 0),
|
||||
},
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/session-work-items/<item_no>/terminate', methods=['POST'])
|
||||
@require_admin
|
||||
def terminate_shipping_session_work_item(item_no: str):
|
||||
"""管理员终止工作项;必须理由 + CONFIRM_TERMINATE。"""
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import serialize_session_work_item
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import terminate_work_item_as_admin
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
item = terminate_work_item_as_admin(
|
||||
admin_user_id=int(g.current_user.id),
|
||||
item_no=item_no,
|
||||
reason=str(body.get('reason') or ''),
|
||||
confirm_token=str(body.get('confirm_token') or ''),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
operation_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'item': serialize_session_work_item(item)}, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/session-work-items/<item_no>/revoke-confirmation', methods=['POST'])
|
||||
@require_admin
|
||||
def revoke_shipping_session_work_item_confirmation(item_no: str):
|
||||
"""管理员 24 小时内撤销确认;库存匹配后拒绝并记受控异常。"""
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import revoke_review_confirmation
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
payload = revoke_review_confirmation(
|
||||
admin_user_id=int(g.current_user.id),
|
||||
item_no=item_no,
|
||||
reason=str(body.get('reason') or ''),
|
||||
confirm_token=str(body.get('confirm_token') or ''),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
operation_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-events', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_notice_audit_events():
|
||||
"""分页查询货代统一审计事件;访问留痕,不返回快照全文。"""
|
||||
from app.services.shipping_notice.audit_query_service import list_shipping_audit_events
|
||||
|
||||
page = _query_int('page', 1)
|
||||
page_size = _query_int('page_size', 25)
|
||||
if page < 1 or not 1 <= page_size <= 100:
|
||||
raise ValidationError('page must be positive and page_size must be between 1 and 100')
|
||||
payload = list_shipping_audit_events(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
filters=_audit_filters_from_request(),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-events/<int:event_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_notice_audit_event(event_id: int):
|
||||
"""读取单条审计详情,含白名单快照与前后差异。"""
|
||||
from app.services.shipping_notice.audit_query_service import get_shipping_audit_event
|
||||
|
||||
payload = get_shipping_audit_event(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
event_id=event_id,
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/audit-events/export', methods=['POST'])
|
||||
@require_admin
|
||||
def export_shipping_notice_audit_events():
|
||||
"""受控导出审计 CSV/JSON;写导出访问审计,禁止敏感正文。"""
|
||||
from app.services.shipping_notice.audit_query_service import export_shipping_audit_events
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
filters = {
|
||||
key: str(body.get(key) or '').strip() or None
|
||||
for key in (
|
||||
'event_type', 'actor_type', 'actor_id', 'run_no', 'task_no', 'document_id',
|
||||
'operation_id', 'request_id', 'aggregate_type', 'aggregate_id', 'result',
|
||||
'conversation_id', 'session_item_id', 'review_case_no', 'owner_user_id',
|
||||
'created_from', 'created_to', 'q',
|
||||
)
|
||||
}
|
||||
exported = export_shipping_audit_events(
|
||||
admin_user_id=g.current_user.id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
filters=filters,
|
||||
limit=int(body.get('limit') or 2000),
|
||||
format=str(body.get('format') or 'csv'),
|
||||
)
|
||||
return Response(
|
||||
exported['content'],
|
||||
status=200,
|
||||
mimetype=exported['content_type'],
|
||||
headers={
|
||||
'Content-Disposition': f'attachment; filename="{exported["filename"]}"',
|
||||
'X-Exported-Count': str(exported['exported']),
|
||||
},
|
||||
)
|
||||
@@ -971,7 +971,7 @@ def workspace_generate_shipping_excel(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
err_msg = task_export_error_message(task)
|
||||
@@ -980,6 +980,15 @@ def workspace_shipping_task_export(task_no: str):
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_task_excel',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
actor_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
metadata={'export': 'excel'},
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@@ -1053,54 +1062,106 @@ def workspace_create_shipping_order_extraction_run():
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
"""查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端。"""
|
||||
"""查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
get_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
return _ok(serialize_order_extraction_run(get_order_extraction_run(user_id=user.id, run_no=run_no)))
|
||||
run = get_order_extraction_run(user_id=user.id, run_no=run_no)
|
||||
payload = serialize_order_extraction_run(run)
|
||||
# 轮询接口 60s 节流:窗口内复用最近访问痕迹,仍可追溯访问者与范围。
|
||||
record_access_audit(
|
||||
action='view_order_extraction_run',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.run_no),
|
||||
actor_id=user.id,
|
||||
run_no=str(run.run_no),
|
||||
conversation_id=run.conversation_id,
|
||||
metadata={'status': str(run.status or ''), 'poll': True},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/progress-events', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_progress_events(run_no: str):
|
||||
"""返回当前用户展开状态卡时所需的脱敏业务阶段时间线。"""
|
||||
"""返回当前用户展开状态卡时所需的脱敏业务阶段时间线;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
|
||||
|
||||
return _ok({'items': list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)})
|
||||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)
|
||||
record_access_audit(
|
||||
action='view_order_extraction_timeline',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run_no),
|
||||
actor_id=user.id,
|
||||
run_no=str(run_no),
|
||||
metadata={'event_count': len(items or []), 'poll': True},
|
||||
)
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/documents', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_documents(run_no: str):
|
||||
"""返回当前用户一次订单抽取的按 PDF 归并详情。"""
|
||||
"""返回当前用户一次订单抽取的按 PDF 归并详情;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_documents
|
||||
|
||||
return _ok({'items': list_user_order_extraction_documents(user_id=user.id, run_no=run_no)})
|
||||
items = list_user_order_extraction_documents(user_id=user.id, run_no=run_no)
|
||||
record_access_audit(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run_no),
|
||||
actor_id=user.id,
|
||||
run_no=str(run_no),
|
||||
metadata={'document_count': len(items or []), 'poll': True},
|
||||
)
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/review', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_run(run_no: str):
|
||||
"""读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照。"""
|
||||
"""读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||||
|
||||
return _ok(serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin)))
|
||||
payload = serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin))
|
||||
record_access_audit(
|
||||
action='view_order_review_run',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run_no),
|
||||
actor_id=user.id,
|
||||
run_no=str(run_no),
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_case(case_no: str):
|
||||
"""读取当前用户的一份 PDF 复核详情;Case 编号不能跨 owner 越权访问。"""
|
||||
"""读取当前用户的一份 PDF 复核详情;Case 编号不能跨 owner 越权访问;访问留痕。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
return _ok(serialize_review_case(get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)))
|
||||
payload = serialize_review_case(get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin))
|
||||
record_access_audit(
|
||||
action='view_order_review_case',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
review_case_no=str(case_no),
|
||||
run_no=str(payload.get('run_no') or '') or None if isinstance(payload, dict) else None,
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
def _review_draft_payload() -> dict:
|
||||
@@ -1302,29 +1363,57 @@ def workspace_create_shipping_order_review_replacement_run(case_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/evidence', methods=['GET'])
|
||||
def workspace_list_shipping_order_review_evidence(case_no: str):
|
||||
"""列出当前用户 PDF 的安全证据摘要;不泄露全文、对象存储位置或模型响应。"""
|
||||
"""列出当前用户 PDF 的安全证据摘要;不泄露全文、对象存储位置或模型响应;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_evidence_service import list_case_evidence
|
||||
|
||||
return _ok(list_case_evidence(user_id=user.id, case_no=case_no))
|
||||
payload = list_case_evidence(user_id=user.id, case_no=case_no)
|
||||
record_access_audit(
|
||||
action='view_order_review_evidence_list',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
review_case_no=str(case_no),
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/evidence/<evidence_id>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_evidence(case_no: str, evidence_id: str):
|
||||
"""读取当前用户的一条字段证据,用于问题导航;evidence_id 不可跨 Case 使用。"""
|
||||
"""读取当前用户的一条字段证据,用于问题导航;evidence_id 不可跨 Case 使用;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence
|
||||
|
||||
return _ok(get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id))
|
||||
payload = get_case_evidence(user_id=user.id, case_no=case_no, evidence_id=evidence_id)
|
||||
record_access_audit(
|
||||
action='view_order_review_evidence',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
review_case_no=str(case_no),
|
||||
metadata={'evidence_id': str(evidence_id)[:64]},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/document-preview', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_document(case_no: str):
|
||||
"""应用代理当前用户的 PDF 预览流;禁止向浏览器下发 MinIO key 或直连地址。"""
|
||||
"""应用代理当前用户的 PDF 预览流;禁止向浏览器下发 MinIO key 或直连地址;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_pdf_bytes
|
||||
|
||||
content, filename = get_case_pdf_bytes(user_id=user.id, case_no=case_no)
|
||||
record_access_audit(
|
||||
action='preview_order_review_document',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
review_case_no=str(case_no),
|
||||
metadata={'preview': 'pdf'},
|
||||
)
|
||||
return send_file(
|
||||
BytesIO(content), mimetype='application/pdf', as_attachment=False, download_name=filename,
|
||||
conditional=True,
|
||||
@@ -1333,11 +1422,34 @@ def workspace_preview_shipping_order_review_document(case_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/seen', methods=['POST'])
|
||||
def workspace_mark_shipping_order_extraction_run_seen(run_no: str):
|
||||
"""确认当前用户已加载终态订单识别卡片;仅用于会话待查看提醒,不改变业务结果。"""
|
||||
"""确认当前用户已加载终态订单识别卡片;写入已读状态变更审计。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import mark_order_extraction_run_seen
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
get_order_extraction_run,
|
||||
mark_order_extraction_run_seen,
|
||||
)
|
||||
|
||||
run = get_order_extraction_run(user_id=user.id, run_no=run_no)
|
||||
before = {'status': 'seen' if run.seen_at is not None else 'unseen'}
|
||||
seen = mark_order_extraction_run_seen(user_id=user.id, run_no=run_no)
|
||||
after_status = 'seen' if (seen or run.seen_at is not None) else before['status']
|
||||
record_fulfillment_audit(
|
||||
event_type='order_extraction_run_seen',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run.run_no),
|
||||
action='mark_run_seen',
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
run_no=str(run.run_no),
|
||||
conversation_id=run.conversation_id,
|
||||
result='success' if seen else ('ignored' if before['status'] == after_status else 'success'),
|
||||
before=before,
|
||||
after={'status': after_status},
|
||||
metadata={'first_seen': bool(seen)},
|
||||
source='api',
|
||||
strict=True,
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'seen': seen})
|
||||
|
||||
@@ -1360,6 +1472,86 @@ def workspace_retry_shipping_order_extraction_run(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/cancel', methods=['POST'])
|
||||
def workspace_cancel_shipping_order_extraction_run(run_no: str):
|
||||
"""
|
||||
请求取消整批订单抽取。
|
||||
|
||||
核心逻辑:排队项立即取消,执行中项进入正在取消;已完成结果保留。管理员代取消必须写原因。
|
||||
"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
|
||||
run = cancel_order_extraction_run(
|
||||
actor=user,
|
||||
run_no=run_no,
|
||||
reason=str(body.get('reason') or '') or None,
|
||||
reason_code=str(body.get('reason_code') or '') or None,
|
||||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok({'run': serialize_order_extraction_run(run)}, request_id=getattr(g, 'request_id', None), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-extraction-runs/<run_no>/documents/<int:document_id>/cancel',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_cancel_shipping_order_extraction_document(run_no: str, document_id: int):
|
||||
"""请求取消单个 PDF Unit;权限与原因规则同整批取消。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if body and not isinstance(body, dict):
|
||||
raise ValidationError('Request body must be an object')
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_unit
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_documents
|
||||
|
||||
unit = cancel_order_extraction_unit(
|
||||
actor=user,
|
||||
run_no=run_no,
|
||||
document_id=int(document_id),
|
||||
reason=str(body.get('reason') or '') or None,
|
||||
reason_code=str(body.get('reason_code') or '') or None,
|
||||
operation_id=str(body.get('operation_id') or getattr(g, 'request_id', '') or '') or None,
|
||||
)
|
||||
run = unit.plan.run if unit.plan is not None else None
|
||||
db.session.commit()
|
||||
documents = serialize_workspace_run_documents(run) if run is not None else []
|
||||
document = next((item for item in documents if int(item.get('document_id') or 0) == int(document_id)), None)
|
||||
return ok(
|
||||
{
|
||||
'run': serialize_order_extraction_run(run) if run is not None else None,
|
||||
'document': document,
|
||||
},
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
status=202,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/timeline', methods=['GET'])
|
||||
def workspace_shipping_order_extraction_timeline(run_no: str):
|
||||
"""返回用户可见的 Run 时间线,含取消请求与重试相关进度事件;访问留痕。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import list_user_order_extraction_progress_events
|
||||
|
||||
items = list_user_order_extraction_progress_events(user_id=user.id, run_no=run_no)
|
||||
record_access_audit(
|
||||
action='view_order_extraction_timeline',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=str(run_no),
|
||||
actor_id=user.id,
|
||||
run_no=str(run_no),
|
||||
metadata={'event_count': len(items or []), 'surface': 'timeline', 'poll': True},
|
||||
)
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/reparse', methods=['POST'])
|
||||
def workspace_reparse_shipping_order_extraction_run(run_no: str):
|
||||
"""
|
||||
@@ -1392,19 +1584,53 @@ def workspace_reparse_shipping_order_extraction_run(run_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_runs():
|
||||
"""列出当前用户订单抽取 Run,可按 HXOPS 会话过滤。"""
|
||||
"""
|
||||
列出当前用户订单抽取 Run。
|
||||
|
||||
核心逻辑:可按会话过滤;传 page 时返回分页供任务中心续办,否则保持会话内短列表契约。
|
||||
"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 50)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
page_raw = request.args.get('page')
|
||||
page_size_raw = request.args.get('page_size')
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
list_order_extraction_runs,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
rows = list_order_extraction_runs(user_id=user.id, conversation_id=conversation_id, limit=limit)
|
||||
if page_raw is not None or page_size_raw is not None:
|
||||
try:
|
||||
page = int(page_raw or 1)
|
||||
page_size = int(page_size_raw or 20)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('page and page_size must be integers') from exc
|
||||
payload = list_order_extraction_runs(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
status=status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
assert isinstance(payload, dict)
|
||||
return _ok({
|
||||
'items': [serialize_order_extraction_run(row) for row in payload['items']],
|
||||
'total': payload['total'],
|
||||
'page': payload['page'],
|
||||
'page_size': payload['page_size'],
|
||||
})
|
||||
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 50)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
rows = list_order_extraction_runs(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
status=status,
|
||||
limit=limit,
|
||||
)
|
||||
assert isinstance(rows, list)
|
||||
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
|
||||
|
||||
|
||||
@@ -1639,3 +1865,101 @@ def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/session-work-items', methods=['GET'])
|
||||
def workspace_list_session_work_items():
|
||||
"""
|
||||
会话 PDF 工作台读模型:未关闭/已关闭分组与统计。
|
||||
|
||||
核心逻辑:仅按 conversation_id 聚合工作项,禁止用最新 Run 充当本次处理范围;
|
||||
敏感读取写入访问审计(查询者、会话、结果数量、请求关联)。
|
||||
"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||
if not conversation_id:
|
||||
raise ValidationError('conversation_id is required', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CONVERSATION_REQUIRED')
|
||||
open_only = str(request.args.get('open_only') or '').strip().lower() in {'1', 'true', 'yes'}
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import project_session_workbench
|
||||
payload = project_session_workbench(
|
||||
user_id=int(user.id),
|
||||
conversation_id=conversation_id,
|
||||
open_only=open_only,
|
||||
include_closed=not open_only,
|
||||
)
|
||||
record_access_audit(
|
||||
action='list_session_work_items',
|
||||
aggregate_type='shipping_conversation',
|
||||
aggregate_id=conversation_id,
|
||||
actor_id=user.id,
|
||||
owner_user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
metadata={
|
||||
'open_count': int(payload.get('open_count') or 0),
|
||||
'closed_count': int(payload.get('closed_count') or 0),
|
||||
'open_only': open_only,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/session-work-items/<item_no>/versions', methods=['GET'])
|
||||
def workspace_list_session_work_item_versions(item_no: str):
|
||||
"""只读版本历史;旧版不可编辑或确认;访问写入审计。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import list_session_work_item_versions
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import get_work_item_for_user
|
||||
item = get_work_item_for_user(user_id=int(user.id), item_no=item_no)
|
||||
versions = list_session_work_item_versions(item=item)
|
||||
record_access_audit(
|
||||
action='list_session_work_item_versions',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id=str(item.item_no),
|
||||
actor_id=user.id,
|
||||
owner_user_id=item.owner_user_id,
|
||||
conversation_id=item.conversation_id,
|
||||
session_item_id=item.item_no,
|
||||
document_id=item.current_document_id,
|
||||
review_case_no=item.current_case_no,
|
||||
metadata={'version_count': len(versions)},
|
||||
)
|
||||
return _ok({
|
||||
'item_no': item.item_no,
|
||||
'current_case_no': item.current_case_no,
|
||||
'current_version_no': int(item.current_version_no or 1),
|
||||
'versions': versions,
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/session-work-items/<item_no>/close', methods=['POST'])
|
||||
def workspace_close_session_work_item(item_no: str):
|
||||
"""用户关闭工作项(取消确认);须填写原因。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
reason = str(body.get('reason') or '').strip()
|
||||
if not reason:
|
||||
raise ValidationError('reason is required', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSE_REASON_REQUIRED')
|
||||
expected_lock = body.get('expected_lock_version')
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import serialize_session_work_item
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
close_work_item,
|
||||
get_work_item_for_user,
|
||||
)
|
||||
item = get_work_item_for_user(user_id=int(user.id), item_no=item_no, for_update=True)
|
||||
close_work_item(
|
||||
item=item,
|
||||
closed_reason='user_cancelled',
|
||||
actor_type='user',
|
||||
actor_id=int(user.id),
|
||||
reason=reason,
|
||||
expected_lock_version=int(expected_lock) if expected_lock is not None else None,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
operation_id=getattr(g, 'request_id', None),
|
||||
event_type='session_work_item_cancelled',
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'item': serialize_session_work_item(item)})
|
||||
@@ -228,6 +228,19 @@ class Config:
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
# 进度细化 / 取消 / 审计导出灰度开关(阶段 5);默认 true,回滚 UI 时按需关闭,不删除审计事实。
|
||||
SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS = int(
|
||||
os.getenv('SHIPPING_NOTICE_AUDIT_RETENTION_DAYS') or '1095'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'false').lower() == 'true'
|
||||
)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取 Run,使用固定模板确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务。
|
||||
逻辑:每个 Unit 先持久化脱敏路由,再确定性解析或标记人工复核;不调用 Dify、Provider 或 Runtime Binding。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行,失败时同步收口 Run;每个 Unit 再确定性解析或标记人工复核;不调用 Dify、Provider 或 Runtime Binding。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -402,14 +402,24 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
|
||||
Returns:
|
||||
`list[dict]`: 当前单元产出的订单数组(确定性成功)。
|
||||
`None`: 当前单元进入 review_required 或最终技术失败。
|
||||
`None`: 当前单元进入 review_required、最终技术失败或取消中止。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
should_abort_unit_for_cancellation,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
while True:
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(unit)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit):
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
return None
|
||||
if unit.status == 'failed':
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
if unit.status in {'review_required', 'candidate_ready'}:
|
||||
if unit.status in {'review_required', 'candidate_ready', 'cancelled'}:
|
||||
return None
|
||||
transition_order_extraction_unit(unit, target_status='routing')
|
||||
record_unit_progress(run=run, unit=unit, event_code='document_queued', job_id=job.id)
|
||||
@@ -417,6 +427,12 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
|
||||
record_unit_progress(run=run, unit=unit, event_code='profile_matching', job_id=job.id)
|
||||
db.session.commit()
|
||||
try:
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(unit)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit):
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
return None
|
||||
route_result = route_deterministic_unit(run, unit=unit)
|
||||
_append_route_decision(
|
||||
run=run,
|
||||
@@ -488,12 +504,14 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次纯确定性订单抽取 Job。
|
||||
|
||||
核心逻辑:物化附件与排版面 Job 纳入主 try;排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,仅用于安全日志。
|
||||
payload: 必须包含 job_id;Run 身份只从 Job.business_ref 读取。
|
||||
|
||||
Raises:
|
||||
Exception: 技术故障交给 Job 队列重试;模板、证据和业务歧义不抛出为技术失败。
|
||||
Exception: 可重试技术故障交给 Job 队列重试;模板、证据和业务歧义不抛出为技术失败。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
@@ -511,36 +529,37 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
fail_job(job.id, error=f'run status is not executable: {run.status}', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'waiting_layout': True}, message='等待附件版面解析', owned_attempt=owned_attempt)
|
||||
return
|
||||
if layout_issues:
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='Order PDF layout prerequisites are incomplete',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'document_count': len(layout_issues)}, job_id=job.id, commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'layout_issues': layout_issues}, message='订单附件解析条件不完整', owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
# [STEP 1] 邮件附件先物化成 Document,再排布局 Job;发送阶段没有 PDF Document。
|
||||
# 必须落在本 try 内:MinerU 关闭/排程失败时 ValidationError 需同步收口 Run,避免 Job 重试耗尽前 UI 一直 queued。
|
||||
materialize_order_extraction_run_inputs(run, finalize_plan=False)
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'waiting_layout': True}, message='等待附件版面解析', owned_attempt=owned_attempt)
|
||||
return
|
||||
if layout_issues:
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='Order PDF layout prerequisites are incomplete',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'document_count': len(layout_issues)}, job_id=job.id, commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'layout_issues': layout_issues}, message='订单附件解析条件不完整', owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
# [STEP 3] 所有 PDF 布局就绪后重建快照,此时才冻结带坐标证据的执行计划。
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
if plan is None:
|
||||
@@ -574,6 +593,15 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
|
||||
# [STEP 1] 每个文档独立路由;当前批次未完整收敛时,再按冻结计划激活下一批附件。
|
||||
while True:
|
||||
db.session.refresh(run)
|
||||
if run.cancellation_requested_at is not None:
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
)
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
if run.status == 'cancelled':
|
||||
break
|
||||
if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds:
|
||||
runtime_budget_stopped = True
|
||||
record_run_progress(
|
||||
@@ -584,6 +612,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
units = _units_for_batch(plan, selection_batch=current_batch)
|
||||
wave_orders: list[dict] = []
|
||||
for unit in units:
|
||||
db.session.refresh(run)
|
||||
if run.cancellation_requested_at is not None:
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
should_abort_unit_for_cancellation,
|
||||
)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit) or unit.status == 'pending':
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
continue
|
||||
# 总时限不能中断正在进行的外部解析,但禁止在到期后启动新的 Unit。
|
||||
if max_runtime_seconds and time.perf_counter() - started >= max_runtime_seconds:
|
||||
runtime_budget_stopped = True
|
||||
@@ -749,6 +787,16 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
job_id=job.id,
|
||||
)
|
||||
# [STEP] 每 PDF 独立下游:立刻物化 Candidate / STP 建单,不阻塞同批其它 Unit。
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(unit)
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
should_abort_unit_for_cancellation,
|
||||
)
|
||||
if should_abort_unit_for_cancellation(run=run, unit=unit):
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
continue
|
||||
try:
|
||||
unit_persist = progress_ready_extraction_unit(
|
||||
run=run, unit=unit, orders=merged_unit_orders,
|
||||
@@ -791,6 +839,44 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_run_result(run=run, orders=orders)
|
||||
requires_review = runtime_budget_stopped or _result_requires_review(units=units, result=result)
|
||||
pending_orders = [
|
||||
{
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'po_number': str(item.get('po_number') or '').strip() or None,
|
||||
'reasons': [
|
||||
str(code).strip()[:96]
|
||||
for code in (item.get('reasons') or [])
|
||||
if str(code or '').strip()
|
||||
][:12],
|
||||
'missing_fields': [
|
||||
str(field).strip()
|
||||
for field in (item.get('missing_fields') or [])
|
||||
if str(field or '').strip()
|
||||
][:20],
|
||||
'duplicate_status': str(item.get('duplicate_status') or '').strip() or None,
|
||||
}
|
||||
for item in (result.get('pending_orders') or [])
|
||||
if isinstance(item, dict)
|
||||
][:50]
|
||||
auto_freeze = result.get('auto_freeze') if isinstance(result.get('auto_freeze'), dict) else {}
|
||||
blocked_tasks = [
|
||||
{
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'task_no': str(item.get('task_no') or '').strip() or None,
|
||||
'code': str(item.get('code') or '').strip() or None,
|
||||
}
|
||||
for item in (auto_freeze.get('blocked_tasks') or [])
|
||||
if isinstance(item, dict)
|
||||
][:30]
|
||||
selection_summary = _selection_progress_summary(run)
|
||||
budget_stopped = bool(
|
||||
runtime_budget_stopped
|
||||
or (
|
||||
selection_summary.get('budget_limited_attachment_count', 0) > 0
|
||||
and bool(requires_review)
|
||||
)
|
||||
)
|
||||
# 收口摘要保留可投影的处理事实,供 Run 级 handling_items 区分待补/冲突/冻结/复核。
|
||||
summary = {
|
||||
'run_no': run.run_no, 'batch_no': result.get('batch_no'),
|
||||
'created_count': int(result.get('created_count') or 0),
|
||||
@@ -798,6 +884,13 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
'non_shipping_count': int(result.get('non_shipping_count') or 0),
|
||||
'execution': execution, 'requires_review': requires_review,
|
||||
'pending_orders': pending_orders,
|
||||
'auto_freeze': {
|
||||
'frozen_task_count': len(auto_freeze.get('frozen_task_nos') or []),
|
||||
'blocked_task_count': len(blocked_tasks),
|
||||
'blocked_tasks': blocked_tasks,
|
||||
},
|
||||
'budget_stopped': budget_stopped,
|
||||
}
|
||||
final_status = (
|
||||
'failed'
|
||||
@@ -808,7 +901,22 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if requires_review
|
||||
else 'completed'
|
||||
)
|
||||
selection_summary = _selection_progress_summary(run)
|
||||
db.session.refresh(run)
|
||||
if run.cancellation_requested_at is not None:
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
finalize_run_cancellation_if_ready,
|
||||
)
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
finalize_run_cancellation_if_ready(
|
||||
run=run,
|
||||
actor_type='system',
|
||||
actor_id='shipping_order_extraction_worker',
|
||||
)
|
||||
db.session.commit()
|
||||
if run.status == 'cancelled':
|
||||
finish_job(job.id, result={'cancelled': True, 'run_no': run.run_no}, message='订单抽取已取消', owned_attempt=owned_attempt)
|
||||
return
|
||||
if selection_summary['budget_limited_attachment_count'] > 0 and final_status != 'completed':
|
||||
budget_stop_reason_codes = _expansion_trigger_reason_codes(
|
||||
wave_units=units,
|
||||
|
||||
@@ -727,6 +727,23 @@ def _sync_parse_intake_after_job_mutation(job_id: int) -> None:
|
||||
sync_intake_after_parse_job_recovery(job)
|
||||
|
||||
|
||||
def _sync_shipping_order_extraction_run_after_job_failure(job_id: int) -> None:
|
||||
"""将最终失败的订单抽取 Job 收口到对应 Run,避免用户界面永久轮询。"""
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None or str(job.job_type or '') != JobType.SHIPPING_ORDER_EXTRACTION.value:
|
||||
return
|
||||
db.session.expire(job)
|
||||
db.session.refresh(job)
|
||||
if str(job.status or '') != 'failed':
|
||||
return
|
||||
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
sync_order_extraction_run_after_job_failure,
|
||||
)
|
||||
|
||||
sync_order_extraction_run_after_job_failure(job)
|
||||
|
||||
|
||||
def finish_job(
|
||||
job: Job | int,
|
||||
*,
|
||||
@@ -934,6 +951,8 @@ def fail_job(
|
||||
rowcount = int(db.session.execute(fail_stmt).rowcount or 0)
|
||||
if rowcount == 1:
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
# 订单抽取的用户态以 Run 为准;Job 耗尽重试后必须同事务收口。
|
||||
_sync_shipping_order_extraction_run_after_job_failure(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return rowcount == 1
|
||||
|
||||
@@ -73,6 +73,7 @@ from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_session_pdf_work_item import ShippingSessionPdfWorkItem
|
||||
from app.models.shipping_order_document_profile import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
@@ -197,6 +198,7 @@ __all__ = [
|
||||
'ShippingOrderExtractionProgressEvent',
|
||||
'ShippingOrderExtractionDiagnosticAudit',
|
||||
'ShippingAuditEvent',
|
||||
'ShippingSessionPdfWorkItem',
|
||||
'ShippingOrderExtractionQualityBatch',
|
||||
'ShippingOrderExtractionQualityLabel',
|
||||
'ShippingOrderDocumentProfile',
|
||||
|
||||
@@ -2,16 +2,19 @@
|
||||
backend/app/models/shipping_audit_event.py
|
||||
|
||||
用途:定义货代领域统一、仅追加的审计事件。
|
||||
依赖:SQLAlchemy Base、货代 Run/Task/Intake 的稳定业务编号。
|
||||
依赖:SQLAlchemy Base、货代 Run/Task/Intake/会话 PDF 工作项的稳定业务编号。
|
||||
逻辑:各业务服务通过 audit_service 追加事件;事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。
|
||||
进度审计阶段扩展 operation_id、对象关联、白名单前后快照、证据引用、结果与保留到期时间;
|
||||
会话工作项阶段追加 owner_user_id、session_item_id 与脱敏 client_ip_hash/user_agent_hash;
|
||||
禁止存储 PDF/邮件正文、模型原文、对象存储 URL、原始 IP/UA 或密钥。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, Index, Integer, JSON, String, event
|
||||
from sqlalchemy import CheckConstraint, DateTime, Index, Integer, JSON, String, Text, event
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -27,9 +30,23 @@ class ShippingAuditEvent(Base):
|
||||
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')",
|
||||
name='ck_shipping_audit_events_actor_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
|
||||
name='ck_shipping_audit_events_result',
|
||||
),
|
||||
Index('ix_shipping_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_run_created', 'run_no', 'created_at'),
|
||||
Index('ix_shipping_audit_events_task_created', 'task_no', 'created_at'),
|
||||
Index('ix_shipping_audit_events_operation_created', 'operation_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_request_created', 'request_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_conversation_created', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_document_created', 'document_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_unit_created', 'unit_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_actor_created', 'actor_type', 'actor_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_event_type_created', 'event_type', 'created_at'),
|
||||
Index('ix_shipping_audit_events_retention_expires', 'retention_expires_at', 'id'),
|
||||
Index('ix_shipping_audit_events_session_item_created', 'session_item_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_owner_created', 'owner_user_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -41,12 +58,37 @@ class ShippingAuditEvent(Base):
|
||||
intake_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
|
||||
actor_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
actor_role: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
request_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
operation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
correlation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
source: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
result: Mapped[str | None] = mapped_column(String(16), nullable=True)
|
||||
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
conversation_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
||||
unit_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
document_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
review_case_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 会话 PDF 工作项稳定编号(item_no);软引用,避免级联删除抹除审计。
|
||||
session_item_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 业务属主(非操作者);代操作场景与 actor_id 区分。
|
||||
owner_user_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
# 仅存哈希,禁止写入原始 IP / User-Agent。
|
||||
client_ip_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
user_agent_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
attempt_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
action: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
reason_code: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
reason: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
before_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
after_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
evidence_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
|
||||
artifact_refs_json: Mapped[Optional[list[dict[str, Any]]]] = mapped_column(JSON, nullable=True)
|
||||
context_refs_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
metadata_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
retention_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ backend/app/models/shipping_order_extraction_run.py
|
||||
用途:定义建单前订单抽取的领域运行记录及其冻结 Intake 集合。
|
||||
依赖:agents、users、jobs、shipping_notice_intakes、shipping_order_schema_versions。
|
||||
逻辑:Run 保存用户可见生命周期和不可变输入快照;自动建单策略随 Schema 快照冻结。
|
||||
取消为请求语义:cancellation_* 元数据记录请求与生效;Worker 在安全点收口,
|
||||
progress_version 作为最后活动版本供轮询与乐观协作。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -53,6 +55,16 @@ class ShippingOrderExtractionRun(Base):
|
||||
postgresql_where=text("status IN ('queued', 'processing')"),
|
||||
sqlite_where=text("status IN ('queued', 'processing')"),
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_runs_cancel_requested',
|
||||
'cancellation_requested_at',
|
||||
'status',
|
||||
),
|
||||
CheckConstraint(
|
||||
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
|
||||
"('user', 'admin', 'system')",
|
||||
name='ck_shipping_order_extraction_runs_cancel_actor',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -103,6 +115,13 @@ class ShippingOrderExtractionRun(Base):
|
||||
progress_mapping_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
attention_generated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
seen_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
# 取消请求元数据:请求不等于生效;排队 Unit 可立即 cancelled,执行中须等安全检查点。
|
||||
cancellation_requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
cancellation_actor_type: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
cancellation_actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
cancellation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
cancellation_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
cancellation_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
@@ -218,6 +237,16 @@ class ShippingOrderExtractionUnit(Base):
|
||||
),
|
||||
Index('ix_shipping_order_extraction_units_plan_status', 'plan_id', 'status'),
|
||||
Index('ix_shipping_order_extraction_units_document', 'document_id'),
|
||||
Index(
|
||||
'ix_shipping_order_extraction_units_cancel_requested',
|
||||
'cancellation_requested_at',
|
||||
'status',
|
||||
),
|
||||
CheckConstraint(
|
||||
"cancellation_actor_type IS NULL OR cancellation_actor_type IN "
|
||||
"('user', 'admin', 'system')",
|
||||
name='ck_shipping_order_extraction_units_cancel_actor',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -244,6 +273,14 @@ class ShippingOrderExtractionUnit(Base):
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
last_activity_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
# 单 Unit 活动版本;取消/重试与状态迁移同事务递增,供乐观协作与投影。
|
||||
activity_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
cancellation_requested_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
cancellation_actor_type: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
cancellation_actor_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
cancellation_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
cancellation_reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
cancellation_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
backend/app/models/shipping_session_pdf_work_item.py
|
||||
|
||||
用途:定义聊天会话内「PDF 工作项」聚合实体,作为本次处理的唯一业务边界。
|
||||
依赖:users、shipping_notice_documents、shipping_order_extraction_runs、shipping_order_review_cases。
|
||||
逻辑:同会话同源 PDF 仅一条工作项;重识别只切换 current_* 版本指针,不新建工作项;
|
||||
关闭后默认折叠。阶段 0 仅落库契约;写路径与读模型在阶段 1 实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingSessionPdfWorkItem(Base):
|
||||
"""会话级 PDF 工作项;当前有效 Run/Case 仅由本表指针表达,禁止前端按最新 Run 猜测。"""
|
||||
|
||||
__tablename__ = 'shipping_session_pdf_work_items'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('item_no', name='uq_shipping_session_pdf_work_items_no'),
|
||||
UniqueConstraint(
|
||||
'conversation_id',
|
||||
'root_document_id',
|
||||
name='uq_shipping_session_pdf_work_items_conversation_root_doc',
|
||||
),
|
||||
# 同一 Case 最多作为一条工作项的当前有效版本,防止双指针并发确认。
|
||||
UniqueConstraint(
|
||||
'current_case_id',
|
||||
name='uq_shipping_session_pdf_work_items_current_case',
|
||||
),
|
||||
CheckConstraint(
|
||||
"lifecycle_status IN ("
|
||||
"'pending_review', 'extracting', 'reparse_failed', 'closed'"
|
||||
")",
|
||||
name='ck_shipping_session_pdf_work_items_lifecycle',
|
||||
),
|
||||
CheckConstraint(
|
||||
"closed_reason IS NULL OR closed_reason IN ("
|
||||
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated'"
|
||||
")",
|
||||
name='ck_shipping_session_pdf_work_items_closed_reason',
|
||||
),
|
||||
CheckConstraint('lock_version >= 1', name='ck_shipping_session_pdf_work_items_lock_version'),
|
||||
CheckConstraint(
|
||||
'current_version_no >= 1',
|
||||
name='ck_shipping_session_pdf_work_items_version_no',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_session_pdf_work_items_conversation_lifecycle',
|
||||
'conversation_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_session_pdf_work_items_owner_lifecycle',
|
||||
'owner_user_id',
|
||||
'lifecycle_status',
|
||||
'updated_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_session_pdf_work_items_open_conversation',
|
||||
'conversation_id',
|
||||
'updated_at',
|
||||
postgresql_where=text("lifecycle_status <> 'closed'"),
|
||||
sqlite_where=text("lifecycle_status <> 'closed'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
item_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
# 同源 PDF 稳定身份:首次纳入会话时的 Document;替换文件不改变本字段。
|
||||
root_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
current_document_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_documents.id'), nullable=False, index=True,
|
||||
)
|
||||
current_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
current_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
current_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_review_cases.id'), nullable=True,
|
||||
)
|
||||
current_case_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 面向用户的版本序号(V1/V2);重识别成功递增,失败回退不递增。
|
||||
current_version_no: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
lifecycle_status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='pending_review', server_default='pending_review',
|
||||
)
|
||||
closed_reason: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
@@ -131,6 +131,7 @@ def _register_builtin_platform_jobs() -> None:
|
||||
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
|
||||
from app.services.schedule.file_asset_cleanup_job import run_file_asset_cleanup_schedule
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
|
||||
|
||||
@@ -143,6 +144,18 @@ def _register_builtin_platform_jobs() -> None:
|
||||
params_schema=({"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},),
|
||||
defaults={"limit": 1000},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-audit-retention",
|
||||
label="货代审计到期清理",
|
||||
handler=run_shipping_audit_retention_schedule,
|
||||
description="按三年保留期分批清理到期的货代统一审计事件;支持 dry_run 观测。",
|
||||
category="shipping",
|
||||
params_schema=(
|
||||
{"key": "limit", "type": "number", "label": "单批上限", "required": False, "default": 1000},
|
||||
{"key": "dry_run", "type": "boolean", "label": "仅演练", "required": False, "default": False},
|
||||
),
|
||||
defaults={"limit": 1000, "dry_run": False},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="shipping-inventory-rpa",
|
||||
label="货代库存 RPA",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
services/schedule/shipping_audit_retention_job.py
|
||||
|
||||
用途:货代统一审计到期清理的 platform Job 入口。
|
||||
依赖:audit_query_service.purge_expired_shipping_audit_events、progress_feature_flags.audit_retention_days。
|
||||
逻辑:platform_api_path=shipping-audit-retention 时由 job_registry 调用;保留期读
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS(写入 retention_expires_at);支持 dry_run。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.audit_query_service import purge_expired_shipping_audit_events
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
|
||||
def run_shipping_audit_retention_schedule(task: Any, run: Any) -> dict[str, Any]:
|
||||
"""
|
||||
按可配置保留期分批清理到期审计事件。
|
||||
|
||||
核心逻辑:读取 job_params.limit / dry_run;保留天数来自 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS;
|
||||
正式删除前可先 dry_run 观测扫描量。
|
||||
"""
|
||||
_ = run
|
||||
params = getattr(task, 'job_params', None) or {}
|
||||
dry_raw = params.get('dry_run', False)
|
||||
dry_run = dry_raw in (True, 1, '1', 'true', 'True', 'yes')
|
||||
result = purge_expired_shipping_audit_events(
|
||||
limit=int(params.get('limit') or 1000),
|
||||
dry_run=dry_run,
|
||||
actor_id=f'schedule:{getattr(task, "id", "unknown")}',
|
||||
)
|
||||
result['retention_days'] = audit_retention_days()
|
||||
return result
|
||||
@@ -0,0 +1,421 @@
|
||||
"""
|
||||
services/shipping_notice/audit_query_service.py
|
||||
|
||||
用途:管理员货代审计查询、前后差异投影、受控导出与到期清理。
|
||||
依赖:ShippingAuditEvent、audit_service 投影规则、fulfillment_audit、progress_audit_contract、SQLAlchemy。
|
||||
逻辑:由 admin API 调用;列表/详情/导出均做管理员访问审计(失败阻断查询);清理使用 Core DELETE
|
||||
绕过 ORM 不可变守卫并写清理审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context
|
||||
from app.services.shipping_notice.progress_audit_contract import AUDIT_SNAPSHOT_ALLOWED_KEYS
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""UTC datetime → ISO8601 Z。"""
|
||||
if value is None:
|
||||
return None
|
||||
return value.isoformat() + ('Z' if value.tzinfo is None else '')
|
||||
|
||||
|
||||
def _parse_iso(value: str | None) -> datetime | None:
|
||||
"""解析可选 ISO 时间;非法值抛 ValidationError。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
normalized = text.replace('Z', '+00:00') if text.endswith('Z') else text
|
||||
return datetime.fromisoformat(normalized).replace(tzinfo=None)
|
||||
except ValueError as exc:
|
||||
raise ValidationError('invalid datetime filter', code='SHIPPING_NOTICE.AUDIT_QUERY_INVALID') from exc
|
||||
|
||||
|
||||
def _diff_snapshots(
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
计算白名单快照前后差异。
|
||||
|
||||
核心逻辑:仅比较 AUDIT_SNAPSHOT_ALLOWED_KEYS;输出 changed/added/removed,不含敏感值猜测。
|
||||
"""
|
||||
left = {k: before.get(k) for k in AUDIT_SNAPSHOT_ALLOWED_KEYS if isinstance(before, dict) and k in before}
|
||||
right = {k: after.get(k) for k in AUDIT_SNAPSHOT_ALLOWED_KEYS if isinstance(after, dict) and k in after}
|
||||
keys = sorted(set(left) | set(right))
|
||||
rows: list[dict[str, Any]] = []
|
||||
for key in keys:
|
||||
if key not in left:
|
||||
rows.append({'key': key, 'change': 'added', 'before': None, 'after': right.get(key)})
|
||||
elif key not in right:
|
||||
rows.append({'key': key, 'change': 'removed', 'before': left.get(key), 'after': None})
|
||||
elif left.get(key) != right.get(key):
|
||||
rows.append({'key': key, 'change': 'changed', 'before': left.get(key), 'after': right.get(key)})
|
||||
return rows
|
||||
|
||||
|
||||
def serialize_shipping_audit_event(event: ShippingAuditEvent, *, include_snapshots: bool = False) -> dict[str, Any]:
|
||||
"""序列化管理员可读审计事件;默认不含完整快照,详情/导出按需打开。"""
|
||||
payload: dict[str, Any] = {
|
||||
'id': int(event.id),
|
||||
'event_type': event.event_type,
|
||||
'aggregate_type': event.aggregate_type,
|
||||
'aggregate_id': event.aggregate_id,
|
||||
'run_no': event.run_no,
|
||||
'task_no': event.task_no,
|
||||
'intake_no': event.intake_no,
|
||||
'actor_type': event.actor_type,
|
||||
'actor_id': event.actor_id,
|
||||
'actor_role': event.actor_role,
|
||||
'request_id': event.request_id,
|
||||
'operation_id': event.operation_id,
|
||||
'correlation_id': event.correlation_id,
|
||||
'source': event.source,
|
||||
'result': event.result,
|
||||
'error_code': event.error_code,
|
||||
'conversation_id': event.conversation_id,
|
||||
'unit_id': event.unit_id,
|
||||
'document_id': event.document_id,
|
||||
'review_case_no': event.review_case_no,
|
||||
'session_item_id': event.session_item_id,
|
||||
'owner_user_id': event.owner_user_id,
|
||||
'client_ip_hash': event.client_ip_hash,
|
||||
'user_agent_hash': event.user_agent_hash,
|
||||
'attempt_no': event.attempt_no,
|
||||
'action': event.action,
|
||||
'reason_code': event.reason_code,
|
||||
'reason': event.reason,
|
||||
'before_hash': event.before_hash,
|
||||
'after_hash': event.after_hash,
|
||||
'metadata': event.metadata_json if isinstance(event.metadata_json, dict) else {},
|
||||
'evidence_refs': event.evidence_refs_json if isinstance(event.evidence_refs_json, list) else [],
|
||||
'artifact_refs': event.artifact_refs_json if isinstance(event.artifact_refs_json, list) else [],
|
||||
'context_refs': event.context_refs_json if isinstance(event.context_refs_json, dict) else {},
|
||||
'retention_expires_at': _iso(event.retention_expires_at),
|
||||
'created_at': _iso(event.created_at),
|
||||
'has_snapshots': bool(event.before_snapshot_json or event.after_snapshot_json),
|
||||
}
|
||||
if include_snapshots:
|
||||
before = event.before_snapshot_json if isinstance(event.before_snapshot_json, dict) else None
|
||||
after = event.after_snapshot_json if isinstance(event.after_snapshot_json, dict) else None
|
||||
payload['before_snapshot'] = before
|
||||
payload['after_snapshot'] = after
|
||||
payload['diff'] = _diff_snapshots(before, after)
|
||||
return payload
|
||||
|
||||
|
||||
def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
"""按管理员筛选条件收窄查询;禁止自由文本全文检索正文。"""
|
||||
if filters.get('event_type'):
|
||||
query = query.filter(ShippingAuditEvent.event_type == str(filters['event_type'])[:64])
|
||||
if filters.get('actor_type'):
|
||||
query = query.filter(ShippingAuditEvent.actor_type == str(filters['actor_type'])[:16])
|
||||
if filters.get('actor_id'):
|
||||
query = query.filter(ShippingAuditEvent.actor_id == str(filters['actor_id'])[:128])
|
||||
if filters.get('run_no'):
|
||||
query = query.filter(ShippingAuditEvent.run_no == str(filters['run_no'])[:64])
|
||||
if filters.get('task_no'):
|
||||
query = query.filter(ShippingAuditEvent.task_no == str(filters['task_no'])[:64])
|
||||
if filters.get('document_id'):
|
||||
query = query.filter(ShippingAuditEvent.document_id == str(filters['document_id'])[:64])
|
||||
if filters.get('operation_id'):
|
||||
query = query.filter(ShippingAuditEvent.operation_id == str(filters['operation_id'])[:64])
|
||||
if filters.get('request_id'):
|
||||
query = query.filter(ShippingAuditEvent.request_id == str(filters['request_id'])[:64])
|
||||
if filters.get('aggregate_type'):
|
||||
query = query.filter(ShippingAuditEvent.aggregate_type == str(filters['aggregate_type'])[:64])
|
||||
if filters.get('aggregate_id'):
|
||||
query = query.filter(ShippingAuditEvent.aggregate_id == str(filters['aggregate_id'])[:128])
|
||||
if filters.get('result'):
|
||||
query = query.filter(ShippingAuditEvent.result == str(filters['result'])[:16])
|
||||
if filters.get('conversation_id'):
|
||||
query = query.filter(ShippingAuditEvent.conversation_id == str(filters['conversation_id'])[:100])
|
||||
if filters.get('session_item_id'):
|
||||
query = query.filter(ShippingAuditEvent.session_item_id == str(filters['session_item_id'])[:64])
|
||||
if filters.get('review_case_no'):
|
||||
query = query.filter(ShippingAuditEvent.review_case_no == str(filters['review_case_no'])[:64])
|
||||
if filters.get('owner_user_id'):
|
||||
query = query.filter(ShippingAuditEvent.owner_user_id == str(filters['owner_user_id'])[:64])
|
||||
created_from = _parse_iso(filters.get('created_from'))
|
||||
created_to = _parse_iso(filters.get('created_to'))
|
||||
if created_from is not None:
|
||||
query = query.filter(ShippingAuditEvent.created_at >= created_from)
|
||||
if created_to is not None:
|
||||
query = query.filter(ShippingAuditEvent.created_at <= created_to)
|
||||
q = str(filters.get('q') or '').strip()
|
||||
if q:
|
||||
# 仅匹配稳定业务编号字段,禁止对 metadata/snapshot 做模糊检索。
|
||||
like = f'%{q[:64]}%'
|
||||
query = query.filter(
|
||||
or_(
|
||||
ShippingAuditEvent.run_no.ilike(like),
|
||||
ShippingAuditEvent.task_no.ilike(like),
|
||||
ShippingAuditEvent.operation_id.ilike(like),
|
||||
ShippingAuditEvent.request_id.ilike(like),
|
||||
ShippingAuditEvent.aggregate_id.ilike(like),
|
||||
ShippingAuditEvent.document_id.ilike(like),
|
||||
ShippingAuditEvent.session_item_id.ilike(like),
|
||||
ShippingAuditEvent.review_case_no.ilike(like),
|
||||
ShippingAuditEvent.conversation_id.ilike(like),
|
||||
)
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def _write_access_audit(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
action: str,
|
||||
request_id: str | None,
|
||||
summary: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
记录管理员审计查询/导出访问。
|
||||
|
||||
核心逻辑:与履约链路一致,落库失败时回滚并抛错,禁止未留痕的敏感访问继续返回。
|
||||
"""
|
||||
ctx = resolve_request_audit_context()
|
||||
resolved_request_id = request_id or ctx.get('request_id')
|
||||
try:
|
||||
append_shipping_audit_event(
|
||||
event_type='audit_access',
|
||||
aggregate_type='shipping_audit',
|
||||
aggregate_id=f'access:{action}',
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
request_id=resolved_request_id,
|
||||
operation_id=resolved_request_id,
|
||||
client_ip=ctx.get('client_ip'),
|
||||
user_agent=ctx.get('user_agent'),
|
||||
source='admin_api',
|
||||
result='success',
|
||||
action=action,
|
||||
metadata=summary,
|
||||
persist_snapshots=False,
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ServiceUnavailableError(
|
||||
'Shipping audit access persistence failed',
|
||||
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
|
||||
details={'action': action},
|
||||
) from exc
|
||||
|
||||
|
||||
def list_shipping_audit_events(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
page: int = 1,
|
||||
page_size: int = 25,
|
||||
filters: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""分页查询货代统一审计事件;写访问审计。"""
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 25)))
|
||||
query = _apply_filters(ShippingAuditEvent.query, filters=filters or {})
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc())
|
||||
.offset((safe_page - 1) * safe_page_size)
|
||||
.limit(safe_page_size)
|
||||
.all()
|
||||
)
|
||||
payload = {
|
||||
'items': [serialize_shipping_audit_event(row, include_snapshots=False) for row in rows],
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
}
|
||||
_write_access_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='list_audit_events',
|
||||
request_id=request_id,
|
||||
summary={
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'total': total,
|
||||
'filters': {
|
||||
key: (filters or {}).get(key)
|
||||
for key in (
|
||||
'event_type', 'actor_type', 'run_no', 'task_no', 'document_id',
|
||||
'operation_id', 'request_id', 'result', 'created_from', 'created_to',
|
||||
)
|
||||
if (filters or {}).get(key)
|
||||
},
|
||||
},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def get_shipping_audit_event(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
event_id: int,
|
||||
) -> dict[str, Any]:
|
||||
"""读取单条审计详情(含白名单快照与 diff)。"""
|
||||
event = ShippingAuditEvent.query.filter_by(id=int(event_id)).first()
|
||||
if event is None:
|
||||
raise NotFoundError('Shipping audit event not found', code='SHIPPING_NOTICE.AUDIT_EVENT_NOT_FOUND')
|
||||
payload = serialize_shipping_audit_event(event, include_snapshots=True)
|
||||
_write_access_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='get_audit_event',
|
||||
request_id=request_id,
|
||||
summary={'event_id': int(event.id), 'event_type': event.event_type, 'run_no': event.run_no},
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def export_shipping_audit_events(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
filters: dict[str, Any] | None = None,
|
||||
limit: int = 2000,
|
||||
format: str = 'csv',
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
受控导出审计事件。
|
||||
|
||||
核心逻辑:上限 5000;CSV 仅稳定字段;禁止导出快照全文与敏感 metadata 嵌套;
|
||||
受 SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED 灰度开关控制。
|
||||
"""
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_export_enabled
|
||||
|
||||
if not audit_export_enabled():
|
||||
raise ValidationError(
|
||||
'Shipping audit export is disabled by feature flag',
|
||||
code='SHIPPING_NOTICE.AUDIT_EXPORT_FEATURE_DISABLED',
|
||||
)
|
||||
safe_limit = min(5000, max(1, int(limit or 2000)))
|
||||
fmt = str(format or 'csv').strip().lower()
|
||||
if fmt not in {'csv', 'json'}:
|
||||
raise ValidationError('export format must be csv or json', code='SHIPPING_NOTICE.AUDIT_EXPORT_INVALID')
|
||||
query = _apply_filters(ShippingAuditEvent.query, filters=filters or {})
|
||||
rows = query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc()).limit(safe_limit).all()
|
||||
items = [serialize_shipping_audit_event(row, include_snapshots=False) for row in rows]
|
||||
_write_access_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='export_audit_events',
|
||||
request_id=request_id,
|
||||
summary={'format': fmt, 'exported': len(items), 'limit': safe_limit},
|
||||
)
|
||||
if fmt == 'json':
|
||||
content = json.dumps({'items': items, 'exported': len(items)}, ensure_ascii=False, separators=(',', ':'))
|
||||
return {
|
||||
'filename': f'shipping-audit-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}.json',
|
||||
'content_type': 'application/json; charset=utf-8',
|
||||
'content': content,
|
||||
'exported': len(items),
|
||||
}
|
||||
|
||||
buffer = io.StringIO()
|
||||
fieldnames = [
|
||||
'id', 'created_at', 'event_type', 'action', 'result', 'actor_type', 'actor_id',
|
||||
'run_no', 'task_no', 'document_id', 'operation_id', 'request_id', 'reason_code', 'error_code',
|
||||
]
|
||||
writer = csv.DictWriter(buffer, fieldnames=fieldnames, extrasaction='ignore')
|
||||
writer.writeheader()
|
||||
for item in items:
|
||||
writer.writerow({key: item.get(key) for key in fieldnames})
|
||||
return {
|
||||
'filename': f'shipping-audit-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}.csv',
|
||||
'content_type': 'text/csv; charset=utf-8',
|
||||
'content': buffer.getvalue(),
|
||||
'exported': len(items),
|
||||
}
|
||||
|
||||
|
||||
def purge_expired_shipping_audit_events(
|
||||
*,
|
||||
limit: int = 1000,
|
||||
dry_run: bool = False,
|
||||
now: datetime | None = None,
|
||||
actor_id: str | int | None = 'system',
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
清理已过保留期的审计事件。
|
||||
|
||||
核心逻辑:先统计候选;dry_run 不删除;正式删除使用 Core DELETE(绕过 ORM append-only 守卫),
|
||||
并写入一条 system 清理审计说明批次规模。
|
||||
|
||||
Args:
|
||||
limit: 单批上限 1-5000。
|
||||
dry_run: True 时只返回将删除数量。
|
||||
now: 可注入当前时间。
|
||||
actor_id: 清理执行者标识。
|
||||
|
||||
Returns:
|
||||
{dry_run, scanned, deleted, cutoff}。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
safe_limit = min(5000, max(1, int(limit or 1000)))
|
||||
candidate_ids = [
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingAuditEvent.id)
|
||||
.filter(
|
||||
ShippingAuditEvent.retention_expires_at.isnot(None),
|
||||
ShippingAuditEvent.retention_expires_at < current,
|
||||
)
|
||||
.order_by(ShippingAuditEvent.retention_expires_at.asc(), ShippingAuditEvent.id.asc())
|
||||
.limit(safe_limit)
|
||||
.all()
|
||||
]
|
||||
if dry_run or not candidate_ids:
|
||||
return {
|
||||
'dry_run': bool(dry_run),
|
||||
'scanned': len(candidate_ids),
|
||||
'deleted': 0,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
|
||||
# Core bulk delete 不加载 ORM 实例,避免触发 before_delete 不可变守卫。
|
||||
# [STEP 1] 先从 identity map 取出候选,防止随后 flush 把已删行重新持久化。
|
||||
tracked = [
|
||||
obj
|
||||
for eid in candidate_ids
|
||||
if (obj := db.session.get(ShippingAuditEvent, eid)) is not None
|
||||
]
|
||||
result = db.session.execute(
|
||||
delete(ShippingAuditEvent).where(ShippingAuditEvent.id.in_(candidate_ids))
|
||||
)
|
||||
deleted = int(result.rowcount or 0)
|
||||
for obj in tracked:
|
||||
db.session.expunge(obj)
|
||||
|
||||
# [STEP 2] 写入系统清理审计(新行),与删除同事务提交。
|
||||
append_shipping_audit_event(
|
||||
event_type='audit_retention_purged',
|
||||
aggregate_type='shipping_audit',
|
||||
aggregate_id=f'purge:{current.strftime("%Y%m%d%H%M%S")}',
|
||||
actor_type='system',
|
||||
actor_id=actor_id,
|
||||
source='retention_job',
|
||||
result='success',
|
||||
action='purge_expired',
|
||||
metadata={'deleted': deleted, 'limit': safe_limit, 'dry_run': False},
|
||||
persist_snapshots=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'dry_run': False,
|
||||
'scanned': len(candidate_ids),
|
||||
'deleted': deleted,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
@@ -1,26 +1,29 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/audit_service.py
|
||||
|
||||
用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据。
|
||||
依赖:ShippingAuditEvent、SQLAlchemy 会话。
|
||||
逻辑:Run、Task、库存和 Chatflow 服务调用本模块写入状态与决策事实;本服务不提交事务,由调用方保证业务与审计原子性。
|
||||
用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据与快照。
|
||||
依赖:ShippingAuditEvent、progress_audit_contract、SQLAlchemy 会话。
|
||||
逻辑:Run、Task、会话 PDF 工作项、库存和 Chatflow 服务调用本模块写入状态与决策事实;
|
||||
本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、
|
||||
证据引用、会话工作项关联、属主与三年保留到期;IP / User-Agent 仅持久化哈希。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
|
||||
|
||||
_FORBIDDEN_METADATA_KEYS = frozenset({
|
||||
'api_key', 'api_base_url', 'authorization', 'body', 'content', 'document_text', 'email_body',
|
||||
'password', 'prompt', 'provider_config', 'quote', 'token',
|
||||
})
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_FORBIDDEN_KEYS,
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS,
|
||||
is_forbidden_audit_key,
|
||||
)
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
|
||||
def _stable_hash(value: Any) -> str:
|
||||
@@ -29,43 +32,210 @@ def _stable_hash(value: Any) -> str:
|
||||
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
|
||||
|
||||
|
||||
def hash_client_context_value(raw: str | None) -> str | None:
|
||||
"""
|
||||
将客户端上下文(IP / User-Agent)转为不可逆哈希。
|
||||
|
||||
核心逻辑:空白返回 None;否则 UTF-8 SHA-256 十六进制,永不落库原文。
|
||||
|
||||
Args:
|
||||
raw: 原始 IP 或 User-Agent;禁止已是哈希的二次哈希由调用方自行保证。
|
||||
|
||||
Returns:
|
||||
64 位十六进制哈希,或 None。
|
||||
"""
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
return hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _collect_forbidden_keys(payload: Any, *, path: str = '') -> list[str]:
|
||||
"""
|
||||
递归收集命中敏感黑名单的键路径。
|
||||
|
||||
核心逻辑:遍历 dict/list;键名大小写不敏感匹配;返回稳定排序路径便于测试断言。
|
||||
"""
|
||||
found: list[str] = []
|
||||
if isinstance(payload, dict):
|
||||
for key, child in payload.items():
|
||||
key_text = str(key)
|
||||
child_path = f'{path}.{key_text}' if path else key_text
|
||||
if is_forbidden_audit_key(key_text):
|
||||
found.append(child_path)
|
||||
found.extend(_collect_forbidden_keys(child, path=child_path))
|
||||
elif isinstance(payload, list):
|
||||
for index, child in enumerate(payload):
|
||||
found.extend(_collect_forbidden_keys(child, path=f'{path}[{index}]'))
|
||||
return found
|
||||
|
||||
|
||||
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""验证元数据仅含脱敏诊断事实,阻断正文、凭据和字段值进入统一审计。"""
|
||||
safe = dict(metadata or {})
|
||||
forbidden = sorted(key for key in safe if str(key).lower() in _FORBIDDEN_METADATA_KEYS)
|
||||
forbidden = _collect_forbidden_keys(safe)
|
||||
if forbidden:
|
||||
raise ValidationError(
|
||||
'Shipping audit metadata contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(forbidden))},
|
||||
)
|
||||
return safe
|
||||
|
||||
|
||||
def project_audit_snapshot(value: Any | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
将业务状态投影为审计白名单快照。
|
||||
|
||||
核心逻辑:仅保留 AUDIT_SNAPSHOT_ALLOWED_KEYS 顶层键;命中敏感键直接拒绝而非静默丢弃。
|
||||
|
||||
Args:
|
||||
value: 受控状态 dict;非 dict 返回 None。
|
||||
|
||||
Returns:
|
||||
白名单快照,或 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 包含禁止键。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(
|
||||
'Shipping audit snapshot must be an object',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
)
|
||||
# 敏感键拒绝入库;未授权业务键静默剔除,避免“悄悄丢敏感字段”造成审计假完整。
|
||||
sensitive = [key for key in value if is_forbidden_audit_key(str(key))]
|
||||
if sensitive:
|
||||
raise ValidationError(
|
||||
'Shipping audit snapshot contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(str(k) for k in sensitive))},
|
||||
)
|
||||
projected = {
|
||||
str(key): value[key]
|
||||
for key in value
|
||||
if str(key) in AUDIT_SNAPSHOT_ALLOWED_KEYS
|
||||
}
|
||||
nested_forbidden = _collect_forbidden_keys(projected)
|
||||
if nested_forbidden:
|
||||
raise ValidationError(
|
||||
'Shipping audit snapshot contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(nested_forbidden))},
|
||||
)
|
||||
return projected or None
|
||||
|
||||
|
||||
def _sanitize_refs(refs: list[dict[str, Any]] | None, *, field_name: str) -> list[dict[str, Any]] | None:
|
||||
"""校验证据/产物引用仅含标识类字段,拒绝 URL 与正文。"""
|
||||
if refs is None:
|
||||
return None
|
||||
if not isinstance(refs, list):
|
||||
raise ValidationError(
|
||||
f'Shipping audit {field_name} must be a list',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
)
|
||||
forbidden = _collect_forbidden_keys(refs)
|
||||
if forbidden:
|
||||
raise ValidationError(
|
||||
f'Shipping audit {field_name} contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
details={'forbidden_keys': sorted(set(forbidden))},
|
||||
)
|
||||
return refs
|
||||
|
||||
|
||||
def default_retention_expires_at(*, now: datetime | None = None) -> datetime:
|
||||
"""
|
||||
计算审计默认保留到期时间(默认三年,可由 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS 覆盖)。
|
||||
|
||||
Args:
|
||||
now: 可选当前时间,便于测试注入。
|
||||
|
||||
Returns:
|
||||
UTC naive 到期时间。
|
||||
"""
|
||||
base = now or datetime.utcnow()
|
||||
return base + timedelta(days=audit_retention_days())
|
||||
|
||||
|
||||
def append_shipping_audit_event(
|
||||
*, event_type: str, aggregate_type: str, aggregate_id: str, run_no: str | None = None,
|
||||
task_no: str | None = None, intake_no: str | None = None, actor_type: str = 'system',
|
||||
actor_id: str | int | None = None, request_id: str | None = None,
|
||||
correlation_id: str | None = None, reason_code: str | None = None,
|
||||
before: Any = None, after: Any = None, metadata: dict[str, Any] | None = None,
|
||||
*,
|
||||
event_type: str,
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
run_no: str | None = None,
|
||||
task_no: str | None = None,
|
||||
intake_no: str | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
actor_role: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
correlation_id: str | None = None,
|
||||
source: str | None = None,
|
||||
result: str | None = None,
|
||||
error_code: str | None = None,
|
||||
conversation_id: str | None = None,
|
||||
unit_id: str | int | None = None,
|
||||
document_id: str | int | None = None,
|
||||
review_case_no: str | None = None,
|
||||
session_item_id: str | None = None,
|
||||
owner_user_id: str | int | None = None,
|
||||
client_ip: str | None = None,
|
||||
user_agent: str | None = None,
|
||||
client_ip_hash: str | None = None,
|
||||
user_agent_hash: str | None = None,
|
||||
attempt_no: int | None = None,
|
||||
action: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
before: Any = None,
|
||||
after: Any = None,
|
||||
evidence_refs: list[dict[str, Any]] | None = None,
|
||||
artifact_refs: list[dict[str, Any]] | None = None,
|
||||
context_refs: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
retention_expires_at: datetime | None = None,
|
||||
persist_snapshots: bool = True,
|
||||
) -> ShippingAuditEvent:
|
||||
"""
|
||||
追加一条货代审计事实。
|
||||
|
||||
Args:
|
||||
event_type: 稳定业务事件名,例如 ``run_status_changed``;禁止传入用户自由文本。
|
||||
event_type: 稳定业务事件名,例如 ``session_work_item_created``;禁止传入用户自由文本。
|
||||
aggregate_type/aggregate_id: 业务聚合类型与稳定编号,不使用可删除记录的外键。
|
||||
before/after: 可复现的受控状态投影;只持久化其哈希。
|
||||
operation_id: 同一次用户/系统操作的关联键,与 request_id 共同贯通事件链。
|
||||
session_item_id: 会话 PDF 工作项 item_no;软引用。
|
||||
owner_user_id: 业务属主,与 actor_id(实际操作者)区分,支撑代操作审计。
|
||||
client_ip/user_agent: 原始客户端上下文,仅哈希后入库;也可直接传 *_hash。
|
||||
before/after: 可复现的受控状态投影;持久化白名单快照及其哈希。
|
||||
evidence_refs/artifact_refs: FileAsset ID、SHA-256、版本与证据坐标,禁止 URL/正文。
|
||||
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
|
||||
persist_snapshots: False 时只写哈希(兼容历史调用方仅传 before/after 哈希语义)。
|
||||
|
||||
Returns:
|
||||
尚未提交的审计事件,由调用方与业务写入在同一事务提交。
|
||||
|
||||
Raises:
|
||||
ValidationError: actor 类型或元数据包含正文、凭据等敏感字段。
|
||||
ValidationError: actor 类型、元数据或快照包含正文、凭据等敏感字段。
|
||||
"""
|
||||
allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin'}
|
||||
if actor_type not in allowed_actor_types:
|
||||
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
|
||||
if result is not None and result not in {'success', 'failure', 'rejected', 'ignored'}:
|
||||
raise ValidationError('Invalid shipping audit result', code='SHIPPING_NOTICE.AUDIT_RESULT_INVALID')
|
||||
|
||||
before_snapshot = project_audit_snapshot(before) if before is not None else None
|
||||
after_snapshot = project_audit_snapshot(after) if after is not None else None
|
||||
if context_refs is not None:
|
||||
_sanitize_metadata(context_refs)
|
||||
|
||||
resolved_ip_hash = client_ip_hash or hash_client_context_value(client_ip)
|
||||
resolved_ua_hash = user_agent_hash or hash_client_context_value(user_agent)
|
||||
|
||||
event = ShippingAuditEvent(
|
||||
event_type=str(event_type)[:64],
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
@@ -75,13 +245,40 @@ def append_shipping_audit_event(
|
||||
intake_no=str(intake_no)[:64] if intake_no else None,
|
||||
actor_type=actor_type,
|
||||
actor_id=str(actor_id)[:128] if actor_id is not None else None,
|
||||
actor_role=str(actor_role)[:64] if actor_role else None,
|
||||
request_id=str(request_id)[:64] if request_id else None,
|
||||
operation_id=str(operation_id)[:64] if operation_id else None,
|
||||
correlation_id=str(correlation_id)[:64] if correlation_id else None,
|
||||
source=str(source)[:32] if source else None,
|
||||
result=result,
|
||||
error_code=str(error_code)[:64] if error_code else None,
|
||||
conversation_id=str(conversation_id)[:100] if conversation_id else None,
|
||||
unit_id=str(unit_id)[:64] if unit_id is not None else None,
|
||||
document_id=str(document_id)[:64] if document_id is not None else None,
|
||||
review_case_no=str(review_case_no)[:64] if review_case_no else None,
|
||||
session_item_id=str(session_item_id)[:64] if session_item_id else None,
|
||||
owner_user_id=str(owner_user_id)[:64] if owner_user_id is not None else None,
|
||||
client_ip_hash=str(resolved_ip_hash)[:64] if resolved_ip_hash else None,
|
||||
user_agent_hash=str(resolved_ua_hash)[:64] if resolved_ua_hash else None,
|
||||
attempt_no=int(attempt_no) if attempt_no is not None else None,
|
||||
action=str(action)[:64] if action else None,
|
||||
reason_code=str(reason_code)[:128] if reason_code else None,
|
||||
before_hash=_stable_hash(before) if before is not None else None,
|
||||
after_hash=_stable_hash(after) if after is not None else None,
|
||||
reason=str(reason)[:2000] if reason else None,
|
||||
before_hash=_stable_hash(before_snapshot if before_snapshot is not None else before)
|
||||
if before is not None else None,
|
||||
after_hash=_stable_hash(after_snapshot if after_snapshot is not None else after)
|
||||
if after is not None else None,
|
||||
before_snapshot_json=before_snapshot if persist_snapshots else None,
|
||||
after_snapshot_json=after_snapshot if persist_snapshots else None,
|
||||
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
|
||||
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
|
||||
context_refs_json=dict(context_refs) if context_refs else None,
|
||||
metadata_json=_sanitize_metadata(metadata),
|
||||
retention_expires_at=retention_expires_at or default_retention_expires_at(),
|
||||
)
|
||||
db.session.add(event)
|
||||
return event
|
||||
|
||||
|
||||
# 供测试与 OpenAPI 契约引用的冻结黑名单导出。
|
||||
FORBIDDEN_AUDIT_METADATA_KEYS = AUDIT_FORBIDDEN_KEYS
|
||||
@@ -194,6 +194,20 @@ def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
|
||||
candidate.acceptance_policy_version = 'manual-review-v1'
|
||||
candidate.selected = True
|
||||
_append_candidate_decision_history(candidate, action='promoted', user_id=user_id)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='candidate_promoted',
|
||||
aggregate_type='order_candidate',
|
||||
aggregate_id=candidate.candidate_no,
|
||||
action='promote',
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
run_no=getattr(candidate, 'run_no', None) or None,
|
||||
document_id=getattr(document, 'id', None),
|
||||
before={'status': 'provisional'},
|
||||
after={'status': 'accepted'},
|
||||
metadata={'acceptance_mode': 'manual'},
|
||||
)
|
||||
db.session.commit()
|
||||
return _serialize_candidate_brief(candidate)
|
||||
|
||||
@@ -214,6 +228,19 @@ def reject_candidate(*, user_id: int, candidate_no: str, reason: str | None = No
|
||||
candidate.acceptance_policy_version = 'manual-review-v1'
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
_append_candidate_decision_history(candidate, action='rejected', user_id=user_id, reason=reason)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='candidate_rejected',
|
||||
aggregate_type='order_candidate',
|
||||
aggregate_id=candidate.candidate_no,
|
||||
action='reject',
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
run_no=getattr(candidate, 'run_no', None) or None,
|
||||
reason_code='manual_rejected',
|
||||
before={'status': 'provisional'},
|
||||
after={'status': 'rejected'},
|
||||
)
|
||||
db.session.commit()
|
||||
return _serialize_candidate_brief(candidate)
|
||||
|
||||
|
||||
@@ -151,6 +151,20 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='task_decision',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task.task_no,
|
||||
action='reject',
|
||||
actor_id=payload.get('user_id') or payload.get('actor_id'),
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
before={'status': 'active'},
|
||||
after={'status': 'rejected'},
|
||||
metadata={'decision': 'reject'},
|
||||
source=event_source,
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -168,6 +182,20 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='task_decision',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task.task_no,
|
||||
action='close',
|
||||
actor_id=payload.get('user_id') or payload.get('actor_id'),
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
before={'status': 'active'},
|
||||
after={'status': 'closed'},
|
||||
metadata={'decision': 'close'},
|
||||
source=event_source,
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
|
||||
@@ -553,12 +553,14 @@ def persist_documents_and_candidates(
|
||||
supplement = parse_email_allocation_tables(
|
||||
html_tables=canonical_html_tables,
|
||||
content_hash=str(body_doc.content_hash or ''),
|
||||
schema_definition=definition,
|
||||
)
|
||||
# Outlook 等客户端可能把正文表展平成纯文本行;HTML 表为空时再使用严格序列解析。
|
||||
if not supplement.get('rows') and not canonical_html_tables:
|
||||
supplement = parse_email_allocation_text(
|
||||
body_text=body_text,
|
||||
content_hash=str(body_doc.content_hash or ''),
|
||||
schema_definition=definition,
|
||||
)
|
||||
supplement['document_id'] = int(body_doc.id)
|
||||
body_doc.order_extraction_result_json = {'email_supplement': supplement}
|
||||
|
||||
+4
-4
@@ -497,9 +497,9 @@ def _matches_termination_rule(
|
||||
if not absolute.y0 <= center_y <= absolute.y1:
|
||||
continue
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if text.casefold() == expected.casefold():
|
||||
if text == expected:
|
||||
return True
|
||||
elif expected.casefold() in text.casefold():
|
||||
elif expected in text:
|
||||
return True
|
||||
return False
|
||||
|
||||
@@ -1116,8 +1116,8 @@ def _text_in_horizontal_region(
|
||||
|
||||
|
||||
def _normalized_header_text(value: str) -> str:
|
||||
"""标准化表头候选,允许空格、斜线和标点差异但不执行模糊语义猜测。"""
|
||||
return re.sub(r'[^a-z0-9]+', '', value.lower())
|
||||
"""标准化表头候选,允许空格、斜线和标点差异但严格保留大小写。"""
|
||||
return re.sub(r'[^A-Za-z0-9]+', '', value)
|
||||
|
||||
|
||||
def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[list[tuple[int, PositionedCharacter]]]:
|
||||
|
||||
@@ -430,9 +430,9 @@ def _not_ready(grid: HtmlGrid, issue: str) -> OpenCVTableGeometryResult:
|
||||
|
||||
|
||||
def _normalized_cell_text(value: Any) -> str:
|
||||
"""以 NFKC、大小写折叠和字母数字/中日韩字符保留生成文本一致性比较键。"""
|
||||
"""以 NFKC 和字母数字/中日韩字符保留生成严格大小写的一致性比较键。"""
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
|
||||
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
|
||||
text = unicodedata.normalize('NFKC', str(value or ''))
|
||||
return re.sub(r'[^0-9A-Za-z\u4e00-\u9fff]+', '', text)
|
||||
@@ -283,9 +283,11 @@ def _find_anchor_matches(
|
||||
pair for pair in row if str(pair[1].get('text') or '').strip()
|
||||
]
|
||||
row_text = ''.join(str(item.get('text') or '') for _index, item in compact)
|
||||
folded = row_text.casefold()
|
||||
# Field anchors are part of the frozen Schema/Profile contract; matching
|
||||
# them case-sensitively prevents one label from being mistaken for another.
|
||||
folded = row_text
|
||||
for label in expected:
|
||||
normalized = re.sub(r'\s+', '', label).casefold()
|
||||
normalized = re.sub(r'\s+', '', label)
|
||||
start = 0
|
||||
while normalized and (position := folded.find(normalized, start)) >= 0:
|
||||
consumed = compact[position:position + len(normalized)]
|
||||
|
||||
@@ -94,9 +94,9 @@ class AnchorRule(OrderProfileModel):
|
||||
def validate_aliases(self) -> 'AnchorRule':
|
||||
"""只接受有限、去重的精确别名,避免把模糊词表当作自由匹配规则。"""
|
||||
aliases = [item.strip() for item in self.aliases]
|
||||
if any(not item for item in aliases) or len({item.casefold() for item in aliases}) != len(aliases):
|
||||
if any(not item for item in aliases) or len(set(aliases)) != len(aliases):
|
||||
raise ValueError('anchor aliases must be non-empty and unique')
|
||||
if self.text.casefold() in {item.casefold() for item in aliases}:
|
||||
if self.text in set(aliases):
|
||||
raise ValueError('anchor aliases must not repeat anchor text')
|
||||
return self
|
||||
|
||||
@@ -305,13 +305,26 @@ class TableRegionProfile(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
class DocumentMatchAnchor(OrderProfileModel):
|
||||
"""文档匹配锚点以管理员框选的标签和值区域验证关系,禁止全文纯文本命中。"""
|
||||
|
||||
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
value: str = Field(min_length=1, max_length=200)
|
||||
value_position: Literal['right', 'below'] = 'right'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
label_region: RelativeRegion | None = None
|
||||
value_region: RelativeRegion | None = None
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
|
||||
class DocumentMatchProfile(OrderProfileModel):
|
||||
"""定义模板唯一匹配所需的静态证据;动态订单业务值不可进入此对象。"""
|
||||
"""定义模板唯一匹配所需的标签-值证据;动态订单业务值不可进入此对象。"""
|
||||
|
||||
document_type: Literal['purchase_order'] = 'purchase_order'
|
||||
page_pattern: Literal['one_or_more'] = 'one_or_more'
|
||||
required_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
optional_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
required_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
optional_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
minimum_score: float = Field(default=0.9, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
|
||||
|
||||
@@ -15,6 +15,11 @@ from pydantic import BaseModel, ConfigDict, Field
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
|
||||
|
||||
|
||||
def _anchor_comparable_text(value: Any) -> str:
|
||||
"""规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。"""
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
|
||||
|
||||
class ProfileMatchCandidate(BaseModel):
|
||||
"""记录单个冻结 Profile 的非敏感匹配分数和失败原因。"""
|
||||
|
||||
@@ -103,19 +108,47 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
)
|
||||
|
||||
|
||||
def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
"""按视觉行重组冻结字符,供标签和值的相对位置校验使用。"""
|
||||
lines: list[list[dict[str, Any]]] = []
|
||||
for glyph in sorted(glyphs, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))):
|
||||
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
|
||||
try:
|
||||
center_y = (float(bbox.get('y0')) + float(bbox.get('y1'))) / 2
|
||||
height = float(bbox.get('y1')) - float(bbox.get('y0'))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if lines:
|
||||
previous = lines[-1]
|
||||
previous_bbox = previous[0].get('bbox') or {}
|
||||
previous_center_y = (float(previous_bbox.get('y0', 0)) + float(previous_bbox.get('y1', 0))) / 2
|
||||
previous_height = float(previous_bbox.get('y1', 0)) - float(previous_bbox.get('y0', 0))
|
||||
if abs(center_y - previous_center_y) <= max(height, previous_height) * .55:
|
||||
previous.append(glyph)
|
||||
continue
|
||||
lines.append([glyph])
|
||||
return [
|
||||
_anchor_comparable_text(''.join(str(item.get('text') or '') for item in sorted(line, key=lambda item: item.get('bbox', {}).get('x0', 0))))
|
||||
for line in lines
|
||||
]
|
||||
|
||||
|
||||
def _anchor_present(
|
||||
anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any], pages: dict[str, Any],
|
||||
) -> bool:
|
||||
"""检查静态锚点是否在整页冻结字符中出现;旧快照才受限回退到表内证据。"""
|
||||
expected = str(anchor.get('text') or '').strip()
|
||||
candidates = [expected, *[str(item).strip() for item in anchor.get('aliases') or []]]
|
||||
if not expected or not all(candidates):
|
||||
"""只在固定标签右侧或下方验证固定值,避免备注中的同文案误命中模板。"""
|
||||
label = _anchor_comparable_text(anchor.get('label'))
|
||||
expected = _anchor_comparable_text(anchor.get('value'))
|
||||
position = str(anchor.get('value_position') or '')
|
||||
if not label or not expected or position not in {'right', 'below'}:
|
||||
return False
|
||||
page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
|
||||
if not page_numbers:
|
||||
page_numbers = sorted(str(page_no) for page_no in pages)
|
||||
for page_no in page_numbers:
|
||||
if anchor.get('page_no') is not None and str(anchor.get('page_no')) != page_no:
|
||||
continue
|
||||
glyphs = page_glyphs.get(page_no)
|
||||
# v1 frozen snapshots do not have page glyphs. Preserve historical matching
|
||||
# rather than silently invalidating published profiles, but never merge rows here.
|
||||
@@ -127,21 +160,47 @@ def _anchor_present(
|
||||
page = pages.get(page_no)
|
||||
if not isinstance(glyphs, list) or not isinstance(page, dict):
|
||||
continue
|
||||
selected = glyphs
|
||||
region = anchor.get('region')
|
||||
if isinstance(region, dict):
|
||||
lines = _page_text_lines(glyphs)
|
||||
label_region = anchor.get('label_region')
|
||||
value_region = anchor.get('value_region')
|
||||
if isinstance(label_region, dict) and isinstance(value_region, dict):
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
x0, y0, x1, y1 = float(region['x0']) * width, float(region['y0']) * height, float(region['x1']) * width, float(region['y1']) * height
|
||||
def region_text(region: dict[str, Any]) -> str:
|
||||
# Center containment separates adjacent lines. Existing edge-only
|
||||
# regions keep a narrow same-line overlap fallback below.
|
||||
selected = [item for item in glyphs if isinstance(item.get('bbox'), dict)
|
||||
and float(region['x0']) * width <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= float(region['x1']) * width
|
||||
and float(region['y0']) * height <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= float(region['y1']) * height]
|
||||
if not selected:
|
||||
overlaps = [item for item in glyphs if isinstance(item.get('bbox'), dict)
|
||||
and float(item['bbox'].get('x1', 0)) >= float(region['x0']) * width
|
||||
and float(item['bbox'].get('x0', 0)) <= float(region['x1']) * width
|
||||
and float(item['bbox'].get('y1', 0)) >= float(region['y0']) * height
|
||||
and float(item['bbox'].get('y0', 0)) <= float(region['y1']) * height]
|
||||
if overlaps:
|
||||
target_y = (float(region['y0']) + float(region['y1'])) * height / 2
|
||||
reference = min(overlaps, key=lambda item: abs(
|
||||
(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 - target_y,
|
||||
))
|
||||
reference_box = reference['bbox']
|
||||
reference_y = (float(reference_box.get('y0', 0)) + float(reference_box.get('y1', 0))) / 2
|
||||
reference_height = max(1.0, float(reference_box.get('y1', 0)) - float(reference_box.get('y0', 0)))
|
||||
selected = [item for item in overlaps if abs(
|
||||
(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 - reference_y,
|
||||
) <= max(reference_height, float(item['bbox'].get('y1', 0)) - float(item['bbox'].get('y0', 0))) * .55]
|
||||
return _anchor_comparable_text(''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0)))))
|
||||
if label in region_text(label_region) and expected in region_text(value_region):
|
||||
return True
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
selected = [item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)
|
||||
and x0 <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= x1
|
||||
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
|
||||
text = ''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))))
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if any(candidate.casefold() == text.casefold() for candidate in candidates):
|
||||
continue
|
||||
for index, line in enumerate(lines):
|
||||
label_index = line.find(label)
|
||||
if label_index < 0:
|
||||
continue
|
||||
if position == 'right' and expected in line[label_index + len(label):]:
|
||||
return True
|
||||
if position == 'below' and index + 1 < len(lines) and expected in lines[index + 1]:
|
||||
return True
|
||||
elif any(candidate.casefold() in text.casefold() for candidate in candidates):
|
||||
return True
|
||||
return False
|
||||
@@ -168,9 +168,9 @@ def _normalized_character_stream(
|
||||
|
||||
|
||||
def _normalize_text(value: Any) -> str:
|
||||
"""以 NFKC/casefold 保留字母数字和中日韩字符,忽略版面空白及标点。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
|
||||
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
|
||||
"""以 NFKC 保留字母数字和中日韩字符,忽略版面空白及标点但保留大小写。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or ''))
|
||||
return re.sub(r'[^0-9A-Za-z\u4e00-\u9fff]+', '', text)
|
||||
|
||||
|
||||
def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool:
|
||||
|
||||
@@ -302,9 +302,25 @@ def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
for table in tables:
|
||||
if not isinstance(table, dict) or not str(table.get('table_id') or ''):
|
||||
continue
|
||||
table_id = str(table['table_id'])
|
||||
try:
|
||||
grid = parse_html_grid(str(table.get('html') or ''), table_id=table_id)
|
||||
except ValidationError:
|
||||
# 候选列表只展示已有布局摘要;异常表格留给预览接口返回精确错误。
|
||||
continue
|
||||
header_preview = [
|
||||
slot.text for slot in (grid.rows[0] if grid.rows else [])
|
||||
if slot is not None and slot.text
|
||||
][:3]
|
||||
result.append({
|
||||
'document_id': document.id, 'table_id': str(table['table_id']),
|
||||
'document_id': document.id, 'table_id': table_id,
|
||||
'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '',
|
||||
'table_index': sum(
|
||||
1 for item in tables[:tables.index(table) + 1]
|
||||
if isinstance(item, dict) and int(item.get('page_no') or 1) == int(table.get('page_no') or 1)
|
||||
),
|
||||
'row_count': grid.row_count, 'column_count': grid.column_count,
|
||||
'header_preview': header_preview,
|
||||
})
|
||||
return {'samples': result}
|
||||
|
||||
@@ -762,6 +778,14 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""执行坐标模板发布门禁:训练样本、独立盲测与跨页声明覆盖均不可绕过。"""
|
||||
from app.models import ShippingOrderDocumentProfileSample
|
||||
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
document_match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
|
||||
required_anchors = document_match.get('required_anchors') if isinstance(document_match.get('required_anchors'), list) else []
|
||||
if not required_anchors:
|
||||
raise ConflictError(
|
||||
'At least one required static document anchor is required before publishing',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_REQUIRED_ANCHOR',
|
||||
)
|
||||
draft_checksum = _quality_checksum(profile)
|
||||
training_count = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=profile.id, sample_role='training',
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""解析 EML 正文 HTML 补充表并保留每格可追溯证据。
|
||||
|
||||
依赖:受控 HTML 网格解析、PO/Reservation 标准化。
|
||||
逻辑:只接受明确表头;表格歧义或缺 PO 保留原因,不将正文直接转成订单。
|
||||
依赖:受控 HTML 网格解析、冻结订单 Schema 表头契约、PO/Reservation 标准化。
|
||||
逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实
|
||||
仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,29 +19,34 @@ from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
_HEADERS = {
|
||||
'po_number': {'po', 'po number', 'po no', 'po #', 'purchase order', 'purchase order number'},
|
||||
'mpn': {'mpn', 'manufacturer part number', 'manufacturer pn', 'part number', 'mfr part number'},
|
||||
'reservation_id': {'reservation id', 'reservation', 'reservation no', 'reservation number'},
|
||||
_STATIC_HEADERS = {
|
||||
'allocation_id': {'allocation id', 'allocation'},
|
||||
'source_type': {'source type', 'source', 'hub code', 'hub'},
|
||||
'source_from_party': {'source from party', 'source from', 'from party', 'supplier'},
|
||||
'allocated_entity': {'allocated entity', 'allocation entity'},
|
||||
'allocated_qty': {'allocated qty', 'allocated quantity', 'allocation qty', 'allocation quantity'},
|
||||
}
|
||||
_NORMALIZED_HEADERS = {
|
||||
field: {normalize_table_header(item) for item in aliases}
|
||||
for field, aliases in _HEADERS.items()
|
||||
_NORMALIZED_STATIC_HEADERS = {
|
||||
field: {normalize_table_header(item).casefold() for item in aliases}
|
||||
for field, aliases in _STATIC_HEADERS.items()
|
||||
}
|
||||
_SCHEMA_FIELD_TO_SUPPLEMENT_FIELD = {
|
||||
'customer_po_number': 'po_number',
|
||||
'part_number': 'mpn',
|
||||
'reservation_id': 'reservation_id',
|
||||
'inventory_source_hint': 'source_type',
|
||||
}
|
||||
|
||||
|
||||
def _field_map(grid: Any) -> tuple[dict[int, str], list[str]]:
|
||||
"""只选择唯一映射的首行表头;重复字段映射直接标为复核。"""
|
||||
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
|
||||
"""将首行映射为 Schema 订单字段或邮件专属字段;重复映射直接标为复核。"""
|
||||
schema_headers = _schema_headers(schema_definition)
|
||||
mapped: dict[int, str] = {}
|
||||
issues: list[str] = []
|
||||
for column, slot in enumerate(grid.rows[0]):
|
||||
normalized = normalize_table_header(slot.text if slot is not None else '')
|
||||
hits = [field for field, aliases in _NORMALIZED_HEADERS.items() if normalized in aliases]
|
||||
normalized = normalize_table_header(slot.text if slot is not None else '').casefold()
|
||||
schema_field = schema_headers.get(normalized)
|
||||
static_hits = [field for field, aliases in _NORMALIZED_STATIC_HEADERS.items() if normalized in aliases]
|
||||
hits = ([schema_field] if schema_field else []) + static_hits
|
||||
if len(hits) == 1:
|
||||
if hits[0] in mapped.values():
|
||||
issues.append('email_supplement_duplicate_header')
|
||||
@@ -53,8 +59,27 @@ def _field_map(grid: Any) -> tuple[dict[int, str], list[str]]:
|
||||
return mapped, sorted(set(issues))
|
||||
|
||||
|
||||
def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str) -> dict[str, Any]:
|
||||
"""输出正文补充行和 DOM 单元格证据,不处理 PDF 合并或数量覆盖。"""
|
||||
def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
|
||||
"""收集邮件补充允许的 Schema 别名;跨字段冲突必须显式保留为不可映射。"""
|
||||
headers: dict[str, str | None] = {}
|
||||
for raw in schema_definition.get('fields') or []:
|
||||
if not isinstance(raw, dict) or not raw.get('enabled', True):
|
||||
continue
|
||||
supplement_field = _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.get(str(raw.get('field_code') or ''))
|
||||
if not supplement_field:
|
||||
continue
|
||||
for value in (raw.get('display_name'), *(raw.get('aliases') or [])):
|
||||
normalized = normalize_table_header(value).casefold()
|
||||
if normalized:
|
||||
if normalized not in headers:
|
||||
headers[normalized] = supplement_field
|
||||
elif headers[normalized] != supplement_field:
|
||||
headers[normalized] = None
|
||||
return headers
|
||||
|
||||
|
||||
def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str, schema_definition: dict[str, Any]) -> dict[str, Any]:
|
||||
"""输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。"""
|
||||
result = empty_email_supplement_result()
|
||||
rows: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
@@ -64,7 +89,7 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str)
|
||||
except Exception:
|
||||
issues.append('email_supplement_table_invalid')
|
||||
continue
|
||||
mapping, table_issues = _field_map(grid)
|
||||
mapping, table_issues = _field_map(grid, schema_definition=schema_definition)
|
||||
issues.extend(table_issues)
|
||||
if table_issues:
|
||||
continue
|
||||
@@ -101,7 +126,7 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str)
|
||||
return result
|
||||
|
||||
|
||||
def parse_email_allocation_text(*, body_text: str, content_hash: str) -> dict[str, Any]:
|
||||
def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_definition: dict[str, Any]) -> dict[str, Any]:
|
||||
"""解析无 HTML 的纵向表头正文,只有完整唯一表头序列才会产出补充行。
|
||||
|
||||
这类邮件客户端会把一行表头和数据单元格都展平成换行文本。按固定表头序列
|
||||
@@ -114,13 +139,19 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str) -> dict[st
|
||||
'allocated_entity', 'mpn', 'allocated_qty', 'po_number',
|
||||
]
|
||||
normalized = [normalize_table_header(token) for token in tokens]
|
||||
aliases = {
|
||||
field: {normalize_table_header(alias) for alias in values}
|
||||
for field, values in _HEADERS.items()
|
||||
schema_headers = _schema_headers(schema_definition)
|
||||
aliases: dict[str, set[str]] = {
|
||||
field: {header for header, mapped_field in schema_headers.items() if mapped_field == field}
|
||||
for field in _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.values()
|
||||
}
|
||||
aliases.update(_NORMALIZED_STATIC_HEADERS)
|
||||
casefold_aliases = {
|
||||
field: {value.casefold() for value in values}
|
||||
for field, values in aliases.items()
|
||||
}
|
||||
start = next((
|
||||
index for index in range(0, len(tokens) - len(expected) + 1)
|
||||
if all(normalized[index + offset] in aliases[field] for offset, field in enumerate(expected))
|
||||
if all(normalized[index + offset].casefold() in casefold_aliases[field] for offset, field in enumerate(expected))
|
||||
), None)
|
||||
if start is None:
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
"""
|
||||
services/shipping_notice/fulfillment_audit.py
|
||||
|
||||
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
|
||||
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / 工作项写路径调用;
|
||||
默认 strict=True,审计写入失败时抛错,禁止业务成功而审计缺失;访问审计逐次留痕;
|
||||
自动附带 request_id 与客户端 IP/UA(仅哈希入库)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _request_id() -> str | None:
|
||||
"""尽量读取当前请求 ID;Worker 场景允许为空。"""
|
||||
try:
|
||||
from flask import g
|
||||
return str(getattr(g, 'request_id', '') or '') or None
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def _client_request_context() -> tuple[str | None, str | None]:
|
||||
"""
|
||||
读取当前请求客户端 IP 与 User-Agent(仅供哈希入库)。
|
||||
|
||||
核心逻辑:优先 X-Forwarded-For 首段;无请求上下文时返回 (None, None)。
|
||||
"""
|
||||
try:
|
||||
from flask import request
|
||||
forwarded = str(request.headers.get('X-Forwarded-For') or '').split(',')[0].strip()
|
||||
ip = forwarded or str(request.remote_addr or '').strip() or None
|
||||
ua = str(request.headers.get('User-Agent') or '').strip() or None
|
||||
return ip, ua
|
||||
except RuntimeError:
|
||||
return None, None
|
||||
|
||||
|
||||
def resolve_request_audit_context() -> dict[str, str | None]:
|
||||
"""
|
||||
解析当前 HTTP 请求的审计关联上下文。
|
||||
|
||||
核心逻辑:合并 request_id 与原始 IP/UA(供 append 侧哈希);无 Flask 请求时全空。
|
||||
|
||||
Returns:
|
||||
含 request_id / client_ip / user_agent 的字典;值均可为 None。
|
||||
"""
|
||||
client_ip, user_agent = _client_request_context()
|
||||
return {
|
||||
'request_id': _request_id(),
|
||||
'client_ip': client_ip,
|
||||
'user_agent': user_agent,
|
||||
}
|
||||
|
||||
|
||||
def record_fulfillment_audit(
|
||||
*,
|
||||
event_type: str,
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
action: str,
|
||||
actor_type: str = 'user',
|
||||
actor_id: str | int | None = None,
|
||||
run_no: str | None = None,
|
||||
task_no: str | None = None,
|
||||
document_id: str | int | None = None,
|
||||
review_case_no: str | None = None,
|
||||
conversation_id: str | None = None,
|
||||
session_item_id: str | None = None,
|
||||
owner_user_id: str | int | None = None,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
result: str = 'success',
|
||||
before: dict[str, Any] | None = None,
|
||||
after: dict[str, Any] | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
source: str = 'api',
|
||||
strict: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
追加履约审计。
|
||||
|
||||
核心逻辑:默认与业务同事务写入;strict=True 时失败抛错,保证必须留存;
|
||||
自动附带 request_id 与客户端 IP/UA 哈希。
|
||||
|
||||
Args:
|
||||
event_type/action: 稳定事件与动作码。
|
||||
before/after: 必须已是白名单可投影的状态摘要。
|
||||
strict: True 时审计失败阻断调用方;False 时仅记日志(仅限显式降级场景)。
|
||||
"""
|
||||
request_id = _request_id()
|
||||
client_ip, user_agent = _client_request_context()
|
||||
try:
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type=aggregate_type,
|
||||
aggregate_id=str(aggregate_id),
|
||||
action=action,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
run_no=run_no,
|
||||
task_no=task_no,
|
||||
document_id=document_id,
|
||||
review_case_no=review_case_no,
|
||||
conversation_id=conversation_id,
|
||||
session_item_id=session_item_id,
|
||||
owner_user_id=owner_user_id,
|
||||
client_ip=client_ip,
|
||||
user_agent=user_agent,
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
result=result,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
source=source,
|
||||
)
|
||||
except Exception as exc:
|
||||
_LOGGER.exception('fulfillment audit append failed event_type=%s aggregate_id=%s', event_type, aggregate_id)
|
||||
if strict:
|
||||
raise ServiceUnavailableError(
|
||||
'Shipping audit persistence failed',
|
||||
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
|
||||
details={'event_type': event_type, 'aggregate_id': str(aggregate_id)},
|
||||
) from exc
|
||||
|
||||
|
||||
def record_access_audit(
|
||||
*,
|
||||
action: str,
|
||||
aggregate_type: str,
|
||||
aggregate_id: str,
|
||||
actor_id: str | int | None,
|
||||
actor_type: str = 'user',
|
||||
run_no: str | None = None,
|
||||
task_no: str | None = None,
|
||||
document_id: str | int | None = None,
|
||||
review_case_no: str | None = None,
|
||||
conversation_id: str | None = None,
|
||||
session_item_id: str | None = None,
|
||||
owner_user_id: str | int | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
strict: bool = True,
|
||||
) -> bool:
|
||||
"""
|
||||
记录敏感读取/导出访问审计(无业务正文);每次调用均落库。
|
||||
|
||||
核心逻辑:自行提交;失败时回滚并按 strict 抛错,禁止静默丢审计;附带客户端哈希。
|
||||
|
||||
Returns:
|
||||
True 表示本次写入了新事件。
|
||||
"""
|
||||
from app import db
|
||||
|
||||
request_id = _request_id()
|
||||
client_ip, user_agent = _client_request_context()
|
||||
try:
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_resource_accessed',
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
action=str(action)[:64],
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
run_no=run_no,
|
||||
task_no=task_no,
|
||||
document_id=document_id,
|
||||
review_case_no=review_case_no,
|
||||
conversation_id=conversation_id,
|
||||
session_item_id=session_item_id,
|
||||
owner_user_id=owner_user_id,
|
||||
client_ip=client_ip,
|
||||
user_agent=user_agent,
|
||||
result='success',
|
||||
metadata=metadata or {'access': True},
|
||||
source='api',
|
||||
persist_snapshots=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('access audit append failed action=%s aggregate_id=%s', action, aggregate_id)
|
||||
if strict:
|
||||
raise ServiceUnavailableError(
|
||||
'Shipping access audit persistence failed',
|
||||
code='SHIPPING_NOTICE.AUDIT_PERSIST_FAILED',
|
||||
details={'action': action, 'aggregate_id': str(aggregate_id)},
|
||||
) from exc
|
||||
return False
|
||||
@@ -615,6 +615,21 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
detail=filename,
|
||||
)
|
||||
log_task_event(task, "export_generated", {"file_name": filename, "artifact_no": artifact.artifact_no}, actor_id=actor_id, source='workspace_api' if actor_id else 'system')
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='excel_generated',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task.task_no,
|
||||
action='generate_excel',
|
||||
actor_type='user' if actor_id else 'system',
|
||||
actor_id=actor_id,
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
before={'status': 'matched'},
|
||||
after={'status': 'waiting_upload'},
|
||||
metadata={'artifact_no': artifact.artifact_no},
|
||||
source='workspace_api' if actor_id else 'system',
|
||||
)
|
||||
_commit_generated_export(path)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -843,6 +858,26 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"max_attempts": max_attempts,
|
||||
},
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='rpa_upload_triggered',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task.task_no,
|
||||
action='upload_rpa_triggered',
|
||||
actor_type='system',
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
before={'status': 'waiting_upload'},
|
||||
after={'status': 'uploading'},
|
||||
metadata={
|
||||
'attempt_no': attempt_no,
|
||||
'max_attempts': max_attempts,
|
||||
'timeout_seconds': timeout_seconds,
|
||||
'attempt_id': int(attempt.id),
|
||||
'artifact_id': int(artifact.id),
|
||||
},
|
||||
source='rpa',
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="running",
|
||||
@@ -950,6 +985,21 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
detail=t("workflow.fulfillment.task_completed", lang=lang),
|
||||
)
|
||||
log_task_event(task, "upload_rpa_success", {"artifact_id": completed.artifact_id, "attempt_id": completed.id})
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
record_fulfillment_audit(
|
||||
event_type='rpa_upload_result',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task.task_no,
|
||||
action='upload_rpa_success',
|
||||
actor_type='rpa',
|
||||
task_no=task.task_no,
|
||||
conversation_id=task.conversation_id,
|
||||
result='success',
|
||||
before={'status': 'uploading'},
|
||||
after={'status': 'uploaded'},
|
||||
metadata={'attempt_id': int(completed.id), 'artifact_id': int(completed.artifact_id or 0) or None},
|
||||
source='rpa_callback',
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.models import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
normalize_customer_name,
|
||||
@@ -82,16 +83,58 @@ def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[Shippin
|
||||
}
|
||||
|
||||
|
||||
def definition_context_field_is_compatible(
|
||||
definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str,
|
||||
) -> bool:
|
||||
"""校验新版 Schema 字段能否承接旧规则快照,防止字段 UUID 漂移误伤稳定业务语义。"""
|
||||
expected_id = str(definition.get('context_field_id') or '')
|
||||
if actual_field_id == expected_id:
|
||||
return True
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
field_code = str(field_config.get('field_code') or '').strip()
|
||||
expected_scope = str(field_config.get('scope') or '')
|
||||
expected_type = str(field_config.get('value_type') or '')
|
||||
schema_version = db.session.get(ShippingOrderSchemaVersion, extraction.schema_version_id)
|
||||
fields = (schema_version.definition_json or {}).get('fields') if schema_version else []
|
||||
actual = next((item for item in fields or [] if str(item.get('field_id') or '') == actual_field_id), None)
|
||||
return bool(
|
||||
field_code
|
||||
and actual
|
||||
and str(actual.get('field_code') or '') == field_code
|
||||
and str(actual.get('scope') or '') == expected_scope == 'header'
|
||||
and str(actual.get('value_type') or '') == expected_type
|
||||
and actual.get('enabled', True)
|
||||
and actual.get('available_for_customer_identity')
|
||||
)
|
||||
|
||||
|
||||
def _resolved_context_field_id(
|
||||
definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]],
|
||||
) -> str | None:
|
||||
"""优先使用快照 UUID;Schema 升级仅在字段业务语义未变化时按 field_code 映射到新 UUID。"""
|
||||
expected_id = str(definition.get('context_field_id') or '')
|
||||
if expected_id in header_values:
|
||||
return expected_id
|
||||
if extraction is None:
|
||||
return None
|
||||
for field_id in header_values:
|
||||
if definition_context_field_is_compatible(definition, extraction, field_id):
|
||||
return field_id
|
||||
return None
|
||||
|
||||
|
||||
def _source_evidence(
|
||||
definitions: list[dict[str, Any]], *, candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake,
|
||||
) -> tuple[list[dict[str, Any]], ShippingOrderExtraction | None]:
|
||||
"""按规则快照的 context_field_id 编译证据,只消费统一已裁决字段值。"""
|
||||
"""按规则快照编译证据;Schema UUID 漂移时仅映射语义兼容的 Header 字段。"""
|
||||
extraction, header_values = _accepted_header_values(candidate)
|
||||
evidence: list[dict[str, Any]] = []
|
||||
for definition in definitions:
|
||||
definition_id = str(definition.get('id') or '')
|
||||
code = str(definition.get('definition_code') or '')
|
||||
field_id = str(definition.get('context_field_id') or '')
|
||||
field_id = _resolved_context_field_id(definition, extraction, header_values)
|
||||
if field_id is None:
|
||||
continue
|
||||
accepted = header_values.get(field_id)
|
||||
if not accepted:
|
||||
continue
|
||||
|
||||
@@ -599,6 +599,71 @@ def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, act
|
||||
return {'document_id': document.id, 'page_no': int(page_no), 'tables': candidates, 'status': 'needs_review'}
|
||||
|
||||
|
||||
def read_preview_page_region_text(
|
||||
profile_id: int, *, data: dict[str, Any], page_no: int, actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""读取管理员框选区域的冻结坐标文字,供画布创建标签-值匹配锚点。
|
||||
|
||||
Args:
|
||||
profile_id: 当前草稿模板;只允许读取其绑定样本。
|
||||
data: 必须含 document_id 和相对坐标 region,禁止传入资产路径或任意正文。
|
||||
page_no: 当前受控预览页号。
|
||||
actor_id: 当前管理员;缺失时按不存在样本关闭。
|
||||
Returns:
|
||||
仅返回框内恢复的纯文本和证据来源,不返回坐标、页面内容或存储信息。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
try:
|
||||
document_id = int(data.get('document_id'))
|
||||
region = data.get('region')
|
||||
x0, y0, x1, y1 = (float(region[key]) for key in ('x0', 'y0', 'x1', 'y1'))
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValidationError('region is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') from exc
|
||||
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
|
||||
raise ValidationError('region is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
document = _bound_sample_document(profile_id, document_id)
|
||||
layout = _ensure_page_coordinate_evidence(document=document, layout=_document_layout(document), page_no=page_no)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page = (evidence.get('pages') or {}).get(str(page_no)) or {}
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValidationError('Page coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
|
||||
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
|
||||
# Prefer character centers: this is the only rule that reliably separates
|
||||
# adjacent document lines. The overlap fallback is used solely for an edge-only
|
||||
# selection and is constrained to the nearest visual line.
|
||||
selected_by_center = []
|
||||
overlapping = []
|
||||
for glyph in glyphs:
|
||||
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
|
||||
if not bbox:
|
||||
continue
|
||||
try:
|
||||
glyph_x0, glyph_x1 = float(bbox['x0']) / width, float(bbox['x1']) / width
|
||||
glyph_y0, glyph_y1 = float(bbox['y0']) / height, float(bbox['y1']) / height
|
||||
except (KeyError, TypeError, ValueError, ZeroDivisionError):
|
||||
continue
|
||||
center_x, center_y = (glyph_x0 + glyph_x1) / 2, (glyph_y0 + glyph_y1) / 2
|
||||
if x0 <= center_x <= x1 and y0 <= center_y <= y1:
|
||||
selected_by_center.append(glyph)
|
||||
elif glyph_x1 >= x0 and glyph_x0 <= x1 and glyph_y1 >= y0 and glyph_y0 <= y1:
|
||||
overlapping.append(glyph)
|
||||
selected = selected_by_center
|
||||
if not selected and overlapping:
|
||||
target_y = (y0 + y1) / 2
|
||||
lines = _page_text_lines(overlapping)
|
||||
nearest = min(lines, key=lambda line: abs(((line[1]['y0'] + line[1]['y1']) / 2 / height) - target_y))
|
||||
selected = nearest[2]
|
||||
text = ' '.join(line[0].strip() for line in _page_text_lines(selected) if line[0].strip()).strip()
|
||||
_audit(profile_id=int(profile_id), document_id=document.id, event_type='preview_region_text_read', actor_id=actor_id, detail={
|
||||
'page_no': int(page_no), 'character_count': len(text), 'source': source,
|
||||
})
|
||||
db.session.commit()
|
||||
return {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'}
|
||||
|
||||
|
||||
def preview_profile_region(
|
||||
profile_id: int, *, data: dict[str, Any], actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -2119,7 +2184,7 @@ def save_draft(
|
||||
|
||||
|
||||
def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""从不可变版本复制新草稿;同编码只允许一个草稿。"""
|
||||
"""从不可变版本复制新草稿,并继承编辑画布所需的标注样本;同编码只允许一个草稿。"""
|
||||
source = db.session.get(ShippingOrderDocumentProfile, profile_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
@@ -2152,6 +2217,18 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
)
|
||||
db.session.add(clone)
|
||||
db.session.flush()
|
||||
annotation_samples = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=source.id, sample_role='annotation',
|
||||
).all()
|
||||
for sample in annotation_samples:
|
||||
# 草稿编辑器需要 annotation 样本加载 PDF;训练和盲测样本仍须重新绑定以保留发布门禁。
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=clone.id,
|
||||
document_id=sample.document_id,
|
||||
table_id=sample.table_id,
|
||||
sample_role='annotation',
|
||||
created_by_id=actor_id,
|
||||
))
|
||||
revision = ShippingOrderDocumentProfileDraftRevision(
|
||||
profile_id=clone.id,
|
||||
revision_no=1,
|
||||
@@ -2167,7 +2244,10 @@ def clone_draft(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
)
|
||||
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, 'revision_no': revision.revision_no,
|
||||
'source_profile_id': source.id,
|
||||
'version': clone.version,
|
||||
'revision_no': revision.revision_no,
|
||||
'inherited_annotation_sample_count': len(annotation_samples),
|
||||
})
|
||||
db.session.commit()
|
||||
result = payload(clone)
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
"""
|
||||
services/shipping_notice/order_extraction_cancel_service.py
|
||||
|
||||
用途:处理订单抽取 Run/Unit 的取消请求,实现取消请求语义与权限校验。
|
||||
依赖:order_extraction_plan 状态机、order_extraction_progress、audit_service、progress_audit_contract、progress_feature_flags。
|
||||
逻辑:排队 Unit 立即 cancelled;执行中 Unit 仅标记 cancellation_requested,由 Worker 在安全点收口;
|
||||
已完成结果保留。业务变更、Progress Event 与审计必须同事务追加。功能开关关闭时拒绝取消。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import g
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
record_order_extraction_progress_event,
|
||||
record_unit_progress,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.progress_feature_flags import order_extraction_cancel_enabled
|
||||
|
||||
ACTIVE_RUN_STATUSES = frozenset({'queued', 'processing'})
|
||||
PENDING_UNIT_STATUS = 'pending'
|
||||
IN_FLIGHT_UNIT_STATUSES = frozenset({'routing', 'matching_profile', 'extracting', 'merging_supplement'})
|
||||
PRESERVE_UNIT_STATUSES = frozenset({'candidate_ready', 'review_required', 'failed', 'cancelled'})
|
||||
|
||||
|
||||
def _require_cancel_feature_enabled() -> None:
|
||||
"""灰度关闭取消能力时拒绝 API,避免投影已隐藏动作后仍被直调。"""
|
||||
if not order_extraction_cancel_enabled():
|
||||
raise ValidationError(
|
||||
'Order extraction cancel is disabled by feature flag',
|
||||
code='SHIPPING_NOTICE.CANCEL_FEATURE_DISABLED',
|
||||
)
|
||||
|
||||
|
||||
def _request_id() -> str | None:
|
||||
"""读取当前请求 ID,用于审计串联。"""
|
||||
value = getattr(g, 'request_id', None)
|
||||
return str(value) if value else None
|
||||
|
||||
|
||||
def _operation_id(explicit: str | None = None) -> str:
|
||||
"""生成或复用 operation_id。"""
|
||||
text = str(explicit or '').strip()
|
||||
if text:
|
||||
return text[:64]
|
||||
request_id = _request_id()
|
||||
if request_id:
|
||||
return request_id[:64]
|
||||
return f'cancel-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}-{id(object()) % 10_000_000}'
|
||||
|
||||
|
||||
def _resolve_cancellation_operation_id(run: ShippingOrderExtractionRun, explicit: str | None = None) -> str:
|
||||
"""
|
||||
复用取消请求时的 operation_id,避免 Worker 收口生成新链路。
|
||||
|
||||
核心逻辑:显式参数 > progress 事件 summary.operation_id > 新建。
|
||||
"""
|
||||
if str(explicit or '').strip():
|
||||
return _operation_id(explicit)
|
||||
event = (
|
||||
ShippingOrderExtractionProgressEvent.query
|
||||
.filter_by(run_id=int(run.id), event_code='cancellation_requested')
|
||||
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.desc())
|
||||
.first()
|
||||
)
|
||||
if event is not None and isinstance(event.summary_json, dict):
|
||||
previous = str(event.summary_json.get('operation_id') or '').strip()
|
||||
if previous:
|
||||
return previous[:64]
|
||||
return _operation_id()
|
||||
|
||||
|
||||
def _is_admin(actor: User) -> bool:
|
||||
"""判断操作者是否具备管理员取消权限。"""
|
||||
return str(getattr(actor, 'role', '') or '') == 'admin'
|
||||
|
||||
|
||||
def _lock_run_for_actor(*, actor: User, run_no: str) -> ShippingOrderExtractionRun:
|
||||
"""
|
||||
按权限锁定 Run。
|
||||
|
||||
核心逻辑:普通用户只能锁定自己的 Run;管理员可锁定任意 Run。
|
||||
"""
|
||||
query = db.session.query(ShippingOrderExtractionRun).filter_by(run_no=str(run_no or '').strip())
|
||||
if not _is_admin(actor):
|
||||
query = query.filter_by(user_id=int(actor.id))
|
||||
run = query.with_for_update().first()
|
||||
if run is None:
|
||||
raise NotFoundError(
|
||||
'Shipping order extraction run not found',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND',
|
||||
)
|
||||
return run
|
||||
|
||||
|
||||
def _validate_cancel_permission(*, actor: User, run: ShippingOrderExtractionRun, reason: str | None) -> None:
|
||||
"""
|
||||
校验取消权限与原因。
|
||||
|
||||
Raises:
|
||||
ForbiddenError: 普通用户取消他人 Run。
|
||||
ValidationError: 管理员代取消缺少原因。
|
||||
"""
|
||||
admin = _is_admin(actor)
|
||||
if not admin and int(run.user_id) != int(actor.id):
|
||||
raise ForbiddenError(
|
||||
'Cannot cancel another user order extraction run',
|
||||
code='SHIPPING_NOTICE.CANCEL_FORBIDDEN',
|
||||
)
|
||||
if admin and int(run.user_id) != int(actor.id) and not str(reason or '').strip():
|
||||
raise ValidationError(
|
||||
'Admin cancel requires a reason',
|
||||
code='SHIPPING_NOTICE.CANCEL_REASON_REQUIRED',
|
||||
)
|
||||
|
||||
|
||||
def _cancellation_payload(*, actor: User, reason: str | None, reason_code: str | None, now: datetime) -> dict[str, Any]:
|
||||
"""构造取消元数据写入字段。"""
|
||||
return {
|
||||
'cancellation_requested_at': now,
|
||||
'cancellation_actor_type': 'admin' if _is_admin(actor) else 'user',
|
||||
'cancellation_actor_id': str(actor.id),
|
||||
'cancellation_reason': str(reason).strip()[:2000] if reason else None,
|
||||
'cancellation_reason_code': str(reason_code).strip()[:64] if reason_code else None,
|
||||
}
|
||||
|
||||
|
||||
def _apply_fields(target: Any, fields: dict[str, Any]) -> None:
|
||||
"""把取消元数据写到 Run 或 Unit。"""
|
||||
for key, value in fields.items():
|
||||
setattr(target, key, value)
|
||||
|
||||
|
||||
def _unit_snapshot(unit: ShippingOrderExtractionUnit) -> dict[str, Any]:
|
||||
"""Unit 审计白名单投影。"""
|
||||
return {
|
||||
'status': unit.status,
|
||||
'activity_version': int(getattr(unit, 'activity_version', 1) or 1),
|
||||
'cancellation_requested': bool(getattr(unit, 'cancellation_requested_at', None)),
|
||||
'attempt_count': int(unit.attempt_count or 0),
|
||||
}
|
||||
|
||||
|
||||
def _run_snapshot(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""Run 审计白名单投影。"""
|
||||
return {
|
||||
'status': run.status,
|
||||
'phase': run.phase,
|
||||
'progress_version': int(run.progress_version or 0),
|
||||
'cancellation_requested': bool(run.cancellation_requested_at),
|
||||
}
|
||||
|
||||
|
||||
def _cancel_pending_unit(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
fields: dict[str, Any],
|
||||
operation_id: str,
|
||||
) -> None:
|
||||
"""立即取消排队 Unit,并写入进度与审计。"""
|
||||
before = _unit_snapshot(unit)
|
||||
_apply_fields(unit, fields)
|
||||
unit.activity_version = int(getattr(unit, 'activity_version', 1) or 1) + 1
|
||||
unit.cancellation_completed_at = fields['cancellation_requested_at']
|
||||
transition_order_extraction_unit(unit, target_status='cancelled', error_code='ORDER_EXTRACTION_CANCELLED')
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='unit_cancelled',
|
||||
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
|
||||
summary={'operation_id': operation_id},
|
||||
commit=False,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_unit_cancel_completed',
|
||||
aggregate_type='order_extraction_unit',
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=run.run_no,
|
||||
actor_type=fields['cancellation_actor_type'],
|
||||
actor_id=fields['cancellation_actor_id'],
|
||||
request_id=_request_id(),
|
||||
operation_id=operation_id,
|
||||
source='api',
|
||||
result='success',
|
||||
action='cancel_unit',
|
||||
reason=fields.get('cancellation_reason'),
|
||||
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
|
||||
conversation_id=run.conversation_id,
|
||||
unit_id=unit.id,
|
||||
document_id=unit.document_id,
|
||||
before=before,
|
||||
after=_unit_snapshot(unit),
|
||||
)
|
||||
|
||||
|
||||
def _request_inflight_unit_cancel(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
fields: dict[str, Any],
|
||||
operation_id: str,
|
||||
) -> None:
|
||||
"""对执行中 Unit 仅写入取消请求,等待 Worker 安全点生效。"""
|
||||
if unit.cancellation_requested_at is not None:
|
||||
return
|
||||
before = _unit_snapshot(unit)
|
||||
_apply_fields(unit, fields)
|
||||
unit.activity_version = int(getattr(unit, 'activity_version', 1) or 1) + 1
|
||||
unit.last_activity_at = fields['cancellation_requested_at']
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='cancellation_requested',
|
||||
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
|
||||
summary={'operation_id': operation_id},
|
||||
commit=False,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_unit_cancel_requested',
|
||||
aggregate_type='order_extraction_unit',
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=run.run_no,
|
||||
actor_type=fields['cancellation_actor_type'],
|
||||
actor_id=fields['cancellation_actor_id'],
|
||||
request_id=_request_id(),
|
||||
operation_id=operation_id,
|
||||
source='api',
|
||||
result='success',
|
||||
action='cancel_unit',
|
||||
reason=fields.get('cancellation_reason'),
|
||||
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
|
||||
conversation_id=run.conversation_id,
|
||||
unit_id=unit.id,
|
||||
document_id=unit.document_id,
|
||||
before=before,
|
||||
after=_unit_snapshot(unit),
|
||||
)
|
||||
|
||||
|
||||
def _has_inflight_units(units: list[ShippingOrderExtractionUnit]) -> bool:
|
||||
"""是否仍有执行中、尚未取消完成的 Unit。"""
|
||||
for unit in units:
|
||||
if unit.status in IN_FLIGHT_UNIT_STATUSES and unit.cancellation_completed_at is None:
|
||||
return True
|
||||
if unit.status == PENDING_UNIT_STATUS and unit.cancellation_completed_at is None:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def finalize_run_cancellation_if_ready(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
operation_id: str | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
若取消已请求且无剩余活跃 Unit,则将 Run 收口为 cancelled。
|
||||
|
||||
核心逻辑:保留 candidate_ready/review_required/failed 结果;仅在无 pending/in-flight 时终态化。
|
||||
|
||||
Returns:
|
||||
是否完成 Run 取消收口。
|
||||
"""
|
||||
if run.cancellation_requested_at is None:
|
||||
return False
|
||||
if run.status == 'cancelled' and run.cancellation_completed_at is not None:
|
||||
return True
|
||||
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
if _has_inflight_units(units):
|
||||
return False
|
||||
before = _run_snapshot(run)
|
||||
op = _resolve_cancellation_operation_id(run, operation_id)
|
||||
now = datetime.utcnow()
|
||||
if run.status in ACTIVE_RUN_STATUSES:
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='cancelled',
|
||||
phase='cancellation_completed',
|
||||
result={
|
||||
'cancelled': True,
|
||||
'completed_count': sum(1 for unit in units if unit.status == 'candidate_ready'),
|
||||
'review_required_count': sum(1 for unit in units if unit.status == 'review_required'),
|
||||
'failed_count': sum(1 for unit in units if unit.status == 'failed'),
|
||||
'cancelled_count': sum(1 for unit in units if unit.status == 'cancelled'),
|
||||
},
|
||||
)
|
||||
run.cancellation_completed_at = now
|
||||
record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={
|
||||
'event_code': 'cancellation_completed',
|
||||
'status': 'cancelled',
|
||||
'reason_code': run.cancellation_reason_code or 'user_cancelled',
|
||||
'summary': {'operation_id': op},
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_run_cancel_completed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=run.run_no,
|
||||
run_no=run.run_no,
|
||||
actor_type=actor_type or run.cancellation_actor_type or 'system',
|
||||
actor_id=actor_id or run.cancellation_actor_id,
|
||||
request_id=_request_id(),
|
||||
operation_id=op,
|
||||
source='worker' if actor_type == 'system' else 'api',
|
||||
result='success',
|
||||
action='cancel_run',
|
||||
reason=run.cancellation_reason,
|
||||
reason_code=run.cancellation_reason_code or 'user_cancelled',
|
||||
conversation_id=run.conversation_id,
|
||||
before=before,
|
||||
after=_run_snapshot(run),
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def apply_worker_cancellation_checkpoint(*, run: ShippingOrderExtractionRun) -> bool:
|
||||
"""
|
||||
Worker 安全检查点:取消剩余 pending,并收口已请求取消的 in-flight Unit。
|
||||
|
||||
Returns:
|
||||
True 表示调用方应停止启动新的 Unit 工作。
|
||||
"""
|
||||
if run.cancellation_requested_at is None:
|
||||
return False
|
||||
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
now = datetime.utcnow()
|
||||
fields = {
|
||||
'cancellation_requested_at': run.cancellation_requested_at,
|
||||
'cancellation_actor_type': run.cancellation_actor_type or 'system',
|
||||
'cancellation_actor_id': run.cancellation_actor_id,
|
||||
'cancellation_reason': run.cancellation_reason,
|
||||
'cancellation_reason_code': run.cancellation_reason_code or 'user_cancelled',
|
||||
}
|
||||
op = _resolve_cancellation_operation_id(run)
|
||||
for unit in units:
|
||||
if unit.status == PENDING_UNIT_STATUS and unit.cancellation_completed_at is None:
|
||||
_cancel_pending_unit(run=run, unit=unit, fields=fields, operation_id=op)
|
||||
elif (
|
||||
unit.status in IN_FLIGHT_UNIT_STATUSES
|
||||
and unit.cancellation_requested_at is not None
|
||||
and unit.cancellation_completed_at is None
|
||||
):
|
||||
before = _unit_snapshot(unit)
|
||||
transition_order_extraction_unit(unit, target_status='cancelled', error_code='ORDER_EXTRACTION_CANCELLED')
|
||||
unit.cancellation_completed_at = now
|
||||
unit.activity_version = int(getattr(unit, 'activity_version', 1) or 1) + 1
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='unit_cancelled',
|
||||
reason_code=unit.cancellation_reason_code or 'user_cancelled',
|
||||
summary={'operation_id': op, 'source': 'worker_checkpoint'},
|
||||
commit=False,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_unit_cancel_completed',
|
||||
aggregate_type='order_extraction_unit',
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
actor_id='shipping_order_extraction_worker',
|
||||
request_id=_request_id(),
|
||||
operation_id=op,
|
||||
source='worker',
|
||||
result='success',
|
||||
action='cancel_unit',
|
||||
reason=unit.cancellation_reason,
|
||||
reason_code=unit.cancellation_reason_code or 'user_cancelled',
|
||||
conversation_id=run.conversation_id,
|
||||
unit_id=unit.id,
|
||||
document_id=unit.document_id,
|
||||
before=before,
|
||||
after=_unit_snapshot(unit),
|
||||
)
|
||||
finalize_run_cancellation_if_ready(
|
||||
run=run,
|
||||
operation_id=op,
|
||||
actor_type='system',
|
||||
actor_id='shipping_order_extraction_worker',
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def should_abort_unit_for_cancellation(*, run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit) -> bool:
|
||||
"""
|
||||
判断 Unit 在外部副作用前是否应中止。
|
||||
|
||||
核心逻辑:Run 或 Unit 已请求取消时返回 True。
|
||||
"""
|
||||
return bool(run.cancellation_requested_at or unit.cancellation_requested_at)
|
||||
|
||||
|
||||
def cancel_order_extraction_run(
|
||||
*,
|
||||
actor: User,
|
||||
run_no: str,
|
||||
reason: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingOrderExtractionRun:
|
||||
"""
|
||||
请求取消整批订单抽取 Run。
|
||||
|
||||
核心逻辑:写入 Run 取消请求;立即取消 pending Unit;执行中 Unit 进入正在取消;
|
||||
若无活跃 Unit 则立即收口为 cancelled。
|
||||
|
||||
Args:
|
||||
actor: 当前用户;管理员代取消必须提供 reason。
|
||||
run_no: Run 编号。
|
||||
reason/reason_code: 取消原因。
|
||||
operation_id: 可选操作关联键。
|
||||
|
||||
Returns:
|
||||
更新后的 Run。
|
||||
"""
|
||||
_require_cancel_feature_enabled()
|
||||
run = _lock_run_for_actor(actor=actor, run_no=run_no)
|
||||
_validate_cancel_permission(actor=actor, run=run, reason=reason)
|
||||
if run.status not in ACTIVE_RUN_STATUSES:
|
||||
raise ConflictError(
|
||||
'Only active order extraction runs can be cancelled',
|
||||
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
|
||||
details={'status': run.status},
|
||||
)
|
||||
op = _operation_id(operation_id)
|
||||
if run.cancellation_requested_at is not None:
|
||||
finalize_run_cancellation_if_ready(
|
||||
run=run,
|
||||
operation_id=op,
|
||||
actor_type='admin' if _is_admin(actor) else 'user',
|
||||
actor_id=str(actor.id),
|
||||
)
|
||||
return run
|
||||
|
||||
before = _run_snapshot(run)
|
||||
now = datetime.utcnow()
|
||||
fields = _cancellation_payload(actor=actor, reason=reason, reason_code=reason_code, now=now)
|
||||
_apply_fields(run, fields)
|
||||
run.progress_version = int(run.progress_version or 0) + 1
|
||||
run.last_activity_at = now
|
||||
|
||||
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
for unit in units:
|
||||
if unit.status == PENDING_UNIT_STATUS:
|
||||
_cancel_pending_unit(run=run, unit=unit, fields=fields, operation_id=op)
|
||||
elif unit.status in IN_FLIGHT_UNIT_STATUSES:
|
||||
_request_inflight_unit_cancel(run=run, unit=unit, fields=fields, operation_id=op)
|
||||
elif unit.status in PRESERVE_UNIT_STATUSES:
|
||||
continue
|
||||
|
||||
record_order_extraction_progress_event(
|
||||
run_no=run.run_no,
|
||||
event={
|
||||
'event_code': 'cancellation_requested',
|
||||
'status': 'cancellation_requested',
|
||||
'reason_code': fields.get('cancellation_reason_code') or 'user_cancelled',
|
||||
'summary': {'operation_id': op},
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_run_cancel_requested',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=run.run_no,
|
||||
run_no=run.run_no,
|
||||
actor_type=fields['cancellation_actor_type'],
|
||||
actor_id=fields['cancellation_actor_id'],
|
||||
request_id=_request_id(),
|
||||
operation_id=op,
|
||||
source='api',
|
||||
result='success',
|
||||
action='cancel_run',
|
||||
reason=fields.get('cancellation_reason'),
|
||||
reason_code=fields.get('cancellation_reason_code') or 'user_cancelled',
|
||||
conversation_id=run.conversation_id,
|
||||
before=before,
|
||||
after=_run_snapshot(run),
|
||||
)
|
||||
finalize_run_cancellation_if_ready(
|
||||
run=run,
|
||||
operation_id=op,
|
||||
actor_type=fields['cancellation_actor_type'],
|
||||
actor_id=fields['cancellation_actor_id'],
|
||||
)
|
||||
db.session.flush()
|
||||
return run
|
||||
|
||||
|
||||
def cancel_order_extraction_unit(
|
||||
*,
|
||||
actor: User,
|
||||
run_no: str,
|
||||
document_id: int,
|
||||
reason: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingOrderExtractionUnit:
|
||||
"""
|
||||
请求取消单个 PDF Unit。
|
||||
|
||||
核心逻辑:仅活跃 Unit 可取消;pending 立即生效,执行中写请求;完成后尝试收口 Run。
|
||||
"""
|
||||
_require_cancel_feature_enabled()
|
||||
run = _lock_run_for_actor(actor=actor, run_no=run_no)
|
||||
_validate_cancel_permission(actor=actor, run=run, reason=reason)
|
||||
if run.status not in ACTIVE_RUN_STATUSES:
|
||||
raise ConflictError(
|
||||
'Only active order extraction runs can cancel units',
|
||||
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
|
||||
details={'status': run.status},
|
||||
)
|
||||
units = list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
unit = next((row for row in units if int(row.document_id) == int(document_id)), None)
|
||||
if unit is None:
|
||||
raise NotFoundError(
|
||||
'Shipping order extraction unit not found',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_NOT_FOUND',
|
||||
)
|
||||
if unit.status in PRESERVE_UNIT_STATUSES and unit.status != 'cancelled':
|
||||
raise ConflictError(
|
||||
'Completed or failed units cannot be cancelled',
|
||||
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
|
||||
details={'status': unit.status},
|
||||
)
|
||||
if unit.status == 'cancelled':
|
||||
return unit
|
||||
|
||||
op = _operation_id(operation_id)
|
||||
now = datetime.utcnow()
|
||||
fields = _cancellation_payload(actor=actor, reason=reason, reason_code=reason_code, now=now)
|
||||
if run.cancellation_requested_at is None and unit.status == PENDING_UNIT_STATUS:
|
||||
# 单文件取消不强制把整批标记为取消请求,除非全部活跃项已取消。
|
||||
pass
|
||||
if unit.status == PENDING_UNIT_STATUS:
|
||||
_cancel_pending_unit(run=run, unit=unit, fields=fields, operation_id=op)
|
||||
elif unit.status in IN_FLIGHT_UNIT_STATUSES:
|
||||
_request_inflight_unit_cancel(run=run, unit=unit, fields=fields, operation_id=op)
|
||||
else:
|
||||
raise ConflictError(
|
||||
'Unit is not cancellable',
|
||||
code='SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
|
||||
details={'status': unit.status},
|
||||
)
|
||||
|
||||
remaining_active = [
|
||||
row for row in units
|
||||
if row.status in (IN_FLIGHT_UNIT_STATUSES | {PENDING_UNIT_STATUS})
|
||||
and row.cancellation_completed_at is None
|
||||
and int(row.id) != int(unit.id)
|
||||
]
|
||||
if not remaining_active and all(
|
||||
row.status in PRESERVE_UNIT_STATUSES or row.cancellation_completed_at is not None
|
||||
for row in units
|
||||
):
|
||||
if run.cancellation_requested_at is None:
|
||||
_apply_fields(run, fields)
|
||||
run.progress_version = int(run.progress_version or 0) + 1
|
||||
finalize_run_cancellation_if_ready(
|
||||
run=run,
|
||||
operation_id=op,
|
||||
actor_type=fields['cancellation_actor_type'],
|
||||
actor_id=fields['cancellation_actor_id'],
|
||||
)
|
||||
db.session.flush()
|
||||
return unit
|
||||
@@ -70,6 +70,30 @@ def _selected_attachment_keys_for_intake(
|
||||
return selected
|
||||
|
||||
|
||||
def _require_selected_document_keys(
|
||||
*, intake: ShippingNoticeIntake, selected_attachment_keys: set[str],
|
||||
) -> None:
|
||||
"""校验本次授权附件已全部物化,阻止空输入进入版面和订单任务。
|
||||
|
||||
AI 触发时机:发送阶段深度解析并持久化 EML 附件后调用。附件目录与原始邮件
|
||||
载荷可能因损坏或解析差异而不一致;此时必须明确报输入准备失败,不能继续尝试
|
||||
创建版面任务并误报版面服务不可用。
|
||||
"""
|
||||
existing_keys = _existing_document_keys(intake)
|
||||
missing_keys = sorted(selected_attachment_keys - existing_keys)
|
||||
if not missing_keys:
|
||||
return
|
||||
raise ConflictError(
|
||||
'Selected shipping notice attachments could not be materialized',
|
||||
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
|
||||
details={
|
||||
'intake_nos': [str(intake.intake_no or '')],
|
||||
'reason': 'selected_attachment_document_missing',
|
||||
'missing_attachment_keys': missing_keys,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _parse_attachment_payload(
|
||||
*, payload: bytes, filename: str, mime_type: str, flask_app: Any | None = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
@@ -310,3 +334,8 @@ def ensure_order_extraction_input_documents(
|
||||
),
|
||||
schema_definition=definition,
|
||||
)
|
||||
# 持久化是后续版面任务唯一允许的输入来源,必须逐项与冻结选择计划一致。
|
||||
_require_selected_document_keys(
|
||||
intake=intake,
|
||||
selected_attachment_keys=selected_attachment_keys,
|
||||
)
|
||||
@@ -421,16 +421,37 @@ def transition_order_extraction_unit(
|
||||
unit.technical_failure_reason_code = None
|
||||
plan_run = getattr(unit.plan, 'run', None)
|
||||
if plan_run is not None and getattr(plan_run, 'run_no', None):
|
||||
request_id = None
|
||||
try:
|
||||
from flask import g
|
||||
request_id = str(getattr(g, 'request_id', '') or '') or None
|
||||
except RuntimeError:
|
||||
request_id = None
|
||||
operation_id = request_id or f'unit-status-{unit.id}-{int(unit.attempt_count or 0)}-{target_status}'
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_unit_status_changed',
|
||||
aggregate_type='order_extraction_unit',
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=str(plan_run.run_no),
|
||||
document_id=int(unit.document_id),
|
||||
actor_type='system',
|
||||
actor_id='shipping_order_extraction_worker',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id[:64],
|
||||
source='worker',
|
||||
result='success',
|
||||
action='unit_status_transition',
|
||||
attempt_no=int(unit.attempt_count or 0),
|
||||
reason_code=unit.reason_code if target_status in {'review_required', 'cancelled'} else unit.error_code if target_status == 'failed' else None,
|
||||
before=before_projection,
|
||||
after={'status': target_status, 'attempt_count': int(unit.attempt_count or 0)},
|
||||
metadata={'target_status': target_status},
|
||||
after={
|
||||
'status': target_status,
|
||||
'attempt_count': int(unit.attempt_count or 0),
|
||||
'retry_status': unit.retry_status,
|
||||
'reason_code': unit.reason_code,
|
||||
'error_code': unit.error_code,
|
||||
},
|
||||
metadata={'target_status': target_status, 'from_status': current},
|
||||
)
|
||||
_refresh_plan_status(unit.plan)
|
||||
return unit
|
||||
@@ -2,8 +2,9 @@
|
||||
services/shipping_notice/order_extraction_progress.py
|
||||
|
||||
用途:记录订单抽取 Run/Unit 的确定性业务事件,作为用户态进度与管理员诊断的共同事实源。
|
||||
依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话。
|
||||
依赖:ShippingOrderExtractionRun/Unit/ProgressEvent ORM、统一数据库会话、progress_audit_contract。
|
||||
逻辑:调用方只能写入受控 event_code;服务负责幂等、顺序号、终态保护和最小化 Run 投影。
|
||||
阶段 0 冻结 cancellation_* 事件码与 mapping v3;写入取消事实在阶段 1 与 Worker 检查点实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,7 +25,7 @@ from app.models import (
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
MAPPING_VERSION = 'shipping-order-progress-v2'
|
||||
MAPPING_VERSION = 'shipping-order-progress-v3'
|
||||
EVENT_RETENTION_DAYS = 90
|
||||
EVENT_CODE_ORDER = {
|
||||
'plan_created': 5,
|
||||
@@ -42,9 +43,47 @@ EVENT_CODE_ORDER = {
|
||||
'candidate_ready': 70,
|
||||
'review_required': 70,
|
||||
'technical_failed': 70,
|
||||
'cancellation_requested': 75,
|
||||
'unit_cancelled': 76,
|
||||
'cancellation_completed': 77,
|
||||
'budget_stopped': 80,
|
||||
'run_completed': 90,
|
||||
}
|
||||
|
||||
|
||||
def _progress_event_status(*, event_code: str, entity_status: str | None = None) -> str:
|
||||
"""
|
||||
将进度事件映射为可检索的过程状态,禁止一律写 completed。
|
||||
|
||||
核心逻辑:取消/失败/排队优先;否则回落到实体当前状态或运行中。
|
||||
"""
|
||||
code = str(event_code or '').strip()
|
||||
if code in {'cancellation_requested'}:
|
||||
return 'cancellation_requested'
|
||||
if code in {'unit_cancelled', 'cancellation_completed'}:
|
||||
return 'cancelled'
|
||||
if code in {'technical_failed'}:
|
||||
return 'failed'
|
||||
if code in {'technical_retrying'}:
|
||||
return 'retrying'
|
||||
if code in {'document_queued', 'plan_created'}:
|
||||
return 'queued'
|
||||
if code in {'layout_parsing_started', 'layout_parsing_completed', 'waiting_layout'}:
|
||||
return 'running'
|
||||
if code in {'candidate_ready', 'run_completed'}:
|
||||
return 'completed'
|
||||
if code in {'review_required'}:
|
||||
return 'review_required'
|
||||
status = str(entity_status or '').strip()
|
||||
if status == 'pending':
|
||||
return 'queued'
|
||||
if status in {'routing', 'matching_profile', 'extracting', 'merging_supplement', 'queued', 'processing'}:
|
||||
return 'running'
|
||||
if status in {'failed', 'cancelled', 'review_required', 'candidate_ready', 'completed', 'partially_completed'}:
|
||||
return status if status != 'candidate_ready' else 'completed'
|
||||
return 'running'
|
||||
|
||||
|
||||
WORKSPACE_EVENT_CODES = {
|
||||
'plan_created',
|
||||
'layout_parsing_started',
|
||||
@@ -61,6 +100,9 @@ WORKSPACE_EVENT_CODES = {
|
||||
'review_required',
|
||||
'technical_retrying',
|
||||
'technical_failed',
|
||||
'cancellation_requested',
|
||||
'unit_cancelled',
|
||||
'cancellation_completed',
|
||||
'budget_stopped',
|
||||
'run_completed',
|
||||
}
|
||||
@@ -165,7 +207,10 @@ def record_order_extraction_progress_event(
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=normalized_no).with_for_update().first()
|
||||
if run is None:
|
||||
return False
|
||||
if run.status in TERMINAL_RUN_STATUSES and event_code not in {'run_completed', 'technical_failed'}:
|
||||
if run.status in TERMINAL_RUN_STATUSES and event_code not in {
|
||||
'run_completed', 'technical_failed', 'cancellation_requested',
|
||||
'cancellation_completed', 'unit_cancelled',
|
||||
}:
|
||||
return False
|
||||
unit_id = int(event['unit_id']) if event.get('unit_id') is not None else None
|
||||
document_id = int(event['document_id']) if event.get('document_id') is not None else None
|
||||
@@ -234,7 +279,7 @@ def record_unit_progress(
|
||||
'unit_id': int(unit.id),
|
||||
'document_id': int(unit.document_id),
|
||||
'event_code': event_code,
|
||||
'status': 'completed',
|
||||
'status': _progress_event_status(event_code=event_code, entity_status=unit.status),
|
||||
'summary': summary,
|
||||
'reason_code': reason_code,
|
||||
'visibility': visibility,
|
||||
@@ -261,7 +306,7 @@ def record_run_progress(
|
||||
commit=commit,
|
||||
event={
|
||||
'event_code': event_code,
|
||||
'status': 'completed',
|
||||
'status': _progress_event_status(event_code=event_code, entity_status=run.status),
|
||||
'summary': summary,
|
||||
'reason_code': reason_code,
|
||||
'visibility': visibility,
|
||||
@@ -296,7 +341,7 @@ def record_layout_document_progress(*, document_id: int, event_code: str, commit
|
||||
event={
|
||||
'document_id': normalized_document_id,
|
||||
'event_code': event_code,
|
||||
'status': 'completed',
|
||||
'status': _progress_event_status(event_code=event_code, entity_status=run.status),
|
||||
'visibility': 'workspace',
|
||||
'occurred_at': datetime.utcnow(),
|
||||
},
|
||||
|
||||
@@ -21,7 +21,7 @@ from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy import and_, or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
@@ -349,7 +349,10 @@ def _build_snapshot(
|
||||
documents_by_intake: dict[int, list[dict[str, Any]]] = {intake.id: [] for intake in intakes}
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.schema_mapping import map_layout_document_to_schema
|
||||
from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_text
|
||||
from app.services.shipping_notice.email_allocation_table_parser import (
|
||||
parse_email_allocation_tables,
|
||||
parse_email_allocation_text,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
table_contract = compile_table_header_contract(dict(schema_version.definition_json or {}))
|
||||
@@ -387,13 +390,27 @@ def _build_snapshot(
|
||||
and isinstance(document.order_extraction_result_json, dict)
|
||||
else None
|
||||
)
|
||||
# 旧 Intake 已经持久化时,也在重新识别的冻结边界补齐纯文本正文补充事实。
|
||||
# 结果只进入本 Run 快照,原始解析记录保持不变,确保可审计。
|
||||
if document.document_type == 'email_body' and not isinstance(email_supplement, dict):
|
||||
email_supplement = parse_email_allocation_text(
|
||||
body_text=str(document.extracted_text or ''),
|
||||
content_hash=str(document.content_hash or ''),
|
||||
)
|
||||
# [STEP 1] 按本 Run 冻结 Schema 重建正文补充事实。上传阶段的预解析
|
||||
# 可能使用较早 Schema;优先复用 Intake 保存的 HTML 表,避免表格展平后丢失列关系。
|
||||
if document.document_type == 'email_body' and (
|
||||
not isinstance(email_supplement, dict) or not list(email_supplement.get('rows') or [])
|
||||
):
|
||||
intake = next((item for item in intakes if int(item.id) == int(document.intake_id)), None)
|
||||
structured = intake.structured_result_json if intake and isinstance(intake.structured_result_json, dict) else {}
|
||||
email = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
html_tables = [str(item) for item in (email.get('body_html_tables') or []) if str(item).strip()]
|
||||
if html_tables:
|
||||
email_supplement = parse_email_allocation_tables(
|
||||
html_tables=html_tables,
|
||||
content_hash=str(document.content_hash or ''),
|
||||
schema_definition=dict(schema_version.definition_json or {}),
|
||||
)
|
||||
else:
|
||||
email_supplement = parse_email_allocation_text(
|
||||
body_text=str(document.extracted_text or ''),
|
||||
content_hash=str(document.content_hash or ''),
|
||||
schema_definition=dict(schema_version.definition_json or {}),
|
||||
)
|
||||
email_supplement['document_id'] = int(document.id)
|
||||
documents_by_intake[document.intake_id].append({
|
||||
'document_id': document.id,
|
||||
@@ -539,19 +556,51 @@ def order_extraction_layouts_failed(run: ShippingOrderExtractionRun) -> bool:
|
||||
def schedule_order_extraction_layouts(
|
||||
run: ShippingOrderExtractionRun, *, created_by_id: int | None,
|
||||
) -> bool:
|
||||
"""发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。"""
|
||||
"""
|
||||
发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。
|
||||
|
||||
核心逻辑:调用 schedule_document_layouts;用返回值与库查询确认每份 PDF 已有布局版本,
|
||||
避免 ORM 关系未刷新导致误报「未创建版面 Job」。
|
||||
"""
|
||||
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 = [
|
||||
scheduled = schedule_document_layouts(documents, created_by_id=created_by_id)
|
||||
# [STEP] 以本轮排程结果与库内版本为准,禁止依赖可能未 refresh 的 layout_versions 关系。
|
||||
scheduled_document_ids = {
|
||||
int(version.document_id)
|
||||
for version in scheduled
|
||||
if getattr(version, 'document_id', None) is not None
|
||||
}
|
||||
from app.models import ShippingDocumentLayoutVersion
|
||||
|
||||
pdf_document_ids = [
|
||||
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
|
||||
]
|
||||
existing_version_ids = {
|
||||
int(document_id)
|
||||
for (document_id,) in db.session.query(ShippingDocumentLayoutVersion.document_id).filter(
|
||||
ShippingDocumentLayoutVersion.document_id.in_(pdf_document_ids or [-1]),
|
||||
).distinct().all()
|
||||
}
|
||||
# 内容级复用的 ready 版本属于历史 Document;lifecycle 已把其 ID 绑定到当前
|
||||
# Document.current_layout_version_id,不能因 version.document_id 不同误判为未排程。
|
||||
reusable_document_ids = {
|
||||
int(document.id)
|
||||
for document in documents
|
||||
if document.current_layout_version_id is not None
|
||||
}
|
||||
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
|
||||
missing = [
|
||||
document_id for document_id in pdf_document_ids
|
||||
if (
|
||||
document_id not in scheduled_document_ids
|
||||
and document_id not in existing_version_ids
|
||||
and document_id not in reusable_document_ids
|
||||
)
|
||||
]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
@@ -612,8 +661,14 @@ def materialize_order_extraction_run_inputs(
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
# 已完成物化并建计划的 Run 重试时直接复用,避免再次抽取或改变执行证据快照。
|
||||
if ShippingOrderExtractionPlan.query.filter_by(run_id=int(run.id)).first() is not None:
|
||||
return ensure_order_extraction_plan(run)
|
||||
# 早期链路可能留下 0 Unit 的空计划;它不含可执行输入,必须丢弃后重新物化,
|
||||
# 否则重试会永远跳过 EML 附件物化并误报版面任务未创建。
|
||||
existing_plan = ShippingOrderExtractionPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if existing_plan is not None:
|
||||
if int(existing_plan.unit_count or 0) > 0:
|
||||
return ensure_order_extraction_plan(run)
|
||||
db.session.delete(existing_plan)
|
||||
db.session.flush()
|
||||
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
@@ -1127,13 +1182,53 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr
|
||||
|
||||
|
||||
def list_order_extraction_runs(
|
||||
*, user_id: int, conversation_id: str | None = None, limit: int = 50,
|
||||
) -> list[ShippingOrderExtractionRun]:
|
||||
"""列出当前用户 Run;可按会话过滤,最多返回 100 条。"""
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str | None = None,
|
||||
limit: int = 50,
|
||||
status: str | None = None,
|
||||
page: int | None = None,
|
||||
page_size: int | None = None,
|
||||
) -> list[ShippingOrderExtractionRun] | dict[str, Any]:
|
||||
"""
|
||||
列出当前用户 Run;可按会话/状态过滤。
|
||||
|
||||
核心逻辑:未传 page 时保持旧契约(最多 100 条列表);传 page 时返回分页字典供任务中心续办。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户主键。
|
||||
conversation_id: 可选会话过滤。
|
||||
limit: 非分页模式下的条数上限。
|
||||
status: 可选业务状态过滤。
|
||||
page: 分页页码(>=1);与 page_size 同时生效。
|
||||
page_size: 分页大小(1-100)。
|
||||
|
||||
Returns:
|
||||
非分页:Run 列表;分页:{items, total, page, page_size}。
|
||||
"""
|
||||
normalized_status = str(status or '').strip() or None
|
||||
if normalized_status and normalized_status not in {
|
||||
'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled',
|
||||
}:
|
||||
raise ValidationError('status is invalid')
|
||||
query = ShippingOrderExtractionRun.query.filter_by(user_id=user_id)
|
||||
if conversation_id:
|
||||
query = query.filter_by(conversation_id=conversation_id)
|
||||
return query.order_by(ShippingOrderExtractionRun.created_at.desc()).limit(min(max(limit, 1), 100)).all()
|
||||
if normalized_status:
|
||||
query = query.filter_by(status=normalized_status)
|
||||
query = query.order_by(ShippingOrderExtractionRun.created_at.desc())
|
||||
if page is None and page_size is None:
|
||||
return query.limit(min(max(int(limit or 50), 1), 100)).all()
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 20)))
|
||||
total = query.count()
|
||||
rows = query.offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all()
|
||||
return {
|
||||
'items': rows,
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
}
|
||||
|
||||
|
||||
def _reparse_difference_summary(run: ShippingOrderExtractionRun) -> dict[str, Any] | None:
|
||||
@@ -1338,6 +1433,15 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
|
||||
'unit_summary': _unit_fact_summary(run),
|
||||
'current_activity': workspace_projection['current_activity'],
|
||||
'available_actions': workspace_projection['available_actions'],
|
||||
'handling_items': workspace_projection.get('handling_items') or [],
|
||||
'primary_notice': workspace_projection.get('primary_notice'),
|
||||
'user_visible_stage': workspace_projection.get('user_visible_stage'),
|
||||
'health_tips': workspace_projection.get('health_tips') or [],
|
||||
'cancellation': workspace_projection.get('cancellation'),
|
||||
'progress_version': workspace_projection.get('progress_version'),
|
||||
'elapsed_seconds': workspace_projection.get('elapsed_seconds'),
|
||||
'last_activity_at': workspace_projection.get('last_activity_at'),
|
||||
'feature_flags': workspace_projection.get('feature_flags') or {},
|
||||
'result': run.result_json,
|
||||
# Worker/provider error text can contain upstream details. Workspace cards only need a
|
||||
# stable code to select a safe, actionable user hint; full diagnostics stay admin-only.
|
||||
@@ -1515,14 +1619,18 @@ def _diagnostic_auto_freeze_policy(run: ShippingOrderExtractionRun) -> dict[str,
|
||||
def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""构建管理员 Run 摘要,只包含状态、标识、计数、时间和脱敏事件,不含输入输出或错误正文。"""
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
cancellation_requested = run.cancellation_requested_at is not None
|
||||
cancellation_completed = run.cancellation_completed_at is not None
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'status': run.status,
|
||||
'phase': run.phase,
|
||||
'conversation_id': run.conversation_id,
|
||||
'user_id': int(run.user_id or 0) or None,
|
||||
'parser_engine_version': run.parser_engine_version,
|
||||
'parser_policy_version': run.parser_policy_version,
|
||||
'attempt_count': int(run.attempt_count or 0),
|
||||
'progress_version': int(run.progress_version or 0),
|
||||
'current_event_code': run.current_stage_code,
|
||||
'active_stage_codes': list(run.active_stage_codes_json or []),
|
||||
'completed_stage_codes': list(run.completed_stage_codes_json or []),
|
||||
@@ -1537,6 +1645,11 @@ def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun)
|
||||
'deterministic_parsing': _diagnostic_elapsed_ms(run.started_at, run.extraction_completed_at),
|
||||
'candidate_materialization': _diagnostic_elapsed_ms(run.extraction_completed_at, run.result_persisted_at),
|
||||
'total': _diagnostic_elapsed_ms(run.created_at, run.finished_at),
|
||||
'elapsed_active': (
|
||||
_diagnostic_elapsed_ms(run.started_at or run.created_at, datetime.utcnow())
|
||||
if run.status in {'queued', 'processing'}
|
||||
else None
|
||||
),
|
||||
},
|
||||
'result_counts': {
|
||||
'created': int(result.get('created_count') or 0),
|
||||
@@ -1544,6 +1657,15 @@ def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun)
|
||||
'pending': int(result.get('pending_count') or 0),
|
||||
'non_shipping': int(result.get('non_shipping_count') or 0),
|
||||
},
|
||||
'cancellation': {
|
||||
'requested': cancellation_requested,
|
||||
'completed': cancellation_completed,
|
||||
'in_flight': cancellation_requested and not cancellation_completed,
|
||||
'requested_at': _diagnostic_iso(run.cancellation_requested_at),
|
||||
'completed_at': _diagnostic_iso(run.cancellation_completed_at),
|
||||
'actor_type': run.cancellation_actor_type,
|
||||
'reason_code': run.cancellation_reason_code,
|
||||
},
|
||||
'auto_freeze_policy': _diagnostic_auto_freeze_policy(run),
|
||||
# 仅错误码可用于运维归类,错误正文可能含上游响应内容,严禁返回。
|
||||
'error_code': run.error_code,
|
||||
@@ -1575,27 +1697,82 @@ def _commit_order_extraction_diagnostic_audit_safely() -> None:
|
||||
|
||||
|
||||
def list_order_extraction_diagnostic_runs(
|
||||
*, admin_user_id: int, request_id: str | None, page: int = 1, page_size: int = 25, status: str | None = None,
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
page: int = 1,
|
||||
page_size: int = 25,
|
||||
status: str | None = None,
|
||||
stale_only: bool = False,
|
||||
cancellation_in_flight: bool = False,
|
||||
queued_stale_seconds: int = 300,
|
||||
running_stale_seconds: int = 1800,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""分页读取管理员诊断 Run 摘要,并写入只读访问审计。"""
|
||||
"""
|
||||
分页读取管理员诊断 Run 摘要,并写入只读访问审计。
|
||||
|
||||
核心逻辑:支持状态、积压卡住、取消中筛选;不返回正文/Provider。
|
||||
"""
|
||||
normalized_status = str(status or '').strip() or None
|
||||
if normalized_status and normalized_status not in {'queued', 'processing', 'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}:
|
||||
raise ValidationError('status is invalid')
|
||||
safe_page = max(1, int(page))
|
||||
safe_page_size = min(100, max(1, int(page_size)))
|
||||
current = now or datetime.utcnow()
|
||||
queued_threshold = min(max(int(queued_stale_seconds or 300), 30), 86400)
|
||||
running_threshold = min(max(int(running_stale_seconds or 1800), 60), 86400)
|
||||
query = ShippingOrderExtractionRun.query
|
||||
if normalized_status:
|
||||
query = query.filter_by(status=normalized_status)
|
||||
if cancellation_in_flight:
|
||||
query = query.filter(
|
||||
ShippingOrderExtractionRun.cancellation_requested_at.isnot(None),
|
||||
ShippingOrderExtractionRun.cancellation_completed_at.is_(None),
|
||||
)
|
||||
if stale_only:
|
||||
# [STEP 1] 积压筛选在服务端按阈值计算,避免前端全量拉取后再猜。
|
||||
queued_cutoff = current - timedelta(seconds=queued_threshold)
|
||||
running_cutoff = current - timedelta(seconds=running_threshold)
|
||||
query = query.filter(
|
||||
or_(
|
||||
and_(
|
||||
ShippingOrderExtractionRun.status == 'queued',
|
||||
ShippingOrderExtractionRun.created_at <= queued_cutoff,
|
||||
),
|
||||
and_(
|
||||
ShippingOrderExtractionRun.status == 'processing',
|
||||
or_(
|
||||
ShippingOrderExtractionRun.started_at <= running_cutoff,
|
||||
and_(
|
||||
ShippingOrderExtractionRun.started_at.is_(None),
|
||||
ShippingOrderExtractionRun.created_at <= running_cutoff,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
)
|
||||
total = query.count()
|
||||
rows = query.order_by(ShippingOrderExtractionRun.created_at.desc(), ShippingOrderExtractionRun.id.desc()).offset(
|
||||
(safe_page - 1) * safe_page_size,
|
||||
).limit(safe_page_size).all()
|
||||
payload = {'items': [_serialize_order_extraction_diagnostic_run(row) for row in rows], 'total': total, 'page': safe_page, 'page_size': safe_page_size}
|
||||
payload = {
|
||||
'items': [_serialize_order_extraction_diagnostic_run(row) for row in rows],
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
}
|
||||
_write_order_extraction_diagnostic_audit(
|
||||
admin_user_id=admin_user_id,
|
||||
action='list_runs',
|
||||
request_id=request_id,
|
||||
summary={'page': safe_page, 'page_size': safe_page_size, 'status': normalized_status},
|
||||
summary={
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'status': normalized_status,
|
||||
'stale_only': bool(stale_only),
|
||||
'cancellation_in_flight': bool(cancellation_in_flight),
|
||||
},
|
||||
)
|
||||
_commit_order_extraction_diagnostic_audit_safely()
|
||||
return payload
|
||||
@@ -1775,12 +1952,24 @@ def transition_order_extraction_run(
|
||||
run.status = target_status
|
||||
run.phase = phase or target_status
|
||||
run.lock_version = int(run.lock_version or 0) + 1
|
||||
request_id = None
|
||||
try:
|
||||
from flask import g
|
||||
request_id = str(getattr(g, 'request_id', '') or '') or None
|
||||
except RuntimeError:
|
||||
request_id = None
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=run.run_no,
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
conversation_id=run.conversation_id,
|
||||
source='worker' if request_id is None else 'api',
|
||||
result='success',
|
||||
action='status_transition',
|
||||
reason_code=error_code if target_status == 'failed' else None,
|
||||
before=before_projection,
|
||||
after={'status': target_status, 'phase': phase or target_status, 'lock_version': int(run.lock_version or 0)},
|
||||
@@ -1960,15 +2149,65 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
|
||||
error_message=str(job.error_message or '订单抽取后台任务执行超时'),
|
||||
)
|
||||
|
||||
|
||||
def sync_order_extraction_run_after_job_failure(job: Any) -> None:
|
||||
"""
|
||||
同步最终失败的订单抽取 Job 到用户态 Run。
|
||||
|
||||
AI 触发时机:无需直接调用;通用队列在 Job 重试耗尽后调用。
|
||||
核心逻辑:Handler 启动前的异常也会使 Job 失败,因此必须将 Run 收口为 failed;
|
||||
若 Job 错误信息指向版面排程失败,则写入更具体的 LAYOUT_SCHEDULING_FAILED 便于前端文案。
|
||||
|
||||
Args:
|
||||
job: 已更新为 failed 的 `shipping_order_extraction` Job。
|
||||
"""
|
||||
if str(getattr(job, 'job_type', '') or '') != 'shipping_order_extraction':
|
||||
return
|
||||
if str(getattr(job, 'status', '') or '') != 'failed':
|
||||
return
|
||||
run = ShippingOrderExtractionRun.query.filter_by(
|
||||
run_no=str(getattr(job, 'business_ref', '') or ''),
|
||||
).with_for_update().first()
|
||||
if run is None or run.status in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}:
|
||||
return
|
||||
|
||||
error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'
|
||||
job_error = str(getattr(job, 'error_message', '') or '')
|
||||
if 'layout job was not created' in job_error.lower():
|
||||
error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED'
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='job_failure')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
phase='job_failed',
|
||||
error_code=error_code,
|
||||
error_message=job_error or '订单抽取后台任务失败',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='technical_failed',
|
||||
reason_code=error_code,
|
||||
summary={
|
||||
'job_id': int(getattr(job, 'id', 0) or 0),
|
||||
'job_attempts': int(getattr(job, 'attempts', 0) or 0),
|
||||
'job_max_attempts': int(getattr(job, 'max_attempts', 0) or 0),
|
||||
},
|
||||
job_id=int(getattr(job, 'id', 0) or 0) or None,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
def _latency_summary(values: list[int]) -> dict[str, int | None]:
|
||||
"""汇总毫秒耗时样本;空集合返回空指标,避免监控端猜测零耗时。"""
|
||||
if not values:
|
||||
return {'count': 0, 'avg_ms': None, 'p95_ms': None, 'max_ms': None}
|
||||
return {'count': 0, 'avg_ms': None, 'p50_ms': None, 'p95_ms': None, 'max_ms': None}
|
||||
ordered = sorted(max(0, int(value)) for value in values)
|
||||
p50_index = max(0, min(len(ordered) - 1, ((len(ordered) * 50 + 99) // 100) - 1))
|
||||
p95_index = max(0, min(len(ordered) - 1, ((len(ordered) * 95 + 99) // 100) - 1))
|
||||
return {
|
||||
'count': len(ordered),
|
||||
'avg_ms': int(sum(ordered) / len(ordered)),
|
||||
'p50_ms': ordered[p50_index],
|
||||
'p95_ms': ordered[p95_index],
|
||||
'max_ms': ordered[-1],
|
||||
}
|
||||
|
||||
@@ -3,14 +3,18 @@ backend/app/services/shipping_notice/order_extraction_workspace_projection.py
|
||||
|
||||
用途:把订单抽取 Run/Unit 的数据库事实投影为工作台摘要和按 PDF 的详情列表。
|
||||
依赖:ShippingNoticeCandidate、ShippingOrderExtractionRun/Unit/RouteDecision/ProgressEvent ORM、
|
||||
冻结 snapshot 和 Unit 结果 JSON。
|
||||
progress_audit_contract、progress_feature_flags、冻结 snapshot 和 Unit 结果 JSON。
|
||||
逻辑:只输出用户可理解的业务信息;文件名、原因码、模板摘要、重复订单 open_existing 入口
|
||||
与可操作按钮都在这里统一裁剪与组装。
|
||||
与可操作按钮都在这里统一裁剪与组装。阶段 1 起由后端唯一投影 user_visible_stage、
|
||||
queue_position、elapsed_seconds、health_tips 与 cancellation;阶段 5 按功能开关裁剪取消动作与健康提示。
|
||||
Run 级 handling_items 拆分「待补信息 / 冲突 / 自动冻结受阻 / PDF 复核 / 技术失败 / 预算停扩」,
|
||||
供聊天卡与右侧「本次处理」按原因展示与跳转,避免仅依赖部分完成/需复核状态码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
@@ -20,8 +24,39 @@ from app.models import (
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import HEALTH_TIP_THRESHOLDS_SECONDS
|
||||
from app.services.shipping_notice.progress_feature_flags import (
|
||||
order_extraction_cancel_enabled,
|
||||
progress_feature_flags_payload,
|
||||
progress_ui_v3_enabled,
|
||||
)
|
||||
|
||||
ACTIVE_UNIT_STATUSES = {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'}
|
||||
IN_FLIGHT_UNIT_STATUSES = {'routing', 'matching_profile', 'extracting', 'merging_supplement'}
|
||||
|
||||
# 候选待处理原因中偏「冲突/歧义」的码;其余有 missing_fields 或待补语义的归入待补信息。
|
||||
_CANDIDATE_CONFLICT_REASON_CODES = frozenset({
|
||||
'email_supplement_conflict',
|
||||
'duplicate_decision_required',
|
||||
'blocking_conflict',
|
||||
'profile_ambiguous',
|
||||
'multiple_business_tables',
|
||||
'multiple_po_detected',
|
||||
'supplement_relation_ambiguous',
|
||||
'email_supplement_ambiguous',
|
||||
'order_must_be_object',
|
||||
})
|
||||
|
||||
# Run 级处理事项展示顺序:越靠前越优先作为 primary_notice。
|
||||
_HANDLING_ITEM_PRIORITY = (
|
||||
'technical_failure',
|
||||
'document_review',
|
||||
'candidate_conflict',
|
||||
'candidate_missing_info',
|
||||
'auto_freeze_blocked',
|
||||
'budget_stopped',
|
||||
'candidate_confirmation',
|
||||
)
|
||||
|
||||
|
||||
def _safe_file_name(value: Any) -> str | None:
|
||||
@@ -29,8 +64,231 @@ def _safe_file_name(value: Any) -> str | None:
|
||||
text = str(value or '').strip().replace('\\', '/')
|
||||
if not text:
|
||||
return None
|
||||
name = text.split('/')[-1].strip()
|
||||
return name[:255] or None
|
||||
return text.rsplit('/', 1)[-1][:255]
|
||||
|
||||
|
||||
def _elapsed_seconds(*, started_at: datetime | None, finished_at: datetime | None, now: datetime | None = None) -> int | None:
|
||||
"""按后端时钟计算已用秒数;未开始返回 None。"""
|
||||
if started_at is None:
|
||||
return None
|
||||
end = finished_at or now or datetime.utcnow()
|
||||
return max(0, int((end - started_at).total_seconds()))
|
||||
|
||||
|
||||
def _cancellation_projection(target: Any) -> dict[str, Any] | None:
|
||||
"""投影取消请求元数据;不向普通用户回传管理员代取消的长文本时可仍保留 reason 供本人查看。"""
|
||||
requested_at = getattr(target, 'cancellation_requested_at', None)
|
||||
if requested_at is None and getattr(target, 'cancellation_completed_at', None) is None:
|
||||
return None
|
||||
return {
|
||||
'requested': requested_at is not None,
|
||||
'requested_at': requested_at.isoformat() + 'Z' if requested_at else None,
|
||||
'completed_at': (
|
||||
target.cancellation_completed_at.isoformat() + 'Z'
|
||||
if getattr(target, 'cancellation_completed_at', None) else None
|
||||
),
|
||||
'actor_type': getattr(target, 'cancellation_actor_type', None),
|
||||
'actor_id': getattr(target, 'cancellation_actor_id', None),
|
||||
'reason': getattr(target, 'cancellation_reason', None),
|
||||
'reason_code': getattr(target, 'cancellation_reason_code', None),
|
||||
}
|
||||
|
||||
|
||||
def _unit_user_visible_stage(unit: ShippingOrderExtractionUnit, *, run: ShippingOrderExtractionRun | None = None) -> str:
|
||||
"""
|
||||
将 Unit 事实投影为用户可见阶段。
|
||||
|
||||
核心逻辑:取消请求优先于业务态;review_required 不得映射为 failed。
|
||||
"""
|
||||
if unit.cancellation_requested_at is not None and unit.cancellation_completed_at is None and unit.status != 'cancelled':
|
||||
return 'cancellation_requested'
|
||||
status = str(unit.status or '')
|
||||
if status == 'pending':
|
||||
return 'document_queued'
|
||||
if status in {'routing', 'matching_profile', 'extracting', 'merging_supplement', 'candidate_ready', 'review_required', 'failed', 'cancelled'}:
|
||||
return status
|
||||
if run is not None and str(run.phase or '') == 'waiting_layout':
|
||||
return 'layout_parsing_started'
|
||||
return status or 'pending'
|
||||
|
||||
|
||||
def _run_user_visible_stage(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit]) -> str:
|
||||
"""Run 级用户可见阶段;取消请求优先。"""
|
||||
if run.cancellation_requested_at is not None and run.cancellation_completed_at is None and run.status != 'cancelled':
|
||||
return 'cancellation_requested'
|
||||
if run.status == 'cancelled':
|
||||
return 'cancelled'
|
||||
if run.status in {'completed', 'partially_completed'}:
|
||||
return 'completed'
|
||||
if run.status == 'review_required':
|
||||
return 'review_required'
|
||||
if run.status == 'failed':
|
||||
return 'failed'
|
||||
if str(run.phase or '') == 'waiting_layout':
|
||||
return 'layout_parsing_started'
|
||||
active = next((unit for unit in units if unit.status in ACTIVE_UNIT_STATUSES), None)
|
||||
if active is not None:
|
||||
return _unit_user_visible_stage(active, run=run)
|
||||
return 'document_queued' if run.status == 'queued' else 'extracting'
|
||||
|
||||
|
||||
def _queue_positions(units: list[ShippingOrderExtractionUnit]) -> dict[int, int]:
|
||||
"""按 position 为 pending Unit 计算 1-based 队列位置。"""
|
||||
pending = sorted(
|
||||
(unit for unit in units if unit.status == 'pending' and unit.cancellation_completed_at is None),
|
||||
key=lambda row: (int(row.position or 0), int(row.id or 0)),
|
||||
)
|
||||
return {int(unit.id): index for index, unit in enumerate(pending, start=1)}
|
||||
|
||||
|
||||
def _health_tips_for_unit(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
now: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按 Unit 事实计算健康提示。
|
||||
|
||||
核心逻辑:仅对未终态 Unit 计算;排队看等待时长,执行中看空闲与累计耗时。
|
||||
"""
|
||||
if unit.status in {'candidate_ready', 'review_required', 'failed', 'cancelled'}:
|
||||
return []
|
||||
if run.status not in {'queued', 'processing'}:
|
||||
return []
|
||||
clock = now or datetime.utcnow()
|
||||
tips: list[dict[str, Any]] = []
|
||||
if unit.status == 'pending':
|
||||
stamp = unit.created_at or run.created_at
|
||||
if stamp is not None:
|
||||
waited = int((clock - stamp).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog']
|
||||
if waited >= threshold:
|
||||
tips.append({
|
||||
'code': 'queue_backlog',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': waited,
|
||||
})
|
||||
return tips
|
||||
|
||||
last_activity = unit.last_activity_at or unit.started_at or unit.created_at
|
||||
if last_activity is not None:
|
||||
idle = int((clock - last_activity).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow']
|
||||
if idle >= threshold:
|
||||
tips.append({
|
||||
'code': 'processing_slow',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': idle,
|
||||
})
|
||||
started = unit.started_at or unit.created_at
|
||||
if started is not None:
|
||||
elapsed = int((clock - started).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention']
|
||||
if elapsed >= threshold:
|
||||
tips.append({
|
||||
'code': 'processing_attention',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': elapsed,
|
||||
})
|
||||
return tips
|
||||
|
||||
|
||||
def _health_tips_for_planned_document(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
stage: str,
|
||||
started_at: datetime | None,
|
||||
now: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Unit 未物化时按 Run/版面等待事实计算健康提示。
|
||||
|
||||
核心逻辑:终态不提醒;排队看创建等待,版面解析看空闲与累计耗时。
|
||||
"""
|
||||
if stage in {'failed', 'cancelled', 'completed', 'candidate_ready'}:
|
||||
return []
|
||||
if run.status not in {'queued', 'processing'}:
|
||||
return []
|
||||
clock = now or datetime.utcnow()
|
||||
tips: list[dict[str, Any]] = []
|
||||
if stage in {'document_queued', 'waiting_layout', 'pending'}:
|
||||
stamp = run.created_at
|
||||
if stamp is not None:
|
||||
waited = int((clock - stamp).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog']
|
||||
if waited >= threshold:
|
||||
tips.append({
|
||||
'code': 'queue_backlog',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': waited,
|
||||
})
|
||||
last_activity = run.last_activity_at or started_at or run.created_at
|
||||
if last_activity is not None and stage in {'layout_parsing_started', 'waiting_layout', 'document_queued'}:
|
||||
idle = int((clock - last_activity).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow']
|
||||
if idle >= threshold:
|
||||
tips.append({
|
||||
'code': 'processing_slow',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': idle,
|
||||
})
|
||||
anchor = started_at or run.created_at
|
||||
if anchor is not None:
|
||||
elapsed = int((clock - anchor).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention']
|
||||
if elapsed >= threshold:
|
||||
tips.append({
|
||||
'code': 'processing_attention',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': elapsed,
|
||||
})
|
||||
return tips
|
||||
|
||||
|
||||
def _health_tips_for_run(run: ShippingOrderExtractionRun, units: list[ShippingOrderExtractionUnit], *, now: datetime | None = None) -> list[dict[str, Any]]:
|
||||
"""根据冻结阈值计算健康提示;仅活跃 Run 返回。"""
|
||||
if run.status not in {'queued', 'processing'}:
|
||||
return []
|
||||
clock = now or datetime.utcnow()
|
||||
tips: list[dict[str, Any]] = []
|
||||
last_activity = run.last_activity_at or run.updated_at or run.created_at
|
||||
if last_activity is not None:
|
||||
idle = int((clock - last_activity).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow']
|
||||
if idle >= threshold:
|
||||
tips.append({
|
||||
'code': 'processing_slow',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': idle,
|
||||
})
|
||||
oldest_pending = None
|
||||
for unit in units:
|
||||
if unit.status != 'pending' or unit.cancellation_completed_at is not None:
|
||||
continue
|
||||
stamp = unit.created_at or run.created_at
|
||||
if stamp is not None and (oldest_pending is None or stamp < oldest_pending):
|
||||
oldest_pending = stamp
|
||||
if oldest_pending is not None:
|
||||
waited = int((clock - oldest_pending).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog']
|
||||
if waited >= threshold:
|
||||
tips.append({
|
||||
'code': 'queue_backlog',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': waited,
|
||||
})
|
||||
started = run.started_at or run.created_at
|
||||
if started is not None:
|
||||
elapsed = int((clock - started).total_seconds())
|
||||
threshold = HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention']
|
||||
if elapsed >= threshold:
|
||||
tips.append({
|
||||
'code': 'processing_attention',
|
||||
'threshold_seconds': threshold,
|
||||
'idle_or_elapsed_seconds': elapsed,
|
||||
})
|
||||
return tips
|
||||
|
||||
|
||||
def _snapshot_documents(run: ShippingOrderExtractionRun) -> dict[int, dict[str, Any]]:
|
||||
@@ -228,15 +486,394 @@ def _open_existing_document_ids(run: ShippingOrderExtractionRun) -> set[int]:
|
||||
}
|
||||
|
||||
|
||||
def _trim_reason_codes(values: Any, *, limit: int = 12) -> list[str]:
|
||||
"""去重并截断原因码列表,避免工作台响应膨胀。"""
|
||||
codes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for raw in values or []:
|
||||
code = str(raw or '').strip()
|
||||
if not code or code in seen:
|
||||
continue
|
||||
seen.add(code)
|
||||
codes.append(code[:96])
|
||||
if len(codes) >= limit:
|
||||
break
|
||||
return codes
|
||||
|
||||
|
||||
def _trim_pending_order_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""裁剪待处理候选事实,只保留用户可见标识与原因。"""
|
||||
missing = item.get('missing_fields') if isinstance(item.get('missing_fields'), list) else []
|
||||
return {
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'po_number': str(item.get('po_number') or '').strip() or None,
|
||||
'reasons': _trim_reason_codes(item.get('reasons')),
|
||||
'missing_fields': [str(field).strip() for field in missing if str(field or '').strip()][:20],
|
||||
'duplicate_status': str(item.get('duplicate_status') or '').strip() or None,
|
||||
}
|
||||
|
||||
|
||||
def _pending_order_facts(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
读取本轮仍待人工处理的候选事实。
|
||||
|
||||
核心逻辑:优先使用 result_json.pending_orders(Worker 收口快照);缺失时回查当前版本 provisional 候选。
|
||||
"""
|
||||
result = run.result_json if isinstance(getattr(run, 'result_json', None), dict) else {}
|
||||
stored = result.get('pending_orders')
|
||||
if isinstance(stored, list) and stored:
|
||||
return [
|
||||
_trim_pending_order_item(item)
|
||||
for item in stored
|
||||
if isinstance(item, dict)
|
||||
][:50]
|
||||
|
||||
if getattr(run, 'id', None) is None:
|
||||
return []
|
||||
rows = (
|
||||
ShippingNoticeCandidate.query.filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingNoticeCandidate.is_current_version.is_(True),
|
||||
ShippingNoticeCandidate.candidate_status == 'provisional',
|
||||
).all()
|
||||
)
|
||||
pending: list[dict[str, Any]] = []
|
||||
for candidate in rows:
|
||||
if str(candidate.duplicate_resolution or '').strip() == 'open_existing':
|
||||
continue
|
||||
reasons: list[str] = []
|
||||
if isinstance(candidate.conflicts_json, list):
|
||||
for conflict in candidate.conflicts_json:
|
||||
if isinstance(conflict, dict):
|
||||
code = str(conflict.get('code') or conflict.get('reason') or '').strip()
|
||||
else:
|
||||
code = str(conflict or '').strip()
|
||||
if code:
|
||||
reasons.append(code)
|
||||
missing = list(candidate.missing_fields_json or []) if isinstance(candidate.missing_fields_json, list) else []
|
||||
if missing and 'required_field_missing' not in reasons:
|
||||
reasons.append('required_field_missing')
|
||||
if str(candidate.duplicate_status or '').strip() in {'conflict', 'needs_decision'}:
|
||||
reasons.append('duplicate_decision_required')
|
||||
if str(candidate.validation_status or '') != 'ready' and not reasons and not missing:
|
||||
reasons.append('required_field_missing')
|
||||
pending.append(_trim_pending_order_item({
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'po_number': candidate.po_number,
|
||||
'reasons': reasons,
|
||||
'missing_fields': missing,
|
||||
'duplicate_status': candidate.duplicate_status,
|
||||
}))
|
||||
return pending[:50]
|
||||
|
||||
|
||||
def _auto_freeze_block_facts(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""汇总自动冻结门禁受阻事实:阻断任务与策略层 blocking_reason_codes。"""
|
||||
result = run.result_json if isinstance(getattr(run, 'result_json', None), dict) else {}
|
||||
auto_freeze = result.get('auto_freeze') if isinstance(result.get('auto_freeze'), dict) else {}
|
||||
blocked_raw = auto_freeze.get('blocked_tasks') if isinstance(auto_freeze.get('blocked_tasks'), list) else []
|
||||
blocked_tasks: list[dict[str, Any]] = []
|
||||
blocked_codes: list[str] = []
|
||||
for item in blocked_raw[:30]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get('code') or '').strip()
|
||||
blocked_tasks.append({
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'task_no': str(item.get('task_no') or '').strip() or None,
|
||||
'code': code or None,
|
||||
})
|
||||
if code:
|
||||
blocked_codes.append(code)
|
||||
policy_raw = getattr(run, 'auto_freeze_policy_json', None)
|
||||
policy = policy_raw if isinstance(policy_raw, dict) else {}
|
||||
policy_codes = _trim_reason_codes(policy.get('blocking_reason_codes'))
|
||||
created_count = max(0, int(result.get('created_count') or 0))
|
||||
# 已建单但策略未放行,或执行阶段有阻断任务,均视为自动冻结受阻。
|
||||
policy_blocked = (
|
||||
created_count > 0
|
||||
and not bool(policy.get('enabled'))
|
||||
and bool(policy_codes)
|
||||
and bool(policy.get('evaluated_from_run'))
|
||||
)
|
||||
return {
|
||||
'blocked_tasks': blocked_tasks,
|
||||
'reason_codes': _trim_reason_codes([*blocked_codes, *policy_codes]),
|
||||
'blocked': bool(blocked_tasks) or policy_blocked,
|
||||
'blocked_task_count': len(blocked_tasks),
|
||||
}
|
||||
|
||||
|
||||
def _budget_stopped_for_run(run: ShippingOrderExtractionRun) -> bool:
|
||||
"""判断本轮是否因预算停扩;优先读 result 快照,其次读选择计划受限计数。"""
|
||||
result = run.result_json if isinstance(getattr(run, 'result_json', None), dict) else {}
|
||||
if bool(result.get('budget_stopped')):
|
||||
return True
|
||||
snapshot = getattr(run, 'input_snapshot_json', None)
|
||||
if not isinstance(snapshot, dict):
|
||||
snapshot = {}
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
budget_limited = max(0, int(selection.get('budget_limited_attachment_count') or 0))
|
||||
pending_expansion = max(0, int(selection.get('pending_expansion_attachment_count') or 0))
|
||||
if str(getattr(run, 'status', '') or '') in {'partially_completed', 'review_required', 'failed'} and (
|
||||
budget_limited > 0 or pending_expansion > 0
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _handling_item(
|
||||
*,
|
||||
category: str,
|
||||
count: int,
|
||||
reason_codes: list[str] | None = None,
|
||||
affected_refs: list[dict[str, Any]] | None = None,
|
||||
primary_action: str,
|
||||
) -> dict[str, Any]:
|
||||
"""组装单条 Run 级处理事项。"""
|
||||
return {
|
||||
'category': category,
|
||||
'count': max(0, int(count)),
|
||||
'reason_codes': _trim_reason_codes(reason_codes or []),
|
||||
'affected_refs': (affected_refs or [])[:20],
|
||||
'primary_action': primary_action,
|
||||
}
|
||||
|
||||
|
||||
def _budget_limited_attachment_refs(run: ShippingOrderExtractionRun) -> list[dict[str, Any]]:
|
||||
"""从冻结选择计划提取预算受限附件引用,供 handling_items 直达定位。"""
|
||||
snapshot = getattr(run, 'input_snapshot_json', None)
|
||||
if not isinstance(snapshot, dict):
|
||||
return []
|
||||
selection = snapshot.get('attachment_selection') if isinstance(snapshot.get('attachment_selection'), dict) else {}
|
||||
items = selection.get('items') if isinstance(selection.get('items'), list) else []
|
||||
budget_codes = {'budget_initial_limit', 'budget_total_limit', 'budget_total_bytes'}
|
||||
refs: list[dict[str, Any]] = []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
codes = {str(code).strip() for code in (item.get('skip_reason_codes') or []) if str(code or '').strip()}
|
||||
if not (codes & budget_codes):
|
||||
continue
|
||||
document_id = int(item.get('document_id') or 0)
|
||||
refs.append({
|
||||
'type': 'attachment',
|
||||
'file_name': _safe_file_name(item.get('filename') or item.get('file_name')),
|
||||
'content_hash': str(item.get('content_hash') or '').strip()[:64] or None,
|
||||
'document_id': document_id if document_id > 0 else None,
|
||||
})
|
||||
if len(refs) >= 10:
|
||||
break
|
||||
return refs
|
||||
|
||||
|
||||
def build_handling_items(
|
||||
run: ShippingOrderExtractionRun,
|
||||
units: list[ShippingOrderExtractionUnit] | None = None,
|
||||
*,
|
||||
open_existing_doc_ids: set[int] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 Run 收口后的混合状态拆成可展示、可跳转的处理事项。
|
||||
|
||||
核心逻辑:不依赖单一 Run.status;分别统计 PDF 复核、技术失败、候选待补/冲突、
|
||||
自动冻结受阻与预算停扩。前端应以本列表为主提示,避免用 heuristic 掩盖后端事实。
|
||||
|
||||
Args:
|
||||
run: 订单抽取 Run。
|
||||
units: 可选 Unit 列表;缺省时从 extraction_plan 读取。
|
||||
open_existing_doc_ids: 已 open_existing 的 document_id,避免误报复核。
|
||||
|
||||
Returns:
|
||||
按优先级排序的 handling_items 列表。
|
||||
"""
|
||||
unit_rows = list(units) if units is not None else (
|
||||
list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
|
||||
)
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else _open_existing_document_ids(run)
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] PDF 技术失败与人工复核(排除已 open_existing)。
|
||||
failed_units = [unit for unit in unit_rows if str(unit.status or '') == 'failed']
|
||||
if failed_units:
|
||||
codes = _trim_reason_codes([
|
||||
getattr(unit, 'technical_failure_reason_code', None) or getattr(unit, 'reason_code', None)
|
||||
for unit in failed_units
|
||||
])
|
||||
items.append(_handling_item(
|
||||
category='technical_failure',
|
||||
count=len(failed_units),
|
||||
reason_codes=codes or ['technical_failure'],
|
||||
affected_refs=[
|
||||
{'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id)}
|
||||
for unit in failed_units[:10]
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
],
|
||||
primary_action='retry_failed_attachments',
|
||||
))
|
||||
|
||||
review_units = [
|
||||
unit for unit in unit_rows
|
||||
if str(unit.status or '') == 'review_required' and int(unit.document_id or 0) not in open_ids
|
||||
]
|
||||
review_count = max(
|
||||
len(review_units),
|
||||
_unresolved_review_document_count(run, open_existing_doc_ids=open_ids),
|
||||
)
|
||||
if review_count > 0:
|
||||
codes = _trim_reason_codes([
|
||||
getattr(unit, 'reason_code', None)
|
||||
for unit in review_units
|
||||
])
|
||||
items.append(_handling_item(
|
||||
category='document_review',
|
||||
count=review_count,
|
||||
reason_codes=codes,
|
||||
affected_refs=[
|
||||
{'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id)}
|
||||
for unit in review_units[:10]
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
],
|
||||
primary_action='enter_manual_review',
|
||||
))
|
||||
|
||||
# [STEP 2] 候选待补信息 / 冲突(来自 pending_orders 或 provisional 候选)。
|
||||
pending_orders = _pending_order_facts(run)
|
||||
conflict_orders: list[dict[str, Any]] = []
|
||||
missing_orders: list[dict[str, Any]] = []
|
||||
confirmation_only: list[dict[str, Any]] = []
|
||||
for item in pending_orders:
|
||||
reasons = {str(code) for code in item.get('reasons') or []}
|
||||
missing_fields = item.get('missing_fields') or []
|
||||
has_conflict = bool(reasons & _CANDIDATE_CONFLICT_REASON_CODES)
|
||||
has_missing = bool(missing_fields) or bool(reasons - _CANDIDATE_CONFLICT_REASON_CODES - {'auto_create_disabled'})
|
||||
if has_conflict:
|
||||
conflict_orders.append(item)
|
||||
elif has_missing:
|
||||
missing_orders.append(item)
|
||||
else:
|
||||
confirmation_only.append(item)
|
||||
|
||||
if conflict_orders:
|
||||
items.append(_handling_item(
|
||||
category='candidate_conflict',
|
||||
count=len(conflict_orders),
|
||||
reason_codes=[code for item in conflict_orders for code in (item.get('reasons') or [])],
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
}
|
||||
for item in conflict_orders[:10]
|
||||
if item.get('candidate_no')
|
||||
],
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
if missing_orders:
|
||||
items.append(_handling_item(
|
||||
category='candidate_missing_info',
|
||||
count=len(missing_orders),
|
||||
reason_codes=[code for item in missing_orders for code in (item.get('reasons') or [])]
|
||||
or ['required_field_missing'],
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
'missing_fields': item.get('missing_fields') or [],
|
||||
}
|
||||
for item in missing_orders[:10]
|
||||
if item.get('candidate_no')
|
||||
],
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
|
||||
# [STEP 3] 自动冻结受阻与预算停扩。
|
||||
freeze = _auto_freeze_block_facts(run)
|
||||
if freeze['blocked']:
|
||||
items.append(_handling_item(
|
||||
category='auto_freeze_blocked',
|
||||
count=max(int(freeze['blocked_task_count'] or 0), 1),
|
||||
reason_codes=list(freeze['reason_codes'] or []),
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'task',
|
||||
'task_no': item.get('task_no'),
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
}
|
||||
for item in freeze['blocked_tasks'][:10]
|
||||
if item.get('task_no') or item.get('candidate_no')
|
||||
],
|
||||
primary_action='view_details',
|
||||
))
|
||||
|
||||
if _budget_stopped_for_run(run):
|
||||
budget_refs = _budget_limited_attachment_refs(run)
|
||||
items.append(_handling_item(
|
||||
category='budget_stopped',
|
||||
count=max(len(budget_refs), 1),
|
||||
reason_codes=['budget_initial_limit'],
|
||||
affected_refs=budget_refs,
|
||||
primary_action='view_details',
|
||||
))
|
||||
|
||||
# [STEP 4] 仅候选确认(无缺失/冲突);已有缺失/冲突事项时不再叠加笼统「待确认」。
|
||||
has_candidate_issue = any(
|
||||
item['category'] in {'candidate_conflict', 'candidate_missing_info'} for item in items
|
||||
)
|
||||
if not has_candidate_issue:
|
||||
confirmation_count = len(confirmation_only)
|
||||
if confirmation_count == 0:
|
||||
candidate_ready_units = [
|
||||
unit for unit in unit_rows
|
||||
if str(unit.status or '') == 'candidate_ready' and int(unit.document_id or 0) not in open_ids
|
||||
]
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
pending_count = max(0, int(result.get('pending_count') or 0))
|
||||
if candidate_ready_units and run.status in {'review_required', 'partially_completed'} and (
|
||||
pending_count > 0 or not items
|
||||
):
|
||||
confirmation_count = max(pending_count, len(candidate_ready_units))
|
||||
if confirmation_count > 0:
|
||||
items.append(_handling_item(
|
||||
category='candidate_confirmation',
|
||||
count=confirmation_count,
|
||||
reason_codes=['auto_create_disabled'] if confirmation_only else [],
|
||||
affected_refs=[
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
}
|
||||
for item in confirmation_only[:10]
|
||||
if item.get('candidate_no')
|
||||
],
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
|
||||
priority = {name: index for index, name in enumerate(_HANDLING_ITEM_PRIORITY)}
|
||||
items.sort(key=lambda row: priority.get(str(row.get('category') or ''), 99))
|
||||
return items
|
||||
|
||||
|
||||
def _primary_notice_from_handling_items(items: list[dict[str, Any]]) -> str | None:
|
||||
"""取优先级最高的处理事项类别,供聊天卡一句通知。"""
|
||||
if not items:
|
||||
return None
|
||||
return str(items[0].get('category') or '') or None
|
||||
|
||||
|
||||
def _run_available_actions(
|
||||
run: ShippingOrderExtractionRun,
|
||||
units: list[ShippingOrderExtractionUnit],
|
||||
*,
|
||||
open_existing_doc_ids: set[int] | None = None,
|
||||
handling_items: list[dict[str, Any]] | None = None,
|
||||
) -> list[str]:
|
||||
"""根据 Run 与 Unit 事实返回用户可见操作;纯 open_existing 不暴露人工复核入口。"""
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else _open_existing_document_ids(run)
|
||||
actions = ['view_details']
|
||||
actions = ['view_details', 'refresh_status']
|
||||
needs_manual_review = any(
|
||||
str(unit.status or '') == 'review_required'
|
||||
and int(unit.document_id) not in open_ids
|
||||
@@ -247,8 +884,24 @@ def _run_available_actions(
|
||||
needs_manual_review = True
|
||||
if needs_manual_review:
|
||||
actions.append('enter_manual_review')
|
||||
if run.status == 'failed' or any(unit.status == 'failed' for unit in units):
|
||||
actions.append('retry_failed_attachments')
|
||||
items = handling_items if handling_items is not None else []
|
||||
categories = {str(item.get('category') or '') for item in items}
|
||||
if categories & {'candidate_conflict', 'candidate_missing_info', 'candidate_confirmation'}:
|
||||
if 'review_candidate' not in actions:
|
||||
actions.append('review_candidate')
|
||||
if 'enter_manual_review' not in actions:
|
||||
actions.append('enter_manual_review')
|
||||
if categories & {'document_review'} and 'enter_manual_review' not in actions:
|
||||
actions.append('enter_manual_review')
|
||||
if run.status == 'failed' or any(unit.status == 'failed' for unit in units) or 'technical_failure' in categories:
|
||||
if 'retry_failed_attachments' not in actions:
|
||||
actions.append('retry_failed_attachments')
|
||||
if (
|
||||
order_extraction_cancel_enabled()
|
||||
and run.status in {'queued', 'processing'}
|
||||
and run.cancellation_completed_at is None
|
||||
):
|
||||
actions.append('cancel_run')
|
||||
return actions
|
||||
|
||||
|
||||
@@ -325,6 +978,7 @@ def _document_available_actions(
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
*,
|
||||
duplicate: dict[str, Any] | None = None,
|
||||
run: ShippingOrderExtractionRun | None = None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
按单元状态与重复决策返回详情项可见操作。
|
||||
@@ -332,16 +986,30 @@ def _document_available_actions(
|
||||
核心逻辑:open_existing 且已有任务号时优先暴露 open_existing,不再映射为人工复核入口。
|
||||
"""
|
||||
dup = duplicate if isinstance(duplicate, dict) else {}
|
||||
actions: list[str] = []
|
||||
if (
|
||||
str(dup.get('duplicate_resolution') or '') == 'open_existing'
|
||||
and str(dup.get('existing_task_no') or '').strip()
|
||||
):
|
||||
return ['open_existing', 'view_evidence']
|
||||
if unit.status == 'candidate_ready':
|
||||
return ['view_evidence', 'review_candidate']
|
||||
if unit.status == 'review_required':
|
||||
return ['view_evidence', 'manual_review']
|
||||
return []
|
||||
actions = ['open_existing', 'view_evidence']
|
||||
elif unit.status == 'candidate_ready':
|
||||
actions = ['view_evidence', 'review_candidate']
|
||||
elif unit.status == 'review_required':
|
||||
actions = ['view_evidence', 'manual_review']
|
||||
elif unit.status == 'failed':
|
||||
actions = ['view_details']
|
||||
else:
|
||||
actions = ['view_details']
|
||||
if (
|
||||
order_extraction_cancel_enabled()
|
||||
and run is not None
|
||||
and run.status in {'queued', 'processing'}
|
||||
and unit.status in (ACTIVE_UNIT_STATUSES)
|
||||
and unit.cancellation_completed_at is None
|
||||
):
|
||||
actions.append('cancel_unit')
|
||||
actions.append('refresh_status')
|
||||
return actions
|
||||
|
||||
|
||||
def _document_reason_code(
|
||||
@@ -377,7 +1045,7 @@ def _planned_layout_documents(
|
||||
documents: dict[int, dict[str, Any]],
|
||||
event_map: dict[tuple[int, str], ShippingOrderExtractionProgressEvent],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""在 Unit 尚未物化时投影已选 PDF,避免版面解析期的详情列表显示为空。"""
|
||||
"""在 Unit 尚未物化时投影已选 PDF,并继承 Run 终态避免展示假处理中。"""
|
||||
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')]
|
||||
@@ -387,36 +1055,80 @@ def _planned_layout_documents(
|
||||
if str(item.get('content_hash') or '').strip()
|
||||
}
|
||||
items: list[dict[str, Any]] = []
|
||||
run_failed = str(run.status or '') == 'failed'
|
||||
run_failure_code = str(run.error_code or '').strip() or 'technical_failure'
|
||||
run_cancelled = str(run.status or '') == 'cancelled'
|
||||
now = datetime.utcnow()
|
||||
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'))
|
||||
if run_failed:
|
||||
status = 'failed'
|
||||
stage = 'failed'
|
||||
elif run_cancelled:
|
||||
status = 'cancelled'
|
||||
stage = 'cancelled'
|
||||
elif str(run.phase or '') == 'waiting_layout':
|
||||
status = 'pending'
|
||||
stage = 'layout_parsing_started' if started and not completed else 'waiting_layout'
|
||||
else:
|
||||
status = 'pending'
|
||||
stage = 'document_queued'
|
||||
started_at = (started.occurred_at or started.received_at or started.created_at) if started else None
|
||||
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',
|
||||
# Job 可在 Unit 物化前最终失败;此时每份计划 PDF 都不能继续显示为 pending。
|
||||
'status': status,
|
||||
'user_visible_stage': stage,
|
||||
'queue_position': index if status == 'pending' and not run_failed and not run_cancelled else None,
|
||||
'elapsed_seconds': _elapsed_seconds(started_at=started_at or run.created_at, finished_at=run.finished_at, now=now)
|
||||
if (started_at or run.created_at) else None,
|
||||
'health_tips': (
|
||||
_health_tips_for_planned_document(
|
||||
run=run,
|
||||
stage=stage,
|
||||
started_at=started_at,
|
||||
now=now,
|
||||
) if progress_ui_v3_enabled() else []
|
||||
),
|
||||
'cancellation': _cancellation_projection(run) if run_cancelled or getattr(run, 'cancellation_requested_at', None) else None,
|
||||
'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,
|
||||
'technical_failure_reason_code': run_failure_code if run_failed else None,
|
||||
'budget_cost': None,
|
||||
'po_number': None,
|
||||
'line_count': 0,
|
||||
'profile': None,
|
||||
'email_supplement': {'status': 'none', 'relation_codes': [], 'conflict_count': 0},
|
||||
'reason_code': None,
|
||||
'reason_code': run_failure_code if run_failed else None,
|
||||
'review_details': [],
|
||||
'duplicate_resolution': None,
|
||||
'existing_task_no': None,
|
||||
'duplicate_status': None,
|
||||
'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,
|
||||
'available_actions': (['cancel_unit'] if (
|
||||
order_extraction_cancel_enabled()
|
||||
and run.status in {'queued', 'processing'}
|
||||
and getattr(run, 'cancellation_completed_at', None) is None
|
||||
) else []),
|
||||
'activity_event_code': 'technical_failed' if run_failed else ('layout_parsing_completed' if completed else 'layout_parsing_started' if started else None),
|
||||
'started_at': started_at.isoformat() + 'Z' if started_at else None,
|
||||
'last_activity_at': (
|
||||
(completed.occurred_at or completed.received_at or completed.created_at).isoformat() + 'Z'
|
||||
if completed else (
|
||||
started_at.isoformat() + 'Z' if started_at else (
|
||||
run.last_activity_at.isoformat() + 'Z' if getattr(run, 'last_activity_at', None) else None
|
||||
)
|
||||
)
|
||||
),
|
||||
'finished_at': (run.finished_at.isoformat() + 'Z' if run_failed and run.finished_at else (
|
||||
(completed.occurred_at or completed.received_at or completed.created_at).isoformat() + 'Z' if completed else None
|
||||
)),
|
||||
})
|
||||
return items
|
||||
|
||||
@@ -500,16 +1212,29 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
field_codes = _schema_field_codes(run)
|
||||
route_by_unit = _latest_route_decisions(run)
|
||||
duplicates_by_doc = _duplicate_projection_by_document(run)
|
||||
queue_positions = _queue_positions(units)
|
||||
now = datetime.utcnow()
|
||||
items: list[dict[str, Any]] = []
|
||||
for unit in units:
|
||||
orders = _orders_from_unit(unit)
|
||||
document = documents.get(int(unit.document_id), {})
|
||||
duplicate = duplicates_by_doc.get(int(unit.document_id), {})
|
||||
started_at = getattr(unit, 'started_at', None) or (unit.created_at if unit.status != 'pending' else None)
|
||||
items.append({
|
||||
'unit_id': int(unit.id),
|
||||
'document_id': int(unit.document_id),
|
||||
'file_name': document.get('file_name'),
|
||||
'status': unit.status,
|
||||
'user_visible_stage': _unit_user_visible_stage(unit, run=run),
|
||||
'queue_position': queue_positions.get(int(unit.id)),
|
||||
'elapsed_seconds': _elapsed_seconds(
|
||||
started_at=started_at,
|
||||
finished_at=getattr(unit, 'finished_at', None),
|
||||
now=now,
|
||||
),
|
||||
'health_tips': _health_tips_for_unit(unit, run=run, now=now) if progress_ui_v3_enabled() else [],
|
||||
'cancellation': _cancellation_projection(unit),
|
||||
'activity_version': int(getattr(unit, 'activity_version', 1) or 1),
|
||||
'selection_batch': int(unit.selection_batch) if unit.selection_batch is not None else None,
|
||||
'group_key': str(unit.group_key or '').strip() or None,
|
||||
'retry_status': str(unit.retry_status or '').strip() or None,
|
||||
@@ -524,7 +1249,7 @@ def serialize_workspace_run_documents(run: ShippingOrderExtractionRun) -> list[d
|
||||
'duplicate_resolution': duplicate.get('duplicate_resolution'),
|
||||
'existing_task_no': duplicate.get('existing_task_no'),
|
||||
'duplicate_status': duplicate.get('duplicate_status'),
|
||||
'available_actions': _document_available_actions(unit, duplicate=duplicate),
|
||||
'available_actions': _document_available_actions(unit, duplicate=duplicate, run=run),
|
||||
'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,
|
||||
@@ -588,6 +1313,30 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
_unresolved_review_document_count(run, open_existing_doc_ids=open_existing_doc_ids),
|
||||
)
|
||||
opened_existing_count = max(open_existing_units, _result_opened_existing_count(run))
|
||||
handling_items = build_handling_items(run, units, open_existing_doc_ids=open_existing_doc_ids)
|
||||
now = datetime.utcnow()
|
||||
if current_activity is not None:
|
||||
active_unit = None
|
||||
if current_activity.get('unit_id') is not None:
|
||||
active_unit = next((unit for unit in units if int(unit.id) == int(current_activity['unit_id'])), None)
|
||||
current_activity = {
|
||||
**current_activity,
|
||||
'user_visible_stage': (
|
||||
_unit_user_visible_stage(active_unit, run=run)
|
||||
if active_unit is not None
|
||||
else _run_user_visible_stage(run, units)
|
||||
),
|
||||
'elapsed_seconds': _elapsed_seconds(
|
||||
started_at=(active_unit.started_at if active_unit is not None else run.started_at) or run.created_at,
|
||||
finished_at=active_unit.finished_at if active_unit is not None else run.finished_at,
|
||||
now=now,
|
||||
),
|
||||
'last_activity_at': (
|
||||
(active_unit.last_activity_at.isoformat() + 'Z')
|
||||
if active_unit is not None and active_unit.last_activity_at
|
||||
else (run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None)
|
||||
),
|
||||
}
|
||||
return {
|
||||
'summary': {
|
||||
'total_documents': _planned_document_count(run, units),
|
||||
@@ -596,11 +1345,27 @@ def serialize_workspace_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
'completed_documents': status_counter.get('candidate_ready', 0),
|
||||
'review_required_documents': review_document_count,
|
||||
'failed_documents': status_counter.get('failed', 0),
|
||||
'cancelled_documents': status_counter.get('cancelled', 0),
|
||||
'candidate_count': sum(_candidate_count(unit) for unit in units),
|
||||
'opened_existing_documents': opened_existing_count,
|
||||
},
|
||||
'current_activity': current_activity,
|
||||
'available_actions': _run_available_actions(run, units, open_existing_doc_ids=open_existing_doc_ids),
|
||||
'handling_items': handling_items,
|
||||
'primary_notice': _primary_notice_from_handling_items(handling_items),
|
||||
'available_actions': _run_available_actions(
|
||||
run,
|
||||
units,
|
||||
open_existing_doc_ids=open_existing_doc_ids,
|
||||
handling_items=handling_items,
|
||||
),
|
||||
'user_visible_stage': _run_user_visible_stage(run, units),
|
||||
# 回滚进度 UI v3 时不下发健康提示,避免前端展示灰度未启用的细化提醒。
|
||||
'health_tips': _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [],
|
||||
'cancellation': _cancellation_projection(run),
|
||||
'progress_version': int(run.progress_version or 0),
|
||||
'elapsed_seconds': _elapsed_seconds(started_at=run.started_at or run.created_at, finished_at=run.finished_at, now=now),
|
||||
'last_activity_at': run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None,
|
||||
'feature_flags': progress_feature_flags_payload(),
|
||||
}
|
||||
|
||||
|
||||
@@ -623,6 +1388,7 @@ def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[
|
||||
'completedDocuments': int(summary.get('completed_documents') or 0),
|
||||
'reviewRequiredDocuments': int(summary.get('review_required_documents') or 0),
|
||||
'failedDocuments': int(summary.get('failed_documents') or 0),
|
||||
'cancelledDocuments': int(summary.get('cancelled_documents') or 0),
|
||||
'candidateCount': int(summary.get('candidate_count') or 0),
|
||||
'openedExistingCount': int(summary.get('opened_existing_documents') or 0),
|
||||
},
|
||||
@@ -631,12 +1397,31 @@ def serialize_workspace_run_chat_state(run: ShippingOrderExtractionRun) -> dict[
|
||||
'unitId': int(current_activity.get('unit_id') or 0),
|
||||
'fileName': current_activity.get('file_name'),
|
||||
'eventCode': str(current_activity.get('event_code') or ''),
|
||||
'userVisibleStage': current_activity.get('user_visible_stage'),
|
||||
'selectionBatch': int(current_activity.get('selection_batch') or 0) or None,
|
||||
'reasonCodes': [str(code) for code in current_activity.get('reason_codes') or [] if str(code).strip()],
|
||||
'elapsedSeconds': current_activity.get('elapsed_seconds'),
|
||||
'lastActivityAt': current_activity.get('last_activity_at'),
|
||||
}
|
||||
if current_activity else None
|
||||
),
|
||||
'availableActions': [str(action) for action in projection.get('available_actions') or []],
|
||||
'handlingItems': [
|
||||
{
|
||||
'category': str(item.get('category') or ''),
|
||||
'count': int(item.get('count') or 0),
|
||||
'reasonCodes': [str(code) for code in item.get('reason_codes') or [] if str(code).strip()],
|
||||
'affectedRefs': list(item.get('affected_refs') or []),
|
||||
'primaryAction': str(item.get('primary_action') or '') or None,
|
||||
}
|
||||
for item in (projection.get('handling_items') or [])
|
||||
if isinstance(item, dict) and str(item.get('category') or '').strip()
|
||||
],
|
||||
'primaryNotice': projection.get('primary_notice'),
|
||||
'userVisibleStage': projection.get('user_visible_stage'),
|
||||
'healthTips': projection.get('health_tips') or [],
|
||||
'cancellation': projection.get('cancellation'),
|
||||
'progressVersion': projection.get('progress_version'),
|
||||
'terminal': str(run.status or '') not in {'queued', 'processing'},
|
||||
'errorCode': str(run.error_code or '') or None,
|
||||
'startedAt': run.started_at.isoformat() + 'Z' if run.started_at else None,
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
backend/app/services/shipping_notice/order_review_confirmation_service.py
|
||||
|
||||
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、progress_workflow.auto_progress。
|
||||
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、fulfillment_audit、
|
||||
progress_workflow.auto_progress。
|
||||
逻辑:确认在单事务内分别锁定 Case 与 Draft(避免 joinedload+FOR UPDATE),
|
||||
冻结不可变 Revision,物化仅供履约的人工 Candidate 与 accepted Extraction;
|
||||
全程不改写机器 Candidate,也不创建 Batch。由 workspace shipping_notice API 调用;
|
||||
全程不改写机器 Candidate,也不创建 Batch。确认成功后无条件写 Case 级统一审计
|
||||
(不依赖工作项是否绑定),再尝试关闭会话工作项。由 workspace shipping_notice API 调用;
|
||||
API commit 后触发 progress_workflow.auto_progress(禁止平行推进链)。
|
||||
"""
|
||||
|
||||
@@ -24,6 +26,7 @@ from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
@@ -31,6 +34,7 @@ from app.models import (
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewConfirmedRevision,
|
||||
ShippingOrderReviewDraft,
|
||||
ShippingSessionPdfWorkItem,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
@@ -44,6 +48,7 @@ from app.services.shipping_notice.candidate_service import ensure_candidate_fulf
|
||||
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.fulfillment_audit import record_fulfillment_audit
|
||||
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
|
||||
@@ -192,6 +197,81 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
|
||||
return extraction
|
||||
|
||||
|
||||
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""
|
||||
按 current_case_id 反查会话工作项编号。
|
||||
|
||||
核心逻辑:确认审计不得因工作项缺失而跳过;仅用于填充关联字段。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case。
|
||||
|
||||
Returns:
|
||||
工作项编号;未绑定时为 None。
|
||||
"""
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
return str(item.item_no) if item is not None else None
|
||||
|
||||
|
||||
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""
|
||||
从 Case 所属 Run 读取会话 ID。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case。
|
||||
|
||||
Returns:
|
||||
conversation_id;Run 缺失时为 None。
|
||||
"""
|
||||
run = case.run
|
||||
if run is None and case.run_id:
|
||||
run = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
return str(run.conversation_id) if run is not None and run.conversation_id else None
|
||||
|
||||
|
||||
def _record_unified_confirmation_audit(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
before: dict[str, Any],
|
||||
after: dict[str, Any],
|
||||
task_no: str | None,
|
||||
idempotency_key: str,
|
||||
) -> None:
|
||||
"""
|
||||
将确认建单写入统一 ShippingAuditEvent,供审计中心无条件覆盖。
|
||||
|
||||
核心逻辑:与 CaseEvent / 工作项关闭同事务;即使未绑定工作项也必须落库,
|
||||
保证操作人、请求关联与前后快照可追溯。
|
||||
|
||||
Args:
|
||||
case: 已置为 confirmed 的 Case。
|
||||
actor_id: 确认操作人用户 ID。
|
||||
before: 确认前状态摘要(白名单字段)。
|
||||
after: 确认后状态摘要(含 task_no)。
|
||||
task_no: 新建任务号。
|
||||
idempotency_key: 建单幂等键。
|
||||
"""
|
||||
record_fulfillment_audit(
|
||||
event_type='review_confirmed',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action='confirm_review_case',
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
review_case_no=str(case.case_no),
|
||||
owner_user_id=case.owner_user_id,
|
||||
document_id=case.document_id,
|
||||
conversation_id=_conversation_id_for_case(case),
|
||||
session_item_id=_session_item_no_for_case(case),
|
||||
task_no=task_no,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata={'idempotency_key': idempotency_key},
|
||||
source='order_review',
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
@@ -225,7 +305,22 @@ def _create_review_candidate(*, case: ShippingOrderReviewCase, intake: ShippingN
|
||||
|
||||
|
||||
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;任何门禁失败都由事务回滚。"""
|
||||
"""
|
||||
确认一个 PDF 草稿并建一张无 Batch 的 Task;任何门禁失败都由事务回滚。
|
||||
|
||||
核心逻辑:成功路径无条件写 Case 级 `review_confirmed` 统一审计(含操作人与前后快照),
|
||||
再尝试关闭绑定的会话工作项;工作项缺失不得跳过统一审计。
|
||||
|
||||
Args:
|
||||
user_id: Case 属主用户 ID。
|
||||
case_no: 复核 Case 编号。
|
||||
expected_draft_version: 客户端声明的草稿版本。
|
||||
idempotency_key: 建单幂等键。
|
||||
warning_acknowledgements: 警告确认列表。
|
||||
|
||||
Returns:
|
||||
含 task_no / case / trigger_auto_progress 的确认结果。
|
||||
"""
|
||||
key = normalize_create_idempotency_key(idempotency_key)
|
||||
if not key:
|
||||
raise ValidationError('idempotency_key is required', code='SHIPPING.REVIEW_IDEMPOTENCY_KEY_REQUIRED')
|
||||
@@ -262,7 +357,14 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
'source_file_name': document.filename,
|
||||
'duplicate_resolution_type': 'normal',
|
||||
}])
|
||||
previous_status = str(case.status or '')
|
||||
previous_disposition = case.disposition
|
||||
case.status = 'confirming'
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
assert_case_is_current_work_item_version,
|
||||
close_work_item_for_case,
|
||||
)
|
||||
assert_case_is_current_work_item_version(case=case)
|
||||
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))
|
||||
@@ -300,6 +402,28 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
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},
|
||||
))
|
||||
# Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯确认事实。
|
||||
_record_unified_confirmation_audit(
|
||||
case,
|
||||
actor_id=int(user_id),
|
||||
before={'status': previous_status, 'disposition': previous_disposition},
|
||||
after={
|
||||
'status': case.status,
|
||||
'disposition': case.disposition,
|
||||
'confirmed_task_no': task.task_no,
|
||||
'draft_version': int(case.current_draft.draft_version),
|
||||
},
|
||||
task_no=task.task_no,
|
||||
idempotency_key=key,
|
||||
)
|
||||
close_work_item_for_case(
|
||||
case=case,
|
||||
closed_reason='confirmed',
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
task_no=task.task_no,
|
||||
event_type='review_confirmed',
|
||||
)
|
||||
log_task_event(task, 'task_created_from_review_case', {'case_no': case.case_no, 'confirmed_revision_id': None})
|
||||
db.session.flush()
|
||||
# 调用方须在 commit 后调用 trigger_auto_progress_after_review_confirm。
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
backend/app/services/shipping_notice/order_review_disposition_service.py
|
||||
|
||||
用途:建单前订单复核的 PDF 处置与单文件重识别服务。
|
||||
依赖:Review Case/Draft/Event、冻结 Run/Document、抽取 Run 创建服务。
|
||||
依赖:Review Case/Draft/Event、冻结 Run/Document、抽取 Run 创建服务、fulfillment_audit。
|
||||
逻辑:处置只改变当前 PDF 的 Case 生命周期;锁定时分别 FOR UPDATE Case 与 Draft,
|
||||
禁止 joinedload+FOR UPDATE。单文件重识别通过新的 Run 保留原始 PDF 与机器结果,
|
||||
成功后才由 Run 终态钩子替代旧 Case。由 workspace shipping_notice API 调用。
|
||||
成功后才由 Run 终态钩子替代旧 Case。每次关键处置同时写 CaseEvent + 统一 ShippingAuditEvent;
|
||||
质量异常原因码 `other` 时备注必填。由 workspace shipping_notice API 调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,6 +24,7 @@ from app.models import (
|
||||
ShippingOrderReviewDraft,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
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
|
||||
|
||||
@@ -63,7 +65,7 @@ def _reason(value: Any, *, allowed: frozenset[str], code: str) -> str:
|
||||
|
||||
|
||||
def _append_event(case: ShippingOrderReviewCase, *, actor_id: int, event_type: str, operation: dict[str, Any]) -> None:
|
||||
"""追加脱敏处置审计,不保存 PDF 正文、原始模型响应或对象存储定位。"""
|
||||
"""追加 Case 域事件;不保存 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,
|
||||
@@ -71,6 +73,58 @@ def _append_event(case: ShippingOrderReviewCase, *, actor_id: int, event_type: s
|
||||
))
|
||||
|
||||
|
||||
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""按 current_case_id 反查会话工作项编号。"""
|
||||
from app.models import ShippingSessionPdfWorkItem
|
||||
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
return str(item.item_no) if item is not None else None
|
||||
|
||||
|
||||
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""从 Case 所属 Run 读取会话 ID。"""
|
||||
run = ShippingOrderExtractionRun.query.get(int(case.run_id)) if case.run_id else None
|
||||
return str(run.conversation_id) if run is not None and run.conversation_id else None
|
||||
|
||||
|
||||
def _record_unified_disposition_audit(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
actor_id: int,
|
||||
event_type: str,
|
||||
action: str,
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
reason_code: str | None = None,
|
||||
reason: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将处置写入统一 ShippingAuditEvent,供管理员审计中心覆盖。
|
||||
|
||||
核心逻辑:与 CaseEvent 同事务;附带会话/工作项关联与请求客户端哈希。
|
||||
"""
|
||||
record_fulfillment_audit(
|
||||
event_type=event_type,
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action=action,
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
review_case_no=str(case.case_no),
|
||||
owner_user_id=case.owner_user_id,
|
||||
document_id=case.document_id,
|
||||
conversation_id=_conversation_id_for_case(case),
|
||||
session_item_id=_session_item_no_for_case(case),
|
||||
reason_code=reason_code,
|
||||
reason=reason,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
source='order_review',
|
||||
)
|
||||
|
||||
|
||||
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)
|
||||
@@ -86,6 +140,15 @@ def create_manual_draft(*, user_id: int, case_no: str, comment: str | None = Non
|
||||
_append_event(case, actor_id=user_id, event_type='manual_draft_created', operation={
|
||||
'previous_status': previous, 'comment': str(comment or '').strip()[:500] or None,
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_manual_draft_created',
|
||||
action='create_manual_draft',
|
||||
before={'status': previous},
|
||||
after={'status': case.status, 'disposition': case.disposition},
|
||||
reason=str(comment or '').strip()[:500] or None,
|
||||
)
|
||||
db.session.flush()
|
||||
return serialize_review_case(case)
|
||||
|
||||
@@ -96,31 +159,88 @@ def mark_non_order(*, user_id: int, case_no: str, reason: str, comment: str | 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')
|
||||
previous = case.status
|
||||
previous_disposition = case.disposition
|
||||
case.status = 'non_order'
|
||||
case.disposition = normalized
|
||||
comment_text = str(comment or '').strip()[:500] or None
|
||||
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,
|
||||
'reason': normalized, 'comment': comment_text,
|
||||
})
|
||||
# Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯。
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_non_order',
|
||||
action='mark_non_order',
|
||||
before={'status': previous, 'disposition': previous_disposition},
|
||||
after={'status': case.status, 'disposition': normalized},
|
||||
reason_code=normalized,
|
||||
reason=comment_text or normalized,
|
||||
)
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import close_work_item_for_case
|
||||
close_work_item_for_case(
|
||||
case=case,
|
||||
closed_reason='non_order',
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
reason=comment_text or normalized,
|
||||
event_type='review_marked_non_order',
|
||||
)
|
||||
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、草稿和机器值,供补件或单文件重识别恢复。"""
|
||||
"""
|
||||
标记文件质量异常并保留 PDF、草稿和机器值,供补件或单文件重识别恢复。
|
||||
|
||||
核心逻辑:原因码 `other` 时备注必填,确保统一审计可复盘具体业务理由。
|
||||
|
||||
Args:
|
||||
user_id: Case 属主用户 ID。
|
||||
case_no: 复核 Case 编号。
|
||||
reason: 质量原因码(见 `_QUALITY_REASONS`)。
|
||||
comment: 备注;`other` 时不可为空。
|
||||
|
||||
Returns:
|
||||
序列化后的 Case。
|
||||
|
||||
Raises:
|
||||
ValidationError: 原因码无效,或 `other` 缺少备注。
|
||||
ConflictError: Case 处于不可处置终态。
|
||||
"""
|
||||
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')
|
||||
comment_text = str(comment or '').strip()[:500] or None
|
||||
if normalized == 'other' and not comment_text:
|
||||
raise ValidationError(
|
||||
'Quality issue comment is required when reason is other',
|
||||
code='SHIPPING.REVIEW_QUALITY_COMMENT_REQUIRED',
|
||||
)
|
||||
previous = case.status
|
||||
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,
|
||||
'reason': normalized, 'comment': comment_text,
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_marked_quality_issue',
|
||||
action='mark_quality_issue',
|
||||
before={'status': previous},
|
||||
after={'status': case.status, 'disposition': normalized},
|
||||
reason_code=normalized,
|
||||
reason=comment_text or normalized,
|
||||
)
|
||||
db.session.flush()
|
||||
return serialize_review_case(case)
|
||||
|
||||
@@ -166,6 +286,14 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
|
||||
_append_event(case, actor_id=user_id, event_type='document_reparse_started', operation={
|
||||
'previous_status': previous, 'reason': normalized, 'successor_run_no': run.run_no,
|
||||
})
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import mark_reparse_started
|
||||
mark_reparse_started(
|
||||
case=case,
|
||||
successor_run=run,
|
||||
reason=normalized,
|
||||
comment=comment,
|
||||
actor_id=user_id,
|
||||
)
|
||||
db.session.flush()
|
||||
return run, reused
|
||||
|
||||
@@ -192,6 +320,15 @@ def create_replacement_upload_intake(*, user_id: int, case_no: str, asset_no: st
|
||||
_append_event(case, actor_id=user_id, event_type='replacement_upload_created', operation={
|
||||
'replacement_intake_no': intake['intake_no'],
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
before={'status': case.status},
|
||||
after={'status': case.status, 'replacement_intake_no': intake['intake_no']},
|
||||
metadata={'replacement_intake_no': intake['intake_no']},
|
||||
)
|
||||
db.session.flush()
|
||||
return intake
|
||||
|
||||
@@ -233,6 +370,32 @@ def create_replacement_document_run(*, user_id: int, case_no: str, intake_no: st
|
||||
'previous_status': previous, 'replacement_intake_no': intake.intake_no,
|
||||
'replacement_document_id': int(pdfs[0].id), 'successor_run_no': run.run_no,
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
before={'status': previous},
|
||||
after={
|
||||
'status': case.status,
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
reason_code='document_quality',
|
||||
metadata={
|
||||
'replacement_document_id': int(pdfs[0].id),
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
)
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import mark_reparse_started
|
||||
mark_reparse_started(
|
||||
case=case,
|
||||
successor_run=run,
|
||||
reason='document_quality',
|
||||
comment=f'replacement for {case.case_no}',
|
||||
actor_id=user_id,
|
||||
replacement_document_id=int(pdfs[0].id),
|
||||
)
|
||||
db.session.flush()
|
||||
return run, reused
|
||||
|
||||
@@ -263,6 +426,7 @@ def finalize_document_reparse(*, run: ShippingOrderExtractionRun, succeeded: boo
|
||||
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
|
||||
'successor_run_no': run.run_no,
|
||||
})
|
||||
# 成功切换由 bind_cases_for_run(新 Case 初始化)完成版本指针;此处不提前改指针。
|
||||
return
|
||||
previous = 'quality_issue'
|
||||
event = ShippingOrderReviewCaseEvent.query.filter(
|
||||
@@ -277,3 +441,9 @@ def finalize_document_reparse(*, run: ShippingOrderExtractionRun, succeeded: boo
|
||||
_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,
|
||||
})
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import mark_reparse_failed_and_restore
|
||||
mark_reparse_failed_and_restore(
|
||||
source_case=source_case,
|
||||
failed_run=run,
|
||||
failure_stage=str(run.status or 'failed'),
|
||||
)
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
建单前订单复核草稿的编辑、校验与审计服务。
|
||||
services/shipping_notice/order_review_draft_service.py
|
||||
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则和 Candidate 履约硬门禁。
|
||||
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本并追加事件,
|
||||
绝不修改机器 Candidate。确认建单不属于本模块,留给阶段 6 的原子确认服务。
|
||||
用途:建单前订单复核草稿的编辑、校验与统一审计。
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则、fulfillment_audit、
|
||||
session_pdf_work_item_service.assert_case_is_current_work_item_version。
|
||||
逻辑:只修改独立 Draft JSON;每次写入锁定 Case/Draft、校验草稿版本并追加 CaseEvent +
|
||||
ShippingAuditEvent(含 request_id/operation_id 与字段前后值);绝不修改机器 Candidate。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -200,19 +202,122 @@ def build_confirmable_draft_summary(case: ShippingOrderReviewCase) -> tuple[dict
|
||||
return {**header, 'lines': lines}, validation
|
||||
|
||||
|
||||
def _record_change(case: ShippingOrderReviewCase, *, actor_id: int, event_type: str, operation: dict[str, Any]) -> dict[str, Any]:
|
||||
"""更新版本、状态和可重放的最小审计事件;不保存 PDF 正文或机器原始响应。"""
|
||||
def _audit_scalar(value: Any, *, limit: int = 200) -> Any:
|
||||
"""
|
||||
将字段值投影为审计可存的受控标量。
|
||||
|
||||
核心逻辑:Decimal/date 转字符串;过长字符串截断;拒绝嵌套大对象。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, Decimal):
|
||||
return format(value.normalize(), 'f')
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
if isinstance(value, bool) or isinstance(value, (int, float)):
|
||||
return value
|
||||
text = str(value)
|
||||
if len(text) > limit:
|
||||
return text[:limit]
|
||||
return text
|
||||
|
||||
|
||||
def _session_item_no_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""按 current_case_id 反查会话工作项编号。"""
|
||||
from app.models import ShippingSessionPdfWorkItem
|
||||
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
return str(item.item_no) if item is not None else None
|
||||
|
||||
|
||||
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""从 Case 所属 Run 读取会话 ID。"""
|
||||
from app.models import ShippingOrderExtractionRun
|
||||
|
||||
run = ShippingOrderExtractionRun.query.get(int(case.run_id)) if case.run_id else None
|
||||
return str(run.conversation_id) if run is not None and run.conversation_id else None
|
||||
|
||||
|
||||
def _record_change(
|
||||
case: ShippingOrderReviewCase, *, actor_id: int, event_type: str,
|
||||
operation: dict[str, Any], validate: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
保存草稿变更并写入统一审计。
|
||||
|
||||
核心逻辑:仅显式校验时跑整单门禁;审计附带 request_id/operation_id、字段前后值与工作项关联。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
assert_case_is_current_work_item_version,
|
||||
)
|
||||
assert_case_is_current_work_item_version(case=case)
|
||||
draft = case.current_draft
|
||||
result = _validation(case)
|
||||
before_version = int(draft.draft_version)
|
||||
previous_status = str(case.status or 'draft')
|
||||
result = _validation(case) if validate else {'status': 'not_validated', 'issues': []}
|
||||
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'
|
||||
case.status = 'ready' if validate and 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,
|
||||
))
|
||||
changed_paths = [
|
||||
key for key in ('field_id', 'line_key', 'action')
|
||||
if key in operation and operation.get(key) is not None
|
||||
]
|
||||
field_id = operation.get('field_id')
|
||||
line_key = operation.get('line_key')
|
||||
previous_value = _audit_scalar(operation.get('previous_value'))
|
||||
new_value = _audit_scalar(operation.get('value') if 'value' in operation else operation.get('new_value'))
|
||||
value_source = str(operation.get('source') or '')[:32] or None
|
||||
before_snapshot: dict[str, Any] = {
|
||||
'draft_version': before_version,
|
||||
'status': previous_status,
|
||||
}
|
||||
after_snapshot: dict[str, Any] = {
|
||||
'draft_version': int(draft.draft_version),
|
||||
'status': case.status,
|
||||
'changed_field_paths': changed_paths,
|
||||
'validation_blocking_count': len([
|
||||
issue for issue in (result.get('issues') or [])
|
||||
if isinstance(issue, dict) and str(issue.get('severity') or '').lower() == 'blocking'
|
||||
]),
|
||||
'validation_warning_count': len([
|
||||
issue for issue in (result.get('issues') or [])
|
||||
if isinstance(issue, dict) and str(issue.get('severity') or '').lower() != 'blocking'
|
||||
]),
|
||||
}
|
||||
if field_id is not None:
|
||||
before_snapshot['field_id'] = str(field_id)[:64]
|
||||
after_snapshot['field_id'] = str(field_id)[:64]
|
||||
before_snapshot['previous_value'] = previous_value
|
||||
after_snapshot['new_value'] = new_value
|
||||
if value_source:
|
||||
after_snapshot['value_source'] = value_source
|
||||
if line_key is not None:
|
||||
before_snapshot['line_key'] = str(line_key)[:64]
|
||||
after_snapshot['line_key'] = str(line_key)[:64]
|
||||
record_fulfillment_audit(
|
||||
event_type='review_draft_changed',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action=event_type,
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
review_case_no=str(case.case_no),
|
||||
owner_user_id=case.owner_user_id,
|
||||
document_id=case.document_id,
|
||||
conversation_id=_conversation_id_for_case(case),
|
||||
session_item_id=_session_item_no_for_case(case),
|
||||
before=before_snapshot,
|
||||
after=after_snapshot,
|
||||
metadata={'case_event_type': event_type},
|
||||
source='order_review',
|
||||
)
|
||||
db.session.flush()
|
||||
return serialize_review_case(case)
|
||||
|
||||
@@ -223,9 +328,15 @@ def patch_header_field(*, user_id: int, case_no: str, field_id: str, value: Any,
|
||||
_assert_version(case, expected_draft_version)
|
||||
field = _require_field(case, field_id, 'header')
|
||||
header = dict(case.current_draft.header_values_json or {})
|
||||
previous_value = _current_value(header, field_id)
|
||||
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})
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='header_field_changed',
|
||||
operation={'field_id': field_id, 'previous_value': previous_value, **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]:
|
||||
@@ -235,9 +346,20 @@ def patch_line_field(*, user_id: int, case_no: str, line_key: str, field_id: str
|
||||
field = _require_field(case, field_id, 'line')
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
target = _find_line(lines, line_key)
|
||||
previous_value = _current_value(target, field_id)
|
||||
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})
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='line_field_changed',
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'field_id': field_id,
|
||||
'previous_value': previous_value,
|
||||
**change,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
|
||||
@@ -277,4 +399,4 @@ def validate_draft(*, user_id: int, case_no: str, expected_draft_version: 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={})
|
||||
return _record_change(case, actor_id=user_id, event_type='draft_validated', operation={}, validate=True)
|
||||
@@ -39,6 +39,113 @@ def _safe_bbox(value: Any) -> dict[str, float] | None:
|
||||
return bbox
|
||||
|
||||
|
||||
def _frozen_page_dimensions(case: ShippingOrderReviewCase, page_no: int) -> tuple[float, float] | None:
|
||||
"""从当前 Run 的冻结版面快照读取页面尺寸,拒绝回读可变 PDF 布局。"""
|
||||
snapshot = case.run.input_snapshot_json if isinstance(case.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(case.document_id):
|
||||
continue
|
||||
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page = pages.get(str(page_no)) if isinstance(pages.get(str(page_no)), dict) else {}
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
return (width, height) if width > 0 and height > 0 else None
|
||||
return None
|
||||
|
||||
|
||||
def _frozen_document_layout(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""返回当前 PDF 的冻结布局快照;禁止查询可变 Document 版面版本。"""
|
||||
snapshot = case.run.input_snapshot_json if isinstance(case.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(case.document_id):
|
||||
layout = document.get('layout_snapshot')
|
||||
return layout if isinstance(layout, dict) else {}
|
||||
return {}
|
||||
|
||||
|
||||
def _frozen_cell_coordinate(
|
||||
case: ShippingOrderReviewCase, observation: dict[str, Any],
|
||||
) -> tuple[int | None, dict[str, float] | None, str | None]:
|
||||
"""按冻结 table_id/cell_id 反查明细单元格 bbox,缺失时只返回空而不猜测。"""
|
||||
table_id = str(observation.get('table_id') or '').strip()
|
||||
cell_id = str(observation.get('cell_id') or '').strip()
|
||||
if not table_id or not cell_id:
|
||||
return None, None, None
|
||||
candidate = _frozen_document_layout(case).get('layout_candidate')
|
||||
if not isinstance(candidate, dict):
|
||||
return None, None, None
|
||||
for page in candidate.get('pages') or []:
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
try:
|
||||
page_no = int(page.get('page_no'))
|
||||
width, height = float(page.get('width')), float(page.get('height'))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if page_no < 1 or width <= 0 or height <= 0:
|
||||
continue
|
||||
for table in page.get('tables') or []:
|
||||
if not isinstance(table, dict) or str(table.get('table_id') or '') != table_id:
|
||||
continue
|
||||
for row in table.get('rows') or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
for cell in row.get('cells') or []:
|
||||
if not isinstance(cell, dict) or str(cell.get('cell_id') or '') != cell_id:
|
||||
continue
|
||||
bbox = cell.get('bbox') if isinstance(cell.get('bbox'), dict) else {}
|
||||
try:
|
||||
normalized = {
|
||||
'x0': float(bbox['x0']) / width,
|
||||
'y0': float(bbox['y0']) / height,
|
||||
'x1': float(bbox['x1']) / width,
|
||||
'y1': float(bbox['y1']) / height,
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return page_no, None, None
|
||||
return page_no, _safe_bbox(normalized), 'frozen_layout_cell'
|
||||
return None, None, None
|
||||
|
||||
|
||||
def _layout_coordinate_evidence(
|
||||
case: ShippingOrderReviewCase, observation: dict[str, Any],
|
||||
) -> tuple[int | None, dict[str, float] | None, str | None]:
|
||||
"""将冻结的绝对坐标证据转为审阅器可绘制的归一化页内 bbox。"""
|
||||
raw = observation.get('layout_evidence') if isinstance(observation.get('layout_evidence'), dict) else {}
|
||||
try:
|
||||
page_no = int(raw.get('page_no'))
|
||||
except (TypeError, ValueError):
|
||||
return None, None, None
|
||||
if page_no < 1:
|
||||
return None, None, None
|
||||
source = str(raw.get('source') or '')[:64] or None
|
||||
dimensions = _frozen_page_dimensions(case, page_no)
|
||||
value_bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None
|
||||
if dimensions is None or value_bbox is None:
|
||||
return page_no, None, source
|
||||
width, height = dimensions
|
||||
try:
|
||||
normalized = {
|
||||
'x0': float(value_bbox['x0']) / width,
|
||||
'y0': float(value_bbox['y0']) / height,
|
||||
'x1': float(value_bbox['x1']) / width,
|
||||
'y1': float(value_bbox['y1']) / height,
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return page_no, None, source
|
||||
return page_no, _safe_bbox(normalized), source
|
||||
|
||||
|
||||
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 {}
|
||||
@@ -56,6 +163,8 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
for index, observation in enumerate(field.get('observations') or []):
|
||||
if not isinstance(observation, dict):
|
||||
continue
|
||||
coordinate_page, coordinate_bbox, coordinate_source = _layout_coordinate_evidence(case, observation)
|
||||
cell_page, cell_bbox, cell_source = _frozen_cell_coordinate(case, observation)
|
||||
page_no = observation.get('page_no')
|
||||
try:
|
||||
page = int(page_no) if page_no is not None else None
|
||||
@@ -69,11 +178,11 @@ def _observations(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
'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,
|
||||
'page_no': coordinate_page or cell_page or 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],
|
||||
'bbox': coordinate_bbox or cell_bbox or _safe_bbox(observation.get('normalized_bbox') or observation.get('bbox')),
|
||||
'source': coordinate_source or cell_source or str(observation.get('source') or 'machine_extraction')[:64],
|
||||
})
|
||||
return items
|
||||
|
||||
|
||||
@@ -116,4 +116,10 @@ def serialize_review_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
'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}
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
# 已被新版识别替代的 Run 不可继续编辑,前端据此跳转而非渲染空白旧 Case。
|
||||
'superseded_by_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
|
||||
'summary': counts,
|
||||
'items': items,
|
||||
}
|
||||
@@ -11,6 +11,8 @@ from __future__ import annotations
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
@@ -23,6 +25,43 @@ from app.models import (
|
||||
)
|
||||
|
||||
|
||||
def _restore_machine_field_source_case(field: Any) -> bool:
|
||||
"""以坐标证据的原始引文修正机器文本大小写,不改写人工值或类型化字段。
|
||||
|
||||
历史坐标抽取曾在上游将部分字符串转小写;`quote` 是同一 PDF 的原文证据,
|
||||
仅当两者忽略大小写和空白后完全相同才可安全恢复展示值。
|
||||
"""
|
||||
if not isinstance(field, dict):
|
||||
return False
|
||||
observations = field.get('observations') if isinstance(field.get('observations'), list) else []
|
||||
changed = False
|
||||
for observation in observations:
|
||||
if not isinstance(observation, dict):
|
||||
continue
|
||||
value, quote = observation.get('value'), observation.get('quote')
|
||||
if not isinstance(value, str) or not isinstance(quote, str):
|
||||
continue
|
||||
source = ' '.join(value.split())
|
||||
original = ' '.join(quote.split())
|
||||
if source and original and source.casefold() == original.casefold() and source != original:
|
||||
observation['value'] = quote
|
||||
changed = True
|
||||
return changed
|
||||
|
||||
|
||||
def _restore_machine_source_case(header: dict[str, Any], lines: list[dict[str, Any]]) -> bool:
|
||||
"""修复现有机器快照的原文大小写;只遍历机器层,绝不触碰人工覆盖层。"""
|
||||
fields = list(header.get('machine_fields') or []) if isinstance(header, dict) else []
|
||||
for line in lines:
|
||||
if isinstance(line, dict):
|
||||
fields.extend(line.get('machine_fields') or [])
|
||||
changed = False
|
||||
for field in fields:
|
||||
# Do not use any(generator): its short-circuit would leave later fields uncorrected.
|
||||
changed = _restore_machine_field_source_case(field) or changed
|
||||
return changed
|
||||
|
||||
|
||||
def _is_pdf_unit(run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit) -> bool:
|
||||
"""仅为冻结快照中的 PDF 文档创建 Case,邮件关系单元不属于人工订单复核。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
@@ -44,10 +83,30 @@ def _single_candidate_id(run: ShippingOrderExtractionRun, unit: ShippingOrderExt
|
||||
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)]
|
||||
def _machine_orders_for_unit(
|
||||
run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""读取当前 PDF 的最终机器订单,优先使用完成合并后的 Run 结果。
|
||||
|
||||
Worker 会在邮件正文补充事实合并后把最终订单写入 Run,而 Unit 可保留合并前中间
|
||||
结果。复核草稿必须按 primary_document_id 读取最终订单,避免页面显示空白机器值。
|
||||
"""
|
||||
result = run.execution_result_json if isinstance(run.execution_result_json, dict) else {}
|
||||
final_orders = [
|
||||
item for item in result.get('orders') or []
|
||||
if isinstance(item, dict) and int(item.get('primary_document_id') or 0) == int(unit.document_id)
|
||||
]
|
||||
if final_orders:
|
||||
return final_orders
|
||||
unit_result = unit.result_json if isinstance(unit.result_json, dict) else {}
|
||||
return [item for item in unit_result.get('orders') or [] if isinstance(item, dict)]
|
||||
|
||||
|
||||
def _initial_draft_payload(
|
||||
run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit,
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""把当前 PDF 的唯一最终机器订单复制为草稿初值;无或多订单保留问题。"""
|
||||
orders = _machine_orders_for_unit(run, unit)
|
||||
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 []
|
||||
@@ -62,9 +121,19 @@ def _initial_draft_payload(unit: ShippingOrderExtractionUnit) -> tuple[dict[str,
|
||||
{'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)
|
||||
]
|
||||
_restore_machine_source_case(header, lines)
|
||||
return header, lines, issues
|
||||
|
||||
|
||||
def _can_backfill_machine_draft(case: ShippingOrderReviewCase) -> bool:
|
||||
"""仅回填从旧中间结果生成的空白草稿,绝不覆盖人工编辑。"""
|
||||
draft = case.current_draft
|
||||
if draft is None or draft.header_values_json or draft.lines_json:
|
||||
return False
|
||||
issues = list(draft.issue_summary_json or [])
|
||||
return any(str(item.get('code') or '') == 'machine_order_unavailable' for item in issues if isinstance(item, dict))
|
||||
|
||||
|
||||
def ensure_run_review_cases(*, run: ShippingOrderExtractionRun) -> list[ShippingOrderReviewCase]:
|
||||
"""为 Run 的每个 PDF Unit 幂等初始化唯一 Case 和 Draft,供 Worker 结果持久化后调用。"""
|
||||
plan = run.extraction_plan
|
||||
@@ -76,9 +145,35 @@ def ensure_run_review_cases(*, run: ShippingOrderExtractionRun) -> list[Shipping
|
||||
continue
|
||||
case = ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).first()
|
||||
if case is not None:
|
||||
if _can_backfill_machine_draft(case):
|
||||
header, lines, issues = _initial_draft_payload(run, unit)
|
||||
if header or lines:
|
||||
# 旧 Case 在 Unit 尚未写入最终结果时已初始化;只修复这种空白机器草稿。
|
||||
case.current_draft.header_values_json = header
|
||||
case.current_draft.lines_json = lines
|
||||
case.current_draft.issue_summary_json = issues
|
||||
case.current_draft.change_reason_json = {
|
||||
'source': 'machine_result_backfill',
|
||||
}
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='machine_result_backfilled',
|
||||
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
elif _restore_machine_source_case(
|
||||
case.current_draft.header_values_json or {}, list(case.current_draft.lines_json or []),
|
||||
):
|
||||
# JSON columns do not detect nested dict mutations automatically.
|
||||
flag_modified(case.current_draft, 'header_values_json')
|
||||
flag_modified(case.current_draft, 'lines_json')
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='machine_source_case_restored',
|
||||
draft_version=int(case.current_draft.draft_version), actor_user_id=None,
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
cases.append(case)
|
||||
continue
|
||||
header, lines, issues = _initial_draft_payload(unit)
|
||||
header, lines, issues = _initial_draft_payload(run, unit)
|
||||
candidate_id = _single_candidate_id(run, unit)
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no=f'SORC-{uuid.uuid4().hex[:16].upper()}',
|
||||
@@ -102,6 +197,9 @@ def ensure_run_review_cases(*, run: ShippingOrderExtractionRun) -> list[Shipping
|
||||
))
|
||||
cases.append(case)
|
||||
db.session.flush()
|
||||
# [STEP] 会话 PDF 工作项绑定:同会话多 PDF 各一条;重识别复用并切换当前版本。
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import bind_cases_for_run
|
||||
bind_cases_for_run(run=run, cases=cases)
|
||||
return cases
|
||||
|
||||
|
||||
|
||||
@@ -17,7 +17,11 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""按冻结字段类型与 normalizer 规范化候选值;类型错误抛稳定业务异常。"""
|
||||
"""按冻结字段类型解析候选值,同时保留原始文本大小写。
|
||||
|
||||
`uppercase_trim` / `lowercase_trim` 仅可用于比较、索引和规则匹配,不能改写
|
||||
PDF/邮件证据对应的业务展示值;否则料号、客户名称、地址和币种会偏离原文件。
|
||||
"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
@@ -52,10 +56,6 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
'Dynamic field value type is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
|
||||
) from exc
|
||||
text = str(value).strip()
|
||||
if normalizer == 'uppercase_trim':
|
||||
text = text.upper()
|
||||
elif normalizer == 'lowercase_trim':
|
||||
text = text.lower()
|
||||
if normalizer == 'reservation_id':
|
||||
text = validated_reservation_id(text) or ''
|
||||
if value_type == 'enum' and text not in set(config.get('enum_options') or []):
|
||||
|
||||
@@ -188,8 +188,10 @@ def _quote_supports_value(value: Any, config: dict[str, Any], quote: str) -> boo
|
||||
continue
|
||||
return False
|
||||
|
||||
normalized_quote = ' '.join(quote.upper().split())
|
||||
normalized_value = ' '.join(str(_json_value(value)).upper().split())
|
||||
# Text evidence is case-sensitive in Schema v1. Whitespace variation in a PDF
|
||||
# remains harmless, but ``abc`` must not prove the distinct value ``ABC``.
|
||||
normalized_quote = ' '.join(quote.split())
|
||||
normalized_value = ' '.join(str(_json_value(value)).split())
|
||||
return bool(normalized_value) and normalized_value in normalized_quote
|
||||
|
||||
|
||||
@@ -203,10 +205,25 @@ def _verified_observations(
|
||||
for item in items:
|
||||
if not isinstance(item, dict) or not str(item.get('document_id') or '').isdigit():
|
||||
continue
|
||||
document = documents.get(int(item['document_id']))
|
||||
document_id = int(item['document_id'])
|
||||
document = documents.get(document_id)
|
||||
value = _normalize(item.get('value'), config)
|
||||
quote = str(item.get('quote') or '').strip()
|
||||
if document is None or value is None or not _validate(value, config):
|
||||
if value is None or not _validate(value, config):
|
||||
continue
|
||||
supplement_evidence = item.get('email_supplement_evidence')
|
||||
if isinstance(supplement_evidence, dict):
|
||||
verified_supplement = _verified_email_supplement_observation(
|
||||
document_id=document_id,
|
||||
documents=documents,
|
||||
value=value,
|
||||
quote=quote,
|
||||
evidence=supplement_evidence,
|
||||
)
|
||||
if verified_supplement is not None:
|
||||
verified.append(verified_supplement)
|
||||
continue
|
||||
if document is None:
|
||||
continue
|
||||
layout_evidence = item.get('layout_evidence') if raw.get('_hxops_order_field_evidence') is True else None
|
||||
if isinstance(layout_evidence, dict) and _valid_coordinate_evidence(layout_evidence):
|
||||
@@ -242,6 +259,41 @@ def _verified_observations(
|
||||
return verified
|
||||
|
||||
|
||||
def _verified_email_supplement_observation(
|
||||
*, document_id: int, documents: dict[int, ShippingNoticeDocument], value: Any,
|
||||
quote: str, evidence: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""验证服务端邮件表合并证据,禁止把任意邮件值伪装成当前 PDF 字段。"""
|
||||
try:
|
||||
table_index = int(evidence.get('table_index'))
|
||||
row_index = int(evidence.get('row_index'))
|
||||
column_index = int(evidence.get('column_index'))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
cell_id = str(evidence.get('cell_id') or '').strip()
|
||||
if table_index < 0 or row_index < 0 or column_index < 0 or not cell_id.startswith('email-supplement:'):
|
||||
return None
|
||||
intake_ids = {int(document.intake_id) for document in documents.values()}
|
||||
document = db.session.get(ShippingNoticeDocument, document_id)
|
||||
if (
|
||||
document is None
|
||||
or int(document.intake_id) not in intake_ids
|
||||
or str(document.document_type or '') != 'email_body'
|
||||
or not quote
|
||||
or not _quote_supports_value(value, {'value_type': 'string'}, quote)
|
||||
):
|
||||
return None
|
||||
return {
|
||||
'value': value, 'document': document, 'quote': quote, 'confidence': 1.0,
|
||||
'source_type': 'email_body_table', 'extractor': 'email_allocation_table',
|
||||
'evidence_ref': f'document:{document_id}:cell:{cell_id}',
|
||||
'evidence_metadata': {
|
||||
'kind': 'email_supplement_table_cell', 'table_index': table_index,
|
||||
'row_index': row_index, 'column_index': column_index, 'cell_id': cell_id,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool:
|
||||
"""只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。"""
|
||||
return (
|
||||
|
||||
@@ -41,8 +41,10 @@ class TableHeaderContract:
|
||||
|
||||
|
||||
def normalize_table_header(value: Any) -> str:
|
||||
"""以 NFKC、大小写折叠和标点空白折叠生成稳定表头比较键。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip().casefold()
|
||||
"""以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。"""
|
||||
# Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are
|
||||
# distinct configured labels, so a permissive match cannot silently bind a column.
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip()
|
||||
text = re.sub(r"[^\w\u4e00-\u9fff]+", ' ', text, flags=re.UNICODE)
|
||||
return re.sub(r'[_\s]+', ' ', text).strip()
|
||||
|
||||
@@ -75,7 +77,9 @@ def compile_table_header_contract(definition: dict[str, Any]) -> TableHeaderCont
|
||||
normalized = normalize_table_header(candidate)
|
||||
if not normalized:
|
||||
continue
|
||||
if field_code == 'reservation_id' and normalized in RESERVATION_ID_FORBIDDEN_HEADERS:
|
||||
# This is a safety denylist, not a business-field match. Keep it
|
||||
# case-insensitive so changing capitalization cannot bypass it.
|
||||
if field_code == 'reservation_id' and normalized.casefold() in RESERVATION_ID_FORBIDDEN_HEADERS:
|
||||
forbidden.append(str(candidate))
|
||||
continue
|
||||
previous = mapping.get(normalized)
|
||||
|
||||
@@ -65,6 +65,21 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
if len(candidates) == 1 or len(reservations) == 1:
|
||||
selected = candidates
|
||||
relation = 'po_fallback'
|
||||
if not selected and not candidates:
|
||||
# 邮件正文的 PO 可能被上游人工录入错误;仅唯一精确 MPN 才能安全补证。
|
||||
mpn_matches = [
|
||||
row for row in rows
|
||||
if str(row.get('mpn') or '').strip().upper() in mpn_values
|
||||
]
|
||||
distinct_matches = {
|
||||
tuple(str(row.get(field) or '').strip() for field in (
|
||||
'po_number', 'mpn', 'reservation_id', 'allocation_id', 'source_type',
|
||||
)): row
|
||||
for row in mpn_matches
|
||||
}
|
||||
if len(distinct_matches) == 1:
|
||||
selected = list(distinct_matches.values())
|
||||
relation = 'mpn_fallback'
|
||||
if not selected:
|
||||
if candidates:
|
||||
order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'})
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
"""
|
||||
services/shipping_notice/progress_audit_contract.py
|
||||
|
||||
用途:冻结货代发货通知进度审计与「会话 PDF 工作项」领域契约词典。
|
||||
依赖:无外部 IO;被 progress / audit / session work item / projection / OpenAPI 与测试引用。
|
||||
逻辑:状态、用户可见阶段、健康提示、取消语义、会话工作项生命周期、审计事件字典、
|
||||
快照白名单与敏感键黑名单的唯一代码源;UI 与 Worker 行为变更在后续阶段实现,
|
||||
本模块只冻结名称与规则,禁止运行时猜测。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Final
|
||||
|
||||
# 进度映射版本;投影与 i18n 必须与此对齐,禁止前端私自发明阶段码。
|
||||
PROGRESS_MAPPING_VERSION: Final[str] = 'shipping-order-progress-v3'
|
||||
|
||||
# 审计默认保留期(天);默认三年,可由环境变量覆盖(阶段 4 留存 Job 读取)。
|
||||
AUDIT_RETENTION_DAYS: Final[int] = 365 * 3
|
||||
|
||||
# 会话未关闭 PDF 工作项上限;超出由阶段 1 写路径拒绝,前端不得自行截断真相。
|
||||
MAX_OPEN_SESSION_WORK_ITEMS: Final[int] = 50
|
||||
|
||||
# 会话 PDF 工作项生命周期(真相源);closed 以外均为未关闭。
|
||||
SESSION_WORK_ITEM_LIFECYCLE_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'pending_review',
|
||||
'extracting',
|
||||
'reparse_failed',
|
||||
'closed',
|
||||
})
|
||||
|
||||
SESSION_WORK_ITEM_CLOSED_REASONS: Final[frozenset[str]] = frozenset({
|
||||
'confirmed',
|
||||
'non_order',
|
||||
'user_cancelled',
|
||||
'admin_terminated',
|
||||
})
|
||||
|
||||
# 会话工作项 / 版本切换 / 人工复核 / 监管相关审计事件字典(阶段 1+ 落库)。
|
||||
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'session_work_item_created',
|
||||
'document_extraction_started',
|
||||
'document_reparse_requested',
|
||||
'document_version_replaced',
|
||||
'document_reparse_failed',
|
||||
'document_previous_version_restored',
|
||||
'review_draft_changed',
|
||||
'review_confirmed',
|
||||
'review_marked_non_order',
|
||||
'review_marked_quality_issue',
|
||||
'review_manual_draft_created',
|
||||
'review_replacement_intake_created',
|
||||
'review_replacement_reparse_started',
|
||||
'session_work_item_cancelled',
|
||||
'admin_impersonated_review_action',
|
||||
'review_confirmation_revoked',
|
||||
'audit_access',
|
||||
'shipping_resource_accessed',
|
||||
})
|
||||
|
||||
# Run 业务状态(真相源);cancellation_requested 不是 Run.status,而是取消请求元数据投影。
|
||||
RUN_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'queued',
|
||||
'processing',
|
||||
'completed',
|
||||
'partially_completed',
|
||||
'review_required',
|
||||
'failed',
|
||||
'cancelled',
|
||||
})
|
||||
|
||||
# Unit 业务状态(真相源);执行中取消请求不伪造即时 cancelled。
|
||||
UNIT_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'pending',
|
||||
'routing',
|
||||
'matching_profile',
|
||||
'extracting',
|
||||
'merging_supplement',
|
||||
'candidate_ready',
|
||||
'review_required',
|
||||
'failed',
|
||||
'cancelled',
|
||||
})
|
||||
|
||||
# 用户可见阶段;由后端投影,前端只做 i18n,禁止自行重算。
|
||||
USER_VISIBLE_STAGES: Final[tuple[str, ...]] = (
|
||||
'pending',
|
||||
'document_queued',
|
||||
'waiting_layout',
|
||||
'layout_parsing_started',
|
||||
'routing',
|
||||
'matching_profile',
|
||||
'extracting',
|
||||
'merging_supplement',
|
||||
'candidate_ready',
|
||||
'review_required',
|
||||
'technical_retrying',
|
||||
'failed',
|
||||
'cancellation_requested',
|
||||
'cancelled',
|
||||
'completed',
|
||||
)
|
||||
|
||||
# 健康提示码;阈值由后端统一计算,前端不得用本地时钟臆造。
|
||||
HEALTH_TIP_CODES: Final[frozenset[str]] = frozenset({
|
||||
'processing_slow', # 连续 60 秒无新活动
|
||||
'queue_backlog', # 排队超过 5 分钟
|
||||
'processing_attention', # 处理超过 30 分钟
|
||||
})
|
||||
|
||||
HEALTH_TIP_THRESHOLDS_SECONDS: Final[dict[str, int]] = {
|
||||
'processing_slow': 60,
|
||||
'queue_backlog': 5 * 60,
|
||||
'processing_attention': 30 * 60,
|
||||
}
|
||||
|
||||
# 取消作用域与权限语义(阶段 1 实现校验)。
|
||||
CANCEL_SCOPES: Final[frozenset[str]] = frozenset({'run', 'unit'})
|
||||
CANCEL_ACTOR_TYPES: Final[frozenset[str]] = frozenset({'user', 'admin', 'system'})
|
||||
|
||||
# 新增/扩展的用户态进度事件;与既有 WORKSPACE_EVENT_CODES 合并后生效。
|
||||
CANCEL_PROGRESS_EVENT_CODES: Final[frozenset[str]] = frozenset({
|
||||
'cancellation_requested',
|
||||
'cancellation_completed',
|
||||
'unit_cancelled',
|
||||
})
|
||||
|
||||
# 工作台可用动作扩展(阶段 1/2 下发);既有动作保持兼容。
|
||||
WORKSPACE_AVAILABLE_ACTIONS: Final[frozenset[str]] = frozenset({
|
||||
'view_details',
|
||||
'enter_manual_review',
|
||||
'retry_failed_attachments',
|
||||
'refresh_status',
|
||||
'cancel_run',
|
||||
'cancel_unit',
|
||||
'view_evidence',
|
||||
'review_candidate',
|
||||
'manual_review',
|
||||
})
|
||||
|
||||
# 审计快照与元数据禁止键(大小写不敏感);原件只允许 FileAsset 标识关联。
|
||||
AUDIT_FORBIDDEN_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'api_key',
|
||||
'api_base_url',
|
||||
'authorization',
|
||||
'body',
|
||||
'client_ip',
|
||||
'content',
|
||||
'document_text',
|
||||
'email_body',
|
||||
'minio',
|
||||
'object_key',
|
||||
'object_url',
|
||||
'password',
|
||||
'prompt',
|
||||
'provider_config',
|
||||
'quote',
|
||||
'raw_content',
|
||||
'raw_output',
|
||||
'secret',
|
||||
'token',
|
||||
'url',
|
||||
'user_agent',
|
||||
})
|
||||
|
||||
# 审计前后快照允许的顶层业务键白名单;未列出的键不得进入 snapshot。
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'status',
|
||||
'phase',
|
||||
'reason_code',
|
||||
'error_code',
|
||||
'attempt_count',
|
||||
'retry_status',
|
||||
'progress_version',
|
||||
'activity_version',
|
||||
'current_stage_code',
|
||||
'user_visible_stage',
|
||||
'cancellation_requested',
|
||||
'unit_count',
|
||||
'document_count',
|
||||
'completed_count',
|
||||
'failed_count',
|
||||
'review_required_count',
|
||||
'cancelled_count',
|
||||
'schema_version_id',
|
||||
'schema_checksum',
|
||||
'profile_code',
|
||||
'profile_version',
|
||||
'profile_checksum',
|
||||
'policy_version',
|
||||
'policy_checksum',
|
||||
'queue_position',
|
||||
'selection_batch',
|
||||
# 会话 PDF 工作项 / 版本指针(禁止字段正文与附件 URL)。
|
||||
'lifecycle_status',
|
||||
'closed_reason',
|
||||
'lock_version',
|
||||
'current_version_no',
|
||||
'current_run_no',
|
||||
'current_case_no',
|
||||
'previous_run_no',
|
||||
'previous_case_no',
|
||||
'root_document_id',
|
||||
'current_document_id',
|
||||
'session_item_no',
|
||||
'item_no',
|
||||
'owner_user_id',
|
||||
'conversation_id',
|
||||
'reparse_failure_stage',
|
||||
'restore_target_case_no',
|
||||
'admin_action',
|
||||
'revocation_blocked',
|
||||
'inventory_matched',
|
||||
'changed_field_paths',
|
||||
'draft_version',
|
||||
'validation_blocking_count',
|
||||
'validation_warning_count',
|
||||
'field_id',
|
||||
'line_key',
|
||||
'previous_value',
|
||||
'new_value',
|
||||
'value_source',
|
||||
'disposition',
|
||||
'confirmed_task_no',
|
||||
'task_no',
|
||||
'replacement_intake_no',
|
||||
'successor_run_no',
|
||||
})
|
||||
|
||||
# 四语言 i18n key 清单(阶段 2 补齐文案;此处仅冻结路径,禁止前端硬编码)。
|
||||
I18N_KEY_INVENTORY: Final[tuple[str, ...]] = (
|
||||
'chat.shippingOrderExtractionUserStage.pending',
|
||||
'chat.shippingOrderExtractionUserStage.document_queued',
|
||||
'chat.shippingOrderExtractionUserStage.waiting_layout',
|
||||
'chat.shippingOrderExtractionUserStage.layout_parsing_started',
|
||||
'chat.shippingOrderExtractionUserStage.routing',
|
||||
'chat.shippingOrderExtractionUserStage.matching_profile',
|
||||
'chat.shippingOrderExtractionUserStage.extracting',
|
||||
'chat.shippingOrderExtractionUserStage.merging_supplement',
|
||||
'chat.shippingOrderExtractionUserStage.candidate_ready',
|
||||
'chat.shippingOrderExtractionUserStage.review_required',
|
||||
'chat.shippingOrderExtractionUserStage.technical_retrying',
|
||||
'chat.shippingOrderExtractionUserStage.failed',
|
||||
'chat.shippingOrderExtractionUserStage.cancellation_requested',
|
||||
'chat.shippingOrderExtractionUserStage.cancelled',
|
||||
'chat.shippingOrderExtractionUserStage.completed',
|
||||
'chat.shippingOrderExtractionHealthTip.processing_slow',
|
||||
'chat.shippingOrderExtractionHealthTip.queue_backlog',
|
||||
'chat.shippingOrderExtractionHealthTip.processing_attention',
|
||||
'chat.shippingOrderExtractionAction.refresh_status',
|
||||
'chat.shippingOrderExtractionAction.cancel_run',
|
||||
'chat.shippingOrderExtractionAction.cancel_unit',
|
||||
'chat.shippingOrderExtractionCancel.confirmTitle',
|
||||
'chat.shippingOrderExtractionCancel.confirmImpact',
|
||||
'chat.shippingOrderExtractionCancel.reasonRequired',
|
||||
'chat.shippingOrderExtractionCancel.reasonOptional',
|
||||
'chat.shippingOrderExtractionActivity.cancellation_requested',
|
||||
'chat.shippingOrderExtractionActivity.cancellation_completed',
|
||||
'chat.shippingOrderExtractionActivity.unit_cancelled',
|
||||
'errors.SHIPPING_NOTICE.CANCEL_FORBIDDEN',
|
||||
'errors.SHIPPING_NOTICE.CANCEL_REASON_REQUIRED',
|
||||
'errors.SHIPPING_NOTICE.CANCEL_NOT_ACTIVE',
|
||||
'errors.SHIPPING_NOTICE.CANCEL_CONFLICT',
|
||||
'errors.SHIPPING_NOTICE.CANCEL_FEATURE_DISABLED',
|
||||
'errors.SHIPPING_NOTICE.AUDIT_EXPORT_FEATURE_DISABLED',
|
||||
'errors.SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
|
||||
'errors.SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN',
|
||||
'admin.shippingAudit.title',
|
||||
'admin.shippingAudit.export',
|
||||
'admin.shippingAudit.diff',
|
||||
)
|
||||
|
||||
|
||||
def is_forbidden_audit_key(key: str) -> bool:
|
||||
"""
|
||||
判断键名是否命中审计敏感黑名单。
|
||||
|
||||
核心逻辑:大小写不敏感精确匹配冻结集合。
|
||||
|
||||
Args:
|
||||
key: 元数据或快照字段名。
|
||||
|
||||
Returns:
|
||||
True 表示禁止写入审计表。
|
||||
"""
|
||||
return str(key or '').strip().lower() in AUDIT_FORBIDDEN_KEYS
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
services/shipping_notice/progress_feature_flags.py
|
||||
|
||||
用途:处理进度细化与全链路审计的灰度/回滚功能开关及审计保留期读取。
|
||||
依赖:tool_common.cfg_bool/cfg_int、Flask config、progress_audit_contract 默认常量。
|
||||
逻辑:取消 API/投影动作、进度 UI v3 健康提示、管理员审计导出分别受控;审计保留天数由
|
||||
SHIPPING_NOTICE_AUDIT_RETENTION_DAYS 覆盖默认三年;关闭开关不删除已写审计事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.progress_audit_contract import AUDIT_RETENTION_DAYS
|
||||
from app.services.shipping_notice.tool_common import cfg_bool, cfg_int
|
||||
|
||||
|
||||
def progress_ui_v3_enabled() -> bool:
|
||||
"""是否启用新进度展示(健康提示、细化阶段文案依赖);默认开启。"""
|
||||
return cfg_bool('SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED', True)
|
||||
|
||||
|
||||
def order_extraction_cancel_enabled() -> bool:
|
||||
"""是否允许 Run/Unit 取消请求;关闭后投影不暴露取消动作且 API 拒绝。"""
|
||||
return cfg_bool('SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED', True)
|
||||
|
||||
|
||||
def audit_export_enabled() -> bool:
|
||||
"""是否允许管理员审计导出;关闭后 list/detail 仍可读(诊断),导出拒绝。"""
|
||||
return cfg_bool('SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED', True)
|
||||
|
||||
|
||||
def audit_retention_days() -> int:
|
||||
"""
|
||||
读取货代统一审计默认保留天数。
|
||||
|
||||
核心逻辑:优先 Flask config / 环境变量 SHIPPING_NOTICE_AUDIT_RETENTION_DAYS;
|
||||
缺失或非法时回退 progress_audit_contract 默认 1095 天。
|
||||
"""
|
||||
return cfg_int('SHIPPING_NOTICE_AUDIT_RETENTION_DAYS', AUDIT_RETENTION_DAYS, min_value=1)
|
||||
|
||||
|
||||
def progress_feature_flags_payload() -> dict[str, bool]:
|
||||
"""供工作台投影下发的开关快照;前端不得本地臆造。"""
|
||||
return {
|
||||
'progress_ui_v3': progress_ui_v3_enabled(),
|
||||
'cancel_enabled': order_extraction_cancel_enabled(),
|
||||
'audit_export_enabled': audit_export_enabled(),
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
"""
|
||||
services/shipping_notice/session_pdf_work_item_projection.py
|
||||
|
||||
用途:会话 PDF 工作台聚合读模型投影(未关闭/已关闭分组、版本摘要、统计)。
|
||||
依赖:ShippingSessionPdfWorkItem、ShippingNoticeDocument、ShippingOrderReviewCase、
|
||||
ShippingOrderExtractionRun、FileAsset。
|
||||
逻辑:由 workspace/admin API 调用;版本历史严格限定会话 + 重识别谱系;
|
||||
管理员投影额外返回 terminate/revoke 动作。前端不得按最新 Run 自行拼装列表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingSessionPdfWorkItem,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import MAX_OPEN_SESSION_WORK_ITEMS
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""UTC datetime → ISO8601 Z。"""
|
||||
if value is None:
|
||||
return None
|
||||
return value.isoformat() + ('Z' if value.tzinfo is None else '')
|
||||
|
||||
|
||||
def _document_filename(document_id: int | None) -> str | None:
|
||||
"""读取 Document 文件名;缺失时返回 None。"""
|
||||
if not document_id:
|
||||
return None
|
||||
document = ShippingNoticeDocument.query.get(int(document_id))
|
||||
if document is None:
|
||||
return None
|
||||
name = str(document.filename or '').strip()
|
||||
if name:
|
||||
return name
|
||||
if document.asset_id:
|
||||
asset = FileAsset.query.get(int(document.asset_id))
|
||||
if asset is not None:
|
||||
return str(asset.original_filename or asset.filename or '').strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def _collect_lineage_run_ids(item: ShippingSessionPdfWorkItem) -> set[int]:
|
||||
"""
|
||||
收集工作项真实版本谱系的 Run ID。
|
||||
|
||||
核心逻辑:从 current_run 向上沿 reparse_of_run_id 追溯祖先(并收集替换文档);
|
||||
再向下收集同会话且 review_reparse 文档落在谱系文档集内的后继 Run。
|
||||
"""
|
||||
docs = {int(item.root_document_id), int(item.current_document_id)}
|
||||
run_ids: set[int] = set()
|
||||
|
||||
# [STEP 1] 向上追溯祖先链,并收集路径上的替换文档 ID。
|
||||
cursor = int(item.current_run_id) if item.current_run_id else None
|
||||
seen: set[int] = set()
|
||||
while cursor and cursor not in seen:
|
||||
seen.add(cursor)
|
||||
run_ids.add(cursor)
|
||||
run = ShippingOrderExtractionRun.query.get(cursor)
|
||||
if run is None:
|
||||
break
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict):
|
||||
marker_doc = int(marker.get('document_id') or 0)
|
||||
if marker_doc:
|
||||
docs.add(marker_doc)
|
||||
cursor = int(run.reparse_of_run_id) if run.reparse_of_run_id else None
|
||||
|
||||
# [STEP 2] 向下扩展后继;仅纳入同会话且文档属于本工作项谱系的重识别分支。
|
||||
frontier = list(run_ids)
|
||||
while frontier:
|
||||
parent_id = frontier.pop()
|
||||
children = ShippingOrderExtractionRun.query.filter_by(reparse_of_run_id=int(parent_id)).all()
|
||||
for child in children:
|
||||
child_id = int(child.id)
|
||||
if child_id in run_ids:
|
||||
continue
|
||||
if str(child.conversation_id or '') != str(item.conversation_id or ''):
|
||||
continue
|
||||
marker = (child.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict):
|
||||
marker_doc = int(marker.get('document_id') or 0)
|
||||
if marker_doc and marker_doc not in docs:
|
||||
continue
|
||||
if marker_doc:
|
||||
docs.add(marker_doc)
|
||||
run_ids.add(child_id)
|
||||
frontier.append(child_id)
|
||||
|
||||
return run_ids
|
||||
|
||||
|
||||
def _collect_lineage_document_ids(
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
lineage_run_ids: set[int],
|
||||
) -> set[int]:
|
||||
"""
|
||||
收集工作项版本谱系涉及的全部 Document ID(含多次替换的中间版本)。
|
||||
|
||||
核心逻辑:根/当前 + 谱系 Run 的 review_reparse.document_id;
|
||||
不把同 Run 其他 PDF 的 Case.document_id 一并纳入,避免兄弟文件污染。
|
||||
"""
|
||||
docs = {int(item.root_document_id), int(item.current_document_id)}
|
||||
if not lineage_run_ids:
|
||||
return docs
|
||||
runs = ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.id.in_(lineage_run_ids),
|
||||
).all()
|
||||
for run in runs:
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict):
|
||||
marker_doc = int(marker.get('document_id') or 0)
|
||||
if marker_doc:
|
||||
docs.add(marker_doc)
|
||||
return docs
|
||||
|
||||
|
||||
def _assign_version_numbers(
|
||||
cases: list[ShippingOrderReviewCase],
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
) -> dict[int, int]:
|
||||
"""
|
||||
按创建时间升序分配真实版本号,并与工作项 current_version_no 对齐。
|
||||
|
||||
核心逻辑:当前 Case 固定为 item.current_version_no;更早 Case 依次递减,
|
||||
禁止按「查询结果下标」倒推导致中间版本丢失后错配。
|
||||
"""
|
||||
if not cases:
|
||||
return {}
|
||||
ordered = sorted(
|
||||
cases,
|
||||
key=lambda case: (case.created_at or datetime.min, int(case.id)),
|
||||
)
|
||||
current_case_id = int(item.current_case_id) if item.current_case_id else None
|
||||
current_version = int(item.current_version_no or 1)
|
||||
current_idx = next(
|
||||
(index for index, case in enumerate(ordered) if int(case.id) == current_case_id),
|
||||
None,
|
||||
)
|
||||
if current_idx is None:
|
||||
return {int(case.id): index + 1 for index, case in enumerate(ordered)}
|
||||
# current_idx 对应 current_version;其前序为更小版本号。
|
||||
base = current_version - current_idx
|
||||
return {
|
||||
int(case.id): max(1, base + index)
|
||||
for index, case in enumerate(ordered)
|
||||
}
|
||||
|
||||
|
||||
def _available_actions(item: ShippingSessionPdfWorkItem, *, for_admin: bool = False) -> list[str]:
|
||||
"""
|
||||
按生命周期投影可用动作;前端不得本地发明。
|
||||
|
||||
Args:
|
||||
item: 工作项。
|
||||
for_admin: True 时附加监管台 terminate/revoke 动作。
|
||||
"""
|
||||
status = str(item.lifecycle_status or '')
|
||||
if status == 'closed':
|
||||
actions = ['view_version_history']
|
||||
if for_admin and item.closed_reason == 'confirmed':
|
||||
actions.append('admin_revoke_confirmation')
|
||||
return actions
|
||||
if status == 'extracting':
|
||||
actions = ['refresh_status', 'view_version_history']
|
||||
if for_admin:
|
||||
actions.append('admin_terminate')
|
||||
return actions
|
||||
actions = [
|
||||
'enter_manual_review',
|
||||
'view_version_history',
|
||||
'request_reparse',
|
||||
'mark_non_order',
|
||||
'cancel',
|
||||
]
|
||||
if status == 'reparse_failed':
|
||||
actions = [
|
||||
'enter_manual_review',
|
||||
'view_version_history',
|
||||
'request_reparse',
|
||||
'cancel',
|
||||
]
|
||||
if status == 'pending_review':
|
||||
# 质量异常/替换入口由复核页完整流程承载;面板提供重识别与关闭。
|
||||
actions.append('replace_file')
|
||||
if for_admin:
|
||||
actions.append('admin_terminate')
|
||||
return actions
|
||||
|
||||
|
||||
def serialize_session_work_item(
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
*,
|
||||
for_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单条会话 PDF 工作项摘要。
|
||||
|
||||
Args:
|
||||
item: ORM 工作项。
|
||||
for_admin: 监管台场景附加管理员动作。
|
||||
|
||||
Returns:
|
||||
前端工作台行模型。
|
||||
"""
|
||||
superseded = bool(item.current_version_no and int(item.current_version_no) > 1)
|
||||
return {
|
||||
'item_no': item.item_no,
|
||||
'conversation_id': item.conversation_id,
|
||||
'owner_user_id': int(item.owner_user_id),
|
||||
'root_document_id': int(item.root_document_id),
|
||||
'current_document_id': int(item.current_document_id),
|
||||
'current_document_filename': _document_filename(item.current_document_id),
|
||||
'current_run_id': int(item.current_run_id) if item.current_run_id else None,
|
||||
'current_run_no': item.current_run_no,
|
||||
'current_case_id': int(item.current_case_id) if item.current_case_id else None,
|
||||
'current_case_no': item.current_case_no,
|
||||
'current_version_no': int(item.current_version_no or 1),
|
||||
'lifecycle_status': item.lifecycle_status,
|
||||
'closed_reason': item.closed_reason,
|
||||
'closed_at': _iso(item.closed_at),
|
||||
'lock_version': int(item.lock_version or 1),
|
||||
'version_replaced': superseded,
|
||||
'available_actions': _available_actions(item, for_admin=for_admin),
|
||||
'created_at': _iso(item.created_at),
|
||||
'updated_at': _iso(item.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def list_session_work_item_versions(*, item: ShippingSessionPdfWorkItem) -> list[dict[str, Any]]:
|
||||
"""
|
||||
只读版本时间线:严格限定本会话 + 工作项重识别/替换谱系。
|
||||
|
||||
核心逻辑:纳入谱系全部 Document(含中间替换版本)的 Case;版本号按创建时间对齐
|
||||
current_version_no,禁止按结果下标倒推;禁止同属主其他会话的同 PDF Case 混入。
|
||||
"""
|
||||
lineage_run_ids = _collect_lineage_run_ids(item)
|
||||
if item.current_case_id is None and not lineage_run_ids:
|
||||
return []
|
||||
|
||||
lineage_docs = _collect_lineage_document_ids(item, lineage_run_ids)
|
||||
query = (
|
||||
ShippingOrderReviewCase.query
|
||||
.join(
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRun.id == ShippingOrderReviewCase.run_id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.owner_user_id == int(item.owner_user_id),
|
||||
ShippingOrderExtractionRun.conversation_id == str(item.conversation_id),
|
||||
ShippingOrderReviewCase.document_id.in_(lineage_docs),
|
||||
)
|
||||
)
|
||||
if lineage_run_ids:
|
||||
query = query.filter(ShippingOrderReviewCase.run_id.in_(lineage_run_ids))
|
||||
elif item.current_case_id:
|
||||
query = query.filter(ShippingOrderReviewCase.id == int(item.current_case_id))
|
||||
else:
|
||||
return []
|
||||
|
||||
cases = query.order_by(
|
||||
ShippingOrderReviewCase.created_at.desc(),
|
||||
ShippingOrderReviewCase.id.desc(),
|
||||
).all()
|
||||
# 首轮多 PDF Run:无 review_reparse 时只保留根文档;后继 Run 只保留 marker 目标文档。
|
||||
if lineage_run_ids:
|
||||
run_marker_docs: dict[int, int] = {}
|
||||
for run in ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.id.in_(lineage_run_ids),
|
||||
).all():
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
if isinstance(marker, dict) and int(marker.get('document_id') or 0):
|
||||
run_marker_docs[int(run.id)] = int(marker['document_id'])
|
||||
root_doc = int(item.root_document_id)
|
||||
cases = [
|
||||
case for case in cases
|
||||
if (
|
||||
int(case.document_id) == run_marker_docs[int(case.run_id)]
|
||||
if int(case.run_id) in run_marker_docs
|
||||
else int(case.document_id) == root_doc
|
||||
)
|
||||
]
|
||||
|
||||
run_ids = {int(case.run_id) for case in cases if case.run_id}
|
||||
run_no_by_id: dict[int, str | None] = {}
|
||||
if run_ids:
|
||||
for run in ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.id.in_(run_ids),
|
||||
).all():
|
||||
run_no_by_id[int(run.id)] = run.run_no
|
||||
|
||||
version_by_case_id = _assign_version_numbers(cases, item=item)
|
||||
rows: list[dict[str, Any]] = []
|
||||
for case in cases:
|
||||
is_current = bool(item.current_case_id and int(case.id) == int(item.current_case_id))
|
||||
version_no = version_by_case_id.get(int(case.id), 1)
|
||||
rows.append({
|
||||
'case_no': case.case_no,
|
||||
'case_status': case.status,
|
||||
'run_id': int(case.run_id),
|
||||
'run_no': run_no_by_id.get(int(case.run_id)),
|
||||
'document_id': int(case.document_id),
|
||||
'document_filename': _document_filename(case.document_id),
|
||||
'is_current': is_current,
|
||||
'is_readonly': not is_current or item.lifecycle_status == 'closed',
|
||||
'version_label': f'V{version_no}',
|
||||
'created_at': _iso(case.created_at),
|
||||
'confirmed_at': _iso(case.confirmed_at),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def project_session_workbench(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
include_closed: bool = True,
|
||||
open_only: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
投影会话工作台:未关闭项、已关闭项与统计。
|
||||
|
||||
Args:
|
||||
user_id: 属主。
|
||||
conversation_id: 会话 ID。
|
||||
include_closed: 是否包含已关闭分组。
|
||||
open_only: True 时仅返回未关闭项(忽略 include_closed)。
|
||||
|
||||
Returns:
|
||||
ShippingSessionWorkItemSummary 形状的读模型。
|
||||
"""
|
||||
conversation = str(conversation_id or '').strip()
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
owner_user_id=int(user_id),
|
||||
conversation_id=conversation,
|
||||
).order_by(
|
||||
ShippingSessionPdfWorkItem.updated_at.desc(),
|
||||
ShippingSessionPdfWorkItem.id.desc(),
|
||||
)
|
||||
items = query.all()
|
||||
open_items = [item for item in items if item.lifecycle_status != 'closed']
|
||||
closed_items = [item for item in items if item.lifecycle_status == 'closed']
|
||||
truncated = False
|
||||
if len(open_items) > MAX_OPEN_SESSION_WORK_ITEMS:
|
||||
open_items = open_items[:MAX_OPEN_SESSION_WORK_ITEMS]
|
||||
truncated = True
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
'conversation_id': conversation,
|
||||
'open_count': len([item for item in items if item.lifecycle_status != 'closed']),
|
||||
'closed_count': len(closed_items),
|
||||
'pending_review_count': len([
|
||||
item for item in open_items
|
||||
if item.lifecycle_status in {'pending_review', 'reparse_failed'}
|
||||
]),
|
||||
'extracting_count': len([item for item in open_items if item.lifecycle_status == 'extracting']),
|
||||
'open_items': [serialize_session_work_item(item) for item in open_items],
|
||||
'max_open_items': MAX_OPEN_SESSION_WORK_ITEMS,
|
||||
'truncated': truncated,
|
||||
}
|
||||
if open_only:
|
||||
payload['closed_items'] = []
|
||||
payload['closed_collapsed'] = True
|
||||
return payload
|
||||
if include_closed:
|
||||
payload['closed_items'] = [serialize_session_work_item(item) for item in closed_items]
|
||||
payload['closed_collapsed'] = True
|
||||
else:
|
||||
payload['closed_items'] = []
|
||||
payload['closed_collapsed'] = True
|
||||
return payload
|
||||
|
||||
|
||||
def project_admin_supervision_page(
|
||||
*,
|
||||
lifecycle_status: str | None = None,
|
||||
owner_user_id: int | None = None,
|
||||
conversation_id: str | None = None,
|
||||
q: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员监管台分页投影(含 admin_terminate / admin_revoke_confirmation 动作)。
|
||||
|
||||
Args:
|
||||
lifecycle_status: 可选生命周期过滤。
|
||||
owner_user_id: 可选属主。
|
||||
conversation_id: 可选会话。
|
||||
q: 可选 item_no / case_no / filename 模糊。
|
||||
page/page_size: 分页。
|
||||
|
||||
Returns:
|
||||
items + pagination。
|
||||
"""
|
||||
query = ShippingSessionPdfWorkItem.query
|
||||
if lifecycle_status:
|
||||
query = query.filter(
|
||||
ShippingSessionPdfWorkItem.lifecycle_status == str(lifecycle_status)[:32],
|
||||
)
|
||||
if owner_user_id is not None:
|
||||
query = query.filter(ShippingSessionPdfWorkItem.owner_user_id == int(owner_user_id))
|
||||
if conversation_id:
|
||||
query = query.filter(
|
||||
ShippingSessionPdfWorkItem.conversation_id == str(conversation_id)[:100],
|
||||
)
|
||||
text = str(q or '').strip()
|
||||
if text:
|
||||
like = f'%{text[:64]}%'
|
||||
query = query.filter(
|
||||
ShippingSessionPdfWorkItem.item_no.ilike(like)
|
||||
| ShippingSessionPdfWorkItem.current_case_no.ilike(like)
|
||||
| ShippingSessionPdfWorkItem.current_run_no.ilike(like)
|
||||
| ShippingSessionPdfWorkItem.conversation_id.ilike(like)
|
||||
)
|
||||
total = query.count()
|
||||
page = max(1, int(page or 1))
|
||||
page_size = min(100, max(1, int(page_size or 20)))
|
||||
rows = (
|
||||
query.order_by(
|
||||
ShippingSessionPdfWorkItem.updated_at.desc(),
|
||||
ShippingSessionPdfWorkItem.id.desc(),
|
||||
)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'items': [serialize_session_work_item(item, for_admin=True) for item in rows],
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'total': int(total),
|
||||
}
|
||||
@@ -0,0 +1,949 @@
|
||||
"""
|
||||
services/shipping_notice/session_pdf_work_item_service.py
|
||||
|
||||
用途:会话 PDF 工作项领域写服务(创建、版本切换、失败回退、关闭、撤销确认)。
|
||||
依赖:ShippingSessionPdfWorkItem、ShippingOrderReviewCase、ShippingTask、audit_service、契约词典。
|
||||
逻辑:由抽取 Run/复核处置/确认服务与 workspace/admin API 调用;所有写操作在同一事务内
|
||||
使用 FOR UPDATE + lock_version,并与审计同事务追加。禁止前端自行推导当前版本指针。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingSessionPdfWorkItem,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
MAX_OPEN_SESSION_WORK_ITEMS,
|
||||
SESSION_WORK_ITEM_CLOSED_REASONS,
|
||||
SESSION_WORK_ITEM_LIFECYCLE_STATUSES,
|
||||
)
|
||||
from app.services.shipping_notice.task_disposition_service import void_task
|
||||
|
||||
# 确认后可撤销窗口(小时)。
|
||||
CONFIRM_REVOKE_WINDOW_HOURS = 24
|
||||
|
||||
# 已进入库存匹配或更后履约阶段的 process_status;禁止直接撤销确认。
|
||||
_INVENTORY_MATCHED_OR_LATER = frozenset({
|
||||
'matched',
|
||||
'waiting_upload',
|
||||
'upload_failed',
|
||||
'uploaded',
|
||||
'closed',
|
||||
'completed',
|
||||
})
|
||||
|
||||
|
||||
def generate_session_work_item_no() -> str:
|
||||
"""生成会话 PDF 工作项稳定业务编号。"""
|
||||
return f"SPWI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:10].upper()}"
|
||||
|
||||
|
||||
def _snapshot(item: ShippingSessionPdfWorkItem) -> dict[str, Any]:
|
||||
"""投影工作项审计白名单快照。"""
|
||||
return {
|
||||
'item_no': item.item_no,
|
||||
'session_item_no': item.item_no,
|
||||
'conversation_id': item.conversation_id,
|
||||
'owner_user_id': item.owner_user_id,
|
||||
'root_document_id': item.root_document_id,
|
||||
'current_document_id': item.current_document_id,
|
||||
'current_run_no': item.current_run_no,
|
||||
'current_case_no': item.current_case_no,
|
||||
'current_version_no': int(item.current_version_no or 1),
|
||||
'lifecycle_status': item.lifecycle_status,
|
||||
'closed_reason': item.closed_reason,
|
||||
'lock_version': int(item.lock_version or 1),
|
||||
}
|
||||
|
||||
|
||||
def _audit(
|
||||
*,
|
||||
event_type: str,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
action: str | None = None,
|
||||
reason: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
result: str = 'success',
|
||||
error_code: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
source: str | None = None,
|
||||
actor_role: str | None = None,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
task_no: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
在当前事务追加会话工作项审计事件。
|
||||
|
||||
核心逻辑:缺省时从 Flask 请求补齐 request_id / operation_id 与客户端 IP/UA(哈希入库)。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context
|
||||
|
||||
ctx = resolve_request_audit_context()
|
||||
resolved_request_id = request_id or ctx.get('request_id')
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id=item.item_no,
|
||||
session_item_id=item.item_no,
|
||||
owner_user_id=item.owner_user_id,
|
||||
conversation_id=item.conversation_id,
|
||||
document_id=item.current_document_id,
|
||||
run_no=item.current_run_no,
|
||||
review_case_no=item.current_case_no,
|
||||
task_no=task_no,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
actor_role=actor_role,
|
||||
request_id=resolved_request_id,
|
||||
operation_id=operation_id or resolved_request_id,
|
||||
client_ip=ctx.get('client_ip'),
|
||||
user_agent=ctx.get('user_agent'),
|
||||
source=source or 'shipping_notice',
|
||||
result=result,
|
||||
error_code=error_code,
|
||||
action=action,
|
||||
reason=reason,
|
||||
reason_code=reason_code,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata=metadata or {},
|
||||
)
|
||||
|
||||
|
||||
def _bump_lock(item: ShippingSessionPdfWorkItem, *, expected_lock_version: int | None = None) -> None:
|
||||
"""乐观锁递增;版本不匹配时拒绝写。"""
|
||||
if expected_lock_version is not None and int(item.lock_version or 0) != int(expected_lock_version):
|
||||
raise ConflictError(
|
||||
'Session PDF work item was updated concurrently',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_VERSION_CONFLICT',
|
||||
)
|
||||
item.lock_version = int(item.lock_version or 1) + 1
|
||||
item.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def _count_open_items(*, conversation_id: str) -> int:
|
||||
"""统计会话未关闭工作项数量。"""
|
||||
return (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter(
|
||||
ShippingSessionPdfWorkItem.conversation_id == str(conversation_id),
|
||||
ShippingSessionPdfWorkItem.lifecycle_status != 'closed',
|
||||
)
|
||||
.count()
|
||||
)
|
||||
|
||||
|
||||
def get_work_item_for_user(*, user_id: int, item_no: str, for_update: bool = False) -> ShippingSessionPdfWorkItem:
|
||||
"""
|
||||
按属主加载工作项。
|
||||
|
||||
Args:
|
||||
user_id: 属主用户 ID。
|
||||
item_no: 工作项业务编号。
|
||||
for_update: True 时行锁。
|
||||
|
||||
Returns:
|
||||
ShippingSessionPdfWorkItem。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 不存在或不属于该用户。
|
||||
"""
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
item_no=str(item_no or '').strip().upper(),
|
||||
owner_user_id=int(user_id),
|
||||
)
|
||||
if for_update:
|
||||
query = query.with_for_update()
|
||||
item = query.first()
|
||||
if item is None:
|
||||
raise NotFoundError('Session PDF work item not found', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_NOT_FOUND')
|
||||
return item
|
||||
|
||||
|
||||
def get_work_item_by_no(*, item_no: str, for_update: bool = False) -> ShippingSessionPdfWorkItem:
|
||||
"""管理员按编号加载工作项(跨用户)。"""
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(item_no=str(item_no or '').strip().upper())
|
||||
if for_update:
|
||||
query = query.with_for_update()
|
||||
item = query.first()
|
||||
if item is None:
|
||||
raise NotFoundError('Session PDF work item not found', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_NOT_FOUND')
|
||||
return item
|
||||
|
||||
|
||||
def find_open_work_item_by_root(
|
||||
*,
|
||||
conversation_id: str,
|
||||
root_document_id: int,
|
||||
for_update: bool = False,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""按会话 + 同源 Document 查找工作项(含已关闭,供幂等复用)。"""
|
||||
query = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
conversation_id=str(conversation_id),
|
||||
root_document_id=int(root_document_id),
|
||||
)
|
||||
if for_update:
|
||||
query = query.with_for_update()
|
||||
return query.first()
|
||||
|
||||
|
||||
def ensure_work_item_for_document(
|
||||
*,
|
||||
conversation_id: str,
|
||||
owner_user_id: int,
|
||||
document_id: int,
|
||||
root_document_id: int | None = None,
|
||||
run: ShippingOrderExtractionRun | None = None,
|
||||
case: ShippingOrderReviewCase | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""
|
||||
为会话内 PDF 幂等绑定/创建工作项。
|
||||
|
||||
核心逻辑:同源 root_document_id 复用;新建时检查未关闭上限 50;绑定当前 Run/Case 指针。
|
||||
|
||||
Args:
|
||||
conversation_id: 聊天会话 ID。
|
||||
owner_user_id: 属主。
|
||||
document_id: 当前 Document。
|
||||
root_document_id: 同源根 Document;默认等于 document_id。
|
||||
run/case: 可选当前版本指针。
|
||||
actor_*: 审计操作者。
|
||||
|
||||
Returns:
|
||||
已存在或新建的工作项。
|
||||
"""
|
||||
root_id = int(root_document_id or document_id)
|
||||
existing = find_open_work_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=root_id,
|
||||
for_update=True,
|
||||
)
|
||||
if existing is not None:
|
||||
before = _snapshot(existing)
|
||||
changed = False
|
||||
if run is not None and (
|
||||
existing.current_run_id != int(run.id)
|
||||
or existing.current_run_no != str(run.run_no)
|
||||
):
|
||||
existing.current_run_id = int(run.id)
|
||||
existing.current_run_no = str(run.run_no)
|
||||
changed = True
|
||||
if case is not None and (
|
||||
existing.current_case_id != int(case.id)
|
||||
or existing.current_case_no != str(case.case_no)
|
||||
):
|
||||
existing.current_case_id = int(case.id)
|
||||
existing.current_case_no = str(case.case_no)
|
||||
if existing.lifecycle_status in {'extracting', 'reparse_failed'}:
|
||||
existing.lifecycle_status = 'pending_review'
|
||||
changed = True
|
||||
if int(existing.current_document_id) != int(document_id):
|
||||
existing.current_document_id = int(document_id)
|
||||
changed = True
|
||||
if existing.lifecycle_status == 'closed':
|
||||
# 已关闭项不因旁路绑定自动重开;由显式恢复/撤销路径处理。
|
||||
return existing
|
||||
if changed:
|
||||
_bump_lock(existing)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='document_extraction_started',
|
||||
item=existing,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id or owner_user_id,
|
||||
before=before,
|
||||
after=_snapshot(existing),
|
||||
action='bind_current_version',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
source='order_extraction',
|
||||
)
|
||||
return existing
|
||||
|
||||
if _count_open_items(conversation_id=conversation_id) >= MAX_OPEN_SESSION_WORK_ITEMS:
|
||||
raise ConflictError(
|
||||
'Session open PDF work item limit exceeded',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_LIMIT_EXCEEDED',
|
||||
details={'limit': MAX_OPEN_SESSION_WORK_ITEMS},
|
||||
)
|
||||
|
||||
item = ShippingSessionPdfWorkItem(
|
||||
item_no=generate_session_work_item_no(),
|
||||
conversation_id=str(conversation_id),
|
||||
owner_user_id=int(owner_user_id),
|
||||
root_document_id=root_id,
|
||||
current_document_id=int(document_id),
|
||||
current_run_id=int(run.id) if run is not None else None,
|
||||
current_run_no=str(run.run_no) if run is not None else None,
|
||||
current_case_id=int(case.id) if case is not None else None,
|
||||
current_case_no=str(case.case_no) if case is not None else None,
|
||||
current_version_no=1,
|
||||
lifecycle_status='pending_review' if case is not None else 'extracting',
|
||||
lock_version=1,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='session_work_item_created',
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id or owner_user_id,
|
||||
before=None,
|
||||
after=_snapshot(item),
|
||||
action='create',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
source='order_extraction',
|
||||
metadata={'root_document_id': root_id},
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def bind_cases_for_run(*, run: ShippingOrderExtractionRun, cases: list[ShippingOrderReviewCase]) -> list[ShippingSessionPdfWorkItem]:
|
||||
"""
|
||||
Run 初始化 Case 后,为每个 PDF Case 绑定/创建会话工作项。
|
||||
|
||||
核心逻辑:重识别后继 Run 优先按 source_case 的 root 复用工作项并切换指针;
|
||||
普通创建按 document_id 作为 root。
|
||||
"""
|
||||
items: list[ShippingSessionPdfWorkItem] = []
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse') if isinstance(run.input_snapshot_json, dict) else None
|
||||
source_case_no = ''
|
||||
source_root_id: int | None = None
|
||||
if isinstance(marker, dict):
|
||||
source_case_no = str(marker.get('source_case_no') or '').strip().upper()
|
||||
if source_case_no:
|
||||
source_case = ShippingOrderReviewCase.query.filter_by(case_no=source_case_no).first()
|
||||
if source_case is not None:
|
||||
existing = ShippingSessionPdfWorkItem.query.filter_by(
|
||||
conversation_id=str(run.conversation_id),
|
||||
current_case_id=int(source_case.id),
|
||||
).first()
|
||||
if existing is None:
|
||||
existing = find_open_work_item_by_root(
|
||||
conversation_id=str(run.conversation_id),
|
||||
root_document_id=int(source_case.document_id),
|
||||
)
|
||||
if existing is not None:
|
||||
source_root_id = int(existing.root_document_id)
|
||||
|
||||
for case in cases:
|
||||
root_id = source_root_id if (
|
||||
source_root_id is not None
|
||||
and isinstance(marker, dict)
|
||||
and int(marker.get('document_id') or 0) == int(case.document_id)
|
||||
) else int(case.document_id)
|
||||
# 若能通过同源找到已有项,优先切换版本而非新建。
|
||||
existing = find_open_work_item_by_root(
|
||||
conversation_id=str(run.conversation_id),
|
||||
root_document_id=root_id,
|
||||
for_update=True,
|
||||
)
|
||||
if existing is not None and run.reparse_of_run_id:
|
||||
items.append(
|
||||
mark_reparse_succeeded(
|
||||
item=existing,
|
||||
run=run,
|
||||
case=case,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
)
|
||||
)
|
||||
continue
|
||||
items.append(
|
||||
ensure_work_item_for_document(
|
||||
conversation_id=str(run.conversation_id),
|
||||
owner_user_id=int(run.user_id),
|
||||
document_id=int(case.document_id),
|
||||
root_document_id=root_id,
|
||||
run=run,
|
||||
case=case,
|
||||
actor_type='system',
|
||||
actor_id=run.user_id,
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def mark_reparse_started(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
successor_run: ShippingOrderExtractionRun,
|
||||
reason: str,
|
||||
comment: str | None = None,
|
||||
actor_id: int,
|
||||
replacement_document_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""
|
||||
单 PDF 重识别开始:锁定旧入口语义,工作项进入 extracting。
|
||||
|
||||
核心逻辑:按当前 Case 定位工作项;写入前后快照与 reparse 审计;不创建新工作项。
|
||||
"""
|
||||
item = (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter_by(current_case_id=int(case.id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if item is None:
|
||||
item = find_open_work_item_by_root(
|
||||
conversation_id=str(successor_run.conversation_id),
|
||||
root_document_id=int(case.document_id),
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return None
|
||||
if item.lifecycle_status == 'closed':
|
||||
raise ConflictError(
|
||||
'Closed session work item cannot be reparsed',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSED',
|
||||
)
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'extracting'
|
||||
if replacement_document_id is not None:
|
||||
item.current_document_id = int(replacement_document_id)
|
||||
# 重识别进行中仍保留旧 Case 指针,供失败回退;成功后再切换。
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='document_reparse_requested',
|
||||
item=item,
|
||||
actor_type='user',
|
||||
actor_id=actor_id,
|
||||
before=before,
|
||||
after={
|
||||
**_snapshot(item),
|
||||
'previous_run_no': before.get('current_run_no'),
|
||||
'previous_case_no': before.get('current_case_no'),
|
||||
},
|
||||
action='reparse_started',
|
||||
reason=comment,
|
||||
reason_code=reason,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
metadata={'successor_run_no': successor_run.run_no},
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def mark_reparse_succeeded(
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
run: ShippingOrderExtractionRun,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""重识别成功:切换当前版本指针,旧 Case 由处置服务标记 superseded。"""
|
||||
before = _snapshot(item)
|
||||
item.current_run_id = int(run.id)
|
||||
item.current_run_no = str(run.run_no)
|
||||
item.current_case_id = int(case.id)
|
||||
item.current_case_no = str(case.case_no)
|
||||
item.current_document_id = int(case.document_id)
|
||||
item.current_version_no = int(item.current_version_no or 1) + 1
|
||||
item.lifecycle_status = 'pending_review'
|
||||
item.closed_reason = None
|
||||
item.closed_at = None
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='document_version_replaced',
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id or item.owner_user_id,
|
||||
before=before,
|
||||
after={
|
||||
**_snapshot(item),
|
||||
'previous_run_no': before.get('current_run_no'),
|
||||
'previous_case_no': before.get('current_case_no'),
|
||||
},
|
||||
action='version_replaced',
|
||||
source='order_extraction_worker',
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def mark_reparse_failed_and_restore(
|
||||
*,
|
||||
source_case: ShippingOrderReviewCase,
|
||||
failed_run: ShippingOrderExtractionRun,
|
||||
failure_stage: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""
|
||||
重识别失败:恢复旧 Case 为当前可操作入口,并写恢复审计。
|
||||
|
||||
核心逻辑:工作项 current_* 仍指向旧 Case(开始时未切换);仅把生命周期改为 reparse_failed。
|
||||
"""
|
||||
item = (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter_by(current_case_id=int(source_case.id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if item is None:
|
||||
item = find_open_work_item_by_root(
|
||||
conversation_id=str(failed_run.conversation_id),
|
||||
root_document_id=int(source_case.document_id),
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return None
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'reparse_failed'
|
||||
# 确保指针仍指向可恢复的旧 Case。
|
||||
item.current_case_id = int(source_case.id)
|
||||
item.current_case_no = str(source_case.case_no)
|
||||
item.current_run_id = int(source_case.run_id)
|
||||
source_run = db.session.get(ShippingOrderExtractionRun, int(source_case.run_id))
|
||||
if source_run is not None:
|
||||
item.current_run_no = str(source_run.run_no)
|
||||
item.current_document_id = int(source_case.document_id)
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
after = {
|
||||
**_snapshot(item),
|
||||
'reparse_failure_stage': failure_stage or failed_run.status,
|
||||
'restore_target_case_no': source_case.case_no,
|
||||
'previous_run_no': failed_run.run_no,
|
||||
}
|
||||
_audit(
|
||||
event_type='document_reparse_failed',
|
||||
item=item,
|
||||
actor_type='system',
|
||||
actor_id=failed_run.user_id,
|
||||
before=before,
|
||||
after=after,
|
||||
action='reparse_failed',
|
||||
result='failure',
|
||||
error_code=str(getattr(failed_run, 'error_code', None) or 'reparse_failed'),
|
||||
source='order_extraction_worker',
|
||||
metadata={'failed_run_no': failed_run.run_no},
|
||||
)
|
||||
_audit(
|
||||
event_type='document_previous_version_restored',
|
||||
item=item,
|
||||
actor_type='system',
|
||||
actor_id=failed_run.user_id,
|
||||
before=before,
|
||||
after=after,
|
||||
action='restore_previous_version',
|
||||
source='order_extraction_worker',
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def close_work_item(
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
closed_reason: str,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
reason: str | None = None,
|
||||
expected_lock_version: int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
actor_role: str | None = None,
|
||||
task_no: str | None = None,
|
||||
event_type: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""关闭工作项(确认建单 / 非订单 / 用户取消 / 管理员终止)。"""
|
||||
normalized = str(closed_reason or '').strip().lower()
|
||||
if normalized not in SESSION_WORK_ITEM_CLOSED_REASONS:
|
||||
raise ValidationError(
|
||||
'Invalid session work item closed reason',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSE_REASON_INVALID',
|
||||
)
|
||||
if item.lifecycle_status == 'closed':
|
||||
return item
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'closed'
|
||||
item.closed_reason = normalized
|
||||
item.closed_at = datetime.utcnow()
|
||||
_bump_lock(item, expected_lock_version=expected_lock_version)
|
||||
db.session.flush()
|
||||
resolved_event = event_type or {
|
||||
'confirmed': 'review_confirmed',
|
||||
'non_order': 'review_marked_non_order',
|
||||
'user_cancelled': 'session_work_item_cancelled',
|
||||
'admin_terminated': 'session_work_item_cancelled',
|
||||
}.get(normalized, 'session_work_item_cancelled')
|
||||
_audit(
|
||||
event_type=resolved_event,
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
actor_role=actor_role,
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='close',
|
||||
reason=reason,
|
||||
reason_code=normalized,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
task_no=task_no,
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def close_work_item_for_case(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
closed_reason: str,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
reason: str | None = None,
|
||||
task_no: str | None = None,
|
||||
event_type: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem | None:
|
||||
"""按 Case 定位并关闭工作项;找不到时静默跳过(兼容尚未绑定的历史数据)。"""
|
||||
item = (
|
||||
ShippingSessionPdfWorkItem.query
|
||||
.filter_by(current_case_id=int(case.id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if item is None:
|
||||
return None
|
||||
return close_work_item(
|
||||
item=item,
|
||||
closed_reason=closed_reason,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
reason=reason,
|
||||
task_no=task_no,
|
||||
event_type=event_type,
|
||||
)
|
||||
|
||||
|
||||
def reopen_work_item_pending_review(
|
||||
*,
|
||||
item: ShippingSessionPdfWorkItem,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_type: str,
|
||||
actor_id: str | int | None,
|
||||
reason: str | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""撤销确认后恢复工作项为待确认。"""
|
||||
before = _snapshot(item)
|
||||
item.lifecycle_status = 'pending_review'
|
||||
item.closed_reason = None
|
||||
item.closed_at = None
|
||||
item.current_case_id = int(case.id)
|
||||
item.current_case_no = str(case.case_no)
|
||||
item.current_document_id = int(case.document_id)
|
||||
_bump_lock(item)
|
||||
db.session.flush()
|
||||
_audit(
|
||||
event_type='review_confirmation_revoked',
|
||||
item=item,
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='revoke_confirmation',
|
||||
reason=reason,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
source='admin_api',
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def task_has_entered_inventory_match(task: ShippingTask) -> bool:
|
||||
"""判断任务是否已进入库存匹配或更后履约阶段。"""
|
||||
return str(task.process_status or '').strip().lower() in _INVENTORY_MATCHED_OR_LATER
|
||||
|
||||
|
||||
def revoke_review_confirmation(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
item_no: str,
|
||||
reason: str,
|
||||
confirm_token: str | None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员在 24 小时内撤销确认:未库存匹配则作废任务并恢复工作项;已匹配则拒绝并记受控异常。
|
||||
|
||||
Args:
|
||||
admin_user_id: 实际操作管理员。
|
||||
item_no: 工作项编号。
|
||||
reason: 必填撤销理由。
|
||||
confirm_token: 二次确认令牌;必须为 ``CONFIRM_REVOKE``。
|
||||
request_id/operation_id: 请求关联。
|
||||
|
||||
Returns:
|
||||
含 status / item_no / task_no / blocked 等摘要。
|
||||
|
||||
Raises:
|
||||
ValidationError/ConflictError/ForbiddenError: 理由、窗口、状态或库存匹配阻断。
|
||||
"""
|
||||
reason_text = str(reason or '').strip()
|
||||
if not reason_text:
|
||||
raise ValidationError(
|
||||
'Admin revoke reason is required',
|
||||
code='SHIPPING_NOTICE.ADMIN_REASON_REQUIRED',
|
||||
)
|
||||
if str(confirm_token or '').strip() != 'CONFIRM_REVOKE':
|
||||
raise ValidationError(
|
||||
'Admin revoke requires secondary confirmation',
|
||||
code='SHIPPING_NOTICE.ADMIN_CONFIRM_REQUIRED',
|
||||
)
|
||||
|
||||
item = get_work_item_by_no(item_no=item_no, for_update=True)
|
||||
if item.lifecycle_status != 'closed' or item.closed_reason != 'confirmed':
|
||||
raise ConflictError(
|
||||
'Only confirmed work items can be revoked',
|
||||
code='SHIPPING_NOTICE.REVOKE_NOT_CONFIRMED',
|
||||
)
|
||||
if item.current_case_id is None:
|
||||
raise ConflictError('Confirmed case pointer missing', code='SHIPPING_NOTICE.REVOKE_CASE_MISSING')
|
||||
case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(id=int(item.current_case_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if case is None or case.status != 'confirmed' or not case.confirmed_task_id:
|
||||
raise ConflictError('Confirmed case is unavailable', code='SHIPPING_NOTICE.REVOKE_CASE_INVALID')
|
||||
if case.confirmed_at is None or (
|
||||
datetime.utcnow() - case.confirmed_at > timedelta(hours=CONFIRM_REVOKE_WINDOW_HOURS)
|
||||
):
|
||||
raise ConflictError(
|
||||
'Confirmation revoke window exceeded',
|
||||
code='SHIPPING_NOTICE.REVOKE_WINDOW_EXPIRED',
|
||||
details={'window_hours': CONFIRM_REVOKE_WINDOW_HOURS},
|
||||
)
|
||||
task = (
|
||||
ShippingTask.query
|
||||
.filter_by(id=int(case.confirmed_task_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if task is None:
|
||||
raise ConflictError('Confirmed task missing', code='SHIPPING_NOTICE.REVOKE_TASK_MISSING')
|
||||
|
||||
before = _snapshot(item)
|
||||
if task_has_entered_inventory_match(task):
|
||||
_audit(
|
||||
event_type='review_confirmation_revoked',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=before,
|
||||
after={
|
||||
**before,
|
||||
'revocation_blocked': True,
|
||||
'inventory_matched': True,
|
||||
},
|
||||
action='revoke_blocked_inventory_matched',
|
||||
reason=reason_text,
|
||||
result='rejected',
|
||||
error_code='SHIPPING_NOTICE.REVOKE_INVENTORY_MATCHED',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
task_no=task.task_no,
|
||||
metadata={'controlled_exception': True},
|
||||
)
|
||||
raise ConflictError(
|
||||
'Cannot revoke confirmation after inventory match; controlled exception recorded',
|
||||
code='SHIPPING_NOTICE.REVOKE_INVENTORY_MATCHED',
|
||||
details={'task_no': task.task_no, 'process_status': task.process_status},
|
||||
)
|
||||
|
||||
# 作废下游任务并恢复 Case/工作项。
|
||||
void_task(
|
||||
task,
|
||||
actor_id=int(admin_user_id),
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
)
|
||||
case.status = 'ready'
|
||||
case.confirmed_task_id = None
|
||||
case.confirmed_at = None
|
||||
case.disposition = None
|
||||
reopen_work_item_pending_review(
|
||||
item=item,
|
||||
case=case,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
_audit(
|
||||
event_type='admin_impersonated_review_action',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='revoke_confirmation',
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
task_no=task.task_no,
|
||||
metadata={'admin_action': 'revoke_confirmation', 'owner_user_id': item.owner_user_id},
|
||||
)
|
||||
db.session.flush()
|
||||
return {
|
||||
'item_no': item.item_no,
|
||||
'case_no': case.case_no,
|
||||
'task_no': task.task_no,
|
||||
'lifecycle_status': item.lifecycle_status,
|
||||
'revoked': True,
|
||||
}
|
||||
|
||||
|
||||
def terminate_work_item_as_admin(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
item_no: str,
|
||||
reason: str,
|
||||
confirm_token: str | None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingSessionPdfWorkItem:
|
||||
"""
|
||||
管理员终止未关闭工作项;必须理由 + 二次确认。
|
||||
|
||||
核心逻辑:已关闭时不改状态,但仍记录本次终止请求的审计(result=ignored,metadata 标记幂等),
|
||||
覆盖重复管理操作尝试,避免仅有首次状态变化可追溯。
|
||||
|
||||
Args:
|
||||
admin_user_id: 管理员用户 ID。
|
||||
item_no: 工作项编号。
|
||||
reason: 终止理由(必填)。
|
||||
confirm_token: 须为 `CONFIRM_TERMINATE`。
|
||||
request_id / operation_id: 可选请求关联;缺省由请求上下文补齐。
|
||||
|
||||
Returns:
|
||||
终止后或已关闭的工作项。
|
||||
"""
|
||||
reason_text = str(reason or '').strip()
|
||||
if not reason_text:
|
||||
raise ValidationError('Admin terminate reason is required', code='SHIPPING_NOTICE.ADMIN_REASON_REQUIRED')
|
||||
if str(confirm_token or '').strip() != 'CONFIRM_TERMINATE':
|
||||
raise ValidationError('Admin terminate requires secondary confirmation', code='SHIPPING_NOTICE.ADMIN_CONFIRM_REQUIRED')
|
||||
item = get_work_item_by_no(item_no=item_no, for_update=True)
|
||||
if item.lifecycle_status == 'closed':
|
||||
snap = _snapshot(item)
|
||||
_audit(
|
||||
event_type='admin_impersonated_review_action',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=snap,
|
||||
after=snap,
|
||||
action='terminate',
|
||||
reason=reason_text,
|
||||
result='ignored',
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
metadata={
|
||||
'admin_action': 'terminate',
|
||||
'owner_user_id': item.owner_user_id,
|
||||
'idempotent': True,
|
||||
'already_closed': True,
|
||||
'closed_reason': item.closed_reason,
|
||||
},
|
||||
)
|
||||
return item
|
||||
before = _snapshot(item)
|
||||
close_work_item(
|
||||
item=item,
|
||||
closed_reason='admin_terminated',
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
event_type='session_work_item_cancelled',
|
||||
)
|
||||
_audit(
|
||||
event_type='admin_impersonated_review_action',
|
||||
item=item,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
actor_role='admin',
|
||||
before=before,
|
||||
after=_snapshot(item),
|
||||
action='terminate',
|
||||
reason=reason_text,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
metadata={'admin_action': 'terminate', 'owner_user_id': item.owner_user_id},
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
def assert_case_is_current_work_item_version(*, case: ShippingOrderReviewCase) -> None:
|
||||
"""
|
||||
确认写路径仅允许当前有效 Case。
|
||||
|
||||
核心逻辑:若工作项存在且 current_case_id 不是本 Case,拒绝确认/编辑。
|
||||
"""
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=int(case.id)).first()
|
||||
if item is not None:
|
||||
if item.lifecycle_status == 'closed':
|
||||
raise ConflictError('Session work item is closed', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_CLOSED')
|
||||
if item.lifecycle_status == 'extracting':
|
||||
raise ConflictError('Document reparse is in progress', code='SHIPPING_NOTICE.SESSION_WORK_ITEM_EXTRACTING')
|
||||
return
|
||||
|
||||
conversation_id = ''
|
||||
if case.run is not None:
|
||||
conversation_id = str(case.run.conversation_id or '')
|
||||
if not conversation_id:
|
||||
run = db.session.get(ShippingOrderExtractionRun, int(case.run_id))
|
||||
conversation_id = str(run.conversation_id or '') if run is not None else ''
|
||||
if not conversation_id:
|
||||
return
|
||||
sibling = find_open_work_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=int(case.document_id),
|
||||
)
|
||||
if sibling is not None and sibling.current_case_id and int(sibling.current_case_id) != int(case.id):
|
||||
raise ConflictError(
|
||||
'Review case has been superseded by a newer version',
|
||||
code='SHIPPING_NOTICE.SESSION_WORK_ITEM_SUPERSEDED',
|
||||
details={
|
||||
'current_case_no': sibling.current_case_no,
|
||||
'item_no': sibling.item_no,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# 供测试引用的冻结集合。
|
||||
SESSION_WORK_ITEM_LIFECYCLES = SESSION_WORK_ITEM_LIFECYCLE_STATUSES
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/tool_common.py
|
||||
|
||||
用途:发货通知 Tool 链共享配置、payload 合并与消息拼接(无阶段业务编排)。
|
||||
依赖:constants、models.ShippingTaskEvent。
|
||||
逻辑:task_workflow / inventory_workflow / fulfillment_workflow 共用,避免 tools 循环依赖。
|
||||
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
|
||||
依赖:constants、models.ShippingTaskEvent、fulfillment_audit(库存/RPA/导出双写,strict)。
|
||||
逻辑:task_workflow / inventory_workflow / fulfillment_workflow 共用;log_task_event 对
|
||||
inventory_rpa_/inventory_source_/export_ 前缀事件同步投影到 ShippingAuditEvent,失败阻断业务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -292,6 +293,43 @@ def log_task_event(
|
||||
before_json=before,
|
||||
after_json=after,
|
||||
))
|
||||
# 库存/RPA/导出关键节点双写统一审计;失败必须阻断,保证审计中心可检索。
|
||||
if str(event_type or '').startswith(('inventory_rpa_', 'inventory_source_', 'export_')):
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
safe_before = None
|
||||
safe_after = None
|
||||
if isinstance(before, dict):
|
||||
safe_before = {
|
||||
key: before[key]
|
||||
for key in ('status', 'phase', 'reason_code', 'error_code', 'attempt_count')
|
||||
if key in before
|
||||
} or None
|
||||
if isinstance(after, dict):
|
||||
safe_after = {
|
||||
key: after[key]
|
||||
for key in ('status', 'phase', 'reason_code', 'error_code', 'attempt_count')
|
||||
if key in after
|
||||
} or None
|
||||
meta: dict[str, Any] = {'dual_write': 'shipping_task_event'}
|
||||
attempt_count = int((detail or {}).get('attempts') or (detail or {}).get('attempt_no') or 0) or None
|
||||
if attempt_count is not None:
|
||||
meta['attempt_count'] = attempt_count
|
||||
record_fulfillment_audit(
|
||||
event_type=f'task_{event_type}'[:64],
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
action=str(event_type)[:64],
|
||||
actor_type='user' if actor_id is not None else 'system',
|
||||
actor_id=actor_id,
|
||||
task_no=str(task.task_no),
|
||||
result='success',
|
||||
before=safe_before,
|
||||
after=safe_after or {'status': getattr(task, 'process_status', None)},
|
||||
metadata=meta,
|
||||
source=str(source or 'system')[:32],
|
||||
strict=True,
|
||||
)
|
||||
|
||||
|
||||
def log_task_action_event(
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
"""
|
||||
migrations/versions/2b4c6d8e0f1a_shipping_progress_and_audit_contract.py
|
||||
|
||||
用途:阶段 0 冻结处理进度取消元数据与全链路审计扩展字段。
|
||||
依赖:shipping_order_extraction_runs/units、shipping_audit_events。
|
||||
逻辑:为 Run/Unit 增加取消请求与生效元数据;为审计表增加 operation_id、白名单快照、
|
||||
证据引用、对象关联与三年保留到期索引。不改变既有业务写路径行为。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '2b4c6d8e0f1a'
|
||||
down_revision = '1a3b5c7d9e0f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _columns(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {column['name'] for column in inspector.get_columns(table_name)}
|
||||
|
||||
|
||||
def _indexes(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {index['name'] for index in inspector.get_indexes(table_name)}
|
||||
|
||||
|
||||
def _check_constraints(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {
|
||||
constraint['name']
|
||||
for constraint in inspector.get_check_constraints(table_name)
|
||||
if constraint.get('name')
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""追加取消与审计契约列及查询索引;幂等跳过已存在对象。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
|
||||
run_cols = _columns(inspector, 'shipping_order_extraction_runs')
|
||||
if 'cancellation_requested_at' not in run_cols:
|
||||
op.add_column('shipping_order_extraction_runs', sa.Column('cancellation_requested_at', sa.DateTime(), nullable=True))
|
||||
if 'cancellation_actor_type' not in run_cols:
|
||||
op.add_column('shipping_order_extraction_runs', sa.Column('cancellation_actor_type', sa.String(length=16), nullable=True))
|
||||
if 'cancellation_actor_id' not in run_cols:
|
||||
op.add_column('shipping_order_extraction_runs', sa.Column('cancellation_actor_id', sa.String(length=128), nullable=True))
|
||||
if 'cancellation_reason' not in run_cols:
|
||||
op.add_column('shipping_order_extraction_runs', sa.Column('cancellation_reason', sa.Text(), nullable=True))
|
||||
if 'cancellation_reason_code' not in run_cols:
|
||||
op.add_column('shipping_order_extraction_runs', sa.Column('cancellation_reason_code', sa.String(length=64), nullable=True))
|
||||
if 'cancellation_completed_at' not in run_cols:
|
||||
op.add_column('shipping_order_extraction_runs', sa.Column('cancellation_completed_at', sa.DateTime(), nullable=True))
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
run_checks = _check_constraints(inspector, 'shipping_order_extraction_runs')
|
||||
run_indexes = _indexes(inspector, 'shipping_order_extraction_runs')
|
||||
if 'ck_shipping_order_extraction_runs_cancel_actor' not in run_checks:
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_order_extraction_runs_cancel_actor',
|
||||
'shipping_order_extraction_runs',
|
||||
"cancellation_actor_type IS NULL OR cancellation_actor_type IN ('user', 'admin', 'system')",
|
||||
)
|
||||
if 'ix_shipping_order_extraction_runs_cancel_requested' not in run_indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_runs_cancel_requested',
|
||||
'shipping_order_extraction_runs',
|
||||
['cancellation_requested_at', 'status'],
|
||||
)
|
||||
|
||||
unit_cols = _columns(inspector, 'shipping_order_extraction_units')
|
||||
if 'activity_version' not in unit_cols:
|
||||
op.add_column(
|
||||
'shipping_order_extraction_units',
|
||||
sa.Column('activity_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
)
|
||||
if 'cancellation_requested_at' not in unit_cols:
|
||||
op.add_column('shipping_order_extraction_units', sa.Column('cancellation_requested_at', sa.DateTime(), nullable=True))
|
||||
if 'cancellation_actor_type' not in unit_cols:
|
||||
op.add_column('shipping_order_extraction_units', sa.Column('cancellation_actor_type', sa.String(length=16), nullable=True))
|
||||
if 'cancellation_actor_id' not in unit_cols:
|
||||
op.add_column('shipping_order_extraction_units', sa.Column('cancellation_actor_id', sa.String(length=128), nullable=True))
|
||||
if 'cancellation_reason' not in unit_cols:
|
||||
op.add_column('shipping_order_extraction_units', sa.Column('cancellation_reason', sa.Text(), nullable=True))
|
||||
if 'cancellation_reason_code' not in unit_cols:
|
||||
op.add_column('shipping_order_extraction_units', sa.Column('cancellation_reason_code', sa.String(length=64), nullable=True))
|
||||
if 'cancellation_completed_at' not in unit_cols:
|
||||
op.add_column('shipping_order_extraction_units', sa.Column('cancellation_completed_at', sa.DateTime(), nullable=True))
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
unit_checks = _check_constraints(inspector, 'shipping_order_extraction_units')
|
||||
unit_indexes = _indexes(inspector, 'shipping_order_extraction_units')
|
||||
if 'ck_shipping_order_extraction_units_cancel_actor' not in unit_checks:
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_order_extraction_units_cancel_actor',
|
||||
'shipping_order_extraction_units',
|
||||
"cancellation_actor_type IS NULL OR cancellation_actor_type IN ('user', 'admin', 'system')",
|
||||
)
|
||||
if 'ix_shipping_order_extraction_units_cancel_requested' not in unit_indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_units_cancel_requested',
|
||||
'shipping_order_extraction_units',
|
||||
['cancellation_requested_at', 'status'],
|
||||
)
|
||||
|
||||
audit_cols = _columns(inspector, 'shipping_audit_events')
|
||||
audit_additions = [
|
||||
('actor_role', sa.Column('actor_role', sa.String(length=64), nullable=True)),
|
||||
('operation_id', sa.Column('operation_id', sa.String(length=64), nullable=True)),
|
||||
('source', sa.Column('source', sa.String(length=32), nullable=True)),
|
||||
('result', sa.Column('result', sa.String(length=16), nullable=True)),
|
||||
('error_code', sa.Column('error_code', sa.String(length=64), nullable=True)),
|
||||
('conversation_id', sa.Column('conversation_id', sa.String(length=100), nullable=True)),
|
||||
('unit_id', sa.Column('unit_id', sa.String(length=64), nullable=True)),
|
||||
('document_id', sa.Column('document_id', sa.String(length=64), nullable=True)),
|
||||
('review_case_no', sa.Column('review_case_no', sa.String(length=64), nullable=True)),
|
||||
('attempt_no', sa.Column('attempt_no', sa.Integer(), nullable=True)),
|
||||
('action', sa.Column('action', sa.String(length=64), nullable=True)),
|
||||
('reason', sa.Column('reason', sa.Text(), nullable=True)),
|
||||
('before_snapshot_json', sa.Column('before_snapshot_json', sa.JSON(), nullable=True)),
|
||||
('after_snapshot_json', sa.Column('after_snapshot_json', sa.JSON(), nullable=True)),
|
||||
('evidence_refs_json', sa.Column('evidence_refs_json', sa.JSON(), nullable=True)),
|
||||
('artifact_refs_json', sa.Column('artifact_refs_json', sa.JSON(), nullable=True)),
|
||||
('context_refs_json', sa.Column('context_refs_json', sa.JSON(), nullable=True)),
|
||||
('retention_expires_at', sa.Column('retention_expires_at', sa.DateTime(), nullable=True)),
|
||||
]
|
||||
for name, column in audit_additions:
|
||||
if name not in audit_cols:
|
||||
op.add_column('shipping_audit_events', column)
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
audit_checks = _check_constraints(inspector, 'shipping_audit_events')
|
||||
if 'ck_shipping_audit_events_result' not in audit_checks:
|
||||
op.create_check_constraint(
|
||||
'ck_shipping_audit_events_result',
|
||||
'shipping_audit_events',
|
||||
"result IS NULL OR result IN ('success', 'failure', 'rejected', 'ignored')",
|
||||
)
|
||||
|
||||
audit_indexes = _indexes(inspector, 'shipping_audit_events')
|
||||
for index_name, columns in (
|
||||
('ix_shipping_audit_events_operation_created', ['operation_id', 'created_at']),
|
||||
('ix_shipping_audit_events_request_created', ['request_id', 'created_at']),
|
||||
('ix_shipping_audit_events_conversation_created', ['conversation_id', 'created_at']),
|
||||
('ix_shipping_audit_events_document_created', ['document_id', 'created_at']),
|
||||
('ix_shipping_audit_events_unit_created', ['unit_id', 'created_at']),
|
||||
('ix_shipping_audit_events_actor_created', ['actor_type', 'actor_id', 'created_at']),
|
||||
('ix_shipping_audit_events_event_type_created', ['event_type', 'created_at']),
|
||||
('ix_shipping_audit_events_retention_expires', ['retention_expires_at', 'id']),
|
||||
):
|
||||
if index_name not in audit_indexes:
|
||||
op.create_index(index_name, 'shipping_audit_events', columns)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚契约列;仅用于受控环境回退,不删除已写入的审计业务事实语义。"""
|
||||
for index_name in (
|
||||
'ix_shipping_audit_events_retention_expires',
|
||||
'ix_shipping_audit_events_event_type_created',
|
||||
'ix_shipping_audit_events_actor_created',
|
||||
'ix_shipping_audit_events_unit_created',
|
||||
'ix_shipping_audit_events_document_created',
|
||||
'ix_shipping_audit_events_conversation_created',
|
||||
'ix_shipping_audit_events_request_created',
|
||||
'ix_shipping_audit_events_operation_created',
|
||||
):
|
||||
op.drop_index(index_name, table_name='shipping_audit_events')
|
||||
op.drop_constraint('ck_shipping_audit_events_result', 'shipping_audit_events', type_='check')
|
||||
for column_name in (
|
||||
'retention_expires_at', 'context_refs_json', 'artifact_refs_json', 'evidence_refs_json',
|
||||
'after_snapshot_json', 'before_snapshot_json', 'reason', 'action', 'attempt_no',
|
||||
'review_case_no', 'document_id', 'unit_id', 'conversation_id', 'error_code', 'result',
|
||||
'source', 'operation_id', 'actor_role',
|
||||
):
|
||||
op.drop_column('shipping_audit_events', column_name)
|
||||
|
||||
op.drop_index('ix_shipping_order_extraction_units_cancel_requested', table_name='shipping_order_extraction_units')
|
||||
op.drop_constraint('ck_shipping_order_extraction_units_cancel_actor', 'shipping_order_extraction_units', type_='check')
|
||||
for column_name in (
|
||||
'cancellation_completed_at', 'cancellation_reason_code', 'cancellation_reason',
|
||||
'cancellation_actor_id', 'cancellation_actor_type', 'cancellation_requested_at', 'activity_version',
|
||||
):
|
||||
op.drop_column('shipping_order_extraction_units', column_name)
|
||||
|
||||
op.drop_index('ix_shipping_order_extraction_runs_cancel_requested', table_name='shipping_order_extraction_runs')
|
||||
op.drop_constraint('ck_shipping_order_extraction_runs_cancel_actor', 'shipping_order_extraction_runs', type_='check')
|
||||
for column_name in (
|
||||
'cancellation_completed_at', 'cancellation_reason_code', 'cancellation_reason',
|
||||
'cancellation_actor_id', 'cancellation_actor_type', 'cancellation_requested_at',
|
||||
):
|
||||
op.drop_column('shipping_order_extraction_runs', column_name)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
migrations/versions/2c5d7e9f1a2b_add_email_supplement_aliases_to_schema_v1.py
|
||||
|
||||
用途:把邮件正文补充表的既有表头别名迁移到 STANDARD_SHIPPING_NOTICE V1 配置。
|
||||
依赖:shipping_order_schemas、shipping_order_schema_versions。
|
||||
逻辑:邮件补充解析器从冻结 Schema 读取 PO、料号、预约单号和库存源别名;本迁移
|
||||
仅补齐当前 V1 的 definition_json(以 JSON 字符串 + CAST jsonb 写入,兼容 psycopg2),
|
||||
不修改历史 Run 快照或已发布版本的业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '2c5d7e9f1a2b'
|
||||
down_revision = '2b4c6d8e0f1a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
_ALIASES_BY_FIELD_CODE = {
|
||||
'customer_po_number': ('PO', 'PO#', 'PO Number', 'PO No', 'Purchase Order', 'Purchase Order Number'),
|
||||
'part_number': ('MPN', 'Manufacturer Part Number', 'Manufacturer PN', 'Part Number', 'Mfr Part Number'),
|
||||
'reservation_id': ('Reservation ID', 'Reservation', 'Reservation No', 'Reservation Number'),
|
||||
'inventory_source_hint': ('Source Type', 'Source', 'Hub Code', 'Hub'),
|
||||
}
|
||||
|
||||
|
||||
def _definition_checksum(definition: dict[str, Any]) -> str:
|
||||
"""使用 Schema 发布服务相同的规范 JSON 算法重算配置校验和。"""
|
||||
encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def _merge_aliases(existing: Any, additions: tuple[str, ...]) -> list[str]:
|
||||
"""保留原别名顺序并追加未出现的新值,避免迁移重复执行产生配置噪声。"""
|
||||
merged = [str(value).strip() for value in existing or [] if str(value).strip()]
|
||||
known = set(merged)
|
||||
for value in additions:
|
||||
if value not in known:
|
||||
merged.append(value)
|
||||
known.add(value)
|
||||
return merged
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为唯一标准 Schema 的 V1 补齐邮件补充表别名,并更新已发布快照校验和。"""
|
||||
bind = op.get_bind()
|
||||
rows = bind.execute(sa.text("""
|
||||
SELECT version.id, version.definition_json
|
||||
FROM shipping_order_schema_versions AS version
|
||||
JOIN shipping_order_schemas AS schema ON schema.id = version.schema_id
|
||||
WHERE schema.schema_code = 'STANDARD_SHIPPING_NOTICE' AND version.version = 1
|
||||
""")).mappings().all()
|
||||
for row in rows:
|
||||
raw_definition = row['definition_json']
|
||||
definition = json.loads(raw_definition) if isinstance(raw_definition, str) else dict(raw_definition or {})
|
||||
fields = definition.get('fields') if isinstance(definition.get('fields'), list) else []
|
||||
changed = False
|
||||
for field in fields:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
additions = _ALIASES_BY_FIELD_CODE.get(str(field.get('field_code') or ''))
|
||||
if not additions:
|
||||
continue
|
||||
merged = _merge_aliases(field.get('aliases'), additions)
|
||||
if merged != field.get('aliases'):
|
||||
field['aliases'] = merged
|
||||
changed = True
|
||||
if changed:
|
||||
# [STEP] psycopg2 不能直接绑定 Python dict;写入规范化 JSON 字符串并显式 ::jsonb。
|
||||
bind.execute(sa.text("""
|
||||
UPDATE shipping_order_schema_versions
|
||||
SET definition_json = CAST(:definition_json AS jsonb), checksum = :checksum
|
||||
WHERE id = :version_id
|
||||
"""), {
|
||||
'version_id': int(row['id']),
|
||||
'definition_json': json.dumps(definition, ensure_ascii=False),
|
||||
'checksum': _definition_checksum(definition),
|
||||
})
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""配置数据迁移不可逆;保留新增别名以避免回滚后已冻结运行无法解释。"""
|
||||
pass
|
||||
@@ -0,0 +1,210 @@
|
||||
"""
|
||||
migrations/versions/3d6e8f0a1b2c_add_shipping_session_pdf_work_items.py
|
||||
|
||||
用途:创建会话 PDF 工作项表,并为审计事件追加会话/属主/客户端哈希字段。
|
||||
依赖:users、shipping_notice_documents、shipping_order_extraction_runs、
|
||||
shipping_order_review_cases、shipping_audit_events。
|
||||
逻辑:同会话同源 PDF 唯一;current_case_id 唯一保证单一当前有效 Case 指针;
|
||||
审计扩展列仅存脱敏哈希与软引用编号,不写原始 IP/UA。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '3d6e8f0a1b2c'
|
||||
down_revision = '2c5d7e9f1a2b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def _columns(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {column['name'] for column in inspector.get_columns(table_name)}
|
||||
|
||||
|
||||
def _indexes(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {index['name'] for index in inspector.get_indexes(table_name)}
|
||||
|
||||
|
||||
def _unique_constraints(inspector: sa.Inspector, table_name: str) -> set[str]:
|
||||
return {
|
||||
constraint['name']
|
||||
for constraint in inspector.get_unique_constraints(table_name)
|
||||
if constraint.get('name')
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建工作项表并扩展审计列;幂等跳过已存在对象。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
tables = set(inspector.get_table_names())
|
||||
|
||||
if 'shipping_session_pdf_work_items' not in tables:
|
||||
op.create_table(
|
||||
'shipping_session_pdf_work_items',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('item_no', sa.String(length=64), nullable=False),
|
||||
sa.Column('conversation_id', sa.String(length=100), nullable=False),
|
||||
sa.Column('owner_user_id', sa.Integer(), nullable=False),
|
||||
sa.Column('root_document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('current_document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('current_run_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_run_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('current_case_id', sa.Integer(), nullable=True),
|
||||
sa.Column('current_case_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('current_version_no', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column(
|
||||
'lifecycle_status',
|
||||
sa.String(length=32),
|
||||
nullable=False,
|
||||
server_default='pending_review',
|
||||
),
|
||||
sa.Column('closed_reason', sa.String(length=32), nullable=True),
|
||||
sa.Column('closed_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('lock_version', sa.Integer(), nullable=False, server_default='1'),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"lifecycle_status IN ("
|
||||
"'pending_review', 'extracting', 'reparse_failed', 'closed'"
|
||||
")",
|
||||
name='ck_shipping_session_pdf_work_items_lifecycle',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"closed_reason IS NULL OR closed_reason IN ("
|
||||
"'confirmed', 'non_order', 'user_cancelled', 'admin_terminated'"
|
||||
")",
|
||||
name='ck_shipping_session_pdf_work_items_closed_reason',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
'lock_version >= 1',
|
||||
name='ck_shipping_session_pdf_work_items_lock_version',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
'current_version_no >= 1',
|
||||
name='ck_shipping_session_pdf_work_items_version_no',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['owner_user_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['root_document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['current_document_id'], ['shipping_notice_documents.id']),
|
||||
sa.ForeignKeyConstraint(['current_run_id'], ['shipping_order_extraction_runs.id']),
|
||||
sa.ForeignKeyConstraint(['current_case_id'], ['shipping_order_review_cases.id']),
|
||||
sa.UniqueConstraint('item_no', name='uq_shipping_session_pdf_work_items_no'),
|
||||
sa.UniqueConstraint(
|
||||
'conversation_id',
|
||||
'root_document_id',
|
||||
name='uq_shipping_session_pdf_work_items_conversation_root_doc',
|
||||
),
|
||||
sa.UniqueConstraint(
|
||||
'current_case_id',
|
||||
name='uq_shipping_session_pdf_work_items_current_case',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_conversation_id',
|
||||
'shipping_session_pdf_work_items',
|
||||
['conversation_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_owner_user_id',
|
||||
'shipping_session_pdf_work_items',
|
||||
['owner_user_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_root_document_id',
|
||||
'shipping_session_pdf_work_items',
|
||||
['root_document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_current_document_id',
|
||||
'shipping_session_pdf_work_items',
|
||||
['current_document_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_current_run_id',
|
||||
'shipping_session_pdf_work_items',
|
||||
['current_run_id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_conversation_lifecycle',
|
||||
'shipping_session_pdf_work_items',
|
||||
['conversation_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_owner_lifecycle',
|
||||
'shipping_session_pdf_work_items',
|
||||
['owner_user_id', 'lifecycle_status', 'updated_at'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_session_pdf_work_items_open_conversation',
|
||||
'shipping_session_pdf_work_items',
|
||||
['conversation_id', 'updated_at'],
|
||||
postgresql_where=sa.text("lifecycle_status <> 'closed'"),
|
||||
sqlite_where=sa.text("lifecycle_status <> 'closed'"),
|
||||
)
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_audit_events' in set(inspector.get_table_names()):
|
||||
audit_cols = _columns(inspector, 'shipping_audit_events')
|
||||
if 'session_item_id' not in audit_cols:
|
||||
op.add_column(
|
||||
'shipping_audit_events',
|
||||
sa.Column('session_item_id', sa.String(length=64), nullable=True),
|
||||
)
|
||||
if 'owner_user_id' not in audit_cols:
|
||||
op.add_column(
|
||||
'shipping_audit_events',
|
||||
sa.Column('owner_user_id', sa.String(length=64), nullable=True),
|
||||
)
|
||||
if 'client_ip_hash' not in audit_cols:
|
||||
op.add_column(
|
||||
'shipping_audit_events',
|
||||
sa.Column('client_ip_hash', sa.String(length=64), nullable=True),
|
||||
)
|
||||
if 'user_agent_hash' not in audit_cols:
|
||||
op.add_column(
|
||||
'shipping_audit_events',
|
||||
sa.Column('user_agent_hash', sa.String(length=64), nullable=True),
|
||||
)
|
||||
inspector = sa.inspect(bind)
|
||||
audit_indexes = _indexes(inspector, 'shipping_audit_events')
|
||||
if 'ix_shipping_audit_events_session_item_created' not in audit_indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_session_item_created',
|
||||
'shipping_audit_events',
|
||||
['session_item_id', 'created_at'],
|
||||
)
|
||||
if 'ix_shipping_audit_events_owner_created' not in audit_indexes:
|
||||
op.create_index(
|
||||
'ix_shipping_audit_events_owner_created',
|
||||
'shipping_audit_events',
|
||||
['owner_user_id', 'created_at'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退审计扩展列与工作项表;不删除历史审计行数据语义由调用方保证。"""
|
||||
bind = op.get_bind()
|
||||
inspector = sa.inspect(bind)
|
||||
tables = set(inspector.get_table_names())
|
||||
|
||||
if 'shipping_audit_events' in tables:
|
||||
audit_indexes = _indexes(inspector, 'shipping_audit_events')
|
||||
if 'ix_shipping_audit_events_owner_created' in audit_indexes:
|
||||
op.drop_index('ix_shipping_audit_events_owner_created', table_name='shipping_audit_events')
|
||||
if 'ix_shipping_audit_events_session_item_created' in audit_indexes:
|
||||
op.drop_index(
|
||||
'ix_shipping_audit_events_session_item_created',
|
||||
table_name='shipping_audit_events',
|
||||
)
|
||||
audit_cols = _columns(inspector, 'shipping_audit_events')
|
||||
for column_name in ('user_agent_hash', 'client_ip_hash', 'owner_user_id', 'session_item_id'):
|
||||
if column_name in audit_cols:
|
||||
op.drop_column('shipping_audit_events', column_name)
|
||||
|
||||
inspector = sa.inspect(bind)
|
||||
if 'shipping_session_pdf_work_items' in set(inspector.get_table_names()):
|
||||
op.drop_table('shipping_session_pdf_work_items')
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/tests/performance/__init__.py
|
||||
|
||||
用途:货代进度/审计阶段 5 性能冒烟测试包标记。
|
||||
"""
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
backend/tests/performance/test_shipping_order_extraction_progress_load.py
|
||||
|
||||
用途:进度投影与审计查询的负载冒烟(阶段 5 压测门槛)。
|
||||
依赖:serialize_workspace_run、audit_query_service、create_order_extraction_run。
|
||||
逻辑:在同一 app context 内连续投影约 20 次(模拟前台轮询峰值);审计列表并发读用线程池,
|
||||
但业务事件计数必须稳定。SQLite 内存库不跨连接共享,故投影压测采用同会话快速重入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.audit_query_service import list_shipping_audit_events
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_rapid_workspace_projection_reads_are_stable(app):
|
||||
"""连续 20 次投影同一 Run(模拟轮询峰值)不得失败,且结果稳定、无写副作用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='LOAD-CONC')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
results = []
|
||||
for _ in range(20):
|
||||
payload = serialize_workspace_run(run)
|
||||
results.append({
|
||||
'stage': payload.get('user_visible_stage'),
|
||||
'actions': tuple(payload['available_actions']),
|
||||
'total': payload['summary']['total_documents'],
|
||||
'progress_version': payload.get('progress_version'),
|
||||
})
|
||||
|
||||
# 关键断言:只读投影可重入;阶段/动作/版本一致,不因轮询漂移。
|
||||
assert len(results) == 20
|
||||
assert len({item['stage'] for item in results}) == 1
|
||||
assert len({item['actions'] for item in results}) == 1
|
||||
assert len({item['progress_version'] for item in results}) == 1
|
||||
assert all('view_details' in item['actions'] or 'refresh_status' in item['actions'] for item in results)
|
||||
|
||||
|
||||
def test_concurrent_audit_list_reads_do_not_duplicate_business_events(app):
|
||||
"""并发审计列表只追加访问审计,不复制业务事件。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='load_probe',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-LOAD-AUDIT',
|
||||
run_no='SNER-LOAD-AUDIT',
|
||||
operation_id='op-load-1',
|
||||
)
|
||||
db.session.commit()
|
||||
before = list_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id='req-load-baseline',
|
||||
filters={'event_type': 'load_probe', 'run_no': 'SNER-LOAD-AUDIT'},
|
||||
)['total']
|
||||
|
||||
def _list_once(idx: int) -> int:
|
||||
with app.app_context():
|
||||
payload = list_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id=f'req-load-{idx}',
|
||||
filters={'event_type': 'load_probe', 'run_no': 'SNER-LOAD-AUDIT'},
|
||||
)
|
||||
return int(payload['total'])
|
||||
|
||||
totals = []
|
||||
# 审计列表在 testing 配置下可跨线程读同一库;若环境为纯内存 SQLite,退化为串行仍校验计数。
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
futures = [pool.submit(_list_once, i) for i in range(10)]
|
||||
for future in as_completed(futures):
|
||||
totals.append(future.result())
|
||||
except Exception:
|
||||
totals = [_list_once(i) for i in range(10)]
|
||||
|
||||
# 关键断言:业务事件计数稳定;访问审计不会伪装成 load_probe。
|
||||
assert before >= 1
|
||||
assert set(totals) == {before}
|
||||
@@ -14,12 +14,12 @@ from app.services.shipping_notice.order_supplement_merge import merge_email_supp
|
||||
|
||||
|
||||
SCHEMA = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number'},
|
||||
{'field_id': 'part', 'field_code': 'part_number'},
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id'},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'aliases': ['Reservation ID']},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
|
||||
]}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ def test_email_supplement_html_grid_merges_by_po_and_mpn_without_overwriting_pdf
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='a' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th><th>Source Type</th><th>Allocated Qty</th></tr><tr><td>4518738152</td><td>D4-A08AR12000002</td><td>2000484577</td><td>DSB CMH</td><td>99</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
supplement['document_id'] = 44
|
||||
assert supplement['rows'][0]['evidence']['reservation_id'] == {
|
||||
@@ -74,10 +75,40 @@ def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
"""邮件 PO 与 PDF 不一致时,唯一完全匹配 MPN 仍可保守补齐预约号。"""
|
||||
order = _order()
|
||||
order['header_fields'][0]['observations'][0]['value'] = '4518838152'
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518738152', 'mpn': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'po_number': '4518838154', 'mpn': 'B3-AR1000270A1',
|
||||
'reservation_id': '4000111701', 'evidence': {},
|
||||
},
|
||||
],
|
||||
}
|
||||
result = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert result['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text():
|
||||
"""Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。"""
|
||||
supplement = parse_email_allocation_text(
|
||||
content_hash='b' * 64,
|
||||
schema_definition=SCHEMA,
|
||||
body_text='''Hello\nallocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nThank you''',
|
||||
)
|
||||
assert supplement['rows'] == [{
|
||||
@@ -92,4 +123,14 @@ def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_b
|
||||
def test_email_supplement_plain_text_deduplicates_quoted_email_rows():
|
||||
"""转发邮件重复同一正文表时只保留一个事实行,避免制造补充关联冲突。"""
|
||||
body = '''allocation_id\nreservation_id\nsource_from_party\nsource_type\nallocated_entity\nmpn\nallocated_qty\nPO#\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152\nA-1\n2000484577\nWelltrust\nDSB CMH\nIEC-CJS\nD4-A08AR12000002\n30\n4518838152'''
|
||||
assert len(parse_email_allocation_text(body_text=body, content_hash='c' * 64)['rows']) == 1
|
||||
assert len(parse_email_allocation_text(body_text=body, content_hash='c' * 64, schema_definition=SCHEMA)['rows']) == 1
|
||||
|
||||
|
||||
def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
|
||||
"""正文 PO/MPN/预约号表头只接受冻结 Schema 明确维护的别名,不再使用代码白名单。"""
|
||||
result = parse_email_allocation_tables(
|
||||
content_hash='d' * 64,
|
||||
schema_definition={'fields': []},
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>4000111701</td></tr></table>'''],
|
||||
)
|
||||
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
|
||||
@@ -56,18 +56,18 @@ def test_table_contract_is_driven_only_by_explicit_schema_aliases():
|
||||
assert parse_notice_table_text(text, contract=None) == []
|
||||
|
||||
|
||||
def test_table_contract_rejects_normalized_alias_collision():
|
||||
"""大小写、全半角或标点差异归一后冲突时必须阻断 Schema 保存/发布。"""
|
||||
def test_table_contract_allows_case_distinct_aliases_and_matches_exact_case():
|
||||
"""Schema v1 的大小写不同别名独立存在,表头只能匹配完全相同的大小写。"""
|
||||
definition = _definition(
|
||||
_field('part_number', ['Customer P/N']),
|
||||
_field('customer_part_number', ['customer p n']),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
compile_table_header_contract(definition)
|
||||
contract = compile_table_header_contract(definition)
|
||||
|
||||
assert caught.value.code == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
assert caught.value.details['table_header_collisions']
|
||||
assert contract.header_to_field['Customer P N'] == 'part_number'
|
||||
assert contract.header_to_field['customer p n'] == 'customer_part_number'
|
||||
assert 'CUSTOMER PN' not in contract.header_to_field
|
||||
|
||||
|
||||
def test_table_contract_rejects_forbidden_reservation_header():
|
||||
@@ -101,9 +101,9 @@ def test_table_contract_excludes_disabled_and_unsupported_context_fields():
|
||||
_field('qty', ['Qty'], value_type='decimal'),
|
||||
))
|
||||
|
||||
assert 'disabled sku' not in contract.header_to_field
|
||||
assert 'sender' not in contract.header_to_field
|
||||
assert contract.header_to_field['qty'] == 'qty'
|
||||
assert 'Disabled SKU' not in contract.header_to_field
|
||||
assert 'Sender' not in contract.header_to_field
|
||||
assert contract.header_to_field['Qty'] == 'qty'
|
||||
|
||||
|
||||
def test_flat_table_parser_drops_zero_quantity_row():
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
"""
|
||||
backend/tests/test_shipping_access_audit_strict.py
|
||||
|
||||
用途:验证敏感访问审计必须逐次留存,失败时阻断调用。
|
||||
依赖:fulfillment_audit.record_access_audit、ShippingAuditEvent、pytest app fixture。
|
||||
逻辑:成功写入可查询;同资源连续两次访问落两条;模拟写入失败时 strict 抛错。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice import fulfillment_audit
|
||||
|
||||
|
||||
def test_access_audit_persists_and_is_queryable(app):
|
||||
"""敏感访问审计写入后可按 action/aggregate 检索。"""
|
||||
with app.app_context():
|
||||
wrote = fulfillment_audit.record_access_audit(
|
||||
action='view_order_extraction_run',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-1',
|
||||
actor_id=42,
|
||||
run_no='SNER-ACCESS-1',
|
||||
metadata={'status': 'processing'},
|
||||
)
|
||||
assert wrote is True
|
||||
row = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_resource_accessed',
|
||||
action='view_order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-1',
|
||||
).one()
|
||||
assert row.actor_id == '42'
|
||||
assert row.run_no == 'SNER-ACCESS-1'
|
||||
|
||||
|
||||
def test_access_audit_records_every_call(app):
|
||||
"""每次访问操作都必须独立留痕,禁止按窗口合并。"""
|
||||
with app.app_context():
|
||||
first = fulfillment_audit.record_access_audit(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-2',
|
||||
actor_id=7,
|
||||
run_no='SNER-ACCESS-2',
|
||||
)
|
||||
second = fulfillment_audit.record_access_audit(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-ACCESS-2',
|
||||
actor_id=7,
|
||||
run_no='SNER-ACCESS-2',
|
||||
)
|
||||
assert first is True
|
||||
assert second is True
|
||||
assert ShippingAuditEvent.query.filter_by(
|
||||
action='view_order_extraction_documents',
|
||||
aggregate_id='SNER-ACCESS-2',
|
||||
).count() == 2
|
||||
|
||||
|
||||
def test_access_audit_strict_raises_when_append_fails(app, monkeypatch):
|
||||
"""审计写入失败时必须抛错,禁止业务侧静默成功。"""
|
||||
with app.app_context():
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError('audit table down')
|
||||
|
||||
monkeypatch.setattr(fulfillment_audit, 'append_shipping_audit_event', _boom)
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
fulfillment_audit.record_access_audit(
|
||||
action='preview_order_review_document',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id='CASE-1',
|
||||
actor_id=1,
|
||||
review_case_no='CASE-1',
|
||||
strict=True,
|
||||
)
|
||||
assert exc.value.code == 'SHIPPING_NOTICE.AUDIT_PERSIST_FAILED'
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_end_to_end.py
|
||||
|
||||
用途:全链路审计关联键覆盖冒烟(上传取消 → 履约关键节点 → 查询 Diff/导出)。
|
||||
依赖:audit_service、fulfillment_audit、audit_query_service。
|
||||
逻辑:用同一 run_no/task_no/operation_id 串联多事件,验证可检索、可 Diff、导出无快照正文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
export_shipping_audit_events,
|
||||
get_shipping_audit_event,
|
||||
list_shipping_audit_events,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
def test_audit_chain_traceable_by_correlation_keys(app):
|
||||
"""关键节点审计均可通过 run_no/task_no/operation_id 追溯,导出不含快照。"""
|
||||
with app.app_context():
|
||||
run_no = 'SNER-E2E-1'
|
||||
task_no = 'ST-E2E-1'
|
||||
operation_id = 'op-e2e-chain-1'
|
||||
|
||||
cancel_event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_cancel_requested',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
operation_id=operation_id,
|
||||
request_id=operation_id,
|
||||
document_id='101',
|
||||
before={'status': 'processing'},
|
||||
after={'status': 'processing', 'cancellation_requested': True},
|
||||
action='cancel_run',
|
||||
)
|
||||
record_fulfillment_audit(
|
||||
event_type='candidate_promoted',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=task_no,
|
||||
action='promote_candidate',
|
||||
run_no=run_no,
|
||||
task_no=task_no,
|
||||
document_id='101',
|
||||
before={'status': 'candidate'},
|
||||
after={'status': 'task_created'},
|
||||
metadata={'operation_id': operation_id},
|
||||
)
|
||||
# fulfillment_audit 不自动 commit;与取消事件同事务提交。
|
||||
db.session.commit()
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-list',
|
||||
filters={'run_no': run_no},
|
||||
)
|
||||
event_types = {item['event_type'] for item in listed['items']}
|
||||
# 关键断言:取消与履约晋级都可按 run_no 检索。
|
||||
assert 'order_extraction_run_cancel_requested' in event_types
|
||||
assert 'candidate_promoted' in event_types
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-detail',
|
||||
event_id=int(cancel_event.id),
|
||||
)
|
||||
assert detail['operation_id'] == operation_id
|
||||
assert any(row['key'] == 'status' or row['key'] == 'cancellation_requested' for row in detail['diff'])
|
||||
|
||||
by_task = list_shipping_audit_events(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-task',
|
||||
filters={'task_no': task_no},
|
||||
)
|
||||
assert by_task['total'] >= 1
|
||||
|
||||
exported = export_shipping_audit_events(
|
||||
admin_user_id=42,
|
||||
request_id='req-e2e-export',
|
||||
filters={'run_no': run_no},
|
||||
format='csv',
|
||||
)
|
||||
assert run_no in exported['content']
|
||||
assert operation_id in exported['content']
|
||||
assert 'before_snapshot' not in exported['content']
|
||||
assert 'email_body' not in exported['content']
|
||||
|
||||
access = ShippingAuditEvent.query.filter_by(event_type='audit_access').count()
|
||||
assert access >= 3
|
||||
@@ -1,7 +1,9 @@
|
||||
"""验证货代统一审计事件的脱敏和 append-only 契约。
|
||||
"""
|
||||
backend/tests/test_shipping_audit_event.py
|
||||
|
||||
依赖:ShippingAuditEvent、audit_service、SQLAlchemy 内存会话。
|
||||
逻辑:审计写入只保存状态哈希和受控元数据;更新、删除或敏感内容均必须被拒绝。
|
||||
用途:验证货代统一审计事件的脱敏、白名单快照和 append-only 契约。
|
||||
依赖:ShippingAuditEvent、audit_service、progress_audit_contract、SQLAlchemy 内存会话。
|
||||
逻辑:审计写入只保存白名单快照/哈希和受控元数据;更新、删除或敏感内容均必须被拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,26 +13,92 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.audit_service import (
|
||||
append_shipping_audit_event,
|
||||
hash_client_context_value,
|
||||
project_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_FORBIDDEN_KEYS,
|
||||
AUDIT_RETENTION_DAYS,
|
||||
I18N_KEY_INVENTORY,
|
||||
)
|
||||
|
||||
|
||||
def test_append_shipping_audit_event_hashes_state_and_rejects_sensitive_metadata(app):
|
||||
"""状态审计仅保存前后哈希,正文或凭据类元数据必须在入库前拒绝。"""
|
||||
"""状态审计保存白名单快照与哈希,正文或凭据类元数据必须在入库前拒绝。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed', aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-1', run_no='SNER-1', before={'status': 'queued'},
|
||||
after={'status': 'running'}, metadata={'target_status': 'running'},
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-1',
|
||||
run_no='SNER-1',
|
||||
operation_id='op-stage0-1',
|
||||
before={'status': 'queued'},
|
||||
after={'status': 'processing'},
|
||||
metadata={'target_status': 'processing'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:可追溯性来自哈希而不是把订单、邮件正文写进审计表。
|
||||
# 关键断言:可追溯性来自哈希与白名单快照,而不是把订单、邮件正文写进审计表。
|
||||
assert event.before_hash and event.after_hash
|
||||
assert event.metadata_json == {'target_status': 'running'}
|
||||
with pytest.raises(ValidationError, match='forbidden'):
|
||||
assert event.before_snapshot_json == {'status': 'queued'}
|
||||
assert event.after_snapshot_json == {'status': 'processing'}
|
||||
assert event.operation_id == 'op-stage0-1'
|
||||
assert event.metadata_json == {'target_status': 'processing'}
|
||||
assert event.retention_expires_at is not None
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='invalid', aggregate_type='run', aggregate_id='1', metadata={'email_body': 'secret'},
|
||||
event_type='invalid',
|
||||
aggregate_type='run',
|
||||
aggregate_id='1',
|
||||
metadata={'email_body': 'secret'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('forbidden_key', sorted(AUDIT_FORBIDDEN_KEYS))
|
||||
def test_audit_forbidden_keys_blacklist_rejects_metadata_and_snapshot(app, forbidden_key: str):
|
||||
"""阶段 0 冻结的敏感键黑名单必须对元数据与快照同时生效。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as meta_err:
|
||||
append_shipping_audit_event(
|
||||
event_type='probe',
|
||||
aggregate_type='run',
|
||||
aggregate_id='SNER-BL',
|
||||
metadata={forbidden_key: 'x'},
|
||||
)
|
||||
assert meta_err.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
|
||||
with pytest.raises(ValidationError) as snap_err:
|
||||
project_audit_snapshot({'status': 'queued', forbidden_key: 'x'})
|
||||
assert snap_err.value.code == 'SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_audit_snapshot_whitelist_strips_unknown_business_keys(app):
|
||||
"""未授权业务键不得进入快照;敏感键仍被拒绝。"""
|
||||
with app.app_context():
|
||||
projected = project_audit_snapshot({
|
||||
'status': 'extracting',
|
||||
'progress_version': 3,
|
||||
'orders': [{'po': '45001'}],
|
||||
})
|
||||
assert projected == {'status': 'extracting', 'progress_version': 3}
|
||||
|
||||
|
||||
def test_audit_evidence_refs_reject_url_payload(app):
|
||||
"""证据引用禁止携带对象存储 URL 等敏感键。"""
|
||||
with app.app_context():
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='evidence_viewed',
|
||||
aggregate_type='document',
|
||||
aggregate_id='12',
|
||||
evidence_refs=[{'file_asset_id': 9, 'url': 'https://minio.example/x'}],
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_SNAPSHOT_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
@@ -50,3 +118,55 @@ def test_shipping_audit_event_rejects_orm_update_and_delete(app):
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_append_shipping_audit_event_hashes_client_context_and_session_item(app):
|
||||
"""会话工作项审计必须记录属主/工作项软引用,且 IP/UA 仅存哈希。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='session_work_item_created',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='SPWI-1',
|
||||
session_item_id='SPWI-1',
|
||||
owner_user_id=42,
|
||||
conversation_id='conv-session-1',
|
||||
client_ip='203.0.113.9',
|
||||
user_agent='Mozilla/5.0 TestAgent',
|
||||
after={
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
},
|
||||
metadata={'source': 'upload'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
assert event.session_item_id == 'SPWI-1'
|
||||
assert event.owner_user_id == '42'
|
||||
assert event.client_ip_hash == hash_client_context_value('203.0.113.9')
|
||||
assert event.user_agent_hash == hash_client_context_value('Mozilla/5.0 TestAgent')
|
||||
assert event.client_ip_hash != '203.0.113.9'
|
||||
assert event.after_snapshot_json == {
|
||||
'lifecycle_status': 'pending_review',
|
||||
'current_version_no': 1,
|
||||
'item_no': 'SPWI-1',
|
||||
}
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
append_shipping_audit_event(
|
||||
event_type='probe',
|
||||
aggregate_type='session_pdf_work_item',
|
||||
aggregate_id='SPWI-2',
|
||||
metadata={'client_ip': '203.0.113.9'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN'
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_stage0_i18n_key_inventory_is_frozen():
|
||||
"""四语言所需 key 清单必须冻结且覆盖阶段/健康/取消/审计错误前缀。"""
|
||||
assert AUDIT_RETENTION_DAYS == 365 * 3
|
||||
joined = '\n'.join(I18N_KEY_INVENTORY)
|
||||
assert 'shippingOrderExtractionUserStage.cancellation_requested' in joined
|
||||
assert 'shippingOrderExtractionHealthTip.processing_attention' in joined
|
||||
assert 'SHIPPING_NOTICE.CANCEL_REASON_REQUIRED' in joined
|
||||
assert 'admin.shippingAudit.export' in joined
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
backend/tests/test_shipping_audit_query_service.py
|
||||
|
||||
用途:验证货代审计查询、白名单 Diff、受控导出与到期清理契约。
|
||||
依赖:audit_query_service、audit_service、ShippingAuditEvent、进度审计契约。
|
||||
逻辑:列表/详情/导出必须写访问审计且不泄露快照正文;清理经 Core DELETE 绕过 append-only 守卫。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
export_shipping_audit_events,
|
||||
get_shipping_audit_event,
|
||||
list_shipping_audit_events,
|
||||
purge_expired_shipping_audit_events,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def test_list_and_detail_write_access_audit_and_whitelist_diff(app):
|
||||
"""列表不含快照全文;详情仅返回白名单 Diff,并分别写访问审计。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-AUDIT-Q1',
|
||||
run_no='SNER-AUDIT-Q1',
|
||||
operation_id='op-audit-q1',
|
||||
before={'status': 'queued', 'progress_version': 1},
|
||||
after={'status': 'processing', 'progress_version': 2},
|
||||
metadata={'target_status': 'processing'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=9001,
|
||||
request_id='req-list-1',
|
||||
page=1,
|
||||
page_size=25,
|
||||
filters={'run_no': 'SNER-AUDIT-Q1'},
|
||||
)
|
||||
# 关键断言:列表可发现业务事件,但不回传 before/after 快照。
|
||||
assert listed['total'] >= 1
|
||||
summary = next(item for item in listed['items'] if item['id'] == event.id)
|
||||
assert summary['has_snapshots'] is True
|
||||
assert 'before_snapshot' not in summary
|
||||
assert 'diff' not in summary
|
||||
|
||||
detail = get_shipping_audit_event(
|
||||
admin_user_id=9001,
|
||||
request_id='req-detail-1',
|
||||
event_id=int(event.id),
|
||||
)
|
||||
# 关键断言:Diff 仅覆盖白名单键变化,不夹带订单正文类字段。
|
||||
assert detail['before_snapshot'] == {'status': 'queued', 'progress_version': 1}
|
||||
assert detail['after_snapshot'] == {'status': 'processing', 'progress_version': 2}
|
||||
changed_keys = {row['key'] for row in detail['diff']}
|
||||
assert changed_keys == {'progress_version', 'status'}
|
||||
|
||||
access_events = ShippingAuditEvent.query.filter_by(event_type='audit_access').all()
|
||||
actions = {row.action for row in access_events}
|
||||
assert 'list_audit_events' in actions
|
||||
assert 'get_audit_event' in actions
|
||||
|
||||
|
||||
def test_export_csv_omits_snapshots_and_writes_access_audit(app):
|
||||
"""CSV 导出仅稳定列,禁止快照全文,并写导出访问审计。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='candidate_promoted',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id='ST-1',
|
||||
run_no='SNER-AUDIT-Q2',
|
||||
task_no='ST-1',
|
||||
before={'status': 'candidate'},
|
||||
after={'status': 'task_created'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
exported = export_shipping_audit_events(
|
||||
admin_user_id=9002,
|
||||
request_id='req-export-1',
|
||||
filters={'run_no': 'SNER-AUDIT-Q2'},
|
||||
limit=100,
|
||||
format='csv',
|
||||
)
|
||||
# 关键断言:导出正文不含 snapshot / email_body 等敏感字段名。
|
||||
content = exported['content']
|
||||
assert 'event_type' in content
|
||||
assert 'SNER-AUDIT-Q2' in content
|
||||
assert 'before_snapshot' not in content
|
||||
assert 'email_body' not in content
|
||||
assert exported['exported'] >= 1
|
||||
|
||||
access = ShippingAuditEvent.query.filter_by(
|
||||
event_type='audit_access',
|
||||
action='export_audit_events',
|
||||
).first()
|
||||
assert access is not None
|
||||
assert access.metadata_json.get('format') == 'csv'
|
||||
|
||||
|
||||
def test_list_filters_session_work_item_context_fields(app):
|
||||
"""会话工作项相关筛选:conversation / session_item / case / owner 精确匹配。"""
|
||||
with app.app_context():
|
||||
target = append_shipping_audit_event(
|
||||
event_type='session_work_item_reparse_started',
|
||||
aggregate_type='shipping_session_pdf_work_item',
|
||||
aggregate_id='SPWI-FILTER-1',
|
||||
conversation_id='conv-filter-1',
|
||||
session_item_id='SPWI-FILTER-1',
|
||||
review_case_no='SRC-FILTER-1',
|
||||
owner_user_id='8801',
|
||||
run_no='SNER-FILTER-1',
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='session_work_item_reparse_started',
|
||||
aggregate_type='shipping_session_pdf_work_item',
|
||||
aggregate_id='SPWI-FILTER-2',
|
||||
conversation_id='conv-filter-2',
|
||||
session_item_id='SPWI-FILTER-2',
|
||||
review_case_no='SRC-FILTER-2',
|
||||
owner_user_id='8802',
|
||||
run_no='SNER-FILTER-2',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=9003,
|
||||
request_id='req-filter-1',
|
||||
page=1,
|
||||
page_size=25,
|
||||
filters={
|
||||
'conversation_id': 'conv-filter-1',
|
||||
'session_item_id': 'SPWI-FILTER-1',
|
||||
'review_case_no': 'SRC-FILTER-1',
|
||||
'owner_user_id': '8801',
|
||||
},
|
||||
)
|
||||
# 关键断言:四字段联合筛选仅命中目标事件。
|
||||
assert listed['total'] == 1
|
||||
assert listed['items'][0]['id'] == int(target.id)
|
||||
assert listed['items'][0]['session_item_id'] == 'SPWI-FILTER-1'
|
||||
assert listed['items'][0]['owner_user_id'] == '8801'
|
||||
|
||||
|
||||
def test_purge_expired_supports_dry_run_and_core_delete(app):
|
||||
"""到期清理支持 dry_run;正式删除经 Core DELETE 并写清理审计。"""
|
||||
with app.app_context():
|
||||
expired = append_shipping_audit_event(
|
||||
event_type='legacy_probe',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-EXPIRED',
|
||||
run_no='SNER-EXPIRED',
|
||||
retention_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
)
|
||||
db.session.commit()
|
||||
expired_id = int(expired.id)
|
||||
|
||||
dry = purge_expired_shipping_audit_events(limit=100, dry_run=True)
|
||||
# 关键断言:演练只扫描不删除。
|
||||
assert dry['dry_run'] is True
|
||||
assert dry['scanned'] >= 1
|
||||
assert dry['deleted'] == 0
|
||||
assert db.session.get(ShippingAuditEvent, expired_id) is not None
|
||||
|
||||
result = purge_expired_shipping_audit_events(limit=100, dry_run=False)
|
||||
assert result['dry_run'] is False
|
||||
assert result['deleted'] >= 1
|
||||
# SQLite 可能复用已删主键;以业务事件类型断言清理结果,不以旧 id 缺失为准。
|
||||
assert ShippingAuditEvent.query.filter_by(
|
||||
event_type='legacy_probe',
|
||||
aggregate_id='SNER-EXPIRED',
|
||||
).first() is None
|
||||
|
||||
purge_audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='audit_retention_purged',
|
||||
).order_by(ShippingAuditEvent.id.desc()).first()
|
||||
assert purge_audit is not None
|
||||
assert purge_audit.metadata_json.get('deleted') >= 1
|
||||
@@ -8,6 +8,8 @@ backend/tests/test_shipping_customer_shadow_resolution.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
@@ -165,6 +167,41 @@ def test_accepted_field_value_resolves_customer_without_mail_header_bypass(app):
|
||||
assert case.customer_id is None and case.business_no is None
|
||||
|
||||
|
||||
def test_schema_uuid_drift_keeps_stable_customer_identity_rule_matching(app):
|
||||
"""新版 Schema 仅重建字段 UUID 时,规则按同 field_code 映射并保留实际取值字段证据。"""
|
||||
with app.app_context():
|
||||
field, original_version = _published_field(code='ship_to_customer')
|
||||
definition, _rule_set = _definition(field)
|
||||
customer = _customer('Inventech Corp Mexico', 'IVMX')
|
||||
identity_rules.create_evidence(
|
||||
target_type='customer', target_id=customer.id,
|
||||
data={'definition_id': definition['id'], 'raw_value': 'Inventec IEC Technologies c/o EP Logistics LLC', 'status': 'approved'},
|
||||
actor_id=1,
|
||||
)
|
||||
original_version.status = 'retired'
|
||||
replacement_field_id = str(uuid.uuid4())
|
||||
replacement_version = ShippingOrderSchemaVersion(
|
||||
schema_id=original_version.schema_id, version=original_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': replacement_field_id, 'field_code': 'ship_to_customer', 'display_name': 'ship_to_customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True, 'available_for_customer_identity': True,
|
||||
'normalizer_key': 'lowercase_trim',
|
||||
}]},
|
||||
checksum='f' * 64, lock_version=1,
|
||||
)
|
||||
db.session.add(replacement_version)
|
||||
db.session.flush()
|
||||
_intake, candidate = _seed_candidate()
|
||||
replacement_field = type('ReplacementField', (), {'id': replacement_field_id})()
|
||||
_attach_value(candidate, replacement_version, replacement_field, 'Inventec IEC Technologies c/o EP Logistics LLC')
|
||||
|
||||
resolution = refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
assert resolution.status == 'unique_candidate'
|
||||
assert resolution.top_customer_id == customer.id
|
||||
assert resolution.evidence_json[0]['context_field_id'] == replacement_field_id
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status', ['needs_review', 'blocked', 'missing'])
|
||||
def test_unaccepted_field_values_never_become_identity_evidence(app, status):
|
||||
"""非 accepted/corroborated 值及原始 LLM JSON 均不能进入客户识别。"""
|
||||
|
||||
@@ -194,6 +194,11 @@ def test_independent_sample_review_reuses_existing_truth_and_excludes_training_i
|
||||
|
||||
available = quality.list_independent_samples(suite_id=suite['id'], actor_id=user.id)['samples']
|
||||
assert {item['document_id'] for item in available} == {documents[1].id, documents[2].id}
|
||||
# 候选下拉必须能区分同页多表,且不回传 HTML、坐标或内部布局内容。
|
||||
assert available[0]['table_index'] == 1
|
||||
assert available[0]['row_count'] > 0 and available[0]['column_count'] > 0
|
||||
assert available[0]['header_preview']
|
||||
assert 'html' not in available[0] and 'bbox' not in available[0]
|
||||
candidate = quality.preview_independent_sample(
|
||||
suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', actor_id=user.id,
|
||||
)
|
||||
@@ -472,6 +477,21 @@ def test_draft_publish_requires_current_approved_blind_test(app):
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
|
||||
|
||||
|
||||
def test_draft_publish_requires_static_document_anchor(app):
|
||||
"""关键断言:零必填锚点的模板不能发布,避免成为匹配所有 PDF 的通配模板。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
with app.app_context():
|
||||
profile, _user, _documents = _published_profile_with_samples()
|
||||
profile.status = 'draft'
|
||||
profile.definition_json = {'document_match': {'required_anchors': []}}
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality.assert_profile_publishable(profile)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_REQUIRED_ANCHOR'
|
||||
|
||||
|
||||
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
"""关键断言:v2 草稿在训练、独立多明细盲测通过后可发布,并冻结正式 checksum 凭证。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
@@ -1065,6 +1065,52 @@ def test_selected_eml_attachments_use_bounded_parallel_deep_extraction(app, ship
|
||||
]
|
||||
|
||||
|
||||
def test_eml_materialization_rejects_missing_selected_document(app, shipping_user, monkeypatch):
|
||||
"""已选附件未落成 Document 时,必须停止在输入准备阶段而非误报版面服务故障。"""
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
import app.services.shipping_notice.order_extraction_materialization as materialization
|
||||
|
||||
with app.app_context():
|
||||
asset, intake = _seed_parsed_intake(shipping_user.id, intake_no='SNI-MISSING-SELECTED-DOCUMENT')
|
||||
asset.original_filename = 'orders.eml'
|
||||
asset.mime_type = 'message/rfc822'
|
||||
db.session.commit()
|
||||
|
||||
def _preview_result(_asset, **_kwargs):
|
||||
return NoticeIntakeResult(
|
||||
filename='orders.eml', source_type='email', source_file_type='message/rfc822',
|
||||
text='mail preview', warnings=[], meta={'attachments': [
|
||||
{
|
||||
'attachment_key': 'att-002', 'filename': 'order.pdf',
|
||||
'mime_type': 'application/pdf', '_payload_bytes': b'pdf',
|
||||
},
|
||||
]},
|
||||
content_hash=str(asset.content_hash), file_size=12, status='accepted', saved_path=None,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(materialization, 'extract_notice_from_asset', _preview_result)
|
||||
# 关键断言:即使持久化层异常静默返回,也不能让空输入进入后续版面调度。
|
||||
monkeypatch.setattr(materialization, 'persist_intake_documents', lambda **_kwargs: {'document_count': 0})
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
materialization.ensure_order_extraction_input_documents(
|
||||
intakes=[intake],
|
||||
attachment_selection={
|
||||
'items': [{
|
||||
'intake_no': intake.intake_no,
|
||||
'attachment_key': 'att-002',
|
||||
'selected': True,
|
||||
'selection_batch': 1,
|
||||
}],
|
||||
},
|
||||
schema_definition={'fields': []},
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE'
|
||||
assert exc_info.value.details['reason'] == 'selected_attachment_document_missing'
|
||||
assert exc_info.value.details['missing_attachment_keys'] == ['att-002']
|
||||
|
||||
|
||||
def test_selected_normal_files_use_global_bounded_parallel_extraction(app, shipping_user, monkeypatch):
|
||||
"""不同普通文件共享首轮并发预算,完成顺序不得改变主线程持久化顺序。"""
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
|
||||
@@ -87,7 +87,7 @@ def _coordinate_definition() -> dict:
|
||||
"""构造最小 v2 坐标模板,供来源授权和服务端 field_id 冻结断言使用。"""
|
||||
return {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'text': 'PURCHASE ORDER'}]},
|
||||
'document_match': {'required_anchors': [{'anchor_id': 'po_title', 'label': 'DOCUMENT TYPE:', 'value': 'PURCHASE ORDER', 'value_position': 'right'}]},
|
||||
'table_regions': [{
|
||||
'region_id': 'main_lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
||||
@@ -614,6 +614,38 @@ def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, mon
|
||||
).one().id == replacement['id']
|
||||
|
||||
|
||||
def test_clone_draft_inherits_annotation_sample_but_not_training_sample(app, monkeypatch):
|
||||
"""从已发布模板新建草稿时,编辑器 PDF 画布可用且不会复用训练发布资格。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _profile: None,
|
||||
)
|
||||
schema = _schema_version()
|
||||
source = service.save_draft(_data(schema.id), actor_id=None)
|
||||
annotation = _bind_ready_profile_sample(
|
||||
source['id'], sample_role='annotation', table_id='annotation-table', filename='annotation.pdf',
|
||||
)
|
||||
_bind_ready_profile_sample(
|
||||
source['id'], sample_role='training', table_id='training-table', filename='training.pdf',
|
||||
)
|
||||
published = service.publish(
|
||||
source['id'], actor_id=None, expected_lock_version=source['lock_version'],
|
||||
)
|
||||
|
||||
clone = service.clone_draft(published['id'], actor_id=None)
|
||||
inherited = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=clone['id']).all()
|
||||
|
||||
assert [(sample.document_id, sample.table_id, sample.sample_role) for sample in inherited] == [
|
||||
(annotation.document_id, 'annotation-table', 'annotation'),
|
||||
]
|
||||
assert db.session.get(ShippingOrderDocumentProfile, clone['id']).training_sample_count == 0
|
||||
audit = ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
profile_id=clone['id'], event_type='draft_cloned',
|
||||
).one()
|
||||
assert audit.detail_json['inherited_annotation_sample_count'] == 1
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=published['id']).count() == 2
|
||||
|
||||
|
||||
def test_profile_publish_rolls_back_when_sample_layout_hash_drifts(app, monkeypatch):
|
||||
"""样本文件与 ready Layout hash 不一致时必须整体回滚,旧 published 不能被部分退役。"""
|
||||
with app.app_context():
|
||||
@@ -949,8 +981,8 @@ def test_profile_definition_validation_exposes_first_invalid_field_path(app):
|
||||
assert getattr(caught.value, 'details', {}).get('field_path') == 'table_regions.0.line_layouts.0.region'
|
||||
|
||||
|
||||
def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
"""普通用户不能维护 Profile;管理员错误使用统一业务 envelope。"""
|
||||
def test_profile_admin_api_rejects_legacy_unbound_draft_creation(app):
|
||||
"""关键断言:旧创建入口不得绕过向导生成没有 annotation/training 样本的草稿。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
@@ -969,54 +1001,13 @@ def test_profile_admin_api_requires_admin_and_uses_standard_errors(app):
|
||||
)
|
||||
assert denied.status_code == 403
|
||||
|
||||
created = client.post(
|
||||
rejected = client.post(
|
||||
'/api/admin/shipping-notice/order-document-profiles',
|
||||
json=_data(schema_id),
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert created.status_code == 201
|
||||
payload = parse_api_data(created.get_json())
|
||||
assert payload['profile_code'] == 'PO_312207'
|
||||
|
||||
lease = client.post(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}/edit-lease",
|
||||
json={'browser_session_id': 'profile-admin-tab', 'operation_id': 'profile-admin-lease'},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert lease.status_code == 201
|
||||
lease_payload = parse_api_data(lease.get_json())
|
||||
|
||||
invalid_definition = _data(schema_id)
|
||||
invalid_definition['definition']['table_regions'][0]['line_layouts'][0]['region']['x1'] = 0
|
||||
invalid = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={
|
||||
**invalid_definition,
|
||||
'expected_lock_version': payload['lock_version'],
|
||||
'browser_session_id': 'profile-admin-tab',
|
||||
'lease_token': lease_payload['lease_token'],
|
||||
'operation_id': 'profile-admin-invalid-definition',
|
||||
},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert invalid.status_code == 400
|
||||
invalid_error = parse_api_error(invalid.get_json())
|
||||
assert invalid_error['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
assert invalid_error['details']['field_path'] == 'table_regions.0.line_layouts.0.region'
|
||||
|
||||
conflict = client.put(
|
||||
f"/api/admin/shipping-notice/order-document-profiles/{payload['id']}",
|
||||
json={
|
||||
**_data(schema_id),
|
||||
'expected_lock_version': payload['lock_version'] + 1,
|
||||
'browser_session_id': 'profile-admin-tab',
|
||||
'lease_token': lease_payload['lease_token'],
|
||||
'operation_id': 'profile-admin-stale-save',
|
||||
},
|
||||
headers={'X-Username': 'profile-admin', 'X-Role': 'admin'},
|
||||
)
|
||||
assert conflict.status_code == 409
|
||||
assert parse_api_error(conflict.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT'
|
||||
assert rejected.status_code == 400
|
||||
assert parse_api_error(rejected.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_profile_sample_api_supports_secure_preview_create_and_version_update(app, monkeypatch):
|
||||
@@ -1281,6 +1272,38 @@ def test_profile_page_preview_uses_memory_fallback_in_development(app, monkeypat
|
||||
assert store.getdel('preview-token') is None
|
||||
|
||||
|
||||
def test_preview_page_region_text_reads_only_the_admin_selected_glyphs(app, monkeypatch):
|
||||
"""画布创建匹配锚点时必须只读取框选坐标内文字,备注中的同名文本不能混入。"""
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': [
|
||||
{'text': 'P', 'bbox': {'x0': 10, 'y0': 10, 'x1': 14, 'y1': 18}},
|
||||
{'text': 'O', 'bbox': {'x0': 15, 'y0': 10, 'x1': 19, 'y1': 18}},
|
||||
{'text': ':', 'bbox': {'x0': 20, 'y0': 10, 'x1': 24, 'y1': 18}},
|
||||
{'text': 'P', 'bbox': {'x0': 10, 'y0': 60, 'x1': 14, 'y1': 68}},
|
||||
{'text': 'O', 'bbox': {'x0': 15, 'y0': 60, 'x1': 19, 'y1': 68}},
|
||||
]},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
document = type('Document', (), {'id': 108})()
|
||||
monkeypatch.setattr(service, '_bound_sample_document', lambda *_args: document)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
monkeypatch.setattr(service, '_ensure_page_coordinate_evidence', lambda **_kwargs: layout)
|
||||
with app.app_context():
|
||||
result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 108, 'region': {'x0': .05, 'y0': .05, 'x1': .3, 'y1': .3}}, page_no=1, actor_id=1,
|
||||
)
|
||||
assert result['text'] == 'PO:'
|
||||
assert result['source'] == 'pdf_coordinate'
|
||||
# Center selection excludes the preceding P instead of pulling a neighboring line.
|
||||
edge_result = service.read_preview_page_region_text(
|
||||
1, data={'document_id': 108, 'region': {'x0': .139, 'y0': .1, 'x1': .245, 'y1': .18}}, page_no=1, actor_id=1,
|
||||
)
|
||||
assert edge_result['text'] == 'O:'
|
||||
|
||||
|
||||
def test_profile_region_preview_requires_a_bound_document(app, monkeypatch):
|
||||
"""局部预览只能作用于当前模板样本,避免管理员接口被 document_id 枚举越权。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_cancel.py
|
||||
|
||||
用途:验收订单抽取 Run/Unit 取消请求、权限、已完成保留与审计原子性。
|
||||
依赖:order_extraction_cancel_service、Run/Unit/Plan ORM、ShippingAuditEvent、进度事件。
|
||||
逻辑:排队 Unit 立即取消;执行中写 cancellation_requested;管理员代取消必须写原因;
|
||||
业务与审计同事务,敏感快照不得含正文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionUnit,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import (
|
||||
apply_worker_cancellation_checkpoint,
|
||||
cancel_order_extraction_run,
|
||||
cancel_order_extraction_unit,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def _attach_units(run, *, statuses: list[str], document_ids: list[int] | None = None) -> list[ShippingOrderExtractionUnit]:
|
||||
"""为测试 Run 物化计划与给定状态的 Unit。"""
|
||||
plan = ShippingOrderExtractionPlan(
|
||||
run_id=run.id,
|
||||
plan_version='shipping_order_extraction.plan.v1',
|
||||
input_snapshot_hash=run.input_snapshot_hash,
|
||||
status='running',
|
||||
unit_count=len(statuses),
|
||||
)
|
||||
db.session.add(plan)
|
||||
db.session.flush()
|
||||
units: list[ShippingOrderExtractionUnit] = []
|
||||
intake_id = int(run.intakes[0].intake_id)
|
||||
for index, status in enumerate(statuses):
|
||||
document_id = int(document_ids[index]) if document_ids and index < len(document_ids) else index + 1
|
||||
unit = ShippingOrderExtractionUnit(
|
||||
plan_id=plan.id,
|
||||
intake_id=intake_id,
|
||||
document_id=document_id,
|
||||
position=index,
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
content_hash=f'hash-{index}',
|
||||
status=status,
|
||||
started_at=datetime.utcnow() if status != 'pending' else None,
|
||||
)
|
||||
db.session.add(unit)
|
||||
units.append(unit)
|
||||
db.session.flush()
|
||||
run.extraction_plan = plan
|
||||
return units
|
||||
|
||||
|
||||
def test_cancel_pending_run_completes_immediately_and_writes_audit(app):
|
||||
"""排队中整批取消应立即收口,并同事务写入进度与审计。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-PENDING')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
units = _attach_units(run, statuses=['pending'], document_ids=[document.id])
|
||||
db.session.commit()
|
||||
|
||||
cancel_order_extraction_run(actor=user, run_no=run.run_no, reason_code='user_cancelled')
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(run)
|
||||
# 关键断言:排队取消立即终态,PDF 为 cancelled。
|
||||
assert run.status == 'cancelled'
|
||||
assert run.cancellation_requested_at is not None
|
||||
assert run.cancellation_completed_at is not None
|
||||
assert all(unit.status == 'cancelled' for unit in units)
|
||||
events = ShippingOrderExtractionProgressEvent.query.filter_by(run_id=run.id).all()
|
||||
codes = {event.event_code for event in events}
|
||||
assert 'cancellation_completed' in codes or 'unit_cancelled' in codes
|
||||
audits = ShippingAuditEvent.query.filter(ShippingAuditEvent.run_no == run.run_no).all()
|
||||
assert any(event.action == 'cancel_run' for event in audits)
|
||||
assert all('email_body' not in (event.metadata_json or {}) for event in audits)
|
||||
|
||||
|
||||
def test_cancel_inflight_unit_requests_then_worker_checkpoint_completes(app):
|
||||
"""执行中取消先进入正在取消,Worker 检查点后才生效并保留已完成 PDF。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-INFLIGHT')
|
||||
second = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-2.pdf',
|
||||
filename='orders-2.pdf',
|
||||
content_hash='b' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 2 QTY 1',
|
||||
)
|
||||
third = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-3.pdf',
|
||||
filename='orders-3.pdf',
|
||||
content_hash='c' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO 3 QTY 1',
|
||||
)
|
||||
db.session.add_all([second, third])
|
||||
db.session.flush()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ready, extracting, pending = _attach_units(
|
||||
run,
|
||||
statuses=['candidate_ready', 'extracting', 'pending'],
|
||||
document_ids=[document.id, second.id, third.id],
|
||||
)
|
||||
run.status = 'processing'
|
||||
run.phase = 'deterministic_parsing'
|
||||
db.session.commit()
|
||||
|
||||
cancel_order_extraction_run(actor=user, run_no=run.run_no)
|
||||
db.session.commit()
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(ready)
|
||||
db.session.refresh(extracting)
|
||||
db.session.refresh(pending)
|
||||
|
||||
# 关键断言:已完成保留;执行中为请求态;排队已取消;Run 尚未伪造为已取消。
|
||||
assert ready.status == 'candidate_ready'
|
||||
assert pending.status == 'cancelled'
|
||||
assert extracting.status == 'extracting'
|
||||
assert extracting.cancellation_requested_at is not None
|
||||
assert run.status == 'processing'
|
||||
projection = serialize_workspace_run(run)
|
||||
assert projection['user_visible_stage'] == 'cancellation_requested'
|
||||
assert projection['summary']['cancelled_documents'] == 1
|
||||
assert projection['summary']['completed_documents'] == 1
|
||||
|
||||
apply_worker_cancellation_checkpoint(run=run)
|
||||
db.session.commit()
|
||||
db.session.refresh(run)
|
||||
db.session.refresh(extracting)
|
||||
assert extracting.status == 'cancelled'
|
||||
assert run.status == 'cancelled'
|
||||
assert run.cancellation_completed_at is not None
|
||||
|
||||
|
||||
def test_admin_cancel_other_user_run_requires_reason(app):
|
||||
"""管理员取消他人任务必须填写原因,否则校验失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-ADMIN')
|
||||
admin = User(username='cancel-admin', email='cancel-admin@example.com', password_hash='x', role='admin')
|
||||
db.session.add(admin)
|
||||
db.session.flush()
|
||||
from app.models import ShippingOrderExtractionRun, ShippingOrderExtractionRunIntake
|
||||
from app.models import ShippingOrderSchemaVersion
|
||||
|
||||
schema_version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
assert schema_version is not None
|
||||
run = ShippingOrderExtractionRun(
|
||||
run_no=f'SNER-CANCEL-ADMIN-{user.id}',
|
||||
user_id=user.id,
|
||||
owner_agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
schema_version_id=int(schema_version.id),
|
||||
input_snapshot_hash='a' * 64,
|
||||
input_snapshot_json={'intakes': [], 'schema': {'version': 1, 'checksum': 'a' * 64}},
|
||||
idempotency_key=f'cancel-admin-{user.id}',
|
||||
status='queued',
|
||||
phase='queued',
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderExtractionRunIntake(run_id=run.id, intake_id=intake.id, position=0))
|
||||
_attach_units(run, statuses=['pending'], document_ids=[document.id])
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
cancel_order_extraction_run(actor=admin, run_no=run.run_no)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.CANCEL_REASON_REQUIRED'
|
||||
db.session.rollback()
|
||||
|
||||
run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
admin = db.session.get(User, admin.id)
|
||||
cancel_order_extraction_run(actor=admin, run_no=run.run_no, reason='积压清理')
|
||||
db.session.commit()
|
||||
db.session.refresh(run)
|
||||
assert run.status == 'cancelled'
|
||||
assert run.cancellation_actor_type == 'admin'
|
||||
assert run.cancellation_reason == '积压清理'
|
||||
|
||||
|
||||
def test_cancel_unit_rejects_completed_document(app):
|
||||
"""已完成 PDF 不可取消,避免回滚业务结果。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='CANCEL-READY')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ready, = _attach_units(run, statuses=['candidate_ready'], document_ids=[document.id])
|
||||
run.status = 'processing'
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
cancel_order_extraction_unit(actor=user, run_no=run.run_no, document_id=int(ready.document_id))
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.CANCEL_NOT_ACTIVE'
|
||||
@@ -54,6 +54,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
serialize_order_extraction_run,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.jobs.queue import fail_job
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan_batch
|
||||
@@ -250,6 +251,41 @@ def test_create_run_freezes_lightweight_input_without_sync_materialization(app):
|
||||
}
|
||||
|
||||
|
||||
def test_create_run_reparses_empty_email_supplement_from_frozen_html_tables(app):
|
||||
"""历史正文补充为空时,Run 必须按冻结 Schema 从 Intake HTML 表恢复预约号。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMAIL-HTML')
|
||||
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
|
||||
schema.definition_json = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#']},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN']},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'aliases': ['Reservation ID']},
|
||||
]}
|
||||
intake.structured_result_json = {
|
||||
'email': {'body_html_tables': ['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>4000111701</td></tr></table>''']},
|
||||
}
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='__email_body__',
|
||||
filename='email-body.html',
|
||||
content_hash='e' * 64,
|
||||
classification='email_context',
|
||||
parse_status='parsed',
|
||||
extracted_text='Outlook flattened text without table columns',
|
||||
order_extraction_result_json={'email_supplement': {'rows': [], 'issues': ['email_supplement_po_header_missing']}},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
body = next(item for item in run.input_snapshot_json['intakes'][0]['documents'] if item['document_type'] == 'email_body')
|
||||
assert body['email_supplement']['rows'][0]['po_number'] == '4518838154'
|
||||
assert body['email_supplement']['rows'][0]['reservation_id'] == '4000111701'
|
||||
|
||||
|
||||
def test_worker_materialization_preserves_request_snapshot_on_retry(app):
|
||||
"""Worker 重试可复用执行计划,但不得改写发送时的请求快照与幂等审计锚点。"""
|
||||
with app.app_context():
|
||||
@@ -274,6 +310,36 @@ def test_worker_materialization_preserves_request_snapshot_on_retry(app):
|
||||
assert run.request_snapshot_json == request_snapshot
|
||||
|
||||
|
||||
def test_worker_rematerializes_a_legacy_empty_plan(app):
|
||||
"""遗留的 0 Unit 空计划不得跳过附件物化,否则重试会永久得到空版面输入。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='EMPTY-PLAN')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
empty_plan = ShippingOrderExtractionPlan(
|
||||
run_id=run.id,
|
||||
plan_version='shipping_order_extraction.plan.v1',
|
||||
input_snapshot_hash=str(run.input_snapshot_hash),
|
||||
status='planned',
|
||||
unit_count=0,
|
||||
)
|
||||
db.session.add(empty_plan)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.order_extraction_run_service import materialize_order_extraction_run_inputs
|
||||
|
||||
with patch('app.services.shipping_notice.order_extraction_run_service.ensure_order_extraction_input_documents'):
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
|
||||
# 关键断言:空计划被替换,重新冻结的执行计划必须实际包含附件 Unit。
|
||||
assert plan.unit_count == 1
|
||||
assert ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).count() == 1
|
||||
|
||||
|
||||
def test_create_run_rejects_an_intake_from_another_upload_batch(app):
|
||||
"""服务端必须拒绝伪造的跨批次 Intake 清单,不能依赖前端筛选。"""
|
||||
with app.app_context():
|
||||
@@ -431,6 +497,50 @@ def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction
|
||||
assert ShippingOrderExtractionRun.query.count() == 1
|
||||
|
||||
|
||||
def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
|
||||
"""相同内容复用历史布局时,当前 Document 的版本绑定应视为排程成功。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, original = _seed_run_input(suffix='REUSE-LAYOUT')
|
||||
db.session.add(ShippingDocumentLayoutVersion(
|
||||
document_id=original.id,
|
||||
version=1,
|
||||
status='ready',
|
||||
source_content_hash=original.content_hash,
|
||||
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:v3',
|
||||
parser_name='mineru',
|
||||
contract_version='shipping_document_table_snapshot.v1',
|
||||
payload_json={},
|
||||
issues_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
duplicate = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=original.asset_id,
|
||||
document_type='attachment',
|
||||
attachment_key='orders-REUSE-LAYOUT-duplicate.pdf',
|
||||
filename='orders-REUSE-LAYOUT-duplicate.pdf',
|
||||
content_hash=original.content_hash,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='PO duplicate',
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
db.session.commit()
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
# 关键断言:复用版本属于原始 Document 也不能造成当前 Run 的排程失败。
|
||||
assert reused is False
|
||||
assert run.status == 'queued'
|
||||
|
||||
|
||||
def test_last_layout_completion_enqueues_waiting_run_once(app):
|
||||
"""最后一份附件布局完成才唤醒 Run,提前完成其中一份不能启动订单提取。"""
|
||||
with app.app_context():
|
||||
@@ -1729,6 +1839,39 @@ def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app)
|
||||
assert aggregate == {session.session_id: (1, 'error')}
|
||||
|
||||
|
||||
def test_final_order_extraction_job_failure_marks_queued_run_failed(app):
|
||||
"""Job 重试耗尽时必须收口 Run,避免聊天页永久显示处理中。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='FINAL-JOB-FAILURE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
assert job is not None
|
||||
job.status = 'running'
|
||||
job.attempts = job.max_attempts
|
||||
job.error_message = None
|
||||
db.session.commit()
|
||||
|
||||
assert fail_job(job.id, error='layout scheduler unavailable', retryable=True, owned_attempt=job.attempts) is True
|
||||
|
||||
db.session.expire_all()
|
||||
failed_run = db.session.get(ShippingOrderExtractionRun, run.id)
|
||||
failed_job = db.session.get(Job, job.id)
|
||||
event = ShippingOrderExtractionProgressEvent.query.filter_by(
|
||||
run_id=run.id,
|
||||
event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED',
|
||||
).one()
|
||||
# 关键断言:队列终态与用户可见 Run 必须同事务收口,前端才能停止轮询。
|
||||
assert failed_job is not None and failed_job.status == 'failed'
|
||||
assert failed_run is not None and failed_run.status == 'failed'
|
||||
assert failed_run.phase == 'job_failed'
|
||||
assert failed_run.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'
|
||||
assert event.job_id == job.id
|
||||
assert intake.order_extraction_status == 'failed'
|
||||
|
||||
|
||||
def test_failed_run_retry_reuses_snapshot_and_execution_result(app):
|
||||
"""手工重试复用同一 Run/快照/确定性结果,只创建新的执行 Job。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -21,7 +21,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
events: list[str] = []
|
||||
run = SimpleNamespace(
|
||||
id=1, user_id=9, run_no='SNER-WORKER-MATERIALIZE', status='queued', current_job_id=None,
|
||||
attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
attempt_count=0, cancellation_requested_at=None, input_snapshot_json={'attachment_selection': {}},
|
||||
)
|
||||
job = SimpleNamespace(id=1, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
plan = SimpleNamespace(id=1, unit_count=0, units=[])
|
||||
@@ -41,12 +41,24 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
'ShippingOrderExtractionUnit',
|
||||
SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: []),
|
||||
)),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: []),
|
||||
),
|
||||
join=lambda *_a, **_k: SimpleNamespace(
|
||||
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
class _Eq:
|
||||
def __eq__(self, _other):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(handler, 'ShippingOrderExtractionPlan', SimpleNamespace(run_id=_Eq()))
|
||||
monkeypatch.setattr(handler, 'transition_order_extraction_run', lambda target, **_kwargs: setattr(target, 'status', 'processing'))
|
||||
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **_kwargs: events.append('failed'))
|
||||
def fake_materialize(_run, *, finalize_plan=True):
|
||||
events.append('finalize' if finalize_plan else 'materialize')
|
||||
return plan if finalize_plan else None
|
||||
@@ -65,6 +77,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
monkeypatch.setattr(handler, '_result_requires_review', lambda **_kwargs: False)
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 1})
|
||||
@@ -109,6 +122,72 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
assert run.phase == 'waiting_layout'
|
||||
|
||||
|
||||
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
|
||||
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
transitions: list[str] = []
|
||||
run = SimpleNamespace(
|
||||
id=3, user_id=9, run_no='SNER-WORKER-LAYOUT-FAIL', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, input_snapshot_json={'attachment_selection': {}},
|
||||
)
|
||||
job = SimpleNamespace(id=3, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
|
||||
def fake_transition(target, *, target_status, **_kwargs):
|
||||
transitions.append(target_status)
|
||||
target.status = target_status
|
||||
|
||||
class _Expr:
|
||||
def in_(self, *_args, **_kwargs):
|
||||
return self
|
||||
|
||||
def __eq__(self, _other):
|
||||
return self
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda _model, _id: job)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderExtractionRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderExtractionUnit',
|
||||
SimpleNamespace(
|
||||
status=_Expr(),
|
||||
query=SimpleNamespace(join=lambda *_a, **_k: SimpleNamespace(
|
||||
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
|
||||
)),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderExtractionPlan', SimpleNamespace(run_id=_Expr()))
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: events.append('materialize'),
|
||||
)
|
||||
|
||||
def _raise_layout_scheduling(_run, *, created_by_id):
|
||||
raise ValidationError(
|
||||
'Order PDF layout job was not created',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', _raise_layout_scheduling)
|
||||
monkeypatch.setattr(handler, 'transition_order_extraction_run', fake_transition)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'fail_job', lambda *_args, **kwargs: events.append(f"fail:{kwargs.get('retryable')}"))
|
||||
monkeypatch.setattr(handler, 'finish_job', lambda *_args, **_kwargs: events.append('finished'))
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'rollback', lambda: None)
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 3})
|
||||
|
||||
assert events == ['materialize', 'fail:False']
|
||||
assert transitions == ['processing', 'failed']
|
||||
assert run.status == 'failed'
|
||||
|
||||
|
||||
def _patch_unit_transitions(monkeypatch):
|
||||
"""用轻量状态机替代 ORM transition,便于验证单元级自动重试行为。"""
|
||||
|
||||
@@ -139,6 +218,7 @@ def _patch_unit_transitions(monkeypatch):
|
||||
def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]):
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.commit', lambda: None)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.rollback', lambda: None)
|
||||
monkeypatch.setattr('app.jobs.handlers.shipping_order_extraction.db.session.refresh', lambda *_args, **_kwargs: None)
|
||||
monkeypatch.setattr(
|
||||
'app.jobs.handlers.shipping_order_extraction.record_unit_progress',
|
||||
lambda *, event_code, reason_code=None, **_kwargs: event_log.append((event_code, reason_code)),
|
||||
@@ -147,6 +227,14 @@ def _patch_worker_io(monkeypatch, *, event_log: list[tuple[str, str | None]]):
|
||||
'app.jobs.handlers.shipping_order_extraction._append_route_decision',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_cancel_service.should_abort_unit_for_cancellation',
|
||||
lambda **_kwargs: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_cancel_service.apply_worker_cancellation_checkpoint',
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
|
||||
def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders(monkeypatch):
|
||||
@@ -190,7 +278,7 @@ def test_process_unit_with_retries_retries_retryable_failures_and_returns_orders
|
||||
|
||||
result = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=1)
|
||||
|
||||
assert result is orders
|
||||
assert result == orders
|
||||
assert unit.status == 'merging_supplement'
|
||||
assert unit.attempt_count == 3
|
||||
assert event_log.count(('technical_retrying', 'SYSTEM.SERVICE_UNAVAILABLE')) == 2
|
||||
|
||||
@@ -1,19 +1,45 @@
|
||||
"""订单抽取工作台投影的纯单元测试。"""
|
||||
"""
|
||||
backend/tests/test_shipping_order_extraction_workspace_projection_unit.py
|
||||
|
||||
用途:订单抽取工作台投影的纯单元测试(无 DB)。
|
||||
依赖:order_extraction_workspace_projection、pytest monkeypatch。
|
||||
逻辑:覆盖 Run 级 currentActivity、handling_items 拆分、布局等待期失败/排队投影。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run_chat_state
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import (
|
||||
_planned_layout_documents,
|
||||
build_handling_items,
|
||||
serialize_workspace_run_chat_state,
|
||||
)
|
||||
|
||||
|
||||
def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
"""Run 级事件也应进入聊天卡 currentActivity,而不是只支持单元级事件。"""
|
||||
run = SimpleNamespace(
|
||||
status='processing',
|
||||
phase='deterministic_parsing',
|
||||
extraction_plan=SimpleNamespace(units=[]),
|
||||
input_snapshot_json={},
|
||||
error_code=None,
|
||||
result_json=None,
|
||||
started_at=None,
|
||||
finished_at=None,
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
last_activity_at=None,
|
||||
progress_version=1,
|
||||
attempt_count=0,
|
||||
cancellation_requested_at=None,
|
||||
cancellation_completed_at=None,
|
||||
cancellation_actor_type=None,
|
||||
cancellation_actor_id=None,
|
||||
cancellation_reason=None,
|
||||
cancellation_reason_code=None,
|
||||
run_no='OER-TEST',
|
||||
auto_freeze_policy_json=None,
|
||||
review_cases=[],
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
@@ -29,14 +55,219 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
|
||||
),
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.progress_ui_v3_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.order_extraction_cancel_enabled',
|
||||
lambda: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.progress_feature_flags_payload',
|
||||
lambda: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection._open_existing_document_ids',
|
||||
lambda _run: set(),
|
||||
)
|
||||
|
||||
result = serialize_workspace_run_chat_state(run)
|
||||
|
||||
assert result['currentActivity'] == {
|
||||
'unitId': 0,
|
||||
'fileName': None,
|
||||
'eventCode': 'expansion_wave_started',
|
||||
'selectionBatch': 2,
|
||||
'reasonCodes': ['budget_initial_limit', 'required_field_missing'],
|
||||
}
|
||||
assert result['currentActivity']['unitId'] == 0
|
||||
assert result['currentActivity']['fileName'] is None
|
||||
assert result['currentActivity']['eventCode'] == 'expansion_wave_started'
|
||||
assert result['currentActivity']['selectionBatch'] == 2
|
||||
assert result['currentActivity']['reasonCodes'] == ['budget_initial_limit', 'required_field_missing']
|
||||
assert result['currentActivity']['userVisibleStage'] == 'extracting'
|
||||
assert result['status'] == 'processing'
|
||||
assert result['handlingItems'] == []
|
||||
assert result['primaryNotice'] is None
|
||||
|
||||
|
||||
def test_build_handling_items_splits_pending_freeze_review_and_failure():
|
||||
"""Run 级 handling_items 必须拆分待补、冲突、冻结、复核与技术失败,不得只给笼统复核态。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={
|
||||
'pending_count': 2,
|
||||
'created_count': 1,
|
||||
'budget_stopped': True,
|
||||
'pending_orders': [
|
||||
{
|
||||
'candidate_no': 'C-1',
|
||||
'po_number': 'PO-1',
|
||||
'reasons': ['required_field_missing'],
|
||||
'missing_fields': ['qty'],
|
||||
},
|
||||
{
|
||||
'candidate_no': 'C-2',
|
||||
'po_number': 'PO-2',
|
||||
'reasons': ['email_supplement_conflict'],
|
||||
'missing_fields': [],
|
||||
},
|
||||
],
|
||||
'auto_freeze': {
|
||||
'blocked_tasks': [
|
||||
{'candidate_no': 'C-3', 'task_no': 'ST-9', 'code': 'auto_freeze_blocked'},
|
||||
],
|
||||
},
|
||||
},
|
||||
auto_freeze_policy_json={
|
||||
'enabled': False,
|
||||
'evaluated_from_run': True,
|
||||
'blocking_reason_codes': ['profile_manual_confirmation_required'],
|
||||
},
|
||||
input_snapshot_json={},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
units = [
|
||||
SimpleNamespace(
|
||||
id=1,
|
||||
document_id=11,
|
||||
status='review_required',
|
||||
reason_code='row_needs_review',
|
||||
technical_failure_reason_code=None,
|
||||
),
|
||||
SimpleNamespace(
|
||||
id=2,
|
||||
document_id=12,
|
||||
status='failed',
|
||||
reason_code=None,
|
||||
technical_failure_reason_code='document_unreadable',
|
||||
),
|
||||
]
|
||||
|
||||
items = build_handling_items(run, units, open_existing_doc_ids=set())
|
||||
categories = [item['category'] for item in items]
|
||||
|
||||
# 关键断言:混合原因必须分别成项,且技术失败优先于文档复核。
|
||||
assert categories[0] == 'technical_failure'
|
||||
assert 'document_review' in categories
|
||||
assert 'candidate_missing_info' in categories
|
||||
assert 'candidate_conflict' in categories
|
||||
assert 'auto_freeze_blocked' in categories
|
||||
assert 'budget_stopped' in categories
|
||||
assert items[0]['primary_action'] == 'retry_failed_attachments'
|
||||
missing = next(item for item in items if item['category'] == 'candidate_missing_info')
|
||||
assert missing['primary_action'] == 'review_candidate'
|
||||
assert 'required_field_missing' in missing['reason_codes']
|
||||
freeze = next(item for item in items if item['category'] == 'auto_freeze_blocked')
|
||||
assert freeze['affected_refs'][0]['task_no'] == 'ST-9'
|
||||
|
||||
|
||||
def test_build_handling_items_budget_stopped_includes_attachment_refs():
|
||||
"""预算停扩必须带上受限附件引用,便于前端直达定位。"""
|
||||
run = SimpleNamespace(
|
||||
status='partially_completed',
|
||||
result_json={'budget_stopped': True, 'pending_count': 0, 'created_count': 0},
|
||||
auto_freeze_policy_json=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{
|
||||
'selected': False,
|
||||
'filename': 'skip-budget.pdf',
|
||||
'content_hash': 'hash-1',
|
||||
'document_id': 42,
|
||||
'skip_reason_codes': ['budget_initial_limit'],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
extraction_plan=None,
|
||||
review_cases=[],
|
||||
id=None,
|
||||
)
|
||||
|
||||
items = build_handling_items(run, [], open_existing_doc_ids=set())
|
||||
budget = next(item for item in items if item['category'] == 'budget_stopped')
|
||||
assert budget['count'] == 1
|
||||
assert budget['affected_refs'][0]['file_name'] == 'skip-budget.pdf'
|
||||
assert budget['affected_refs'][0]['document_id'] == 42
|
||||
|
||||
|
||||
def test_planned_documents_inherit_failed_run_status_before_units_exist():
|
||||
"""Job 在 Unit 物化前失败时,右侧每份 PDF 必须显示失败而非处理中。"""
|
||||
run = SimpleNamespace(
|
||||
status='failed',
|
||||
phase=None,
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED',
|
||||
finished_at=None,
|
||||
created_at=None,
|
||||
last_activity_at=None,
|
||||
cancellation_requested_at=None,
|
||||
cancellation_completed_at=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{'selected': True, 'filename': 'first.pdf', 'content_hash': 'a'},
|
||||
{'selected': True, 'filename': 'second.pdf', 'content_hash': 'b'},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
rows = _planned_layout_documents(run, {}, {})
|
||||
|
||||
# 关键断言:没有 Unit 也不允许以 pending 投影掩盖最终 Run 失败。
|
||||
assert [row['status'] for row in rows] == ['failed', 'failed']
|
||||
assert [row['user_visible_stage'] for row in rows] == ['failed', 'failed']
|
||||
assert {row['reason_code'] for row in rows} == {'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED'}
|
||||
|
||||
|
||||
def test_planned_documents_expose_queue_stage_and_health_tips(monkeypatch):
|
||||
"""Unit 未物化时也应投影排队阶段,并在阈值到达后给出健康提示。"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
now = datetime(2026, 7, 30, 12, 0, 0)
|
||||
run = SimpleNamespace(
|
||||
status='queued',
|
||||
phase='waiting_layout',
|
||||
error_code=None,
|
||||
finished_at=None,
|
||||
created_at=now - timedelta(minutes=10),
|
||||
last_activity_at=now - timedelta(minutes=10),
|
||||
cancellation_requested_at=None,
|
||||
cancellation_completed_at=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {
|
||||
'items': [
|
||||
{'selected': True, 'filename': 'po.pdf', 'content_hash': 'h1', 'selection_batch': 1},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.progress_ui_v3_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.order_extraction_cancel_enabled',
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_workspace_projection.datetime',
|
||||
SimpleNamespace(utcnow=lambda: now),
|
||||
)
|
||||
|
||||
rows = _planned_layout_documents(run, {}, {})
|
||||
|
||||
assert len(rows) == 1
|
||||
assert rows[0]['user_visible_stage'] == 'waiting_layout'
|
||||
assert rows[0]['status'] == 'pending'
|
||||
assert rows[0]['queue_position'] == 1
|
||||
assert any(tip['code'] == 'queue_backlog' for tip in rows[0]['health_tips'])
|
||||
assert 'cancel_unit' in rows[0]['available_actions']
|
||||
|
||||
|
||||
def test_progress_event_status_maps_process_states():
|
||||
"""进度事件 status 必须表达过程态,不得一律 completed。"""
|
||||
from app.services.shipping_notice.order_extraction_progress import _progress_event_status
|
||||
|
||||
assert _progress_event_status(event_code='document_queued') == 'queued'
|
||||
assert _progress_event_status(event_code='extracting', entity_status='extracting') == 'running'
|
||||
assert _progress_event_status(event_code='run_completed') == 'completed'
|
||||
assert _progress_event_status(event_code='technical_failed') == 'failed'
|
||||
@@ -3,13 +3,13 @@
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
|
||||
|
||||
|
||||
def _profile(code: str, *, required: str = 'PURCHASE ORDER', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
|
||||
"""构造不包含订单号、料号、数量或金额的最小冻结 Profile。"""
|
||||
def _profile(code: str, *, value: str = 'FACTORY A', optional: list[str] | None = None, score: float = .9, margin: float = .15) -> dict:
|
||||
"""构造最小冻结 Profile;工厂值必须与 PLANT NAME 标签形成关系才可命中。"""
|
||||
return {'profile_code': code, 'version': 1, 'checksum': f'{code.lower():0<64}'[:64], 'definition': {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {
|
||||
'required_anchors': [{'anchor_id': 'title', 'text': required}],
|
||||
'optional_anchors': [{'anchor_id': f'optional_{index}', 'text': value} for index, value in enumerate(optional or [])],
|
||||
'required_anchors': [{'anchor_id': 'plant_name', 'label': 'PLANT NAME:', 'value': value, 'value_position': 'right'}],
|
||||
'optional_anchors': [{'anchor_id': f'optional_{index}', 'label': 'TYPE:', 'value': item, 'value_position': 'right'} for index, item in enumerate(optional or [])],
|
||||
'minimum_score': score, 'minimum_margin': margin,
|
||||
},
|
||||
'table_regions': [{'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}, 'line_layouts': [{
|
||||
@@ -19,7 +19,7 @@ def _profile(code: str, *, required: str = 'PURCHASE ORDER', optional: list[str]
|
||||
}}
|
||||
|
||||
|
||||
def _layout(text: str = 'PURCHASE ORDER') -> dict:
|
||||
def _layout(text: str = 'PLANT NAME: FACTORY A') -> dict:
|
||||
"""构造最小页面坐标证据,业务文本仅用于证明它没有参与匹配逻辑。"""
|
||||
return {'tables': [{'table_id': 'table-1', 'page_no': 1}], 'coordinate_evidence': {
|
||||
'tables': {'table-1': [
|
||||
@@ -29,13 +29,23 @@ def _layout(text: str = 'PURCHASE ORDER') -> dict:
|
||||
}}
|
||||
|
||||
|
||||
def test_profile_matcher_uniquely_matches_static_anchors_not_dynamic_order_values():
|
||||
"""同一静态版式在订单号、料号、数量变化后仍稳定命中同一 Profile。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'])], layout=_layout('PURCHASE ORDER SUPPLIER A PO-999 QTY 999 PART-X'))
|
||||
def test_profile_matcher_uniquely_matches_label_value_anchor_not_dynamic_order_values():
|
||||
"""工厂标签和值关系不受订单号、料号、数量变化影响。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'])], layout=_layout('PLANT NAME: FACTORY A TYPE: UM17 PO-999 QTY 999 PART-X'))
|
||||
assert result.status == 'unique_match'
|
||||
assert result.profile_code == 'PO_A'
|
||||
|
||||
|
||||
def test_profile_matcher_ignores_pdf_whitespace_when_matching_label_value_anchor():
|
||||
"""PDF 坐标字符逐字拼接时空白会丢失,标签和值关系仍必须可命中。"""
|
||||
result = match_frozen_coordinate_profiles(
|
||||
profiles=[_profile('PO_A', value='IEC Technologies, S. de R.L. de C.V')],
|
||||
layout=_layout('PLANT NAME: IEC Technologies, S. de R.L. de C.V'),
|
||||
)
|
||||
|
||||
assert result.status == 'unique_match'
|
||||
|
||||
|
||||
def test_profile_matcher_rejects_similar_profiles_when_margin_is_insufficient():
|
||||
"""相同静态锚点的两个 Profile 必须返回 ambiguous,禁止按版本或顺序选择。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A'), _profile('PO_B')], layout=_layout())
|
||||
@@ -44,7 +54,7 @@ def test_profile_matcher_rejects_similar_profiles_when_margin_is_insufficient():
|
||||
|
||||
def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
|
||||
"""缺静态锚点为 layout_drift;没有坐标页证据则为 evidence_insufficient。"""
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('DELIVERY NOTE')).status == 'layout_drift'
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=_layout('REMARK: FACTORY A')).status == 'layout_drift'
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout={'tables': []}).status == 'evidence_insufficient'
|
||||
|
||||
|
||||
@@ -52,10 +62,10 @@ def test_profile_matcher_reports_only_missing_anchor_identifiers():
|
||||
"""缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。"""
|
||||
profile = _profile('PO_A')
|
||||
profile['definition']['document_match']['required_anchors'].append({
|
||||
'anchor_id': 'customer_logo', 'text': 'ACME LOGO',
|
||||
'anchor_id': 'customer_logo', 'label': 'CUSTOMER:', 'value': 'ACME LOGO', 'value_position': 'right',
|
||||
})
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_layout('PURCHASE ORDER PO-12345'))
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_layout('PLANT NAME: FACTORY A PO-12345'))
|
||||
|
||||
# 关键断言:管理员能定位配置缺项,而诊断不泄露订单业务值。
|
||||
assert result.status == 'layout_drift'
|
||||
@@ -67,7 +77,7 @@ def test_profile_matcher_reports_only_missing_anchor_identifiers():
|
||||
|
||||
def test_profile_matcher_requires_optional_score_threshold():
|
||||
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout())
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['UM17'], score=.95)], layout=_layout())
|
||||
assert result.status == 'no_match'
|
||||
|
||||
|
||||
@@ -76,7 +86,7 @@ def test_profile_matcher_uses_page_glyphs_for_anchor_outside_table():
|
||||
layout = _layout('LINE ITEMS')
|
||||
layout['coordinate_evidence']['page_glyphs'] = {'1': [
|
||||
{'text': char, 'bbox': {'x0': 10 + index * 4, 'y0': 10, 'x1': 13 + index * 4, 'y1': 20}}
|
||||
for index, char in enumerate('PURCHASE ORDER')
|
||||
for index, char in enumerate('PLANT NAME: FACTORY A')
|
||||
]}
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout=layout)
|
||||
|
||||
@@ -35,6 +35,7 @@ from app.services.shipping_notice.order_review_draft_service import (
|
||||
delete_line,
|
||||
patch_header_field,
|
||||
patch_line_field,
|
||||
validate_draft,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_evidence_service import get_case_evidence, list_case_evidence
|
||||
from app.services.shipping_notice.order_review_disposition_service import (
|
||||
@@ -95,6 +96,47 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
|
||||
assert db.session.get(ShippingNoticeCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
|
||||
|
||||
|
||||
def test_review_case_backfills_final_run_order_for_an_empty_legacy_draft(app):
|
||||
"""最终合并订单可回填旧空草稿,复核页不得把成功 PDF 显示为机器订单不可用。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-FINAL-ORDER')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
# 先模拟 Worker 在最终合并结果写入前创建的空白旧 Case。
|
||||
legacy_case = ensure_run_review_cases(run=run)[0]
|
||||
run.execution_result_json = {'orders': [{
|
||||
'primary_document_id': unit.document_id,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': 'PO-FINAL'}]}],
|
||||
'lines': [{'fields': [{'field_id': 'part', 'observations': [{'value': 'A001'}]}]}],
|
||||
}]}
|
||||
|
||||
refreshed = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
# 关键断言:按当前 PDF 的 primary_document_id 回填,不依赖旧 Unit 中间结果。
|
||||
assert refreshed.id == legacy_case.id
|
||||
assert refreshed.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'PO-FINAL'
|
||||
assert refreshed.current_draft.lines_json[0]['machine_fields'][0]['observations'][0]['value'] == 'A001'
|
||||
assert not any(item['code'] == 'machine_order_unavailable' for item in refreshed.current_draft.issue_summary_json)
|
||||
|
||||
|
||||
def test_review_case_restores_original_case_from_machine_coordinate_quote(app):
|
||||
"""历史坐标结果的小写机器值应以同源原文 quote 回填,人工层保持不变。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-SOURCE-CASE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{
|
||||
'header_fields': [{'field_id': 'part', 'observations': [{
|
||||
'value': 'd4-a08ar12000002', 'quote': 'D4-A08AR12000002',
|
||||
}]}],
|
||||
'lines': [],
|
||||
}]}
|
||||
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
assert case.current_draft.header_values_json['machine_fields'][0]['observations'][0]['value'] == 'D4-A08AR12000002'
|
||||
|
||||
|
||||
def test_review_case_without_or_with_multiple_candidates_never_picks_a_machine_source(app):
|
||||
"""无 Candidate 和旧多 Candidate 都必须创建 Case,但不得任意选择机器结果作为来源。"""
|
||||
with app.app_context():
|
||||
@@ -270,10 +312,13 @@ def test_review_draft_edits_are_versioned_audited_and_preserve_machine_values(ap
|
||||
user_id=user.id, case_no=case.case_no, line_key='machine-1', field_id='qty-id', value='3',
|
||||
expected_draft_version=2,
|
||||
)
|
||||
# 关键断言:单字段改动不会清除其他字段,校验结果仍保留到 Draft。
|
||||
# 关键断言:单字段改动不会触发整单必填校验,避免用户逐项编辑时被其他空字段阻断。
|
||||
assert updated['draft']['lines'][0]['values']['qty-id']['value'] == '3'
|
||||
assert updated['draft']['validation']['status'] == 'ready'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id).count() == 3
|
||||
assert updated['draft']['validation']['status'] == 'not_validated'
|
||||
assert updated['draft']['issues'] == []
|
||||
validated = validate_draft(user_id=user.id, case_no=case.case_no, expected_draft_version=3)
|
||||
assert validated['draft']['validation']['status'] == 'ready'
|
||||
assert ShippingOrderReviewCaseEvent.query.filter_by(case_id=case.id).count() == 4
|
||||
|
||||
|
||||
def test_review_draft_empty_line_and_last_line_delete_remain_blocking(app):
|
||||
@@ -303,16 +348,19 @@ def test_review_draft_empty_line_and_last_line_delete_remain_blocking(app):
|
||||
db.session.commit()
|
||||
|
||||
added = add_line(user_id=user.id, case_no=case.case_no, expected_draft_version=1)
|
||||
assert added['draft']['validation']['status'] == 'needs_review'
|
||||
assert any(item['code'] == 'required_field_missing' for item in added['draft']['issues'])
|
||||
assert added['draft']['validation']['status'] == 'not_validated'
|
||||
assert added['draft']['issues'] == []
|
||||
validated = validate_draft(user_id=user.id, case_no=case.case_no, expected_draft_version=2)
|
||||
assert validated['draft']['validation']['status'] == 'needs_review'
|
||||
assert any(item['code'] == 'required_field_missing' for item in validated['draft']['issues'])
|
||||
|
||||
deleted_empty = delete_line(
|
||||
user_id=user.id, case_no=case.case_no, line_key=added['draft']['lines'][-1]['line_key'],
|
||||
expected_draft_version=2,
|
||||
expected_draft_version=3,
|
||||
)
|
||||
deleted = delete_line(user_id=user.id, case_no=case.case_no, line_key='machine-1', expected_draft_version=3)
|
||||
assert deleted_empty['draft']['validation']['status'] == 'ready'
|
||||
assert deleted['draft']['validation']['status'] == 'needs_review'
|
||||
deleted = delete_line(user_id=user.id, case_no=case.case_no, line_key='machine-1', expected_draft_version=4)
|
||||
assert deleted_empty['draft']['validation']['status'] == 'not_validated'
|
||||
assert deleted['draft']['validation']['status'] == 'not_validated'
|
||||
assert not deleted['draft']['lines']
|
||||
|
||||
|
||||
@@ -341,6 +389,79 @@ def test_review_evidence_is_case_scoped_and_omits_untrusted_bbox(app):
|
||||
assert 'storage_key' not in str(payload)
|
||||
|
||||
|
||||
def test_review_evidence_normalizes_frozen_layout_coordinates(app):
|
||||
"""坐标订单字段必须以冻结页尺寸换算为前端可绘制 bbox,并准确切换证据页。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-COORDINATE-EVIDENCE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
intake_snapshot = dict(snapshot['intakes'][0])
|
||||
document_snapshot = dict(intake_snapshot['documents'][0])
|
||||
document_snapshot['layout_snapshot'] = {
|
||||
'coordinate_evidence': {'pages': {'2': {'width': 800, 'height': 1000}}},
|
||||
}
|
||||
intake_snapshot['documents'] = [document_snapshot]
|
||||
snapshot['intakes'] = [intake_snapshot]
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [{
|
||||
'field_id': 'ship-to', 'observations': [{
|
||||
'value': 'Example', 'quote': 'Example',
|
||||
'layout_evidence': {
|
||||
'page_no': 2, 'source': 'pdf_coordinate',
|
||||
'value_bbox': {'x0': 80, 'y0': 200, 'x1': 400, 'y1': 300},
|
||||
},
|
||||
}],
|
||||
}], 'lines': []}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
item = list_case_evidence(user_id=user.id, case_no=case.case_no)['items'][0]
|
||||
|
||||
assert item['page_no'] == 2
|
||||
assert item['source'] == 'pdf_coordinate'
|
||||
assert item['bbox'] == {'x0': 0.1, 'y0': 0.2, 'x1': 0.5, 'y1': 0.3}
|
||||
|
||||
|
||||
def test_review_evidence_resolves_line_cell_bbox_from_frozen_layout(app):
|
||||
"""明细只可按冻结 table/cell 坐标高亮,不能根据行列或文本位置猜测。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-LINE-CELL-EVIDENCE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
intake_snapshot = dict(snapshot['intakes'][0])
|
||||
document_snapshot = dict(intake_snapshot['documents'][0])
|
||||
document_snapshot['layout_snapshot'] = {
|
||||
'layout_candidate': {
|
||||
'pages': [{
|
||||
'page_no': 1, 'width': 1000, 'height': 500,
|
||||
'tables': [{'table_id': 'table-lines', 'rows': [{'cells': [{
|
||||
'cell_id': 'line-0-part', 'bbox': {'x0': 100, 'y0': 200, 'x1': 350, 'y1': 250},
|
||||
}]}]}],
|
||||
}],
|
||||
},
|
||||
}
|
||||
intake_snapshot['documents'] = [document_snapshot]
|
||||
snapshot['intakes'] = [intake_snapshot]
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [], 'lines': [{'fields': [{
|
||||
'field_id': 'part-number', 'observations': [{
|
||||
'value': 'PART-1', 'quote': 'PART-1', 'table_id': 'table-lines', 'cell_id': 'line-0-part',
|
||||
}],
|
||||
}]}]}]}
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
|
||||
item = list_case_evidence(user_id=user.id, case_no=case.case_no)['items'][0]
|
||||
|
||||
# 关键断言:明细精确按冻结单元格投影到第 1 页,归一化坐标可直接供 PDF canvas 绘制。
|
||||
assert item['line_index'] == 0
|
||||
assert item['page_no'] == 1
|
||||
assert item['source'] == 'frozen_layout_cell'
|
||||
assert item['bbox'] == {'x0': 0.1, 'y0': 0.4, 'x1': 0.35, 'y1': 0.5}
|
||||
|
||||
|
||||
def test_manual_draft_and_dispositions_are_case_scoped_and_preserve_machine_facts(app):
|
||||
"""无 Candidate 仅能启用唯一草稿;非订单和质量异常不删除当前 PDF 的机器历史。"""
|
||||
with app.app_context():
|
||||
@@ -425,6 +546,9 @@ def test_document_reparse_supersedes_only_after_success_and_rejects_final_case(a
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
assert case.status == 'superseded'
|
||||
assert case.disposition == 'reparsed'
|
||||
# 关键断言:旧 Run 明确投影后继编号,前端可跳转而非把已替代 Case 渲染为空白。
|
||||
run.superseded_by_run_id = replacement.id
|
||||
assert serialize_review_run(run)['superseded_by_run_no'] == replacement.run_no
|
||||
try:
|
||||
reparse_case_document(user_id=user.id, case_no=case.case_no, reason='other')
|
||||
except Exception as exc:
|
||||
|
||||
@@ -22,6 +22,7 @@ from app.services.shipping_notice.order_schema import service
|
||||
from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version
|
||||
from app.services.shipping_notice.notice_line_table import parse_notice_table_text
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
|
||||
|
||||
def _config(field_id: str, name: str, *, value_type: str) -> dict:
|
||||
@@ -71,6 +72,40 @@ def _save_and_publish(draft: dict, fields: list[dict]) -> dict:
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('normalizer', ['lowercase_trim', 'uppercase_trim'])
|
||||
def test_text_normalizers_preserve_source_case_for_user_visible_values(normalizer):
|
||||
"""大小写规则只服务于匹配;PDF 提取后展示和保存的业务文本必须保持原文。"""
|
||||
assert normalize_order_field_value(
|
||||
'Inventec D4-A08AR12000002 USD',
|
||||
{'value_type': 'string', 'normalizer_key': normalizer},
|
||||
) == 'Inventec D4-A08AR12000002 USD'
|
||||
|
||||
|
||||
def test_dynamic_schema_rejects_text_evidence_with_only_case_difference(app):
|
||||
"""Schema v1 不得让大小写不同的 PDF 引文证明文本字段值。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(part['id'], '内部料号', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
document.extracted_text = 'Part No: abc-123'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [], 'lines': [{'fields': [{'field_id': part['id'], 'observations': [{
|
||||
'value': 'ABC-123', 'document_id': document.id, 'quote': 'Part No: abc-123',
|
||||
}]}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='c' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert result['blocked_fields'] == ['part_number']
|
||||
assert result['lines'] == [{}]
|
||||
|
||||
|
||||
def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
"""自动建单开关写入草稿 definition;发布后才生效,并写入审计摘要。"""
|
||||
from app.core.errors import ConflictError
|
||||
@@ -124,8 +159,8 @@ def test_schema_saves_per_field_auto_creation_confidence_and_global_switch(app):
|
||||
assert published_event.after_snapshot_json.get('auto_creation_policy') == {'enabled': True}
|
||||
|
||||
|
||||
def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
"""草稿保存阶段即应拒绝不同字段占用同一标准化表头,避免歧义进入发布版本。"""
|
||||
def test_schema_save_allows_case_distinct_table_aliases(app):
|
||||
"""Schema v1 可保存仅大小写不同的别名,运行期按精确大小写匹配。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
part = service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
@@ -136,13 +171,13 @@ def test_schema_save_rejects_normalized_table_alias_collision(app):
|
||||
second = _config(customer['id'], '客户料号', value_type='string')
|
||||
second['aliases'] = ['customer p n']
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
service.save_draft(draft['id'], {
|
||||
'fields': [first, second], 'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
saved = service.save_draft(draft['id'], {
|
||||
'fields': [first, second], 'expected_lock_version': draft['lock_version'],
|
||||
})
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
assert caught.value.details['table_header_collisions']
|
||||
assert [item['aliases'] for item in saved['definition']['fields']] == [
|
||||
['Customer P/N'], ['customer p n'],
|
||||
]
|
||||
|
||||
|
||||
def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
@@ -171,7 +206,7 @@ def test_retired_run_schema_keeps_its_frozen_table_aliases(app):
|
||||
|
||||
frozen_version = db.session.get(ShippingOrderSchemaVersion, first['id'])
|
||||
frozen_contract = compile_table_header_contract(frozen_version.definition_json or {})
|
||||
assert frozen_contract.header_to_field['legacy sku'] == 'part_number'
|
||||
assert frozen_contract.header_to_field['Legacy SKU'] == 'part_number'
|
||||
assert parse_notice_table_text(documents[1].extracted_text, contract=frozen_contract) == [{
|
||||
'part_number': 'PART-FROZEN', 'qty': 4.0,
|
||||
}]
|
||||
@@ -407,6 +442,43 @@ def test_confirmed_order_field_coordinate_evidence_is_persisted_and_backend_mark
|
||||
assert observation.evidence_ref == f'document:{documents[1].id}:order-field:{po["id"]}:page:1'
|
||||
|
||||
|
||||
def test_email_supplement_table_evidence_is_accepted_for_reservation_id(app):
|
||||
"""邮件分配表按 PO+MPN 合并后,预约单号必须保留为已验证行字段。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
reservation = service.save_field(
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
published = _save_and_publish(draft, [_config(reservation['id'], '预约单号', value_type='string')])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
body = documents[0]
|
||||
body.document_type = 'email_body'
|
||||
|
||||
result = persist_dynamic_order(
|
||||
raw_order={
|
||||
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
|
||||
'header_fields': [], 'lines': [{'fields': [{'field_id': reservation['id'], 'observations': [{
|
||||
'value': '4000111701', 'document_id': body.id, 'quote': '4000111701',
|
||||
'email_supplement_evidence': {
|
||||
'table_index': 1, 'row_index': 2, 'column_index': 1,
|
||||
'cell_id': 'email-supplement:test:1:r2:c1',
|
||||
},
|
||||
}]}]}],
|
||||
},
|
||||
intake_id=intake_id, snapshot_hash='s' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
observation = ShippingOrderFieldObservation.query.filter_by(
|
||||
extraction_id=result['extraction'].id, field_id=reservation['id'],
|
||||
).one()
|
||||
assert result['lines'] == [{'reservation_id': '4000111701'}]
|
||||
assert result['blocked_fields'] == []
|
||||
assert observation.source_type == 'email_body_table'
|
||||
assert observation.extractor == 'email_allocation_table'
|
||||
assert observation.evidence_metadata_json['cell_id'] == 'email-supplement:test:1:r2:c1'
|
||||
|
||||
|
||||
def test_dynamic_schema_contract_and_cross_document_persistence(app):
|
||||
"""同一字段在 EML 与 PDF 一致时应 corroborated,并生成类型化值与 field_code 投影。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
backend/tests/test_shipping_progress_audit_contract_stage0.py
|
||||
|
||||
用途:验收处理进度细化与全链路审计阶段 0 契约冻结。
|
||||
依赖:progress_audit_contract、order_extraction_progress、ShippingOrderExtractionRun/Unit ORM、Alembic head。
|
||||
逻辑:核对状态词典、取消事件码、模型取消字段与迁移 head,确保后续阶段不漂移契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
MAPPING_VERSION,
|
||||
WORKSPACE_EVENT_CODES,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
CANCEL_PROGRESS_EVENT_CODES,
|
||||
HEALTH_TIP_CODES,
|
||||
HEALTH_TIP_THRESHOLDS_SECONDS,
|
||||
PROGRESS_MAPPING_VERSION,
|
||||
RUN_STATUSES,
|
||||
UNIT_STATUSES,
|
||||
USER_VISIBLE_STAGES,
|
||||
WORKSPACE_AVAILABLE_ACTIONS,
|
||||
)
|
||||
|
||||
|
||||
def test_stage0_status_and_stage_dictionaries_are_unique_source():
|
||||
"""状态、用户可见阶段与健康提示必须形成唯一冻结词典。"""
|
||||
assert RUN_STATUSES == {
|
||||
'queued', 'processing', 'completed', 'partially_completed',
|
||||
'review_required', 'failed', 'cancelled',
|
||||
}
|
||||
assert UNIT_STATUSES == {
|
||||
'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement',
|
||||
'candidate_ready', 'review_required', 'failed', 'cancelled',
|
||||
}
|
||||
assert 'cancellation_requested' in USER_VISIBLE_STAGES
|
||||
assert HEALTH_TIP_CODES == {'processing_slow', 'queue_backlog', 'processing_attention'}
|
||||
assert HEALTH_TIP_THRESHOLDS_SECONDS['processing_slow'] == 60
|
||||
assert HEALTH_TIP_THRESHOLDS_SECONDS['queue_backlog'] == 300
|
||||
assert HEALTH_TIP_THRESHOLDS_SECONDS['processing_attention'] == 1800
|
||||
assert {'cancel_run', 'cancel_unit', 'refresh_status'} <= WORKSPACE_AVAILABLE_ACTIONS
|
||||
|
||||
|
||||
def test_stage0_progress_mapping_includes_cancel_events():
|
||||
"""进度映射 v3 必须允许取消相关事件码写入(阶段 1 才会真正产生事件)。"""
|
||||
assert MAPPING_VERSION == PROGRESS_MAPPING_VERSION == 'shipping-order-progress-v3'
|
||||
assert CANCEL_PROGRESS_EVENT_CODES <= WORKSPACE_EVENT_CODES
|
||||
|
||||
|
||||
def test_stage0_run_unit_models_expose_cancellation_contract():
|
||||
"""Run/Unit ORM 必须具备取消请求元数据与活动版本字段。"""
|
||||
run_cols = set(ShippingOrderExtractionRun.__table__.columns.keys())
|
||||
unit_cols = set(ShippingOrderExtractionUnit.__table__.columns.keys())
|
||||
for name in (
|
||||
'cancellation_requested_at', 'cancellation_actor_type', 'cancellation_actor_id',
|
||||
'cancellation_reason', 'cancellation_reason_code', 'cancellation_completed_at',
|
||||
'progress_version',
|
||||
):
|
||||
assert name in run_cols
|
||||
for name in (
|
||||
'activity_version', 'cancellation_requested_at', 'cancellation_actor_type',
|
||||
'cancellation_actor_id', 'cancellation_reason', 'cancellation_reason_code',
|
||||
'cancellation_completed_at',
|
||||
):
|
||||
assert name in unit_cols
|
||||
|
||||
|
||||
def test_stage0_audit_model_exposes_extended_contract_columns():
|
||||
"""审计模型必须具备 operation_id、快照、证据引用与保留到期字段。"""
|
||||
cols = set(ShippingAuditEvent.__table__.columns.keys())
|
||||
for name in (
|
||||
'operation_id', 'actor_role', 'source', 'result', 'error_code', 'conversation_id',
|
||||
'unit_id', 'document_id', 'review_case_no', 'attempt_no', 'action', 'reason',
|
||||
'before_snapshot_json', 'after_snapshot_json', 'evidence_refs_json',
|
||||
'artifact_refs_json', 'context_refs_json', 'retention_expires_at',
|
||||
):
|
||||
assert name in cols
|
||||
|
||||
|
||||
def test_stage0_alembic_head_includes_progress_audit_migration():
|
||||
"""迁移链必须包含阶段 0 契约 revision(可为祖先,不必是唯一 head)。"""
|
||||
config = Config()
|
||||
config.set_main_option('script_location', 'migrations')
|
||||
script = ScriptDirectory.from_config(config)
|
||||
revision = script.get_revision('2b4c6d8e0f1a')
|
||||
assert revision is not None
|
||||
assert revision.down_revision == '1a3b5c7d9e0f'
|
||||
# 后续迁移可能接在其后;只要各 head 从 base 升级路径包含该 revision 即可。
|
||||
heads = list(script.get_heads())
|
||||
assert heads, 'Alembic heads must not be empty'
|
||||
for head in heads:
|
||||
path = {rev.revision for rev in script.walk_revisions('base', head)}
|
||||
assert '2b4c6d8e0f1a' in path, f'head {head} missing progress/audit revision 2b4c6d8e0f1a'
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
backend/tests/test_shipping_progress_feature_flags.py
|
||||
|
||||
用途:验收进度 UI v3 / 取消 / 审计导出功能开关与回滚语义。
|
||||
依赖:progress_feature_flags、cancel_service、audit_query_service、Flask testing config。
|
||||
逻辑:关闭开关后 API 拒绝且投影不暴露取消动作;关闭导出不影响列表可读。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
export_shipping_audit_events,
|
||||
list_shipping_audit_events,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction_cancel_service import cancel_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_run_service import create_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
|
||||
from app.services.shipping_notice.progress_feature_flags import progress_feature_flags_payload
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def test_feature_flags_payload_defaults_enabled(app):
|
||||
"""默认三开关均为开启,便于灰度前全量验证。"""
|
||||
with app.app_context():
|
||||
flags = progress_feature_flags_payload()
|
||||
assert flags == {
|
||||
'progress_ui_v3': True,
|
||||
'cancel_enabled': True,
|
||||
'audit_export_enabled': True,
|
||||
}
|
||||
|
||||
|
||||
def test_cancel_feature_flag_blocks_api_and_projection(app):
|
||||
"""关闭取消开关后投影无 cancel_run,直接调用取消 API 返回 FEATURE_DISABLED。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='FLAG-CANCEL')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
app.config['SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED'] = False
|
||||
projection = serialize_workspace_run(run)
|
||||
# 关键断言:回滚取消能力时前端拿不到取消按钮事实。
|
||||
assert 'cancel_run' not in projection['available_actions']
|
||||
assert projection['feature_flags']['cancel_enabled'] is False
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
cancel_order_extraction_run(actor=user, run_no=run.run_no)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.CANCEL_FEATURE_DISABLED'
|
||||
|
||||
|
||||
def test_progress_ui_v3_flag_suppresses_health_tips(app):
|
||||
"""关闭进度 UI v3 时不下发健康提示,但保留阶段事实字段。"""
|
||||
with app.app_context():
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='FLAG-UI')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.status = 'processing'
|
||||
run.phase = 'extracting'
|
||||
run.started_at = datetime.utcnow() - timedelta(minutes=40)
|
||||
run.last_activity_at = datetime.utcnow() - timedelta(minutes=5)
|
||||
db.session.commit()
|
||||
|
||||
app.config['SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED'] = False
|
||||
projection = serialize_workspace_run(run)
|
||||
assert projection['feature_flags']['progress_ui_v3'] is False
|
||||
assert projection['health_tips'] == []
|
||||
assert projection['user_visible_stage']
|
||||
|
||||
|
||||
def test_audit_export_flag_blocks_export_only(app):
|
||||
"""关闭导出开关后 list 仍可读,export 拒绝且不删除既有审计。"""
|
||||
with app.app_context():
|
||||
append_shipping_audit_event(
|
||||
event_type='flag_probe',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-FLAG-AUDIT',
|
||||
run_no='SNER-FLAG-AUDIT',
|
||||
)
|
||||
db.session.commit()
|
||||
app.config['SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED'] = False
|
||||
|
||||
listed = list_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id='req-flag-list',
|
||||
filters={'run_no': 'SNER-FLAG-AUDIT'},
|
||||
)
|
||||
assert listed['total'] >= 1
|
||||
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
export_shipping_audit_events(
|
||||
admin_user_id=1,
|
||||
request_id='req-flag-export',
|
||||
filters={'run_no': 'SNER-FLAG-AUDIT'},
|
||||
)
|
||||
assert caught.value.code == 'SHIPPING_NOTICE.AUDIT_EXPORT_FEATURE_DISABLED'
|
||||
@@ -0,0 +1,102 @@
|
||||
"""
|
||||
tests/test_shipping_progress_stage3_diagnostics.py
|
||||
|
||||
用途:覆盖阶段 3 任务中心分页与管理员诊断筛选(积压/取消中)及健康 P50。
|
||||
依赖:pytest、Flask app fixture、order_extraction_run_service。
|
||||
逻辑:断言用户仅看到自己的 Run;管理员列表可按取消中过滤;latency 含 p50_ms。
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderExtractionRun
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
get_order_extraction_run_health,
|
||||
list_order_extraction_diagnostic_runs,
|
||||
list_order_extraction_runs,
|
||||
)
|
||||
|
||||
|
||||
def _seed(app, suffix: str):
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
return _seed_run_input(suffix=suffix)
|
||||
|
||||
|
||||
def test_list_order_extraction_runs_paginates_for_owner(app):
|
||||
"""任务中心分页只返回当前用户 Run,并支持状态过滤。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed(app, 'S3PAGE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
payload = list_order_extraction_runs(
|
||||
user_id=user.id,
|
||||
page=1,
|
||||
page_size=10,
|
||||
status='queued',
|
||||
)
|
||||
assert isinstance(payload, dict)
|
||||
assert payload['total'] >= 1
|
||||
assert any(item.run_no == run.run_no for item in payload['items'])
|
||||
empty = list_order_extraction_runs(user_id=user.id, page=1, page_size=10, status='failed')
|
||||
assert empty['total'] == 0 or all(item.status == 'failed' for item in empty['items'])
|
||||
|
||||
|
||||
def test_diagnostic_list_filters_cancellation_in_flight(app):
|
||||
"""管理员诊断列表可筛出取消中的 Run。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed(app, 'S3CANCEL')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.status = 'processing'
|
||||
run.phase = 'processing'
|
||||
run.cancellation_requested_at = datetime.utcnow()
|
||||
run.cancellation_actor_type = 'user'
|
||||
run.cancellation_actor_id = str(user.id)
|
||||
db.session.commit()
|
||||
|
||||
payload = list_order_extraction_diagnostic_runs(
|
||||
admin_user_id=user.id,
|
||||
request_id='stage3-test',
|
||||
page=1,
|
||||
page_size=25,
|
||||
cancellation_in_flight=True,
|
||||
)
|
||||
assert any(item['run_no'] == run.run_no for item in payload['items'])
|
||||
hit = next(item for item in payload['items'] if item['run_no'] == run.run_no)
|
||||
assert hit['cancellation']['in_flight'] is True
|
||||
assert 'error_message' not in hit
|
||||
|
||||
|
||||
def test_health_latency_includes_p50(app):
|
||||
"""健康汇总 latency 必须同时提供 P50 与 P95。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed(app, 'S3P50')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
base = datetime.utcnow() - timedelta(minutes=3)
|
||||
run.created_at = base
|
||||
run.started_at = base + timedelta(seconds=2)
|
||||
run.extraction_completed_at = base + timedelta(seconds=5)
|
||||
run.result_persisted_at = base + timedelta(seconds=6)
|
||||
run.finished_at = base + timedelta(seconds=8)
|
||||
run.status = 'completed'
|
||||
run.phase = 'completed'
|
||||
db.session.commit()
|
||||
|
||||
report = get_order_extraction_run_health(now=base + timedelta(seconds=10))
|
||||
assert report['latency']['total']['p50_ms'] is not None
|
||||
assert report['latency']['total']['p95_ms'] is not None
|
||||
@@ -0,0 +1,225 @@
|
||||
"""
|
||||
backend/tests/test_shipping_session_pdf_work_item_migration.py
|
||||
|
||||
用途:验收会话 PDF 工作项迁移结构、唯一约束与审计扩展列。
|
||||
依赖:Alembic Operations、SQLite 内存库、3d6e8f0a1b2c 迁移、领域契约词典。
|
||||
逻辑:构造最小前置表后 upgrade;断言同会话同源唯一、当前 Case 唯一、审计哈希列与索引存在。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_session_pdf_work_item import ShippingSessionPdfWorkItem
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_RETENTION_DAYS,
|
||||
MAX_OPEN_SESSION_WORK_ITEMS,
|
||||
SESSION_WORK_ITEM_AUDIT_EVENT_TYPES,
|
||||
SESSION_WORK_ITEM_CLOSED_REASONS,
|
||||
SESSION_WORK_ITEM_LIFECYCLE_STATUSES,
|
||||
)
|
||||
|
||||
|
||||
def _pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""创建工作项外键依赖的最小 stub 表,避免迁移在 SQLite 上因缺表失败。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('users', metadata, sa.Column('id', sa.Integer(), primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_notice_documents',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_extraction_runs',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_order_review_cases',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
)
|
||||
sa.Table(
|
||||
'shipping_audit_events',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('event_type', sa.String(64), nullable=False),
|
||||
sa.Column('aggregate_type', sa.String(64), nullable=False),
|
||||
sa.Column('aggregate_id', sa.String(128), nullable=False),
|
||||
sa.Column('actor_type', sa.String(16), nullable=False),
|
||||
sa.Column('metadata_json', sa.JSON(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def test_session_work_item_contract_dictionaries_frozen():
|
||||
"""阶段 0 契约词典必须冻结生命周期、关闭原因、审计事件与上限。"""
|
||||
assert SESSION_WORK_ITEM_LIFECYCLE_STATUSES == {
|
||||
'pending_review', 'extracting', 'reparse_failed', 'closed',
|
||||
}
|
||||
assert SESSION_WORK_ITEM_CLOSED_REASONS == {
|
||||
'confirmed', 'non_order', 'user_cancelled', 'admin_terminated',
|
||||
}
|
||||
assert 'session_work_item_created' in SESSION_WORK_ITEM_AUDIT_EVENT_TYPES
|
||||
assert 'document_version_replaced' in SESSION_WORK_ITEM_AUDIT_EVENT_TYPES
|
||||
assert 'document_previous_version_restored' in SESSION_WORK_ITEM_AUDIT_EVENT_TYPES
|
||||
assert MAX_OPEN_SESSION_WORK_ITEMS == 50
|
||||
assert AUDIT_RETENTION_DAYS == 365 * 3
|
||||
|
||||
|
||||
def test_session_work_item_and_audit_models_expose_stage0_columns():
|
||||
"""ORM 必须暴露工作项指针字段与审计会话扩展列。"""
|
||||
work_cols = set(ShippingSessionPdfWorkItem.__table__.columns.keys())
|
||||
for name in (
|
||||
'item_no', 'conversation_id', 'owner_user_id', 'root_document_id',
|
||||
'current_document_id', 'current_run_id', 'current_run_no',
|
||||
'current_case_id', 'current_case_no', 'current_version_no',
|
||||
'lifecycle_status', 'closed_reason', 'closed_at', 'lock_version',
|
||||
):
|
||||
assert name in work_cols
|
||||
|
||||
audit_cols = set(ShippingAuditEvent.__table__.columns.keys())
|
||||
for name in ('session_item_id', 'owner_user_id', 'client_ip_hash', 'user_agent_hash'):
|
||||
assert name in audit_cols
|
||||
|
||||
|
||||
def test_shipping_session_pdf_work_item_migration_structure_and_constraints():
|
||||
"""迁移必须创建工作项表、唯一约束、会话状态索引与审计扩展列。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.3d6e8f0a1b2c_add_shipping_session_pdf_work_items'
|
||||
)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
original_op = migration.op
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
try:
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_session_pdf_work_items' in inspector.get_table_names()
|
||||
|
||||
columns = {
|
||||
item['name'] for item in inspector.get_columns('shipping_session_pdf_work_items')
|
||||
}
|
||||
assert {
|
||||
'item_no', 'conversation_id', 'owner_user_id', 'root_document_id',
|
||||
'current_document_id', 'current_run_id', 'current_run_no',
|
||||
'current_case_id', 'current_case_no', 'current_version_no',
|
||||
'lifecycle_status', 'closed_reason', 'closed_at', 'lock_version',
|
||||
} <= columns
|
||||
|
||||
unique_names = {
|
||||
item['name']
|
||||
for item in inspector.get_unique_constraints('shipping_session_pdf_work_items')
|
||||
if item.get('name')
|
||||
}
|
||||
assert 'uq_shipping_session_pdf_work_items_no' in unique_names
|
||||
assert 'uq_shipping_session_pdf_work_items_conversation_root_doc' in unique_names
|
||||
assert 'uq_shipping_session_pdf_work_items_current_case' in unique_names
|
||||
|
||||
indexes = {
|
||||
item['name'] for item in inspector.get_indexes('shipping_session_pdf_work_items')
|
||||
}
|
||||
assert 'ix_shipping_session_pdf_work_items_conversation_lifecycle' in indexes
|
||||
assert 'ix_shipping_session_pdf_work_items_open_conversation' in indexes
|
||||
|
||||
audit_cols = {
|
||||
item['name'] for item in inspector.get_columns('shipping_audit_events')
|
||||
}
|
||||
assert {
|
||||
'session_item_id', 'owner_user_id', 'client_ip_hash', 'user_agent_hash',
|
||||
} <= audit_cols
|
||||
audit_indexes = {
|
||||
item['name'] for item in inspector.get_indexes('shipping_audit_events')
|
||||
}
|
||||
assert 'ix_shipping_audit_events_session_item_created' in audit_indexes
|
||||
assert 'ix_shipping_audit_events_owner_created' in audit_indexes
|
||||
|
||||
# 同会话两个 PDF → 两条工作项;同源重复 → 唯一约束拒绝。
|
||||
connection.execute(sa.text('INSERT INTO users (id) VALUES (1)'))
|
||||
connection.execute(sa.text('INSERT INTO shipping_notice_documents (id) VALUES (101), (102)'))
|
||||
connection.execute(sa.text('INSERT INTO shipping_order_review_cases (id) VALUES (201), (202)'))
|
||||
now = datetime.utcnow().isoformat(sep=' ')
|
||||
connection.execute(
|
||||
sa.text(
|
||||
'INSERT INTO shipping_session_pdf_work_items ('
|
||||
'item_no, conversation_id, owner_user_id, root_document_id, '
|
||||
'current_document_id, current_case_id, current_version_no, '
|
||||
'lifecycle_status, lock_version, created_at, updated_at'
|
||||
') VALUES '
|
||||
"('SPWI-A', 'conv-1', 1, 101, 101, 201, 1, 'pending_review', 1, :now, :now),"
|
||||
"('SPWI-B', 'conv-1', 1, 102, 102, 202, 1, 'pending_review', 1, :now, :now)"
|
||||
),
|
||||
{'now': now},
|
||||
)
|
||||
# SQLite 唯一冲突会使事务进入 aborted;用 SAVEPOINT 隔离断言后继续 downgrade。
|
||||
connection.execute(sa.text('SAVEPOINT sp_dup_root'))
|
||||
with pytest.raises(Exception):
|
||||
connection.execute(
|
||||
sa.text(
|
||||
'INSERT INTO shipping_session_pdf_work_items ('
|
||||
'item_no, conversation_id, owner_user_id, root_document_id, '
|
||||
'current_document_id, current_version_no, lifecycle_status, '
|
||||
'lock_version, created_at, updated_at'
|
||||
') VALUES '
|
||||
"('SPWI-DUP', 'conv-1', 1, 101, 101, 1, 'pending_review', 1, :now, :now)"
|
||||
),
|
||||
{'now': now},
|
||||
)
|
||||
connection.execute(sa.text('ROLLBACK TO SAVEPOINT sp_dup_root'))
|
||||
|
||||
# 同一 Case 不能成为两个工作项的当前有效指针。
|
||||
connection.execute(sa.text('SAVEPOINT sp_dup_case'))
|
||||
with pytest.raises(Exception):
|
||||
connection.execute(
|
||||
sa.text(
|
||||
'INSERT INTO shipping_session_pdf_work_items ('
|
||||
'item_no, conversation_id, owner_user_id, root_document_id, '
|
||||
'current_document_id, current_case_id, current_version_no, '
|
||||
'lifecycle_status, lock_version, created_at, updated_at'
|
||||
') VALUES '
|
||||
"('SPWI-C', 'conv-2', 1, 102, 102, 201, 1, 'pending_review', 1, :now, :now)"
|
||||
),
|
||||
{'now': now},
|
||||
)
|
||||
connection.execute(sa.text('ROLLBACK TO SAVEPOINT sp_dup_case'))
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
assert 'shipping_session_pdf_work_items' not in inspector.get_table_names()
|
||||
reverted_audit = {
|
||||
item['name'] for item in inspector.get_columns('shipping_audit_events')
|
||||
}
|
||||
assert {
|
||||
'session_item_id', 'owner_user_id', 'client_ip_hash', 'user_agent_hash',
|
||||
}.isdisjoint(reverted_audit)
|
||||
finally:
|
||||
migration.op = original_op
|
||||
|
||||
|
||||
def test_stage0_alembic_head_includes_session_work_item_migration():
|
||||
"""迁移链必须包含会话工作项 revision,且其为当前 Alembic head。"""
|
||||
from alembic.config import Config
|
||||
from alembic.script import ScriptDirectory
|
||||
|
||||
config = Config()
|
||||
config.set_main_option('script_location', 'migrations')
|
||||
script = ScriptDirectory.from_config(config)
|
||||
revision = script.get_revision('3d6e8f0a1b2c')
|
||||
assert revision is not None
|
||||
assert revision.down_revision == '2c5d7e9f1a2b'
|
||||
heads = list(script.get_heads())
|
||||
assert '3d6e8f0a1b2c' in heads
|
||||
lineage = [item.revision for item in script.walk_revisions()]
|
||||
assert lineage[0] == '3d6e8f0a1b2c'
|
||||
assert '2c5d7e9f1a2b' in lineage
|
||||
assert '2b4c6d8e0f1a' in lineage
|
||||
@@ -0,0 +1,739 @@
|
||||
"""
|
||||
backend/tests/test_shipping_session_work_items.py
|
||||
|
||||
用途:验收会话 PDF 工作项聚合、重识别成功替换、失败回退与关闭统计。
|
||||
依赖:订单抽取 Run 测试夹具、ensure_run_review_cases、处置/确认服务、工作项投影。
|
||||
逻辑:同会话两 PDF 始终两条工作项;单文件重识别不丢另一项;失败恢复旧入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingSessionPdfWorkItem,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_disposition_service import (
|
||||
finalize_document_reparse,
|
||||
mark_non_order,
|
||||
reparse_case_document,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import project_session_workbench
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import (
|
||||
close_work_item,
|
||||
get_work_item_by_no,
|
||||
revoke_review_confirmation,
|
||||
terminate_work_item_as_admin,
|
||||
)
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
|
||||
def _materialized_run(*, user, agent, session, intake):
|
||||
"""显式物化 Plan/Unit,与 Worker 时序一致。"""
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
ensure_order_extraction_plan(run)
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def _seed_two_pdf_work_items(suffix: str):
|
||||
"""同会话两条工作项:先物化单 PDF Run/Case,再为第二 PDF 直接建工作项。"""
|
||||
user, agent, session, intake, document_a = _seed_run_input(suffix=f'{suffix}-A')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
cases = ensure_run_review_cases(run=run)
|
||||
document_b = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document_a.asset_id,
|
||||
attachment_key=f'file-b-{suffix}',
|
||||
document_type='attachment',
|
||||
filename=f'{suffix}-B.pdf',
|
||||
content_hash=f'hash-b-{suffix}',
|
||||
parse_status='parsed',
|
||||
extracted_text='order b',
|
||||
)
|
||||
db.session.add(document_b)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import ensure_work_item_for_document
|
||||
item_a = ensure_work_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document_a.id),
|
||||
run=run,
|
||||
case=cases[0] if cases else None,
|
||||
)
|
||||
item_b = ensure_work_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(document_b.id),
|
||||
run=run,
|
||||
)
|
||||
db.session.commit()
|
||||
return user, agent, session, intake, document_a, document_b, run, cases, item_a, item_b
|
||||
|
||||
|
||||
def test_session_two_pdfs_create_two_stable_work_items(app):
|
||||
"""同会话两个 PDF 生成两条稳定工作项;聚合 API 不依赖最新 Run。"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, document_a, document_b, _run, _cases, _item_a, _item_b = _seed_two_pdf_work_items(
|
||||
'SWI-TWO',
|
||||
)
|
||||
items = ShippingSessionPdfWorkItem.query.filter_by(conversation_id=session.session_id).all()
|
||||
assert len(items) == 2
|
||||
assert {item.root_document_id for item in items} == {document_a.id, document_b.id}
|
||||
|
||||
summary = project_session_workbench(user_id=int(user.id), conversation_id=session.session_id)
|
||||
assert summary['open_count'] == 2
|
||||
assert len(summary['open_items']) == 2
|
||||
|
||||
|
||||
def test_single_pdf_reparse_keeps_sibling_work_item_and_restores_on_failure(app):
|
||||
"""对第一个 PDF 重识别:仍保留两条工作项;失败后恢复旧入口。"""
|
||||
with app.app_context():
|
||||
user, _agent, session, _intake, _document_a, document_b, run, cases, item_a, item_b = _seed_two_pdf_work_items(
|
||||
'SWI-REPARSE',
|
||||
)
|
||||
case_a = cases[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
replacement, reused = reparse_case_document(
|
||||
user_id=user.id, case_no=case_a.case_no, reason='rule_updated',
|
||||
)
|
||||
assert reused is False
|
||||
db.session.refresh(item_a)
|
||||
assert item_a.lifecycle_status == 'extracting'
|
||||
assert ShippingSessionPdfWorkItem.query.filter_by(conversation_id=session.session_id).count() == 2
|
||||
|
||||
finalize_document_reparse(run=replacement, succeeded=False)
|
||||
db.session.refresh(item_a)
|
||||
db.session.refresh(case_a)
|
||||
assert case_a.status == 'unreviewed'
|
||||
assert item_a.lifecycle_status == 'reparse_failed'
|
||||
assert item_a.current_case_no == case_a.case_no
|
||||
db.session.refresh(item_b)
|
||||
assert item_b.root_document_id == document_b.id
|
||||
|
||||
|
||||
def test_reparse_success_switches_current_case_pointer(app):
|
||||
"""重识别成功后新 Case 成为当前可操作版本,旧 Case 不可再确认。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-OK')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
transition_order_extraction_run(run, target_status='processing')
|
||||
transition_order_extraction_run(run, target_status='review_required', result={})
|
||||
db.session.commit()
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).one()
|
||||
old_case_no = case.case_no
|
||||
old_version = int(item.current_version_no)
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_run_service.schedule_order_extraction_layouts',
|
||||
return_value=True,
|
||||
):
|
||||
replacement, _ = reparse_case_document(user_id=user.id, case_no=case.case_no, reason='other')
|
||||
finalize_document_reparse(run=replacement, succeeded=True)
|
||||
ensure_order_extraction_plan(replacement)
|
||||
new_cases = ensure_run_review_cases(run=replacement)
|
||||
db.session.commit()
|
||||
|
||||
db.session.refresh(item)
|
||||
db.session.refresh(case)
|
||||
assert case.status == 'superseded'
|
||||
assert new_cases
|
||||
assert item.current_case_no == new_cases[0].case_no
|
||||
assert item.current_case_no != old_case_no
|
||||
assert int(item.current_version_no) == old_version + 1
|
||||
assert item.lifecycle_status == 'pending_review'
|
||||
|
||||
|
||||
def test_close_and_admin_terminate_require_reason(app):
|
||||
"""用户关闭与管理员终止均写关闭状态;管理员无理由/无二次确认被拒绝。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-CLOSE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).one()
|
||||
|
||||
close_work_item(
|
||||
item=item,
|
||||
closed_reason='user_cancelled',
|
||||
actor_type='user',
|
||||
actor_id=user.id,
|
||||
reason='user abort',
|
||||
)
|
||||
db.session.commit()
|
||||
summary = project_session_workbench(user_id=int(user.id), conversation_id=session.session_id)
|
||||
assert summary['closed_count'] == 1
|
||||
assert summary['open_count'] == 0
|
||||
|
||||
# 再建一项测管理员终止门禁
|
||||
item2_doc = ShippingNoticeDocument(
|
||||
intake_id=intake.id, asset_id=document.asset_id, attachment_key='file-term',
|
||||
document_type='attachment', filename='term.pdf', content_hash='term-hash',
|
||||
parse_status='parsed', extracted_text='x',
|
||||
)
|
||||
db.session.add(item2_doc)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.session_pdf_work_item_service import ensure_work_item_for_document
|
||||
item2 = ensure_work_item_for_document(
|
||||
conversation_id=session.session_id,
|
||||
owner_user_id=int(user.id),
|
||||
document_id=int(item2_doc.id),
|
||||
run=run,
|
||||
)
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as missing_reason:
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id, item_no=item2.item_no, reason='', confirm_token='CONFIRM_TERMINATE',
|
||||
)
|
||||
assert missing_reason.value.code == 'SHIPPING_NOTICE.ADMIN_REASON_REQUIRED'
|
||||
with pytest.raises(ValidationError) as missing_confirm:
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id, item_no=item2.item_no, reason='stop', confirm_token='nope',
|
||||
)
|
||||
assert missing_confirm.value.code == 'SHIPPING_NOTICE.ADMIN_CONFIRM_REQUIRED'
|
||||
|
||||
# 首次终止成功后,重复终止须写幂等审计(result=ignored + already_closed),不得静默吞掉管理操作尝试。
|
||||
from app.models import ShippingAuditEvent
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id,
|
||||
item_no=item2.item_no,
|
||||
reason='first terminate',
|
||||
confirm_token='CONFIRM_TERMINATE',
|
||||
)
|
||||
db.session.commit()
|
||||
first_count = ShippingAuditEvent.query.filter_by(
|
||||
aggregate_id=item2.item_no,
|
||||
action='terminate',
|
||||
).count()
|
||||
assert first_count >= 1
|
||||
terminate_work_item_as_admin(
|
||||
admin_user_id=user.id,
|
||||
item_no=item2.item_no,
|
||||
reason='repeat terminate attempt',
|
||||
confirm_token='CONFIRM_TERMINATE',
|
||||
)
|
||||
db.session.commit()
|
||||
idempotent_events = ShippingAuditEvent.query.filter_by(
|
||||
aggregate_id=item2.item_no,
|
||||
action='terminate',
|
||||
result='ignored',
|
||||
).all()
|
||||
assert len(idempotent_events) == 1
|
||||
assert (idempotent_events[0].metadata_json or {}).get('already_closed') is True
|
||||
assert (idempotent_events[0].metadata_json or {}).get('idempotent') is True
|
||||
|
||||
|
||||
def test_admin_revoke_blocks_inventory_matched_and_allows_within_window(app):
|
||||
"""24 小时内且未库存匹配可撤销;已 matched 拒绝并记阻断。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-REVOKE')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
task = ShippingTask(
|
||||
task_no='SN-SWI-REVOKE-1',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
process_status='parsed',
|
||||
lifecycle_status='active',
|
||||
source_type='review_confirmation',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = int(task.id)
|
||||
case.confirmed_at = datetime.utcnow()
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).one()
|
||||
item.lifecycle_status = 'closed'
|
||||
item.closed_reason = 'confirmed'
|
||||
item.closed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# 已库存匹配 → 拒绝
|
||||
task.process_status = 'matched'
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
revoke_review_confirmation(
|
||||
admin_user_id=user.id,
|
||||
item_no=item.item_no,
|
||||
reason='undo',
|
||||
confirm_token='CONFIRM_REVOKE',
|
||||
)
|
||||
assert blocked.value.code == 'SHIPPING_NOTICE.REVOKE_INVENTORY_MATCHED'
|
||||
|
||||
# 恢复为未匹配并可撤销
|
||||
task.process_status = 'parsed'
|
||||
case.confirmed_at = datetime.utcnow() - timedelta(hours=1)
|
||||
db.session.commit()
|
||||
result = revoke_review_confirmation(
|
||||
admin_user_id=user.id,
|
||||
item_no=item.item_no,
|
||||
reason='undo within window',
|
||||
confirm_token='CONFIRM_REVOKE',
|
||||
)
|
||||
db.session.commit()
|
||||
assert result['revoked'] is True
|
||||
refreshed = get_work_item_by_no(item_no=item.item_no)
|
||||
assert refreshed.lifecycle_status == 'pending_review'
|
||||
|
||||
|
||||
def test_version_history_excludes_other_conversation_same_document(app):
|
||||
"""版本历史不得混入同属主、同 PDF 但不同会话的 Case。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import (
|
||||
list_session_work_item_versions,
|
||||
project_admin_supervision_page,
|
||||
)
|
||||
|
||||
user, agent, session_a, intake_a, document_a = _seed_run_input(suffix='SWI-VER-A')
|
||||
run_a = _materialized_run(user=user, agent=agent, session=session_a, intake=intake_a)
|
||||
case_a = ensure_run_review_cases(run=run_a)[0]
|
||||
item_a = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case_a.id).one()
|
||||
|
||||
# 同属主第二会话 + 第二份 PDF,再把 Case 的 document_id 改成与 A 相同以制造污染面。
|
||||
session_b = ChatSession(
|
||||
session_id=f'{session_a.session_id}-B',
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
title='other conversation',
|
||||
)
|
||||
db.session.add(session_b)
|
||||
db.session.flush()
|
||||
asset_b = FileAsset(
|
||||
asset_no='FA-SWI-VER-B',
|
||||
owner_user_id=user.id,
|
||||
original_filename='orders-b.pdf',
|
||||
storage_provider='minio',
|
||||
storage_bucket='test',
|
||||
storage_key=f'temporary/{user.id}/orders-b.pdf',
|
||||
content_hash=('b' * 64),
|
||||
file_size=100,
|
||||
mime_type='application/pdf',
|
||||
upload_status='ready',
|
||||
lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset_b)
|
||||
db.session.flush()
|
||||
intake_b = ShippingNoticeIntake(
|
||||
intake_no='SNI-SWI-VER-B',
|
||||
asset_id=asset_b.id,
|
||||
user_id=user.id,
|
||||
conversation_id=session_b.session_id,
|
||||
purpose='shipping_notice',
|
||||
parse_status='parsed',
|
||||
parser_version='v6',
|
||||
extracted_text='root text b',
|
||||
expires_at=datetime.utcnow() + timedelta(hours=1),
|
||||
)
|
||||
db.session.add(intake_b)
|
||||
db.session.flush()
|
||||
document_b = ShippingNoticeDocument(
|
||||
intake_id=intake_b.id,
|
||||
asset_id=asset_b.id,
|
||||
attachment_key='file-b',
|
||||
document_type='attachment',
|
||||
filename='orders-b.pdf',
|
||||
content_hash=('b' * 64),
|
||||
parse_status='parsed',
|
||||
extracted_text='order b',
|
||||
)
|
||||
db.session.add(document_b)
|
||||
db.session.flush()
|
||||
run_b = _materialized_run(user=user, agent=agent, session=session_b, intake=intake_b)
|
||||
case_b = ensure_run_review_cases(run=run_b)[0]
|
||||
case_b.document_id = int(document_a.id)
|
||||
db.session.commit()
|
||||
|
||||
versions = list_session_work_item_versions(item=item_a)
|
||||
case_nos = {row['case_no'] for row in versions}
|
||||
assert case_a.case_no in case_nos
|
||||
# 关键断言:即使 document_id 相同,异会话 Case 也不得进入本工作项版本谱系。
|
||||
assert case_b.case_no not in case_nos
|
||||
|
||||
admin_page = project_admin_supervision_page(owner_user_id=int(user.id), page=1, page_size=50)
|
||||
admin_item = next(
|
||||
(row for row in admin_page['items'] if row['item_no'] == item_a.item_no),
|
||||
None,
|
||||
)
|
||||
assert admin_item is not None
|
||||
assert 'admin_terminate' in admin_item['available_actions']
|
||||
|
||||
|
||||
def test_mark_quality_issue_and_draft_write_unified_audit(app):
|
||||
"""质量问题与草稿字段变更均写入统一审计,草稿含 request 关联与前后值。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_quality_issue
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
from flask import g
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='SWI-AUD')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json or {})
|
||||
schema = dict(snapshot.get('schema') or {})
|
||||
definition = dict(schema.get('definition') or {})
|
||||
definition['fields'] = [
|
||||
{
|
||||
'field_id': 'po-id',
|
||||
'field_code': 'po_number',
|
||||
'scope': 'header',
|
||||
'value_type': 'string',
|
||||
'required': False,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': [],
|
||||
},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
flag_modified(run, 'input_snapshot_json')
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {
|
||||
'orders': [{
|
||||
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-BEFORE'}]}],
|
||||
'lines': [],
|
||||
}],
|
||||
}
|
||||
flag_modified(unit, 'result_json')
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
|
||||
mark_quality_issue(user_id=int(user.id), case_no=case.case_no, reason='blurred', comment='soft scan')
|
||||
db.session.commit()
|
||||
quality_events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_marked_quality_issue',
|
||||
aggregate_id=case.case_no,
|
||||
).all()
|
||||
assert len(quality_events) == 1
|
||||
assert quality_events[0].action == 'mark_quality_issue'
|
||||
|
||||
case.status = 'draft'
|
||||
db.session.commit()
|
||||
g.request_id = 'req-draft-audit-1'
|
||||
draft_version = int(case.current_draft.draft_version)
|
||||
patch_header_field(
|
||||
user_id=int(user.id),
|
||||
case_no=case.case_no,
|
||||
field_id='po-id',
|
||||
value='PO-AFTER',
|
||||
expected_draft_version=draft_version,
|
||||
)
|
||||
db.session.commit()
|
||||
draft_events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_draft_changed',
|
||||
aggregate_id=case.case_no,
|
||||
).order_by(ShippingAuditEvent.id.desc()).all()
|
||||
assert draft_events
|
||||
latest = draft_events[0]
|
||||
assert latest.request_id == 'req-draft-audit-1'
|
||||
assert latest.operation_id == 'req-draft-audit-1'
|
||||
before = latest.before_snapshot_json or {}
|
||||
after = latest.after_snapshot_json or {}
|
||||
assert before.get('field_id') == 'po-id'
|
||||
assert before.get('previous_value') == 'PO-BEFORE'
|
||||
assert after.get('new_value') == 'PO-AFTER'
|
||||
|
||||
|
||||
def test_version_history_keeps_intermediate_replacement_docs_and_labels(app):
|
||||
"""多次替换后中间 Document Case 仍在版本历史,且 Vn 与 current_version_no 对齐。"""
|
||||
with app.app_context():
|
||||
from app.models import (
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderReviewCase,
|
||||
)
|
||||
from app.services.shipping_notice.session_pdf_work_item_projection import (
|
||||
list_session_work_item_versions,
|
||||
)
|
||||
|
||||
user, agent, session, intake, document_a = _seed_run_input(suffix='SWI-MID')
|
||||
run1 = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case1 = ensure_run_review_cases(run=run1)[0]
|
||||
item = ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case1.id).one()
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(run_id=int(run1.id)).one()
|
||||
plan_id = int(plan.id)
|
||||
|
||||
document_b = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document_a.asset_id,
|
||||
attachment_key='replace-b',
|
||||
document_type='attachment',
|
||||
filename='replace-b.pdf',
|
||||
content_hash=('m' * 64),
|
||||
parse_status='parsed',
|
||||
extracted_text='order mid',
|
||||
)
|
||||
document_c = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
asset_id=document_a.asset_id,
|
||||
attachment_key='replace-c',
|
||||
document_type='attachment',
|
||||
filename='replace-c.pdf',
|
||||
content_hash=('n' * 64),
|
||||
parse_status='parsed',
|
||||
extracted_text='order latest',
|
||||
)
|
||||
db.session.add_all([document_b, document_c])
|
||||
db.session.flush()
|
||||
|
||||
unit2 = ShippingOrderExtractionUnit(
|
||||
plan_id=plan_id,
|
||||
intake_id=int(intake.id),
|
||||
document_id=int(document_b.id),
|
||||
position=2,
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
status='candidate_ready',
|
||||
)
|
||||
unit3 = ShippingOrderExtractionUnit(
|
||||
plan_id=plan_id,
|
||||
intake_id=int(intake.id),
|
||||
document_id=int(document_c.id),
|
||||
position=3,
|
||||
unit_type='document_extraction',
|
||||
document_type='attachment',
|
||||
status='candidate_ready',
|
||||
)
|
||||
db.session.add_all([unit2, unit3])
|
||||
db.session.flush()
|
||||
|
||||
run2 = ShippingOrderExtractionRun(
|
||||
run_no=f'{run1.run_no}-R2',
|
||||
user_id=int(run1.user_id),
|
||||
owner_agent_id=int(run1.owner_agent_id),
|
||||
parser_engine_version=run1.parser_engine_version,
|
||||
parser_policy_version=run1.parser_policy_version,
|
||||
auto_freeze_policy_json=dict(run1.auto_freeze_policy_json or {}),
|
||||
conversation_id=str(run1.conversation_id),
|
||||
schema_version_id=int(run1.schema_version_id),
|
||||
input_snapshot_hash=f'hash-mid-r2-{(run1.input_snapshot_hash or "h")}'[:64],
|
||||
input_snapshot_json={
|
||||
**dict(run1.input_snapshot_json or {}),
|
||||
'review_reparse': {'document_id': int(document_b.id), 'source_case_no': case1.case_no},
|
||||
},
|
||||
idempotency_key=f'idem-mid-r2-{run1.id}-{document_b.id}'[:64],
|
||||
status='completed',
|
||||
reparse_of_run_id=int(run1.id),
|
||||
)
|
||||
db.session.add(run2)
|
||||
db.session.flush()
|
||||
case2 = ShippingOrderReviewCase(
|
||||
case_no=f'{case1.case_no}-V2',
|
||||
run_id=int(run2.id),
|
||||
unit_id=int(unit2.id),
|
||||
document_id=int(document_b.id),
|
||||
owner_user_id=int(user.id),
|
||||
status='superseded',
|
||||
current_draft_id=case1.current_draft_id,
|
||||
)
|
||||
db.session.add(case2)
|
||||
db.session.flush()
|
||||
|
||||
run3 = ShippingOrderExtractionRun(
|
||||
run_no=f'{run1.run_no}-R3',
|
||||
user_id=int(run1.user_id),
|
||||
owner_agent_id=int(run1.owner_agent_id),
|
||||
parser_engine_version=run1.parser_engine_version,
|
||||
parser_policy_version=run1.parser_policy_version,
|
||||
auto_freeze_policy_json=dict(run1.auto_freeze_policy_json or {}),
|
||||
conversation_id=str(run1.conversation_id),
|
||||
schema_version_id=int(run1.schema_version_id),
|
||||
input_snapshot_hash=f'hash-mid-r3-{(run1.input_snapshot_hash or "h")}'[:64],
|
||||
input_snapshot_json={
|
||||
**dict(run1.input_snapshot_json or {}),
|
||||
'review_reparse': {'document_id': int(document_c.id), 'source_case_no': case2.case_no},
|
||||
},
|
||||
idempotency_key=f'idem-mid-r3-{run1.id}-{document_c.id}'[:64],
|
||||
status='completed',
|
||||
reparse_of_run_id=int(run2.id),
|
||||
)
|
||||
db.session.add(run3)
|
||||
db.session.flush()
|
||||
case3 = ShippingOrderReviewCase(
|
||||
case_no=f'{case1.case_no}-V3',
|
||||
run_id=int(run3.id),
|
||||
unit_id=int(unit3.id),
|
||||
document_id=int(document_c.id),
|
||||
owner_user_id=int(user.id),
|
||||
status='draft',
|
||||
current_draft_id=case1.current_draft_id,
|
||||
)
|
||||
db.session.add(case3)
|
||||
db.session.flush()
|
||||
case1.status = 'superseded'
|
||||
item.current_run_id = int(run3.id)
|
||||
item.current_run_no = run3.run_no
|
||||
item.current_case_id = int(case3.id)
|
||||
item.current_case_no = case3.case_no
|
||||
item.current_document_id = int(document_c.id)
|
||||
item.current_version_no = 3
|
||||
db.session.commit()
|
||||
|
||||
versions = list_session_work_item_versions(item=item)
|
||||
by_case = {row['case_no']: row for row in versions}
|
||||
# 关键断言:中间替换文档 B 不得因“仅根/当前文档过滤”而丢失。
|
||||
assert set(by_case) == {case1.case_no, case2.case_no, case3.case_no}
|
||||
assert by_case[case1.case_no]['version_label'] == 'V1'
|
||||
assert by_case[case2.case_no]['version_label'] == 'V2'
|
||||
assert by_case[case3.case_no]['version_label'] == 'V3'
|
||||
assert by_case[case3.case_no]['is_current'] is True
|
||||
|
||||
|
||||
def test_mark_non_order_always_writes_case_unified_audit(app):
|
||||
"""标记非订单必须写 Case 级统一审计(含状态/处置前后快照),不依赖工作项是否存在。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_non_order
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='SWI-NO')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
# 删除工作项,模拟尚未绑定或历史数据。
|
||||
ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).delete()
|
||||
db.session.commit()
|
||||
|
||||
previous = case.status
|
||||
mark_non_order(user_id=int(user.id), case_no=case.case_no, reason='duplicate_file', comment='dup pdf')
|
||||
db.session.commit()
|
||||
events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_marked_non_order',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=case.case_no,
|
||||
).all()
|
||||
assert len(events) == 1
|
||||
assert events[0].action == 'mark_non_order'
|
||||
assert events[0].reason_code == 'duplicate_file'
|
||||
before = events[0].before_snapshot_json or {}
|
||||
after = events[0].after_snapshot_json or {}
|
||||
assert before.get('status') == previous
|
||||
assert after.get('status') == 'non_order'
|
||||
assert after.get('disposition') == 'duplicate_file'
|
||||
|
||||
|
||||
def test_mark_quality_issue_other_requires_comment(app):
|
||||
"""原因码 other 时备注为空必须拒绝,保证审计可复盘业务理由。"""
|
||||
with app.app_context():
|
||||
from app.services.shipping_notice.order_review_disposition_service import mark_quality_issue
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='SWI-QO')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as missing_comment:
|
||||
mark_quality_issue(user_id=int(user.id), case_no=case.case_no, reason='other', comment=' ')
|
||||
assert missing_comment.value.code == 'SHIPPING.REVIEW_QUALITY_COMMENT_REQUIRED'
|
||||
|
||||
|
||||
def test_confirm_review_case_always_writes_case_unified_audit(app):
|
||||
"""确认建单必须写 Case 级统一审计,即使工作项已删除仍可追溯操作人与前后快照。"""
|
||||
with app.app_context():
|
||||
from app.models import ShippingAuditEvent, ShippingNoticeCandidate, ShippingOrderReviewConfirmedRevision
|
||||
from app.services.shipping_notice.order_review_confirmation_service import confirm_review_case
|
||||
from app.services.shipping_notice.order_review_draft_service import patch_header_field
|
||||
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='SWI-CFM')
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
snapshot = dict(run.input_snapshot_json)
|
||||
schema = dict(snapshot['schema'])
|
||||
definition = dict(schema['definition'])
|
||||
definition['fields'] = [
|
||||
{'field_id': 'po-id', 'field_code': 'po_number', 'scope': 'header', 'value_type': 'string', 'required': False, 'normalizer_key': 'trim', 'validator_keys': []},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['atomic_part_number']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'required': True, 'normalizer_key': 'trim', 'validator_keys': ['positive_decimal']},
|
||||
{'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'required': True, 'normalizer_key': 'reservation_id', 'validator_keys': ['reservation_id']},
|
||||
]
|
||||
schema['definition'] = definition
|
||||
snapshot['schema'] = schema
|
||||
run.input_snapshot_json = snapshot
|
||||
unit = run.extraction_plan.units[0]
|
||||
unit.result_json = {'orders': [{'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-CFM'}]}], 'lines': [{'fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '2'}]},
|
||||
{'field_id': 'reservation-id', 'observations': [{'value': '3000092999'}]},
|
||||
]}]}]}
|
||||
db.session.add(ShippingNoticeCandidate(
|
||||
candidate_no='CAND-SWI-CFM', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='machine-cfm', order_extraction_run_id=run.id, structured_result_json={'machine': 'ok'},
|
||||
))
|
||||
db.session.commit()
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
ShippingSessionPdfWorkItem.query.filter_by(current_case_id=case.id).delete()
|
||||
db.session.commit()
|
||||
validated = patch_header_field(
|
||||
user_id=user.id, case_no=case.case_no, field_id='po-id', value='PO-CONFIRMED', expected_draft_version=1,
|
||||
)
|
||||
db.session.commit()
|
||||
previous = case.status
|
||||
result = confirm_review_case(
|
||||
user_id=user.id,
|
||||
case_no=case.case_no,
|
||||
expected_draft_version=validated['draft']['draft_version'],
|
||||
idempotency_key='swi-confirm-audit-1',
|
||||
warning_acknowledgements=[{'code': 'manual_checked'}],
|
||||
)
|
||||
db.session.commit()
|
||||
events = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_confirmed',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=case.case_no,
|
||||
).all()
|
||||
# 关键断言:无工作项时仍有 Case 级确认审计,含前后状态与 task 关联。
|
||||
assert len(events) == 1
|
||||
assert events[0].action == 'confirm_review_case'
|
||||
assert events[0].actor_id == str(user.id)
|
||||
assert events[0].task_no == result['task_no']
|
||||
before = events[0].before_snapshot_json or {}
|
||||
after = events[0].after_snapshot_json or {}
|
||||
assert before.get('status') == previous
|
||||
assert after.get('status') == 'confirmed'
|
||||
assert after.get('confirmed_task_no') == result['task_no']
|
||||
assert ShippingOrderReviewConfirmedRevision.query.filter_by(case_id=case.id).count() == 1
|
||||
|
||||
|
||||
def test_audit_query_access_audit_is_strict(app, monkeypatch):
|
||||
"""审计中心查询访问审计失败时必须阻断,不得继续返回敏感结果。"""
|
||||
with app.app_context():
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.shipping_notice import audit_query_service
|
||||
from app.services.shipping_notice.audit_query_service import list_shipping_audit_events
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError('audit table down')
|
||||
|
||||
monkeypatch.setattr(audit_query_service, 'append_shipping_audit_event', _boom)
|
||||
with pytest.raises(ServiceUnavailableError) as exc:
|
||||
list_shipping_audit_events(admin_user_id=1, request_id='req-strict', page=1, page_size=10)
|
||||
assert exc.value.code == 'SHIPPING_NOTICE.AUDIT_PERSIST_FAILED'
|
||||
+10
-3
@@ -93,8 +93,8 @@
|
||||
|
||||
#### 客户可配置识别规则改造(分阶段)
|
||||
|
||||
- **目标**:以“已发布订单上下文字段 + 识别定义 + 主数据证据值 + 发布规则集”取代写死证据类型。识别定义只保存稳定 `context_field_id`;邮箱、域名和订单业务值均先进入统一 Observation→Decision→FieldValue,客户识别不得重读 EML、模板或原始 LLM 输出。完整阶段、Review 门禁和验收标准见 [customer_identity_rules_plan.md](features/shipping-notice/customer_identity_rules_plan.md)。
|
||||
- **来源边界**:业务定义仅可引用已发布订单 Schema 的 Header 稳定 `field_id`,只消费 `accepted/corroborated` 的字段裁决值;不得引用显示名称、`field_code`、Line 字段、LLM 原始输出或 PO/数量/日期等非身份字段。
|
||||
- **目标**:以“已发布订单上下文字段 + 识别定义 + 主数据证据值 + 发布规则集”取代写死证据类型。识别定义保存发布时 `context_field_id` 快照;邮箱、域名和订单业务值均先进入统一 Observation→Decision→FieldValue,客户识别不得重读 EML、模板或原始 LLM 输出。完整阶段、Review 门禁和验收标准见 [customer_identity_rules_plan.md](features/shipping-notice/customer_identity_rules_plan.md)。
|
||||
- **来源边界**:业务定义仅可引用已发布订单 Schema 的 Header 字段,只消费 `accepted/corroborated` 的字段裁决值;运行时优先使用快照 `field_id`,Schema 普通升级导致 UUID 变化时仅可按同一 `field_code`、Header 作用域、值类型及身份授权映射,不得按显示名称、Line 字段、LLM 原始输出或 PO/数量/日期等非身份字段回退。
|
||||
- **对象边界**:Bill-to 客户主体与 Ship-to 送货站点分别识别;地址、联系人和收货方默认只用于站点候选/人工确认,不能单独自动确认客户主体。
|
||||
- **发布与依赖**:识别规则集须草稿/发布/退役并保留不可变审计快照;被启用规则引用的订单字段不可退役或从发布 Schema 移除。
|
||||
- **Dify 边界**:不新增或修改 Dify Tool/画布;Dify 仅按现有动态契约回传 Header Observation,配置由业务管理员手工核对,HXOPS 后端负责最终裁决、匹配和确认。
|
||||
@@ -171,8 +171,15 @@
|
||||
- 首次发送无需先创建聊天消息:Run 创建事务会创建本地 ChatSession 并原子绑定尚未归属会话的 Intake,前端使用返回的 `conversation_id` 更新路由。
|
||||
- 订单识别状态卡必须可在刷新/重新进入会话后按 Run 列表恢复;活动态只显示不确定进度,不按固定轮询频率重复写 ChatLog,只有业务状态变化才原位持久化。
|
||||
- 订单抽取进度必须来自 HXOPS 持久化的 Run / PDF Unit / Progress Event 数据库事实;用户卡片只展示 `summary/current_activity/available_actions` 及按 PDF 归并结果,不再消费 Dify 节点事件、Workflow 阶段或浏览器 SSE。浏览器继续使用自适应短轮询,页面刷新、重新登录和 Worker 重启后均可恢复同一事实视图。
|
||||
- **处理进度细化与全链路审计(2026-07-29)**:
|
||||
- 用户可见阶段必须覆盖排队、版面预处理、路由、模板匹配、提取、正文合并、候选生成、人工复核、技术重试、失败、正在取消、已取消、完成;禁止把多种内部态压缩为单一“自动处理中”,禁止虚假百分比或 ETA。
|
||||
- 普通用户可刷新自己的 Run、取消自己创建的活跃 Run/Unit;管理员可取消任意活跃项但代取消必须填写原因。整批取消为主操作;已完成 PDF 结果保留;仅失败项可重试且保留 Attempt/审计历史。`review_required` 不得显示为技术失败。
|
||||
- 健康提醒:60 秒无活动、排队超 5 分钟、处理超 30 分钟分别提示;前台轮询约 2 秒,失焦降为 5–10 秒,断网退避恢复后立即刷新。
|
||||
- 全链路审计覆盖上传、Run/Unit、解析、复核、建单履约、管理操作与系统动作;审计追加不可改删,默认保留 3 年;快照白名单脱敏,禁止正文/密钥/对象存储 URL;查询、详情、导出与受保护证据下载均写访问审计。管理员审计中心(阶段 4)提供筛选、前后 Diff 与受控导出;到期清理由平台 Job `shipping-audit-retention` 执行。
|
||||
- 灰度与回滚(阶段 5):环境变量控制新进度展示、Run/Unit 取消、管理员审计导出;关闭后已写入事件与审计保持只读兼容,禁止回滚删除审计事实。
|
||||
- 验收范围:契约/迁移、取消与审计原子性、聊天进度卡与右侧 PDF 明细、任务中心续办、管理员运行诊断与审计导出、压测与灰度。不引入 Temporal/Airflow/n8n 等重型工作流平台,不把 Dify 接入订单抽取主链。
|
||||
- 用户状态卡、Run 查询和历史聊天回放只可显示稳定错误码与通用可操作提示;Worker、Provider 或上游异常正文不得进入用户 API、ChatLog 或前端状态。
|
||||
- 新上线 Run 的完成、待确认和失败状态应在用户离开会话后形成会话级待查看提示;进入对应会话且终态卡片成功加载后才清除。管理员在货代管理域只读诊断 Run、Job Attempt 和脱敏节点时间线;不提供管理端强制操作。
|
||||
- 新上线 Run 的完成、待确认和失败状态应在用户离开会话后形成会话级待查看提示;进入对应会话且终态卡片成功加载后才清除。管理员在货代管理域只读诊断 Run、Job Attempt 和脱敏节点时间线;阶段 4 已提供受控审计查询与导出(`/admin/shipping-audit`)。
|
||||
- Run 失败或取消时 Intake 恢复为可重试失败态;切换会话后的迟到轮询响应不得更新当前页面或重启旧 Run 计时器。
|
||||
- 管理员必须可查询最近 1-168 小时订单抽取 Run 的状态、当前活动事件、错误码分布、失败率、重试数、积压 Run,以及排队、处理和总耗时;监控视图不得返回文档正文、Provider 配置、原始结果或错误正文。
|
||||
- 前端 Run 查询单次最多等待 10 秒;超时或切换会话只取消当前 GET,后台 Run 继续执行,页面保持进行态并按退避策略重试。
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# 处理进度细化与全链路审计 — 阶段验收与合规报告
|
||||
|
||||
> 日期:2026-07-30(评审整改后刷新)
|
||||
> 范围:货代发货通知 Agent(进度细化 + 全链路审计)
|
||||
> 结论:**阶段 0–5 底座通过**;正式评审指出的进度语义/管理员取消/访问审计/筛选缺口已按下列整改闭合。
|
||||
|
||||
## 0. 正式评审整改(相对「未达标」结论)
|
||||
|
||||
| 评审项 | 整改 |
|
||||
| --- | --- |
|
||||
| 排队计入「处理中」/计数矛盾 | 右栏分列「排队」「处理中」;`pending`/`document_queued` 不再计入 running |
|
||||
| PDF 无健康提醒与最后活动 | 文档级 `health_tips`;右栏展示 `last_activity`;Unit 未物化时补全 `user_visible_stage` |
|
||||
| 聊天区笼统提示 / 无批次卡信息 | 进度卡 compact 行展示当前文件+阶段+耗时;含排队计数芯片 |
|
||||
| 管理员不可取消任意 Run / 无原因 | Admin Runs 页取消入口;代取消强制原因;聊天/任务中心取消可填原因 |
|
||||
| 审计筛选维度不全 | 审计中心补 `actor_id`/`document_id`/`request_id`/`result`/起止时间 |
|
||||
| 敏感读取/导出无统一审计 | Excel 下载、复核 Run/Case/证据写入 `shipping_resource_accessed` |
|
||||
| 取消 `operation_id` Worker 收口断裂 | Worker/收口复用 `cancellation_requested` 事件中的 `operation_id` |
|
||||
| Unit 状态审计字段不全 | 补 `operation_id`/`request_id`/`source`/`result`/`action`/`attempt_no` |
|
||||
| 进度事件 status 恒为 completed | 按 event_code/实体状态映射 queued/running/retrying/cancelled 等 |
|
||||
| Layout-wait 无健康提醒 | Unit 未物化时按 Run 等待时长计算 `health_tips` |
|
||||
| Layout 进度事件 status 恒 completed | `record_layout_document_progress` 改用过程态映射 |
|
||||
| 聊天卡早期无文件时仍笼统提示 | 兜底使用 Run 级 `userVisibleStage` |
|
||||
| 轮询/文档查询无访问审计 | Run/时间线/文档列表/timeline **逐次**写入访问审计 |
|
||||
| PDF 预览无访问审计 | `document-preview` 写入 `preview_order_review_document` |
|
||||
| seen_at 无状态审计 | `mark_run_seen` 写入前后快照(unseen→seen) |
|
||||
| 审计失败静默成功 | `record_access_audit`/`record_fulfillment_audit` 默认 strict,失败抛 `AUDIT_PERSIST_FAILED` |
|
||||
| 统一审计 dual-write 可静默失败 | `log_task_event` 库存/RPA/导出双写改为 `strict=True`,失败阻断业务 |
|
||||
| 轮询访问 60s 节流 | 已移除;按每次访问操作完整留痕 |
|
||||
| 阶段 0 Alembic 测试误要求唯一 head | 改为校验各 head 升级路径包含 `2b4c6d8e0f1a` |
|
||||
|
||||
## 1. 阶段对照
|
||||
|
||||
| 阶段 | 目标 | 状态 | 主要证据 |
|
||||
| --- | --- | --- | --- |
|
||||
| 0 | 契约/模型/迁移/黑名单/i18n 清单 | 通过 | `progress_audit_contract.py`、迁移 `2b4c6d8e0f1a`、`test_shipping_progress_audit_contract_stage0.py` |
|
||||
| 1 | 取消/投影/Worker 检查点/API | 通过 | `order_extraction_cancel_service`、workspace projection、`test_shipping_order_extraction_cancel.py` |
|
||||
| 2 | 聊天卡 + 右侧 PDF + 轮询 | 通过 | `ShippingOrderExtractionCard`、`ShippingSessionSummaryPanel`、四语言文案 |
|
||||
| 3 | 任务中心续办 + 管理员诊断 | 通过 | Task center「我的识别」、admin runs health/stale 筛选 |
|
||||
| 4 | 审计中心/Diff/导出/留存/履约审计 | 通过 | `/admin/shipping-audit`、`audit_query_service`、`shipping-audit-retention`、`fulfillment_audit` |
|
||||
| 5 | 压测冒烟、灰度开关、UAT/回滚、Dify 说明 | 通过 | `progress_feature_flags`、performance/e2e 测试、本文档与 technical §阶段 5 |
|
||||
|
||||
## 2. 合规核对
|
||||
|
||||
| 项 | 结果 |
|
||||
| --- | --- |
|
||||
| 不引入 Temporal/Airflow/n8n/Dify 抽取主链 | 通过 |
|
||||
| 无伪百分比/ETA | 通过(后端阶段事实 + FE 展示工具) |
|
||||
| 审计无 PDF/邮件正文/模型原文/对象 URL/密钥 | 通过(白名单 + 黑名单 + 导出字段裁剪) |
|
||||
| 取消为请求语义,安全点生效 | 通过 |
|
||||
| `review_required` ≠ 技术失败 | 通过 |
|
||||
| 回滚不删除审计事实 | 通过(三开关只关入口) |
|
||||
| 四语言错误码/文案 | 通过 |
|
||||
|
||||
## 3. 灰度与回滚(上线操作)
|
||||
|
||||
1. **test**:三开关保持 `true`,跑定向 pytest + 前端 e2e vitest + `npm run build`。
|
||||
2. **prod 灰度**:先确认管理员审计中心可用;观察取消成功率、轮询失败率、导出访问审计。
|
||||
3. **回滚**:按需将对应开关设为 `false` 并滚动后端配置;**禁止** `DELETE` 审计表或降级迁移抹除事件。
|
||||
4. **留存 Job**:注册/启用 `shipping-audit-retention`(可先 `dry_run=true`)。
|
||||
|
||||
## 4. Dify 配置说明(最终交付)
|
||||
|
||||
管理员只需确认货代 Chatflow:
|
||||
|
||||
1. **不**输出或依赖进度字段(如 `progress`、`current_stage_code`、`workflow_accepted`、`_hxops_*progress*`)。
|
||||
2. **不**实现取消/重试业务逻辑;取消由 HXOPS API + Worker 完成。
|
||||
3. **不**写入 `shipping_audit_events` 或携带对象存储 URL/密钥到用户可见输出。
|
||||
4. 订单抽取主链保持 HXOPS 本地确定性解析;Chatflow 仅服务无附件问答与后续交互。
|
||||
|
||||
**无需**为本次功能新增任何 Dify 节点、变量、Tool 或 Prompt。
|
||||
|
||||
## 5. 建议回归命令
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m pytest tests/test_shipping_progress_feature_flags.py tests/test_shipping_audit_end_to_end.py tests/test_shipping_audit_query_service.py tests/performance/test_shipping_order_extraction_progress_load.py -q
|
||||
|
||||
cd ../frontend
|
||||
npx vitest run src/features/chat/e2e/shipping-order-extraction-progress.spec.ts src/features/admin/e2e/shipping-audit.spec.ts src/features/admin/shippingConfigNavigation.spec.ts
|
||||
npm run build
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
# 会话 PDF 工作项架构 — 全阶段最终验收合规报告
|
||||
|
||||
> 日期:2026-07-30(第三轮评审修复后更新)
|
||||
> 范围:货代发货通知「本次处理 / PDF 重识别 / 人工复核 / 审计」分阶段实施(阶段 0–4)+ 三轮 P1/P2 缺口修复
|
||||
> 结论:**核心多 PDF 链路可用;第三轮已关闭「确认审计条件性缺口 / 质量异常理由不足 / 重复终止无痕 / 审计列表关联字段缺失」。上线前仍须完成迁移与联调冒烟。**
|
||||
|
||||
## 1. 架构目标(复核)
|
||||
|
||||
以聊天会话为业务聚合边界,用 `ShippingSessionPdfWorkItem` 稳定承载每份 PDF;重识别只切换 `current_*` 版本指针,不新建工作项、不移除同会话其他 PDF。不再以「最新 Run」充当本次处理。
|
||||
|
||||
## 2. 分阶段门禁结果
|
||||
|
||||
| 阶段 | 目标 | 合规 Review | 状态 | 报告 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 0–4 | 领域底座 → 审计中心 | 分阶段通过 | **通过(含三轮 P1/P2 修复)** | stage0–stage4 |
|
||||
|
||||
## 3. 第三轮评审缺口与修复对照
|
||||
|
||||
| 严重度 | 缺口 | 修复要点 |
|
||||
| --- | --- | --- |
|
||||
| P1 | 确认建单统一审计依赖工作项 | Case 级 `review_confirmed` 无条件写入(含操作人、前后快照、task_no);再尝试关闭工作项 |
|
||||
| P2 | 已关闭工作项重复终止无审计 | `terminate_work_item_as_admin` 幂等路径写 `result=ignored` + `already_closed` / `idempotent` |
|
||||
| P2 | 质量异常 `other` 可空备注 | 后端 `SHIPPING.REVIEW_QUALITY_COMMENT_REQUIRED`;前端弹窗选原因码,`other` 强制说明 |
|
||||
| UI | 审计列表缺会话/工作项/Case | 列表增加三列,详情抽屉已有字段保持 |
|
||||
|
||||
## 4. 总体验收场景核对
|
||||
|
||||
| # | 场景 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 1–8 | 双 PDF / 重识别 / 失败恢复 / 确认 / 撤销 / 审计 | 通过 |
|
||||
| 9 | 版本历史不混入其他会话 | 通过 |
|
||||
| 10 | 多次替换保留中间版本且 V1/V2/V3 对齐 | 通过 |
|
||||
| 11 | 非订单 Case 统一审计(无工作项时亦写入) | 通过 |
|
||||
| 12 | 监管台 / 审计中心访问可追溯且严格 | 通过 |
|
||||
| 13 | 移动端可完成明细增删复制;小屏优先编辑 | 通过 |
|
||||
| 14 | 确认建单 Case 统一审计(无工作项时亦写入) | 通过(本轮单测) |
|
||||
| 15 | 重复终止写幂等审计 | 通过(本轮单测) |
|
||||
| 16 | 质量异常 `other` 空备注拒绝;UI 须选原因 | 通过(本轮) |
|
||||
|
||||
## 5. 范围与红线
|
||||
|
||||
- 未做旧接口兼容迁移;未引入工作流引擎运行时。
|
||||
- 审计禁止 PDF/邮件正文、对象 URL、凭据、原始 IP/UA(仅哈希)。
|
||||
- **Dify 配置由管理员手动确认,本实施未改任何 Dify 节点。**
|
||||
|
||||
## 6. 上线检查清单
|
||||
|
||||
1. 执行迁移至 head `3d6e8f0a1b2c`(`flask db upgrade`)。
|
||||
2. 确认 `SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095`。
|
||||
3. 双 PDF + 多次替换文件:版本历史含中间 Vn。
|
||||
4. 无工作项历史 Case 确认后,审计中心可按 Case 查到 `review_confirmed`。
|
||||
5. 质量异常选择「其他」时无说明应被前后端拒绝。
|
||||
6. 监管台对已关闭项再次终止:审计中心可见 `result=ignored` 且 metadata 含 `already_closed`。
|
||||
7. 审计中心列表可直接看到会话 / 工作项 / Case 列。
|
||||
|
||||
## 7. 建议回归命令
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m pytest tests/test_shipping_session_work_items.py tests/test_shipping_access_audit_strict.py -q
|
||||
|
||||
cd ../frontend
|
||||
npx vitest run src/features/chat/components/ShippingSessionSummaryPanel.spec.ts
|
||||
npm run build
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
# 会话 PDF 工作项架构 — 阶段 0 验收与合规报告
|
||||
|
||||
> 日期:2026-07-30
|
||||
> 范围:领域契约与数据底座(`ShippingSessionPdfWorkItem` + 审计扩展)
|
||||
> 结论:**阶段 0 通过**,可进入阶段 1。
|
||||
|
||||
## 1. 阶段目标
|
||||
|
||||
建立「会话 PDF 工作项」作为唯一聚合实体,消除右侧面板依赖「最新 Run」的根因;扩展审计上下文以支撑后续版本切换与代操作追溯。
|
||||
|
||||
## 2. 关键节点核对
|
||||
|
||||
| 节点 | 输出 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 工作项模型 | `backend/app/models/shipping_session_pdf_work_item.py` | 通过 |
|
||||
| 模型导出 | `backend/app/models/__init__.py` | 通过 |
|
||||
| 审计扩展列 | `session_item_id` / `owner_user_id` / `client_ip_hash` / `user_agent_hash` | 通过 |
|
||||
| 审计写入 | `audit_service` 哈希 IP/UA;白名单含工作项指针字段 | 通过 |
|
||||
| 契约词典 | 生命周期、关闭原因、事件字典、上限 50、保留 3 年 | 通过 |
|
||||
| 迁移 | `3d6e8f0a1b2c`(head,`down_revision=2c5d7e9f1a2b`) | 通过 |
|
||||
| 测试 | `test_shipping_session_pdf_work_item_migration.py` + 审计哈希用例 | 通过 |
|
||||
|
||||
## 3. 验收标准
|
||||
|
||||
| 标准 | 证据 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 同会话两个 PDF 可生成两个稳定工作项 | `(conversation_id, root_document_id)` 唯一;迁移测试插入 SPWI-A/B | 通过 |
|
||||
| 单 PDF 重识别不创建新工作项 | 同源唯一约束;写路径复用在阶段 1 | 通过(底座) |
|
||||
| DB 阻止同一 Case 成为两个当前指针 | `uq_shipping_session_pdf_work_items_current_case` | 通过 |
|
||||
| 关键变更可持久化会话/PDF/版本/操作者/快照/请求关联 | 审计列 + `SESSION_WORK_ITEM_AUDIT_EVENT_TYPES` + 快照白名单 | 通过(底座) |
|
||||
|
||||
## 4. 合规与范围
|
||||
|
||||
- 未实现阶段 1+ API / 前端 / 监管台(按阶段门禁)。
|
||||
- 未改 Dify 配置。
|
||||
- IP/UA 仅存哈希;禁止键新增 `client_ip` / `user_agent`。
|
||||
- 不引入 Temporal/Airflow 运行时依赖。
|
||||
|
||||
## 5. 建议回归
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m pytest tests/test_shipping_session_pdf_work_item_migration.py tests/test_shipping_audit_event.py -q
|
||||
```
|
||||
@@ -0,0 +1,40 @@
|
||||
# 会话 PDF 工作项架构 — 阶段 1 验收与合规报告
|
||||
|
||||
> 日期:2026-07-30
|
||||
> 范围:后端业务状态机与聚合读模型
|
||||
> 结论:**阶段 1 通过**,可进入阶段 2。
|
||||
|
||||
## 1. 阶段目标
|
||||
|
||||
实现会话级工作台 API、版本切换、重识别失败回退、关闭及管理员撤销;禁止以「最新 Run」充当会话级当前事实。
|
||||
|
||||
## 2. 关键节点核对
|
||||
|
||||
| 节点 | 输出 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 领域服务 | `session_pdf_work_item_service.py` | 通过 |
|
||||
| 读模型投影 | `session_pdf_work_item_projection.py` | 通过 |
|
||||
| Run/Case 绑定 | `ensure_run_review_cases` → `bind_cases_for_run` | 通过 |
|
||||
| 重识别开始/失败 | `mark_reparse_started` / `mark_reparse_failed_and_restore` | 通过 |
|
||||
| 确认/非订单关闭 | `confirm_review_case` / `mark_non_order` | 通过 |
|
||||
| 草稿审计 | `_record_change` → `review_draft_changed` | 通过 |
|
||||
| Workspace API | `GET/POST session-work-items*` | 通过 |
|
||||
| Admin 监管 | 列表 / terminate / revoke-confirmation | 通过 |
|
||||
| 审计筛选扩展 | conversation / session_item / case / owner | 通过 |
|
||||
| 测试 | `test_shipping_session_work_items.py` 5 passed | 通过 |
|
||||
|
||||
## 3. 验收标准
|
||||
|
||||
| 标准 | 证据 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| 2 PDF 重识别后聚合仍 2 项 | `test_single_pdf_reparse_keeps_sibling...` | 通过 |
|
||||
| 最新 Run 变化不丢项 | 工作项按 conversation 聚合,不按 run 列表 | 通过 |
|
||||
| 成功后旧 Case 不可确认;失败恢复 | `test_reparse_success...` + failure restore | 通过 |
|
||||
| 确认/取消/非订单/重识别/代操作/撤销有审计 | 服务内 `append_shipping_audit_event` | 通过 |
|
||||
| 业务与审计同事务 | 服务不自行 commit | 通过 |
|
||||
|
||||
## 4. 范围控制
|
||||
|
||||
- 未改聊天右侧前端(阶段 2)。
|
||||
- 未建监管台/复核页 UI(阶段 3)。
|
||||
- 未改 Dify 配置。
|
||||
@@ -0,0 +1,22 @@
|
||||
# 会话 PDF 工作项架构 — 阶段 2 验收与合规报告
|
||||
|
||||
> 日期:2026-07-30
|
||||
> 范围:聊天右侧「本次处理」改用会话工作项读模型
|
||||
> 结论:**阶段 2 通过**,可进入阶段 3。
|
||||
|
||||
## 验收要点
|
||||
|
||||
| 标准 | 结果 |
|
||||
| --- | --- |
|
||||
| 右侧按 conversationId 拉取工作项,不以最新 Run 定范围 | 通过 |
|
||||
| 2 PDF + 单文件重识别后仍显示 2 行 | 通过(spec) |
|
||||
| 每行入口使用 current_case_no / current_run_no | 通过 |
|
||||
| 已关闭默认折叠 | 通过 |
|
||||
| 四语言文案 | 通过 |
|
||||
| Vitest 相关规格 | 18 passed |
|
||||
|
||||
## 证据
|
||||
|
||||
- `ShippingSessionSummaryPanel.vue` 主数据源改为 session-work-items API
|
||||
- `sessionWorkItemsRefreshTrigger` 在终态/重识别/恢复后触发刷新
|
||||
- `ShippingSessionSummaryPanel.spec.ts` + `useShippingOrderExtractionRuns.spec.ts`
|
||||
@@ -0,0 +1,22 @@
|
||||
# 会话 PDF 工作项架构 — 阶段 3 验收与合规报告
|
||||
|
||||
> 日期:2026-07-30
|
||||
> 范围:人工复核版本历史、操作确认弹窗、管理员监管台
|
||||
> 结论:**阶段 3 通过**,可进入阶段 4。
|
||||
|
||||
## 验收要点
|
||||
|
||||
| 标准 | 结果 |
|
||||
| --- | --- |
|
||||
| 复核页展示当前版本与替代关系;旧版只读可跳转当前 | 通过 |
|
||||
| 确认/重识别/非订单/替换需二次确认与影响说明 | 通过 |
|
||||
| 管理员代操作无理由或无二次确认被拒绝 | 通过(服务端 + 前端) |
|
||||
| 24h 内且未库存匹配可撤销;已匹配拒绝 | 通过(阶段 1 服务 + 监管台入口) |
|
||||
| 监管台路由 `/admin/shipping-review-supervision` | 通过 |
|
||||
| Vitest + npm run build | 通过 |
|
||||
|
||||
## 主要交付
|
||||
|
||||
- `ReviewVersionHistoryPanel.vue` / `ReviewActionConfirmDialog.vue`
|
||||
- `ShippingReviewSupervisionPage.vue` + API 客户端
|
||||
- 四语言 admin/chat 文案
|
||||
@@ -0,0 +1,19 @@
|
||||
# 会话 PDF 工作项架构 — 阶段 4 验收与合规报告
|
||||
|
||||
> 日期:2026-07-30
|
||||
> 范围:审计中心筛选增强、留存配置、文档
|
||||
> 结论:**阶段 4 通过**。
|
||||
|
||||
## 验收要点
|
||||
|
||||
| 标准 | 结果 |
|
||||
| --- | --- |
|
||||
| 审计可按会话/工作项/Case/属主筛选 | 通过 |
|
||||
| 导出默认脱敏(无 PDF/邮件/URL/凭据) | 通过(既有白名单 + 扩展) |
|
||||
| 详情含操作者、属主、快照 Diff | 通过 |
|
||||
| 留存可配置,默认 1095 天 | 通过(`SHIPPING_NOTICE_AUDIT_RETENTION_DAYS`) |
|
||||
| 导出/查看自身写审计 | 通过(既有 access audit) |
|
||||
|
||||
## 环境变量
|
||||
|
||||
各环境已增加:`SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095`(`.env.shared` / dev / test / prod)。
|
||||
@@ -522,10 +522,44 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工
|
||||
|
||||
- Run 是订单抽取的唯一业务真相;Job 仅代表一次执行尝试。Run 终态固定为 `completed / partially_completed / review_required / failed / cancelled`,其中 `review_required` 表示全部 PDF 都是业务拒识,`partially_completed` 表示成功与人工处理并存。
|
||||
- Unit 是 PDF 级处理单元,状态固定为 `pending / routing / matching_profile / extracting / merging_supplement / candidate_ready / review_required / failed / cancelled`;一份 PDF 的拒识或失败不得覆盖其他 PDF 已有结果。
|
||||
- **取消是请求语义,不是即时伪造终态**:Run/Unit 记录 `cancellation_requested_at / cancellation_actor_* / cancellation_reason* / cancellation_completed_at`;排队 Unit 可立即 `cancelled`,执行中 Unit 投影为用户可见阶段 `cancellation_requested`,Worker 仅在文件边界与外部副作用前安全点生效。已完成 Unit 结果保留。
|
||||
- 同一 `user_id + owner_agent_id + conversation_id` 同时最多一个 `queued / processing` Run;不同会话可并行。现有 Intake 单活跃约束继续生效。
|
||||
- 用户卡片只显示后端事实投影:Run 汇总、当前文件、当前业务动作、可操作按钮,以及按 PDF 打开的详情抽屉。用户端不再展示 Workflow、节点、Provider、LLM、伪百分比或内部运行标识。
|
||||
- 用户接口不得返回正文、原始订单、Prompt、密钥、Provider 配置、异常堆栈、绝对路径、MinIO 地址、Workflow Run ID、节点类型或 Job 信息。管理员诊断继续只读、脱敏并与用户契约分层。
|
||||
|
||||
#### 进度用户态契约(2026-07-29 扩展冻结)
|
||||
|
||||
| 内部状态/事件 | 用户可见阶段 `user_visible_stage` | 用户展示 |
|
||||
| --- | --- | --- |
|
||||
| `pending` / `document_queued` | `pending` / `document_queued` | 已接收,排队等待处理 |
|
||||
| `waiting_layout` / `layout_parsing_started` | `waiting_layout` / `layout_parsing_started` | 正在预处理文档结构 |
|
||||
| `routing` | `routing` | 正在识别文件类型与处理规则 |
|
||||
| `matching_profile` / `profile_matching` | `matching_profile` | 正在匹配订单解析模板 |
|
||||
| `extracting` / `table_reconstructed` / `order_fields_extracted` | `extracting` | 正在提取订单信息 |
|
||||
| `merging_supplement` / `email_supplement_merged` | `merging_supplement` | 正在合并邮件正文补充信息 |
|
||||
| `candidate_ready` | `candidate_ready` | 识别完成,正在生成订单结果 |
|
||||
| `review_required` | `review_required` | 需要人工确认(不得显示为技术失败) |
|
||||
| `technical_retrying` | `technical_retrying` | 正在重试 |
|
||||
| `failed` / `technical_failed` | `failed` | 处理失败,可重试 |
|
||||
| 取消已请求未生效 | `cancellation_requested` | 正在取消 |
|
||||
| `cancelled` / `unit_cancelled` / `cancellation_completed` | `cancelled` | 已取消 |
|
||||
| Run/Unit 成功终态 | `completed` | 处理完成 |
|
||||
|
||||
- 投影字段冻结:`user_visible_stage`、`queue_position`(仅排队 Unit)、`elapsed_seconds`、`last_activity_at`、`health_tips[]`、`cancellation`、`available_actions`、`handling_items[]`(Run 级待补/冲突/冻结/复核/失败/预算停扩)、`primary_notice`、`progress_version`(Run)/`activity_version`(Unit)。
|
||||
- Run 收口 `result_json` 保留受控处理事实:`pending_orders`(候选号/原因/缺失字段)、`auto_freeze.blocked_tasks`、`budget_stopped`;聊天卡与右侧「本次处理」按 `handling_items.category` 展示原因码、`affected_refs`(任务号/候选号/受限附件)与 `primary_action` 跳转,禁止仅用 `partially_completed`/`review_required` 笼统提示。聊天消息持久化去重签名包含 `handling_items`/`primary_notice`,保证历史会话恢复最新处理说明。
|
||||
- 健康提示阈值(后端统一计算,前端禁止本地臆造):连续 60 秒无新活动 → `processing_slow`;排队超过 5 分钟 → `queue_backlog`;处理超过 30 分钟 → `processing_attention`。
|
||||
- 轮询策略:前台活跃 2 秒;页面失焦 5–10 秒;网络失败指数退避,恢复后立即刷新。刷新只读事实,不产生业务变更。
|
||||
- `available_actions` 扩展:`refresh_status` / `cancel_run` / `cancel_unit`(权限与活跃态由服务端下发);既有 `view_details / enter_manual_review / retry_failed_attachments / view_evidence / review_candidate / manual_review` 保持。
|
||||
- 进度映射版本:`shipping-order-progress-v3`;新增事件码 `cancellation_requested` / `unit_cancelled` / `cancellation_completed`。
|
||||
- 代码唯一源:`backend/app/services/shipping_notice/progress_audit_contract.py`;前端类型:`shipping.api.types.ts`。
|
||||
|
||||
#### Run/Unit 取消状态机(契约)
|
||||
|
||||
1. 普通用户仅可取消自己创建的活跃 Run/Unit;管理员可取消任意活跃项,代取消必须填写原因。
|
||||
2. 整批取消为主操作;单文件取消在 PDF 行“更多操作”中,需二次确认。
|
||||
3. 仅失败项允许重试;重试保留原 Run、输入快照、旧 Attempt 与审计历史。
|
||||
4. API(阶段 1 实现):`POST .../order-extraction-runs/{run_no}/cancel`、`POST .../documents/{document_id}/cancel`、`GET .../timeline`(可复用 progress-events 并扩展取消/重试历史)。
|
||||
|
||||
#### 业务事件与工作台投影
|
||||
|
||||
| event_code | 业务含义 | 用户展示 |
|
||||
@@ -540,24 +574,96 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工
|
||||
| `review_required` | 业务拒识 | 需要人工复核 |
|
||||
| `technical_retrying` | 技术失败后重试中 | 系统正在重试失败附件 |
|
||||
| `technical_failed` | 技术失败 | 可重试失败附件 |
|
||||
| `cancellation_requested` | 已收到取消请求 | 正在取消(安全点生效前) |
|
||||
| `unit_cancelled` | 单 PDF 已取消 | 已取消 |
|
||||
| `cancellation_completed` | Run 取消收口完成 | 已取消(保留已完成结果) |
|
||||
| `run_completed` | 本次 Run 汇总完成 | 显示最终结论与下一步操作 |
|
||||
|
||||
- 用户工作台主接口固定返回 `summary / current_activity / available_actions`;详情接口固定返回按 PDF 归并的 `documents[]`。所有计数、当前活动和按钮权限均由后端计算,前端不得自行猜测。
|
||||
- `available_actions` 由服务端根据 Run/Unit 当前状态下发;聊天卡片只渲染 `view_details / enter_manual_review / retry_failed_attachments`,详情项只渲染 `view_evidence / review_candidate / manual_review`。
|
||||
- 事件必须是已经发生并持久化的事实,前端只根据 `event_code` 做 i18n 文案映射;不允许把 Dify 节点标题或自定义显示文本当作业务阶段。
|
||||
- 计数必须以 Unit 事实为准,禁止依赖可能滞后的批次摘要自行重算。
|
||||
- 事件必须是已经发生并持久化的事实,前端只根据 `event_code` / `user_visible_stage` 做 i18n 文案映射;不允许把 Dify 节点标题或自定义显示文本当作业务阶段。
|
||||
|
||||
#### 事件、健康与恢复
|
||||
|
||||
- 订单域使用独立短事务持久化 Progress Event、Run 摘要和文档详情投影,不能复用长时间 Worker 业务事务。事件以幂等键和序号去重;重复执行、迟到事件与终态保护必须保证事实不倒退。
|
||||
- 浏览器仅使用短轮询读取 Run 与 Documents 投影;网络失败只标记“暂时无法刷新状态”,不能把业务 Run 判成失败。页面刷新、重新登录和 Worker 重启后必须恢复到同一事实视图。
|
||||
- 健康阈值由后端统一计算:60 秒无新活动只在详情提示;积压判断基于 `queued / processing` 的持续时长与最终失败率。展示阈值不终止、不重试任务,真实超时仍沿用现有 Worker 策略。
|
||||
- 健康阈值由后端统一计算:60 秒无新活动只在详情提示;积压判断基于排队时长;处理超 30 分钟提示关注。展示阈值不终止、不重试任务,真实超时仍沿用现有 Worker 策略。
|
||||
|
||||
#### 全链路审计矩阵与脱敏保留(2026-07-29 冻结)
|
||||
|
||||
- `shipping_audit_events` 为货代域统一 append-only 账本;业务变更与审计必须同事务写入,禁止“业务已变更、审计缺失”或相反半成品。
|
||||
- 扩展字段:`operation_id`、`actor_role`、`source`、`result`、`error_code`、`conversation_id`、`unit_id`、`document_id`、`review_case_no`、`attempt_no`、`action`、`reason`、白名单 `before_snapshot_json`/`after_snapshot_json`、`evidence_refs_json`/`artifact_refs_json`、`context_refs_json`、`retention_expires_at`(默认 3 年)。
|
||||
- 快照仅允许 `progress_audit_contract.AUDIT_SNAPSHOT_ALLOWED_KEYS`;敏感黑名单包含 `password/token/secret/raw_content/body/url/quote/prompt/...`;原件只存 FileAsset ID + SHA-256 + 版本 + 证据坐标。
|
||||
- 必须审计节点:上传与接入、Run/Unit 状态迁移与取消/重试、解析阶段、人工复核、建单与履约、管理操作、Worker/回调/清理等系统动作。访问审计(查看详情、导出、下载受保护证据)与业务审计通过 `operation_id/request_id` 串联。
|
||||
- 迁移:`2b4c6d8e0f1a_shipping_progress_and_audit_contract`。
|
||||
- 四语言 i18n key 清单冻结见 `progress_audit_contract.I18N_KEY_INVENTORY`;阶段 2 补齐文案,阶段 0 禁止硬编码中文。
|
||||
|
||||
#### 待查看、管理诊断与保留
|
||||
|
||||
- 新功能上线后产生的 `completed / partially_completed / review_required / failed` Run 创建待查看标记;用户进入对应会话且终态卡片成功加载后才确认已查看。会话历史显示未查看数量和严重级别;仅加载列表、后台预取或失败请求不得清除。
|
||||
- 管理入口固定为“货代管理 → 订单识别 → 识别任务”,所有现有管理员可只读访问;不新增权限点,不提供管理员重试、取消、强制完成、导出或状态修改。
|
||||
- 管理入口固定为“货代管理 → 订单识别 → 识别任务”,并在“运行与审计”分组提供独立「运行与审计中心」(`AdminShippingAudit` / `/admin/shipping-audit`);管理员可查询/导出统一审计,普通用户不可访问。
|
||||
- 管理端访问记录订单域诊断审计:列表与详情访问分别记录一次;详情包含 Job Attempt、Unit 诊断和脱敏事件时间线。审计仅保留筛选摘要,绝不保存正文或输入输出。
|
||||
- 进度明细保留 90 天,Run 摘要、阶段累计耗时、Job Attempt 和最终错误码长期保留。默认排程 `shipping-order-extraction-progress-cleanup` 每日 03:15(Asia/Shanghai)分批清理明细;清理失败不得影响主链路并在下一次排程重试。
|
||||
- 进度明细保留 90 天;统一业务审计默认保留 3 年;Run 摘要、阶段累计耗时、Job Attempt 和最终错误码长期保留。默认排程 `shipping-order-extraction-progress-cleanup` 每日 03:15(Asia/Shanghai)分批清理进度明细;审计留存 Job `shipping-audit-retention`(阶段 4)支持 `limit`/`dry_run`,经 Core DELETE 绕过 append-only 守卫并写 `audit_retention_purged`。
|
||||
|
||||
#### 阶段 4:管理员审计中心、Diff、导出与履约接线(2026-07-30)
|
||||
|
||||
- 后端:`audit_query_service` 提供分页列表(无快照全文)、详情白名单 Diff、CSV/JSON 受控导出(上限 5000)、到期清理;列表/详情/导出均写 `audit_access`。
|
||||
- Admin API:`GET /api/admin/shipping-notice/audit-events`、`GET .../audit-events/<id>`、`POST .../audit-events/export`。
|
||||
- 履约链路:`fulfillment_audit.record_fulfillment_audit` 接入 Candidate 晋级/驳回、Decision 驳回/关闭、Excel 生成与 RPA 触发/成功回调;审计失败不得回滚业务成功路径。
|
||||
- 前端:`ShippingAuditCenterPage` + `shipping-audit.api`;侧栏注册 `shipping_audit` 于 `admin.nav.shippingRunAudit`;四语言 `admin.shippingAudit.*`。
|
||||
- 测试:`test_shipping_audit_query_service.py`;导航契约 `shippingConfigNavigation.spec.ts`。
|
||||
- **阶段 4 Dify**:无需修改画布;审计查询/导出/留存与履约审计均由 HXOPS 完成。
|
||||
|
||||
#### 会话 PDF 工作项架构(阶段 0–4,2026-07-30)
|
||||
|
||||
| 阶段 | 范围 | 关键交付 |
|
||||
| --- | --- | --- |
|
||||
| 0 | 领域契约与数据底座 | `ShippingSessionPdfWorkItem` 模型、审计列 `session_item_id`/`owner_user_id`、迁移 `3d6e8f0a1b2c` |
|
||||
| 1 | 后端状态机与 API | `session_pdf_work_item_service`、Workspace/Admin 监管 API、审计筛选扩展 |
|
||||
| 2 | 聊天右侧读模型 | `ShippingSessionSummaryPanel` 改拉 session-work-items,不再以最新 Run 定范围 |
|
||||
| 3 | 人工复核监管 UI | (并行开发)管理员复核/监管工作台 |
|
||||
| 4 | 审计中心与留存 | `ShippingAuditCenterPage` 增加 conversation/session_item/case/owner 筛选与详情;`SHIPPING_NOTICE_AUDIT_RETENTION_DAYS`(默认 1095)+ Job `shipping-audit-retention` |
|
||||
|
||||
- 验收文档:`session-pdf-work-item-stage0-acceptance.md` … `stage2-acceptance.md`、汇总 `session-pdf-work-item-final-acceptance.md`。
|
||||
- **Dify 边界(全阶段)**:Chatflow **不得**写入进度、取消、会话工作项或审计快照;HXOPS 拥有 Run/Unit/Progress Event/`shipping_audit_events`/session-work-items 真相。
|
||||
|
||||
#### 阶段 5:压测、灰度开关、回滚与 UAT(2026-07-30)
|
||||
|
||||
##### 功能开关(回滚 UI,不删审计)
|
||||
|
||||
| 环境变量 | 默认 | 关闭效果 |
|
||||
| --- | --- | --- |
|
||||
| `SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED` | `true` | 投影不下发 `health_tips`;阶段事实仍可读 |
|
||||
| `SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED` | `true` | 投影去掉 `cancel_run`/`cancel_unit`;取消 API 返回 `CANCEL_FEATURE_DISABLED` |
|
||||
| `SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED` | `true` | 列表/详情仍可查;导出返回 `AUDIT_EXPORT_FEATURE_DISABLED` |
|
||||
|
||||
- 代码:`progress_feature_flags.py`;投影下发 `feature_flags` 快照。
|
||||
- **回滚原则**:只关开关与前端入口;已写入 Progress Event / `shipping_audit_events` 保持只读兼容,禁止回滚删除审计事实。
|
||||
- **灰度顺序**:先管理员审计导出与诊断 → 观察取消成功率与轮询失败率 → 再对业务用户放开进度 UI v3 / 取消。
|
||||
|
||||
##### 压测与告警阈值
|
||||
|
||||
| 指标 | 门槛 | 观测 |
|
||||
| --- | --- | --- |
|
||||
| 并发投影只读(约 20 次重入) | 无异常、阶段/动作/版本一致 | `tests/performance/test_shipping_order_extraction_progress_load.py` |
|
||||
| 前台轮询 | 活跃 2s / 失焦 5–10s;失败指数退避 | 聊天 composable |
|
||||
| 健康提示 | 60s 无活动 / 排队 5min / 处理 30min | 仅展示,不终止任务 |
|
||||
| 审计导出 | 单次 ≤5000;写 `audit_access` | 管理端审计中心 |
|
||||
| 取消幂等 | 重复请求不破坏已完成 Unit | cancel 服务 + Worker 检查点 |
|
||||
|
||||
##### UAT 清单(业务验收)
|
||||
|
||||
1. 上传多 PDF:卡片阶段细化、无伪百分比/ETA;`review_required` 不显示为技术失败。
|
||||
2. 刷新只读;整批/单文件取消需确认;执行中显示「正在取消」,已完成结果保留。
|
||||
3. 任务中心「我的识别」可续办;管理员识别任务诊断与审计中心可查 Diff/导出。
|
||||
4. 关闭三开关后:无取消按钮、无健康提示芯片、导出被拒;历史审计仍可查。
|
||||
5. 全链路关键节点可按 `run_no/task_no/document_id/request_id/operation_id` 追溯。
|
||||
|
||||
##### 阶段 5 Dify 手工配置说明(最终)
|
||||
|
||||
- **确认**:货代 Chatflow **不**输出进度字段、**不**拦截取消、**不**写入审计快照,**不**成为订单抽取主链。
|
||||
- **无需**新增 Tool、节点、变量或 Prompt 以支持进度/取消/审计。
|
||||
- 若画布仍保留历史进度相关输出变量,应忽略或删除依赖;HXOPS 工作台一律以 Run/Unit/Progress Event / `shipping_audit_events` 为真相。
|
||||
|
||||
#### 2026-07-28 Dify 手工配置说明
|
||||
|
||||
@@ -569,9 +675,14 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工
|
||||
- **一封 EML 仍是一个 Intake**;一个 Document 可以产生多个 Candidate;跨附件同一订单由 LLM 合并并以一个主 Document、多个 evidence 记录来源。
|
||||
- **判重粒度是订单 Candidate,不是整封邮件或单个附件**:附件 hash 是证据之一,最终通过身份指纹 + 内容指纹区分完全重复与可能修订。
|
||||
- **自动建单硬条件**:`classification=shipping_request`、至少一条合法 `part_number` + 正数 Qty、分类与 `part_number`/Qty 置信度达阈值、两者均有非空原文证据、无阻断冲突、无必须人工决策的修订。
|
||||
- **自动建单硬条件**:`classification=shipping_request`、至少一条合法 `part_number` + 正数 Qty、分类与 `part_number`/Qty 置信度达阈值、两者均有非空原文证据、无阻断冲突、无必须人工决策的修订。
|
||||
- **流程字段允许缺失**:Reservation ID 缺失不阻止 Task 创建,但会阻止库存、匹配、Excel 与上传;自然对话补齐后重新进入解析确认。订单行 `inventory_source_hint` 可选,不单独触发门禁。
|
||||
|
||||
#### 2026-07-29 处理进度与全链路审计 — Dify 边界
|
||||
|
||||
- **不引入 Dify 到订单抽取主链**;进度、取消、重试、审计全部由 HXOPS 后端事实与 Job Worker 完成。
|
||||
- 管理员无需为取消、健康提示、审计导出或时间线新增任何 Dify Tool、节点、变量或 Prompt。
|
||||
- 全部任务结束后的正式 Dify 配置说明见阶段 5 与 [progress-audit-stage-acceptance.md](./progress-audit-stage-acceptance.md):现有货代 Chatflow 不输出进度字段、不拦截取消、不写入审计快照。
|
||||
|
||||
### 阶段 2 订单抽取执行边界
|
||||
|
||||
订单抽取由 HXOPS 冻结 Run、抽取计划和后台 Worker 执行。应用管理不配置内部执行器、Runtime Binding 或 Dify Workflow;普通货代 Chatflow 只负责无附件问答和后续交互,不参与订单抽取执行。
|
||||
@@ -1818,7 +1929,7 @@ docker compose --env-file .env.prod stop hxops-kb-worker hxops-backend
|
||||
|
||||
### 1.6 前端入口
|
||||
|
||||
- **聊天与上传**:主上传入口与一句过程通知;纯 `open_existing` 显示「发现重复文件,已关联已有任务」;会话右侧「本次处理」为唯一状态详情面(每 PDF 原因、复核 / 重复标签 / 已有任务深链)。文档投影含 `duplicate_resolution` / `existing_task_no` / `opened_existing_documents`。**不**渲染履约写操作按钮,**不**挂载顶部批次进度条与右侧批次履约抽屉。
|
||||
- **聊天与上传**:主上传入口与一句过程通知(优先 `primary_notice`/`handling_items`);纯 `open_existing` 显示「发现重复文件,已关联已有任务」;会话右侧「本次处理」为唯一状态详情面(Run 级处理事项 + 每 PDF 原因、复核 / 重复标签 / 已有任务深链)。文档投影含 `duplicate_resolution` / `existing_task_no` / `opened_existing_documents`。**不**渲染履约写操作按钮,**不**挂载顶部批次进度条与右侧批次履约抽屉。
|
||||
- **人工复核工作台**:建单前例外 PDF 的唯一写入口(Case/Draft/确认建单);确认后走与直通相同的 `auto_progress` 链。
|
||||
- **发货任务处理工作台**:建单后履约写操作的唯一入口(客户确认、库存源、缺口、Excel 下载、人工上传凭据)。业务按钮只消费后端 `ui_state.action_buttons` / `summary.allowed_actions`,禁止前端按 `process_status` 二次推导。
|
||||
- **我的待办**:跨会话聚合待复核 / 异常 / 待人工上传;徽标与列表同源后端 `todo_category`(SQL CASE 与状态机同序);`list_my_todos` 对 Review Case + Task 做 `UNION ALL` 后数据库 `COUNT`/`OFFSET`/`LIMIT`,仅水合当前页(`total` 为真实总数,禁止截断子集冒充);打开后深链进入复核或任务处理主区。
|
||||
@@ -2178,7 +2289,7 @@ API 层
|
||||
|
||||
订单抽取的执行结果只使用 `deterministic`、`review_required` 和 `skipped`:前者表示固定模板已产生可验证结果;后两者表示业务处理完成但需人工处理或无需解析,均不得计入技术失败。Run 终态固定为 `completed`、`needs_review`、`failed` 和 `cancelled`;只有解析器、数据库、对象存储或 Job 等技术故障可以进入 `failed`。
|
||||
|
||||
`shipping_audit_events` 是货代域统一的 append-only 审计账本。每条记录包含 `event_type`、聚合类型/编号、Run/Task/Intake 编号、操作者、请求与关联编号、原因码、前后状态哈希、脱敏元数据和时间。它不对可删除业务对象设置外键;ORM 更新或删除会被拒绝。审计元数据严禁包含邮件/PDF 正文、订单字段值、quote、坐标、Prompt、Token、API Key 或 Provider 配置。
|
||||
`shipping_audit_events` 是货代域统一的 append-only 审计账本。每条记录包含 `event_type`、聚合类型/编号、Run/Task/Intake 编号、操作者、`request_id`/`operation_id`、关联对象(conversation/unit/document/review_case/attempt)、`action`/`reason`、结果与错误码、白名单前后快照及其哈希、证据/产物引用、脱敏元数据和 `retention_expires_at`(默认 3 年)。它不对可删除业务对象设置外键;ORM 更新或删除会被拒绝。审计元数据与快照严禁包含邮件/PDF 正文、订单字段值、quote、坐标、Prompt、Token、API Key、对象存储 URL 或 Provider 配置。
|
||||
|
||||
#### 阶段 1:确定性订单解析与 Dify 退役(2026-07-27)
|
||||
|
||||
|
||||
+4
-2
@@ -65,11 +65,13 @@
|
||||
| 上传与发送门禁状态一致性 | 已实现 | Intake 状态接口返回 `preview_status / ready_for_extraction / attachment_directory_complete` 等快览事实;聊天附件快览成功后显示“已就绪/已发现 N 个附件”并允许发送,不再因上传阶段版面任务阻塞;真正的订单识别进度在点击发送后单独展示 |
|
||||
| 点击发送完整订单抽取 | 已实现 | Run 冻结文档、Schema、模板 Profile 和确定性解析器版本;Worker 只执行本地模板解析、证据门禁和幂等重放,不依赖 Dify、Provider 或 Runtime Binding;旧的一附件多订单投影待订单复核目标态阶段 7 清理 |
|
||||
| 订单识别生命周期反馈 | 已实现 | Run 状态卡按真实确定性解析进度和终态计数更新并持久化到 `ChatLog.payload`;聊天历史可恢复,侧栏显示未查看终态提醒,处理中不伪造百分比 |
|
||||
| 处理进度细化与全链路审计 | 已实现 | 阶段 0–5 + 正式评审整改:排队/处理中分列、文档级健康提醒与最后活动、管理员取消任意 Run(代取消必填原因)、审计完整筛选(含 conversation/session_item/review_case/owner)、敏感访问审计、取消 operation_id 串联、进度事件真实状态、库存/RPA/导出双写统一审计。Run 级 `handling_items`/`primary_notice` 拆分待补信息/冲突/自动冻结受阻/PDF 复核/技术失败/预算停扩,聊天卡与右侧「本次处理」按原因展示并跳转。灰度开关 `PROGRESS_UI_V3`/`ORDER_EXTRACTION_CANCEL`/`AUDIT_EXPORT`;审计保留 `SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095`。Dify 无需改画布 |
|
||||
| 会话 PDF 工作项(阶段 0–4) | 已实现(阶段 3 UI 并行) | 会话级 PDF 聚合实体、Workspace/Admin 监管 API、聊天右侧工作项列表、审计中心会话字段筛选与可配置三年留存 Job;见 [technical.md §会话 PDF 工作项](features/shipping-notice/technical.md) 与 `session-pdf-work-item-final-acceptance.md` |
|
||||
| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,PDF 数量保持权威,歧义统一进入人工复核 |
|
||||
| PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 |
|
||||
| 订单模板版本中心(阶段 0-7) | 已实现 | 订单文档模板按 `profile_code` 聚合版本族;已落地独立版本详情、历史只读样本画布、服务端语义差异、审计记录页签、实际使用页签,以及阶段 7 的 blind test 隔离与发布治理 |
|
||||
| 订单模板录入 UX 重构(阶段 0-7) | 已完成 | 已完成 Draft Revision、Lease、向导、独立草稿编辑器自动保存、不可变验证运行与两步发布报告;盲测工作台支持独立样本复核、执行与批准,编辑器在可见状态自动续租。阶段 7 已删除旧兼容工作台/创建路径和直接发布入口,并完成前后端构建、定向回归、迁移链及四语言校验。Dify 无需配置变更,仅由管理员核对本地确定性解析主链未接入模板治理接口。 |
|
||||
| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。确认后复用同一 `auto_progress` 链 |
|
||||
| 订单人工复核工作台(阶段 0-7) | 已实现 | 每个 PDF Unit 一个 Review Case,机器 Candidate/Extraction 不可变、人工 Draft 独立版本化;按 PDF 独立处置、证据复核与原子确认建单,不支持多订单 PDF 或跨 PDF 合并/拆分。字段和明细可按冻结 bbox 定位 PDF 原文(明细按 table/cell 反查),版本历史按需展开;确认后展示 `auto_progress` 真实结果/检查点并可直达任务进度工作台。 |
|
||||
| **STP 直通 + 例外工作台** | 进行中 | 可信 PDF 自动建 Task 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知;`checkpoint_kind` + 可解释 `summary`;我的待办跨会话入口。首期不触发货代 RPA 上传、不改 Dify |
|
||||
| 模板发布与自动冻结资格分离(阶段 4) | 已实现 | Profile 的发布仅允许确定性解析;每个发布版本独立冻结人工确认资格,首版强制 `manual_confirmation` 且自动冻结关闭,盲测批准、旧版本资格或 checksum 变化均不能越过该门禁 |
|
||||
| Run 自动冻结门禁与执行 | 已实现 | Run 创建时冻结 `manual_confirmation` 初始策略;结果落库后按模板资格、已确认 Bill-to 客户、业务场景、技术失败、预算停止和待处理订单刷新 `auto_freeze_policy_json`。仅资格与全部门禁显式放行时,自动消费当前 Run 的 accepted Candidate 并冻结新建 Task;不触发库存、Excel 或上传履约副作用。 |
|
||||
@@ -89,7 +91,7 @@
|
||||
| 客户身份与业务编号规则 | 已文档化 | 内部 `SN-...` 与业务号分离;业务号固定为 `客户简码 + YYMMDD + 两位流水`,例如 `WYC26071501`,日期口径 `Asia/Shanghai` |
|
||||
| 客户受控合并 | 已实现 | 管理员预览历史保留与未来配置迁移后,输入源简码和原因归并至启用目标客户;历史业务/编号/审计不改写,识别证据和来源键迁移,源客户标记为 merged 并不可再用于新任务 |
|
||||
| 期初客户导入与对账 | 已实现 | 标准 Excel 模板、上传暂存、预检查重、冲突决策、单事务发布、来源键幂等重导和 CSV 对账 |
|
||||
| 客户影子识别 | 已实现 | Candidate 抽取后记录客户候选、证据和版本;支持人工真值标签与准确率报告,不绑定、不编号、不阻断现有货代流程 |
|
||||
| 客户影子识别 | 已实现 | Candidate 抽取后记录客户候选、证据和版本;Schema 普通升级造成字段 UUID 变化时,按冻结语义安全映射新版 Header 字段;支持人工真值标签与准确率报告,不绑定、不编号、不阻断现有货代流程 |
|
||||
| 客户人工确认与 Gate | 已实现 | `customer_review`;业务用户从标准客户主数据中确认,客户未稳定时阻断库存源、RPA、匹配、Excel 和上传 |
|
||||
| 受控自动客户识别 | 已实现 | 仅对 approved 且允许自动匹配的邮箱/非公共域名/模板指纹开放;唯一命中才自动确认,默认关闭;管理端可查询自动裁决、自动确认、历史回填和“原号作废 + 新号替代”纠错审计 |
|
||||
| 客户治理闭环 | 已实现 | 客户与识别证据关键变更记录快照时间线;简码、状态、自动匹配授权必须填写原因。自动确认在总开关外再受有效人工标注样本量(默认 20)与准确率(默认 98%)门禁约束,未达标保持 `customer_review`;客户主数据页展示时间线和降级原因 |
|
||||
|
||||
+9
-1
@@ -102,7 +102,7 @@
|
||||
- Excel 命名规则由已发布模板的 `filename_pattern` 定义;未定义时读取环境变量 `SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN`。两者均由后端编译、校验并在 Artifact 保存规则来源、版本、最终文件名和独立流水。客户端请求不得携带命名模式或文件名;流水即使 Artifact 作废亦不得复用。
|
||||
- LLM Observation 必须有真实 `evidence_ref`,并以 `evidence_verified=false` 落库;任意关键字段存在该类 Observation 时,冻结门禁返回 `SHIPPING.ORDER_LLM_REVIEW_REQUIRED`。Dify 故障只能转人工复核,不能使确定性模板路径降级为猜测。
|
||||
- JSON API 按统一 envelope 返回。关键错误码至少包括 `SHIPPING.ORDER_SNAPSHOT_FROZEN`、`SHIPPING.ORDER_LLM_REVIEW_REQUIRED`、`SHIPPING.RESERVATION_CONFLICT`、`SHIPPING.INVENTORY_STALE`、`SHIPPING.EXPORT_NOT_READY`、`SHIPPING.UPLOAD_EVIDENCE_REQUIRED`;权限矩阵禁止 Dify/普通用户调用冻结、制单、上传回调和作废接口。
|
||||
- **引用与快照**:规则保存 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。
|
||||
- **引用与快照**:规则保存发布时的 `context_field_id`,发布/运行快照同时冻结字段代码、显示名、Schema 字段配置、规则集版本、定义和命中证据。运行期优先按快照 ID 取值;普通 Schema 升级仅在 `field_code`、Header 作用域、值类型和身份授权均未变化时映射新 ID,实际命中字段 ID 仍写入证据链。字段退役、删除或 Schema 发布移除被启用规则引用字段时服务端阻断。
|
||||
- **裁决边界**:客户主体和送货站点独立候选;编码确定性匹配优先;多命中、冲突、未命中均进入人工复核。业务弱证据(地址、联系人、名称)默认不得单独自动确认;公共邮箱域名永久禁止。
|
||||
- **Dify**:不新增 Tool 或修改画布。Dify 继续按已发布动态 Schema 契约提交 Header Observation;HXOPS 完成证据校验、字段裁决、规则匹配、质量门禁和最终确认。
|
||||
|
||||
@@ -148,6 +148,14 @@
|
||||
- 订单完整抽取不展示虚假百分比;Run 卡片展示排队、当前文件与业务动作、终态摘要及下一步操作,轮询断线不改变后台作业状态。
|
||||
- 订单抽取进度采用“订单域事实建模、工作台投影展示”:订单域以独立短事务持久化脱敏业务事件、Run 当前投影和 90 天明细;浏览器通过 Run API 与 Documents API 自适应短轮询读取投影,用户端与管理员端按字段白名单分层展示。
|
||||
- 订单进度事件只允许固定 `event_code` 与稳定原因码,不能依赖 Dify 节点标题、节点类型或自由显示文本推断业务阶段;迟到事件不得回退终态。进度记录失败不得影响订单落库事务。
|
||||
- **处理进度细化与全链路审计技术约束(2026-07-29)**:
|
||||
- **不引入** Temporal、Airflow、Argo、n8n 等重型工作流平台;继续使用现有 Flask + SQLAlchemy + Job Worker/Redis。业务 Run/Unit 是真相,Job 是执行尝试,Progress Event 与 `shipping_audit_events` 追加不可变。
|
||||
- 跨对象关联键:`request_id + operation_id + run_no + unit_id + task_no + attempt_no`;取消使用乐观 `progress_version`/`activity_version` 与状态迁移白名单,外部副作用前检查取消请求。
|
||||
- 审计与业务同事务;快照白名单 + 敏感键黑名单;默认保留 3 年并以 `retention_expires_at` 索引支持受控归档。轮询按 Run 精确查询并服务端聚合,避免前端全量过滤。
|
||||
- 功能开关控制“新进度展示 / Run-Unit 取消 / 管理员审计导出”;回滚 UI 时已写入事件与审计保持只读兼容,不回滚删除审计事实。
|
||||
- 契约代码源:`progress_audit_contract.py`;迁移 head 含 `2b4c6d8e0f1a`。
|
||||
- 阶段 4:管理员审计中心 API(`audit_query_service` + `/api/admin/shipping-notice/audit-events*`)、履约关键节点 `fulfillment_audit`、平台 Job `shipping-audit-retention`;前端 `/admin/shipping-audit`。
|
||||
- 阶段 5:功能开关 `SHIPPING_NOTICE_PROGRESS_UI_V3_ENABLED` / `SHIPPING_NOTICE_ORDER_EXTRACTION_CANCEL_ENABLED` / `SHIPPING_NOTICE_AUDIT_EXPORT_ENABLED`(`progress_feature_flags.py`);压测冒烟 `tests/performance/`;回滚只关开关不删审计。
|
||||
|
||||
### 2.x 字段资产与 Schema 契约基础(目标态)
|
||||
|
||||
|
||||
@@ -16,7 +16,9 @@
|
||||
|
||||
| 功能分类 | 功能子项 | 功能描述 | 测试代码撰写要求 | 测试输入数据 (示例) | 预期测试输出 (示例) |
|
||||
| :--- | :--- | :--- | :--- | :--- | :--- |
|
||||
| **发货通知** | **STP 直通 + 例外工作台契约** | checkpoint_kind / 可解释 summary / 待办分类同源;auto_progress 止于待人工上传且不触发货代 RPA 上传;创建者可处理、管理员只读。 | `test_shipping_notice_state_machine.py`、`test_shipping_notice_ui_state.py`、`test_shipping_notice_query_service.py`(my-todos)、`test_shipping_notice_stp_acceptance.py`、technical.md §1.6 / §3.4 | 可信直通、多 PDF 隔离、人工复核确认后 auto_progress、无证据拒绝人工上传、跨会话待办、禁 RPA 上传 | 任意入口相同 checkpoint/kind/summary/actions;待办深链进入复核或任务处理;四语言与构建通过。 |
|
||||
| **发货通知** | **处理进度细化与全链路审计(阶段 0 契约)** | 冻结用户可见阶段、取消请求语义、健康提示阈值、审计字段/脱敏黑名单/三年保留与 i18n key 清单;迁移 `2b4c6d8e0f1a`。 | `test_shipping_progress_audit_contract_stage0.py`、`test_shipping_audit_event.py`、technical.md 进度/审计契约 | 敏感键元数据/快照、Run/Unit 取消列、Alembic head | 黑名单拒绝;契约词典唯一;head=`2b4c6d8e0f1a`。 |
|
||||
| **发货通知** | **处理进度细化与全链路审计(阶段 4 审计中心)** | 管理员统一审计查询、白名单 Diff、受控 CSV/JSON 导出、访问审计、履约关键节点审计、三年到期清理 Job。 | `test_shipping_audit_query_service.py`、`shippingConfigNavigation.spec.ts`、`audit_query_service`/`fulfillment_audit`/`shipping-audit-retention` | 列表无快照、详情 Diff、导出上限、dry_run/正式清理、导航 `shipping_audit` | 访问写 `audit_access`;导出无 snapshot/正文;Core DELETE 写 `audit_retention_purged`;侧栏与路由可发现。 |
|
||||
| **发货通知** | **处理进度细化与全链路审计(阶段 5 灰度与压测)** | 功能开关控制进度 UI/取消/审计导出;并发投影与审计列表冒烟;全链路关联键追溯;UAT/回滚文档。 | `test_shipping_progress_feature_flags.py`、`tests/performance/test_shipping_order_extraction_progress_load.py`、`test_shipping_audit_end_to_end.py`、前端 `e2e/*.spec.ts` | 关开关后无取消动作、导出拒绝、20 并发投影、run/task/operation 可追溯 | 回滚不删审计;`CANCEL_FEATURE_DISABLED`/`AUDIT_EXPORT_FEATURE_DISABLED`;Dify 无需改画布。 |
|
||||
| **发货通知** | **字段资产库与标准目录** | 全局系统标准 57 项只读;扩展可创建/弃用/恢复;禁止物理删除与 mail/context 入资产;标准不可弃用。 | `test_shipping_field_asset_service.py`、迁移 `1b2c3d4e5f6a`、前端 `shipping-field-assets` 导航单测 | 种子标准、扩展撞标准码、sender_email、无原因弃用、DELETE | 标准=57;扩展 active⇄retired 有审计;409 `FIELD_ASSET_DELETE_FORBIDDEN` / `STANDARD_NO_RETIRE` / `CONTEXT_FORBIDDEN`。 |
|
||||
| **发货通知** | **Schema 采用式契约与建议集** | 唯一 Schema 仅采用资产;草稿取消采用不删资产;retired 扩展不可采用;C4 建议 15 项可一键勾选但须手动发布。 | `order_schema/service` 相关测试、`shippingConfigNavigation.spec.ts`、Schema 页采用 UI | 空 Schema 初始化、采用建议 15、取消采用、发布 V1 | published 只读;definition 仅含采用字段;建议集不等于自动发布。 |
|
||||
| **发货通知** | **字段影响分析与发布门禁** | 取消采用或弃用前汇总下游引用;配置引用阻断,历史 Run 只读不阻断;发布同事务写 checksum。 | `test_field_impact_analysis.py`、Schema publish API | Excel/模板仍引用 field_id、历史 Observation 仅提示、lock 冲突 | 409 `FIELD_IMPACT_BLOCKED`/`publish_blocked` 审计;无阻断时可发布。 |
|
||||
|
||||
@@ -57,6 +57,10 @@ const ShippingIdentityRulesPage = () =>
|
||||
import("@/features/admin/modules/shipping-identity-rules/ShippingIdentityRulesPage.vue");
|
||||
const ShippingOrderExtractionRunsPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-extraction-runs/ShippingOrderExtractionRunsPage.vue");
|
||||
const ShippingAuditCenterPage = () =>
|
||||
import("@/features/admin/modules/shipping-audit/ShippingAuditCenterPage.vue");
|
||||
const ShippingReviewSupervisionPage = () =>
|
||||
import("@/features/admin/modules/shipping-review-supervision/ShippingReviewSupervisionPage.vue");
|
||||
const ShippingOrderDocumentProfilesPage = () =>
|
||||
import("@/features/admin/modules/shipping-order-document-profiles/ShippingOrderDocumentProfilesPage.vue");
|
||||
const OrderProfileVersionDetailPage = () =>
|
||||
@@ -199,6 +203,18 @@ export const adminRoutes: RouteRecordRaw[] = [
|
||||
component: ShippingOrderExtractionRunsPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'order_extraction_runs', title: "识别任务" },
|
||||
},
|
||||
{
|
||||
path: "shipping-audit",
|
||||
name: "AdminShippingAudit",
|
||||
component: ShippingAuditCenterPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'shipping_audit', title: "运行与审计" },
|
||||
},
|
||||
{
|
||||
path: "shipping-review-supervision",
|
||||
name: "AdminShippingReviewSupervision",
|
||||
component: ShippingReviewSupervisionPage,
|
||||
meta: { requiresAdmin: true, adminModule: "shipping_inventory", adminSubModule: 'shipping_review_supervision', title: "复核监管" },
|
||||
},
|
||||
{
|
||||
path: "shipping-order-document-profiles",
|
||||
name: "AdminShippingOrderDocumentProfiles",
|
||||
|
||||
@@ -82,9 +82,21 @@ export type ShippingOrderExtractionDiagnosticAutoFreezePolicy = {
|
||||
|
||||
export type ShippingOrderExtractionDiagnosticRun = {
|
||||
run_no: string; status: string; phase: string; conversation_id: string;
|
||||
attempt_count: number; current_event_code?: string | null; created_at?: string | null; started_at?: string | null;
|
||||
candidate_materialized_at?: string | null; finished_at?: string | null; error_code?: string | null; durations_ms: Record<string, number | null>;
|
||||
user_id?: number | null;
|
||||
attempt_count: number; progress_version?: number | null;
|
||||
current_event_code?: string | null; created_at?: string | null; started_at?: string | null;
|
||||
candidate_materialized_at?: string | null; finished_at?: string | null; last_activity_at?: string | null;
|
||||
error_code?: string | null; durations_ms: Record<string, number | null>;
|
||||
result_counts: Record<string, number>;
|
||||
cancellation?: {
|
||||
requested: boolean;
|
||||
completed: boolean;
|
||||
in_flight: boolean;
|
||||
requested_at?: string | null;
|
||||
completed_at?: string | null;
|
||||
actor_type?: string | null;
|
||||
reason_code?: string | null;
|
||||
} | null;
|
||||
auto_freeze_policy: ShippingOrderExtractionDiagnosticAutoFreezePolicy;
|
||||
};
|
||||
export type ShippingOrderExtractionDiagnosticDetail = {
|
||||
@@ -93,13 +105,50 @@ export type ShippingOrderExtractionDiagnosticDetail = {
|
||||
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'review_required' | 'skipped'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>;
|
||||
progress_events: Array<{ sequence_no: number; visibility: 'workspace' | 'admin'; event_code: string; status?: string | null; unit_id?: number | null; document_id?: number | null; reason_code?: string | null; summary?: Record<string, unknown> | null; occurred_at?: string | null }>;
|
||||
};
|
||||
export const listShippingOrderExtractionDiagnosticRuns = (page = 1, pageSize = 25, status = '') => {
|
||||
export type ShippingOrderExtractionHealth = {
|
||||
generated_at: string;
|
||||
health_status: 'healthy' | 'degraded' | string;
|
||||
window_hours: number;
|
||||
thresholds: Record<string, number>;
|
||||
counts: Record<string, number>;
|
||||
status_counts: Record<string, number>;
|
||||
phase_counts: Record<string, number>;
|
||||
error_code_counts: Record<string, number>;
|
||||
failure_rate: number;
|
||||
latency: Record<string, { count: number; avg_ms?: number | null; p50_ms?: number | null; p95_ms?: number | null; max_ms?: number | null }>;
|
||||
stale_run_nos: string[];
|
||||
};
|
||||
export const listShippingOrderExtractionDiagnosticRuns = (
|
||||
page = 1,
|
||||
pageSize = 25,
|
||||
status = '',
|
||||
options?: { staleOnly?: boolean; cancellationInFlight?: boolean },
|
||||
) => {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
|
||||
if (status) params.set('status', status);
|
||||
if (options?.staleOnly) params.set('stale_only', 'true');
|
||||
if (options?.cancellationInFlight) params.set('cancellation_in_flight', 'true');
|
||||
return requestJson<{ items: ShippingOrderExtractionDiagnosticRun[]; total: number; page: number; page_size: number }>(`/api/admin/shipping-notice/order-extraction-runs?${params}`, auth());
|
||||
};
|
||||
export const getShippingOrderExtractionDiagnosticRun = (runNo: string) =>
|
||||
requestJson<ShippingOrderExtractionDiagnosticDetail>(`/api/admin/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}`, auth());
|
||||
/** 管理员取消任意活跃订单抽取 Run;代取消必须提供 reason。 */
|
||||
export const cancelShippingOrderExtractionRun = (
|
||||
runNo: string,
|
||||
payload: { reason?: string | null; reason_code?: string | null } = {},
|
||||
) => requestJson<{ run: ShippingOrderExtractionDiagnosticRun }>(
|
||||
`/api/admin/shipping-notice/order-extraction-runs/${encodeURIComponent(runNo)}/cancel`,
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 管理员健康聚合:积压、失败率、P50/P95 时延与卡住 Run 编号。 */
|
||||
export const getShippingOrderExtractionHealth = (windowHours = 24) => {
|
||||
const params = new URLSearchParams({ window_hours: String(windowHours) });
|
||||
return requestJson<ShippingOrderExtractionHealth>(
|
||||
`/api/admin/shipping-notice/order-extraction-runs/health?${params}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
/** 下载管理员可访问的库存快照,并保留服务端指定的原始文件名。 */
|
||||
export const downloadShippingInventorySnapshot = async (snapshotId: number, fallbackName: string): Promise<void> => {
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* features/admin/api/shipping-audit.api.ts
|
||||
* 用途:货代统一审计查询/详情/导出 HTTP 客户端。
|
||||
* 依赖:shared/api/client、getAuthHeaders。
|
||||
* 逻辑:由 ShippingAuditCenterPage 调用;导出走 blob 下载并保留服务端文件名。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
|
||||
export type ShippingAuditEventSummary = {
|
||||
id: number;
|
||||
event_type: string;
|
||||
aggregate_type: string;
|
||||
aggregate_id: string;
|
||||
run_no?: string | null;
|
||||
task_no?: string | null;
|
||||
document_id?: string | null;
|
||||
conversation_id?: string | null;
|
||||
session_item_id?: string | null;
|
||||
review_case_no?: string | null;
|
||||
owner_user_id?: string | null;
|
||||
actor_type: string;
|
||||
actor_id?: string | null;
|
||||
request_id?: string | null;
|
||||
operation_id?: string | null;
|
||||
result?: string | null;
|
||||
action?: string | null;
|
||||
reason_code?: string | null;
|
||||
error_code?: string | null;
|
||||
has_snapshots: boolean;
|
||||
created_at?: string | null;
|
||||
};
|
||||
|
||||
export type ShippingAuditDiffRow = {
|
||||
key: string;
|
||||
change: 'added' | 'removed' | 'changed' | string;
|
||||
before: unknown;
|
||||
after: unknown;
|
||||
};
|
||||
|
||||
export type ShippingAuditEventDetail = ShippingAuditEventSummary & {
|
||||
before_snapshot?: Record<string, unknown> | null;
|
||||
after_snapshot?: Record<string, unknown> | null;
|
||||
diff?: ShippingAuditDiffRow[];
|
||||
metadata?: Record<string, unknown>;
|
||||
evidence_refs?: Array<Record<string, unknown>>;
|
||||
artifact_refs?: Array<Record<string, unknown>>;
|
||||
};
|
||||
|
||||
export type ShippingAuditFilters = {
|
||||
event_type?: string;
|
||||
actor_type?: string;
|
||||
/** 操作者用户 ID;与后端 audit_query_service.actor_id 对齐 */
|
||||
actor_id?: string;
|
||||
run_no?: string;
|
||||
task_no?: string;
|
||||
document_id?: string;
|
||||
operation_id?: string;
|
||||
request_id?: string;
|
||||
/** 会话 ID;与后端 conversation_id 筛选对齐 */
|
||||
conversation_id?: string;
|
||||
/** 会话 PDF 工作项编号 */
|
||||
session_item_id?: string;
|
||||
/** 人工复核 Case 编号 */
|
||||
review_case_no?: string;
|
||||
/** 工作项属主用户 ID */
|
||||
owner_user_id?: string;
|
||||
result?: string;
|
||||
created_from?: string;
|
||||
created_to?: string;
|
||||
q?: string;
|
||||
};
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
|
||||
/**
|
||||
* 分页查询审计事件列表(无快照全文)。
|
||||
*/
|
||||
export function listShippingAuditEvents(page = 1, pageSize = 25, filters: ShippingAuditFilters = {}) {
|
||||
const params = new URLSearchParams({ page: String(page), page_size: String(pageSize) });
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
if (value) params.set(key, String(value));
|
||||
});
|
||||
return requestJson<{ items: ShippingAuditEventSummary[]; total: number; page: number; page_size: number }>(
|
||||
`/api/admin/shipping-notice/audit-events?${params}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取单条审计详情(含白名单快照与 diff)。
|
||||
*/
|
||||
export function getShippingAuditEvent(eventId: number) {
|
||||
return requestJson<ShippingAuditEventDetail>(
|
||||
`/api/admin/shipping-notice/audit-events/${encodeURIComponent(String(eventId))}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 受控导出审计 CSV/JSON,并触发浏览器下载。
|
||||
*/
|
||||
export async function exportShippingAuditEvents(
|
||||
filters: ShippingAuditFilters = {},
|
||||
format: 'csv' | 'json' = 'csv',
|
||||
): Promise<void> {
|
||||
const response = await fetch('/api/admin/shipping-notice/audit-events/export', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ ...filters, format, limit: 2000 }),
|
||||
});
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const blob = await response.blob();
|
||||
const disposition = response.headers.get('Content-Disposition') || '';
|
||||
const filename = disposition.match(/filename="?([^";]+)"?/i)?.[1]
|
||||
|| `shipping-audit.${format}`;
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
const anchor = document.createElement('a');
|
||||
anchor.href = objectUrl;
|
||||
anchor.download = filename;
|
||||
anchor.click();
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
@@ -391,6 +391,15 @@ export const getOrderProfilePageTextCandidates = (profileId: number, documentId:
|
||||
auth(),
|
||||
);
|
||||
|
||||
/** 读取当前受控样本中框选区域的坐标文本;仅用于画布生成文档匹配锚点。 */
|
||||
export const readOrderProfilePreviewPageRegionText = (
|
||||
profileId: number, documentId: number, pageNo: number, region: { x0: number; y0: number; x1: number; y1: number },
|
||||
) => requestJson<{ document_id: number; page_no: number; text: string; source: string | null; status: 'needs_review' }>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/region-text`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId, region }), ...jsonAuth(),
|
||||
},
|
||||
);
|
||||
|
||||
/** 使用当前 Profile 绑定样本执行局部坐标重建候选。 */
|
||||
export const previewOrderProfileRegion = (
|
||||
profileId: number, documentId: number, tableId: string, definition: ShippingOrderDocumentProfile['definition'],
|
||||
@@ -426,8 +435,8 @@ export const removeOrderProfileTestSample = (suiteId: number, sampleId: number)
|
||||
);
|
||||
|
||||
/** 列出未参与当前模板标注/训练且可用于盲测的受控订单样本。 */
|
||||
export const listOrderProfileBlindTestAvailableSamples = (suiteId: number) => requestJson<{ samples: OrderProfileBlindTestAvailableSample[] }>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/available-samples`, auth(),
|
||||
export const listOrderProfileBlindTestAvailableSamples = (suiteId: number, signal?: AbortSignal) => requestJson<{ samples: OrderProfileBlindTestAvailableSample[] }>(
|
||||
`/api/admin/shipping-notice/order-document-profile-test-suites/${suiteId}/available-samples`, { ...auth(), signal },
|
||||
);
|
||||
/** 自动运行独立样本,候选仅供管理员勾选复核,尚未写入真值。 */
|
||||
export const previewOrderProfileBlindTestCandidate = (suiteId: number, payload: { document_id: number; table_id: string }) => requestJson<OrderProfileBlindTestCandidate>(
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* features/admin/api/shipping-review-supervision.api.ts
|
||||
* 用途:管理员跨用户会话 PDF 工作项监管 HTTP 客户端。
|
||||
* 依赖:shared/api/client、chat 域 ShippingSessionWorkItem 类型。
|
||||
* 逻辑:由 ShippingReviewSupervisionPage 调用;终止/撤销须理由与 confirm_token。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { ShippingSessionWorkItem } from '@/features/chat/types/shipping.api.types';
|
||||
|
||||
export type ShippingReviewSupervisionFilters = {
|
||||
lifecycle_status?: string;
|
||||
owner_user_id?: string;
|
||||
conversation_id?: string;
|
||||
q?: string;
|
||||
};
|
||||
|
||||
export type ShippingReviewSupervisionPage = {
|
||||
items: ShippingSessionWorkItem[];
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
};
|
||||
|
||||
export const SUPERVISION_CONFIRM_TERMINATE = 'CONFIRM_TERMINATE';
|
||||
export const SUPERVISION_CONFIRM_REVOKE = 'CONFIRM_REVOKE';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
|
||||
/**
|
||||
* 分页查询跨用户会话 PDF 工作项;服务端已做管理员鉴权。
|
||||
*/
|
||||
export function listShippingReviewSupervisionItems(
|
||||
page = 1,
|
||||
pageSize = 20,
|
||||
filters: ShippingReviewSupervisionFilters = {},
|
||||
) {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
page_size: String(pageSize),
|
||||
});
|
||||
if (filters.lifecycle_status) params.set('lifecycle_status', filters.lifecycle_status);
|
||||
if (filters.owner_user_id) params.set('owner_user_id', filters.owner_user_id);
|
||||
if (filters.conversation_id) params.set('conversation_id', filters.conversation_id);
|
||||
if (filters.q) params.set('q', filters.q);
|
||||
return requestJson<ShippingReviewSupervisionPage>(
|
||||
`/api/admin/shipping-notice/session-work-items?${params}`,
|
||||
auth(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员终止工作项;必须填写 reason 且 confirm_token 为 CONFIRM_TERMINATE。
|
||||
*/
|
||||
export function terminateShippingReviewSupervisionItem(
|
||||
itemNo: string,
|
||||
payload: { reason: string; confirm_token: typeof SUPERVISION_CONFIRM_TERMINATE },
|
||||
) {
|
||||
return requestJson<{ item: ShippingSessionWorkItem }>(
|
||||
`/api/admin/shipping-notice/session-work-items/${encodeURIComponent(itemNo)}/terminate`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员 24 小时内撤销确认;必须填写 reason 且 confirm_token 为 CONFIRM_REVOKE。
|
||||
*/
|
||||
export function revokeShippingReviewSupervisionConfirmation(
|
||||
itemNo: string,
|
||||
payload: { reason: string; confirm_token: typeof SUPERVISION_CONFIRM_REVOKE },
|
||||
) {
|
||||
return requestJson<Record<string, unknown>>(
|
||||
`/api/admin/shipping-notice/session-work-items/${encodeURIComponent(itemNo)}/revoke-confirmation`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...getAuthHeaders(),
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* features/admin/api/shipping-review-supervision.spec.ts
|
||||
* 用途:复核监管台 API 契约——confirm_token 与理由必填边界。
|
||||
* 依赖:shipping-review-supervision.api 常量。
|
||||
* 逻辑:断言终止/撤销 token 稳定,便于前后端与 i18n 对齐。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
SUPERVISION_CONFIRM_REVOKE,
|
||||
SUPERVISION_CONFIRM_TERMINATE,
|
||||
} from './shipping-review-supervision.api';
|
||||
|
||||
describe('shipping review supervision api contract', () => {
|
||||
it('requires stable terminate confirm token', () => {
|
||||
expect(SUPERVISION_CONFIRM_TERMINATE).toBe('CONFIRM_TERMINATE');
|
||||
});
|
||||
|
||||
it('requires stable revoke confirm token', () => {
|
||||
expect(SUPERVISION_CONFIRM_REVOKE).toBe('CONFIRM_REVOKE');
|
||||
});
|
||||
|
||||
it('rejects empty reason before submit in UI contract', () => {
|
||||
const reason = ' ';
|
||||
// 关键断言:监管台须在客户端拦截空理由,与服务端校验一致。
|
||||
expect(reason.trim().length).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -21,6 +21,8 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| 'AdminShippingOrderSchema'
|
||||
| 'AdminShippingIdentityRules'
|
||||
| 'AdminShippingOrderExtractionRuns'
|
||||
| 'AdminShippingAudit'
|
||||
| 'AdminShippingReviewSupervision'
|
||||
| 'AdminShippingOrderDocumentProfiles';
|
||||
path:
|
||||
| 'shipping-notice'
|
||||
@@ -28,6 +30,8 @@ export interface ShippingConfigSubModuleMeta {
|
||||
| 'shipping-order-schema'
|
||||
| 'shipping-identity-rules'
|
||||
| 'shipping-order-extraction-runs'
|
||||
| 'shipping-audit'
|
||||
| 'shipping-review-supervision'
|
||||
| 'shipping-order-document-profiles';
|
||||
labelKey: string;
|
||||
groupKey: 'admin.nav.shippingOrderRecognition' | 'admin.nav.shippingInventoryManagement' | 'admin.nav.shippingRunAudit';
|
||||
@@ -69,6 +73,8 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [
|
||||
{ id: 'warehouse_mappings', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.externalMappings', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'mappings' } },
|
||||
{ id: 'routing_rules', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.rules', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'rules' } },
|
||||
{ id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } },
|
||||
{ id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' },
|
||||
{ id: 'shipping_review_supervision', routeName: 'AdminShippingReviewSupervision', path: 'shipping-review-supervision', labelKey: 'admin.nav.shippingReviewSupervision', groupKey: 'admin.nav.shippingRunAudit' },
|
||||
{ id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } },
|
||||
{ id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } },
|
||||
];
|
||||
|
||||
Loaded 100 of 158 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user