chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑
This commit is contained in:
1 parent
5ef8329bd8
commit
4ec4e57005
183 files changed
+14653
-3936
No files matched your search
@@ -27,6 +27,7 @@ from app.services.shipping_notice import order_document_profile_lease_service as
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from app.services.shipping_notice import order_document_profile_xfa_preview_service as xfa_preview_service
|
||||
from app.services.shipping_notice import order_document_profile_xfa_automark_service as xfa_automark_service
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as pdf_automark_service
|
||||
from app.services.shipping_notice import order_document_profile_revision_service as revision_service
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
@@ -533,6 +534,56 @@ def get_order_document_profile_preview_page(profile_id: int, page_no: int):
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/xfa-pdf-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_xfa_pdf_preview(profile_id: int):
|
||||
"""兼容旧 XFA 路由:签发统一编辑画布的单用途原 PDF 令牌。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(service.authorize_pdf_preview(
|
||||
profile_id, document_id=data.get('document_id'), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/xfa-pdf-preview', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_xfa_pdf_preview(profile_id: int):
|
||||
"""兼容旧 XFA 路由:消费短时令牌返回原 PDF,仅供 PDF.js 内存渲染。"""
|
||||
pdf = service.read_pdf_preview(
|
||||
token=str(request.args.get('preview_token') or ''), actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(pdf), mimetype='application/pdf', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['Content-Disposition'] = 'inline'
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/pdf-preview', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_pdf_preview(profile_id: int):
|
||||
"""签发坐标 PDF 与 XFA 共用的单用途原 PDF 画布令牌。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(service.authorize_pdf_preview(
|
||||
profile_id, document_id=data.get('document_id'), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/pdf-preview', methods=['GET'])
|
||||
@require_admin
|
||||
def get_order_document_profile_pdf_preview(profile_id: int):
|
||||
"""消费统一画布令牌返回原 PDF 字节,禁止缓存、下载和重放。"""
|
||||
pdf = service.read_pdf_preview(
|
||||
token=str(request.args.get('preview_token') or ''), actor_id=_actor_id(),
|
||||
)
|
||||
response = send_file(io.BytesIO(pdf), mimetype='application/pdf', as_attachment=False, max_age=0)
|
||||
response.headers['Cache-Control'] = 'private, no-store, max-age=0'
|
||||
response.headers['Pragma'] = 'no-cache'
|
||||
response.headers['X-Content-Type-Options'] = 'nosniff'
|
||||
response.headers['Content-Disposition'] = 'inline'
|
||||
return response
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/samples/<int:sample_binding_id>/preview-pages', methods=['POST'])
|
||||
@require_admin
|
||||
def authorize_order_document_profile_frozen_sample_preview_pages(profile_id: int, sample_binding_id: int):
|
||||
@@ -1048,6 +1099,38 @@ def reject_order_document_profile_xfa_visual_binding(profile_id: int, binding_id
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/pdf-automark',
|
||||
methods=['POST'],
|
||||
)
|
||||
@require_admin
|
||||
def enqueue_order_document_profile_pdf_automark(profile_id: int):
|
||||
"""入队统一 PDF 自动标记;客户端不得按 XFA/普通 PDF 选择接口。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
document_id = data.get('document_id')
|
||||
if document_id in (None, ''):
|
||||
raise ValidationError('document_id is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
return _private_ok(pdf_automark_service.enqueue_pdf_automark(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
table_id=str(data.get('table_id') or '').strip() or None,
|
||||
schema_version_id=int(data['schema_version_id']) if data.get('schema_version_id') not in (None, '') else None,
|
||||
page_no=int(data['page_no']) if data.get('page_no') not in (None, '') else None,
|
||||
actor_id=_actor_id(),
|
||||
force=bool(data.get('force')),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/pdf-automark/jobs/<int:job_id>',
|
||||
methods=['GET'],
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_pdf_automark_job(profile_id: int, job_id: int):
|
||||
"""轮询统一 PDF 自动标记 Job 的 candidates/diagnostics 契约。"""
|
||||
return _private_ok(pdf_automark_service.get_pdf_automark_job(job_id, profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route(
|
||||
'/shipping-notice/order-document-profiles/<int:profile_id>/xfa/automark',
|
||||
methods=['POST'],
|
||||
|
||||
@@ -704,7 +704,7 @@ def workspace_shipping_task_detail(task_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
return _ok({
|
||||
**serialize_task_detail(task, viewer_user_id=user.id, is_admin=is_admin),
|
||||
'ui_state': build_task_ui_state(task),
|
||||
'ui_state': build_task_ui_state(task, include_stage_context=True),
|
||||
})
|
||||
|
||||
|
||||
@@ -752,7 +752,7 @@ def workspace_shipping_task_ui_state(task_no: str):
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_task_ui_state(task))
|
||||
return _ok(build_task_ui_state(task, include_stage_context=True))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
@@ -1239,6 +1239,32 @@ def workspace_shipping_task_export(task_no: str):
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/inventory-file', methods=['GET'])
|
||||
def workspace_shipping_task_inventory_file(task_no: str):
|
||||
"""下载当前任务实际关联的库存快照;无 active link 或托管文件时 fail-closed。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
|
||||
resolved = resolve_task_inventory_download(task)
|
||||
if resolved is None:
|
||||
raise NotFoundError('Inventory file not found', code='SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND')
|
||||
path, download_name = resolved
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_task_inventory_file',
|
||||
aggregate_type='shipping_task',
|
||||
aggregate_id=str(task.task_no),
|
||||
actor_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
reason_code='inventory_file_downloaded',
|
||||
metadata={'inventory_file': download_name},
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||
def workspace_list_shipping_order_intakes():
|
||||
"""列出当前会话下未消费的活跃接入记录。"""
|
||||
@@ -1545,6 +1571,29 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
"""读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。"""
|
||||
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_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
|
||||
runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin)
|
||||
payload = serialize_review_queue(runs)
|
||||
record_access_audit(
|
||||
action='view_order_review_queue',
|
||||
aggregate_type='conversation',
|
||||
aggregate_id=str(payload.get('conversation_id') or ''),
|
||||
actor_id=user.id,
|
||||
conversation_id=str(payload.get('conversation_id') or '') or None,
|
||||
run_no=str(run_no),
|
||||
metadata={'item_count': len(payload.get('items') or [])},
|
||||
)
|
||||
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 越权访问;访问留痕。"""
|
||||
@@ -2838,6 +2887,39 @@ def workspace_preview_shipping_order_review_document(case_no: str):
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/intake-parse-context', methods=['GET'],
|
||||
)
|
||||
def workspace_get_shipping_order_review_intake_parse_context(case_no: str):
|
||||
"""
|
||||
返回当前 Case 所属 Intake 的受控解析上下文,并记录敏感读取访问审计。
|
||||
|
||||
核心逻辑:只委托 Case 边界服务构造附件/同 Intake 邮件正文 DTO;PDF 二进制仍必须通过
|
||||
document-preview 代理读取,禁止把对象存储地址或资产内部定位下发至浏览器。
|
||||
"""
|
||||
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_intake_parse_context
|
||||
|
||||
payload = get_case_intake_parse_context(user_id=user.id, case_no=case_no)
|
||||
attachment = payload['attachment']
|
||||
record_access_audit(
|
||||
action='view_order_review_intake_parse_context',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case_no),
|
||||
actor_id=user.id,
|
||||
document_id=attachment['document_id'],
|
||||
review_case_no=str(case_no),
|
||||
metadata={
|
||||
'access_action': 'view_order_review_intake_parse_context',
|
||||
'workbench_event': 'intake_parse_context_viewed',
|
||||
'attachment_preview_kind': attachment['preview_kind'],
|
||||
'has_email_context': payload['email'] is not None,
|
||||
},
|
||||
)
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/email-evidence-preview/<int:document_id>', methods=['GET'])
|
||||
def workspace_preview_shipping_order_review_email_evidence(case_no: str, document_id: int):
|
||||
"""返回当前复核 Case 同 Intake 邮件正文的受控文本预览,不返回原始 EML 或附件。"""
|
||||
|
||||
@@ -59,8 +59,15 @@ class NotFoundError(AppError):
|
||||
message: str = "Resource not found",
|
||||
*,
|
||||
code: str = "RESOURCE.NOT_FOUND",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(code=code, message=message, http_status=404, retryable=False)
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=404,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
|
||||
@@ -12,6 +12,7 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
procurement_contract_review,
|
||||
schedule_run,
|
||||
shipping_document_layout,
|
||||
shipping_inventory_callback_process,
|
||||
shipping_notice_parse,
|
||||
shipping_notice_run,
|
||||
shipping_order_extraction,
|
||||
@@ -21,6 +22,7 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_line_auto_fulfill,
|
||||
shipping_post_ot_wave_progress,
|
||||
shipping_review_revalidate_progress,
|
||||
shipping_pdf_automark,
|
||||
shipping_xfa_ocr_automark,
|
||||
wecom_directory_sync,
|
||||
)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_inventory_callback_process.py
|
||||
|
||||
用途:异步处理已收件的库存 RPA batch 回调,避免 Worker HTTP 回调被 Excel 处理阻塞。
|
||||
依赖:Job 队列、inventory_rpa_workflow 的正式批量处理函数。
|
||||
逻辑:HTTP 回调只写本 Job;shipping worker 领取后执行结构校验、库存解析、任务关联与后续推进。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS)
|
||||
def run_shipping_inventory_callback_process(ctx: JobContext, payload: dict) -> None:
|
||||
"""处理一个已收件的库存 RPA 回调。
|
||||
|
||||
【AI 触发时机】:仅由 ``rpa_report_inventory_batch`` 在 HTTP 收件成功后入队;
|
||||
不得由浏览器 Worker 直接调用。
|
||||
"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id') if isinstance(payload, dict) else None
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
raise RuntimeError('missing_inventory_callback_process_job_id')
|
||||
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
|
||||
|
||||
result = process_rpa_report_inventory_batch(dict(job.payload_json or {}))
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'status': 'processed', 'callback_result': result},
|
||||
message='库存 RPA 回调已异步处理',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001 - queue must retain retryable receipt evidence
|
||||
db.session.rollback()
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc),
|
||||
result={'status': 'processing_failed', 'error': str(exc)[:1000]},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
app/jobs/handlers/shipping_pdf_automark.py
|
||||
|
||||
用途:执行统一 PDF 自动标记 Job,不向调用方暴露 XFA/普通 PDF 分流。
|
||||
依赖:Job 队列、order_document_profile_pdf_automark_service。
|
||||
逻辑:冻结 Job 载荷后委托统一证据管线;成功或受控失败均按通用 Job 契约终态化。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.extensions import db
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_PDF_AUTOMARK)
|
||||
def run_shipping_pdf_automark(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行统一 PDF 自动标记;任何 PDF 类型均复用同一 Job 生命周期。"""
|
||||
_ = ctx
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
frozen = dict(job.payload_json or {})
|
||||
frozen.setdefault('job_id', int(job.id))
|
||||
from app.services.shipping_notice import order_document_profile_pdf_automark_service as automark_service
|
||||
try:
|
||||
result = automark_service.execute_pdf_automark_job(frozen)
|
||||
except automark_service.PdfAutomarkError as exc:
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc.message or exc)[:500],
|
||||
result={'status': 'failed', 'error_code': exc.error_code, 'details': dict(exc.details or {})},
|
||||
retryable=bool(exc.retryable),
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc)[:500],
|
||||
result={'status': 'failed', 'error_code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_FAILED'},
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
finish_job(job.id, result=result, message='PDF automark completed', owned_attempt=owned_attempt)
|
||||
@@ -25,6 +25,7 @@ from app.services.shipping_notice.process_gate_job_service import (
|
||||
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
|
||||
claim_and_run_gate_attempt,
|
||||
enqueue_gate_attempt_job,
|
||||
schedule_waiting_external_poll,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_service import complete_gate_attempt
|
||||
|
||||
@@ -127,4 +128,11 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
|
||||
fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)
|
||||
# [STEP] 外部等待不是终态:Attempt 已正常执行完且 Gate 明确等待外部系统时,
|
||||
# 必须在当前 Job 成功收口后创建新的延迟 poll Attempt。此前只结束 Job,造成
|
||||
# Gate 永久停在 waiting_external,批次中心持续显示“处理中”。
|
||||
result_payload = result if isinstance(result, dict) else {'status': 'ok'}
|
||||
finish_job(job.id, result=result_payload, owned_attempt=owned_attempt)
|
||||
if str(result_payload.get('gate_status') or '').strip().lower() == 'waiting_external':
|
||||
schedule_waiting_external_poll(attempt_id=attempt_id)
|
||||
db.session.commit()
|
||||
@@ -20,9 +20,13 @@ class JobType(StrEnum):
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout'
|
||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
||||
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
|
||||
# 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。
|
||||
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
|
||||
# XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移)
|
||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||
# 旧 XFA 专用 Job 仅兼容已入队任务;新入口一律使用 SHIPPING_PDF_AUTOMARK。
|
||||
SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark'
|
||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||
SHIPPING_STP_AUTO_CREATE = 'shipping_stp_auto_create'
|
||||
@@ -68,7 +72,8 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_xfa_ocr_automark',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark', 'shipping_xfa_ocr_automark',
|
||||
'shipping_inventory_callback_process',
|
||||
'shipping_auto_progress',
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||
|
||||
@@ -386,6 +386,7 @@ def submit_auto_progress(
|
||||
# ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_contract import is_technical_gate_party
|
||||
from app.services.shipping_notice.process_gate_executor import is_navigation_action
|
||||
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
|
||||
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
|
||||
|
||||
@@ -428,7 +429,15 @@ def submit_auto_progress(
|
||||
action_code = str(getattr(gate, 'next_action_code', '') or '').strip()
|
||||
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
|
||||
# system/worker Gate 才可自动创建 Attempt 并入队。
|
||||
if gate is not None and action_code and is_technical_gate_party(execution.responsible_party):
|
||||
# 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。
|
||||
# upload_inventory_file 等导航动作必须保留给用户;否则成功回调已同步
|
||||
# 的库存事实会被旧人工阻断动作再次覆盖。
|
||||
if (
|
||||
gate is not None
|
||||
and action_code
|
||||
and not is_navigation_action(action_code)
|
||||
and is_technical_gate_party(execution.responsible_party)
|
||||
):
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=str(gate.gate_code),
|
||||
|
||||
@@ -23,6 +23,22 @@ from app.services.shipping_notice.intake_service import can_force_create_shippin
|
||||
|
||||
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
||||
_STP_DUPLICATE_OK = frozenset({'none', 'unchecked'})
|
||||
_LIFECYCLE_ELIGIBLE_STATUSES = frozenset({'provisional', 'accepted'})
|
||||
|
||||
|
||||
def is_current_reviewable_candidate(candidate: ShippingOrderCandidate | None) -> bool:
|
||||
"""判断 Candidate 是否可作为订单生命周期的当前准入事实。
|
||||
|
||||
触发时机:Case、批次投影和 Gate 收口需要决定是否可以从接收解析进入订单复核时。
|
||||
仅当前版本且仍可复核/已接受的 Candidate 可以开放生命周期;已拒绝、过期、被替代
|
||||
或空 Candidate 只能保留审计,不能影响实时阶段或前端入口。
|
||||
"""
|
||||
return bool(
|
||||
candidate is not None
|
||||
and bool(getattr(candidate, 'is_current_version', False))
|
||||
and str(getattr(candidate, 'candidate_status', '') or '').strip().lower()
|
||||
in _LIFECYCLE_ELIGIBLE_STATUSES
|
||||
)
|
||||
|
||||
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingOrderCandidate) -> tuple[bool, list[str]]:
|
||||
|
||||
@@ -18,7 +18,12 @@ from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.query_service import get_batch_for_user, get_task_for_user, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_for_user,
|
||||
get_task_for_user,
|
||||
list_sorted_batch_tasks,
|
||||
resolve_task_export_download,
|
||||
)
|
||||
|
||||
MAX_ARCHIVE_TASKS = 100
|
||||
|
||||
@@ -54,14 +59,18 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N
|
||||
|
||||
|
||||
def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExportArtifact]]:
|
||||
"""批量查询每票全部可下载 Artifact,滚动履约不得遗漏前一轮 Excel。"""
|
||||
task_ids = [int(task.id) for task in tasks if task.id is not None]
|
||||
rows = ShippingExportArtifact.query.join(ShippingNotice, ShippingNotice.id == ShippingExportArtifact.task_id).filter(
|
||||
ShippingExportArtifact.task_id.in_(task_ids), ShippingExportArtifact.status == 'ready',
|
||||
).order_by(ShippingExportArtifact.created_at, ShippingExportArtifact.id).all()
|
||||
"""批量解析每票当前正式 Artifact,与单文件下载使用同一授权事实。"""
|
||||
result: dict[int, list[ShippingExportArtifact]] = {}
|
||||
for item in rows:
|
||||
result.setdefault(int(item.task_id), []).append(item)
|
||||
for task in tasks:
|
||||
if task.id is None or resolve_task_export_download(task) is None:
|
||||
continue
|
||||
artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
|
||||
ShippingExportArtifact.file_path == task.export_file_path,
|
||||
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
|
||||
if artifact is not None:
|
||||
result[int(task.id)] = [artifact]
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@@ -142,6 +142,28 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil
|
||||
return link.inventory_file if link else None
|
||||
|
||||
|
||||
def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] | None:
|
||||
"""解析当前任务可下载的活动库存快照,禁止按库存源或订单反查猜测文件。
|
||||
|
||||
Args:
|
||||
task: 已完成用户归属鉴权的正式发货任务。
|
||||
|
||||
Returns:
|
||||
托管文件绝对路径与下载文件名;没有 active link、文件失效或缺失时返回 None。
|
||||
"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file is None:
|
||||
return None
|
||||
storage_path = str(inv_file.storage_path or '').strip()
|
||||
if not storage_path or storage_path.startswith('failed://'):
|
||||
return None
|
||||
path = Path(storage_path).resolve()
|
||||
if not path.is_file():
|
||||
return None
|
||||
filename = str(inv_file.source_file_name or f'{inv_file.inventory_file_no}{path.suffix or ".xlsx"}').strip()
|
||||
return path, filename
|
||||
|
||||
|
||||
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
|
||||
@@ -174,4 +174,23 @@ def sync_preparation_source_from_rpa_attempt(
|
||||
elif rows and all(row.status in {'ready', 'reusable', 'skipped'} for row in rows):
|
||||
preparation.status = 'succeeded'
|
||||
preparation.completed_at = datetime.utcnow()
|
||||
# RPA 回调是跨阶段「从库存准备恢复」的异步终点。Gate Attempt 已在
|
||||
# 发出 Trigger 时正确记录 waiting_external;此处聚合到终态后必须同步收口
|
||||
# 对应 RecoveryPlan,避免已完成的计划继续占用 active-plan 互斥位。
|
||||
if (
|
||||
preparation.status in {'succeeded', 'failed'}
|
||||
and preparation.recovery_plan_id
|
||||
):
|
||||
from app.models import ShippingProcessRecoveryPlan
|
||||
|
||||
plan = db.session.get(ShippingProcessRecoveryPlan, int(preparation.recovery_plan_id))
|
||||
if plan is not None and plan.status in {
|
||||
'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual',
|
||||
}:
|
||||
plan.status = 'succeeded' if preparation.status == 'succeeded' else 'failed'
|
||||
plan.started_at = plan.started_at or datetime.utcnow()
|
||||
plan.completed_at = datetime.utcnow()
|
||||
if preparation.status == 'failed':
|
||||
plan.failure_code = 'inventory_preparation_failed'
|
||||
plan.failure_detail_json = {'message': '库存准备 RPA 回调失败'}
|
||||
db.session.flush()
|
||||
@@ -67,6 +67,7 @@ from app.services.shipping_notice.query_service import (
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.rpa import (
|
||||
inventory_drop_dir,
|
||||
inventory_processed_dir,
|
||||
write_inventory_export_trigger_for_task,
|
||||
)
|
||||
@@ -2080,6 +2081,184 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""快速收件库存 RPA batch 回调,并将业务处理交给 shipping worker。
|
||||
|
||||
【AI 触发时机】:freight_rpa_worker 已完成库存文件导出、需要确认 HXOPS 已接收回调时调用。
|
||||
本函数只验证回调信封并持久化 Job;禁止在 HTTP 请求内解析 Excel、关联任务或推进 Gate。
|
||||
"""
|
||||
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
callback_id = str(payload.get('callback_id') or '').strip()
|
||||
batch_run_no = str(payload.get('batch_run_no') or '').strip()
|
||||
results = payload.get('results') or []
|
||||
if not callback_id or not batch_run_no or not isinstance(results, list):
|
||||
return tool_response(status='failed', message='callback_schema_invalid', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
|
||||
})
|
||||
|
||||
# Worker 的 HTTP 超时可能在平台已收件后才发生。相同 callback 重放必须先复用活动 Job,
|
||||
# 不得再次依赖可能已被 Worker 清理的 shared drop 源文件。
|
||||
from app.models import Job
|
||||
|
||||
existing_job = (
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == 'shipping_inventory_callback_process',
|
||||
Job.business_ref == f'inventory-callback:{callback_id}',
|
||||
Job.status.in_(('queued', 'running')),
|
||||
)
|
||||
.order_by(Job.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing_job is not None:
|
||||
return tool_response(
|
||||
status='ok',
|
||||
message='库存 RPA 回调已收件,正在异步处理库存文件。',
|
||||
data={
|
||||
'job_id': int(existing_job.id),
|
||||
'batch_run_no': batch_run_no,
|
||||
'result_status': 'accepted',
|
||||
'callback_result_status': 'accepted',
|
||||
},
|
||||
extra={'result_status': 'accepted'},
|
||||
)
|
||||
|
||||
receipt_payload = _persist_batch_callback_receipt(
|
||||
payload,
|
||||
callback_id=callback_id,
|
||||
)
|
||||
if receipt_payload is None:
|
||||
return tool_response(status='failed', message='callback_file_receipt_failed', data={
|
||||
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_file_receipt_failed',
|
||||
})
|
||||
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
|
||||
receipt_payload,
|
||||
domain='shipping_notice',
|
||||
business_ref=f'inventory-callback:{callback_id}',
|
||||
message='库存 RPA 回调已收件,等待异步处理',
|
||||
max_attempts=3,
|
||||
commit=True,
|
||||
)
|
||||
return tool_response(
|
||||
status='ok',
|
||||
message='库存 RPA 回调已收件,正在异步处理库存文件。',
|
||||
data={
|
||||
'job_id': int(job_id),
|
||||
'batch_run_no': batch_run_no,
|
||||
'result_status': 'accepted',
|
||||
'callback_result_status': 'accepted',
|
||||
},
|
||||
extra={'result_status': 'accepted'},
|
||||
)
|
||||
|
||||
|
||||
def _persist_batch_callback_receipt(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
callback_id: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""将成功回调的 Excel 快速复制到 HXOPS 受控收件区。
|
||||
|
||||
【AI 触发时机】:仅由 batch HTTP 回调在入队前调用。它只做共享 drop 目录白名单校验
|
||||
和文件复制,绝不读取 Excel 内容、校验结构或更新任务状态;因此 Worker 可在短超时内
|
||||
得到“已收件”的确定响应,后台 Job 不依赖 RPA 随后可能清理的共享目录。
|
||||
|
||||
Returns:
|
||||
用受控副本路径替换成功项 ``file_path`` 后的 payload;无法安全收件时返回 None。
|
||||
"""
|
||||
allowed_root = inventory_drop_dir()
|
||||
if allowed_root is None:
|
||||
return None
|
||||
try:
|
||||
allowed_root = allowed_root.resolve()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
|
||||
safe_callback_id = ''.join(
|
||||
char if char.isalnum() or char in {'-', '_'} else '_'
|
||||
for char in callback_id
|
||||
).strip('_') or 'unknown'
|
||||
receipt_dir = _storage_root() / 'rpa_callback_receipts' / safe_callback_id
|
||||
receipt_payload = dict(payload)
|
||||
receipt_results: list[dict[str, Any]] = []
|
||||
copied_paths: list[Path] = []
|
||||
try:
|
||||
for index, raw_item in enumerate(payload.get('results') or []):
|
||||
item = dict(raw_item) if isinstance(raw_item, dict) else raw_item
|
||||
if not isinstance(item, dict) or str(item.get('status') or '').strip().lower() != 'success':
|
||||
receipt_results.append(item)
|
||||
continue
|
||||
|
||||
raw_path = str(item.get('file_path') or '').strip()
|
||||
source_path = Path(raw_path).resolve() if raw_path else None
|
||||
if source_path is None or not source_path.is_file():
|
||||
return None
|
||||
try:
|
||||
source_path.relative_to(allowed_root)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
suffix = source_path.suffix.lower()
|
||||
if suffix not in {'.xls', '.xlsx', '.csv'}:
|
||||
return None
|
||||
receipt_path = receipt_dir / f'{index:03d}_{source_path.name}'
|
||||
if not receipt_path.is_file():
|
||||
receipt_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source_path, receipt_path)
|
||||
copied_paths.append(receipt_path)
|
||||
item['file_path'] = str(receipt_path)
|
||||
receipt_results.append(item)
|
||||
except (OSError, ValueError):
|
||||
for copied_path in copied_paths:
|
||||
try:
|
||||
copied_path.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
return None
|
||||
|
||||
receipt_payload['results'] = receipt_results
|
||||
return receipt_payload
|
||||
|
||||
|
||||
def _received_batch_callback_file_path(
|
||||
file_path: str,
|
||||
*,
|
||||
callback_id: str,
|
||||
) -> Path | None:
|
||||
"""验证 batch 处理可读取的文件仅来自 RPA drop 或本回调受控收件区。"""
|
||||
candidate = Path(file_path).resolve() if file_path else None
|
||||
if candidate is None or not candidate.is_file():
|
||||
return None
|
||||
allowed_roots: list[Path] = []
|
||||
drop_dir = inventory_drop_dir()
|
||||
if drop_dir is not None:
|
||||
allowed_roots.append(drop_dir.resolve())
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
|
||||
safe_callback_id = ''.join(
|
||||
char if char.isalnum() or char in {'-', '_'} else '_'
|
||||
for char in callback_id
|
||||
).strip('_') or 'unknown'
|
||||
allowed_roots.append((_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve())
|
||||
for allowed_root in allowed_roots:
|
||||
try:
|
||||
candidate.relative_to(allowed_root)
|
||||
return candidate
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
RPA 批量库存导出回调:为每个 Warehouse 创建库存快照,可选关联发货任务。
|
||||
【AI 触发时机】:freight_rpa_worker 完成 inventory_export_batch 后 POST 本接口。
|
||||
@@ -2153,6 +2332,9 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True})
|
||||
continue
|
||||
task: ShippingNotice | None = None
|
||||
# 仅正式三元组 Attempt 走延后确认;历史事件兼容回调及缺字段回调均不能
|
||||
# 读取未初始化变量,后者会在后续身份/来源校验中按业务错误拒绝。
|
||||
structured_attempt = False
|
||||
if task_no:
|
||||
task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no})
|
||||
if task is None:
|
||||
@@ -2170,8 +2352,12 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload=dict(merged_item),
|
||||
callback_payload={**dict(merged_item), '_defer_success_confirmation': True},
|
||||
)
|
||||
# 历史任务可能只有 inventory_rpa_triggered 审计事件,没有结构化
|
||||
# Attempt。此类回调继续走兼容入库链;新链路只对明确定位到 Attempt
|
||||
# 的结果启用“入库完成后再确认”约束。
|
||||
structured_attempt = _a is not None
|
||||
if per_source_code == 'idempotent_ok':
|
||||
skipped.append({
|
||||
"source_code": source_code,
|
||||
@@ -2234,6 +2420,14 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'error': 'RPA callback identity does not match the active preparation attempt.',
|
||||
})
|
||||
continue
|
||||
if per_source_code not in {'validated', 'not_found'}:
|
||||
failed.append({
|
||||
'source_code': source_code,
|
||||
'warehouse_id': warehouse_id,
|
||||
'task_no': task_no,
|
||||
'error_code': f'per_source_callback_{per_source_code}',
|
||||
})
|
||||
continue
|
||||
task = _lock_task_for_rpa_callback(task)
|
||||
|
||||
if task and raw_status in {"skipped", "failed"}:
|
||||
@@ -2278,7 +2472,13 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
ShippingProcessExecution,
|
||||
int(task.active_process_execution_id),
|
||||
)
|
||||
if execution is not None:
|
||||
# CandidateSet 已重冻结时,Task 指针可能尚未被下一轮提交
|
||||
# 覆写;迟到回调只能保留原始审计,不得回写旧 Gate。
|
||||
if (
|
||||
execution is not None
|
||||
and int(getattr(execution, 'task_id', 0) or 0) == int(task.id)
|
||||
and str(getattr(execution, 'status', '') or '').strip().lower() != 'superseded'
|
||||
):
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
@@ -2339,14 +2539,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
})
|
||||
continue
|
||||
file_path = str(merged_item.get("file_path") or "").strip()
|
||||
path = Path(file_path).resolve() if file_path else None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
allowed_root = inventory_drop_dir()
|
||||
if path and allowed_root:
|
||||
try:
|
||||
path.relative_to(allowed_root.resolve())
|
||||
except ValueError:
|
||||
path = None
|
||||
path = _received_batch_callback_file_path(
|
||||
file_path,
|
||||
callback_id=callback_id,
|
||||
)
|
||||
if not path or not path.is_file():
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
@@ -2455,14 +2651,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"difference": structure_check["difference"],
|
||||
},
|
||||
}
|
||||
if task_no and source_run_no_item:
|
||||
from app.models import ShippingTaskInventoryRpaAttempt
|
||||
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
|
||||
if _att:
|
||||
# 成功回调是该 Attempt 的最终事实;清理旧失败态,避免投影继续显示 failed/retry。
|
||||
_att.status = 'succeeded'
|
||||
_att.callback_id = item_callback_id or callback_id; _att.callback_received_at = datetime.utcnow(); _att.file_generated = True; _att.file_path = str(path); _att.file_sha256 = server_hash; _att.file_size = server_size; _att.file_exists_at_callback = True; _att.execution_phase = 'callback_received'; _att.transaction_status = 'succeeded'
|
||||
_att.error_code = None; _att.error_message = None; _att.transaction_error_code = None
|
||||
created.append(created_entry)
|
||||
if item_orphan_path:
|
||||
batch_new_storage_paths.append(item_orphan_path)
|
||||
@@ -2505,8 +2693,35 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
_resolve_effective_callback_run_no(task, merged_item),
|
||||
)
|
||||
# 只有快照创建/复用、结构校验、库存行解析、任务关联都已完成,
|
||||
# 才确认逐源 Attempt 并触发 AutoProgress。该调用在单项保存点内,
|
||||
# 任一后续异常都会一并回滚,防止成功状态先于库存事实落库。
|
||||
if source_run_no_item and structured_attempt:
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
if path.is_file():
|
||||
final_code, _ = per_source_callback_handler(
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload={
|
||||
**dict(merged_item),
|
||||
'inventory_file_no': inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
if final_code != 'succeeded':
|
||||
raise _RpaCallbackItemAbort(
|
||||
f'per_source_callback_confirmation_failed:{final_code}'
|
||||
)
|
||||
|
||||
drop_dir = inventory_drop_dir()
|
||||
is_drop_file = False
|
||||
if drop_dir is not None:
|
||||
try:
|
||||
path.relative_to(drop_dir.resolve())
|
||||
is_drop_file = True
|
||||
except ValueError:
|
||||
pass
|
||||
if is_drop_file and path.is_file():
|
||||
pending_callback_moves.append({
|
||||
"path": path,
|
||||
"run_no": run_no or None,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""
|
||||
services/shipping_notice/lifecycle_projection.py
|
||||
|
||||
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份四阶段业务生命周期。
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。
|
||||
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。
|
||||
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_REASON_OWNING_GATE
|
||||
|
||||
|
||||
LIFECYCLE_STAGES: tuple[dict[str, str], ...] = (
|
||||
{'code': 'intake_parse', 'label': '接收解析'},
|
||||
{'code': 'order_review', 'label': '订单复核'},
|
||||
{'code': 'fulfillment_prep', 'label': '通知准备'},
|
||||
{'code': 'upload_complete', 'label': '通知完成'},
|
||||
)
|
||||
|
||||
LIFECYCLE_STAGE_CODES: tuple[str, ...] = tuple(stage['code'] for stage in LIFECYCLE_STAGES)
|
||||
|
||||
# 正式 Gate 到用户生命周期的唯一映射。任何页面均不得维护第二份 Gate 映射。
|
||||
LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
|
||||
'document_materialization': 'intake_parse',
|
||||
'layout_parsing': 'intake_parse',
|
||||
'document_profile_routing': 'intake_parse',
|
||||
'order_field_extraction': 'intake_parse',
|
||||
'field_completeness': 'order_review',
|
||||
'reservation_validation': 'order_review',
|
||||
'customer_resolution': 'order_review',
|
||||
'duplicate_detection': 'order_review',
|
||||
'field_conflict_resolution': 'order_review',
|
||||
'order_freeze_readiness': 'order_review',
|
||||
'task_creation': 'order_review',
|
||||
'inventory_source_routing': 'fulfillment_prep',
|
||||
'inventory_preparation': 'fulfillment_prep',
|
||||
'inventory_field_mapping': 'fulfillment_prep',
|
||||
'inventory_matching': 'fulfillment_prep',
|
||||
'inventory_sufficiency': 'fulfillment_prep',
|
||||
'excel_readiness': 'fulfillment_prep',
|
||||
'artifact_generation': 'fulfillment_prep',
|
||||
'freight_upload_rpa': 'upload_complete',
|
||||
'manual_upload_handoff': 'upload_complete',
|
||||
}
|
||||
|
||||
# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。
|
||||
LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
|
||||
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
|
||||
('order_review', {
|
||||
'customer_resolving', 'duplicate_checking', 'order_creating', 'review_required',
|
||||
'waiting_review', 'waiting_human_review', 'waiting_human', 'pre_ot_stp', 'order_review',
|
||||
}),
|
||||
('fulfillment_prep', {
|
||||
'inventory_source_resolving', 'inventory_fetching', 'inventory_fetch', 'inventory_preparation',
|
||||
'inventory_candidates_calculated', 'inventory_candidates_frozen', 'inventory_snapshots_ready',
|
||||
'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating',
|
||||
'excel_generate', 'excel_generated',
|
||||
}),
|
||||
('upload_complete', {'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'completed'}),
|
||||
)
|
||||
|
||||
|
||||
def lifecycle_entries(*, lifecycle_stage: str | None, has_candidate_context: bool) -> list[dict[str, str]]:
|
||||
"""返回只读生命周期入口;无有效 Candidate/正式任务时不开放任何订单生命周期面。"""
|
||||
if not has_candidate_context or lifecycle_stage not in LIFECYCLE_STAGE_CODES:
|
||||
return []
|
||||
current_index = LIFECYCLE_STAGE_CODES.index(str(lifecycle_stage))
|
||||
return [
|
||||
{
|
||||
'code': code,
|
||||
'state': 'current' if index == current_index else ('available' if index < current_index else 'unavailable'),
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
}
|
||||
for index, code in enumerate(LIFECYCLE_STAGE_CODES)
|
||||
]
|
||||
|
||||
|
||||
def project_lifecycle(
|
||||
*,
|
||||
current_gate: dict[str, Any] | None,
|
||||
blocking_reason: dict[str, Any] | None,
|
||||
legacy_stage: str | None,
|
||||
has_candidate_context: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
|
||||
|
||||
``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。
|
||||
"""
|
||||
gate = current_gate if isinstance(current_gate, dict) else {}
|
||||
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
|
||||
if gate_code in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
|
||||
authority = 'process_gate'
|
||||
else:
|
||||
reason = blocking_reason if isinstance(blocking_reason, dict) else {}
|
||||
reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip()
|
||||
owning_gate = PROCESS_GATE_REASON_OWNING_GATE.get(reason_code)
|
||||
if owning_gate in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[owning_gate]
|
||||
authority = 'blocking_reason'
|
||||
else:
|
||||
normalized_legacy = str(legacy_stage or '').strip().lower()
|
||||
lifecycle_stage = next(
|
||||
(code for code, aliases in LIFECYCLE_STAGE_RANGES if normalized_legacy in aliases),
|
||||
normalized_legacy if normalized_legacy in LIFECYCLE_STAGE_CODES else None,
|
||||
)
|
||||
authority = 'legacy_fallback' if lifecycle_stage else 'unclassified'
|
||||
return {
|
||||
'lifecycle_stage': lifecycle_stage,
|
||||
'lifecycle_entries': lifecycle_entries(
|
||||
lifecycle_stage=lifecycle_stage,
|
||||
has_candidate_context=has_candidate_context,
|
||||
),
|
||||
'lifecycle_authority': authority,
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
"""
|
||||
services/shipping_notice/order_document_profile_pdf_automark_service.py
|
||||
|
||||
用途:统一 PDF 自动标记任务的入队、执行与查询契约。
|
||||
依赖:Job 队列、坐标重建服务、XFA 多源视觉服务、Profile 模型。
|
||||
逻辑:入口只接受 PDF/profile/sample,上层不传 XFA 类型;执行期读取 Profile 实际
|
||||
template_mode,普通 PDF 复用冻结坐标重建,XFA 复用 PDFium + Widget + OCR +
|
||||
datasets 对照。两者输出同一个 {kind, candidates, diagnostics} Job 结果结构。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingOrderDocumentProfile
|
||||
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
|
||||
|
||||
|
||||
class PdfAutomarkError(Exception):
|
||||
"""统一 PDF 自动标记的受控 Job 失败。"""
|
||||
|
||||
def __init__(self, message: str, *, error_code: str, details: dict[str, Any] | None = None, retryable: bool = False) -> None:
|
||||
super().__init__(message)
|
||||
self.message = message
|
||||
self.error_code = error_code
|
||||
self.details = dict(details or {})
|
||||
self.retryable = retryable
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取模板 Profile;缺失时拒绝创建无归属自动标注任务。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return profile
|
||||
|
||||
|
||||
def _is_xfa_profile(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""由 Profile 已持久化能力识别 datasets,而不是由浏览器传递文档类型。"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
return str(profile.template_mode or definition.get('template_mode') or '') == 'xfa_dataset'
|
||||
|
||||
|
||||
def enqueue_pdf_automark(
|
||||
profile_id: int, *, document_id: int, table_id: str | None, schema_version_id: int | None,
|
||||
page_no: int | None, actor_id: int | None, force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""入队统一 PDF 自动标记;调用方无须也不得传入 XFA 类型开关。"""
|
||||
if actor_id is None:
|
||||
raise ValidationError('Actor is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
profile = _profile(profile_id)
|
||||
if str(profile.status or '') != 'draft':
|
||||
raise ValidationError('Only draft profiles support automark', code='SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE')
|
||||
if not document_id:
|
||||
raise ValidationError('document_id is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if not _is_xfa_profile(profile) and not str(table_id or '').strip():
|
||||
raise ValidationError('table_id is required for coordinate profiles', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
capability = 'xfa_datasets' if _is_xfa_profile(profile) else 'coordinate'
|
||||
payload = {
|
||||
'profile_id': int(profile_id), 'document_id': int(document_id), 'table_id': str(table_id or '').strip() or None,
|
||||
'schema_version_id': int(schema_version_id) if schema_version_id else None,
|
||||
'page_no': int(page_no) if page_no else 1, 'actor_id': int(actor_id), 'capability': capability,
|
||||
}
|
||||
ref = f'pdf-automark:{int(profile_id)}:{int(document_id)}:{payload["table_id"] or "page"}:{payload["page_no"]}'
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_PDF_AUTOMARK, payload, domain=SHIPPING_NOTICE_JOB_DOMAIN, business_ref=ref,
|
||||
created_by_id=int(actor_id), message='Waiting for PDF automark', max_attempts=2,
|
||||
dedupe_active=not force, commit=True,
|
||||
)
|
||||
job = db.session.get(Job, int(job_id))
|
||||
return {'job_id': int(job_id), 'status': str(job.status if job else 'queued'), 'profile_id': int(profile_id), 'document_id': int(document_id)}
|
||||
|
||||
|
||||
def execute_pdf_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""执行统一证据管线;仅在这里按 Profile 的实际能力选择已有适配实现。"""
|
||||
profile_id = int(payload.get('profile_id') or 0)
|
||||
document_id = int(payload.get('document_id') or 0)
|
||||
if profile_id <= 0 or document_id <= 0:
|
||||
raise PdfAutomarkError('profile_id and document_id are required', error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
profile = _profile(profile_id)
|
||||
if _is_xfa_profile(profile):
|
||||
from app.services.shipping_notice import order_document_profile_xfa_automark_service as xfa
|
||||
try:
|
||||
result = xfa.execute_xfa_ocr_automark_job(payload)
|
||||
except xfa.XfaOcrAutomarkError as exc:
|
||||
raise PdfAutomarkError(exc.message, error_code=exc.error_code, details=exc.details, retryable=exc.retryable) from exc
|
||||
return {**result, 'kind': 'visual_binding', 'candidates': list(result.get('suggestions') or []), 'diagnostics': {'evidence': ['pdfium', 'acroform_widget', 'ocr', 'xfa_datasets']}}
|
||||
table_id = str(payload.get('table_id') or '').strip()
|
||||
if not table_id:
|
||||
raise PdfAutomarkError('table_id is required for coordinate profiles', error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
from app.core.errors import ValidationError as AppValidationError
|
||||
from app.services.shipping_notice import order_document_profile_service as coordinate
|
||||
request = {'document_id': document_id, 'table_id': table_id, 'schema_version_id': payload.get('schema_version_id')}
|
||||
try:
|
||||
reconstruction = coordinate.suggest_coordinate_reconstruction(request, actor_id=payload.get('actor_id'))
|
||||
except AppValidationError as exc:
|
||||
if exc.code != 'SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE':
|
||||
raise PdfAutomarkError(str(exc), error_code=exc.code, details=dict(exc.details or {})) from exc
|
||||
try:
|
||||
coordinate.generate_ocr_coordinate_evidence(document_id=document_id, table_id=table_id, actor_id=payload.get('actor_id'))
|
||||
reconstruction = coordinate.suggest_coordinate_reconstruction(request, actor_id=payload.get('actor_id'))
|
||||
except Exception as retry_exc: # noqa: BLE001
|
||||
raise PdfAutomarkError('PDF coordinate evidence is unavailable', error_code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from retry_exc
|
||||
fields = coordinate.suggest_order_field_layouts({
|
||||
'document_id': document_id, 'schema_version_id': payload.get('schema_version_id'), 'page_no': int(payload.get('page_no') or 1),
|
||||
}, actor_id=payload.get('actor_id'))
|
||||
return {
|
||||
'status': 'success', 'profile_id': profile_id, 'document_id': document_id, 'kind': 'coordinate_regions',
|
||||
'candidates': [{'candidate_kind': 'coordinate_reconstruction', 'payload': reconstruction}, {'candidate_kind': 'order_fields', 'payload': fields}],
|
||||
'diagnostics': {'evidence': ['pdfium_native_coordinates', 'ocr_if_needed'], 'table_id': table_id}, 'error_code': None,
|
||||
}
|
||||
|
||||
|
||||
def get_pdf_automark_job(job_id: int, *, profile_id: int) -> dict[str, Any]:
|
||||
"""按统一 DTO 查询 PDF 自动标记任务,拒绝跨 Profile 读取。"""
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None or str(job.job_type or '') != JobType.SHIPPING_PDF_AUTOMARK.value:
|
||||
raise NotFoundError('PDF automark job not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_JOB_NOT_FOUND')
|
||||
payload = dict(job.payload_json or {})
|
||||
if int(payload.get('profile_id') or 0) != int(profile_id):
|
||||
raise NotFoundError('PDF automark job not found for profile', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PDF_AUTOMARK_JOB_NOT_FOUND')
|
||||
result = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {}
|
||||
return {
|
||||
'job_id': int(job.id), 'status': str(job.status or ''), 'kind': result.get('kind'),
|
||||
'candidates': list(result.get('candidates') or []), 'diagnostics': dict(result.get('diagnostics') or {}),
|
||||
'preview_render_checksum': result.get('preview_render_checksum'),
|
||||
'renderer_version': result.get('renderer_version'),
|
||||
'error_code': result.get('error_code'), 'message': job.message,
|
||||
}
|
||||
@@ -64,6 +64,7 @@ from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-preview:'
|
||||
XFA_PDF_PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-xfa-pdf-preview:'
|
||||
|
||||
|
||||
def _definition_hash(definition: dict[str, Any]) -> str:
|
||||
@@ -1409,6 +1410,76 @@ def render_preview_page(*, token: str, page_no: int, actor_id: int | None) -> by
|
||||
return stream.getvalue()
|
||||
|
||||
|
||||
def authorize_pdf_preview(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""签发绑定样本原 PDF 的单次内存预览令牌,不暴露对象存储定位信息。
|
||||
|
||||
编辑画布对坐标 PDF 与 XFA PDF 共用该通道和 PDF.js 渲染;授权范围仍严格限定为
|
||||
管理员、当前 Profile 已绑定的 PDF 样本、短时且单次消费的令牌。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
try:
|
||||
safe_document_id = int(document_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('document_id is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order profile PDF preview not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND')
|
||||
document = _bound_sample_document(profile_id, safe_document_id)
|
||||
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
raise ValidationError('Only PDF samples support PDF preview', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE')
|
||||
asset = db.session.get(FileAsset, document.asset_id)
|
||||
if asset is None:
|
||||
raise ValidationError('Sample file is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE')
|
||||
grant_token = secrets.token_urlsafe(24)
|
||||
_preview_grant_store().setex(
|
||||
f'{XFA_PDF_PREVIEW_GRANT_KEY_PREFIX}{grant_token}', PREVIEW_GRANT_TTL_SECONDS,
|
||||
json.dumps({
|
||||
'profile_id': int(profile_id), 'document_id': document.id, 'actor_id': int(actor_id),
|
||||
'asset_id': int(asset.id), 'content_hash': str(asset.content_hash or ''),
|
||||
}, separators=(',', ':')),
|
||||
)
|
||||
_audit(profile_id=int(profile_id), document_id=document.id, event_type='pdf_preview_authorized', actor_id=actor_id, detail={
|
||||
'ttl_seconds': PREVIEW_GRANT_TTL_SECONDS,
|
||||
})
|
||||
db.session.commit()
|
||||
return {'document_id': document.id, 'preview_token': grant_token, 'expires_in_seconds': PREVIEW_GRANT_TTL_SECONDS}
|
||||
|
||||
|
||||
def read_pdf_preview(*, token: str, actor_id: int | None) -> bytes:
|
||||
"""原子消费原 PDF 预览令牌并读取绑定样本;失败不保留可重放凭据。"""
|
||||
raw_grant = _preview_grant_store().getdel(f'{XFA_PDF_PREVIEW_GRANT_KEY_PREFIX}{str(token)}')
|
||||
try:
|
||||
grant = json.loads(raw_grant) if raw_grant else None
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
grant = None
|
||||
if not isinstance(grant, dict) or actor_id is None or grant.get('actor_id') != int(actor_id):
|
||||
raise NotFoundError('Order profile PDF preview not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND')
|
||||
document = _bound_sample_document(grant['profile_id'], grant['document_id'])
|
||||
asset = db.session.get(FileAsset, document.asset_id)
|
||||
if asset is None or int(asset.id) != int(grant.get('asset_id') or 0) or str(asset.content_hash or '') != str(grant.get('content_hash') or ''):
|
||||
raise NotFoundError('Order profile PDF preview not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND')
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
try:
|
||||
payload = read_asset_bytes(asset)
|
||||
except Exception as exc:
|
||||
raise ValidationError('PDF preview is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE') from exc
|
||||
_audit(profile_id=grant['profile_id'], document_id=document.id, event_type='pdf_preview_viewed', actor_id=actor_id, detail={})
|
||||
db.session.commit()
|
||||
return payload
|
||||
|
||||
|
||||
def authorize_xfa_pdf_preview(profile_id: int, *, document_id: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""兼容旧 XFA 路由;统一画布授权已迁移至 authorize_pdf_preview。"""
|
||||
return authorize_pdf_preview(profile_id, document_id=document_id, actor_id=actor_id)
|
||||
|
||||
|
||||
def read_xfa_pdf_preview(*, token: str, actor_id: int | None) -> bytes:
|
||||
"""兼容旧 XFA 原 PDF 路由;令牌仍按统一单次消费语义读取。"""
|
||||
return read_pdf_preview(token=token, actor_id=actor_id)
|
||||
|
||||
|
||||
def page_text_candidates(profile_id: int, *, document_id: int, page_no: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""???????????????? bbox?token ID?HTML ????????"""
|
||||
if actor_id is None:
|
||||
|
||||
+22
-14
@@ -6,6 +6,7 @@ services/shipping_notice/order_document_profile_xfa_automark_service.py
|
||||
visual_binding_service(确认)、lease_service、audit helpers、Job 模型。
|
||||
逻辑:Admin API 调用 enqueue/get/accept/reject;Worker Handler 调用
|
||||
execute_xfa_ocr_automark_job。编辑图源为原生 PDF 页,不再依赖 /xfa/preview。
|
||||
datasets 是正式值,Widget 与 OCR 是独立采集的视觉证据,成功后统一融合;
|
||||
high 且无 mismatch 才可接受为 confirmed;medium/low 仅写 suggested;
|
||||
mismatch 硬阻断。永不自动 confirmed。空白壳 OCR 无内容 → 空建议成功。
|
||||
"""
|
||||
@@ -398,13 +399,13 @@ def _normalize_suggestion(item: dict[str, Any], *, page_no: int) -> dict[str, An
|
||||
|
||||
def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Worker 执行体:OCR 原生 PDF 页并合并 Widget/OCR 建议。
|
||||
Worker 执行体:采集原生 PDF 页的 Widget/OCR 证据并合并视觉建议。
|
||||
|
||||
核心逻辑:
|
||||
1. 加载 PDFium 原生页 PNG(与编辑画布同源);
|
||||
2. 无页/空白壳 → 空建议成功(不报 XFA_PREVIEW_UNAVAILABLE);
|
||||
3. 逐页 recognize_preview_page;无 OCR 行时不生成 datasets stub 建议;
|
||||
4. merge_visual_binding_suggestions(按 field_key 跨页去重);
|
||||
3. 每页先独立收集 AcroForm Widget,再执行强制 OCR;两者不互为前置条件;
|
||||
4. OCR 成功后 merge_visual_binding_suggestions(按 field_key 跨页去重);
|
||||
5. 回写 Profile.definition.xfa_ocr_automark。
|
||||
|
||||
Args:
|
||||
@@ -414,7 +415,7 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
写入 Job.result_json 的字典。
|
||||
|
||||
Raises:
|
||||
XfaOcrAutomarkError: 受控失败(样本缺失 / OCR 引擎不可用等)。
|
||||
XfaOcrAutomarkError: 受控失败(样本缺失 / 强制 OCR 不可用等)。
|
||||
"""
|
||||
profile_id = int(payload.get('profile_id') or 0)
|
||||
document_id = int(payload.get('document_id') or 0)
|
||||
@@ -503,6 +504,17 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
png = page.get('png_bytes')
|
||||
if not isinstance(png, (bytes, bytearray)) or not png:
|
||||
continue
|
||||
pending_targets = [
|
||||
item for item in flat_targets
|
||||
if str(item.get('field_key') or '') not in suggestions_by_key
|
||||
]
|
||||
# Widget 与 OCR 是独立证据:先采集 Widget,OCR 失败仍留下可审计的诊断,
|
||||
# 但不能把缺少强制 OCR 交叉校验的候选误标为成功。
|
||||
widgets = _widget_candidates_for_page(
|
||||
document_id=document_id,
|
||||
page_no=page_no,
|
||||
targets=pending_targets,
|
||||
)
|
||||
try:
|
||||
ocr_lines = recognize_preview_page(bytes(png))
|
||||
except ServiceUnavailableError as exc:
|
||||
@@ -513,7 +525,12 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
actor_id=int(actor_id) if actor_id is not None else None,
|
||||
result='failure',
|
||||
error_code=str(getattr(exc, 'code', None) or AUTOMARK_OCR_UNAVAILABLE),
|
||||
detail={'page_no': page_no, 'job_id': payload.get('job_id')},
|
||||
detail={
|
||||
'page_no': page_no,
|
||||
'job_id': payload.get('job_id'),
|
||||
'widget_candidate_count': len(widgets),
|
||||
'dataset_target_count': len(pending_targets),
|
||||
},
|
||||
)
|
||||
raise XfaOcrAutomarkError(
|
||||
'XFA native PDF OCR is unavailable',
|
||||
@@ -522,17 +539,8 @@ def execute_xfa_ocr_automark_job(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
retryable=False,
|
||||
) from exc
|
||||
|
||||
pending_targets = [
|
||||
item for item in flat_targets
|
||||
if str(item.get('field_key') or '') not in suggestions_by_key
|
||||
]
|
||||
# 无 OCR 行时不向 matcher 传 datasets 目标,避免空白壳刷出 needs_review stub。
|
||||
ocr_targets = pending_targets if ocr_lines else []
|
||||
widgets = _widget_candidates_for_page(
|
||||
document_id=document_id,
|
||||
page_no=page_no,
|
||||
targets=pending_targets,
|
||||
)
|
||||
if not ocr_lines and not widgets:
|
||||
continue
|
||||
|
||||
|
||||
@@ -596,6 +596,7 @@ def _trim_pending_order_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
'candidate_no': str(item.get('candidate_no') or '').strip() or None,
|
||||
'po_number': str(item.get('po_number') or '').strip() or None,
|
||||
'document_id': int(item.get('document_id') or 0) 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,
|
||||
@@ -611,11 +612,26 @@ def _pending_order_facts(run: ShippingOrderProcessingRun) -> list[dict[str, Any]
|
||||
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 [
|
||||
pending = [
|
||||
_trim_pending_order_item(item)
|
||||
for item in stored
|
||||
if isinstance(item, dict)
|
||||
][:50]
|
||||
# 历史 Worker 快照没有 document_id;实时投影必须补齐同 Run 的 Candidate 归属,
|
||||
# 否则无法保证一个 PDF 不会被多个处理类别重复计数。
|
||||
if getattr(run, 'id', None) is not None:
|
||||
documents_by_candidate = {
|
||||
str(row.candidate_no): int(row.primary_document_id)
|
||||
for row in ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
).all()
|
||||
if row.candidate_no and row.primary_document_id
|
||||
}
|
||||
for item in pending:
|
||||
if item.get('document_id') is None:
|
||||
item['document_id'] = documents_by_candidate.get(str(item.get('candidate_no') or ''))
|
||||
return pending
|
||||
|
||||
if getattr(run, 'id', None) is None:
|
||||
return []
|
||||
@@ -649,6 +665,7 @@ def _pending_order_facts(run: ShippingOrderProcessingRun) -> list[dict[str, Any]
|
||||
pending.append(_trim_pending_order_item({
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'po_number': candidate.po_number,
|
||||
'document_id': candidate.primary_document_id,
|
||||
'reasons': reasons,
|
||||
'missing_fields': missing,
|
||||
'duplicate_status': candidate.duplicate_status,
|
||||
@@ -674,6 +691,19 @@ def _auto_freeze_block_facts(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
})
|
||||
if code:
|
||||
blocked_codes.append(code)
|
||||
if blocked_tasks and getattr(run, 'id', None) is not None:
|
||||
document_by_candidate = {
|
||||
str(candidate.candidate_no): int(candidate.primary_document_id)
|
||||
for candidate in ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
).all()
|
||||
if candidate.candidate_no and candidate.primary_document_id
|
||||
}
|
||||
for item in blocked_tasks:
|
||||
document_id = document_by_candidate.get(str(item.get('candidate_no') or ''))
|
||||
if document_id:
|
||||
item['document_id'] = document_id
|
||||
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'))
|
||||
@@ -781,23 +811,77 @@ def build_handling_items(
|
||||
)
|
||||
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]] = []
|
||||
# 处理事项的统计实体是业务文件,不是来源行。预算快照、Candidate、Unit 分别
|
||||
# 可能只带 content_hash、document_id 或 root_document_id;只按 document_id
|
||||
# 认领会让同一 PDF 落入多个类别并被相加。
|
||||
claimed_file_keys: set[str] = set()
|
||||
aliases_by_document_id: dict[int, set[str]] = {}
|
||||
for unit in unit_rows:
|
||||
document_id = int(getattr(unit, 'document_id', None) or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
aliases = aliases_by_document_id.setdefault(document_id, {f'document:{document_id}'})
|
||||
content_hash = str(getattr(unit, 'content_hash', None) or '').strip().lower()
|
||||
if content_hash:
|
||||
aliases.add(f'content-hash:{content_hash}')
|
||||
|
||||
def claim(refs: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""按 content_hash → root_document_id → document_id 互斥认领业务文件。"""
|
||||
kept: list[dict[str, Any]] = []
|
||||
for ref in refs:
|
||||
document_id = int(ref.get('document_id') or 0)
|
||||
keys: set[str] = set()
|
||||
# _identity_content_hash 仅用于本次互斥认领,不能改变既有 affected_refs 契约。
|
||||
content_hash = str(
|
||||
ref.get('_identity_content_hash') or ref.get('content_hash') or '',
|
||||
).strip().lower()
|
||||
root_document_id = int(ref.get('root_document_id') or 0)
|
||||
if content_hash:
|
||||
keys.add(f'content-hash:{content_hash}')
|
||||
if root_document_id > 0:
|
||||
keys.add(f'root-document:{root_document_id}')
|
||||
if document_id > 0:
|
||||
keys.update(aliases_by_document_id.get(document_id, set()))
|
||||
keys.add(f'document:{document_id}')
|
||||
# 无稳定文件身份的历史行不得相互误合并,仍保留其自身可审计定位。
|
||||
if not keys:
|
||||
candidate_no = str(ref.get('candidate_no') or '').strip()
|
||||
task_no = str(ref.get('task_no') or '').strip()
|
||||
keys.add(f'legacy:{candidate_no or task_no or id(ref)}')
|
||||
if keys & claimed_file_keys:
|
||||
continue
|
||||
claimed_file_keys.update(keys)
|
||||
# 身份别名是投影内部实现细节,不能泄漏到 affected_refs API。
|
||||
kept.append({
|
||||
key: value
|
||||
for key, value in ref.items()
|
||||
if not str(key).startswith('_identity_')
|
||||
})
|
||||
return kept
|
||||
|
||||
# [STEP 1] PDF 技术失败与人工复核(排除已 open_existing)。
|
||||
failed_units = [unit for unit in unit_rows if str(unit.status or '') == 'failed']
|
||||
if failed_units:
|
||||
# 先对全量事实认领,再由 _handling_item 截断 affected_refs 的展示长度。
|
||||
# 若在认领前截断,排在第 11 份之后的同一 PDF 可能再次落入低优先级类别,
|
||||
# 既破坏互斥统计,也会把真实数量错误压成 10。
|
||||
failed_refs = claim([
|
||||
{
|
||||
'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id),
|
||||
'_identity_content_hash': str(getattr(unit, 'content_hash', None) or '').strip().lower() or None,
|
||||
}
|
||||
for unit in failed_units
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
])
|
||||
if failed_refs:
|
||||
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),
|
||||
count=len(failed_refs),
|
||||
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
|
||||
],
|
||||
affected_refs=failed_refs,
|
||||
primary_action='retry_failed_attachments',
|
||||
))
|
||||
|
||||
@@ -805,24 +889,34 @@ def build_handling_items(
|
||||
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:
|
||||
review_refs = claim([
|
||||
{
|
||||
'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id),
|
||||
'_identity_content_hash': str(getattr(unit, 'content_hash', None) or '').strip().lower() or None,
|
||||
}
|
||||
for unit in review_units
|
||||
if getattr(unit, 'document_id', None) is not None
|
||||
])
|
||||
if not review_refs:
|
||||
review_refs = claim([
|
||||
{'type': 'document', 'document_id': int(case.document_id), 'case_no': case.case_no}
|
||||
for case in getattr(run, 'review_cases', []) or []
|
||||
if (
|
||||
str(case.status or '') not in {'confirmed', 'non_order', 'superseded'}
|
||||
and int(case.document_id or 0) not in open_ids
|
||||
and int(case.document_id or 0) > 0
|
||||
)
|
||||
])
|
||||
if review_refs:
|
||||
codes = _trim_reason_codes([
|
||||
getattr(unit, 'reason_code', None)
|
||||
for unit in review_units
|
||||
])
|
||||
items.append(_handling_item(
|
||||
category='document_review',
|
||||
count=review_count,
|
||||
count=len(review_refs),
|
||||
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
|
||||
],
|
||||
affected_refs=review_refs,
|
||||
primary_action='enter_manual_review',
|
||||
))
|
||||
|
||||
@@ -832,6 +926,9 @@ def build_handling_items(
|
||||
missing_orders: list[dict[str, Any]] = []
|
||||
confirmation_only: list[dict[str, Any]] = []
|
||||
for item in pending_orders:
|
||||
document_id = int(item.get('document_id') or 0)
|
||||
if document_id > 0 and aliases_by_document_id.get(document_id, {f'document:{document_id}'}) & claimed_file_keys:
|
||||
continue
|
||||
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)
|
||||
@@ -844,103 +941,121 @@ def build_handling_items(
|
||||
confirmation_only.append(item)
|
||||
|
||||
if conflict_orders:
|
||||
conflict_refs = claim([
|
||||
{'type': 'candidate', 'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'), 'document_id': item.get('document_id')}
|
||||
for item in conflict_orders if item.get('candidate_no')
|
||||
])
|
||||
else:
|
||||
conflict_refs = []
|
||||
if conflict_refs:
|
||||
items.append(_handling_item(
|
||||
category='candidate_conflict',
|
||||
count=len(conflict_orders),
|
||||
count=len(conflict_refs),
|
||||
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')
|
||||
],
|
||||
affected_refs=conflict_refs,
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
if missing_orders:
|
||||
missing_refs = claim([
|
||||
{'type': 'candidate', 'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'), 'document_id': item.get('document_id'),
|
||||
'missing_fields': item.get('missing_fields') or []}
|
||||
for item in missing_orders if item.get('candidate_no')
|
||||
])
|
||||
else:
|
||||
missing_refs = []
|
||||
if missing_refs:
|
||||
items.append(_handling_item(
|
||||
category='candidate_missing_info',
|
||||
count=len(missing_orders),
|
||||
count=len(missing_refs),
|
||||
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')
|
||||
],
|
||||
affected_refs=missing_refs,
|
||||
primary_action='review_candidate',
|
||||
))
|
||||
|
||||
# [STEP 3] 自动冻结受阻与预算停扩。
|
||||
freeze = _auto_freeze_block_facts(run)
|
||||
if freeze['blocked']:
|
||||
freeze_refs = claim([
|
||||
{'type': 'task', 'task_no': item.get('task_no'),
|
||||
'candidate_no': item.get('candidate_no'), 'document_id': item.get('document_id')}
|
||||
for item in freeze['blocked_tasks']
|
||||
if item.get('task_no') or item.get('candidate_no')
|
||||
])
|
||||
else:
|
||||
freeze_refs = []
|
||||
if freeze_refs:
|
||||
items.append(_handling_item(
|
||||
category='auto_freeze_blocked',
|
||||
count=max(int(freeze['blocked_task_count'] or 0), 1),
|
||||
count=len(freeze_refs),
|
||||
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')
|
||||
],
|
||||
affected_refs=freeze_refs,
|
||||
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:
|
||||
budget_refs = claim(budget_refs)
|
||||
if budget_refs:
|
||||
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',
|
||||
category='budget_stopped',
|
||||
count=len(budget_refs),
|
||||
reason_codes=['budget_initial_limit'],
|
||||
affected_refs=budget_refs,
|
||||
primary_action='view_details',
|
||||
))
|
||||
|
||||
# [STEP 4] 仅候选确认。每份 PDF 只保留一个最高优先级事项,但不能因为
|
||||
# 另一份 PDF 有冲突/缺字段,就把本文件的「待确认」整体吞掉。
|
||||
# 待确认候选同样必须先按文件认领:同一 PDF 可能产出多个候选行,
|
||||
# 但批次中心的「处理事项」统计口径是待处理文件而不是候选记录数。
|
||||
# 没有 document_id 的历史候选保留 candidate_no 作为兼容定位键,不能
|
||||
# 与任何已知文件行混合相加。
|
||||
confirmation_refs = claim([
|
||||
{
|
||||
'type': 'candidate',
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'po_number': item.get('po_number'),
|
||||
'document_id': item.get('document_id'),
|
||||
}
|
||||
for item in confirmation_only
|
||||
if item.get('candidate_no')
|
||||
])
|
||||
if not confirmation_refs:
|
||||
candidate_ready_refs = claim([
|
||||
{
|
||||
'type': 'document', 'document_id': int(unit.document_id), 'unit_id': int(unit.id),
|
||||
'_identity_content_hash': str(getattr(unit, 'content_hash', None) or '').strip().lower() or None,
|
||||
}
|
||||
for unit in unit_rows
|
||||
if (
|
||||
str(unit.status or '') == 'candidate_ready'
|
||||
and int(unit.document_id or 0) not in open_ids
|
||||
and not (
|
||||
aliases_by_document_id.get(
|
||||
int(unit.document_id or 0),
|
||||
{f'document:{int(unit.document_id or 0)}'},
|
||||
) & claimed_file_keys
|
||||
)
|
||||
)
|
||||
])
|
||||
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_refs and run.status in {'review_required', 'partially_completed'} and (
|
||||
pending_count > 0 or not items
|
||||
):
|
||||
confirmation_refs = candidate_ready_refs
|
||||
if confirmation_refs:
|
||||
items.append(_handling_item(
|
||||
category='candidate_confirmation',
|
||||
count=len(confirmation_refs),
|
||||
reason_codes=['auto_create_disabled'] if confirmation_only else [],
|
||||
affected_refs=confirmation_refs,
|
||||
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
|
||||
|
||||
@@ -241,15 +241,23 @@ def reconcile_single_case_for_auto_progress(
|
||||
# [STEP 3] Draft validate(refresh_validation=True 且有 current_draft)
|
||||
if refresh_validation and loaded_case.current_draft is not None:
|
||||
try:
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
validate_out = validate_draft(
|
||||
user_id=int(loaded_case.owner_user_id),
|
||||
case_no=str(loaded_case.case_no),
|
||||
expected_draft_version=int(loaded_case.current_draft.draft_version),
|
||||
)
|
||||
result['validate_status'] = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
draft_has_manual_values,
|
||||
validate_draft,
|
||||
)
|
||||
if draft_has_manual_values(loaded_case.current_draft):
|
||||
# 自动协调不消费人工编辑;显式保存 API 会先执行 validate_draft,
|
||||
# 再以 skip_validate=True 进入后续推进。
|
||||
result['validate_status'] = 'waiting_manual_validation'
|
||||
else:
|
||||
validate_out = validate_draft(
|
||||
user_id=int(loaded_case.owner_user_id),
|
||||
case_no=str(loaded_case.case_no),
|
||||
expected_draft_version=int(loaded_case.current_draft.draft_version),
|
||||
)
|
||||
result['validate_status'] = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
'validate_draft failed case_no=%s err=%s',
|
||||
@@ -347,15 +355,24 @@ def reconcile_run_review_cases_for_auto_progress(
|
||||
validate_status = 'skipped'
|
||||
if case.current_draft is not None:
|
||||
try:
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
validate_out = validate_draft(
|
||||
user_id=int(case.owner_user_id),
|
||||
case_no=str(case.case_no),
|
||||
expected_draft_version=int(case.current_draft.draft_version),
|
||||
)
|
||||
validate_status = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
draft_has_manual_values,
|
||||
validate_draft,
|
||||
)
|
||||
if draft_has_manual_values(case.current_draft):
|
||||
# 与单 Case 协调器及 Recovery Sweeper 保持同一语义:
|
||||
# 后台批量协调不得代替用户确认人工修改,否则每次扫描都会
|
||||
# 写入新的 validation 快照并使前端 CAS 版本持续过期。
|
||||
validate_status = 'waiting_manual_validation'
|
||||
else:
|
||||
validate_out = validate_draft(
|
||||
user_id=int(case.owner_user_id),
|
||||
case_no=str(case.case_no),
|
||||
expected_draft_version=int(case.current_draft.draft_version),
|
||||
)
|
||||
validate_status = (
|
||||
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_LOGGER.warning(
|
||||
'validate_draft failed case_no=%s err=%s',
|
||||
|
||||
@@ -13,7 +13,7 @@ services/shipping_notice/order_review_draft_service.py
|
||||
履约波次确认经 build_confirmable_draft_summary(line_keys) 仅对选中行重算 validation;
|
||||
库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定;
|
||||
路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放;
|
||||
显式校验后同步客户/Reservation/重复订单/库存路由 Gate(findings.details)。
|
||||
显式校验后同步字段完整性、字段冲突、客户/Reservation/重复订单/库存路由 Gate(findings.details)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -60,6 +60,52 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
||||
_EDITABLE_STATUSES = frozenset({'unreviewed', 'draft', 'ready'})
|
||||
|
||||
|
||||
def draft_has_manual_values(draft: ShippingOrderReviewDraft | Any | None) -> bool:
|
||||
"""
|
||||
判断草稿是否含需由用户显式提交的人工值。
|
||||
|
||||
核心逻辑:仅 ``source=manual`` 和 ``source=manual_override`` 表示用户改写了
|
||||
机器草稿;后台恢复不得替用户重复校验或推进。该判断同时供 STP 与 Recovery 使用,
|
||||
防止两条链路对“人工编辑”给出相反结论。
|
||||
"""
|
||||
if draft is None:
|
||||
return False
|
||||
|
||||
containers: list[dict[str, Any]] = []
|
||||
header = getattr(draft, 'header_values_json', None)
|
||||
if isinstance(header, dict):
|
||||
containers.append(header)
|
||||
for line in (getattr(draft, 'lines_json', None) or []):
|
||||
if isinstance(line, dict):
|
||||
containers.append(line)
|
||||
|
||||
for container in containers:
|
||||
values = container.get('values') if isinstance(container.get('values'), dict) else {}
|
||||
for item in values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') in {'manual', 'manual_override'}:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def draft_requires_manual_validation(draft: ShippingOrderReviewDraft | Any | None) -> bool:
|
||||
"""
|
||||
判断人工值是否尚未被用户显式“保存订单并校验”确认。
|
||||
|
||||
核心逻辑:人工值存在本身不等于永久禁止建单;只要当前 Draft 版本已由显式
|
||||
校验生成 validation_version,即可由该次用户提交后的同步推进消费。后台恢复
|
||||
仍使用 ``draft_has_manual_values``,不会代替用户触发这个提交。
|
||||
"""
|
||||
if not draft_has_manual_values(draft):
|
||||
return False
|
||||
validation = getattr(draft, 'validation_result_json', None)
|
||||
if not isinstance(validation, dict):
|
||||
return True
|
||||
try:
|
||||
return int(validation.get('validation_version')) != int(getattr(draft, 'draft_version'))
|
||||
except (TypeError, ValueError):
|
||||
return True
|
||||
|
||||
|
||||
def soft_load_review_case_for_audit(*, user_id: int, case_no: str) -> ShippingOrderReviewCase | None:
|
||||
"""
|
||||
无行锁加载属主 Case(及 Draft),供路由层/早期门禁写拒绝审计。
|
||||
@@ -1376,10 +1422,46 @@ def _blocking_issues_for_gate(
|
||||
item for item in (validation.get('issues') or [])
|
||||
if isinstance(item, dict)
|
||||
and str(item.get('owning_gate_code') or '') == gate_code
|
||||
and str(item.get('severity') or '') == 'blocking'
|
||||
# auto_create_blocking 同样是当前复核必须解释的业务阻断:
|
||||
# 可人工建单不代表可自动建单,不能让它从 Gate 投影中消失。
|
||||
and str(item.get('severity') or '') in {'blocking', 'auto_create_blocking'}
|
||||
]
|
||||
|
||||
|
||||
def _candidate_conflict_locator(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
从 Candidate 原始冲突补齐字段定位,避免资格层的聚合 issue 丢失 field_code。
|
||||
|
||||
核心逻辑:资格评估可能将 ``evidence_missing`` 聚合为单条 field_conflict Finding;
|
||||
这里仅在 Finding 未附字段时读取首个阻断 Candidate conflict,供 Gate 和右栏说明。
|
||||
|
||||
Args:
|
||||
case: 当前复核 Case,可能未绑定 Candidate。
|
||||
|
||||
Returns:
|
||||
含 field_code / line_index 的定位字典;无可用事实时返回空字典。
|
||||
"""
|
||||
if not getattr(case, 'candidate_id', None):
|
||||
return {}
|
||||
from app.models import ShippingOrderCandidate
|
||||
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||||
for conflict in list(getattr(candidate, 'conflicts_json', None) or []):
|
||||
if not isinstance(conflict, dict):
|
||||
continue
|
||||
if str(conflict.get('severity') or '').lower() not in {'blocking', 'error'}:
|
||||
continue
|
||||
field_code = str(conflict.get('field') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
return {
|
||||
'field_code': field_code,
|
||||
'line_index': conflict.get('line_index'),
|
||||
'line_key': conflict.get('line_key'),
|
||||
}
|
||||
return {}
|
||||
|
||||
|
||||
def _sync_review_gates_safe(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
@@ -1388,7 +1470,7 @@ def _sync_review_gates_safe(
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将客户/Reservation/重复订单/库存路由校验结果同步到统一 Gate。
|
||||
将字段完整性、字段冲突、客户/Reservation/重复订单/库存路由校验结果同步到统一 Gate。
|
||||
|
||||
核心逻辑:按 owning_gate 折叠阻断;原因码经 canonicalize;库存门禁附带
|
||||
unavailable_reasons 等业务事实。失败向上抛出,与 Draft 同事务回滚。
|
||||
@@ -1408,6 +1490,62 @@ def _sync_review_gates_safe(
|
||||
result = validation if isinstance(validation, dict) else _validation(case)
|
||||
base_details = dict(details or {})
|
||||
|
||||
assessment = result.get('assessment') if isinstance(result.get('assessment'), dict) else {}
|
||||
missing_fields = list(assessment.get('missing_required_fields') or [])
|
||||
invalid_lines = list(assessment.get('invalid_lines') or [])
|
||||
# [STEP 1] 字段完整性直接以当前 Draft 的 assessment 为准,主动覆盖旧 Gate 快照。
|
||||
# 不能只同步 issues:当缺字段已补齐时,旧 required_field_missing 会永久误导用户。
|
||||
sync_review_gate_for_case(
|
||||
case=case,
|
||||
gate_code='field_completeness',
|
||||
passed=not missing_fields and not invalid_lines,
|
||||
actor_id=int(user_id),
|
||||
blocking_reason_code='required_field_missing' if (missing_fields or invalid_lines) else None,
|
||||
default_reason_code='required_field_missing',
|
||||
details={
|
||||
**base_details,
|
||||
'missing_required_fields': missing_fields,
|
||||
'invalid_lines': invalid_lines,
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 2] 自动建单冲突必须同步为字段冲突 Gate;否则右栏会保留已过期的缺字段提示。
|
||||
conflict_issues = _blocking_issues_for_gate(result, 'field_conflict_resolution')
|
||||
if not conflict_issues:
|
||||
sync_review_gate_for_case(
|
||||
case=case,
|
||||
gate_code='field_conflict_resolution',
|
||||
passed=True,
|
||||
actor_id=int(user_id),
|
||||
details=base_details,
|
||||
)
|
||||
else:
|
||||
primary_conflict = conflict_issues[0]
|
||||
conflict_locator = _candidate_conflict_locator(case)
|
||||
sync_review_gate_for_case(
|
||||
case=case,
|
||||
gate_code='field_conflict_resolution',
|
||||
passed=False,
|
||||
actor_id=int(user_id),
|
||||
blocking_reason_code=canonicalize_reason_code(
|
||||
str(primary_conflict.get('reason_code') or primary_conflict.get('code') or 'field_conflict')
|
||||
) or 'field_conflict',
|
||||
default_reason_code='field_conflict',
|
||||
details={
|
||||
**base_details,
|
||||
'line_key': primary_conflict.get('line_key') or conflict_locator.get('line_key'),
|
||||
'line_index': primary_conflict.get('line_index')
|
||||
if primary_conflict.get('line_index') is not None else conflict_locator.get('line_index'),
|
||||
'field_code': primary_conflict.get('field_code') or conflict_locator.get('field_code'),
|
||||
'issue_codes': [
|
||||
canonicalize_reason_code(str(item.get('reason_code') or item.get('code') or ''))
|
||||
for item in conflict_issues
|
||||
if canonicalize_reason_code(str(item.get('reason_code') or item.get('code') or ''))
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 3] 其余复核 Gate 继续按 owning_gate 同步。
|
||||
for gate_code, default_reason in (
|
||||
('customer_resolution', 'customer_unresolved'),
|
||||
('reservation_validation', 'reservation_missing'),
|
||||
|
||||
@@ -17,7 +17,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderReviewCase
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake, ShippingOrderReviewCase
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.field_highlight_contract import build_field_highlight_projection
|
||||
from app.services.shipping_notice.order_review_service import get_user_review_case
|
||||
@@ -591,6 +591,61 @@ def get_case_pdf_bytes(*, user_id: int, case_no: str) -> tuple[bytes, str]:
|
||||
return read_asset_bytes(asset), str(document.filename or 'document.pdf').replace('\n', '').replace('\r', '')[:255]
|
||||
|
||||
|
||||
def get_case_intake_parse_context(*, user_id: int, case_no: str) -> dict[str, Any]:
|
||||
"""
|
||||
返回当前复核 Case 所属 Intake 的受控解析上下文,供工作台关联 PDF 与邮件正文。
|
||||
|
||||
核心逻辑:先经 Case owner 鉴权,读取 Case 主 Document 所属 Intake;direct_pdf
|
||||
强制不投影正文,其余来源再以 intake_id 查询唯一 email_body。严禁按 document_id
|
||||
或会话跨 Intake 回读正文,且不返回 FileAsset 存储位置或原始 EML。
|
||||
|
||||
Args:
|
||||
user_id: 当前登录用户,仅允许读取其拥有的 Case。
|
||||
case_no: 复核 Case 编号。
|
||||
|
||||
Returns:
|
||||
含主附件安全元数据与可选同 Intake 邮件正文的 DTO。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Case 主文档不存在时拒绝返回不完整或跨边界上下文。
|
||||
"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
attachment = db.session.get(ShippingOrderDocument, int(case.document_id))
|
||||
if attachment is None:
|
||||
raise NotFoundError(
|
||||
'Intake parse context is unavailable',
|
||||
code='SHIPPING.REVIEW_INTAKE_CONTEXT_NOT_FOUND',
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(attachment.asset_id)) if attachment.asset_id else None
|
||||
is_pdf = bool(
|
||||
asset and (
|
||||
str(asset.mime_type or '').lower() == 'application/pdf'
|
||||
or str(attachment.filename or '').lower().endswith('.pdf')
|
||||
)
|
||||
)
|
||||
intake = db.session.get(ShippingOrderIntake, int(attachment.intake_id))
|
||||
body = None if intake is not None and intake.source_type == 'direct_pdf' else (
|
||||
ShippingOrderDocument.query.filter_by(
|
||||
intake_id=attachment.intake_id,
|
||||
document_type='email_body',
|
||||
).one_or_none()
|
||||
)
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'attachment': {
|
||||
'document_id': int(attachment.id),
|
||||
'filename': str(attachment.filename or '')[:255],
|
||||
'mime_type': str(asset.mime_type or '') if asset else None,
|
||||
'preview_kind': 'pdf' if is_pdf else 'unsupported',
|
||||
},
|
||||
'email': None if body is None else {
|
||||
'document_id': int(body.id),
|
||||
'filename': str(body.filename or 'email.eml')[:255],
|
||||
'text': str(body.extracted_text or '')[:20_000],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_case_email_evidence_text(*, user_id: int, case_no: str, document_id: int) -> dict[str, Any]:
|
||||
"""返回同一 Intake 邮件正文的已解析文本,禁止读取原始 EML、附件或存储地址。"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
|
||||
@@ -319,7 +319,10 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d
|
||||
except (TypeError, ValueError):
|
||||
line_index = -1
|
||||
value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')]
|
||||
if len(value_keys) < 2:
|
||||
reason = str(item.get('reason') or 'field_conflict')
|
||||
# 证据缺失/单值冲突没有可供二选一的 values,但仍会阻断自动建单。
|
||||
# 必须投影给工作台,避免资格摘要与字段裁决区同时丢失定位事实。
|
||||
if len(value_keys) < 2 and reason not in {'evidence_missing', 'pdf_evidence_missing'}:
|
||||
continue
|
||||
observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid]
|
||||
options = [
|
||||
@@ -338,7 +341,7 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d
|
||||
'line_index': line_index if line_index >= 0 else None,
|
||||
'line_key': line_key,
|
||||
'severity': str(item.get('severity') or 'blocking'),
|
||||
'reason': str(item.get('reason') or 'field_conflict'),
|
||||
'reason': reason,
|
||||
'options': options,
|
||||
'observation_ids': observation_ids,
|
||||
})
|
||||
|
||||
@@ -562,9 +562,11 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
|
||||
return actions
|
||||
if case.status == 'reparse_pending':
|
||||
return ['view']
|
||||
# 替代 PDF 的写入资格与质量异常标记不同:前者在服务层允许质量异常和普通待复核
|
||||
# Case 使用,必须作为独立动作下发,避免前端借用 mark_quality_issue 猜测权限。
|
||||
if case.status == 'quality_issue':
|
||||
return ['view', 'mark_quality_issue', 'reparse']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'validate']
|
||||
return ['view', 'mark_quality_issue', 'reparse', 'upload_replacement']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'upload_replacement', 'validate']
|
||||
if case.candidate_id is None and case.disposition != 'manual_order':
|
||||
actions.append('create_draft')
|
||||
else:
|
||||
@@ -729,6 +731,7 @@ def serialize_review_case(
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -739,6 +742,7 @@ def serialize_review_case(
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(formal_ot['task_id']))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -1016,6 +1020,63 @@ def serialize_review_case(
|
||||
}
|
||||
|
||||
|
||||
def _serialize_review_case_summary(
|
||||
case: ShippingOrderReviewCase,
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
) -> dict[str, Any]:
|
||||
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。"""
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None
|
||||
# 空 Review Case 只是解析异常/人工处置容器,不能显示为已进入订单复核。
|
||||
# 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。
|
||||
lifecycle_stage = 'intake_parse'
|
||||
lifecycle_entries: list[dict[str, str]] = []
|
||||
# 接收解析是无 Candidate Case 的独立处置面,不属于订单生命周期入口;
|
||||
# 前端只能以此显式授权读取当前 Case 的解析上下文,不能据此开放订单复核。
|
||||
intake_parse_authorized = False
|
||||
candidate_is_reviewable = False
|
||||
if case.confirmed_task_id:
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
if formal_ot.get('has_formal_ot'):
|
||||
task_ui_state = build_task_ui_state(formal_ot['task'])
|
||||
lifecycle_stage = str(task_ui_state.get('lifecycle_stage') or lifecycle_stage)
|
||||
lifecycle_entries = list(task_ui_state.get('lifecycle_entries') or [])
|
||||
else:
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
candidate_is_reviewable = is_current_reviewable_candidate(candidate)
|
||||
if not case.confirmed_task_id and candidate_is_reviewable:
|
||||
# [AUTHORITY] 建单前的有效 Candidate 已由 Case 一对一绑定;后端明确授权
|
||||
# 接收解析回看与订单复核,后续履约阶段保持不可用。
|
||||
from app.services.shipping_notice.lifecycle_projection import lifecycle_entries as project_lifecycle_entries
|
||||
|
||||
lifecycle_entries = project_lifecycle_entries(
|
||||
lifecycle_stage='order_review',
|
||||
has_candidate_context=True,
|
||||
)
|
||||
lifecycle_stage = 'order_review'
|
||||
elif not case.confirmed_task_id:
|
||||
intake_parse_authorized = True
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'document_id': int(case.document_id),
|
||||
'file_name': _document_filename(run, int(case.document_id)),
|
||||
'status': case.status,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
|
||||
'available_actions': _allowed_actions(case),
|
||||
# 后端按 Case/正式任务裁决,禁止工作台仅为当前项从草稿拼接 PO 或阶段。
|
||||
'po_number': str(candidate.po_number or '').strip() or None if candidate is not None else None,
|
||||
'lifecycle_stage': lifecycle_stage,
|
||||
# 与批次中心 / 任务中心同义;前端不得再根据 Case status 或 stage 推断入口。
|
||||
'lifecycle_entries': lifecycle_entries,
|
||||
'intake_parse_authorized': intake_parse_authorized,
|
||||
}
|
||||
|
||||
|
||||
def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
"""返回 Run 的 Case 汇总和轻量列表,避免 N+1 查询及泄露机器原始结果。"""
|
||||
cases = list(run.review_cases or [])
|
||||
@@ -1023,18 +1084,28 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
items = []
|
||||
for case in cases:
|
||||
counts[case.status] = counts.get(case.status, 0) + 1
|
||||
items.append({
|
||||
'case_no': case.case_no,
|
||||
'document_id': int(case.document_id),
|
||||
'file_name': _document_filename(run, int(case.document_id)),
|
||||
'status': case.status,
|
||||
'draft_version': int(case.current_draft.draft_version) if case.current_draft is not None else None,
|
||||
'issue_count': len(case.current_draft.issue_summary_json or []) if case.current_draft is not None else 0,
|
||||
'available_actions': _allowed_actions(case),
|
||||
})
|
||||
items.append(_serialize_review_case_summary(case, run=run))
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'superseded_by_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
|
||||
'summary': counts,
|
||||
'items': items,
|
||||
}
|
||||
|
||||
|
||||
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
|
||||
"""返回会话级订单队列;保留来源 Run,避免混淆单次 Run 摘要。"""
|
||||
items: list[dict[str, Any]] = []
|
||||
for run in runs:
|
||||
for case in run.review_cases or []:
|
||||
items.append({
|
||||
**_serialize_review_case_summary(case, run=run),
|
||||
'source_run_no': run.run_no,
|
||||
})
|
||||
counts = {
|
||||
'total': len(items),
|
||||
'needs_action': sum(1 for item in items if item['status'] in ('unreviewed', 'draft', 'ready')),
|
||||
'processing': sum(1 for item in items if item['status'] in ('confirming', 'reparse_pending')),
|
||||
'completed': sum(1 for item in items if item['status'] in ('confirmed', 'non_order', 'quality_issue')),
|
||||
}
|
||||
return {'conversation_id': runs[0].conversation_id if runs else None, 'summary': counts, 'items': items}
|
||||
@@ -25,17 +25,52 @@ _RESERVATION_ISSUE_CODES = frozenset({
|
||||
|
||||
|
||||
def _reservation_field_id(case: ShippingOrderReviewCase) -> str | None:
|
||||
"""从 Run 冻结 Schema 解析 reservation_id 的 field_id。"""
|
||||
"""
|
||||
从 Run 冻结 Schema 解析明细 reservation_id 的 field_id。
|
||||
|
||||
核心逻辑:字段身份由 field_code 与 scope 共同决定;同名表头 Reservation
|
||||
不能作为明细预约号投影的读取键,否则合法的明细值会被误判为缺失。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_projection import _schema_fields
|
||||
|
||||
for item in _schema_fields(case.run):
|
||||
if str(item.get('field_code') or '').strip() == 'reservation_id':
|
||||
if (
|
||||
str(item.get('field_code') or '').strip() == 'reservation_id'
|
||||
and str(item.get('scope') or '').strip() == 'line'
|
||||
):
|
||||
fid = str(item.get('field_id') or '').strip()
|
||||
if fid:
|
||||
return fid
|
||||
return None
|
||||
|
||||
|
||||
def _current_line_reservation_id(raw_line: dict[str, Any], reservation_field_id: str | None) -> str | None:
|
||||
"""
|
||||
读取 Draft 当前行的有效 Reservation。
|
||||
|
||||
核心逻辑:读取优先级与编辑工作面一致:人工 values[field_id].value → 冻结 machine_fields
|
||||
→ 顶层兼容字段。校验 Job 尚未回写 line_projections 时,摘要必须读取同一份 Draft 真源。
|
||||
"""
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
values = raw_line.get('values') if isinstance(raw_line.get('values'), dict) else {}
|
||||
entry = values.get(reservation_field_id) if reservation_field_id else None
|
||||
if isinstance(entry, dict) and 'value' in entry:
|
||||
value = entry.get('value')
|
||||
else:
|
||||
value = None
|
||||
for field in list(raw_line.get('machine_fields') or []):
|
||||
if not isinstance(field, dict) or str(field.get('field_id') or '') != reservation_field_id:
|
||||
continue
|
||||
observations = field.get('observations') if isinstance(field.get('observations'), list) else []
|
||||
if observations and isinstance(observations[0], dict):
|
||||
value = observations[0].get('value')
|
||||
break
|
||||
if value is None:
|
||||
value = raw_line.get('reservation_id')
|
||||
return validated_reservation_id(value) or None
|
||||
|
||||
|
||||
def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
投影建单前 Reservation 校验摘要。
|
||||
@@ -61,6 +96,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
|
||||
|
||||
validation = dict(draft.validation_result_json or {})
|
||||
line_projections = list(validation.get('line_projections') or [])
|
||||
reservation_field_id = _reservation_field_id(case)
|
||||
issues = [
|
||||
item for item in list(validation.get('issues') or [])
|
||||
if isinstance(item, dict)
|
||||
@@ -102,7 +138,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
|
||||
for idx, line in enumerate(raw_lines):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
rid = str(line.get('reservation_id') or '').strip() or None
|
||||
rid = _current_line_reservation_id(line, reservation_field_id)
|
||||
lines_out.append({
|
||||
'line_index': idx,
|
||||
'line_key': str(line.get('line_key') or '').strip() or None,
|
||||
@@ -117,7 +153,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
|
||||
return {
|
||||
'needs_attention': needs_attention,
|
||||
'status': status,
|
||||
'reservation_field_id': _reservation_field_id(case),
|
||||
'reservation_field_id': reservation_field_id,
|
||||
'lines': lines_out,
|
||||
'issues': [
|
||||
{
|
||||
|
||||
@@ -106,6 +106,7 @@ def _invalidate_downstream_if_needed(
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -277,6 +277,11 @@ def _backfill_existing_case_from_ready_unit(
|
||||
operation_json={'document_id': int(unit.document_id)},
|
||||
))
|
||||
_ensure_order_task_for_case_candidate(run, candidate_id=case.candidate_id)
|
||||
# Candidate/Case 物化后收口初始解析 Gate,确保实时阶段进入订单复核。
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
reconcile_extraction_gates_for_review_case,
|
||||
)
|
||||
reconcile_extraction_gates_for_review_case(case=case, actor_type='system')
|
||||
|
||||
|
||||
def ensure_review_case_for_unit(
|
||||
@@ -334,6 +339,10 @@ def ensure_review_case_for_unit(
|
||||
operation_json={'candidate_linked': candidate_id is not None, 'issue_count': len(issues)},
|
||||
))
|
||||
_ensure_order_task_for_case_candidate(run, candidate_id=candidate_id)
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
reconcile_extraction_gates_for_review_case,
|
||||
)
|
||||
reconcile_extraction_gates_for_review_case(case=case, actor_type='system')
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
@@ -409,6 +418,26 @@ def get_review_run_visible_to_user(
|
||||
return run
|
||||
|
||||
|
||||
def get_review_queue_visible_to_user(
|
||||
run_no: str,
|
||||
user_id: int,
|
||||
*,
|
||||
is_admin: bool = False,
|
||||
) -> list[ShippingOrderProcessingRun]:
|
||||
"""按当前 Run 定位会话,并返回该用户会话内未被替代的 Review Run。"""
|
||||
anchor = get_review_run_visible_to_user(run_no, user_id, is_admin=is_admin)
|
||||
query = ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.conversation_id == anchor.conversation_id,
|
||||
)
|
||||
if not is_admin:
|
||||
query = query.filter(ShippingOrderProcessingRun.user_id == int(user_id))
|
||||
query = query.filter(ShippingOrderProcessingRun.superseded_by_run_id.is_(None))
|
||||
return query.order_by(
|
||||
ShippingOrderProcessingRun.created_at.asc(),
|
||||
ShippingOrderProcessingRun.id.asc(),
|
||||
).all()
|
||||
|
||||
|
||||
def get_review_case_visible_to_user(
|
||||
case_no: str,
|
||||
user_id: int,
|
||||
|
||||
@@ -38,7 +38,10 @@ from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
finalize_sync_auto_progress_after_commit,
|
||||
schedule_auto_progress_after_review_confirm,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import _validation
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
_validation,
|
||||
draft_requires_manual_validation,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
extraction_emergency_stop_enabled,
|
||||
xfa_shadow_mode_enabled,
|
||||
@@ -93,22 +96,41 @@ def _draft_has_manual_edits(case: ShippingOrderReviewCase) -> bool:
|
||||
|
||||
核心逻辑:header/line values 中任一 source=manual 即视为需显式确认。
|
||||
"""
|
||||
return case.current_draft is None or draft_requires_manual_validation(case.current_draft)
|
||||
|
||||
|
||||
def _refresh_validation_preserving_manual_confirmation(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
重算 STP 资格事实,同时保留当前 Draft 已完成的显式人工校验身份。
|
||||
|
||||
核心逻辑:Worker 必须在执行前重验配置、证据与门禁,但 ``validation_version``
|
||||
代表用户已对当前 Draft 版本点击“保存订单并校验”。若该值恰好等于当前版本,
|
||||
重验不能撤销该确认;草稿版本变化时绝不继承,仍会被 manual-validation 门禁拦截。
|
||||
|
||||
Args:
|
||||
case: 含当前 Draft 的复核 Case。
|
||||
|
||||
Returns:
|
||||
最新资格事实,必要时附带当前版本的 validation_version。
|
||||
"""
|
||||
draft = case.current_draft
|
||||
if draft is None:
|
||||
return True
|
||||
header = draft.header_values_json if isinstance(draft.header_values_json, dict) else {}
|
||||
values = header.get('values') if isinstance(header.get('values'), dict) else {}
|
||||
for item in values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') == 'manual':
|
||||
return True
|
||||
for raw_line in draft.lines_json or []:
|
||||
if not isinstance(raw_line, dict):
|
||||
continue
|
||||
line_values = raw_line.get('values') if isinstance(raw_line.get('values'), dict) else {}
|
||||
for item in line_values.values():
|
||||
if isinstance(item, dict) and str(item.get('source') or '') == 'manual':
|
||||
return True
|
||||
return False
|
||||
validation = _validation(case)
|
||||
prior = draft.validation_result_json if isinstance(draft.validation_result_json, dict) else {}
|
||||
try:
|
||||
confirmed_version = int(prior.get('validation_version'))
|
||||
except (TypeError, ValueError):
|
||||
confirmed_version = None
|
||||
if confirmed_version == int(draft.draft_version):
|
||||
validation['validation_version'] = confirmed_version
|
||||
for key in ('validation_checksum', 'validated_at', 'validated_case_no', 'validated_document_id'):
|
||||
if key in prior:
|
||||
validation[key] = prior[key]
|
||||
draft.validation_result_json = validation
|
||||
draft.issue_summary_json = list(validation.get('issues') or [])
|
||||
return validation
|
||||
|
||||
|
||||
def _is_xfa_case(*, candidate: ShippingOrderCandidate | None, validation: dict[str, Any]) -> bool:
|
||||
@@ -554,9 +576,7 @@ def ensure_stp_auto_create_for_case(
|
||||
|
||||
candidate = _persist_case_candidate_qualification(case=case, run=resolved_run)
|
||||
if refresh_validation:
|
||||
validation = _validation(case)
|
||||
case.current_draft.validation_result_json = validation
|
||||
case.current_draft.issue_summary_json = list(validation.get('issues') or [])
|
||||
validation = _refresh_validation_preserving_manual_confirmation(case=case)
|
||||
else:
|
||||
validation = (
|
||||
dict(case.current_draft.validation_result_json)
|
||||
|
||||
@@ -62,6 +62,20 @@ _PROGRESS_EVENT_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
'run_completed': 'candidate_creating',
|
||||
}
|
||||
|
||||
# 正式 Process Gate 的库存履约阶段 → 统一 15 阶投影阶段。
|
||||
# Gate 码不是 15 阶成员,必须在写路径转换后再回写 OT,避免已建单任务残留建单前 stage。
|
||||
_PROCESS_GATE_TO_PROCESSING_STAGE: dict[str, str] = {
|
||||
'inventory_source_routing': 'inventory_source_resolving',
|
||||
'inventory_preparation': 'inventory_fetching',
|
||||
'inventory_field_mapping': 'inventory_fetching',
|
||||
'inventory_matching': 'inventory_matching',
|
||||
'inventory_sufficiency': 'inventory_matching',
|
||||
'excel_readiness': 'excel_generating',
|
||||
'artifact_generation': 'excel_generating',
|
||||
'freight_upload_rpa': 'freight_uploading',
|
||||
'manual_upload_handoff': 'freight_uploading',
|
||||
}
|
||||
|
||||
|
||||
def _clamp_early_stage(stage: str, *, source_type: str | None) -> str:
|
||||
"""
|
||||
@@ -335,6 +349,19 @@ def sync_order_task_stage_for_notice(
|
||||
if ot is None:
|
||||
return None
|
||||
status, stage = map_notice_to_processing_status_stage(notice)
|
||||
# [STEP] Execution.current_gate_code 是正式履约事实,优先于尚未来得及写入 Notice
|
||||
# 领域字段的默认映射;只接受 active/waiting_external/blocked 执行,避免旧 Execution 回退 OT。
|
||||
active_execution_id = getattr(notice, 'active_process_execution_id', None)
|
||||
if active_execution_id is not None:
|
||||
from app.models import ShippingProcessExecution
|
||||
|
||||
execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
|
||||
execution_status = str(getattr(execution, 'status', None) or '').strip().lower()
|
||||
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
|
||||
gate_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code)
|
||||
if execution_status in {'active', 'waiting_external', 'blocked'} and gate_stage:
|
||||
stage = gate_stage
|
||||
status = 'automating' if execution_status in {'active', 'waiting_external'} else 'blocked'
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = 'inventory_matching'
|
||||
return sync_order_task_processing_state(
|
||||
|
||||
@@ -263,6 +263,9 @@ def _attempts_summary(
|
||||
for code in source_codes:
|
||||
att = _latest_attempt(task_no, code, session=session)
|
||||
result[code] = {
|
||||
# PreparationSourceAttempt 必须持有不可变 RPA Attempt 主键;回调据此
|
||||
# 回写准备轮次及关联 RecoveryPlan,不能仅靠 task/source 猜测最新记录。
|
||||
'attempt_id': int(att.id) if att else None,
|
||||
'attempt_no': att.attempt_no if att else 0,
|
||||
'status': att.status if att else 'not_started',
|
||||
'run_no': att.run_no if att else None,
|
||||
@@ -407,7 +410,12 @@ def ensure_all_required_sources_prepared(
|
||||
gate_id = None
|
||||
if execution_id:
|
||||
execution_row = sess.get(ShippingProcessExecution, int(execution_id))
|
||||
if execution_row is not None and execution_row.current_gate_code:
|
||||
if (
|
||||
execution_row is not None
|
||||
and int(getattr(execution_row, 'task_id', 0) or 0) == int(task.id)
|
||||
and str(getattr(execution_row, 'status', '') or '').strip().lower() != 'superseded'
|
||||
and execution_row.current_gate_code
|
||||
):
|
||||
gate_row = sess.query(ShippingProcessGate).filter_by(
|
||||
execution_id=int(execution_row.id),
|
||||
gate_code=str(execution_row.current_gate_code),
|
||||
@@ -504,7 +512,7 @@ def per_source_callback_handler(
|
||||
|
||||
Returns:
|
||||
(result_code: str, attempt: ShippingTaskInventoryRpaAttempt | None)
|
||||
result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, succeeded, failed}
|
||||
result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, validated, succeeded, failed}
|
||||
"""
|
||||
sess = session or db.session
|
||||
task_no = str(task.task_no or '').strip()
|
||||
@@ -596,6 +604,12 @@ def per_source_callback_handler(
|
||||
sess.flush([attempt])
|
||||
return 'task_terminal', attempt
|
||||
|
||||
# Batch Worker 必须先在不改变 Attempt 状态的条件下完成身份围栏校验;Excel
|
||||
# 入库、结构校验、任务关联都成功后,才会以同一三元组再次调用本函数写入
|
||||
# succeeded。否则单项保存点回滚时会留下“RPA 已成功、库存未就绪”的假事实。
|
||||
if bool(callback_payload.get('_defer_success_confirmation')):
|
||||
return 'validated', attempt
|
||||
|
||||
# [STEP 6] 写回调结果
|
||||
attempt.callback_payload_json = dict(callback_payload or {})
|
||||
attempt.callback_received_at = datetime.utcnow()
|
||||
|
||||
@@ -23,6 +23,7 @@ from typing import Any
|
||||
|
||||
from app.models import (
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderCandidate,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingNotice,
|
||||
@@ -31,6 +32,7 @@ from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
bind_execution_task,
|
||||
ensure_execution_for_workflow_version,
|
||||
skip_gate_as_superseded,
|
||||
sync_gate_from_business_result,
|
||||
)
|
||||
|
||||
@@ -227,6 +229,7 @@ def find_execution_for_case(case: ShippingOrderReviewCase) -> ShippingProcessExe
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -237,6 +240,7 @@ def find_execution_for_task(task: ShippingNotice) -> ShippingProcessExecution |
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -605,6 +609,7 @@ def sync_early_pipeline_gates(
|
||||
idempotency_key=f'early:layout:{execution.execution_no}:{layouts_ready}',
|
||||
force=True,
|
||||
)
|
||||
|
||||
if not layouts_ready:
|
||||
return
|
||||
apply_gate_outcome(
|
||||
@@ -660,6 +665,71 @@ def sync_early_pipeline_gates(
|
||||
)
|
||||
|
||||
|
||||
def reconcile_extraction_gates_for_review_case(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingProcessExecution | None:
|
||||
"""在当前 Candidate 已物化后收口旧解析 Gate,避免阶段回退到接收解析。
|
||||
|
||||
触发时机:Review Case 初建或补回 Candidate 后调用。Case 本身可能先于机器候选
|
||||
创建,不能把“已创建人工容器”误当作“文件已解析成功”;未关联当前 Candidate 时
|
||||
不创建 Execution、也不推进任何解析 Gate,仍由真实解析链路裁决。
|
||||
|
||||
Args:
|
||||
case: 已持久化的复核 Case;必须关联当前 Candidate 才可推进。
|
||||
actor_type: 审计操作主体。
|
||||
actor_id: 可选审计主体标识。
|
||||
|
||||
Returns:
|
||||
已同步的正式 Execution;Candidate 尚未物化或已失效时返回 ``None``。
|
||||
"""
|
||||
candidate = (
|
||||
ShippingOrderCandidate.query.get(int(case.candidate_id))
|
||||
if case.candidate_id is not None else None
|
||||
)
|
||||
# [STEP] Candidate 是“解析成功”的最小业务事实。禁止由空 Case 关闭旧 Gate,
|
||||
# 否则缺候选的 PDF 会被错误投影为可进入订单复核。
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
if not is_current_reviewable_candidate(candidate):
|
||||
return None
|
||||
execution = find_execution_for_case(case)
|
||||
if execution is None:
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=int(case.id), actor_type=actor_type, actor_id=actor_id,
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
for code in (
|
||||
'document_materialization', 'layout_parsing',
|
||||
'document_profile_routing', 'order_field_extraction',
|
||||
):
|
||||
skip_gate_as_superseded(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=code,
|
||||
disposition='superseded_by_candidate',
|
||||
effective_result_json={
|
||||
'source': 'candidate_ready',
|
||||
'candidate_id': int(candidate.id),
|
||||
'review_case_id': int(case.id),
|
||||
},
|
||||
actor_type=actor_type,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
missing = list(getattr(candidate, 'missing_fields_json', None) or [])
|
||||
apply_gate_outcome(
|
||||
execution=execution, gate_code='field_completeness', passed=not missing,
|
||||
effective_result={'findings': [], 'blocked_fields': missing, 'source': 'candidate_ready'},
|
||||
blocking_reason_code=None if not missing else 'required_field_missing',
|
||||
actor_type=actor_type, actor_id=actor_id,
|
||||
idempotency_key=f'candidate-ready:field-completeness:{case.id}:{",".join(sorted(map(str, missing)))}',
|
||||
force=True,
|
||||
)
|
||||
return execution
|
||||
|
||||
|
||||
def _fulfillment_blocking_finding(
|
||||
*,
|
||||
gate_code: str,
|
||||
@@ -793,10 +863,15 @@ def sync_fulfillment_gates_from_task(
|
||||
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
|
||||
status = _derived_fulfillment_status(task)
|
||||
match_status = str(task.match_status or '').strip()
|
||||
has_export = bool(str(task.export_file_path or '').strip())
|
||||
has_inventory_lines = isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0
|
||||
status = _derived_fulfillment_status(task)
|
||||
# [STEP 1A] 已验证并绑定的库存行是库存准备的正式成功事实。RPA 回调与
|
||||
# 旧失败/超时 Attempt 可以乱序到达;不能让遗留的 rpa_exhausted 把已成功
|
||||
# 入库的任务重新投影为 waiting_inventory,否则 Gate 会停在“手工上传”。
|
||||
if has_inventory_lines and status == 'waiting_inventory':
|
||||
status = 'inventory_ready'
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
|
||||
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
|
||||
|
||||
@@ -563,6 +563,7 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
|
||||
'extraction_incomplete': 'order_field_extraction',
|
||||
'order_extraction_failed': 'order_field_extraction',
|
||||
'order_extraction_cancelled': 'order_field_extraction',
|
||||
'generic_extraction_disabled': 'order_field_extraction',
|
||||
'evidence_missing': 'order_field_extraction',
|
||||
'required_field_missing': 'field_completeness',
|
||||
'final_required_field_missing': 'field_completeness',
|
||||
|
||||
@@ -827,9 +827,7 @@ def _handle_retry_inventory_preparation(
|
||||
# 用户触发的重新获取库存不能把“已提交但未确认”伪装成业务完成;
|
||||
# Gate 仍可记录 waiting_external,调用方可据此轮询,但测试/审计需区分
|
||||
# 人工重试动作本身与系统自动轮询动作。
|
||||
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'}
|
||||
if payload.get('action_code') == 'poll_inventory_preparation'
|
||||
else {'waiting', 'waiting_external', 'pending'},
|
||||
waiting_statuses={'waiting', 'waiting_external', 'pending', 'running'},
|
||||
blocking_reason_code=prep_reason,
|
||||
)
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=actor_id)
|
||||
@@ -939,11 +937,14 @@ def _handle_retry_inventory_matching(
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
重试库存匹配;匹配已完成但仍有缺口时返回业务人工阻断。
|
||||
重试库存匹配;匹配已完成但仍有缺口时通过当前匹配 Gate,交由库存满足性 Gate
|
||||
保持业务人工阻断。
|
||||
|
||||
核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和
|
||||
“匹配成功但库存不足”。后者必须以库存满足性人工复核收口,不能误记为
|
||||
技术失败,否则 RecoveryPlan 会反复失败且页面看不到有效推进。
|
||||
“匹配成功但库存不足”。匹配成功但库存不足时,前置的
|
||||
``sync_fulfillment_gates_from_task`` 已将缺口写入 inventory_sufficiency;
|
||||
当前 inventory_matching Attempt 必须以 passed 收口,否则会覆盖正确的
|
||||
满足性 Gate 归属并再次显示“进入库存匹配处理”。
|
||||
"""
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory
|
||||
@@ -958,16 +959,9 @@ def _handle_retry_inventory_matching(
|
||||
match_status in {'partial', 'unfulfillable'} or has_shortage
|
||||
):
|
||||
return {
|
||||
'outcome': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
'blocking_reason_json': {
|
||||
'message': '库存重新匹配已完成,仍存在库存缺口。',
|
||||
'match_status': match_status or None,
|
||||
},
|
||||
'recommendation_json': {
|
||||
'navigation_action': 'open_shortage_review',
|
||||
'dispatch_mode': 'navigate',
|
||||
},
|
||||
# 缺口归属由 sync_fulfillment_gates_from_task 写入
|
||||
# inventory_sufficiency;不能在这里再次阻断 inventory_matching。
|
||||
'outcome': 'passed',
|
||||
'effective_result_json': {
|
||||
'findings': [],
|
||||
'match_status': match_status or None,
|
||||
|
||||
@@ -198,10 +198,34 @@ def schedule_waiting_external_poll(
|
||||
60,
|
||||
)
|
||||
if (now - waiting_since).total_seconds() >= timeout_sec:
|
||||
# [STEP] 超时:创建 Attempt 将 Gate 转为人工阻断,停止无限轮询。
|
||||
# 回调与延迟 poll 可能交错:在把等待状态转为超时前,必须从当前任务事实
|
||||
# 重算 Gate。否则 RPA 已成功入库后,旧 poll 会用历史 waiting_since 覆盖成功结果。
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
if str(gate.gate_code or '').strip() == 'inventory_preparation' and execution.task_id:
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
task = db.session.get(ShippingNotice, int(execution.task_id))
|
||||
has_inventory_lines = bool(
|
||||
isinstance(getattr(task, 'inventory_lines_json', None), list)
|
||||
and getattr(task, 'inventory_lines_json', None)
|
||||
)
|
||||
if task is not None and has_inventory_lines:
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
|
||||
db.session.flush()
|
||||
db.session.refresh(gate)
|
||||
if gate.status != 'waiting_external':
|
||||
return None
|
||||
# [STEP] 超时:创建 Attempt 将 Gate 转为人工阻断,停止无限轮询。
|
||||
# 外部轮询超时是新的、可恢复的业务事实;不能保留原来的
|
||||
# inventory_rpa_queued,否则页面会同时显示“等待外部”和“人工处理”。
|
||||
timeout_reason = (
|
||||
'inventory_rpa_timeout'
|
||||
if str(gate.gate_code or '').strip() == 'inventory_preparation'
|
||||
else (gate.blocking_reason_code or 'gate_invalidated')
|
||||
)
|
||||
poll_attempt = queue_gate_attempt(
|
||||
execution_no=str(execution.execution_no),
|
||||
gate_code=gate.gate_code,
|
||||
@@ -221,7 +245,7 @@ def schedule_waiting_external_poll(
|
||||
complete_gate_attempt(
|
||||
attempt_id=int(poll_attempt.id),
|
||||
outcome='blocked_manual',
|
||||
blocking_reason_code=gate.blocking_reason_code or 'gate_invalidated',
|
||||
blocking_reason_code=timeout_reason,
|
||||
blocking_reason_json={
|
||||
'message': '外部等待超时,请人工处理',
|
||||
'waiting_since': waiting_since.isoformat(),
|
||||
@@ -240,8 +264,29 @@ def schedule_waiting_external_poll(
|
||||
action = gate.next_action_code or primary_next_action_for_gate(
|
||||
gate_code=gate.gate_code, status='waiting_external',
|
||||
)
|
||||
if not action:
|
||||
# ``poll_inventory_preparation`` 只能轮询库存准备 Gate。跨 Gate 恢复
|
||||
# (例如从 inventory_matching 回到 inventory_preparation)完成后,原 Gate
|
||||
# 可能短暂保留 waiting_external,但不能把准备阶段的轮询动作投递到该原 Gate;
|
||||
# 否则 executor 的归属校验会把过期 poll 误记为技术失败。
|
||||
if not action and str(gate.gate_code or '').strip() == 'inventory_preparation':
|
||||
action = 'poll_inventory_preparation'
|
||||
if (
|
||||
str(gate.gate_code or '').strip() != 'inventory_preparation'
|
||||
and str(action or '').strip() == 'poll_inventory_preparation'
|
||||
):
|
||||
_LOGGER.info(
|
||||
'skip stale inventory-preparation poll: gate_id=%s gate_code=%s',
|
||||
gate.id,
|
||||
gate.gate_code,
|
||||
)
|
||||
return None
|
||||
if not action:
|
||||
_LOGGER.info(
|
||||
'skip stale external-wait poll: gate_id=%s gate_code=%s has no waiting action',
|
||||
gate.id,
|
||||
gate.gate_code,
|
||||
)
|
||||
return None
|
||||
execution = db.session.get(ShippingProcessExecution, int(gate.execution_id))
|
||||
if execution is None:
|
||||
return None
|
||||
|
||||
@@ -922,6 +922,7 @@ def find_execution_projection_for_case(case_id: int) -> dict[str, Any] | None:
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(case_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -935,6 +936,7 @@ def find_execution_projection_for_task(task_id: int) -> dict[str, Any] | None:
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -170,7 +170,7 @@ def request_gate_action(
|
||||
|
||||
execution = get_execution_by_no(execution_no)
|
||||
execution_status = str(execution.status or '').strip().lower()
|
||||
if execution_status in {'completed', 'cancelled'}:
|
||||
if execution_status in {'completed', 'cancelled', 'superseded'}:
|
||||
raise ValidationError(
|
||||
'Process execution is terminal; write actions are not allowed',
|
||||
code='SHIPPING.PROCESS_EXECUTION_TERMINAL',
|
||||
|
||||
@@ -290,6 +290,7 @@ def ensure_execution_for_workflow_version(
|
||||
existing = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(review_case_id=int(review_case_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.with_for_update()
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
@@ -298,6 +299,7 @@ def ensure_execution_for_workflow_version(
|
||||
existing = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.with_for_update()
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
@@ -641,6 +643,13 @@ def complete_gate_attempt(
|
||||
if execution is None:
|
||||
raise NotFoundError('Process execution not found', code='SHIPPING.PROCESS_EXECUTION_NOT_FOUND')
|
||||
|
||||
if str(execution.status or '').strip().lower() == 'superseded':
|
||||
raise ConflictError(
|
||||
'Superseded process execution cannot complete gate attempts',
|
||||
code='SHIPPING.PROCESS_EXECUTION_SUPERSEDED',
|
||||
details={'execution_no': execution.execution_no},
|
||||
)
|
||||
|
||||
now = _utc_now()
|
||||
before = {
|
||||
'status': gate.status,
|
||||
@@ -749,6 +758,114 @@ def complete_gate_attempt(
|
||||
return gate
|
||||
|
||||
|
||||
def skip_gate_as_superseded(
|
||||
*,
|
||||
execution_no: str,
|
||||
gate_code: str,
|
||||
disposition: str,
|
||||
effective_result_json: dict[str, Any] | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | int | None = None,
|
||||
) -> ShippingProcessGate:
|
||||
"""以明确替代语义关闭不再需要的 Gate,并终止活动 Attempt。
|
||||
|
||||
触发时机:更高层、可审计的业务事实(例如当前有效 Candidate)已形成,旧技术
|
||||
Gate 不应继续主导当前阶段时调用。已真实通过的 Gate 保持 ``passed``,不能被
|
||||
事后改写;其余 Gate 收口为 ``skipped``,且留下 disposition 供诊断和审计区分。
|
||||
|
||||
Args:
|
||||
execution_no: 正式 Execution 编号。
|
||||
gate_code: 需要收口的 Gate 编码。
|
||||
disposition: 稳定替代原因,例如 ``superseded_by_candidate``。
|
||||
effective_result_json: 受控业务证据,不得含原始文档或敏感内容。
|
||||
"""
|
||||
execution = _locked_execution(execution_no)
|
||||
if str(execution.status or '').strip().lower() == 'superseded':
|
||||
raise ConflictError(
|
||||
'Superseded process execution cannot skip gates',
|
||||
code='SHIPPING.PROCESS_EXECUTION_SUPERSEDED',
|
||||
details={'execution_no': execution.execution_no},
|
||||
)
|
||||
gate = _locked_gate(execution=execution, gate_code=gate_code)
|
||||
reason = str(disposition or '').strip() or 'superseded'
|
||||
previous_result = gate.effective_result_json if isinstance(gate.effective_result_json, dict) else {}
|
||||
# 候选收口可重复调用;同一替代事实已写入时不再制造新审计事件或版本。
|
||||
if gate.status == 'skipped' and str(previous_result.get('disposition') or '') == reason:
|
||||
return gate
|
||||
# 旧实现曾把 candidate_ready 收口伪记为 passed。它不是技术 Gate 的真实成功,
|
||||
# 因此可被安全纠正为 skipped;其他 passed 仍是不可改写的真实执行事实。
|
||||
candidate_ready_compatibility_pass = (
|
||||
gate.status == 'passed'
|
||||
and str(previous_result.get('source') or '') == 'candidate_ready'
|
||||
)
|
||||
if gate.status == 'passed' and not candidate_ready_compatibility_pass:
|
||||
return gate
|
||||
|
||||
now = _utc_now()
|
||||
active_attempts = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter(
|
||||
ShippingProcessGateAttempt.gate_id == int(gate.id),
|
||||
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
|
||||
)
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
latest_attempt_id = gate.latest_attempt_id
|
||||
for attempt in active_attempts:
|
||||
attempt.status = 'superseded'
|
||||
attempt.finished_at = now
|
||||
attempt.lease_token = None
|
||||
attempt.lease_expires_at = None
|
||||
attempt.error_code = reason[:64]
|
||||
attempt.error_summary = 'Gate superseded by higher-level business fact.'
|
||||
latest_attempt_id = int(attempt.id)
|
||||
|
||||
before = {
|
||||
'status': gate.status,
|
||||
'gate_code': gate.gate_code,
|
||||
'blocking_reason_code': gate.blocking_reason_code,
|
||||
}
|
||||
result = dict(previous_result)
|
||||
result.update(dict(effective_result_json or {}))
|
||||
result['disposition'] = reason
|
||||
gate.status = 'skipped'
|
||||
gate.blocking_reason_code = None
|
||||
gate.blocking_reason_json = None
|
||||
gate.recommendation_json = None
|
||||
gate.effective_result_json = result
|
||||
gate.next_action_code = None
|
||||
gate.latest_attempt_id = latest_attempt_id
|
||||
gate.evaluation_version = int(gate.evaluation_version) + 1
|
||||
gate.lock_version = int(gate.lock_version) + 1
|
||||
gate.updated_at = now
|
||||
execution.lock_version = int(execution.lock_version) + 1
|
||||
execution.updated_at = now
|
||||
_refresh_execution_pointers(execution)
|
||||
record_fulfillment_audit(
|
||||
event_type='process_gate_superseded',
|
||||
aggregate_type='process_gate',
|
||||
aggregate_id=f'{execution.execution_no}:{gate.gate_code}',
|
||||
action='skip',
|
||||
actor_type=actor_type if actor_type in {'user', 'system', 'rpa', 'chatflow', 'admin'} else 'system',
|
||||
actor_id=actor_id,
|
||||
result='success',
|
||||
reason_code=reason,
|
||||
before=before,
|
||||
after={
|
||||
'status': gate.status,
|
||||
'gate_code': gate.gate_code,
|
||||
'execution_no': execution.execution_no,
|
||||
'current_gate_code': execution.current_gate_code,
|
||||
},
|
||||
metadata={'disposition': reason},
|
||||
source='process_gate',
|
||||
)
|
||||
db.session.flush()
|
||||
return gate
|
||||
|
||||
|
||||
def _enqueue_auto_progress_after_gate_pass(
|
||||
*,
|
||||
execution: ShippingProcessExecution,
|
||||
@@ -776,6 +893,16 @@ def _enqueue_auto_progress_after_gate_pass(
|
||||
# 通过后必须继续进入库存匹配;关闭自动匹配时才保留人工恢复入口。
|
||||
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
|
||||
return
|
||||
# 自动续跑只可投递真实执行动作。导航动作属于人工工作台入口,不能因
|
||||
# Gate 的默认责任方为 worker 而被 Job 执行后重新写回人工阻断状态。
|
||||
from app.services.shipping_notice.process_gate_executor import is_navigation_action
|
||||
|
||||
if is_navigation_action(str(next_gate.next_action_code)):
|
||||
return
|
||||
# retry_inventory_preparation 是用户显式恢复动作,会强制写新的 RPA Trigger。
|
||||
# 自动推进只能轮询 waiting_external,绝不能把失败恢复误当作下一步执行。
|
||||
if next_gate.next_action_code == 'retry_inventory_preparation':
|
||||
return
|
||||
if (
|
||||
(
|
||||
next_gate.next_action_code in {'retry_inventory_matching'}
|
||||
@@ -912,6 +1039,14 @@ def sync_gate_from_business_result(
|
||||
"""
|
||||
key = str(idempotency_key or '').strip() or f'sync:{execution_no}:{gate_code}:{uuid.uuid4().hex}'
|
||||
execution = _locked_execution(execution_no)
|
||||
# [STEP] CandidateSet 重冻结后旧 Execution 仅保留审计价值。任何迟到的
|
||||
# 回调、Worker 或业务同步都不能再写入其 Gate,否则历史链会重新覆盖实时阶段。
|
||||
if str(execution.status or '').strip().lower() == 'superseded':
|
||||
raise ConflictError(
|
||||
'Superseded process execution cannot accept business results',
|
||||
code='SHIPPING.PROCESS_EXECUTION_SUPERSEDED',
|
||||
details={'execution_no': execution.execution_no},
|
||||
)
|
||||
gate = _locked_gate(execution=execution, gate_code=gate_code)
|
||||
|
||||
# [STEP] Gate Worker 执行器可能在当前 Attempt 内同步最新业务事实。
|
||||
|
||||
@@ -51,7 +51,7 @@ def record_projection_inconsistency_audit(payload: dict[str, Any]) -> None:
|
||||
review_case_no=str(payload.get('case_no') or '').strip() or None,
|
||||
conversation_id=str(payload.get('conversation_id') or '').strip() or None,
|
||||
actor_type='system',
|
||||
result='blocked',
|
||||
result='failure',
|
||||
error_code=PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
reason_code=PROJECTION_INCONSISTENT_ERROR_CODE,
|
||||
reason='shipping_notice_no present with pre-create stage',
|
||||
@@ -165,7 +165,7 @@ def assert_notice_task_ownership(
|
||||
review_case_no=expect_case,
|
||||
actor_type='user' if actor_id is not None else 'system',
|
||||
actor_id=actor_id,
|
||||
result='blocked',
|
||||
result='failure',
|
||||
error_code=TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
|
||||
reason_code=TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
|
||||
reason='formal notice does not belong to current case/run/order task',
|
||||
|
||||
@@ -496,6 +496,13 @@ def reconcile_processing_projection_facts(
|
||||
# inventory_matching/running,但 Gate 已经进入 Excel 或上传节点;先把统一
|
||||
# 投影游标对齐 Gate,禁止旧 primary_action 继续生成 match_inventory。
|
||||
gate_stage = {
|
||||
# 正式 20-Gate 进入履约后,兼容 OT 字段可能尚未被旧写路径同步。
|
||||
# 读投影必须以 Gate 统一覆盖,避免历史 waiting_review 重新污染批次中心。
|
||||
'inventory_source_routing': 'inventory_source_resolving',
|
||||
'inventory_preparation': 'inventory_fetching',
|
||||
'inventory_field_mapping': 'inventory_fetching',
|
||||
'inventory_matching': 'inventory_matching',
|
||||
'inventory_sufficiency': 'inventory_matching',
|
||||
'excel_readiness': 'excel_generating',
|
||||
'artifact_generation': 'excel_generating',
|
||||
'freight_upload_rpa': 'freight_uploading',
|
||||
@@ -811,12 +818,19 @@ def apply_user_projection_fields(
|
||||
|
||||
# ===== [STEP 6] 计算 blocking_reason: {code, i18n_key, details} 或 None =====
|
||||
_REASON_TO_I18N_KEY: dict[str, str] = {
|
||||
# 批次中心与订单生命周期工作台共用 chat 文案域,避免把内部原因码裸露给用户。
|
||||
'generic_extraction_disabled': 'chat.shippingProcessing.reasonCode.generic_extraction_disabled',
|
||||
'inventory_file_missing': 'chat.shippingProcessing.reasonCode.inventory_file_missing',
|
||||
'inventory_match_failed': 'chat.shippingProcessing.reasonCode.inventory_match_failed',
|
||||
'inventory_preparation_failed': 'chat.shippingProcessing.reasonCode.inventory_preparation_failed',
|
||||
'manual_upload_pending': 'chat.shippingProcessing.reasonCode.manual_upload_pending',
|
||||
'inventory_source_unstable': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
|
||||
'inventory_snapshot_missing': 'workspace.shippingNotice.processGate.reasons.inventory_file_missing',
|
||||
'inventory_match_incomplete': 'workspace.shippingNotice.processGate.reasons.inventory_match_failed',
|
||||
'inventory_source_candidates_need_human': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
|
||||
'upload_rpa_failed': 'workspace.shippingNotice.processGate.reasons.upload_rpa_failed',
|
||||
'inventory_shortage': 'workspace.shippingNotice.processGate.reasons.inventory_insufficient',
|
||||
'inventory_shortage_review_required': 'workspace.shippingNotice.processGate.reasons.inventory_shortage_review_required',
|
||||
'inventory_source_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_source_conflicted',
|
||||
'inventory_source_unresolved': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
|
||||
'inventory_multi_file_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_multi_file_conflict',
|
||||
@@ -924,6 +938,7 @@ def apply_user_projection_fields(
|
||||
_ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = {
|
||||
'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules',
|
||||
'retry_inventory_preparation': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_preparation',
|
||||
'retry_inventory_matching': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_matching',
|
||||
'open_inventory_source_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_source_review',
|
||||
'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review',
|
||||
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
|
||||
|
||||
@@ -700,6 +700,7 @@ def _sync_process_gates_after_progress(task: Any, payload: dict[str, Any]) -> No
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -131,6 +131,27 @@ _REVIEW_CASE_STATUS_TODO: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[str, str]]:
|
||||
"""裁决建单前 Review Case 的生命周期查看入口。
|
||||
|
||||
只有关联当前有效订单 Candidate 的 Case 才能进入订单生命周期工作台;空 Case、
|
||||
已替代 Candidate 与拒绝/过期 Candidate 仍是解析或处置对象,不能因待办列表存在
|
||||
而获得订单复核、库存准备或通知完成入口。
|
||||
"""
|
||||
candidate = (
|
||||
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
|
||||
if case.candidate_id is not None
|
||||
else None
|
||||
)
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
if not is_current_reviewable_candidate(candidate):
|
||||
return []
|
||||
from app.services.shipping_notice.lifecycle_projection import lifecycle_entries
|
||||
|
||||
return lifecycle_entries(lifecycle_stage='order_review', has_candidate_context=True)
|
||||
|
||||
|
||||
class TaskProjection(str, Enum):
|
||||
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
|
||||
|
||||
@@ -1318,6 +1339,7 @@ def serialize_review_case_todo(
|
||||
del is_admin
|
||||
run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None
|
||||
document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None
|
||||
lifecycle_entries = _review_case_lifecycle_entries(case)
|
||||
source_name = None
|
||||
if document is not None:
|
||||
source_name = str(getattr(document, "filename", None) or "").strip() or None
|
||||
@@ -1376,6 +1398,10 @@ def serialize_review_case_todo(
|
||||
"created_at": case.created_at.isoformat() if case.created_at else None,
|
||||
"ui_state": {
|
||||
"stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4},
|
||||
# [AUTHORITY] 任务中心、批次中心和工作台均消费该入口;禁止前端按 Case
|
||||
# 状态或待办类别补造订单复核权限。
|
||||
"lifecycle_stage": "order_review" if lifecycle_entries else None,
|
||||
"lifecycle_entries": lifecycle_entries,
|
||||
"checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"},
|
||||
"todo": {"title": current_todo, "message": current_todo},
|
||||
"actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []},
|
||||
@@ -1539,6 +1565,9 @@ def serialize_intake_todo(
|
||||
"created_at": intake.created_at.isoformat() if intake.created_at else None,
|
||||
"ui_state": {
|
||||
"stage": {"code": "intake_parse", "label": "接收解析", "index": 1, "total": 4},
|
||||
# Intake 尚未有当前有效订单 Candidate;只能进入对话查看解析,不能进入生命周期工作台。
|
||||
"lifecycle_stage": "intake_parse",
|
||||
"lifecycle_entries": [],
|
||||
"checkpoint": {"code": "order_field_extraction", "kind": str(
|
||||
CheckpointKind.MUST_HUMAN if failed else CheckpointKind.AUTO_CONTINUE
|
||||
), "label": "订单解析"},
|
||||
|
||||
@@ -224,7 +224,9 @@ def claim_next_shipping_notice_job() -> Job | None:
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
JobType.SHIPPING_DOCUMENT_LAYOUT,
|
||||
JobType.SHIPPING_PROCESS_GATE,
|
||||
JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS,
|
||||
JobType.SHIPPING_AUTO_PROGRESS,
|
||||
JobType.SHIPPING_PDF_AUTOMARK,
|
||||
JobType.SHIPPING_XFA_OCR_AUTOMARK,
|
||||
JobType.SHIPPING_STP_AUTO_CREATE,
|
||||
JobType.SHIPPING_LINE_AUTO_FULFILL,
|
||||
|
||||
@@ -39,6 +39,7 @@ from datetime import datetime, timezone
|
||||
from typing import Any, Literal, TypedDict
|
||||
|
||||
from app.models import (
|
||||
ShippingProcessExecution,
|
||||
ShippingOrderReviewCase,
|
||||
User,
|
||||
)
|
||||
@@ -85,7 +86,7 @@ REVIEW_DOMAIN_ACTION_CODES: frozenset[str] = frozenset({
|
||||
'create_draft', 'edit_draft', 'validate',
|
||||
'retry_stp_auto_create',
|
||||
'reconcile_and_progress',
|
||||
'adjudicate_duplicate',
|
||||
'resolve_field_conflicts', 'adjudicate_duplicate',
|
||||
'create_revision', 'force_create', 'reuse_existing', 'adjudicate',
|
||||
'open_order_review', 'open_profile_review',
|
||||
'mark_non_order', 'mark_quality_issue', 'reparse',
|
||||
@@ -404,9 +405,11 @@ def project_case_allowed_actions(
|
||||
return actions
|
||||
if case.status == 'reparse_pending':
|
||||
return ['view']
|
||||
# 替代 PDF 的写入资格由 disposition service 的 Case 状态裁决,独立于
|
||||
# mark_quality_issue;统一投影必须下发独立动作,供各页面一致消费。
|
||||
if case.status == 'quality_issue':
|
||||
return ['view', 'mark_quality_issue', 'reparse']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'validate']
|
||||
return ['view', 'mark_quality_issue', 'reparse', 'upload_replacement']
|
||||
actions = ['view', 'mark_non_order', 'mark_quality_issue', 'reparse', 'upload_replacement', 'validate']
|
||||
if case.candidate_id is None and case.disposition != 'manual_order':
|
||||
actions.append('create_draft')
|
||||
else:
|
||||
@@ -555,6 +558,103 @@ def project_case_current_gate(
|
||||
)
|
||||
|
||||
|
||||
def _project_case_formal_gate_summary(
|
||||
case: ShippingOrderReviewCase,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
读取 Case 绑定的正式 ProcessExecution 用户态摘要。
|
||||
|
||||
Case 草稿、STP Job 仅描述复核上下文;当前业务阶段、人工阻断与恢复动作
|
||||
必须由 ProcessExecution Gate 裁决。本函数让所有 Case bundle 消费方使用
|
||||
与批次中心完全相同的正式 Gate 读模型,而不是在各投影端重建状态。
|
||||
"""
|
||||
case_id = getattr(case, 'id', None)
|
||||
if case_id is None:
|
||||
return None
|
||||
from flask import has_app_context
|
||||
|
||||
if not has_app_context():
|
||||
# 纯投影契约测试与离线诊断没有 Flask application context;此时没有可读
|
||||
# 的持久化 Execution,保持原有 Case 派生事实即可。
|
||||
return None
|
||||
execution = (
|
||||
ShippingProcessExecution.query.filter_by(review_case_id=int(case_id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
if execution is None:
|
||||
return None
|
||||
from app.services.shipping_notice.process_gate_projection import project_user_gate_summary
|
||||
|
||||
summary = project_user_gate_summary(execution)
|
||||
current = summary.get('current_blocking_gate') or summary.get('current_gate')
|
||||
return summary if isinstance(current, dict) and current.get('gate_code') else None
|
||||
|
||||
|
||||
def _project_case_formal_gate_facts(
|
||||
summary: dict[str, Any] | None,
|
||||
) -> tuple[CurrentGate, BlockingReason, UserStatus] | None:
|
||||
"""
|
||||
将正式 Gate 摘要归一化为 Case bundle 的三项用户事实。
|
||||
|
||||
正式 Execution 存在时,Gate 事实必须覆盖 Case 的历史阻断:
|
||||
只有已入队/运行或等待外部回执才表示系统正在推进;建单前的订单冻结
|
||||
校验仍需用户从编辑区提交,不能因 ``pending`` 误显示为系统处理中。
|
||||
"""
|
||||
if not isinstance(summary, dict):
|
||||
return None
|
||||
current = summary.get('current_blocking_gate') or summary.get('current_gate')
|
||||
if not isinstance(current, dict):
|
||||
return None
|
||||
gate_code = str(current.get('gate_code') or '').strip()
|
||||
if not gate_code:
|
||||
return None
|
||||
gate_status = str(current.get('status') or '').strip().lower()
|
||||
reason_code = str(
|
||||
summary.get('blocking_reason_code')
|
||||
or current.get('blocking_reason_code')
|
||||
or ''
|
||||
).strip() or None
|
||||
raw_details = (
|
||||
(summary.get('explainability') or {}).get('details')
|
||||
if isinstance(summary.get('explainability'), dict)
|
||||
else None
|
||||
)
|
||||
details = raw_details if isinstance(raw_details, dict) else None
|
||||
blocking_reason = BlockingReason(
|
||||
code=reason_code,
|
||||
i18n_key=_REASON_TO_I18N_KEY.get(reason_code, 'shipping.review.blocked_generic') if reason_code else None,
|
||||
details=details,
|
||||
)
|
||||
current_gate = CurrentGate(
|
||||
gate_code=gate_code,
|
||||
next_action_code=(
|
||||
str(summary.get('next_action_code') or current.get('next_action_code') or '').strip()
|
||||
or None
|
||||
),
|
||||
blocking_reason_code=reason_code,
|
||||
)
|
||||
if gate_code == 'order_freeze_readiness' and gate_status == 'pending':
|
||||
# 保存并校验是订单编辑区底栏唯一提交入口;这里仅输出交接状态,
|
||||
# 不创建右栏 CTA,也不把尚未提交的校验伪装为已开始的自动任务。
|
||||
blocking_reason = BlockingReason(code=None, i18n_key=None, details=None)
|
||||
user_status: UserStatus = 'waiting_human'
|
||||
elif gate_status in {'pending', 'queued', 'running', 'waiting_external'}:
|
||||
# 没有人工阻断时仅投影系统推进态;下一步文案由前端状态映射给出。
|
||||
blocking_reason = BlockingReason(code=None, i18n_key=None, details=None)
|
||||
user_status: UserStatus = 'running'
|
||||
elif gate_status == 'blocked_manual':
|
||||
user_status: UserStatus = 'waiting_human'
|
||||
elif gate_status in {'blocked_retryable', 'invalidated'}:
|
||||
user_status = 'retryable'
|
||||
elif gate_status == 'failed_terminal':
|
||||
user_status = 'failed'
|
||||
else:
|
||||
return None
|
||||
return current_gate, blocking_reason, user_status
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [4] blocking_reason(code/i18n_key/details)
|
||||
# ============================================================
|
||||
@@ -711,31 +811,25 @@ def project_case_primary_action(
|
||||
return {'code': 'open_order_review', 'variant': 'warning',
|
||||
'label_key': 'shipping.actions.open_order_review'}
|
||||
|
||||
# 1f: waiting_human → edit_draft / validate
|
||||
# 1f: 草稿编辑和保存校验分别属于主编辑区与底栏,不得升级为当前任务 CTA。
|
||||
if user_status == 'waiting_human':
|
||||
if 'edit_draft' in actions:
|
||||
return {'code': 'edit_draft', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.edit_draft'}
|
||||
if 'validate' in actions:
|
||||
return {'code': 'validate', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.validate'}
|
||||
return None
|
||||
|
||||
# 1g: idle → 有 create_draft 优先(首次打开草稿面板 CTA)
|
||||
if user_status == 'idle':
|
||||
if 'create_draft' in actions:
|
||||
return {'code': 'create_draft', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.create_draft'}
|
||||
return None
|
||||
if 'edit_draft' in actions:
|
||||
return {'code': 'edit_draft', 'variant': 'primary',
|
||||
'label_key': 'shipping.actions.edit_draft'}
|
||||
return None
|
||||
|
||||
# 1h: running/queued → 次优先 view(但 edit_draft 仍然允许)
|
||||
if user_status == 'running' and 'edit_draft' in actions:
|
||||
return {'code': 'edit_draft', 'variant': 'default',
|
||||
'label_key': 'shipping.actions.edit_draft'}
|
||||
return None
|
||||
|
||||
# 1i: 兜底 — 按 _PRIMARY_ACTION_ORDER 优先级取第一个命中的动作码
|
||||
for code in _PRIMARY_ACTION_ORDER:
|
||||
if code in {'edit_draft', 'create_draft', 'validate'}:
|
||||
continue
|
||||
if code in actions:
|
||||
variant = 'default'
|
||||
if code in ('reconcile_and_progress', 'create_draft', 'retry_stp_auto_create'):
|
||||
@@ -1067,6 +1161,14 @@ def project_review_case_projection_bundle(
|
||||
blocking_reason = project_case_blocking_reason(automation)
|
||||
# [STEP 5] user_status
|
||||
user_status = project_case_user_status(case, automation)
|
||||
# [STEP 5.1] 已持久化的正式 Gate 是实时状态唯一裁决源。此前这里用 Case
|
||||
# 草稿状态重算 order_review_build/idle,会覆盖批次投影已读取的
|
||||
# field_completeness / required_field_missing,造成同一文件前后端状态冲突。
|
||||
formal_gate_facts = _project_case_formal_gate_facts(
|
||||
_project_case_formal_gate_summary(case),
|
||||
)
|
||||
if formal_gate_facts is not None:
|
||||
current_gate, blocking_reason, user_status = formal_gate_facts
|
||||
# [STEP 6] primary_action
|
||||
# 建单前 STP 已失败时,主操作的阶段必须随失败事实停在 pre_ot_stp;
|
||||
# 不能因 Case 仍为 ready 回退到 customer_resolution/order_review 的展示语义。
|
||||
|
||||
@@ -786,6 +786,19 @@ def reconcile_and_progress(
|
||||
# 用 case_after 替换引用,防止后续审计写入已失效对象。
|
||||
case = case_after
|
||||
user = db.session.get(User, int(user_id))
|
||||
# 归属 L3 歧义不是可继续处理的业务结果:调用方若收到普通 200 outcome,
|
||||
# 仍可能继续执行后续复用/推进。回滚与敏感审计完成后必须硬隔离,要求
|
||||
# 用户回到人工裁决面,而不是把不确定归属投影成可操作阶段。
|
||||
raise ValidationError(
|
||||
'Ambiguous task ownership requires manual adjudication',
|
||||
code='SHIPPING.RECONCILE_OWNERSHIP_ANOMALY',
|
||||
details={
|
||||
'hard_isolation': True,
|
||||
'case_no': str(case_after.case_no),
|
||||
'match': match_result,
|
||||
'user_action': user_action,
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 5] 写审计 + 幂等持久化(CaseEvent 保证下一次同 operation_id 可回返)
|
||||
_write_reconcile_audit_and_event(
|
||||
|
||||
@@ -47,6 +47,11 @@ from app.services.shipping_notice.processing_projection_invariants import (
|
||||
from app.services.shipping_notice.processing_ownership import (
|
||||
record_projection_inconsistency_audit,
|
||||
)
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGE_RANGES,
|
||||
project_lifecycle,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import resolve_task_export_download
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
DIRECT_PDF_ALLOWED_STAGES,
|
||||
ORDER_INTAKE_SOURCE_TYPES,
|
||||
@@ -441,7 +446,11 @@ def _intake_source_summary(
|
||||
|
||||
candidate_count = (
|
||||
db.session.query(ShippingOrderCandidate.id)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake.id))
|
||||
.filter(
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')),
|
||||
)
|
||||
.count()
|
||||
)
|
||||
subject = str(email.get('subject') or '').strip() or None
|
||||
@@ -629,11 +638,37 @@ def project_intake_work_item(
|
||||
}),
|
||||
'upload_states': sorted(set(upload_states)),
|
||||
}
|
||||
payload['user_group'] = (
|
||||
'failed' if status in {'failed', 'blocked'}
|
||||
else 'waiting_human' if status in {'waiting_human', 'waiting_review'}
|
||||
else 'processing'
|
||||
)
|
||||
# EML 根卡只汇总子文件的正式裁决;不能保留 Intake 的旧解析阶段,
|
||||
# 否则候选已落为 Review Case 仍会被父卡投影成“接收解析中”。
|
||||
if aggregate_states:
|
||||
if any(state in {'failed', 'retryable'} for state in aggregate_states):
|
||||
payload['user_status'] = 'failed'
|
||||
payload['user_group'] = 'failed'
|
||||
elif any(state in {'waiting_human', 'idle'} for state in aggregate_states):
|
||||
payload['user_status'] = 'waiting_human'
|
||||
payload['user_group'] = 'waiting_human'
|
||||
elif all(state == 'completed' for state in aggregate_states):
|
||||
payload['user_status'] = 'completed'
|
||||
payload['user_group'] = 'completed'
|
||||
else:
|
||||
payload['user_status'] = 'running'
|
||||
payload['user_group'] = 'processing'
|
||||
representative = next(
|
||||
(child for child in aggregate_children if str(child.get('user_status') or '') in {'failed', 'retryable', 'waiting_human', 'idle'}),
|
||||
aggregate_children[0],
|
||||
)
|
||||
payload['user_stage'] = str(representative.get('user_stage') or representative.get('stage') or payload.get('user_stage') or '')
|
||||
payload['stage'] = payload['user_stage']
|
||||
payload['current_gate'] = representative.get('current_gate')
|
||||
payload['blocking_reason'] = representative.get('blocking_reason')
|
||||
payload['primary_action'] = representative.get('primary_action')
|
||||
payload['available_actions'] = list(representative.get('available_actions') or [])
|
||||
if not (source_type == 'eml' and payload.get('aggregate_children')):
|
||||
payload['user_group'] = (
|
||||
'failed' if status in {'failed', 'blocked'}
|
||||
else 'waiting_human' if status in {'waiting_human', 'waiting_review'}
|
||||
else 'processing'
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
@@ -818,17 +853,28 @@ def _order_task_source_summary(
|
||||
"""
|
||||
run_candidate_count = (
|
||||
db.session.query(ShippingOrderCandidate.id)
|
||||
.filter(ShippingOrderCandidate.order_extraction_run_id == int(run.id))
|
||||
.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')),
|
||||
)
|
||||
.count()
|
||||
)
|
||||
candidate: ShippingOrderCandidate | None = None
|
||||
if order_task is not None and order_task.candidate_id:
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(order_task.candidate_id))
|
||||
if candidate is None:
|
||||
# 已替代 Candidate 仅供审计。旧 OT 不得借同 Run 的新候选重新获得另一 PDF
|
||||
# 的生命周期上下文或按钮。
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
if not is_current_reviewable_candidate(candidate):
|
||||
candidate = None
|
||||
if candidate is None and (order_task is None or not order_task.candidate_id):
|
||||
candidate = (
|
||||
ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderCandidate.candidate_status.in_(('provisional', 'accepted')),
|
||||
)
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.first()
|
||||
@@ -870,6 +916,7 @@ def _order_task_source_summary(
|
||||
parsed_document_count = 1 if str(task_document.parse_status or '') == 'parsed' else 0
|
||||
candidate_count = 1
|
||||
document_id = int(task_document.id)
|
||||
content_hash = str(task_document.content_hash or '').strip().lower() or None
|
||||
else:
|
||||
parsed_document_count = 0
|
||||
if intake_ids:
|
||||
@@ -883,13 +930,17 @@ def _order_task_source_summary(
|
||||
.count()
|
||||
)
|
||||
task_document_count = int(document_count)
|
||||
candidate_count = int(run_candidate_count)
|
||||
# OT 已绑定但 Candidate 已被替代时,不能把同 Run 的当前候选借给它。
|
||||
# 该 OT 只保留历史审计信息;生命周期入口必须关闭。
|
||||
candidate_count = 0 if (order_task is not None and order_task.candidate_id) else int(run_candidate_count)
|
||||
document_id = None
|
||||
content_hash = None
|
||||
|
||||
return {
|
||||
'email_subject': None,
|
||||
'filename': filename,
|
||||
'document_id': document_id,
|
||||
'content_hash': content_hash,
|
||||
'document_count': task_document_count,
|
||||
'parsed_document_count': int(parsed_document_count),
|
||||
'candidate_count': int(candidate_count),
|
||||
@@ -928,29 +979,31 @@ def _order_task_current_gate(
|
||||
Returns:
|
||||
ProcessGateSummary 形状 dict;无需门禁时 None。
|
||||
"""
|
||||
# Child OT 必须先按自身 Candidate 找 Case;仅按 run_id 取最新 Case 会把
|
||||
# 多 PDF 的子订单阶段错误绑定到根 PDF。
|
||||
# 每个已绑定 Candidate 的 OT(包括根 OT)都必须先按自身 Candidate 找 Case;
|
||||
# 仅按 run_id 取最新 Case 会把多 PDF 或已替代根 OT 的阶段错误绑定到另一份 PDF。
|
||||
# 只有尚未绑定 Candidate 的兼容 OT 才能按 Run 回退查找。
|
||||
open_case = None
|
||||
is_child_order_task = bool(
|
||||
order_task is not None
|
||||
and getattr(order_task, 'candidate_id', None)
|
||||
and str(getattr(order_task, 'task_no', '') or '').strip()
|
||||
!= str(getattr(run, 'user_task_no', '') or '').strip()
|
||||
)
|
||||
if is_child_order_task:
|
||||
if order_task is not None and getattr(order_task, 'candidate_id', None):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.query.join(
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidate.id == ShippingOrderReviewCase.candidate_id,
|
||||
).filter(
|
||||
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is None:
|
||||
if open_case is None and not (
|
||||
order_task is not None and getattr(order_task, 'candidate_id', None)
|
||||
):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.candidate_id.isnot(None),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
@@ -965,6 +1018,7 @@ def _order_task_current_gate(
|
||||
|
||||
execution = (
|
||||
ShippingProcessExecution.query.filter_by(review_case_id=int(open_case.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
@@ -1007,7 +1061,10 @@ def _order_task_current_gate(
|
||||
active_execution_id = getattr(notice, 'active_process_execution_id', None)
|
||||
if active_execution_id is not None:
|
||||
execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
|
||||
if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(notice.id):
|
||||
if execution is not None and (
|
||||
int(getattr(execution, 'task_id', 0) or 0) != int(notice.id)
|
||||
or str(getattr(execution, 'status', '') or '').strip().lower() == 'superseded'
|
||||
):
|
||||
execution = None
|
||||
if execution is None:
|
||||
execution = (
|
||||
@@ -1196,7 +1253,8 @@ def _project_order_task_work_item(
|
||||
from app.models import ShippingProcessExecution
|
||||
active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
|
||||
active_gate = str(getattr(active_execution, 'current_gate_code', '') or '').strip().lower()
|
||||
if active_gate in SHIPPING_PROCESSING_STAGES:
|
||||
active_status = str(getattr(active_execution, 'status', '') or '').strip().lower()
|
||||
if active_status != 'superseded' and active_gate in SHIPPING_PROCESSING_STAGES:
|
||||
stage = active_gate
|
||||
stage_label_key = active_gate
|
||||
# order_creating 无共享投影时仍统一用户文案键。
|
||||
@@ -1262,18 +1320,27 @@ def _project_order_task_work_item(
|
||||
open_case = None
|
||||
if order_task is not None and getattr(order_task, 'candidate_id', None):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.query.join(
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidate.id == ShippingOrderReviewCase.candidate_id,
|
||||
).filter(
|
||||
ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_case is None:
|
||||
# 已绑定 Candidate 的 OT 不得借同 Run 的另一 Case 补阶段;这会使历史根 OT
|
||||
# 重新获得当前 PDF 的 Gate、生命周期入口和操作权限。
|
||||
if open_case is None and not (
|
||||
order_task is not None and getattr(order_task, 'candidate_id', None)
|
||||
):
|
||||
open_case = (
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.candidate_id.isnot(None),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')),
|
||||
ShippingOrderReviewCase.confirmed_task_id.is_(None),
|
||||
)
|
||||
@@ -1394,20 +1461,39 @@ def _project_order_task_work_item(
|
||||
child['stage'] = 'order_creating'
|
||||
child['stage_label_key'] = 'order_creating'
|
||||
child['legacy_stage'] = 'order_creating'
|
||||
formal_gate_projection = isinstance(payload.get('current_gate'), dict) and bool(
|
||||
str((payload.get('current_gate') or {}).get('gate_code') or '').strip()
|
||||
)
|
||||
# 六字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions / retryable
|
||||
if isinstance(bundle.get('user_status'), str):
|
||||
payload['user_status'] = bundle['user_status']
|
||||
if isinstance(bundle.get('blocking_reason'), dict):
|
||||
payload['blocking_reason'] = dict(bundle['blocking_reason'])
|
||||
if isinstance(bundle.get('primary_action'), dict) and (pre_ot_stp or not formal_gate_projection):
|
||||
payload['primary_action'] = dict(bundle['primary_action'])
|
||||
if isinstance(bundle.get('current_gate'), dict) and (pre_ot_stp or not formal_gate_projection):
|
||||
current_gate = dict(payload.get('current_gate') or {})
|
||||
current_gate.update(bundle['current_gate'])
|
||||
payload['current_gate'] = current_gate
|
||||
if isinstance(bundle.get('user_stage'), str):
|
||||
# 未确认 Case 的正式阶段只能由 Review bundle 给出;旧 OT.stage
|
||||
# 仍可能是 document_parsing/customer_resolving,不能在读路径回退阶段。
|
||||
payload['user_stage'] = bundle['user_stage']
|
||||
if isinstance(bundle.get('user_current_gate_code'), str):
|
||||
payload['user_current_gate_code'] = bundle['user_current_gate_code']
|
||||
# Case bundle 必须能够显式清空旧阻断,不能仅在有新 reason 时覆盖;
|
||||
# 否则字段冲突已裁决后,右栏仍会显示“字段存在冲突”。
|
||||
bundle_blocking_reason = bundle.get('blocking_reason')
|
||||
payload['blocking_reason'] = (
|
||||
dict(bundle_blocking_reason)
|
||||
if isinstance(bundle_blocking_reason, dict)
|
||||
else None
|
||||
)
|
||||
# 未确认 Review Case 是建单前用户动作的唯一事实源。即使旧 OT 留有正式 Gate,
|
||||
# 也必须用最新 bundle 显式覆盖(包括 None),否则已解决字段冲突仍会显示旧裁决按钮。
|
||||
bundle_primary_action = bundle.get('primary_action')
|
||||
payload['primary_action'] = (
|
||||
dict(bundle_primary_action)
|
||||
if isinstance(bundle_primary_action, dict)
|
||||
else None
|
||||
)
|
||||
# 同一 Case 的 Gate 也是完整展示事实;禁止与 OT 历史 Gate 合并,
|
||||
# 以免残留 field_conflict_resolution / resolve_field_conflicts。
|
||||
bundle_current_gate = bundle.get('current_gate')
|
||||
payload['current_gate'] = (
|
||||
dict(bundle_current_gate)
|
||||
if isinstance(bundle_current_gate, dict)
|
||||
else None
|
||||
)
|
||||
if isinstance(bundle.get('available_actions'), list):
|
||||
old_actions = list(payload.get('available_actions') or [])
|
||||
keep_notice_side = [a for a in old_actions if a not in REVIEW_DOMAIN_ACTION_CODES]
|
||||
@@ -1679,7 +1765,7 @@ def _eml_aggregate_user_group(
|
||||
"""按用户关注优先级确定一张 EML Intake 卡的唯一分组。"""
|
||||
if any(state in {'failed', 'retryable'} for state in states):
|
||||
return 'failed'
|
||||
if any(state == 'waiting_human' for state in states):
|
||||
if any(state in {'waiting_human', 'idle'} for state in states):
|
||||
return 'waiting_human'
|
||||
if any(state not in {'completed', 'cancelled'} for state in states):
|
||||
return 'processing'
|
||||
@@ -1717,7 +1803,7 @@ def _eml_aggregate_document_children(
|
||||
"""
|
||||
if intake is None:
|
||||
return [
|
||||
{**child, 'ui_state': _processing_ui_state_from_item(child)}
|
||||
_with_processing_ui_state(child)
|
||||
for child in order_task_children
|
||||
]
|
||||
|
||||
@@ -1731,7 +1817,7 @@ def _eml_aggregate_document_children(
|
||||
)
|
||||
if not documents:
|
||||
return [
|
||||
{**child, 'ui_state': _processing_ui_state_from_item(child)}
|
||||
_with_processing_ui_state(child)
|
||||
for child in order_task_children
|
||||
]
|
||||
|
||||
@@ -1764,10 +1850,60 @@ def _eml_aggregate_document_children(
|
||||
str(unit.reason_code or unit.error_code or 'unit_review_required').strip()
|
||||
if review_required and unit is not None else None
|
||||
)
|
||||
# Case 是候选落库后的正式人工阶段事实;Unit 保留 candidate_ready 不能让
|
||||
# EML 聚合退回「接收解析」。终态 Case 不再提供复核入口。
|
||||
review_case = (
|
||||
ShippingOrderReviewCase.query.filter_by(unit_id=int(unit.id)).one_or_none()
|
||||
if review_required and unit is not None else None
|
||||
ShippingOrderReviewCase.query.filter(
|
||||
ShippingOrderReviewCase.unit_id == int(unit.id),
|
||||
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')),
|
||||
).one_or_none()
|
||||
if unit is not None else None
|
||||
)
|
||||
review_required = review_required or review_case is not None
|
||||
review_bundle: dict[str, Any] | None = None
|
||||
if review_case is not None:
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
draft = getattr(review_case, 'current_draft', None)
|
||||
validation = (
|
||||
dict(draft.validation_result_json or {})
|
||||
if draft is not None and isinstance(draft.validation_result_json, dict)
|
||||
else None
|
||||
)
|
||||
review_bundle = project_review_case_projection_bundle(
|
||||
review_case, validation=validation, post_confirm=None, is_admin=False,
|
||||
)
|
||||
# Case 只是人工处置容器,不等于已生成订单候选。空 Candidate Case 必须
|
||||
# 保留解析链路的 Gate/阶段,禁止从 Review Bundle 继承旧的订单复核事实。
|
||||
review_candidate = (
|
||||
db.session.get(ShippingOrderCandidate, int(review_case.candidate_id))
|
||||
if review_case is not None and review_case.candidate_id is not None
|
||||
else None
|
||||
)
|
||||
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
|
||||
|
||||
has_current_candidate = bool(
|
||||
is_current_reviewable_candidate(review_candidate)
|
||||
and int(getattr(review_candidate, 'primary_document_id', 0) or 0) == int(document.id)
|
||||
)
|
||||
review_status = str((review_bundle or {}).get('user_status') or 'waiting_human')
|
||||
review_stage = str((review_bundle or {}).get('user_stage') or 'order_review')
|
||||
review_gate = (review_bundle or {}).get('current_gate')
|
||||
review_reason = (review_bundle or {}).get('blocking_reason')
|
||||
review_primary = (review_bundle or {}).get('primary_action')
|
||||
review_actions = list((review_bundle or {}).get('available_actions') or [])
|
||||
if review_case is not None and not has_current_candidate:
|
||||
review_stage = 'intake_parse'
|
||||
review_gate = _intake_current_gate(intake)
|
||||
review_reason = None
|
||||
review_primary = {
|
||||
'code': 'open_order_review',
|
||||
'variant': 'primary',
|
||||
'label_key': 'shipping.actions.open_order_review',
|
||||
}
|
||||
review_actions = ['open_order_review']
|
||||
run = db.session.get(ShippingOrderProcessingRun, int(review_case.run_id)) if review_case is not None else None
|
||||
leaf = {
|
||||
'work_item_type': 'document',
|
||||
@@ -1784,35 +1920,66 @@ def _eml_aggregate_document_children(
|
||||
'submission_no': '',
|
||||
'intake_no': str(intake.intake_no),
|
||||
'status': 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing',
|
||||
'stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'stage_label_key': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'stage': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
|
||||
'stage_label_key': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
|
||||
'progress_version': int(getattr(intake, 'progress_version', None) or 1),
|
||||
'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '',
|
||||
'current_gate': None,
|
||||
'available_actions': ['open_order_review'] if review_case is not None else [],
|
||||
'current_gate': review_gate if review_case is not None else None,
|
||||
'available_actions': review_actions if review_case is not None else [],
|
||||
'blocking_reason': (
|
||||
{'code': failure_reason_code, 'details': {}}
|
||||
if unit_failed else
|
||||
{'code': review_reason_code, 'details': {}}
|
||||
if review_required else None
|
||||
review_reason if review_case is not None else
|
||||
{'code': review_reason_code, 'details': {}} if review_required else None
|
||||
),
|
||||
'primary_action': {'code': 'open_order_review'} if review_case is not None else None,
|
||||
'user_status': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'running',
|
||||
'user_stage': 'document_parsing' if (failed or unit_failed) else 'waiting_review' if review_required else 'candidate_creating',
|
||||
'primary_action': review_primary if review_case is not None else None,
|
||||
'user_status': 'failed' if (failed or unit_failed) else review_status if review_case is not None else 'waiting_human' if review_required else 'running',
|
||||
'user_stage': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
|
||||
'user_group': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing',
|
||||
'facts': {'upload_state': 'not_created'},
|
||||
# 与 Case summary 同义:无 Candidate 的解析处置可进入独立接收解析面,
|
||||
# 但 lifecycle_entries 仍保持空,绝不能视为订单生命周期授权。
|
||||
'intake_parse_authorized': bool(review_case is not None and not has_current_candidate),
|
||||
'child_order_tasks': [],
|
||||
}
|
||||
summary = {}
|
||||
summary.update({
|
||||
'document_id': int(document.id),
|
||||
# 跨 Run 重识别可能产生新 document_id;内容哈希是批次统计的稳定文件身份。
|
||||
'content_hash': str(document.content_hash or '').strip().lower() or None,
|
||||
'filename': str(document.filename or '').strip() or None,
|
||||
'document_count': 1,
|
||||
'parsed_document_count': 1 if str(document.parse_status or '').strip().lower() == 'parsed' else 0,
|
||||
})
|
||||
# [AUTHORITY] EML 建单前叶子没有 OT 摘要可回填 Candidate。只有 Review Case
|
||||
# 关联的当前有效 Candidate,且其主文档就是本 PDF,才能开放生命周期入口;
|
||||
# 同一邮件的兄弟附件绝不能借此获得订单复核权限。
|
||||
if existing is None:
|
||||
summary['candidate_count'] = int(
|
||||
has_current_candidate
|
||||
)
|
||||
leaf['source_summary'] = summary
|
||||
leaf['ui_state'] = _processing_ui_state_from_item(leaf)
|
||||
result.append(leaf)
|
||||
# 有/无预建 OT 的 EML 附件都在这里汇合。批次中心的文件级主动作只能
|
||||
# 是生命周期入口;create/edit/validate 是 Case 内部处置,必须在工作台内
|
||||
# 呈现。只保留正式 Process Gate 的主动作;Case 内部码(例如
|
||||
# order_review_build)即使带 next_action 也不能夺走批次入口。
|
||||
leaf_case_no = str(leaf.get('case_no') or '').strip()
|
||||
leaf_gate = leaf.get('current_gate') if isinstance(leaf.get('current_gate'), dict) else {}
|
||||
leaf_primary = leaf.get('primary_action') if isinstance(leaf.get('primary_action'), dict) else {}
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODE_SET
|
||||
|
||||
has_formal_gate = str(leaf_gate.get('gate_code') or '').strip() in PROCESS_GATE_CODE_SET
|
||||
if (
|
||||
leaf_case_no
|
||||
and not has_formal_gate
|
||||
and str(leaf_primary.get('code') or '').strip() in {'create_draft', 'edit_draft', 'validate'}
|
||||
):
|
||||
leaf['primary_action'] = {
|
||||
'code': 'open_order_review',
|
||||
'variant': 'primary',
|
||||
'label_key': 'shipping.actions.open_order_review',
|
||||
}
|
||||
result.append(_with_processing_ui_state(leaf))
|
||||
return result
|
||||
|
||||
|
||||
@@ -1870,7 +2037,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
states = [_state(item) for item in aggregate_children]
|
||||
upload_states = [_upload_state(item) for item in aggregate_children]
|
||||
failed_count = sum(state in {'failed', 'retryable'} for state in states)
|
||||
waiting_count = sum(state == 'waiting_human' for state in states)
|
||||
waiting_count = sum(state in {'waiting_human', 'idle'} for state in states)
|
||||
# 用户视角的完成必须同时满足任务完成和货代上传成功;候选已生成等中间态仍在处理中。
|
||||
completed_count = sum(
|
||||
state == 'completed' and upload_state == 'succeeded'
|
||||
@@ -1895,7 +2062,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
'order_creating'
|
||||
if str(item.get('user_stage') or '').strip().lower() == 'pre_ot_stp'
|
||||
else str(item.get('user_stage') or item.get('stage') or '').strip()
|
||||
for item in children
|
||||
for item in aggregate_children
|
||||
if _state(item) != 'completed' or _upload_state(item) != 'succeeded'
|
||||
),
|
||||
'completed',
|
||||
@@ -1939,11 +2106,11 @@ def _aggregate_eml_order_task_work_items(
|
||||
# 待人工按钮”的矛盾组合。
|
||||
actionable_states = (
|
||||
{'failed', 'retryable'} if aggregate_group == 'failed'
|
||||
else {'waiting_human'} if aggregate_group == 'waiting_human'
|
||||
else {'waiting_human', 'idle'} if aggregate_group == 'waiting_human'
|
||||
else set()
|
||||
)
|
||||
actionable_child = next(
|
||||
(item for item in children if _state(item) in actionable_states),
|
||||
(item for item in aggregate_children if _state(item) in actionable_states),
|
||||
None,
|
||||
)
|
||||
if actionable_child is not None:
|
||||
@@ -1978,7 +2145,7 @@ def _aggregate_eml_order_task_work_items(
|
||||
'stages': sorted(summary_stages),
|
||||
'reason_codes': sorted({
|
||||
str(code).strip()
|
||||
for item in children
|
||||
for item in aggregate_children
|
||||
for code in (
|
||||
(item.get('blocking_reason') or {}).get('code')
|
||||
if isinstance(item.get('blocking_reason'), dict) else None,
|
||||
@@ -2179,16 +2346,52 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
primary_raw = item.get('primary_action')
|
||||
primary = dict(primary_raw) if isinstance(primary_raw, dict) else None
|
||||
source_summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
|
||||
lifecycle = project_lifecycle(
|
||||
current_gate=(
|
||||
item.get('current_gate')
|
||||
if isinstance(item.get('current_gate'), dict)
|
||||
else {'gate_code': item.get('user_current_gate_code')}
|
||||
),
|
||||
blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None,
|
||||
legacy_stage=str(item.get('user_stage') or item.get('stage') or ''),
|
||||
# root_order_task_no 只是导航身份;必须有当前 Candidate 或正式通知事实才开放入口。
|
||||
has_candidate_context=bool(
|
||||
int(source_summary.get('candidate_count') or 0) > 0
|
||||
or item.get('has_formal_ot')
|
||||
or item.get('shipping_notice_no')
|
||||
),
|
||||
)
|
||||
lifecycle_stage = lifecycle['lifecycle_stage']
|
||||
if primary is not None:
|
||||
action_target = _action_lifecycle_target(primary.get('code'), lifecycle_stage=lifecycle_stage)
|
||||
if action_target is not None:
|
||||
primary['execution_mode'] = 'navigate'
|
||||
primary['target_surface'] = 'order_lifecycle_workbench'
|
||||
primary['target_lifecycle_stage'] = action_target
|
||||
primary_code = str((primary or {}).get('code') or '').strip()
|
||||
secondary: list[dict[str, Any]] = []
|
||||
for raw_code in item.get('available_actions') or []:
|
||||
code = str(raw_code or '').strip()
|
||||
if not code or code == primary_code:
|
||||
continue
|
||||
secondary.append({'code': code, 'enabled': True})
|
||||
action_target = _action_lifecycle_target(code, lifecycle_stage=lifecycle_stage)
|
||||
action = {'code': code, 'enabled': True}
|
||||
if action_target is not None:
|
||||
action.update({
|
||||
'execution_mode': 'navigate',
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
'target_lifecycle_stage': action_target,
|
||||
})
|
||||
secondary.append(action)
|
||||
return {
|
||||
'status': str(item.get('user_status') or item.get('status') or 'running'),
|
||||
'stage': str(item.get('user_stage') or item.get('stage') or ''),
|
||||
# 生命周期阶段是批次中心和工作台共享的业务语义;技术节点仍保留在 stage。
|
||||
'lifecycle_stage': lifecycle_stage,
|
||||
# 三阶段入口由后端一次性裁决;前端只按 state 投影,不得以候选数或阶段顺序二次判断。
|
||||
'lifecycle_entries': lifecycle['lifecycle_entries'],
|
||||
'lifecycle_authority': lifecycle['lifecycle_authority'],
|
||||
'blocking_reason': (
|
||||
dict(item['blocking_reason'])
|
||||
if isinstance(item.get('blocking_reason'), dict)
|
||||
@@ -2199,20 +2402,242 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _with_processing_ui_state(item: dict[str, Any]) -> dict[str, Any]:
|
||||
"""一次裁决后同时下发 ui_state 与工作项顶层生命周期镜像。
|
||||
|
||||
``ui_state`` 是页面的完整权威 DTO;顶层镜像使批次叶子、Review Queue 与其它
|
||||
受控消费者无须依赖嵌套形状即可读取同一阶段和入口。该函数只复制既有裁决结果,
|
||||
禁止按旧状态、候选数或消费界面重新计算。
|
||||
"""
|
||||
projected = dict(item)
|
||||
ui_state = _processing_ui_state_from_item(projected)
|
||||
projected['ui_state'] = ui_state
|
||||
projected['lifecycle_stage'] = ui_state.get('lifecycle_stage')
|
||||
projected['lifecycle_entries'] = list(ui_state.get('lifecycle_entries') or [])
|
||||
projected['lifecycle_authority'] = ui_state.get('lifecycle_authority')
|
||||
return projected
|
||||
|
||||
|
||||
def _action_lifecycle_target(action_code: Any, *, lifecycle_stage: str | None) -> str | None:
|
||||
"""将已授权动作映射到工作台展示面;未知动作不生成导航目标。"""
|
||||
code = str(action_code or '').strip().lower()
|
||||
if code in {
|
||||
'open_order_review', 'open_order_processing', 'edit_draft', 'create_draft',
|
||||
'reconcile_and_progress', 'confirm_customer', 'resolve_field_conflicts',
|
||||
'adjudicate_duplicate', 'open_profile_review',
|
||||
}:
|
||||
# 空 Candidate Case 的同一入口用于解析处置;不得借动作码跳到订单复核。
|
||||
return 'order_review' if lifecycle_stage == 'order_review' else 'intake_parse'
|
||||
if code in {
|
||||
'open_inventory_source_review', 'confirm_inventory_source', 'retry_resolve_inventory_source',
|
||||
'open_inventory_match_review', 'match_inventory', 'rematch', 'open_shortage_review',
|
||||
'upload_inventory_file', 'retry_inventory_preparation', 'regenerate_excel', 'generate_excel',
|
||||
}:
|
||||
return 'fulfillment_prep'
|
||||
if code in {
|
||||
'download_excel', 'open_manual_upload', 'wait_manual_upload', 'mark_manual_uploaded',
|
||||
'retry_freight_upload_rpa', 'retry_upload',
|
||||
}:
|
||||
return 'upload_complete'
|
||||
# 历史 Review 投影的 view 与 view_result 同为只读查看入口;必须由后端附带
|
||||
# 当前已裁决的工作台目标,前端不得因缺失目标误判为“前置阶段未完成”。
|
||||
return lifecycle_stage if code in {'view', 'view_result', 'view_record'} else None
|
||||
|
||||
|
||||
def _lifecycle_stage_from_item(item: dict[str, Any]) -> str | None:
|
||||
"""批次统计使用与任务详情相同的共享生命周期裁决,不维护独立映射。"""
|
||||
return project_lifecycle(
|
||||
current_gate=(
|
||||
item.get('current_gate')
|
||||
if isinstance(item.get('current_gate'), dict)
|
||||
else {'gate_code': item.get('user_current_gate_code')}
|
||||
),
|
||||
blocking_reason=item.get('blocking_reason') if isinstance(item.get('blocking_reason'), dict) else None,
|
||||
legacy_stage=str(item.get('user_stage') or item.get('stage') or ''),
|
||||
has_candidate_context=bool(item.get('has_formal_ot') or item.get('shipping_notice_no')),
|
||||
)['lifecycle_stage']
|
||||
|
||||
|
||||
def _current_file_representatives(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""为批次投影选择每个业务文件唯一的当前代表项。
|
||||
|
||||
核心逻辑:EML 聚合根不参与文件口径;同一文件的旧 Run、旧 OT 或历史失败
|
||||
投影只保留最新活动项。四阶段、文件统计、未分类统计必须共用本函数,避免一个
|
||||
PDF 同时被计入多个阶段或多个状态组。
|
||||
|
||||
Args:
|
||||
work_items: 已完成 EML 聚合和用户态投影的工作项。
|
||||
|
||||
Returns:
|
||||
按稳定业务文件身份去重后的当前代表项列表。
|
||||
"""
|
||||
file_items = [
|
||||
child
|
||||
for item in work_items
|
||||
for child in (item.get('aggregate_children') or [item])
|
||||
if isinstance(child, dict)
|
||||
]
|
||||
|
||||
def _file_key(item: dict[str, Any], index: int) -> str:
|
||||
"""优先用稳定文档身份;缺少正式标识时保守地不跨工作项合并。"""
|
||||
summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
|
||||
# 与跨 Run 聚合保持同一身份优先级:同内容重传可产生不同根文档,
|
||||
# 必须先以内容哈希归并,避免历史版本重新出现在当前状态组。
|
||||
content_hash = str(summary.get('content_hash') or '').strip().lower()
|
||||
if content_hash:
|
||||
return f'content-hash:{content_hash}'
|
||||
root_document_id = int(summary.get('root_document_id') or 0)
|
||||
if root_document_id > 0:
|
||||
return f'root-document:{root_document_id}'
|
||||
document_id = int(summary.get('document_id') or 0)
|
||||
if document_id > 0:
|
||||
return f'document:{document_id}'
|
||||
work_item_no = str(item.get('work_item_no') or '').strip()
|
||||
return f'item:{work_item_no or index}'
|
||||
|
||||
def _activity_key(item: dict[str, Any]) -> tuple[str, int]:
|
||||
"""最新活动优先;同一时刻以更需人工处理的状态稳定打破平局。"""
|
||||
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
priority = {
|
||||
'failed': 0, 'retryable': 0, 'waiting_human': 1,
|
||||
'running': 2, 'completed': 3, 'cancelled': 4,
|
||||
}.get(status, 5)
|
||||
timestamp = str(item.get('last_activity_at') or item.get('updated_at') or item.get('created_at') or '')
|
||||
return timestamp, -priority
|
||||
|
||||
unique_by_file: dict[str, dict[str, Any]] = {}
|
||||
for index, item in enumerate(file_items):
|
||||
key = _file_key(item, index)
|
||||
current = unique_by_file.get(key)
|
||||
if current is None or _activity_key(item) > _activity_key(current):
|
||||
unique_by_file[key] = item
|
||||
return list(unique_by_file.values())
|
||||
|
||||
|
||||
def _display_work_items_from_current_files(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""保留 EML 容器,同时仅展示每份文件的当前代表项。
|
||||
|
||||
核心逻辑:批次文件行不能直接以叶子代表项替换 EML 父卡,否则附件失去 intake
|
||||
归属并出现“汇总五份、列表只见三份”。本函数只替换父卡的子文件集合,并按该集合
|
||||
重算父卡用户态;非 EML 叶子直接保留当前代表项。
|
||||
|
||||
Args:
|
||||
work_items: 已完成 EML 聚合和用户态投影的完整工作项。
|
||||
|
||||
Returns:
|
||||
与互斥统计完全同源、且保留 EML 展开层级的展示工作项。
|
||||
"""
|
||||
representatives = _current_file_representatives(work_items)
|
||||
representative_ids = {id(item) for item in representatives}
|
||||
displayed: list[dict[str, Any]] = []
|
||||
|
||||
def _state(item: dict[str, Any]) -> str:
|
||||
return str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
|
||||
def _upload_state(item: dict[str, Any]) -> str:
|
||||
facts = item.get('facts') if isinstance(item.get('facts'), dict) else {}
|
||||
return str(facts.get('upload_state') or '').strip().lower()
|
||||
|
||||
for item in work_items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
children = item.get('aggregate_children')
|
||||
if not isinstance(children, list) or not children:
|
||||
if id(item) in representative_ids:
|
||||
displayed.append(item)
|
||||
continue
|
||||
|
||||
current_children = [child for child in children if id(child) in representative_ids]
|
||||
if not current_children:
|
||||
continue
|
||||
clone = dict(item)
|
||||
states = [_state(child) for child in current_children]
|
||||
upload_states = [_upload_state(child) for child in current_children]
|
||||
group = _eml_aggregate_user_group(
|
||||
states=states,
|
||||
upload_states=upload_states,
|
||||
children=current_children,
|
||||
)
|
||||
status = (
|
||||
'failed' if group == 'failed' else
|
||||
'waiting_human' if group == 'waiting_human' else
|
||||
'cancelled' if group == 'cancelled' else
|
||||
'completed' if group == 'completed' else
|
||||
'running'
|
||||
)
|
||||
actionable_states = (
|
||||
{'failed', 'retryable'} if group == 'failed' else
|
||||
{'waiting_human', 'idle'} if group == 'waiting_human' else set()
|
||||
)
|
||||
representative = next(
|
||||
(child for child in current_children if _state(child) in actionable_states),
|
||||
current_children[0],
|
||||
)
|
||||
source_summary = dict(clone.get('source_summary') or {})
|
||||
source_summary['document_count'] = len(current_children)
|
||||
clone.update({
|
||||
'aggregate_children': current_children,
|
||||
'user_group': group,
|
||||
'user_status': status,
|
||||
'status': status,
|
||||
'user_stage': str(representative.get('user_stage') or representative.get('stage') or ''),
|
||||
'stage': str(representative.get('user_stage') or representative.get('stage') or ''),
|
||||
'current_gate': representative.get('current_gate'),
|
||||
'blocking_reason': representative.get('blocking_reason') if actionable_states else None,
|
||||
'primary_action': representative.get('primary_action') if actionable_states else None,
|
||||
'available_actions': list(representative.get('available_actions') or []) if actionable_states else [],
|
||||
'source_summary': source_summary,
|
||||
'facts': {
|
||||
**dict(clone.get('facts') or {}),
|
||||
'upload_state': (
|
||||
'failed' if any(value == 'failed' for value in upload_states) else
|
||||
'succeeded' if upload_states and all(value == 'succeeded' for value in upload_states) else
|
||||
'uploading' if any(value in {'uploading', 'callback_received'} for value in upload_states) else
|
||||
'manual_upload_pending' if any(value == 'manual_upload_pending' for value in upload_states) else
|
||||
'not_created'
|
||||
),
|
||||
},
|
||||
'aggregate_summary': {
|
||||
'intake_no': clone.get('intake_no'),
|
||||
'total': len(current_children),
|
||||
'completed': sum(
|
||||
state == 'completed' and upload_state == 'succeeded'
|
||||
for state, upload_state in zip(states, upload_states)
|
||||
),
|
||||
'processing': sum(
|
||||
state not in {'failed', 'retryable', 'waiting_human', 'idle', 'completed'}
|
||||
or (state == 'completed' and upload_state != 'succeeded')
|
||||
for state, upload_state in zip(states, upload_states)
|
||||
),
|
||||
'needs_action': sum(state in {'waiting_human', 'idle'} for state in states),
|
||||
'failed': sum(state in {'failed', 'retryable'} for state in states),
|
||||
'stages': sorted({
|
||||
str(child.get('user_stage') or child.get('stage') or '').strip()
|
||||
for child in current_children
|
||||
if str(child.get('user_stage') or child.get('stage') or '').strip()
|
||||
}),
|
||||
'reason_codes': sorted({
|
||||
str((child.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
for child in current_children
|
||||
if isinstance(child.get('blocking_reason'), dict)
|
||||
and str((child.get('blocking_reason') or {}).get('code') or '').strip()
|
||||
}),
|
||||
'upload_states': sorted(set(upload_states)),
|
||||
},
|
||||
})
|
||||
# 父卡的 ui_state 同样必须由当前附件集合重新封装;不能透传聚合前的旧按钮。
|
||||
displayed.append(_with_processing_ui_state(clone))
|
||||
return displayed
|
||||
|
||||
|
||||
def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从最终用户态工作项构建批次四阶段主进度。
|
||||
|
||||
业务阶段映射和状态优先级只在后端维护;15 个技术节点仍附着在单项诊断字段,
|
||||
绝不要求前端通过 stage 索引再计算四阶段。
|
||||
"""
|
||||
ranges = (
|
||||
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
|
||||
('order_review', {'order_creating', 'review_required', 'waiting_review', 'pre_ot_stp'}),
|
||||
('fulfillment_prep', {'inventory_fetching', 'inventory_matching', 'excel_generating'}),
|
||||
('upload_complete', {'freight_uploading', 'completed'}),
|
||||
)
|
||||
ranked_items = sorted(
|
||||
work_items,
|
||||
_current_file_representatives(work_items),
|
||||
key=lambda item: {
|
||||
'failed': 0,
|
||||
'retryable': 0,
|
||||
@@ -2222,33 +2647,75 @@ def _batch_four_stage_nodes(work_items: list[dict[str, Any]]) -> list[dict[str,
|
||||
'cancelled': 4,
|
||||
}.get(str(item.get('user_status') or item.get('status') or '').strip().lower(), 5),
|
||||
)
|
||||
selected = ranked_items[0] if ranked_items else {}
|
||||
active_index = 0
|
||||
selected_status = str(selected.get('user_status') or selected.get('status') or '').strip().lower()
|
||||
stage = str(selected.get('user_stage') or selected.get('stage') or '').strip().lower()
|
||||
for index, (_, stage_codes) in enumerate(ranges):
|
||||
if stage in stage_codes:
|
||||
active_index = index
|
||||
break
|
||||
all_completed = bool(work_items) and all(
|
||||
str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
in {'completed', 'cancelled'}
|
||||
for item in work_items
|
||||
)
|
||||
for item in work_items:
|
||||
stage = str(item.get('user_stage') or item.get('stage') or '').strip().lower()
|
||||
for index, (_, stage_codes) in enumerate(ranges):
|
||||
if stage in stage_codes:
|
||||
break
|
||||
# 每一阶段的计数和首个阻断原因也在服务端统一裁决;前端不能从筛选后的
|
||||
# EML/文件行反算,否则聚合、历史项和权限裁剪会让摘要口径漂移。
|
||||
stage_summaries: dict[str, dict[str, Any]] = {
|
||||
code: {
|
||||
'total': 0,
|
||||
'completed': 0,
|
||||
'needs_action': 0,
|
||||
'processing': 0,
|
||||
'failed': 0,
|
||||
'blocking_reason': None,
|
||||
}
|
||||
for code, _ in LIFECYCLE_STAGE_RANGES
|
||||
}
|
||||
for item in ranked_items:
|
||||
lifecycle_stage = _lifecycle_stage_from_item(item)
|
||||
if lifecycle_stage is None:
|
||||
continue
|
||||
summary = stage_summaries[lifecycle_stage]
|
||||
summary['total'] += 1
|
||||
# 四阶段与文件概览必须消费同一正式用户分组。user_status 可能在旧 Run
|
||||
# 兼容投影中残留为 running,不能把后端已裁决为“待处理”的文件再显示为处理中。
|
||||
item_group = _batch_user_group(item)
|
||||
if item_group == 'completed':
|
||||
summary['completed'] += 1
|
||||
continue
|
||||
if item_group == 'failed':
|
||||
summary['failed'] += 1
|
||||
summary['needs_action'] += 1
|
||||
elif item_group == 'waiting_human':
|
||||
summary['needs_action'] += 1
|
||||
else:
|
||||
summary['processing'] += 1
|
||||
if summary['blocking_reason'] is None and isinstance(item.get('blocking_reason'), dict):
|
||||
reason = item['blocking_reason']
|
||||
summary['blocking_reason'] = {
|
||||
key: reason[key]
|
||||
for key in ('code', 'i18n_key')
|
||||
if reason.get(key)
|
||||
} or None
|
||||
|
||||
nodes: list[dict[str, Any]] = []
|
||||
for index, (code, _) in enumerate(ranges):
|
||||
status = 'passed' if all_completed or index < active_index else 'pending'
|
||||
if not all_completed and index == active_index:
|
||||
status = 'blocked' if selected_status in {'failed', 'retryable', 'waiting_human'} else 'running'
|
||||
nodes.append({'code': code, 'label_key': code, 'status': status})
|
||||
for code, _ in LIFECYCLE_STAGE_RANGES:
|
||||
summary = stage_summaries[code]
|
||||
# 卡片状态只由本阶段聚合事实计算,禁止由其他阶段的优先文件反向影响。
|
||||
status = (
|
||||
'blocked' if summary['failed'] or summary['needs_action']
|
||||
else 'running' if summary['processing']
|
||||
else 'passed' if summary['completed']
|
||||
else 'pending'
|
||||
)
|
||||
nodes.append({
|
||||
'code': code,
|
||||
'label_key': code,
|
||||
'status': status,
|
||||
'summary': stage_summaries[code],
|
||||
})
|
||||
return nodes
|
||||
|
||||
|
||||
def _unclassified_summary(work_items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""统计无法归入四阶段的业务文件,避免批次摘要与文件清单口径不一致。"""
|
||||
return {
|
||||
'count': sum(
|
||||
1 for item in _current_file_representatives(work_items)
|
||||
if _lifecycle_stage_from_item(item) is None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""投影本次已就绪产出物;只暴露后端确认可下载的正式 Excel。"""
|
||||
artifacts: list[dict[str, Any]] = []
|
||||
@@ -2260,10 +2727,10 @@ def _batch_output_artifacts(work_items: list[dict[str, Any]]) -> list[dict[str,
|
||||
task = ShippingOrderTask.query.filter_by(task_no=task_no).first()
|
||||
notice_id = getattr(task, 'shipping_notice_id', None) if task is not None else None
|
||||
notice = db.session.get(ShippingNotice, int(notice_id)) if notice_id else None
|
||||
filename = str(getattr(notice, 'export_file_name', None) or '').strip() if notice else ''
|
||||
path = str(getattr(notice, 'export_file_path', None) or '').strip() if notice else ''
|
||||
if not filename or not path:
|
||||
resolved = resolve_task_export_download(notice)
|
||||
if resolved is None:
|
||||
continue
|
||||
_, filename = resolved
|
||||
seen.add(task_no)
|
||||
artifacts.append({
|
||||
'order_task_no': task_no,
|
||||
@@ -2281,8 +2748,11 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An
|
||||
优先级与 EML 聚合保持一致:失败/可重试优先,其次待人工;系统处理中不伪造
|
||||
人工入口。批次动作始终引用一个已授权叶子/EML action,写路径仍会二次校验。
|
||||
"""
|
||||
# 批次主状态与文件计数、四阶段必须消费同一份“每文件唯一当前代表项”。
|
||||
# 否则历史 Run 的失败/待办虽然不再计数,仍可能抢走批次 CTA,形成
|
||||
# “数字是当前、按钮却指向历史”的第二裁决源。
|
||||
ranked = sorted(
|
||||
work_items,
|
||||
_current_file_representatives(work_items),
|
||||
key=lambda item: {
|
||||
'failed': 0,
|
||||
'retryable': 0,
|
||||
@@ -2315,35 +2785,36 @@ def _batch_ui_state_from_items(work_items: list[dict[str, Any]]) -> dict[str, An
|
||||
}
|
||||
|
||||
|
||||
def _batch_user_group(item: dict[str, Any]) -> str:
|
||||
"""归一批次统计使用的互斥用户分组,优先消费领域投影已裁决的 user_group。"""
|
||||
group = str(item.get('user_group') or '').strip().lower()
|
||||
if group in {'failed', 'waiting_human', 'processing', 'completed'}:
|
||||
return group
|
||||
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
if status in {'failed', 'retryable'}:
|
||||
return 'failed'
|
||||
if status in {'waiting_human', 'waiting_review', 'idle'}:
|
||||
return 'waiting_human'
|
||||
if status in {'completed', 'cancelled'}:
|
||||
return 'completed'
|
||||
return 'processing'
|
||||
|
||||
|
||||
def _batch_file_counts(work_items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""按后端最终 EML 聚合结果统计业务文件,EML 容器永不计数。"""
|
||||
groups = {'failed': set(), 'waiting_human': set(), 'processing': set(), 'completed': set()}
|
||||
for item in work_items:
|
||||
group = str(item.get('user_group') or '').strip().lower()
|
||||
if group not in groups:
|
||||
status = str(item.get('user_status') or item.get('status') or '').strip().lower()
|
||||
group = 'failed' if status in {'failed', 'retryable'} else (
|
||||
'waiting_human' if status in {'waiting_human', 'waiting_review'} else (
|
||||
'completed' if status == 'completed' else 'processing'
|
||||
)
|
||||
)
|
||||
for child in item.get('aggregate_children') or [item]:
|
||||
if not isinstance(child, dict):
|
||||
continue
|
||||
summary = child.get('source_summary') if isinstance(child.get('source_summary'), dict) else {}
|
||||
filename = str(summary.get('filename') or '').strip().lower()
|
||||
if filename.endswith('.eml'):
|
||||
continue
|
||||
document_id = int(summary.get('document_id') or 0)
|
||||
key = f'document:{document_id}' if document_id else f'filename:{filename}'
|
||||
if filename or document_id:
|
||||
groups[group].add(key)
|
||||
"""按唯一当前业务文件统计互斥状态组,EML 容器永不计数。"""
|
||||
groups = {'failed': 0, 'waiting_human': 0, 'processing': 0, 'completed': 0}
|
||||
for item in _current_file_representatives(work_items):
|
||||
group = _batch_user_group(item)
|
||||
summary = item.get('source_summary') if isinstance(item.get('source_summary'), dict) else {}
|
||||
filename = str(summary.get('filename') or '').strip().lower()
|
||||
if not filename.endswith('.eml') and (filename or int(summary.get('document_id') or 0)):
|
||||
groups[group] += 1
|
||||
return {
|
||||
'total_files': len(set().union(*groups.values())),
|
||||
'failed_files': len(groups['failed']),
|
||||
'waiting_human_files': len(groups['waiting_human']),
|
||||
'processing_files': len(groups['processing']),
|
||||
'completed_files': len(groups['completed']),
|
||||
'total_files': sum(groups.values()),
|
||||
'failed_files': groups['failed'],
|
||||
'waiting_human_files': groups['waiting_human'],
|
||||
'processing_files': groups['processing'],
|
||||
'completed_files': groups['completed'],
|
||||
}
|
||||
|
||||
|
||||
@@ -2368,6 +2839,9 @@ def _conversation_processing_from_work_items(
|
||||
Returns:
|
||||
与 project_conversation_processing 同形的 dict。
|
||||
"""
|
||||
# 文件清单必须与批次统计、四阶段和 CTA 使用相同的当前文件代表项,同时
|
||||
# 保留 EML 父卡,避免附件失去邮件归属或在多个状态组重复出现。
|
||||
display_work_items = _display_work_items_from_current_files(work_items)
|
||||
needs_action: list[dict[str, Any]] = []
|
||||
processing: list[dict[str, Any]] = []
|
||||
completed: list[dict[str, Any]] = []
|
||||
@@ -2375,7 +2849,7 @@ def _conversation_processing_from_work_items(
|
||||
focused = str(focused_task_no or '').strip() or None
|
||||
recent = str(recent_task_no or '').strip() or None
|
||||
|
||||
for item in work_items:
|
||||
for item in display_work_items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('work_item_type') or '') not in {'order_task', 'order_intake'}:
|
||||
@@ -2441,6 +2915,7 @@ def _conversation_processing_from_work_items(
|
||||
'archived': [row for row in all_rows if row.get('user_group') == 'archived'],
|
||||
},
|
||||
'four_stage_nodes': _batch_four_stage_nodes(work_items),
|
||||
'unclassified_summary': _unclassified_summary(work_items),
|
||||
'ui_state': _batch_ui_state_from_items(work_items),
|
||||
'output_artifacts': _batch_output_artifacts(work_items),
|
||||
}
|
||||
@@ -2773,12 +3248,11 @@ def project_conversation_processing_items(
|
||||
# 保证对话正文、右侧任务区和 API 消费同一 user_status/user_stage/upload_state 事实。
|
||||
work_items = _aggregate_eml_order_task_work_items(work_items)
|
||||
# [AUTHORITY] 顶层 work_items 与 conversation_processing.status_groups 必须使用
|
||||
# 相同的展示 DTO。否则 direct PDF / EML 聚合根会缺 ui_state,迫使前端从旧
|
||||
# gate 或 available_actions 重新裁决状态与按钮。
|
||||
work_items = [
|
||||
{**item, 'ui_state': _processing_ui_state_from_item(item)}
|
||||
for item in work_items
|
||||
]
|
||||
# 同一份“当前文件代表项”展示 DTO。否则前端兼容消费者若从顶层 work_items
|
||||
# 读取,会重新看到历史 Run/旧失败项,绕过批次统计已经完成的互斥裁决。
|
||||
# 该函数保留 EML 父容器,只裁掉其历史附件,不能以叶子项直接替换父卡。
|
||||
work_items = _display_work_items_from_current_files(work_items)
|
||||
work_items = [_with_processing_ui_state(item) for item in work_items]
|
||||
|
||||
recent_override = str(recent_task_no or '').strip() or None
|
||||
rebuilt = _conversation_processing_from_work_items(
|
||||
|
||||
@@ -287,6 +287,13 @@ def shipping_recovery_tick() -> int:
|
||||
nested.rollback()
|
||||
continue
|
||||
|
||||
# 人工改写后的草稿必须等待用户点击“保存订单并校验”。恢复扫描只补偿
|
||||
# 遗漏的系统任务,不能反复写入校验快照导致前端版本持续过期。
|
||||
from app.services.shipping_notice.order_review_draft_service import draft_has_manual_values
|
||||
if draft_has_manual_values(locked_case.current_draft):
|
||||
nested.rollback()
|
||||
continue
|
||||
|
||||
db.session.execute(text(
|
||||
"SELECT pg_advisory_xact_lock(hashtext('shipping_stp_sweeper'), :case_id)"
|
||||
), {"case_id": int(case_id)})
|
||||
|
||||
@@ -64,6 +64,8 @@ def _request_formal_gate_action(
|
||||
current_id = getattr(task, 'active_process_execution_id', None)
|
||||
if current_id:
|
||||
execution = ShippingProcessExecution.query.filter_by(id=int(current_id)).with_for_update().first()
|
||||
if execution is not None and str(execution.status or '').strip().lower() == 'superseded':
|
||||
execution = None
|
||||
if execution is None:
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
task_id=int(task.id), actor_type='user', actor_id=int(user_id),
|
||||
|
||||
@@ -32,6 +32,7 @@ def _task_has_process_execution(task: ShippingNotice | None) -> bool:
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.first()
|
||||
is not None
|
||||
)
|
||||
|
||||
@@ -49,9 +49,14 @@ from app.services.shipping_notice.constants import (
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
from app.services.shipping_notice.lifecycle_projection import (
|
||||
LIFECYCLE_STAGES,
|
||||
project_lifecycle,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import (
|
||||
compute_batch_process_summary,
|
||||
list_sorted_batch_tasks,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_summary,
|
||||
)
|
||||
@@ -66,8 +71,8 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
|
||||
WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
|
||||
{"id": "shipping-stage-1", "code": "intake_parse", "label": "接收解析"},
|
||||
{"id": "shipping-stage-2", "code": "order_review", "label": "订单复核"},
|
||||
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "发货准备"},
|
||||
{"id": "shipping-stage-4", "code": "upload_complete", "label": "上传完成"},
|
||||
{"id": "shipping-stage-3", "code": "fulfillment_prep", "label": "通知准备"},
|
||||
{"id": "shipping-stage-4", "code": "upload_complete", "label": "通知完成"},
|
||||
)
|
||||
|
||||
_CURRENT_STEP_INDEX_MAP: dict[str, int] = {
|
||||
@@ -132,36 +137,6 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
|
||||
}
|
||||
|
||||
# 业务人员可见的四阶段;Gate/checkpoint 仍保留内部精度,但不得成为主进度条。
|
||||
BUSINESS_STAGES: tuple[dict[str, Any], ...] = (
|
||||
{"code": "intake_parse", "label": "接收解析"},
|
||||
{"code": "order_review", "label": "订单复核"},
|
||||
{"code": "fulfillment_prep", "label": "发货准备"},
|
||||
{"code": "upload_complete", "label": "上传完成"},
|
||||
)
|
||||
|
||||
_STAGE_GATE_CODES: dict[str, str] = {
|
||||
"document_materialization": "intake_parse",
|
||||
"layout_parsing": "intake_parse",
|
||||
"document_profile_routing": "intake_parse",
|
||||
"order_field_extraction": "intake_parse",
|
||||
"field_completeness": "order_review",
|
||||
"reservation_validation": "order_review",
|
||||
"customer_resolution": "order_review",
|
||||
"duplicate_detection": "order_review",
|
||||
"field_conflict_resolution": "order_review",
|
||||
"order_freeze_readiness": "order_review",
|
||||
"task_creation": "order_review",
|
||||
"inventory_source_routing": "fulfillment_prep",
|
||||
"inventory_preparation": "fulfillment_prep",
|
||||
"inventory_field_mapping": "fulfillment_prep",
|
||||
"inventory_matching": "fulfillment_prep",
|
||||
"inventory_sufficiency": "fulfillment_prep",
|
||||
"excel_readiness": "fulfillment_prep",
|
||||
"artifact_generation": "fulfillment_prep",
|
||||
"freight_upload_rpa": "upload_complete",
|
||||
"manual_upload_handoff": "upload_complete",
|
||||
}
|
||||
|
||||
_STAGE_CHECKPOINT_CODES: dict[str, str] = {
|
||||
CP_PARSE_REVIEW: "order_review",
|
||||
CP_RSV_REQ: "order_review",
|
||||
@@ -184,17 +159,36 @@ _STAGE_CHECKPOINT_CODES: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
def _business_stage(
|
||||
def _task_lifecycle(
|
||||
*, task: ShippingNotice, checkpoint: str | None, process_gate: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""将内部 Gate/checkpoint 投影为四阶段;不向前端暴露底层状态枚举。"""
|
||||
gate = (process_gate or {}).get("current_blocking_gate") or (process_gate or {}).get("current_gate") or {}
|
||||
gate_code = str(gate.get("gate_code") or "").strip()
|
||||
stage_code = _STAGE_GATE_CODES.get(gate_code) or _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ""))
|
||||
if not stage_code:
|
||||
stage_code = "upload_complete" if str(checkpoint or "") in {CP_UPLOADED, CP_COMPLETED} else "intake_parse"
|
||||
index = next((i for i, item in enumerate(BUSINESS_STAGES) if item["code"] == stage_code), 0)
|
||||
return {**BUSINESS_STAGES[index], "index": index + 1, "total": len(BUSINESS_STAGES)}
|
||||
"""以共享裁决器投影正式任务生命周期;旧 checkpoint 仅作无 Gate 的兼容兜底。"""
|
||||
gate = (process_gate or {}).get('current_blocking_gate') or (process_gate or {}).get('current_gate')
|
||||
legacy_stage = _STAGE_CHECKPOINT_CODES.get(str(checkpoint or ''))
|
||||
if legacy_stage is None:
|
||||
legacy_stage = 'upload_complete' if str(checkpoint or '') in {CP_UPLOADED, CP_COMPLETED} else None
|
||||
if legacy_stage is None:
|
||||
# 仅没有 Gate 时,沿用旧任务领域事实映射;不能覆盖正式 Gate。
|
||||
legacy_index = _derive_current_step_index(task)
|
||||
legacy_stage = ('intake_parse', 'order_review', 'fulfillment_prep', 'upload_complete')[legacy_index]
|
||||
return project_lifecycle(
|
||||
current_gate=gate if isinstance(gate, dict) else None,
|
||||
blocking_reason=(
|
||||
{'code': process_gate.get('blocking_reason_code')}
|
||||
if isinstance(process_gate, dict) and process_gate.get('blocking_reason_code')
|
||||
else None
|
||||
),
|
||||
legacy_stage=legacy_stage,
|
||||
# ShippingNotice 是已确认的正式 OT;生命周期入口可回看,写动作仍由 Gate 授权。
|
||||
has_candidate_context=True,
|
||||
)
|
||||
|
||||
|
||||
def _business_stage(lifecycle: dict[str, Any]) -> dict[str, Any]:
|
||||
"""将共享生命周期结果包装为任务详情既有的阶段 DTO。"""
|
||||
stage_code = str(lifecycle.get('lifecycle_stage') or 'intake_parse')
|
||||
index = next((i for i, item in enumerate(LIFECYCLE_STAGES) if item['code'] == stage_code), 0)
|
||||
return {**LIFECYCLE_STAGES[index], 'index': index + 1, 'total': len(LIFECYCLE_STAGES)}
|
||||
|
||||
|
||||
def _unified_action(action: dict[str, Any], *, default_kind: str = "recovery") -> dict[str, Any]:
|
||||
@@ -289,14 +283,24 @@ def _derive_current_step_index(task: ShippingNotice) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def build_shipping_workflow_steps(task: ShippingNotice, checkpoint: str | None) -> list[dict[str, str]]:
|
||||
def build_shipping_workflow_steps(
|
||||
task: ShippingNotice,
|
||||
checkpoint: str | None,
|
||||
*,
|
||||
lifecycle_stage: str | None = None,
|
||||
) -> list[dict[str, str]]:
|
||||
"""
|
||||
构造四阶段流程状态。
|
||||
|
||||
Returns:
|
||||
list[dict]: 每步包含 id/code/label/status,status 为 completed/current/pending/blocked。
|
||||
"""
|
||||
current_index = _derive_current_step_index(task)
|
||||
lifecycle_index = next(
|
||||
(index for index, item in enumerate(LIFECYCLE_STAGES) if item['code'] == lifecycle_stage),
|
||||
None,
|
||||
)
|
||||
# 正式 Gate 已存在时,四阶段流程条必须使用同一裁决结果;旧字段只服务于历史兼容。
|
||||
current_index = lifecycle_index if lifecycle_index is not None else _derive_current_step_index(task)
|
||||
pending_reason = str(task.pending_human_reason or "").strip()
|
||||
checkpoint_value = str(checkpoint or "").strip()
|
||||
steps: list[dict[str, str]] = []
|
||||
@@ -359,7 +363,17 @@ def _action_buttons_for_task(task: ShippingNotice) -> list[dict[str, str]]:
|
||||
# 保留重试/重匹配/驳回,但把指定源放在首位作为主恢复入口。
|
||||
rest = [btn for btn in (ui.action_buttons or []) if str(btn.get('id') or '') != 'confirm_inventory_source']
|
||||
return [confirm_btn, *rest]
|
||||
return ui.action_buttons
|
||||
action_buttons = list(ui.action_buttons or [])
|
||||
# [AUTHORITY] ``export_file_name`` 只是历史字段,不能作为下载授权或文件存在的证据。
|
||||
# 只有任务当前 Artifact 已由后端解析为可下载文件时,才把 download_excel 下发给
|
||||
# 任一前端;下载 API 仍会在真正读取文件时再次校验,抵御页面快照过期。
|
||||
if any(str((button or {}).get('id') or '') == 'download_excel' for button in action_buttons):
|
||||
if resolve_task_export_download(task) is None:
|
||||
action_buttons = [
|
||||
button for button in action_buttons
|
||||
if str((button or {}).get('id') or '') != 'download_excel'
|
||||
]
|
||||
return action_buttons
|
||||
|
||||
_PARSE_STAGE_CHECKPOINTS = {
|
||||
CP_PARSE_REVIEW,
|
||||
@@ -690,7 +704,235 @@ def _build_task_summary(
|
||||
return summary
|
||||
|
||||
|
||||
def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
def _build_stage_context(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
lifecycle_stage: str,
|
||||
stp_facts: dict[str, Any] | None,
|
||||
process_gate: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造四阶段工作台的只读事实摘要,禁止把它作为新的业务状态机。
|
||||
|
||||
通知准备只消费已经冻结的订单行、库存匹配结果和 Excel Artifact;通知完成
|
||||
只以真实上传 Attempt 判定成功,不能因进入 ``upload_complete`` 工作面而假装完成。
|
||||
"""
|
||||
from app.models.shipping_excel_template import ShippingExportArtifact
|
||||
from app.models.shipping_fulfillment import (
|
||||
ShippingInventoryVerification,
|
||||
ShippingUploadAttempt,
|
||||
)
|
||||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
||||
from app.models.shipping_notice_line import ShippingNoticeLine
|
||||
|
||||
facts = stp_facts if isinstance(stp_facts, dict) else {}
|
||||
raw_rows = task.line_results_json if isinstance(task.line_results_json, list) else []
|
||||
fact_rows = facts.get('line_resolutions') if isinstance(facts.get('line_resolutions'), list) else []
|
||||
fact_by_key = {
|
||||
str(row.get('line_key') or ''): row
|
||||
for row in fact_rows
|
||||
if isinstance(row, dict) and str(row.get('line_key') or '')
|
||||
}
|
||||
# 正式结构化匹配事实是通知准备的首要来源;旧 JSON/STP 仅作为历史任务兼容回退。
|
||||
current_match_rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=task.id, is_current=True)
|
||||
.order_by(ShippingNoticeLineInventoryMatch.line_index, ShippingNoticeLineInventoryMatch.id)
|
||||
.all()
|
||||
if getattr(task, 'id', None) is not None else []
|
||||
)
|
||||
match_by_key = {
|
||||
str(row.line_key or ''): row
|
||||
for row in current_match_rows
|
||||
if str(row.line_key or '')
|
||||
}
|
||||
match_by_index = {
|
||||
int(row.line_index): row
|
||||
for row in current_match_rows
|
||||
if row.line_index is not None
|
||||
}
|
||||
verification_rows: dict[str, dict[str, Any]] = {}
|
||||
latest_verification = (
|
||||
ShippingInventoryVerification.query
|
||||
.filter_by(task_id=task.id, status='completed')
|
||||
.order_by(ShippingInventoryVerification.created_at.desc(), ShippingInventoryVerification.id.desc())
|
||||
.first()
|
||||
if getattr(task, 'id', None) is not None else None
|
||||
)
|
||||
if latest_verification is not None:
|
||||
# 核验行没有 line_key,按冻结订单行/Reservation 顺序作为最后一级兼容回退。
|
||||
for position, verification_line in enumerate(latest_verification.lines):
|
||||
verification_rows[str(position)] = {
|
||||
'required_qty': verification_line.required_qty,
|
||||
'available_qty': verification_line.available_qty,
|
||||
'shortage_qty': (
|
||||
max(verification_line.required_qty - verification_line.available_qty, 0)
|
||||
if verification_line.required_qty is not None and verification_line.available_qty is not None
|
||||
else None
|
||||
),
|
||||
'status': verification_line.status,
|
||||
}
|
||||
# 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对
|
||||
# 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。
|
||||
frozen_order_lines: list[dict[str, Any]] = []
|
||||
preparation_lines: list[dict[str, Any]] = []
|
||||
notice_lines = (
|
||||
ShippingNoticeLine.query.filter_by(notice_id=task.id).order_by(ShippingNoticeLine.position).all()
|
||||
if getattr(task, 'id', None) is not None else []
|
||||
)
|
||||
for line in notice_lines:
|
||||
frozen_order_lines.append({
|
||||
'line_key': getattr(line, 'line_key', None),
|
||||
'reservation_id': getattr(line, 'reservation_id', None),
|
||||
'part_number': getattr(line, 'part_number', None),
|
||||
'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None,
|
||||
})
|
||||
|
||||
# 匹配表只输出已经存在的匹配/核验事实。历史任务尚未双写正式行时可用旧 JSON
|
||||
# 兼容,但绝不能把未匹配的冻结订单行伪装为“库存匹配结果”。
|
||||
row_count = max(len(raw_rows), len(fact_rows), len(current_match_rows))
|
||||
for index in range(row_count):
|
||||
line = notice_lines[index] if index < len(notice_lines) else None
|
||||
match_row = match_by_key.get(str(getattr(line, 'line_key', '') or '')) or match_by_index.get(index)
|
||||
structured = ({
|
||||
'line_key': match_row.line_key,
|
||||
'reservation_id': match_row.reservation_id,
|
||||
'part_number': match_row.part_number,
|
||||
'required_qty': match_row.required_qty,
|
||||
'available_qty': match_row.matched_qty or match_row.available_qty,
|
||||
'shortage_qty': match_row.shortage_qty,
|
||||
'resolved_inventory_source_code': match_row.inventory_source_code,
|
||||
'disposition': match_row.match_result,
|
||||
} if match_row is not None else {})
|
||||
legacy_source = fact_by_key.get(
|
||||
str(getattr(line, 'line_key', '') or ''),
|
||||
fact_rows[index] if index < len(fact_rows) and isinstance(fact_rows[index], dict) else {},
|
||||
)
|
||||
# 结构化事实优先,但不以空值覆盖历史/STP 投影中仍有价值的证据字段。
|
||||
source = {
|
||||
**(legacy_source if isinstance(legacy_source, dict) else {}),
|
||||
**{
|
||||
key: value
|
||||
for key, value in structured.items()
|
||||
if value is not None and value != ''
|
||||
},
|
||||
}
|
||||
verification = verification_rows.get(str(index), {})
|
||||
result = raw_rows[index] if index < len(raw_rows) and isinstance(raw_rows[index], dict) else {}
|
||||
required_qty = result.get('required_qty', source.get('required_qty', verification.get('required_qty', getattr(line, 'required_qty', None))))
|
||||
available_qty = result.get('available_qty', source.get('available_qty', source.get('matched_qty', verification.get('available_qty'))))
|
||||
shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty')))
|
||||
preparation_lines.append({
|
||||
'line_key': getattr(line, 'line_key', None) or source.get('line_key'),
|
||||
'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None),
|
||||
'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None),
|
||||
'required_qty': required_qty,
|
||||
'available_qty': available_qty,
|
||||
'shortage_qty': shortage_qty,
|
||||
'source_code': source.get('resolved_inventory_source_code') or source.get('inventory_source_code'),
|
||||
'status': result.get('line_status') or source.get('disposition') or verification.get('status') or None,
|
||||
})
|
||||
|
||||
has_match_result = bool(current_match_rows or raw_rows or any(
|
||||
row.get('matched_qty') is not None
|
||||
or row.get('shortage_qty') is not None
|
||||
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage'}
|
||||
for row in fact_rows if isinstance(row, dict)
|
||||
))
|
||||
gate = process_gate if isinstance(process_gate, dict) else {}
|
||||
gate_code = str((gate.get('current_blocking_gate') or gate.get('current_gate') or {}).get('gate_code') or '')
|
||||
preparation_status = (
|
||||
'ready' if has_match_result else
|
||||
'blocked' if gate_code else
|
||||
'processing'
|
||||
)
|
||||
|
||||
inventory_sources: list[dict[str, Any]] = []
|
||||
latest_preparation = None
|
||||
if getattr(task, 'id', None):
|
||||
from app.models.shipping_inventory_preparation import ShippingInventoryPreparationAttempt
|
||||
|
||||
latest_preparation = (
|
||||
ShippingInventoryPreparationAttempt.query
|
||||
.filter_by(task_id=task.id)
|
||||
.filter(ShippingInventoryPreparationAttempt.status != 'superseded')
|
||||
.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
|
||||
|
||||
downloadable_inventory = resolve_task_inventory_download(task)
|
||||
for source_attempt in (getattr(latest_preparation, 'source_attempts', None) or []):
|
||||
inventory_sources.append({
|
||||
'source_code': source_attempt.source_code,
|
||||
'status': source_attempt.status,
|
||||
'inventory_file_id': source_attempt.inventory_file_id,
|
||||
})
|
||||
|
||||
artifact = None
|
||||
attempts = []
|
||||
if getattr(task, 'id', None):
|
||||
artifact = ShippingExportArtifact.query.filter_by(task_id=task.id).order_by(
|
||||
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
|
||||
).first()
|
||||
attempts = ShippingUploadAttempt.query.join(
|
||||
ShippingExportArtifact,
|
||||
ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id,
|
||||
).filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
).order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc()).all()
|
||||
latest_attempt = attempts[0] if attempts else None
|
||||
latest_status = str(getattr(latest_attempt, 'status', '') or '').lower()
|
||||
upload_outcome = (
|
||||
'succeeded' if latest_status == 'succeeded' else
|
||||
'failed' if latest_status in {'failed', 'timed_out'} else
|
||||
'unknown' if latest_status == 'unknown' else
|
||||
'running' if latest_status in {'pending', 'running'} else
|
||||
'awaiting_manual' if lifecycle_stage == 'upload_complete' else
|
||||
'not_started'
|
||||
)
|
||||
return {
|
||||
'preparation': {
|
||||
'status': preparation_status,
|
||||
'reason_code': gate.get('blocking_reason_code') or None,
|
||||
'frozen_order': {
|
||||
'task_no': task.task_no,
|
||||
'snapshot_id': task.order_snapshot_id,
|
||||
},
|
||||
'inventory_source_code': facts.get('inventory_source_code'),
|
||||
'match_status': facts.get('match_status'),
|
||||
'frozen_order_lines': frozen_order_lines,
|
||||
'lines': preparation_lines,
|
||||
'has_match_result': has_match_result,
|
||||
# 任务级库存准备源只说明文件获取进度;实际匹配源必须从 lines[].source_code 读取。
|
||||
'inventory_sources': inventory_sources,
|
||||
'inventory_file': {
|
||||
'available': downloadable_inventory is not None,
|
||||
'file_name': downloadable_inventory[1] if downloadable_inventory is not None else None,
|
||||
},
|
||||
'artifact': {
|
||||
'file_name': artifact.file_name if artifact is not None else None,
|
||||
'status': artifact.status if artifact is not None else 'not_generated',
|
||||
},
|
||||
},
|
||||
'upload': {
|
||||
'outcome': upload_outcome,
|
||||
'latest_attempt': ({
|
||||
'id': latest_attempt.id,
|
||||
'status': latest_attempt.status,
|
||||
'mode': latest_attempt.mode,
|
||||
'freight_ref_no': latest_attempt.freight_ref_no,
|
||||
'error_code': latest_attempt.error_code,
|
||||
'finished_at': latest_attempt.finished_at.isoformat() if latest_attempt.finished_at else None,
|
||||
} if latest_attempt is not None else None),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def build_task_ui_state(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
include_stage_context: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建单票任务 UI State。
|
||||
|
||||
@@ -712,8 +954,10 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
button for button in action_buttons
|
||||
if str((button or {}).get('id') or '') in _non_recovery_action_ids
|
||||
]
|
||||
steps = build_shipping_workflow_steps(task, ui.checkpoint)
|
||||
current_index = _derive_current_step_index(task)
|
||||
lifecycle = _task_lifecycle(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
|
||||
stage = _business_stage(lifecycle)
|
||||
steps = build_shipping_workflow_steps(task, ui.checkpoint, lifecycle_stage=stage['code'])
|
||||
current_index = int(stage['index']) - 1
|
||||
current_step = steps[current_index] if 0 <= current_index < len(steps) else None
|
||||
summary = _build_task_summary(
|
||||
task,
|
||||
@@ -732,8 +976,32 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
summary['diagnostic_hint'] = process_gate['diagnostic_hint']
|
||||
if process_gate.get('current_blocking_gate'):
|
||||
summary['allowed_actions'] = []
|
||||
stage = _business_stage(task=task, checkpoint=ui.checkpoint, process_gate=process_gate)
|
||||
actions = _unified_actions(process_gate=process_gate, action_buttons=action_buttons)
|
||||
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
|
||||
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧 checkpoint 动作,也只在
|
||||
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
|
||||
if resolve_task_export_download(task) is not None:
|
||||
download_action = _unified_action({
|
||||
'id': 'download_excel',
|
||||
'label': '下载 Excel',
|
||||
'kind': 'view',
|
||||
'enabled': True,
|
||||
}, default_kind='view')
|
||||
action_codes = {
|
||||
str((action or {}).get('code') or '')
|
||||
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
|
||||
}
|
||||
if download_action['code'] not in action_codes:
|
||||
actions['secondary'].append(download_action)
|
||||
stage_context = (
|
||||
_build_stage_context(
|
||||
task,
|
||||
lifecycle_stage=stage['code'],
|
||||
stp_facts=summary.get('stp_facts'),
|
||||
process_gate=process_gate,
|
||||
)
|
||||
if include_stage_context else None
|
||||
)
|
||||
checkpoint_payload = {
|
||||
"code": ui.checkpoint,
|
||||
"kind": str(ui.checkpoint_kind),
|
||||
@@ -749,6 +1017,9 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
"task_no": task.task_no,
|
||||
"batch_no": None,
|
||||
"stage": stage,
|
||||
"lifecycle_stage": stage["code"],
|
||||
"lifecycle_entries": lifecycle['lifecycle_entries'],
|
||||
"lifecycle_authority": lifecycle['lifecycle_authority'],
|
||||
"checkpoint": checkpoint_payload,
|
||||
"checkpoint_view": checkpoint_payload,
|
||||
"todo": {
|
||||
@@ -756,6 +1027,8 @@ def build_task_ui_state(task: ShippingNotice) -> dict[str, Any]:
|
||||
"message": summary.get("message"),
|
||||
},
|
||||
"actions": actions,
|
||||
# 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。
|
||||
**({'stage_context': stage_context} if stage_context is not None else {}),
|
||||
"reason": reason,
|
||||
"lifecycle_status": task.lifecycle_status,
|
||||
"checkpoint_code": ui.checkpoint,
|
||||
@@ -797,6 +1070,7 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
|
||||
execution = (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=task_pk)
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.order_by(ShippingProcessExecution.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
@@ -89,12 +89,19 @@ def _decode_png_to_ndarray(png_bytes: bytes) -> Any:
|
||||
|
||||
def is_ocr_engine_available() -> bool:
|
||||
"""
|
||||
探测 RapidOCR 是否可导入(不强制加载模型权重)。
|
||||
探测 XFA 自动标记所需 OCR 运行时是否完整(不强制加载模型权重)。
|
||||
|
||||
XFA 自动标记把 OCR 作为 datasets/Widget 的视觉交叉证据,因此 shipping
|
||||
Worker 必须在领取任务前通过此探测。仅检查 RapidOCR 本体不足以保证页图
|
||||
解码和 ONNX 推理可执行,故同时检查 OpenCV、NumPy 与 ONNX Runtime。
|
||||
|
||||
Returns:
|
||||
True 表示引擎模块可导入;False 表示本进程不可用。
|
||||
"""
|
||||
try:
|
||||
import cv2 # noqa: F401
|
||||
import numpy # noqa: F401
|
||||
import onnxruntime # noqa: F401
|
||||
import rapidocr_onnxruntime # noqa: F401
|
||||
|
||||
return True
|
||||
@@ -104,7 +111,7 @@ def is_ocr_engine_available() -> bool:
|
||||
|
||||
def recognize_preview_page(png_bytes: bytes) -> list[dict[str, Any]]:
|
||||
"""
|
||||
对 XFA 合成预览 PNG 页执行 OCR,返回归一化文本行。
|
||||
对 XFA 原生 PDF 渲染 PNG 页执行 OCR,返回归一化文本行。
|
||||
|
||||
核心逻辑:解码 PNG → 惰性调用 document_layout.ocr_pdf.extract_ocr_lines →
|
||||
将页面坐标映射为 0..1 normalized_bbox。引擎缺失或解码失败时抛 OCR_UNAVAILABLE,
|
||||
|
||||
Reference in new issue
Block a user