chore(shipping-notice): 统一货代发货生命周期阶段命名并优化全链路业务逻辑

This commit is contained in:
hugo committed 2026-08-17 19:56:51 +08:00
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'],
+84 -2
View File
@@ -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 或附件。"""
+8 -1
View File
@@ -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):
+2
View File
@@ -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()
+7 -2
View File
@@ -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:
@@ -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
)
+322 -48
View File
@@ -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,
+22
View File
@@ -56,6 +56,28 @@ def test_claim_next_shipping_recovers_stale_layout_jobs(app, monkeypatch):
assert recovered == [True]
def test_claim_next_shipping_claims_inventory_callback_process_job(app):
"""库存 RPA 回调收件 Job 必须由 shipping worker 消费,不能永久停在 queued。"""
from app import db
from app.jobs import store
with app.app_context():
job = Job(
domain='shipping_notice',
job_type=JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS.value,
status='queued',
payload_json={'callback_id': 'callback-test'},
)
db.session.add(job)
db.session.commit()
claimed = store.claim_next(queues=['shipping'])
assert claimed is not None
assert claimed['id'] == job.id
assert claimed['job_type'] == JobType.SHIPPING_INVENTORY_CALLBACK_PROCESS
def test_find_shipping_notice_job_id_matches_task_no(app):
from app import db
from app.jobs.queue import _find_shipping_notice_job_id
@@ -132,6 +132,20 @@ def test_p3_t4_primary_action_matrix(bcode, actions_in, retryable, expected_pa_c
assert got['variant'] == variant, label
@pytest.mark.pure_unit
def test_resolved_field_conflict_has_no_current_task_cta():
"""字段冲突清零后,保存校验留在底栏,当前任务不得再制造 CTA。"""
from app.services.shipping_notice.reconciliation_projector import project_case_primary_action
action = project_case_primary_action(
'waiting_human',
{},
['view', 'validate'],
)
assert action is None
@pytest.mark.pure_unit
def test_p3_t2_allowed_actions_inject_reconcile_and_remove_retry():
"""[P3 T2] 业务阻断 → REMOVE_SET 删除 retry_stp_auto_create 且注入 reconcile_and_progress。"""
@@ -183,6 +197,95 @@ def test_p3_t5_bundle_six_fields_shapes():
assert bundle['primary_action'] is None or isinstance(bundle['primary_action'], dict)
@pytest.mark.pure_unit
def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
"""正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。"""
from app.services.shipping_notice import reconciliation_projector
case = _fake_case(status='draft', candidate_id=None)
monkeypatch.setattr(
reconciliation_projector,
'_project_case_formal_gate_summary',
lambda _case: {
'current_gate': {
'gate_code': 'field_completeness',
'status': 'blocked_manual',
'blocking_reason_code': 'required_field_missing',
'next_action_code': 'edit_order_fields',
},
'current_blocking_gate': {
'gate_code': 'field_completeness',
'status': 'blocked_manual',
'blocking_reason_code': 'required_field_missing',
'next_action_code': 'edit_order_fields',
},
'blocking_reason_code': 'required_field_missing',
'next_action_code': 'edit_order_fields',
},
)
bundle = reconciliation_projector.project_review_case_projection_bundle(
case,
validation={'can_build': False, 'can_auto_create': False},
post_confirm=None,
is_admin=False,
)
assert bundle['current_gate']['gate_code'] == 'field_completeness'
assert bundle['current_gate']['blocking_reason_code'] == 'required_field_missing'
assert bundle['blocking_reason']['code'] == 'required_field_missing'
assert bundle['user_status'] == 'waiting_human'
@pytest.mark.pure_unit
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
from app.services.shipping_notice.reconciliation_projector import (
_project_case_formal_gate_facts,
)
facts = _project_case_formal_gate_facts({
'current_gate': {
'gate_code': 'inventory_source_routing',
'status': 'pending',
'blocking_reason_code': None,
'next_action_code': None,
},
'current_blocking_gate': None,
'blocking_reason_code': None,
'next_action_code': None,
})
assert facts is not None
current_gate, blocking_reason, user_status = facts
assert current_gate['gate_code'] == 'inventory_source_routing'
assert blocking_reason['code'] is None
assert user_status == 'running'
@pytest.mark.pure_unit
def test_pending_order_freeze_readiness_waits_for_the_user_to_submit_validation():
"""建单前校验未提交时必须提示人工保存,不能伪装为自动处理中。"""
from app.services.shipping_notice.reconciliation_projector import (
_project_case_formal_gate_facts,
)
facts = _project_case_formal_gate_facts({
'current_gate': {
'gate_code': 'order_freeze_readiness',
'status': 'pending',
'blocking_reason_code': None,
'next_action_code': None,
},
})
assert facts is not None
current_gate, blocking_reason, user_status = facts
assert current_gate['gate_code'] == 'order_freeze_readiness'
assert blocking_reason['code'] is None
assert user_status == 'waiting_human'
# ============================================================
# [P4 T6] 管理员权限拦截(纯函数 PRE-CHECK,通过 monkeypatch 替换锁 DB 查询)
# ============================================================
@@ -4,6 +4,8 @@ from __future__ import annotations
import importlib.util
import sys
import threading
import time
from pathlib import Path
@@ -60,3 +62,44 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
content = sentinel.read_text(encoding="utf-8")
assert "scope_id=hxops-rpa-test-data" in content
assert "host=WIN-RPA-01" in content
def test_maybe_send_heartbeat_does_not_block_trigger_loop_when_http_stalls(tmp_path, monkeypatch):
"""断言底层 HTTP 卡住时,主 Worker 仍能立即继续扫描 Trigger。"""
module = _load_freight_rpa_heartbeat_module()
release_request = threading.Event()
request_started = threading.Event()
calls: list[dict] = []
def stalled_post(payload):
calls.append(payload)
request_started.set()
release_request.wait(timeout=2)
return False
monkeypatch.setattr(module, "post_heartbeat", stalled_post)
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "15")
started = time.monotonic()
sent_at = module.maybe_send_heartbeat(
trigger_dir=tmp_path,
drop_dir=tmp_path,
last_sent_mono=0.0,
force=True,
)
# 核心断言:投递而非等待卡住的 HTTP 请求,扫描循环可立即继续。
assert time.monotonic() - started < 0.2
assert sent_at > 0
assert request_started.wait(timeout=0.5)
module.maybe_send_heartbeat(
trigger_dir=tmp_path,
drop_dir=tmp_path,
last_sent_mono=0.0,
force=True,
)
# 同一时刻只允许一个后台请求,避免后端异常时线程无限累积。
assert len(calls) == 1
release_request.set()
assert module._HEARTBEAT_THREAD is not None
module._HEARTBEAT_THREAD.join(timeout=1)
+171
View File
@@ -185,6 +185,138 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
}
def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_path):
"""Crane 动态 Warehouse 在导出前未知时,v2 trigger 不应被身份校验拒绝。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_batch_crane_dynamic.json"
source = {
"source_code": "CRANE",
"connector_type": "crane",
"task_no": "SN-CRANE-DYNAMIC",
"callback_id": "PSR-CRANE-DYNAMIC:C1",
"source_run_no": "PSR-CRANE-DYNAMIC",
"attempt_no": 2,
"lease_token": "lease-crane",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
}
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "BATCH-CRANE-DYNAMIC:batch:C1",
"batch_run_no": "BATCH-CRANE-DYNAMIC",
"task_no": "SN-CRANE-DYNAMIC",
"inventory_sources": [source],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
assert completed["results"][0]["callback_id"] == "PSR-CRANE-DYNAMIC:C1"
assert completed["results"][0]["expected_warehouse_id"] is None
assert (processed_dir / trigger_path.name).is_file()
def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch, tmp_path):
"""可识别的非法 batch trigger 必须回传 batch callback_id,供平台记录拒绝终态。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_batch_invalid.json"
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "BATCH-INVALID:batch:C1",
"batch_run_no": "BATCH-INVALID",
"task_no": "SN-BATCH-INVALID",
"inventory_sources": [{
"source_code": "DBS",
"connector_type": "dbs",
"task_no": "SN-BATCH-INVALID",
"callback_id": "PSR-BATCH-INVALID:C1",
"source_run_no": "PSR-BATCH-INVALID",
"attempt_no": 2,
"lease_token": "lease-batch",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
}],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
assert callbacks[0][1]["callback_id"] == "BATCH-INVALID:batch:C1"
assert callbacks[0][1]["identity_errors"] == ["inventory_sources[0].expected_warehouse_id"]
def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path):
"""Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_batch_interrupt.json"
source = {
"source_code": "CRANE",
"connector_type": "crane",
"task_no": "SN-CRANE-INTERRUPT",
"callback_id": "PSR-CRANE-INTERRUPT:C1",
"source_run_no": "PSR-CRANE-INTERRUPT",
"attempt_no": 1,
"lease_token": "lease-interrupt",
"candidate_set_id": 12,
"execution_id": 88,
"gate_id": 901,
}
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "BATCH-INTERRUPT:batch:C1",
"batch_run_no": "BATCH-INTERRUPT",
"task_no": "SN-CRANE-INTERRUPT",
"inventory_sources": [source],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
stopped = []
class _Context:
def close(self):
raise KeyboardInterrupt
class _Playwright:
def stop(self):
stopped.append(True)
monkeypatch.setattr(worker, "_open_browser", lambda *_args, **_kwargs: (_Playwright(), _Context(), object(), tmp_path / "profile"))
monkeypatch.setattr(worker, "_ensure_crane_session", lambda *_args, **_kwargs: None)
monkeypatch.setattr(worker, "_export_crane_inventory_source", lambda *_args, **_kwargs: (_ for _ in ()).throw(KeyboardInterrupt()))
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
with pytest.raises(KeyboardInterrupt):
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
assert stopped == [True]
assert [path for path, _body in callbacks] == ["/api/shipping-notice/rpa/inventory-batch-claimed"]
assert trigger_path.is_file()
assert not (processed_dir / trigger_path.name).exists()
def test_env_strips_wrapping_quotes(monkeypatch):
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
worker = _load_freight_rpa_worker()
@@ -1108,6 +1240,45 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
}
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
"""DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。"""
worker = _load_freight_rpa_worker()
observed: dict[str, object] = {}
class _FakePage:
def set_default_timeout(self, value: int) -> None:
observed["timeout"] = value
class _FakeContext:
pages = [_FakePage()]
class _FakeChromium:
def launch_persistent_context(self, profile: str, **kwargs):
observed["profile"] = profile
return _FakeContext()
class _FakePlaywright:
chromium = _FakeChromium()
class _FakeStarter:
def start(self):
return _FakePlaywright()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true")
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
_playwright, context, page, profile_dir = worker._open_browser(
tmp_path / "downloads", reuse_dsv_session=True
)
assert context is not None
assert page is not None
assert profile_dir == tmp_path / "profile" / "dsv360_session"
assert observed["profile"] == str(profile_dir)
assert worker._should_cleanup_browser_profile(profile_dir) is False
def test_is_dsv_username_page_ignores_login_method_page_text():
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
worker = _load_freight_rpa_worker()
@@ -16,6 +16,10 @@ def _load_dsv_report_export():
return _load_rpa_module("dsv_report_export")
def _load_dsv_auth_login_flow():
return _load_rpa_module("dsv_auth_login_flow")
def _load_rpa_module(module_name: str):
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py"
scripts_dir = str(module_path.parent)
@@ -195,6 +199,128 @@ def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(
reset.assert_not_called()
def test_dsv_session_prepare_emits_elapsed_stage_logs(monkeypatch):
"""DSV session 准备应记录完整耗时,供真实运行区分认证和首页等待。"""
worker = _load_dsv_report_export()
page = MagicMock()
chain = MagicMock()
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
monkeypatch.setattr(worker, "_is_dsv_session_active", MagicMock(return_value=True))
monkeypatch.setattr(worker, "_is_dsv_in_report_navigation_context", MagicMock(return_value=False))
monkeypatch.setattr(worker, "_wait_for_dsv_home_ready", MagicMock())
monkeypatch.setattr(worker, "_wait_for_dsv_reports_nav_stable", MagicMock())
worker._ensure_dsv_session(page, "https://s360.dbschenker.com/")
assert [call.args[:2] for call in chain.call_args_list] == [
("session_prepare", "start"),
("session_prepare", "end"),
]
def test_dsv_navigation_emits_elapsed_stage_logs(monkeypatch):
"""Reports 到参数页的整段导航应记录耗时,不能只依赖零散 DOM 调试日志。"""
worker = _load_dsv_report_export()
page = MagicMock()
chain = MagicMock()
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
monkeypatch.setattr(worker, "_env", lambda _key, default=None: "")
monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock())
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
worker._navigate_dsv_to_report_form(
page,
{"navigation": {"program_label": "AWS", "report_name": "On Hand Inventory by Location"}},
)
assert [call.args[:2] for call in chain.call_args_list] == [
("report_navigation", "start"),
("report_navigation", "end"),
]
def test_dsv_menu_item_uses_compatibility_fallback_only_after_fast_path_misses(monkeypatch):
"""快速菜单点击未确认下一级时,必须保留原兼容路径,避免降低 DSV 成功率。"""
navigation = _load_rpa_module("dsv_navigation")
page = MagicMock()
compatibility = MagicMock()
monkeypatch.setattr(navigation, "_try_dsv_menu_item_fast_path", MagicMock(return_value=False))
monkeypatch.setattr(navigation, "_click_dsv_menu_item_compat", compatibility)
navigation._click_dsv_menu_item(page, "AWS", next_text="Inventory")
compatibility.assert_called_once_with(page, "AWS", next_text="Inventory")
def test_dsv_report_group_skips_compatibility_fallback_after_fast_path_confirms(monkeypatch):
"""快速路径确认报表已展开后,不应再触发耗时的 Report Group 兼容点击。"""
navigation = _load_rpa_module("dsv_navigation")
page = MagicMock()
compatibility = MagicMock()
monkeypatch.setattr(navigation, "_try_dsv_report_group_fast_path", MagicMock(return_value=True))
monkeypatch.setattr(navigation, "_click_dsv_report_group_compat", compatibility)
navigation._click_dsv_report_group(page, "Inventory", next_text="On Hand Inventory by Location")
compatibility.assert_not_called()
def test_dsv_report_execution_emits_parameter_and_download_stage_logs(monkeypatch):
"""报表结果就绪与 Excel 下载应分段计时,且不应等待不可靠的 networkidle。"""
worker = _load_dsv_report_export()
page = MagicMock()
download = MagicMock()
download_context = MagicMock()
download_context.__enter__.return_value = MagicMock(value=download)
download_context.__exit__.return_value = False
page.expect_download.return_value = download_context
chain = MagicMock()
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
monkeypatch.setattr(worker, "_fill_report_parameters", MagicMock())
monkeypatch.setattr(worker, "_click_dsv_view_report", MagicMock())
monkeypatch.setattr(worker, "_wait_dsv_report_ready", MagicMock())
monkeypatch.setattr(worker, "_dsv_report_has_inventory_data_rows", MagicMock(return_value=True))
monkeypatch.setattr(worker, "_click_dsv_export_excel", MagicMock())
assert worker._run_dsv_inventory_export_from_form(page, {}) is download
assert [call.args[:2] for call in chain.call_args_list] == [
("report_parameter_fill", "start"),
("report_parameter_fill", "end"),
("report_execute_and_download", "start"),
("report_result_ready", "start"),
("report_result_ready", "end"),
("excel_export_and_download", "start"),
("excel_download_event", "start"),
("excel_download_event", "end"),
("excel_export_and_download", "end"),
("report_execute_and_download", "end"),
]
page.wait_for_load_state.assert_not_called()
def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
"""持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。"""
flow = _load_dsv_auth_login_flow()
page = MagicMock()
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password")
selector_wait = MagicMock()
auth_ready = MagicMock()
monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True)
monkeypatch.setattr(flow, "_wait_for_visible_selector", selector_wait)
monkeypatch.setattr(flow, "_wait_for_dsv_auth_page_ready", auth_ready)
flow._maybe_auto_login_dsv(page)
# 核心断言:会话已在 Portal 时,不能走用户名 15 秒探测或认证页轮询。
selector_wait.assert_not_called()
auth_ready.assert_not_called()
def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch):
"""program/report 变化时仍应回 portal 首页。"""
worker = _load_dsv_report_export()
@@ -205,6 +205,84 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a
assert count >= 1
def test_contract_04a_sweeper_skips_manual_draft_waiting_for_user_validation(app):
"""人工草稿等待“保存并校验”时,恢复扫描不得再次改写 Draft 版本。"""
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
manual_case = SimpleNamespace(
id=41,
case_no='SORC-P1-04A',
status='ready',
confirmed_task_id=None,
current_draft=SimpleNamespace(
header_values_json={},
lines_json=[{'values': {'part_number': {'source': 'manual', 'value': 'P-1'}}}],
),
)
with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[41]), patch.object(
sw, '_scan_stale_inventory_attempts', return_value=0,
), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch(
'app.services.shipping_notice.shipping_recovery_sweeper_service.db',
) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as review_case, patch(
'app.services.shipping_notice.order_review_auto_progress_coordinator.'
'reconcile_single_case_for_auto_progress',
) as coordinator:
mock_session = MagicMock()
mock_session.begin_nested.return_value = MagicMock()
type(mock_db).session = mock_session
review_case.query.filter_by.return_value.with_for_update.return_value.first.return_value = manual_case
count = sw.shipping_recovery_tick()
# 这条 Case 必须留给用户显式保存;后台补偿不应启动校验或推进。
assert count == 0
coordinator.assert_not_called()
def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
"""批量协调也不得为人工草稿重复写入 validation 版本。"""
from app.services.shipping_notice import order_review_auto_progress_coordinator as coord
run = SimpleNamespace(id=42, run_no='SNER-P1-04B')
case = SimpleNamespace(
id=42,
case_no='SORC-P1-04B',
status='ready',
confirmed_task_id=None,
document_id=420,
candidate_id=42,
run_id=42,
run=run,
owner_user_id=1,
current_draft=SimpleNamespace(
draft_version=8,
header_values_json={},
lines_json=[{'values': {'part_number': {'source': 'manual', 'value': 'P-1'}}}],
),
)
with patch(
'app.services.shipping_notice.order_review_auto_progress_coordinator.ShippingOrderReviewCase',
) as review_case, patch.object(
coord.db, 'session', MagicMock(),
) as session_mock, patch.object(
coord, '_customer_step_for_case', return_value=('skipped', None),
), patch(
'app.services.shipping_notice.order_review_draft_service.validate_draft',
) as validate_mock, patch(
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
return_value={'status': 'waiting_manual_validation'},
):
review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
SimpleNamespace(id=42),
]
session_mock.get.return_value = case
result = coord.reconcile_run_review_cases_for_auto_progress(run=run)
validate_mock.assert_not_called()
assert result[0]['validate_status'] == 'waiting_manual_validation'
def test_contract_05_recovery_tick_scans_stale_inventory_attempts(app):
"""合同 5:shipping recovery tick 必须调用逐源库存超时扫描。"""
from app.services.shipping_notice import shipping_recovery_sweeper_service as sw
@@ -9,6 +9,8 @@ tests/test_shipping_auto_progress_p0_3.py
from __future__ import annotations
from unittest.mock import patch
from app import db
from app.models import (
Job,
@@ -137,6 +139,34 @@ def test_formal_execution_queues_one_gate_attempt_job(app):
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 1
def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
"""人工导航动作不得因 Gate 责任方为 worker 而被自动投递执行。"""
task = _task_with_candidate()
execution = ensure_execution_for_workflow_version(review_case_id=903, task_id=int(task.id))
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'inventory_rpa_timeout'
gate.next_action_code = 'upload_inventory_file'
execution.status = 'blocked'
execution.current_gate_code = 'inventory_preparation'
execution.primary_next_action_code = 'upload_inventory_file'
execution.responsible_party = 'worker'
task.active_process_execution_id = int(execution.id)
db.session.commit()
# 同步事实是本用例之外的职责;这里固定复现“同步后仍需人工导航”的当前 Gate。
with patch(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
):
result = submit_auto_progress(task=task, trigger='callback_recovery')
assert result['status'] == 'waiting_human'
assert result['gate_code'] == 'inventory_preparation'
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0
def test_active_stp_job_without_retry_metadata_is_reused(app):
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
from types import SimpleNamespace
@@ -42,9 +42,11 @@ def test_manual_upload_records_receipt_asset(app):
)
attempt = record_manual_upload(
task, artifact_id=artifact.id, evidence_asset_no=payload['asset_no'], operator_id=user.id,
freight_ref_no='FREIGHT-RECEIPT-1',
)
assert attempt.mode == 'manual'
assert attempt.status == 'succeeded'
assert attempt.evidence_asset_id is not None
assert attempt.freight_ref_no == 'FREIGHT-RECEIPT-1'
assert db.session.get(type(reservation), reservation.id).status == 'uploaded'
assert ShippingUploadAttempt.query.count() == 1
@@ -34,6 +34,13 @@ def _with_v2_batch_envelope(payload: dict) -> dict:
return v2_inventory_batch_payload(payload)
def _process_batch_callback(payload: dict) -> dict:
"""在测试中执行 Worker 的异步 batch 处理体,保留既有业务断言。"""
from app.services.shipping_notice.inventory_rpa_workflow import process_rpa_report_inventory_batch
return process_rpa_report_inventory_batch(_with_v2_batch_envelope(payload))
def _tool_headers():
return {"Content-Type": "application/json", "X-Integration-Key": "test-integration-key"}
@@ -418,11 +425,11 @@ def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
with app.app_context():
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
result = _process_batch_callback({
"run_no": "RUN-EMPTY-ITEM",
"trigger_type": "scheduled",
"results": [{}],
}))
})
assert result["status"] == "ok"
assert result["result_status"] == "failed"
assert result["data"]["result_status"] == "failed"
@@ -444,7 +451,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
result = _process_batch_callback({
"run_no": "RUN-MIXED",
"trigger_type": "scheduled",
"results": [
@@ -462,7 +469,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
"error_message": "timeout",
},
],
}))
})
assert result["status"] == "ok"
assert result["result_status"] == "partial_failed"
assert result["data"]["result_status"] == "partial_failed"
@@ -484,11 +491,11 @@ def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
result = _process_batch_callback({
"run_no": "RUN-MAPPING-CONFIRMED",
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
}))
})
assert result["success_count"] == 1
snapshot = ShippingInventoryFile.query.filter_by(rpa_run_no="RUN-MAPPING-CONFIRMED").one()
assert snapshot.mapping_source == "parsing_profile"
@@ -503,7 +510,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
with app.app_context():
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
result = _process_batch_callback({
"run_no": "RUN-ALL-FAIL",
"trigger_type": "scheduled",
"results": [{
@@ -513,7 +520,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
"success": False,
"error_message": "timeout",
}],
}))
})
assert result["status"] == "ok"
assert result["result_status"] == "failed"
assert result["failed_count"] == 1
@@ -597,8 +604,9 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon
def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
"""batch 顶层 run_no 应注入 result item,带 task_no 的成功项可入库。"""
"""任务型 RPA 回调只收件入队,不得同步解析 Excel 或推进库存任务。"""
from app import db
from app.models import Job
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
drop_dir = tmp_path / "drop"
@@ -625,7 +633,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
db.session.add(task)
db.session.commit()
result = rpa_report_inventory_batch({
receipt = rpa_report_inventory_batch(_with_v2_batch_envelope({
"run_no": "RUN-BATCH-TOP",
"trigger_type": "on_demand",
"results": [{
@@ -636,11 +644,40 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path):
"source_code": task.inventory_source_code,
"warehouse_id": task.inventory_warehouse_id,
}],
})
}))
db.session.refresh(task)
assert result["status"] == "ok"
assert result["success_count"] == 1
assert receipt["status"] == "ok"
assert receipt["result_status"] == "accepted"
assert task.inventory_snapshot_id is None
job = db.session.get(Job, int(receipt["data"]["job_id"]))
assert job is not None
assert job.status == "queued"
assert job.job_type == "shipping_inventory_callback_process"
assert job.payload_json["batch_run_no"] == "RUN-BATCH-TOP"
received_path = Path(job.payload_json["results"][0]["file_path"])
assert received_path.is_file()
assert received_path != sample
assert received_path.parent.name == "test-callback_RUN-BATCH-TOP"
sample.unlink()
replay = rpa_report_inventory_batch(_with_v2_batch_envelope({
"run_no": "RUN-BATCH-TOP",
"trigger_type": "on_demand",
"results": [{
"task_no": task.task_no,
"status": "success",
"success": True,
"file_path": str(sample),
"source_code": task.inventory_source_code,
"warehouse_id": task.inventory_warehouse_id,
}],
}))
assert replay["result_status"] == "accepted"
assert replay["data"]["job_id"] == job.id
result = _process_batch_callback(job.payload_json)
db.session.refresh(task)
assert result["result_status"] == "success"
assert task.inventory_snapshot_id is not None
@@ -669,7 +706,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
db.session.add(task)
db.session.commit()
result = rpa_report_inventory_batch({
result = _process_batch_callback({
"run_no": "RUN-BATCH-FAIL",
"trigger_type": "on_demand",
"results": [{
@@ -683,7 +720,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path):
assert result["status"] == "ok"
assert result["failed_count"] == 1
assert task.pending_human_reason == "rpa_pending"
assert task.pending_human_reason == "rpa_exhausted"
assert task.error_message
failed_events = ShippingTaskEvent.query.filter_by(
task_id=task.id,
@@ -745,7 +782,7 @@ def test_batch_callback_rejects_unknown_task_no(app, tmp_path):
with app.app_context():
before = ShippingInventoryFile.query.filter_by(snapshot_status="ready").count()
result = rpa_report_inventory_batch({
result = _process_batch_callback({
"run_no": "RUN-UNKNOWN-TASK",
"trigger_type": "on_demand",
"results": [{
@@ -819,7 +856,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path):
db.session.add(task)
db.session.commit()
result = rpa_report_inventory_batch({
result = _process_batch_callback({
"run_no": "RUN-BATCH-NO-IDENT",
"trigger_type": "on_demand",
"results": [{
@@ -855,7 +892,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
)
with app.app_context():
warmup = rpa_report_inventory_batch({
warmup = _process_batch_callback({
"run_no": run_no,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
@@ -886,7 +923,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey
db.session.add(task)
db.session.commit()
result = rpa_report_inventory_batch({
result = _process_batch_callback({
"run_no": run_no,
"trigger_type": "on_demand",
"results": [scheduled_rpa_batch_item(
@@ -931,7 +968,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
wb.close()
with app.app_context():
first_result = rpa_report_inventory_batch({
first_result = _process_batch_callback({
"run_no": run_no,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
@@ -944,7 +981,7 @@ def test_reused_snapshot_rejects_content_mismatch(app, tmp_path):
original_lines = list(snap.inventory_lines_json or [])
assert first_result["success_count"] == 1
second_result = rpa_report_inventory_batch({
second_result = _process_batch_callback({
"run_no": run_no,
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item(
@@ -1012,7 +1049,7 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
db.session.commit()
before_b_status = task_b.pending_human_reason
result = rpa_report_inventory_batch({
result = _process_batch_callback({
"run_no": run_no,
"trigger_type": "on_demand",
"results": [
@@ -1040,6 +1077,65 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path,
assert task_b.pending_human_reason == before_b_status
def test_batch_ingest_failure_does_not_confirm_per_source_attempt(app, tmp_path, monkeypatch):
"""Excel 入库失败前不得把逐源 RPA Attempt 标为成功或触发自动推进。"""
from app import db
drop_dir = tmp_path / "drop"
drop_dir.mkdir(parents=True, exist_ok=True)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
sample = drop_dir / "failed_before_confirm.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
callback_calls: list[dict] = []
def fail_loaded(*_args, **_kwargs):
raise RuntimeError("loaded boom")
def record_per_source_callback(*_args, **kwargs):
callback_payload = dict(kwargs.get("callback_payload") or {})
if callback_payload.get("inventory_file_no"):
callback_calls.append(callback_payload)
return "succeeded", None
monkeypatch.setattr(
"app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response",
fail_loaded,
)
monkeypatch.setattr(
"app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler",
record_per_source_callback,
)
with app.app_context():
task = ShippingNotice(
task_no="SN-BATCH-DEFER-CONFIRM",
source_type="manual",
pending_human_reason="rpa_pending",
lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}],
)
_confirm_direct_rpa_task_customer(task)
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-DEFER-CONFIRM")
db.session.add(task)
db.session.commit()
result = _process_batch_callback({
"run_no": "RUN-BATCH-DEFER-CONFIRM",
"trigger_type": "on_demand",
"results": [scheduled_rpa_batch_item(
"DSV360_AWSDU",
success=True,
file_path=str(sample),
task_no=task.task_no,
)],
})
assert result["failed_count"] == 1
# 关键断言:保存点内入库失败时,禁止先写 RPA 成功事实并创建后续自动推进。
assert callback_calls == []
def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, monkeypatch):
"""共享快照被另一任务复用失败时,不得影响已关联任务的 active link。"""
from app import db
@@ -1075,7 +1171,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
db.session.add_all([task_ok, task_fail])
db.session.commit()
ok_result = rpa_report_inventory_batch({
ok_result = _process_batch_callback({
"run_no": run_no,
"trigger_type": "on_demand",
"results": [scheduled_rpa_batch_item(
@@ -1097,7 +1193,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m
"app.services.shipping_notice.inventory_rpa_workflow.ingest_inventory_file",
lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("ingest boom")),
)
fail_result = rpa_report_inventory_batch({
fail_result = _process_batch_callback({
"run_no": run_no,
"trigger_type": "on_demand",
"results": [scheduled_rpa_batch_item(
@@ -1282,7 +1378,7 @@ def test_callback_move_failure_enqueues_cleanup_job(app, tmp_path, monkeypatch):
"run_no": "RUN-MOVE-FAIL",
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
}
result = rpa_report_inventory_batch(payload)
result = _process_batch_callback(payload)
queue = callback_cleanup_queue_dir()
jobs = list(queue.glob("move_*.json")) if queue else []
@@ -1328,7 +1424,7 @@ def test_callback_quarantine_failure_still_enqueues_cleanup_job(app, tmp_path, m
"run_no": "RUN-QUARANTINE-FAIL",
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
}
result = rpa_report_inventory_batch(payload)
result = _process_batch_callback(payload)
queue = callback_cleanup_queue_dir()
jobs = list(queue.glob("move_*.json")) if queue else []
@@ -398,7 +398,7 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
from tests.test_shipping_order_review_service import _materialized_run
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-REV-DL')
user, agent, session, intake, document = _seed_run_input(suffix='TODO-REV-DL')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.result_json = {
@@ -408,6 +408,15 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
'conflicts': [],
}],
}
from app.models import ShippingOrderCandidate
db.session.add(ShippingOrderCandidate(
candidate_no='CAND-TODO-REV-DL',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='todo-review-deep-link',
order_extraction_run_id=run.id,
))
db.session.commit()
cases = ensure_run_review_cases(run=run)
assert cases
@@ -423,12 +432,38 @@ def test_list_my_todos_includes_open_review_case_with_run_deep_link(app):
assert hit['conversation_id'] == session.session_id
assert hit['can_handle'] is True
assert hit['ui_state']['summary']['entry_surface'] == 'review_workbench'
assert hit['ui_state']['lifecycle_stage'] == 'order_review'
assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [
'available', 'current', 'unavailable', 'unavailable',
]
counts = count_my_todos(user.id)
assert counts['pending'] >= 1
assert counts['total_pending_badge'] == counts['pending']
def test_open_review_case_without_current_candidate_has_no_lifecycle_entry(app):
"""历史空 Review Case 可以处置,但不能被待办页默认授权进入订单生命周期。"""
with app.app_context():
from app import db
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from app.services.shipping_notice.query_service import list_my_todos
from tests.test_shipping_order_review_service import _materialized_run
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, _document = _seed_run_input(suffix='TODO-EMPTY-CASE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
unit.result_json = {'orders': []}
db.session.commit()
case = ensure_run_review_cases(run=run)[0]
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
hit = next(item for item in pending['items'] if item.get('review_case_no') == case.case_no)
assert hit['ui_state']['lifecycle_stage'] is None
assert hit['ui_state']['lifecycle_entries'] == []
def test_list_my_todos_includes_orphan_parse_failed_intake(app):
"""
未建 OT 且解析失败的 Intake 须进入 pending,并暴露 conversation 深链字段。
@@ -483,6 +518,8 @@ def test_list_my_todos_includes_orphan_parse_failed_intake(app):
assert hit['source_file_name'] == 'orphan-fail.pdf'
assert hit['can_handle'] is True
assert hit['ui_state']['summary']['entry_surface'] == 'conversation_processing'
assert hit['ui_state']['lifecycle_stage'] == 'intake_parse'
assert hit['ui_state']['lifecycle_entries'] == []
filtered = list_my_todos(
user.id, bucket='pending', page=1, page_size=50, todo_category='intake_parse',
+428 -5
View File
@@ -6,7 +6,9 @@ tests/test_shipping_notice_ui_state.py
逻辑:build_task_ui_state.summary 含 STP 可解释字段;复核 vs 待上传入口面正确。
"""
from app.models import ShippingNotice
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User
from app.services.shipping_notice.constants import (
CP_EXPORT_READY,
CP_PARSE_REVIEW,
@@ -80,6 +82,19 @@ def test_build_task_ui_state_summary_has_required_keys(app) -> None:
assert "stp_facts" not in state["summary"]
def test_task_ui_state_stage_context_is_opt_in(app) -> None:
"""列表等轻量调用默认不得加载阶段工作面详情。"""
with app.app_context():
task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual")
state = build_task_ui_state(task)
detailed_state = build_task_ui_state(task, include_stage_context=True)
# 关键断言:只有详情接口显式请求时才查询行、Artifact 和上传 Attempt。
assert "stage_context" not in state
assert "stage_context" in detailed_state
def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(app) -> None:
"""业务 UI 只消费四阶段与后端统一 actions,不再要求前端解释旧七步。"""
with app.app_context():
@@ -98,6 +113,111 @@ def test_build_task_ui_state_exposes_four_business_stages_and_unified_actions(ap
assert all("code" in item and "kind" in item for item in state["actions"]["secondary"])
def test_build_task_ui_state_exposes_backend_owned_lifecycle_entries(app) -> None:
"""正式工作台的四个入口必须由后端下发,页面不能按阶段顺序自行生成。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-LIFECYCLE-ENTRIES",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual",
)
state = build_task_ui_state(task)
assert state["lifecycle_stage"] == "order_review"
assert state["lifecycle_entries"] == [
{"code": "intake_parse", "state": "available", "target_surface": "order_lifecycle_workbench"},
{"code": "order_review", "state": "current", "target_surface": "order_lifecycle_workbench"},
{"code": "fulfillment_prep", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
{"code": "upload_complete", "state": "unavailable", "target_surface": "order_lifecycle_workbench"},
]
def test_task_ui_state_ignores_superseded_process_execution(app) -> None:
"""被替代的 Execution 不能继续给正式工作台下发历史 Gate 或按钮。"""
with app.app_context():
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
)
user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual')
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.status = 'superseded'
db.session.flush()
state = build_task_ui_state(task)
assert state['process_gate'] is None
def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
"""正式 Gate 与旧任务字段冲突时,任务详情必须与批次中心同样以 Gate 裁决阶段。"""
with app.app_context():
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(
task_no='SN-UI-GATE-AUTHORITY',
user_id=user.id,
source_type='manual',
# 模拟历史字段尚未同步:旧字段仍像解析复核。
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
)
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.current_gate_code = 'inventory_matching'
db.session.flush()
state = build_task_ui_state(task)
assert state['lifecycle_stage'] == 'fulfillment_prep'
assert state['lifecycle_authority'] == 'process_gate'
assert state['stage']['code'] == 'fulfillment_prep'
assert state['current_step']['code'] == 'fulfillment_prep'
assert [entry['state'] for entry in state['lifecycle_entries']] == [
'available', 'available', 'current', 'unavailable',
]
def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> None:
"""正式人工上传 Gate 必须裁决为通知完成,不受旧复核字段影响。"""
with app.app_context():
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
task = ShippingNotice(
task_no='SN-UI-UPLOAD-GATE-AUTHORITY',
user_id=user.id,
source_type='manual',
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
)
db.session.add(task)
db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
execution.current_gate_code = 'manual_upload_handoff'
db.session.flush()
state = build_task_ui_state(task)
assert state['lifecycle_stage'] == 'upload_complete'
assert state['lifecycle_authority'] == 'process_gate'
assert state['stage']['code'] == 'upload_complete'
assert [entry['state'] for entry in state['lifecycle_entries']] == [
'available', 'available', 'available', 'current',
]
def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(app) -> None:
"""库存匹配/上传结果只映射四个业务阶段。"""
with app.app_context():
@@ -113,7 +233,10 @@ def test_build_task_ui_state_maps_domain_facts_to_fulfillment_and_upload_stages(
upload_status="uploaded",
)
assert build_task_ui_state(fulfillment)["stage"]["code"] == "fulfillment_prep"
assert build_task_ui_state(upload)["stage"]["code"] == "upload_complete"
upload_state = build_task_ui_state(upload, include_stage_context=True)
assert upload_state["stage"]["code"] == "upload_complete"
# 旧 Task 字段只能决定工作面;没有可追溯 UploadAttempt 时不得显示上传成功。
assert upload_state["stage_context"]["upload"]["outcome"] == "awaiting_manual"
def test_entry_surface_parse_review_is_review_workbench(app) -> None:
@@ -130,7 +253,7 @@ def test_entry_surface_parse_review_is_review_workbench(app) -> None:
def test_entry_surface_export_ready_is_task_workbench(app) -> None:
"""Excel 待人工上传登记应进入任务处理工作台(下载 + 登记)。"""
"""Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-EXPORT",
@@ -149,10 +272,59 @@ def test_entry_surface_export_ready_is_task_workbench(app) -> None:
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
assert "download_excel" in button_ids
# 关键断言:没有可验证 Artifact 时,遗留 export_file_name 不得生成下载按钮。
assert "download_excel" not in button_ids
assert "mark_manual_uploaded" in button_ids
def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypatch) -> None:
"""下载入口必须由后端 Artifact 解析结果裁决,而不是由遗留文件名裁决。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-RESOLVED-EXPORT",
source_type="manual",
export_file_path="/tmp/shipping-export.xlsx",
export_file_name="shipping-export.xlsx",
)
monkeypatch.setattr(
'app.services.shipping_notice.ui_state.resolve_task_export_download',
lambda _task: (object(), 'shipping-export.xlsx'),
)
state = build_task_ui_state(task)
button_ids = [
item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
assert "download_excel" in button_ids
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
with app.app_context():
task = ShippingNotice(task_no="SN-UI-GATE-EXPORT", source_type="manual")
monkeypatch.setattr(
'app.services.shipping_notice.ui_state.resolve_task_export_download',
lambda _task: (None, 'shipping-export.xlsx'),
)
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda _task: {
'current_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
'current_blocking_gate': {'gate_code': 'freight_upload_rpa', 'evaluation_version': 3},
'primary_action': {'code': 'retry_freight_upload_rpa', 'label': '重新上传'},
'action_presentation': [],
},
)
state = build_task_ui_state(task)
assert state['actions']['primary']['code'] == 'retry_freight_upload_rpa'
assert [item['code'] for item in state['actions']['secondary']] == ['download_excel']
def test_stp_facts_candidates_frozen_projected(app) -> None:
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
with app.app_context():
@@ -203,12 +375,263 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
],
},
)
state = build_task_ui_state(task)
state = build_task_ui_state(task, include_stage_context=True)
rows = state["summary"]["stp_facts"]["line_resolutions"]
assert rows[0]["effective_reservation_id"] == "3000092917"
assert rows[0]["part_number"] == "PN-1"
assert rows[0]["resolved_inventory_source_code"] == "DBS_DUB"
assert rows[0]["inventory_file_no"] == "INV-1"
stage_context = state["stage_context"]
assert stage_context["preparation"]["status"] == "ready"
assert stage_context["preparation"]["lines"] == [{
"line_key": None,
"reservation_id": "3000092917",
"part_number": "PN-1",
"required_qty": None,
"available_qty": None,
"shortage_qty": None,
"source_code": "DBS_DUB",
"status": "ok",
}]
# 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。
assert stage_context["upload"]["outcome"] == "not_started"
def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
"""通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STRUCTURED-MATCH",
source_type="manual",
match_status="partial",
inventory_source_code="DBS_DUB",
inventory_source_status="resolved",
inventory_source_method="stp_line_match",
line_results_json=[],
)
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key="line-1",
line_index=0,
match_result="matched",
inventory_status="ready",
required_qty="10",
available_qty="7",
matched_qty="7",
shortage_qty="3",
reservation_id="RSV-1",
part_number="PN-1",
inventory_source_code="DBS_DUB",
is_current=True,
))
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
assert preparation["has_match_result"] is True
assert preparation["lines"] == [{
"line_key": "line-1",
"reservation_id": "RSV-1",
"part_number": "PN-1",
"required_qty": "10",
"available_qty": "7",
"shortage_qty": "3",
"source_code": "DBS_DUB",
"status": "matched",
}]
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
with app.app_context():
task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual")
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLine(
notice_id=task.id,
position=0,
line_key="line-frozen-1",
reservation_id="RSV-FROZEN",
part_number="PN-FROZEN",
required_qty="6",
))
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
assert preparation["frozen_order_lines"] == [{
"line_key": "line-frozen-1",
"reservation_id": "RSV-FROZEN",
"part_number": "PN-FROZEN",
"required_qty": "6.00000000",
}]
assert preparation["lines"] == []
assert preparation["has_match_result"] is False
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
from app.services.shipping_notice.inventory_file_store import resolve_task_inventory_download
with app.app_context():
inventory_path = tmp_path / "task-inventory.xlsx"
inventory_path.write_bytes(b"inventory-content")
task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual")
inventory_file = ShippingInventoryFile(
inventory_file_no="SIF-UI-DOWNLOAD",
storage_path=str(inventory_path),
source_file_name="task-inventory.xlsx",
snapshot_status="ready",
)
db.session.add_all([task, inventory_file])
db.session.flush()
# 未建立 task link 时不得因为文件存在而放行下载。
assert resolve_task_inventory_download(task) is None
db.session.add(ShippingTaskInventoryLink(
task_id=task.id,
inventory_file_id=inventory_file.id,
is_active=True,
access_mode="readonly",
))
db.session.commit()
resolved = resolve_task_inventory_download(task)
assert resolved is not None
assert resolved[0] == inventory_path.resolve()
assert resolved[1] == "task-inventory.xlsx"
def test_workspace_inventory_download_requires_owned_active_file(app, client, tmp_path) -> None:
"""库存下载路由只能返回当前用户任务的 active link 文件,不能泄漏其他任务或无关联文件。"""
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
with app.app_context():
owner = User(username='inventory-download-owner', email='inventory-download-owner@example.com')
other = User(username='inventory-download-other', email='inventory-download-other@example.com')
db.session.add_all([owner, other])
db.session.flush()
inventory_path = tmp_path / 'inventory-download.xlsx'
inventory_path.write_bytes(b'inventory-download-content')
task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual')
no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual')
inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-DOWNLOAD-API',
storage_path=str(inventory_path),
source_file_name='inventory-download.xlsx',
snapshot_status='ready',
)
db.session.add_all([task, no_file_task, inventory_file])
db.session.flush()
db.session.add(ShippingTaskInventoryLink(
task_id=task.id,
inventory_file_id=inventory_file.id,
is_active=True,
access_mode='readonly',
))
db.session.commit()
owner_headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
# 关键断言:活动 link 文件可下载,并以服务端原始内容响应。
success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers)
assert success.status_code == 200
assert success.data == b'inventory-download-content'
assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '')
# 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。
missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
assert missing.status_code == 404
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND'
forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
assert forbidden.status_code == 404
def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None:
"""结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。"""
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-STRUCTURED-PARTIAL",
source_type="manual",
match_status="partial",
inventory_source_status="resolved",
inventory_source_method="stp_line_match",
step_payload_json={"line_inventory_resolutions": [{
"line_index": 0,
"line_key": "line-1",
"effective_reservation_id": "RSV-LEGACY",
"part_number": "PN-LEGACY",
"inventory_file_no": "INV-1",
"disposition": "ok",
}]},
)
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key="line-1",
line_index=0,
match_result="matched",
inventory_status="ready",
required_qty="10",
available_qty="8",
shortage_qty="2",
inventory_source_code="DBS_DUB",
is_current=True,
))
db.session.commit()
line = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]["lines"][0]
assert line["reservation_id"] == "RSV-LEGACY"
assert line["part_number"] == "PN-LEGACY"
assert line["available_qty"] == "8"
def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch) -> None:
"""正式详情接口必须原样携带通知准备摘要,供工作台首屏消费。"""
from types import SimpleNamespace
from app.api.workspace import shipping_notice as api
from app.services.shipping_notice import query_service
with app.app_context():
task = ShippingNotice(
task_no="SN-UI-DETAIL-CONTEXT",
source_type="manual",
match_status="fulfillable",
inventory_source_status="resolved",
inventory_source_method="stp_line_match",
)
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id,
line_key="line-1",
line_index=0,
match_result="matched",
inventory_status="ready",
required_qty="2",
available_qty="2",
shortage_qty="0",
reservation_id="RSV-DETAIL",
part_number="PN-DETAIL",
inventory_source_code="DBS_DUB",
is_current=True,
))
db.session.commit()
monkeypatch.setattr(api, '_require_user', lambda: SimpleNamespace(id=1, role='user'))
monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task)
monkeypatch.setattr(api, '_ok', lambda data: data)
payload = api.workspace_shipping_task_detail(task.task_no)
preparation = payload['ui_state']['stage_context']['preparation']
assert preparation['has_match_result'] is True
assert preparation['lines'][0]['reservation_id'] == 'RSV-DETAIL'
def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
@@ -1380,7 +1380,9 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
with app.app_context():
schema = _schema_version()
user = User(username='preview-admin', email='preview-admin@example.com', role='admin', status='active')
other_user = User(username='other-admin', email='other-admin@example.com', role='admin', status='active')
db.session.add(user)
db.session.add(other_user)
db.session.flush()
asset = FileAsset(
asset_no='FA-PREVIEW-SAMPLE', owner_user_id=user.id, original_filename='preview.pdf',
@@ -1410,7 +1412,6 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
'profile_code': 'PREVIEW_V2', 'display_name': 'Preview', 'schema_version_id': schema.id,
'document_id': document.id, 'definition': _coordinate_definition(),
}, actor_id=user.id)
db.session.commit()
document_id = document.id
profile_id = draft['id']
@@ -1460,6 +1461,63 @@ def test_profile_page_preview_is_bound_single_use_and_never_exposes_storage_url(
assert candidates.status_code == 200
assert 'html' not in str(parse_api_data(candidates.get_json()))
# 坐标模板与 XFA 必须共用原 PDF + PDF.js 的受控画布入口;模板类型不得扩大样本读取范围。
raw_coordinate_authorized = client.post(
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
json={'document_id': document_id}, headers=headers,
)
assert raw_coordinate_authorized.status_code == 200
raw_coordinate_grant = parse_api_data(raw_coordinate_authorized.get_json())
assert 'storage_bucket' not in str(raw_coordinate_grant) and 'storage_key' not in str(raw_coordinate_grant)
raw_coordinate_pdf = client.get(
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/pdf-preview",
query_string={'preview_token': raw_coordinate_grant['preview_token']}, headers=headers,
)
assert raw_coordinate_pdf.status_code == 200
assert raw_coordinate_pdf.mimetype == 'application/pdf'
assert raw_coordinate_pdf.data == b'%PDF-preview'
assert raw_coordinate_pdf.headers['Cache-Control'] == 'private, no-store, max-age=0'
with app.app_context():
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
profile.template_mode = 'xfa_dataset'
db.session.commit()
# XFA 编辑画布可短时读取绑定原件,但绝不获得对象存储地址或可重放下载链接。
raw_authorized = client.post(
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
json={'document_id': document_id}, headers=headers,
)
assert raw_authorized.status_code == 200
assert raw_authorized.headers['Cache-Control'] == 'private, no-store, max-age=0'
raw_grant = parse_api_data(raw_authorized.get_json())
assert 'storage_bucket' not in str(raw_grant) and 'storage_key' not in str(raw_grant)
foreign = client.get(
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
query_string={'preview_token': raw_grant['preview_token']},
headers={'X-Username': 'other-admin', 'X-Role': 'admin'},
)
assert foreign.status_code == 404
raw_authorized = client.post(
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
json={'document_id': document_id}, headers=headers,
)
raw_grant = parse_api_data(raw_authorized.get_json())
raw_pdf = client.get(
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
)
assert raw_pdf.status_code == 200
assert raw_pdf.mimetype == 'application/pdf'
assert raw_pdf.data == b'%PDF-preview'
assert raw_pdf.headers['Cache-Control'] == 'private, no-store, max-age=0'
assert b'private-bucket' not in raw_pdf.data and b'internal/preview.pdf' not in raw_pdf.data
raw_replay = client.get(
f"/api/admin/shipping-notice/order-document-profiles/{profile_id}/xfa-pdf-preview",
query_string={'preview_token': raw_grant['preview_token']}, headers=headers,
)
assert raw_replay.status_code == 404
def test_profile_page_preview_fails_closed_without_redis_or_sample_binding(app, monkeypatch):
"""预览授权依赖 Redis 且只能读取 Profile 已绑定样本,不能降级为进程内或任意文档读取。"""
@@ -37,7 +37,10 @@ def test_workspace_projection_exposes_run_level_current_activity(monkeypatch):
cancellation_actor_id=None,
cancellation_reason=None,
cancellation_reason_code=None,
id=None,
run_no='OER-TEST',
reparse_source=None,
superseding_run=None,
auto_freeze_policy_json=None,
review_cases=[],
)
@@ -151,7 +154,9 @@ def test_build_handling_items_splits_pending_freeze_review_and_failure():
assert 'candidate_missing_info' in categories
assert 'candidate_conflict' in categories
assert 'auto_freeze_blocked' in categories
assert 'budget_stopped' in categories
# 未提供受限文件引用时,预算停扩只能作为 Run 历史上下文,不能伪造一个
# 文件级处理事项参与统计;否则同一 PDF 会被多类事项重复相加。
assert 'budget_stopped' not in categories
assert items[0]['primary_action'] == 'retry_failed_attachments'
missing = next(item for item in items if item['category'] == 'candidate_missing_info')
assert missing['primary_action'] == 'review_candidate'
@@ -191,6 +196,233 @@ def test_build_handling_items_budget_stopped_includes_attachment_refs():
assert budget['affected_refs'][0]['document_id'] == 42
def test_build_handling_items_counts_one_document_in_only_one_primary_category():
"""同一 PDF 同时存在解析复核、候选待补和预算原因时,只能计入最高优先级事项。"""
run = SimpleNamespace(
status='partially_completed',
result_json={
'pending_count': 1,
'pending_orders': [{
'candidate_no': 'C-9',
'po_number': 'PO-9',
'document_id': 99,
'reasons': ['required_field_missing'],
'missing_fields': ['qty'],
}],
'budget_stopped': True,
},
auto_freeze_policy_json=None,
input_snapshot_json={
'attachment_selection': {
'items': [{
'selected': False,
'filename': 'same.pdf',
'document_id': 99,
'skip_reason_codes': ['budget_initial_limit'],
}],
},
},
extraction_plan=None,
review_cases=[],
id=None,
)
units = [SimpleNamespace(
id=9,
document_id=99,
status='review_required',
reason_code='row_needs_review',
technical_failure_reason_code=None,
)]
items = build_handling_items(run, units, open_existing_doc_ids=set())
assert [item['category'] for item in items] == ['document_review']
assert items[0]['count'] == 1
def test_build_handling_items_claims_same_pdf_by_content_hash_when_budget_snapshot_lacks_document_id():
"""预算快照仅保留哈希时,仍不得把同一 PDF 与复核事项重复统计。"""
run = SimpleNamespace(
status='partially_completed',
result_json={'budget_stopped': True, 'pending_count': 0},
auto_freeze_policy_json=None,
input_snapshot_json={
'attachment_selection': {
'items': [{
'selected': False,
'filename': 'same.pdf',
# 历史预算计划可能没有 document_id,但保留了冻结时的内容哈希。
'content_hash': 'same-content-hash',
'skip_reason_codes': ['budget_initial_limit'],
}],
},
},
extraction_plan=None,
review_cases=[],
id=None,
)
units = [SimpleNamespace(
id=10,
document_id=100,
content_hash='same-content-hash',
status='review_required',
reason_code='row_needs_review',
technical_failure_reason_code=None,
)]
items = build_handling_items(run, units, open_existing_doc_ids=set())
# 文档复核优先级更高;预算原因可作为解释存在,但不能再增加第二个文件计数。
assert [item['category'] for item in items] == ['document_review']
assert items[0]['count'] == 1
def test_build_handling_items_keeps_unclaimed_candidate_ready_unit_as_confirmation():
"""没有 pending_orders 时,候选就绪文件仍应稳定生成唯一待确认事项。"""
run = SimpleNamespace(
status='review_required',
result_json={'pending_count': 1},
auto_freeze_policy_json=None,
input_snapshot_json={},
extraction_plan=None,
review_cases=[],
id=None,
)
units = [SimpleNamespace(
id=12,
document_id=120,
content_hash='candidate-ready-hash',
status='candidate_ready',
reason_code=None,
technical_failure_reason_code=None,
)]
items = build_handling_items(run, units, open_existing_doc_ids=set())
assert [item['category'] for item in items] == ['candidate_confirmation']
assert items[0]['count'] == 1
assert items[0]['affected_refs'][0]['document_id'] == 120
def test_build_handling_items_deduplicates_confirmation_candidates_by_document():
"""同一 PDF 的多个仅待确认 Candidate 只能统计为一个文件待办。"""
run = SimpleNamespace(
status='review_required',
result_json={
'pending_count': 2,
'pending_orders': [
{
'candidate_no': 'C-SAME-1',
'po_number': 'PO-SAME-1',
'document_id': 101,
'reasons': [],
'missing_fields': [],
},
{
'candidate_no': 'C-SAME-2',
'po_number': 'PO-SAME-2',
'document_id': 101,
'reasons': [],
'missing_fields': [],
},
],
},
auto_freeze_policy_json=None,
input_snapshot_json={},
extraction_plan=None,
review_cases=[],
id=None,
)
items = build_handling_items(run, [], open_existing_doc_ids=set())
assert [item['category'] for item in items] == ['candidate_confirmation']
assert items[0]['count'] == 1
assert items[0]['affected_refs'] == [{
'type': 'candidate',
'candidate_no': 'C-SAME-1',
'po_number': 'PO-SAME-1',
'document_id': 101,
}]
def test_build_handling_items_keeps_confirmation_for_other_document_after_conflict():
"""某 PDF 冲突时,其他 PDF 的待确认事项仍须保留且互不重复计数。"""
run = SimpleNamespace(
status='review_required',
result_json={
'pending_count': 2,
'pending_orders': [
{
'candidate_no': 'C-CONFLICT',
'po_number': 'PO-CONFLICT',
'document_id': 201,
'reasons': ['email_supplement_conflict'],
'missing_fields': [],
},
{
'candidate_no': 'C-CONFIRM',
'po_number': 'PO-CONFIRM',
'document_id': 202,
'reasons': [],
'missing_fields': [],
},
],
},
auto_freeze_policy_json=None,
input_snapshot_json={},
extraction_plan=None,
review_cases=[],
id=None,
)
items = build_handling_items(run, [], open_existing_doc_ids=set())
assert [item['category'] for item in items] == [
'candidate_conflict', 'candidate_confirmation',
]
assert [item['count'] for item in items] == [1, 1]
assert items[1]['affected_refs'][0]['document_id'] == 202
def test_build_handling_items_claims_all_documents_before_limiting_refs():
"""超过展示上限时,同一 PDF 仍只能归入一个最高优先级处理事项。"""
pending_orders = [
{
'candidate_no': f'C-CONFLICT-{document_id}',
'po_number': f'PO-{document_id}',
'document_id': document_id,
'reasons': ['email_supplement_conflict'],
'missing_fields': [],
}
for document_id in range(1, 12)
]
# 第 11 份 PDF 同时带有低优先级的待确认记录;截断前认领才能防止重复。
pending_orders.append({
'candidate_no': 'C-DUPLICATE-11',
'po_number': 'PO-11',
'document_id': 11,
'reasons': [],
'missing_fields': [],
})
run = SimpleNamespace(
status='review_required',
result_json={'pending_count': len(pending_orders), 'pending_orders': pending_orders},
auto_freeze_policy_json=None,
input_snapshot_json={},
extraction_plan=None,
review_cases=[],
id=None,
)
items = build_handling_items(run, [], open_existing_doc_ids=set())
assert [item['category'] for item in items] == ['candidate_conflict']
# 统计使用全量互斥文件集合,affected_refs 仅为最多 20 条的展示样本。
assert items[0]['count'] == 11
assert len(items[0]['affected_refs']) == 11
def test_planned_documents_inherit_failed_run_status_before_units_exist():
"""Job 在 Unit 物化前失败时,右侧每份 PDF 必须显示失败而非处理中。"""
run = SimpleNamespace(
@@ -9,10 +9,13 @@ tests/test_shipping_order_review_field_conflict.py
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
from app.services.shipping_notice.order_review_field_conflict_service import (
project_review_case_field_conflicts,
)
from app.services.shipping_notice.order_review_draft_service import _sync_review_gates_safe
from app.core.errors import NotFoundError
def test_project_review_case_field_conflicts_builds_stable_keys():
@@ -88,3 +91,94 @@ def test_project_review_case_field_conflicts_empty_without_candidate():
"""无 Candidate 时投影为空列表。"""
case = SimpleNamespace(candidate_id=None, current_draft=None)
assert project_review_case_field_conflicts(case) == []
def test_project_review_case_field_conflicts_keeps_single_value_evidence_gap_actionable():
"""证据缺失不是双值冲突,也必须投影字段和行号,供用户手工补证据/裁决。"""
candidate = SimpleNamespace(
conflicts_json=[{
'field': 'part_number',
'line_index': 0,
'severity': 'blocking',
'reason': 'evidence_missing',
}],
structured_result_json={},
)
case = SimpleNamespace(
candidate_id=1,
current_draft=SimpleNamespace(lines_json=[{'line_key': 'line-1', 'line_index': 0, 'values': {}}]),
)
from app.services.shipping_notice import order_review_field_conflict_service as svc
original = svc._candidate_for_case
svc._candidate_for_case = lambda _case: candidate
try:
items = project_review_case_field_conflicts(case)
finally:
svc._candidate_for_case = original
# 关键断言:不可自动建单的证据缺失不能在字段冲突投影层静默丢失。
assert items == [{
'conflict_key': '0:part_number',
'field_code': 'part_number',
'line_index': 0,
'line_key': 'line-1',
'severity': 'blocking',
'reason': 'evidence_missing',
'options': [],
'observation_ids': [],
}]
def test_sync_review_gates_replaces_stale_missing_field_gate_with_field_conflict():
"""草稿字段已齐全时,Gate 必须通过完整性并把最新证据冲突归属到字段冲突门禁。"""
case = SimpleNamespace(
case_no='SORC-TEST',
current_draft=SimpleNamespace(draft_version=9),
)
validation = {
'assessment': {'missing_required_fields': [], 'invalid_lines': []},
'failed_gates': ['field_conflicts_resolved'],
'issues': [{
'code': 'candidate_qualification_blocked',
'reason_code': 'field_conflict',
'owning_gate_code': 'field_conflict_resolution',
'severity': 'auto_create_blocking',
'field_code': None,
'line_index': None,
}],
'line_projections': [],
}
with patch(
'app.services.shipping_notice.process_gate_bridge.sync_review_gate_for_case',
) as sync_gate, patch(
'app.services.shipping_notice.process_gate_bridge.sync_inventory_routing_gate_for_case',
), patch(
'app.services.shipping_notice.order_review_draft_service._candidate_conflict_locator',
return_value={'field_code': 'part_number', 'line_index': 0},
):
_sync_review_gates_safe(case=case, user_id=7, validation=validation)
calls = {call.kwargs['gate_code']: call.kwargs for call in sync_gate.call_args_list}
# 关键断言:旧 required_field_missing 不得滞留为当前阻断。
assert calls['field_completeness']['passed'] is True
# 关键断言:自动建单证据冲突必须带字段/行号成为用户可见的正式 Gate。
assert calls['field_conflict_resolution']['passed'] is False
assert calls['field_conflict_resolution']['blocking_reason_code'] == 'field_conflict'
assert calls['field_conflict_resolution']['details']['field_code'] == 'part_number'
assert calls['field_conflict_resolution']['details']['line_index'] == 0
def test_not_found_error_preserves_stale_conflict_key_details():
"""过期冲突操作必须返回可处理的 404 业务错误,不能因错误构造器再次抛出 TypeError。"""
error = NotFoundError(
'Field conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': '-1:part_number'},
)
# 关键断言:前端可据此识别“页面数据过期”并刷新,而非收到 500。
assert error.http_status == 404
assert error.details == {'conflict_key': '-1:part_number'}
@@ -8,6 +8,7 @@
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -16,6 +17,9 @@ from app import db
from app.core.errors import NotFoundError
from app.models import (
ShippingOrderDocument,
ShippingOrderIntake,
FileAsset,
ShippingAuditEvent,
ShippingInventoryRoutingRule,
ShippingInventoryRoutingRuleCondition,
ShippingOrderCandidate,
@@ -26,7 +30,14 @@ from app.models import (
ShippingNotice,
User,
)
from app.services.shipping_notice.order_review_projection import serialize_review_case, serialize_review_run
from app.services.shipping_notice.order_review_projection import (
serialize_review_case,
serialize_review_run,
serialize_review_queue,
)
from app.services.shipping_notice.order_review_reservation_service import (
project_review_case_reservation,
)
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_workspace_run
from app.services.shipping_notice.order_review_service import (
ensure_review_case_for_unit,
@@ -34,7 +45,203 @@ from app.services.shipping_notice.order_review_service import (
get_review_case_visible_to_user,
get_review_run_visible_to_user,
get_user_review_case,
get_review_queue_visible_to_user,
)
from app.services.shipping_notice.process_gate_bridge import find_execution_for_case
def test_review_queue_aggregates_active_runs_in_same_conversation(app):
"""会话队列汇总同一对话的多个有效 Run,并排除已被替代的版本。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE')
first = _materialized_run(user=user, agent=agent, session=session, intake=intake)
ensure_run_review_cases(run=first)
second_asset = FileAsset(
asset_no='FA-RUN-REVIEW-QUEUE-SECOND',
owner_user_id=user.id,
original_filename='orders-review-queue-second.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/orders-review-queue-second.pdf',
content_hash='c' * 64,
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(second_asset)
db.session.flush()
second_intake = ShippingOrderIntake(
intake_no='SNI-RUN-REVIEW-QUEUE-SECOND',
asset_id=second_asset.id,
user_id=user.id,
conversation_id=session.session_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
extracted_text='second order input',
structured_result_json={},
)
db.session.add(second_intake)
db.session.flush()
db.session.add(ShippingOrderDocument(
intake_id=second_intake.id,
asset_id=second_asset.id,
document_type='attachment',
attachment_key='orders-review-queue-second.pdf',
filename='orders-review-queue-second.pdf',
content_hash='b' * 64,
classification='order_notice',
parse_status='parsed',
extracted_text='PO REVIEW QUEUE SECOND',
))
db.session.commit()
second = _materialized_run(user=user, agent=agent, session=session, intake=second_intake)
ensure_run_review_cases(run=second)
replacement_asset = FileAsset(
asset_no='FA-RUN-REVIEW-QUEUE-REPLACEMENT',
owner_user_id=user.id,
original_filename='orders-review-queue-replacement.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/orders-review-queue-replacement.pdf',
content_hash='d' * 64,
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(replacement_asset)
db.session.flush()
replacement_intake = ShippingOrderIntake(
intake_no='SNI-RUN-REVIEW-QUEUE-REPLACEMENT',
asset_id=replacement_asset.id,
user_id=user.id,
conversation_id=session.session_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
extracted_text='replacement order input',
structured_result_json={},
)
db.session.add(replacement_intake)
db.session.flush()
db.session.add(ShippingOrderDocument(
intake_id=replacement_intake.id,
asset_id=replacement_asset.id,
document_type='attachment',
attachment_key='orders-review-queue-replacement.pdf',
filename='orders-review-queue-replacement.pdf',
content_hash='e' * 64,
classification='order_notice',
parse_status='parsed',
extracted_text='PO REVIEW QUEUE REPLACEMENT',
))
db.session.commit()
replacement = _materialized_run(user=user, agent=agent, session=session, intake=replacement_intake)
ensure_run_review_cases(run=replacement)
second.superseded_by_run_id = replacement.id
db.session.commit()
queue = serialize_review_queue(get_review_queue_visible_to_user(
first.run_no, user.id, is_admin=False,
))
assert [item['source_run_no'] for item in queue['items']] == [first.run_no, replacement.run_no]
assert queue['items'][0]['case_no'] == first.review_cases[0].case_no
assert queue['summary']['total'] == 2
def test_review_queue_projects_each_case_po_and_lifecycle_stage(app):
"""工作台左侧队列须为每个文件下发后端裁决的 PO 与生命周期,不由前端跨 Case 拼接。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-LIFECYCLE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-LIFECYCLE',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-lifecycle',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-001',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
db.session.commit()
item = serialize_review_queue([run])['items'][0]
assert item['case_no'] == case.case_no
assert item['po_number'] == 'PO-QUEUE-001'
assert item['lifecycle_stage'] == 'order_review'
assert [entry['state'] for entry in item['lifecycle_entries']] == [
'available', 'current', 'unavailable', 'unavailable',
]
def test_review_queue_uses_formal_task_lifecycle_stage(app):
"""Case 已绑定正式任务后,队列阶段必须随正式 Gate/领域事实推进。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-QUEUE-FORMAL-STAGE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-QUEUE-FORMAL-STAGE',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='review-queue-formal-stage',
order_extraction_run_id=run.id,
po_number='PO-QUEUE-002',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=run.extraction_plan.units[0])
notice = ShippingNotice(
task_no='SN-REVIEW-QUEUE-FORMAL-STAGE',
user_id=user.id,
conversation_id=session.session_id,
source_type='manual',
source_candidate_id=candidate.id,
match_status='partial',
inventory_lines_json=[{'part_number': 'PN-QUEUE-002'}],
)
db.session.add(notice)
db.session.flush()
case.status = 'confirmed'
case.confirmed_task_id = notice.id
db.session.commit()
item = serialize_review_queue([run])['items'][0]
assert item['po_number'] == 'PO-QUEUE-002'
assert item['lifecycle_stage'] == 'fulfillment_prep'
assert [entry['state'] for entry in item['lifecycle_entries']] == [
'available', 'available', 'current', 'unavailable',
]
def test_review_case_projects_replacement_upload_as_its_own_permission(app):
"""替代件上传必须独立于质量异常标记权限,前端不得以别的动作码推断。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-REPLACEMENT-ACTION')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
draft_actions = serialize_review_case(case)['available_actions']
assert 'upload_replacement' in draft_actions
assert 'mark_quality_issue' in draft_actions
case.status = 'quality_issue'
db.session.commit()
quality_actions = serialize_review_case(case)['available_actions']
assert 'upload_replacement' in quality_actions
assert 'mark_quality_issue' in quality_actions
case.status = 'confirmed'
db.session.commit()
assert 'upload_replacement' not in serialize_review_case(case)['available_actions']
from app.services.shipping_notice.order_review_draft_service import (
add_line,
adopt_inventory_routing_suggestion,
@@ -48,6 +255,7 @@ from app.services.shipping_notice.order_review_draft_service import (
validate_draft,
)
from app.services.shipping_notice.order_review_evidence_service import (
get_case_intake_parse_context,
get_case_email_evidence_text,
get_case_evidence,
list_case_evidence,
@@ -96,6 +304,103 @@ def _seed_review_inventory_routing_catch_all(*, reservation_field_id: str = 'res
db.session.commit()
def test_reservation_summary_reads_current_draft_value_before_async_validation():
"""合法预约号已保存但校验 Job 未落投影时,右栏不得误报缺失。"""
case = SimpleNamespace(
run=SimpleNamespace(input_snapshot_json={
'schema': {'definition': {'fields': [{
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
}]}},
}),
current_draft=SimpleNamespace(
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
lines_json=[{
'line_key': 'line-1',
'values': {'reservation-id': {'value': '33874', 'source': 'manual'}},
}],
),
)
result = project_review_case_reservation(case)
# 关键断言:33874 符合 5 位预约号契约;未完成异步校验不等于缺少预约号。
assert result['status'] == 'ok'
assert result['needs_attention'] is False
assert result['lines'][0]['effective_reservation_id'] == '33874'
def test_reservation_summary_uses_line_field_when_header_and_line_share_code():
"""同名表头字段不得遮蔽明细 Reservation,避免有效预约号被投影为缺失。"""
case = SimpleNamespace(
run=SimpleNamespace(input_snapshot_json={
'schema': {'definition': {'fields': [
{'field_id': 'header-reservation-id', 'field_code': 'reservation_id', 'scope': 'header'},
{'field_id': 'line-reservation-id', 'field_code': 'reservation_id', 'scope': 'line'},
]}},
}),
current_draft=SimpleNamespace(
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
lines_json=[{
'line_key': 'line-1',
'values': {'line-reservation-id': {'value': '33894', 'source': 'manual'}},
}],
),
)
result = project_review_case_reservation(case)
# 关键断言:字段身份是 (field_code, scope),必须读取 line.reservation_id。
assert result['reservation_field_id'] == 'line-reservation-id'
assert result['status'] == 'ok'
assert result['lines'][0]['effective_reservation_id'] == '33894'
def test_reservation_summary_keeps_missing_value_blocked_before_async_validation():
"""校验 Job 尚未落投影时,空预约号仍必须显示为真正的待处理问题。"""
case = SimpleNamespace(
run=SimpleNamespace(input_snapshot_json={
'schema': {'definition': {'fields': [{
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
}]}},
}),
current_draft=SimpleNamespace(
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
lines_json=[{'line_key': 'line-1', 'values': {}}],
),
)
result = project_review_case_reservation(case)
# 关键断言:仅修复合法 Draft 值的漏读,不能放宽缺失 Reservation 的门禁。
assert result['status'] == 'needs_attention'
assert result['needs_attention'] is True
assert result['lines'][0]['effective_reservation_id'] is None
def test_reservation_summary_reads_machine_value_before_async_validation():
"""未被人工修改的机器预约号也须与 Draft 编辑工作面一致。"""
case = SimpleNamespace(
run=SimpleNamespace(input_snapshot_json={
'schema': {'definition': {'fields': [{
'field_id': 'reservation-id', 'field_code': 'reservation_id', 'scope': 'line',
}]}},
}),
current_draft=SimpleNamespace(
validation_result_json={'status': 'not_validated', 'issues': [], 'line_projections': []},
lines_json=[{
'line_key': 'line-1',
'machine_fields': [{'field_id': 'reservation-id', 'observations': [{'value': '33874'}]}],
}],
),
)
result = project_review_case_reservation(case)
# 关键断言:values 缺失时,必须回退同一 Draft 的冻结机器值,而不是显示为空。
assert result['status'] == 'ok'
assert result['lines'][0]['effective_reservation_id'] == '33874'
def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candidate_readonly(app):
"""同一 PDF 重入只保留一个 Case/Draft,草稿复制机器快照但不改写 Candidate。"""
with app.app_context():
@@ -130,6 +435,197 @@ def test_review_case_initialization_is_pdf_unit_unique_and_keeps_machine_candida
assert db.session.get(ShippingOrderCandidate, candidate.id).structured_result_json == {'machine': 'unchanged'}
def test_review_case_initialization_closes_legacy_extraction_gates(app):
"""候选已落为 Review Case 时,正式流程不得仍把当前阶段裁决为接收解析。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-GATE-RECONCILE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-GATE', intake_id=intake.id,
primary_document_id=document.id, candidate_key='review-gate',
order_extraction_run_id=run.id, missing_fields_json=['qty'],
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=unit)
execution = find_execution_for_case(case)
db.session.flush()
gates = {row.gate_code: row for row in execution.gates}
# Candidate 已形成是更高层业务事实;旧解析 Gate 必须以 skipped 收口,
# 不能伪造为各技术步骤都曾成功执行。
assert gates['document_materialization'].status == 'skipped'
assert gates['document_materialization'].effective_result_json['disposition'] == 'superseded_by_candidate'
assert gates['document_materialization'].effective_result_json['candidate_id'] == candidate.id
# 缺字段为空时 field_completeness 可继续自动通过;关键不变量是当前 Gate
# 不得再回退到任何旧解析节点。
assert execution.current_gate_code not in {
'document_materialization', 'layout_parsing',
'document_profile_routing', 'order_field_extraction',
}
assert gates['field_completeness'].status == 'blocked_manual'
# 批次中心与 Case 详情均经共享 bundle;正式 Gate 的缺字段阻断不能在
# Case 草稿投影时回退为 order_review_build / idle。
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
bundle = project_review_case_projection_bundle(
case,
validation=None,
post_confirm=None,
is_admin=False,
)
assert bundle['current_gate']['gate_code'] == 'field_completeness'
assert bundle['blocking_reason']['code'] == 'required_field_missing'
assert bundle['user_status'] == 'waiting_human'
def test_candidate_gate_reconciliation_supersedes_active_legacy_attempt(app):
"""Candidate 形成时必须终止旧解析 Attempt,迟到结果不能夺回当前阶段。"""
with app.app_context():
from app.core.errors import ConflictError
from app.services.shipping_notice.process_gate_service import (
complete_gate_attempt,
mark_attempt_running,
queue_gate_attempt,
)
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-GATE-ACTIVE-ATTEMPT')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-GATE-ACTIVE', intake_id=intake.id,
primary_document_id=document.id, candidate_key='review-gate-active',
order_extraction_run_id=run.id, candidate_status='provisional',
)
db.session.add(candidate)
db.session.flush()
# 先构造已经关联 Candidate 的 Case 与正在执行的旧解析 Attempt,再触发收口。
case = ShippingOrderReviewCase(
case_no='SNRC-REVIEW-GATE-ACTIVE', run_id=run.id, unit_id=unit.id,
document_id=document.id, candidate_id=candidate.id, owner_user_id=user.id,
status='unreviewed',
)
db.session.add(case)
db.session.flush()
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
execution = ensure_execution_for_workflow_version(review_case_id=case.id, actor_type='system')
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='document_materialization',
trigger_type='system_requeue', actor_type='system', actor_id='test',
idempotency_key='candidate-supersedes-active-attempt',
input_snapshot={'action_code': 'retry_with_latest_rules'},
)
mark_attempt_running(attempt_id=attempt.id, worker_id='test')
from app.services.shipping_notice.process_gate_bridge import reconcile_extraction_gates_for_review_case
reconcile_extraction_gates_for_review_case(case=case)
db.session.refresh(attempt)
gate = next(row for row in execution.gates if row.gate_code == 'document_materialization')
assert attempt.status == 'superseded'
assert gate.status == 'skipped'
assert execution.current_gate_code not in {
'document_materialization', 'layout_parsing',
'document_profile_routing', 'order_field_extraction',
}
with pytest.raises(ConflictError) as exc:
complete_gate_attempt(attempt_id=attempt.id, outcome='passed')
assert exc.value.code == 'SHIPPING.PROCESS_GATE_ATTEMPT_IMMUTABLE'
def test_candidate_gate_reconciliation_is_idempotent_and_corrects_legacy_compatibility_pass(app):
"""Candidate 收口重试不制造重复审计,旧 candidate_ready 伪 passed 会被纠正。"""
with app.app_context():
user, agent, session, intake, document = _seed_run_input(suffix='REVIEW-GATE-IDEMPOTENT')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
candidate = ShippingOrderCandidate(
candidate_no='CAND-REVIEW-GATE-IDEMPOTENT', intake_id=intake.id,
primary_document_id=document.id, candidate_key='review-gate-idempotent',
order_extraction_run_id=run.id, candidate_status='provisional',
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=unit)
execution = find_execution_for_case(case)
gate = next(row for row in execution.gates if row.gate_code == 'layout_parsing')
first_version = gate.evaluation_version
from app.services.shipping_notice.process_gate_bridge import reconcile_extraction_gates_for_review_case
reconcile_extraction_gates_for_review_case(case=case)
db.session.refresh(gate)
assert gate.evaluation_version == first_version
# 模拟历史代码遗留的 candidate_ready/passed,下一次收口应只修正该兼容错误。
gate.status = 'passed'
gate.effective_result_json = {'source': 'candidate_ready'}
db.session.flush()
reconcile_extraction_gates_for_review_case(case=case)
db.session.refresh(gate)
assert gate.status == 'skipped'
assert gate.effective_result_json['disposition'] == 'superseded_by_candidate'
def test_review_case_without_candidate_does_not_close_legacy_extraction_gates(app):
"""空 Review Case 只是人工容器,不能被误判为候选已生成并跳过接收解析。"""
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='REVIEW-GATE-NO-CANDIDATE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
case = ensure_review_case_for_unit(run=run, unit=unit)
# 核心断言:没有 Candidate 时不创建正式 Execution,更不能将解析 Gate 标为 passed。
assert case is not None
assert case.candidate_id is None
assert find_execution_for_case(case) is None
item = serialize_review_queue([run])['items'][0]
# 空 Case 是解析处置对象:不得标为订单复核,更不能下发生命周期入口。
assert item['lifecycle_stage'] == 'intake_parse'
assert item['lifecycle_entries'] == []
# 解析上下文读取是独立 capability,不能通过伪造生命周期入口授权。
assert item['intake_parse_authorized'] is True
def test_find_execution_for_case_ignores_superseded_execution(app):
"""已替代 Execution 只能审计,Case 实时读取不得重新使用其旧 Gate。"""
with app.app_context():
from app.models import ShippingProcessExecution
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
)
user, agent, session, intake, document = _seed_run_input(suffix='SUPERSEDED-EXECUTION')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
candidate = ShippingOrderCandidate(
candidate_no='CAND-SUPERSEDED-EXECUTION', intake_id=intake.id,
primary_document_id=document.id, candidate_key='superseded-execution',
order_extraction_run_id=run.id,
)
db.session.add(candidate)
db.session.flush()
case = ensure_review_case_for_unit(run=run, unit=unit)
old = find_execution_for_case(case)
assert old is not None
old.status = 'superseded'
db.session.flush()
current = ensure_execution_for_workflow_version(
review_case_id=case.id, actor_type='system', actor_id='test',
)
db.session.flush()
assert current.id != old.id
assert ShippingProcessExecution.query.filter_by(review_case_id=case.id).count() == 2
assert find_execution_for_case(case).id == current.id
def test_review_cases_follow_each_ready_unit_for_any_pdf_count_and_completion_order(app):
"""任意数量 PDF 乱序完成时,只能为当前已就绪 Unit 建 Case,兄弟 PDF 不得被提前初始化。"""
with app.app_context():
@@ -594,6 +1090,185 @@ def test_review_email_evidence_preview_reads_only_the_sibling_email_body(app):
}
def test_case_intake_parse_context_returns_own_attachment_and_sibling_email(app):
"""上下文只能投影当前 Case 附件及同一 Intake 的已解析邮件正文。"""
with app.app_context():
user, agent, session, intake, attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT')
body = ShippingOrderDocument(
intake_id=intake.id,
document_type='email_body',
attachment_key='body',
filename='source.eml',
content_hash='a' * 64,
classification='email_body',
parse_status='parsed',
extracted_text='approved body text',
)
db.session.add(body)
db.session.commit()
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
context = get_case_intake_parse_context(user_id=user.id, case_no=case.case_no)
assert context == {
'case_no': case.case_no,
'attachment': {
'document_id': attachment.id,
'filename': attachment.filename,
'mime_type': 'application/pdf',
'preview_kind': 'pdf',
},
'email': {
'document_id': body.id,
'filename': 'source.eml',
'text': 'approved body text',
},
}
assert 'storage_key' not in str(context)
def test_case_intake_parse_context_never_reads_email_from_another_intake(app):
"""跨 Intake 邮件正文不能混入新上下文 DTO,当前 Case 只读自身正文。"""
with app.app_context():
user, agent, session, intake, _attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT-OWN')
own_body = ShippingOrderDocument(
intake_id=intake.id,
document_type='email_body',
attachment_key='body',
filename='own.eml',
content_hash='a' * 64,
classification='email_body',
parse_status='parsed',
extracted_text='only own body',
)
db.session.add(own_body)
db.session.flush()
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
other_asset = FileAsset(
asset_no='FA-REVIEW-INTAKE-CONTEXT-OTHER',
owner_user_id=user.id,
original_filename='other.eml',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/other.eml',
content_hash='b' * 64,
file_size=100,
mime_type='message/rfc822',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(other_asset)
db.session.flush()
other_intake = ShippingOrderIntake(
intake_no='SNI-REVIEW-INTAKE-CONTEXT-OTHER',
asset_id=other_asset.id,
user_id=user.id,
conversation_id=session.session_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
)
db.session.add(other_intake)
db.session.flush()
other_body = ShippingOrderDocument(
intake_id=other_intake.id,
document_type='email_body',
attachment_key='body',
filename='other.eml',
content_hash='b' * 64,
classification='email_body',
parse_status='parsed',
extracted_text='must not leak',
)
db.session.add(other_body)
db.session.commit()
context = get_case_intake_parse_context(user_id=user.id, case_no=case.case_no)
assert context['email'] == {
'document_id': own_body.id,
'filename': 'own.eml',
'text': 'only own body',
}
assert other_body.id != context['email']['document_id']
assert 'must not leak' not in str(context)
def test_case_intake_parse_context_rejects_another_owner_and_missing_attachment(app):
"""Case owner 与主附件均是上下文边界;任一边界失效都不得回退到其他记录。"""
with app.app_context():
user, agent, session, intake, _attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT-NOT-FOUND')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
other = User(
username='review-intake-context-other',
email='review-intake-context-other@example.com',
password_hash='x',
)
db.session.add(other)
db.session.commit()
with pytest.raises(NotFoundError):
get_case_intake_parse_context(user_id=other.id, case_no=case.case_no)
case.document_id = 999_999
db.session.commit()
with pytest.raises(NotFoundError) as exc:
get_case_intake_parse_context(user_id=user.id, case_no=case.case_no)
assert exc.value.code == 'SHIPPING.REVIEW_INTAKE_CONTEXT_NOT_FOUND'
def test_case_intake_parse_context_returns_no_email_for_direct_pdf_and_api_audits(app):
"""直接 PDF 即使遗留正文也不得投影;读取 API 必须记脱敏访问审计。"""
with app.app_context():
user, agent, session, intake, attachment = _seed_run_input(suffix='REVIEW-INTAKE-CONTEXT-PDF')
intake.source_type = 'direct_pdf'
# 模拟历史异常数据:direct_pdf Intake 仍残留同 Intake email_body。
db.session.add(ShippingOrderDocument(
intake_id=intake.id,
document_type='email_body',
attachment_key='legacy-body',
filename='legacy.eml',
content_hash='c' * 64,
classification='email_body',
parse_status='parsed',
extracted_text='must not appear for direct PDF',
))
db.session.commit()
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
from app.core.auth.jwt import issue_local_access_token
client = app.test_client()
response = client.get(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/intake-parse-context',
headers={'Authorization': f'Bearer {issue_local_access_token(user)}'},
)
assert response.status_code == 200
payload = response.get_json()['data']
assert payload['attachment']['document_id'] == attachment.id
assert payload['attachment']['preview_kind'] == 'pdf'
assert payload['email'] is None
assert 'storage_key' not in str(payload)
audit = ShippingAuditEvent.query.filter_by(
event_type='shipping_resource_accessed',
action='view_order_review_intake_parse_context',
review_case_no=case.case_no,
).one()
assert audit.aggregate_type == 'order_review_case'
assert audit.document_id == str(attachment.id)
assert audit.metadata_json == {
'access_action': 'view_order_review_intake_parse_context',
'workbench_event': 'intake_parse_context_viewed',
'attachment_preview_kind': 'pdf',
'has_email_context': False,
}
def test_review_evidence_normalizes_frozen_layout_coordinates(app):
"""坐标订单字段必须以冻结页尺寸换算为前端可绘制 bbox,并准确切换证据页。"""
with app.app_context():
@@ -15,6 +15,7 @@ from unittest.mock import patch
from app.services.shipping_notice.order_task_stage_machine import (
resolve_pre_confirm_stage,
resolve_processing_stage_for_progress_event,
sync_order_task_stage_for_notice,
write_run_unified_processing_stage,
)
from app.services.shipping_notice.shipping_processing_projection import (
@@ -183,3 +184,38 @@ def test_notice_bound_order_task_does_not_reapply_pre_confirm_stage():
assert result is order_task
assert order_task.stage == 'inventory_matching'
sync_mock.assert_not_called()
def test_active_inventory_preparation_gate_overrides_stale_pre_create_order_task_stage():
"""正式 Execution 已进入库存准备时,同步不得把 OT 保留在 waiting_review。"""
notice = SimpleNamespace(
id=14,
order_task_id=81,
active_process_execution_id=92,
current_step=None,
upload_status=None,
export_file_path=None,
pending_human_reason=None,
review_status=None,
match_status=None,
lifecycle_status='active',
inventory_lines_json=None,
)
order_task = SimpleNamespace(stage='waiting_review', status='waiting_review')
execution = SimpleNamespace(
current_gate_code='inventory_preparation',
status='waiting_external',
)
with patch('app.services.shipping_notice.order_task_stage_machine.db') as mock_db, patch(
'app.services.shipping_notice.order_task_stage_machine.sync_order_task_processing_state',
) as sync_mock:
mock_db.session.get.side_effect = [order_task, execution]
sync_order_task_stage_for_notice(notice)
sync_mock.assert_called_once_with(
order_task,
stage='inventory_fetching',
status='automating',
reason_code='notice_fulfillment_sync',
source='order_task_stage_machine',
)
@@ -0,0 +1,73 @@
"""
tests/test_shipping_pdf_automark.py
用途:验证统一 PDF 自动标记 Job 对不同 PDF 能力输出同一候选契约。
依赖:order_document_profile_pdf_automark_service、pytest mock。
逻辑:普通 PDF 复用坐标重建与 OCR 回退;XFA 复用多源融合执行器,但调用方不传类型。
"""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from app.core.errors import ValidationError
from app.services.shipping_notice.order_document_profile_pdf_automark_service import (
execute_pdf_automark_job,
)
pytestmark = pytest.mark.pure_unit
def test_coordinate_pdf_automark_retries_with_ocr_and_returns_candidates():
"""关键断言:普通 PDF 在坐标不足时由统一 Job 触发 OCR 后仍返回 candidates[]。"""
profile = SimpleNamespace(template_mode='coordinate', definition_json={}, status='draft')
reconstruction = {'subrow_layouts': [{'row_offset': 0}], 'header_regions': []}
fields = {'order_field_candidates': [], 'page_no': 1}
coordinate = MagicMock()
coordinate.suggest_coordinate_reconstruction.side_effect = [
ValidationError('missing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE'),
reconstruction,
]
coordinate.suggest_order_field_layouts.return_value = fields
with patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
return_value=profile,
), patch(
'app.services.shipping_notice.order_document_profile_service',
coordinate,
create=True,
):
# execute 函数内部延迟导入,直接替换模块缓存中的服务对象。
with patch.dict('sys.modules', {
'app.services.shipping_notice.order_document_profile_service': coordinate,
}):
result = execute_pdf_automark_job({
'profile_id': 12, 'document_id': 77, 'table_id': 'table-1', 'schema_version_id': 3, 'page_no': 1,
})
assert result['kind'] == 'coordinate_regions'
assert [item['candidate_kind'] for item in result['candidates']] == ['coordinate_reconstruction', 'order_fields']
coordinate.generate_ocr_coordinate_evidence.assert_called_once_with(document_id=77, table_id='table-1', actor_id=None)
def test_xfa_pdf_automark_delegates_multi_source_evidence_to_same_contract():
"""关键断言:XFA 由 Profile 能力自动识别,不要求客户端传类型且仍返回 candidates[]。"""
profile = SimpleNamespace(template_mode='xfa_dataset', definition_json={'template_mode': 'xfa_dataset'}, status='draft')
xfa = MagicMock()
xfa.execute_xfa_ocr_automark_job.return_value = {
'status': 'success', 'suggestions': [{'suggestion_id': 's-1'}], 'error_code': None,
}
with patch(
'app.services.shipping_notice.order_document_profile_pdf_automark_service._profile',
return_value=profile,
), patch.dict('sys.modules', {
'app.services.shipping_notice.order_document_profile_xfa_automark_service': xfa,
}):
result = execute_pdf_automark_job({'profile_id': 12, 'document_id': 77})
assert result['kind'] == 'visual_binding'
assert result['candidates'] == [{'suggestion_id': 's-1'}]
assert result['diagnostics']['evidence'] == ['pdfium', 'acroform_widget', 'ocr', 'xfa_datasets']
@@ -168,6 +168,41 @@ def test_inventory_matching_retryable_exposes_retry_action():
assert technical_auto_only is False
def test_inventory_matching_shortage_completes_matching_gate_and_routes_to_sufficiency(app, monkeypatch):
"""匹配已完成但存在缺口时,当前匹配 Gate 必须通过并交给满足性 Gate。"""
from app.services.shipping_notice import process_gate_executor as executor
from app.models import ShippingNotice
task = SimpleNamespace(
task_no='SN-SHORTAGE-1',
match_status='partial',
shortage_json=[{'line_key': 'L1', 'shortage_qty': '2'}],
)
execution = SimpleNamespace(task_id=7)
gate = SimpleNamespace(gate_code='inventory_matching')
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.match_inventory',
lambda _payload: {'status': 'needs_human'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_kwargs: None,
)
monkeypatch.setattr(ShippingNotice, 'query', SimpleNamespace(get=lambda _id: task))
with app.app_context():
outcome = executor._handle_retry_inventory_matching(
execution=execution,
gate=gate,
payload={},
)
assert outcome['outcome'] == 'passed'
assert outcome['output_snapshot']['business_result'] == 'inventory_shortage'
@pytest.mark.pure_unit
def test_inventory_preparation_retryable_without_reason_uses_contract_action():
"""无特定原因码、仅 blocked_retryable 时沿用 Gate 合同默认动作(retry_inventory_preparation)。"""
@@ -14,10 +14,11 @@ from unittest.mock import MagicMock, patch
from app import db
from app.jobs.handlers.shipping_process_gate import run_shipping_process_gate
from app.jobs.types import JobType
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
from app.models import Job, ShippingNotice, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_job_service import (
SHIPPING_PROCESS_GATE_JOB_DOMAIN,
enqueue_gate_attempt_job,
schedule_waiting_external_poll,
)
from app.services.shipping_notice.process_gate_service import (
ensure_execution_for_workflow_version,
@@ -114,3 +115,155 @@ def test_gate_failure_does_not_auto_retry(app):
)
assert queued_jobs == 0
assert int(first_job_id) > 0
def test_gate_waiting_external_schedules_next_poll(app):
"""外部等待的 Gate Job 成功后必须创建下一次延迟轮询,不能永久停在处理中。"""
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-poll')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='layout_parsing',
trigger_type='system_requeue',
actor_type='system',
actor_id='wait-poll',
idempotency_key='wait-poll-1',
input_snapshot={'action_code': 'retry_layout_parsing', 'payload': {}},
)
job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id))
job = db.session.get(Job, int(job_id))
assert job is not None
job.status = 'running'
job.attempts = 1
db.session.commit()
ctx = MagicMock()
ctx.extras = {'worker_label': 'wait-poll-worker'}
with patch(
'app.jobs.handlers.shipping_process_gate.claim_and_run_gate_attempt',
return_value={
'attempt_id': int(attempt.id),
'gate_code': 'inventory_preparation',
'gate_status': 'waiting_external',
},
), patch(
'app.jobs.handlers.shipping_process_gate.schedule_waiting_external_poll',
return_value=999,
) as schedule_poll:
run_shipping_process_gate(ctx, {'attempt_id': int(attempt.id), 'job_id': int(job_id)})
schedule_poll.assert_called_once_with(attempt_id=int(attempt.id))
completed_job = db.session.get(Job, int(job_id))
assert completed_job is not None
assert completed_job.status == 'success'
def test_waiting_inventory_gate_timeout_uses_timeout_reason(app):
"""库存 RPA 外部等待超时时须改为 timeout 原因,不可遗留 queued 文案。"""
from datetime import datetime, timedelta
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-timeout')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
assert execution.task_id == task_id
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='system_requeue',
actor_type='system',
actor_id='wait-timeout',
idempotency_key='wait-timeout-1',
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
)
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
assert gate is not None
gate.status = 'waiting_external'
gate.blocking_reason_code = 'inventory_rpa_queued'
gate.effective_result_json = {
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
}
# schedule_waiting_external_poll 只会在上一轮 Attempt 已正常收口后执行;
# 保持该前置条件,避免 queued Attempt 触发并发保护而掩盖超时分支。
attempt.status = 'succeeded'
attempt.finished_at = datetime.utcnow()
db.session.commit()
with app.app_context():
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
db.session.commit()
# 前面的 nested app context 使用了独立 scoped session;清掉外层 identity map,
# 才能断言内层同步实际提交的 Gate 事实,而不是旧会话中的 waiting_external 缓存。
db.session.expire_all()
refreshed = db.session.get(ShippingProcessGate, int(gate.id))
assert refreshed is not None
assert refreshed.status == 'blocked_manual'
assert refreshed.blocking_reason_code == 'inventory_rpa_timeout'
def test_waiting_inventory_gate_timeout_rechecks_callback_facts_before_blocking(app, monkeypatch):
"""迟到的超时轮询不得覆盖已经成功落库的库存回调事实。"""
from datetime import datetime, timedelta
_user, review_case_id, task_id = _seed_workflow_version(suffix='wait-timeout-callback-won')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
assert execution.task_id == task_id
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='system_requeue',
actor_type='system',
actor_id='wait-timeout-callback-won',
idempotency_key='wait-timeout-callback-won-1',
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
)
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
assert gate is not None
gate.status = 'waiting_external'
gate.blocking_reason_code = 'inventory_rpa_queued'
gate.effective_result_json = {
'waiting_since': (datetime.utcnow() - timedelta(hours=1)).isoformat(),
}
task = db.session.get(ShippingNotice, task_id)
assert task is not None
task.inventory_lines_json = [{'part_number': 'CALLBACK-SUCCESS', 'quantity': 1}]
assert task.inventory_lines_json
attempt.status = 'succeeded'
attempt.finished_at = datetime.utcnow()
db.session.commit()
sync_calls = []
def _sync_callback_success(*, execution, **_kwargs):
sync_calls.append(int(execution.id))
refreshed_gate = db.session.get(ShippingProcessGate, int(gate.id))
assert refreshed_gate is not None
refreshed_gate.status = 'passed'
refreshed_gate.blocking_reason_code = None
db.session.flush()
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
_sync_callback_success,
)
with app.app_context():
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
db.session.commit()
# nested app context 已提交同步结果;外层会话须失效旧 Gate 缓存后再读取。
db.session.expire_all()
refreshed = db.session.get(ShippingProcessGate, int(gate.id))
assert sync_calls == [int(execution.id)]
assert refreshed is not None
assert refreshed.status == 'passed'
assert refreshed.blocking_reason_code is None
@@ -173,6 +173,106 @@ def test_ensure_execution_creates_all_contract_gates(gate_execution):
def test_ensure_execution_for_task_ignores_superseded_execution(app):
"""Task 指针指向已替代 Execution 时必须创建新正式链,不能复用历史 Gate。"""
with app.app_context():
_user, _review_case_id, task_id = _seed_workflow_version(suffix='superseded-task')
old = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
old.status = 'superseded'
db.session.flush()
current = ensure_execution_for_workflow_version(task_id=task_id, actor_type='system')
assert current.id != old.id
assert current.status == 'active'
def test_auto_progress_does_not_queue_manual_inventory_retry(gate_execution, monkeypatch):
"""自动推进不得把用户恢复动作 retry_inventory_preparation 重新触发为 RPA。"""
from app.services.shipping_notice import process_gate_service
for prior_gate in (
ShippingProcessGate.query
.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
)
.all()
):
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_retryable'
gate.next_action_code = 'retry_inventory_preparation'
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: queued.append(kwargs),
)
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=gate,
)
assert queued == []
def test_auto_progress_does_not_queue_manual_inventory_navigation(gate_execution, monkeypatch):
"""库存已入库后的 upload_inventory_file 是导航动作,不能被自动续跑执行。"""
from app.services.shipping_notice import process_gate_service
for prior_gate in (
ShippingProcessGate.query
.filter(
ShippingProcessGate.execution_id == int(gate_execution.id),
ShippingProcessGate.sequence_no < 13,
)
.all()
):
prior_gate.status = 'passed'
gate = ShippingProcessGate.query.filter_by(
execution_id=int(gate_execution.id), gate_code='inventory_preparation',
).one()
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'inventory_rpa_timeout'
gate.next_action_code = 'upload_inventory_file'
process_gate_service._refresh_execution_pointers(gate_execution)
db.session.flush()
queued: list[dict[str, object]] = []
monkeypatch.setattr(
process_gate_service,
'queue_gate_attempt',
lambda **kwargs: queued.append(kwargs),
)
process_gate_service._enqueue_auto_progress_after_gate_pass(
execution=gate_execution,
gate=gate,
)
assert queued == []
def test_fingerprint_skip_does_not_rerun_passed_gate(gate_execution):
@@ -684,3 +784,29 @@ def test_idempotent_key_conflicts_across_execution(app):
)
assert exc.value.code == 'SHIPPING.PROCESS_GATE_IDEMPOTENCY_CONFLICT'
def test_superseded_execution_rejects_late_business_gate_result(app):
"""候选版本已替换后,迟到结果不得重新写回旧 Gate。"""
from app.core.errors import ConflictError
with app.app_context():
_user, review_case_id, task_id = _seed_workflow_version(suffix='superseded-sync')
execution = ensure_execution_for_workflow_version(
review_case_id=review_case_id,
task_id=task_id,
)
execution.status = 'superseded'
db.session.flush()
with pytest.raises(ConflictError) as exc:
sync_gate_from_business_result(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
passed=False,
blocking_reason_code='inventory_preparation_failed',
effective_result_json={'findings': []},
idempotency_key='late-result-must-not-write-superseded-execution',
)
assert exc.value.code == 'SHIPPING.PROCESS_EXECUTION_SUPERSEDED'
@@ -80,6 +80,83 @@ def test_rpa_attempt_status_updates_its_bound_preparation_source(app):
assert preparation.status == 'succeeded'
def test_rpa_callback_completes_waiting_preparation_recovery_plan(app):
"""RPA 成功回调完成准备轮次后,关联恢复计划不得继续占用 waiting_external。"""
from app import db
from app.models import (
ShippingNotice,
ShippingProcessExecution,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.inventory_recovery_service import (
create_inventory_preparation_round,
sync_inventory_preparation_round,
sync_preparation_source_from_rpa_attempt,
)
task = ShippingNotice(task_no='SN-PREP-PLAN-COMPLETE')
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-PREP-PLAN-COMPLETE', task_id=int(task.id), status='active',
current_gate_code='inventory_preparation',
)
db.session.add(execution)
db.session.flush()
plan = ShippingProcessRecoveryPlan(
plan_no='RCP-PREP-PLAN-COMPLETE', execution_id=int(execution.id),
current_gate='inventory_matching', action_code='retry_inventory_from_preparation',
target_gate='inventory_preparation', resume_after_gate='inventory_matching',
status='waiting_external', invalidation_plan_json={},
idempotency_key='prep-plan-complete', actor_type='user',
)
db.session.add(plan)
db.session.flush()
preparation = create_inventory_preparation_round(
task=task, execution_id=int(execution.id), recovery_plan_id=int(plan.id),
action_code='retry_inventory_from_preparation', source_codes=['DBS'], gate_attempt_id=None,
)
rpa = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-PREP-PLAN-COMPLETE',
status='queued', lease_token='lease-prep-plan', extra_json={}, callback_payload_json={},
)
db.session.add(rpa)
db.session.flush()
sync_inventory_preparation_round(
preparation_attempt=preparation,
result={'pending_source_codes': ['DBS'], 'source_attempts': {'DBS': {'attempt_id': rpa.id}}},
)
sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(rpa.id), rpa_status='succeeded')
db.session.refresh(plan)
assert preparation.status == 'succeeded'
assert plan.status == 'succeeded'
assert plan.completed_at is not None
def test_per_source_summary_exposes_attempt_id_for_preparation_lineage(app):
"""新建 RPA Attempt 的汇总必须返回主键,准备轮次才能被回调准确收口。"""
from app import db
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
from app.services.shipping_notice.per_source_rpa_service import _attempts_summary
task = ShippingNotice(task_no='SN-PREP-SUMMARY-ID')
db.session.add(task)
db.session.flush()
attempt = ShippingTaskInventoryRpaAttempt(
task_no=task.task_no, source_code='DBS', attempt_no=1,
source_run_no='PSR-PREP-SUMMARY-ID', status='queued',
lease_token='lease-prep-summary', extra_json={}, callback_payload_json={},
)
db.session.add(attempt)
db.session.flush()
summary = _attempts_summary(task.task_no, source_codes=['DBS'])
assert summary['DBS']['attempt_id'] == int(attempt.id)
def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, app):
"""库存准备 Trigger 必须把 GateAttempt 身份原样带到 RPA。"""
from app import db
@@ -186,7 +263,7 @@ def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkey
payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77},
)
assert seen['actor_id'] == 77
assert result['outcome'] in {'blocked_retryable', 'blocked_manual'}
assert result['outcome'] == 'waiting_external'
def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
@@ -340,7 +417,7 @@ def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app,
def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch):
"""批量成功项也必须先通过逐源身份校验,不能先入库再拒绝。"""
"""异步批量处理体必须先通过逐源身份校验,不能先入库再拒绝。"""
from app import db
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice import inventory_rpa_workflow
@@ -360,7 +437,8 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
lambda task: legacy_called.__setitem__('value', True) or task,
)
response = inventory_rpa_workflow.rpa_report_inventory_batch({
# HTTP 入口只负责受控收件和入队;身份围栏属于 Worker 正式处理体。
response = inventory_rpa_workflow.process_rpa_report_inventory_batch({
'schema_version': 'shipping_inventory_rpa.v2',
'callback_id': 'batch-callback-identity',
'batch_run_no': 'BATCH-CALLBACK-IDENTITY',
@@ -458,6 +536,80 @@ def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
assert execution.status == 'active'
def test_ready_inventory_snapshot_overrides_stale_rpa_exhausted_gate(app):
"""迟到成功回调已落库存行时,历史 RPA 耗尽不得把准备 Gate 回退为人工上传。"""
from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
task = ShippingNotice(
task_no='SN-RPA-LATE-SUCCESS',
pending_human_reason='rpa_exhausted',
inventory_lines_json=[{'part_number': 'PN-1', 'available_qty': 1}],
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-RPA-LATE-SUCCESS', task_id=task.id, status='active',
current_gate_code='inventory_preparation',
)
db.session.add(execution)
db.session.flush()
sync_fulfillment_gates_from_task(execution=execution)
preparation = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_preparation',
).one()
matching = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_matching',
).one()
assert preparation.status == 'passed'
assert preparation.blocking_reason_code is None
# 断言自动推进确实进入后续匹配,而不是伪造“整条链路成功”。
assert matching.status == 'blocked_retryable'
assert matching.blocking_reason_code == 'inventory_match_failed'
def test_external_wait_skips_stale_preparation_poll_after_gate_switch(app):
"""跨 Gate 恢复后,旧准备轮询不得在库存匹配 Gate 产生技术失败。"""
from datetime import datetime
from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_job_service import schedule_waiting_external_poll
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
task = ShippingNotice(task_no='SN-STALE-PREP-POLL')
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-STALE-PREP-POLL', task_id=task.id, status='active',
current_gate_code='inventory_matching',
)
db.session.add(execution)
db.session.flush()
sync_fulfillment_gates_from_task(execution=execution)
gate = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_matching',
).one()
gate.status = 'waiting_external'
gate.next_action_code = 'poll_inventory_preparation'
gate.effective_result_json = {'waiting_since': datetime.utcnow().isoformat()}
attempt = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code=gate.gate_code,
trigger_type='user_retry', actor_type='system', actor_id='test',
idempotency_key='stale-preparation-poll',
input_snapshot={'action_code': 'retry_inventory_from_preparation', 'payload': {}},
)
db.session.flush()
assert schedule_waiting_external_poll(attempt_id=int(attempt.id)) is None
assert attempt.job_id is None
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
"""正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。"""
from app import db
@@ -956,7 +1108,7 @@ def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch)
'freeze_mode': 'manual',
}
assert task.order_snapshot_id == 901
assert result['outcome'] == 'blocked_retryable'
assert result['outcome'] == 'waiting_external'
def test_manual_business_block_is_a_successful_attempt(app):
@@ -14,7 +14,10 @@ from unittest.mock import MagicMock, patch
import pytest
from app.core.errors import ConflictError
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
from app.services.shipping_notice.processing_ownership import (
assert_notice_task_ownership,
record_projection_inconsistency_audit,
)
from app.services.shipping_notice.processing_projection_invariants import (
PROJECTION_INCONSISTENT_ERROR_CODE,
TASK_OWNERSHIP_MISMATCH_ERROR_CODE,
@@ -65,6 +68,24 @@ def test_reconcile_marks_inconsistency_and_strips_fulfillment():
assert len(payload['stage_nodes']) == 15
def test_projection_inconsistency_audit_uses_allowed_failure_result(app):
"""不一致审计必须以 audit_service 接受的 failure 落库,不能在 GET 路径反复报参数非法。"""
with app.app_context():
with patch(
'app.services.shipping_notice.processing_ownership.append_shipping_audit_event',
) as append_mock, patch(
'app.services.shipping_notice.processing_ownership.db.session.flush',
):
record_projection_inconsistency_audit({
'projection_inconsistency_code': PROJECTION_INCONSISTENT_ERROR_CODE,
'work_item_no': 'OT-9',
'shipping_notice_no': 'SN-9',
'stage': 'waiting_review',
})
assert append_mock.call_args.kwargs['result'] == 'failure'
def test_assert_ownership_noop_without_expected_context():
"""未传期望 OT/Case/Run 时不拦截(兼容旧客户端)。"""
task = SimpleNamespace(id=1, task_no='SN-1', order_task_id=None)
@@ -83,6 +83,29 @@ def test_projection_fact_read_failure_is_fail_closed():
assert payload['blocking_reason']['code'] == 'projection_data_inconsistent'
def test_inventory_shortage_gate_projects_a_user_visible_blocking_reason():
"""库存缺口 Gate 不能只保留内部码而遗漏批次/工作台的统一阻塞原因。"""
payload = apply_user_projection_fields(reconcile_processing_projection_facts({
'status': 'blocked',
'stage': 'inventory_matching',
'source_type': 'eml',
'current_gate': {
'gate_code': 'inventory_sufficiency',
'status': 'blocked_manual',
'next_action_code': 'open_shortage_review',
'blocking_reason_code': 'inventory_shortage_review_required',
},
'available_actions': ['open_shortage_review'],
}))
assert payload['user_status'] == 'waiting_human'
assert payload['blocking_reason'] == {
'code': 'inventory_shortage_review_required',
'i18n_key': 'workspace.shippingNotice.processGate.reasons.inventory_shortage_review_required',
'details': {},
}
def test_normalize_unknown_action_codes():
"""未知 / 别名动作码映射到契约或丢弃。"""
assert normalize_action_code('retry_failed_documents') == 'retry'
@@ -295,6 +318,93 @@ def test_inventory_snapshot_missing_projects_retryable_inventory_action():
}
def test_formal_blocked_gate_overrides_stale_preparation_running_state():
"""正式 Gate 已阻断时,旧库存准备 waiting 不能把用户态降回系统处理中。"""
payload = apply_user_projection_fields({
'status': 'processing',
'stage': 'inventory_preparation',
'source_type': 'order_task',
'current_gate': {
'gate_code': 'inventory_preparation',
'status': 'blocked_retryable',
'next_action_code': 'retry_inventory_preparation',
'blocking_reason_code': 'technical_failure_present',
},
'available_actions': ['retry_inventory_preparation'],
})
# 关键断言:Gate 是业务裁决真相;Preparation Attempt 只能作为过程明细。
assert payload['user_status'] == 'retryable'
assert payload['primary_action']['code'] == 'retry_inventory_preparation'
def test_formal_inventory_matching_retry_projects_business_i18n_key():
"""正式 OT 的库存重试不得让页面回退展示内部 action code。"""
payload = apply_user_projection_fields({
'status': 'blocked',
'stage': 'inventory_matching',
'source_type': 'order_task',
'shipping_notice_no': 'SN-RETRY-MATCH',
'current_gate': {
'gate_code': 'inventory_matching',
'status': 'blocked_retryable',
'next_action_code': 'retry_inventory_matching',
'blocking_reason_code': 'inventory_match_failed',
},
'available_actions': ['retry_inventory_matching'],
})
assert payload['primary_action'] == {
'code': 'retry_inventory_matching',
'i18n_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_matching',
'parameters': {},
}
def test_formal_inventory_gate_overrides_stale_waiting_review_compatibility_fields():
"""正式库存 Gate 必须覆盖历史 OT 的 waiting_review,防止阶段回退。"""
payload = reconcile_processing_projection_facts({
'work_item_no': 'OT-GATE-OVERRIDE',
'shipping_notice_no': 'SN-GATE-OVERRIDE',
'status': 'waiting_review',
'stage': 'waiting_review',
'source_type': 'order_task',
'current_gate': {
'gate_code': 'inventory_preparation',
'status': 'blocked_manual',
'next_action_code': 'retry_inventory_preparation',
'blocking_reason_code': 'inventory_rpa_timeout',
},
'available_actions': ['open_order_review'],
})
assert payload['status'] == 'waiting_review'
assert payload['stage'] == 'inventory_fetching'
assert 'projection_inconsistency_code' not in payload
assert payload['available_actions'] == ['retry_inventory_preparation']
def test_inventory_file_missing_exposes_a_user_facing_reason_i18n_key():
"""库存文件缺失需携带可翻译原因,批次中心不得回显内部原因码。"""
payload = apply_user_projection_fields({
'status': 'blocked',
'stage': 'inventory_preparation',
'source_type': 'order_task',
'current_gate': {
'gate_code': 'inventory_preparation',
'status': 'blocked_manual',
'blocking_reason_code': 'inventory_file_missing',
},
'available_actions': [],
})
assert payload['blocking_reason'] == {
'code': 'inventory_file_missing',
'i18n_key': 'chat.shippingProcessing.reasonCode.inventory_file_missing',
'details': {},
}
def test_inventory_file_empty_keeps_gate_retry_as_the_only_primary_action():
"""库存文件缺失必须保留 Gate 重试,不得降级为线外上传或空按钮。"""
payload = apply_user_projection_fields({
@@ -23,6 +23,7 @@ from app import db
from app.models import (
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderCandidate,
ShippingOrderSubmission,
User,
)
@@ -33,7 +34,11 @@ from app.services.shipping_notice.progress_audit_contract import (
)
from app.services.shipping_notice.shipping_processing_projection import (
_aggregate_eml_order_task_work_items,
_batch_file_counts,
_batch_four_stage_nodes,
_batch_ui_state_from_items,
_conversation_processing_from_work_items,
_processing_ui_state_from_item,
_project_order_task_work_item,
map_run_status_to_processing_status,
map_run_to_processing_stage,
@@ -85,6 +90,566 @@ def test_map_run_status_to_processing_status() -> None:
assert map_run_status_to_processing_status('unknown') == 'processing'
@pytest.mark.parametrize(
('stage', 'expected_lifecycle_stage'),
[
('inventory_preparation', 'fulfillment_prep'),
('inventory_candidates_calculated', 'fulfillment_prep'),
('inventory_candidates_frozen', 'fulfillment_prep'),
('inventory_snapshots_ready', 'fulfillment_prep'),
('inventory_matched', 'fulfillment_prep'),
('excel_generated', 'fulfillment_prep'),
('upload_receipt_recorded', 'upload_complete'),
],
)
def test_batch_four_stage_nodes_maps_auto_progress_gate_stages(
stage: str,
expected_lifecycle_stage: str,
) -> None:
"""自动推进 Gate 的真实阶段码必须归入对应四阶段,不能回退到接收解析。"""
nodes = _batch_four_stage_nodes([{
'stage': stage,
'user_stage': stage,
'status': 'running',
'user_status': 'running',
}])
summaries = {node['code']: node['summary']['total'] for node in nodes}
assert summaries[expected_lifecycle_stage] == 1
assert summaries['intake_parse'] == (1 if expected_lifecycle_stage == 'intake_parse' else 0)
@pytest.mark.parametrize(
('item', 'expected_lifecycle_stage'),
[
({'user_stage': 'inventory_match'}, 'fulfillment_prep'),
({'user_stage': 'freight_upload'}, 'upload_complete'),
({'user_stage': 'customer_resolving'}, 'order_review'),
({'user_stage': 'duplicate_checking'}, 'order_review'),
({'user_stage': 'waiting_human_review'}, 'order_review'),
# Case bundle 已归一化为业务阶段时,批次摘要与生命周期入口必须直接识别,
# 不能错误落入 unclassified 并禁用订单复核入口。
({'user_stage': 'order_review'}, 'order_review'),
# 正式 Gate 是当前业务位置,必须覆盖尚未同步的历史技术 stage。
({'stage': 'document_parsing', 'current_gate': {'gate_code': 'inventory_matching'}}, 'fulfillment_prep'),
({'stage': 'document_parsing', 'user_current_gate_code': 'inventory_matching'}, 'fulfillment_prep'),
# 无 Gate 时,正式阻塞原因的 owning gate 仍可唯一确定业务阶段。
({'blocking_reason': {'code': 'inventory_file_missing'}}, 'fulfillment_prep'),
({'blocking_reason': {'code': 'generic_extraction_disabled'}}, 'intake_parse'),
],
)
def test_batch_four_stage_nodes_prefers_formal_gate_and_maps_legacy_stage_aliases(
item: dict[str, object],
expected_lifecycle_stage: str,
) -> None:
"""批次四阶段必须以正式 Gate 为准,库存/上传状态不能回退到接收解析。"""
nodes = _batch_four_stage_nodes([{
**item,
'status': 'waiting_human',
'user_status': 'waiting_human',
}])
summaries = {node['code']: node['summary']['total'] for node in nodes}
assert summaries[expected_lifecycle_stage] == 1
assert summaries['intake_parse'] == (1 if expected_lifecycle_stage == 'intake_parse' else 0)
def test_processing_ui_state_lifecycle_entries_follow_backend_stage_order() -> None:
"""通知准备未完成时通知完成必须由后端裁决为不可进入,不能由前端自行限制。"""
fulfillment_state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'inventory_match',
'current_gate': {'gate_code': 'inventory_matching'},
'source_summary': {'candidate_count': 1},
'run_no': 'SNER-LIFECYCLE',
'case_no': 'SNRC-LIFECYCLE',
'root_order_task_no': 'OT-LIFECYCLE',
'primary_action': {'code': 'open_inventory_match_review'},
'available_actions': [],
})
assert fulfillment_state['lifecycle_stage'] == 'fulfillment_prep'
assert fulfillment_state['lifecycle_entries'] == [
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
]
assert fulfillment_state['primary_action']['execution_mode'] == 'navigate'
assert fulfillment_state['primary_action']['target_surface'] == 'order_lifecycle_workbench'
assert fulfillment_state['primary_action']['target_lifecycle_stage'] == 'fulfillment_prep'
secondary_state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'inventory_match',
'current_gate': {'gate_code': 'inventory_matching'},
'source_summary': {'candidate_count': 1},
'run_no': 'SNER-LIFECYCLE-SECONDARY',
'case_no': 'SNRC-LIFECYCLE-SECONDARY',
'root_order_task_no': 'OT-LIFECYCLE-SECONDARY',
'available_actions': ['view_result'],
})
assert secondary_state['secondary_actions'] == [{
'code': 'view_result',
'enabled': True,
'execution_mode': 'navigate',
'target_surface': 'order_lifecycle_workbench',
'target_lifecycle_stage': 'fulfillment_prep',
}]
legacy_view_state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'waiting_review',
'source_summary': {'candidate_count': 1},
'run_no': 'SNER-LIFECYCLE-VIEW',
'case_no': 'SNRC-LIFECYCLE-VIEW',
'root_order_task_no': 'OT-LIFECYCLE-VIEW',
# 历史 Review 投影仍可能下发 view;它与 view_result 一样只是后端已授权的查看入口。
'available_actions': ['view'],
})
assert legacy_view_state['secondary_actions'] == [{
'code': 'view',
'enabled': True,
'execution_mode': 'navigate',
'target_surface': 'order_lifecycle_workbench',
'target_lifecycle_stage': 'order_review',
}]
review_state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'waiting_review',
'source_summary': {'candidate_count': 1},
'run_no': 'SNER-REVIEW',
'case_no': 'SNRC-REVIEW',
'root_order_task_no': 'OT-REVIEW',
'available_actions': [],
})
assert review_state['lifecycle_entries'] == [
{'code': 'intake_parse', 'state': 'available', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'order_review', 'state': 'current', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'fulfillment_prep', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
{'code': 'upload_complete', 'state': 'unavailable', 'target_surface': 'order_lifecycle_workbench'},
]
def test_processing_ui_state_exposes_shared_gate_authority() -> None:
"""批次投影须标明正式 Gate 裁决,不能让旧 technical stage 覆盖库存准备阶段。"""
state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'document_parsing',
'current_gate': {'gate_code': 'inventory_matching'},
'source_summary': {'candidate_count': 1},
'available_actions': [],
})
assert state['lifecycle_stage'] == 'fulfillment_prep'
assert state['lifecycle_authority'] == 'process_gate'
def test_processing_ui_state_without_candidate_does_not_expose_lifecycle_entries() -> None:
"""仅有解析任务标识不等于订单候选,三个入口必须全部缺席。"""
state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'waiting_human_review',
'source_summary': {'candidate_count': 0},
'run_no': 'SNER-NO-CANDIDATE',
'case_no': None,
# 解析任务也可有 root OT 导航标识;它不能错误开放三阶段工作台。
'root_order_task_no': 'OT-PARSING-ONLY',
'available_actions': [],
})
assert state['lifecycle_entries'] == []
def test_processing_ui_state_empty_review_case_does_not_expose_lifecycle_entries() -> None:
"""Review Case 未关联 Candidate 时仍属解析中,不能以 Case 编号开放生命周期。"""
state = _processing_ui_state_from_item({
'user_status': 'waiting_human',
'user_stage': 'waiting_human_review',
'source_summary': {'candidate_count': 0},
'run_no': 'SNER-EMPTY-CASE',
'case_no': 'SORC-EMPTY-CANDIDATE',
'available_actions': [],
})
assert state['lifecycle_entries'] == []
def test_intake_candidate_context_ignores_superseded_candidate(app) -> None:
"""历史 Candidate 只能审计,不能重新打开当前文件的生命周期入口。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, document = _seed_run_input(suffix='SUPERSEDED-CANDIDATE')
candidate = ShippingOrderCandidate(
candidate_no='CAND-SUPERSEDED-CONTEXT',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='superseded-context',
is_current_version=False,
)
db.session.add(candidate)
db.session.commit()
item = project_intake_work_item(intake)
assert item['source_summary']['candidate_count'] == 0
assert _processing_ui_state_from_item(item)['lifecycle_entries'] == []
@pytest.mark.parametrize('candidate_status', ('rejected', 'expired'))
def test_intake_candidate_context_ignores_non_reviewable_current_candidate(app, candidate_status: str) -> None:
"""当前版本但已拒绝/过期的 Candidate 不能重新开放订单生命周期入口。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, agent, session, intake, document = _seed_run_input(suffix=f'NON-REVIEWABLE-{candidate_status}')
candidate = ShippingOrderCandidate(
candidate_no=f'CAND-NON-REVIEWABLE-{candidate_status}',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key=f'non-reviewable-{candidate_status}',
is_current_version=True,
candidate_status=candidate_status,
)
db.session.add(candidate)
db.session.commit()
item = project_intake_work_item(intake)
assert item['source_summary']['candidate_count'] == 0
assert _processing_ui_state_from_item(item)['lifecycle_entries'] == []
def test_order_task_current_gate_ignores_empty_review_case(app) -> None:
"""空 Case 不能回退合成订单复核 Gate;当前阶段仍须由真实解析链路负责。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
from app.models import ShippingOrderReviewCase, ShippingOrderTask
user, agent, session, intake, document = _seed_run_input(suffix='EMPTY-CASE-GATE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
task = ShippingOrderTask(
task_no='OT-EMPTY-CASE-GATE',
user_id=user.id,
conversation_id=session.session_id,
extraction_run_id=run.id,
candidate_id=None,
status='processing',
stage='candidate_creating',
)
case = ShippingOrderReviewCase(
case_no='SORC-EMPTY-GATE',
run_id=run.id,
unit_id=run.extraction_plan.units[0].id,
document_id=document.id,
candidate_id=None,
owner_user_id=user.id,
status='unreviewed',
)
db.session.add_all([task, case])
db.session.commit()
item = _project_order_task_work_item(run, order_task=task)
assert item is not None
assert item['current_gate'] is None
def test_order_task_with_superseded_candidate_cannot_borrow_current_candidate(app) -> None:
"""历史 OT 不能借同 Run 的当前 Candidate 显示另一 PDF 的订单生命周期。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
from app.models import ShippingOrderTask
user, agent, session, intake, document = _seed_run_input(suffix='SUPERSEDED-OT-CANDIDATE')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
old = ShippingOrderCandidate(
candidate_no='CAND-OLD-OT', intake_id=intake.id,
primary_document_id=document.id, candidate_key='old-ot',
order_extraction_run_id=run.id, is_current_version=False,
)
current = ShippingOrderCandidate(
candidate_no='CAND-CURRENT-OTHER', intake_id=intake.id,
primary_document_id=document.id, candidate_key='current-other',
order_extraction_run_id=run.id, is_current_version=True,
)
task = ShippingOrderTask(
task_no='OT-SUPERSEDED-CANDIDATE', user_id=user.id,
conversation_id=session.session_id, extraction_run_id=run.id,
candidate_id=None, status='processing', stage='candidate_creating',
)
db.session.add_all([old, current])
db.session.flush()
task.candidate_id = old.id
db.session.add(task)
db.session.commit()
item = _project_order_task_work_item(run, order_task=task)
assert item is not None
assert item['source_summary']['candidate_count'] == 0
assert _processing_ui_state_from_item(item)['lifecycle_entries'] == []
def test_batch_projection_reports_unclassified_files_and_stage_status_from_own_summary() -> None:
"""四阶段卡片只读取自身汇总;未归类文件必须显式计数,不能静默消失。"""
projection = _conversation_processing_from_work_items([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-REVIEW',
'root_order_task_no': 'OT-REVIEW', 'source_type': 'direct_pdf',
'source_summary': {'document_id': 1, 'filename': 'review.pdf'},
'user_status': 'waiting_human', 'user_stage': 'waiting_review',
'blocking_reason': {'code': 'order_review_required'},
'available_actions': [],
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-UNKNOWN',
'root_order_task_no': 'OT-UNKNOWN', 'source_type': 'direct_pdf',
'source_summary': {'document_id': 2, 'filename': 'unknown.pdf'},
'user_status': 'running', 'user_stage': 'unmapped_legacy_stage',
'available_actions': [],
},
])
nodes = {node['code']: node for node in projection['four_stage_nodes']}
assert nodes['order_review']['status'] == 'blocked'
assert nodes['intake_parse']['status'] == 'pending'
assert projection['unclassified_summary'] == {'count': 1}
def test_batch_four_stage_nodes_counts_each_eml_child_file_not_the_aggregate_root() -> None:
"""同一 EML 的两份订单 PDF 应在四阶段摘要中计为两项,而非一张父卡。"""
nodes = _batch_four_stage_nodes([{
'work_item_type': 'order_task',
'work_item_no': 'INTAKE:SNI-DOUBLE',
'source_type': 'eml',
'user_status': 'waiting_human',
'user_stage': 'order_review',
'aggregate_children': [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-1',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'current_gate': {'gate_code': 'field_completeness'},
'blocking_reason': {'code': 'required_field_missing'},
'source_summary': {'document_id': 301, 'filename': 'first.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-DOUBLE-2',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'current_gate': {'gate_code': 'field_completeness'},
'blocking_reason': {'code': 'required_field_missing'},
'source_summary': {'document_id': 302, 'filename': 'second.pdf'},
},
],
}])
order_review = next(node for node in nodes if node['code'] == 'order_review')
assert order_review['status'] == 'blocked'
assert order_review['summary']['total'] == 2
assert order_review['summary']['needs_action'] == 2
def test_batch_four_stage_nodes_deduplicates_a_document_to_its_latest_projection() -> None:
"""同一 PDF 的历史失败投影不能与当前通知准备投影重复计数或覆盖当前阶段。"""
nodes = _batch_four_stage_nodes([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'blocking_reason': {'code': 'intake_parse_failed'},
'source_summary': {'document_id': 401, 'filename': 'same.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
'last_activity_at': '2026-08-15T10:00:00Z',
'blocking_reason': {'code': 'inventory_match_failed'},
'source_summary': {'document_id': 401, 'filename': 'same.pdf'},
},
])
by_stage = {node['code']: node['summary'] for node in nodes}
assert by_stage['intake_parse']['total'] == 0
assert by_stage['fulfillment_prep'] == {
'total': 1, 'completed': 0, 'needs_action': 1, 'processing': 0,
'failed': 0, 'blocking_reason': {'code': 'inventory_match_failed'},
}
def test_batch_file_counts_uses_the_same_current_file_representative_as_stage_summary() -> None:
"""同一 PDF 的历史失败项不能同时计入失败和当前处理中的文件数量。"""
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-OLD',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'source_summary': {'document_id': 501, 'filename': 'same.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
'last_activity_at': '2026-08-15T10:00:00Z',
'source_summary': {'document_id': 501, 'filename': 'same.pdf'},
},
]
assert _batch_file_counts(work_items) == {
'total_files': 1,
'failed_files': 0,
'waiting_human_files': 1,
'processing_files': 0,
'completed_files': 0,
}
def test_batch_stage_summary_uses_the_same_user_group_as_file_counts() -> None:
"""待处理组不能因旧 user_status=running 被阶段卡错误显示为处理中。"""
work_items = [{
'work_item_type': 'order_task',
'work_item_no': 'OT-GROUP-OVERRIDES-STATUS',
'user_group': 'waiting_human',
'user_status': 'running',
'user_stage': 'inventory_matching',
'source_summary': {'document_id': 502, 'filename': 'waiting.pdf'},
}]
assert _batch_file_counts(work_items)['waiting_human_files'] == 1
fulfillment = next(
node for node in _batch_four_stage_nodes(work_items)
if node['code'] == 'fulfillment_prep'
)
assert fulfillment['summary']['needs_action'] == 1
assert fulfillment['summary']['processing'] == 0
def test_conversation_status_groups_use_the_same_current_file_representative() -> None:
"""文件清单不能保留旧失败项,否则会与互斥统计和当前 CTA 相互矛盾。"""
projection = _conversation_processing_from_work_items([
{
'work_item_type': 'order_task', 'work_item_no': 'OT-HISTORY-LIST',
'user_status': 'failed', 'user_stage': 'document_parsing',
'user_group': 'failed', 'last_activity_at': '2026-08-15T09:00:00Z',
'source_summary': {'document_id': 525, 'filename': 'same.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT-LIST',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
'user_group': 'waiting_human', 'last_activity_at': '2026-08-15T10:00:00Z',
'source_summary': {'document_id': 525, 'filename': 'same.pdf'},
},
])
assert projection['summary']['total_files'] == 1
assert projection['status_groups']['failed'] == []
assert [row['user_task_no'] for row in projection['status_groups']['waiting_human']] == [
'OT-CURRENT-LIST',
]
def test_batch_ui_state_uses_the_same_current_file_representative_as_counts() -> None:
"""历史失败项不得在互斥统计后仍抢走批次当前按钮。"""
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-HISTORY',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'primary_action': {'code': 'retry_parse'},
'available_actions': ['retry_parse'],
'blocking_reason': {'code': 'intake_parse_failed'},
'source_summary': {'document_id': 551, 'filename': 'same.pdf'},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-CURRENT',
'user_status': 'waiting_human', 'user_stage': 'inventory_matching',
'last_activity_at': '2026-08-15T10:00:00Z',
'primary_action': {'code': 'open_inventory_match_review'},
'available_actions': ['open_inventory_match_review'],
'blocking_reason': {'code': 'inventory_match_failed'},
'source_summary': {'document_id': 551, 'filename': 'same.pdf'},
},
]
assert _batch_ui_state_from_items(work_items) == {
'status': 'waiting_human',
'stage': 'inventory_matching',
'blocking_reason': {'code': 'inventory_match_failed'},
'primary_action': {'code': 'open_inventory_match_review'},
'secondary_actions': [],
}
def test_batch_file_counts_deduplicates_reparse_versions_by_content_hash() -> None:
"""重解析产生新 document_id 时,内容哈希相同的 PDF 仍只计当前一项。"""
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-V1',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'source_summary': {
'document_id': 601, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64,
},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-V2',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'last_activity_at': '2026-08-15T10:00:00Z',
'source_summary': {
'document_id': 602, 'filename': 'reparse.pdf', 'content_hash': 'a' * 64,
},
},
]
assert _batch_file_counts(work_items)['total_files'] == 1
assert _batch_file_counts(work_items)['waiting_human_files'] == 1
def test_batch_file_counts_prefers_content_hash_over_different_root_document_ids() -> None:
"""同内容 PDF 重传即使根文档不同,也只能保留最新一份实时投影。"""
work_items = [
{
'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V1',
'user_status': 'failed', 'user_stage': 'document_parsing',
'last_activity_at': '2026-08-15T09:00:00Z',
'source_summary': {
'document_id': 701, 'root_document_id': 701,
'filename': 'same-content.pdf', 'content_hash': 'b' * 64,
},
},
{
'work_item_type': 'order_task', 'work_item_no': 'OT-ROOT-V2',
'user_status': 'waiting_human', 'user_stage': 'order_review',
'last_activity_at': '2026-08-15T10:00:00Z',
'source_summary': {
'document_id': 702, 'root_document_id': 702,
'filename': 'same-content.pdf', 'content_hash': 'b' * 64,
},
},
]
assert _batch_file_counts(work_items)['total_files'] == 1
assert _batch_file_counts(work_items)['waiting_human_files'] == 1
def test_batch_output_artifacts_only_projects_formal_downloadable_artifact() -> None:
"""批次下载资格必须来自正式 Artifact,不得由旧 notice 路径字段伪造。"""
from app.services.shipping_notice.shipping_processing_projection import _batch_output_artifacts
with patch('app.services.shipping_notice.shipping_processing_projection.ShippingOrderTask.query') as task_query:
task_query.filter_by.return_value.first.return_value = SimpleNamespace(shipping_notice_id=9)
with patch('app.services.shipping_notice.shipping_processing_projection.db.session.get') as get_notice:
get_notice.return_value = SimpleNamespace(
id=9,
task_no='OT-EXPORT',
export_file_name='legacy.xlsx',
export_file_path='D:/legacy.xlsx',
)
with patch('app.services.shipping_notice.shipping_processing_projection.resolve_task_export_download', return_value=None):
assert _batch_output_artifacts([{'root_order_task_no': 'OT-EXPORT'}]) == []
def test_aggregate_eml_work_items_uses_upload_completion_not_candidate_completion() -> None:
"""同一 EML 聚合卡仅在所有附件上传成功后完成,候选生成仍属于处理中。"""
base = {
@@ -372,7 +937,68 @@ def test_eml_review_required_leaf_exposes_its_existing_review_case_action(app) -
assert leaf['run_no'] == run.run_no
assert leaf['case_no'] == review_case.case_no
assert leaf['ui_state']['primary_action'] == {'code': 'open_order_review'}
assert leaf['ui_state']['primary_action']['code'] == 'open_order_review'
# 空 Candidate Case 的入口只打开接收解析处置面,不能伪装为订单复核。
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert leaf['ui_state']['primary_action']['target_lifecycle_stage'] == 'intake_parse'
# 无 Candidate 的人工解析 Case 仍可进入解析复核,但不得伪装成订单生命周期。
assert leaf['source_summary']['candidate_count'] == 0
assert leaf['ui_state']['lifecycle_entries'] == []
assert leaf['intake_parse_authorized'] is True
def test_eml_candidate_review_leaf_opens_lifecycle_only_for_its_primary_document(app) -> None:
"""有效 Candidate 只为其主 PDF 开放订单生命周期,兄弟 PDF 必须保持关闭。"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
user, agent, session, intake, first_pdf = _seed_run_input(
suffix='EML-CANDIDATE-LEAF-LIFECYCLE',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
second_pdf = ShippingOrderDocument(
intake_id=int(intake.id), document_type='attachment',
attachment_key='candidate-sibling.pdf', filename='candidate-sibling.pdf',
content_hash='7' * 64, classification='order_notice', parse_status='parsed',
)
db.session.add(second_pdf)
db.session.flush()
first_unit = next(unit for unit in run.extraction_plan.units if int(unit.document_id) == int(first_pdf.id))
candidate = ShippingOrderCandidate(
candidate_no='CAND-EML-LEAF-LIFECYCLE', intake_id=intake.id,
order_extraction_run_id=run.id, primary_document_id=first_pdf.id,
candidate_key='eml-candidate-leaf-lifecycle', is_current_version=True,
candidate_status='provisional',
)
db.session.add(candidate)
db.session.flush()
first_unit.status = 'review_required'
first_unit.reason_code = 'required_field_missing'
review_case = ensure_review_case_for_unit(run=run, unit=first_unit)
db.session.commit()
item = project_intake_work_item(intake)
by_document_id = {
int(child['source_summary']['document_id']): child
for child in item['aggregate_children']
}
candidate_leaf = by_document_id[int(first_pdf.id)]
sibling_leaf = by_document_id[int(second_pdf.id)]
assert review_case is not None
assert candidate_leaf['source_summary']['candidate_count'] == 1
# 顶层字段与 ui_state 必须是同一次后端裁决,供批次与工作台共用。
assert candidate_leaf['lifecycle_stage'] == candidate_leaf['ui_state']['lifecycle_stage']
assert candidate_leaf['lifecycle_entries'] == candidate_leaf['ui_state']['lifecycle_entries']
assert [entry['state'] for entry in candidate_leaf['ui_state']['lifecycle_entries']] == [
'available', 'current', 'unavailable', 'unavailable',
]
assert sibling_leaf['source_summary']['candidate_count'] == 0
assert sibling_leaf['lifecycle_entries'] == sibling_leaf['ui_state']['lifecycle_entries']
assert sibling_leaf['ui_state']['lifecycle_entries'] == []
def test_conversation_projection_is_the_complete_batch_display_source(app) -> None:
@@ -422,6 +1048,14 @@ def test_conversation_projection_is_the_complete_batch_display_source(app) -> No
assert projection['summary']['total_files'] == 2
assert projection['four_stage_nodes'][1] == {
'code': 'order_review', 'label_key': 'order_review', 'status': 'blocked',
'summary': {
'total': 1,
'completed': 0,
'needs_action': 1,
'processing': 0,
'failed': 1,
'blocking_reason': {'code': 'intake_parse_failed'},
},
}
@@ -738,6 +1372,7 @@ def test_project_conversation_processing_items_includes_work_items(app, shipping
# 顶层工作项与会话状态组均消费同一后端 ui_state;前端无需读取 Gate 补按钮。
assert solo['ui_state']['status'] == 'running'
assert solo['ui_state']['stage'] == 'document_parsing'
assert solo['ui_state']['lifecycle_stage'] == 'intake_parse'
assert solo['ui_state']['blocking_reason'] is None
assert solo['ui_state']['primary_action'] is None
assert [action['code'] for action in solo['ui_state']['secondary_actions']] == solo['available_actions']
@@ -863,8 +1498,11 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
assert item['work_item_type'] == 'order_task'
assert item['current_gate'] is not None
assert item['current_gate']['status'] == 'blocked'
assert item['current_gate']['next_action_code'] == 'open_order_review'
# 未确认 Case 的当前 Gate / 下一步必须来自 Review Case bundle,
# 不再保留旧 OT 的 open_order_review 伪门禁。
assert item['current_gate']['gate_code'] == 'order_review_build'
assert item['current_gate']['next_action_code'] == 'mark_non_order'
assert item['user_stage'] == 'order_review'
assert item['source_summary']['candidate_count'] >= 1
assert item['source_summary']['po_number'] == 'PO-OT-1'
assert item['source_summary']['customer_name'] == 'ACME Co'
@@ -874,6 +1512,49 @@ def test_project_order_task_work_item_fills_gate_and_candidate_summary(app, ship
assert item['source_summary']['filename'] == document.filename
def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shipping_user):
"""候选已生成且 Case 未终态时,EML 叶子必须进入订单复核,不能回退为接收解析。"""
del shipping_user
with app.app_context():
from app.models import ShippingOrderCandidate
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(suffix='EML-CASE-LEAF')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
unit = run.extraction_plan.units[0]
candidate = ShippingOrderCandidate(
candidate_no=f'OCAND-EML-{uuid.uuid4().hex[:8]}', intake_id=intake.id,
primary_document_id=document.id, candidate_key='eml-case-leaf',
order_extraction_run_id=run.id, is_current_version=True,
)
db.session.add(candidate)
db.session.flush()
case = ensure_run_review_cases(run=run)[0]
assert unit.status == 'candidate_ready'
assert case.status == 'unreviewed'
db.session.commit()
result = _aggregate_eml_order_task_work_items([{
'work_item_type': 'order_task', 'work_item_no': 'OT-EML-CASE',
'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no,
'status': 'processing', 'stage': 'candidate_creating', 'user_status': 'running',
'user_stage': 'candidate_creating', 'user_group': 'processing',
'last_activity_at': '', 'available_actions': [], 'facts': {'upload_state': 'not_created'},
'source_summary': {'document_id': 0, 'filename': 'mail.eml'},
}])
leaf = result[0]['aggregate_children'][0]
assert result[0]['user_status'] == 'waiting_human'
assert result[0]['user_stage'] == 'order_review'
assert leaf['case_no'] == case.case_no
assert leaf['user_status'] == 'idle'
assert leaf['user_stage'] == 'order_review'
assert leaf['current_gate']['gate_code'] == 'order_review_build'
assert 'edit_draft' in leaf['available_actions']
def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_user):
"""
BE-07:投影 stage/status 以 OT 已写入值为准,禁止读路径用 Notice 覆盖。
@@ -100,6 +100,56 @@ def test_ensure_stp_force_retry_keeps_failed_and_sets_retry_of(app):
assert new_job.retry_of_job_id == 50
def test_worker_revalidation_preserves_current_manual_validation_confirmation(app):
"""手动保存校验后的同版本 STP 重验不得丢失确认身份并误判 needs_review。"""
from app.services.shipping_notice import order_stp_auto_create_service as svc
case = SimpleNamespace(
id=3,
case_no='SORC-STP-MANUAL-CONFIRMED',
status='ready',
confirmed_task_id=None,
document_id=12,
candidate_id=None,
disposition=None,
run_id=3,
run=SimpleNamespace(run_no='SNER-TEST-MANUAL-CONFIRMED', id=3),
owner_user_id=1,
current_draft=SimpleNamespace(
draft_version=4,
validation_result_json={
'status': 'ready', 'can_build': True, 'can_auto_create': True,
'validation_version': 4,
},
issue_summary_json=[],
header_values_json={},
lines_json=[{
'line_key': 'machine-1',
'values': {'part-id': {'value': 'D4-A08AR12000001', 'source': 'manual'}},
}],
),
)
new_job = SimpleNamespace(id=52, status='queued', retry_of_job_id=None)
refreshed = {'status': 'ready', 'can_build': True, 'can_auto_create': True, 'issues': []}
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
svc, '_is_xfa_case', return_value=False,
), patch.object(svc, '_validation', return_value=refreshed), patch.object(
svc, 'find_active_stp_job', return_value=None,
), patch.object(svc, 'find_latest_stp_job', return_value=None), patch.object(
svc, 'build_stp_idempotency_key', return_value='stp-auto:SNER-TEST-MANUAL-CONFIRMED:doc-12:v4',
), patch.object(svc, 'enqueue', return_value=52), patch.object(
svc, 'record_fulfillment_audit',
), patch.object(svc, 'db') as mock_db:
mock_db.session.get.return_value = new_job
mock_db.session.flush = MagicMock()
result = svc.ensure_stp_auto_create_for_case(case=case, commit=False, refresh_validation=True)
# 关键断言:重新计算资格事实不等于撤销同一 Draft 版本已完成的人工保存校验。
assert result['status'] == 'queued'
assert case.current_draft.validation_result_json['validation_version'] == 4
def test_retry_stp_auto_create_for_case_rejects_confirmed(app):
"""已 confirmed Case 不得走 STP retry,须走确认后推进重试。"""
from app.core.errors import ConflictError
@@ -181,6 +181,80 @@ def test_execute_blank_native_pdf_returns_empty_suggestions():
assert profile.definition_json['xfa_ocr_automark']['suggestion_count'] == 0
def test_execute_automark_collects_widget_before_failing_unavailable_ocr():
"""关键断言:OCR 是强制证据,但其失败不得阻止独立 Widget 采集和审计。"""
from app.core.errors import ServiceUnavailableError
from app.services.shipping_notice.order_document_profile_xfa_automark_service import (
execute_xfa_ocr_automark_job,
)
profile = MagicMock(
id=12,
status='draft',
template_mode='xfa_dataset',
definition_json=_definition_with_binding(),
)
native = {
'pages': [{'page_no': 1, 'png_bytes': b'png'}],
'page_count': 1,
'preview_render_checksum': 'sha256:' + ('d' * 64),
'renderer_version': 'hxops.native_pdf.v1',
'render_mode': 'native_pdf',
}
widget = {
'field_key': 'path-po',
'page_no': 1,
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3},
'confidence': 0.95,
}
merged = {
'suggested_visual_bindings': [{
**widget,
'source': 'acroform_widget',
'match_class': 'high',
'suggestion_origin': 'widget_template',
}],
}
with patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service._profile',
return_value=profile,
), patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service._load_native_pdf_pages_for_ocr',
return_value=native,
), patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service._dataset_targets_flat',
return_value=[{'field_key': 'path-po', 'value': 'PO-1'}],
), patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service._widget_candidates_for_page',
return_value=[widget],
), patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service.recognize_preview_page',
side_effect=ServiceUnavailableError('OCR unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_UNAVAILABLE'),
), patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service.merge_visual_binding_suggestions',
return_value=merged,
) as merge_mock, patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service._audit_automark',
) as audit_mock, patch(
'app.services.shipping_notice.order_document_profile_xfa_automark_service.db',
):
with pytest.raises(Exception, match='XFA native PDF OCR is unavailable'):
execute_xfa_ocr_automark_job({
'profile_id': 12,
'document_id': 77,
'actor_id': 1,
'job_id': 9,
})
# Widget 已独立采集;OCR 缺失时不产生不完整的融合建议。
assert merge_mock.call_count == 0
assert any(
call.kwargs.get('event_type') == 'xfa_ocr_failed'
and call.kwargs.get('detail', {}).get('widget_candidate_count') == 1
for call in audit_mock.call_args_list
)
def test_accept_high_requires_checksum_and_confirms(app):
"""关键断言:high 接受走 confirm,且须携带 preview_render_checksum。"""
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
+61
View File
@@ -0,0 +1,61 @@
"""
tests/test_worker_shipping.py
用途:验证 Shipping Worker 在 Windows spawn 模式下使用启动它的虚拟环境解释器。
依赖:worker_shipping、pytest monkeypatch。
逻辑:避免 multiprocessing 子进程回退到系统 Python,导致 OCR 等可选依赖从错误环境加载。
"""
from __future__ import annotations
import sys
import pytest
import worker_shipping
from app.jobs.types import JobType
from app.services.shipping_notice import queue_service
pytestmark = pytest.mark.pure_unit
def test_configure_shipping_worker_process_executable_uses_current_interpreter(monkeypatch):
"""子进程解释器必须与 Worker 主进程一致,防止环境混用。"""
recorded: list[str] = []
monkeypatch.setattr(worker_shipping.mp, 'set_executable', recorded.append)
worker_shipping.configure_shipping_worker_process_executable()
# 关键断言:Windows spawn 子进程不能回退到 PATH 上的系统 Python。
assert recorded == [sys.executable]
def test_assert_shipping_worker_capabilities_rejects_missing_xfa_ocr(monkeypatch):
"""关键断言:shipping Worker 在领取 Job 前必须拒绝缺少 XFA OCR 的运行环境。"""
monkeypatch.setattr(worker_shipping, 'is_ocr_engine_available', lambda: False)
with pytest.raises(RuntimeError, match='XFA OCR dependency is unavailable'):
worker_shipping.assert_shipping_worker_capabilities()
def test_assert_shipping_worker_capabilities_accepts_complete_xfa_ocr(monkeypatch):
"""关键断言:完整 OCR 环境允许 shipping Worker 启动并消费队列。"""
monkeypatch.setattr(worker_shipping, 'is_ocr_engine_available', lambda: True)
worker_shipping.assert_shipping_worker_capabilities()
def test_shipping_worker_claims_unified_pdf_automark_jobs(monkeypatch):
"""统一自动标注必须进入 shipping worker 的领取白名单,不能永久 queued。"""
received: dict[str, object] = {}
def claim_next_job(**kwargs):
received.update(kwargs)
return None
monkeypatch.setattr('app.jobs.queue.claim_next_job', claim_next_job)
queue_service.claim_next_shipping_notice_job()
assert JobType.SHIPPING_PDF_AUTOMARK in received['job_types']
+27
View File
@@ -11,12 +11,37 @@ backend/worker_shipping.py
from __future__ import annotations
import multiprocessing as mp
import sys
from typing import Callable
from app import create_app
from app.services.shipping_notice.xfa_ocr_adapter import is_ocr_engine_available
from worker import _configure_logging, _resolve_config_name, main
def configure_shipping_worker_process_executable() -> None:
"""固定 Windows spawn 子进程解释器,防止可选 OCR 依赖跨虚拟环境加载。"""
mp.set_executable(sys.executable)
def assert_shipping_worker_capabilities() -> None:
"""
在 shipping Worker 消费队列前验证 XFA 自动标记的强制 OCR 运行时。
XFA 自动标记需以 OCR 对 PDFium 页面、AcroForm Widget 和 datasets 进行视觉
交叉校验;不可把缺少依赖的问题延迟到已领取的 Job。失败即退出,供 Supervisor
或本地启动脚本明确暴露错误并阻止错误解释器参与同一 `shipping` 队列。
Raises:
RuntimeError: RapidOCR/OpenCV/ONNX Runtime 任一缺失。
"""
if not is_ocr_engine_available():
raise RuntimeError(
'XFA OCR dependency is unavailable in the shipping Worker interpreter; '
'install backend/requirements-ocr.txt in this virtual environment.'
)
def _worker_loop(worker_index: int) -> None:
"""启动一个 shipping 队列子进程,并使用独立日志标签区分并发执行。"""
from app.services.shipping_notice.shipping_recovery_sweeper_service import shipping_recovery_tick
@@ -53,6 +78,8 @@ def main_shipping() -> None:
from app.services.shipping_notice.shipping_recovery_sweeper_service import shipping_recovery_tick
from flask import current_app
configure_shipping_worker_process_executable()
assert_shipping_worker_capabilities()
config_name = _resolve_config_name()
bootstrap_app = create_app(config_name)
concurrency = max(int(bootstrap_app.config.get('SHIPPING_NOTICE_WORKER_CONCURRENCY', 2) or 2), 1)